1 #include <msp/core/raii.h>
2 #include <msp/strings/format.h>
3 #include <msp/strings/regex.h>
4 #include "programparser.h"
13 using namespace ProgramSyntax;
15 ProgramParser::Operator ProgramParser::operators[] =
17 { "[", 2, BINARY, LEFT_TO_RIGHT },
18 { "(", 2, BINARY, LEFT_TO_RIGHT },
19 { ".", 2, BINARY, LEFT_TO_RIGHT },
20 { "++", 2, POSTFIX, LEFT_TO_RIGHT },
21 { "--", 2, POSTFIX, LEFT_TO_RIGHT },
22 { "++", 3, PREFIX, RIGHT_TO_LEFT },
23 { "--", 3, PREFIX, RIGHT_TO_LEFT },
24 { "+", 3, PREFIX, RIGHT_TO_LEFT },
25 { "-", 3, PREFIX, RIGHT_TO_LEFT },
26 { "~", 3, PREFIX, RIGHT_TO_LEFT },
27 { "!", 3, PREFIX, RIGHT_TO_LEFT },
28 { "*", 4, BINARY, LEFT_TO_RIGHT },
29 { "/", 4, BINARY, LEFT_TO_RIGHT },
30 { "%", 4, BINARY, LEFT_TO_RIGHT },
31 { "+", 5, BINARY, LEFT_TO_RIGHT },
32 { "-", 5, BINARY, LEFT_TO_RIGHT },
33 { "<<", 6, BINARY, LEFT_TO_RIGHT },
34 { ">>", 6, BINARY, LEFT_TO_RIGHT },
35 { "<", 7, BINARY, LEFT_TO_RIGHT },
36 { ">", 7, BINARY, LEFT_TO_RIGHT },
37 { "<=", 7, BINARY, LEFT_TO_RIGHT },
38 { ">=", 7, BINARY, LEFT_TO_RIGHT },
39 { "==", 8, BINARY, LEFT_TO_RIGHT },
40 { "!=", 8, BINARY, LEFT_TO_RIGHT },
41 { "&", 9, BINARY, LEFT_TO_RIGHT },
42 { "^", 10, BINARY, LEFT_TO_RIGHT },
43 { "|", 11, BINARY, LEFT_TO_RIGHT },
44 { "&&", 12, BINARY, LEFT_TO_RIGHT },
45 { "^^", 13, BINARY, LEFT_TO_RIGHT },
46 { "||", 14, BINARY, LEFT_TO_RIGHT },
47 { "?", 15, BINARY, RIGHT_TO_LEFT },
48 { ":", 15, BINARY, RIGHT_TO_LEFT },
49 { "=", 16, BINARY, RIGHT_TO_LEFT },
50 { "+=", 16, BINARY, RIGHT_TO_LEFT },
51 { "-=", 16, BINARY, RIGHT_TO_LEFT },
52 { "*=", 16, BINARY, RIGHT_TO_LEFT },
53 { "/=", 16, BINARY, RIGHT_TO_LEFT },
54 { "%=", 16, BINARY, RIGHT_TO_LEFT },
55 { "<<=", 16, BINARY, RIGHT_TO_LEFT },
56 { ">>=", 16, BINARY, RIGHT_TO_LEFT },
57 { "&=", 16, BINARY, RIGHT_TO_LEFT },
58 { "^=", 16, BINARY, RIGHT_TO_LEFT },
59 { "|=", 16, BINARY, RIGHT_TO_LEFT },
60 { ",", 17, BINARY, LEFT_TO_RIGHT },
61 { { 0 }, 18, NO_OPERATOR, LEFT_TO_RIGHT }
64 ProgramParser::ProgramParser():
68 ProgramParser::~ProgramParser()
73 Module &ProgramParser::parse(const string &s, const string &n, unsigned i)
82 Module &ProgramParser::parse(IO::Base &io, const string &n, unsigned i)
90 unsigned len = io.read(buffer, sizeof(buffer));
91 source.append(buffer, len);
97 void ProgramParser::parse_source()
101 string::size_type slashes = source.find("//////");
102 if(slashes==string::npos)
105 string::size_type newline = source.find('\n', slashes);
106 string pragma = format("#pragma MSP stage(%s)", source.substr(slashes+6, newline-slashes-6));
107 source.replace(slashes, newline-slashes, pragma);
112 cur_stage = &module->shared;
113 iter = source.begin();
114 source_end = source.end();
116 allow_preprocess = true;
117 while(RefPtr<Statement> statement = parse_global_declaration())
118 cur_stage->content.body.push_back(statement);
121 string ProgramParser::format_error(const std::string &message)
123 string location = format("%s:%d: ", source_name, current_line);
124 return location+message;
127 string ProgramParser::format_syntax_error(const std::string &expected)
129 return format_error(format("Syntax error at '%s': expected %s", last_token, expected));
132 const string &ProgramParser::peek_token(unsigned index)
134 while(next_tokens.size()<=index)
135 next_tokens.push_back(parse_token_());
136 return (last_token = next_tokens[index]);
139 const string &ProgramParser::parse_token()
141 if(!next_tokens.empty())
143 last_token = next_tokens.front();
144 next_tokens.pop_front();
148 return (last_token = parse_token_());
151 string ProgramParser::parse_token_()
155 skip_comment_and_whitespace();
158 else if(allow_preprocess && *iter=='#')
160 allow_preprocess = false;
161 SetForScope<deque<string> > clear_tokens(next_tokens, deque<string>());
164 else if(isalpha(*iter) || *iter=='_')
165 return parse_identifier();
166 else if(isdigit(*iter))
167 return parse_number();
169 return parse_other();
173 string ProgramParser::parse_identifier()
176 while(iter!=source_end)
178 if(isalnum(*iter) || *iter=='_')
187 string ProgramParser::parse_number()
189 bool accept_sign = false;
191 while(iter!=source_end)
193 if(isdigit(*iter) || *iter=='.')
195 else if(*iter=='e' || *iter=='E')
200 else if(accept_sign && (*iter=='+' || *iter=='-'))
209 string ProgramParser::parse_other()
214 string token(1, *iter++);
215 for(unsigned i=1; (i<3 && iter!=source_end); ++i)
217 bool matched = false;
218 for(const Operator *j=operators; (!matched && j->type); ++j)
220 matched = (j->token[i]==*iter);
221 for(unsigned k=0; (matched && k<i && j->token[k]); ++k)
222 matched = (j->token[k]==token[k]);
234 void ProgramParser::skip_comment_and_whitespace()
236 unsigned comment = 0;
237 while(iter!=source_end)
243 else if(!isspace(*iter))
264 else if(comment==3 && *iter=='*')
277 allow_preprocess = (comment<3);
284 void ProgramParser::expect(const string &token)
286 string parsed = parse_token();
288 throw runtime_error(format_syntax_error(format("'%s'", token)));
291 string ProgramParser::expect_type()
293 string token = parse_token();
295 throw runtime_error(format_syntax_error("a type"));
299 string ProgramParser::expect_identifier()
301 string token = parse_token();
302 if(!is_identifier(token))
303 throw runtime_error(format_syntax_error("an identifier"));
307 bool ProgramParser::check(const string &token)
309 bool result = (peek_token()==token);
315 bool ProgramParser::is_interface_qualifier(const string &token)
317 return (token=="uniform" || token=="in" || token=="out");
320 bool ProgramParser::is_sampling_qualifier(const string &token)
322 return (token=="centroid" || token=="sample");
325 bool ProgramParser::is_interpolation_qualifier(const string &token)
327 return (token=="smooth" || token=="flat" || token=="noperspective");
330 bool ProgramParser::is_precision_qualifier(const string &token)
332 return (token=="highp" || token=="mediump" || token=="lowp");
335 bool ProgramParser::is_qualifier(const string &token)
337 return (token=="const" ||
338 is_interface_qualifier(token) ||
339 is_sampling_qualifier(token) ||
340 is_interpolation_qualifier(token) ||
341 is_precision_qualifier(token));
344 bool ProgramParser::is_builtin_type(const string &token)
346 static Regex re("^(void|float|int|bool|[ib]?vec[234]|mat[234](x[234])?|sampler((1D|2D)(Array)?(Shadow)?|Cube(Shadow)?|3D))$");
347 return re.match(token);
350 bool ProgramParser::is_type(const string &token)
352 return is_builtin_type(token) || declared_types.count(token);
355 bool ProgramParser::is_identifier(const string &token)
357 static Regex re("^[a-zA-Z_][a-zA-Z0-9_]*$");
358 return re.match(token);
361 void ProgramParser::preprocess()
365 string::const_iterator line_end = iter;
366 for(; (line_end!=source_end && *line_end!='\n'); ++line_end) ;
367 SetForScope<string::const_iterator> stop_at_line_end(source_end, line_end);
369 string token = peek_token();
372 else if(token=="define" || token=="undef" || token=="if" || token=="ifdef" || token=="ifndef" || token=="else" ||
373 token=="elif" || token=="endif" || token=="error" || token=="extension" || token=="version" || token=="line")
374 throw runtime_error(format_error(format("Unsupported preprocessor directive '%s'", token)));
375 else if(!token.empty())
376 throw runtime_error(format_syntax_error("a preprocessor directive"));
381 void ProgramParser::preprocess_pragma()
384 string token = parse_token();
386 preprocess_pragma_msp();
389 void ProgramParser::preprocess_pragma_msp()
391 string token = peek_token();
395 throw runtime_error(format_error(format("Unrecognized MSP pragma '%s'", token)));
397 token = parse_token();
399 throw runtime_error(format_syntax_error("end of line"));
402 void ProgramParser::preprocess_stage()
404 if(!allow_stage_change)
405 throw runtime_error(format_error("Changing stage not allowed here"));
409 string token = expect_identifier();
410 StageType stage = SHARED;
413 else if(token=="geometry")
415 else if(token=="fragment")
418 throw runtime_error(format_syntax_error("stage identifier"));
421 if(stage<=cur_stage->type)
422 throw runtime_error(format_error(format("Stage '%s' not allowed here", token)));
424 module->stages.push_back(stage);
426 if(cur_stage->type!=SHARED)
427 module->stages.back().previous = cur_stage;
428 cur_stage = &module->stages.back();
431 RefPtr<Statement> ProgramParser::parse_global_declaration()
433 allow_stage_change = true;
434 string token = peek_token();
435 allow_stage_change = false;
438 return parse_import();
439 else if(token=="precision")
440 return parse_precision();
441 else if(token=="layout")
443 RefPtr<Layout> layout = parse_layout();
444 token = peek_token();
445 if(is_interface_qualifier(token) && peek_token(1)==";")
447 RefPtr<InterfaceLayout> iface_lo = new InterfaceLayout;
448 iface_lo->source = source_index;
449 iface_lo->line = current_line;
450 iface_lo->layout.qualifiers = layout->qualifiers;
451 iface_lo->interface = parse_token();
457 RefPtr<VariableDeclaration> var = parse_variable_declaration();
458 var->layout = layout;
462 else if(token=="struct")
463 return parse_struct_declaration();
464 else if(is_interface_qualifier(token))
466 string next = peek_token(1);
467 if(is_type(next) || is_qualifier(next))
468 return parse_variable_declaration();
470 return parse_interface_block();
472 else if(is_qualifier(token))
473 return parse_variable_declaration();
474 else if(is_type(token))
476 if(peek_token(2)=="(")
477 return parse_function_declaration();
479 return parse_variable_declaration();
481 else if(token.empty())
484 throw runtime_error(format_syntax_error("a global declaration"));
487 RefPtr<Statement> ProgramParser::parse_statement()
489 string token = peek_token();
491 return parse_conditional();
492 else if(token=="for")
494 else if(token=="while")
495 return parse_while();
496 else if(token=="passthrough")
497 return parse_passthrough();
498 else if(token=="return")
499 return parse_return();
500 else if(token=="break" || token=="continue" || token=="discard")
502 RefPtr<Jump> jump = new Jump;
503 jump->source = source_index;
504 jump->line = current_line;
505 jump->keyword = parse_token();
510 else if(is_qualifier(token) || is_type(token))
511 return parse_variable_declaration();
512 else if(!token.empty())
514 RefPtr<ExpressionStatement> expr = new ExpressionStatement;
515 expr->source = source_index;
516 expr->line = current_line;
517 expr->expression = parse_expression();
523 throw runtime_error(format_syntax_error("a statement"));
526 RefPtr<Import> ProgramParser::parse_import()
528 if(cur_stage->type!=SHARED)
529 throw runtime_error(format_error("Imports are only allowed in the shared section"));
532 RefPtr<Import> import = new Import;
533 import->source = source_index;
534 import->line = current_line;
535 import->module = expect_identifier();
540 RefPtr<Precision> ProgramParser::parse_precision()
543 RefPtr<Precision> precision = new Precision;
544 precision->source = source_index;
545 precision->line = current_line;
547 precision->precision = parse_token();
548 if(!is_precision_qualifier(precision->precision))
549 throw runtime_error(format_syntax_error("a precision qualifier"));
551 precision->type = parse_token();
552 // Not entirely accurate; only float, int and sampler types are allowed
553 if(!is_builtin_type(precision->type))
554 throw runtime_error(format_syntax_error("a builtin type"));
561 RefPtr<Layout> ProgramParser::parse_layout()
565 RefPtr<Layout> layout = new Layout;
568 string token = parse_token();
570 throw runtime_error(format_syntax_error("a layout qualifier name"));
572 layout->qualifiers.push_back(Layout::Qualifier());
573 Layout::Qualifier &qual = layout->qualifiers.back();
574 qual.identifier = token;
577 qual.value = parse_token();
579 if(peek_token()==")")
589 void ProgramParser::parse_block(Block &block, bool require_braces)
591 bool have_braces = (require_braces || peek_token()=="{");
597 while(peek_token()!="}")
598 block.body.push_back(parse_statement());
601 block.body.push_back(parse_statement());
603 block.use_braces = (require_braces || block.body.size()!=1);
609 RefPtr<Expression> ProgramParser::parse_expression(unsigned precedence)
611 RefPtr<Expression> left;
612 VariableReference *left_var = 0;
615 string token = peek_token();
617 const Operator *oper = 0;
618 for(Operator *i=operators; (!oper && i->type); ++i)
619 if(token==i->token && (!left || i->type!=PREFIX) && (left || i->type!=POSTFIX))
622 if(token==";" || token==")" || token=="]" || token=="," || (oper && precedence && oper->precedence>=precedence))
627 throw runtime_error(format_syntax_error("an expression"));
634 throw runtime_error(format_error("Syntax error before '(': function name must be an identifier"));
635 left = parse_function_call(*left_var);
639 RefPtr<MemberAccess> memacc = new MemberAccess;
642 memacc->member = expect_identifier();
645 else if(oper && oper->type==POSTFIX)
647 RefPtr<UnaryExpression> unary = new UnaryExpression;
648 unary->oper = parse_token();
649 unary->prefix = false;
650 unary->expression = left;
653 else if(oper && oper->type==BINARY)
654 left = parse_binary(left, oper);
656 throw runtime_error(format_syntax_error("an operator"));
664 RefPtr<ParenthesizedExpression> parexpr = new ParenthesizedExpression;
665 parexpr->expression = parse_expression();
669 else if(isdigit(token[0]) || token=="true" || token=="false")
671 RefPtr<Literal> literal = new Literal;
672 literal->token = parse_token();
675 else if(is_identifier(token))
677 RefPtr<VariableReference> var = new VariableReference;
678 var->name = expect_identifier();
680 left_var = var.get();
682 else if(oper && oper->type==PREFIX)
684 RefPtr<UnaryExpression> unary = new UnaryExpression;
685 unary->oper = parse_token();
686 unary->prefix = true;
687 unary->expression = parse_expression(oper->precedence);
691 throw runtime_error(format_syntax_error("an expression"));
696 RefPtr<BinaryExpression> ProgramParser::parse_binary(const RefPtr<Expression> &left, const Operator *oper)
698 RefPtr<BinaryExpression> binary = (oper->precedence==16 ? new Assignment : new BinaryExpression);
700 binary->oper = parse_token();
701 if(binary->oper=="[")
703 binary->right = parse_expression();
708 binary->right = parse_expression(oper->precedence+(oper->assoc==RIGHT_TO_LEFT));
712 RefPtr<FunctionCall> ProgramParser::parse_function_call(const VariableReference &var)
714 RefPtr<FunctionCall> call = new FunctionCall;
715 call->name = var.name;
716 call->constructor = is_type(call->name);
718 while(peek_token()!=")")
720 if(!call->arguments.empty())
722 call->arguments.push_back(parse_expression());
728 RefPtr<StructDeclaration> ProgramParser::parse_struct_declaration()
731 RefPtr<StructDeclaration> strct = new StructDeclaration;
732 strct->source = source_index;
733 strct->line = current_line;
735 strct->name = expect_identifier();
736 parse_block(strct->members, true);
739 declared_types.insert(strct->name);
743 RefPtr<VariableDeclaration> ProgramParser::parse_variable_declaration()
745 RefPtr<VariableDeclaration> var = new VariableDeclaration;
746 var->source = source_index;
747 var->line = current_line;
749 string token = peek_token();
750 while(is_qualifier(token))
753 if(is_interface_qualifier(token))
754 var->interface = token;
755 else if(is_sampling_qualifier(token))
756 var->sampling = token;
757 else if(is_interpolation_qualifier(token))
758 var->interpolation = token;
759 else if(is_precision_qualifier(token))
760 var->precision = token;
761 else if(token=="const")
762 var->constant = true;
763 token = peek_token();
766 var->type = expect_type();
767 var->name = expect_identifier();
774 var->array_size = parse_expression();
780 var->init_expression = parse_expression();
786 RefPtr<FunctionDeclaration> ProgramParser::parse_function_declaration()
788 RefPtr<FunctionDeclaration> func = new FunctionDeclaration;
789 func->source = source_index;
790 func->line = current_line;
792 func->return_type = expect_type();
793 func->name = expect_identifier();
795 while(peek_token()!=")")
797 if(!func->parameters.empty())
800 RefPtr<VariableDeclaration> var = new VariableDeclaration;
801 string token = peek_token();
802 if(token=="in" || token=="out" || token=="inout")
803 var->interface = parse_token();
804 var->type = expect_type();
805 var->name = expect_identifier();
806 func->parameters.push_back(var);
810 string token = peek_token();
813 func->definition = func.get();
814 parse_block(func->body, true);
819 throw runtime_error(format_syntax_error("'{' or ';'"));
824 RefPtr<InterfaceBlock> ProgramParser::parse_interface_block()
826 RefPtr<InterfaceBlock> iface = new InterfaceBlock;
827 iface->source = source_index;
828 iface->line = current_line;
830 iface->interface = parse_token();
831 if(!is_interface_qualifier(iface->interface))
832 throw runtime_error(format_syntax_error("an interface qualifier"));
834 iface->name = expect_identifier();
835 parse_block(iface->members, true);
838 iface->instance_name = expect_identifier();
850 RefPtr<Conditional> ProgramParser::parse_conditional()
853 RefPtr<Conditional> cond = new Conditional;
854 cond->source = source_index;
855 cond->line = current_line;
857 cond->condition = parse_expression();
860 parse_block(cond->body, false);
862 string token = peek_token();
866 parse_block(cond->else_body, false);
872 RefPtr<Iteration> ProgramParser::parse_for()
875 RefPtr<Iteration> loop = new Iteration;
876 loop->source = source_index;
877 loop->line = current_line;
879 string token = peek_token();
881 loop->init_statement = parse_statement();
886 RefPtr<ExpressionStatement> expr = new ExpressionStatement;
887 expr->expression = parse_expression();
888 loop->init_statement = expr;
892 if(peek_token()!=";")
893 loop->condition = parse_expression();
895 if(peek_token()!=")")
896 loop->loop_expression = parse_expression();
899 parse_block(loop->body, false);
904 RefPtr<Iteration> ProgramParser::parse_while()
907 RefPtr<Iteration> loop = new Iteration;
908 loop->source = source_index;
909 loop->line = current_line;
911 loop->condition = parse_expression();
914 parse_block(loop->body, false);
919 RefPtr<Passthrough> ProgramParser::parse_passthrough()
921 expect("passthrough");
922 RefPtr<Passthrough> pass = new Passthrough;
923 pass->source = source_index;
924 pass->line = current_line;
925 if(cur_stage->type==GEOMETRY)
928 pass->subscript = parse_expression();
935 RefPtr<Return> ProgramParser::parse_return()
938 RefPtr<Return> ret = new Return;
939 ret->source = source_index;
940 ret->line = current_line;
941 if(peek_token()!=";")
942 ret->expression = parse_expression();