Databases and Compilers Lab

85
PART 1 DATBASE

Transcript of Databases and Compilers Lab

Page 1: Databases and Compilers Lab

PART 1

DATBASE

Page 2: Databases and Compilers Lab

Assignment 1

Aim: Analyze the problem and come with the entities in it. Identify what Data has to be persisted in the databases.

The Following are the entities and its attributes

Bus:

Bus_No : varchar(10) (primary key)

Source : varchar(20)

Destination : varchar(20)

Passenger:

PNR_No : Number(9) (primary key)

Ticket_No : Number(9)

Name : varchar(15)

Age : integer(4)

Sex : char(10) ; Male/Female

PPNO : varchar(15)

Reservation:

PNR_No : number(9) (foreign key)

Journey_date : date

No_of_seats : integer(8)

Address : varchar(50)

Contact_No : Number(9)

Status : Char(2)

Cancellation :

PNR_No : number(9)(foreign key)

Journey_date : date

1

Page 3: Databases and Compilers Lab

No_of_seats : integer(8)

Address : varchar(50)

Contact_No : Number(9)

Status : Char(2)

Ticket:

Ticket_No : number(9)(primary key)

Journey_date : date

Age : int(4)

Sex : Char(10)

Source : varchar

Destination :varchar

Dep_time : varchar

2

Page 4: Databases and Compilers Lab

Assignment 2

Aim: Concept design with E-R model. Relate the entities appropriately. Apply cardinalities for each relation.

3

Page 5: Databases and Compilers Lab

Assignment 3

Aim: Represent all entities in a tabular fashion. Represent all relationships in a tabular fashion.

The fallowing are tabular representation of the above entities and relationships

BUS:

Bus_no Source Destination

Passenger:

Pnr_No Ticket_no Name Age Sex PPNO

Reservation:

Pnr_No Journey_date No_of_seats Address Contact_No Status

Cancellation:

Pnr_No Journey_date No_of_seats Address Contact_No Status

Ticket:

Ticket_No Journey_date Age sex source Destination Dep_time

4

Page 6: Databases and Compilers Lab

Assignment 4

Aim: Installation of MySQL and practicing DDL commands.

1. Steps for installing MySQL

Step 1Make sure you already downloaded the MySQL essential 5.0.45 win32.msi file. Double click on the .msi file.

Step 2This is MySQL Server 5.0 setup wizard. The setup wizard will install MySQL Server 5.0 release 5.0.45 on your computer. To continue, click next.

Step 3Choose the setup type that best suits your needs. For common program features select Typical and it’s recommended for general use. To continue, click next.

5

Page 7: Databases and Compilers Lab

Step 4

This wizard is ready to begin installation. Destination folder will be in C:\Program Files\MySQL\MySQL Server 5.0\. To continue, click next.

6

Page 8: Databases and Compilers Lab

Step 5The program features you selected are being installed. Please wait while the setup wizard installs MySQL 5.0. This may take several minutes.

Step 6To continue, click next.

7

Page 9: Databases and Compilers Lab

Step 7To continue, click next.

Step 8Wizard Completed. Setup has finished installing MySQL 5.0. Check the configure the MySQL server now to continue. Click Finish to exit the wizard

d.

8

Page 10: Databases and Compilers Lab

Step 9The configuration wizard will allow you to configure the MySQL Server 5.0 server instance. To continue, click next.

Step 10Select a standard configuration and this will use a general purpose configuration for the server that can be tuned manually. To continue, click next.

9

Page 11: Databases and Compilers Lab

Step 11

Check on the install as windows service and include bin directory in windows path. To continue, click next.

Step 12Please set the security options by entering the root password and confirm retype the password. To continue, click next.

10

Page 12: Databases and Compilers Lab

Step 13Ready to execute? Clicks execute to continue.

Step 14Processing configuration in progress.

11

Page 13: Databases and Compilers Lab

Step 15Configuration file created. Windows service MySQL5 installed. Press finish to close the wizard.

2. Practicing DDL commands

2.1 CREATE Table

a) Passenger Table

SQL> create table Passenger(PNR_NO Numeric(9) primary key , Ticket_NO Numeric(9), Name varchar(20), Age Number(4), Sex char(10), PPNO varchar(15));

Table created.

SQL> desc passenger

Name Null? Type

----------------------------------------- -------- ----------------------------

PNR_NO NOT NULL NUMBER(9)

TICKET_NO NUMBER(9)

NAME VARCHAR2(20)

AGE NUMBER(4)

SEX CHAR(10)

12

Page 14: Databases and Compilers Lab

PPNO VARCHAR2(15)

b) Reservation Table

