Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- a) To evaluate an arithmetic expression using YACC tool
- File: 4a.l %{ #include<stdio.h> #include "y.tab.h" extern int yylval; %} %% [0-9]+ { yylval=atoi(yytext); return NUMBER; } [\t] ; [\n] return 0; . return yytext[0]; %%
- int yywrap() { return 1; }
- File: 4a.y %{ #include<stdio.h> int flag=0; %} %token NUMBER %left '+' '-' %left '*' '/' '%' %left '(' ')' %% ArithmeticExpression: E{ printf("\nResult=%d\n",$$); return 0; } E:E'+'E {$$=$1+$3;} |E'-'E {$$=$1-$3;} |E'*'E {$$=$1*$3;} |E'/'E {$$=$1/$3;} |E'%'E {$$=$1%$3;} |'('E')' {$$=$2;} | NUMBER {$$=$1;} ; %% void main() { printf("\nEnter any arithmetic expression: "); yyparse(); if(flag==0) printf("\nExpression is valid\n\n"); } void yyerror() { printf("\nExpression is invalid\n\n"); flag=1; }
- b) To recognize valid variable name using YACC tool
- File: 4b.l %{ #include<stdio.h> #include "y.tab.h" %} %% new return NEW; "[" return OPEN_SQ; "]" return CLOSE_SQ; "=" return EQ; "," return COMMA; "_" return UD; (["\t"])+ return WS; [a-zA-Z]+[a-zA-Z0-9]* return ID; [0-9]+ return DIGIT; \n return 0; %%
- File: 4b.y %{ #include<stdio.h> #include "y.tab.h" %} %token BUILTIN UD WS ID OPEN_SQ CLOSE_SQ EQ NEW SC COMMA DIGIT %% start : varlist WS varlist {printf("invalid declaration \n\n");} | varlist UD DIGIT {printf("valid declaration \n\n");} | varlist {printf("valid declaration \n\n");}
- | varlist UD varlist {printf("valid declaration \n\n");} | varlist : varlist COMMA ID | ID; %% int yywrap() { return 1; } int main() { printf("\nEnter variable declaration: "); yyparse(); return 1; } int yyerror(char *s) { fprintf(stderr,"invalid declaration\n\n",s); return 1; }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement