Sunteți pe pagina 1din 19

System Programming (2150708)

Ahmedabad Institute of Technology

Computer Engineering &


Information Technology Department

SYSTEM PROGRAMMING

Laboratory Manual
Year: 2019-2020

Prepared By:Prof. Parekh Madhuri


& Prof Bansari Thakkar

AIT SP
System Programming (2150708)

INDEX

Sr.N Page No.


Experiment Date Marks Signature
o. From To
Write a program to print the content
1. of file and display file content using 1 2
of file pointer
Write a program to implement the
2. 3 6
lexical analyzer.
Write a program to left factor the
3. 7 9
given grammar.
Write a program to remove the Left
4. 10 12
Recursion from a given grammar.
Implement Recursive Descendant
Parsing for the given Grammar.
5. E -> T + E / T 13 17
T -> F * T / F
F -> ( E ) / i
Implement Predictive Parser for the
given grammar.
6. T -> F * T / F 18 26
F -> ( E ) / i
E -> T + E / T
Write a SAL program in text file and
7. 27 32
generate SYMTAB and LITTAB
8. Use macro features of C language. 33 34
Write a program which generates
Quadruple Table for
9. 35 37
the given postfix
String.
Write a C program to parse a given
string using Predictive parsing for
given grammar.
10. type → simple | ↑id | array [ simple ] 38 41
of type
simple → integer | char | num dotdot
num

AIT SP
System Programming (2150708)

Practical-1 Date:-

Write a program to print the content of file and display file content using of file pointer.

#include <stdio.h>
#include <stdlib.h> // For exit() int
main()
{
FILE *fptr;

char filename[100], c;

printf("Enter the filename to open \n");


scanf("%s", filename);

// Open file
fptr = fopen(filename, "r");
if (fptr== NULL)
{
printf("Cannot open file \n");
exit(0);
}

// Read contents from file c =


fgetc(fptr);
while (c != EOF)
{
printf ("%c", c); c =
fgetc(fptr);
}

fclose(fptr); return 0;
}

Output:

Enter the filename to open


a.txt
/*Contents of a.txt*/

Exercise
C program to copy contents of one file to another file

EVALUATION:
Involvement Understanding / Problem solving Timely Completion Total
(4) (3) (3) (10)

Signature with date: ________________

AIT SP 1
System Programming (2150708)

Practical 2 Date:-

Write a program to implement the lexical analyzer.

Software Required:

 Turbo C Compiler

Knowledge Required:

 Concepts of lexical analysis.

Theory/Logic:

 Lexical analysis is a function in which the stream of characters making up the


source program is read from left to right and grouped into tokens that are sequences
of characters having a collective meaning.

 In a compiler, lexical analysis is called linear analysis or Scanning.

 A lexical analyzer reads and converts the input into a stream of tokens to be analyzed
by the parser.
 The sentences of a language consist of string of tokens.

 A sequence of input characters that comprises a single token is called a lexeme.

 A lexical Analyzer can insulate a parser from the lexeme representation of tokens.

 A lexical analyzer generates tokens for any program that is given as an input to it.

 It mainly generates 7 types of tokens: keywords, identifiers, constants,


literals, special symbols, operators, comments.

SOURCE LEXICAL TOKENS

CODE ANALYZER

AIT SP 2
System Programming (2150708)

LEXICAL ANALYSIS COMPLETED


Advantages:
 Simple Design: As Lexical Analyzer is separated from other analysis phases of
compilation, its design becomes simpler and easy to implement.
 Compiler efficiency and portability is improved.
Disadvantages:
 A large amount of time is spent in reading the source program and partitioning it
into tokens.
 So specialized buffering techniques for reading input characters and
processing tokens need to be applied to speed up compiler.
 One more disadvantage is that the lexical analyzer needs to read the whole
symbol table every time an identifier is encountered in the source code.

Application:
 Removal of White Spaces and comments.
 Recognizing Identifiers and Keywords, Recognizing Constants.
Conclusion:

 A Lexical Analyzer reads and converts the input into a stream of tokens to be
analyzed by the parser.

Question:
1. What is Lexical Analyzer?
Answer:
Lexical Analysis is a function in which the stream of characters making up the
source program is read from left to right and grouped into tokens that are sequences of
characters having a collective meaning.

2. Why Lexical Analyzer is separated from syntax analyzer?


Answer:
The lexical analyzer is separated from the syntax analyzer to improve the
efficiency of the compiler and the portability of the lexical analyzer as it can be used
with any other syntax analyzer.

Exercise
Write down a Program for Lexical Analyzer in C.

EVALUATION:

Involvement Understanding / Problem solving Timely Completion Total


(4) (3) (3) (10)

Signature with date: ________________

AIT SP 3
System Programming (2150708)

Practical 3 Date:-

