]> git.tdb.fi Git - libs/gl.git/blobdiff - source/glsl/validate.cpp
Check the flat qualifier from the correct member
[libs/gl.git] / source / glsl / validate.cpp
index fcccb526e0dc3bc62831e3c949f8bb767b929591..f6b11ef22e34f8e019a43c5ff040eb8f05283c08 100644 (file)
@@ -1,6 +1,9 @@
 #include <cstring>
+#include <msp/core/algorithm.h>
 #include <msp/core/raii.h>
 #include <msp/strings/format.h>
+#include <msp/strings/utils.h>
+#include "reflect.h"
 #include "validate.h"
 
 using namespace std;
@@ -9,44 +12,293 @@ namespace Msp {
 namespace GL {
 namespace SL {
 
-Validator::Validator():
-       stage(0)
-{ }
-
-void Validator::diagnose(Node &node, Diagnostic::Severity severity, const string &message)
+void Validator::diagnose(Node &node, Node &provoking_node, Diagnostic::Severity severity, const string &message)
 {
        Diagnostic diag;
        diag.severity = severity;
        diag.source = node.source;
        diag.line = node.line;
+       diag.provoking_source = provoking_node.source;
+       diag.provoking_line = provoking_node.line;
        diag.message = message;
        stage->diagnostics.push_back(diag);
+
+       last_provoker = &provoking_node;
 }
 
+void Validator::add_info(Node &node, const string &message)
+{
+       if(!last_provoker)
+               throw logic_error("Tried to add info without a previous provoker");
+       diagnose(node, *last_provoker, Diagnostic::INFO, message);
+}
 
-TypeValidator::TypeValidator():
-       in_struct(false)
-{ }
 
-void TypeValidator::visit(BasicTypeDeclaration &type)
+void DeclarationValidator::apply(Stage &s, const Features &f)
 {
-       if(type.kind==BasicTypeDeclaration::VECTOR)
+       stage = &s;
+       features = f;
+       s.content.visit(*this);
+
+       Node *global_err_node = 0;
+       auto i = s.functions.find("main()");
+       if(i!=s.functions.end())
+               global_err_node = i->second;
+       else
+       {
+               for(auto j=s.content.body.begin(); (!global_err_node && j!=s.content.body.end()); ++j)
+                       if((*j)->source>0)
+                               global_err_node = j->get();
+       }
+
+       if(s.type==Stage::TESS_CONTROL)
+       {
+               if(!have_output_vertex_count)
+                       error(*global_err_node, "No vertex count qualifier found on output");
+       }
+       else if(s.type==Stage::TESS_EVAL)
        {
-               BasicTypeDeclaration::Kind base_kind = BasicTypeDeclaration::VOID;
-               if(BasicTypeDeclaration *basic_base = dynamic_cast<BasicTypeDeclaration *>(type.base_type))
-                       base_kind = basic_base->kind;
-               if(base_kind!=BasicTypeDeclaration::BOOL && base_kind!=BasicTypeDeclaration::INT && base_kind!=BasicTypeDeclaration::FLOAT)
-                       error(type, format("Invalid base type '%s' for vector type '%s'", type.base, type.name));
+               if(!have_input_primitive)
+                       error(*global_err_node, "No primitive type qualifier found on input");
        }
-       else if(type.kind==BasicTypeDeclaration::ARRAY)
+       else if(s.type==Stage::GEOMETRY)
        {
-               if(BasicTypeDeclaration *basic_base = dynamic_cast<BasicTypeDeclaration *>(type.base_type))
-                       if(basic_base->kind==BasicTypeDeclaration::VOID)
-                               error(type, format("Invalid base type '%s' for array type '%s'", type.base, type.name));
+               if(!have_input_primitive)
+                       error(*global_err_node, "No primitive type qualifier found on input");
+               if(!have_output_primitive)
+                       error(*global_err_node, "No primitive type qualifier found on output");
+               if(!have_output_vertex_count)
+                       error(*global_err_node, "No vertex count qualifier found on output");
+       }
+       else if(s.type==Stage::COMPUTE)
+       {
+               if(!have_workgroup_size)
+                       error(*global_err_node, "No workgroup size qualifier found");
+       }
+}
+
+const char *DeclarationValidator::describe_variable(ScopeType scope)
+{
+       switch(scope)
+       {
+       case GLOBAL: return "global variable";
+       case STRUCT: return "struct member";
+       case INTERFACE_BLOCK: return "interface block member";
+       case FUNCTION_PARAM: return "function parameter";
+       case FUNCTION: return "local variable";
+       default: return "variable";
+       }
+}
+
+void DeclarationValidator::visit(Layout &layout)
+{
+       bool push_constant = false;
+       bool binding = false;
+       for(const Layout::Qualifier &q: layout.qualifiers)
+       {
+               bool allowed = false;
+               string err_descr;
+               bool value = true;
+               if(q.name=="location")
+                       allowed = (variable && scope==GLOBAL);
+               else if(q.name=="binding" || q.name=="set")
+               {
+                       binding = true;
+
+                       if(q.name=="set" && features.target_api!=VULKAN)
+                       {
+                               error(layout, "Layout qualifier 'set' not allowed when targeting OpenGL");
+                               continue;
+                       }
+
+                       if(variable)
+                       {
+                               const TypeDeclaration *base_type = get_ultimate_base_type(variable->type_declaration);
+                               bool uniform = (variable->interface=="uniform");
+                               allowed = (scope==GLOBAL && uniform && dynamic_cast<const ImageTypeDeclaration *>(base_type));
+                               err_descr = (uniform ? "variable of non-opaque type" : "non-uniform variable");
+                       }
+                       else if(iface_block)
+                       {
+                               allowed = (iface_block->interface=="uniform");
+                               err_descr = "non-uniform interface block";
+                       }
+               }
+               else if(q.name=="constant_id")
+               {
+                       allowed = (variable && scope==GLOBAL);
+                       if(allowed)
+                       {
+                               if(!variable->constant)
+                               {
+                                       allowed = false;
+                                       err_descr = "non-constant variable";
+                               }
+                               else
+                               {
+                                       BasicTypeDeclaration *basic = dynamic_cast<BasicTypeDeclaration *>(variable->type_declaration);
+                                       if(!basic || basic->kind<BasicTypeDeclaration::BOOL || basic->kind>BasicTypeDeclaration::INT)
+                                       {
+                                               allowed = false;
+                                               err_descr = format("variable of type '%s'",
+                                                       (variable->type_declaration ? variable->type_declaration->name : variable->type));
+                                       }
+                               }
+                       }
+               }
+               else if(q.name=="offset")
+                       allowed = (variable && scope==INTERFACE_BLOCK && iface_block->interface=="uniform");
+               else if(q.name=="align")
+                       allowed = (scope==INTERFACE_BLOCK && iface_block->interface=="uniform");
+               else if(q.name=="points")
+               {
+                       allowed = (stage->type==Stage::GEOMETRY && iface_layout && (iface_layout->interface=="in" || iface_layout->interface=="out"));
+                       value = false;
+                       if(allowed)
+                       {
+                               if(iface_layout->interface=="in")
+                                       have_input_primitive = true;
+                               else if(iface_layout->interface=="out")
+                                       have_output_primitive = true;
+                       }
+               }
+               else if(q.name=="triangles")
+               {
+                       allowed = ((stage->type==Stage::GEOMETRY || stage->type==Stage::TESS_EVAL) && iface_layout && iface_layout->interface=="in");
+                       value = false;
+                       if(allowed)
+                               have_input_primitive = true;
+               }
+               else if(q.name=="lines" || q.name=="lines_adjacency" || q.name=="triangles_adjacency")
+               {
+                       allowed = (stage->type==Stage::GEOMETRY && iface_layout && iface_layout->interface=="in");
+                       value = false;
+                       if(allowed)
+                               have_input_primitive = true;
+               }
+               else if(q.name=="quads" || q.name=="isolines")
+               {
+                       allowed = (stage->type==Stage::TESS_EVAL && iface_layout && iface_layout->interface=="in");
+                       value = false;
+                       if(allowed)
+                               have_input_primitive = true;
+               }
+               else if(q.name=="line_strip" || q.name=="triangle_strip")
+               {
+                       allowed = (stage->type==Stage::GEOMETRY && iface_layout && iface_layout->interface=="out");
+                       value = false;
+                       if(allowed)
+                               have_output_primitive = true;
+               }
+               else if(q.name=="invocations")
+                       allowed = (stage->type==Stage::GEOMETRY && iface_layout && iface_layout->interface=="in");
+               else if(q.name=="max_vertices")
+               {
+                       allowed = (stage->type==Stage::GEOMETRY && iface_layout && iface_layout->interface=="out");
+                       if(allowed)
+                               have_output_vertex_count = true;
+               }
+               else if(q.name=="vertices")
+               {
+                       allowed = (stage->type==Stage::TESS_CONTROL && iface_layout && iface_layout->interface=="out");
+                       if(allowed)
+                               have_output_vertex_count = true;
+               }
+               else if(q.name=="cw" || q.name=="ccw" ||
+                       q.name=="equal_spacing" || q.name=="fractional_even_spacing" || q.name=="fractional_odd_spacing")
+               {
+                       allowed = (stage->type==Stage::TESS_EVAL && iface_layout && iface_layout->interface=="in");
+                       value = false;
+               }
+               else if(q.name=="std140" || q.name=="std430")
+               {
+                       allowed = (iface_block && !variable && iface_block->interface=="uniform");
+                       value = false;
+               }
+               else if(q.name=="column_major" || q.name=="row_major")
+               {
+                       allowed = (variable && scope==INTERFACE_BLOCK);
+                       if(allowed)
+                       {
+                               BasicTypeDeclaration *basic = dynamic_cast<BasicTypeDeclaration *>(variable->type_declaration);
+                               while(basic && basic->kind==BasicTypeDeclaration::ARRAY)
+                                       basic = dynamic_cast<BasicTypeDeclaration *>(basic->base_type);
+                               allowed = (basic && basic->kind==BasicTypeDeclaration::MATRIX);
+                               err_descr = "non-matrix variable";
+                       }
+               }
+               else if(q.name=="push_constant")
+               {
+                       push_constant = true;
+                       allowed = (iface_block && !variable && iface_block->interface=="uniform");
+                       value = false;
+               }
+               else if(q.name=="local_size_x" || q.name=="local_size_y" || q.name=="local_size_z")
+               {
+                       allowed = (stage->type==Stage::COMPUTE && iface_layout && iface_layout->interface=="in");
+                       if(allowed)
+                               have_workgroup_size = true;
+               }
+               else if(q.name=="rgba32f" || q.name=="rgba16f" || q.name=="rg32f" || q.name=="rg16f" || q.name=="r32f" || q.name=="r16f" ||
+                       q.name=="rgba16" || q.name=="rgba8" || q.name=="rg16" || q.name=="rg8" || q.name=="r16" || q.name=="r8" ||
+                       q.name=="rgba16_snorm" || q.name=="rgba8_snorm" || q.name=="rg16_snorm" || q.name=="rg8_snorm" || q.name=="r16_snorm" || q.name=="r8_snorm")
+               {
+                       allowed = variable;
+                       value = false;
+                       if(allowed)
+                       {
+                               const TypeDeclaration *base_type = get_ultimate_base_type(variable->type_declaration);
+                               const ImageTypeDeclaration *image = dynamic_cast<const ImageTypeDeclaration *>(base_type);
+                               allowed = (image && !image->sampled);
+                               err_descr = (image ? "sampled image" : "non-image variable");
+                       }
+               }
+
+               if(!allowed)
+               {
+                       if(err_descr.empty())
+                       {
+                               if(variable)
+                                       err_descr = describe_variable(scope);
+                               else if(iface_block)
+                                       err_descr = "interface block";
+                               else if(iface_layout)
+                                       err_descr = format("interface '%s'", iface_layout->interface);
+                               else
+                                       err_descr = "unknown declaration";
+                       }
+                       error(layout, format("Layout qualifier '%s' not allowed on %s", q.name, err_descr));
+               }
+               else if(value && !q.has_value)
+                       error(layout, format("Layout qualifier '%s' requires a value", q.name));
+               else if(!value && q.has_value)
+                       error(layout, format("Layout qualifier '%s' does not allow a value", q.name));
        }
+
+       if(push_constant && binding)
+               error(layout, "Layout qualifier 'push_constant' not allowed together with 'binding' or 'set'");
+}
+
+void DeclarationValidator::visit(InterfaceLayout &layout)
+{
+       SetForScope<InterfaceLayout *> set_layout(iface_layout, &layout);
+       TraversingVisitor::visit(layout);
+}
+
+void DeclarationValidator::visit(BasicTypeDeclaration &type)
+{
+       BasicTypeDeclaration *basic_base = dynamic_cast<BasicTypeDeclaration *>(type.base_type);
+       BasicTypeDeclaration::Kind base_kind = (basic_base ? basic_base->kind : BasicTypeDeclaration::VOID);
+
+       if(type.kind==BasicTypeDeclaration::VECTOR && (base_kind<BasicTypeDeclaration::BOOL || base_kind>BasicTypeDeclaration::FLOAT))
+               error(type, format("Invalid base type '%s' for vector type '%s'", type.base, type.name));
+       else if(type.kind==BasicTypeDeclaration::MATRIX && base_kind!=BasicTypeDeclaration::VECTOR)
+               error(type, format("Invalid base type '%s' for matrix type '%s'", type.base, type.name));
+       else if(type.kind==BasicTypeDeclaration::ARRAY && basic_base && base_kind==BasicTypeDeclaration::VOID)
+               error(type, format("Invalid base type '%s' for array type '%s'", type.base, type.name));
 }
 
-void TypeValidator::visit(ImageTypeDeclaration &type)
+void DeclarationValidator::visit(ImageTypeDeclaration &type)
 {
        BasicTypeDeclaration::Kind base_kind = BasicTypeDeclaration::VOID;
        if(BasicTypeDeclaration *basic_base = dynamic_cast<BasicTypeDeclaration *>(type.base_type))
@@ -55,40 +307,127 @@ void TypeValidator::visit(ImageTypeDeclaration &type)
                error(type, format("Invalid base type '%s' for image type '%s'", type.base, type.name));
 }
 
-void TypeValidator::visit(StructDeclaration &strct)
+void DeclarationValidator::visit(StructDeclaration &strct)
 {
-       SetFlag set_struct(in_struct);
+       SetForScope<ScopeType> set_scope(scope, (strct.block_name.empty() ? STRUCT : INTERFACE_BLOCK));
+       SetForScope<VariableDeclaration *> set_iface(iface_block, strct.block_declaration);
        TraversingVisitor::visit(strct);
 }
 
-void TypeValidator::visit(VariableDeclaration &var)
+void DeclarationValidator::visit(VariableDeclaration &var)
 {
-       if(in_struct)
+       SetForScope<VariableDeclaration *> set_var((var.block_declaration ? iface_block : variable), &var);
+
+       const char *descr = describe_variable(scope);
+
+       if(var.layout)
        {
-               if(var.layout)
-                       error(var, "Struct members can't have layouts");
-               if(var.init_expression)
-                       error(var, "Struct members can't have initializers");
+               if(scope!=GLOBAL && scope!=INTERFACE_BLOCK)
+                       error(var, format("Layout qualifier not allowed on %s", descr));
+               else
+                       var.layout->visit(*this);
        }
 
-       TraversingVisitor::visit(var);
+       if(var.constant)
+       {
+               if(scope==STRUCT || scope==INTERFACE_BLOCK)
+                       error(var, format("Constant qualifier not allowed on %s", descr));
+               if(!var.init_expression)
+                       error(var, "Constant variable must have an initializer");
+       }
+
+       if(!var.interpolation.empty() || !var.sampling.empty())
+       {
+               if(var.interface=="in" && stage->type==Stage::VERTEX)
+                       error(var, "Interpolation qualifier not allowed on vertex input");
+               else if(var.interface=="out" && stage->type==Stage::FRAGMENT)
+                       error(var, "Interpolation qualifier not allowed on fragment output");
+               else if((var.interface!="in" && var.interface!="out") || (scope==FUNCTION_PARAM || scope==FUNCTION))
+                       error(var, "Interpolation qualifier not allowed on non-interpolated variable");
+               else if(var.sampling=="patch" && (stage->type!=Stage::TESS_CONTROL || var.interface!="out") && (stage->type!=Stage::TESS_EVAL || var.interface!="in"))
+                       error(var, "Per-patch variables only allowed on tessellation control output or tessellation evaluation input");
+               if(var.sampling=="patch" && !var.interpolation.empty())
+                       error(var, "Interpolation qualifier not allowed on per-patch variable");
+       }
+
+       if(!var.interface.empty())
+       {
+               if(iface_block && var.interface!=iface_block->interface)
+                       error(var, format("Mismatched interface qualifier '%s' inside '%s' block", var.interface, iface_block->interface));
+               else if(scope==STRUCT || scope==FUNCTION)
+                       error(var, format("Interface qualifier not allowed on %s", descr));
+               else if(scope==GLOBAL && var.interface=="uniform" && !var.block_declaration && features.target_api==VULKAN)
+               {
+                       if(!dynamic_cast<const ImageTypeDeclaration *>(get_ultimate_base_type(var.type_declaration)))
+                               error(var, "Interface qualifier 'uniform' not allowed on non-opaque variable in global scope");
+               }
+       }
+
+       TypeDeclaration *type = var.type_declaration;
+       BasicTypeDeclaration::Kind kind = BasicTypeDeclaration::ALIAS;
+       while(BasicTypeDeclaration *basic = dynamic_cast<BasicTypeDeclaration *>(type))
+       {
+               kind = basic->kind;
+               type = basic->base_type;
+       }
+       if(dynamic_cast<ImageTypeDeclaration *>(type))
+       {
+               if(scope!=GLOBAL && scope!=FUNCTION_PARAM)
+                       error(var, format("Type '%s' not allowed on %s", type->name, descr));
+               else if(scope==GLOBAL && var.interface!="uniform")
+                       error(var, format("Type '%s' only allowed with uniform interface", type->name));
+       }
+       else if(var.block_declaration)
+       {
+               if(stage->type==Stage::VERTEX && var.interface=="in")
+                       error(var, "Interface block not allowed on vertex shader input");
+               else if(stage->type==Stage::FRAGMENT && var.interface=="out")
+                       error(var, "Interface block not allowed on fragment shader output");
+       }
+       else if(kind==BasicTypeDeclaration::VOID)
+               error(var, "Type 'void' not allowed on variable");
+       else if(kind==BasicTypeDeclaration::BOOL && var.source!=BUILTIN_SOURCE)
+       {
+               if(scope==INTERFACE_BLOCK)
+                       error(var, "Type 'bool' not allowed in an interface block");
+               else if(!var.interface.empty())
+                       error(var, "Type 'bool' not allowed on interface variable");
+       }
+
+       if(var.array && !var.array_size)
+               error(var, "Array must have a size");
+
+       if(var.init_expression)
+       {
+               if(scope==GLOBAL && !var.constant)
+                       error(var, format("Initializer not allowed on non-constant %s", descr));
+               else if(scope!=GLOBAL && scope!=FUNCTION)
+                       error(var, format("Initializer not allowed on %s", descr));
+               else
+                       var.init_expression->visit(*this);
+       }
 }
 
+void DeclarationValidator::visit(FunctionDeclaration &func)
+{
+       SetForScope<ScopeType> set_scope(scope, FUNCTION_PARAM);
+       for(const RefPtr<VariableDeclaration> &p: func.parameters)
+               p->visit(*this);
+       scope = FUNCTION;
+       func.body.visit(*this);
+}
 
-DeclarationValidator::DeclarationValidator():
-       anonymous_block(false)
-{ }
 
-void DeclarationValidator::multiple_definition(const string &name, Statement &statement, Statement &previous)
+void IdentifierValidator::multiple_definition(const string &name, Statement &statement, Statement &previous)
 {
        error(statement, format("Multiple definition of %s", name));
-       diagnose(previous, Diagnostic::INFO, "Previous definition is here");
+       add_info(previous, "Previous definition is here");
 }
 
-Statement *DeclarationValidator::find_definition(const string &name)
+Statement *IdentifierValidator::find_definition(const string &name)
 {
        BlockDeclarationMap *decls = &declarations[current_block];
-       BlockDeclarationMap::const_iterator i = decls->find(name);
+       auto i = decls->find(name);
        if(i==decls->end() && anonymous_block)
        {
                decls = &declarations[current_block->parent];
@@ -97,7 +436,7 @@ Statement *DeclarationValidator::find_definition(const string &name)
        return (i!=decls->end() ? i->second : 0);
 }
 
-void DeclarationValidator::check_definition(const string &name, Statement &statement)
+void IdentifierValidator::check_definition(const string &name, Statement &statement)
 {
        if(Statement *previous = find_definition(name))
                multiple_definition(format("'%s'", name), statement, *previous);
@@ -105,67 +444,84 @@ void DeclarationValidator::check_definition(const string &name, Statement &state
                record_definition(name, statement);
 }
 
-void DeclarationValidator::record_definition(const string &name, Statement &statement)
+void IdentifierValidator::record_definition(const string &name, Statement &statement)
 {
        declarations[current_block].insert(make_pair(name, &statement));
        if(anonymous_block)
                declarations[current_block->parent].insert(make_pair(name, &statement));
 }
 
-void DeclarationValidator::visit(TypeDeclaration &type)
+void IdentifierValidator::visit(TypeDeclaration &type)
 {
-       check_definition(type.name, type);
+       if(type.source!=INTERNAL_SOURCE)
+               check_definition(type.name, type);
 }
 
-void DeclarationValidator::visit(StructDeclaration &strct)
+void IdentifierValidator::visit(StructDeclaration &strct)
 {
-       check_definition(strct.name, strct);
+       if(strct.block_name.empty())
+               check_definition(strct.name, strct);
        TraversingVisitor::visit(strct);
 }
 
-void DeclarationValidator::visit(VariableDeclaration &var)
+void IdentifierValidator::visit(VariableDeclaration &var)
 {
-       check_definition(var.name, var);
-       TraversingVisitor::visit(var);
-}
+       if(var.block_declaration)
+       {
+               string key = format("%s %s", var.interface, var.block_declaration->block_name);
+               auto i = interface_blocks.find(key);
+               if(i!=interface_blocks.end())
+                       multiple_definition(format("interface block '%s %s'", var.interface, var.block_declaration->block_name), var, *i->second);
+               else
+                       interface_blocks.insert(make_pair(key, &var));
 
-void DeclarationValidator::visit(InterfaceBlock &iface)
-{
-       string key = iface.interface+iface.name;
-       map<string, InterfaceBlock *>::const_iterator i = interface_blocks.find(key);
-       if(i!=interface_blocks.end())
-               multiple_definition(format("interface block '%s %s'", iface.interface, iface.name), iface, *i->second);
-       else
-               interface_blocks.insert(make_pair(key, &iface));
+               if(Statement *previous = find_definition(var.block_declaration->block_name))
+               {
+                       const VariableDeclaration *prev_var = dynamic_cast<const VariableDeclaration *>(previous);
+                       if(!prev_var || !prev_var->block_declaration)
+                               multiple_definition(format("'%s'", var.block_declaration->block_name), var, *previous);
+               }
+               else
+                       record_definition(var.block_declaration->block_name, var);
 
-       if(Statement *previous = find_definition(iface.name))
-       {
-               if(!dynamic_cast<InterfaceBlock *>(previous))
-                       multiple_definition(format("'%s'", iface.name), iface, *previous);
+               if(var.name.find(' ')!=string::npos)
+               {
+                       // Inject anonymous interface block members into the global scope
+                       for(const auto &kvp: var.block_declaration->members.variables)
+                               check_definition(kvp.first, *kvp.second);
+               }
        }
-       else
-               record_definition(iface.name, iface);
 
-       if(!iface.instance_name.empty())
-               check_definition(iface.instance_name, iface);
+       if(var.name.find(' ')==string::npos)
+               check_definition(var.name, var);
 
-       SetFlag set_anon(anonymous_block, iface.instance_name.empty());
-       TraversingVisitor::visit(iface);
+       TraversingVisitor::visit(var);
 }
 
-void DeclarationValidator::visit(FunctionDeclaration &func)
+void IdentifierValidator::visit(FunctionDeclaration &func)
 {
+       string key = func.name+func.signature;
+       auto i = overloaded_functions.find(key);
+       if(i==overloaded_functions.end())
+               overloaded_functions.insert(make_pair(key, &func));
+       else if(func.return_type_declaration && i->second->return_type_declaration!=func.return_type_declaration)
+       {
+               error(func, format("Conflicting return type '%s' for function '%s'", func.return_type_declaration->name, func.name));
+               if(i->second->return_type_declaration)
+                       add_info(*i->second, format("Previously declared as returning '%s'", i->second->return_type_declaration->name));
+       }
+
        if(Statement *previous = find_definition(func.name))
        {
-               FunctionDeclaration *prev_func = dynamic_cast<FunctionDeclaration *>(previous);
-               if(prev_func && prev_func->definition==&func)
-                       declarations[current_block][func.name] = &func;
-               else
+               if(!dynamic_cast<FunctionDeclaration *>(previous))
                        multiple_definition(format("'%s'", func.name), func, *previous);
        }
        else
                record_definition(func.name, func);
 
+       if(func.definition==&func)
+               check_definition(func.name+func.signature, func);
+
        TraversingVisitor::visit(func);
 }
 
@@ -186,18 +542,47 @@ void ReferenceValidator::visit(VariableReference &var)
 {
        if(!var.declaration)
                error(var, format("Use of undeclared variable '%s'", var.name));
-       else if(stage->type!=Stage::VERTEX && var.declaration->interface=="in" && !var.declaration->linked_declaration)
-               error(var, format("Use of unlinked input variable '%s'", var.name));
+       else if(stage->type!=Stage::VERTEX && var.declaration->interface=="in" && var.name.compare(0, 3, "gl_") && !var.declaration->linked_declaration)
+               error(var, format("Use of unlinked input %s '%s'", (var.declaration->block_declaration ? "block" : "variable"), var.name));
 }
 
-void ReferenceValidator::visit(InterfaceBlockReference &iface)
+void ReferenceValidator::visit(MemberAccess &memacc)
 {
-       /* An interface block reference without a declaration should be impossible
-       since references are generated based on existing declarations. */
-       if(!iface.declaration)
-               error(iface, format("Use of undeclared interface block '%s'", iface.name));
-       else if(stage->type!=Stage::VERTEX && iface.declaration->interface=="in" && !iface.declaration->linked_block)
-               error(iface, format("Use of unlinked input block '%s'", iface.name));
+       if(memacc.left->type && !memacc.declaration)
+               error(memacc, format("Use of undeclared member '%s'", memacc.member));
+       TraversingVisitor::visit(memacc);
+}
+
+void ReferenceValidator::visit(FunctionCall &call)
+{
+       if((!call.constructor && !call.declaration) || (call.constructor && !call.type))
+       {
+               bool have_declaration = call.constructor;
+               if(!call.constructor)
+               {
+                       auto i = stage->functions.lower_bound(call.name);
+                       have_declaration = (i!=stage->functions.end() && i->second->name==call.name);
+               }
+
+               if(have_declaration)
+               {
+                       bool valid_types = true;
+                       string signature;
+                       for(auto j=call.arguments.begin(); (valid_types && j!=call.arguments.end()); ++j)
+                       {
+                               if((*j)->type)
+                                       append(signature, ", ", (*j)->type->name);
+                               else
+                                       valid_types = false;
+                       }
+
+                       if(valid_types)
+                               error(call, format("No matching %s found for '%s(%s)'", (call.constructor ? "constructor" : "overload"), call.name, signature));
+               }
+               else
+                       error(call, format("Call to undeclared function '%s'", call.name));
+       }
+       TraversingVisitor::visit(call);
 }
 
 void ReferenceValidator::visit(VariableDeclaration &var)
@@ -215,14 +600,74 @@ void ReferenceValidator::visit(FunctionDeclaration &func)
 }
 
 
+void ExpressionValidator::visit(VariableReference &var)
+{
+       if(var.declaration && constant_expression)
+       {
+               if(!var.declaration->constant)
+               {
+                       const char *kind = (var.declaration->block_declaration ? "interface block" : "non-constant variable");
+                       error(var, format("Reference to %s '%s' in a constant expression", kind, var.name));
+               }
+               else if(var.declaration->layout && constant_expression==FIXED_CONSTANT)
+               {
+                       if(has_layout_qualifier(var.declaration->layout.get(), "constant_id"))
+                               error(var, format("Reference to specialization constant '%s' in a fixed constant expression", var.name));
+               }
+       }
+}
+
+void ExpressionValidator::visit(Swizzle &swizzle)
+{
+       unsigned size = 0;
+       if(BasicTypeDeclaration *basic = dynamic_cast<BasicTypeDeclaration *>(swizzle.left->type))
+       {
+               if(basic->kind==BasicTypeDeclaration::INT || basic->kind==BasicTypeDeclaration::FLOAT)
+                       size = 1;
+               else if(basic->kind==BasicTypeDeclaration::VECTOR)
+                       size = basic->size;
+       }
+
+       if(size)
+       {
+               static const char component_names[] = { 'x', 'y', 'z', 'w', 'r', 'g', 'b', 'a', 's', 't', 'p', 'q' };
+               int flavour = -1;
+               for(unsigned i=0; i<swizzle.count; ++i)
+               {
+                       unsigned component_flavour = (std::find(component_names, component_names+12, swizzle.component_group[i])-component_names)/4;
+                       if(flavour==-1)
+                               flavour = component_flavour;
+                       else if(flavour>=0 && component_flavour!=static_cast<unsigned>(flavour))
+                       {
+                               error(swizzle, format("Flavour of swizzle component '%c' is inconsistent with '%c'",
+                                       swizzle.component_group[i], swizzle.component_group[0]));
+                               flavour = -2;
+                       }
+
+                       if(swizzle.components[i]>=size)
+                               error(swizzle, format("Access to component '%c' which is not present in '%s'",
+                                       swizzle.component_group[i], swizzle.left->type->name));
+               }
+       }
+       else if(swizzle.left->type)
+               error(swizzle, format("Swizzle applied to '%s' which is neither a scalar nor a vector", swizzle.left->type->name));
+
+       TraversingVisitor::visit(swizzle);
+}
+
 void ExpressionValidator::visit(UnaryExpression &unary)
 {
        if(unary.expression->type)
        {
                if(!unary.type)
                        error(unary, format("No matching operator '%s' found for '%s'", unary.oper->token, unary.expression->type->name));
-               else if((unary.oper->token[1]=='+' || unary.oper->token[1]=='-') && !unary.expression->lvalue)
-                       error(unary, format("Operand of '%s' is not an lvalue", unary.oper->token));
+               else if(unary.oper->token[1]=='+' || unary.oper->token[1]=='-')
+               {
+                       if(constant_expression)
+                               error(unary, format("Use of '%s' in a constant expression", unary.oper->token));
+                       else if(!unary.expression->lvalue)
+                               error(unary, format("Operand of '%s' is not an lvalue", unary.oper->token));
+               }
        }
        TraversingVisitor::visit(unary);
 }
@@ -230,8 +675,14 @@ void ExpressionValidator::visit(UnaryExpression &unary)
 void ExpressionValidator::visit(BinaryExpression &binary)
 {
        if(!binary.type && binary.left->type && binary.right->type)
-               error(binary, format("No matching operator '%s' found for '%s' and '%s'",
-                       binary.oper->token, binary.left->type->name, binary.right->type->name));
+       {
+               if(binary.oper->token[0]=='[')
+                       error(binary, format("Can't index element of '%s' with '%s'",
+                               binary.left->type->name, binary.right->type->name));
+               else
+                       error(binary, format("No matching operator '%s' found for '%s' and '%s'",
+                               binary.oper->token, binary.left->type->name, binary.right->type->name));
+       }
        TraversingVisitor::visit(binary);
 }
 
@@ -239,7 +690,9 @@ void ExpressionValidator::visit(Assignment &assign)
 {
        if(assign.left->type)
        {
-               if(!assign.left->lvalue)
+               if(constant_expression)
+                       error(assign, "Assignment in constant expression");
+               else if(!assign.left->lvalue)
                        error(assign, "Target of assignment is not an lvalue");
                if(assign.right->type)
                {
@@ -257,12 +710,297 @@ void ExpressionValidator::visit(Assignment &assign)
        TraversingVisitor::visit(assign);
 }
 
+void ExpressionValidator::visit(TernaryExpression &ternary)
+{
+       if(ternary.condition->type)
+       {
+               BasicTypeDeclaration *basic_cond = dynamic_cast<BasicTypeDeclaration *>(ternary.condition->type);
+               if(!basic_cond || basic_cond->kind!=BasicTypeDeclaration::BOOL)
+                       error(ternary, "Ternary operator condition is not a boolean");
+               else if(!ternary.type && ternary.true_expr->type && ternary.false_expr->type)
+                       error(ternary, format("Ternary operator has incompatible types '%s' and '%s'",
+                               ternary.true_expr->type->name, ternary.false_expr->type->name));
+       }
+       TraversingVisitor::visit(ternary);
+}
+
+void ExpressionValidator::visit(StructDeclaration &strct)
+{
+       SetFlag set_struct(in_struct);
+       TraversingVisitor::visit(strct);
+}
+
 void ExpressionValidator::visit(VariableDeclaration &var)
 {
        if(var.init_expression && var.init_expression->type && var.type_declaration && var.init_expression->type!=var.type_declaration)
                error(var, format("Initializing a variable of type '%s' with an expression of incompatible type '%s'",
                        var.type_declaration->name, var.init_expression->type->name));
-       TraversingVisitor::visit(var);
+
+       if(var.layout)
+               var.layout->visit(*this);
+       if(var.init_expression)
+       {
+               ConstantKind const_kind = (!var.constant ? NOT_CONSTANT :
+                       has_layout_qualifier(var.layout.get(), "constant_id") ? FIXED_CONSTANT : SPEC_CONSTANT);
+
+               SetForScope<ConstantKind> set_const(constant_expression, const_kind);
+               TraversingVisitor::visit(var.init_expression);
+       }
+       if(var.array_size)
+       {
+               SetForScope<ConstantKind> set_const(constant_expression, (in_struct || !var.interface.empty() ? FIXED_CONSTANT : SPEC_CONSTANT));
+               TraversingVisitor::visit(var.array_size);
+       }
+}
+
+void ExpressionValidator::visit(FunctionDeclaration &func)
+{
+       SetForScope<FunctionDeclaration *> set_func(current_function, &func);
+       TraversingVisitor::visit(func);
+}
+
+void ExpressionValidator::visit(Conditional &cond)
+{
+       if(cond.condition->type)
+       {
+               BasicTypeDeclaration *basic_cond = dynamic_cast<BasicTypeDeclaration *>(cond.condition->type);
+               if(!basic_cond || basic_cond->kind!=BasicTypeDeclaration::BOOL)
+                       error(cond, "Condition is not a boolean");
+       }
+       TraversingVisitor::visit(cond);
+}
+
+void ExpressionValidator::visit(Iteration &iter)
+{
+       if(iter.condition->type)
+       {
+               BasicTypeDeclaration *basic_cond = dynamic_cast<BasicTypeDeclaration *>(iter.condition->type);
+               if(!basic_cond || basic_cond->kind!=BasicTypeDeclaration::BOOL)
+                       error(iter, "Loop condition is not a boolean");
+       }
+       TraversingVisitor::visit(iter);
+}
+
+void ExpressionValidator::visit(Return &ret)
+{
+       if(current_function && current_function->return_type_declaration)
+       {
+               TypeDeclaration *return_type = current_function->return_type_declaration;
+               BasicTypeDeclaration *basic_return = dynamic_cast<BasicTypeDeclaration *>(return_type);
+               if(ret.expression)
+               {
+                       if(ret.expression->type && ret.expression->type!=return_type)
+                               error(ret, format("Return expression type '%s' is incompatible with declared return type '%s'",
+                                       ret.expression->type->name, return_type->name));
+               }
+               else if(!basic_return || basic_return->kind!=BasicTypeDeclaration::VOID)
+                       error(ret, "Return statement without an expression in a function not returning 'void'");
+       }
+
+       TraversingVisitor::visit(ret);
+}
+
+
+void FlowControlValidator::visit(Block &block)
+{
+       for(const RefPtr<Statement> &s: block.body)
+       {
+               if(!reachable)
+               {
+                       diagnose(*s, Diagnostic::WARN, "Unreachable code detected");
+                       break;
+               }
+               s->visit(*this);
+       }
+}
+
+void FlowControlValidator::visit(FunctionDeclaration &func)
+{
+       func.body.visit(*this);
+
+       if(func.definition==&func && func.return_type_declaration)
+       {
+               const BasicTypeDeclaration *basic_ret = dynamic_cast<const BasicTypeDeclaration *>(func.return_type_declaration);
+               if(reachable && (!basic_ret || basic_ret->kind!=BasicTypeDeclaration::VOID))
+                       error(func, "Missing return statement at the end of a function not returning 'void'");
+       }
+       reachable = true;
+}
+
+void FlowControlValidator::visit(Conditional &cond)
+{
+       cond.body.visit(*this);
+       bool reachable_if_true = reachable;
+       reachable = true;
+       cond.else_body.visit(*this);
+       reachable |= reachable_if_true;
+}
+
+void FlowControlValidator::visit(Iteration &iter)
+{
+       iter.body.visit(*this);
+       reachable = true;
+}
+
+
+void StageInterfaceValidator::visit(VariableDeclaration &var)
+{
+       int location = get_layout_value(var.layout.get(), "location");
+       if(var.interface=="in" && var.linked_declaration)
+       {
+               const Layout *linked_layout = var.linked_declaration->layout.get();
+               int linked_location = get_layout_value(linked_layout, "location");
+               if(linked_location!=location)
+               {
+                       error(var, format("Mismatched location %d for 'in %s'", location, var.name));
+                       add_info(*var.linked_declaration, format("Linked to 'out %s' with location %d",
+                               var.linked_declaration->name, linked_location));
+               }
+               if(var.type_declaration && var.linked_declaration->type_declaration)
+               {
+                       TypeDeclaration *type = var.type_declaration;
+                       if(stage->type==Stage::TESS_CONTROL || stage->type==Stage::GEOMETRY)
+                       {
+                               if(const BasicTypeDeclaration *basic = dynamic_cast<const BasicTypeDeclaration *>(type))
+                                       if(basic->kind==BasicTypeDeclaration::ARRAY && basic->base_type)
+                                               type = basic->base_type;
+                       }
+                       if(!TypeComparer().apply(*type, *var.linked_declaration->type_declaration))
+                       {
+                               error(var, format("Mismatched type '%s' for 'in %s'", type->name, var.name));
+                               add_info(*var.linked_declaration, format("Linked to 'out %s' with type '%s'",
+                                       var.linked_declaration->name, var.linked_declaration->type_declaration->name));
+                       }
+               }
+               if((var.sampling=="patch") != (var.linked_declaration->sampling=="patch"))
+               {
+                       error(var, format("Mismatched sampling qualifier '%s' for 'in %s'", var.sampling, var.name));
+                       add_info(*var.linked_declaration, format("Linked to 'out %s' qualified as '%s'",
+                               var.linked_declaration->name, var.linked_declaration->sampling));
+               }
+       }
+
+       if(location>=0 && !var.interface.empty())
+       {
+               map<unsigned, VariableDeclaration *> &used = used_locations[var.interface];
+
+               unsigned loc_count = LocationCounter().apply(var);
+               for(unsigned i=0; i<loc_count; ++i)
+               {
+                       auto j = used.find(location+i);
+                       if(j!=used.end())
+                       {
+                               error(var, format("Overlapping location %d for '%s %s'", location+i, var.interface, var.name));
+                               add_info(*j->second, format("Previously used here for '%s %s'", j->second->interface, j->second->name));
+                       }
+                       else
+                               used[location+i] = &var;
+               }
+       }
+}
+
+
+void GlobalInterfaceValidator::apply(Module &module)
+{
+       for(Stage &s: module.stages)
+       {
+               stage = &s;
+               s.content.visit(*this);
+       }
+}
+
+void GlobalInterfaceValidator::check_uniform(const Uniform &uni)
+{
+       auto i = used_names.find(uni.name);
+       if(i!=used_names.end())
+       {
+               if(uni.location>=0 && i->second->location>=0 && i->second->location!=uni.location)
+               {
+                       error(*uni.node, format("Mismatched location %d for uniform '%s'", uni.location, uni.name));
+                       add_info(*i->second->node, format("Previously declared here with location %d", i->second->location));
+               }
+               if(i->second->desc_set!=uni.desc_set)
+               {
+                       error(*uni.node, format("Mismatched descriptor set %d for uniform '%s'", uni.desc_set, uni.name));
+                       add_info(*i->second->node, format("Previously declared here with descriptor set %d", i->second->desc_set));
+               }
+               if(uni.bind_point>=0 && i->second->bind_point>=0 && i->second->bind_point!=uni.bind_point)
+               {
+                       error(*uni.node, format("Mismatched binding %d for uniform '%s'", uni.bind_point, uni.name));
+                       add_info(*i->second->node, format("Previously declared here with binding %d", i->second->bind_point));
+               }
+               if(uni.type && i->second->type && !TypeComparer().apply(*uni.type, *i->second->type))
+               {
+                       string type_name = (dynamic_cast<const StructDeclaration *>(uni.type) ?
+                               "structure" : format("type '%s'", uni.type->name));
+                       error(*uni.node, format("Mismatched %s for uniform '%s'", type_name, uni.name));
+
+                       string message = "Previously declared here";
+                       if(!dynamic_cast<const StructDeclaration *>(i->second->type))
+                               message += format(" with type '%s'", i->second->type->name);
+                       add_info(*i->second->node, message);
+               }
+       }
+       else
+               used_names.insert(make_pair(uni.name, &uni));
+
+       if(uni.location>=0)
+       {
+               auto j = used_locations.find(uni.location);
+               if(j!=used_locations.end())
+               {
+                       if(j->second->name!=uni.name)
+                       {
+                               error(*uni.node, format("Overlapping location %d for '%s'", uni.location, uni.name));
+                               add_info(*j->second->node, format("Previously used here for '%s'", j->second->name));
+                       }
+               }
+               else
+               {
+                       for(unsigned k=0; k<uni.loc_count; ++k)
+                               used_locations.insert(make_pair(uni.location+k, &uni));
+               }
+       }
+
+       if(uni.bind_point>=0)
+       {
+               map<unsigned, const Uniform *> &used = used_bindings[uni.desc_set];
+               auto j = used.find(uni.bind_point);
+               if(j!=used.end())
+               {
+                       if(j->second->name!=uni.name)
+                       {
+                               error(*uni.node, format("Overlapping binding %d for '%s'", uni.bind_point, uni.name));
+                               add_info(*j->second->node, format("Previously used here for '%s'", j->second->name));
+                       }
+               }
+               else
+                       used.insert(make_pair(uni.bind_point, &uni));
+       }
+}
+
+void GlobalInterfaceValidator::visit(VariableDeclaration &var)
+{
+       if(var.interface=="uniform")
+       {
+               Uniform uni;
+               uni.node = &var;
+               uni.type = var.type_declaration;
+               uni.name = (var.block_declaration ? var.block_declaration->block_name : var.name);
+               if(var.layout)
+               {
+                       if(!var.block_declaration)
+                       {
+                               uni.location = get_layout_value(var.layout.get(), "location");
+                               uni.loc_count = LocationCounter().apply(var);
+                       }
+                       uni.desc_set = get_layout_value(var.layout.get(), "set", 0);
+                       uni.bind_point = get_layout_value(var.layout.get(), "binding");
+               }
+
+               uniforms.push_back(uni);
+               check_uniform(uniforms.back());
+       }
 }
 
 } // namespace SL