Pages

Monday, 13 May 2013

Second package of flex and bison usage... another grammar implementation...

This is my second attempt at using flex and bison... you might find it useful...

Grammar:
E->E+E
E->(E)
E->T
T->id


Here is the flex specification file: saved as clexer2.l

%{
//family cparser2.y - clang2
#include<stdlib.h>
#include"cparser2.tab.h"
int yylval;
%}
%%
[0-9]+ {yylval=atoi(yytext);return id;}
[+()] return *yytext;
\n |
. ;
%%


Here is the bison specification file: saved as cparser2.y

%{
//family clexer2.l clang2
#include<stdio.h>
int yywrap(void);
void yyerror(char*);
%}
%left '+'
%left '('
%left ')'
%token id;
%%
S:S E {$$=$2;}
|
;
E:E'+'E {$$=$1+$3; printf("Ans: %d\n",$$);}
|'('E')' {$$=$2;}
|T {$$=$1;}
;
T:id {$$=$1;}
;
%%
int main(void)
{
yyparse();
return 0;
}
int yywrap(void)
{
return 1;
}
void yyerror(char* msg)
{
printf("%s",msg);
}


Now all you have to do is run the following commands:



flex clexer2.l

bison -d cparser2.y

gcc -o clang2 lex.yy.c cparser2.tab.c


Now you have to run the program on your linux OS as:

./clang2

No comments:

Post a Comment