Saturday 30 April 2016

Programming with lex and Yacc

1. Counting number of lines , words etc. using Lex

%{
int nchar,word,line;
%}
%%
\n  { line++; nchar++;}
[^ \t\n]+  { word++; nchar+=yyleng; }
.  { nchar++; }
%%

int main()
{
yylex();
printf("%d\t%d\t%d\n",nchar,word,line);
return 0;
}

Execution steps:

1. lex filename.l
2. gcc lex.yy.c -ll
3. ./a.out
4. CTRL+D


2. Calculator using Lex and Yacc

// yacc file
%{
#include<stdio.h>
#include<stdlib.h>
void yyerror(char *s);
%}
%token NAME NUMBER
%%
statement:NAME '=' expression
          | expression {printf("\n%d\n",$1);};
expression:expression '+' NUMBER {$$=$1+$3;}
          | expression '-' NUMBER {$$=$1-$3;}
          | expression '*' NUMBER {$$=$1*$3;}
          | expression '/' NUMBER
          {
             if($3==0)
                yyerror("Division by Zero");
             else
                $$=$1/$3;
          }
          |NUMBER {$$=$1;}
          ;
%%
int main()
{
while(yyparse());
}

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


// lex file
%{
#include<stdio.h>
#include<stdlib.h>
#include"y.tab.h"
extern int yylval;
%}
%%
[0-9]+ {yylval=atoi(yytext); return NUMBER;}
[ \t]  {;}
\n     return 0;
.      return yytext[0];
%%



Execution steps:
1. yacc -d filename.y
2. lex filename.l
3. gcc lex.yy.c y.tab.c -ll
4. ./a.out

No comments:

Post a Comment