]> git.tdb.fi Git - libs/gl.git/blob - source/glsl/resolve.cpp
Convert Technique and RenderPass loaders to use shared actions
[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                         index = 0;
297                         for(NodeList<Statement>::const_iterator j=strct->members.body.begin(); (j!=strct->members.body.end() && j->get()!=i->second); ++j)
298                                 ++index;
299
300                         if(record_target)
301                                 add_to_chain(r_assignment_target, Assignment::Target::MEMBER, index);
302                 }
303         }
304         else if(BasicTypeDeclaration *basic = dynamic_cast<BasicTypeDeclaration *>(memacc.left->type))
305         {
306                 bool scalar_swizzle = ((basic->kind==BasicTypeDeclaration::INT || basic->kind==BasicTypeDeclaration::FLOAT) && memacc.member.size()==1);
307                 bool vector_swizzle = (basic->kind==BasicTypeDeclaration::VECTOR && memacc.member.size()<=4);
308                 if(scalar_swizzle || vector_swizzle)
309                 {
310                         static const char component_names[] = { 'x', 'r', 's', 'y', 'g', 't', 'z', 'b', 'p', 'w', 'a', 'q' };
311
312                         bool ok = true;
313                         UInt8 components[4] = { };
314                         for(unsigned i=0; (ok && i<memacc.member.size()); ++i)
315                                 ok = ((components[i] = (find(component_names, component_names+12, memacc.member[i])-component_names)/3) < 4);
316
317                         if(ok)
318                         {
319                                 Swizzle *swizzle = new Swizzle;
320                                 swizzle->source = memacc.source;
321                                 swizzle->line = memacc.line;
322                                 swizzle->oper = memacc.oper;
323                                 swizzle->left = memacc.left;
324                                 swizzle->component_group = memacc.member;
325                                 swizzle->count = memacc.member.size();
326                                 copy(components, components+memacc.member.size(), swizzle->components);
327                                 r_replacement_expr = swizzle;
328                         }
329                 }
330         }
331
332         r_any_resolved |= (declaration!=memacc.declaration || index!=memacc.index);
333         memacc.declaration = declaration;
334         memacc.index = index;
335 }
336
337 void VariableResolver::visit(Swizzle &swizzle)
338 {
339         TraversingVisitor::visit(swizzle);
340
341         if(record_target)
342         {
343                 unsigned mask = 0;
344                 for(unsigned i=0; i<swizzle.count; ++i)
345                         mask |= 1<<swizzle.components[i];
346                 add_to_chain(r_assignment_target, Assignment::Target::SWIZZLE, mask);
347         }
348 }
349
350 void VariableResolver::visit(BinaryExpression &binary)
351 {
352         if(binary.oper->token[0]=='[')
353         {
354                 {
355                         /* The subscript expression is not a part of the primary assignment
356                         target. */
357                         SetFlag set(record_target, false);
358                         visit(binary.right);
359                 }
360                 visit(binary.left);
361
362                 if(record_target)
363                 {
364                         unsigned index = 0x3F;
365                         if(Literal *literal_subscript = dynamic_cast<Literal *>(binary.right.get()))
366                                 if(literal_subscript->value.check_type<int>())
367                                         index = literal_subscript->value.value<int>();
368                         add_to_chain(r_assignment_target, Assignment::Target::ARRAY, index);
369                 }
370         }
371         else
372                 TraversingVisitor::visit(binary);
373 }
374
375 void VariableResolver::visit(Assignment &assign)
376 {
377         {
378                 SetFlag set(record_target);
379                 r_assignment_target = Assignment::Target();
380                 visit(assign.left);
381                 r_any_resolved |= (r_assignment_target<assign.target || assign.target<r_assignment_target);
382                 assign.target = r_assignment_target;
383         }
384
385         r_self_referencing = false;
386         visit(assign.right);
387         assign.self_referencing = (r_self_referencing || assign.oper->token[0]!='=');
388 }
389
390 void VariableResolver::merge_layouts(Layout &to_layout, const Layout &from_layout)
391 {
392         for(vector<Layout::Qualifier>::const_iterator i=from_layout.qualifiers.begin(); i!=from_layout.qualifiers.end(); ++i)
393         {
394                 bool found = false;
395                 for(vector<Layout::Qualifier>::iterator j=to_layout.qualifiers.begin(); (!found && j!=to_layout.qualifiers.end()); ++j)
396                         if(j->name==i->name)
397                         {
398                                 j->has_value = i->value;
399                                 j->value = i->value;
400                                 found = true;
401                         }
402
403                 if(!found)
404                         to_layout.qualifiers.push_back(*i);
405         }
406 }
407
408 void VariableResolver::visit(VariableDeclaration &var)
409 {
410         TraversingVisitor::visit(var);
411         VariableDeclaration *&ptr = current_block->variables[var.name];
412         if(!ptr)
413                 ptr = &var;
414         else if(!current_block->parent && ptr->interface==var.interface && ptr->type==var.type)
415         {
416                 if(ptr->source==BUILTIN_SOURCE)
417                         redeclared_builtins.push_back(&var);
418                 else
419                         stage->diagnostics.push_back(Diagnostic(Diagnostic::WARN, var.source, var.line,
420                                 format("Redeclaring non-builtin variable '%s' is deprecated", var.name)));
421
422                 if(var.init_expression)
423                         ptr->init_expression = var.init_expression;
424                 if(var.layout)
425                 {
426                         if(ptr->layout)
427                                 merge_layouts(*ptr->layout, *var.layout);
428                         else
429                                 ptr->layout = var.layout;
430                 }
431                 nodes_to_remove.insert(&var);
432
433                 r_any_resolved = true;
434         }
435 }
436
437 void VariableResolver::visit(InterfaceBlock &iface)
438 {
439         /* Block names can be reused in different interfaces.  Prefix the name with
440         the first character of the interface to avoid conflicts. */
441         stage->interface_blocks.insert(make_pair(format("%s %s", iface.interface, iface.block_name), &iface));
442         if(!iface.instance_name.empty())
443                 stage->interface_blocks.insert(make_pair(iface.instance_name, &iface));
444
445         TraversingVisitor::visit(iface);
446 }
447
448
449 ExpressionResolver::ExpressionResolver():
450         stage(0),
451         r_any_resolved(false)
452 { }
453
454 bool ExpressionResolver::apply(Stage &s)
455 {
456         stage = &s;
457         r_any_resolved = false;
458         s.content.visit(*this);
459         return r_any_resolved;
460 }
461
462 bool ExpressionResolver::is_scalar(BasicTypeDeclaration &type)
463 {
464         return (type.kind==BasicTypeDeclaration::INT || type.kind==BasicTypeDeclaration::FLOAT);
465 }
466
467 bool ExpressionResolver::is_vector_or_matrix(BasicTypeDeclaration &type)
468 {
469         return (type.kind==BasicTypeDeclaration::VECTOR || type.kind==BasicTypeDeclaration::MATRIX);
470 }
471
472 BasicTypeDeclaration *ExpressionResolver::get_element_type(BasicTypeDeclaration &type)
473 {
474         if(is_vector_or_matrix(type) || type.kind==BasicTypeDeclaration::ARRAY)
475         {
476                 BasicTypeDeclaration *basic_base = dynamic_cast<BasicTypeDeclaration *>(type.base_type);
477                 return (basic_base ? get_element_type(*basic_base) : 0);
478         }
479         else
480                 return &type;
481 }
482
483 bool ExpressionResolver::can_convert(BasicTypeDeclaration &from, BasicTypeDeclaration &to)
484 {
485         if(from.kind==BasicTypeDeclaration::INT && to.kind==BasicTypeDeclaration::FLOAT)
486                 return from.size<=to.size;
487         else if(from.kind!=to.kind)
488                 return false;
489         else if((from.kind==BasicTypeDeclaration::VECTOR || from.kind==BasicTypeDeclaration::MATRIX) && from.size==to.size)
490         {
491                 BasicTypeDeclaration *from_base = dynamic_cast<BasicTypeDeclaration *>(from.base_type);
492                 BasicTypeDeclaration *to_base = dynamic_cast<BasicTypeDeclaration *>(to.base_type);
493                 return (from_base && to_base && can_convert(*from_base, *to_base));
494         }
495         else
496                 return false;
497 }
498
499 ExpressionResolver::Compatibility ExpressionResolver::get_compatibility(BasicTypeDeclaration &left, BasicTypeDeclaration &right)
500 {
501         if(&left==&right)
502                 return SAME_TYPE;
503         else if(can_convert(left, right))
504                 return LEFT_CONVERTIBLE;
505         else if(can_convert(right, left))
506                 return RIGHT_CONVERTIBLE;
507         else
508                 return NOT_COMPATIBLE;
509 }
510
511 BasicTypeDeclaration *ExpressionResolver::find_type(BasicTypeDeclaration::Kind kind, unsigned size)
512 {
513         for(vector<BasicTypeDeclaration *>::const_iterator i=basic_types.begin(); i!=basic_types.end(); ++i)
514                 if((*i)->kind==kind && (*i)->size==size)
515                         return *i;
516         return 0;
517 }
518
519 BasicTypeDeclaration *ExpressionResolver::find_type(BasicTypeDeclaration &elem_type, BasicTypeDeclaration::Kind kind, unsigned size)
520 {
521         for(vector<BasicTypeDeclaration *>::const_iterator i=basic_types.begin(); i!=basic_types.end(); ++i)
522                 if(get_element_type(**i)==&elem_type && (*i)->kind==kind && (*i)->size==size)
523                         return *i;
524         return 0;
525 }
526
527 void ExpressionResolver::convert_to(RefPtr<Expression> &expr, BasicTypeDeclaration &type)
528 {
529         RefPtr<FunctionCall> call = new FunctionCall;
530         call->name = type.name;
531         call->constructor = true;
532         call->arguments.push_back_nocopy(expr);
533         call->type = &type;
534         expr = call;
535 }
536
537 bool ExpressionResolver::convert_to_element(RefPtr<Expression> &expr, BasicTypeDeclaration &elem_type)
538 {
539         if(BasicTypeDeclaration *expr_basic = dynamic_cast<BasicTypeDeclaration *>(expr->type))
540         {
541                 BasicTypeDeclaration *to_type = &elem_type;
542                 if(is_vector_or_matrix(*expr_basic))
543                         to_type = find_type(elem_type, expr_basic->kind, expr_basic->size);
544                 if(to_type)
545                 {
546                         convert_to(expr, *to_type);
547                         return true;
548                 }
549         }
550
551         return false;
552 }
553
554 bool ExpressionResolver::truncate_vector(RefPtr<Expression> &expr, unsigned size)
555 {
556         if(BasicTypeDeclaration *expr_basic = dynamic_cast<BasicTypeDeclaration *>(expr->type))
557                 if(BasicTypeDeclaration *expr_elem = get_element_type(*expr_basic))
558                 {
559                         RefPtr<Swizzle> swizzle = new Swizzle;
560                         swizzle->left = expr;
561                         swizzle->oper = &Operator::get_operator(".", Operator::POSTFIX);
562                         swizzle->component_group = string("xyzw", size);
563                         swizzle->count = size;
564                         for(unsigned i=0; i<size; ++i)
565                                 swizzle->components[i] = i;
566                         if(size==1)
567                                 swizzle->type = expr_elem;
568                         else
569                                 swizzle->type = find_type(*expr_elem, BasicTypeDeclaration::VECTOR, size);
570                         expr = swizzle;
571
572                         return true;
573                 }
574
575         return false;
576 }
577
578 void ExpressionResolver::resolve(Expression &expr, TypeDeclaration *type, bool lvalue)
579 {
580         r_any_resolved |= (type!=expr.type || lvalue!=expr.lvalue);
581         expr.type = type;
582         expr.lvalue = lvalue;
583 }
584
585 void ExpressionResolver::visit(Block &block)
586 {
587         SetForScope<Block *> set_block(current_block, &block);
588         for(NodeList<Statement>::iterator i=block.body.begin(); i!=block.body.end(); ++i)
589         {
590                 insert_point = i;
591                 (*i)->visit(*this);
592         }
593 }
594
595 void ExpressionResolver::visit(Literal &literal)
596 {
597         if(literal.value.check_type<bool>())
598                 resolve(literal, find_type(BasicTypeDeclaration::BOOL, 1), false);
599         else if(literal.value.check_type<int>())
600                 resolve(literal, find_type(BasicTypeDeclaration::INT, 32), false);
601         else if(literal.value.check_type<float>())
602                 resolve(literal, find_type(BasicTypeDeclaration::FLOAT, 32), false);
603 }
604
605 void ExpressionResolver::visit(VariableReference &var)
606 {
607         if(var.declaration)
608                 resolve(var, var.declaration->type_declaration, true);
609 }
610
611 void ExpressionResolver::visit(InterfaceBlockReference &iface)
612 {
613         if(iface.declaration)
614                 resolve(iface, iface.declaration->type_declaration, true);
615 }
616
617 void ExpressionResolver::visit(MemberAccess &memacc)
618 {
619         TraversingVisitor::visit(memacc);
620
621         if(memacc.declaration)
622                 resolve(memacc, memacc.declaration->type_declaration, memacc.left->lvalue);
623 }
624
625 void ExpressionResolver::visit(Swizzle &swizzle)
626 {
627         TraversingVisitor::visit(swizzle);
628
629         if(BasicTypeDeclaration *left_basic = dynamic_cast<BasicTypeDeclaration *>(swizzle.left->type))
630         {
631                 BasicTypeDeclaration *left_elem = get_element_type(*left_basic);
632                 if(swizzle.count==1)
633                         resolve(swizzle, left_elem, swizzle.left->lvalue);
634                 else if(left_basic->kind==BasicTypeDeclaration::VECTOR && left_elem)
635                         resolve(swizzle, find_type(*left_elem, left_basic->kind, swizzle.count), swizzle.left->lvalue);
636         }
637 }
638
639 void ExpressionResolver::visit(UnaryExpression &unary)
640 {
641         TraversingVisitor::visit(unary);
642
643         BasicTypeDeclaration *basic = dynamic_cast<BasicTypeDeclaration *>(unary.expression->type);
644         if(!basic)
645                 return;
646
647         char oper = unary.oper->token[0];
648         if(oper=='!')
649         {
650                 if(basic->kind!=BasicTypeDeclaration::BOOL)
651                         return;
652         }
653         else if(oper=='~')
654         {
655                 if(basic->kind!=BasicTypeDeclaration::INT)
656                         return;
657         }
658         else if(oper=='+' || oper=='-')
659         {
660                 BasicTypeDeclaration *elem = get_element_type(*basic);
661                 if(!elem || !is_scalar(*elem))
662                         return;
663         }
664         resolve(unary, basic, unary.expression->lvalue);
665 }
666
667 void ExpressionResolver::visit(BinaryExpression &binary, bool assign)
668 {
669         /* Binary operators are only defined for basic types (not for image or
670         structure types). */
671         BasicTypeDeclaration *basic_left = dynamic_cast<BasicTypeDeclaration *>(binary.left->type);
672         BasicTypeDeclaration *basic_right = dynamic_cast<BasicTypeDeclaration *>(binary.right->type);
673         if(!basic_left || !basic_right)
674                 return;
675
676         char oper = binary.oper->token[0];
677         if(oper=='[')
678         {
679                 /* Subscripting operates on vectors, matrices and arrays, and the right
680                 operand must be an integer. */
681                 if((!is_vector_or_matrix(*basic_left) && basic_left->kind!=BasicTypeDeclaration::ARRAY) || basic_right->kind!=BasicTypeDeclaration::INT)
682                         return;
683
684                 resolve(binary, basic_left->base_type, binary.left->lvalue);
685                 return;
686         }
687         else if(basic_left->kind==BasicTypeDeclaration::ARRAY || basic_right->kind==BasicTypeDeclaration::ARRAY)
688                 // No other binary operator can be used with arrays.
689                 return;
690
691         BasicTypeDeclaration *elem_left = get_element_type(*basic_left);
692         BasicTypeDeclaration *elem_right = get_element_type(*basic_right);
693         if(!elem_left || !elem_right)
694                 return;
695
696         Compatibility compat = get_compatibility(*basic_left, *basic_right);
697         Compatibility elem_compat = get_compatibility(*elem_left, *elem_right);
698         if(elem_compat==NOT_COMPATIBLE)
699                 return;
700         if(assign && (compat==LEFT_CONVERTIBLE || elem_compat==LEFT_CONVERTIBLE))
701                 return;
702
703         TypeDeclaration *type = 0;
704         char oper2 = binary.oper->token[1];
705         if((oper=='<' && oper2!='<') || (oper=='>' && oper2!='>'))
706         {
707                 /* Relational operators compare two scalar integer or floating-point
708                 values. */
709                 if(!is_scalar(*elem_left) || !is_scalar(*elem_right) || compat==NOT_COMPATIBLE)
710                         return;
711
712                 type = find_type(BasicTypeDeclaration::BOOL, 1);
713         }
714         else if((oper=='=' || oper=='!') && oper2=='=')
715         {
716                 // Equality comparison can be done on any compatible types.
717                 if(compat==NOT_COMPATIBLE)
718                         return;
719
720                 type = find_type(BasicTypeDeclaration::BOOL, 1);
721         }
722         else if(oper2=='&' || oper2=='|' || oper2=='^')
723         {
724                 // Logical operators can only be applied to booleans.
725                 if(basic_left->kind!=BasicTypeDeclaration::BOOL || basic_right->kind!=BasicTypeDeclaration::BOOL)
726                         return;
727
728                 type = basic_left;
729         }
730         else if((oper=='&' || oper=='|' || oper=='^' || oper=='%') && !oper2)
731         {
732                 // Bitwise operators and modulo can only be applied to integers.
733                 if(basic_left->kind!=BasicTypeDeclaration::INT || basic_right->kind!=BasicTypeDeclaration::INT)
734                         return;
735
736                 type = (compat==LEFT_CONVERTIBLE ? basic_right : basic_left);
737         }
738         else if((oper=='<' || oper=='>') && oper2==oper)
739         {
740                 // Shifts apply to integer scalars and vectors, with some restrictions.
741                 if(elem_left->kind!=BasicTypeDeclaration::INT || elem_right->kind!=BasicTypeDeclaration::INT)
742                         return;
743                 unsigned left_size = (basic_left->kind==BasicTypeDeclaration::INT ? 1 : basic_left->kind==BasicTypeDeclaration::VECTOR ? basic_left->size : 0);
744                 unsigned right_size = (basic_right->kind==BasicTypeDeclaration::INT ? 1 : basic_right->kind==BasicTypeDeclaration::VECTOR ? basic_right->size : 0);
745                 if(!left_size || (left_size==1 && right_size!=1) || (left_size>1 && right_size!=1 && right_size!=left_size))
746                         return;
747
748                 /* If the left operand is a vector and right is scalar, convert the right
749                 operand to a vector too. */
750                 if(left_size>1 && right_size==1)
751                 {
752                         BasicTypeDeclaration *vec_right = find_type(*elem_right, basic_left->kind, basic_left->size);
753                         if(!vec_right)
754                                 return;
755
756                         convert_to(binary.right, *vec_right);
757                 }
758
759                 type = basic_left;
760                 // Don't perform conversion even if the operands are of different sizes.
761                 compat = SAME_TYPE;
762         }
763         else if(oper=='+' || oper=='-' || oper=='*' || oper=='/')
764         {
765                 // Arithmetic operators require scalar elements.
766                 if(!is_scalar(*elem_left) || !is_scalar(*elem_right))
767                         return;
768
769                 if(oper=='*' && is_vector_or_matrix(*basic_left) && is_vector_or_matrix(*basic_right) &&
770                         (basic_left->kind==BasicTypeDeclaration::MATRIX || basic_right->kind==BasicTypeDeclaration::MATRIX))
771                 {
772                         /* Multiplication has special rules when at least one operand is a
773                         matrix and the other is a vector or a matrix. */
774                         unsigned left_columns = basic_left->size&0xFFFF;
775                         unsigned right_rows = basic_right->size;
776                         if(basic_right->kind==BasicTypeDeclaration::MATRIX)
777                                 right_rows >>= 16;
778                         if(left_columns!=right_rows)
779                                 return;
780
781                         BasicTypeDeclaration *elem_result = (elem_compat==LEFT_CONVERTIBLE ? elem_right : elem_left);
782
783                         if(basic_left->kind==BasicTypeDeclaration::VECTOR)
784                                 type = find_type(*elem_result, BasicTypeDeclaration::VECTOR, basic_right->size&0xFFFF);
785                         else if(basic_right->kind==BasicTypeDeclaration::VECTOR)
786                                 type = find_type(*elem_result, BasicTypeDeclaration::VECTOR, basic_left->size>>16);
787                         else
788                                 type = find_type(*elem_result, BasicTypeDeclaration::MATRIX, (basic_left->size&0xFFFF0000)|(basic_right->size&0xFFFF));
789                 }
790                 else if(compat==NOT_COMPATIBLE)
791                 {
792                         // Arithmetic between scalars and matrices or vectors is supported.
793                         if(is_scalar(*basic_left) && is_vector_or_matrix(*basic_right))
794                                 type = (elem_compat==RIGHT_CONVERTIBLE ? find_type(*elem_left, basic_right->kind, basic_right->size) : basic_right);
795                         else if(is_vector_or_matrix(*basic_left) && is_scalar(*basic_right))
796                                 type = (elem_compat==LEFT_CONVERTIBLE ? find_type(*elem_right, basic_left->kind, basic_left->size) : basic_left);
797                         else
798                                 return;
799                 }
800                 else if(compat==LEFT_CONVERTIBLE)
801                         type = basic_right;
802                 else
803                         type = basic_left;
804         }
805         else
806                 return;
807
808         if(assign && type!=basic_left)
809                 return;
810
811         bool converted = true;
812         if(compat==LEFT_CONVERTIBLE)
813                 convert_to(binary.left, *basic_right);
814         else if(compat==RIGHT_CONVERTIBLE)
815                 convert_to(binary.right, *basic_left);
816         else if(elem_compat==LEFT_CONVERTIBLE)
817                 converted = convert_to_element(binary.left, *elem_right);
818         else if(elem_compat==RIGHT_CONVERTIBLE)
819                 converted = convert_to_element(binary.right, *elem_left);
820
821         if(!converted)
822                 type = 0;
823
824         resolve(binary, type, assign);
825 }
826
827 void ExpressionResolver::visit(BinaryExpression &binary)
828 {
829         TraversingVisitor::visit(binary);
830         visit(binary, false);
831 }
832
833 void ExpressionResolver::visit(Assignment &assign)
834 {
835         TraversingVisitor::visit(assign);
836
837         if(assign.oper->token[0]!='=')
838                 return visit(assign, true);
839         else if(assign.left->type!=assign.right->type)
840         {
841                 BasicTypeDeclaration *basic_left = dynamic_cast<BasicTypeDeclaration *>(assign.left->type);
842                 BasicTypeDeclaration *basic_right = dynamic_cast<BasicTypeDeclaration *>(assign.right->type);
843                 if(!basic_left || !basic_right)
844                         return;
845
846                 Compatibility compat = get_compatibility(*basic_left, *basic_right);
847                 if(compat==RIGHT_CONVERTIBLE)
848                         convert_to(assign.right, *basic_left);
849                 else if(compat!=SAME_TYPE)
850                         return;
851         }
852
853         resolve(assign, assign.left->type, true);
854 }
855
856 void ExpressionResolver::visit(TernaryExpression &ternary)
857 {
858         TraversingVisitor::visit(ternary);
859
860         BasicTypeDeclaration *basic_cond = dynamic_cast<BasicTypeDeclaration *>(ternary.condition->type);
861         if(!basic_cond || basic_cond->kind!=BasicTypeDeclaration::BOOL)
862                 return;
863
864         TypeDeclaration *type = 0;
865         if(ternary.true_expr->type==ternary.false_expr->type)
866                 type = ternary.true_expr->type;
867         else
868         {
869                 BasicTypeDeclaration *basic_true = dynamic_cast<BasicTypeDeclaration *>(ternary.true_expr->type);
870                 BasicTypeDeclaration *basic_false = dynamic_cast<BasicTypeDeclaration *>(ternary.false_expr->type);
871                 if(!basic_true || !basic_false)
872                         return;
873
874                 Compatibility compat = get_compatibility(*basic_true, *basic_false);
875                 if(compat==NOT_COMPATIBLE)
876                         return;
877
878                 type = (compat==LEFT_CONVERTIBLE ? basic_true : basic_false);
879
880                 if(compat==LEFT_CONVERTIBLE)
881                         convert_to(ternary.true_expr, *basic_false);
882                 else if(compat==RIGHT_CONVERTIBLE)
883                         convert_to(ternary.false_expr, *basic_true);
884         }
885
886         resolve(ternary, type, false);
887 }
888
889 void ExpressionResolver::visit_constructor(FunctionCall &call)
890 {
891         if(call.arguments.empty())
892                 return;
893
894         map<string, TypeDeclaration *>::const_iterator i = stage->types.find(call.name);
895         if(i==stage->types.end())
896                 return;
897         else if(call.arguments.size()==1 && i->second==call.arguments[0]->type)
898                 ;
899         else if(BasicTypeDeclaration *basic = dynamic_cast<BasicTypeDeclaration *>(i->second))
900         {
901                 BasicTypeDeclaration *elem = get_element_type(*basic);
902                 if(!elem)
903                         return;
904
905                 vector<ArgumentInfo> args;
906                 args.reserve(call.arguments.size());
907                 unsigned arg_component_total = 0;
908                 bool has_matrices = false;
909                 for(NodeArray<Expression>::const_iterator j=call.arguments.begin(); j!=call.arguments.end(); ++j)
910                 {
911                         ArgumentInfo info;
912                         if(!(info.type=dynamic_cast<BasicTypeDeclaration *>((*j)->type)))
913                                 return;
914                         if(is_scalar(*info.type) || info.type->kind==BasicTypeDeclaration::BOOL)
915                                 info.component_count = 1;
916                         else if(info.type->kind==BasicTypeDeclaration::VECTOR)
917                                 info.component_count = info.type->size;
918                         else if(info.type->kind==BasicTypeDeclaration::MATRIX)
919                         {
920                                 info.component_count = (info.type->size>>16)*(info.type->size&0xFFFF);
921                                 has_matrices = true;
922                         }
923                         else
924                                 return;
925                         arg_component_total += info.component_count;
926                         args.push_back(info);
927                 }
928
929                 bool convert_args = false;
930                 if((is_scalar(*basic) || basic->kind==BasicTypeDeclaration::BOOL) && call.arguments.size()==1 && !has_matrices)
931                 {
932                         if(arg_component_total>1)
933                                 truncate_vector(call.arguments.front(), 1);
934
935                         /* Single-element type constructors never need to convert their
936                         arguments because the constructor *is* the conversion. */
937                 }
938                 else if(basic->kind==BasicTypeDeclaration::VECTOR && !has_matrices)
939                 {
940                         /* Vector constructors need either a single scalar argument or
941                         enough components to fill out the vector. */
942                         if(arg_component_total!=1 && arg_component_total<basic->size)
943                                 return;
944
945                         /* A vector of same size can be converted directly.  For other
946                         combinations the individual arguments need to be converted. */
947                         if(call.arguments.size()==1)
948                         {
949                                 if(arg_component_total==1)
950                                         convert_args = true;
951                                 else if(arg_component_total>basic->size)
952                                         truncate_vector(call.arguments.front(), basic->size);
953                         }
954                         else if(arg_component_total==basic->size)
955                                 convert_args = true;
956                         else
957                                 return;
958                 }
959                 else if(basic->kind==BasicTypeDeclaration::MATRIX)
960                 {
961                         unsigned column_count = basic->size&0xFFFF;
962                         unsigned row_count = basic->size>>16;
963                         if(call.arguments.size()==1)
964                         {
965                                 /* A matrix can be constructed from a single element or another
966                                 matrix of sufficient size. */
967                                 if(arg_component_total==1)
968                                         convert_args = true;
969                                 else if(args.front().type->kind==BasicTypeDeclaration::MATRIX)
970                                 {
971                                         unsigned arg_columns = args.front().type->size&0xFFFF;
972                                         unsigned arg_rows = args.front().type->size>>16;
973                                         if(arg_columns<column_count || arg_rows<row_count)
974                                                 return;
975
976                                         /* Always generate a temporary here and let the optimization
977                                         stage inline it if that's reasonable. */
978                                         RefPtr<VariableDeclaration> temporary = new VariableDeclaration;
979                                         temporary->type = args.front().type->name;
980                                         temporary->name = get_unused_variable_name(*current_block, "_temp");
981                                         temporary->init_expression = call.arguments.front();
982                                         current_block->body.insert(insert_point, temporary);
983
984                                         // Create expressions to build each column.
985                                         vector<RefPtr<Expression> > columns;
986                                         columns.reserve(column_count);
987                                         for(unsigned j=0; j<column_count; ++j)
988                                         {
989                                                 RefPtr<VariableReference> ref = new VariableReference;
990                                                 ref->name = temporary->name;
991
992                                                 RefPtr<Literal> index = new Literal;
993                                                 index->token = lexical_cast<string>(j);
994                                                 index->value = static_cast<int>(j);
995
996                                                 RefPtr<BinaryExpression> subscript = new BinaryExpression;
997                                                 subscript->left = ref;
998                                                 subscript->oper = &Operator::get_operator("[", Operator::BINARY);
999                                                 subscript->right = index;
1000                                                 subscript->type = args.front().type->base_type;
1001
1002                                                 columns.push_back(subscript);
1003                                                 if(arg_rows>row_count)
1004                                                         truncate_vector(columns.back(), row_count);
1005                                         }
1006
1007                                         call.arguments.resize(column_count);
1008                                         copy(columns.begin(), columns.end(), call.arguments.begin());
1009
1010                                         /* Let VariableResolver process the new nodes and finish
1011                                         resolving the constructor on the next pass. */
1012                                         r_any_resolved = true;
1013                                         return;
1014                                 }
1015                                 else
1016                                         return;
1017                         }
1018                         else if(arg_component_total==column_count*row_count && !has_matrices)
1019                         {
1020                                 /* Construct a matrix from individual components in column-major
1021                                 order.  Arguments must align at column boundaries. */
1022                                 vector<RefPtr<Expression> > columns;
1023                                 columns.reserve(column_count);
1024
1025                                 vector<RefPtr<Expression> > column_args;
1026                                 column_args.reserve(row_count);
1027                                 unsigned column_component_count = 0;
1028
1029                                 for(unsigned j=0; j<call.arguments.size(); ++j)
1030                                 {
1031                                         const ArgumentInfo &info = args[j];
1032                                         if(!column_component_count && info.type->kind==BasicTypeDeclaration::VECTOR && info.component_count==row_count)
1033                                                 // A vector filling the entire column can be used as is.
1034                                                 columns.push_back(call.arguments[j]);
1035                                         else
1036                                         {
1037                                                 column_args.push_back(call.arguments[j]);
1038                                                 column_component_count += info.component_count;
1039                                                 if(column_component_count==row_count)
1040                                                 {
1041                                                         /* The column has filled up.  Create a vector constructor
1042                                                         for it.*/
1043                                                         RefPtr<FunctionCall> column_call = new FunctionCall;
1044                                                         column_call->name = basic->base_type->name;
1045                                                         column_call->constructor = true;
1046                                                         column_call->arguments.resize(column_args.size());
1047                                                         copy(column_args.begin(), column_args.end(), column_call->arguments.begin());
1048                                                         column_call->type = basic->base_type;
1049                                                         visit_constructor(*column_call);
1050                                                         columns.push_back(column_call);
1051
1052                                                         column_args.clear();
1053                                                         column_component_count = 0;
1054                                                 }
1055                                                 else if(column_component_count>row_count)
1056                                                         // Argument alignment mismatch.
1057                                                         return;
1058                                         }
1059                                 }
1060                         }
1061                         else
1062                                 return;
1063                 }
1064                 else
1065                         return;
1066
1067                 if(convert_args)
1068                 {
1069                         // The argument list may have changed so can't rely on args.
1070                         for(NodeArray<Expression>::iterator j=call.arguments.begin(); j!=call.arguments.end(); ++j)
1071                                 if(BasicTypeDeclaration *basic_arg = dynamic_cast<BasicTypeDeclaration *>((*j)->type))
1072                                 {
1073                                         BasicTypeDeclaration *elem_arg = get_element_type(*basic_arg);
1074                                         if(elem_arg!=elem)
1075                                                 convert_to_element(*j, *elem);
1076                                 }
1077                 }
1078         }
1079         else if(StructDeclaration *strct = dynamic_cast<StructDeclaration *>(i->second))
1080         {
1081                 if(call.arguments.size()!=strct->members.body.size())
1082                         return;
1083
1084                 unsigned k = 0;
1085                 for(NodeList<Statement>::const_iterator j=strct->members.body.begin(); j!=strct->members.body.end(); ++j, ++k)
1086                 {
1087                         if(VariableDeclaration *var = dynamic_cast<VariableDeclaration *>(j->get()))
1088                         {
1089                                 if(!call.arguments[k]->type || call.arguments[k]->type!=var->type_declaration)
1090                                         return;
1091                         }
1092                         else
1093                                 return;
1094                 }
1095         }
1096
1097         resolve(call, i->second, false);
1098 }
1099
1100 void ExpressionResolver::visit(FunctionCall &call)
1101 {
1102         TraversingVisitor::visit(call);
1103
1104         if(call.declaration)
1105                 resolve(call, call.declaration->return_type_declaration, false);
1106         else if(call.constructor)
1107                 visit_constructor(call);
1108 }
1109
1110 void ExpressionResolver::visit(BasicTypeDeclaration &type)
1111 {
1112         basic_types.push_back(&type);
1113 }
1114
1115 void ExpressionResolver::visit(VariableDeclaration &var)
1116 {
1117         TraversingVisitor::visit(var);
1118         if(!var.init_expression)
1119                 return;
1120
1121         BasicTypeDeclaration *var_basic = dynamic_cast<BasicTypeDeclaration *>(var.type_declaration);
1122         BasicTypeDeclaration *init_basic = dynamic_cast<BasicTypeDeclaration *>(var.init_expression->type);
1123         if(!var_basic || !init_basic)
1124                 return;
1125
1126         Compatibility compat = get_compatibility(*var_basic, *init_basic);
1127         if(compat==RIGHT_CONVERTIBLE)
1128                 convert_to(var.init_expression, *var_basic);
1129 }
1130
1131
1132 bool FunctionResolver::apply(Stage &s)
1133 {
1134         stage = &s;
1135         s.functions.clear();
1136         r_any_resolved = false;
1137         s.content.visit(*this);
1138         return r_any_resolved;
1139 }
1140
1141 void FunctionResolver::visit(FunctionCall &call)
1142 {
1143         FunctionDeclaration *declaration = 0;
1144         if(stage->types.count(call.name))
1145                 call.constructor = true;
1146         else
1147         {
1148                 string arg_types;
1149                 bool has_signature = true;
1150                 for(NodeArray<Expression>::const_iterator i=call.arguments.begin(); (has_signature && i!=call.arguments.end()); ++i)
1151                 {
1152                         if((*i)->type)
1153                                 append(arg_types, ",", (*i)->type->name);
1154                         else
1155                                 has_signature = false;
1156                 }
1157
1158                 if(has_signature)
1159                 {
1160                         map<string, FunctionDeclaration *>::iterator i = stage->functions.find(format("%s(%s)", call.name, arg_types));
1161                         declaration = (i!=stage->functions.end() ? i->second : 0);
1162                 }
1163         }
1164
1165         r_any_resolved |= (declaration!=call.declaration);
1166         call.declaration = declaration;
1167
1168         TraversingVisitor::visit(call);
1169 }
1170
1171 void FunctionResolver::visit(FunctionDeclaration &func)
1172 {
1173         if(func.signature.empty())
1174         {
1175                 string param_types;
1176                 for(NodeArray<VariableDeclaration>::const_iterator i=func.parameters.begin(); i!=func.parameters.end(); ++i)
1177                 {
1178                         if((*i)->type_declaration)
1179                                 append(param_types, ",", (*i)->type_declaration->name);
1180                         else
1181                                 return;
1182                 }
1183                 func.signature = format("(%s)", param_types);
1184                 r_any_resolved = true;
1185         }
1186
1187         string key = func.name+func.signature;
1188         FunctionDeclaration *&stage_decl = stage->functions[key];
1189         vector<FunctionDeclaration *> &decls = declarations[key];
1190         if(func.definition==&func)
1191         {
1192                 if(stage_decl && stage_decl->definition)
1193                 {
1194                         if(!func.overrd)
1195                                 stage->diagnostics.push_back(Diagnostic(Diagnostic::WARN, func.source, func.line,
1196                                         format("Overriding function '%s' without the override keyword is deprecated", key)));
1197                         if(!stage_decl->definition->virtua)
1198                                 stage->diagnostics.push_back(Diagnostic(Diagnostic::WARN, func.source, func.line,
1199                                         format("Overriding function '%s' not declared as virtual is deprecated", key)));
1200                 }
1201                 stage_decl = &func;
1202
1203                 // Set all previous declarations to use this definition.
1204                 for(vector<FunctionDeclaration *>::iterator i=decls.begin(); i!=decls.end(); ++i)
1205                 {
1206                         r_any_resolved |= (func.definition!=(*i)->definition);
1207                         (*i)->definition = func.definition;
1208                         (*i)->body.body.clear();
1209                 }
1210         }
1211         else
1212         {
1213                 FunctionDeclaration *definition = (stage_decl ? stage_decl->definition : 0);
1214                 r_any_resolved |= (definition!=func.definition);
1215                 func.definition = definition;
1216
1217                 if(!stage_decl)
1218                         stage_decl = &func;
1219         }
1220         decls.push_back(&func);
1221
1222         TraversingVisitor::visit(func);
1223 }
1224
1225 } // namespace SL
1226 } // namespace GL
1227 } // namespace Msp