Lex / Yacc用于布尔计算

时间:2014-03-03 18:24:31

标签: compiler-construction yacc lex

我正在尝试使用Lex / Yacc编写一个用于计算NAND布尔表达式的程序。

例如,如果输入为“true nand(false nand true)”,我的程序应该打印“false”

这是我到目前为止所做的,但我真的被困了

我错过了什么或做错了什么?

boolean.l

%{
#include "y.tab.h"
%}


%%
"true"|"false" {return BOOL;}
"nand"         {return NAND;}
[()]           {return yytext[0];}

%%

boolean.y

%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();
}

1 个答案:

答案 0 :(得分:1)

如果您将TRUEFALSE两个单独的令牌放在一起,那么您会有更多的时间。

%token TRUE FALSE NAND
%left NAND

%%
boolexp: boolexp NAND boolterm    {$$ = !($1 && $3);}
        | boolterm    {$$=$1;}
;

boolterm: '(' boolexp ')' {$$ = $2;}
        | bool  {$$ = $1;}
;

bool: TRUE {$$ = 1;}
    | FALSE ($$ = 0;}
;