SQL> create table Reservation(PNR_NO Numeric(9), No_of_seats Number(8), Address varchar(50), Contact_No Numeric(9), Status char(3));

Table created.

SQL> desc Reservation

Name Null? Type

----------------------------------------- -------- ----------------------------

PNR_NO NUMBER(9)

NO_OF_SEATS NUMBER(8)

ADDRESS VARCHAR2(50)

CONTACT_NO NUMBER(9)

STATUS CHAR(3)

c) Bus Table

SQL> create table Bus(Bus_No varchar(5) primary key, source varchar(20), destination varchar(20));

Table created.

SQL> desc bus;

Name Null? Type

----------------------------------------- -------- ----------------------------

BUS_NO NOT NULL VARCHAR2(5)

SOURCE VARCHAR2(20)

DESTINATION VARCHAR2(20)

d) Cancellation Table

SQL> create table Cancellation(PNR_NO Numeric(9), No_of_seats Number(8), Address varchar(50), Contact_No Numeric(9), Status char(3));

13

Page 15: Databases and Compilers Lab

Table created.

SQL> desc Cancellation

Name Null? Type

----------------------------------------- -------- ----------------------------

PNR_NO NUMBER(9)

NO_OF_SEATS NUMBER(8)

ADDRESS VARCHAR2(50)

CONTACT_NO NUMBER(9)

STATUS CHAR(3)

e) Ticket Table

SQL> create table Ticket(Ticket_No Numeric(9) primary key, age number(4), sex char(4) Not

null, source varchar(2), destination varchar(20), dep_time varchar(4));

Table created.

SQL> desc Ticket

Name Null? Type

----------------------------------------- -------- ----------------------------

TICKET_NO NOT NULL NUMBER(9)

AGE NUMBER(4)

SEX NOT NULL CHAR(4)

SOURCE VARCHAR2(2)

DESTINATION VARCHAR2(20)

DEP_TIME VARCHAR2(4)

2.2 ALTER Table

SQL> ALTER TABLE Reservation ADD FOREIGN KEY (PNR_NO) REFERENCES Passenger(PNR_NO);

14

Page 16: Databases and Compilers Lab

Table altered.

SQL> ALTER TABLE Cancellation ADD FOREIGN KEY (PNR_NO) REFERENCES Passenger(PNR_NO);

Table altered.

SQL> alter table Ticket add constraint check_age check(age>18);

Table altered.

2.3 INSERT

SQL> insert into Passenger values(&PNR_NO,&TICKET_NO, '&Name', &Age, '&Sex', '&PPNO');

Enter value for pnr_no: 1Enter value for ticket_no: 1Enter value for name: SACHINEnter value for age: 12Enter value for sex: mEnter value for ppno: sd1234old 1: insert into Passenger values(&PNR_NO,&TICKET_NO, '&Name', &Age, '&Sex',

'&PPNO')

new 1: insert into Passenger values(1,1,'SACHIN',12,'m','sd1234')

1 row created.

SQL> /

Enter value for pnr_no: 2Enter value for ticket_no: 2Enter value for name: rahulEnter value for age: 34Enter value for sex: mEnter value for ppno: sd3456old 1: insert into Passenger values(&PNR_NO,&TICKET_NO, '&Name', &Age, '&Sex', '&PPNO')

new 1: insert into Passenger values(2,2,'rahul',34,'m','sd3456')

1 row created.

SQL> /

Enter value for pnr_no: 3Enter value for ticket_no: 3Enter value for name: swetha

15

Page 17: Databases and Compilers Lab

Enter value for age: 24Enter value for sex: fEnter value for ppno: sdqw34old 1: insert into Passenger values(&PNR_NO,&TICKET_NO, '&Name', &Age, '&Sex', '&PPNO')

new 1: insert into Passenger values(3,3,'swetha',24,'f','sdqw34')

1 row created.

SQL> /

Enter value for pnr_no: 4Enter value for ticket_no: 4Enter value for name: raviEnter value for age: 56Enter value for sex: mEnter value for ppno: sdqazxold 1: insert into Passenger values(&PNR_NO,&TICKET_NO, '&Name', &Age, '&Sex', '&PPNO')

new 1: insert into Passenger values(4,4,'ravi',56,'m','sdqazx')

1 row created.

SQL> /

Enter value for pnr_no: 4Enter value for ticket_no: 5Enter value for name: asifEnter value for age: 33Enter value for sex: mEnter value for ppno: iuyhjkold 1: insert into Passenger values(&PNR_NO,&TICKET_NO, '&Name', &Age, '&Sex', '&PPNO')

