database and compiler lab
TRANSCRIPT
Ellenki College of Engineering & Technology Databases and Compiler Lab
MTech CSE 2nd Semester
Ellenki College of Engineering & Technology Name : Patelguda (V), Near BHEL, Patancheru (M), Medak (Dist.) Roll No :
Database Programs Index
S NO NAME OF THE PROGRAM DATE
1 Basic DDL Commands
2 DML Commands
3 Querying
4 Triggers
5 Procedures
6 Cursors
MTech CSE 2nd Semester Databases and Compiler lab
Ellenki College of Engineering & Technology Name : Patelguda (V), Near BHEL, Patancheru (M), Medak (Dist.) Roll No :
Compiler Programs Index
S NO NAME OF THE PROGRAM DATE
1 A Program to Design Lexical Analyzer
2 Implement the Lexical Analyzer Using Lex Tool
3 Implementation of Predictive Parser
4 Design LALR Bottom up Parser
5Convert The BNF rules into Yacc form and write code to generate abstract syntax tree
6 A Program to Generate Machine Code
MTech CSE 2nd Semester Databases and Compiler lab
Ellenki College of Engineering & Technology Name : Patelguda (V), Near BHEL, Patancheru (M), Medak (Dist.) Roll No :
MTech CSE 2nd Semester Databases and Compiler lab
Ellenki College of Engineering & Technology Name : Patelguda (V), Near BHEL, Patancheru (M), Medak (Dist.) Roll No :
1.Practicing Basic DDL Commands The basic MySQL DDL Commands such as CREATE, DROP, etc
A.Create tables:
mysql>create table bus(BusNo varchar(10),source varchar(10),Destination varchar(10),Primary Key(BusNo)); Query OK, 0 rows affected (0.31 sec)
mysql> create table passenger(pnr_no numeric(10),ticket_no numeric(10),name varchar(15),age int(3),sex char(10),ppno varchar(15) primary key(pnr_no)); Query OK, 0 rows affected (0.31 sec)
mysql> create table reservation(pnr_no numeric(10),Journey_Data datetime,No_Of_Seats numeric(10),Address Varchar(30),ConTact_No numeric(10),Status Char(2),foreign key (pnr_no) REFERENCES passenger(pnr_no)); Query OK, 0 rows affected (0.31 sec)
mysql> create table cancellation(pnr_no numeric(10),Journey_Data datetime,No_Of_Seats numeric(10),Address Varchar(30),ConTact_No numeric(10),Status char(2),foreign key (pnr_no) REFERENCES passenger(pnr_no)); Query OK, 0 rows affected (0.14 sec)
mysql> create table ticket(ticket_no numeric(10),Journey_Data datetime,ageb int(3),sex char(10),source varchar(15),destination varchar(15),Dep_time varchar(10),primary key(ticket_no)); Query OK, 0 rows affected (0.28 sec)
B. Describe Tables:
MTech CSE 2nd Semester Databases and Compiler lab
Ellenki College of Engineering & Technology Name : Patelguda (V), Near BHEL, Patancheru (M), Medak (Dist.) Roll No :
mysql> describe bus;
+---------------+---------------+------+----------+-----------+---------+ | Field | Type | Null | Key | Default | Extra | +---------------+---------------+------+----------+----------+---------+ | bus no | varchar(10) | NO | PRI | | | | source | varchar(15) | YES | | NULL | | | destination | varchar(15) | YES | | NULL | | +---------------+---------------+------+-----------+----------+---------+ 3 rows in set (0.03 sec)
mysql> describe passenger; +-------------+------------------+------+-----+----------+-------+ | Field | Type | Null | Key | Default | Extra | +-------------+------------------+------+-----+----------+-------+ | pnr_no | decimal(10,0) | NO | PRI | 0 | | | ticket_no | decimal(10,0) | YES | | NULL | | | name | varchar(15) | YES | | NULL | | | age | int(3) | YES | | NULL | | | sex | char(10) | YES | | NULL | | | ppno | varchar(15) | YES | | NULL | | +------------+-------------------+------+-----+-----------+-------+ 6 rows in set (0.44 sec)
MTech CSE 2nd Semester Databases and Compiler lab
Ellenki College of Engineering & Technology Name : Patelguda (V), Near BHEL, Patancheru (M), Medak (Dist.) Roll No :
2.Practicing DML Commands
A. Insert Command: inserts data into a table
mysql> insert into bus values("ap092356","hyderabad","Gunter"); Query OK, 1 row affected (0.06 sec)
mysql> select * from bus; +--------------+-------------+-------------+ | bus no | source | destination | +---------- +-------------+--------------+ | ap092356 | hyderabad | Gunter | +-------------+-------------+--------------+ 1 row in set (0.00 sec)
mysql> insert into bus values("ap092490","Hyderabad","Gunter"); Query OK, 1 row affected (0.11 sec)
mysql> insert into bus values("ap212356","Hyderabad","Bangalore"); Query OK, 1 row affected (0.13 sec) mysql> insert into passenger values(1001,123,"sam",25,"male",9908233232); Query OK, 1 row affected (0.03 sec)
B. Update Command: Updates existing data within a table
mysql> update bus set destination="Tirupati"; Query OK, 1 row affected (0.06 sec) Rows matched: 1 Changed: 1 Warnings: 0
C. Select Command: Retrieve data from the Data Base mysql> select * from bus;
+-------------+--------------+-------------+ | bus no | source | destination| +-------------+--------------+-------------+ | ap092356 | hyderabad | Tirupati | | ap092490 | Hyderabad | Gunter | | ap212356 | Hyderabad | Bangalore |
MTech CSE 2nd Semester Databases and Compiler lab
Ellenki College of Engineering & Technology Name : Patelguda (V), Near BHEL, Patancheru (M), Medak (Dist.) Roll No :
+-------------+--------------+--------------+ 3 rows in set (0.00 sec)
3. Querying1.Display unique Pnr_No of all passengers
mysql> select distinct pnr_no from passenger;+--------+| pnr_no |+--------+| 1001 || 1002 || 1005 || 1023 || 1040 || 1435 || 1956 |+--------+7 rows in set (0.02 sec)
2.Display all the names of male passengers. mysql> select name from passenger where sex="male";
+----------+| name |+----------+| sam || prashant|| ranga || subhani |+----------+4 rows in set (0.00 sec)
3.Display the ticket numbers and names of all passengers.
MTech CSE 2nd Semester Databases and Compiler lab
Ellenki College of Engineering & Technology Name : Patelguda (V), Near BHEL, Patancheru (M), Medak (Dist.) Roll No :
mysql> select ticket_no,name from passenger;+-----------+------------+| ticket_no | name |+-----------+------------+| 123 | sam || 123 | bala || 126 | anitha || 124 | deepti || 127 | prashant || 125 | ranga || 128 | subhani |+-----------+------------+7 rows in set (0.00 sec)
4.Display the source and destination having journey time more than 10 hours.
mysql> select source,destination from ticket where timediff(arr_time,dep_time) > '10:00:00';+-------------+---------------+| source | destination |+-------------+---------------+| Hyderabad | gunter |+--------------+--------------+1 row in set (0.00 sec)
5.Find the ticket numbers of the passengers whose name start with “A” and ends with “H”
mysql> select ticket_no,name from passenger where name like "a%h";+-----------+-------+| ticket_no | name |+-----------+-------+| 129 | alah || 130 | ah |+-----------+-------+2 rows in set (0.00 sec)
6.Find the names of passengers whose age is between 30 and 45
MTech CSE 2nd Semester Databases and Compiler lab
Ellenki College of Engineering & Technology Name : Patelguda (V), Near BHEL, Patancheru (M), Medak (Dist.) Roll No :
mysql> select name,age from passenger where age between 30 and 45;+-----------+------+ | name | age |+-----------+------+ | bala | 30 | | anitha | 33 | | alah | 30 | | ah | 30 | | subhani | 33 |+-----------+-------+5 rows in set (0.20 sec)
7.Display all the passengers names beginning with ‘A’
mysql> select * from passenger where name like"a%";+---------+------------+--------+------+--------+----------------+| pnr_no | ticket_no | name | age | sex | ppno |+---------+------------+--------+------+--------+-----------------+| 1005 | 126 | anitha | 33 | female| 9441038706 || 1008 | 129 | alah | 30 | male | 9002345122 || 1009 | 130 | ah | 30 | male | 9002345122 |+--------+-------------+--------+------+--------+-----------------+3 rows in set (0.00 sec)
8.Display sorted list of passengers names
mysql> select name from passenger order by name;+----------+| name |+----------+| ah || alah || anitha || bala || deepti || prashant|
MTech CSE 2nd Semester Databases and Compiler lab
Ellenki College of Engineering & Technology Name : Patelguda (V), Near BHEL, Patancheru (M), Medak (Dist.) Roll No :
| ranga || sam || subhani |+-----------+9 rows in set (0.01 sec)
9.Display the bus numbers that travel on Sunday and Wednesday
mysql> select bus no from bus,ticket where bus.destination=ticket.destination and (dayname(journey_data)='sunday' or dayname(journey_data)='wednesday');+-------------+| bus no |+-------------+| ap092490 || ap092490 |+-------------+2 rows in set (0.00 sec)
10.Write a query to display the information present in the passenger and cancellation tables use UNION Operator
mysql> select pnr_no from passenger union select pnr_no from cancellation;
+---------+| pnr_no |
+---------+| 1001 || 1002 || 1005 || 1008 || 1009 || 1023 || 1040 || 1435 || 1956 |+---------+
MTech CSE 2nd Semester Databases and Compiler lab
Ellenki College of Engineering & Technology Name : Patelguda (V), Near BHEL, Patancheru (M), Medak (Dist.) Roll No :
9 rows in set (0.01 sec) 11. Display the number of days in a week on which the bus is available.
mysql> select day_travel from bus where bus no="ap092356";
+------------------+| day_travel |+------------------+| sun,tue,thur,sat |+------------------+1 row in set (0.00 sec)
12. Find number of seats booked for each PNR_NO using Group by Clause Hint: Use Group By On PNR_NO mysql> SELECT NO_OF_SEATS FROM RESERVATION GROUP BY PNR_NO;
+--------------------+| NO_OF_SEATS |+--------------------+| 2 |+--------------------+1 row in set (0.00 sec)
13. SELECT Distinct PNR_NO that are present
mysql> SELECT DISTINCT PNR_NO FROM PASSENGER;+----------+| PNR_NO |+----------+| 1001 || 1002 || 1005 || 1008 || 1009 || 1023 || 1040 |
MTech CSE 2nd Semester Databases and Compiler lab
Ellenki College of Engineering & Technology Name : Patelguda (V), Near BHEL, Patancheru (M), Medak (Dist.) Roll No :
| 1435 || 1956 |+----------+9 rows in set (0.00 sec)
14. Find total number of cancelled seats
mysql> select sum(no_of_seats) from cancellation;+---------------------+| sum(no_of_seats) |+---------------------+| 7 |+---------------------+1 row in set (0.00 sec)
15. Write a query to count the number of tickets booked for the buses, which traveled after the date “2010-07-02”.
mysql> select count(ticket_no) from ticket where date(journey_date) > '2010-07-02';+--------------------+| count(ticket_no) |+--------------------+| 3 |+--------------------+1 row in set (0.00 sec)
MTech CSE 2nd Semester Databases and Compiler lab
Ellenki College of Engineering & Technology Name : Patelguda (V), Near BHEL, Patancheru (M), Medak (Dist.) Roll No :
4.Triggers: Creation of Insert trigger, Delete Trigger, Update TriggerEX: mysql> delimiter $$; mysql> create trigger updatecheck before update on passenger 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$$;
Query OK, 0 rows affected (0.08 sec)
mysql> delimiter ;
5.Procedures: In this we will learn creation of stored procedure, Execution of procedure and Modification of procedure.
mysql> delimiter $$; mysql> create procedure p1() -> begin
-> select count(ticket_no) from ticket where ageb>20; -> end$$;Query OK, 0 rows affected (0.00 sec)
mysql> delimiter ;mysql> call p1();+----------------------+| count(ticket_no) |+----------------------+| 3 |+----------------------+1 row in set (0.03 sec)
MTech CSE 2nd Semester Databases and Compiler lab
Ellenki College of Engineering & Technology Name : Patelguda (V), Near BHEL, Patancheru (M), Medak (Dist.) Roll No :
6.cursors:
We will define a cursor that defines a result set. Open the cursor to establish the Result set. Fetch the data into local variables as needed from the cursor one Row at a time. Then we will close the cursor.
mysql> delimiter $$;mysql> create procedure procd() -> begin -> declare busn varchar(20); -> declare dest varchar(20); -> declare cu5 cursor for select busno,destination from bus where destination="tirupati"; -> open cu5; -> fetch cu5 into busn,dest; -> select * from bus where destination=dest; -> close cu5; -> end$$;Query OK, 0 rows affected (0.00 sec)
mysql> delimiter ;
mysql> call procd();+-------------+-------------+--------------+--------------------+ | bus no | source | destination | day_travel |+-------------+-------------+--------------+--------------------+ | ap092356 | hyderabad | Tirupati | sun,tue,thur,sat |+-------------+-------------+--------------+--------------------+1 row in set (0.08 sec)
Query OK, 0 rows affected (0.08 sec)
MTech CSE 2nd Semester Databases and Compiler lab
Ellenki College of Engineering & Technology Name : Patelguda (V), Near BHEL, Patancheru (M), Medak (Dist.) Roll No :
MTech CSE 2nd Semester Databases and Compiler lab
Ellenki College of Engineering & Technology Name : Patelguda (V), Near BHEL, Patancheru (M), Medak (Dist.) Roll No :
1)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))
{tokenvalue=c-'0';c=getc(f1);
MTech CSE 2nd Semester Databases and Compiler lab
Ellenki College of Engineering & Technology Name : Patelguda (V), Near BHEL, Patancheru (M), Medak (Dist.) Roll No :
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++)
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;
MTech CSE 2nd Semester Databases and Compiler lab
Ellenki College of Engineering & Technology Name : Patelguda (V), Near BHEL, Patancheru (M), Medak (Dist.) Roll No :
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 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 7
MTech CSE 2nd Semester Databases and Compiler lab
Ellenki College of Engineering & Technology Name : Patelguda (V), Near BHEL, Patancheru (M), Medak (Dist.) Roll No :
2)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;} /*{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");}
MTech CSE 2nd Semester Databases and Compiler lab
Ellenki College of Engineering & Technology Name : Patelguda (V), Near BHEL, Patancheru (M), Medak (Dist.) Roll No :
{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]);
exit(0);
}yyin = file;
}yylex();
printf("\n\n");
return 0; }int yywrap() { return 0;
MTech CSE 2nd Semester Databases and Compiler lab
Ellenki College of Engineering & Technology Name : Patelguda (V), Near BHEL, Patancheru (M), Medak (Dist.) Roll No :
}
Input: $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
MTech CSE 2nd Semester Databases and Compiler lab
Ellenki College of Engineering & Technology Name : Patelguda (V), Near BHEL, Patancheru (M), Medak (Dist.) Roll No :
3) 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 999char 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 entrykeywords[]={"if",KEYWORD,"else",KEYWORD,"for",KEYWORD,"int",KEYWORD,"float",KEYWORD,"double",KEYWORD,"char",KEYWORD,"struct",KEYWORD,"return",KEYWORD,0,0};void Error_Message(char *m){fprintf(stderr,"line %d, %s \n",lineno,m);exit(1);}int look_up(char s[ ])
MTech CSE 2nd Semester Databases and Compiler lab
Ellenki College of Engineering & Technology Name : Patelguda (V), Near BHEL, Patancheru (M), Medak (Dist.) Roll No :
{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(){
int t;int val,i=0;while(1)
{t=getchar();if(t==' '||t=='\t');else if(t=='\n')lineno=lineno+1;
MTech CSE 2nd Semester Databases and Compiler lab
Ellenki College of Engineering & Technology Name : Patelguda (V), Near BHEL, Patancheru (M), Medak (Dist.) Roll No :
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;
}else if(t==EOF)
return DONE;else{
tokenval=NONE; return t; } } }void Match(int t) { if(lookahead==t) lookahead=lexer(); else
MTech CSE 2nd Semester Databases and Compiler lab
Ellenki College of Engineering & Technology Name : Patelguda (V), Near BHEL, Patancheru (M), Medak (Dist.) Roll No :
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();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) {
MTech CSE 2nd Semester Databases and Compiler lab
Ellenki College of Engineering & Technology Name : Patelguda (V), Near BHEL, Patancheru (M), Medak (Dist.) Roll No :
case '*' : t=lookahead;Match(lookahead);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;
} } }void parser()
MTech CSE 2nd Semester Databases and Compiler lab
Ellenki College of Engineering & Technology Name : Patelguda (V), Near BHEL, Patancheru (M), Medak (Dist.) Roll No :
{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 parsingEnter the expression And place ; at the endPress Ctrl-Z to terminatea+b*c;Identifier: aIdentifier: bIdentifier: cArithmetic Operator: *Arithmetic Operator: +2*3;Number: 2Number: 3Arithmetic Operator: *+3;line 5,Syntax errorCtrl-Z
MTech CSE 2nd Semester Databases and Compiler lab
Ellenki College of Engineering & Technology Name : Patelguda (V), Near BHEL, Patancheru (M), Medak (Dist.) Roll No :
4) Design LALR Bottom up Parser . <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
MTech CSE 2nd Semester Databases and Compiler lab
Ellenki College of Engineering & Technology Name : Patelguda (V), Near BHEL, Patancheru (M), Medak (Dist.) Roll No :
{$$=$1 + $3 ;}| term;
Ter m: 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.out2+35.0000
MTech CSE 2nd Semester Databases and Compiler lab
Ellenki College of Engineering & Technology Name : Patelguda (V), Near BHEL, Patancheru (M), Medak (Dist.) Roll No :
5) 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
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;}
\< |\> |\>= |
MTech CSE 2nd Semester Databases and Compiler lab
Ellenki College of Engineering & Technology Name : Patelguda (V), Near BHEL, Patancheru (M), Medak (Dist.) Roll No :
\<= |==
{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;%}
%union { char var[10];
MTech CSE 2nd Semester Databases and Compiler lab
Ellenki College of Engineering & Technology Name : Patelguda (V), Near BHEL, Patancheru (M), Medak (Dist.) Roll No :
}%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 ;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,"",$$);}
MTech CSE 2nd Semester Databases and Compiler lab
Ellenki College of Engineering & Technology Name : Patelguda (V), Near BHEL, Patancheru (M), Medak (Dist.) Roll No :
| '(' 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");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;
MTech CSE 2nd Semester Databases and Compiler lab
Ellenki College of Engineering & Technology Name : Patelguda (V), Near BHEL, Patancheru (M), Medak (Dist.) Roll No :
}| VAR | NUM ;
W 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);Index++;}
;%%extern FILE *yyin;int main(int argc,char *argv[]){
FILE *fp;int i;if(argc>1){
MTech CSE 2nd Semester Databases and Compiler lab
Ellenki College of Engineering & Technology Name : Patelguda (V), Near BHEL, Patancheru (M), Medak (Dist.) Roll No :
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; }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){
MTech CSE 2nd Semester Databases and Compiler lab
Ellenki College of Engineering & Technology Name : Patelguda (V), Near BHEL, Patancheru (M), Medak (Dist.) Roll No :
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() { 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; }
MTech CSE 2nd Semester Databases and Compiler lab
Ellenki College of Engineering & Technology Name : Patelguda (V), Near BHEL, Patancheru (M), Medak (Dist.) Roll No :
}
Output:
$lex int.l$yacc –d int.y$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
MTech CSE 2nd Semester Databases and Compiler lab
Ellenki College of Engineering & Technology Name : Patelguda (V), Near BHEL, Patancheru (M), Medak (Dist.) Roll No :
6) 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){
fscanf(fp1,"%s",result); fprintf(fp2,"\n\t OUT %s",result); }if(strcmp(op,"goto")==0)
{fscanf(fp1,"%s %s",operand1,operand2);
MTech CSE 2nd Semester Databases and Compiler lab
Ellenki College of Engineering & Technology Name : Patelguda (V), Near BHEL, Patancheru (M), Medak (Dist.) Roll No :
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);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);
MTech CSE 2nd Semester Databases and Compiler lab
Ellenki College of Engineering & Technology Name : Patelguda (V), Near BHEL, Patancheru (M), Medak (Dist.) Roll No :
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;
} }fclose(fp2);
fclose(fp1);fp2=fopen("target.txt","r");if(fp2==NULL){
printf("Error opening the file\n"); exit(0); }do { ch=fgetc(fp2);
MTech CSE 2nd Semester Databases and Compiler lab
Ellenki College of Engineering & Technology Name : Patelguda (V), Near BHEL, Patancheru (M), Medak (Dist.) Roll No :
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 []=a 2 3 *t1 6 t2
+a[2] t2 t3
-a[2] t1 t2/t3 t2 t2uminus t2 t2print t2goto t2 t3=t3 99uminus 25 t2*t2 t3 t3uminus t1 t1+t1 t3 t4print t4
Output: Enter filename of the intermediate code: int.txt
STORE t1,2STORE a[0],1STORE a[1],2STORE a[2],3
MTech CSE 2nd Semester Databases and Compiler lab
Ellenki College of Engineering & Technology Name : Patelguda (V), Near BHEL, Patancheru (M), Medak (Dist.) Roll No :
LOAD t1,R0LOAD 6,R1ADD R1,R0STORE R0,t3
LOAD a[2],R0LOAD t2,R1ADD R1,R0STORE R0,t3
LOAD a[t2],R0LOAD t1,R1SUB R1,R0STORE R0,t2
LOAD t3,R0LOAD t2,R1DIV R1,R0STORE R0,t2
LOAD t2,R1STORE R1,t2LOAD t2,R0JGT 5,label#11
Label#11: OUT t2 JMP t2,label#13
Label#13: STORE t3,99LOAD 25,R1STORE R1,t2
LOAD t2,R0LOAD t3,R1MUL R1,R0STORE R0,t3
LOAD t1,R1 STORE R1,t1
LOAD t1,R0LOAD t3,R1
MTech CSE 2nd Semester Databases and Compiler lab
Ellenki College of Engineering & Technology Name : Patelguda (V), Near BHEL, Patancheru (M), Medak (Dist.) Roll No :
ADD R1,R0STORE R0,t4OUT t4
MTech CSE 2nd Semester Databases and Compiler lab