Solving bison conflict over 2nd lookahead -
i'm writing parser project , got stuck on issue. here's self contained example of problem:
%error-verbose %token id %token var %token end_var %token constant %token @ %token value %% unit: regular_var_decl | direct_var_decl; regular_var_decl: var constant_opt id ':' value ';' end_var; constant_opt: /* empty */ | constant; direct_var_decl: var id @ value ':' value ';' end_var; %% #include <stdlib.h> #include <stdio.h> yylex() { static int = 0; static int tokens[] = { var, id, ':', value, ';', end_var, 0 }; return tokens[i++]; }; yyerror(str) char *str; { printf("fail: %s\n", str); }; main() { yyparse(); return 0; };
one build bison test.y && cc test.tab.c && ./a.out
.
it warns me constant_opt
useless due conflicts.
this ambiguity solved using lalr(2), since after id
find ':' or at
... how solve issue on bison?
a simple solution not abbreviate optional constant:
regular_var_decl: var id ':' value ';' end_var; constant_var_decl: var constant id ':' value ';' end_var; direct_var_decl: var id @ value ':' value ';' end_var;
that allows reduction decision deferred until enough information known. (you factor ':' value ';' end_var
non-terminal if useful.)
another possibility leave grammar was, , ask bison produce glr parser (%glr-parser
). glr parser retain 2 (or more) parallel parses until ambiguity can resolved, should fix constant_opt
problem. (note shift/reduce conflicts still reported bison; cannot tell whether language ambiguous until ambiguous sentence discovered @ runtime.) of time, no additional change grammar needs made, slow parse down little bit.
a final possibility, less useful here, accept superset of language , issue error message in action:
var_decl: var const_opt id at_value_opt ':' value ';' end_var { if (/* pseudocode */ $2 && $4) { /* flag syntax error */ } }
that depends on 2 opt
terminals returning semantic value can interrogated somehow empty.
Comments
Post a Comment