2013-03-10 103 views
1

我正在寫野牛的簡單解析器。分析程序檢查程序是否有任何語法錯誤就我下面的語法:去除野牛的歧義

%{ 
#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。我在這個文件的開頭定義了運算符的優先級,我嘗試了很多這些優先級的組合,但是我仍然得到這個錯誤。我如何消除這種歧義?謝謝

+0

你能列出shift/reduce錯誤嗎? – valtron 2013-03-10 22:55:23

+0

我該怎麼做? – yrazlik 2013-03-10 22:56:39

+0

它只是說衝突:13 shift/reduce – yrazlik 2013-03-10 22:56:57

回答

3

tOR,tANDtDOTPROD也需要指定它們的優先順序。

+0

也有關聯性。 – 2013-03-10 23:16:28