0% found this document useful (0 votes)
11 views52 pages

CD LAB MANUAL (1)

The document outlines a series of experiments related to lexical analysis and syntax analysis using C programming, LEX, and YACC tools. It includes the development of a lexical analyzer, implementation of a calculator, generation of YACC specifications for syntactic categories, and validation of control structures in C. Each experiment provides an aim, introduction, algorithm, program code, and results, demonstrating successful execution and verification of outputs.

Uploaded by

Annie
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views52 pages

CD LAB MANUAL (1)

The document outlines a series of experiments related to lexical analysis and syntax analysis using C programming, LEX, and YACC tools. It includes the development of a lexical analyzer, implementation of a calculator, generation of YACC specifications for syntactic categories, and validation of control structures in C. Each experiment provides an aim, introduction, algorithm, program code, and results, demonstrating successful execution and verification of outputs.

Uploaded by

Annie
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

INDEX

S.No DATE NAME OF THE EXPERIMENT PAGE NO REMARKS SIGN

1 Develop a lexical analyser to recognize


a few patterns in C

2 Implementation of lexical analyzer


using lex tool

Generate yacc specification for a few


3a syntactic categories:
Arithmetic expression that uses
operator
+,-,* and /.

3b Program to recognize a valid variable


which starts with a letter followed by
any number of letter or digital

Program to recognize a valid control


3c structure syntax of C language (For
loop, While loop, If-else, If-else-if,
Switch-Case, etc..)

3d Implementation of calculator using


LEX and YACC

4 Generate three address code for a


simple program

Implementation of Type
5
Checking

6 Implementation of Simple code


optimization

7 Implement the back end of the


compiler
EX. NO:1
DATE:
DEVELOP A LEXICAL ANALYZER TO RECOGNIZE
A FEW PATTERNS IN C

AIM:
To Write a C program to develop a lexical analyzer to recognize a few patterns in C.

INTRODUCTION:
Lexical analysis is the process of converting a sequence of characters (such as in a
computer program of web page) into a sequence of tokens (strings with an identified
“meaning”). A program that perform lexical analysis may be called a lexer, tokenize or
scanner.

TOKEN
A token is a structure representing a lexeme that explicitly indicates its
categorization for the Purpose of parsing. A category of token is what in linguistics
might be called a part-of- speech. Examples of token categories may include
“identifier” and “integer literal”, although the set of Token differ in different
programming languages.
The process of forming tokens from an input stream of characters is called tokenization.

Consider this expression in the C programming


language: Sum=3 + 2;
Tokenized and represented by the following table:

Lexem Token category


e
Sum “identifier”
= “assignment operator”
3 “integer literal”
+ “addition operator”
2 “integer literal”
; “end of the statement”

ALGORITHM:

1. Start the program


2. Include the header files.
3. Allocate memory for the variable by dynamic memory allocation function.
4. Use the file accessing functions to read the file.
5. Get the input file from the user.
6. Separate all the file contents as tokens and match it with the functions.
7. Define all the keywords in a separate file and name it as key.c
8. Define all the operators in a separate file and name it as open.c
9. Give the input program in a file and name it as input.c
10. Finally print the output after recognizing all the tokens.
11. Stop the program.

PROGRAM: (DEVELOP A LEXICAL ANALYZER TO RECOGNIZE A FEW


PATTERNS IN C)

