我正在尝试使用“IF ELSE”语句实现我自己的计算器。这是基本的计算器示例:
/* description: Parses end executes mathematical expressions. */
/* lexical grammar */
%lex
%%
\s+ /* skip whitespace */
[0-9]+("."[0-9]+)?\b return 'NUMBER'
"*" return '*'
"/" return '/'
"-" return '-'
"+" return '+'
"^" return '^'
"(" return '('
")" return ')'
"PI" return 'PI'
"E" return 'E'
<<EOF>> return 'EOF'
. return 'INVALID'
/lex
/* operator associations and precedence */
%left '+' '-'
%left '*' '/'
%left '^'
%left UMINUS
%start expressions
%% /* language grammar */
expressions
: e EOF
{return $1;}
;
e
: e '+' e
{$$ = $1+$3;}
| e '-' e
{$$ = $1-$3;}
| e '*' e
{$$ = $1*$3;}
| e '/' e
{$$ = $1/$3;}
| e '^' e
{$$ = Math.pow($1, $3);}
| '-' e %prec UMINUS
{$$ = -$2;}
| '(' e ')'
{$$ = $2;}
| NUMBER
{$$ = Number(yytext);}
| E
{$$ = Math.E;}
| PI
{$$ = Math.PI;}
;
我不明白如果我添加这样的“IF”语句:
IfStatement
: "IF" "(" Expression ")" Statement
{
$$ = new IfStatementNode($3, $5, null, createSourceLocation(null, @1, @5));
}
| "IF" "(" Expression ")" Statement "ELSE" Statement
{
$$ = new IfStatementNode($3, $5, $7, createSourceLocation(null, @1, @7));
}
;
解析器生成良好。那么我如何使用这样的语句 IF(5>2)THEN (5+2) ELSE (5*2)。计算器的功能当然很好用,但“IF”却不行。