]> git.tdb.fi Git - libs/gl.git/blob - source/glsl/resolve.cpp
Use standard fixed-size integer types
[libs/gl.git] / source / glsl / resolve.cpp
1 #include <msp/core/algorithm.h>
2 #include <msp/core/raii.h>
3 #include <msp/strings/utils.h>
4 #include "reflect.h"
5 #include "resolve.h"
6
7 using namespace std;
8
9 namespace Msp {
10 namespace GL {
11 namespace SL {
12
13 void BlockHierarchyResolver::enter(Block &block)
14 {
15         r_any_resolved |= (current_block!=block.parent);
16         block.parent = current_block;
17 }
18
19
20 TypeResolver::TypeResolver():
21         stage(0),
22         iface_block(0),
23         r_any_resolved(false)
24 { }
25
26 bool TypeResolver::apply(Stage &s)
27 {
28         stage = &s;
29         s.types.clear();
30         r_any_resolved = false;
31         s.content.visit(*this);
32         return r_any_resolved;
33 }
34
35 TypeDeclaration *TypeResolver::get_or_create_array_type(TypeDeclaration &type)
36 {
37         auto i = array_types.find(&type);
38         if(i!=array_types.end())
39                 return i->second;
40
41         BasicTypeDeclaration *array = new BasicTypeDeclaration;
42         array->source = INTERNAL_SOURCE;
43         array->name = type.name+"[]";
44         array->kind = BasicTypeDeclaration::ARRAY;
45         array->base = type.name;
46         array->base_type = &type;
47         stage->content.body.insert(type_insert_point, array);
48         array_types[&type] = array;
49         return array;
50 }
51
52 void TypeResolver::resolve_type(TypeDeclaration *&type, const string &name, bool array)
53 {
54         TypeDeclaration *resolved = 0;
55         auto i = stage->types.find(name);
56         if(i!=stage->types.end())
57         {
58                 auto j = alias_map.find(i->second);
59                 resolved = (j!=alias_map.end() ? j->second : i->second);
60         }
61
62         if(resolved && array)
63                 resolved = get_or_create_array_type(*resolved);
64
65         r_any_resolved |= (resolved!=type);
66         type=resolved;
67 }
68
69 void TypeResolver::visit(Block &block)
70 {
71         for(auto i=block.body.begin(); i!=block.body.end(); ++i)
72         {
73                 if(!block.parent)
74                         type_insert_point = i;
75                 (*i)->visit(*this);
76         }
77 }
78
79 void TypeResolver::visit(BasicTypeDeclaration &type)
80 {
81         resolve_type(type.base_type, type.base, false);
82
83         if(type.kind==BasicTypeDeclaration::VECTOR && type.base_type)
84                 if(BasicTypeDeclaration *basic_base = dynamic_cast<BasicTypeDeclaration *>(type.base_type))
85                         if(basic_base->kind==BasicTypeDeclaration::VECTOR)
86                         {
87                                 type.kind = BasicTypeDeclaration::MATRIX;
88                                 /* A matrix's base type is its column vector type.  This will put
89                                 the column vector's size, i.e. the matrix's row count, in the high
90                                 half of the size. */
91                                 type.size |= basic_base->size<<16;
92                         }
93
94         if(type.kind==BasicTypeDeclaration::ALIAS && type.base_type)
95                 alias_map[&type] = type.base_type;
96         else if(type.kind==BasicTypeDeclaration::ARRAY && type.base_type)
97                 array_types[type.base_type] = &type;
98
99         stage->types.insert(make_pair(type.name, &type));
100 }
101
102 void TypeResolver::visit(ImageTypeDeclaration &type)
103 {
104         resolve_type(type.base_type, type.base, false);
105         stage->types.insert(make_pair(type.name, &type));
106 }
107
108 void TypeResolver::visit(StructDeclaration &strct)
109 {
110         stage->types.insert(make_pair(strct.name, &strct));
111         TraversingVisitor::visit(strct);
112 }
113
114 void TypeResolver::visit(VariableDeclaration &var)
115 {
116         resolve_type(var.type_declaration, var.type, var.array);
117         if(iface_block && var.interface==iface_block->interface)
118                 var.interface.clear();
119 }
120
121 void TypeResolver::visit(InterfaceBlock &iface)
122 {
123         if(iface.members)
124         {
125                 SetForScope<InterfaceBlock *> set_iface(iface_block, &iface);
126                 iface.members->visit(*this);
127
128                 StructDeclaration *strct = new StructDeclaration;
129                 strct->source = INTERNAL_SOURCE;
130                 strct->name = format("_%s_%s", iface.interface, iface.block_name);
131                 strct->members.body.splice(strct->members.body.begin(), iface.members->body);
132                 stage->content.body.insert(type_insert_point, strct);
133                 stage->types.insert(make_pair(strct->name, strct));
134
135                 iface.members = 0;
136                 strct->interface_block = &iface;
137                 iface.struct_declaration = strct;
138         }
139
140         TypeDeclaration *type = iface.struct_declaration;
141         if(type && iface.array)
142                 type = get_or_create_array_type(*type);
143         r_any_resolved = (type!=iface.type_declaration);
144         iface.type_declaration = type;
145 }
146
147 void TypeResolver::visit(FunctionDeclaration &func)
148 {
149         resolve_type(func.return_type_declaration, func.return_type, false);
150         TraversingVisitor::visit(func);
151 }
152
153
154 VariableResolver::VariableResolver():
155         stage(0),
156         r_any_resolved(false),
157         record_target(false),
158         r_self_referencing(false)
159 { }
160
161 bool VariableResolver::apply(Stage &s)
162 {
163         stage = &s;
164         s.interface_blocks.clear();
165         r_any_resolved = false;
166         s.content.visit(*this);
167         for(VariableDeclaration *v: redeclared_builtins)
168                 v->source = GENERATED_SOURCE;
169         NodeRemover().apply(s, nodes_to_remove);
170         return r_any_resolved;
171 }
172
173 void VariableResolver::enter(Block &block)
174 {
175         block.variables.clear();
176 }
177
178 void VariableResolver::visit(RefPtr<Expression> &expr)
179 {
180         r_replacement_expr = 0;
181         expr->visit(*this);
182         if(r_replacement_expr)
183         {
184                 expr = r_replacement_expr;
185                 /* Don't record assignment target when doing a replacement, because chain
186                 information won't be correct. */
187                 r_assignment_target.declaration = 0;
188                 r_any_resolved = true;
189         }
190         r_replacement_expr = 0;
191 }
192
193 void VariableResolver::check_assignment_target(Statement *declaration)
194 {
195         if(record_target)
196         {
197                 if(r_assignment_target.declaration)
198                 {
199                         /* More than one reference found in assignment target.  Unable to
200                         determine what the primary target is. */
201                         record_target = false;
202                         r_assignment_target.declaration = 0;
203                 }
204                 else
205                         r_assignment_target.declaration = declaration;
206         }
207         // TODO This check is overly broad and may prevent some optimizations.
208         else if(declaration && declaration==r_assignment_target.declaration)
209                 r_self_referencing = true;
210 }
211
212 void VariableResolver::visit(VariableReference &var)
213 {
214         VariableDeclaration *declaration = 0;
215
216         /* Look for variable declarations in the block hierarchy first.  Interface
217         blocks are always defined in the top level so we can't accidentally skip
218         one. */
219         for(Block *block=current_block; (!declaration && block); block=block->parent)
220         {
221                 auto i = block->variables.find(var.name);
222                 if(i!=block->variables.end())
223                         declaration = i->second;
224         }
225
226         if(!declaration)
227         {
228                 const map<string, InterfaceBlock *> &blocks = stage->interface_blocks;
229                 auto i = blocks.find(var.name);
230                 if(i==blocks.end())
231                 {
232                         // Look for the variable in anonymous interface blocks.
233                         for(i=blocks.begin(); i!=blocks.end(); ++i)
234                                 if(i->second->instance_name.empty() && i->second->struct_declaration)
235                                         if(i->second->struct_declaration->members.variables.count(var.name))
236                                                 break;
237                 }
238
239                 if(i!=blocks.end())
240                 {
241                         /* The name refers to either an interface block with an instance name
242                         or a variable declared inside an anonymous interface block.  Prepare
243                         new syntax tree nodes accordingly. */
244                         InterfaceBlockReference *iface_ref = new InterfaceBlockReference;
245                         iface_ref->source = var.source;
246                         iface_ref->line = var.line;
247                         iface_ref->declaration = i->second;
248
249                         if(i->second->instance_name.empty())
250                         {
251                                 iface_ref->name = format("%s %s", i->second->interface, i->second->block_name);
252
253                                 MemberAccess *memacc = new MemberAccess;
254                                 memacc->source = var.source;
255                                 memacc->line = var.line;
256                                 memacc->left = iface_ref;
257                                 memacc->member = var.name;
258
259                                 r_replacement_expr = memacc;
260                         }
261                         else
262                         {
263                                 iface_ref->name = var.name;
264                                 r_replacement_expr = iface_ref;
265                         }
266                 }
267         }
268
269         r_any_resolved |= (declaration!=var.declaration);
270         var.declaration = declaration;
271
272         check_assignment_target(var.declaration);
273 }
274
275 void VariableResolver::visit(InterfaceBlockReference &iface)
276 {
277         auto i = stage->interface_blocks.find(iface.name);
278         InterfaceBlock *declaration = (i!=stage->interface_blocks.end() ? i->second : 0);
279         r_any_resolved |= (declaration!=iface.declaration);
280         iface.declaration = declaration;
281
282         check_assignment_target(iface.declaration);
283 }
284
285 void VariableResolver::visit(MemberAccess &memacc)
286 {
287         TraversingVisitor::visit(memacc);
288
289         VariableDeclaration *declaration = 0;
290         int index = -1;
291         if(StructDeclaration *strct = dynamic_cast<StructDeclaration *>(memacc.left->type))
292         {
293                 auto i = strct->members.variables.find(memacc.member);
294                 if(i!=strct->members.variables.end())
295                 {
296                         declaration = i->second;
297                         index = 0;
298                         for(auto j=strct->members.body.begin(); (j!=strct->members.body.end() && j->get()!=i->second); ++j)
299                                 ++index;
300
301                         if(record_target)
302                                 add_to_chain(r_assignment_target, Assignment::Target::MEMBER, index);
303                 }
304         }
305         else if(BasicTypeDeclaration *basic = dynamic_cast<BasicTypeDeclaration *>(memacc.left->type))
306         {
307                 bool scalar_swizzle = ((basic->kind==BasicTypeDeclaration::INT || basic->kind==BasicTypeDeclaration::FLOAT) && memacc.member.size()==1);
308                 bool vector_swizzle = (basic->kind==BasicTypeDeclaration::VECTOR && memacc.member.size()<=4);
309                 if(scalar_swizzle || vector_swizzle)
310                 {
311                         static const char component_names[] = { 'x', 'r', 's', 'y', 'g', 't', 'z', 'b', 'p', 'w', 'a', 'q' };
312
313                         bool ok = true;
314                         uint8_t components[4] = { };
315                         for(unsigned i=0; (ok && i<memacc.member.size()); ++i)
316                                 ok = ((components[i] = (std::find(component_names, component_names+12, memacc.member[i])-component_names)/3) < 4);
317
318                         if(ok)
319                         {
320                                 Swizzle *swizzle = new Swizzle;
321                                 swizzle->source = memacc.source;
322                                 swizzle->line = memacc.line;
323                                 swizzle->oper = memacc.oper;
324                                 swizzle->left = memacc.left;
325                                 swizzle->component_group = memacc.member;
326                                 swizzle->count = memacc.member.size();
327                                 copy(components, components+memacc.member.size(), swizzle->components);
328                                 r_replacement_expr = swizzle;
329                         }
330                 }
331         }
332
333         r_any_resolved |= (declaration!=memacc.declaration || index!=memacc.index);
334         memacc.declaration = declaration;
335         memacc.index = index;
336 }
337
338 void VariableResolver::visit(Swizzle &swizzle)
339 {
340         TraversingVisitor::visit(swizzle);
341
342         if(record_target)
343         {
344                 unsigned mask = 0;
345                 for(unsigned i=0; i<swizzle.count; ++i)
346                         mask |= 1<<swizzle.components[i];
347                 add_to_chain(r_assignment_target, Assignment::Target::SWIZZLE, mask);
348         }
349 }
350
351 void VariableResolver::visit(BinaryExpression &binary)
352 {
353         if(binary.oper->token[0]=='[')
354         {
355                 {
356                         /* The subscript expression is not a part of the primary assignment
357                         target. */
358                         SetFlag set(record_target, false);
359                         visit(binary.right);
360                 }
361                 visit(binary.left);
362
363                 if(record_target)
364                 {
365                         unsigned index = 0x3F;
366                         if(Literal *literal_subscript = dynamic_cast<Literal *>(binary.right.get()))
367                                 if(literal_subscript->value.check_type<int>())
368                                         index = literal_subscript->value.value<int>();
369                         add_to_chain(r_assignment_target, Assignment::Target::ARRAY, index);
370                 }
371         }
372         else
373                 TraversingVisitor::visit(binary);
374 }
375
376 void VariableResolver::visit(Assignment &assign)
377 {
378         {
379                 SetFlag set(record_target);
380                 r_assignment_target = Assignment::Target();
381                 visit(assign.left);
382                 r_any_resolved |= (r_assignment_target<assign.target || assign.target<r_assignment_target);
383                 assign.target = r_assignment_target;
384         }
385
386         r_self_referencing = false;
387         visit(assign.right);
388         assign.self_referencing = (r_self_referencing || assign.oper->token[0]!='=');
389 }
390
391 void VariableResolver::merge_layouts(Layout &to_layout, const Layout &from_layout)
392 {
393         for(const Layout::Qualifier &q: from_layout.qualifiers)
394         {
395                 auto i = find_member(to_layout.qualifiers, q.name, &Layout::Qualifier::name);
396                 if(i!=to_layout.qualifiers.end())
397                 {
398                         i->has_value = q.value;
399                         i->value = q.value;
400                 }
401                 else
402                         to_layout.qualifiers.push_back(q);
403         }
404 }
405
406 void VariableResolver::visit(VariableDeclaration &var)
407 {
408         TraversingVisitor::visit(var);
409         VariableDeclaration *&ptr = current_block->variables[var.name];
410         if(!ptr)
411                 ptr = &var;
412         else if(!current_block->parent && ptr->interface==var.interface && ptr->type==var.type)
413         {
414                 if(ptr->source==BUILTIN_SOURCE)
415                         redeclared_builtins.push_back(&var);
416                 else
417                         stage->diagnostics.push_back(Diagnostic(Diagnostic::WARN, var.source, var.line,
418                                 format("Redeclaring non-builtin variable '%s' is deprecated", var.name)));
419
420                 if(var.init_expression)
421                         ptr->init_expression = var.init_expression;
422                 if(var.layout)
423                 {
424                         if(ptr->layout)
425                                 merge_layouts(*ptr->layout, *var.layout);
426                         else
427                                 ptr->layout = var.layout;
428                 }
429                 nodes_to_remove.insert(&var);
430
431                 r_any_resolved = true;
432         }
433 }
434
435 void VariableResolver::visit(InterfaceBlock &iface)
436 {
437         /* Block names can be reused in different interfaces.  Prefix the name with
438         the first character of the interface to avoid conflicts. */
439         stage->interface_blocks.insert(make_pair(format("%s %s", iface.interface, iface.block_name), &iface));
440         if(!iface.instance_name.empty())
441                 stage->interface_blocks.insert(make_pair(iface.instance_name, &iface));
442
443         TraversingVisitor::visit(iface);
444 }
445
446
447 ExpressionResolver::ExpressionResolver():
448         stage(0),
449         r_any_resolved(false)
450 { }
451
452 bool ExpressionResolver::apply(Stage &s)
453 {
454         stage = &s;
455         r_any_resolved = false;
456         s.content.visit(*this);
457         return r_any_resolved;
458 }
459
460 ExpressionResolver::Compatibility ExpressionResolver::get_compatibility(BasicTypeDeclaration &left, BasicTypeDeclaration &right)
461 {
462         if(&left==&right)
463                 return SAME_TYPE;
464         else if(can_convert(left, right))
465                 return LEFT_CONVERTIBLE;
466         else if(can_convert(right, left))
467                 return RIGHT_CONVERTIBLE;
468         else
469                 return NOT_COMPATIBLE;
470 }
471
472 BasicTypeDeclaration *ExpressionResolver::find_type(BasicTypeDeclaration::Kind kind, unsigned size, bool sign)
473 {
474         auto i = find_if(basic_types,
475                 [kind, size, sign](const BasicTypeDeclaration *t){ return t->kind==kind && t->size==size && t->sign==sign; });
476         return (i!=basic_types.end() ? *i : 0);
477 }
478
479 BasicTypeDeclaration *ExpressionResolver::find_type(BasicTypeDeclaration &elem_type, BasicTypeDeclaration::Kind kind, unsigned size)
480 {
481         auto i = find_if(basic_types,
482                 [&elem_type, kind, size](BasicTypeDeclaration *t){ return get_element_type(*t)==&elem_type && t->kind==kind && t->size==size; });
483         return (i!=basic_types.end() ? *i : 0);
484 }
485
486 void ExpressionResolver::convert_to(RefPtr<Expression> &expr, BasicTypeDeclaration &type)
487 {
488         RefPtr<FunctionCall> call = new FunctionCall;
489         call->name = type.name;
490         call->constructor = true;
491         call->arguments.push_back_nocopy(expr);
492         call->type = &type;
493         expr = call;
494 }
495
496 bool ExpressionResolver::convert_to_element(RefPtr<Expression> &expr, BasicTypeDeclaration &elem_type)
497 {
498         if(BasicTypeDeclaration *expr_basic = dynamic_cast<BasicTypeDeclaration *>(expr->type))
499         {
500                 BasicTypeDeclaration *to_type = &elem_type;
501                 if(is_vector_or_matrix(*expr_basic))
502                         to_type = find_type(elem_type, expr_basic->kind, expr_basic->size);
503                 if(to_type)
504                 {
505                         convert_to(expr, *to_type);
506                         return true;
507                 }
508         }
509
510         return false;
511 }
512
513 bool ExpressionResolver::truncate_vector(RefPtr<Expression> &expr, unsigned size)
514 {
515         if(BasicTypeDeclaration *expr_basic = dynamic_cast<BasicTypeDeclaration *>(expr->type))
516                 if(BasicTypeDeclaration *expr_elem = get_element_type(*expr_basic))
517                 {
518                         RefPtr<Swizzle> swizzle = new Swizzle;
519                         swizzle->left = expr;
520                         swizzle->oper = &Operator::get_operator(".", Operator::POSTFIX);
521                         swizzle->component_group = string("xyzw", size);
522                         swizzle->count = size;
523                         for(unsigned i=0; i<size; ++i)
524                                 swizzle->components[i] = i;
525                         if(size==1)
526                                 swizzle->type = expr_elem;
527                         else
528                                 swizzle->type = find_type(*expr_elem, BasicTypeDeclaration::VECTOR, size);
529                         expr = swizzle;
530
531                         return true;
532                 }
533
534         return false;
535 }
536
537 void ExpressionResolver::resolve(Expression &expr, TypeDeclaration *type, bool lvalue)
538 {
539         r_any_resolved |= (type!=expr.type || lvalue!=expr.lvalue);
540         expr.type = type;
541         expr.lvalue = lvalue;
542 }
543
544 void ExpressionResolver::visit(Block &block)
545 {
546         SetForScope<Block *> set_block(current_block, &block);
547         for(auto i=block.body.begin(); i!=block.body.end(); ++i)
548         {
549                 insert_point = i;
550                 (*i)->visit(*this);
551         }
552 }
553
554 void ExpressionResolver::visit(Literal &literal)
555 {
556         if(literal.value.check_type<bool>())
557                 resolve(literal, find_type(BasicTypeDeclaration::BOOL, 1), false);
558         else if(literal.value.check_type<int>())
559                 resolve(literal, find_type(BasicTypeDeclaration::INT, 32, true), false);
560         else if(literal.value.check_type<unsigned>())
561                 resolve(literal, find_type(BasicTypeDeclaration::INT, 32, false), false);
562         else if(literal.value.check_type<float>())
563                 resolve(literal, find_type(BasicTypeDeclaration::FLOAT, 32), false);
564 }
565
566 void ExpressionResolver::visit(VariableReference &var)
567 {
568         if(var.declaration)
569                 resolve(var, var.declaration->type_declaration, true);
570 }
571
572 void ExpressionResolver::visit(InterfaceBlockReference &iface)
573 {
574         if(iface.declaration)
575                 resolve(iface, iface.declaration->type_declaration, true);
576 }
577
578 void ExpressionResolver::visit(MemberAccess &memacc)
579 {
580         TraversingVisitor::visit(memacc);
581
582         if(memacc.declaration)
583                 resolve(memacc, memacc.declaration->type_declaration, memacc.left->lvalue);
584 }
585
586 void ExpressionResolver::visit(Swizzle &swizzle)
587 {
588         TraversingVisitor::visit(swizzle);
589
590         if(BasicTypeDeclaration *left_basic = dynamic_cast<BasicTypeDeclaration *>(swizzle.left->type))
591         {
592                 BasicTypeDeclaration *left_elem = get_element_type(*left_basic);
593                 if(swizzle.count==1)
594                         resolve(swizzle, left_elem, swizzle.left->lvalue);
595                 else if(left_basic->kind==BasicTypeDeclaration::VECTOR && left_elem)
596                         resolve(swizzle, find_type(*left_elem, left_basic->kind, swizzle.count), swizzle.left->lvalue);
597         }
598 }
599
600 void ExpressionResolver::visit(UnaryExpression &unary)
601 {
602         TraversingVisitor::visit(unary);
603
604         BasicTypeDeclaration *basic = dynamic_cast<BasicTypeDeclaration *>(unary.expression->type);
605         if(!basic)
606                 return;
607
608         char oper = unary.oper->token[0];
609         if(oper=='!')
610         {
611                 if(basic->kind!=BasicTypeDeclaration::BOOL)
612                         return;
613         }
614         else if(oper=='~')
615         {
616                 if(basic->kind!=BasicTypeDeclaration::INT)
617                         return;
618         }
619         else if(oper=='+' || oper=='-')
620         {
621                 BasicTypeDeclaration *elem = get_element_type(*basic);
622                 if(!elem || !is_scalar(*elem))
623                         return;
624         }
625         resolve(unary, basic, unary.expression->lvalue);
626 }
627
628 void ExpressionResolver::visit(BinaryExpression &binary, bool assign)
629 {
630         /* Binary operators are only defined for basic types (not for image or
631         structure types). */
632         BasicTypeDeclaration *basic_left = dynamic_cast<BasicTypeDeclaration *>(binary.left->type);
633         BasicTypeDeclaration *basic_right = dynamic_cast<BasicTypeDeclaration *>(binary.right->type);
634         if(!basic_left || !basic_right)
635                 return;
636
637         char oper = binary.oper->token[0];
638         if(oper=='[')
639         {
640                 /* Subscripting operates on vectors, matrices and arrays, and the right
641                 operand must be an integer. */
642                 if((!is_vector_or_matrix(*basic_left) && basic_left->kind!=BasicTypeDeclaration::ARRAY) || basic_right->kind!=BasicTypeDeclaration::INT)
643                         return;
644
645                 resolve(binary, basic_left->base_type, binary.left->lvalue);
646                 return;
647         }
648         else if(basic_left->kind==BasicTypeDeclaration::ARRAY || basic_right->kind==BasicTypeDeclaration::ARRAY)
649                 // No other binary operator can be used with arrays.
650                 return;
651
652         BasicTypeDeclaration *elem_left = get_element_type(*basic_left);
653         BasicTypeDeclaration *elem_right = get_element_type(*basic_right);
654         if(!elem_left || !elem_right)
655                 return;
656
657         Compatibility compat = get_compatibility(*basic_left, *basic_right);
658         Compatibility elem_compat = get_compatibility(*elem_left, *elem_right);
659         if(elem_compat==NOT_COMPATIBLE)
660                 return;
661         if(assign && (compat==LEFT_CONVERTIBLE || elem_compat==LEFT_CONVERTIBLE))
662                 return;
663
664         TypeDeclaration *type = 0;
665         char oper2 = binary.oper->token[1];
666         if((oper=='<' && oper2!='<') || (oper=='>' && oper2!='>'))
667         {
668                 /* Relational operators compare two scalar integer or floating-point
669                 values. */
670                 if(!is_scalar(*elem_left) || !is_scalar(*elem_right) || compat==NOT_COMPATIBLE)
671                         return;
672
673                 type = find_type(BasicTypeDeclaration::BOOL, 1);
674         }
675         else if((oper=='=' || oper=='!') && oper2=='=')
676         {
677                 // Equality comparison can be done on any compatible types.
678                 if(compat==NOT_COMPATIBLE)
679                         return;
680
681                 type = find_type(BasicTypeDeclaration::BOOL, 1);
682         }
683         else if(oper2=='&' || oper2=='|' || oper2=='^')
684         {
685                 // Logical operators can only be applied to booleans.
686                 if(basic_left->kind!=BasicTypeDeclaration::BOOL || basic_right->kind!=BasicTypeDeclaration::BOOL)
687                         return;
688
689                 type = basic_left;
690         }
691         else if((oper=='&' || oper=='|' || oper=='^' || oper=='%') && !oper2)
692         {
693                 // Bitwise operators and modulo can only be applied to integers.
694                 if(basic_left->kind!=BasicTypeDeclaration::INT || basic_right->kind!=BasicTypeDeclaration::INT)
695                         return;
696
697                 type = (compat==LEFT_CONVERTIBLE ? basic_right : basic_left);
698         }
699         else if((oper=='<' || oper=='>') && oper2==oper)
700         {
701                 // Shifts apply to integer scalars and vectors, with some restrictions.
702                 if(elem_left->kind!=BasicTypeDeclaration::INT || elem_right->kind!=BasicTypeDeclaration::INT)
703                         return;
704                 unsigned left_size = (basic_left->kind==BasicTypeDeclaration::INT ? 1 : basic_left->kind==BasicTypeDeclaration::VECTOR ? basic_left->size : 0);
705                 unsigned right_size = (basic_right->kind==BasicTypeDeclaration::INT ? 1 : basic_right->kind==BasicTypeDeclaration::VECTOR ? basic_right->size : 0);
706                 if(!left_size || (left_size==1 && right_size!=1) || (left_size>1 && right_size!=1 && right_size!=left_size))
707                         return;
708
709                 /* If the left operand is a vector and right is scalar, convert the right
710                 operand to a vector too. */
711                 if(left_size>1 && right_size==1)
712                 {
713                         BasicTypeDeclaration *vec_right = find_type(*elem_right, basic_left->kind, basic_left->size);
714                         if(!vec_right)
715                                 return;
716
717                         convert_to(binary.right, *vec_right);
718                 }
719
720                 type = basic_left;
721                 // Don't perform conversion even if the operands are of different sizes.
722                 compat = SAME_TYPE;
723         }
724         else if(oper=='+' || oper=='-' || oper=='*' || oper=='/')
725         {
726                 // Arithmetic operators require scalar elements.
727                 if(!is_scalar(*elem_left) || !is_scalar(*elem_right))
728                         return;
729
730                 if(oper=='*' && is_vector_or_matrix(*basic_left) && is_vector_or_matrix(*basic_right) &&
731                         (basic_left->kind==BasicTypeDeclaration::MATRIX || basic_right->kind==BasicTypeDeclaration::MATRIX))
732                 {
733                         /* Multiplication has special rules when at least one operand is a
734                         matrix and the other is a vector or a matrix. */
735                         unsigned left_columns = basic_left->size&0xFFFF;
736                         unsigned right_rows = basic_right->size;
737                         if(basic_right->kind==BasicTypeDeclaration::MATRIX)
738                                 right_rows >>= 16;
739                         if(left_columns!=right_rows)
740                                 return;
741
742                         BasicTypeDeclaration *elem_result = (elem_compat==LEFT_CONVERTIBLE ? elem_right : elem_left);
743
744                         if(basic_left->kind==BasicTypeDeclaration::VECTOR)
745                                 type = find_type(*elem_result, BasicTypeDeclaration::VECTOR, basic_right->size&0xFFFF);
746                         else if(basic_right->kind==BasicTypeDeclaration::VECTOR)
747                                 type = find_type(*elem_result, BasicTypeDeclaration::VECTOR, basic_left->size>>16);
748                         else
749                                 type = find_type(*elem_result, BasicTypeDeclaration::MATRIX, (basic_left->size&0xFFFF0000)|(basic_right->size&0xFFFF));
750                 }
751                 else if(compat==NOT_COMPATIBLE)
752                 {
753                         // Arithmetic between scalars and matrices or vectors is supported.
754                         if(is_scalar(*basic_left) && is_vector_or_matrix(*basic_right))
755                                 type = (elem_compat==RIGHT_CONVERTIBLE ? find_type(*elem_left, basic_right->kind, basic_right->size) : basic_right);
756                         else if(is_vector_or_matrix(*basic_left) && is_scalar(*basic_right))
757                                 type = (elem_compat==LEFT_CONVERTIBLE ? find_type(*elem_right, basic_left->kind, basic_left->size) : basic_left);
758                         else
759                                 return;
760                 }
761                 else if(compat==LEFT_CONVERTIBLE)
762                         type = basic_right;
763                 else
764                         type = basic_left;
765         }
766         else
767                 return;
768
769         if(assign && type!=basic_left)
770                 return;
771
772         bool converted = true;
773         if(compat==LEFT_CONVERTIBLE)
774                 convert_to(binary.left, *basic_right);
775         else if(compat==RIGHT_CONVERTIBLE)
776                 convert_to(binary.right, *basic_left);
777         else if(elem_compat==LEFT_CONVERTIBLE)
778                 converted = convert_to_element(binary.left, *elem_right);
779         else if(elem_compat==RIGHT_CONVERTIBLE)
780                 converted = convert_to_element(binary.right, *elem_left);
781
782         if(!converted)
783                 type = 0;
784
785         resolve(binary, type, assign);
786 }
787
788 void ExpressionResolver::visit(BinaryExpression &binary)
789 {
790         TraversingVisitor::visit(binary);
791         visit(binary, false);
792 }
793
794 void ExpressionResolver::visit(Assignment &assign)
795 {
796         TraversingVisitor::visit(assign);
797
798         if(assign.oper->token[0]!='=')
799                 return visit(assign, true);
800         else if(assign.left->type!=assign.right->type)
801         {
802                 BasicTypeDeclaration *basic_left = dynamic_cast<BasicTypeDeclaration *>(assign.left->type);
803                 BasicTypeDeclaration *basic_right = dynamic_cast<BasicTypeDeclaration *>(assign.right->type);
804                 if(!basic_left || !basic_right)
805                         return;
806
807                 Compatibility compat = get_compatibility(*basic_left, *basic_right);
808                 if(compat==RIGHT_CONVERTIBLE)
809                         convert_to(assign.right, *basic_left);
810                 else if(compat!=SAME_TYPE)
811                         return;
812         }
813
814         resolve(assign, assign.left->type, true);
815 }
816
817 void ExpressionResolver::visit(TernaryExpression &ternary)
818 {
819         TraversingVisitor::visit(ternary);
820
821         BasicTypeDeclaration *basic_cond = dynamic_cast<BasicTypeDeclaration *>(ternary.condition->type);
822         if(!basic_cond || basic_cond->kind!=BasicTypeDeclaration::BOOL)
823                 return;
824
825         TypeDeclaration *type = 0;
826         if(ternary.true_expr->type==ternary.false_expr->type)
827                 type = ternary.true_expr->type;
828         else
829         {
830                 BasicTypeDeclaration *basic_true = dynamic_cast<BasicTypeDeclaration *>(ternary.true_expr->type);
831                 BasicTypeDeclaration *basic_false = dynamic_cast<BasicTypeDeclaration *>(ternary.false_expr->type);
832                 if(!basic_true || !basic_false)
833                         return;
834
835                 Compatibility compat = get_compatibility(*basic_true, *basic_false);
836                 if(compat==NOT_COMPATIBLE)
837                         return;
838
839                 type = (compat==LEFT_CONVERTIBLE ? basic_true : basic_false);
840
841                 if(compat==LEFT_CONVERTIBLE)
842                         convert_to(ternary.true_expr, *basic_false);
843                 else if(compat==RIGHT_CONVERTIBLE)
844                         convert_to(ternary.false_expr, *basic_true);
845         }
846
847         resolve(ternary, type, false);
848 }
849
850 void ExpressionResolver::visit_constructor(FunctionCall &call)
851 {
852         if(call.arguments.empty())
853                 return;
854
855         auto i = stage->types.find(call.name);
856         if(i==stage->types.end())
857                 return;
858         else if(call.arguments.size()==1 && i->second==call.arguments[0]->type)
859                 ;
860         else if(BasicTypeDeclaration *basic = dynamic_cast<BasicTypeDeclaration *>(i->second))
861         {
862                 BasicTypeDeclaration *elem = get_element_type(*basic);
863                 if(!elem)
864                         return;
865
866                 vector<ArgumentInfo> args;
867                 args.reserve(call.arguments.size());
868                 unsigned arg_component_total = 0;
869                 bool has_matrices = false;
870                 for(const RefPtr<Expression> &a: call.arguments)
871                 {
872                         ArgumentInfo info;
873                         if(!(info.type=dynamic_cast<BasicTypeDeclaration *>(a->type)))
874                                 return;
875                         if(is_scalar(*info.type) || info.type->kind==BasicTypeDeclaration::BOOL)
876                                 info.component_count = 1;
877                         else if(info.type->kind==BasicTypeDeclaration::VECTOR)
878                                 info.component_count = info.type->size;
879                         else if(info.type->kind==BasicTypeDeclaration::MATRIX)
880                         {
881                                 info.component_count = (info.type->size>>16)*(info.type->size&0xFFFF);
882                                 has_matrices = true;
883                         }
884                         else
885                                 return;
886                         arg_component_total += info.component_count;
887                         args.push_back(info);
888                 }
889
890                 bool convert_args = false;
891                 if((is_scalar(*basic) || basic->kind==BasicTypeDeclaration::BOOL) && call.arguments.size()==1 && !has_matrices)
892                 {
893                         if(arg_component_total>1)
894                                 truncate_vector(call.arguments.front(), 1);
895
896                         /* Single-element type constructors never need to convert their
897                         arguments because the constructor *is* the conversion. */
898                 }
899                 else if(basic->kind==BasicTypeDeclaration::VECTOR && !has_matrices)
900                 {
901                         /* Vector constructors need either a single scalar argument or
902                         enough components to fill out the vector. */
903                         if(arg_component_total!=1 && arg_component_total<basic->size)
904                                 return;
905
906                         /* A vector of same size can be converted directly.  For other
907                         combinations the individual arguments need to be converted. */
908                         if(call.arguments.size()==1)
909                         {
910                                 if(arg_component_total==1)
911                                         convert_args = true;
912                                 else if(arg_component_total>basic->size)
913                                         truncate_vector(call.arguments.front(), basic->size);
914                         }
915                         else if(arg_component_total==basic->size)
916                                 convert_args = true;
917                         else
918                                 return;
919                 }
920                 else if(basic->kind==BasicTypeDeclaration::MATRIX)
921                 {
922                         unsigned column_count = basic->size&0xFFFF;
923                         unsigned row_count = basic->size>>16;
924                         if(call.arguments.size()==1)
925                         {
926                                 /* A matrix can be constructed from a single element or another
927                                 matrix of sufficient size. */
928                                 if(arg_component_total==1)
929                                         convert_args = true;
930                                 else if(args.front().type->kind==BasicTypeDeclaration::MATRIX)
931                                 {
932                                         unsigned arg_columns = args.front().type->size&0xFFFF;
933                                         unsigned arg_rows = args.front().type->size>>16;
934                                         if(arg_columns<column_count || arg_rows<row_count)
935                                                 return;
936
937                                         /* Always generate a temporary here and let the optimization
938                                         stage inline it if that's reasonable. */
939                                         RefPtr<VariableDeclaration> temporary = new VariableDeclaration;
940                                         temporary->type = args.front().type->name;
941                                         temporary->name = get_unused_variable_name(*current_block, "_temp");
942                                         temporary->init_expression = call.arguments.front();
943                                         current_block->body.insert(insert_point, temporary);
944
945                                         // Create expressions to build each column.
946                                         vector<RefPtr<Expression> > columns;
947                                         columns.reserve(column_count);
948                                         for(unsigned j=0; j<column_count; ++j)
949                                         {
950                                                 RefPtr<VariableReference> ref = new VariableReference;
951                                                 ref->name = temporary->name;
952
953                                                 RefPtr<Literal> index = new Literal;
954                                                 index->token = lexical_cast<string>(j);
955                                                 index->value = static_cast<int>(j);
956
957                                                 RefPtr<BinaryExpression> subscript = new BinaryExpression;
958                                                 subscript->left = ref;
959                                                 subscript->oper = &Operator::get_operator("[", Operator::BINARY);
960                                                 subscript->right = index;
961                                                 subscript->type = args.front().type->base_type;
962
963                                                 columns.push_back(subscript);
964                                                 if(arg_rows>row_count)
965                                                         truncate_vector(columns.back(), row_count);
966                                         }
967
968                                         call.arguments.resize(column_count);
969                                         copy(columns.begin(), columns.end(), call.arguments.begin());
970
971                                         /* Let VariableResolver process the new nodes and finish
972                                         resolving the constructor on the next pass. */
973                                         r_any_resolved = true;
974                                         return;
975                                 }
976                                 else
977                                         return;
978                         }
979                         else if(arg_component_total==column_count*row_count && !has_matrices)
980                         {
981                                 /* Construct a matrix from individual components in column-major
982                                 order.  Arguments must align at column boundaries. */
983                                 vector<RefPtr<Expression> > columns;
984                                 columns.reserve(column_count);
985
986                                 vector<RefPtr<Expression> > column_args;
987                                 column_args.reserve(row_count);
988                                 unsigned column_component_count = 0;
989
990                                 for(unsigned j=0; j<call.arguments.size(); ++j)
991                                 {
992                                         const ArgumentInfo &info = args[j];
993                                         if(!column_component_count && info.type->kind==BasicTypeDeclaration::VECTOR && info.component_count==row_count)
994                                                 // A vector filling the entire column can be used as is.
995                                                 columns.push_back(call.arguments[j]);
996                                         else
997                                         {
998                                                 column_args.push_back(call.arguments[j]);
999                                                 column_component_count += info.component_count;
1000                                                 if(column_component_count==row_count)
1001                                                 {
1002                                                         /* The column has filled up.  Create a vector constructor
1003                                                         for it.*/
1004                                                         RefPtr<FunctionCall> column_call = new FunctionCall;
1005                                                         column_call->name = basic->base_type->name;
1006                                                         column_call->constructor = true;
1007                                                         column_call->arguments.resize(column_args.size());
1008                                                         copy(column_args.begin(), column_args.end(), column_call->arguments.begin());
1009                                                         column_call->type = basic->base_type;
1010                                                         visit_constructor(*column_call);
1011                                                         columns.push_back(column_call);
1012
1013                                                         column_args.clear();
1014                                                         column_component_count = 0;
1015                                                 }
1016                                                 else if(column_component_count>row_count)
1017                                                         // Argument alignment mismatch.
1018                                                         return;
1019                                         }
1020                                 }
1021                         }
1022                         else
1023                                 return;
1024                 }
1025                 else
1026                         return;
1027
1028                 if(convert_args)
1029                 {
1030                         // The argument list may have changed so can't rely on args.
1031                         for(RefPtr<Expression> &a: call.arguments)
1032                                 if(BasicTypeDeclaration *basic_arg = dynamic_cast<BasicTypeDeclaration *>(a->type))
1033                                 {
1034                                         BasicTypeDeclaration *elem_arg = get_element_type(*basic_arg);
1035                                         if(elem_arg!=elem)
1036                                                 convert_to_element(a, *elem);
1037                                 }
1038                 }
1039         }
1040         else if(StructDeclaration *strct = dynamic_cast<StructDeclaration *>(i->second))
1041         {
1042                 if(call.arguments.size()!=strct->members.body.size())
1043                         return;
1044
1045                 auto j = call.arguments.begin();
1046                 for(const RefPtr<Statement> &s: strct->members.body)
1047                 {
1048                         if(VariableDeclaration *var = dynamic_cast<VariableDeclaration *>(s.get()))
1049                         {
1050                                 if(!(*j)->type || (*j)->type!=var->type_declaration)
1051                                         return;
1052                         }
1053                         else
1054                                 return;
1055                         ++j;
1056                 }
1057         }
1058
1059         resolve(call, i->second, false);
1060 }
1061
1062 void ExpressionResolver::visit(FunctionCall &call)
1063 {
1064         TraversingVisitor::visit(call);
1065
1066         if(call.declaration)
1067                 resolve(call, call.declaration->return_type_declaration, false);
1068         else if(call.constructor)
1069                 visit_constructor(call);
1070 }
1071
1072 void ExpressionResolver::visit(BasicTypeDeclaration &type)
1073 {
1074         basic_types.push_back(&type);
1075 }
1076
1077 void ExpressionResolver::visit(VariableDeclaration &var)
1078 {
1079         TraversingVisitor::visit(var);
1080         if(!var.init_expression)
1081                 return;
1082
1083         BasicTypeDeclaration *var_basic = dynamic_cast<BasicTypeDeclaration *>(var.type_declaration);
1084         BasicTypeDeclaration *init_basic = dynamic_cast<BasicTypeDeclaration *>(var.init_expression->type);
1085         if(!var_basic || !init_basic)
1086                 return;
1087
1088         Compatibility compat = get_compatibility(*var_basic, *init_basic);
1089         if(compat==RIGHT_CONVERTIBLE)
1090                 convert_to(var.init_expression, *var_basic);
1091 }
1092
1093
1094 bool FunctionResolver::apply(Stage &s)
1095 {
1096         stage = &s;
1097         s.functions.clear();
1098         r_any_resolved = false;
1099         s.content.visit(*this);
1100         return r_any_resolved;
1101 }
1102
1103 bool FunctionResolver::can_convert_arguments(const FunctionCall &call, const FunctionDeclaration &decl)
1104 {
1105         if(decl.parameters.size()!=call.arguments.size())
1106                 return false;
1107
1108         for(unsigned j=0; j<call.arguments.size(); ++j)
1109         {
1110                 const TypeDeclaration *arg_type = call.arguments[j]->type;
1111                 const TypeDeclaration *param_type = decl.parameters[j]->type_declaration;
1112                 if(arg_type==param_type)
1113                         continue;
1114
1115                 const BasicTypeDeclaration *arg_basic = dynamic_cast<const BasicTypeDeclaration *>(arg_type);
1116                 const BasicTypeDeclaration *param_basic = dynamic_cast<const BasicTypeDeclaration *>(param_type);
1117                 if(arg_basic && param_basic && can_convert(*arg_basic, *param_basic))
1118                         continue;
1119
1120                 return false;
1121         }
1122
1123         return true;
1124 }
1125
1126 void FunctionResolver::visit(FunctionCall &call)
1127 {
1128         FunctionDeclaration *declaration = 0;
1129         if(stage->types.count(call.name))
1130                 call.constructor = true;
1131         else
1132         {
1133                 string arg_types;
1134                 bool has_signature = true;
1135                 for(auto i=call.arguments.begin(); (has_signature && i!=call.arguments.end()); ++i)
1136                 {
1137                         if((*i)->type)
1138                                 append(arg_types, ",", (*i)->type->name);
1139                         else
1140                                 has_signature = false;
1141                 }
1142
1143                 if(has_signature)
1144                 {
1145                         auto i = stage->functions.find(format("%s(%s)", call.name, arg_types));
1146                         declaration = (i!=stage->functions.end() ? i->second : 0);
1147
1148                         if(!declaration)
1149                         {
1150                                 for(i=stage->functions.lower_bound(call.name+"("); (i!=stage->functions.end() && i->second->name==call.name); ++i)
1151                                         if(can_convert_arguments(call, *i->second))
1152                                         {
1153                                                 if(declaration)
1154                                                 {
1155                                                         declaration = 0;
1156                                                         break;
1157                                                 }
1158                                                 else
1159                                                         declaration = i->second;
1160                                         }
1161                         }
1162                 }
1163         }
1164
1165         r_any_resolved |= (declaration!=call.declaration);
1166         call.declaration = declaration;
1167
1168         TraversingVisitor::visit(call);
1169 }
1170
1171 void FunctionResolver::visit(FunctionDeclaration &func)
1172 {
1173         if(func.signature.empty())
1174         {
1175                 string param_types;
1176                 for(const RefPtr<VariableDeclaration> &p: func.parameters)
1177                 {
1178                         if(p->type_declaration)
1179                                 append(param_types, ",", p->type_declaration->name);
1180                         else
1181                                 return;
1182                 }
1183                 func.signature = format("(%s)", param_types);
1184                 r_any_resolved = true;
1185         }
1186
1187         string key = func.name+func.signature;
1188         FunctionDeclaration *&stage_decl = stage->functions[key];
1189         vector<FunctionDeclaration *> &decls = declarations[key];
1190         if(func.definition==&func)
1191         {
1192                 if(stage_decl && stage_decl->definition)
1193                 {
1194                         if(!func.overrd)
1195                                 stage->diagnostics.push_back(Diagnostic(Diagnostic::WARN, func.source, func.line,
1196                                         format("Overriding function '%s' without the override keyword is deprecated", key)));
1197                         if(!stage_decl->definition->virtua)
1198                                 stage->diagnostics.push_back(Diagnostic(Diagnostic::WARN, func.source, func.line,
1199                                         format("Overriding function '%s' not declared as virtual is deprecated", key)));
1200                 }
1201                 stage_decl = &func;
1202
1203                 // Set all previous declarations to use this definition.
1204                 for(FunctionDeclaration *f: decls)
1205                 {
1206                         r_any_resolved |= (func.definition!=f->definition);
1207                         f->definition = func.definition;
1208                         f->body.body.clear();
1209                 }
1210         }
1211         else
1212         {
1213                 FunctionDeclaration *definition = (stage_decl ? stage_decl->definition : 0);
1214                 r_any_resolved |= (definition!=func.definition);
1215                 func.definition = definition;
1216
1217                 if(!stage_decl)
1218                         stage_decl = &func;
1219         }
1220         decls.push_back(&func);
1221
1222         TraversingVisitor::visit(func);
1223 }
1224
1225 } // namespace SL
1226 } // namespace GL
1227 } // namespace Msp