new 1: insert into Passenger values(4,5,'asif',33,'m','iuyhjk')

insert into Passenger values(4,5,'asif',33,'m','iuyhjk')

*

ERROR at line 1: ORA-00001: unique constraint (SYSTEM.SYS_C004023) violated

SQL> select * from Passenger;

16

Page 18: Databases and Compilers Lab

PNR_NO TICKET_NO NAME AGE SEX PPNO

---------- ---------- -------------------- ---------- ---------- ---------------

1 1 SACHIN 12 m sd1234

2 2 rahul 34 m sd3456

3 3 swetha 24 f sdqw34

4 4 ravi 56 m sdqazx

SQL> insert into Bus values('&Bus_No','&source','&destination');

Enter value for bus_no: 1Enter value for source: hydEnter value for destination: ban

old 1: insert into Bus values('&Bus_No','&source','&destination')

new 1: insert into Bus values('1','hyd','ban')

1 row created.

SQL> /

Enter value for bus_no: 2Enter value for source: hydEnter value for destination: chn

old 1: insert into Bus values('&Bus_No','&source','&destination')

new 1: insert into Bus values('2','hyd','chn')

1 row created.

SQL> /

Enter value for bus_no: 4Enter value for source: hydEnter value for destination: mum

old 1: insert into Bus values('&Bus_No','&source','&destination')

new 1: insert into Bus values('4','hyd','mum')

17

Page 19: Databases and Compilers Lab

1 row created.

SQL> /

Enter value for bus_no: 5Enter value for source: hydEnter value for destination: kol

old 1: insert into Bus values('&Bus_No','&source','&destination')

new 1: insert into Bus values('5','hyd','kol')

1 row created.

SQL> /

Enter value for bus_no: 5Enter value for source: secEnter value for destination: ban

old 1: insert into Bus values('&Bus_No','&source','&destination')

new 1: insert into Bus values('5','sec','ban')

insert into Bus values('5','sec','ban')

*

ERROR at line 1:

ORA-00001: unique constraint (SYSTEM.SYS_C004025) violated

SQL> insert into Reservation values(&PNR_NO, &No_of_seats, '&Address', &Contact_No , '&Status');

Enter value for pnr_no: 1Enter value for no_of_seats: 2Enter value for address: masabtankEnter value for contact_no: 9009897812Enter value for status: s

old 1: insert into Reservation values(&PNR_NO, &No_of_seats, '&Address', &Contact_No,' &Status')

new 1: insert into Reservation values(1,2,'masabtank',9009897812,'s')

1 row created.

18

Page 20: Databases and Compilers Lab

SQL> insert into Reservation values(&PNR_NO,&No_of_seats,'&Address',&Contact_No,'&Status');

Enter value for pnr_no: 8Enter value for no_of_seats: 3Enter value for address: cbtEnter value for contact_no: 9090887753Enter value for status: s

old 1: insert into Reservation values(&PNR_NO, &No_of_seats, '&Address', &Contact_No, '&Status')

new 1: insert into Reservation values(8,3,'cbt',9090887753,'s')

insert into Reservation values(8,3,'cbt',9090887753,'s')

*

ERROR at line 1:

ORA-02291: integrity constraint (SYSTEM.SYS_C004024) violated - parent key not found

2.4 UPDATE Table

SQL> update Passenger set age='43' where PNR_NO='2';

1 row updated.

SQL> select * from Passenger;

PNR_NO TICKET_NO NAME AGE SEX PPNO

---------- ---------- -------------------- ---------- ---------- ---------------

1 1 SACHIN 12 m sd1234

2 2 rahul 43 m sd3456

3 3 swetha 24 f sdqw34

4 4 ravi 56 m sdqazx

2.5 DELETE

SQL> delete from Passenger where PNR_NO='4';

1 row deleted.

19

Page 21: Databases and Compilers Lab

SQL> select * from Passenger;

PNR_NO TICKET_NO NAME AGE SEX PPNO

---------- - --------- -------------------- ---------- ---------- ---------------

1 1 SACHIN 12 m sd1234

2 2 rahul 43 m sd3456

3 3 swetha 24 f sdqw34

2.5 DROP Table

SQL> drop table Cancellation;

Table dropped.

20

Page 22: Databases and Compilers Lab

Assignment 5

Aim: Practice the fallowing Queries

1. Display Unique PNR_NO of all Passengers

SQL> select PNR_NO from Passenger;

PNR_NO

----------

1

2

3

4

5

6

7

7 rows selected.

2. Display all the names of male Passengers

SQL> select Name from Passenger where Sex='m';

NAME

--------------------

SACHIN

rahul

rafi

salim

riyaz