#include<stdio.h>
#include<conio.h>
#include<ctype.h>
#include<string.h>
void main()
{
FILE *fi,*fo,*fop,*fk;int
flag=0,i=1;
char c,t,a[15],ch[15],file[20];clrscr();
printf("\n Enter the File Name:");
scanf("%s",&file);
fi=fopen(file,"r")
fo=fopen("inter.c","w");
fop=fopen("oper.c","r");
fk=fopen("key.c","r");
c=getc(fi); while(!feof(fi))
{
if(isalpha(c)||isdigit(c)||(c=='['||c==']'||c=='.'==1))fputc(c,fo);
else
{
if(c=='\n') fprintf(fo,"\t$\t");
else fprintf(fo,"\t%c\t",c);
}
c=getc(fi);
}
fclose(fi);
fclose(fo);
fi=fopen("inter.c","r"); printf("\n Lexical
Analysis");fscanf(fi,"%s",a);
printf("\n Line: %d\n",i++);
while(!feof(fi))
{
if(strcmp(a,"$")==0)
{
printf("\n Line: %d \n",i++);
fscanf(fi,"%s",a);
}
fscanf(fop,"%s",ch);
while(!feof(fop))
{
if(strcmp(ch,a)==0)
{
fscanf(fop,"%s",ch); printf("\t\t%s\t:\t%s\n",a,ch);
flag=1;
} fscanf(fop,"%s",ch);
}
rewind(fop);
fscanf(fk,"%s",ch);
while(!feof(fk))
{
if(strcmp(ch,a)==0)
{
fscanf(fk,"%k",ch);
printf("\t\t%s\t:\tKeyword\n",a);flag=1;
}
fscanf(fk,"%s",ch);
}
rewind(fk);
if(flag==0)
{
if(isdigit(a[0])) printf("\t\t%s\t:\tConstant\n",a);
else
printf("\t\t%s\t:\tIdentifier\n",a);
}
flag=0; fscanf(fi,"%s",a); }
getch();
}
Key.C:
int void
main
char
if for
while
else
printf
scanf
FILE
Include
stdio.h
conio.h
iostream.h
Oper.C:
( open para
) closepara
{ openbrace
} closebrace
< lesser
> greater
" doublequote ' singlequote
: colon
; semicolon
# preprocessor
= equal
== asign
% percentage
^ bitwise
& reference
* star
+ add
- sub
\ backslash
/ slash

Input.C:
#include "stdio.h"
#include "conio.h" void
main()
{
int a=10,b,c;
a=b*c;
getch();
}
OUTPUT:

RESULT:

Thus the above program for developing the lexical the lexical analyzer and
recognizingthe few pattern s in C is executed successfully and the output is verified.
EX.NO:2
DATE:

IMPLEMENTATION OF LEXICAL ANALYZER USING LEX TOOL

AIM:

To write a program to implement the Lexical Analyzer using lex tool.

INTRODUCTION:

THEORY:

 A language for specifying lexical analyzer.


 There is a wide range of tools for construction of lexical analyzer. The
majority ofthese tools are based on regular expressions.
 The one of the traditional tools of that kind is lex.
LEX:
 The lex is used in the manner depicted. A specification of the lexical
analyzer is preferred by creating a program lex.1 in the lex language.
 Then lex.1 is run through the lex compiler to produce a „c‟ program lex.yy.c.
 The program lex.yy.c consists of a tabular representation of a transition
diagram constructed from the regular expression of lex.1 together with a
standard routine thatuses table of recognize leximes.
 Lex.yy.c is run through the „C‟ compiler to produce as object program a.out,
which is the lexical analyzer that transform as input stream into sequence of
tokens.

LEX SOURCE:
ALGORITHM:

1. Start the program


2. Lex program consists of three parts.
3. Declaration %%
4. Translation rules %%
5. Auxiliary procedure.
6. The declaration section includes declaration of variables, main test,
constants and regular
7. Definitions.
8. Translation rule of lex program are statements of the form
9. P1{action}
10. P2{action
} 11. …..
12. …..
13. Pn{action}
14. Write program in the vi editor and save it with .1 extension.
15. Compile the lex program with lex compiler to produce output file as lex.yy.c.
16. Eg. $ lex filename.1
17. $gcc lex.yy.c-11
18. Compile that file with C compiler and verify the output.

PROGRAM: (LEXICAL ANALYZER USING LEX TOOL)

#include<stdio.h>
#include<ctype.h>
#include<conio.h>
#include<string.h> char
vars[100][100];int vcnt;
char input[1000],c; char
token[50],tlen;
int state=0,pos=0,i=0,id; char
*getAddress(char str[])
{
for(i=0;i<vcnt;i++)
if(strcmp(str,vars[i])==0)
return vars[i];
strcpy(vars[vcnt],str);return
vars[vcnt++];
}
int isrelop(char c)
{
if(c=='+'||c=='-'||c=='*'||c=='/'||c=='%'||c=='^')return 1;
else return
0;
}
int main(void)
{
clrscr();
printf("Enter the Input String:");gets(input);
do
{
c=input[pos];
putchar(c);
switch(state)
{
case 0:
if(isspace(c))
printf("\b");
if(isalpha(c))
{
token[0]=c;
tlen=1;
state=1;
}
if(isdigit(c))
state=2;
if(isrelop(c))
state=3; if(c==';')
printf("\t<3,3>\n");
if(c=='=')
printf("\t<4,4>\n");break;
case 1:
if(!isalnum(c))
{
token[tlen]='\o'; printf("\b\t<1,%p>\n",getAddress(token));
state=0;
pos--;
}
else token[tlen++]=c;
break;
case 2: if(!isdigit(c))
{
printf("\b\t<2,%p>\n",&input[pos]);state=0;
pos--;
}
break;
case 3:
id=input[pos-1];
if(c=='=')
printf("\t<%d,%d>\n",id*10,id*10);else{
printf("\b\t<%d,%d>\n",id,id);
pos--;
}state=0;
break;
}
pos++;
}
while(c!=0);
getch();
return 0;
}
OUTPUT:

RESULT:

Thus the program for the exercise on lexical analysis using lex has been
successfullyexecuted and output is verified.
EX.NO:3
DATE:

GENERATE YACC SPECIFICATION FOR A FEW


SYNTACTICCATEGORIES.

AIM :
To write a c program to do exercise on syntax analysis using YACC.
INTRODUCTION :
YACC (yet another compiler) is a program designed to produce designed to
compile a LALR (1) grammar and to produce the source code of the synthetically
analyses of the language produced by the grammar.

ALGORITHM :
1. Start the program.
2. Write the code for parser. l in the declaration port.
3. Write the code for the „y‟ parser.
4. Also write the code for different arithmetical operations.
5. Write additional code to print the result of computation.
6. Execute and verify it.
7. Stop the program.

A) PROGRAM TO RECOGNIZE A VALID ARITHMETIC EXPRESSION


