Anda di halaman 1dari 49

Cseitquestions.blogspot.

in

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

CS6612 COMPILER LABORATORY SYLLABUS


1. Implementation of Symbol Table
2. Develop a lexical analyzer to recognize a few patterns in C. (Ex. identifiers, constants,
comments, operators etc.)
3. Implementation of Lexical Analyzer using Lex Tool
4. 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) Implementation of Calculator using LEX and YACC
5. Convert the BNF rules into Yacc form and write code to generate Abstract Syntax Tree.
6. Implement type checking
7. Implement control flow analysis and Data flow Analysis
8. Implement any one storage allocation strategies(Heap,Stack,Static)
9. Construction of DAG
10. 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.
11. Implementation of Simple Code Optimization Techniques

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

COMPILER LAB

EXP.NO.

NAME OF THE EXPERIMENT

Implementation of Symbol Table

Develop a lexical analyzer to recognize a few patterns in C.

Implementation of Lexical Analyzer using Lex Tool

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) Implementation of Calculator using LEX and YACC

Convert the BNF rules into Yacc form and write code to generate
Abstract Syntax Tree.

Implement type checking

Implement stack storage allocation

Construction of DAG

Implement the back end of the compiler

10

Implement the front end of the compiler

11

Implementation of Simple Code Optimization Techniques.

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

Compiler is a System Software that converts High level language to low level
language .We human beings cant program in machine language (low level lang.)
understood by Computers so we program in high level language and compiler is the
software which bridges the gap between user and computer.
Its a very complicated piece of software which took 18 man years to build
first compiler. To build this S/w it is divided into six phases which are
1) Lexical Analysis
2)Syntax
Analysis
3)Semantic Analysis
4)Intermediate Code
5)Code Optimization
6)Code Generation.
Lex helps write programs whose control flow is directed by instances of regular expressions
in the input stream. It is well suited for editor-script type transformations and for
segmenting input in preparation for a parsing routine.
Lex source is a table of regular expressions and corresponding program fragments. The table
is translated to a program which reads an input stream, copying it to an output stream and
partitioning the input into strings which match the given expressions. As each such string is
recognized the corresponding program fragment is executed. The recognition of the
expressions is performed by a deterministic finite automaton generated by Lex. The program
fragments written by the user are executed in the order in which the corresponding regular
expressions occur in the input stream.
The lexical analysis programs written with Lex accept ambiguous specifications and choose
the longest match possible at each input point. If necessary, substantial lookahead is
performed on the input, but the input stream will be backed up to the end of the current
partition, so that the user has general freedom to manipulate it.
List of Apparatus:
Hardware Requirements:
Processsor: Pentium I
RAM:
128MB
Hard Disk 40 GB
Floppy Drive 1.44MB
Software Requirements:
Language:
C/C++

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

EXERCISE 1
SYMBOL TABLE IMPLEMENTATION
Aim:
To write a C program to implement a symbol table.
Steps :
1) Start the program.
2) Get the input from the user wit h the terminat ing symbol $.
3) Allocate memory for the variable by dynamic memory allocat ion funct ion.
4) If the next character of the symbo l is an operator then only the memory is
allocated.
5) While reading, the input symbol is inserted into symbol table along with its
memoryaddress.
6 ) T he s t e p s a r e r e p e a t e d t i l l $ i s r e a c he d .
7) To reach a variable, enter the variable to the searched and symbol table has
been checkedfor corresponding variable, the variable along with its address is displayed
as result.
8)Stop the program.
Program:
#include <stdio.h>
#include<conio.h>
#include<ctype.h>
#include<alloc.h>
#include<string.h>
#include<math.h>
void main()
{
int i=0,j=0,x=0,n,flag=0;
void *p,*add[5];
char ch,srch,b[15],d[15],c;
clrscr();
printf("Expression terminated by $ : ");
while((c=getchar())!='$')
{
b[i]=c;i++;
}
n=i-1;
printf("Given Expression : ");

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

i=0;
while(i<=n)
{
printf("%c",b[i]);
i++;
}
printf("\nSymbolTable\n");
printf("Symbol\taddr\ttype");
while(j<=n)
{
c=b[j];
if(isalpha(toascii(c)))
{
if(j==n)
{
p=malloc(c);
add[x]=p;
d[x]=c;
printf("%c\t%d\tidentifier",c,p);
}else
{
ch=b[j+1];
if(ch=='+'||ch=='-'||ch=='*'||ch=='=')
{
p=malloc(c);
add[x]=p;
d[x]=c;
printf("\n%c\t%d\tidentifier\n",c,p);
x++;
}}}
j++;
}
printf("\nThe symbol is to be searched");
srch=getch();
for(i=0;i<=x;i++)
{
if(srch==d[i])
{
printf("\nSymbol Found");
printf("\n%c%s%d\n",srch," @address ",add[i]);
flag=1;
}}
if(flag==0)
printf("\nSymbol Not Found");
getch();
}

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

