Monday 13 May 2013

Flex Bison Beginning.... baby steps....

I have been trying to learn lex and yacc of late. Well the tools that I actually use are flex and bison.
Anyways, here is a small program to demonstrate the use of both in conjunction...

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


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

%{
//This lexer is for cparser1.y together they make clang1
#include<stdio.h>
#include"cparser1.tab.h"
int yylval;
%}
%%
[0-9]+ {yylval=atoi(yytext);return id;}
[+] return *yytext;
\n |
. ;
%%


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

%{
//this is the parser for the grammar E->E+T; E->T; T->id used in conjunction with clexer1.l
#include<stdio.h>
#include<stdlib.h>
void yyerror(char*);
int yywrap(void);
%}
%token id
%%
S:S E {$$=$2;}      //merely to augment the grammar
|       //represents epsilon
;
E:E'+'T {$$=$1+$3; printf("Ans: %d\n",$$);}
|T {$$=$1;}
;
T:id {$$=$1;}
;
%%
int main(void)
{
yyparse();
return 0;
}
void yyerror(char *msg)
{
printf("%s\n",msg);
}
int yywrap(void)
{
return 1;
}


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



flex clexer1.l

bison -d cparser1.y

gcc -o clang1 lex.yy.c cparser1.tab.c


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

./clang1

No comments:

Post a Comment