1 #include <msp/core/algorithm.h>
2 #include <msp/core/raii.h>
3 #include <msp/strings/format.h>
4 #include <msp/strings/regex.h>
5 #include <msp/strings/utils.h>
7 #include "glsl_error.h"
8 #include "modulecache.h"
19 Parser::Parser(ModuleCache *s):
21 preprocessor(tokenizer),
24 tokenizer.signal_preprocess.connect(sigc::mem_fun(&preprocessor, &Preprocessor::preprocess));
25 preprocessor.signal_version.connect(sigc::mem_fun(this, &Parser::set_required_version));
26 preprocessor.signal_source.connect(sigc::mem_fun(this, &Parser::source_reference));
27 preprocessor.signal_stage_change.connect(sigc::mem_fun(this, &Parser::stage_change));
28 preprocessor.signal_line.connect(sigc::mem_fun(this, &Parser::line_change));
31 void Parser::parse(Module &m, const string &s, const string &n, int i)
33 SetForScope<Module *> set_module(module, &m);
38 void Parser::parse(Module &m, IO::Base &io, const string &n, int i)
40 SetForScope<Module *> set_module(module, &m);
45 unsigned len = io.read(buffer, sizeof(buffer));
46 source.append(buffer, len);
51 void Parser::parse_source(const string &name, int index)
53 cur_stage = &module->shared;
57 source_reference(1, name);
59 if(const Stage *builtin = get_builtins(Stage::SHARED))
61 for(const auto &kvp: builtin->types)
62 global_types.insert(kvp.first);
65 tokenizer.begin(source, name);
66 allow_stage_change = true;
67 while(!tokenizer.peek_token().empty())
68 if(RefPtr<Statement> statement = parse_with_recovery(&Parser::parse_global_declaration))
70 cur_stage->content.body.push_back(statement);
71 if(next_global_declaration)
73 cur_stage->content.body.push_back(next_global_declaration);
74 next_global_declaration = 0;
79 throw invalid_shader_source(join(errors.begin(), errors.end(), "\n"));
82 void Parser::set_required_version(const Version &ver)
84 cur_stage->required_features.glsl_version = ver;
87 void Parser::source_reference(unsigned index, const string &name)
89 if(index<1 || base_index<0)
90 throw invalid_shader_source(tokenizer.get_location(), "Invalid source reference");
92 module->source_map.set_name(base_index+index-1, name);
95 void Parser::stage_change(Stage::Type stage)
97 if(!allow_stage_change)
98 throw invalid_shader_source(tokenizer.get_location(), "Changing stage not allowed here");
99 else if(stage<=cur_stage->type)
100 throw invalid_shader_source(tokenizer.get_location(), "Stage '%s' not allowed here", Stage::get_stage_name(stage));
102 module->stages.push_back(stage);
104 if(cur_stage->type!=Stage::SHARED)
105 module->stages.back().previous = cur_stage;
106 cur_stage = &module->stages.back();
109 if(const Stage *builtin = get_builtins(stage))
111 for(const auto &kvp: builtin->types)
112 stage_types.insert(kvp.first);
114 for(const Module *m: imported_modules)
116 auto j = find_member(m->stages, stage, &Stage::type);
117 if(j!=m->stages.end())
119 for(const auto &kvp: j->types)
120 stage_types.insert(kvp.first);
125 void Parser::line_change(int index, unsigned line)
128 source_index = base_index+index-1;
132 index = source_index;
134 string name = module->source_map.get_name(index);
136 name = format("<%d>", index);
137 tokenizer.set_location(Location(name, line));
140 string Parser::expect_type()
142 string token = tokenizer.parse_token();
144 throw parse_error(tokenizer.get_location(), token, "a type");
148 string Parser::expect_identifier()
150 string token = tokenizer.parse_token();
151 if(!is_identifier(token))
152 throw parse_error(tokenizer.get_location(), token, "an identifier");
156 int Parser::expect_integer()
158 string token = tokenizer.parse_token();
160 throw parse_error(tokenizer.get_location(), token, "an integer literal");
161 return lexical_cast<int>(token);
164 bool Parser::check(const string &token)
166 bool result = (tokenizer.peek_token()==token);
168 tokenizer.parse_token();
172 bool Parser::is_interface_qualifier(const string &token)
174 return (token=="uniform" || token=="in" || token=="out");
177 bool Parser::is_sampling_qualifier(const string &token)
179 return (token=="centroid" || token=="sample");
182 bool Parser::is_interpolation_qualifier(const string &token)
184 return (token=="smooth" || token=="flat" || token=="noperspective");
187 bool Parser::is_precision_qualifier(const string &token)
189 return (token=="highp" || token=="mediump" || token=="lowp");
192 bool Parser::is_qualifier(const string &token)
194 return (token=="const" ||
195 is_interface_qualifier(token) ||
196 is_sampling_qualifier(token) ||
197 is_interpolation_qualifier(token) ||
198 is_precision_qualifier(token));
201 bool Parser::is_type(const string &token)
203 return global_types.count(token) || stage_types.count(token);
206 bool Parser::is_identifier(const string &token)
208 static Regex re("^[a-zA-Z_][a-zA-Z0-9_]*$");
209 return static_cast<bool>(re.match(token));
213 RefPtr<T> Parser::create_node()
215 RefPtr<T> node = new T;
216 node->source = source_index;
217 node->line = tokenizer.get_location().line;
222 RefPtr<T> Parser::parse_with_recovery(RefPtr<T> (Parser::*parse_func)())
224 tokenizer.clear_progress_mark();
227 return (this->*parse_func)();
229 catch(const invalid_shader_source &exc)
231 errors.push_back(exc.what());
234 if(tokenizer.get_last_token()!=";" || !tokenizer.get_progress_mark())
236 unsigned scope_level = 0;
239 if(tokenizer.peek_token()=="}" && scope_level==0)
241 if(!tokenizer.get_progress_mark())
242 tokenizer.parse_token();
246 string token = tokenizer.parse_token();
255 else if(token==";" && scope_level==0)
257 else if(token.empty())
265 RefPtr<Statement> Parser::parse_global_declaration()
267 string token = tokenizer.peek_token();
268 SetFlag disallow(allow_stage_change, false);
271 return parse_import();
272 else if(token=="precision")
273 return parse_precision();
274 else if(token=="layout")
276 RefPtr<Layout> layout = parse_layout();
277 token = tokenizer.peek_token();
278 if(is_interface_qualifier(token) && tokenizer.peek_token(1)==";")
280 RefPtr<InterfaceLayout> iface_lo = create_node<InterfaceLayout>();
281 iface_lo->layout.source = layout->source;
282 iface_lo->layout.line = layout->line;
283 iface_lo->layout.qualifiers = layout->qualifiers;
284 iface_lo->interface = tokenizer.parse_token();
285 tokenizer.expect(";");
288 else if(is_interface_qualifier(token) && tokenizer.peek_token(2)=="{")
290 RefPtr<StructDeclaration> iface_strct = parse_interface_block();
291 VariableDeclaration *iface_var = iface_strct->block_declaration;
292 iface_var->layout = layout;
293 next_global_declaration = iface_var;
298 RefPtr<VariableDeclaration> var = parse_variable_declaration();
299 var->layout = layout;
303 else if(token=="typedef")
304 return parse_type_declaration();
305 else if(token=="struct")
306 return parse_struct_declaration();
307 else if(is_interface_qualifier(token))
309 string next = tokenizer.peek_token(1);
310 if(is_type(next) || is_qualifier(next))
311 return parse_variable_declaration();
314 RefPtr<StructDeclaration> iface_strct = parse_interface_block();
315 next_global_declaration = iface_strct->block_declaration;
319 else if(is_qualifier(token))
320 return parse_variable_declaration();
321 else if(token=="virtual")
322 return parse_function_declaration();
323 else if(is_type(token))
325 if(tokenizer.peek_token(2)=="(")
326 return parse_function_declaration();
328 return parse_variable_declaration();
330 else if(token.empty())
333 throw parse_error(tokenizer.get_location(), token, "a global declaration");
336 RefPtr<Statement> Parser::parse_statement()
338 string token = tokenizer.peek_token();
340 return parse_conditional();
341 else if(token=="for")
343 else if(token=="while")
344 return parse_while();
345 else if(token=="passthrough")
346 return parse_passthrough();
347 else if(token=="return")
348 return parse_return();
349 else if(token=="break" || token=="continue" || token=="discard")
351 RefPtr<Jump> jump = create_node<Jump>();
352 jump->keyword = tokenizer.parse_token();
353 tokenizer.expect(";");
357 else if(is_qualifier(token) || is_type(token))
358 return parse_variable_declaration();
361 tokenizer.parse_token();
362 throw invalid_shader_source(tokenizer.get_location(), "Empty statement not allowed");
364 else if(!token.empty())
366 RefPtr<ExpressionStatement> expr = create_node<ExpressionStatement>();
367 expr->expression = parse_expression();
368 tokenizer.expect(";");
373 throw parse_error(tokenizer.get_location(), token, "a statement");
376 RefPtr<Import> Parser::parse_import()
378 if(cur_stage->type!=Stage::SHARED)
379 throw invalid_shader_source(tokenizer.get_location(), "Imports are only allowed in the shared section");
381 tokenizer.expect("import");
382 RefPtr<Import> import = create_node<Import>();
383 import->module = expect_identifier();
384 tokenizer.expect(";");
388 const Module &imported_mod = mod_cache->get_module(import->module);
389 imported_modules.push_back(&imported_mod);
390 for(const auto &kvp: imported_mod.shared.types)
391 global_types.insert(kvp.first);
397 RefPtr<Precision> Parser::parse_precision()
399 tokenizer.expect("precision");
400 RefPtr<Precision> precision = create_node<Precision>();
402 precision->precision = tokenizer.parse_token();
403 if(!is_precision_qualifier(precision->precision))
404 throw parse_error(tokenizer.get_location(), precision->precision, "a precision qualifier");
406 // TODO Add validation for this
407 precision->type = expect_type();
409 tokenizer.expect(";");
414 RefPtr<Layout> Parser::parse_layout()
416 tokenizer.expect("layout");
417 tokenizer.expect("(");
418 RefPtr<Layout> layout = create_node<Layout>();
421 string token = tokenizer.parse_token();
423 throw parse_error(tokenizer.get_location(), token, "a layout qualifier name");
425 layout->qualifiers.push_back(token);
426 Layout::Qualifier &qual = layout->qualifiers.back();
428 if((qual.has_value = check("=")))
430 if(qual.name=="constant_id" && tokenizer.peek_token()=="auto")
433 tokenizer.parse_token();
436 qual.value = expect_integer();
439 if(tokenizer.peek_token()==")")
442 tokenizer.expect(",");
444 tokenizer.expect(")");
450 void Parser::parse_block(Block &block, bool require_braces, RefPtr<T> (Parser::*parse_content)())
452 bool have_braces = (require_braces || tokenizer.peek_token()=="{");
454 tokenizer.expect("{");
458 while(tokenizer.peek_token()!="}")
459 if(RefPtr<Statement> node = parse_with_recovery(parse_content))
460 block.body.push_back(node);
463 block.body.push_back((this->*parse_content)());
465 block.use_braces = (require_braces || block.body.size()!=1);
468 tokenizer.expect("}");
471 RefPtr<Expression> Parser::parse_expression(const Operator *outer_oper)
473 unsigned outer_precedence = (outer_oper ? outer_oper->precedence+(outer_oper->assoc==Operator::RIGHT_TO_LEFT) : 20);
474 RefPtr<Expression> left;
475 VariableReference *left_var = 0;
478 string token = tokenizer.peek_token();
480 const Operator *oper = 0;
481 for(const Operator *i=Operator::operators; (!oper && i->type); ++i)
482 if(token==i->token && (!left || i->type!=Operator::PREFIX) && (left || i->type!=Operator::POSTFIX))
485 bool lower_precedence = (oper && oper->type!=Operator::PREFIX && oper->precedence>=outer_precedence);
486 if(token==";" || token==")" || token=="]" || token=="," || token==":" || lower_precedence)
491 throw parse_error(tokenizer.get_location(), token, "an expression");
498 throw invalid_shader_source(tokenizer.get_location(), "Syntax error before '(': function name must be an identifier");
499 left = parse_function_call(*left_var);
503 RefPtr<MemberAccess> memacc = create_node<MemberAccess>();
506 tokenizer.parse_token();
507 memacc->member = expect_identifier();
510 else if(oper && oper->type==Operator::POSTFIX)
512 RefPtr<UnaryExpression> unary = create_node<UnaryExpression>();
514 tokenizer.parse_token();
515 unary->expression = left;
518 else if(oper && oper->type==Operator::BINARY)
519 left = parse_binary(left, *oper);
520 else if(oper && oper->type==Operator::TERNARY)
521 left = parse_ternary(left, *oper);
523 throw parse_error(tokenizer.get_location(), token, "an operator");
530 tokenizer.parse_token();
531 left = parse_expression();
532 tokenizer.expect(")");
534 else if(isdigit(token[0]) || token=="true" || token=="false")
535 left = parse_literal();
536 else if(is_identifier(token))
538 RefPtr<VariableReference> var = create_node<VariableReference>();
539 var->name = expect_identifier();
541 left_var = var.get();
543 else if(oper && oper->type==Operator::PREFIX)
545 RefPtr<UnaryExpression> unary = create_node<UnaryExpression>();
547 tokenizer.parse_token();
548 unary->expression = parse_expression(oper);
552 throw parse_error(tokenizer.get_location(), token, "an expression");
557 RefPtr<Literal> Parser::parse_literal()
559 RefPtr<Literal> literal = create_node<Literal>();
560 literal->token = tokenizer.parse_token();
561 if(isdigit(literal->token[0]))
563 // TODO have the tokenizer return the type of the token
564 if(literal->token.back()=='u')
565 literal->value = lexical_cast<unsigned>(literal->token.substr(0, literal->token.size()-1));
566 else if(literal->token.back()=='f')
567 literal->value = lexical_cast<float>(literal->token.substr(0, literal->token.size()-1));
568 else if(literal->token.find('.')!=string::npos)
569 literal->value = lexical_cast<float>(literal->token);
571 literal->value = lexical_cast<int>(literal->token);
573 else if(literal->token=="true" || literal->token=="false")
574 literal->value = (literal->token=="true");
576 throw parse_error(tokenizer.get_location(), literal->token, "a literal");
581 RefPtr<BinaryExpression> Parser::parse_binary(const RefPtr<Expression> &left, const Operator &oper)
583 RefPtr<BinaryExpression> binary = (oper.precedence==16 ?
584 static_cast<RefPtr<BinaryExpression> >(create_node<Assignment>()) : create_node<BinaryExpression>());
586 binary->oper = &oper;
587 tokenizer.expect(oper.token);
590 binary->right = parse_expression();
591 tokenizer.expect(oper.token2);
594 binary->right = parse_expression(&oper);
598 RefPtr<TernaryExpression> Parser::parse_ternary(const RefPtr<Expression> &cond, const Operator &oper)
600 RefPtr<TernaryExpression> ternary = create_node<TernaryExpression>();
601 ternary->condition = cond;
602 ternary->oper = &oper;
603 tokenizer.expect("?");
604 ternary->true_expr = parse_expression(&oper);
605 tokenizer.expect(":");
606 ternary->false_expr = parse_expression(&oper);
610 RefPtr<FunctionCall> Parser::parse_function_call(const VariableReference &var)
612 RefPtr<FunctionCall> call = create_node<FunctionCall>();
613 call->name = var.name;
614 call->oper = &Operator::get_operator("(", Operator::POSTFIX);
615 tokenizer.expect("(");
616 while(tokenizer.peek_token()!=")")
618 if(!call->arguments.empty())
619 tokenizer.expect(",");
620 call->arguments.push_back(parse_expression());
622 tokenizer.expect(")");
626 void Parser::add_type(TypeDeclaration &type)
628 cur_stage->types[type.name] = &type;
629 if(cur_stage->type==Stage::SHARED)
630 global_types.insert(type.name);
632 stage_types.insert(type.name);
635 RefPtr<TypeDeclaration> Parser::parse_type_declaration()
637 tokenizer.expect("typedef");
639 RefPtr<TypeDeclaration> type;
640 if(tokenizer.peek_token()=="image")
641 type = parse_image_type_declaration();
643 type = parse_basic_type_declaration();
645 tokenizer.expect(";");
650 RefPtr<BasicTypeDeclaration> Parser::parse_basic_type_declaration()
652 RefPtr<BasicTypeDeclaration> type = create_node<BasicTypeDeclaration>();
654 if(tokenizer.peek_token()=="vector")
656 type->kind = BasicTypeDeclaration::VECTOR;
658 tokenizer.parse_token();
659 tokenizer.expect("(");
660 type->size = expect_integer();
661 tokenizer.expect(")");
664 type->base = expect_type();
665 type->name = expect_identifier();
667 if(type->kind==BasicTypeDeclaration::ALIAS && check("["))
669 type->kind = BasicTypeDeclaration::ARRAY;
670 tokenizer.expect("]");
676 RefPtr<ImageTypeDeclaration> Parser::parse_image_type_declaration()
678 tokenizer.expect("image");
679 tokenizer.expect("(");
681 RefPtr<ImageTypeDeclaration> type = create_node<ImageTypeDeclaration>();
684 string token = tokenizer.parse_token();
685 if(token=="dimensions")
687 tokenizer.expect("=");
688 token = tokenizer.parse_token();
690 type->dimensions = ImageTypeDeclaration::ONE;
692 type->dimensions = ImageTypeDeclaration::TWO;
694 type->dimensions = ImageTypeDeclaration::THREE;
695 else if(token=="cube")
696 type->dimensions = ImageTypeDeclaration::CUBE;
698 throw parse_error(tokenizer.get_location(), token, "dimensions");
703 tokenizer.expect("]");
706 else if(token=="sampled")
707 type->sampled = true;
708 else if(token=="shadow")
711 throw parse_error(tokenizer.get_location(), token, "image type attribute");
713 token = tokenizer.peek_token();
717 tokenizer.expect(",");
719 tokenizer.expect(")");
721 type->base = expect_type();
722 type->name = expect_identifier();
727 RefPtr<StructDeclaration> Parser::parse_struct_declaration()
729 tokenizer.expect("struct");
730 RefPtr<StructDeclaration> strct = create_node<StructDeclaration>();
732 strct->name = expect_identifier();
733 parse_block(strct->members, true, &Parser::parse_variable_declaration);
734 tokenizer.expect(";");
740 RefPtr<VariableDeclaration> Parser::parse_variable_declaration()
742 RefPtr<VariableDeclaration> var = create_node<VariableDeclaration>();
744 string token = tokenizer.peek_token();
745 while(is_qualifier(token))
747 tokenizer.parse_token();
748 if(is_interface_qualifier(token))
749 var->interface = token;
750 else if(is_sampling_qualifier(token))
751 var->sampling = token;
752 else if(is_interpolation_qualifier(token))
753 var->interpolation = token;
754 else if(is_precision_qualifier(token))
755 var->precision = token;
756 else if(token=="const")
757 var->constant = true;
758 token = tokenizer.peek_token();
761 var->type = expect_type();
762 var->name = expect_identifier();
769 var->array_size = parse_expression();
770 tokenizer.expect("]");
775 var->init_expression = parse_expression();
777 tokenizer.expect(";");
781 RefPtr<VariableDeclaration> Parser::parse_variable_declaration_with_layout()
783 RefPtr<Layout> layout;
784 if(tokenizer.peek_token()=="layout")
785 layout = parse_layout();
787 RefPtr<VariableDeclaration> var = parse_variable_declaration();
788 var->layout = layout;
793 RefPtr<FunctionDeclaration> Parser::parse_function_declaration()
795 RefPtr<FunctionDeclaration> func = create_node<FunctionDeclaration>();
797 func->virtua = check("virtual");
798 func->return_type = expect_type();
799 func->name = expect_identifier();
800 tokenizer.expect("(");
801 while(tokenizer.peek_token()!=")")
803 if(!func->parameters.empty())
804 tokenizer.expect(",");
806 RefPtr<VariableDeclaration> var = create_node<VariableDeclaration>();
807 string token = tokenizer.peek_token();
808 if(token=="in" || token=="out" || token=="inout")
809 var->interface = tokenizer.parse_token();
810 var->type = expect_type();
811 var->name = expect_identifier();
812 func->parameters.push_back(var);
814 tokenizer.expect(")");
816 func->overrd = check("override");
818 string token = tokenizer.peek_token();
821 func->definition = func.get();
822 parse_block(func->body, true, &Parser::parse_statement);
825 tokenizer.parse_token();
827 throw parse_error(tokenizer.get_location(), token, "'{' or ';'");
832 RefPtr<StructDeclaration> Parser::parse_interface_block()
834 RefPtr<StructDeclaration> strct = create_node<StructDeclaration>();
835 RefPtr<VariableDeclaration> var = create_node<VariableDeclaration>();
837 var->interface = tokenizer.parse_token();
838 if(!is_interface_qualifier(var->interface))
839 throw parse_error(tokenizer.get_location(), var->interface, "an interface qualifier");
841 strct->block_name = expect_identifier();
842 string name_base = format("_%s_%s", var->interface, strct->block_name);
843 strct->name = name_base;
844 for(unsigned i=1; (stage_types.count(strct->name) || global_types.count(strct->name)); ++i)
845 strct->name = format("%s_%d", name_base, i);
846 var->type = strct->name;
847 parse_block(strct->members, true, &Parser::parse_variable_declaration_with_layout);
850 var->name = expect_identifier();
854 tokenizer.expect("]");
856 tokenizer.expect(";");
859 var->name = format("%s %s", var->interface, strct->block_name);
861 strct->block_declaration = var.release();
867 RefPtr<Conditional> Parser::parse_conditional()
869 tokenizer.expect("if");
870 RefPtr<Conditional> cond = create_node<Conditional>();
871 tokenizer.expect("(");
872 cond->condition = parse_expression();
873 tokenizer.expect(")");
875 parse_block(cond->body, false, &Parser::parse_statement);
877 string token = tokenizer.peek_token();
880 tokenizer.parse_token();
881 parse_block(cond->else_body, false, &Parser::parse_statement);
887 RefPtr<Iteration> Parser::parse_for()
889 tokenizer.expect("for");
890 RefPtr<Iteration> loop = create_node<Iteration>();
891 tokenizer.expect("(");
892 string token = tokenizer.peek_token();
894 loop->init_statement = parse_statement();
899 RefPtr<ExpressionStatement> expr = create_node<ExpressionStatement>();
900 expr->expression = parse_expression();
901 loop->init_statement = expr;
903 tokenizer.expect(";");
905 if(tokenizer.peek_token()!=";")
906 loop->condition = parse_expression();
907 tokenizer.expect(";");
908 if(tokenizer.peek_token()!=")")
909 loop->loop_expression = parse_expression();
910 tokenizer.expect(")");
912 parse_block(loop->body, false, &Parser::parse_statement);
917 RefPtr<Iteration> Parser::parse_while()
919 tokenizer.expect("while");
920 RefPtr<Iteration> loop = create_node<Iteration>();
921 tokenizer.expect("(");
922 loop->condition = parse_expression();
923 tokenizer.expect(")");
925 parse_block(loop->body, false, &Parser::parse_statement);
930 RefPtr<Passthrough> Parser::parse_passthrough()
932 tokenizer.expect("passthrough");
933 RefPtr<Passthrough> pass = create_node<Passthrough>();
934 if(cur_stage->type==Stage::GEOMETRY)
936 tokenizer.expect("[");
937 pass->subscript = parse_expression();
938 tokenizer.expect("]");
940 tokenizer.expect(";");
944 RefPtr<Return> Parser::parse_return()
946 tokenizer.expect("return");
947 RefPtr<Return> ret = create_node<Return>();
948 if(tokenizer.peek_token()!=";")
949 ret->expression = parse_expression();
950 tokenizer.expect(";");