OUTPUT

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

Result
Thus the above the program is executed and the required output is obtained.
EXERCISE 2

IMPLEMENTATION OF LEXICAL ANALYZER IN C


Aim:
To write a C Program to implement a Lexical analyzer.
Steps:
1)Start the program.
2)Declare all the variables and file pointers.
3 ) D i s p l a y t he i n p u t p r o g r a m.
4)Separate the keyword in the program and display it.
5)Display the header files of the input program.
6)Separate the operators of the input program and display it.
7 ) P r i nt t he p u n c t u a t io n m a r k s .
8)Print the constant that are present in input program.
9)Print the ident ifiers of the input program.
10)Stop the program.
Program:
#include<stdio.h>
#include<conio.h>
#include<ctype.h>
#include<string.h>
void main()
{
FILE *fp;
int i,j;
char arr[100],k;
char kw[10][10]={"int","float","double","end","main","void","include","printf","scanf"};
char hf[2][10]={"stdio.h","conio.h"};
char op[5]={'+','-','*','/','%'};
char punc[6]={'(',')','{','}',','};
clrscr();
fp=fopen("input.c","r");
printf("InputProgram\n");
while(!feof(fp))

Cseitquestions.blogspot.in

{
arr[0]=fgetc(fp);
printf("%c",arr[0]);
}
fclose(fp);
printf("\nSymboltable\n");
fp=fopen("input.c","r");
printf("\nKeywords");
while(!feof(fp))
{
arr[0]=fgetc(fp);
fscanf(fp,"%s",arr);
for(i=0;i<10;i++)
{
if(strcmp(arr,kw[i])==0)
{
printf("\t%s",arr);
}}}
fclose(fp);
fp=fopen("input.c","r");
printf("\nHeader files");
while(!feof(fp))
{
arr[0]=fgetc(fp);
fscanf(fp,"%s",arr);
for(i=0;i<2;i++)
{
if(strcmp(arr,hf[i])==0)
{
printf("\t%s",arr);
}}}
fclose(fp);
fp=fopen("input.c","r");
printf("\nOperators");
while(!feof(fp))
{
arr[0]=fgetc(fp);
for(i=0;i<5;i++)
{
if(arr[0]==op[i])
{
printf("\t%c",arr[0]);
}}}
fclose(fp);
fp=fopen("input.c","r");
printf("\npunctuation");

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

while(!feof(fp))
{
arr[0]=fgetc(fp);
for(i=0;i<6;i++)
{
if(arr[0]==punc[i])
{
printf("\t%c",arr[0]);}}}
fclose(fp);
fp=fopen("input.c","r");
printf("\nConstants");
while(!feof(fp))
{
arr[0]=fgetc(fp);
if(isdigit(arr[0]))
{
printf(" %c ",arr[0]);}}
fclose(fp);
fp=fopen("input.c","r");
printf("\nidentifier ");
while(!feof(fp))
{
fscanf(fp,"%s",arr);
for(i=0;i<2;i++)
{
if(strcmp(arr,kw[i])==0)
{
fscanf(fp,"%s",arr);
j=0;
while(j<strlen(arr) && arr[j]!=';')
{
printf("%c",arr[j]);
j++;
}}}}
fclose(fp);
getch();
}

