2

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

%{
#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。我在这个文件的开头定义了运算符的优先级,我尝试了很多这些优先级的组合,但我仍然得到这个错误。我怎样才能消除这种歧义?谢谢

4

1 回答 1

4

tOR, tAND, 并且tDOTPROD还需要指定它们的优先级。

于 2013-03-10T23:05:32.693 回答