3. Display Ticket numbers and names of all Passengers

SQL> select Ticket_NO,Name from Passenger;

21

Page 23: Databases and Compilers Lab

TICKET_NO NAME

---------- --------------------

1 SACHIN

2 rahul

3 swetha

23 rafi

12 salim

34 riyaz

21 neha

7 rows selected.

4. Display the source and destination having journey time more than 10 hours.

SQL> select source, destination from Ticket where Journey_Dur>10;

SOURCE DESTINATION

---------- --------------------

HYD BAN

SEC BAN

HYD MUM

5. Find the ticket number of passenger whose name starts with ‘S’ and ends with ‘H’

SQL> select Ticket_NO from Passenger where Name like'S%'and name like'%N';

TICKET_NO

----------

1

6. Find the names of the passenger whose age is between 20 and 40

SQL> select Name from Passenger where age between 20 and 40;

22

Page 24: Databases and Compilers Lab

NAME

--------------------

swetha

rafi

riyaz

neha

7. Display all the name of the passengers beginning with ‘r’

SQL> select Name from Passenger where Name like 'r%';

NAME

--------------------

rahul

rafi

riyaz

8. Display the sorted list of Passenger Names

SQL> select Name from Passenger ORDER BY Name;

NAME

--------------------

SACHIN

neha

rafi

rahul

riyaz

salim

swetha

7 rows selected.

23

Page 25: Databases and Compilers Lab

Assignment 6

Aim: Practice queries using Aggregate functions, Group by, having and Creation and Dropping

of views

1. Write a query to Display the information present in the Cancellation and Reservation Tables

SQL> select * from Reservation UNION select * from Cancellation;

PNR_NO NO_OF_SEATS ADDRESS CONTACT_NO STATUS

---------- - ---------- -------------------- ---------- --- --------------

1 2 sdfgh 1234543 s

1 3 msbtnk 123456789 s

2 2 ldkp 234567891 s

2 2 wertgfds 12212121 n

3 4 dskng 345678912 n

3 5 azxsdcvf 13243546 s

4 2 ddfdsfsdfdsf 3456789 s

4 5 abids 567891234 s

5 2 allbd 891234567 s

5 11 liopujth 43256787 s

6 1 koti 231456781 s

PNR_NO NO_OF_SEATS ADDRESS CONTACT_NO STATUS

---------- -- --------- -------------------- ----------

6 31 swebnht 453212345 s

7 2 dbdhfdbhf 90876543 s

7 3 jklhg 2345671 s

14 rows selected.

2. Find the distinct PNR_NO that are present

24

Page 26: Databases and Compilers Lab

SQL> SELECT PNR_NO, COUNT(*) AS NoOccurances FROM Passenger GROUP BY PNR_NO HAVING COUNT(*)>0;

PNR_NO NOOCCURANCES

---------- ------------

1 1

2 1

3 1

4 1

5 1

6 1

7 1

7 rows selected.

3. Find the No of Seats booked for each PNR_NO using GROUP BY Clause.

SQL> select PNR_NO,sum(No_of_seats) from Reservation group by PNR_NO;

PNR_NO SUM(NO_OF_SEATS)

---------- ----------------

1 3

6 1

2 2

4 5

5 2

3 6

7 3

7 rows selected.

4. Find the number of seats booked in each class where the number of seats is greater than 1.

25

Page 27: Databases and Compilers Lab

SQL> select class,sum(No_of_seats) from Reservation where class='a 'or class='b' or class=

'c' group by class having sum(No_of_seats)>1;

CLASS SUM(NO_OF_SEATS)

---- ---------------

a 13

b 7

c 2

5. Find the total number of cancelled seats.

SQL> select sum(No_of_seats) from Cancellation;

SUM(NO_OF_SEATS)

----------------

22

6. Creating and dropping views

a) CREATE VIEW

SQL> create view male_pass as select PNR_NO,age from Passenger where sex='m';

View created.

SQL> select * from male_pass;

PNR_NO AGE

---------- ----------

1 12

2 43

4 22

5 45

6 32

Create a view from two tables with all columns.

26

Page 28: Databases and Compilers Lab

SQL> create view v1 as select * from Passenger full natural join Reservation;

View created.

b) INSERT

SQL> insert into male_pass values(&PNR_NO,&age);

Enter value for pnr_no: 12

Enter value for age: 22

old 1: insert into male_pass values(&PNR_NO,&age)

new 1: insert into male_pass values(12,22)

1 row created.

c) DROP VIEW

SQL> drop view male_pass;

View dropped.

Assignment 7

27

Page 29: Databases and Compilers Lab