THAT USES OPERATOR +, - , * AND /.

PROGRAM:
#include<stdio.h>
#include<conio.h>
void main()
{ char s[5];
clrscr();
printf("\n Enter any operator:");gets(s);
switch(s[0])
{
case'>': if(s[1]=='=')
printf("\n Greater than or equal");else
printf("\n Greater than");break;
case'<': if(s[1] =='=')

printf("\n Less than or equal");elseprintf("\nLess


than"); break;
case'=': if(s[1]=='=')
printf("\nEqual to"); else
printf("\nAssignment");
break; case'!':
if(s[1]=='=')
printf("\nNot Equal");else
printf("\n Bit Not");break;
case'&': if(s[1]=='&')
printf("\nLogical AND");else
printf("\n Bitwise AND");break;
case'|': if(s[1]=='|')
printf("\nLogical OR");else
printf("\nBitwise OR");break;
case'+': printf("\n Addition");break;
case'-': printf("\nSubstraction");break;
case'*': printf("\nMultiplication");break;
case'/': printf("\nDivision");
break;
case'%': printf("Modulus");
break;
default: printf("\n Not a operator");
}
getch();
}
OUTPUT:

RESULT:

Thus the program for the exercise on the syntax using YACC has been executed
successfully and Output is verified.
B) PROGRAM TO RECOGNISE A VALID VARIABLE WHICH
STARTSWITH A LETTER FOLLOWED BY ANY NUMBER OF
LETTERS ORDIGITS

PROGRAM :
variable_test.l

%{
/* This LEX program returns the tokens for the Expression */#include "y.tab.h"
%}
%%
"int " {return INT;} "float"
{return FLOAT;} "double"
{return DOUBLE;}[a-zA-Z]*[0-
9]*{
printf("\nIdentifier is %s",yytext);return ID;
}
return yytext[0];
\n return 0;int
yywrap()
{
return 1;
}

variable_test.y

%{
#include
/* This YACC program is for recognising the Expression*/
%}
%token ID INT FLOAT DOUBLE
%%
D;T L
; L:L,ID
|ID
;
T:INT
|FLOAT
|DOUBLE
;
%%
extern FILE *yyin;
main()
{
do
{
yyparse();
}while(!feof(yyin));
}
yyerror(char*s)
{
}

OUTPUT:

RESULT:

