Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
AND ENGINEERING
LAB MANUAL
UNIX PROGRAMMING AND COMPILER DESIGN
[
Date of Issue:
Compiled By:
Date of Revision:
Verified By:
Authorized By
HOD CSE
INDEX
S.No
Contents
Page.no
Lab Objective
4-5
Guidelines to Students
6-7
9-17
18-48
54-66
References
67
LAB OBJECTIVE
Upon successful completion of this Lab the student will be able to:
1.
Demonstrate how to use the following Bourne Shell commands: cat, grep, ls,
more, ps, chmod, finger, ftp, etc.
2.
4.
Use the following Bourne Shell constructs: test, if then, if then else, if then elif,
for, while, until, and case.
Learn tracing mechanisms (for debugging), user variables, BourneShell
variables, read-only variables, positional parameters, reading input to a
BourneShell script, command substitution, comments, and exporting variables.
In addition, test on numeric values, test on file type, and test on character strings
are covered.
Copy, move, and delete files and directories
5.
6.
7.
8.
9.
10.
3.
RAM
256 MB
Hard Disk
40 GB
Mouse
Optical Mouse
Present
Software
All systems are configured in DUAL BOOT mode i.e, Students can boot from
Windows XP or Linux as per their lab requirement.
This is very useful for students because they are familiar with different
Operating Systems so that they can execute their programs in different
programming environments.
Each student has a separate login for database access
Oracle 9i client version is installed in all systems. On the server, account for
each student has been created.
This is very useful because students can save their work ( scenarios,
pl/sql programs, data related projects ,etc) in their own accounts. Each student
work is safe and secure from other students.
Latest Technologies like DOT NET and J2EE are installed in some systems.
Before submitting their final project, they can start doing mini project from 2nd
year onwards.
Systems are assigned numbers and same system is allotted for students when
they do the lab.
Guidelines to Students
How to Run Shell Scripts
There are two ways you can execute your shell scripts. Once you have created a script
file:
Method 1
Pass the file as an argument to the shell that you want to interpret your script.
Step 1 : create the script using vi, ex or ed
For example, the script file show has the following lines
echo Here is the date and time
date
Step 2 : To run the script, pass the filename as an argument to the sh (shell )
$ sh show
Here is the date and time
Sat jun 03 13:40:15 PST 2006
Method 2:
Make your script executable using the chmod command.
When we create a file, by default it is created with read and write permission turned on
and execute permission turned off. A file can be made executable using chmod.
Step 1 : create the script using vi, ex or ed
For example, the script file show has the following lines
echo Here is the date and time
date
Step 2 : Make the file executable
6
6
7
10
11
Programs
Write a shell script to generate a multiplication table
Write a shell script that copies multiple files to a directory.
Write a shell script that counts the number of lines and words
present in a given file.
Write a shell script that displays the list of all files in a given
directory.
Write a shell script (small calculator) that
adds,subtracts,multiplies and divides the given two integers.
There are division options: one returns the quotient and
the other returns remainder.
The script requires 3 arguments: The operation to be used
and two integer numbers.
The options are add(-a),subtract(-s),multiply(m),quotient(-c) and remainder)-r).
Write a Shell Script to reverse the rows and columns of a
matrix
Write a C program that counts the number of blanks in a text
file.
a) Using standard I/O
b) Using system calls.
Implement in C the following Unix commands using system
calls.
a) cat
b) ls
c) mv
Write a program that takes one or more file/directory names
as command line input and reports the following information
on file:
c) File type.
d) Number of
links.
e) Time of last access.
f) Read, Write
and Execute permissions.
C program that illustrates how to execute two commands
concurrently with a command pipe
Write a C program that illustrates the creation of child process
Page
No
18
19-20
21-22
23-24
25-26
27-28
29
30-32
33-34
35-37
38-39
8
12
13
14
15
16
40
41
42-44
45-46
47-48
Command
CAT
Syntax
cat [argument] [specific file]
Description
Examples
Command
pwd
Syntax
pwd
Description
Examples
ls
ls [options] [names]
Description
Examples
Description
Examples
Command
rm
Syntax
Options
rm [options] files
-d, --directory
unlink FILE, even if it is a non-empty directory
11
(super-user only)
-f, --force
ignore nonexistent files, never prompt
-i, --interactive
prompt before any removal
-r, -R, --recursive
remove the contents of directories recursively
-v, --verbose
explain what is being done
Description
Examples
directory, and all of its' contents, are erased from the disk,
including any sub-directories and files.
Command
Syntax
Options
cp
cp [options] file1 file2
cp [options] files directory
-b backup files that are about to be overwritten or removed
-i interactive mode; if dest exists, you'll be asked whether to
overwrite the file
-p
Description
Examples
Command
grep
Syntax
Options
Description
Think of the "grep" command as a "search" command
(most people wish it was named "search"). It is used to
search for text strings within one or more files.
13
Examples
Command
mkdir
Syntax
mkdir [options] directory name
Description
Examples
14
mkdir -p /home/joe/customer/acme
This command creates a new directory named
/home/joe/customer/acme, and creates any intermediate
directories that are needed. If only /home/joe existed to begin
with, then the directory "customer" is created, and the
directory "acme" is created inside of customer.
Command
rmdir
Syntax
rmdir [options] directories
Description
Examples
Command
Syntax
kill
kill [options] IDs
Description
kill ends one or more process IDs. In order to do this you
must own the process or be designated a privileged user. To
find the process ID of a certain job use ps.
Examples
Command
ps
16
Syntax
ps [options]
Description
Examples
17
1)
18
Step1:
Step2:
Step3:
Step4:
Step5:
Start
read n
for i=1 to 10
print n*i
Stop
Test Data:
Valid Data Set:
n should not 0
Result
1) Enter the number 4
4*1=4
4*2=8
4*3=12
4*4=16
4*5=20
4*6=24
4*7=28
4*8=32
4*9=36
4*10=40
Viva-Voce Questions
1. Why * is proceeded by \ ?
2. What are different types of shells?
3. How to execute shell script?
4. Explain syntax of for loop?
5. How arithmetic operations are done in Shell?
6. How to combine echo & read?
2) Name of the Experiment
AIM: Write a shell script that copies multiple files to a directory.
S/W & H/W Requirements:
S/W: Office-XP, Turbo C.
H/W: Pentium IV Processor, 256 MB RAM, 40 GB Hard Disk
19
ALGORITHM
Step1:
Step2:
Step3:
Start
read dir1
if (dir1==dir name)
Print directory existes
Else
Print directory not exists
if step 3 is true then
Read file1
If file1 is exists
Copy the file1 into file2 and print The file copied to dir1 directory
Else File is not exists
Stop
Step4:
Step5:
Step6:
Test Data:
Not applicable
Not applicable
Result
1) Enter Directory Name :
Guru
Directory does not exist.
cse
Directory exist
Enter file name to be copied and type quit
File copied
Enter file name to be copied and type quit
File copied
Enter file name to be copied and type quit
Karuna
Rajani
quit
Viva-Voce Questions
1.
2.
3.
4.
20
21
Start
read a file1
if file1 exists
Print no. of lines are.. l
Print no. of words are w
Print no. of characters are.. c
else
Print file1 is not exists
Stop
Step4:
Step5:
Test Data:
Not applicable
Not applicable
Result
1) Enter file name
Lines
:
Words :
Characters:
2) Enter file name
Lines
:
Words :
Characters:
Demo
This is demo
File to know
Number of words
Characters and line
4
13
65
engineer
Guru Nanak Engineering College
1
4
30
Viva-Voce Questions
1. Which command is used for display file?
22
2.
3.
4.
5.
6.
23
S/W:
Office-XP, Turbo C.
Start
read dir1
if (dir1==dir name)
Print Directory exists
if step3 is true
Read file1
if(-r dir1/file1) then
Print read
else if (-w dir1/file1) then
Print write
else if(-x dir1/file1) then
Print Execute
else
Print file1 is not exists
Stop
Test Data:
Valid Data Set:
Not applicable
Not applicable
Result
24
Viva-Voce Questions
1.
2.
3.
4.
5.
6.
25
There are division options: one returns the quotient and the other returns remainder.
The script requires 3 arguments: The operation to be used and two integer numbers.
The options are add (-a), subtract (-s), multiply (-m), quotient (-c) and remainder)-r).
S/W & H/W Requirements:
S/W: Office-XP, Turbo C.
H/W: Pentium IV Processor, 256 MB RAM, 40 GB Hard Disk
ALGORITHM
Step1:
Start
Step2:
read a, b, option
Step3:
if (option==1) then
Result=a+b
Print result
Step4:
if (option==2) then
Result=a-b
Print result
Step5:
if(option==3) then
Result=a*b
Print result
Step6:
if(option==4) then
Result=a%b
Print result
Step7:
if(option==5)
Result=a/b
Print result
Else if
Print Invalid operation
Step8:
Stop
Test Data:
Valid Data Set:
Result
26
4 5
3
20
8
5
4
Viva-Voce Questions
1.
2.
3.
4.
5.
6.
27
AIM: Write a shell script to reverse the rows and columns of a matrix.
S/W & H/W Requirements:
S/W: Office-XP, Turbo C.
H/W: Pentium IV Processor, 256 MB RAM, 40 GB Hard Disk
ALGORITHM
Step1: Start
Step2: read m1[],m2[],a, b
Step3: for i=1 to a
for j=1 to b
print m1[i][j]
Step4: for i=1 to b
for j=1 to a
m2[i][j]=m1[i][j]
Step5: print m2[i][j]
Step6: Stop
Test Data:
Valid Data Set:
1 2
3 4
Not applicable
Not applicable
Result
Enter the matrix size 2 3
Enter the matrix
The resultant matrix is
1
4
2
5
1
2
3
4
5
6
3
6
28
Viva-Voce Questions
1.
2.
3.
4.
5.
29
Start
read fiel1, char ch, int sc
initiate sc to 0 i.e sc=0
if(file1==NULL) then
Print unable to open a file
else if
While end of file
ch=fgetc(file1)
if(ch== )
sc=sc+1
print no. of spaces are sc
Stop
Step5:
Step6:
Step7:
Step8:
Step9:
Test Data:
Not applicable
Not applicable
Result
1)
$ cc blank.c
$ ./a.out blank.c
Spaces are 11
Viva-Voce Questions
1.
2.
3.
4.
5.
30
Step6:
Step7:
Start
read
int fd,i
char ch[1]
if(argc<2)
Print Usage:mycat filename
fd=open ( argv[1],O_RDONLY)
if(fd==-1)
Print argv[1] is not exists
Else
Print Contents of the file are argv[1]
while(read(fd,ch,1)>0)
Print (ch [0])
Stop
Step6:
start
create a structure dinfo
read dp
if (argc<2)
dp=opendir( .)
if(dp==NULL)
Print unable to open the directory
Else
While(dinfo=readdir(dp))!=NULL)
Print dinfo->d_name
Stop
31
Not applicable
Not applicable
Result:
Implementing cat command
1) $ cc cat.c
$ ./a.out one
Contents of the file one is: Welcome to Unix Programming
Implementing ls command
$ cc ls.c
$ ./a.out kal
.
..
File 1
Kal2.sh
Implementing mv command
32
$ cc mv.c
$ ./a.out b c
File moved or renamed successfully
Viva-Voce Questions:
1.
2.
3.
4.
5.
33
Start
read a FILE *stream
int buffer_character
stream= fopen(test,r)
if(stream==(FILE *))0)
Print (stderr,Error opening file(printed to standard error))
while ((buffer_character=getc(stream))!=EOF)
write the character to standard out and check for errors
if((putc(buffer_character,stdout))==EOF)
Print (stderr,Error writing to standard out.(printed to standard error))
if(fclose(stream))==EOF)
Print(stderr,Error closing stream.(printed to standard error))
stop
Test Data:
Valid Data Set:
Not applicable
Not applicable
Result:
cc file inf.c
./a.out file.inf.c
34
Size 320
Type and permission : 10064
No.of links : 1
Access time . Apr 20 10:45:35
Viva-Voce Questions:
1.
2.
3.
4.
5.
6.
35
Step7:
Step8:
Step9:
Step10:
Start
read int i,pid
static char path[]=/u/test2
fork a child process
pid=fork()
if(pid==0)
chdir(path)
for i=0 to 30000
sub2()
i++ /*30000 calls to sub2 in child profile*/
else /*parent process.leave gmon.out in current directory*/
for i=0 to 1000
sub1(pid)
i++ /*1000 calls to sub1 in parent profile*/
read int sub1(pid) /*silly little function called by parent 1000 times
int pid,i
print (Im the parent ,child pid )
print(Im the child)
stop
Test Data:
Valid Data Set:
Not applicable
36
Not applicable
Result:
sh-2.00$ fork
Process 19643 about to fork a child.
PID TT S
TIME COMMAND
19632 p1 S
0:00.36 -bash (bash)
19638 p1 S + 0:00.07 script showem
19640 p1 S + 0:00.03 script showem
19641 p2 S
0:00.15 sh -is
19643 p2 S + 0:00.04 fork
19644 p2 S + 0:00.01 fork
19645 p2 S + 0:00.04 sh -c ps
19646 p2 R + 0:00.04 sh -c ps
19648 p2 R + 0:00.00 sh -c ps
PID TT S
TIME COMMAND
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
bbbbbbbbb
19632 p1 S
0:00.36 -bash (bash)
19638 p1 S + 0:00.07 script showem
19640 p1 R + 0:00.03 script showem
19641 p2 S
0:00.15 sh -is
19643 p2 S + 0:00.04 fork
19644 p2 S + 0:00.01 fork
19645 p2 R + 0:00.04 sh -c ps
19646 p2 S + 0:00.04 sh -c ps
Created child process 19644.
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
bbbbbbbbb
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
bbbbbbbbb
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
bbbbbbbbb
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
bbbbbbbbb
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
bbbbbbbbb
37
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
bbbbbbbbb
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
bbbbbbbbb
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
bbbbbbbbb
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
bbbbbbbbb
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
sh-2.00$ exit
exit
Viva-Voce Questions;
1.
2.
3.
4.
5.
38
Start
read pid_t pid
pid=fork()
switch(pid)
if case = -1
Print Fork called
Else if case= 0
Print It is child process
Step6: else
Print It is parent process : CHILD PID is pid
Step7: Stop
Test Data:
Valid Data Set:
Not applicable
Not applicable
Result:
39
$ cc fork.c
$ ./a.out fork.c
It is a child process
It is parent process : child pid is : 16281
What is process?
What are the various attributes of process & when they will be saved?
What is the purpose of fork() system call?explain with syntax?
What is zombie process?
What is chioldprocess & parent process?what are its pids?
What is the purpose of esec & wait system call?
40
Step6:
Step7:
Start
create a structure of time t
Read int h,m,s,s1
read time t
s1=t.ti_sec;
while(!kbhit())
h=t.ti_hour
m=t.ti_min
s=t.ti_sec
if(s1==s)
print( h,m,s)
Stop
Test Data:
Valid Data Set:
InValid Data Set:
Limiting Data Set:
Result
9:57:19
41
Viva-Voce Questions
1.
2.
3.
4.
5.
Start
read int semidkey_t key
create a union semun
if((key=ftok(semdemo.c,J))==-1)
Perror(ftok)
create a semaphore set with 1 semaphore
If((semid=semget(key,1,0666|IPC_CREAT))==-1)
Perror(semget)
initiliaze semaphore #0 to 1
Arg.val=1
if(semctl(semid,0,SETVAL,arg)==-1)
Perror(semctl)
Stop
Test Data:
Valid Data Set:
Not applicable
Not applicable
Result
42
$ cc fork.c
$ ./a.out fork.c
It is a child process
It is parent process : child pid is : 16281
Viva-Voce Questions:
1.
2.
3.
4.
5.
What is semaphore?
What are the two types of locking ?Explain difference?
What is file locking & record locking?
Which function is used for file locking explain with syntax?
Explain fcntl function used for record locking?
43
remove-item(item)
up(mutex)
up(empty)
consume-item(item)
item=(item+1)%10
Step8: produce-item(int I)
int mquid;
sleep(1)
print enter data for item no I
read Pmsg.s
Pmsg.mtype=5
Step9: enter-item(int I)
int mqid
mqid=msgget((key-t)25,ipc-CREAT:0644)
msgnd(mqid,&pmsg,sizeof(pmsg.s)0)
print item written
Step10:down(int semid)
sop.sem-num=0
sop.sem-op=-1
sop.sem-flg=0
semop(semid,&sop,1)
Step11:up(int semid)
sop.em-num=0
sop.op=-1
sop.flag=0
semop(semid,&sop,1)
Step12:remove-item(int I)
int mqid
mqid=msgget((key-t)25,IPC-CREATE:0644)
msgrcv(mqid,&cmsg,sizeof(cmsg.s),5,0)
print item read from queue
Step13:Consume-item(int I)
Print item value is I,cmsg.s
Step14:/*main program*/
read pid,mqid
Step15:mutex=semget(ckey-t)27,I,IPC-CREAT:0644)
Step16:semct 1(mutex,0,SETVAL,1)
Step17:empty=(semget(ckey-t)28,I,IPC-CREAT:0644)
Step18:full=semget(ckey-t)29,I,IPC-CREAT:0644)
Step19:sem1(full,0,STEVAL,0)
Step20:mqid=msgget(key-t)25,IPC-CREAT:0644)
Step21:pid=fork()
Step22:if(pid==0)
Execute Consumer() function
Else
Execute Producer() function
Step23:Stop
44
Test Data:
Valid Data Set:
Not applicable
Not applicable
Result:
Viva-Voce Questions:
1.
2.
3.
4.
5.
45
46
else
y3 = sin(DEG_TO_RAD(1.0/i))
y4 = sin(DEG_TO_RAD(i))
Step12: /* load files */
print(fp1,"%f %f\n",i,y1)
print(fp2,"%f %f\n",i,y2)
print(fp3,"%f %f\n",i,y3)
print(fp4,"%f %f\n",i,y4)
Step13:/* reads up to data file */
flush(fp1)
flush(fp2)
flush(fp3)
flush(fp4)
Step14: /* plot graph */
PlotOne()
usleep(250)
void quit()
Step15: print caught: Shutting down pipes
Step16: StopPlot()
Step17: print closing data files
fclose(fp1)
fclose(fp2)
fclose(fp3)
fclose(fp4)
Step18: print deleting data files
Step19: RemoveDat()
Step20: Stop
Test Data:
Valid Data Set:
Not applicable
Not applicable
Result:
Enter files:
ABCD
Caught :Shutting down pipes
Closing data files
47
Viva-Voce Questions
1.
2.
3.
4.
5.
48
* the server.
*/
key = 1234
Step5:
Step6:
Step7:
/*Send a message. */
if (msgsnd(msqid, &sbuf, buf_length, IPC_NOWAIT) < 0) {
print %d, %d, %s, %d\n", msqid,sbuf.mtype,sbuf.mtext,
buf_length)
perror("msgsnd")
else
print Message: \"%s\" Sent\n", sbuf.mtext
Step12:
Stop
Test Data:
Valid Data Set:
Not applicable
Not applicable
Result:
Enter some text:
Enter some text:
Enter some text:
You Wrote:
You Wrote:
Hello
How r u
Today
Hello
How r u
49
You Wrote:
Today
Viva-Voce Questions:
1.
2.
3.
4.
5.
LAB OBJECTIVE
The language Processors comprises assemblers, compilers and interpreters. It deals with
the recognition the translation, and the execution of formal languages It is closely related
to compiler construction.
50
PART B
To provide an understanding of the language translation peculiarities by designing a
complete translator for a mini language.
Consider the following mini language, a simple procedural high-level language, only
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> ::= { <variabledefinition> <slist> }
| {<slist>}
<variabledefinition> ::= int <vardeflist> ;
<vardeflist> ::= <vardec> I <vardec> , <vardetlist> <vardec> ::= <identifier> I
<identifier> [ <constant> ] <slist> ::= <statement> I <statement> ; <slist>
<statement> ::= <assignment> I <ifstatement> I <whilestatement> I <block> I
<printstatement> I <empty>
<assignment> ::= <identifier> = <expression>
I <identifier> [ <expression> ] = <expression> <ifstatement> ::= if <bexpression> then
<slist> else <slist> endif
51
52
5.
Convert the BNF rules into Yacc form and write code to generate abstract syntax
tree.
6.
Write program to generate machine code from the abstract syntax tree generated
by the parser. TI following instruction set may be considered as target code.
The following is a simple register-based machine, supporting a total of 17 instructions. It
has the distinct internal storage areas. The first is the set of 8 registers, used by the
individual instruction as detailed below, the second is an area used for the storage of
variables and the third is an area for the storage of program. The instructions can be
preceded by a label. This consists of an int, in the range 1 to 9999 and the label is
followed by a colon to separate it from the rest of II instruction. The numerical label can
be used as the argument to a jump instruction, as detailed bel In the description of the
individual instructions below, instruction argument types are specified follows:
R
specifies a register in the form RO, R1, R2, R3, R4, R5, R6 or R7 (or rO, r1, etc.).
L
specifies a numerical label (in the range 1 to 9999).
v
specifies a ''variable location" (a variable number, or a variable location pointed to by a
register below).
A
specifies a constant value, a variable location, a register or a variable location pointed to
by a regi (an indirect address). Constant values are specified as an integer value,
optionally preceded~, minus sign, preceded by a # symbol. An indirect address is
specified by an @ followed by a regi So, for example, an A-type argument could have
the form 4 (variable number 4), #4 (the constant 4), r4 (register 4) or @r4 (the contents
of register 4 identifies the variable location to be access,
The instruction set is defined as follows:
LOAD A,R
loads the integer value specified by A into register R.
STORE R,V
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.
ADDA,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.
MULA, 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.
53
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 . .
E 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.
Syllabus Programs
Page
No
54-56
54
59-60
3
Convert the BNF rules into YACC form and write code to generate
abstract syntax tree
Write program to generate machine code from the abstract syntax tree
generated by the Parser .The following instruction set may considered as
target code.
63-64
65-66
H/W:
ALGORITHM:
We make use of two functions.
look up() it takes string as argument and checks its presence in the symbol table. If the
string is found then returns the address else it returns NULL .
55
insert() it takes string as its argument and the same is inserted into the symbol table
and the corresponding address is returned.
Step1:
Step2:
Step3:
Step4:
Start
function scan
lexbuf[50] of char
tokenvalue[10]
begin
store scanned char in c
if c blank or tab,then
do nothing
else if c is \n,then
line_number :=line_number=1
else if c is a digit
token value:=value of the digit and successive digits
return tokentype
p:=lookup(lexbuf)
if p:=NULL, then
p:=insert(lexbuf,id)
token value:=lexbuf
return(attribute from symboltable)
else
tokenvalue:=NULL
return(NULL) end
Stop
Test Data:
Valid Data Set:
Not applicable
Not applicable
Result
INPUT file xx.txt
{
int t1,t2
56
t1=2
t2=t1*3/2;
if t2>5 then
print(t2);
else
{
int t3;
t3=99;
t2=-25
print(-t1+t2+t3);
}
End if
OUTPUT
SOB
int
ID
SEPE
ID
ENDST
ID
ASSIGN
ENDST
ID
ASSIGN
ID
MULOP
DIVOP
ENDST
If
ID
GT
NUM
Then
print
OPENPRA
ID
CLOSEPRA
ENDST
else
SOB
int
ID
ENDST
ID
ASSIGN
NUM
ID
ASSIGN
SUBOP
NUM
ENDST
OPENPRA
SUBOP
ID
ADDOP
ID
MULOP
ID
CLOSEPRA
ENDST
EOB
endif
Viva-Voce Questions
1.
2.
3.
4.
57
H/W:
ALGORITHM:
58
Step1:
Step2:
Start
Declare the declarations for the given language tokens like digit,
alphabet, white space, delimiters, etc.
digit[0-9]
letter[A-Z a-z]
delim[\t\n]
W${delim}+ID{(letter)(letter/digit)}+
Integer {digit}+
%%
{ws} {print (SpecialCharacters)}
{ID} {print(Identifiers)}
{digit} {print(\n Integer)}
if {printf(keyword)}
else {print(keyword)}
& & {print(logoical operators)}
>{print(logoical operators)}
<{print(logoical operators)}
<={print(logoical operators)}
>={print(logoical operators)}
= {printf(\n \n)}
!{printf(\n \n)}
+ {printf(arithmetic operator)}
- {printf (arithmetic)
* {printf(arithmetic)}
% {printf(arithmetic)}
% % {printf(arithmetic)}
Step3: Write the auxillary procedure in main() function
Step4: end
Step5: Stop
Test Data:
Valid Data Set:
Not applicable
Not applicable
Result
59
Viva-Voce Questions
1. What is Parsing?
2. Construct the parsing table for the given?
S1 iC+SS1|a
S1 eS1|
C b
3. What is Token?
4. What is Jlex?
5. What is Flex?
H/W:
ALGORITHM
60
Step1:
Step2:
Step3:
Step4:
Step5:
Step6:
Step7:
Step8:
Step9:
Step10:
Start
declare w[10] as char and Z as an array
enter the string with $ at the end
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]))
if step 4 is satisfied then the string is accepted
Else string is not
give for the grammer A-> bc/ab in the loop A(int k)
Describe the grammer b->c/d in the loop B (int k)
Similarly describe the grammer D->d/abcd
if steps7,8,9 are satisfied accordingly string is accepted
Else string is not accepted
Stop
Test Data:
Valid Data Set:
Not applicable
Not applicable
Result
INPUT file
{
int a, ba[10];
a=a*a;
b=a*b;
if a<b
print (a);
else
print(b);
}
aa.txt
OUTPUT:
Successful parsing
Viva-Voce Questions
61
1.
2.
3.
4.
5.
H/W:
62
ALGORITHM
Step1:
Step2:
Step3:
Step4:
Step5:
Step6:
Step7:
Step8:
Step9:
Step10:
Start
Initially the parser has s0 on the stack where s0 is the initial state and w$
is in buffer
Set ip point to the first symbol of w$
repeat forever, begin
Let S be the state on top of the stack and a symbol pointed to by ip
If action [S, a] =shift S then begin
Push S1 on to the top of the stack
Advance ip to next input symbol
Else if action [S, a], reduce A->B then begin
Pop 2* |B| symbols of the stack
Let S1 be the state now on the top of the stack
Output the production A->B
End
else if action [S, a]=accepted, then return
Else
Error()
End
Stop
Test Data:
Valid Data Set:
Not applicable
Not applicable
Result
[
[
[
[
] $ lex parser.l
] $ Yacc -d parser.y
] $ cc lex.yy.c y.tab.c -ll -ld
] $ ./a.out
2+3
5.000
63
Viva-Voce Questions
1.
2.
3.
4.
5.
H/W:
64
ALGORITHM
Step1:
Start
Step2:
declare the declarations as a header file
{include<ctype.h>}
Step3:
token digit
Step4:
define the translations rules like line, expr, term, factor
Line:exp \n {print(\n %d \n,$1)}
Expr:expr+ term ($$=$1=$3}
Term:term + factor($$ =$1*$3}
Factor
Factor:(enter) {$$ =$2)
%%
Step5:
define the supporting C routines
Step6:
Stop
Test Data:
Valid Data Set:
Not applicable
Not applicable
Result
[
[
[
[
POS
0
1
2
3
4
5
6
]
]
]
]
Operator
<
==
+
=
Goto
<
==
$ lex int.l
$ Yacc -d int y
$ cc lex.yy.c y.tab.c -ll -ly
$ ./a.out test.c
Arg1
a
to
a
t1
Arg2
b
FALSE
b
a
t2
b
FALSE
Result
to
5
+1
a
5
t2
10
65
7
8
9
10
11
12
13
14
15
16
+
=
GOTO
<=
==
=
GOTO
+
=
a
t3
a
t4
a
t5
b
FALSE
b
a
t6
+3
a
5
t4
+=5
+5
c
17
t6
c
Viva-Voce Questions
1.
2.
3.
4.
5.
66
S/W:
H/W:
ALGORITHM
Step1:
Start
Step2:
for every three address statement of the form x=y op z
Step3:
begin
Step4:
Call getreg() to obtain the location L which the computation y op z should
be performed
Step5:
Obtain the current location of the operand y by consulting its address
descriptor ,and if the values of Y are currently both in the memory
location as well as in the register, then prefer the register.If the value of y
is not currently available in 1,then generate an instruction MOV y,l
Step6:
Generate the instruction OP Z,l and update the address descriptor of X to
indicate that X is now available in l and in register then update t\ its
descriptor to indicate that it will contain the run time value of x
Step7:
If the current values of y ad/or z are in register and we have no further use
for them,and they are live at the end of the block,then after the register
descriptor to indicate that after the execution of the statem,ent x=y op
z,those registers will no longer contain y and / or z.
Step8:
store all results
Step9:
Stop
Test Data:
Valid Data Set:
Not applicable
Not applicable
Result
Input file text1.txt
=+ 1
67
a
a
a
+
1
2
3
a
2
3
4
b
t1 , 2
a[1],2
a[2],3
a[3],4
LOAD a , R0
LOAD b , R1
ADD R1 , R0
SUB R0 , c
Viva-Voce Questions
1.
2.
3.
4.
5.
References:
BOOKS:
Unix the ultimate Guide,
Unix networking programming,
Advanced Programming in Unix environment,
Sumitabha das,TMH
W.R Stevens Pearson/PHI
W.R Stevens Pearson/PHI
68
LMAN Narosa
Andrew N. Appel,Cambridge
University Press
John R.Levine,Tony Mason,Doug
Brown,Orelly
WEBSITES:
www.unix.com
www.compilerdesign.com
www.lexicalanalyzer.com
www.w3school.com
69