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")
487 return parse_iteration();
488 else if(token=="passthrough")
489 return parse_passthrough();
490 else if(token=="return")
491 return parse_return();
492 else if(token=="break" || token=="continue" || token=="discard")
494 RefPtr<Jump> jump = new Jump;
495 jump->keyword = parse_token();
500 else if(is_qualifier(token) || is_type(token))
501 return parse_variable_declaration();
502 else if(!token.empty())
504 RefPtr<ExpressionStatement> expr = new ExpressionStatement;
505 expr->expression = parse_expression();
511 throw runtime_error(format_syntax_error("a statement"));
514 RefPtr<Import> ProgramParser::parse_import()
516 if(cur_stage->type!=SHARED)
517 throw runtime_error(format_error("Imports are only allowed in the shared section"));
520 RefPtr<Import> import = new Import;
521 import->module = parse_token();
526 RefPtr<Precision> ProgramParser::parse_precision()
529 RefPtr<Precision> precision = new Precision;
531 precision->precision = parse_token();
532 if(!is_precision_qualifier(precision->precision))
533 throw runtime_error(format_syntax_error("a precision qualifier"));
535 precision->type = parse_token();
536 // Not entirely accurate; only float, int and sampler types are allowed
537 if(!is_builtin_type(precision->type))
538 throw runtime_error(format_syntax_error("a builtin type"));
545 RefPtr<Layout> ProgramParser::parse_layout()
549 RefPtr<Layout> layout = new Layout;
552 string token = parse_token();
554 throw runtime_error(format_syntax_error("a layout qualifier name"));
556 layout->qualifiers.push_back(Layout::Qualifier());
557 Layout::Qualifier &qual = layout->qualifiers.back();
558 qual.identifier = token;
561 qual.value = parse_token();
563 if(peek_token()==")")
573 void ProgramParser::parse_block(Block &block, bool require_braces)
575 bool have_braces = (require_braces || peek_token()=="{");
581 while(peek_token()!="}")
582 block.body.push_back(parse_statement());
585 block.body.push_back(parse_statement());
587 block.use_braces = (require_braces || block.body.size()!=1);
593 RefPtr<Expression> ProgramParser::parse_expression(unsigned precedence)
595 RefPtr<Expression> left;
596 VariableReference *left_var = 0;
599 string token = peek_token();
601 const Operator *oper = 0;
602 for(Operator *i=operators; (!oper && i->type); ++i)
603 if(token==i->token && (!left || i->type!=PREFIX) && (left || i->type!=POSTFIX))
606 if(token==";" || token==")" || token=="]" || token=="," || (oper && precedence && oper->precedence>=precedence))
611 throw runtime_error(format_syntax_error("an expression"));
618 throw runtime_error(format_error("Syntax error before '(': function name must be an identifier"));
619 left = parse_function_call(*left_var);
623 RefPtr<MemberAccess> memacc = new MemberAccess;
626 memacc->member = expect_identifier();
629 else if(oper && oper->type==POSTFIX)
631 RefPtr<UnaryExpression> unary = new UnaryExpression;
632 unary->oper = parse_token();
633 unary->prefix = false;
634 unary->expression = left;
637 else if(oper && oper->type==BINARY)
638 left = parse_binary(left, oper);
640 throw runtime_error(format_syntax_error("an operator"));
648 RefPtr<ParenthesizedExpression> parexpr = new ParenthesizedExpression;
649 parexpr->expression = parse_expression();
653 else if(isdigit(token[0]) || token=="true" || token=="false")
655 RefPtr<Literal> literal = new Literal;
656 literal->token = parse_token();
659 else if(is_identifier(token))
661 RefPtr<VariableReference> var = new VariableReference;
662 var->name = expect_identifier();
664 left_var = var.get();
666 else if(oper && oper->type==PREFIX)
668 RefPtr<UnaryExpression> unary = new UnaryExpression;
669 unary->oper = parse_token();
670 unary->prefix = true;
671 unary->expression = parse_expression(oper->precedence);
675 throw runtime_error(format_syntax_error("an expression"));
680 RefPtr<BinaryExpression> ProgramParser::parse_binary(const RefPtr<Expression> &left, const Operator *oper)
682 RefPtr<BinaryExpression> binary = (oper->precedence==16 ? new Assignment : new BinaryExpression);
684 binary->oper = parse_token();
685 if(binary->oper=="[")
687 binary->right = parse_expression();
692 binary->right = parse_expression(oper->precedence+(oper->assoc==RIGHT_TO_LEFT));
696 RefPtr<FunctionCall> ProgramParser::parse_function_call(const VariableReference &var)
698 RefPtr<FunctionCall> call = new FunctionCall;
699 call->name = var.name;
700 call->constructor = is_type(call->name);
702 while(peek_token()!=")")
704 if(!call->arguments.empty())
706 call->arguments.push_back(parse_expression());
712 RefPtr<StructDeclaration> ProgramParser::parse_struct_declaration()
715 RefPtr<StructDeclaration> strct = new StructDeclaration;
717 strct->name = expect_identifier();
718 parse_block(strct->members, true);
721 declared_types.insert(strct->name);
725 RefPtr<VariableDeclaration> ProgramParser::parse_variable_declaration()
727 RefPtr<VariableDeclaration> var = new VariableDeclaration;
729 string token = peek_token();
730 while(is_qualifier(token))
733 if(is_interface_qualifier(token))
734 var->interface = token;
735 else if(is_sampling_qualifier(token))
736 var->sampling = token;
737 else if(is_interpolation_qualifier(token))
738 var->interpolation = token;
739 else if(is_precision_qualifier(token))
740 var->precision = token;
741 else if(token=="const")
742 var->constant = true;
743 token = peek_token();
746 var->type = expect_type();
747 var->name = expect_identifier();
754 var->array_size = parse_expression();
760 var->init_expression = parse_expression();
766 RefPtr<FunctionDeclaration> ProgramParser::parse_function_declaration()
768 RefPtr<FunctionDeclaration> func = new FunctionDeclaration;
770 func->return_type = expect_type();
771 func->name = expect_identifier();
773 while(peek_token()!=")")
775 if(!func->parameters.empty())
778 RefPtr<VariableDeclaration> var = new VariableDeclaration;
779 string token = peek_token();
780 if(token=="in" || token=="out" || token=="inout")
781 var->interface = parse_token();
782 var->type = expect_type();
783 var->name = expect_identifier();
784 func->parameters.push_back(var);
788 string token = peek_token();
791 func->definition = func.get();
792 parse_block(func->body, true);
797 throw runtime_error(format_syntax_error("'{' or ';'"));
802 RefPtr<InterfaceBlock> ProgramParser::parse_interface_block()
804 RefPtr<InterfaceBlock> iface = new InterfaceBlock;
806 iface->interface = parse_token();
807 if(!is_interface_qualifier(iface->interface))
808 throw runtime_error(format_syntax_error("an interface qualifier"));
810 iface->name = expect_identifier();
811 parse_block(iface->members, true);
814 iface->instance_name = expect_identifier();
826 RefPtr<Conditional> ProgramParser::parse_conditional()
830 RefPtr<Conditional> cond = new Conditional;
831 cond->condition = parse_expression();
834 parse_block(cond->body, false);
836 string token = peek_token();
840 parse_block(cond->else_body, false);
846 RefPtr<Iteration> ProgramParser::parse_iteration()
850 RefPtr<Iteration> loop = new Iteration;
851 string token = peek_token();
853 loop->init_statement = parse_statement();
856 RefPtr<ExpressionStatement> expr = new ExpressionStatement;
857 expr->expression = parse_expression();
859 loop->init_statement = expr;
861 loop->condition = parse_expression();
863 loop->loop_expression = parse_expression();
866 parse_block(loop->body, false);
871 RefPtr<Passthrough> ProgramParser::parse_passthrough()
873 expect("passthrough");
874 RefPtr<Passthrough> pass = new Passthrough;
875 if(cur_stage->type==GEOMETRY)
878 pass->subscript = parse_expression();
885 RefPtr<Return> ProgramParser::parse_return()
888 RefPtr<Return> ret = new Return;
889 if(peek_token()!=";")
890 ret->expression = parse_expression();