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