]> git.tdb.fi Git - libs/gl.git/blob - source/glsl/validate.cpp
Use ObjectInstance instead of AnimatedObject in Scene loader
[libs/gl.git] / source / glsl / validate.cpp
1 #include <algorithm>
2 #include <cstring>
3 #include <msp/core/raii.h>
4 #include <msp/strings/format.h>
5 #include <msp/strings/utils.h>
6 #include "reflect.h"
7 #include "validate.h"
8
9 using namespace std;
10
11 namespace Msp {
12 namespace GL {
13 namespace SL {
14
15 Validator::Validator():
16         stage(0),
17         last_provoker(0)
18 { }
19
20 void Validator::diagnose(Node &node, Node &provoking_node, Diagnostic::Severity severity, const string &message)
21 {
22         Diagnostic diag;
23         diag.severity = severity;
24         diag.source = node.source;
25         diag.line = node.line;
26         diag.provoking_source = provoking_node.source;
27         diag.provoking_line = provoking_node.line;
28         diag.message = message;
29         stage->diagnostics.push_back(diag);
30
31         last_provoker = &provoking_node;
32 }
33
34 void Validator::add_info(Node &node, const string &message)
35 {
36         if(!last_provoker)
37                 throw logic_error("Tried to add info without a previous provoker");
38         diagnose(node, *last_provoker, Diagnostic::INFO, message);
39 }
40
41
42 DeclarationValidator::DeclarationValidator():
43         scope(GLOBAL),
44         iface_layout(0),
45         iface_block(0),
46         variable(0)
47 { }
48
49 const char *DeclarationValidator::describe_variable(ScopeType scope)
50 {
51         switch(scope)
52         {
53         case GLOBAL: return "global variable";
54         case STRUCT: return "struct member";
55         case INTERFACE_BLOCK: return "interface block member";
56         case FUNCTION_PARAM: return "function parameter";
57         case FUNCTION: return "local variable";
58         default: return "variable";
59         }
60 }
61
62 void DeclarationValidator::visit(Layout &layout)
63 {
64         for(vector<Layout::Qualifier>::const_iterator i=layout.qualifiers.begin(); i!=layout.qualifiers.end(); ++i)
65         {
66                 bool allowed = false;
67                 string err_descr;
68                 bool value = true;
69                 if(i->name=="location")
70                         allowed = (variable && scope==GLOBAL);
71                 else if(i->name=="binding" || i->name=="set")
72                 {
73                         if(i->name=="set")
74                         {
75                                 error(layout, "Layout qualifier 'set' not allowed when targeting OpenGL");
76                                 continue;
77                         }
78
79                         if(variable)
80                         {
81                                 TypeDeclaration *type = variable->type_declaration;
82                                 while(BasicTypeDeclaration *basic = dynamic_cast<BasicTypeDeclaration *>(type))
83                                         type = basic->base_type;
84                                 bool uniform = (variable->interface=="uniform");
85                                 allowed = (scope==GLOBAL && uniform && dynamic_cast<ImageTypeDeclaration *>(type));
86                                 err_descr = (uniform ? "variable of non-opaque type" : "non-uniform variable");
87                         }
88                         else if(iface_block)
89                         {
90                                 allowed = (iface_block->interface=="uniform");
91                                 err_descr = "non-uniform interface block";
92                         }
93                 }
94                 else if(i->name=="constant_id")
95                 {
96                         allowed = (variable && scope==GLOBAL);
97                         if(allowed)
98                         {
99                                 if(!variable->constant)
100                                 {
101                                         allowed = false;
102                                         err_descr = "non-constant variable";
103                                 }
104                                 else
105                                 {
106                                         BasicTypeDeclaration *basic = dynamic_cast<BasicTypeDeclaration *>(variable->type_declaration);
107                                         if(!basic || basic->kind<BasicTypeDeclaration::BOOL || basic->kind>BasicTypeDeclaration::INT)
108                                         {
109                                                 allowed = false;
110                                                 err_descr = format("variable of type '%s'",
111                                                         (variable->type_declaration ? variable->type_declaration->name : variable->type));
112                                         }
113                                 }
114                         }
115                 }
116                 else if(i->name=="offset")
117                         allowed = (variable && scope==INTERFACE_BLOCK && iface_block->interface=="uniform");
118                 else if(i->name=="align")
119                         allowed = (scope==INTERFACE_BLOCK && iface_block->interface=="uniform");
120                 else if(i->name=="points")
121                 {
122                         allowed = (stage->type==Stage::GEOMETRY && iface_layout && (iface_layout->interface=="in" || iface_layout->interface=="out"));
123                         value = false;
124                 }
125                 else if(i->name=="lines" || i->name=="lines_adjacency" || i->name=="triangles" || i->name=="triangles_adjacency")
126                 {
127                         allowed = (stage->type==Stage::GEOMETRY && iface_layout && iface_layout->interface=="in");
128                         value = false;
129                 }
130                 else if(i->name=="line_strip" || i->name=="triangle_strip")
131                 {
132                         allowed = (stage->type==Stage::GEOMETRY && iface_layout && iface_layout->interface=="out");
133                         value = false;
134                 }
135                 else if(i->name=="invocations")
136                         allowed = (stage->type==Stage::GEOMETRY && iface_layout && iface_layout->interface=="in");
137                 else if(i->name=="max_vertices")
138                         allowed = (stage->type==Stage::GEOMETRY && iface_layout && iface_layout->interface=="out");
139                 else if(i->name=="std140" || i->name=="std430")
140                 {
141                         allowed = (iface_block && !variable && iface_block->interface=="uniform");
142                         value = false;
143                 }
144                 else if(i->name=="column_major" || i->name=="row_major")
145                 {
146                         allowed = (variable && scope==INTERFACE_BLOCK);
147                         if(allowed)
148                         {
149                                 BasicTypeDeclaration *basic = dynamic_cast<BasicTypeDeclaration *>(variable->type_declaration);
150                                 while(basic && basic->kind==BasicTypeDeclaration::ARRAY)
151                                         basic = dynamic_cast<BasicTypeDeclaration *>(basic->base_type);
152                                 allowed = (basic && basic->kind==BasicTypeDeclaration::MATRIX);
153                                 err_descr = "non-matrix variable";
154                         }
155                 }
156
157                 if(!allowed)
158                 {
159                         if(err_descr.empty())
160                         {
161                                 if(variable)
162                                         err_descr = describe_variable(scope);
163                                 else if(iface_block)
164                                         err_descr = "interface block";
165                                 else if(iface_layout)
166                                         err_descr = format("interface '%s'", iface_layout->interface);
167                                 else
168                                         err_descr = "unknown declaration";
169                         }
170                         error(layout, format("Layout qualifier '%s' not allowed on %s", i->name, err_descr));
171                 }
172                 else if(value && !i->has_value)
173                         error(layout, format("Layout qualifier '%s' requires a value", i->name));
174                 else if(!value && i->has_value)
175                         error(layout, format("Layout qualifier '%s' does not allow a value", i->name));
176         }
177 }
178
179 void DeclarationValidator::visit(InterfaceLayout &layout)
180 {
181         SetForScope<InterfaceLayout *> set_layout(iface_layout, &layout);
182         TraversingVisitor::visit(layout);
183 }
184
185 void DeclarationValidator::visit(BasicTypeDeclaration &type)
186 {
187         BasicTypeDeclaration *basic_base = dynamic_cast<BasicTypeDeclaration *>(type.base_type);
188         BasicTypeDeclaration::Kind base_kind = (basic_base ? basic_base->kind : BasicTypeDeclaration::VOID);
189
190         if(type.kind==BasicTypeDeclaration::VECTOR && (base_kind<BasicTypeDeclaration::BOOL || base_kind>BasicTypeDeclaration::FLOAT))
191                 error(type, format("Invalid base type '%s' for vector type '%s'", type.base, type.name));
192         else if(type.kind==BasicTypeDeclaration::MATRIX && base_kind!=BasicTypeDeclaration::VECTOR)
193                 error(type, format("Invalid base type '%s' for matrix type '%s'", type.base, type.name));
194         else if(type.kind==BasicTypeDeclaration::ARRAY && basic_base && base_kind==BasicTypeDeclaration::VOID)
195                 error(type, format("Invalid base type '%s' for array type '%s'", type.base, type.name));
196 }
197
198 void DeclarationValidator::visit(ImageTypeDeclaration &type)
199 {
200         BasicTypeDeclaration::Kind base_kind = BasicTypeDeclaration::VOID;
201         if(BasicTypeDeclaration *basic_base = dynamic_cast<BasicTypeDeclaration *>(type.base_type))
202                 base_kind = basic_base->kind;
203         if(base_kind!=BasicTypeDeclaration::INT && base_kind!=BasicTypeDeclaration::FLOAT)
204                 error(type, format("Invalid base type '%s' for image type '%s'", type.base, type.name));
205 }
206
207 void DeclarationValidator::visit(StructDeclaration &strct)
208 {
209         SetForScope<ScopeType> set_scope(scope, (scope!=INTERFACE_BLOCK ? STRUCT : scope));
210         TraversingVisitor::visit(strct);
211 }
212
213 void DeclarationValidator::visit(VariableDeclaration &var)
214 {
215         SetForScope<VariableDeclaration *> set_var(variable, &var);
216
217         const char *descr = describe_variable(scope);
218
219         if(var.layout)
220         {
221                 if(scope!=GLOBAL && scope!=INTERFACE_BLOCK)
222                         error(var, format("Layout qualifier not allowed on %s", descr));
223                 else
224                         var.layout->visit(*this);
225         }
226
227         if(var.constant)
228         {
229                 if(scope==STRUCT || scope==INTERFACE_BLOCK)
230                         error(var, format("Constant qualifier not allowed on %s", descr));
231                 if(!var.init_expression)
232                         error(var, "Constant variable must have an initializer");
233         }
234
235         if(!var.interpolation.empty() || !var.sampling.empty())
236         {
237                 if(var.interface!="in" && stage->type==Stage::VERTEX)
238                         error(var, "Interpolation qualifier not allowed on vertex input");
239                 else if(var.interface!="out" && stage->type==Stage::FRAGMENT)
240                         error(var, "Interpolation qualifier not allowed on fragment output");
241                 else if((var.interface!="in" && var.interface!="out") || (scope==FUNCTION_PARAM || scope==FUNCTION))
242                         error(var, "Interpolation qualifier not allowed on non-interpolated variable");
243         }
244
245         if(!var.interface.empty())
246         {
247                 if(iface_block && var.interface!=iface_block->interface)
248                         error(var, format("Mismatched interface qualifier '%s' inside '%s' block", var.interface, iface_block->interface));
249                 else if(scope==STRUCT || scope==FUNCTION)
250                         error(var, format("Interface qualifier not allowed on %s", descr));
251         }
252
253         TypeDeclaration *type = var.type_declaration;
254         BasicTypeDeclaration::Kind kind = BasicTypeDeclaration::ALIAS;
255         while(BasicTypeDeclaration *basic = dynamic_cast<BasicTypeDeclaration *>(type))
256         {
257                 kind = basic->kind;
258                 type = basic->base_type;
259         }
260         if(dynamic_cast<ImageTypeDeclaration *>(type))
261         {
262                 if(scope!=GLOBAL && scope!=FUNCTION_PARAM)
263                         error(var, format("Type '%s' not allowed on %s", type->name, descr));
264                 else if(scope==GLOBAL && var.interface!="uniform")
265                         error(var, format("Type '%s' only allowed with uniform interface", type->name));
266         }
267         else if(kind==BasicTypeDeclaration::VOID)
268                 error(var, "Type 'void' not allowed on variable");
269         else if(kind==BasicTypeDeclaration::BOOL && !var.interface.empty() && var.source!=BUILTIN_SOURCE)
270                 error(var, "Type 'bool' not allowed on interface variable");
271
272         if(var.init_expression)
273         {
274                 if(scope==GLOBAL && !var.constant)
275                         error(var, format("Initializer not allowed on non-constant %s", descr));
276                 else if(scope!=GLOBAL && scope!=FUNCTION)
277                         error(var, format("Initializer not allowed on %s", descr));
278                 else
279                         var.init_expression->visit(*this);
280         }
281 }
282
283 void DeclarationValidator::visit(InterfaceBlock &iface)
284 {
285         SetForScope<ScopeType> set_scope(scope, INTERFACE_BLOCK);
286         SetForScope<InterfaceBlock *> set_iface(iface_block, &iface);
287
288         if(stage->type==Stage::VERTEX && iface.interface=="in")
289                 error(iface, "Interface block not allowed on vertex shader input");
290         else if(stage->type==Stage::FRAGMENT && iface.interface=="out")
291                 error(iface, "Interface block not allowed on fragment shader output");
292
293         TraversingVisitor::visit(iface);
294         if(iface.struct_declaration)
295                 iface.struct_declaration->visit(*this);
296 }
297
298 void DeclarationValidator::visit(FunctionDeclaration &func)
299 {
300         SetForScope<ScopeType> set_scope(scope, FUNCTION_PARAM);
301         for(NodeArray<VariableDeclaration>::const_iterator i=func.parameters.begin(); i!=func.parameters.end(); ++i)
302                 (*i)->visit(*this);
303         scope = FUNCTION;
304         func.body.visit(*this);
305 }
306
307
308 IdentifierValidator::IdentifierValidator():
309         anonymous_block(false)
310 { }
311
312 void IdentifierValidator::multiple_definition(const string &name, Statement &statement, Statement &previous)
313 {
314         error(statement, format("Multiple definition of %s", name));
315         add_info(previous, "Previous definition is here");
316 }
317
318 Statement *IdentifierValidator::find_definition(const string &name)
319 {
320         BlockDeclarationMap *decls = &declarations[current_block];
321         BlockDeclarationMap::const_iterator i = decls->find(name);
322         if(i==decls->end() && anonymous_block)
323         {
324                 decls = &declarations[current_block->parent];
325                 i = decls->find(name);
326         }
327         return (i!=decls->end() ? i->second : 0);
328 }
329
330 void IdentifierValidator::check_definition(const string &name, Statement &statement)
331 {
332         if(Statement *previous = find_definition(name))
333                 multiple_definition(format("'%s'", name), statement, *previous);
334         else
335                 record_definition(name, statement);
336 }
337
338 void IdentifierValidator::record_definition(const string &name, Statement &statement)
339 {
340         declarations[current_block].insert(make_pair(name, &statement));
341         if(anonymous_block)
342                 declarations[current_block->parent].insert(make_pair(name, &statement));
343 }
344
345 void IdentifierValidator::visit(TypeDeclaration &type)
346 {
347         check_definition(type.name, type);
348 }
349
350 void IdentifierValidator::visit(StructDeclaration &strct)
351 {
352         check_definition(strct.name, strct);
353         TraversingVisitor::visit(strct);
354 }
355
356 void IdentifierValidator::visit(VariableDeclaration &var)
357 {
358         check_definition(var.name, var);
359         TraversingVisitor::visit(var);
360 }
361
362 void IdentifierValidator::visit(InterfaceBlock &iface)
363 {
364         string key = format("%s %s", iface.interface, iface.block_name);
365         map<string, InterfaceBlock *>::const_iterator i = interface_blocks.find(key);
366         if(i!=interface_blocks.end())
367                 multiple_definition(format("interface block '%s %s'", iface.interface, iface.block_name), iface, *i->second);
368         else
369                 interface_blocks.insert(make_pair(key, &iface));
370
371         if(Statement *previous = find_definition(iface.block_name))
372         {
373                 if(!dynamic_cast<InterfaceBlock *>(previous))
374                         multiple_definition(format("'%s'", iface.block_name), iface, *previous);
375         }
376         else
377                 record_definition(iface.block_name, iface);
378
379         if(!iface.instance_name.empty())
380                 check_definition(iface.instance_name, iface);
381
382         if(iface.instance_name.empty() && iface.struct_declaration)
383         {
384                 // Inject anonymous interface block members into the global scope
385                 const map<string, VariableDeclaration *> &iface_vars = iface.struct_declaration->members.variables;
386                 for(map<string, VariableDeclaration *>::const_iterator j=iface_vars.begin(); j!=iface_vars.end(); ++j)
387                         check_definition(j->first, *j->second);
388         }
389 }
390
391 void IdentifierValidator::visit(FunctionDeclaration &func)
392 {
393         string key = func.name+func.signature;
394         map<string, FunctionDeclaration *>::const_iterator i = overloaded_functions.find(key);
395         if(i==overloaded_functions.end())
396                 overloaded_functions.insert(make_pair(key, &func));
397         else if(func.return_type_declaration && i->second->return_type_declaration!=func.return_type_declaration)
398         {
399                 error(func, format("Conflicting return type '%s' for function '%s'", func.return_type_declaration->name, func.name));
400                 if(i->second->return_type_declaration)
401                         add_info(*i->second, format("Previously declared as returning '%s'", i->second->return_type_declaration->name));
402         }
403
404         if(Statement *previous = find_definition(func.name))
405         {
406                 if(!dynamic_cast<FunctionDeclaration *>(previous))
407                         multiple_definition(format("'%s'", func.name), func, *previous);
408         }
409         else
410                 record_definition(func.name, func);
411
412         if(func.definition==&func)
413                 check_definition(func.name+func.signature, func);
414
415         TraversingVisitor::visit(func);
416 }
417
418
419 void ReferenceValidator::visit(BasicTypeDeclaration &type)
420 {
421         if(!type.base.empty() && !type.base_type)
422                 error(type, format("Use of undeclared type '%s'", type.base));
423 }
424
425 void ReferenceValidator::visit(ImageTypeDeclaration &type)
426 {
427         if(!type.base.empty() && !type.base_type)
428                 error(type, format("Use of undeclared type '%s'", type.base));
429 }
430
431 void ReferenceValidator::visit(VariableReference &var)
432 {
433         if(!var.declaration)
434                 error(var, format("Use of undeclared variable '%s'", var.name));
435         else if(stage->type!=Stage::VERTEX && var.declaration->interface=="in" && var.name.compare(0, 3, "gl_") && !var.declaration->linked_declaration)
436                 error(var, format("Use of unlinked input variable '%s'", var.name));
437 }
438
439 void ReferenceValidator::visit(MemberAccess &memacc)
440 {
441         if(memacc.left->type && !memacc.declaration)
442                 error(memacc, format("Use of undeclared member '%s'", memacc.member));
443         TraversingVisitor::visit(memacc);
444 }
445
446 void ReferenceValidator::visit(InterfaceBlockReference &iface)
447 {
448         /* An interface block reference without a declaration should be impossible
449         since references are generated based on existing declarations. */
450         if(!iface.declaration)
451                 error(iface, format("Use of undeclared interface block '%s'", iface.name));
452         else if(stage->type!=Stage::VERTEX && iface.declaration->interface=="in" && !iface.declaration->linked_block)
453                 error(iface, format("Use of unlinked input block '%s'", iface.name));
454 }
455
456 void ReferenceValidator::visit(FunctionCall &call)
457 {
458         if((!call.constructor && !call.declaration) || (call.constructor && !call.type))
459         {
460                 bool have_declaration = call.constructor;
461                 if(!call.constructor)
462                 {
463                         map<string, FunctionDeclaration *>::iterator i = stage->functions.lower_bound(call.name);
464                         have_declaration = (i!=stage->functions.end() && i->second->name==call.name);
465                 }
466
467                 if(have_declaration)
468                 {
469                         bool valid_types = true;
470                         string signature;
471                         for(NodeArray<Expression>::const_iterator j=call.arguments.begin(); (valid_types && j!=call.arguments.end()); ++j)
472                         {
473                                 if((*j)->type)
474                                         append(signature, ", ", (*j)->type->name);
475                                 else
476                                         valid_types = false;
477                         }
478
479                         if(valid_types)
480                                 error(call, format("No matching %s found for '%s(%s)'", (call.constructor ? "constructor" : "overload"), call.name, signature));
481                 }
482                 else
483                         error(call, format("Call to undeclared function '%s'", call.name));
484         }
485         TraversingVisitor::visit(call);
486 }
487
488 void ReferenceValidator::visit(VariableDeclaration &var)
489 {
490         if(!var.type_declaration)
491                 error(var, format("Use of undeclared type '%s'", var.type));
492         TraversingVisitor::visit(var);
493 }
494
495 void ReferenceValidator::visit(InterfaceBlock &iface)
496 {
497         if(!iface.struct_declaration)
498                 error(iface, format("Interface block '%s %s' lacks a struct declaration", iface.interface, iface.block_name));
499         TraversingVisitor::visit(iface);
500 }
501
502 void ReferenceValidator::visit(FunctionDeclaration &func)
503 {
504         if(!func.return_type_declaration)
505                 error(func, format("Use of undeclared type '%s'", func.return_type));
506         TraversingVisitor::visit(func);
507 }
508
509
510 ExpressionValidator::ExpressionValidator():
511         current_function(0),
512         constant_expression(false)
513 { }
514
515 void ExpressionValidator::visit(VariableReference &var)
516 {
517         if(var.declaration && constant_expression && !var.declaration->constant)
518                 error(var, format("Reference to non-constant variable '%s' in a constant expression", var.name));
519 }
520
521 void ExpressionValidator::visit(InterfaceBlockReference &iface)
522 {
523         if(constant_expression)
524                 error(iface, format("Reference to interface block '%s' in a constant expression", iface.name));
525 }
526
527 void ExpressionValidator::visit(Swizzle &swizzle)
528 {
529         unsigned size = 0;
530         if(BasicTypeDeclaration *basic = dynamic_cast<BasicTypeDeclaration *>(swizzle.left->type))
531         {
532                 if(basic->kind==BasicTypeDeclaration::INT || basic->kind==BasicTypeDeclaration::FLOAT)
533                         size = 1;
534                 else if(basic->kind==BasicTypeDeclaration::VECTOR)
535                         size = basic->size;
536         }
537
538         if(size)
539         {
540                 static const char component_names[] = { 'x', 'y', 'z', 'w', 'r', 'g', 'b', 'a', 's', 't', 'p', 'q' };
541                 int flavour = -1;
542                 for(unsigned i=0; i<swizzle.count; ++i)
543                 {
544                         unsigned component_flavour = (find(component_names, component_names+12, swizzle.component_group[i])-component_names)/4;
545                         if(flavour==-1)
546                                 flavour = component_flavour;
547                         else if(flavour>=0 && component_flavour!=static_cast<unsigned>(flavour))
548                         {
549                                 error(swizzle, format("Flavour of swizzle component '%c' is inconsistent with '%c'",
550                                         swizzle.component_group[i], swizzle.component_group[0]));
551                                 flavour = -2;
552                         }
553
554                         if(swizzle.components[i]>=size)
555                                 error(swizzle, format("Access to component '%c' which is not present in '%s'",
556                                         swizzle.component_group[i], swizzle.left->type->name));
557                 }
558         }
559         else if(swizzle.left->type)
560                 error(swizzle, format("Swizzle applied to '%s' which is neither a scalar nor a vector", swizzle.left->type->name));
561
562         TraversingVisitor::visit(swizzle);
563 }
564
565 void ExpressionValidator::visit(UnaryExpression &unary)
566 {
567         if(unary.expression->type)
568         {
569                 if(!unary.type)
570                         error(unary, format("No matching operator '%s' found for '%s'", unary.oper->token, unary.expression->type->name));
571                 else if(unary.oper->token[1]=='+' || unary.oper->token[1]=='-')
572                 {
573                         if(constant_expression)
574                                 error(unary, format("Use of '%s' in a constant expression", unary.oper->token));
575                         else if(!unary.expression->lvalue)
576                                 error(unary, format("Operand of '%s' is not an lvalue", unary.oper->token));
577                 }
578         }
579         TraversingVisitor::visit(unary);
580 }
581
582 void ExpressionValidator::visit(BinaryExpression &binary)
583 {
584         if(!binary.type && binary.left->type && binary.right->type)
585         {
586                 if(binary.oper->token[0]=='[')
587                         error(binary, format("Can't index element of '%s' with '%s'",
588                                 binary.left->type->name, binary.right->type->name));
589                 else
590                         error(binary, format("No matching operator '%s' found for '%s' and '%s'",
591                                 binary.oper->token, binary.left->type->name, binary.right->type->name));
592         }
593         TraversingVisitor::visit(binary);
594 }
595
596 void ExpressionValidator::visit(Assignment &assign)
597 {
598         if(assign.left->type)
599         {
600                 if(constant_expression)
601                         error(assign, "Assignment in constant expression");
602                 else if(!assign.left->lvalue)
603                         error(assign, "Target of assignment is not an lvalue");
604                 if(assign.right->type)
605                 {
606                         if(assign.oper->token[0]!='=')
607                         {
608                                 if(!assign.type)
609                                         error(assign, format("No matching operator '%s' found for '%s' and '%s'",
610                                                 string(assign.oper->token, strlen(assign.oper->token)-1), assign.left->type->name, assign.right->type->name));
611                         }
612                         else if(assign.left->type!=assign.right->type)
613                                 error(assign, format("Assignment to variable of type '%s' from expression of incompatible type '%s'",
614                                         assign.left->type->name, assign.right->type->name));
615                 }
616         }
617         TraversingVisitor::visit(assign);
618 }
619
620 void ExpressionValidator::visit(TernaryExpression &ternary)
621 {
622         if(ternary.condition->type)
623         {
624                 BasicTypeDeclaration *basic_cond = dynamic_cast<BasicTypeDeclaration *>(ternary.condition->type);
625                 if(!basic_cond || basic_cond->kind!=BasicTypeDeclaration::BOOL)
626                         error(ternary, "Ternary operator condition is not a boolean");
627                 else if(!ternary.type && ternary.true_expr->type && ternary.false_expr->type)
628                         error(ternary, format("Ternary operator has incompatible types '%s' and '%s'",
629                                 ternary.true_expr->type->name, ternary.false_expr->type->name));
630         }
631         TraversingVisitor::visit(ternary);
632 }
633
634 void ExpressionValidator::visit(VariableDeclaration &var)
635 {
636         if(var.init_expression && var.init_expression->type && var.type_declaration && var.init_expression->type!=var.type_declaration)
637                 error(var, format("Initializing a variable of type '%s' with an expression of incompatible type '%s'",
638                         var.type_declaration->name, var.init_expression->type->name));
639
640         if(var.layout)
641                 var.layout->visit(*this);
642         if(var.init_expression)
643         {
644                 SetFlag set_const(constant_expression, var.constant);
645                 TraversingVisitor::visit(var.init_expression);
646         }
647         if(var.array_size)
648         {
649                 SetFlag set_const(constant_expression);
650                 TraversingVisitor::visit(var.array_size);
651         }
652 }
653
654 void ExpressionValidator::visit(FunctionDeclaration &func)
655 {
656         SetForScope<FunctionDeclaration *> set_func(current_function, &func);
657         TraversingVisitor::visit(func);
658 }
659
660 void ExpressionValidator::visit(Conditional &cond)
661 {
662         if(cond.condition->type)
663         {
664                 BasicTypeDeclaration *basic_cond = dynamic_cast<BasicTypeDeclaration *>(cond.condition->type);
665                 if(!basic_cond || basic_cond->kind!=BasicTypeDeclaration::BOOL)
666                         error(cond, "Condition is not a boolean");
667         }
668         TraversingVisitor::visit(cond);
669 }
670
671 void ExpressionValidator::visit(Iteration &iter)
672 {
673         if(iter.condition->type)
674         {
675                 BasicTypeDeclaration *basic_cond = dynamic_cast<BasicTypeDeclaration *>(iter.condition->type);
676                 if(!basic_cond || basic_cond->kind!=BasicTypeDeclaration::BOOL)
677                         error(iter, "Loop condition is not a boolean");
678         }
679         TraversingVisitor::visit(iter);
680 }
681
682 void ExpressionValidator::visit(Return &ret)
683 {
684         if(current_function && current_function->return_type_declaration)
685         {
686                 TypeDeclaration *return_type = current_function->return_type_declaration;
687                 BasicTypeDeclaration *basic_return = dynamic_cast<BasicTypeDeclaration *>(return_type);
688                 if(ret.expression)
689                 {
690                         if(ret.expression->type && ret.expression->type!=return_type)
691                                 error(ret, format("Return expression type '%s' is incompatible with declared return type '%s'",
692                                         ret.expression->type->name, return_type->name));
693                 }
694                 else if(!basic_return || basic_return->kind!=BasicTypeDeclaration::VOID)
695                         error(ret, "Return statement without an expression in a function not returning 'void'");
696         }
697
698         TraversingVisitor::visit(ret);
699 }
700
701
702 FlowControlValidator::FlowControlValidator():
703         reachable(true)
704 { }
705
706 void FlowControlValidator::visit(Block &block)
707 {
708         for(NodeList<Statement>::const_iterator i=block.body.begin(); i!=block.body.end(); ++i)
709         {
710                 if(!reachable)
711                 {
712                         diagnose(**i, Diagnostic::WARN, "Unreachable code detected");
713                         break;
714                 }
715                 (*i)->visit(*this);
716         }
717 }
718
719 void FlowControlValidator::visit(FunctionDeclaration &func)
720 {
721         func.body.visit(*this);
722
723         if(func.definition==&func && func.return_type_declaration)
724         {
725                 const BasicTypeDeclaration *basic_ret = dynamic_cast<const BasicTypeDeclaration *>(func.return_type_declaration);
726                 if(reachable && (!basic_ret || basic_ret->kind!=BasicTypeDeclaration::VOID))
727                         error(func, "Missing return statement at the end of a function not returning 'void'");
728         }
729         reachable = true;
730 }
731
732 void FlowControlValidator::visit(Conditional &cond)
733 {
734         cond.body.visit(*this);
735         bool reachable_if_true = reachable;
736         reachable = true;
737         cond.else_body.visit(*this);
738         reachable |= reachable_if_true;
739 }
740
741 void FlowControlValidator::visit(Iteration &iter)
742 {
743         iter.body.visit(*this);
744         reachable = true;
745 }
746
747
748 int StageInterfaceValidator::get_location(const Layout &layout)
749 {
750         for(vector<Layout::Qualifier>::const_iterator i=layout.qualifiers.begin(); i!=layout.qualifiers.end(); ++i)
751                 if(i->name=="location")
752                         return i->value;
753         return -1;
754 }
755
756 void StageInterfaceValidator::visit(VariableDeclaration &var)
757 {
758         int location = (var.layout ? get_location(*var.layout) : -1);
759         if(var.interface=="in" && var.linked_declaration)
760         {
761                 const Layout *linked_layout = var.linked_declaration->layout.get();
762                 int linked_location = (linked_layout ? get_location(*linked_layout) : -1);
763                 if(linked_location!=location)
764                 {
765                         error(var, format("Mismatched location %d for 'in %s'", location, var.name));
766                         add_info(*var.linked_declaration, format("Linked to 'out %s' with location %d",
767                                 var.linked_declaration->name, linked_location));
768                 }
769                 if(var.type_declaration && var.linked_declaration->type_declaration)
770                 {
771                         TypeDeclaration *type = var.type_declaration;
772                         if(stage->type==Stage::GEOMETRY)
773                         {
774                                 if(const BasicTypeDeclaration *basic = dynamic_cast<const BasicTypeDeclaration *>(type))
775                                         if(basic->kind==BasicTypeDeclaration::ARRAY && basic->base_type)
776                                                 type = basic->base_type;
777                         }
778                         if(!TypeComparer().apply(*type, *var.linked_declaration->type_declaration))
779                         {
780                                 error(var, format("Mismatched type '%s' for 'in %s'", type->name, var.name));
781                                 add_info(*var.linked_declaration, format("Linked to 'out %s' with type '%s'",
782                                         var.linked_declaration->name, var.linked_declaration->type_declaration->name));
783                         }
784                 }
785         }
786
787         if(location>=0 && !var.interface.empty())
788         {
789                 map<unsigned, VariableDeclaration *> &used = used_locations[var.interface];
790
791                 unsigned loc_count = LocationCounter().apply(var);
792                 for(unsigned i=0; i<loc_count; ++i)
793                 {
794                         map<unsigned, VariableDeclaration *>::const_iterator j = used.find(location+i);
795                         if(j!=used.end())
796                         {
797                                 error(var, format("Overlapping location %d for '%s %s'", location+i, var.interface, var.name));
798                                 add_info(*j->second, format("Previously used here for '%s %s'", j->second->interface, j->second->name));
799                         }
800                         else
801                                 used[location+i] = &var;
802                 }
803         }
804 }
805
806
807 void GlobalInterfaceValidator::apply(Module &module)
808 {
809         for(list<Stage>::iterator i=module.stages.begin(); i!=module.stages.end(); ++i)
810         {
811                 stage = &*i;
812                 i->content.visit(*this);
813         }
814 }
815
816 void GlobalInterfaceValidator::check_uniform(const Uniform &uni)
817 {
818         map<string, const Uniform *>::const_iterator i = used_names.find(uni.name);
819         if(i!=used_names.end())
820         {
821                 if(uni.location>=0 && i->second->location>=0 && i->second->location!=uni.location)
822                 {
823                         error(*uni.node, format("Mismatched location %d for uniform '%s'", uni.location, uni.name));
824                         add_info(*i->second->node, format("Previously declared here with location %d", i->second->location));
825                 }
826                 if(uni.bind_point>=0 && i->second->bind_point>=0 && i->second->bind_point!=uni.bind_point)
827                 {
828                         error(*uni.node, format("Mismatched binding %d for uniform '%s'", uni.bind_point, uni.name));
829                         add_info(*i->second->node, format("Previously declared here with binding %d", i->second->bind_point));
830                 }
831                 if(uni.type && i->second->type && !TypeComparer().apply(*uni.type, *i->second->type))
832                 {
833                         string type_name = (dynamic_cast<const StructDeclaration *>(uni.type) ?
834                                 "structure" : format("type '%s'", uni.type->name));
835                         error(*uni.node, format("Mismatched %s for uniform '%s'", type_name, uni.name));
836
837                         string message = "Previously declared here";
838                         if(!dynamic_cast<const StructDeclaration *>(i->second->type))
839                                 message += format(" with type '%s'", i->second->type->name);
840                         add_info(*i->second->node, message);
841                 }
842         }
843         else
844                 used_names.insert(make_pair(uni.name, &uni));
845
846         if(uni.location>=0)
847         {
848                 map<unsigned, const Uniform *>::const_iterator j = used_locations.find(uni.location);
849                 if(j!=used_locations.end())
850                 {
851                         if(j->second->name!=uni.name)
852                         {
853                                 error(*uni.node, format("Overlapping location %d for '%s'", uni.location, uni.name));
854                                 add_info(*j->second->node, format("Previously used here for '%s'", j->second->name));
855                         }
856                 }
857                 else
858                 {
859                         for(unsigned k=0; k<uni.loc_count; ++k)
860                                 used_locations.insert(make_pair(uni.location+k, &uni));
861                 }
862         }
863
864         if(uni.bind_point>=0)
865         {
866                 map<unsigned, const Uniform *> &used = used_bindings[uni.desc_set];
867                 map<unsigned, const Uniform *>::const_iterator j = used.find(uni.bind_point);
868                 if(j!=used.end())
869                 {
870                         if(j->second->name!=uni.name)
871                         {
872                                 error(*uni.node, format("Overlapping binding %d for '%s'", uni.bind_point, uni.name));
873                                 add_info(*j->second->node, format("Previously used here for '%s'", j->second->name));
874                         }
875                 }
876                 else
877                         used.insert(make_pair(uni.bind_point, &uni));
878         }
879 }
880
881 void GlobalInterfaceValidator::visit(VariableDeclaration &var)
882 {
883         if(var.interface=="uniform")
884         {
885                 Uniform uni;
886                 uni.node = &var;
887                 uni.type = var.type_declaration;
888                 uni.name = var.name;
889                 if(var.layout)
890                 {
891                         uni.location = get_layout_value(*var.layout, "location");
892                         uni.loc_count = LocationCounter().apply(var);
893                         uni.desc_set = get_layout_value(*var.layout, "set", 0);
894                         uni.bind_point = get_layout_value(*var.layout, "binding");
895                 }
896
897                 uniforms.push_back(uni);
898                 check_uniform(uniforms.back());
899         }
900 }
901
902 void GlobalInterfaceValidator::visit(InterfaceBlock &iface)
903 {
904         if(iface.interface=="uniform")
905         {
906                 Uniform uni;
907                 uni.node = &iface;
908                 uni.type = iface.struct_declaration;
909                 uni.name = iface.block_name;
910                 if(iface.layout)
911                 {
912                         uni.desc_set = get_layout_value(*iface.layout, "set", 0);
913                         uni.bind_point = get_layout_value(*iface.layout, "binding");
914                 }
915
916                 uniforms.push_back(uni);
917                 check_uniform(uniforms.back());
918         }
919 }
920
921 } // namespace SL
922 } // namespace GL
923 } // namespace Msp