我正在尝试使用Lex / Yacc编写一个用于计算NAND布尔表达式的程序。
例如,如果输入为“true nand(false nand true)”,我的程序应该打印“false”
这是我到目前为止所做的,但我真的被困了
我错过了什么或做错了什么?
%{
#include "y.tab.h"
%}
%%
"true"|"false" {return BOOL;}
"nand" {return NAND;}
[()] {return yytext[0];}
%%
%token BOOL NAND
%left NAND
%%
boolexp: boolexp NAND boolterm {$$ = !($1 && $3);}
| boolterm {$$=$1;}
;
boolterm: '(' boolexp ')'
| BOOL {$$ = (strcmp($1, "true")) ? 1 : 0;}
;
%%
#include <lex.yy.c>
int main(void) {
yyparse();
}
答案 0 :(得分:1)
如果您将TRUE
和FALSE
两个单独的令牌放在一起,那么您会有更多的时间。
%token TRUE FALSE NAND
%left NAND
%%
boolexp: boolexp NAND boolterm {$$ = !($1 && $3);}
| boolterm {$$=$1;}
;
boolterm: '(' boolexp ')' {$$ = $2;}
| bool {$$ = $1;}
;
bool: TRUE {$$ = 1;}
| FALSE ($$ = 0;}
;