]> git.tdb.fi Git - libs/gl.git/blob - source/glsl/validate.cpp
Split the Light class into subclasses by light type
[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(const Layout::Qualifier &q: layout.qualifiers)
65         {
66                 bool allowed = false;
67                 string err_descr;
68                 bool value = true;
69                 if(q.name=="location")
70                         allowed = (variable && scope==GLOBAL);
71                 else if(q.name=="binding" || q.name=="set")
72                 {
73                         if(q.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(q.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(q.name=="offset")
117                         allowed = (variable && scope==INTERFACE_BLOCK && iface_block->interface=="uniform");
118                 else if(q.name=="align")
119                         allowed = (scope==INTERFACE_BLOCK && iface_block->interface=="uniform");
120                 else if(q.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(q.name=="lines" || q.name=="lines_adjacency" || q.name=="triangles" || q.name=="triangles_adjacency")
126                 {
127                         allowed = (stage->type==Stage::GEOMETRY && iface_layout && iface_layout->interface=="in");
128                         value = false;
129                 }
130                 else if(q.name=="line_strip" || q.name=="triangle_strip")
131                 {
132                         allowed = (stage->type==Stage::GEOMETRY && iface_layout && iface_layout->interface=="out");
133                         value = false;
134                 }
135                 else if(q.name=="invocations")
136                         allowed = (stage->type==Stage::GEOMETRY && iface_layout && iface_layout->interface=="in");
137                 else if(q.name=="max_vertices")
138                         allowed = (stage->type==Stage::GEOMETRY && iface_layout && iface_layout->interface=="out");
139                 else if(q.name=="std140" || q.name=="std430")
140                 {
141                         allowed = (iface_block && !variable && iface_block->interface=="uniform");
142                         value = false;
143                 }
144                 else if(q.name=="column_major" || q.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", q.name, err_descr));
171                 }
172                 else if(value && !q.has_value)
173                         error(layout, format("Layout qualifier '%s' requires a value", q.name));
174                 else if(!value && q.has_value)
175                         error(layout, format("Layout qualifier '%s' does not allow a value", q.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(const RefPtr<VariableDeclaration> &p: func.parameters)
302                 p->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         auto 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         auto 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                 for(const auto &kvp: iface.struct_declaration->members.variables)
386                         check_definition(kvp.first, *kvp.second);
387         }
388 }
389
390 void IdentifierValidator::visit(FunctionDeclaration &func)
391 {
392         string key = func.name+func.signature;
393         auto i = overloaded_functions.find(key);
394         if(i==overloaded_functions.end())
395                 overloaded_functions.insert(make_pair(key, &func));
396         else if(func.return_type_declaration && i->second->return_type_declaration!=func.return_type_declaration)
397         {
398                 error(func, format("Conflicting return type '%s' for function '%s'", func.return_type_declaration->name, func.name));
399                 if(i->second->return_type_declaration)
400                         add_info(*i->second, format("Previously declared as returning '%s'", i->second->return_type_declaration->name));
401         }
402
403         if(Statement *previous = find_definition(func.name))
404         {
405                 if(!dynamic_cast<FunctionDeclaration *>(previous))
406                         multiple_definition(format("'%s'", func.name), func, *previous);
407         }
408         else
409                 record_definition(func.name, func);
410
411         if(func.definition==&func)
412                 check_definition(func.name+func.signature, func);
413
414         TraversingVisitor::visit(func);
415 }
416
417
418 void ReferenceValidator::visit(BasicTypeDeclaration &type)
419 {
420         if(!type.base.empty() && !type.base_type)
421                 error(type, format("Use of undeclared type '%s'", type.base));
422 }
423
424 void ReferenceValidator::visit(ImageTypeDeclaration &type)
425 {
426         if(!type.base.empty() && !type.base_type)
427                 error(type, format("Use of undeclared type '%s'", type.base));
428 }
429
430 void ReferenceValidator::visit(VariableReference &var)
431 {
432         if(!var.declaration)
433                 error(var, format("Use of undeclared variable '%s'", var.name));
434         else if(stage->type!=Stage::VERTEX && var.declaration->interface=="in" && var.name.compare(0, 3, "gl_") && !var.declaration->linked_declaration)
435                 error(var, format("Use of unlinked input variable '%s'", var.name));
436 }
437
438 void ReferenceValidator::visit(MemberAccess &memacc)
439 {
440         if(memacc.left->type && !memacc.declaration)
441                 error(memacc, format("Use of undeclared member '%s'", memacc.member));
442         TraversingVisitor::visit(memacc);
443 }
444
445 void ReferenceValidator::visit(InterfaceBlockReference &iface)
446 {
447         /* An interface block reference without a declaration should be impossible
448         since references are generated based on existing declarations. */
449         if(!iface.declaration)
450                 error(iface, format("Use of undeclared interface block '%s'", iface.name));
451         else if(stage->type!=Stage::VERTEX && iface.declaration->interface=="in" && !iface.declaration->linked_block)
452                 error(iface, format("Use of unlinked input block '%s'", iface.name));
453 }
454
455 void ReferenceValidator::visit(FunctionCall &call)
456 {
457         if((!call.constructor && !call.declaration) || (call.constructor && !call.type))
458         {
459                 bool have_declaration = call.constructor;
460                 if(!call.constructor)
461                 {
462                         auto i = stage->functions.lower_bound(call.name);
463                         have_declaration = (i!=stage->functions.end() && i->second->name==call.name);
464                 }
465
466                 if(have_declaration)
467                 {
468                         bool valid_types = true;
469                         string signature;
470                         for(auto j=call.arguments.begin(); (valid_types && j!=call.arguments.end()); ++j)
471                         {
472                                 if((*j)->type)
473                                         append(signature, ", ", (*j)->type->name);
474                                 else
475                                         valid_types = false;
476                         }
477
478                         if(valid_types)
479                                 error(call, format("No matching %s found for '%s(%s)'", (call.constructor ? "constructor" : "overload"), call.name, signature));
480                 }
481                 else
482                         error(call, format("Call to undeclared function '%s'", call.name));
483         }
484         TraversingVisitor::visit(call);
485 }
486
487 void ReferenceValidator::visit(VariableDeclaration &var)
488 {
489         if(!var.type_declaration)
490                 error(var, format("Use of undeclared type '%s'", var.type));
491         TraversingVisitor::visit(var);
492 }
493
494 void ReferenceValidator::visit(InterfaceBlock &iface)
495 {
496         if(!iface.struct_declaration)
497                 error(iface, format("Interface block '%s %s' lacks a struct declaration", iface.interface, iface.block_name));
498         TraversingVisitor::visit(iface);
499 }
500
501 void ReferenceValidator::visit(FunctionDeclaration &func)
502 {
503         if(!func.return_type_declaration)
504                 error(func, format("Use of undeclared type '%s'", func.return_type));
505         TraversingVisitor::visit(func);
506 }
507
508
509 ExpressionValidator::ExpressionValidator():
510         current_function(0),
511         constant_expression(false)
512 { }
513
514 void ExpressionValidator::visit(VariableReference &var)
515 {
516         if(var.declaration && constant_expression && !var.declaration->constant)
517                 error(var, format("Reference to non-constant variable '%s' in a constant expression", var.name));
518 }
519
520 void ExpressionValidator::visit(InterfaceBlockReference &iface)
521 {
522         if(constant_expression)
523                 error(iface, format("Reference to interface block '%s' in a constant expression", iface.name));
524 }
525
526 void ExpressionValidator::visit(Swizzle &swizzle)
527 {
528         unsigned size = 0;
529         if(BasicTypeDeclaration *basic = dynamic_cast<BasicTypeDeclaration *>(swizzle.left->type))
530         {
531                 if(basic->kind==BasicTypeDeclaration::INT || basic->kind==BasicTypeDeclaration::FLOAT)
532                         size = 1;
533                 else if(basic->kind==BasicTypeDeclaration::VECTOR)
534                         size = basic->size;
535         }
536
537         if(size)
538         {
539                 static const char component_names[] = { 'x', 'y', 'z', 'w', 'r', 'g', 'b', 'a', 's', 't', 'p', 'q' };
540                 int flavour = -1;
541                 for(unsigned i=0; i<swizzle.count; ++i)
542                 {
543                         unsigned component_flavour = (find(component_names, component_names+12, swizzle.component_group[i])-component_names)/4;
544                         if(flavour==-1)
545                                 flavour = component_flavour;
546                         else if(flavour>=0 && component_flavour!=static_cast<unsigned>(flavour))
547                         {
548                                 error(swizzle, format("Flavour of swizzle component '%c' is inconsistent with '%c'",
549                                         swizzle.component_group[i], swizzle.component_group[0]));
550                                 flavour = -2;
551                         }
552
553                         if(swizzle.components[i]>=size)
554                                 error(swizzle, format("Access to component '%c' which is not present in '%s'",
555                                         swizzle.component_group[i], swizzle.left->type->name));
556                 }
557         }
558         else if(swizzle.left->type)
559                 error(swizzle, format("Swizzle applied to '%s' which is neither a scalar nor a vector", swizzle.left->type->name));
560
561         TraversingVisitor::visit(swizzle);
562 }
563
564 void ExpressionValidator::visit(UnaryExpression &unary)
565 {
566         if(unary.expression->type)
567         {
568                 if(!unary.type)
569                         error(unary, format("No matching operator '%s' found for '%s'", unary.oper->token, unary.expression->type->name));
570                 else if(unary.oper->token[1]=='+' || unary.oper->token[1]=='-')
571                 {
572                         if(constant_expression)
573                                 error(unary, format("Use of '%s' in a constant expression", unary.oper->token));
574                         else if(!unary.expression->lvalue)
575                                 error(unary, format("Operand of '%s' is not an lvalue", unary.oper->token));
576                 }
577         }
578         TraversingVisitor::visit(unary);
579 }
580
581 void ExpressionValidator::visit(BinaryExpression &binary)
582 {
583         if(!binary.type && binary.left->type && binary.right->type)
584         {
585                 if(binary.oper->token[0]=='[')
586                         error(binary, format("Can't index element of '%s' with '%s'",
587                                 binary.left->type->name, binary.right->type->name));
588                 else
589                         error(binary, format("No matching operator '%s' found for '%s' and '%s'",
590                                 binary.oper->token, binary.left->type->name, binary.right->type->name));
591         }
592         TraversingVisitor::visit(binary);
593 }
594
595 void ExpressionValidator::visit(Assignment &assign)
596 {
597         if(assign.left->type)
598         {
599                 if(constant_expression)
600                         error(assign, "Assignment in constant expression");
601                 else if(!assign.left->lvalue)
602                         error(assign, "Target of assignment is not an lvalue");
603                 if(assign.right->type)
604                 {
605                         if(assign.oper->token[0]!='=')
606                         {
607                                 if(!assign.type)
608                                         error(assign, format("No matching operator '%s' found for '%s' and '%s'",
609                                                 string(assign.oper->token, strlen(assign.oper->token)-1), assign.left->type->name, assign.right->type->name));
610                         }
611                         else if(assign.left->type!=assign.right->type)
612                                 error(assign, format("Assignment to variable of type '%s' from expression of incompatible type '%s'",
613                                         assign.left->type->name, assign.right->type->name));
614                 }
615         }
616         TraversingVisitor::visit(assign);
617 }
618
619 void ExpressionValidator::visit(TernaryExpression &ternary)
620 {
621         if(ternary.condition->type)
622         {
623                 BasicTypeDeclaration *basic_cond = dynamic_cast<BasicTypeDeclaration *>(ternary.condition->type);
624                 if(!basic_cond || basic_cond->kind!=BasicTypeDeclaration::BOOL)
625                         error(ternary, "Ternary operator condition is not a boolean");
626                 else if(!ternary.type && ternary.true_expr->type && ternary.false_expr->type)
627                         error(ternary, format("Ternary operator has incompatible types '%s' and '%s'",
628                                 ternary.true_expr->type->name, ternary.false_expr->type->name));
629         }
630         TraversingVisitor::visit(ternary);
631 }
632
633 void ExpressionValidator::visit(VariableDeclaration &var)
634 {
635         if(var.init_expression && var.init_expression->type && var.type_declaration && var.init_expression->type!=var.type_declaration)
636                 error(var, format("Initializing a variable of type '%s' with an expression of incompatible type '%s'",
637                         var.type_declaration->name, var.init_expression->type->name));
638
639         if(var.layout)
640                 var.layout->visit(*this);
641         if(var.init_expression)
642         {
643                 SetFlag set_const(constant_expression, var.constant);
644                 TraversingVisitor::visit(var.init_expression);
645         }
646         if(var.array_size)
647         {
648                 SetFlag set_const(constant_expression);
649                 TraversingVisitor::visit(var.array_size);
650         }
651 }
652
653 void ExpressionValidator::visit(FunctionDeclaration &func)
654 {
655         SetForScope<FunctionDeclaration *> set_func(current_function, &func);
656         TraversingVisitor::visit(func);
657 }
658
659 void ExpressionValidator::visit(Conditional &cond)
660 {
661         if(cond.condition->type)
662         {
663                 BasicTypeDeclaration *basic_cond = dynamic_cast<BasicTypeDeclaration *>(cond.condition->type);
664                 if(!basic_cond || basic_cond->kind!=BasicTypeDeclaration::BOOL)
665                         error(cond, "Condition is not a boolean");
666         }
667         TraversingVisitor::visit(cond);
668 }
669
670 void ExpressionValidator::visit(Iteration &iter)
671 {
672         if(iter.condition->type)
673         {
674                 BasicTypeDeclaration *basic_cond = dynamic_cast<BasicTypeDeclaration *>(iter.condition->type);
675                 if(!basic_cond || basic_cond->kind!=BasicTypeDeclaration::BOOL)
676                         error(iter, "Loop condition is not a boolean");
677         }
678         TraversingVisitor::visit(iter);
679 }
680
681 void ExpressionValidator::visit(Return &ret)
682 {
683         if(current_function && current_function->return_type_declaration)
684         {
685                 TypeDeclaration *return_type = current_function->return_type_declaration;
686                 BasicTypeDeclaration *basic_return = dynamic_cast<BasicTypeDeclaration *>(return_type);
687                 if(ret.expression)
688                 {
689                         if(ret.expression->type && ret.expression->type!=return_type)
690                                 error(ret, format("Return expression type '%s' is incompatible with declared return type '%s'",
691                                         ret.expression->type->name, return_type->name));
692                 }
693                 else if(!basic_return || basic_return->kind!=BasicTypeDeclaration::VOID)
694                         error(ret, "Return statement without an expression in a function not returning 'void'");
695         }
696
697         TraversingVisitor::visit(ret);
698 }
699
700
701 FlowControlValidator::FlowControlValidator():
702         reachable(true)
703 { }
704
705 void FlowControlValidator::visit(Block &block)
706 {
707         for(const RefPtr<Statement> &s: block.body)
708         {
709                 if(!reachable)
710                 {
711                         diagnose(*s, Diagnostic::WARN, "Unreachable code detected");
712                         break;
713                 }
714                 s->visit(*this);
715         }
716 }
717
718 void FlowControlValidator::visit(FunctionDeclaration &func)
719 {
720         func.body.visit(*this);
721
722         if(func.definition==&func && func.return_type_declaration)
723         {
724                 const BasicTypeDeclaration *basic_ret = dynamic_cast<const BasicTypeDeclaration *>(func.return_type_declaration);
725                 if(reachable && (!basic_ret || basic_ret->kind!=BasicTypeDeclaration::VOID))
726                         error(func, "Missing return statement at the end of a function not returning 'void'");
727         }
728         reachable = true;
729 }
730
731 void FlowControlValidator::visit(Conditional &cond)
732 {
733         cond.body.visit(*this);
734         bool reachable_if_true = reachable;
735         reachable = true;
736         cond.else_body.visit(*this);
737         reachable |= reachable_if_true;
738 }
739
740 void FlowControlValidator::visit(Iteration &iter)
741 {
742         iter.body.visit(*this);
743         reachable = true;
744 }
745
746
747 int StageInterfaceValidator::get_location(const Layout &layout)
748 {
749         return get_layout_value(layout, "location", -1);
750 }
751
752 void StageInterfaceValidator::visit(VariableDeclaration &var)
753 {
754         int location = (var.layout ? get_location(*var.layout) : -1);
755         if(var.interface=="in" && var.linked_declaration)
756         {
757                 const Layout *linked_layout = var.linked_declaration->layout.get();
758                 int linked_location = (linked_layout ? get_location(*linked_layout) : -1);
759                 if(linked_location!=location)
760                 {
761                         error(var, format("Mismatched location %d for 'in %s'", location, var.name));
762                         add_info(*var.linked_declaration, format("Linked to 'out %s' with location %d",
763                                 var.linked_declaration->name, linked_location));
764                 }
765                 if(var.type_declaration && var.linked_declaration->type_declaration)
766                 {
767                         TypeDeclaration *type = var.type_declaration;
768                         if(stage->type==Stage::GEOMETRY)
769                         {
770                                 if(const BasicTypeDeclaration *basic = dynamic_cast<const BasicTypeDeclaration *>(type))
771                                         if(basic->kind==BasicTypeDeclaration::ARRAY && basic->base_type)
772                                                 type = basic->base_type;
773                         }
774                         if(!TypeComparer().apply(*type, *var.linked_declaration->type_declaration))
775                         {
776                                 error(var, format("Mismatched type '%s' for 'in %s'", type->name, var.name));
777                                 add_info(*var.linked_declaration, format("Linked to 'out %s' with type '%s'",
778                                         var.linked_declaration->name, var.linked_declaration->type_declaration->name));
779                         }
780                 }
781         }
782
783         if(location>=0 && !var.interface.empty())
784         {
785                 map<unsigned, VariableDeclaration *> &used = used_locations[var.interface];
786
787                 unsigned loc_count = LocationCounter().apply(var);
788                 for(unsigned i=0; i<loc_count; ++i)
789                 {
790                         auto j = used.find(location+i);
791                         if(j!=used.end())
792                         {
793                                 error(var, format("Overlapping location %d for '%s %s'", location+i, var.interface, var.name));
794                                 add_info(*j->second, format("Previously used here for '%s %s'", j->second->interface, j->second->name));
795                         }
796                         else
797                                 used[location+i] = &var;
798                 }
799         }
800 }
801
802
803 void GlobalInterfaceValidator::apply(Module &module)
804 {
805         for(Stage &s: module.stages)
806         {
807                 stage = &s;
808                 s.content.visit(*this);
809         }
810 }
811
812 void GlobalInterfaceValidator::check_uniform(const Uniform &uni)
813 {
814         auto i = used_names.find(uni.name);
815         if(i!=used_names.end())
816         {
817                 if(uni.location>=0 && i->second->location>=0 && i->second->location!=uni.location)
818                 {
819                         error(*uni.node, format("Mismatched location %d for uniform '%s'", uni.location, uni.name));
820                         add_info(*i->second->node, format("Previously declared here with location %d", i->second->location));
821                 }
822                 if(uni.bind_point>=0 && i->second->bind_point>=0 && i->second->bind_point!=uni.bind_point)
823                 {
824                         error(*uni.node, format("Mismatched binding %d for uniform '%s'", uni.bind_point, uni.name));
825                         add_info(*i->second->node, format("Previously declared here with binding %d", i->second->bind_point));
826                 }
827                 if(uni.type && i->second->type && !TypeComparer().apply(*uni.type, *i->second->type))
828                 {
829                         string type_name = (dynamic_cast<const StructDeclaration *>(uni.type) ?
830                                 "structure" : format("type '%s'", uni.type->name));
831                         error(*uni.node, format("Mismatched %s for uniform '%s'", type_name, uni.name));
832
833                         string message = "Previously declared here";
834                         if(!dynamic_cast<const StructDeclaration *>(i->second->type))
835                                 message += format(" with type '%s'", i->second->type->name);
836                         add_info(*i->second->node, message);
837                 }
838         }
839         else
840                 used_names.insert(make_pair(uni.name, &uni));
841
842         if(uni.location>=0)
843         {
844                 auto j = used_locations.find(uni.location);
845                 if(j!=used_locations.end())
846                 {
847                         if(j->second->name!=uni.name)
848                         {
849                                 error(*uni.node, format("Overlapping location %d for '%s'", uni.location, uni.name));
850                                 add_info(*j->second->node, format("Previously used here for '%s'", j->second->name));
851                         }
852                 }
853                 else
854                 {
855                         for(unsigned k=0; k<uni.loc_count; ++k)
856                                 used_locations.insert(make_pair(uni.location+k, &uni));
857                 }
858         }
859
860         if(uni.bind_point>=0)
861         {
862                 map<unsigned, const Uniform *> &used = used_bindings[uni.desc_set];
863                 auto j = used.find(uni.bind_point);
864                 if(j!=used.end())
865                 {
866                         if(j->second->name!=uni.name)
867                         {
868                                 error(*uni.node, format("Overlapping binding %d for '%s'", uni.bind_point, uni.name));
869                                 add_info(*j->second->node, format("Previously used here for '%s'", j->second->name));
870                         }
871                 }
872                 else
873                         used.insert(make_pair(uni.bind_point, &uni));
874         }
875 }
876
877 void GlobalInterfaceValidator::visit(VariableDeclaration &var)
878 {
879         if(var.interface=="uniform")
880         {
881                 Uniform uni;
882                 uni.node = &var;
883                 uni.type = var.type_declaration;
884                 uni.name = var.name;
885                 if(var.layout)
886                 {
887                         uni.location = get_layout_value(*var.layout, "location");
888                         uni.loc_count = LocationCounter().apply(var);
889                         uni.desc_set = get_layout_value(*var.layout, "set", 0);
890                         uni.bind_point = get_layout_value(*var.layout, "binding");
891                 }
892
893                 uniforms.push_back(uni);
894                 check_uniform(uniforms.back());
895         }
896 }
897
898 void GlobalInterfaceValidator::visit(InterfaceBlock &iface)
899 {
900         if(iface.interface=="uniform")
901         {
902                 Uniform uni;
903                 uni.node = &iface;
904                 uni.type = iface.struct_declaration;
905                 uni.name = iface.block_name;
906                 if(iface.layout)
907                 {
908                         uni.desc_set = get_layout_value(*iface.layout, "set", 0);
909                         uni.bind_point = get_layout_value(*iface.layout, "binding");
910                 }
911
912                 uniforms.push_back(uni);
913                 check_uniform(uniforms.back());
914         }
915 }
916
917 } // namespace SL
918 } // namespace GL
919 } // namespace Msp