validexp.l
//LEX Program
/* declaration section in this sections we will declare the different value and include the header file which we are using in this program to run this program */
%{
#include"y.tab.h"
extern yylval;
%}
/* defined section */
%%
[0-9]+ {yylval=atoi(yytext); return NUMBER;} //this is send to the yacc code as token INTEGER
[a-zA-Z]+ {return ID;} //this is send to the yacc code as token ID
[\t]+ ;
\n {return 0;}
. {return yytext[0];}
%%
validexp.y
//yacc program
//decelration section
#include<stdio.h>
%}
//definition section
%token NUMBER ID // token from lex file
%left '+' '-' // left associative
%left '*' '/'
%%
expr: expr '+' expr // grammer production rule
|expr '-' expr
|expr '*' expr
|expr '/' expr
|'-'NUMBER
|'-'ID
|'('expr')'
|NUMBER
|ID
;
%%
//main function
main()
{
printf("Enter the expression\n");
yyparse();
printf("\nExpression is valid\n");
exit(0);
}
//if error occured
int yyerror(char *s)
{
printf("\nExpression is invalid");
exit(0);
}
how to run
save the file as given above
compile the yacc code "yacc -d validexp.y"
compile the lex code "flex validexp.l"
now compile c file code "cc lex.yy.c y.tab.c -o validexp -ll"
execute the file "./validexp"
Comments
Post a Comment