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