1 #include <msp/core/raii.h>
2 #include <msp/strings/format.h>
3 #include <msp/strings/regex.h>
4 #include <msp/strings/utils.h>
6 #include "glsl_error.h"
18 preprocessor(tokenizer),
21 tokenizer.signal_preprocess.connect(sigc::mem_fun(&preprocessor, &Preprocessor::preprocess));
22 preprocessor.signal_version.connect(sigc::mem_fun(this, &Parser::set_required_version));
23 preprocessor.signal_source.connect(sigc::mem_fun(this, &Parser::source_reference));
24 preprocessor.signal_stage_change.connect(sigc::mem_fun(this, &Parser::stage_change));
25 preprocessor.signal_line.connect(sigc::mem_fun(this, &Parser::line_change));
33 Module &Parser::parse(const string &s, const string &n, int i)
40 Module &Parser::parse(IO::Base &io, const string &n, int i)
46 unsigned len = io.read(buffer, sizeof(buffer));
47 source.append(buffer, len);
53 void Parser::parse_source(const string &name, int index)
58 cur_stage = &module->shared;
62 source_reference(1, name);
64 // TODO Need to somehow get type names from imports
65 if(const Stage *builtin = get_builtins(Stage::SHARED))
67 for(map<string, TypeDeclaration *>::const_iterator i=builtin->types.begin(); i!=builtin->types.end(); ++i)
68 declared_types.insert(i->first);
72 declared_types.insert("void");
73 declared_types.insert("bool");
74 declared_types.insert("int");
75 declared_types.insert("float");
78 tokenizer.begin(source, name);
79 allow_stage_change = true;
80 while(!tokenizer.peek_token().empty())
81 if(RefPtr<Statement> statement = parse_with_recovery(&Parser::parse_global_declaration))
82 cur_stage->content.body.push_back(statement);
85 throw invalid_shader_source(join(errors.begin(), errors.end(), "\n"));
88 void Parser::set_required_version(const Version &ver)
90 cur_stage->required_features.glsl_version = ver;
93 void Parser::source_reference(unsigned index, const string &name)
95 if(index<1 || base_index<0)
96 throw invalid_shader_source(tokenizer.get_location(), "Invalid source reference");
98 module->source_map.set_name(base_index+index-1, name);
101 void Parser::stage_change(Stage::Type stage)
103 if(!allow_stage_change)
104 throw invalid_shader_source(tokenizer.get_location(), "Changing stage not allowed here");
105 else if(stage<=cur_stage->type)
106 throw invalid_shader_source(tokenizer.get_location(), "Stage '%s' not allowed here", Stage::get_stage_name(stage));
108 module->stages.push_back(stage);
110 if(cur_stage->type!=Stage::SHARED)
111 module->stages.back().previous = cur_stage;
112 cur_stage = &module->stages.back();
115 void Parser::line_change(int index, unsigned line)
118 source_index = base_index+index-1;
122 index = source_index;
124 string name = module->source_map.get_name(index);
126 name = format("<%d>", index);
127 tokenizer.set_location(Location(name, line));
130 string Parser::expect_type()
132 string token = tokenizer.parse_token();
134 throw parse_error(tokenizer.get_location(), token, "a type");
138 string Parser::expect_identifier()
140 string token = tokenizer.parse_token();
141 if(!is_identifier(token))
142 throw parse_error(tokenizer.get_location(), token, "an identifier");
146 int Parser::expect_integer()
148 string token = tokenizer.parse_token();
150 throw parse_error(tokenizer.get_location(), token, "an integer literal");
151 return lexical_cast<int>(token);
154 bool Parser::check(const string &token)
156 bool result = (tokenizer.peek_token()==token);
158 tokenizer.parse_token();
162 bool Parser::is_interface_qualifier(const string &token)
164 return (token=="uniform" || token=="in" || token=="out");
167 bool Parser::is_sampling_qualifier(const string &token)
169 return (token=="centroid" || token=="sample");
172 bool Parser::is_interpolation_qualifier(const string &token)
174 return (token=="smooth" || token=="flat" || token=="noperspective");
177 bool Parser::is_precision_qualifier(const string &token)
179 return (token=="highp" || token=="mediump" || token=="lowp");
182 bool Parser::is_qualifier(const string &token)
184 return (token=="const" ||
185 is_interface_qualifier(token) ||
186 is_sampling_qualifier(token) ||
187 is_interpolation_qualifier(token) ||
188 is_precision_qualifier(token));
191 bool Parser::is_type(const string &token)
193 return declared_types.count(token);
196 bool Parser::is_identifier(const string &token)
198 static Regex re("^[a-zA-Z_][a-zA-Z0-9_]*$");
199 return re.match(token);
203 RefPtr<T> Parser::create_node()
205 RefPtr<T> node = new T;
206 node->source = source_index;
207 node->line = tokenizer.get_location().line;
212 RefPtr<T> Parser::parse_with_recovery(RefPtr<T> (Parser::*parse_func)())
214 tokenizer.clear_progress_mark();
217 return (this->*parse_func)();
219 catch(const invalid_shader_source &exc)
221 errors.push_back(exc.what());
224 if(tokenizer.get_last_token()!=";" || !tokenizer.get_progress_mark())
226 unsigned scope_level = 0;
229 if(tokenizer.peek_token()=="}" && scope_level==0)
231 if(!tokenizer.get_progress_mark())
232 tokenizer.parse_token();
236 string token = tokenizer.parse_token();
245 else if(token==";" && scope_level==0)
247 else if(token.empty())
255 RefPtr<Statement> Parser::parse_global_declaration()
257 string token = tokenizer.peek_token();
258 SetFlag disallow(allow_stage_change, false);
261 return parse_import();
262 else if(token=="precision")
263 return parse_precision();
264 else if(token=="layout")
266 RefPtr<Layout> layout = parse_layout();
267 token = tokenizer.peek_token();
268 if(is_interface_qualifier(token) && tokenizer.peek_token(1)==";")
270 RefPtr<InterfaceLayout> iface_lo = create_node<InterfaceLayout>();
271 iface_lo->layout.qualifiers = layout->qualifiers;
272 iface_lo->interface = tokenizer.parse_token();
273 tokenizer.expect(";");
278 RefPtr<VariableDeclaration> var = parse_variable_declaration();
279 var->layout = layout;
283 else if(token=="typedef")
284 return parse_type_declaration();
285 else if(token=="struct")
286 return parse_struct_declaration();
287 else if(is_interface_qualifier(token))
289 string next = tokenizer.peek_token(1);
290 if(is_type(next) || is_qualifier(next))
291 return parse_variable_declaration();
293 return parse_interface_block();
295 else if(is_qualifier(token))
296 return parse_variable_declaration();
297 else if(is_type(token))
299 if(tokenizer.peek_token(2)=="(")
300 return parse_function_declaration();
302 return parse_variable_declaration();
304 else if(token.empty())
307 throw parse_error(tokenizer.get_location(), token, "a global declaration");
310 RefPtr<Statement> Parser::parse_statement()
312 string token = tokenizer.peek_token();
314 return parse_conditional();
315 else if(token=="for")
317 else if(token=="while")
318 return parse_while();
319 else if(token=="passthrough")
320 return parse_passthrough();
321 else if(token=="return")
322 return parse_return();
323 else if(token=="break" || token=="continue" || token=="discard")
325 RefPtr<Jump> jump = create_node<Jump>();
326 jump->keyword = tokenizer.parse_token();
327 tokenizer.expect(";");
331 else if(is_qualifier(token) || is_type(token))
332 return parse_variable_declaration();
335 tokenizer.parse_token();
336 throw invalid_shader_source(tokenizer.get_location(), "Empty statement not allowed");
338 else if(!token.empty())
340 RefPtr<ExpressionStatement> expr = create_node<ExpressionStatement>();
341 expr->expression = parse_expression();
342 tokenizer.expect(";");
347 throw parse_error(tokenizer.get_location(), token, "a statement");
350 RefPtr<Import> Parser::parse_import()
352 if(cur_stage->type!=Stage::SHARED)
353 throw invalid_shader_source(tokenizer.get_location(), "Imports are only allowed in the shared section");
355 tokenizer.expect("import");
356 RefPtr<Import> import = create_node<Import>();
357 import->module = expect_identifier();
358 tokenizer.expect(";");
362 RefPtr<Precision> Parser::parse_precision()
364 tokenizer.expect("precision");
365 RefPtr<Precision> precision = create_node<Precision>();
367 precision->precision = tokenizer.parse_token();
368 if(!is_precision_qualifier(precision->precision))
369 throw parse_error(tokenizer.get_location(), precision->precision, "a precision qualifier");
371 // TODO Add validation for this
372 precision->type = expect_type();
374 tokenizer.expect(";");
379 RefPtr<Layout> Parser::parse_layout()
381 tokenizer.expect("layout");
382 tokenizer.expect("(");
383 RefPtr<Layout> layout = create_node<Layout>();
386 string token = tokenizer.parse_token();
388 throw parse_error(tokenizer.get_location(), token, "a layout qualifier name");
390 layout->qualifiers.push_back(Layout::Qualifier());
391 Layout::Qualifier &qual = layout->qualifiers.back();
394 if((qual.has_value = check("=")))
396 if(qual.name=="constant_id" && tokenizer.peek_token()=="auto")
399 tokenizer.parse_token();
402 qual.value = expect_integer();
405 if(tokenizer.peek_token()==")")
408 tokenizer.expect(",");
410 tokenizer.expect(")");
416 void Parser::parse_block(Block &block, bool require_braces, RefPtr<T> (Parser::*parse_content)())
418 bool have_braces = (require_braces || tokenizer.peek_token()=="{");
420 tokenizer.expect("{");
424 while(tokenizer.peek_token()!="}")
425 if(RefPtr<Statement> node = parse_with_recovery(parse_content))
426 block.body.push_back(node);
429 block.body.push_back((this->*parse_content)());
431 block.use_braces = (require_braces || block.body.size()!=1);
434 tokenizer.expect("}");
437 RefPtr<Expression> Parser::parse_expression(unsigned precedence)
439 RefPtr<Expression> left;
440 VariableReference *left_var = 0;
443 string token = tokenizer.peek_token();
445 const Operator *oper = 0;
446 for(const Operator *i=Operator::operators; (!oper && i->type); ++i)
447 if(token==i->token && (!left || i->type!=Operator::PREFIX) && (left || i->type!=Operator::POSTFIX))
450 if(token==";" || token==")" || token=="]" || token=="," || (oper && precedence && oper->precedence>=precedence))
455 throw parse_error(tokenizer.get_location(), token, "an expression");
462 throw invalid_shader_source(tokenizer.get_location(), "Syntax error before '(': function name must be an identifier");
463 left = parse_function_call(*left_var);
467 RefPtr<MemberAccess> memacc = create_node<MemberAccess>();
470 tokenizer.parse_token();
471 memacc->member = expect_identifier();
474 else if(oper && oper->type==Operator::POSTFIX)
476 RefPtr<UnaryExpression> unary = create_node<UnaryExpression>();
478 tokenizer.parse_token();
479 unary->expression = left;
482 else if(oper && oper->type==Operator::BINARY)
483 left = parse_binary(left, *oper);
485 throw parse_error(tokenizer.get_location(), token, "an operator");
492 tokenizer.parse_token();
493 RefPtr<ParenthesizedExpression> parexpr = create_node<ParenthesizedExpression>();
494 parexpr->expression = parse_expression();
495 tokenizer.expect(")");
498 else if(isdigit(token[0]) || token=="true" || token=="false")
499 left = parse_literal();
500 else if(is_identifier(token))
502 RefPtr<VariableReference> var = create_node<VariableReference>();
503 var->name = expect_identifier();
505 left_var = var.get();
507 else if(oper && oper->type==Operator::PREFIX)
509 RefPtr<UnaryExpression> unary = create_node<UnaryExpression>();
511 tokenizer.parse_token();
512 unary->expression = parse_expression(oper->precedence);
516 throw parse_error(tokenizer.get_location(), token, "an expression");
521 RefPtr<Literal> Parser::parse_literal()
523 RefPtr<Literal> literal = create_node<Literal>();
524 literal->token = tokenizer.parse_token();
525 if(isdigit(literal->token[0]))
527 // TODO have the tokenizer return the type of the token
528 if(isnumrc(literal->token))
529 literal->value = lexical_cast<int>(literal->token);
531 literal->value = lexical_cast<float>(literal->token);
533 else if(literal->token=="true" || literal->token=="false")
534 literal->value = (literal->token=="true");
536 throw parse_error(tokenizer.get_location(), literal->token, "a literal");
541 RefPtr<BinaryExpression> Parser::parse_binary(const RefPtr<Expression> &left, const Operator &oper)
543 RefPtr<BinaryExpression> binary = (oper.precedence==16 ?
544 static_cast<RefPtr<BinaryExpression> >(create_node<Assignment>()) : create_node<BinaryExpression>());
546 binary->oper = &oper;
547 tokenizer.expect(oper.token);
548 if(oper.token[0]=='[')
550 binary->right = parse_expression();
551 tokenizer.expect("]");
554 binary->right = parse_expression(oper.precedence+(oper.assoc==Operator::RIGHT_TO_LEFT));
558 RefPtr<FunctionCall> Parser::parse_function_call(const VariableReference &var)
560 RefPtr<FunctionCall> call = create_node<FunctionCall>();
561 call->name = var.name;
562 call->constructor = is_type(call->name);
563 call->oper = &Operator::get_operator("(", Operator::POSTFIX);
564 tokenizer.expect("(");
565 while(tokenizer.peek_token()!=")")
567 if(!call->arguments.empty())
568 tokenizer.expect(",");
569 call->arguments.push_back(parse_expression());
571 tokenizer.expect(")");
575 RefPtr<TypeDeclaration> Parser::parse_type_declaration()
577 tokenizer.expect("typedef");
579 RefPtr<TypeDeclaration> type;
580 if(tokenizer.peek_token()=="image")
581 type = parse_image_type_declaration();
583 type = parse_basic_type_declaration();
585 tokenizer.expect(";");
586 declared_types.insert(type->name);
590 RefPtr<BasicTypeDeclaration> Parser::parse_basic_type_declaration()
592 RefPtr<BasicTypeDeclaration> type = create_node<BasicTypeDeclaration>();
594 if(tokenizer.peek_token()=="vector")
596 type->kind = BasicTypeDeclaration::VECTOR;
598 tokenizer.parse_token();
599 tokenizer.expect("(");
600 type->size = expect_integer();
601 tokenizer.expect(")");
604 type->base = expect_type();
605 type->name = expect_identifier();
607 if(type->kind==BasicTypeDeclaration::ALIAS && check("["))
609 type->kind = BasicTypeDeclaration::ARRAY;
610 tokenizer.expect("]");
616 RefPtr<ImageTypeDeclaration> Parser::parse_image_type_declaration()
618 tokenizer.expect("image");
619 tokenizer.expect("(");
621 RefPtr<ImageTypeDeclaration> type = create_node<ImageTypeDeclaration>();
624 string token = tokenizer.parse_token();
625 if(token=="dimensions")
627 tokenizer.expect("=");
628 token = tokenizer.parse_token();
630 type->dimensions = ImageTypeDeclaration::ONE;
632 type->dimensions = ImageTypeDeclaration::TWO;
634 type->dimensions = ImageTypeDeclaration::THREE;
635 else if(token=="cube")
636 type->dimensions = ImageTypeDeclaration::CUBE;
638 throw parse_error(tokenizer.get_location(), token, "dimensions");
643 tokenizer.expect("]");
646 else if(token=="sampled")
647 type->sampled = true;
648 else if(token=="shadow")
651 throw parse_error(tokenizer.get_location(), token, "image type attribute");
653 token = tokenizer.peek_token();
657 tokenizer.expect(",");
659 tokenizer.expect(")");
661 type->base = expect_type();
662 type->name = expect_identifier();
667 RefPtr<StructDeclaration> Parser::parse_struct_declaration()
669 tokenizer.expect("struct");
670 RefPtr<StructDeclaration> strct = create_node<StructDeclaration>();
672 strct->name = expect_identifier();
673 parse_block(strct->members, true, &Parser::parse_variable_declaration);
674 tokenizer.expect(";");
676 declared_types.insert(strct->name);
680 RefPtr<VariableDeclaration> Parser::parse_variable_declaration()
682 RefPtr<VariableDeclaration> var = create_node<VariableDeclaration>();
684 string token = tokenizer.peek_token();
685 while(is_qualifier(token))
687 tokenizer.parse_token();
688 if(is_interface_qualifier(token))
689 var->interface = token;
690 else if(is_sampling_qualifier(token))
691 var->sampling = token;
692 else if(is_interpolation_qualifier(token))
693 var->interpolation = token;
694 else if(is_precision_qualifier(token))
695 var->precision = token;
696 else if(token=="const")
697 var->constant = true;
698 token = tokenizer.peek_token();
701 var->type = expect_type();
702 var->name = expect_identifier();
709 var->array_size = parse_expression();
710 tokenizer.expect("]");
715 var->init_expression = parse_expression();
717 tokenizer.expect(";");
721 RefPtr<VariableDeclaration> Parser::parse_variable_declaration_with_layout()
723 RefPtr<Layout> layout;
724 if(tokenizer.peek_token()=="layout")
725 layout = parse_layout();
727 RefPtr<VariableDeclaration> var = parse_variable_declaration();
728 var->layout = layout;
733 RefPtr<FunctionDeclaration> Parser::parse_function_declaration()
735 RefPtr<FunctionDeclaration> func = create_node<FunctionDeclaration>();
737 func->return_type = expect_type();
738 func->name = expect_identifier();
739 tokenizer.expect("(");
740 while(tokenizer.peek_token()!=")")
742 if(!func->parameters.empty())
743 tokenizer.expect(",");
745 RefPtr<VariableDeclaration> var = create_node<VariableDeclaration>();
746 string token = tokenizer.peek_token();
747 if(token=="in" || token=="out" || token=="inout")
748 var->interface = tokenizer.parse_token();
749 var->type = expect_type();
750 var->name = expect_identifier();
751 func->parameters.push_back(var);
753 tokenizer.expect(")");
755 string token = tokenizer.peek_token();
758 func->definition = func.get();
759 parse_block(func->body, true, &Parser::parse_statement);
762 tokenizer.parse_token();
764 throw parse_error(tokenizer.get_location(), token, "'{' or ';'");
769 RefPtr<InterfaceBlock> Parser::parse_interface_block()
771 RefPtr<InterfaceBlock> iface = create_node<InterfaceBlock>();
773 iface->interface = tokenizer.parse_token();
774 if(!is_interface_qualifier(iface->interface))
775 throw parse_error(tokenizer.get_location(), iface->interface, "an interface qualifier");
777 iface->name = expect_identifier();
778 parse_block(iface->members, true, &Parser::parse_variable_declaration_with_layout);
781 iface->instance_name = expect_identifier();
785 tokenizer.expect("]");
787 tokenizer.expect(";");
793 RefPtr<Conditional> Parser::parse_conditional()
795 tokenizer.expect("if");
796 RefPtr<Conditional> cond = create_node<Conditional>();
797 tokenizer.expect("(");
798 cond->condition = parse_expression();
799 tokenizer.expect(")");
801 parse_block(cond->body, false, &Parser::parse_statement);
803 string token = tokenizer.peek_token();
806 tokenizer.parse_token();
807 parse_block(cond->else_body, false, &Parser::parse_statement);
813 RefPtr<Iteration> Parser::parse_for()
815 tokenizer.expect("for");
816 RefPtr<Iteration> loop = create_node<Iteration>();
817 tokenizer.expect("(");
818 string token = tokenizer.peek_token();
820 loop->init_statement = parse_statement();
825 RefPtr<ExpressionStatement> expr = create_node<ExpressionStatement>();
826 expr->expression = parse_expression();
827 loop->init_statement = expr;
829 tokenizer.expect(";");
831 if(tokenizer.peek_token()!=";")
832 loop->condition = parse_expression();
833 tokenizer.expect(";");
834 if(tokenizer.peek_token()!=")")
835 loop->loop_expression = parse_expression();
836 tokenizer.expect(")");
838 parse_block(loop->body, false, &Parser::parse_statement);
843 RefPtr<Iteration> Parser::parse_while()
845 tokenizer.expect("while");
846 RefPtr<Iteration> loop = create_node<Iteration>();
847 tokenizer.expect("(");
848 loop->condition = parse_expression();
849 tokenizer.expect(")");
851 parse_block(loop->body, false, &Parser::parse_statement);
856 RefPtr<Passthrough> Parser::parse_passthrough()
858 tokenizer.expect("passthrough");
859 RefPtr<Passthrough> pass = create_node<Passthrough>();
860 if(cur_stage->type==Stage::GEOMETRY)
862 tokenizer.expect("[");
863 pass->subscript = parse_expression();
864 tokenizer.expect("]");
866 tokenizer.expect(";");
870 RefPtr<Return> Parser::parse_return()
872 tokenizer.expect("return");
873 RefPtr<Return> ret = create_node<Return>();
874 if(tokenizer.peek_token()!=";")
875 ret->expression = parse_expression();
876 tokenizer.expect(";");