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