0

I am new to using flex and bison I have implemented a simple calculator. I am trying to determine if an input is a sentence in the grammar.

For example if I enter: a = 2; b = 3; print a+b;

It would return: "a = 2; b = 3; print a+b; is a sentence"

Right now it will actually do the calculator but I don't care about the actual calculation I just want to know if the input is a sentence in the grammar.

I am not really sure how to go about doing this. Any help or hints would be appreciated.

My flex code is:

   %{
       #include "y.tab.h"
       #include <stdlib.h>
       void yyerror(char *);
   %}

   %%

   [a-z]       {
                   yylval = *yytext - 'a';
                   return VARIABLE;
               }

   [0-9]+      {
                   yylval = atoi(yytext);
                   return INTEGER;
               }

   [-()+=/^*;]     { return *yytext; }

   "print"         return PRINT;

   [ \t]   ;       /* skip whitespace */

   .               yyerror("invalid characters.");

   %%

   int yywrap(void) {
       return 1;
   }

My Bison code is:

   %{
       #include <stdio.h>
       #include <math.h>
       void yyerror(char *);
       int yylex(void);
       char *in;
       int sym[26];
   %}

   %token INTEGER VARIABLE PRINT
   %left '+' '-'
   %left '*' '/'
   %right '^'

   %%

   program:
          program statement              { }      
          | /* NULL */                   { }
          ;

   statement:
          ';'                            { $$ = ';'; }
          | expression ';'               { $$ = $1; }
          | VARIABLE '=' expression ';'  { sym[$1] = $3; }
          | PRINT expression ';'         { printf("%d\n", $2); }
          ;

   expression:
           INTEGER
           | VARIABLE                      { $$ = sym[$1]; }   
           | expression '+' expression     { $$ = $1 + $3; }
           | expression '-' expression     { $$ = $1 - $3; }
           | expression '*' expression     { $$ = $1 * $3; }
           | expression '/' expression     { $$ = $1 / $3; }
           | expression '^' expression     { $$ = pow($1,$3); }
           | '(' expression ')'            { $$ = $2; }
           | '-' expression                { $$ = -$2; }
           ;

   %%

  void yyerror(char *s) {
       fprintf(stderr, "%s\n", s);
  }

  int main(void) {
       while (1) {
           yyparse();
       }
   }
user207421
  • 305,947
  • 44
  • 307
  • 483
Steven
  • 1
  • 1

1 Answers1

2

The yyparse function generated by bison returns 0 if the (entire) input matched the grammar, and 1 if there was a syntax error. (It can also return 2 to indicate that it ran out of memory trying to parse the grammar, but that's rare unless you're using yacc-compatible mode.)

So if you just want to check for correctness, remove all the actions from your bison productions; then you can parse the input and check the return code from yyparse.

rici
  • 234,347
  • 28
  • 237
  • 341