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