Professional Documents
Culture Documents
LAB MANUAL
DEPARTMENT OF CSE
(COMPUTATIONAL INTELLIGENCE)
(AIML)
(COMPUTATIONAL INTELLIGENCE)
Vision
Mission
The department of CSE (Emerging Technologies) is committed to:
To offer highest Professional and Academic Standards in terms of Personal growth and
satisfaction.
Make the society as the hub of emerging technologies and thereby capture
opportunities in new age technologies.
To create a benchmark in the areas of Research, Education and Public Outreach.
To provide students a platform where independent learning and scientific study are
encouraged with emphasis on latest engineering techniques.
QUALITY POLICY
To pursue continual improvement of teaching learning process of Undergraduate and
Post Graduate programs in Engineering & Management vigorously.
To provide state of art infrastructure and expertise to impart the quality education and
research environment to students for a complete learning experiences.
To offer quality relevant and cost effective programmes to produce engineers as per
requirements of the industry need.
Additional/Extra Programs
1 Write a Lex Program to convert abc to ABC
Write a lex program to find out total number of
2
vowels, and consonants from the giv1en input sting.
Importance of Compiler Design Lab
Every software has to be translated to its equivalent machine instruction form so that it will be
executed by the underlying machine. There are many different types of system softwares that
help during this translation process. Compiler is one such an important System Software that
converts High level language programs to its equivalent machine (low level) language. It is
impossible to learn and use machine language in software development for the users. Therefore
we use high level computer languages to write programs and then convert such programs into
machine understandable form with the help of mediator softwares such as compilers,
interpreters, assemblers etc.Thus compiler bridges the gap between the user and the machine,
i.e., computer.
It's a very complicated piece of software which took 18 man years to build first compiler .To
build this software we must understand the principles, tools, and techniques used in its working.
The compiler goes through the following sequence of steps called phases of a compiler.
1) Lexical Analysis
2) Syntax Analysis
3) Semantic Analysis
4) Intermediate Code Generation
5) Code Optimization
6) Code Generation.
In performing its role, compiler also uses the services of two essential components namely, Symbol
Table and Error Handler
The objective of the Compiler Design Laboratory is to understand and implement the principles,
techniques, and also available tools used in compiler construction process. This will enable the
students to work in the development phase of new computer languages in industry.
2
MALLA REDDY COLLEGE OF ENGINEERING & TECHNOLOGY
Maisammaguda, Dhulapally Post, Via Hakimpet, Secunderabad – 500100
------------------------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------------------------
DEPARTMENT OF COMPUTATIONAL INTELLIGENCE
1. Students are advised to come to the laboratory at least 5 minutes before (to starting time),
those who come after 5 minutes will not be allowed into the lab.
2. Plan your task properly much before to the commencement, come prepared to the lab with the
synopsis / program / experiment details.
3. Student should enter into the laboratory with:
a. Laboratory observation notes with all the details (Problem statement, Aim, Algorithm,
Procedure, Program, Expected Output, etc.,) filled in for the lab session.
b. Laboratory Record updated up to the last session experiments and other utensils (if
any) needed in the lab.
c. Proper Dress code and Identity card.
4. Sign in the laboratory login register, write the TIME-IN, and occupy the computer system
allotted to you by the faculty.
5. Execute your task in the laboratory, and record the results / output in the lab observation note
book, and get certified by the concerned faculty.
6. All the students should be polite and cooperative with the laboratory staff, must maintain the
discipline and decency in the laboratory.
7. Computer labs are established with sophisticated and high end branded systems, which
should be utilized properly.
8. Students / Faculty must keep their mobile phones in SWITCHED OFF mode during the lab
sessions. Misuse of the equipment, misbehaviors with the staff and systems etc., will attract
severe punishment.
9. Students must take the permission of the faculty in case of any urgency to go out ; if anybody
found loitering outside the lab / class without permission during working hours will be treated
seriously and punished appropriately.
10. Students should LOG OFF/ SHUT DOWN the computer system before he/she leaves the lab
after completing the task (experiment) in all aspects. He/she must ensure the system / seat is
kept properly.
3
MALLA REDDY COLLEGE OF ENGINEERING & TECHNOLOGY
Maisammaguda, Dhulapally Post, Via Hakimpet, Secunderabad – 500100
------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------------------------
DEPARTMENT OF COMPUTATIONAL INTELLIGENCE
OBJECTIVES:
To provide an Understanding of the language translation peculiarities by
designing complete translator for mini language.
1. Intel based desktop PC with minimum of 166MHz or faster processor with at least 64 MB
RAM and 100 MB free disk space.
2. C ++ Compiler and JDK kit, Lex or Flex and YACC tools ( Unix/Linux utilities )
4
SOURCE LANGUAGE ( A Case Study)
Consider the following mini language, a simple procedural High Level Language, operating on
integer data with a syntax looking vaguely like a simple C crossed with Pascal. The syntax of the
language is defined by the following BNF grammar:
<program> ::= <block>
<block> ::= { <variable definition> <slist> }
| { <slist> }
<variable definition> ::= int <vardeflist> ;
<vardeflist> ::= <vardec> | <vardec>, <vardeflist>
<vardec> ::= <identifier> | <identifier> [<constant>]
<slist> ::= <statement> |<statement> ; <slist>
<statement> ::= <assignment> | <ifstatement> | <whilestatement> | <block>
| <printstatement> | <empty>
<assignment> ::= < identifier> = <expression>
| <identifier> [<expression>] = [<expression>
<ifstatement> ::= if <bexpression> then <slist> else <slist> endif
| if <bexpression> then <slist> endif
<whilestatement> ::= while <bexpression> do <slist> enddo
<printstatement> ::= print{ <expression> }
<expression> ::= <expression> <addingop> <term> | <term> | <addingop> <term>
<bexpression> ::= <expression> <relop> <expression>
<relop> ::= < | <= | = = | >= | > |!=
<addingop> ::= + | -
<term> ::= <term> <multop> <factor> | <factor>
<multop> ::= * | /
<factor> ::= <constant> | <identifier> |<identifier> [<expression>
| (<expression>)
<constant> ::= <digit> | <digit> <constant>
<identifier> ::= <identifier> <letterordigit> | <letter>
<letterordigit> ::= a|b|c|….|y|z
<digit> ::= 0|1|2|3|…|8|9
<empty> ::= has the obvious meaning
Comments : zero or more characters enclosed between the standard C/Java style comment brockets
/*…*/. The language has the rudimentary support for 1-Dimensional arrays. Ex: int a[3] declares a as
an array of 3 elements, referenced as a[0],a[1],a[2].
5
t2=25;
print(-11+t2*t3); /* this is not a comment on two lines */
}
Endif
}
1. Write a LEX Program to Scan and Count the number of characters, words, and lines in a file.
2. Write a C Program to implement NFAs that recognize identifiers, constants, and operators of the
mini language.
3. Write a C Program to implement DFAs that recognize identifiers, constants, and operators of the
mini language.
4. Design a Lexical analyzer for the above language. The lexical analyzer should ignore redundant
spaces, tabs and newlines. It should also ignore comments. Although the syntax specification
states that identifiers can be arbitrarily long, you may restrict the length to some reasonable
value.
5. Implement the lexical analyzer using JLex, flex, flex or lex or other lexical analyzer generating
tools.
6. Design Predictive parser for the given language
7. Design LALR bottom up parser for the above language.
8. Convert the BNF rules into Yacc form and write code to generate abstract syntax tree.
9. Write program to generate machine code from the abstract syntax tree generated by the parser.
The following instruction set may be considered as target code.
6
stores the value in register R to variable V.
OUT R
outputs the value in register R.
NEG R
negates the value in register R.
ADD A, R
adds the value specified by A to register R, leaving the result in register R.
SUB A, R
subtracts the value specified by A from register R, leaving the result in register R.
MUL A, R
multiplies the value specified by A by register R, leaving the result in register R.
DIV A, R
divides register R by the value specified by A, leaving the result in register R.
JMP L
causes an unconditional jump to the instruction with the label L.
JEQ R, L
jumps to the instruction with the label L if the value in register R is zero.
JNE R, L
jumps to the instruction with the label L if the value in register R is not zero.
JGE R, L
jumps to the instruction with the label L if the value in register R is greater than or equal to zero.
JGT R, L
jumps to the instruction with the label L if the value in register R is greater than zero.
JLE R, L
jumps to the instruction with the label L if the value in register R is less than or equal to zero.
JLT R, L
jumps to the instruction with the label L if the value in register R is less than zero.
NOP
is an instruction with no effect. It can be tagged by a label.
STOP
stops execution of the machine.
All programs should terminate by executing a STOP instruction.
7
1. Problem Statement: Write a LEX Program to Scan and Count the number of characters, words,
and lines in a file.
AIM : To Write a C Program to Scan and Count the number of characters, words, and lines in a
file.
ALGORITHM / PROCEDURE/PROGRAM:
1. Start
2. Read the input file/text
3. Initialize the counters for characters, words, lines to zero
4. Scan the characters, words, lines and
5. increment the respective counters
6. Display the counts
7. End
Output:
No of characters: 35
No of words : 7
No of lines : 2
[ Viva Questions ]
1. What is Compiler?
2. List various language Translators.
3. Is it necessary to translate a HLL program? Explain.
4. List out the phases of a compiler?
5. Which phase of the compiler is called an optional phase?why
8
2. Problem Statement: Write a C Program to implement NFAs that recognize identifiers,
constants, and operators of the mini language.
AIM: To Write a C Program to implement NFAs that recognize identifiers, constants, and
operators of the mini language.
1. Start
2. Design the NFA (N) to recognize Identifiers, Constants, and Operators
3. Read the input string w give it as input to the NFA
4. NFA processes the input and outputs “Yes” if w b Є L(N), “No” otherwise
5. Display the output
6. End
Output: Yes
Output: Yes
Output: Yes
[ Viva Questions ]
9
3. Problem Statement: Write a C Program to implement DFAs that recognize identifiers,
constants, and operators of the mini language.
AIM: To Write a C Program to implement DFAs that recognize identifiers, constants, and
operators of the mini language.
ALGORITHM / PROCEDURE:
1 Start
2 Design the DFAs (M) to recognize Identifiers, Constants, and Operators
3 Read the input string w give it as input to the DFA M
4 DFA processes the input and outputs “Yes” if w b Є L(M), “No” otherwise
5 Display the output
6 End
Output: Yes
Output: Yes
Output: Yes
[ Viva Questions ]
1. What is an Interpreter?
2. What are the other language processors you know?
3. What is the difference between DFA / minimum DFA?
4. Write the difference between the interpreter and Compiler
10
4. Problem Statement: Design a Lexical analyzer. The lexical analyzer should ignore redundant s
tabs and new lines. It should also ignore comments. Although the syntax specification s those
identifiers can be arbitrarily long, you may restrict the length to some reasonable Value.
AIM: Write a C/C++ program to implement the design of a Lexical analyzer to recognize
the tokens defined by the given grammar.
ALGORITHM / PROCEDURE:
1. Start
2. Declare an array of characters, an input file to store the input;
3. Read the character from the input file and put it into character type of variable, say ‘c’.
4. If ‘c’ is blank then do nothing.
5. If ‘c’ is new line character line=line+1.
6. If ‘c’ is digit, set token Val, the value assigned for a digit and return the ‘NUMBER’.
7. If ‘c’ is proper token then assign the token value.
8. Print the complete table with Token entered by the user,Associated token value.
9. Stop
#include<string.h>
#include<ctype.h>
#include<stdio.h>
void keyword(char str[10])
{
if(strcmp("for",str)==0||strcmp("while",str)==0||strcmp("do",str)==0||strcmp("int",str
)==0||strcmp("float",str)==0||strcmp("char",str)==0||strcmp("double",str)==0||strcmp("static",
str)==0||strcmp("switch",str)==0||strcmp("case",str)==0)
printf("\n%s is a keyword",str);
else
printf("\n%s is an identifier",str);
}
main()
11
{
FILE *f1,*f2,*f3;
char c, str[10], st1[10];
int num[100], lineno=0, tokenvalue=0,i=0,j=0,k=0;
printf("\n Enter the c program : ");/*gets(st1);*/
f1=fopen("input","w");
while((c=getchar())!=EOF)
putc(c,f1);
fclose(f1);
f1=fopen("input","r");
f2=fopen("identifier","w");
f3=fopen("specialchar","w");
while((c=getc(f1))!=EOF)
{
if(isdigit(c))
{
tokenvalue=c-'0';
c=getc(f1);
while(isdigit(c))
{
tokenvalue*=10+c-'0';
c=getc(f1);
}
num[i++]=tokenvalue;
ungetc(c,f1);
}
else
if(isalpha(c))
{
putc(c,f2);
c=getc(f1);
while(isdigit(c)||isalpha(c)||c=='_'||c=='$')
{
putc(c,f2);
c=getc(f1);
12
}
putc(' ',f2);
ungetc(c,f1);
}
else
if(c==' '||c=='\t')
printf(" ");
else
if(c=='\n')
lineno++;
else
putc(c,f3);
}
fclose(f2);
fclose(f3);
fclose(f1);
printf("\n The no's in the program are :");
for(j=0; j<i; j++)
printf("%d", num[j]);
printf("\n");
f2=fopen("identifier", "r");
k=0;
printf("The keywords and identifiers are:");
while((c=getc(f2))!=EOF)
{
if(c!=' ')
str[k++]=c;
else
{
str[k]='\0';
keyword(str);
k=0;
}
}
fclose(f2);
13
f3=fopen("specialchar","r");
printf("\n Special characters are : ");
while((c=getc(f3))!=EOF)
printf("%c",c);
printf("\n");
fclose(f3);
printf("Total no. of lines are:%d", lineno);
}
Output :
Enter the C program: a+b*c
Ctrl-D
The no’s in the program are:
The keywords and identifiers are:
a is an identifier and terminal
b is an identifier and terminal
c is an identifier and terminal
Special characters are:
+*
Total no. of lines are: 1
[ Viva Questions ]
14
5. Problem Statement: Implement the lexical analyzer using JLex, flex or other lexical
Analyzer generating tools.
AIM: To Implement the lexical analyzer using JLex, flex or lex other lexical analyzer generating
Tools.
ALGORITHM / PROCEDURE:
1. Start
2. Open a file in text editor
3. Create a Lex specifications file to accept keywords, identifiers, constants, operators and
relational operators in the following format.
a) %{
Definition of constant /header files
%}
b) Regular Expressions
%%
Transition rules
%%
c) Auxiliary Procedure (main( ) function)
OUTPUT :
[ Viva Questions ]
16
6. Problem Statement: Design a Predictive Parser for the following grammar
G: { E-> TE’, E’ -> +TE’ | 0, T-> FT’, T’-> *FT’|0, F-> (E) | id}
AIM: To write a ‘C’ Program to implement for the Predictive Parser (Non Recursive Descent parser)
for the
given grammar ,
F F-> id F->(E)
ALGORITHM / PROCEDURE:
Step1: Start
Step2: Declare a character array w[10] and Z as an array
Step3: Enter the string with $ at the end
Step4: if (A(w[z]) then increment z and check for (B(w[z])) and if satisfies increment z and
check for ‘d’ if d is present then increment and check for (D(w[z]))
Step5: if step 4 is satisfied then the string is accepted
Else string is not
Step 6: Exit
SOURCE CODE :
18
return 1;
else
return 0;
}
else
return 0;
}
else
return 1;
}
TPRIME()
{
token=lexer();
if(token==mulop)
{
lookahead++;
if(F())
{
if(TPRIME())
return 1;
else
return 0;
}
else return 0;
}
else return 1;
}
F()
{
token=lexer();
if(token==id)
return 1;
else
{
if(token==4)
{
if(E())
{
if(token==5)
return 1;
else return 0;
}
else return 0;
}
else return 0;
}
}
lexer()
{
if(lexbuff[lookahead]!='\n')
{
while(lexbuff[lookahead]=='\t')
19
lookahead++;
if(isalpha(lexbuff[lookahead]))
{
while(isalnum(lexbuff[lookahead]))
lookahead++;
return(id);
}
else
{
if(isdigit(lexbuff[lookahead]))
{
while(isdigit(lexbuff[lookahead]))
lookahead++;
return CONST;
}
else
{
if(lexbuff[lookahead]=='+')
{
return(addop);
}
else
{
if(lexbuff[lookahead]=='*')
{
return(mulop);
}
else
{
if(lexbuff[lookahead]=='(')
{
lookahead++;
return(op);
}
else
{
if(lexbuff[lookahead]==')')
{
return(op);
}
else
{
return(err);
}
}
}
}
}
}
}
else
return (col);
20
}
OUTPUT :
Viva Questions:
21
7. Problem Statement: Design a LALR Bottom Up Parser for the given grammar
AIM: To Design and implement an LALR bottom up Parser for checking the syntax of the
Statements in the given language.
ALGORITHM/PROCEDURE/CODE:
<parser.l>
%{
#include<stdio.h>
#include "y.tab.h"
%}
%%
[0-9]+ {yylval.dval=atof(yytext);
return DIGIT;
}
\n|. return yytext[0];
%%
<parser.y>
%{
/*This YACC specification file generates the LALR parser for the program
considered in experiment 4.*/
#include<stdio.h>
%}
%union
{
double dval;
}
%token <dval> DIGIT
%type <dval> expr
%type <dval> term
%type <dval> factor
%%
line: expr '\n' {
;
printf("%g\n",$1);
}
expr: expr '+' term {$$=$1 + $3 ;}
| term
;
term: term '*' factor {$$=$1 * $3 ;}
| factor
;
factor: '(' expr ')' {$$=$2 ;}
| DIGIT
;
%%
int main()
{
yyparse();
22
}
yyerror(char *s)
{
printf("%s",s);
}
Output:
$lex parser.l
$yacc –d parser.y
$cc lex.yy.c y.tab.c –ll –lm
$./a.out
2+3
5.0000
Viva Questions?
1. What is yacc? Are there any other tools available for parser generation?
2. How do you use it?
3. Structure of parser specification program
4. How many ways we can generate the Parser
5. How a
23
8. Problem statement: Convert The BNF rules into YACC form and write code to generate abstract
syntax tree.
AIM: To Implement the process of conversion from BNF rules to Yacc form and generate Abstract
Syntax Tree.
ALGORITHM/PROCEDURE
<int.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];
%%
<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
24
{
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); }
| VAR
| NUM
;
25
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);
}
;
WHILELOOP: WHILE '(' CONDITION ')'
{
strcpy(QUAD[Index].op,"==");
strcpy(QUAD[Index].arg1,$3);
strcpy(QUAD[Index].arg2,"FALSE");
26
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");
exit(0);
}
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");
exit(0);
}
stk.items[stk.top]=data;
}
int pop()
27
{
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);
}
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;
}
}
Output:
$ lex int.l
$ yacc –d int.y
$ gcc lex.yy.c y.tab.c –ll –lm
$ ./a.out test.c
28
OUTPUT:
Viva Questions:
1. What is abstract syntax tree?
2. What is quadruple?
3. What is the difference between Triples and Indirect Triple?
4. State different forms of Three address statements.
5. What are different intermediate code forms?
29
9. Problem Statement: A program to generate machine code from the abstract syntax tree
generated by the parser.
Aim: To write a C Program to Generate Machine Code from the Abstract Syntax Tree
using the specified machine instruction formats.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int label[20];
int no=0;
int main()
{
FILE *fp1,*fp2;
char fname[10],op[10],ch;
char operand1[8],operand2[8],result[8];
int i=0,j=0;
printf("\n Enter filename of the intermediate code");
scanf("%s",&fname);
fp1=fopen(fname,"r");
fp2=fopen("target.txt","w");
if(fp1==NULL || fp2==NULL)
{
printf("\n Error opening the file");
exit(0);
}
while(!feof(fp1))
{
fprintf(fp2,"\n");
fscanf(fp1,"%s",op);
i++;
if(check_label(i))
fprintf(fp2,"\nlabel#%d",i);
if(strcmp(op,"print")==0)
{
fscanf(fp1,"%s",result);
fprintf(fp2,"\n\t OUT %s",result);
}
if(strcmp(op,"goto")==0)
{
fscanf(fp1,"%s %s",operand1,operand2);
fprintf(fp2,"\n\t JMP %s,label#%s",operand1,operand2);
label[no++]=atoi(operand2);
}
if(strcmp(op,"[]=")==0)
{
fscanf(fp1,"%s %s %s",operand1,operand2,result);
fprintf(fp2,"\n\t STORE %s[%s],%s",operand1,operand2,result);
}
30
if(strcmp(op,"uminus")==0)
{
fscanf(fp1,"%s %s",operand1,result);
fprintf(fp2,"\n\t LOAD -%s,R1",operand1);
fprintf(fp2,"\n\t STORE R1,%s",result);
}
switch(op[0])
{
case '*': fscanf(fp1,"%s %s %s",operand1,operand2,result);
fprintf(fp2,"\n \t LOAD",operand1);
fprintf(fp2,"\n \t LOAD %s,R1",operand2);
fprintf(fp2,"\n \t MUL R1,R0");
fprintf(fp2,"\n \t STORE R0,%s",result);
break;
case '+': fscanf(fp1,"%s %s %s",operand1,operand2,result);
fprintf(fp2,"\n \t LOAD %s,R0",operand1);
fprintf(fp2,"\n \t LOAD %s,R1",operand2);
fprintf(fp2,"\n \t ADD R1,R0");
fprintf(fp2,"\n \t STORE R0,%s",result);
break;
case '-': fscanf(fp1,"%s %s %s",operand1,operand2,result);
fprintf(fp2,"\n \t LOAD %s,R0",operand1);
fprintf(fp2,"\n \t LOAD %s,R1",operand2);
fprintf(fp2,"\n \t SUB R1,R0");
fprintf(fp2,"\n \t STORE R0,%s",result);
break;
case '/': fscanf(fp1,"%s %s %s",operand1,operand2,result);
fprintf(fp2,"\n \t LOAD %s,R0",operand1);
fprintf(fp2,"\n \t LOAD %s,R1",operand2);
fprintf(fp2,"\n \t DIV R1,R0");
fprintf(fp2,"\n \t STORE R0,%s",result);
break;
case '%': fscanf(fp1,"%s %s %s",operand1,operand2,result);
fprintf(fp2,"\n \t LOAD %s,R0",operand1);
fprintf(fp2,"\n \t LOAD %s,R1",operand2);
fprintf(fp2,"\n \t DIV R1,R0");
fprintf(fp2,"\n \t STORE R0,%s",result);
break;
case '=': fscanf(fp1,"%s %s",operand1,result);
fprintf(fp2,"\n\t STORE %s %s",operand1,result);
break;
case '>': j++;
fscanf(fp1,"%s %s %s",operand1,operand2,result);
fprintf(fp2,"\n \t LOAD %s,R0",operand1);
fprintf(fp2,"\n\t JGT %s,label#%s",operand2,result);
label[no++]=atoi(result);
break;
case '<': fscanf(fp1,"%s %s %s",operand1,operand2,result);
fprintf(fp2,"\n \t LOAD %s,R0",operand1); fprintf(fp2,"\n\t
JLT %s,label#%d",operand2,result);
label[no++]=atoi(result);
break;
31
}
}
fclose(fp2); fclose(fp1);
fp2=fopen("target.txt","r");
if(fp2==NULL)
{
printf("Error opening the file\n");
exit(0);
}
do
{
ch=fgetc(fp2);
printf("%c",ch);
}while(ch!=EOF);
fclose(fp1);
return 0;
}
int check_label(int k)
{
int i;
for(i=0;i<no;i++)
{
if(k==label[i])
return 1;
}
return 0;
}
Input :
$ vi int.txt
= t1 2
[]= a 0 1
[]=a 1 2
[]=a 2 3
*t1 6 t2
+a[2] t2 t3
-a[2] t1 t2
/t3 t2 t2
uminus t2 t2
print t2
goto t2 t3
=t3 99
uminus 25 t2
*t2 t3 t3
uminus t1 t1
+t1 t3 t4
print t4
Output :
32
Enter filename of the intermediate code: int.txt
STORE t1, 2
STORE a[0], 1
STORE a[1], 2
STORE a[2], 3
LOAD t1, R0
LOAD 6, R1
ADD R1, R0
STORE R0, t3
LOAD a[2], R0
LOAD t2, R1
ADD R1,R0
STORE R0,t3
LOAD a[t2],R0
LOAD t1,R1
SUB R1,R0
STORE R0,t2
LOAD t3,R0
LOAD t2,R1
DIV R1,R0
STORE R0,t2
LOAD t2,R1
STORE R1,t2
LOAD t2,R0
JGT 5,label#11
Label#11: OUT t2
JMP t2,label#13
Label#13: STORE t3,99
LOAD 25,R1
STORE R1,t2
LOAD t2,R0
LOAD t3,R1
MUL R1,R0
STORE R0,t3
LOAD t1,R1
STORE R1,t1
LOAD t1,R0
LOAD t3,R1
ADD R1,R0
STORE R0,t4
OUT t4
33
CD –ADDITIONAL / EXTRA PROGRAMS
1). Problem Statement: Write a LEX Program to convert the substring “abc” to “ABC” from the
given input string.
Lex Program
%{
/*The Program replaces the substring abc by ABC from
the given input string*/
#include<stdio.h>
#include<sting.h>
int i;
%}
%%
[a-zA-Z]* {
for(i=0;i<=yyleng;i++)
{
If((yytext[i]==’a’)&&( yytext[i+1]==’b’)&&( yytext[i+2]==’c’))
{
yytext[i]=’A’;
yytext[i+1]=’B’;
yytext[i+2]=’C’;
}
}
Printf(“%s”, yytext);
}
[\t]*return;
.*{ECHO;}
\n {printf(“%s”, yytext);}
%%
main()
{
yytext();
}
int yywrap()
{
return 1;
}
34
2). Problem Statement: Write a lex program to find out total number of vowels and consonants
from the given input sting.
Lex Program
%{
/*Definition section*/
int vowel_cnt=0,consonant_cnt=0;
%}
vowel [aeiou]+
consonant [^aeiou]
eol \n
%%
{eol} return 0;
[\t]+ ;
{vowel} {vowel_cnt++;}
%%
int main()
{
printf(“\n Enter some input string\n”);
yylex();
printf(“vowels=%d and consonant=%d\n”,vowel_cnt,consonant_cnt);
return 0;
}
Int yywrap()
{
return 1;
}
%{
/*Definition section*/
int vowel_cnt=0,consonant_cnt=0;
%}
vowel [aeiou]+
consonant [^aeiou]
eol \n
%%
{eol} return 0;
[\t]+ ;
{vowel} {vowel_cnt++;}
%%
int main()
{
printf(“\n Enter some input string\n”);
yylex();
printf(“vowels=%d and consonant=%d\n”,vowel_cnt,consonant_cnt);
return 0;
}
Int yywrap()
{
return 1;
}
35
36
UNIFIED MODELING LANGUAGE
Introduction
The unified modeling language (UML) is a standard language for writing software blue prints.
Visualizing
Specifying
Constructing
Documenting
UML is a language that provides vocabulary and the rules for combing words in that vocabulary for
the purpose of communication
A modeling language is a language whose vocabulary and rules focus on the concept and physical
representation of a system. Vocabulary and rules of a language tell us how to create and real well
formed models, but they don’t tell you what model you should create and when should create them.
Visualizing
The UML is more than just a bunch of graphical symbols. In UML each symbol has well defined
semantics. In this manner one developer can write a model in the UML and another developer or even
another tool can interpret the model unambiguously.
Specifying
UML is used for specifying means building models that are precise, unambiguous and complete. UML
addresses the specification of all the important analysis, design and implementation decisions that must
be made in developing and deploying a software intensive system.
UML is not a visual programming language but its models can be directly connected to a variety of
programming languages. This means that it is possible to map from a model in the UML to a
programming language such as java, c++ or Visual Basic or even to tables in a relational database or
the persistent store of an object-oriented database. This mapping permits forward engineering. The
generation of code from a UML model into a programming language.
The reverse engineering is also possible you can reconstruct a model from an
implementation back into the UML.
Documenting
UML is a language for Documenting. A software organization produces all sorts of artifacts in addition
to raw executable code. These artifacts include Requirements, Architecture, Design, Source code,
Project plans, Test, Prototype, and Release. Such artifacts are not only the deliverables of a project,
they are also critical in controlling, measuring and communicating about a system during its
development and after its deployment.
To understand the UML, we need to form a conceptual model of the language and this requires
learning three major elements.
The Rules that direct how those building blocks may be put together. Some common mechanisms that
apply throughout the UML. As UML describes the real time systems it is very important to make a
conceptual model and then proceed gradually. Conceptual model of UML can be mastered by learning
the following three major elements:
Defined as:
Things
Relationships
Diagrams
Things:
Things are the most important building blocks of UML. Things can be:
Structural
Behavioral
Grouping
Annotational
Structural things:
The Structural things define the static part of the model. They represent physical a
Conceptual elements. Following are the brief descriptions of the structural things.
Class:
Interface:
Use case represents a set of actions performed by a system for a specific goal.
Component:
Node: A node can be defined as a physical element that exists at run time.
Behavioral things:
A behavioral thing consists of the dynamic parts of UML models. Following are the behavioral things:
Interaction:
Interaction is defined as a behavior that consists of a group of messages exchanged among elements to
accomplish a specific task.
State machine:
State machine is useful when the state of an object in its life cycle is important. It defines the sequence
of states an object goes through in response to events. Events are external factors responsible for state
change.
Grouping things:
Grouping things can be defined as a mechanism to group elements of a UML model together. There is
only one grouping thing available.
Package: Package is the only one grouping thing available for gathering structural and behavioral
things.
Relationships in UML:
Relationship is another most important building block of UML. It shows how elements are associated
with each other and this association describes the functionality of an application. There are four kinds
of relationships available.
Dependency:
Dependency is a relationship between two things in which change in one element also affects the other
one.
Association:
Association is basically a set of links that connects elements of an UML model. It also describes how
many objects are taking part in that relationship.
Generalization:
Realization:
Realization can be defined as a relationship in which two elements are connected. One element
describes some responsibility which is not implemented and the other one implements them. This
relationship exists in case of interfaces.
UML diagrams are the ultimate output of the entire discussion. All the elements,
Relationships are used to make a complete UML diagram and the diagram represents a System. The
visual effect of the UML diagram is the most important part of the entire process. All the other
elements are used to make it a complete one.
UML includes the following nine diagrams and the details are described in the following
Class diagram
Object diagram
Use case diagram
Sequence diagram
Collaboration diagram
Activity diagram
State chart diagram
Deployment diagram
Component diagram
Any real world system is used by different users. The users can be developers, testers, business people,
analysts and many more. So before designing a system the architecture is made with different
perspectives in mind. The most important part is to visualize the system from different viewer’s
perspective. The better we understand the better we make the system. UML plays an important role in
defining different perspectives of a system. These perspectives are:
Design
Implementation
Process
Deployment
And the centre is the Use Case view which connects all these four. A Use case represents the
functionality of the system. So the other perspectives are connected with use case.
Design of a system consists of classes, interfaces and collaboration. UML provides class diagram,
object diagram to support this. Implementation defines the components assembled together to make a
complete physical system. UML component diagram is used to support implementation perspective.
Process defines the flow of the system. So the same elements as used in Design are also used to
support this perspective.
Deployment represents the physical nodes of the system that forms the hardware. UML deployment
diagram is used to support this perspective.
The software to be designed will control a simulated automated teller machine (ATM) having a
magnetic stripe reader for reading an ATM card, a customer console (keyboard and display) for
interaction with the customer, a slot for depositing envelopes, a dispenser for cash, a printer for
printing customer receipts, and a key-operated switch to allow an operator to start or stop the machine.
The ATM will communicate with the bank’s computer over an appropriate communication link. (The
software on the latter is not part of the requirements for this problem.)
The ATM will service one customer at a time. A customer will be required to insert an ATM card and
enter a personal identification number (PIN) – both of which will be sent to the bank for validation as
part of each transaction. The customer will then be able to perform one or more transactions. The card
will be retained in the machine until the customer indicates that he/she desires no further transactions,
at which point it will be returned – except as noted below.
The ATM must be able to provide the following services to the customer:
1. A customer must be able to make a cash withdrawal from any suitable account linked to the
card. Approval must be obtained from the bank before cash is dispensed.
2. A customer must be able to make a deposit to any account linked to the card, consisting of cash
and/or checks in an envelope. The customer will enter the amount of the deposit into the ATM,
subject to manual verification when the envelope is removed from the machine by an operator.
Approval must be obtained from the bank before physically accepting the envelope.
3. A customer must be able to make a transfer of money between any two accounts linked to the
card.
4. A customer must be able to make a balance inquiry of any account linked to the card.
5. A customer must be able to abort a transaction in progress by pressing the Cancel key instead
of responding to a request from the machine.
The ATM will communicate each transaction to the bank and obtain verification that it was allowed by
the bank. Ordinarily, a transaction will be considered complete by the bank once it has been approved.
If the bank determines that the customer’s PIN is invalid, the customer will be required to re-enter the
PIN before a transaction can proceed. If the customer is unable to successfully enter the PIN after three
tries, the card will be permanently retained by the machine, and the customer will have to contact the
bank to get it back.
If a transaction fails for any reason other than an invalid PIN, the ATM will display an explanation of
the problem, and will then ask the customer whether he/she wants to do another transaction.
The ATM will provide the customer with a printed receipt for each successful transaction, showing the
date, time, machine location, type of transaction, account(s), amount, and ending and available
balance(s) of the affected account (“to” account for transfers).
The ATM will have a key-operated switch that will allow an operator to start and stop the servicing of
customers. After turning the switch to the “on” position, the operator will be required to verify and
enter the total cash on hand. The machine can only be turned off when it is not servicing a customer.
When the switch is moved to the “off” position, the machine will shut down, so that the operator may
remove deposit envelopes and reload the machine with cash, blank receipts, etc.
2. THEORY:
The class diagram is a static diagram. It represents the static view of an application. Class diagram is
not only used for visualizing, describing and documenting different aspects of a system but also for
constructing executable code of the software application. The class diagram describes the attributes
and operations of a class and also the constraints imposed on the system. The class diagram shows a
collection of classes, interfaces, associations, collaborations and constraints. It is also known as a
structural diagram.
Purpose:
The purpose of the class diagram is to model the static view of an application. The class diagrams are
the only diagrams which can be directly mapped with object oriented languages and thus widely used
at the time of construction. The UML diagrams like activity diagram, sequence diagram can only give
the sequence Flow of the application but class diagram is a bit different. So it is the most popular UML
diagram in the coder community. So the purpose of the class diagram can be summarized as:
Contents:
Classes
Interfaces
AIM: To design and implement Use case diagram for ATM system
THEORY: A Use case Diagram is a diagram that shows a set of Use cases and actors and their
relationships. These diagrams are used to model the static use case view of a system.
To model a system the most important aspect is to capture the dynamic behaviour. To clarify a bit in
details, dynamic behaviour means the behaviour of the system when it is running /operating. So only
static behaviour is not sufficient to model a system rather dynamic behaviour is more important than
static behaviour. In UML there are five diagrams available to model dynamic nature and use case
diagram is one of them. Now as we have to discuss that the use case diagram is dynamic in nature
there should be some internal or external factors for making the interaction.These internal and external
agents are known as actors. So use case diagrams are consists of actors, use cases and their
relationships. The diagram is used to model the system/subsystem ofan application. A single use case
diagram captures a particular functionality of a system. So to model the entire system numbers of use
case diagrams are used.
Purpose:
The purpose of use case diagram is to capture the dynamic aspect of a system. But this definition is too
generic to describe the purpose. Because other four diagrams (activity, sequence, collaboration and
Statechart) are also having the same purpose. So we will look into some specific purpose which will
distinguish it from other four diagrams. Use case diagrams are used to gather the requirements of a
system including internal and external influences. These requirements are mostly design requirements.
So when a system is analyzed to gather its functionalities use cases are prepared and actors are
identified.
So in brief, the purposes of use case diagrams can be as follows:
Enter pin
Withdraw
user atm
Deposit
Balance enquiry
cancel
admin1 check
A withdrawal transaction asks the customer to choose a type of account to withdraw from (e.g.
checking) from a menu of possible accounts, and to choose a dollar amount from a menu of possible
amounts. The system verifies that it has sufficient money on hand to satisfy the request before sending
the transaction to the bank. (If not, the customer is informed and asked to enter a different amount.) If
the transaction is approved by the bank, the appropriate amount of cash is dispensed by the machine
before it issues a receipt. A withdrawal transaction can be cancelled by the customer pressing the
Cancel key any time prior to choosing the dollar amount.
A deposit transaction asks the customer to choose a type of account to deposit to (e.g. checking) from a
menu of possible accounts, and to type in a dollar amount on the keyboard. The transaction is initially
sent to the bank to verify that the ATM can accept a deposit from this customer to this account. If the
transaction is approved, the machine accepts an envelope from the customer containing cash and/or
checks before it issues a receipt. Once the envelope has been received, a second message is sent to the
bank, to confirm that the bank can credit the customer’s account – contingent on manual verification of
the deposit envelope contents by an operator later.
A deposit transaction can be cancelled by the customer pressing the Cancel key any time prior to
inserting the envelope containing the deposit. The transaction is automatically cancelled if the
customer fails to insert the envelope containing the deposit within a reasonable period of time after
being asked to do so.
Transfer UseCase
A transfer transaction asks the customer to choose a type of account to transfer from (e.g. checking)
from a menu of possible accounts, to choose a different account to transfer to, and to type in a dollar
amount on the keyboard. No further action is required once the transaction is approved by the bank
before printing the receipt.
A transfer transaction can be cancelled by the customer pressing the Cancel key any time prior to
entering a dollar amount.
An inquiry transaction asks the customer to choose a type of account to inquire about from a menu of
possible accounts. No further action is required once the transaction is approved by the bank before
printing the receipt. An inquiry transaction can be cancelled by the customer pressing the Cancel key
any time prior to choosing the account to inquire about.
ValidateUser usecase:
If the customer fails three times to enter the correct PIN, the card is permanently retained, a screen is
displayed informing the customer of this and suggesting he/she contact the bank, and the entire
customer session is aborted.
PrintBill usecase
This usecase is for printing corresponding bill after transactions(withdraw or deposit ,or balance
enquiry, transfer) are completed.
Update Account
This usecase is for updating corresponding user accounts after transactions (withdraw or deposit or
transfer) are completed
3. Interaction diagrams
We have two types of interaction diagrams in UML. One is sequence diagram and the other is a
collaboration diagram. The sequence diagram captures the time sequence of message flow from one
object to another and the collaboration diagram describes the organization of objects in a system taking
part in the message flow.
So the following things are to identified clearly before drawing the interaction diagram:
Objects
Focus of control
Messages
Life line
Contents.
Objects
Links
Messages
THEORY: A Sequence diagram is an interaction diagram that emphasizes the time ordering of
messages.This diagram is used to show the dynamic view of a system.
THEORY: A Usecase diagram is a diagram that shows a set of use cases and actors and their
relationships. These diagrams are used to model the static usecase view of a system.
1: check pin no
3: check account
5: check amount
7: update account
ATM ADMIN
2: pin valid/invalid
4: display status
6: display status
5. STATECHART Diagram
Statechart diagram is used to model dynamic nature of a system. They define different states of an
object during its lifetime. And these states are changed by events. So Statechart diagrams are useful to
model reactive systems. Reactive systems can be defined as a system that responds to external or
internal events.
Statechart diagram describes the flow of control from one state to another state. States are defined as a
condition in which an object exists and it changes when some event is triggered. So the most important
purpose of Statechart diagram is to model life time of an object from creation to termination.
Statechart diagrams are also used for forward and reverse engineering of a system. But the main
purpose is to model reactive system.
Contents
Common use
AIM: To design and implement State chart diagram for ATM system
THEORY: A statechart diagram shows a state machine, emphazing the flow of control from state to
state .A state machine is a behavior that specifies the sequences of states an object goes through during
its life time in response to events together with responses to those events. We can use these diagrams
to model the dynamic view of a system.
THEORY: An activity diagram shows the flow from activity to activity .An activity is an ongoing non
atomic execution within a state machine .Activities ultimately results in some action, which is made up
of executable atomic computations. We can use these diagrams to model the dynamic aspects of a
system.
Activity diagram is basically a flow chart to represent the flow form one activity to another. The
activity can be described as an operation of the system. So the control flow is drawn from one
operation to another. This flow can be sequential, branched or concurrent. Activity diagrams deals with
all type of flow by using elements like fork, join etc.
Fork
A fork represents the splitting of a single flow of control into two or more concurrentFlow of control.
A fork may have one incoming transition and two or more outgoing transitions, each of which
represents an independent flow of control. Below fork the activities associated with each of these path
continues in parallel.
Join
A join represents the synchronization of two or more concurrent flows of control. A join may have two
or more incoming transition and one outgoing transition. Above the join the activities associated with
each of these paths continues in parallel.
Branching
A branch specifies alternate paths takes based on some Boolean expression Branch is represented by
diamond Branch may have one incoming transition and two or more outgoing one on each outgoing
transition, you place a Boolean expression shouldn’t overlap but they should cover all possibilities.
Swimlane:
Swimlanes are useful when we model workflows of business processes to partition the activity states
on an activity diagram into groups. Each group representing the business organization responsible for
those activities, these groups are called Swimlanes.
THEORY:
Component diagrams are used to model physical aspects of a system. Now the question is what are
these physical aspects? Physical aspects are the elements like executables, libraries, files, documents
etc which resides in a node. So component diagrams are used to visualize the organization and
relationships among components in a system. These diagrams are also used to make executable
systems.
Purpose:
A single component diagram cannot represent the entire system but a collection of
Before drawing a component diagram the following artifacts are to be identified clearly:
Use a meaningful name to identify the component for which the diagram is to be drawn.
Prepare a mental layout before producing using tools.
Use notes for clarifying important points.
Contents
THEORY:
Deployment diagrams are used to visualize the topology of the physical components of a system where
the software components are deployed. So deployment diagrams are used to describe the static
deployment view of a system. Deployment diagrams consist of nodes and their relationships.
Purpose:
The name Deployment itself describes the purpose of the diagram. Deployment diagrams
are used for describing the hardware components where software components are deployed.
Deployment diagram