INPUT:
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c;
a=10;

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

b=5;
c=a+b;
printf(The sum is %d,c);
getch();
}

OUTPUT:

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

Result:
Thus the above the program is executed and the required output is obtained
EXERCISE 3
IMPLEMENTATION OF LEXICAL ANALYSER USING LEX TOOL
Aim:
To write a lex program to implement the lexical analyzer.
Steps:
1.Start the program
2.Open a file file.c in read and include the yylex() tool for input scanning.
3 . D e f i n e t he a l p h a b e t s a n d nu m b e r s .
4.Print the preprocessor, function, keyword using yytext.lex tool.
5.Print the relational, assignment and all the operator using yytext() tool.
6 . A l s o s c a n a n d p r i nt w h e r e t h e lo o p e nd s a n d be g i n s .
7 . U s e y yw r a p ( ) t o e nt e r a n e r r o r .
8.Stop the program.
Program:
%{
int COMMENT=0;
%}
identifier [_a-zA-Z][_a-zA-Z0-9]*
%%
#.* {printf("\n%s is a PREPROCESSOR DIRECTIVE",yytext);}
int |
float |
char |
while |
for |
do |
if |
break |

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

continue |
void |
switch |
case |
long |
struct |
const |
typedef |
return |
else |
goto {printf("\n\t%s is a KEYWORD",yytext);}
"/*" {COMMENT=1;
printf("\n\n\t COMMENT ENDS\n");}
{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 %s is a STRING",yytext);}
[0-9]+ {if(!COMMENT) printf("\n %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);}
|\n
%%
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()

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

{
return 0;
}
INPUT(area.c):
# include<stdio.h>
#include<stdlib.h>
double area_of_circle(double r);
int main(int arge.char*argv[])
{
if(arge<2)
{
printf(usage:%s radius\n,argv[0]);
{
exit(1);
}
else
{
double radius=atof(argv[1]);
double area=area_of_circle(radius);
printf("Area of circle with radius %f=%f\n",radius,area);
}
return 0;
}
OUTPUT

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

Result:
Thus the above the program is executed and the required output is obtained.
EXERCISE 4A
YACC PROGRAM TO RECOGNIZE A VALID ARITHMETICEXPRESSION
Aim:
To write a YACC program to recognize a valid arithmetic expression that uses operators +, -, *
and /.
Steps:
1.Start the program
2. Open a file filename.c in read and include the yylex() tool for input scanning.
3 . D e f i n e t h e a r it h m e t i c e xp r e s s i o n
4 . A l s o s c a n a nd p r i nt w h e r e t h e lo o p e nd s a nd b e g i n s .
5 . U s e ya c c t o p r i nt t he valid arithmetic expression.
6. Stop the program.
Program:
LEX
%{
#include"y.tab.h"extern yylval;
%}
%%
[0-9]+ {yylval=atoi(yytext); return NUMBER;}
[a-zA-Z]+ {return ID;}
[\t]+ ;
\n {return 0;}
. {return yytext[0];}
%%
YACC
%{
#include<stdio.h>
%}
%token NUMBER ID
%left '+' '-'
%left '*' '/'
%%
expr: expr '+' expr
|expr '-' expr
|expr '*' expr
|expr '/' expr
|'-'NUMBER|
'-'ID
|'('expr')'
|NUMBER
|ID;

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

%%
main()
{
printf("Enter the expression\n");
yyparse();
printf("\nExpression is valid\n");
exit(0);
}
int yyerror(char *s)
{
printf("\nExpression is invalid");
exit(0);
}
Criteria for evaluation:
$lex p4a.l
$yacc d p4a.y
$cc lex.yy.c y.tab.c ll
$./a.out
Enter the expression(a*b+5)
Expression is valid
$./a.out
Enter the expression
(a+6-)
Expression is invalid

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

Result:
Thus the above the program is executed and the required output is obtained.
EXERCISE 4B
YACC PROGRAM TO RECOGNIZE A VALID VARIABLE
Aim:
To write a YACC program to recognize a valid variable, which starts with a letter,
followed by any number of letters or digits.
Steps:
1 . Start the program
2. Open a file filename.c in read and include the yylex() tool for input scanning.
3 . D e f i n e t h e s t r i n g va r i a b l e
4 . A l s o s c a n a nd p r i nt w h e r e t h e lo o p e nd s a nd b e g i n s .
5 . U s e ya c c t o p r i nt t he string is valid or not.
6. Stop the program.
Program:
LEX
%{
#include"y.tab.h"extern yylval;
%}
%%
[0-9]+ {yylval=atoi(yytext); return DIGIT;}
[a-zA-Z]+ {return LETTER;}
[\t] ;
\n return 0;
.{return yytext[0];}
%%
YACC
%{
#include<stdio.h>
%}
%token LETTER DIGIT
%%
variable: LETTER|LETTER rest
;
rest: LETTER rest
|DIGIT rest
|LETTER
|DIGIT

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

;
%%
main()
{
yyparse();
printf("The string is a valid variable\n");
}
int yyerror(char *s)
{
printf("this is not a valid variable\n");
exit(0);
}
Criteria for evaluation:
$lex p4b.l
$yacc d p4b.y
$cc lex.yy.c y.tab.c ll
$./a.out
input34
The string is a valid variable
$./a.out
89file
This is not a valid variable.

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

Result:
Thus the above the program is executed and the required output is obtained.

EXERCISE 4C
IMPLEMENTATION OF CALCULATION USING LEX ANDYACC
Aim:
To write a program to implement calculator using lex and yacc.
Steps:
1.Start the program.
2.Perform the calculat ion using both the lex and yacc.
3.In the lex tool, if the given expression contains numbers and letters then they are displayed.
4.In the same way, the digits, letters and uminus are identified and displayed using yacctool.
5.The calculat ion is performed and the result is displayed.
6.Stop the program.
Program:
USING LEX TOOL:
%{
#include<stdio.h>
#include"y.tab.h"
int c;
extern int yylaval;
%}
%%
"";
[a-z]
{
c=yytext[0];
yylaval=c-'a';
return(LETTER);
}
[0-9]
{
c=yytext[0];
yylaval=c-'0';
return(DIGIT);

Cseitquestions.blogspot.in

}
[a-z0-9/b]
{
c=yytext[0];
return(c);
}
USING YACC TOOL:
%{
#include<stdio.h>
int regs[26];
int base;
%}
%start list
%token DIGIT LETTER
%left'|'
%left'&'
%left'+''-'
%left'*''/''%'
%left UMINUS
%%
list:
|
list stat'\n'
|list error'\n'
{
yyerror();
};
stat:expr
{
printf("%d\n",$1);
}
|
LETTER'='expr
{
regs[$1]=$3;
};
expr:'('expr')'
{
$$=$2;
}
|
expr'*'expr
{
$$=$1*$3;
}
|

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

expr'/'expr
{
$$=$1/$3;
}
|
expr'%'expr
{
$$=$1%$3;
}
|
expr'+'expr
{
$$=$1+$3;
}
|
expr'-'expr
{
$$=$1-$3;
}
|
expr'&'expr
{
$$=$1&$3;
}
|
expr'|'expr
{
$$=$1|$3;
}
|
'-'expr%prec UMINUS
{
$$=-$2;
}
|
LETTER
{
$$=regs[$1];
}
|
number
;
number:DIGIT
{
$$=$1;
base=($1==0)?8:10;
}
|

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

number DIGIT
{
$$=base*$1+$2;
}
%%
main()
{
return(yyparse());
}
yyerror(s)
char*s;
{
fprintf(stderr,"%s\n",s);
}
yywrap()
{
return(1);
}
OUTPUT

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

Result:
Thus the above the program is executed and the required output is obtained
EXERCISE 5
ABSTRACT SYNTAX TREE
Aim:
Convert the BNF rules into Yacc form and write code to generate Abstract Syntax Tree.
Steps:
1. Start the program.
2. Include the yylex() tool for open a file as <int.l>&<int.y> .
3. A l s o s c a n a n d p r i nt w h e r e t h e lo o p e nd s a nd b e g i n s .
4 . U s e ya c c t o p r i nt t he a b s t r a c t s ynt a x t r e e
5 . Stop the program.
Program:
<int.l>
%{
#include"y.tab.h"
#include<stdio.h>
#include<string.h>
int LineNo=1;
%}

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

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];
%%
<int.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 {
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

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

%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);}
| 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);

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

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);
}
;
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");

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

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");
exit(0);
}
yyin=fp;
}
yyparse();
printf("\n\n\t\t ----------------------------""\n\t\t Pos Operator
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");
exit(0);
}
stk.items[stk.top]=data;
}
int pop()
{
int data;
if(stk.top==-1)

Arg1 Arg2

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

{
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);
}
Input:
$vi test.c
main()
{
int a,b,c;
if(a<b)
{
a=a+b;
}
while(a<b)
{
a=a+b;
}
if(a<=b)
{
c=a-b;
}
else
{
c=a+b;
}}
Criteria for evaluation:
$lex int.l
$yacc d int.y
$gcc lex.yy.c y.tab.c ll lm
$./a.out test.c

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