Thus the program for the exercise on the syntax using YACC has been executed
successfully and Output is verified.
C) PROGRAM TO RECOGNIZE A VALID CONTROL STRUCTURES
SYNTAX OF C LANGUAGE (FOR 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.
Step3: Validating the given statement according to the rule using yacc.
Step4: Using the syntax rule print the result of the given syntax.
Step5: Stop the program.

PROGRAM:
FOR LOOP
LEX PART : for.l

%{
#include<stdio.h>
#include "y.tab.h"
%}
alpha [A-Za-z]
digit [0-9]
%%
[\t \n] for
return FOR;
{digit}+ return NUM;
{alpha}({alpha}|{digit})* return ID;
"<=" return LE;
">=" return GE;
"==" return EQ;
"!=" return NE;
"||" return OR;
"&&" return AND;
. return yytext[0];
%%
yywrap()
{}
YACC PART : for.y
%{
#include <stdio.h>
#include <stdlib.h>
%}
%token ID NUM FOR LE GE EQ NE OR AND
%right '='
%left OR AND
%left '>' '<' LE GE EQ NE
%left '+' '-'
%left '*' '/'
%right UMINUS
%left '!'
%%
S : ST {printf("Input accepted\n"); exit(0);};
ST : FOR '(' E ';' E2 ';' E ')' DEF
;
DEF : '{' BODY '}'
| E';'
| ST
|
;
BODY : BODY BODY
| E ';'
| ST
|
;
E : ID '=' E
| E '+' E
| E '-' E
| E '*' E
| E '/' E
| E '<' E
| E '>' E
| E LE E
| E GE E
| E EQ E
| E NE E
| E OR E
| E AND E
| E '+' '+'
| E '-' '-'
| ID
| NUM
;
E2 : E'<'E | E'>'E
| E LE E
| E GE E
| E EQ E
| E NE E
| E OR E
| E AND E
;
%%
main() {
printf("Enter the
expression:\n"); yyparse(); }
yyerror() {
printf("\nEntered arithmetic expression is Invalid\n\n");
}

OUTPUT:
$:lex for.l
$:yacc for.y
$:cc lex.yy.c y.tab.h $:./a.out

PROGRAM:
WHILE LOOP
LEX PART : while.l
%{
#include<stdio.h>
#include "y.tab.h"
%}
alpha [A-Za-z]
digit [0-9]
%%
[\t \n]
while return WHILE;
{digit}+ return NUM;
{alpha}({alpha}|{digit})* return ID;
"<=" return LE;
">=" return GE;
"==" return EQ;
"!=" return NE;
"||" return OR;
"&&" return AND;
. return yytext[0];
%%
yywrap()
{}
YACC PART :while.y
%{
#include <stdio.h>
#include <stdlib.h>
%}
%token ID NUM WHILE LE GE EQ NE OR AND
%right '='
%left AND OR
%left '<' '>' LE GE EQ NE
%left '+''-'
%left '*''/'
%right UMINUS
%left '!'
%%
S : ST1 {printf("Input accepted.\n");exit(0);};
ST1 : WHILE'(' E2 ')' '{' ST '}'
ST : ST ST
| E';'
;
E : ID'='E
| E'+'E
| E'-'E
| E'*'E
| E'/'E
| E'<'E
| E'>'E
| E LE E
| E GE E
| E EQ E
| E NE E
| E OR E
| E AND E
| ID
| NUM
;
E2 : E'<'E
| E'>'E
| E LE E
| E GE E
| E EQ E
| E NE E
| E OR E
| E AND E
| ID
| NUM
;
%%
main()
{
printf("Enter the exp: ");
yyparse();
}
yyerror()
{
printf("\nEntered arithmetic expression is Invalid\n\n");
}

OUTPUT:
$:lex while.l
$:yacc while.y
$:cc lex.yy.c y.tab.h
$:./a.out

PROGRAM:
IF THEN ELSE
LEX PART : if.l

%{
#include<stdio.h>
#include "y.tab.h"
%}

alpha [A-Za-z]
digit [0-9]
%%
[ \t\n]
if return IF; then
return THEN; else
return ELSE; {digit}+
return NUM;
{alpha}({alpha}|{digit})* return ID;
"<=" return LE;
">=" return GE;
"==" return EQ;
"!=" return NE;
"||" return OR;
"&&" return AND;
. return yytext[0];
%%
yywrap()
{}

YACC PART : if.y

%{
#include <stdio.h>
#include <stdlib.h>
%}
%token ID NUM IF THEN LE GE EQ NE OR AND ELSE

%right '='
%left AND OR
%left '<' '>' LE GE EQ NE
%left '+''-'
%left '*''/'
%right UMINUS
%left '!'
%%
S : ST {printf("Input accepted.\n");exit(0);};
ST : IF '(' E2 ')' THEN ST1';' ELSE ST1';'
| IF '(' E2 ')' THEN ST1';'
;
ST1 : ST
|E
;
E : ID'='E
| E'+'E
| E'-'E
| E'*'E
| E'/'E
| E'<'E
| E'>'E
| E LE E
| E GE E
| E EQ E
| E NE E
| E OR E
| E AND E
| ID
| NUM
;
E2 : E'<'E
| E'>'E
| E LE E
| E GE E
| E EQ E
| E NE E
| E OR E
| E AND E
| ID
| NUM
;
%%
main()
{
printf("Enter the exp: ");
yyparse();
}
yyerror()
{
printf("\nEntered arithmetic expression is Invalid\n\n");
}

OUTPUT:
$:lex if.l
$:yacc if.y
$:cc lex.yy.c y.tab.h
$:./a.out
PROGRAM:
IF THEN ELSEIF THEN ELSE
LEX PART : elseif.l

%{
#include<stdio.h>
#include "y.tab.h"
%}
alpha [A-Za-z]
digit [0-9]
%%
[ \t\n]
if return IF; then
return THEN; else
return ELSE; elseif
return ELSEIF;
{digit}+ return
NUM;
{alpha}({alpha}|{digit})* return ID;
"<=" return LE;
">=" return GE;
"==" return EQ;
"!=" return NE;
"||" return OR;
"&&" return AND;
. return yytext[0];
%%
yywrap()
{} YACC
PART :
elseif.y
%{
#include <stdio.h>
#include <stdlib.h>

%}
%token ID NUM IF THEN LE GE EQ NE OR AND ELSE
%right '='
%left AND OR
%left '<' '>' LE GE EQ NE
%left '+''-'
%left '*''/'
%right UMINUS
%left '!'
%%
S : ST {printf("Input accepted.\n");exit(0);};
ST : IF '(' E2 ')' THEN ST1';' ELSEIF '(' E2 ')' THEN ST1';' ELSE ST1';'
| IF '(' E2 ')' THEN ST1';'
;
ST1 : ST
|E
;
E : ID'='E
| E'+'E
| E'-'E
| E'*'E
| E'/'E
| E'<'E
| E'>'E
| E LE E
| E GE E
| E EQ E
| E NE E
| E OR E
| E AND E
| ID
| NUM
;
E2 : E'<'E
| E'>'E
| E LE E
| E GE E
| E EQ E
| E NE E
| E OR E
| E AND E
| ID
| NUM
;
%%
main()
{
printf("Enter the exp: ");
yyparse();
}
yyerror()
{
printf("\nEntered arithmetic expression is Invalid\n\n");
}

OUTPUT:
$:lex elseif.l
$:yacc elseif.y
$:cc lex.yy.c y.tab.h
$:./a.out
RESULT:

Thus the program has been executed successfully and verified.

PROGRAM:
SWITCH
LEX PART : switch.l

%{
#include<stdio.h>
#include "y.tab.h"
%}
alpha [A-Za-z]
digit [0-9]
%%
[ \n\t] if return IF;
then return THEN;
while return WHILE;
switch return SWITCH;
case return CASE;
default return
DEFAULT; break
return BREAK;
{digit}+ return NUM;
{alpha}({alpha}|{digit})* return ID;
"<=" return LE;
">=" return GE;
"==" return EQ;
"!=" return NE;
"&&" return AND;
"||" return OR;
. return yytext[0];
%%
yywrap(){}

YACC PART : switch.y

%{
#include<stdio.h>
#include<stdlib.h>
%}
%token ID NUM SWITCH CASE DEFAULT BREAK LE GE EQ NE AND OR IF THEN
WHILE
%right '='
%left AND OR
%left '<' '>' LE GE EQ NE
%left '+''-'
%left '*''/'
%right UMINUS
%left '!'
%%
S : ST{printf("\nInput accepted.\n");exit(0);};
;
ST : SWITCH'('ID')''{'B'}'
;
B : C
| CD
;
C : CC
| CASE NUM':'ST1 BREAK';'
;
D : DEFAULT':'ST1 BREAK';'
| DEFAULT':'ST1
;
ST1 : WHILE'('E2')' E';'
| IF'('E2')'THEN E';'
| ST1 ST1
| E';'
;
E2 : E'<'E
| E'>'E
| E LE E
| E GE E
| E EQ E
| E NE E
| E AND E
| E OR E
;
E : ID'='E
| E'+'E
| E'-'E
| E'*'E
| E'/'E
| E'<'E
| E'>'E
| E LE E
| E GE E
| E EQ E
| E NE E
| E AND E
| E OR E
| ID
| NUM
;

%%
main()
{
printf("Enter the exp: ");
yyparse();
}
yyerror()
{
printf("\nEntered arithmetic expression is Invalid\n\n");
}

OUTPUT:
$:lex switch.l
$:yacc switch.y
$:cc lex.yy.c y.tab.h
$:./a.out

RESULT:

Thus the given program has been successfully executed and output is verified
D) IMPLEMENTATION OF CALCULATOR USING LEX AND YACC

PROGRAM:

%{

#include<stdio.h>int

op=0,i; float a,b;

%}

dig[0-9]+|([0-9]*)"."([0-9]+)

add "+"

sub "-"

mul"*"

div "/"

pow "^"

ln \n

%%

{dig}{digi();}

{add}{op=1;}

{sub}{op=2;}

{mul}{op=3;}

{div}{op=4;}

{pow}{op=5;}

{ln}{printf("\n the result:%f\n\n",a);}

%%

digi()

if(op==0)

a=atof(yytext);
else

b=atof(yytext);

switch(op)

case 1:a=a+b;

break;

case 2:a=a-b;

break;

case 3:a=a*b;

break;

case 4:a=a/b;

break;

case 5:for(i=a;b>1;b--)a=a*i;

break;

op=0;

main(int argv,char *argc[])

yylex();

yywrap()

return 1;

}
OUTPUT:

Lex cal.l

Cc lex.yy.c-ll

a.out

4*8

The result=32

RESULT:

Thus the program for the exercise on the syntax using YACC has been executed

successfully and Output is verified.


EX.NO:4
DATE:

GENERATE THREE ADDRESS CODE FOR A SIMPLE PROGRAM

AIM:

To write a C program for generating three address code for a simple program

AlGORITHM:

1. Start a program.
2. Get the input expression from the user.
3. Break down the input expression into tokens.
4. Convert the infix expression into postfix expression
5. Generate three address code.
6. Print the output.
7. Stop the program.

PROGRAM:

%{
#include
#include
#include “y.tab.h”
%}
%%
[0-9]+ {yylval.dval=atoi(yytext);return NUM;}
[t];
n return 0;
. {return yytext[0];}
%%
void yyerror(char *str)
{
printf(“n Invalid Character...”);
}
int main()
{
printf(“Enter Expression x => “);
yyparse();
return(0);
}
********************** threee.y ***********************
%{
#include
int yylex(void);
char p=‟A‟-1;
%}
%union

{
char dval;
}
%token NUM
%left „+‟ „-„
%left „*‟ „/‟
%nonassoc UMINUS
%type S
%type E
%%
S : E {printf(” x = %cn”,$$);}

;
E : NUM {}
| E „+‟ E {p++;printf(“n %c = %c + %c “,p,$1,$3);$$=p;}
| E „-„ E {p++;printf(“n %c = %c – %c “,p,$1,$3);$$=p;}
| E „*‟ E {p++;printf(“n %c = %c * %c “,p,$1,$3);$$=p;}
| E „/‟ E {p++;printf(“n %c = %c / %c “,p,$1,$3);$$=p;}
| „(„E‟)‟ {$$=p;}
| „-„ E %prec UMINUS {p++;printf(“n %c = -%c “,p,$2);$$=p;}
;
%%

OUTPUT:

[a40@localhost ~]$ lex threee.l


[a40@localhost ~]$ yacc -d threee.y
[a40@localhost ~]$ cc lex.yy.c y.tab.c -ll
[a40@localhost ~]$ ./a.out

Enter Expression x => 1+2-3*3/1+4*5


A = 1+2
B = 3*3
C = B/1
D = A-C
E = 4*5
F = D+E
X=F

RESULT:

Thus the program has been executed successfully and Output is verified.
EX.NO:5
DATE:

IMPLEMENTATION OF TYPE CHECKING


AIM:

To write a C program for implementing type checking for given expression.

INTRODUCTION:

The type analysis and type checking is an important activity done in the semantic
analysis phase. The need for type checking is
1. To detect the errors arising in the expression due to incompatible operand.
2. To generate intermediate code for expressions due to incompatible operand

Role of type
checker

Source parse tree parse Intermediate


program tree

ALGORITHM:

1. Start a program.
2. Include all the header files.
3. Initialize all the functions and variables.
4. Get the expression from the user and separate into the tokens.
5. After separation, specify the identifiers, operators and number.
6. Print the output.
7. Stop the program.

PROGRAM: ( TYPE CHECKING)

#include<stdio.h>
char str[50],opstr[75];
int f[2][9]={2,3,4,4,4,0,6,6,0,1,1,3,3,5,5,0,5,0};
int col,col1,col2;char c;
swt()
{
switch(c)
{
case'+':col=0;break; case'-
':col=1;break;
case'*':col=2;break;
case'/':col=3;break;
case'^':col=4;break;
case'(':col=5;break;
case')':col=6;break;
case'd':col=7;break;
case'$':col=8;break;
default:printf("\nTERMINAL MISSMATCH\n");
exit(1);
}
// return 0;
}
main()
{
int i=0,j=0,col1,cn,k=0;int
t1=0,foundg=0;
char temp[20];
clrscr();
printf("\nEnter arithmetic expression:");scanf("%s",&str);
while(str[i]!='\0')i++;
str[i]='$';
str[++i]='\0';
printf("%s\n",str);come:
i=0;
opstr[0]='$';j=1;
c='$';
swt();
col1=col;
c=str[i];
swt();
col2=col;
if(f[1][col1]> f[2][col2])
{
opstr[j]='>';j++;
}
else if(f[1][col1]<f[2][col2])
{
opstr[j]='<';j++;

}
else
{ opstr[j]='=';j++;

}
while(str[i]!='$')
{
c=str[i];
swt();
col1=col;
c=str[++i];
swt();
col2=col;
opstr[j]=str[--i];j++;
if(f[0][col1]>f[1][col2])
{
opstr[j]='>';j++;
}
else if(f[0][col1]<f[1][col2])
{
opstr[j]='<';j++;
}
else
{
opstr[j]='=';j++;
}
i++;
}
opstr[j]='$';
opstr[++j]='\0';
printf("\nPrecedence Input:%s\n",opstr);i=0;
j=0;
while(opstr[i]!='\0')
{
foundg=0;
while(foundg!=1)
{
if(opstr[i]=='\0')goto redone;
if(opstr[i]=='>')foundg=1; t1=i;
i++;
}
if(foundg==1)
for(i=t1;i>0;i--)
if(opstr[i]=='<')break; if(i==0){printf("\nERROR\n");exit(1);}
cn=i; j=0;
i=t1+1;
while(opstr[i]!='\0')
{
temp[j]=opstr[i];
j++;i++;
}
temp[j]='\0';
opstr[cn]='E'; opstr[++cn]='\0';
strcat(opstr,temp);
printf("\n%s",opstr);
i=1;
}
redone:k=0;
while(opstr[k]!='\0')
{
k++;
if(opstr[k]=='<')
{
Printf("\nError");exit(1);
}
}
if((opstr[0]=='$')&&(opstr[2]=='$'))goto sue;i=1
while(opstr[i]!='\0')
{
c=opstr[i]; if(c=='+'||c=='*'||c=='/'||c=='$')
{
temp[j]=c;j++;}i++;
}
temp[j]='\0';
strcpy(str,temp);goto
come;
sue:
printf("\n success");return 0;
}
OUTPUT:
RESULT:

Thus the program has been executed successfully and Output is verified.
EX.NO:6
DATE:

IMPLEMENTATION OF SIMPLE CODE OPTIMIZATION


TECHNIQUES

AIM:
To write a C program to implement simple code optimization technique.

INTRODUCTION:
Optimization is a program transformation technique, which tries to improve the code
by making it consume less resource (i.e. CPU, memory) and deliver high speed.

In optimization, high-level general programming constructs are replaced by very


efficient low level programming codes. A code optimizing process must follow the
three rules given below:

The output code must not, in any way, change the meaning of the program.

 Optimization should increases the speed of the program and if possible, the
program should demand less number of resources.
 Optimization should itself be fast and fast and should not delay the overall
compilingprocess.

Efforts for an optimized code can be made at various levels of compiling the process.

 At the beginning, users can change/rearrange the code or use better algorithms
to writethe code.
 After generating intermediate code, the compiler can modify the intermediate
code byaddress calculations and improving loops.
 While producing the target machine code, the compiler can make use of
memoryhierarchy and cpu registers.

Optimization can be categorized broadly into two types: Machine independent and
Machine dependent.

Machine independent optimization

In this optimization, the compiler takes in the intermediate code and transforms a part
of the code that does not involve any CPU registers and/or absolute memory locations.
For
Example:
do

item=10;

value=value+item;

}while(value<100);
This code involves repeated assignment of the identifier item, which if we put this way:

