1
votes

I'm trying to implement a calculator for nor expressions, such as true nor true nor (false nor false) using Flex and Bison, but I keep getting my error message back. Here is my .l file:

%{
#include <stdlib.h>
#include "y.tab.h"
%}

%% 
("true"|"false")    {return BOOLEAN;}

.|\n    {yyerror();}

%%

int main(void)
{
    yyparse();
    return 0;
}

int yywrap(void)
{
     return 0;
}
int yyerror(void)
{
     printf("Error\n");
}

Here is my .y file:

/* Bison declarations.  */
 %token BOOLEAN
 %left 'nor'

 %% /* The grammar follows.  */
 input:
   /* empty */
 | input line
 ;

 line:
   '\n'
 | exp '\n'  { printf ("%s",$1); }
 ;

 exp:
   BOOLEAN            { $$ = $1;           }
 | exp 'nor' exp      { $$ = !($1 || $3);  }
 | '(' exp ')'        { $$ = $2;           }
 ;
 %%

Does anyone see the problem?

2

2 Answers

1
votes

The reason why you get errors is that your lexer only recognizes one type of token, namely BOOLEAN, but not the newline, parentheses or nor (and you produce an error for everything else). For single letter tokens like parentheses and the newline you can return the character itself as a token type:

\n { return '\n'; }

For nor thought you should introduce a token type like you did for BOOLEAN and add an appropriate rule to the lexer.

1
votes

The simple way to handle all the single-character tokens, which as @vitaut correctly says you aren't handling at all yet, is to return yytext[0] for the dot rule, and let the parser sort out which ones are legal.

You have also lost the values of the BOOLEANs 'true' and 'false', which should be stored into yylval as 1 and 0 respectively, which will then turn up in $1, $3 etc. If you're going to have more datatypes in the longer term, you need to look into the %union directive.