Result:
Thus the above the program is executed and the required output is obtained.

EXERCISE 6
IMPLEMENT TYPE CHECKING

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

Aim:
To check whether string belongs to a grammar or not
Steps:
1 Start the program.
2 Declare two character arrays str[],token[] and initialize integer variables a=0,b=0,c,d.
3. Input the string from the user.
4. Print the token generated for the string .
5. Compare tokens and store the result in d.
6. If d=0 then print that the string is in the grammar.
7. Else print that the string is not in the grammar.
8. Stop the program.
Program:
#include<stdio.h>
#include<conio.h>
#include<ctype.h>
#include<string.h> void
main()
{
int a=0,b=0,c;
char
str[20],tok[11];
clrscr();
printf("Input the expression = ");
gets(str);
while(str[a]!='\0')
{
if((str[a]=='(')||(str[a]=='{'))
{
tok[b]='4';
b++;
}
if((str[a]==')')||(str[a]=='}'))
{
tok[b]='5';
b++;
}
if(isdigit(str[a]))
{
while(isdigit(str[a]))
{
a++;
}
a--;
tok[b]='6';
b++;
}
if(str[a]=='+')
{

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

tok[b]='2';
b++;
}
if(str[a]=='*')
{
tok[b]='3';
b++;
}
a++;
}
tok[b]='\0';
puts(tok);
b=0;
while(tok[b]!='\0')
{
if(((tok[b]=='6')&&(tok[b+1]=='2')&&(tok[b+2]=='6'))||((tok[b]=='6')&&(tok[b+1
]=='3')&&(tok[b+2]=='6'))||((tok[b]=='4')&&(tok[b+1]=='6')&&(tok[b+2]=='5'))/*||((tok[b
]!=6)&&(tok[b+1]!='\0'))*/)
{
tok[b]='6';
c=b+1;
while(tok[c]!='\0')
{
tok[c]=tok[c+2];
c++;
}
tok[c]='\0';
puts(tok);
b=0;
}
else
{
b++;
puts(tok);
}
}
int
d;
d=strcmp(tok,"6");
if(d==0)
{
printf("It is in the grammar.");
}
else
{printf("It is not in the grammar.");
}
getch();
}

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