item=10;

do

value=value+item;

}while(value<100);

Should not only save the cpu cycles, but can be used on any processor.

Machine dependent optimization

Machine dependent optimization is done after the target code has been generated and
when the code is transformed according to the target machine architecture. It involves
CPU registers and may have absolute memory references rather than relative
references. Machine- dependent optimizers put efforts to take maximum advantage of
memory hierarchy.

ALGORITHM:

1. Start the program


2. Declare the variables and functions.
3. Enter the expressionand state it in the variable a, b, c.
4. Calculate the variables b & c with „temp‟ and store it in f1 and f2.
5. If(f1=null && f2=null) then expression could not be optimized.
6. Print the results.
7. Stop the program.

PROGRAM: (SIMPLE CODE OPTIMIZATION TECHNIQUE)

Before using for:

#include<iostream.h>

#include <conio.h> int main()

int i, n; int

fact=1;
cout<<"\nEnter a number: ";
cin>>n; for(i=n;i>=1;i-

-)fact=fact *i;

cout<<"The factoral value is: "<<fact;getch();

return 0;

OUTPUT:
After: (SIMPLE CODE OPTIMIZATION TECHNIQUE)

Using do-while:

#include<iostream.h>

#include<conio.h>void
main()

clrscr();int
n,f;

f=1;

