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