Aim: Create of insert trigger, delete trigger and update trigger.

1. To write a TRIGGER to ensure that Bus table does not contain duplicate of null values in Bus_No column.

a) CREATE OR RELPLACE TRIGGER trig1 before insert on Bus for each row

DECLARE a number;

BEGIN

if(:new.Bus_No is Null) then

raise_application_error(-20001,'error:: Bus_No cannot be null');

else

select count(*) into a from Bus where Bus_No =:new. Bus_No;

if(a=1) then

raise_application_error(-20002,'error:: cannot have duplicate Bus_No ');

end if;

end if;

END;

RESULT:

SQL> @trigger

Trigger created.

SQL> select * from Bus;

BUS_NO SOURCE DESTINATION

----- -------------------- --------------------

110 hyd ban

221 hyd chn

412 hyd mum

501 hyd kol

SQL> insert into Bus values(&Bus_No,'&source','&destination');

Enter value for Bus_No: null

Enter value for source: Chen

Enter value for destination: hyd

old 1: insert into Bus values(&Bus_No, '&source', '&destination')

new 1: insert into Bus values(null,Chen','hyd')

28

Page 30: Databases and Compilers Lab

insert into Bus values(null,’Chen','hyd')

*

ERROR at line 1:

ORA-20001: error::Bus_No cannot be null

35

ORA-06512: at "SYSTEM.TRIG1", line 5

ORA-04088: error during execution of trigger 'SYSTEM.TRIG1'

SQL> /

Enter value for Bus_No: 110

Enter value for source:KOL

Enter value for destination: hyd

old 1: insert into Bus values(&Bus_No, '&source', '&destination')

new 1: insert into Bus values(110,KOL','hyd')

insert into Bus values(110,’KOL','hyd')

*

ERROR at line 1:

ORA-20002: error:: cannot have duplicate Bus_No

ORA-06512: at "SYSTEM.TRIG1", line 9

ORA-04088: error during execution of trigger 'SYSTEM.TRIG1'

b) Create Trigger updchek before update on Ticket

For Each Row

Begin

If New.Ticket_No>60 Then

Set New.Ticket_No=Ticket_No;

Else

Set New.Ticket_No=0;

End If

End.

SQL> @trigger

Trigger created.

29

Page 31: Databases and Compilers Lab

c) CREATE OR RELPLACE TRIGGER trig1 before insert on Passenger for each row

DECLARE a number;

BEGIN

if(:new.PNR_NO is Null) then

raise_application_error(-20001,'error:: PNR_NO cannot be null');

else

select count(*) into a from Passenger where PNR_NO =:new. PNR_NO;

if(a=1) then

raise_application_error(-20002,'error:: cannot have duplicate PNR_NO ');

end if;

end if;

END;

SQL> @trigger

Trigger created.

Assignment 8

Aim: To write a Cursor to display the list of Male and Female Passengers.

30

Page 32: Databases and Compilers Lab

Analyst.

DECLARE

cursor c(jb varchar2) is select Name from Passenger where Sex=m;

pr Passenger.Sex%type;

BEGIN

open c('m');

dbms_RESULT.put_line(' Name of Male Passenger are:');

loop

fetch c into pr;

exit when c%notfound;

dbms_RESULT.put_line(pr);

end loop;

close c;

open c('f');

dbms_RESULT.put_line(' Name of female Passengers are:');

loop

fetch c into em;

exit when c%notfound;

dbms_RESULT.put_line(em);

end loop;

close c;

END;

RESULT:

Name of Male Passenger are:

SACHIN

rahul

rafi

salim

riyaz

Name of female Passengers are:

swetha

31

Page 33: Databases and Compilers Lab

neha

PL/SQL procedure successfully completed.

b) To write a Cursor to display List of Passengers from Passenger Table.

DECLARE

cursor c is select PNR_NO, Name, Age, Sex from Passenger ;

i Passenger.PNR_NO%type;

j Passenger.Name%type;

k Passenger.Age%type;

l Passenger.Sex%type;

BEGIN

open c;

dbms_RESULT.put_line('PNR_NO, Name, Age, Sex of Passengers are:= ');

loop

fetch c into i, j, k, l;

exit when c%notfound;

dbms_RESULT.put_line(i||' '||j||' '||k||' '||l);

end loop;

close c;

END;

RESULT:

SQL>@Passenger

PNR_NO NAME AGE SEX

---------- -------------------- ---------- ----------

1 SACHIN 12 m

2 rahul 43 m

3 swetha 24 f

4 rafi 22 m

PL/SQL procedure successfully completed.

32

Page 34: Databases and Compilers Lab

PART II

COMPILER DESIGN

Program 1

33

Page 35: Databases and Compilers Lab

Aim: Write A Program to Design Lexical Analyzer.

#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()

{

FILE *f1,*f2,*f3;

char c,str[10],st1[10];

int num[100],lineno=0,tokenvalue=0,i=0,j=0,k=0;

printf("\nEnter 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))

34

Page 36: Databases and Compilers Lab

{

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

}

putc(' ',f2);

ungetc(c,f1);

}

else if(c==' '||c=='\t')

printf(" ");

else if(c=='\n')

lineno++;

else

putc(c,f3);

}

35

Page 37: Databases and Compilers Lab

fclose(f2);

fclose(f3);

fclose(f1);

printf("\nThe 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 identifiersare:");

while((c=getc(f2))!=EOF)

{

if(c!=' ')

str[k++]=c;

else

{

str[k]='\0';

keyword(str);

k=0;

}

}

fclose(f2);

f3=fopen("specialchar","r");

printf("\nSpecial characters are");

while((c=getc(f3))!=EOF)

printf("%c",c);

printf("\n");

fclose(f3);

printf("Total no. of lines are:%d",lineno);

}

