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