PARK COLLEGE OF TECHNOLOGY
Karumathampatti, Coimabatore – 641659
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
CS3501-COMPILER DESIGN LABORATORY
RECORD NOTE BOOK
Name of the Student :
Department :
Year & Semester :
Reg. No :
THIS IS TO CERTIFY THAT THIS IS A BONAFIDE RECORD OF WORK DONE BY THE ABOVE
STUDENT LABORATORY DURING THE ________YEAR / ________ SEMESTER
Faculty In-charge Head of the Department
Submitted for the University Practical Examination held on
Internal Examiner External Examiner
CS3501-COMPILER DESIGN LABORATORY
LIST OF EXPERIMENTS :
1. Using the LEX tool, Develop a lexical analyzer to recognize a few patterns in C. (Ex. identifiers,
constants, comments, operators etc.). Create a symbol table, while recognizing identifiers.
2. Implement a Lexical Analyzer using LEX Tool
3. Generate YACC specification for a few syntactic categories.
a. Program to recognize a valid arithmetic expression that uses operator +, -, * and /.
b. Program to recognize a valid variable which starts with a letter followed by any number of
letters or digits.
c. Program to recognize a valid control structures syntax of C language (For loop, while loop, if-
else, if-else-if, switch-case, etc.).
d. Implementation of calculator using LEX and YACC
4. Generate three address code for a simple program using LEX and YACC.
5. Implement type checking using Lex and Yacc.
6. Implement simple code optimization techniques (Constant folding, Strength reduction and
Algebraic transformation)
7. Implement back-end of the compiler for which the three address code is given as input and
the 8086 assembly language code is produced as output.
TOTAL: 60 PERIODS
INDEX
S.No. Date Name of Experiment Page No. Marks Signature
Develop a Lexical Analyzer to
Recognize the Patterns In C
1. 2
(Ex. identifiers, constants, comments,
operators etc.)
Implementation of Lexical Analyzer
2. 5
Using Lex Tool
Program to recognize a Valid
3(a). Arithmetic Expression that 9
uses Operator +, - , * And /.
Program to Recognize a Valid
Variable which Starts with a
3(b). 12
Letter Followed by Any
Number of Letters or Digits
Program to Recognize a Valid
Control Structures Syntax of C
3(c). Language (For Loop,While 14
Loop, If-Else, If- Else-If,
Switch-Case, etc…)
Implementation of Calculator Using
3(d). 18
Lex And Yacc
Generate Three Address Codes for a
4. 22
Simple Program Using Lex and Yacc
Implement Type Check
5. 29
Using Lex and Yacc
Implementation of
Simple Code
6. Optimization 32
Techniques (Constant
Folding.,)
Implementation of Back End of the
7. 36
Compiler
Page | 1
EX NO : 1 DEVELOP A LEXICAL ANALYZER TO RECOGNIZE
THE PATTERNS IN C
DATE : (Ex. identifiers, constants, comments, operators etc.)
AIM :
The main objective is to develop a lexical analyzer to recognize the patterns (Ex. identifiers,
constants, comments, operators etc.) using C program.
ALGORITHM:
1. Start the program.
2. Open the file.
3. Declare the variable and functions.
4. Input: Programming language 'if' statement
Output: A sequence of tokens.
5. Tokens have to be identified and its respective attributes have to be printed.
6. Execute the program
7. Stop the program.
Page | 2
PROGRAM :
#include<stdio.h>
int main()
{
FILE *fp;
char op[20]={'+','-','*','/','%'};
int i,j=0,num=0,flag,f;
char file[20],ch,id[30];
printf("\n\t\t Token Seperation \n\n");
printf("Enter the file name:");
scanf("%s",file);
fp=fopen(file,"r");
while(ch!=EOF)
{
printf("%c",ch);
ch=getc(fp);
}
fclose(fp);
fp=fopen(file,"r");
printf("\n\t Line number \t Token \t\t Type \n");
printf("\n\t ");
while(!feof(fp))
{
flag=0;
ch=fgetc(fp);
i=0;
if(isalpha(ch)||isdigit(ch))
{
f=0;
while(isalpha(ch)||isdigit(ch))
{id[j++]=ch;
ch=fgetc(fp); }
id[j]='\0';
j=0;
if(f==0)
printf("\n\t %d \t\t %s \t\t Identifier",num,id); }
i=0;
while(i<5&&flag!=1)
{
if(ch==op[i])
{
printf("\n\t %d \t\t %c \t\t Operator",num,ch);
flag=1; }
i++; }
i=0;
if(ch=='\n')
num++;
}
fclose(fp);
}
Page | 3
OUTPUT :
INPUT FILE:
[compiler@localhost ~]$ vi sat.txt
a=b*c-d/e
linus@linus:~/Desktop$ gcc lexical.c -o cse
linus@linus:~/Desktop$ ./cse
Token Separation
Enter the file name: sat.txt
a=b*c-d/e
Line number Token Type
0 a Identifier
0 b Identifier
0 * Operator
0 c Identifier
0 - Operator
0 d Identifier
0 / Operator
0 e Identifier
linus@linus:~/Desktop$
RESULT:
Thus the C program to develop a lexical analyzer to recognize the patterns has been executed
successfully.
Page | 4
EX NO : 2 IMPLEMENTATION OF LEXICAL ANALYZER USING LEX
DATE : TOOL
AIM :
The main objective is to implement a lexical analyzer using LEX tool.
ALGORITHM:
1. Start the program.
2. Lex program consists of three parts.
• Declaration %%
• Translation rules %%
• Auxilary procedure.
3. The declaration section includes declaration of variables, maintest, constants and regular
definitions.
4. Translation rule of lex program are statements of the form
• P1 {action}
• P2 {action}
• Pn {action}
5. Write a program in the vi editor and save it with .l extension.
6. Compile the lex program with lex compiler to produce output file as lex.yy.c.
eg $ lex filename.l and $ cc lex.yy.c -ll
7. Compile that file with C compiler and verify the output.
Page | 5
PROGRAM :
/* program name is lexp.l */
%{
/* program to recognize a c program */
int COMMENT=0;
%}
identifier [a-zA-Z][a-zA-Z0-9]*
%%
#.* { printf("\n%s is a PREPROCESSOR DIRECTIVE",yytext);}
int |
float |
char |
double |
while |
for |
do |
if |
break |
continue |
void |
switch |
case |
long |
struct |
const |
typedef |
return |
else |
goto {printf("\n\t%s is a KEYWORD",yytext);}
"/*" {COMMENT = 1;}
"*/" {COMMENT = 0;}
{identifier}\( {if(!COMMENT)printf("\n\nFUNCTION\n\t%s",yytext);}
\{ {if(!COMMENT) printf("\n BLOCK BEGINS");}
\} {if(!COMMENT) printf("\n BLOCK ENDS");}
{identifier}(\[[0-9]*\])? {if(!COMMENT) printf("\n %s IDENTIFIER",yytext);}
\".*\" {if(!COMMENT) printf("\n\t%s is a STRING",yytext);}
[0-9]+ {if(!COMMENT) printf("\n\t%s is a NUMBER",yytext);}
\)(\;)? {if(!COMMENT) printf("\n\t");ECHO;printf("\n");}
\( ECHO;
= {if(!COMMENT)printf("\n\t%s is an ASSIGNMENT OPERATOR",yytext);}
\<= |
\>= |
\< |
== |
\> {if(!COMMENT) printf("\n\t%s is a RELATIONAL OPERATOR",yytext);}
%%
Page | 6
int main(int argc,char **argv)
{
if (argc > 1)
{
FILE *file;
file = fopen(argv[1],"r");
if(!file)
{
printf("could not open %s \n",argv[1]);
exit(0);
}
yyin = file;
}
yylex();
printf("\n\n");
return 0;
}
int yywrap()
{
return 0;
}
hi.c
#include<stdio.h>
int main()
{
int a,b;
}
Page | 7
OUTPUT :
linus@linus:~/Desktop$ lex lex.l
linus@linus:~/Desktop$ gcc lex.
lex.l lex.l~ lex.yy.c
linus@linus:~/Desktop$ gcc lex.yy.c -o aa
linus@linus:~/Desktop$ ./aa hi.c
#include<stdio.h> is a PREPROCESSOR DIRECTIVE
int is a KEYWORD
FUNCTION
main()
BLOCK BEGINS
int is a KEYWORD
a IDENTIFIER,
b IDENTIFIER;
BLOCK ENDS
RESULT:
Thus the above program is compiled and executed successfully and output is verified.
Page | 8
EX NO : 3 (A) PROGRAM TO RECOGNIZE A VALID ARITHMETIC
DATE : EXPRESSION THAT USES OPERATOR +, - , * AND /.
AIM:
To write a Program to recognize a valid arithmetic expression that uses operator +, - , * and /.=
ALGORITHM:
1. Start the program
2. Create the program using YACC tool
3. Create the input file arith_id.y and the file is used to print the valid arithmetic expression.
4. Display the arithmetic expression using yyparse() function
5. Stop the program
Page | 9
PROGRAM :
%{
#include<stdio.h>
#include<ctype.h>
#include<stdlib.h>
%}
%token num let
%left '+' '-'
%left '*' '/'
%%
Stmt : Stmt '\n' { printf("\n..valid expresssion..\n"); exit(0); }
| expr
|
| error '\n' { printf("\n..invalid..\n"); exit(0); }
;
expr : num
| let
| expr '+' expr
| expr '-' expr
| expr '*' expr
| expr '/' expr
| '(' expr ')'
;
%%
main()
{
printf("enter an expression to validate:");
yyparse();
}
yylex()
{
int ch;
while((ch = getchar() ) == ' ');
if(isdigit(ch))
return num;
if(isalpha(ch))
return let;
return ch;
}
yyerror(char *s)
{
printf("%s",s);
}
Page | 10
OUTPUT :
linus@linus:~/Desktop$ yacc -d operator.y
linus@linus:~/Desktop$ gcc y.tab.c -o aa
linus@linus:~/Desktop$ ./aa
enter an expression to validate:4+t
..valid expresssion..
linus@linus:~/Desktop$ ./aa
enter an expression to validate:a+*5
syntax error
..invalid..
linus@linus:~/Desktop$
RESULT:
Thus the above program is compiled and executed successfully and output is verified.
Page | 11
EX NO : 3 (B) PROGRAM TO RECOGNIZE A VALID VARIABLE
WHICH STARTS WITH A LETTER FOLLOWED BY
DATE : ANY NUMBER OF LETTERS OR DIGITS
AIM:
To write a Program to recognize a valid variable which starts with a letter followed by any number
of letters or digits.
PROGRAM :
%{
#include<stdio.h>
#include<ctype.h>
%}
%token let dig
%%
TERM : XTERM '\n' { printf("\n Accepted\n"); }
| error { yyerror("Rejected\n"); } ;
XTERM : XTERM let
| XTERM dig
| let
;
%%
yylex()
{
char ch;
while((ch=getchar())==' ');
if(isalpha(ch))
return let;
if(isdigit(ch))
return dig;
return ch;
}
main()
{
printf("enter a variable:");
yyparse();
}
yyerror(char *s)
{
printf("%s",s);
}
Page | 12
OUTPUT :
linus@linus:~/Desktop$ yacc -d var.y
linus@linus:~/Desktop$ gcc y.tab.c -o aa
linus@linus:~/Desktop$ ./aa
enter a variable:abc12
Accepted
^C
linus@linus:~/Desktop$ ./aa
enter a variable:12abc
syntax error Rejected
Rejected
Rejected
Rejected
Rejected
Rejected
Rejected
RESULT:
Thus the above program is compiled and executed successfully and output is verified.
Page | 13
EX NO : 3 (C) PROGRAM TO RECOGNIZE A VALID CONTROL
STRUCTURES SYNTAX OF C LANGUAGE (FOR
DATE :
LOOP,WHILE LOOP, IF-ELSE, IF-ELSE-IF, SWITCH-
CASE, ETC.)
AIM:
To write a yacc program to validate control structures syntax.
ALGORITHM:
Step1:Start the program.
Step2:Read the statement.
Step4:Validating the given statement according to the rule using yacc.
Step5:Using the syntax rule print the result of the given syntax.
Step6:Stop the program
PROGRAM:
Control.l
%{
#include "y.tab.h"
%}
%%
"for" { return FOR; }
"while" { return WHILE; }
"if" { return IF; }
"else" { return ELSE; }
"switch" { return SWITCH; }
"case" { return CASE; }
"break" { return BREAK; }
"continue" { return CONTINUE; }
"default" { return DEFAULT; }
[a-zA-Z_][a-zA-Z0-9_]* { yylval.str = strdup(yytext); return ID; }
"(" { return '('; }
")" { return ')'; }
"{" { return '{'; }
"}" { return '}'; }
";" { return ';'; }
[ \t\n] ; /* skip whitespace */
. ;
%%
int yywrap() {
return 1;
}
Page | 14
Control.y
%{
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
%}
%token FOR WHILE IF ELSE SWITCH CASE BREAK CONTINUE DEFAULT
%token ID
%%
program:
/* empty */
| program statement '\n' { printf("Statement recognized\n"); }
statement:
for_loop
| while_loop
| if_else
| switch_case
| ID '=' expression ';' { printf("Assignment Statement: %s\n", $1); }
| BREAK ';' { printf("Break Statement\n"); }
| CONTINUE ';' { printf("Continue Statement\n"); }
for_loop:
FOR '(' assignment ';' condition ';' expression ')' statement { printf("For Loop recognized\n"); }
while_loop:
WHILE '(' condition ')' statement { printf("While Loop recognized\n"); }
if_else:
IF '(' condition ')' statement
| IF '(' condition ')' statement ELSE statement { printf("If-Else recognized\n"); }
| IF '(' condition ')' statement ELSE if_else { printf("If-Else-If recognized\n"); }
switch_case:
SWITCH '(' expression ')' '{' case_list '}' { printf("Switch-Case recognized\n"); }
case_list:
/* empty */
| case_list CASE constant_expression ':' statement
assignment:
ID '=' expression
condition:
expression
expression:
ID
| expression '+' expression
| expression '-' expression
| '(' expression ')'
Page | 15
constant_expression:
/* constants or expressions that result in constants */
%%
int main() {
yyparse();
return 0;
}
Input.c
int main() {
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) {
printf("Even: %d\n", i);
} else {
printf("Odd: %d\n", i);
}
}
switch (choice) {
case 1:
printf("You chose 1\n");
break;
case 2:
printf("You chose 2\n");
break;
default:
printf("Invalid choice\n");
}
return 0;
}
OUTPUT
linus@linus:~$ lex control.l
linus@linus:~$ yacc -d control.y
linus@linus:~$ gcc lex.yy.c y.tab.c -o control_parser -ll
linus@linus:~$ ./control_parser < input.c
Statement recognized
For Loop recognized
Assignment Statement: i
Condition recognized
Expression recognized
Statement recognized
If-Else-If recognized
Statement recognized
Break Statement
Statement recognized
Page | 16
Continue Statement
Switch-Case recognized
Case Statement
Statement recognized
Case Statement
Statement recognized
Default Case Statement
Statement recognized
RESULT :
Thus, the given program to recognize valid control structures is executed
successfully.
Page | 17
EX NO : 3 (D) IMPLEMENTATION OF CALCULATOR USING LEX
DATE : AND YACC
AIM :
To write a program to implement a Calculator using LEX and YACC.
ALGORITHM :
1. Start the program
2. Math.h is used to calculate the mathematical functions using LEX and YACC
3. The program is created then defines the possible symbol files in the calci.y file name.
4. Yyparse() is used to parse the input string
5. Yyerror() is used to report the error
6. Stop the program.
Page | 18
PROGRAM :
cal.l
%{
#include <stdlib.h>
#include <stdio.h>
#include "y.tab.h"
void yyerror(char*);
extern int yylval;
%}
%%
[ \t]+ ;
[0-9]+ {yylval = atoi(yytext);
return INTEGER;}
[-+*/] {return *yytext;}
"(" {return *yytext;}
")" {return *yytext;}
\n {return *yytext;}
. {char msg[25];
sprintf(msg,"%s <%s>","invalid character",yytext);
yyerror(msg);
}
cal.y
%{
#include <stdlib.h>
#include <stdio.h>
int yylex(void);
#include "y.tab.h"
%}
%token INTEGER
%%
program:
line program
| line
line:
expr '\n' { printf("%d\n",$1); }
| 'n'
expr:
expr '+' mulex { $$ = $1 + $3; }
| expr '-' mulex { $$ = $1 - $3; }
| mulex { $$ = $1; }
mulex:
mulex '*' term { $$ = $1 * $3; }
| mulex '/' term { $$ = $1 / $3; }
| term { $$ = $1; }
term:
'(' expr ')' { $$ = $2; }
| INTEGER { $$ = $1; }
%%
int yyerror(char *s)
{
Page | 19
fprintf(stderr,"%s\n",s);
return;
}
yywrap()
{
return(1);
}
int main(void)
{
/*yydebug=1;*/
yyparse();
return 0;
}
Page | 20
OUTPUT :
linus@linus:~$ cd Desktop/
linus@linus:~/Desktop$ lex cal.l
linus@linus:~/Desktop$ yacc -d cal.y
linus@linus:~/Desktop$ gcc lex.yy.c y.tab.c
linus@linus:~/Desktop$ ./a.out
10+10
20
4-2
2
2++2
syntax error
linus@linus:~/Desktop$
RESULT:
Thus the above program is compiled and executed successfully and output is verified.
Page | 21
EX NO : 4 GENERATE THREE ADDRESS CODES FOR A
SIMPLE PROGRAM USING LEX AND YACC
DATE :
AIM :
To generate three address codes for a simple program using lex and yacc .
ALGORITHM:
LEX:
1. Declare the required header file and variable declaration with in ‘%{‘ and ‘%}’.
2. LEX requires regular expressions to identify valid arithmetic expression token of lexemes.
3. LEX call yywrap() function after input is over. It should return 1 when work is done or
should return 0 when more processing is required
YACC:
1. Declare the required header file and variable declaration with in ‘%{‘ and ‘%}’.
2. Define tokens in the first section and also define the associativity of the operations
3. Mention the grammar productions and the action for each production.
4. Call yyparse() to initiate the parsing process.
5. yyerror() function is called when all productions in the grammar in second section
doesn't match to the input statement.
6. Make_symtab_entry() function to make the symbol table entry.
Page | 22
PROGRAM :
tac.l
%{
#include"y.tab.h"
#include<stdio.h>
#include<string.h>
int LineNo=1;
%}
identifier [a-zA-Z][_a-zA-Z0-9]*
number [0-9]+|([0-9]*\.[0-9]+)
%%
main ()
return MAIN;
if return IF;
else return ELSE;
while return WHILE;
int |
char |
float return TYPE;
{identifier} {strcpy(yylval.var,yytext);
return VAR;}
{number} {strcpy(yylval.var,yytext);
return NUM;}
\< |
\> |
\>= |
\<= |
== {strcpy(yylval.var,yytext);
return RELOP;}
[ \t] ;
\n LineNo++;
. return yytext[0];
%%
tac.y
%{
#include<string.h>
#include<stdio.h>
struct quad
{
char op[5];
char arg1[10];
char arg2[10];
char result[10];
}QUAD[30];
struct stack
Page | 23
{
int items[100];
int top;
}stk;
int Index=0,tIndex=0,StNo,Ind,tInd;
extern int LineNo;
%}
%union
{
char var[10];
}
%token <var> NUM VAR RELOP
%token MAIN IF ELSE WHILE TYPE
%type <var> EXPR ASSIGNMENT CONDITION IFST ELSEST WHILELOOP
%left '-' '+'
%left '*' '/'
%%
PROGRAM : MAIN BLOCK
;
BLOCK: '{' CODE '}'
;
CODE: BLOCK
| STATEMENT CODE
| STATEMENT
;
STATEMENT: DESCT ';'
| ASSIGNMENT ';'
| CONDST
| WHILEST
;
DESCT: TYPE VARLIST
;
VARLIST: VAR ',' VARLIST
| VAR
;
ASSIGNMENT: VAR '=' EXPR{
strcpy(QUAD[Index].op,"=");
strcpy(QUAD[Index].arg1,$3);
strcpy(QUAD[Index].arg2,"");
strcpy(QUAD[Index].result,$1);
strcpy($$,QUAD[Index++].result);
}
;
EXPR: EXPR '+' EXPR {AddQuadruple("+",$1,$3,$$);}
| EXPR '-' EXPR {AddQuadruple("-",$1,$3,$$);}
| EXPR '*' EXPR {AddQuadruple("*",$1,$3,$$);}
| EXPR '/' EXPR {AddQuadruple("/",$1,$3,$$);}
| '-' EXPR {AddQuadruple("UMIN",$2,"",$$);}
| '(' EXPR ')' {strcpy($$,$2);}
Page | 24
| VAR
| NUM
;
CONDST: IFST{
Ind=pop();
sprintf(QUAD[Ind].result,"%d",Index);
Ind=pop();
sprintf(QUAD[Ind].result,"%d",Index);
}
| IFST ELSEST
;
IFST: IF '(' CONDITION ')' {
strcpy(QUAD[Index].op,"==");
strcpy(QUAD[Index].arg1,$3);
strcpy(QUAD[Index].arg2,"FALSE");
strcpy(QUAD[Index].result,"-1");
push(Index);
Index++;
}
BLOCK {
strcpy(QUAD[Index].op,"GOTO");
strcpy(QUAD[Index].arg1,"");
strcpy(QUAD[Index].arg2,"");
strcpy(QUAD[Index].result,"-1");
push(Index);
Index++;
};
ELSEST: ELSE{
tInd=pop();
Ind=pop();
push(tInd);
sprintf(QUAD[Ind].result,"%d",Index);
}
BLOCK{
Ind=pop();
sprintf(QUAD[Ind].result,"%d",Index);
};
CONDITION: VAR RELOP VAR {AddQuadruple($2,$1,$3,$$);
StNo=Index-1;
}
| VAR
| NUM
;
WHILEST: WHILELOOP{
Ind=pop();
sprintf(QUAD[Ind].result,"%d",StNo);
Ind=pop();
sprintf(QUAD[Ind].result,"%d",Index);
}
;
Page | 25
WHILELOOP: WHILE '(' CONDITION ')' {
strcpy(QUAD[Index].op,"==");
strcpy(QUAD[Index].arg1,$3);
strcpy(QUAD[Index].arg2,"FALSE");
strcpy(QUAD[Index].result,"-1");
push(Index);
Index++;
}
BLOCK {
strcpy(QUAD[Index].op,"GOTO");
strcpy(QUAD[Index].arg1,"");
strcpy(QUAD[Index].arg2,"");
strcpy(QUAD[Index].result,"-1");
push(Index);
Index++;
}
;
%%
extern FILE *yyin;
int main(int argc,char *argv[])
{
FILE *fp;
int i;
if(argc>1)
{
fp=fopen(argv[1],"r");
if(!fp)
{
printf("\n File not found");
}
yyin=fp;
}
yyparse();
printf("\n\n\t\t ----------------------------""\n\t\t Pos Operator Arg1 Arg2 Result"
"\n\t\t ");
for(i=0;i<Index;i++)
{
printf("\n\t\t %d\t %s\t %s\t %s\t%s",i,QUAD[i].op,QUAD[i].arg1,QUAD[i].arg2,QUAD[i].result);
}
printf("\n\t\t ------- ");
printf("\n\n");
return 0;
}
void push(int data)
{
stk.top++;
if(stk.top==100)
{
printf("\n Stack overflow\n");
Page | 26
stk.items[stk.top]=data;
}
int pop()
{
int data;
if(stk.top==-1)
{
printf("\n Stack underflow\n");
exit(0);
}
data=stk.items[stk.top--];
return data;
}
void AddQuadruple(char op[5],char arg1[10],char arg2[10],char result[10])
{
strcpy(QUAD[Index].op,op);
strcpy(QUAD[Index].arg1,arg1);
strcpy(QUAD[Index].arg2,arg2);
sprintf(QUAD[Index].result,"t%d",tIndex++);
strcpy(result,QUAD[Index++].result);
}
yyerror()
{
printf("\n Error on line no:%d",LineNo);
}
yywrap()
{
return(1);
}
Page | 27
OUTPUT :
linus@linus:~/Desktop$ ./aa test.c
linus@linus:~/Desktop$ lex tac.l
linus@linus:~/Desktop$ yacc -d tac.y
linus@linus:~/Desktop$ gcc lex.yy.c y.tab.c -o aa
------------------------------------------------------------------------
Pos Operator Arg1 Arg2 Result
------------------------------------------------------------------------
0 < a b t0
1 == t0 FALSE 5
2 + a b t1
3 = t1 a
4 GOTO 5
5 < a b t2
6 == t2 FALSE 10
7 + a b t3
8 = t3 a
9 GOTO 5
10 <= a b t4
11 == t4 FALSE 15
12 - a b t5
13 = t5 c
14 GOTO 17
15 + a b t6
16 = t6 c
-----------------------------------------------------------------------
RESULT :
Thus the program to generate three address codes for a simple program using lex and yacc .
has been implemented successfully.
Page | 28
EX NO : 5
IMPLEMENT TYPE CHECKING
DATE : USING LEX AND YACC
AIM :
The main objective of this C program is to implement type checking.
ALGORITHM:
1. Start the program.
2. Declare the variable and functions.
3. Input: Programming language structure is created.
4. Check the file type.
5. Execute the program
6. Stop the program
Page | 29
PROGRAM :
#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
int main(int argc,char*argv[])
{
int i;
struct stat buf;
for(i=1;i<argc;i++)
{
if(lstat(argv[i],&buf)<0)
printf("lstat error!\n");
else if(S_ISREG(buf.st_mode))
printf("regular file!\n");
else if(S_ISDIR(buf.st_mode))
printf("Directory file!\n");
else if(S_ISCHR(buf.st_mode))
printf("character device file!\n");
else if(S_ISFIFO(buf.st_mode))
printf("FIFO file!\n");
else
printf("socket file\n");
}
}
Page | 30
OUTPUT :
linus@linus:~$ gcc typechecking.c -o qq
linus@linus:~$ ./qq
linus@linus:~$ ./qq aa.odt
regular file!
linus@linus:~$ ./qq Examples
lstat error!
linus@linus:~$ ./qq os
Directory file!
linus@linus:~$ ./qq ss.png
regular file!
linus@linus:~$
RESULT:
Thus the C program is to implement type checking has been implemented.
Page | 31
EX NO : 6 IMPLEMENTATION OF SIMPLE CODE
DATE : OPTIMIZATION TECHNIQUES (Constant Folding.,)
AIM :
The main objective is to write a C program to implement code optimization techniques.
OUTCOME:
This program displays intermediate code as the output of constant folding.
SAMPLE PROGRAM TITLE:
Implement a C program to find the number of whitespaces and newline characters.
ALGORITHM:
1. Start the program.
2. Declare the variables and structures.
3. Write the generated code into output definition of the file.
4. Print the output.
5. Stop the program.
Page | 32
PROGRAM:
#include<stdio.h>
#include<unistd.h>
#include<string.h>
#include<termios.h>
struct op
{
char l;
char r[20];
}op[10],pr[10];
void main()
{
int a,i,k,j,n,z=0,m,q;
char *p,*l;
char temp,t;
char *tem;
printf("Enter the Number of Values:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("left: ");
op[i].l=getchar();
printf("\tright: ");
scanf("%s",op[i].r);
}
printf("Intermediate Code\n") ;
for(i=0;i<n;i++)
{
printf("%c=",op[i].l);
printf("%s\n",op[i].r);
}
for(i=0;i<n-1;i++)
{
temp=op[i].l;
for(j=0;j<n;j++)
{
p=strchr(op[j].r,temp);
if(p)
{
pr[z].l=op[i].l;
strcpy(pr[z].r,op[i].r);
z++;
}}}
pr[z].l=op[n-1].l;
strcpy(pr[z].r,op[n-1].r);
z++;
printf("\nAfter Dead Code Elimination\n");
for(k=0;k<z;k++)
{
Page | 33
printf("%c\t=",pr[k].l);
printf("%s\n",pr[k].r);
}
for(m=0;m<z;m++)
{
tem=pr[m].r;
for(j=m+1;j<z;j++)
{
p=strstr(tem,pr[j].r);
if(p)
{
t=pr[j].l;
pr[j].l=pr[m].l;
for(i=0;i<z;i++)
{
l=strchr(pr[i].r,t) ;
if(l)
{
a=l-pr[i].r;
printf("pos: %d",a);
pr[i].r[a]=pr[m].l;
}}}}}
printf("Eliminate Common Expression\n");
for(i=0;i<z;i++)
{
printf("%c\t=",pr[i].l);
printf("%s\n",pr[i].r);
}
for(i=0;i<z;i++)
{
for(j=i+1;j<z;j++)
{
q=strcmp(pr[i].r,pr[j].r);
if((pr[i].l==pr[j].l)&&!q)
{
pr[i].l='\0';
strcpy(pr[i].r,'\0');
}}}
printf("Optimized Code\n");
for(i=0;i<z;i++)
{
if(pr[i].l!='\0')
{
printf("%c=",pr[i].l);
printf("%s\n",pr[i].r);
}}}
Page | 34
OUTPUT:
Enter the Number of Values:5
Left: a right: 9
Left: b right: c+d
Left: e right: c+d
Left: f right: b+e
Left: r right: f
Intermediate Code
a=9
b=c+d
e=c+d
f=b+e
r=:f
After Dead Code Elimination
=f
Eliminate Common Expression
=f
Optimized Code
=f
RESULT:
Thus the C program to implement code optimization technique has been executed successfully.
Page | 35
EX NO : 7
IMPLEMENTATION OF BACK END OF THE COMPILER
DATE :
AIM :
The main objective is to write a C program to implement of back end of the compiler which takes
the three address code and produces the 8086 assembly language instructions that can be assembled and
run using a 8086 assembler. The target assembly instructions can be simple move, add, sub, jump. Also
simple addressing modes are used.
ALGORITHM:
1- Start the program and open the file.
2- Get address code sequence.
3- Determine current location of 3 using address (for 1st operand).
4- If current location not already exist generate move (B,O).
5- Update address of operand and Import the files
6- Store the move instruction in memory
7- Stop
Page | 36
PROGRAM:
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
void main()
{
int i=2,j=0,k=2,k1=0;
char ip[10],kk[10];
FILE*fp;
printf("\n enter the filename of the intermediate code");
scanf("%s",&kk);
fp=fopen(kk,"r");
if(fp==NULL)
{
printf("\n Error in opening the file");
}
while(!feof(fp))
{
fscanf(fp,"%s/n",ip);
printf("\t\t%s\n",ip);
}
rewind(fp);
printf("\n ------------- \n");
printf("\t statement \t\t target code\n");
while(!feof(fp))
{
fscanf(fp,"%s",ip);
printf("\t%s",ip);
printf("\t\t MOV%c,R%d\n\t",ip[i+k],j);
if(ip[i+1]=='+')
printf("\t\tADD");
else
printf("\t\tSUB");
if(islower(ip[i]))
printf("%c,R%d\n\n",ip[i+k1],j);
else
printf("%c,%c\n",ip[i],ip[i+2]);
j++;
k1=2;
k=0;
}
printf("\n \n");
fclose(fp);
}
Page | 37
OUTPUT :
Enter the filename of intermediate code : b.txt
x=a-b
y=a-c
z=a+b
c=A-B
c=A-B
Statement Target code
x=a-b Mov,R0
SUBa,R0
y=a-c MOVa,R1
SUBc,R1
z=a+b MOCa,R2
ADDb,R2
c=A-B MOVa,R4
SUBA,B
c=A-B MOVA,R5
SUBA,B
RESULT:
Thus the C program to implement Back end compiler using 8086 assembler has been executed
successfully.
Page | 38