36

Page 38: Databases and Compilers Lab

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

Program 2

37

Page 39: Databases and Compilers Lab

Aim: Implement the Lexical Analyzer Using Lex Tool.

/* program name is lexp.l */

%{

/* program to recognize a c program */

int COMMENT=0;

%}

identifier [a-zA-Z][a-zA-Z0-9]*

%%

#.* { printf("\n%s is a PREPROCESSOR DIRECTIVE",yytext);}

int |

float |

char |

double |

while |

for |

do |

if |

break |

continue |

void |

switch |

case |

long |

struct |

const |

typedef |

return |

else |

goto {printf("\n\t%s is a KEYWORD",yytext);}

"/*" {COMMENT = 1;}

38

Page 40: Databases and Compilers Lab

/*{printf("\n\n\t%s is a COMMENT\n",yytext);}*/

"*/" {COMMENT = 0;}

/* printf("\n\n\t%s is a COMMENT\n",yytext);}*/

{identifier}\( {if(!COMMENT)printf("\n\nFUNCTION\n\t%s",yytext);}

\{ {if(!COMMENT) printf("\n BLOCK BEGINS");}

\} {if(!COMMENT) printf("\n BLOCK ENDS");}

{identifier}(\[[0-9]*\])? {if(!COMMENT) printf("\n %s IDENTIFIER",yytext);}

\".*\" {if(!COMMENT) printf("\n\t%s is a STRING",yytext);}

[0-9]+ {if(!COMMENT) printf("\n\t%s is a NUMBER",yytext);}

\)(\;)? {if(!COMMENT) printf("\n\t");ECHO;printf("\n");}