cout<<"Enter the number:\n";cin>>n;

do

f=f*n;

n--;

}while(n>0);

cout<<"The factorial value is:"<<f;getch();

}
OUTPUT:

RESULT:

Thus the Simple Code optimization technique is successfully executed


EX.NO.7
DATE:
IMPLEMENT THE BACK END OF THE COMPILER

AIM:

To implement the 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.
INTRODUCTION:
A compiler is a computer program that implements a programming language
specification to “translate” programs, usually as a set of files which constitute the
source code written in source language, into their equivalent machine readable
instructions(the target language, often having a binary form known as object code).
This translation process is called compilation.
BACK END:
 Some local optimization
 Register allocation
 Peep-hole optimization
 Code generation
 Instruction scheduling
The main phases of the back end include the following:
 Analysis: This is the gathering of program information from the intermediate
representation derived from the input; data-flow analysis is used to build use-
define chains, together with dependence analysis, alias analysis, pointer analysis,
escape analysis etc.
 Optimization: The intermediate language representation is transformed into
functionally equivalent but faster (or smaller) forms. Popular optimizations are
expansion, dead, constant, propagation, loop transformation, register allocation
and even automatic parallelization.
 Code generation: The transformed language is translated into the output
language, usually the native machine language of the system. This involves
resource and storage decisions, such as deciding which variables to fit into
registers and memory and the selection and scheduling of appropriate machine
instructions along with their associated modes. Debug data may also need to be
generated to facilitate debugging.
ALGORITHM:

