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