消除野牛的歧义

时间:2013-03-10 22:51:39

标签: parsing bison context-free-grammar flex-lexer ambiguity

我正在野牛中编写一个简单的解析器。解析器检查程序是否有关于我的后续语法的任何语法错误:

%{
#include <stdio.h>
void yyerror (const char *s) /* Called by yyparse on error */
{
    printf ("%s\n", s);
}
%}
%token tNUM tINT tREAL tIDENT tINTTYPE tREALTYPE tINTMATRIXTYPE 
%token tREALMATRIXTYPE tINTVECTORTYPE tREALVECTORTYPE tTRANSPOSE
%token tIF tENDIF tDOTPROD tEQ tNE tGTE tLTE tGT tLT tOR tAND
%left "(" ")" "[" "]"
%left "<" "<=" ">" ">="
%right "="
%left "+" "-"
%left "*" "/"
%left "||"
%left "&&"
%left "==" "!="

%% /* Grammar rules and actions follow */
prog: stmtlst ;
stmtlst: stmt | stmt stmtlst ;
stmt: decl | asgn | if;
decl: type vars "=" expr ";" ;
type: tINTTYPE | tINTVECTORTYPE  | tINTMATRIXTYPE | tREALTYPE | tREALVECTORTYPE 
      | tREALMATRIXTYPE ;
vars: tIDENT | tIDENT "," vars ;
asgn: tIDENT "=" expr ";" ;
if: tIF "(" bool ")" stmtlst tENDIF ;
expr: tIDENT | tINT | tREAL | vectorLit | matrixLit | expr "+" expr| expr "-" expr
  | expr "*" expr | expr "/" expr| expr tDOTPROD expr | transpose ;
transpose: tTRANSPOSE "(" expr ")" ;
vectorLit: "[" row "]" ;
matrixLit: "[" row ";" rows "]" ;
row: value | value "," row ;
rows: row  | row ";" rows ; 
value: tINT | tREAL | tIDENT ;
bool: comp | bool tAND bool | bool tOR bool ;
comp: expr relation expr ;
relation: tGT | tLT | tGTE | tLTE | tNE | tEQ ;
%%
int main ()
{    
    if (yyparse()) {
        // parse error
        printf("ERROR\n");
        return 1;
    }
    else {
        // successful parsing
        printf("OK\n");
        return 0;
    }
}

代码可能看起来冗长而复杂,但我认为我要问的不需要完整的代码,但无论如何我更喜欢编写代码。我确信我的语法是正确的,但含糊不清。当我尝试通过编写“bison -d filename.y”来创建程序的可执行文件时,我收到一条错误消息,指出冲突:13 shift / reduce 。我在这个文件的开头定义了运算符的优先级,我尝试了很多这些优先级的组合,但我仍然得到这个错误。我怎样才能消除这种歧义?谢谢

1 个答案:

答案 0 :(得分:4)

tORtANDtDOTPROD也需要指定其优先级。