Professional Documents
Culture Documents
MTech DB and Compiler Lab Manual
MTech DB and Compiler Lab Manual
MTech DB and Compiler Lab Manual
JOGINPALLY B. R ENGINEERING COLLEGE (Affiliated to JNTU, Hyd. & Approved by AICTE New Delhi)
09J21D5818
09J21D5818
OBSERVATION BOOK
Rollno: 09J21D5818 Name: CH.VENUGOPAL
09J21D5818
DATABASES AND COMPILERS LAB Objective: This lab enables and students to practice the concepts learnt in the subject DBMS by developing a database for an example company named Roadway Travels whose description is as follows. The student is expected to practice the designing, developing and querying a database in the content of example database Roadway Travels. Students are expected to use Mysql database Roadway Travels Roadway Travels is in Business since 1997 with buses connecting different places in Indian. Its main office located in Hyderabad The company wants to computerize its operations in the following areas: Reservations Ticketing Cancellations Reservations: Reservations are directly handled by booking office. Reservations can be made 60 days in advance either cash or credit. In case the ticket is not available, await listed ticket is issued to the customer. This ticket is confirmed against the cancellation Cancellation and Modification: Cancellations are also directly handed at the booking office. Cancellation charges will be charged .wait listed tickets that do not get confirmed are fully refunded
09J21D5818
09J21D5818
09J21D5818
Passenger: Pnr_No
Ticket_no
Name
Age
Sex
PPNO
Reservation: Pnr_No
Journey_date
No_of_seats
Address
Contact_No
Status
No_of_seats
Address
Contact_No
Status
Ticket: Ticket_No
Journey_date Age
sex
source
Destination
Dep_time
09J21D5818
Step 3 Choose the setup type that best suits your needs. For common program features select Typical and its recommended for general use. To continue, click next.
09J21D5818
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.
Step 5 The program features you selected are being installed. Please wait while the setup wizard installs MySQL 5.0. This may take several minutes.
09J21D5818
10
09J21D5818
Step 8 Wizard Completed. Setup has finished installing MySQL 5.0. Check the configure the MySQL server now to continue. Click Finish to exit the wizard
d.
11
09J21D5818
Step 9 The configuration wizard will allow you to configure the MySQL Server 5.0 server instance. To continue, click next.
Step 10 Select a standard configuration and this will use a general purpose configuration for the server that can be tuned manually. To continue, click next.
Step 11 Check on the install as windows service and include bin directory in windows path. To continue, click next.
JOGINPALLY B.R. ENGINEERING COLLEGE
12
09J21D5818
Step 12 Please set the security options by entering the root password and confirm retype the password. To continue, click next.
13
09J21D5818
14
09J21D5818
Step 15 Configuration 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) 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)
JOGINPALLY B.R. ENGINEERING COLLEGE
15
09J21D5818
NUMBER(9) CHAR(3)
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)); 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); 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
JOGINPALLY B.R. ENGINEERING COLLEGE
16
09J21D5818
SQL> insert into Passenger values(&PNR_NO,&TICKET_NO, '&Name', &Age, '&Sex', '&PPNO'); Enter value for pnr_no: 1 Enter value for ticket_no: 1 Enter value for name: SACHIN Enter value for age: 12 Enter value for sex: m Enter value for ppno: sd1234 old 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: 2 Enter value for ticket_no: 2 Enter value for name: rahul Enter value for age: 34 Enter value for sex: m Enter value for ppno: sd3456 old 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: 3 Enter value for ticket_no: 3 Enter value for name: swetha Enter value for age: 24 Enter value for sex: f Enter value for ppno: sdqw34 old 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: 4 Enter value for ticket_no: 4 Enter value for name: ravi Enter value for age: 56 Enter value for sex: m Enter value for ppno: sdqazx old 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: 4 Enter value for ticket_no: 5 Enter value for name: asif
JOGINPALLY B.R. ENGINEERING COLLEGE
17
09J21D5818
Enter value for age: 33 Enter value for sex: m Enter value for ppno: iuyhjk old 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; PNR_NO ---------1 2 3 4 TICKET_NO ---------1 2 3 4 NAME -------------------SACHIN rahul swetha ravi AGE SEX PPNO ---------- ---------- --------------12 m sd1234 34 m sd3456 24 f sdqw34 56 m sdqazx
SQL> insert into Bus values('&Bus_No','&source','&destination'); Enter value for bus_no: 1 Enter value for source: hyd Enter 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: 2 Enter value for source: hyd Enter 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: 4 Enter value for source: hyd Enter value for destination: mum old 1: insert into Bus values('&Bus_No','&source','&destination') new 1: insert into Bus values('4','hyd','mum') 1 row created. SQL> / Enter value for bus_no: 5 Enter value for source: hyd Enter 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: 5
JOGINPALLY B.R. ENGINEERING COLLEGE
18
09J21D5818
Enter value for source: sec Enter 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: 1 Enter value for no_of_seats: 2 Enter value for address: masabtank Enter value for contact_no: 9009897812 Enter 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. SQL> insert into Reservation values(&PNR_NO,&No_of_seats,'&Address',&Contact_No,'&Status'); Enter value for pnr_no: 8 Enter value for no_of_seats: 3 Enter value for address: cbt Enter value for contact_no: 9090887753 Enter 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
19
09J21D5818
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 -------------------------------------- ---------1 1 SACHIN 12 2 2 rahul 43 3 3 swetha 24 4 4 ravi 56
2.5 DELETE SQL> delete from Passenger where PNR_NO='4'; 1 row deleted. SQL> select * from Passenger; PNR_NO TICKET_NO NAME ---------- ---------------------------1 1 SACHIN 2 2 rahul 3 3 swetha
20
09J21D5818
21
09J21D5818
6.
SQL> select Name from Passenger where age between 20 and 40; NAME -------------------swetha rafi riyaz neha 7.
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.
22
09J21D5818
Week8 and week9: 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 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.
23
09J21D5818
3. 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. 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.
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
JOGINPALLY B.R. ENGINEERING COLLEGE
24
09J21D5818
Create a view from two tables with all columns. 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.
25
09J21D5818
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') insert into Bus values(null,Chen','hyd') *
JOGINPALLY B.R. ENGINEERING COLLEGE
26
09J21D5818
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.
27
09J21D5818
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.
28
09J21D5818
29
09J21D5818
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 ---------1 2 3 4 NAME SACHIN rahul swetha rafi AGE SEX 12 43 24 22 m m f m -------------------- ---------- ----------
30
09J21D5818
PART II
COMPILER DESIGN
31
09J21D5818
32
09J21D5818
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); } fclose(f2); fclose(f3); fclose(f1); printf("\nThe no's in the program are"); for(j=0;j<i;j++)
JOGINPALLY B.R. ENGINEERING COLLEGE
33
09J21D5818
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); }
Output:
Enter the C program a+b*c Ctrl-D The nos in the program are:
34
09J21D5818
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
35
09J21D5818
36
09J21D5818
"*/" {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");} \( = \<= | \>= | \< | == | \> %% 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]); exit(0); } yyin = file; } yylex();
JOGINPALLY B.R. ENGINEERING COLLEGE
37
09J21D5818
Input:
$vi var.c #include<stdio.h> main() { int a,b; }
Output:
JOGINPALLY B.R. ENGINEERING COLLEGE
38
09J21D5818
$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
39
09J21D5818
#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,"flo at",KEYWORD,"double",KEYWORD,"char",KEYWORD,"struct",KEYWORD,"return",KE YWORD,0,0}; void Error_Message(char *m)
JOGINPALLY B.R. ENGINEERING COLLEGE
40
09J21D5818
{ 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; for(ptr=keywords;ptr->token;ptr+1) insert(ptr->lexptr,ptr->token); }*/ int lexer()
JOGINPALLY B.R. ENGINEERING COLLEGE
41
09J21D5818
{ 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) ungetc(t,stdin); val=look_up(buffer); if(val==0) val=insert(buffer,ID); tokenval=val; return symtable[val].token; }
JOGINPALLY B.R. ENGINEERING COLLEGE
42
09J21D5818
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); else printf("\n Token %d tokenval %d",t,tokenval); } void F() { //void E(); switch(lookahead) { case '(' : Match('('); E();
JOGINPALLY B.R. ENGINEERING COLLEGE
43
09J21D5818
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); F(); display(t,NONE); continue; case '/' : t=lookahead; Match(lookahead); display(t,NONE); continue; default : return; } } } void E() {
JOGINPALLY B.R. ENGINEERING COLLEGE
44
09J21D5818
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; } } } 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 ");
JOGINPALLY B.R. ENGINEERING COLLEGE
45
09J21D5818
Output:
Program for recursive decent parsing 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
46
09J21D5818
<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 ;} 47
09J21D5818
| term ; term: term '*' factor | factor ; factor: '(' expr ')' | DIGIT ; %% int main() { yyparse(); } yyerror(char *s) { printf("%s",s); } {$$=$2 ;} {$$=$1 * $3 ;}
Output:
$lex parser.l $yacc d parser.y $cc lex.yy.c y.tab.c ll lm $./a.out 2+3 5.0000
48
09J21D5818
Program 5
Aim: Convert The BNF rules into Yacc form and write code to generate abstract syntax
tree. <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 else while int | char | float return TYPE; return IF; return ELSE; return WHILE;
{identifier} {strcpy(yylval.var,yytext); return VAR;} {number} {strcpy(yylval.var,yytext); return NUM;} \< | \> | \>= |
JOGINPALLY B.R. ENGINEERING COLLEGE
49
09J21D5818
<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; %} %union
JOGINPALLY B.R. ENGINEERING COLLEGE
50
09J21D5818
{ char var[10]; } %token <var> NUM VAR RELOP %token MAIN IF ELSE WHILE TYPE %type <var> EXPR ASSIGNMENT CONDITION IFST ELSEST WHILELOOP %left '-' '+' %left '*' '/' %% PROGRAM : MAIN BLOCK ; BLOCK: '{' CODE '}' ; CODE: BLOCK | STATEMENT CODE | STATEMENT ; STATEMENT: DESCT ';' | ASSIGNMENT ';' | CONDST | WHILEST ; DESCT: TYPE VARLIST ; VARLIST: VAR ',' VARLIST | VAR ;
JOGINPALLY B.R. ENGINEERING COLLEGE
51
09J21D5818
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); } | IFST ELSEST ; IFST: IF '(' CONDITION ')' { strcpy(QUAD[Index].op,"=="); strcpy(QUAD[Index].arg1,$3); strcpy(QUAD[Index].arg2,"FALSE"); strcpy(QUAD[Index].result,"-1");
JOGINPALLY B.R. ENGINEERING COLLEGE
52
09J21D5818
push(Index); Index++; } BLOCK { strcpy(QUAD[Index].op,"GOTO"); strcpy(QUAD[Index].arg1,""); strcpy(QUAD[Index].arg2,""); strcpy(QUAD[Index].result,"-1"); push(Index); Index++; } ; ELSEST: ELSE{ tInd=pop(); Ind=pop(); push(tInd); sprintf(QUAD[Ind].result,"%d",Index); } BLOCK{ Ind=pop(); sprintf(QUAD[Ind].result,"%d",Index); } ; CONDITION: VAR RELOP VAR {AddQuadruple($2,$1,$3,$$); StNo=Index-1; } | VAR | NUM ; WHILEST: WHILELOOP{ Ind=pop();
JOGINPALLY B.R. ENGINEERING COLLEGE
53
09J21D5818
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); 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");
JOGINPALLY B.R. ENGINEERING COLLEGE
54
09J21D5818
exit(0); } yyin=fp; } yyparse(); printf("\n\n\t\t ----------------------------""\n\t\t Pos Operator Arg1 Arg2 Result" "\n\t\t --------------------"); for(i=0;i<Index;i++) { printf("\n\t\t %d\t %s\t %s\t %s\t %s",i,QUAD[i].op,QUAD[i].arg1,QUAD[i].arg2,QUAD[i].result); } printf("\n\t\t -----------------------"); printf("\n\n"); return 0; } void push(int data) { stk.top++; if(stk.top==100) { printf("\n Stack overflow\n"); exit(0); } stk.items[stk.top]=data; } int pop() { int data; if(stk.top==-1) { printf("\n Stack underflow\n"); exit(0); }
JOGINPALLY B.R. ENGINEERING COLLEGE
55
09J21D5818
data=stk.items[stk.top--]; return data; } void AddQuadruple(char op[5],char arg1[10],char arg2[10],char result[10]) { strcpy(QUAD[Index].op,op); strcpy(QUAD[Index].arg1,arg1); strcpy(QUAD[Index].arg2,arg2); sprintf(QUAD[Index].result,"t%d",tIndex++); strcpy(result,QUAD[Index++].result); } yyerror() { printf("\n Error on line no:%d",LineNo); }
Input:
$vi test.c main() { int a,b,c; if(a<b) { a=a+b; } while(a<b) { a=a+b; } if(a<=b) { c=a-b; } else
JOGINPALLY B.R. ENGINEERING COLLEGE
56
09J21D5818
{ c=a+b; } }
Output:
$lex int.l $yacc d int.y $gcc lex.yy.c y.tab.c ll lm $./a.out test.c Pos 0 1 2 3 4 5 6 7 8 9 10 11 12 13
14 15 16
Arg1 a to a t1
Arg2 b FALSE b 5
Result to
t1 a 5
a t2 a t3 FALSE
b 10 b
t2
t3 a 5
a t4 a t5
b FALSE b
t4 15 t5 c
17
a t6
t3 c
57
09J21D5818
___________________________________________________
Program 6 Aim: A Program to Generate Machine Code.
#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)
JOGINPALLY B.R. ENGINEERING COLLEGE
58
09J21D5818
{ fscanf(fp1,"%s",result); fprintf(fp2,"\n\t OUT %s",result); } if(strcmp(op,"goto")==0) { fscanf(fp1,"%s %s",operand1,operand2); fprintf(fp2,"\n\t JMP %s,label#%s",operand1,operand2); label[no++]=atoi(operand2); } if(strcmp(op,"[]=")==0) { fscanf(fp1,"%s %s %s",operand1,operand2,result); fprintf(fp2,"\n\t STORE %s[%s],%s",operand1,operand2,result); } 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);
JOGINPALLY B.R. ENGINEERING COLLEGE
59
09J21D5818
break; case '-': fscanf(fp1,"%s %s %s",operand1,operand2,result); fprintf(fp2,"\n \t LOAD %s,R0",operand1); fprintf(fp2,"\n \t LOAD %s,R1",operand2); fprintf(fp2,"\n \t SUB R1,R0"); fprintf(fp2,"\n \t STORE R0,%s",result); break; case '/': fscanf(fp1,"%s %s %s",operand1,operand2,result); fprintf(fp2,"\n \t LOAD %s,R0",operand1); fprintf(fp2,"\n \t LOAD %s,R1",operand2); fprintf(fp2,"\n \t DIV R1,R0"); fprintf(fp2,"\n \t STORE R0,%s",result); break; case '%': fscanf(fp1,"%s %s %s",operand1,operand2,result); fprintf(fp2,"\n \t LOAD %s,R0",operand1); fprintf(fp2,"\n \t LOAD %s,R1",operand2); fprintf(fp2,"\n \t DIV R1,R0"); fprintf(fp2,"\n \t STORE R0,%s",result); break; case '=': fscanf(fp1,"%s %s",operand1,result); fprintf(fp2,"\n\t STORE %s %s",operand1,result); break; case '>': j++; fscanf(fp1,"%s %s %s",operand1,operand2,result); fprintf(fp2,"\n \t LOAD %s,R0",operand1); fprintf(fp2,"\n\t JGT %s,label#%s",operand2,result); label[no++]=atoi(result); break; case '<': fscanf(fp1,"%s %s %s",operand1,operand2,result); fprintf(fp2,"\n \t LOAD %s,R0",operand1); fprintf(fp2,"\n\t JLT %s,label#%d",operand2,result); label[no++]=atoi(result); break; }
JOGINPALLY B.R. ENGINEERING COLLEGE
60
09J21D5818
} fclose(fp2); fclose(fp1); fp2=fopen("target.txt","r"); if(fp2==NULL) { printf("Error opening the file\n"); exit(0); } do { ch=fgetc(fp2); printf("%c",ch); }while(ch!=EOF); fclose(fp1); return 0; } int check_label(int k) { int i; for(i=0;i<no;i++) { if(k==label[i]) return 1; } return 0; }
Input:
$vi int.txt =t1 2
[]=a 0 1 []=a 1 2
JOGINPALLY B.R. ENGINEERING COLLEGE
61
09J21D5818
[]=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 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
JOGINPALLY B.R. ENGINEERING COLLEGE
62
09J21D5818
SUB R1,R0 STORE R0,t2 LOAD t3,R0 LOAD t2,R1 DIV R1,R0 STORE R0,t2 LOAD t2,R1 STORE R1,t2 LOAD t2,R0 JGT 5,label#11 Label#11: OUT t2 JMP t2,label#13 Label#13: STORE t3,99 LOAD 25,R1 STORE R1,t2 LOAD t2,R0 LOAD t3,R1 MUL R1,R0 STORE R0,t3 LOAD t1,R1 STORE R1,t1 LOAD t1,R0 LOAD t3,R1 ADD R1,R0 STORE R0,t4 OUT t4
63
09J21D5818
64