Aim: Write a program to left factor the given grammar.

Software Required:

 Turbo C Compiler

Knowledge Required:

 Algorithm to remove the Left Factoring from the given grammar.

Theory/Logic:

 Left factoring is a grammar transformation that is useful for producing a


grammar suitable for predictive parsing.

 The basic idea is that when it is not clear which of the two alternative
productions to use to expand a non terminal A ,we may be able to rewrite
the A production to defer the decision until we have seen enough of the
input to make the right choice.
 Algorithm
Input: Grammar G with no cycles or productions.

Output: An equivalent grammar with no left recursion


.
Method:

 for each non terminal A find the longest prefix a common to two or
more of its alternatives.

 If a!=null replace all the A productions A->aB |aB |….Y where Y


represents all the alternatives that do not begin with a by A->aA|Y

A->B|B|…..B

Here A is the new non terminal repeatedly apply this alternative


until no two alternative have common prefix

AIT SP 4
System Programming (2150708)

#include<stdio.h>
#include<string.h>

int main()
{
char gram[20],part1[20],part2[20],modifiedGram[20],newGram[20],tempGram[20];
int i,j=0,k=0,l=0,pos;

printf("Enter Production : A->");


gets(gram);

for(i=0;gram[i]!='|';i++,j++)
part1[j]=gram[i];
part1[j]='\0';

for(j=++i,i=0;gram[j]!='\0';j++,i++)
part2[i]=gram[j];
part2[i]='\0';

for(i=0;i<strlen(part1)||i<strlen(part2);i++)
{
if(part1[i]==part2[i])
{
modifiedGram[k]=part1[i];
k++;
pos=i+1;
}
}

for(i=pos,j=0;part1[i]!='\0';i++,j++)
{
newGram[j]=part1[i];
}
newGram[j++]='|';

for(i=pos;part2[i]!='\0';i++,j++)
{
newGram[j]=part2[i];
}

modifiedGram[k]='X';
modifiedGram[++k]='\0';
newGram[j]='\0';
printf("\n A->%s",modifiedGram);
printf("\n X->%s\n",newGram);
}

AIT SP 5
System Programming (2150708)

Advantage:
 Left factoring is d grammar transformation that is useful for producing a grammar
suitable for predictive parsing.
 We can eliminate repetitive grammar productions.
Disadvantage:
 There might be in the grammar that no left factoring is there so in that case this
method is not useful in parsing.

Exercise:-Write down a program to generate following output of given input.


Input: S=iEiSeS|iEts|b
Output: S=iEtSeS|iEtS|b
S1 : iEtSeS
S2 : iEtS
S3 : b
S=iEtSA|b
A=eS|#

EVALUATION:

Involvement Understanding / Problem solving Timely Completion Total


(4) (3) (3) (10)

Signature with date: ________________

AIT SP 6
System Programming (2150708)

Practical 4 Date:-
Aim: Write c program to remove left recursion from given grammar.

Knowledge Requirement:
Algorithm to solve immediate left recursion should be known and how to apply it
should be known.

Theory/Logic:
 Top-down parsing methods can not handle left-recursive grammars.
 So a transformation that eliminates left-recursion is needed.
 This program will eliminate left-recursion problem of given grammar.
Algorithm:
Input: Grammar G with no cycles or null-productions.
Output: An equivalent grammar with no left recursion.
Method: Apply the algorithm given below to G.

1. Arrange the non terminals in some order A1, A2 ,…..An.

2. for i:=1 to n do begin

for j:=1 to i-1 do begin

Replace each production of the form Ai->Ajy


by the production Aj->s1y|s2y|….|sky.
Where Aj->s1|s2|…|sk are all the current Aj-productions;
End
Eliminate the immediate left recursion among the Ai-productions.
End
Advantage:
 Top-down parsing methods cannot handle left-recursive grammars, so a
transformation that eliminates left recursion is needed.
Disadvantage:
 It is not easier process for each and every grammar to eliminate left recursion.
There might be in the grammar that no left recursion is there so in that case
this method is not useful in parsing.
Conclusion:
 So by eliminating left recursion it will be easy to generate the parse tree by the
generated grammar.

Exercise:-Write down a program to remove left recursion from the following input
Input:- E→EA/A,A→AT/a,T→a,E->1

EVALUATION:

Involvement Understanding / Problem solving Timely Completion Total


(4) (3) (3) (10)

AIT SP 7
System Programming (2150708)

Signature with date: ________________


Practical-5 Date:-

AIM:- Implement recursive Descendant parsing for given grammar.


E->T+E/T
T->F*T/F
U-F->E/i

Knowledge Required:
 Concept of Predictive parsing
 The whole knowledge of the First set of the Grammar.
 Knowledge about the look ahead symbol.

Theory/Logic:
 Recursive-decent parsing is a top-down method of syntax analysis in which
