Vedant 9564 Batch B
Vedant 9564 Batch B
r.
S Experiment Title ubmission Remarks
S
No. Date
lass
C : T.E. (Computer)
Subject Name :System Programming and Compiler Construction
Subject Code :(CPC601)
1
Practical No:
02/02/2024
Date of Performance:
Vedant Pathare
Name of the Student:
Evaluation:
ALGORITHM
tep1:Start the program for performing insert, display,delete, search and modify option
S
in symbol table
Step2: Define the structure of the Symbol Table
Step3:Enter the choice for performing the operationsin the symbol Table
Step4:If the entered choice is 1, search the symboltable for the symbol to be inserted. If
the symbol is
already present, it displays “Duplicate Symbol”. Else, insert the symbol and the
corresponding address in
the symbol table.
Step5:If the entered choice is 2, the symbols presentin the symbol table are displayed.
Step6: If the entered choice is 3, the symbol to bedeleted is searched in the symbol table.
Step7: If it is not found in the symbol table it displays“Label Not found”. Else, the
symbol is deleted.
Step8:If the entered choice is 5, the symbol to bemodified is searched in the symbol
table.
Source Code:
import java.util.ArrayList;
import java.util.Scanner;
FR. CONCEICAO RODRIGUES COLLEGE OF ENGINEERING
while(true) {
switch(choice) {
case '1':
System.out.print("Enter symbol to add: ");
char symbol = sc.next().charAt(0);
sc.nextLine();
Token token = new Token(symbol);
symbolTable.addToken(token);
break;
case '2':
System.out.print("Enter symbol to delete: ");
char symbol1 = sc.next().charAt(0);
sc.nextLine();
Token token1 = new Token(symbol1);
symbolTable.deleteToken(token1);
break;
case '3':
System.out.print("Enter symbol to search: ");
char symbol2 = sc.next().charAt(0);
sc.nextLine();
Token token2 = new Token(symbol2);
symbolTable.searchToken(token2);
break;
case '4':
FR. CONCEICAO RODRIGUES COLLEGE OF ENGINEERING
case '5':
symbolTable.displayTable();
break;
case '6':
System.out.println("Program terminated!");
sc.close();
System.exit(0);
break;
default:
System.out.println("Invalid choice!");
}
System.out.println();
}
}
}
class Token {
}
}
class SymbolTable {
public SymbolTable() {
tokens = new ArrayList<>();
}
Screenshots:
1. Insert
FR. CONCEICAO RODRIGUES COLLEGE OF ENGINEERING
2. Delete
FR. CONCEICAO RODRIGUES COLLEGE OF ENGINEERING
3. Search
FR. CONCEICAO RODRIGUES COLLEGE OF ENGINEERING
4. Modify
FR. CONCEICAO RODRIGUES COLLEGE OF ENGINEERING
5. Display
Postlab Questions:
1. E xplain different phases of compiler. Illustrate all the output after each phase for the
following statement
a= b +c -d *5
FR. CONCEICAO RODRIGUES COLLEGE OF ENGINEERING
09/02/2024
Date of Submission:
9564
Roll No:
Vedant Pathare
Name of the Student:
Evaluation:
Experiment No 2
Theory:
TH
ERO
LE OFLE
XICALAN
ALYZER
The lexical analyzer is the first phase of a compiler. Its main task is to read the input
c haracters and produce as output a sequence of tokens that the parser uses for syntax analysis. Upon
receiving a “get next token” command from the parser, the lexical analyzer reads input characters
until it can identify the next token.
Source Code:
import java.util.ArrayList;
import java.util.Scanner;
import java.io.File;
import java.util.Arrays;
public RefinedSymbolTable() {
tokens = new ArrayList<>();
}
Output:
SPCC_Data.txt
Conclusion:Thus, we have successfully read file input consisting of various expressions and
converted them into tokens stored in the symbol table.
Post Lab Questions:
. E
1 xplain the role of automata theory in compiler design.
2. What are the errors that are handled by the Lexical analysis phase?
FR. CONCEICAO RODRIGUES COLLEGE OF ENGINEERING
lass
C : T.E. (Computer)
Subject Name :System Programming and Compiler Construction
Subject Code :(CPC601)
3
Practical No:
Design recursive descent parser
Title:
09/02/2024
Date of Performance:
9564
Roll No:
Vedant Pathare
Name of the Student:
Evaluation:
Experiment No 3
Procedure for E
otethatthe'next'looksaheadandalwaysprovidesthenextcharacterthatwillbereadfrom
N
theinputstream.Thisfeatureisessentialifwewishourparserstobeabletopredictwhatis
due to arrive as input.
ote that 'errorhandler' is a procedure that notifies the user that a syntax error has been made
N
and then possibly terminates execution.
I n order to recognize a T, the parser must figure out which of the productions to execute. This
is not difficult and is done in the procedure that appears below.
Procedure for T
I n the above routine, the parser determines whether T had the form (E) or x. If not then the
error routine was called, otherwise the appropriate terminals and nonterminals were
recognized.
FR. CONCEICAO RODRIGUES COLLEGE OF ENGINEERING
Algorithm:
1. Make grammar suitable for parsing i.e. remove left recursion(if required).
2. Write a function for each production with error handler.
3 . Given input is said to be valid if input is scanned completely and no error function is
called.
Source Code:
import java.util.Scanner;
}
class RecursiveDecentParser {
private String input;
private Scanner inputScanner;
RecursiveDecentParser() {
acceptInputString();
inputScanner = new Scanner(input);
}
}
FR. CONCEICAO RODRIGUES COLLEGE OF ENGINEERING
Output:
onclusion:Thus,wehavesuccessfullyimplementedarecursivedescentparserandverified
C
that it can correctly parse valid strings.
Postlab:
1. What is left Recursion ? Write the rules for removing left recursion.
2. What is left factoring ? Write rules for eliminating left factoring.
3. Difference between top down and Bottom up parsing
FR. CONCEICAO RODRIGUES COLLEGE OF ENGINEERING
lass
C : T.E. (Computer)
Subject Name :System Programming and Compiler Construction
Subject Code :(CPC601)
4
Practical No:
To generate an Intermediate code.
Title:
16/02/2024
Date of Performance:
9564
Roll No:
Vedant Pathare
Name of the Student:
Evaluation:
Experiment No 4
● I f a compiler translates the source language to its targetmachinelanguagewithout
havingtheoptionforgeneratingintermediatecode,thenforeachnewmachine,afull
native compiler is required.
● I ntermediate code eliminates the need of a new full compiler for every unique
machine by keeping the analysis portion same for all the compilers.
● The second part of compiler, synthesis, is changed according to the target machine.
● I t becomes easier to apply the source code modifications to improve code
performance by applying code optimization techniques on the intermediate code.
● r being used as registers in the target program.
● Athree-addresscodehasatmostthreeaddresslocationstocalculatetheexpression.
A three-address code can be represented in two forms : quadruples and triples.
FR. CONCEICAO RODRIGUES COLLEGE OF ENGINEERING
Quadruples
ach instruction in quadruplespresentationisdividedintofourfields:operator,arg1,arg2,
E
and result. The above example is represented below in quadruples format:
Triples
ach instruction in triples presentation has three fields : op, arg1, and arg2.The resultsof
E
respective sub-expressions are denoted by the position of expression. Triples represent
similarity with DAG and syntax tree. They are equivalent to DAG while representing
expressions.
= (2)
riples face the problem of code immovability while optimization, as the results are
T
positional and changing the order or position of an expression may cause problems.
FR. CONCEICAO RODRIGUES COLLEGE OF ENGINEERING
Indirect Triples
hisrepresentationisanenhancementovertriplesrepresentation.Itusespointersinsteadof
T
positiontostoreresults.Thisenablestheoptimizerstofreelyre-positionthesub-expression
to produce an optimized code.
Source Code:
import java.util.Scanner;
while (true) {
System.out.println("Generatethree-addresscodefor:1)Assignment2)Conditional
3)Indexed Assignment 4)Copy 5)Exit");
System.out.print("Enter your choice: ");
int choice = scanner.nextInt();
scanner.nextLine();
System.out.println();
switch (choice) {
case 1:
generateAssignmentCode();
break;
case 2:
generateConditionalCode();
break;
case 3:
generateIndexedAssignmentCode();
break;
case 4:
generateCopyCode();
break;
case 5:
System.out.println("Exiting...");
scanner.close();
System.exit(0);
default:
System.out.println("Invalid choice. Please enter a number from 1 to 5.");
}
System.out.println();
FR. CONCEICAO RODRIGUES COLLEGE OF ENGINEERING
}
}
ystem.out.println("Three-address code:");
S
System.out.println(code.toString());
}
ystem.out.println("Three-address code:");
S
System.out.println(code.toString());
}
ystem.out.println("Three-address code:");
S
System.out.println(code.toString());
}
}
Output:
FR. CONCEICAO RODRIGUES COLLEGE OF ENGINEERING
Postlab Question
1. Write the intermediate code generated for ---- while ( a<b ) do
If ( c< d) then
X= y+z
Else
X= y-z
2. Write the intermediate code generated for ---- switch E
Begin
case V1: S1
case V2: S2
….
default: Sn
end
FR. CONCEICAO RODRIGUES COLLEGE OF ENGINEERING
lass
C : T.E. (Computer)
Subject Name :System Programming and Compiler Construction
Subject Code :(CPC601)
5
Practical No:
Study of Lexical analyzer tool -Flex/Lex
Title:
01/03/2024
Date of Performance:
9564
Roll No:
Vedant Pathare
Name of the Student:
Evaluation:
Experiment No 5
Lex is a program generator designed for lexical processing of character input streams.
Itaccepts a high-level, problem oriented specification for character string matching,
andproduces a program in a general purpose language which recognizes regular
expressions.The regular expressions are specified by the user in the source specifications
given to Lex.The Lex written code recognizes these expressions in an input stream and
partitions theinput stream into strings matching theexpressions.Attheboundariesbetween
stringsprogram sections provided by the user are executed. The Lex source file associates
theregular expressions and the program fragments. As each expressionappearsintheinput
tothe programwrittenbyLex,thecorrespondingfragmentisexecuted.Theusersuppliesthe
additionalcodebeyondexpressionmatchingneededtocompletehistasks,possiblyincluding
codewrittenbyothergenerators.Theprogramthatrecognizestheexpressionsisgeneratedin
thegeneralpurposeprogramminglanguageemployedfortheuser'sprogramfragments.Thus,
a high level expression language is provided to write thestring expressions to be matched
while the user's freedom to write actions isunimpaired. This avoids forcing the user who
wishes touseastringmanipulationlanguageforinputanalysistowriteprocessingprograms
in the same and ofteninappropriate string handling language.
Lex is not a complete language, but rather a generator representing a new language
featurewhichcanbeaddedtodifferentprogramminglanguages,called̀`hostlanguages.''Just
asgeneral purpose languages can produce code to run on different computer hardware,
Lexcan write code in different host languages. The host language is used for the output
codegenerated by Lex and also for the program fragments added by the user. Compatible
runtimelibraries for the different host languages are also provided. This makes Lex
adaptabletodifferentenvironmentsanddifferentusers.LexitselfexistsonUNIX,GCOS,and
OS/370;butthecodegeneratedbyLexmaybetakenanywherewhereappropriatecompilers
exist.
FR. CONCEICAO RODRIGUES COLLEGE OF ENGINEERING
Lex turns the user's expressions and actions (called source in this pic) into the
hostgeneral-purpose language; the generated program is named yylex. The yylex program
willrecognize expressions in a stream (called input in this pic) and perform the
specifiedactions for each expression as it is detected.
For a trivial example, consider a program to delete from the input all blanks or tabs at the
ends of lines.
%%
[ \t]+$ ;
is all that is required. The program contains a %% delimiter to mark the beginning of
therules, and one rule. This rule contains a regular expression which matches one or
moreinstances of the charactersblankortab(written\tforvisibility,inaccordancewiththe
Clanguageconvention)justpriortotheendofaline.Thebracketsindicatethecharacterclass
madeofblankandtab;the+indicates̀`oneormore...'';andthe$indicates̀`endofline,''as
in QED. No action is specified, so the program generated by Lex (yylex) willignore these
characters.Everythingelsewillbecopied.Tochangeanyremainingstringofblanksortabsto
a single blank, add another rule:
%%
FR. CONCEICAO RODRIGUES COLLEGE OF ENGINEERING
[ \t]+$ ;
Lexcanbeusedaloneforsimpletransformations,orforanalysisandstatisticsgatheringona
lexical level. Lex can also be used with a parser generator to perform the lexicalanalysis
phase.
{definitions}
%%
{rules}
%%
{user subroutines}
wherethedefinitionsandtheusersubroutinesareoftenomitted.Thesecond%%isoptional,
but the first is required to mark the beginning of the rules. The absoluteminimum Lex
program is thus
%%
(nodefinitions,norules)whichtranslatesintoaprogramwhichcopiestheinputtotheoutput
unchanged.In the outline of Lex programs shown above, the rules represent the user's
controldecisions; theyareatable,inwhichtheleftcolumncontainsregularexpressionsand
the rightcolumn contains actions, program fragments to be executed when the expressions
arerecognized. Thus an individual rule mightappearintegerprintf("foundkeywordINT");to
look for the string integer in the input stream and print the message ̀`found keyword
FR. CONCEICAO RODRIGUES COLLEGE OF ENGINEERING
INT''whenever it appears. In this example the host procedural language is C and the C
libraryfunctionprintfisusedtoprintthestring.Theendoftheexpressionisindicatedbythe
firstblankortabcharacter.IftheactionismerelyasingleCexpression,itcanjustbegivenon
theright side of the line; if it is compound, ortakesmorethanaline,itshouldbeenclosed
inbraces.
Implementation Details:
2. Enter keywords, rules for identifier and constant, operators and relational operators. In
a) %{
%}
%%
Transition rules
%%
4. Call lex tool on the terminal e.g. [root@localhost]# lex Mylex.l This lex tool will convert
5. Compile the file lex.yy.c e.g.gcc lex.yy.c.Aftercompiling the file lex.yy.c, this will
7. Give input on the terminal to thea.outfile uponprocessing output will be displayed
Sample Code
{
%
#include<stdio.h>
int key_word=0;
%}
%%
"include"|"for"|"define" {key_word++;}
%%
int main()
{
printf("enter the sentence");
yylex();
printf("keyword are: %d\n ",key_word);
}
int yywrap() { return 1; }
%{
#include <stdio.h>
%}
%%
FR. CONCEICAO RODRIGUES COLLEGE OF ENGINEERING
[aeiouAEIOU] vowels++;
[a-zA-Z] consonants++;
[\n] ;
. ;
%%
int main()
{
printf ("This Lex program counts the number of vowels and ");
yylex();
return 0;
}
Output:
#lex alphalex.l
#gcc lex.yy.c
#./a.out
This Lex program counts the number of vowels and consonants in given text.
Iceream
Test Cases:
Conclusion:
FR. CONCEICAO RODRIGUES COLLEGE OF ENGINEERING
Theory:
arser for a grammar is a program which takes in the language string as its input and
P
produces either acorrespondingparsetreeoraerror.SyntaxofaLanguageTheruleswhich
tellswhetherastringisavalidprogramornotarecalledthesyntaxSemanticsofLanguage
TheruleswhichgivemeaningtoprogramsarecalledthesemanticofalanguageTokensWhen
a string representing a program is broken into sequence of substrings, such that each
substring represents a constant, identifier, operator, keyword etc of the language, these
substrings are called the tokens of the language.
Lexical Analysis
hefunctionoflexicalAnalyzeristoreadtheinputstreamrepresentingthesourceprogram,
T
one character at a time and translate into valid tokens.
I mplementation Details
1: Create a lex file
1. Definitions
2. Rules
efinitionsconsistsofanyexternal‘C’definitionsusedinthelexactionsorsubroutines.The
D
other types of definitions are definitions are lex definitions which are essentially the lex
substitutionstrings,lexstartstatesandlextablesizedeclarations.Therulesisthebasicpart
whichspecifiestheregularexpressionsandtheircorrespondingactions.TheuserSubroutines
are the functions that are used in the Lex actions.
2:YaccistheUtilitywhichgeneratesthefunction‘yyparse’whichisindeedtheParser.Yacc
describes a context free, LALR(1) grammer and supports both bottom up and top-down
parsing. The general format for the yacc file is very similar to that of the lex file.
1. Declarations
3. Subroutines
Yacc Rule-
he general style of coding the rules is to have all Terminals in lower –case and all
T
non-terminals in upper –case.
o facilitate a proper syntax directed translation the Yacc has something calls
T
pseudo-variableswhichformsabridgebetweenthevaluesofterminals/non-terminalsand
theactions.Thesepseudovariablesare$$,$1,$2,$3,………….The$$istheL.H.Svalue
of the rulewhereas$1isthefirstR.H.Svalueoftherule,soisthe$2etc.Thedefault
type for pseudo variables is integer unless they are specified by % type.
%token <type> etc.
Perform the following steps, in order, to create the desk calculator example program:
FR. CONCEICAO RODRIGUES COLLEGE OF ENGINEERING
1. P
rocess theyaccgrammar file using the-doptional flag (which tells theyacc
command to create a file that defines the tokens used in addition to the C language
source code):
yacc -d calc.yacc
lex.yy.c The C language source file that thelexcommand createdfor the lexical
analyzer.
cc y.tab.c lex.yy.c
6. U
se thelicommand to verify that the following fileswere created:
y.tab.o The object file for they.tab.csource file
lex.yy.o The object file for thelex.yy.csource file
a.out The executable program file
Source Code:
1. Program to count the number of vowels and consonants in a given string.
%{
# include<stdio.h>
int vowels=0;
int consonants=0;
}
%
%%
[aeiouAEIOU] vowels++;
[a-zA-Z] consonants++;
[\n] ;
FR. CONCEICAO RODRIGUES COLLEGE OF ENGINEERING
. ;
%%
int main()
{
printf("This Lex program counts the number of vowels and consonants in given
text.");
printf("\nEnter the text and terminate it with CTRL-d.\n");
yyin = stdin;
yylex();
printf("Vowels = %d, consonants = %d.\n", vowels, consonants);
return 0;
}
int yywrap() {
return 1;
}
2 . Program to count the number of characters, words, spaces, end of linesinagiveninput
file.
%{
# include<stdio.h>
int c=0, w=0, s=0, l=0;
}
%
WORD [^ \t\n,\.]+
EOL [\n]
BLANK [ ]
%%
{WORD} {w++; c=c+yyleng;}
{BLANK} {s++;}
{EOL} {l++;}
, {c++;}
%%
int yywrap() {
FR. CONCEICAO RODRIGUES COLLEGE OF ENGINEERING
return 1;
}
int main(int argc, char *argv[]) {
if(argc!=2) {
printf("Usage: <./a.out> <sourcefile>\n");
exit(0);
}
yyin = fopen(argv[1], "r");
yylex();
printf("Noofcharacters=%d\nNoofwords=%d\nNoofspaces=%d\nNooflines=
%d\n", c,w,s,l);
}
%{
# include<stdio.h>
int posint=0, negint=0, posfraction=0, negfraction=0;
}
%
%%
[-][0-9]+ {negint++;}
[+]?[0-9]+ {posint++;}
[+]?[0-9]*\.[0-9]+ {posfraction++;}
[-][0-9]*\.[0-9]+ {negfraction++;}
%%
int yywrap() {
FR. CONCEICAO RODRIGUES COLLEGE OF ENGINEERING
return 1;
}
int main(int argc, char *argv[]) {
if(argc!=2) {
printf("Usage: <./a.out> <sourcefile>\n");
exit(0);
}
yyin = fopen(argv[1], "r");
yylex();
printf("No of +ve integers=%d\nNo of -ve integers=%d\nNo of +ve
fractions=%d\nNo of -ve fractions=%d\n", posint, negint, posfraction, negfraction);
}
4 .ProgramtocountthenumberofcommentlinesinagivenCprogram,eliminatethemand
copy that program into separate file.
%{
# include<stdio.h>
int com=0;
}
%
%s COMMENT
%%
"/*"[.]*"*/" {com++;}
"/*" {BEGIN COMMENT ;}
<COMMENT>"*/" {BEGIN 0; com++ ;}
<COMMENT>\n {com++;}
FR. CONCEICAO RODRIGUES COLLEGE OF ENGINEERING
COMMENT>. {;}
<
.|\n {fprintf(yyout, "%s", yytext);}
%%
int yywrap() {
return 1;
}
int main(int argc, char *argv[]) {
if(argc!=3) {
printf("Usage: a.out source destination\n");
exit(0);
}
yyin=fopen(argv[1], "r");
yyout=fopen(argv[2], "w");
yylex();
printf("No of comment lines=%d\n", com);
}
FR. CONCEICAO RODRIGUES COLLEGE OF ENGINEERING
%{
# include<stdio.h>
int opr=0, opd=0;
}
%
%%
[\+\-\*\/\=] {printf("OPERATORS ARE %s\n", yytext); opr++;}
[a-zA-Z]+ {printf("OPERANDS ARE %s\n", yytext); opd++;}
[0-9]+ {printf("OPERANDS ARE %s\n", yytext); opd++;}
%%
int yywrap() {
return 1;
}
int main() {
printf("Enter the Expression:\n");
yylex();
printf("\nNUMBER OF OPERATORS ARE %d\n", opr);
printf("NUMBER OF OPERANDS ARE %d\n", opd);
}
FR. CONCEICAO RODRIGUES COLLEGE OF ENGINEERING
Conclusion:
e have successfullyexperimentedwiththeLex&Yacctool,enhancingourunderstanding
W
of compiler construction and lexical analysis.
Postlab:
lass
C : T.E. (Computer)
Subject Name :System Programming and Compiler Construction
Subject Code :(CPC601)
Vedant Pathare
Name of the Student:
Evaluation:
Experiment No 6
Aim: Generate a target code for the optimized code.
Algorithm:
he final phase in compiler model is the code generator. It takes as input an intermediate
T
representation of the source program and produces as output an equivalent target program.
he code generation algorithm takes as input a sequence of three address statements
T
constitutingabasicblock.Foreachthreeaddressstatementoftheformx=yopzweperform
following function:
1 .InvokeafunctiongetregtodeterminethelocationLwheretheresultofcomputationyop
z should be stored. ( L cab be a register or memory location .
3 .Generateinstructionpoz,Lwherezisacurrentlocationofz.Againaddressdescriptorof
x to indicatethatxisinlocationL.ifLisaregister,updateitsdescriptortoindicatethatit
contains the value of x, and remove x from all other register descriptor.
4 .Ifthecurrentvaluesofyandzhavenonextuses,arenotliveonexitfromtheblock,and
areinregistersaltertheregisterdescriptortoindicatethat,afterexecutionofx=yopz,those
register no longer will contain y and z, resply.
ight be one whose data is referenced furthest in thefuture,oronewhosevalueisalsoin
m
memory. We leave the exact choice unspecified, since there is no one proven best way to
make the selection.
4 .Ifxisnotusedintheblock,ornosuitableoccupiedregistercanfound,selectthememory
location of x as L.
Source Code:
def allocateRegister(operand):
if operand in registers.values(): # Operand already present in one of the registers, use it
for key, value in registers.items():
if operand == value:
return key
else:
register_name = "R" + str(len(registers)) # Allocate a new register for the operand
registers[register_name] = operand # Assign operand to register
output_code.append("MOV"+operand+","+register_name) #AddMOVstatementto
output
return register_name
def renameReg(location,operand):
if operand in registers.values():
for key, value in registers.items():
if operand==value:
registers[key]=location
#print(registers)
output_code.append(output_line)
Output:
FR. CONCEICAO RODRIGUES COLLEGE OF ENGINEERING
Conclusion:
hus,wehavesuccessfullygeneratedtargetcode(Assemblylanguagecode)fromthegiven
T
intermediate code and have satisfactorily demonstrated the code generation phase of a
compiler.
Postlab:
Explain design issues of code generator phase?
What are basic blocks? State their properties
FR. CONCEICAO RODRIGUES COLLEGE OF ENGINEERING
Evaluation:
Experiment No 7
Algorithm:
Pass 1:
1. Start
Go to step 9
5.2 If it is ‘EQU’
Go to step 3
5.4 If it is ‘END’
Go to step 3
6. Search opcode in Machine Opcode Table.
8. Process any literals and enter them into literal Table.
12. Stop.
Pass2:
1.Start
5.3 If it is ‘USING’
Evaluate operand and enter base reg no. and value into base table
Go to step 3
5.4 If it is ‘DROP’
5.5 If it is ‘END’
10.1 Evaluate both register expressions and insert into second byte.
11.1 Evaluate register and index expressions and insert into second byte.
13 Stop.
Implementation Details
2. Display output of Pass1 as the output file with Op-code Table, Symbol Table.
3. Display output of pass2 as the Op-code Table, Symbol Table , Copy file.
Test Cases:
Source Code:
1. Pass1:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void main()
{
char opcode[10], mnemonic[10], operand[10], label[10], code[10];
int locctr = 0, start, length, flag = 0;
FILE *fp1, *fp2, *fp3, *fp4;
fp1 = fopen("INPUT.txt", "r");
fp2 = fopen("st.txt", "w");
fp3 = fopen("out.txt", "w");
fp4 = fopen("MOT.txt", "r");
Output:
2. Pass2:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void main()
{
char opcode[10], mnemonic[10], operand[10], operand1[10], label[10], code[10], address[10],
sizeAddress[10], Motlabel[10];
int locctr = 0, start, length, flag = 0;
FILE *fp1, *fp2, *fp3, *fp4, *fp5, *fp6, *fp411;
fp1 = fopen("INPUT.txt", "r");
fp2 = fopen("st.txt", "r");
fp3 = fopen("out.txt", "r");
fp4 = fopen("MOT.txt", "r");
fp411 = fopen("MOT.txt", "r");
fp5 = fopen("bt.txt", "w");
fp6 = fopen("outTable.txt", "w");
Thus, we have successfully implemented a two-pass assembler by developing pass1 and pass2
separately and running the programs sequentially.
12/04/2024
Date of Submission:
9564
Roll No:
Evaluation:
Experiment No 8
Learning Objective:To understand how the pre-processor replaces all the macros in the program by its
real definition prior to the compilation process of the program.
Algorithm:
Pass1:
5. Read next statement from source program (macro name line)
6. Enter Macro name found in step 5 in name field of MNT ( macro name table)
12. Create and substitute index notation for arguments in the source statement if any.
15. Check if currently read source statement is pseudo-opcode MEND. If yes then goto step 3 else goto
step 11.
FR. CONCEICAO RODRIGUES COLLEGE OF ENGINEERING
17.Check if pseudo-opcode END is encountered. If yes goto step 18 else goto step 19
19. Go to step 3
Pass2:
3. If macro name found then goto step 4 else goto step 11.
9. Check if currently retrieved line is pseuodo-opcode MEND, if yes goto step 1 else goto step 10
10. Write statement formed in step 8 to expanded source file and goto step 6
12. Check if pseudo-opcode END encountered, if yes goto step 13 else goto step 1
Implementation Details
2.Display output of Pass1 as the output file, MDT, MNT, and ALA tables.
3.Display output of pass2 as the expanded source file, MDT, MNT and ALA tables.
Test Cases :
Source Code:
include <stdio.h>
#
#include <string.h>
#include <stdlib.h>
int checkIfPresent(char inputOpcode[]) { // this function will return position of macroname in mnt if
present
char macroname[10], mdtpointer[10]; char label[10], opcode[10], operand[10];
FILE *mnptr;
mnptr = fopen("MNT.txt", "r");
fscanf(mnptr, "%s%s", macroname, mdtpointer);
int i = 0;
while (strcmp(macroname, "END") != 0) {
if (strcmp(inputOpcode, macroname) == 0) {
return i;
}
fscanf(mnptr, "%s%s", macroname, mdtpointer);
i++;
}
return -1;
}
int main() {
char opcode[10], mnemonic[10], operand[10], label[10], code[10],macroname[10], opcodemdt[10],
operandmdt[10];
int mdtline[10],locctr = 0, start, length, flag= 0;
FILE *fp1, *fp2, *fp3, *fp4;
fp1 = fopen("Exp8_Input.txt", "r");
fp2 = fopen("MNT.txt", "r");
fp3 = fopen("MDT.txt", "r");
fp4 = fopen("expsrc.txt", "w"); // Ignoring macro definition lines
while (strcmp(opcode,"Start") != 0) {
fscanf(fp1, "%s%s%s", label, opcode, operand);
}
FR. CONCEICAO RODRIGUES COLLEGE OF ENGINEERING
Input:
Source Code Macro Name Table (MNT) Macro Definition Table (MDT)
Output:
FR. CONCEICAO RODRIGUES COLLEGE OF ENGINEERING
onclusion: Thus, we have implemented a two pass macro processor which reads the source program,
C
the MNT and the MDT and generates the expanded source code successfully.