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