Having issues with flex/bison. I execute one statement and the result appears only after I execute a second statement. Why?
Here's what I want:
d>5
3 = 5
5+6=
11
PR 2+3
5
d>5
3 = 5
Here's what I get (notice the bottom part of the result):
d>5
3 = 5
5+6=
11
PR 2+3
d>5
53 = 5
Here's the flex:
%{
#include "calc.tab.h"
#include <stdlib.h>
%}
%%
[ ] {}
[0-9]+ { yylval = atoi( yytext ); return NUM; }
[a-z] { yylval = yytext[0] - 'a'; return NAME; }
. { return (int) yytext[0]; }
"PR" { return PR; }
%%
int yywrap(void)
{
return 1;
}
Here's the yacc/bison:
/* Infix notation calculator--calc */
%{
#define YYDEBUG 1
#define YYSTYPE int
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
/* prototypes */
void yyerror (char* s);
int yylex(void);
void storeVar (char vName, int vValue);
void printVar (int value);
int sym[30];
%}
/* BISON Declarations */
%start input /* what rule starts */
%token NUM
%token NAME
%token PR
%left '-' '+' /* these done for precdence */
%left '*' '/'
%right '^' /* exponentiation */
/* Grammar follows */
%%
input: /* empty string */
| input line
;
/* line: '\n' */
/* | exp '\n' { printf ("\t%.10g\n", $1); } */
line: '\n' { printf(" "); }
| var '>' NUM { printf("%d %s %d", $1, "=", $3); }
| PR exp { printVar($2); }
| exp '=' { printf("%d", $1); }
;
exp: NUM { $$ = $1; }
| exp '+' exp { $$ = $1 + $3; }
| exp '-' exp { $$ = $1 - $3; }
| exp '*' exp { $$ = $1 * $3; }
| exp '/' exp { $$ = $1 / $3; }
| exp '^' exp { $$ = pow ($1, $3); }
| '(' exp ')' { $$ = $2; }
;
var: NAME { $$ = $1; }
%%
int main ()
{
yyparse ();
}
void yyerror (char *s) /* Called by yyparse on error */
{
printf ("%s\n", s);
}
void storeVar (char vName, int vValue)
{
sym[(int)vName-97] = vValue;
}
void printVar (int value)
{
printf("%d", value);
//printf("%d", array[0]);
}