CD Lab Manual SN76 - Merged
CD Lab Manual SN76 - Merged
DATE:
AIM:
To write a program to generate three address code for simple expression using LEX and YACC tool.
ALGORITHM:
LEX
4. Declare the required header file and variable declaration with in ‘%{‘ and ‘%}’.
5. LEX requires regular expressions or patterns to identify token of lexemes for recognize a valid
variable.
6. Lex call yywrap() function after input is over. It should return 1 when work is done or should
return 0when more processing is required.
YACC
7. Declare the required header file and variable declaration with in ‘%{‘ and ‘%}’.
8. Define tokens in the first section and also define the associativity of the operations
9. Mention the grammar productions and the action for each production.
10. $$ refer to the top of the stack position while $1 for the first value, $2 for the second value in the
stack.
11. Call yyparse() to initiate the parsing process.
12. yyerror() function is called when all productions in the grammar in second section doesn't
match to theinput statement.
PROGRAM:
Type.l
%{
#include "y.tab.h"
%}
%%
[0-9]+(\.[0-9]+)? {
yylval.dval = atof(yytext);
return NUMBER;
}
[+-/*] {
return *yytext;
}
[ \t\n]
.{
return *yytext;
}
%%
int yywrap()
{
return 1;
}
Type.y
%{
#include <stdio.h>
%}
%union {
double dval;
}
%token <dval> NUMBER
%left '+' '-'
%left '*' '/'
%type <dval> expr
%%
input: /* empty */
| input line
;
expr: NUMBER
| expr '+' expr {
$$ = $1 + $3;
}
| expr '-' expr {
$$ = $1 - $3;
}
| expr '*' expr {
$$ = $1 * $3;
}
| expr '/' expr {
if ($3 == 0) {
printf("Error: Division by zero\n");
}
$$ = $1 / $3;
}
;
%%
int main() {
yyparse();
return 0;
}
int yyerror()
{
printf("mismatch type \n");
}
OUTPUT:
D:\compiler>lex type.l
D:\compiler>yacc -d type.y
D:\compiler>gcc lex.yy.c y.tab.c
D:\compiler>a.exe
8.0
8+7.0
mismatch type
RESULT :
Thus the output is executed for type checking using lex and yacc.