使用BISON制作计算器

时间:2014-02-19 12:35:27

标签: compiler-construction bison yacc

这是我的野牛代码。问题是,当我输入例如4+3时,程序检测到语法错误。但是当我输入4 + 3时,即数字由空格分隔,它会计算并完美地显示结果。请提示它可能出错的地方。


input:
 | input line
 ;

line: NEWLINE
 | expr NEWLINE     {cout << $1 << endl; $$ = $1;}
 ;
expr: term
 | expr PLUS term    {$$ = $1 + $3;}
 | expr MINUS term  {$$ = $1 - $3;}
 | expr LSHIFT term {checkedShifting($1, $3, &$$, true);}
 | expr RSHIFT term {checkedShifting($1, $3, &$$, false);}
 ;
term: factor
 | term MUL factor  {$$ = $1 * $3;}
 | term DIV factor  {checkedDivision($1, $3, &$$);}
 | term MOD factor  {checkedMod($1, $3, &$$);}
 ;
factor: NUMBER
   | LBRACE expr RBRACE     {$$ = $2;}
   | factor EXPONENT factor {$$ = pow($1, $3);}
   ;

编辑:这是我的lex代码: http://paste.ubuntu.com/6959725/

野牛代码: http://paste.ubuntu.com/6959727/

1 个答案:

答案 0 :(得分:2)

乍一看,似乎4 + 3应该被标记为{number}{signednumber},而不是{number}{PLUS}{number}

此外,我认为您不应该为签名号码设置特殊令牌。解析器应该弄清楚这是一元还是二元加/减。