Criteria for evaluation:


Input the expression = (23+)
4625 4625 4625 4625 4625
It is not in the grammar.
Input the expression = (2+(3+4)+5)
46246265265 46246265265 46246265265
46246265265 46246265265 462465265
462465265 462465265 462465265 4626265
4626265 46265 46265 465 6 6
It is in the grammar.

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

Result:
Thus the above the program is executed and the required output is obtained.
EXERCISE 7
IMPLEMENTATION OF STACK STORAGE ALLOCATION
Aim:
To write a program to implement a stack storage using array.
Steps:
INSERTION
PUSH(item)
1. If (item = max of stack) Print
overflow Return
2. top = top + 1
3. stack[top] = item
4. Return
DELETION
POP(item)
1. If (top = - 1) Print underflow
Return
2. Item = stack[top]
3. top = top 1
4. Return
DISPLAY
1. If top = - 1
Print underflow
2. repeat step 3 for i = top to i >= 0
3. Print stack[i]
4. Return
Program:
#include<stdio.h>
#include<conio.h>
#define MAXSIZE10
void push();
int pop();
void traverse();
int stack[MAXSIZE];
int Top=-1;
void main()
{
int choice; char ch;
do

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

{
clrscr(); printf("\n1.PUSH");
printf("\n2. POP ");
printf("\n3. TRAVERSE "); printf("\nEnter your
choice"); scanf("%d",&choice);
switch(choice)
{
case 1: push();
break;
case 2: printf("\nThe deleted element is %d",pop());
break;
case 3: traverse();
break;
default: printf("\nYou Entered Wrong Choice");
}
printf("\nDo You Wish To Continue(Y/N)"); fflush(stdin);
scanf("%c",&ch);
}
while(ch=='Y' || ch=='y');
}
void push()
{
int item;
if(Top == MAXSIZE - 1)
{
printf("\nThe Stack IsFull");
getch();
exit(0);
}
else
{
printf("Enter the element to beinserted");
scanf("%d",&item);
Top= Top+1; stack[Top] = item;
}
}
int pop()
{
int item; if(Top == -1)
{
printf("The stack is Empty");
getch();
exit(0);
}
else
{
item = stack[Top];

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

Top = Top-1;
}
return(item);
}
void traverse()
{
int i; if(Top == -1)
{
printf("The Stack is Empty");
getch();
exit(0);
}
else
{
for(i=Top;i>=0;i--)
{
printf("Traverse the element");
printf("\n%d",stack[i]);
}
}
}

OUTPUT

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

Result:
Thus the above the program is executed and the required output is obtained.
EXERCISE 8
CONSTRUCTION OF DAG
Aim:
To write a program to construct Direct Acyclic Graph using c.
Steps:
1. Start the program.
2. Include the structure for node creation & construct the tree.
3. A l s o s c a n a n d p r i nt w h e r e t h e lo o p e nd s a nd b e g i n s .
4 . p r i nt t he Direct Acyclic Graph .
5 . Stop the program.
Program:
#include<stdio.h>
#include<conio.h>
struct node
{
struct node *next;
char id[10];
char left[10];
char right[10];
char attach[3][10];
};
struct node *head;
file *f;
int i,s=0;
char str[25],store[10][25];
void construct_tree()
{
struct node *temp;
struct node *t;
struct node *ptr;
int flag=0,fl=0;
temp=head;
if(s==5 || s==6)
{

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

while(temp->next!=null)
{
if(!strcmp(store[2],temp->next->left))
flag+=1;
if(!strcmp(store[4],temp->next->right))
flag+=2;
if(flag!=0)
break;
temp=temp->next;
}
t=head;
while(t->next!=null)
t=t->next;
if(flag==0)
{
ptr=(struct node*)malloc(sizeof(struct node));
t->next=ptr;
if(s==5)
strcpy(ptr->id,store[3]);
else
strcpy(ptr->id,strcat(store[3],store[5]));
t=head;
while(t->next!=null)
{
if(!strcmp(t->next->attach[0],store[2]))
{
f1=1;
break;
}
if(strcmp(t->next->attach[1],))
if(!strcmp(t->next->attach[1],store[2]))
{
f1 = 1;
break;
}
t=t->next;
}
if(f1)
strcpy(ptr->left,t->next->id);
else
strcpy(ptr->left,store[2]);
f1=0;
t=head;
while(t->next!=null)
{
if(!strcmp(t->next->attach[0],store[4]))
{

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

f1 = 1;
break;
}
if(strcmp(t->next->attach[1],))
if(!strcmp(t->next->attach[1],store[4]))
{
f1= 1;
break;
}
t=t->next;
}
if(f1)
strcpy(ptr->right,t->next->id);
else
strcpy(ptr->right,store[0]);
strcpy(ptr->attach[1],,);
ptr->next=null;
}
else if(flag==3)
strcpy(temp->next->attack[1],store[0];
}
if(s==3)
{
while(temp->next!=null)
{
if(!strcmp(store[2],temp->next->attach[0]))
break;
temp=temp->next;
}
strcpy(temp->next->attach[1],store[0]);
}
}
int main()
{
struct node *temp;
struct node *t;
clrscr();
f=fopen(input.text,r);
head=(struct node*)malloc(size of (struct node));
head->next=null;
while(!feof(f))
{
fscanf(f,%s,str);
if(!strcmp(str,;))
{
construct _tree();
s=0;

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

}else
strcpy(store[s++],str);
}printf(\n\nid\tleft\tright\tattached ids\n\n);
temp=head;
while(temp->next!=null)
{
printf(\n\n%s\t%s\t%s\t%s,temp->next->id,
temp->next->left,temp->next->right,temp->next->attach[0]);
if(strcmp(temp->next->attach[1],))
printf(\t%s,temp->next->attach[1]);
temp=temp->next;
} getch();
return 0;}

Criteria for evaluation:


INPUT:
t1 = 4 * I;
t2 = a[t1];
t3 = 4 *I;
t4= b [t3];
t5= t2 *t4;
t6 = prod + t5;
prod = 16;
t7 = i+1;
i=t7;

OUTPUT:
ID
LEFT
*
4
[]
a
[]
b
*
[]
+
prod
+
I

RIGHT
I
*
*
[]
*
|

ATTACHED
t1
t2
t4
t5
t6
t7

IDs
t3

prod
i

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

Result:
Thus the above the program is executed and the required output is obtained.
EXERCISE 9
IMPLEMENTATION THE BACK END OF COMPILER
Aim:
To write a C program to implement the Back end of the compiler.
Steps:
1) St ar t t he pr o gr a m.
2)Get the three variables from statements and stored in the text file k.txt.
3)Compile the program and give the pat h of the source file.
4)Execute the program.
5)Target code for the given statement was produced.
6)Stop the program.
Program:
#include<stdio.h>
#include<conio.h>
#include<ctype.h>
#include<stdlib.h>
void main()
{
int i=2,j=0,k=2,k1=0;
char ip[10],kk[10];
FILE *fp;clrscr();
printf("\nEnter the filename of the intermediate code");
scanf("%s",&kk);
fp=fopen(kk,"r");
if(fp==NULL)
{
printf("\nError in Opening the file");

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

getch();
}clrscr();
while(!feof(fp))
{
fscanf(fp,"%s\n",ip);
printf("\t\t%s\n",ip);
}
rewind(fp);
printf("\n------------------------------\n");
printf("\tStatement \t\t target code\n");
printf("\n------------------------------\n");
while(!feof(fp))
{
fscanf(fp,"%s",ip);
printf("\t%s",ip);
printf("\t\tMOV %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");
getch();
fclose(fp);
}
OUTPUT

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

Result:
Thus the above the program is executed and the required output is obtained.
EXERCISE 10
IMPLEMENTATION THE FRONT END OF COMPILER
Aim:
To write a C program to implement the front end of the compiler.
Steps:
1) Start the program.
2 ) G e t t he c o d i n g fr o m t he u s e r .
3) Find the operators, arguments and results from the coding.

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

