You are on page 1of 4

2009503536

Intermediate Code Generation for Array List


Ex No: 8
29-02-11
Aim:
To write a lex and yacc program to generate intermediate code for array list.
Description:
An arraylist is a type declaration. It is of the form {array[i1,i2,....in]
where in = i or a[i]}.
The grammar for arraylist is
S -> L '=' E
E -> E + E | E E | E * E | E / E | L
L -> Elist ] | id
Elist -> Elist , E | id [ E
We define a semantic action for each production and generate the
intermediate code for the array list
Source Program:
array.l
%{
#include<stdio.h>
#include"y.tab.h"
%}
%%
[a-z]+ {yylval.s=*yytext; return id;}
[-+*/,;=] {return *yytext;}
"["|"]" { return *yytext;}
\n { return *yytext; };
1

2009503536

[\t]+ ;
%%
array.y
%{
#include<stdio.h>
#include<string.h>
char temp='A';
%}
%union {char s;struct array{ char offset; char place;char arr;int ndim;}ar;}
%token<s>id
%left '+' '-'
%type<ar>L
%type<ar>E
%type<ar>elist
%start S
%%
S : L '=' E
{if($1.offset=='\0')
printf("\n%c = %c",$1.place,$3.place);
else
printf("%c[%c] = %c",$1.place,$1.offset,$3.place);
}
E : E '+' E { $$.place = temp++;
printf("\n%c = %c + %c",$$.place,$1.place,$3.place);
}
| E '-' E { $$.place = temp++;
printf("\n%c = %c - %c",$$.place,$1.place,$3.place);
}
| E '*' E { $$.place = temp++;
printf("\n%c = %c * %c",$$.place,$1.place,$3.place);
}
| E '/' E { $$.place = temp++;
2

2009503536

printf("\n%c = %c / %c",$$.place,$1.place,$3.place);
}
|L
{ $$.place = temp++;
if($1.offset=='\0')
$$.place = $1.place;
else
printf("\n%c = %c[%c]",$$.place,$1.place,$1.offset);
}
L : elist ']'
{ $$.place = temp++;
$$.offset=temp++;
printf("\n%c = C(%c)",$$.place,$1.arr);
printf("\n%c = %c * w[%c]",$$.offset,$1.place,$1.arr);
}
| id{$$.offset='\0'; $$.place=$1;}
elist : elist ',' E
{ $$.arr = $1.arr;
$1.ndim=1;
$$.place = temp++;
printf("\n%c = %c * limit(%d,%c)",$$.place,$1.place,$$.ndim,$$.arr);
printf("\n%c = %c + %c",$$.place,$$.place,$3.place);
}
| id '[' E
{$$.arr = $1;
$$.ndim=1;
$$.place=$3.place;
}
%%
int main()
{
return yyparse();
3

2009503536

}
void yyerror(char *s)
{
printf("%s",s);
}
Sample Output:
a[i] = b[i+j,a[k]]
B = C(a)
C = i * w[a]
F=i+j
H = C(a)
I = k * w[a]
J = H[I]
K = F * limit(1,b)
K=K+J
L = C(b)
M = K * w[b]
N = L[M]
B[C] = N

Result:
Thus the intermediate code has been generated for arraylist and the output is
verified.

You might also like