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