4 ) D i s p l a y t h e va l u e i n t h e t a b l e .
5) Stop the program.
Program:
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char pg[100][100],str1[24];
int tem=-1,ct=0,i=-1,j=0,j1,pos=-1,t=-1,flag,flag1,tt=0,fg=0;
clrscr();
printf("Enter the codings \n");
while(i>-2)
{
i++;
lab1:
t++;
scanf("%s",&pg[i]);
if((strcmp(pg[i],"getch();"))==0)
{
i=-2;
goto lab1;
}
}
printf("\n pos \t oper \t arg1 \t arg2 \tresult \n");
while(j<t)
{
l o p :
c t = 0 ;
if(pg[j][1]=='=')
{
pos++;
tem++;
printf("%d\t%c\t%c\t%c\tt%d\n",pos,pg[j][3],pg[j][2],pg[j][4],tem);
pos++;
printf("%d\t:=\tt%d\t\t%c\n",pos,tem,pg[j][0]);
}
else
if(((strcmp(pg[j],"if"))==0)||((strcmp(pg[j],"while"))==0))
{
if((strcmp(pg[j],"if"))==0)
strcpy(str1,"if");
if((strcmp(pg[j],"while"))==0)
strcpy(str1,"ehile");
j++;
j1=j;
tem++;
pos++;

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

if(pg[j][3]=='=')
printf("%d\t%c\t%c\t%c\tt%%d\n",pos,pg[j][2],pg[j][1],pg[j][4],tem);
else
printf("%d\t%c\t%c\t%c\tt%d\n",pos,pg[j][2],pg[j][1],pg[j][3],tem);
j1+=2;
pos++;
while((strcmp(pg[j],"}"))!=0)
{
j++;
if(pg[j][1]=='=')
{
tt=j;
fg=1;
}
ct++;
}
ct=ct+pos+1;
printf("%d\t==\tt%d\tFALSE\t%d\n",pos,tem,ct);
if(fg==1)
{
j=tt;
goto lop;
}
while((strcmp(pg[j],"}"))!=0)
{
pos++;
tem++;
printf("%d\t%c\t%c\t%c\tt%d\n",pos,pg[j][3],pg[j][2],pg[j][4],tem);
pos++;
printf("%d\t:=\tt%d\t\t%c\n",pos,tem,pg[j][0]);
j++;
}
if((strcmp(pg[j+1],"else"))==0)
{
ct=0;
j++;
j1=j;
j1+=2;
pos++;
while((strcmp(pg[j],"}"))!=0)
{
j1++;
ct++;
}
ct=ct*2;
ct++;
ct+=(pos+1);
j+=2;

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

printf("%d\tGOTO\t\t\\t%d\n",pos,ct);
while((strcmp(pg[j],"}"))!=0)
{
pos++;
tem++;
printf("%d\t%c\t%c\t%c\tt%d\n",pos,pg[j][3],pg[j][2],pg[j][4],tem);
pos++;
printf("%t:=\tt%d\t\t%c\n",pos,tem,pg[j][0]);
j++;
}
pos++;
printf("%d\tGOTO\t\t\t\%d\n",pos,ct);
}
}
if((strcmp(pg[j],"}"))==0)
{
pos++;
printf("%d\tGOTO\t\t\t%d\n",pos,pos+1);
}
j++;
}
getch();
}
OUTPUT

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

