Question

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

No correct solution

OTHER TIPS

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;}
;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top