YACC Program To Evaluate An Express
YACC Program To Evaluate An Express
DESCRIPTION:
Each translation rule input to YACC has a string specification that resembles a
production of a grammar-it has a nonterminal on the LHS and a few alternatives on
the RHS. For simplicity, we will refer to a string specification as a production. YACC
generates an LALR(1) parser for language L from the productions, which is a bottom-
up parser. The parser would operate as follows: For a shift action, it would invoke the
scanner to obtain the next token and continue the parse by using that token. While
performing a reduced action in accordance with production, it would perform the
semantic action associated with that production.
The semantic actions associated with productions achieve the building of an
intermediate representation or target code as follows:
SOURCE CODE :
%{
/* Definition section*/
#include "y.tab.h"
extern yylval;
%}
%%
[0-9]+ {
yylval = atoi(yytext);
return NUMBER;
}
\n { return 0; }
. { return yytext[0]; }
%%
%token NUMBER ID
%left '+''-'
%left '*''/'
%%
E:T {
printf("Result = %d\n", $$);
return 0;
}
T:
T '+' T { $$ = $1 + $3; }
| T '-' T { $$ = $1 - $3; }
| T '*' T { $$ = $1 * $3; }
| T '/' T { $$ = $1 / $3; }
| '-' NUMBER { $$ = -$2; }
| '-' ID { $$ = -$2; }
| '(' T ')' { $$ = $2; }
| NUMBER { $$ = $1; }
| ID { $$ = $1; };
%%
int main()
{
printf("Enter the expression\n");
yyparse();
}
int yyerror(char* s)
{
printf("\n Expression is invalid\n");
}
Input-Output:
$ lex wk-8.l
$ yacc -d wk-8.y
$ cc lex.yy.c y.tab.c -ll
$ ./a.out
Enter the expression
2*(5+3)/2
Result = 8
$ ./a.out
Enter the expression
12/((5-2)*(-8+6))
Result = -2