Result:
Thus the above the program is executed and the required output is obtained.
EXERCISE 11
IMPLEMENTATION OF SIMPLE CODE OPTIMIZATION TECHNIQUES
Aim:
To write a program for implementation of Code Optimization Technique in for and
do-while loop using C++.
Steps:
1.Generate the program for factorial program using for and do-while loop to specify
optimization technique.
2.In for loop variable initialization is activated first and the condition is checked next. If the
condition is true the corresponding statements are executed and specified increment /
decrement operation is performed.
3.The for loop operation is activated till the condition failure.
4.In do-while loop the variable is initialized and the statements are executed then the
condition checking and increment / decrement operation is performed.
5.When comparing both for and do-while loop for optimization do-while is best because first
the statement execution is done then only the condition is checked. So, during the statement
execution itself we can fin the inconvenience of the result and no need to wait for the
specified condition result.
6.Finally when considering Code Optimization in loop do-while is best with respect to
performance.
Program:
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;

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

cout<<"The factoral value is: "<<fact;


getch();
return 0;
}
After:
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();
}

Criteria for evaluation:


USING for LOOP
Enter the number: 5
The factorial value is: 120
USING do-while LOOP
Enter the number: 3
The factorial value is: 6

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

Cseitquestions.blogspot.in

Result:
Thus the program for implementation of Code Optimization technique is executed and
verified.

Anda mungkin juga menyukai