Monday, 2 December 2013

Recognize Arithmetic Expression using Yacc

YACC

%{
#include<stdio.h>
%}
%token digit;

%%
input : program { printf("Valid"); }
;
program : program expr
|
;
expr :  digit
| expr '+' expr
| expr '-' expr
| expr '*' expr
| expr '/' expr
| expr '^' expr
;
%%
int main()
{
printf("Enter the expression : ");
yyparse();
return 0;
}
int yyerror(char *s)
{
printf("%s",s);
}


LEX

%{
#include "y.tab.h"
%}
%%
[0-9]+ { return digit; }
\n { return 0; }
[ \t] ;
. { return (int) yytext[0]; }
%%
int yywrap()
{
return 1;
}


HOW TO RUN:
$ yacc -d arith.y
$ lex arith.l
$ gcc lex.yy.c y.tab.h -o arith
$ ./arith

OUTPUT:
Enter the expression : 3+4-4
Valid
vijay@ubuntu:~/Desktop/lppractice$ ./arith
Enter the expression : 3344---
syntax error

No comments:

Post a Comment