we execute set of recursive procedures to process the input. A procedure is
associated with each non-terminal of a grammar.

 Here, we consider a special form of recursive-decent parsing, called predictive


parsing, in which the look-ahead symbol unambiguously determines the
procedure selected for each non-terminal.

 The sequence of procedures called in processing the input implicitly defines a


parse tree for the input.

 A predictive parser is a program consisting of a procedure for every non-


terminal. Each procedure does two things.

1. It decides which production t use by looking at the look-ahead symbol.


The production with right side α is used if the look-ahead symbol is in
FIRST(α). If there is a conflict between two right sides for any look-
ahead symbol, then we cannot use this parsing method on this
grammar. A production with € o the right side is used if the look-ahead
symbol is not in the FIRST set for any other right hand side.

2. The procedure uses a production by mimicking the right side. A non-


terminal results in a call to the procedure for the non-terminal, and a
token matching the look-ahead symbol results in the next input token
being read. If at some point the token in the production does not match
the look-ahead symbol, an error is declared.

AIT SP 8
System Programming (2150708)

Example:

Advantage:
 It helps in successful parsing of the string without backtracking.
Application:
 This application can be used for the parsing of this particular parser.
Conclusion:
 This application successfully parses the valid string from the given grammer.

Exercise:-Write down a program to generate the recursive descent parser from the
given grammar.
E→iE’,E’->+iE’|epsilon

EVALUATION:

Involvement Understanding / Problem solving Timely Completion Total


(4) (3) (3) (10)

Signature with date: ________________

AIT SP 9
System Programming (2150708)

Practical-6 Date:-
Aim : Write a program to Implement Predictive Parser for the given grammar
T -> F * T / F
F -> ( E ) / i
E -> T + E / T
Knowledge Required:

 The whole knowledge of the First set of the Grammar.


 Knowledge about the look ahead symbol.
Theory/Logic:
The sequence of procedures called in processing the input implicitly defines a
parse tree for the input.

A predictive parser is a program consisting of a procedure for every non-


terminal. Each procedure does two things.

It decides which production t use by looking at the look-ahead symbol.

The production with right side α is used if the look-ahead symbol is in


FIRST(α). If there is a conflict between two right sides for any look-ahead
symbol, then we cannot use this parsing method on this grammar. A
production with € o the right side is used if the look-ahead symbol is not in
the FIRST set for any other right hand side.

The procedure uses a production by mimicking the right side. A non-terminal


results in a call to the procedure for the non-terminal, and a token matching
the look-ahead symbol results in the next input token being read. If at some
point the token in the production does not match the look-ahead symbol, an
error is declared.
Advantage:
 It helps in successful parsing of the string without backtracking.
Application:
 This application can be used for the parsing of this particular parser.
Conclusion:
 This application successfully parses the valid string from the given grammer.

AIT SP 10
System Programming (2150708)

Exercise:-Write a program to generate the following output.

EVALUATION:

Involvement Understanding / Problem solving Timely Completion Total


(4) (3) (3) (10)

Signature with date: ________________

AIT SP 11
System Programming (2150708)

Practical-7 Date:-
AIM:-Write a SAL program in text file and generate SYMTAB and LITTAB
Knowledge Required:
To Know about Assembly Language Pass-1 Assembler
Theory/Logic: Translate assembly language programs to object programs or machine
code is called an Assembler.
 One-pass assemblers are used when
o it is necessary or desirable to avoid a second pass over the source program
o the external storage for the intermediate file between two passes is slow or is
inconvenient to use
 Main problem: forward references to both data and instructions
 One simple way to eliminate this problem: require that all areas be defined before they
are referenced.
o It is possible, although inconvenient, to do so for data items.

Forward jump to instruction items cannot be easily eliminated


Algorithm for Pass 1 assembler:
begin
if starting address is given
LOCCTR = starting address;
else
LOCCTR = 0;
while OPCODE != END do ;; or EOF
begin
read a line from the code
if there is a label
if this label is in SYMTAB, then error
else insert (label, LOCCTR) into SYMTAB
search OPTAB for the op code
if found
LOCCTR += N ;; N is the length of this instruction (4 for MIPS)
else if this is an assembly directive
update LOCCTR as directed
else error
write line to intermediate file
end
program size = LOCCTR - starting address;
end
Q-1) What is Symbol table?
Stored and looked up to assign address to labels,efficient insertion and retrieval is needed,
deletion does not occur
EVALUATION:
Involvement Understanding / Problem solving Timely Completion Total
(4) (3) (3) (10)

Signature with date: ________________

AIT SP 12
System Programming (2150708)

Practical-8 Date:-
Aim:Use macro features of C language.

Knowledge Required:
-Concept of subroutine and user define function

Theory/Logic:-

