1 #include <msp/core/raii.h>
2 #include <msp/strings/format.h>
3 #include <msp/strings/regex.h>
4 #include "programparser.h"
11 using namespace ProgramSyntax;
13 ProgramParser::Operator ProgramParser::operators[] =
15 { "[", 2, BINARY, LEFT_TO_RIGHT },
16 { "(", 2, BINARY, LEFT_TO_RIGHT },
17 { ".", 2, BINARY, LEFT_TO_RIGHT },
18 { "++", 2, POSTFIX, LEFT_TO_RIGHT },
19 { "--", 2, POSTFIX, LEFT_TO_RIGHT },
20 { "++", 3, PREFIX, RIGHT_TO_LEFT },
21 { "--", 3, PREFIX, RIGHT_TO_LEFT },
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 { "*", 4, BINARY, LEFT_TO_RIGHT },
27 { "/", 4, BINARY, LEFT_TO_RIGHT },
28 { "%", 4, BINARY, LEFT_TO_RIGHT },
29 { "+", 5, BINARY, LEFT_TO_RIGHT },
30 { "-", 5, BINARY, LEFT_TO_RIGHT },
31 { "<<", 6, BINARY, LEFT_TO_RIGHT },
32 { ">>", 6, BINARY, LEFT_TO_RIGHT },
33 { "<", 7, BINARY, LEFT_TO_RIGHT },
34 { ">", 7, BINARY, LEFT_TO_RIGHT },
35 { "<=", 7, BINARY, LEFT_TO_RIGHT },
36 { ">=", 7, BINARY, LEFT_TO_RIGHT },
37 { "==", 8, BINARY, LEFT_TO_RIGHT },
38 { "!=", 8, BINARY, LEFT_TO_RIGHT },
39 { "&", 9, BINARY, LEFT_TO_RIGHT },
40 { "^", 10, BINARY, LEFT_TO_RIGHT },
41 { "|", 11, BINARY, LEFT_TO_RIGHT },
42 { "&&", 12, BINARY, LEFT_TO_RIGHT },
43 { "^^", 13, BINARY, LEFT_TO_RIGHT },
44 { "||", 14, BINARY, LEFT_TO_RIGHT },
45 { "?", 15, BINARY, RIGHT_TO_LEFT },
46 { ":", 15, BINARY, RIGHT_TO_LEFT },
47 { "=", 16, BINARY, RIGHT_TO_LEFT },
48 { "+=", 16, 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 { ",", 17, BINARY, LEFT_TO_RIGHT },
59 { { 0 }, 18, NO_OPERATOR, LEFT_TO_RIGHT }
62 ProgramParser::ProgramParser():
66 ProgramParser::~ProgramParser()
71 Module &ProgramParser::parse(const string &s, const string &n)
79 Module &ProgramParser::parse(IO::Base &io, const string &n)
86 unsigned len = io.read(buffer, sizeof(buffer));
87 source.append(buffer, len);
93 void ProgramParser::parse_source()
97 string::size_type slashes = source.find("//////");
98 if(slashes==string::npos)
101 string::size_type newline = source.find('\n', slashes);
102 string pragma = format("#pragma MSP stage(%s)", source.substr(slashes+6, newline-slashes-6));
103 source.replace(slashes, newline-slashes, pragma);
108 cur_stage = &module->shared;
109 iter = source.begin();
110 source_end = source.end();
112 allow_preprocess = true;
113 while(RefPtr<Node> statement = parse_global_declaration())
114 cur_stage->content.body.push_back(statement);
117 string ProgramParser::format_error(const std::string &message)
119 string location = format("%s:%d: ", source_name, current_line);
120 return location+message;
123 string ProgramParser::format_syntax_error(const std::string &expected)
125 return format_error(format("Syntax error at '%s': expected %s", last_token, expected));
128 const string &ProgramParser::peek_token(unsigned index)
130 while(next_tokens.size()<=index)
131 next_tokens.push_back(parse_token_());
132 return (last_token = next_tokens[index]);
135 const string &ProgramParser::parse_token()
137 if(!next_tokens.empty())
139 last_token = next_tokens.front();
140 next_tokens.pop_front();
144 return (last_token = parse_token_());
147 string ProgramParser::parse_token_()
151 skip_comment_and_whitespace();
154 else if(allow_preprocess && *iter=='#')
156 allow_preprocess = false;
157 SetForScope<deque<string> > clear_tokens(next_tokens, deque<string>());
160 else if(isalpha(*iter) || *iter=='_')
161 return parse_identifier();
162 else if(isdigit(*iter))
163 return parse_number();
165 return parse_other();
169 string ProgramParser::parse_identifier()
172 while(iter!=source_end)
174 if(isalnum(*iter) || *iter=='_')
183 string ProgramParser::parse_number()
185 bool accept_sign = false;
187 while(iter!=source_end)
189 if(isdigit(*iter) || *iter=='.')
191 else if(*iter=='e' || *iter=='E')
196 else if(accept_sign && (*iter=='+' || *iter=='-'))
205 string ProgramParser::parse_other()
210 string token(1, *iter++);
211 for(unsigned i=1; (i<3 && iter!=source_end); ++i)
213 bool matched = false;
214 for(const Operator *j=operators; (!matched && j->type); ++j)
216 matched = (j->token[i]==*iter);
217 for(unsigned k=0; (matched && k<i && j->token[k]); ++k)
218 matched = (j->token[k]==token[k]);
230 void ProgramParser::skip_comment_and_whitespace()
232 unsigned comment = 0;
233 while(iter!=source_end)
239 else if(!isspace(*iter))
260 else if(comment==3 && *iter=='*')
273 allow_preprocess = (comment<3);
280 void ProgramParser::expect(const string &token)
282 string parsed = parse_token();
284 throw runtime_error(format_syntax_error(format("'%s'", token)));
287 string ProgramParser::expect_type()
289 string token = parse_token();
291 throw runtime_error(format_syntax_error("a type"));
295 string ProgramParser::expect_identifier()
297 string token = parse_token();
298 if(!is_identifier(token))
299 throw runtime_error(format_syntax_error("an identifier"));
303 bool ProgramParser::check(const string &token)
305 bool result = (peek_token()==token);
311 bool ProgramParser::is_interface_qualifier(const string &token)
313 return (token=="uniform" || token=="in" || token=="out");
316 bool ProgramParser::is_sampling_qualifier(const string &token)
318 return (token=="centroid" || token=="sample");
321 bool ProgramParser::is_interpolation_qualifier(const string &token)
323 return (token=="smooth" || token=="flat" || token=="noperspective");
326 bool ProgramParser::is_precision_qualifier(const string &token)
328 return (token=="highp" || token=="mediump" || token=="lowp");
331 bool ProgramParser::is_qualifier(const string &token)
333 return (token=="const" ||
334 is_interface_qualifier(token) ||
335 is_sampling_qualifier(token) ||
336 is_interpolation_qualifier(token) ||
337 is_precision_qualifier(token));
340 bool ProgramParser::is_builtin_type(const string &token)
342 static Regex re("^(void|float|int|bool|[ib]?vec[234]|mat[234](x[234])?|sampler((1D|2D)(Array)?(Shadow)?|Cube(Shadow)?|3D))$");
343 return re.match(token);
346 bool ProgramParser::is_type(const string &token)
348 return is_builtin_type(token) || declared_types.count(token);
351 bool ProgramParser::is_identifier(const string &token)
353 static Regex re("^[a-zA-Z_][a-zA-Z0-9_]*$");
354 return re.match(token);
357 void ProgramParser::preprocess()
361 string::const_iterator line_end = iter;
362 for(; (line_end!=source_end && *line_end!='\n'); ++line_end) ;
363 SetForScope<string::const_iterator> stop_at_line_end(source_end, line_end);
365 string token = peek_token();
368 else if(token=="define" || token=="undef" || token=="if" || token=="ifdef" || token=="ifndef" || token=="else" ||
369 token=="elif" || token=="endif" || token=="error" || token=="extension" || token=="version" || token=="line")
370 throw runtime_error(format_error(format("Unsupported preprocessor directive '%s'", token)));
371 else if(!token.empty())
372 throw runtime_error(format_syntax_error("a preprocessor directive"));
377 void ProgramParser::preprocess_pragma()
380 string token = parse_token();
382 preprocess_pragma_msp();
385 void ProgramParser::preprocess_pragma_msp()
387 string token = peek_token();
391 throw runtime_error(format_error(format("Unrecognized MSP pragma '%s'", token)));
393 token = parse_token();
395 throw runtime_error(format_syntax_error("end of line"));
398 void ProgramParser::preprocess_stage()
400 if(!allow_stage_change)
401 throw runtime_error(format_error("Changing stage not allowed here"));
405 string token = expect_identifier();
406 StageType stage = SHARED;
409 else if(token=="geometry")
411 else if(token=="fragment")
414 throw runtime_error(format_syntax_error("stage identifier"));
417 if(stage<=cur_stage->type)
418 throw runtime_error(format_error(format("Stage '%s' not allowed here", token)));
420 module->stages.push_back(stage);
422 if(cur_stage->type!=SHARED)
423 module->stages.back().previous = cur_stage;
424 cur_stage = &module->stages.back();
427 RefPtr<Node> ProgramParser::parse_global_declaration()
429 allow_stage_change = true;
430 string token = peek_token();
431 allow_stage_change = false;
434 return parse_import();
435 else if(token=="precision")
436 return parse_precision();
437 else if(token=="layout")
439 RefPtr<Layout> layout = parse_layout();
440 token = peek_token();
441 if(is_interface_qualifier(token) && peek_token(1)==";")
443 RefPtr<InterfaceLayout> iface_lo = new InterfaceLayout;
444 iface_lo->layout.qualifiers = layout->qualifiers;
445 iface_lo->interface = parse_token();
451 RefPtr<VariableDeclaration> var = parse_variable_declaration();
452 var->layout = layout;
456 else if(token=="struct")
457 return parse_struct_declaration();
458 else if(is_interface_qualifier(token))
460 string next = peek_token(1);
461 if(is_type(next) || is_qualifier(next))
462 return parse_variable_declaration();
464 return parse_interface_block();
466 else if(is_qualifier(token))
467 return parse_variable_declaration();
468 else if(is_type(token))
470 if(peek_token(2)=="(")
471 return parse_function_declaration();
473 return parse_variable_declaration();
475 else if(token.empty())
478 throw runtime_error(format_syntax_error("a global declaration"));
481 RefPtr<Node> ProgramParser::parse_statement()
483 string token = peek_token();
485 return parse_conditional();
486 else if(token=="for")
488 else if(token=="while")
489 return parse_while();
490 else if(token=="passthrough")
491 return parse_passthrough();
492 else if(token=="return")
493 return parse_return();
494 else if(token=="break" || token=="continue" || token=="discard")
496 RefPtr<Jump> jump = new Jump;
497 jump->keyword = parse_token();
502 else if(is_qualifier(token) || is_type(token))
503 return parse_variable_declaration();
504 else if(!token.empty())
506 RefPtr<ExpressionStatement> expr = new ExpressionStatement;
507 expr->expression = parse_expression();
513 throw runtime_error(format_syntax_error("a statement"));
516 RefPtr<Import> ProgramParser::parse_import()
518 if(cur_stage->type!=SHARED)
519 throw runtime_error(format_error("Imports are only allowed in the shared section"));
522 RefPtr<Import> import = new Import;
523 import->module = parse_token();
528 RefPtr<Precision> ProgramParser::parse_precision()
531 RefPtr<Precision> precision = new Precision;
533 precision->precision = parse_token();
534 if(!is_precision_qualifier(precision->precision))
535 throw runtime_error(format_syntax_error("a precision qualifier"));
537 precision->type = parse_token();
538 // Not entirely accurate; only float, int and sampler types are allowed
539 if(!is_builtin_type(precision->type))
540 throw runtime_error(format_syntax_error("a builtin type"));
547 RefPtr<Layout> ProgramParser::parse_layout()
551 RefPtr<Layout> layout = new Layout;
554 string token = parse_token();
556 throw runtime_error(format_syntax_error("a layout qualifier name"));
558 layout->qualifiers.push_back(Layout::Qualifier());
559 Layout::Qualifier &qual = layout->qualifiers.back();
560 qual.identifier = token;
563 qual.value = parse_token();
565 if(peek_token()==")")
575 void ProgramParser::parse_block(Block &block, bool require_braces)
577 bool have_braces = (require_braces || peek_token()=="{");
583 while(peek_token()!="}")
584 block.body.push_back(parse_statement());
587 block.body.push_back(parse_statement());
589 block.use_braces = (require_braces || block.body.size()!=1);
595 RefPtr<Expression> ProgramParser::parse_expression(unsigned precedence)
597 RefPtr<Expression> left;
598 VariableReference *left_var = 0;
601 string token = peek_token();
603 const Operator *oper = 0;
604 for(Operator *i=operators; (!oper && i->type); ++i)
605 if(token==i->token && (!left || i->type!=PREFIX) && (left || i->type!=POSTFIX))
608 if(token==";" || token==")" || token=="]" || token=="," || (oper && precedence && oper->precedence>=precedence))
613 throw runtime_error(format_syntax_error("an expression"));
620 throw runtime_error(format_error("Syntax error before '(': function name must be an identifier"));
621 left = parse_function_call(*left_var);
625 RefPtr<MemberAccess> memacc = new MemberAccess;
628 memacc->member = expect_identifier();
631 else if(oper && oper->type==POSTFIX)
633 RefPtr<UnaryExpression> unary = new UnaryExpression;
634 unary->oper = parse_token();
635 unary->prefix = false;
636 unary->expression = left;
639 else if(oper && oper->type==BINARY)
640 left = parse_binary(left, oper);
642 throw runtime_error(format_syntax_error("an operator"));
650 RefPtr<ParenthesizedExpression> parexpr = new ParenthesizedExpression;
651 parexpr->expression = parse_expression();
655 else if(isdigit(token[0]) || token=="true" || token=="false")
657 RefPtr<Literal> literal = new Literal;
658 literal->token = parse_token();
661 else if(is_identifier(token))
663 RefPtr<VariableReference> var = new VariableReference;
664 var->name = expect_identifier();
666 left_var = var.get();
668 else if(oper && oper->type==PREFIX)
670 RefPtr<UnaryExpression> unary = new UnaryExpression;
671 unary->oper = parse_token();
672 unary->prefix = true;
673 unary->expression = parse_expression(oper->precedence);
677 throw runtime_error(format_syntax_error("an expression"));
682 RefPtr<BinaryExpression> ProgramParser::parse_binary(const RefPtr<Expression> &left, const Operator *oper)
684 RefPtr<BinaryExpression> binary = (oper->precedence==16 ? new Assignment : new BinaryExpression);
686 binary->oper = parse_token();
687 if(binary->oper=="[")
689 binary->right = parse_expression();
694 binary->right = parse_expression(oper->precedence+(oper->assoc==RIGHT_TO_LEFT));
698 RefPtr<FunctionCall> ProgramParser::parse_function_call(const VariableReference &var)
700 RefPtr<FunctionCall> call = new FunctionCall;
701 call->name = var.name;
702 call->constructor = is_type(call->name);
704 while(peek_token()!=")")
706 if(!call->arguments.empty())
708 call->arguments.push_back(parse_expression());
714 RefPtr<StructDeclaration> ProgramParser::parse_struct_declaration()
717 RefPtr<StructDeclaration> strct = new StructDeclaration;
719 strct->name = expect_identifier();
720 parse_block(strct->members, true);
723 declared_types.insert(strct->name);
727 RefPtr<VariableDeclaration> ProgramParser::parse_variable_declaration()
729 RefPtr<VariableDeclaration> var = new VariableDeclaration;
731 string token = peek_token();
732 while(is_qualifier(token))
735 if(is_interface_qualifier(token))
736 var->interface = token;
737 else if(is_sampling_qualifier(token))
738 var->sampling = token;
739 else if(is_interpolation_qualifier(token))
740 var->interpolation = token;
741 else if(is_precision_qualifier(token))
742 var->precision = token;
743 else if(token=="const")
744 var->constant = true;
745 token = peek_token();
748 var->type = expect_type();
749 var->name = expect_identifier();
756 var->array_size = parse_expression();
762 var->init_expression = parse_expression();
768 RefPtr<FunctionDeclaration> ProgramParser::parse_function_declaration()
770 RefPtr<FunctionDeclaration> func = new FunctionDeclaration;
772 func->return_type = expect_type();
773 func->name = expect_identifier();
775 while(peek_token()!=")")
777 if(!func->parameters.empty())
780 RefPtr<VariableDeclaration> var = new VariableDeclaration;
781 string token = peek_token();
782 if(token=="in" || token=="out" || token=="inout")
783 var->interface = parse_token();
784 var->type = expect_type();
785 var->name = expect_identifier();
786 func->parameters.push_back(var);
790 string token = peek_token();
793 func->definition = func.get();
794 parse_block(func->body, true);
799 throw runtime_error(format_syntax_error("'{' or ';'"));
804 RefPtr<InterfaceBlock> ProgramParser::parse_interface_block()
806 RefPtr<InterfaceBlock> iface = new InterfaceBlock;
808 iface->interface = parse_token();
809 if(!is_interface_qualifier(iface->interface))
810 throw runtime_error(format_syntax_error("an interface qualifier"));
812 iface->name = expect_identifier();
813 parse_block(iface->members, true);
816 iface->instance_name = expect_identifier();
828 RefPtr<Conditional> ProgramParser::parse_conditional()
832 RefPtr<Conditional> cond = new Conditional;
833 cond->condition = parse_expression();
836 parse_block(cond->body, false);
838 string token = peek_token();
842 parse_block(cond->else_body, false);
848 RefPtr<Iteration> ProgramParser::parse_for()
852 RefPtr<Iteration> loop = new Iteration;
853 string token = peek_token();
855 loop->init_statement = parse_statement();
860 RefPtr<ExpressionStatement> expr = new ExpressionStatement;
861 expr->expression = parse_expression();
862 loop->init_statement = expr;
866 if(peek_token()!=";")
867 loop->condition = parse_expression();
869 if(peek_token()!=")")
870 loop->loop_expression = parse_expression();
873 parse_block(loop->body, false);
878 RefPtr<Iteration> ProgramParser::parse_while()
882 RefPtr<Iteration> loop = new Iteration;
883 loop->condition = parse_expression();
886 parse_block(loop->body, false);
891 RefPtr<Passthrough> ProgramParser::parse_passthrough()
893 expect("passthrough");
894 RefPtr<Passthrough> pass = new Passthrough;
895 if(cur_stage->type==GEOMETRY)
898 pass->subscript = parse_expression();
905 RefPtr<Return> ProgramParser::parse_return()
908 RefPtr<Return> ret = new Return;
909 if(peek_token()!=";")
910 ret->expression = parse_expression();