1. Start the program


2. Open the source file and store the contents as quadruples.
3. Check for operators, in quadruples, if it is an arithmetic operator generator
it or ifassignment operator generates it, else perform unary minus on
register C.
4. Write the generated code into output definition of the file in outp.c
5. Print the output.
6. Stop the program.

PROGRAM: (BACK END OF THE COMPILER)

#include<stdio.h>

#include<stdio.h>

//#include<conio.h>

#include<string.h> void

main()

char icode[10][30],str[20],opr[10];int i=0;

//clrscr();

printf("\n Enter the set of intermediate code (terminated byexit):\n");

do

scanf("%s",icode[i]);

} while(strcmp(icode[i++],"exit")!=0);
printf("\n target code generation");

printf("\n************************");i=0;

do

strcpy(str,icode[i]);switch(str[3])

case '+':

strcpy(opr,"ADD");

break;

case '-':

strcpy(opr,"SUB");break;

case '*':

strcpy(opr,"MUL");

break;

case '/':

strcpy(opr,"DIV");break;

}
printf("\n\tMov %c,R%d",str[2],i);

printf("\n\t%s%c,R%d",opr,str[4],i);

printf("\n\tMov R%d,%c",i,str[0]);

}while(strcmp(icode[++i],"exit")!=0);

//getch();

}
OUTPUT:

RESULT:

Thus the program was implemented to the TAC has been successfully executed.

You might also like