问题
I'm trying to write a program for calculating a NAND boolean expression using Lex/Yacc.
For example, if input is "true nand (false nand true)," my program should print "false"
This is what I have so far,, but I am really stuck
What am I missing or doing wrong?
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:
You'd have a lot easier time if you made TRUE
and FALSE
two separate tokens.
%token TRUE FALSE NAND
%left NAND
%%
boolexp: boolexp NAND boolterm {$$ = !($1 && $3);}
| boolterm {$$=$1;}
;
boolterm: '(' boolexp ')' {$$ = $2;}
| bool {$$ = $1;}
;
bool: TRUE {$$ = 1;}
| FALSE ($$ = 0;}
;
来源:https://stackoverflow.com/questions/22154353/lex-yacc-for-boolean-calculation