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