\( ECHO;

= {if(!COMMENT)printf("\n\t%s is an ASSIGNMENT OPERATOR",yytext);}

\<= |

\>= |

\< |

== |

\> {if(!COMMENT) printf("\n\t%s is a RELATIONAL OPERATOR",yytext);}

%%

int main(int argc,char **argv)

{

if (argc > 1)

{

FILE *file;

file = fopen(argv[1],"r");

if(!file)

{

printf("could not open %s \n",argv[1]);

39

Page 41: Databases and Compilers Lab

exit(0);

}

yyin = file;

}

yylex();

printf("\n\n");

return 0;

}

int yywrap()

{

return 0;

}

Input:

40

Page 42: Databases and Compilers Lab

$vi var.c

#include<stdio.h>

main()

{

int a,b;

}

Output:

$lex lex.l

$cc lex.yy.c

$./a.out var.c

#include<stdio.h> is a PREPROCESSOR DIRECTIVE

FUNCTION

main (

)

BLOCK BEGINS

int is a KEYWORD

a IDENTIFIER

b IDENTIFIER

BLOCK ENDS

Program 3

41

Page 43: Databases and Compilers Lab

Aim:Implementation of Predictive Parser.

#include<stdio.h>

#include<ctype.h>

#include<string.h>

#include<stdlib.h>

#define SIZE 128

#define NONE -1

#define EOS '\0'

#define NUM 257

#define KEYWORD 258

#define ID 259

#define DONE 260

#define MAX 999

char lexemes[MAX];

char buffer[SIZE];

int lastchar=-1;

int lastentry=0;

int tokenval=DONE;

int lineno=1;

int lookahead;

struct entry

{

char *lexptr;

int token;

}symtable[100];

struct entry

keywords[]={"if",KEYWORD,"else",KEYWORD,"for",KEYWORD,"int",KEYWORD,"float",

KEYWORD,"double",KEYWORD,"char",KEYWORD,"struct",KEYWORD,"return",KEYWO

RD,0,0};

42

Page 44: Databases and Compilers Lab

void Error_Message(char *m)

{

fprintf(stderr,"line %d, %s \n",lineno,m);

exit(1);

}

int look_up(char s[ ])

{

int k;

for(k=lastentry;k>0;k--)

if(strcmp(symtable[k].lexptr,s)==0)

return k;

return 0;

}

int insert(char s[ ],int tok)

{

int len;

len=strlen(s);

if(lastentry+1>=MAX)

Error_Message("Symbpl table is full");

if(lastchar+len+1>=MAX)

Error_Message("Lexemes array is full");

lastentry=lastentry+1;

symtable[lastentry].token=tok;

symtable[lastentry].lexptr=&lexemes[lastchar+1];

lastchar=lastchar+len+1;

strcpy(symtable[lastentry].lexptr,s);

return lastentry;

}

/*void Initialize()

{

struct entry *ptr;

43

Page 45: Databases and Compilers Lab

for(ptr=keywords;ptr->token;ptr+1)

insert(ptr->lexptr,ptr->token);

}*/

int lexer()

{

int t;

int val,i=0;

while(1)

{

t=getchar();

if(t==' '||t=='\t');

else if(t=='\n')

lineno=lineno+1;

else if(isdigit(t))

{

ungetc(t,stdin);

scanf("%d",&tokenval);

return NUM;

}

else if(isalpha(t))

{

while(isalnum(t))

{

buffer[i]=t;

t=getchar();

i=i+1;

if(i>=SIZE)

Error_Message("Compiler error");

}

buffer[i]=EOS;

if(t!=EOF)

44

Page 46: Databases and Compilers Lab

ungetc(t,stdin);

val=look_up(buffer);

if(val==0)

val=insert(buffer,ID);

tokenval=val;

return symtable[val].token;

}

else if(t==EOF)

return DONE;

else

{

tokenval=NONE;

return t;

}

}

}

void Match(int t)

{

if(lookahead==t)

lookahead=lexer();

else

Error_Message("Syntax error");

}

void display(int t,int tval)

{

if(t=='+'||t=='-'||t=='*'||t=='/')

printf("\nArithmetic Operator: %c",t);

else if(t==NUM)

printf("\n Number: %d",tval);

else if(t==ID)

printf("\n Identifier: %s",symtable[tval].lexptr);

45

Page 47: Databases and Compilers Lab

else

printf("\n Token %d tokenval %d",t,tokenval);

}

void F()

{

//void E();

switch(lookahead)

{

case '(' : Match('(');

E();

Match(')');

break;

case NUM : display(NUM,tokenval);

Match(NUM);

break;

case ID : display(ID,tokenval);

Match(ID);

break;

default : Error_Message("Syntax error");

}

}

void T()

{

int t;

F();

while(1)

{

switch(lookahead)

{

case '*' : t=lookahead;

Match(lookahead);

46

Page 48: Databases and Compilers Lab

F();

display(t,NONE);

continue;

case '/' : t=lookahead;

Match(lookahead);

display(t,NONE);

continue;

default : return;

}

}

}

void E()

{

int t;

T();

while(1)

{

switch(lookahead)

{

case '+' : t=lookahead;

Match(lookahead);

T();

display(t,NONE);

continue;

case '-' : t=lookahead;

Match(lookahead);

T();

display(t,NONE);

continue;

default : return;

}

47

Page 49: Databases and Compilers Lab

}

}

void parser()

{

lookahead=lexer();

while(lookahead!=DONE)

{

E();

Match(';');

}

}

main()

{

char ans[10];

printf("\n Program for recursive decent parsing ");

printf("\n Enter the expression ");

printf("And place ; at the end\n");

printf("Press Ctrl-Z to terminate\n");

parser();

}

Output:

Program for recursive decent parsing

48

Page 50: Databases and Compilers Lab

Enter the expression And place ; at the end

Press Ctrl-Z to terminate

a+b*c;

Identifier: a

Identifier: b

Identifier: c

Arithmetic Operator: *

Arithmetic Operator: +

2*3;

Number: 2

Number: 3

Arithmetic Operator: *

+3;

line 5,Syntax error

Ctrl-Z

Program 4

Aim: Design LALR Bottom up Parser.

49

Page 51: Databases and Compilers Lab

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

50

Page 52: Databases and Compilers Lab

| term

;

term: term '*' factor {$$=$1 * $3 ;}

| factor

;

factor: '(' expr ')' {$$=$2 ;}

| DIGIT

;

%%

int main()

{

yyparse();

}

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

Program 5

Aim: Convert The BNF rules into Yacc form and write code to generate abstract syntax tree.

51

Page 53: Databases and Compilers Lab

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

\< |

\> |

\>= |

52

Page 54: Databases and Compilers Lab

\<= |

== {strcpy(yylval.var,yytext);

return RELOP;}

[ \t] ;

\n LineNo++;

. return yytext[0];

%%

<int.y>

%{

#include<string.h>

#include<stdio.h>

struct quad

{

char op[5];

char arg1[10];

char arg2[10];

char result[10];

}QUAD[30];

struct stack

{

int items[100];

int top;

}stk;

int Index=0,tIndex=0,StNo,Ind,tInd;

extern int LineNo;

53

Page 55: Databases and Compilers Lab

%}

%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

;

54

Page 56: Databases and Compilers Lab

DESCT: TYPE VARLIST

;

VARLIST: VAR ',' VARLIST

| VAR

;

ASSIGNMENT: VAR '=' EXPR{

strcpy(QUAD[Index].op,"=");

strcpy(QUAD[Index].arg1,$3);

strcpy(QUAD[Index].arg2,"");

strcpy(QUAD[Index].result,$1);

strcpy($$,QUAD[Index++].result);

}

;

EXPR: EXPR '+' EXPR {AddQuadruple("+",$1,$3,$$);}

| EXPR '-' EXPR {AddQuadruple("-",$1,$3,$$);}

| EXPR '*' EXPR {AddQuadruple("*",$1,$3,$$);}

| EXPR '/' EXPR {AddQuadruple("/",$1,$3,$$);}

| '-' EXPR {AddQuadruple("UMIN",$2,"",$$);}

| '(' EXPR ')' {strcpy($$,$2);}

| VAR

| NUM

;

CONDST: IFST{

Ind=pop();

sprintf(QUAD[Ind].result,"%d",Index);

Ind=pop();

sprintf(QUAD[Ind].result,"%d",Index);

55

Page 57: Databases and Compilers Lab

}

| 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();

56

Page 58: Databases and Compilers Lab

sprintf(QUAD[Ind].result,"%d",Index);

}

