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