Kavi Assign6
Kavi Assign6
Programming Assignment-6
Generate intermediate code using Lex and Yacc Tools
Name : Kavidhesh G
Reg No : 3122 21 5001 042
Develop an intermediate code generator to generate three address code for the following
statements by writing suitable syntax directed translation rules
1. Assignment statements
2. Boolean expressions
Aim
To Develop an intermediate code generator to generate three address code for the
Assignment statements Boolean expressions.
Code
Input.txt
a := b * -c + b* -c
Intermediate.y
%{
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
if (strcmp(op, "=") == 0) {
} else if (arg2) {
} else {
void emit_if_goto(const char* op, const char* arg1, const char* arg2, const char* label) {
int yylex();
%}
%token <id> ID
%left OR
%left AND
%nonassoc LT
%left PLUS MINUS
%%
stmt_list:
stmt:
assignment | boolean_expr ;
assignment:
expr:
expr PLUS expr { int t = new_temp(); char temp[10]; sprintf(temp, "t%d", t); emit("+", $1,
$3, temp); $$ = strdup(temp); }
| expr MINUS expr { int t = new_temp(); char temp[10]; sprintf(temp, "t%d", t); emit("-", $1,
$3, temp); $$ = strdup(temp); }
| expr MULT expr { int t = new_temp(); char temp[10]; sprintf(temp, "t%d", t); emit("*", $1,
$3, temp); $$ = strdup(temp); }
| expr DIV expr { int t = new_temp(); char temp[10]; sprintf(temp, "t%d", t); emit("/", $1, $3,
temp); $$ = strdup(temp); }
| MINUS expr %prec UMINUS { int t = new_temp(); char temp[10]; sprintf(temp, "t%d", t);
emit("-", $2, NULL, temp); $$ = strdup(temp); }
| ID { $$ = strdup($1); }
;
boolean_expr:
| expr OR expr { int t = new_temp(); char temp[10]; sprintf(temp, "t%d", t); emit("or", $1,
$3, temp); $$ = strdup(temp); }
| expr AND expr { int t = new_temp(); char temp[10]; sprintf(temp, "t%d", t); emit("and", $1,
$3, temp); $$ = strdup(temp); }
%%
int main() {
return yyparse();
Intermediate.l
%{
#include "intermediate.tab.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
%}
%%
"and" { return AND; }
"or" { return OR; }
":=" { return ASSIGN; }
"+" { return PLUS; }
"-" { return MINUS; }
"*" { return MULT; }
"/" { return DIV; }
"<" { return LT; }
"(" { return LPAREN; }
")" { return RPAREN; }
";" { return SEMICOLON; }
[0-9]+ { yylval.num = atoi(yytext); return NUM; }
[a-zA-Z][a-zA-Z0-9]* { yylval.id = strdup(yytext); return ID; }
[ \t\n]+ { /* ignore whitespace */ }
. { printf("Unknown character: %s\n", yytext); }
%%
int yywrap() {
return 1;
}
Output
Input 1 : result := a / (b - c) + d * -e
Input 2 : a := b * -c + b* -c
Learning Outcome