A macro name is an abbreviation, which stands for some related lines of code. Macros
are useful for the following purposes:

· To simplify and reduce the amount of repetitive coding

· To reduce errors caused by repetitive coding

· To make an assembly program more readable.


Write a program to Use Macro feature of C Language for calculating the area of cube and
square.
#include<stdio.h>
#include<conio.h>
#define START void main() {
#define MAX(a,b) (((a)>(b))?(a):(b))
#define SQUARE(x) ((x)*(x))
#define CUBE(x) (SQUARE(x)*(x))
#define PRINT_SQUARE printf("Square of %d is %d\n",x,SQUARE(x));
#define PRINT_CUBE printf("Cube of %d is %d\n",x,CUBE(x));
#define PRINT_MAX printf("The maximum value from %d and %d is %d\n",a,b,MAX(a,b));
#define END getch();}
START
inta,b,x;
clrscr();
printf("Enter the values of a,b,x: ");
scanf("%d %d %d",&a,&b,&x);
PRINT_SQUARE
PRINT_CUBE

AIT SP 13
System Programming (2150708)

PRINT_MAX
END

Advantage:-
Macro Expansion.
A macro call leads to macro expansion. During macro expansion, the macro statement is
replaced by sequence of assembly statements.

EVALUATION:

Involvement Understanding / Problem solving Timely Completion Total


(4) (3) (3) (10)

Signature with date: ________________

AIT SP 14
System Programming (2150708)

Practical-9 Date:-

Aim:-Write a program which generates Quadruple Table for the given postfix String.

Knowledge Required:
-Concept of Postfix,Prefix
Theory/Logic:
 The quadruple is a structure with at the most tour fields such as op,arg1,arg2 and
result.
 The op field is used to represent the internal code for operator, the arg1 and arg2
represent the two operands used and result field is used to store the result of an
expression.
 Moreover, Consider the input statement x:= -a*b + -a*b

Exercise:-Write down a program to generate the following output.

Advantage:-
- Using quadruples, we can move a statement that computes A without requiring any
changes in the statements using A, because the result field is explicit.

- Thus, quadruple representation is easier to work with when using an optimizing


compiler, which entails a lot of code movement.

EVALUATION:
Involvement Understanding / Problem solving Timely Completion Total
(4) (3) (3) (10)

Signature with date: ________________

AIT SP 15
System Programming (2150708)

Practical-10 Date:-

Aim: Write a C program to parse a given string using Predictive parsing for given
grammar.
type → simple | ↑id | array [ simple ] of type
simple → integer | char | num dotdot num

Software Required:

 Turbo C Compiler

Knowledge Required:

 Concept of Predictive parsing


 The whole knowledge of the First set of the Grammar.
 Knowledge about the look ahead symbol.

Theory/Logic:
 Recursive-decent parsing is a top-down method of syntax analysis in which
we execute set of recursive procedures to process the input. A procedure is
associated with each non-terminal of a grammar.

 Here, we consider a special form of recursive-decent parsing, called predictive


parsing, in which the look-ahead symbol unambiguously determines the
procedure selected for each non-terminal.

 The sequence of procedures called in processing the input implicitly defines a


parse tree for the input.

 A predictive parser is a program consisting of a procedure for every non-


terminal. Each procedure does two things.

1. It decides which production t use by looking at the look-ahead symbol.


The production with right side α is used if the look-ahead symbol is in
FIRST(α). If there is a conflict between two right sides for any look-
ahead symbol, then we cannot use this parsing method on this
grammar. A production with € o the right side is used if the look-ahead
symbol is not in the FIRST set for any other right hand side.

2. The procedure uses a production by mimicking the right side. A non-


terminal results in a call to the procedure for the non-terminal, and a
token matching the look-ahead symbol results in the next input token
being read. If at some point the token in the production does not match
the look-ahead symbol, an error is declared.

AIT SP 16
System Programming (2150708)

Exercise:-Write down a program to generate the following output with use of given
grammar.
Input: type=simple|^ id|array [ simple ]
simple=int|char|num..num

Output:The grammar is :
type=simple|^ id|array [ simple ]
simple=int|char|num..num

Enter any string: [ num .. num ]


CONGRATULATION SUCCESS PARSING

Advantage:
 It helps in successful parsing of the string without backtracking.
Application:
 This application can be used for the parsing of this particular parser.
Conclusion:
 This application successfully parses the valid string from the given grammer.
Question:
1. What is predictive parser?

A non backtracking form of Top Down parsing is predictive parsing.

2. Which grammar can be used for predictive parsing?



To do predictive parsing we must transform a grammar in two ways:
 Eliminate left recursion
 Perform left factoring

EVALUATION:

Involvement Understanding / Problem solving Timely Completion Total


(4) (3) (3) (10)

Signature with date: ________________

AIT SP 17

S-ar putea să vă placă și