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