;

CONDITION: VAR RELOP VAR {AddQuadruple($2,$1,$3,$$);

StNo=Index-1;

}

| VAR

| NUM

;

WHILEST: WHILELOOP{

Ind=pop();

sprintf(QUAD[Ind].result,"%d",StNo);

Ind=pop();

sprintf(QUAD[Ind].result,"%d",Index);

}

;

WHILELOOP: WHILE '(' CONDITION ')' {

strcpy(QUAD[Index].op,"==");

strcpy(QUAD[Index].arg1,$3);

strcpy(QUAD[Index].arg2,"FALSE");

strcpy(QUAD[Index].result,"-1");

push(Index);

Index++;

}

BLOCK {

strcpy(QUAD[Index].op,"GOTO");

strcpy(QUAD[Index].arg1,"");

strcpy(QUAD[Index].arg2,"");

strcpy(QUAD[Index].result,"-1");

push(Index);

57

Page 59: Databases and Compilers Lab

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;

}

58

Page 60: Databases and Compilers Lab

void push(int data)

{

stk.top++;

if(stk.top==100)

{

printf("\n Stack overflow\n");

exit(0);

}

stk.items[stk.top]=data;

}

int pop()

{

int data;

if(stk.top==-1)

{

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()

{

59

Page 61: Databases and Compilers Lab

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

60

Page 62: Databases and Compilers Lab

$gcc lex.yy.c y.tab.c –ll –lm$./a.out test.c

Pos Operator Arg1 Arg2 Result

0 < a b to

1 == to FALSE 5

2 + a b t1

3 = t1 a

4 GOTO 5

5 < a b t2

6 == t2 FALSE 10

7 + a b t3

8 = t3 a

9 GOTO 5

10 <= a b t4

11 == t4 FALSE 15

12 - a b t5

13 = t5 c

14 GOTO 17

15 + a b t3

16 = t6 c

___________________________________________________

Program 6

Aim: A Program to Generate Machine Code.

61

Page 63: Databases and Compilers Lab

#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);

62

Page 64: Databases and Compilers Lab

}

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

}

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

63

Page 65: Databases and Compilers Lab

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

64

Page 66: Databases and Compilers Lab

label[no++]=atoi(result);

break;

}

}

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;

}

65

Page 67: Databases and Compilers Lab

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:

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

66

Page 68: Databases and Compilers Lab

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

67

Page 69: Databases and Compilers Lab

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

68