[go: up one dir, main page]

0% found this document useful (0 votes)
41 views32 pages

Compiler Design Lab Manual

The document is a lab manual for Compiler Design, detailing experiments on implementing a Lexical Analyzer, Predictive Parser, generating Three Address Code, and designing an SLR(1) Bottom Up Parser. Each experiment includes problem statements, aims, algorithms, source code, and expected outputs, along with viva questions for assessment. The manual serves as a practical guide for students to understand compiler design concepts through hands-on coding exercises.

Uploaded by

Safgbkj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views32 pages

Compiler Design Lab Manual

The document is a lab manual for Compiler Design, detailing experiments on implementing a Lexical Analyzer, Predictive Parser, generating Three Address Code, and designing an SLR(1) Bottom Up Parser. Each experiment includes problem statements, aims, algorithms, source code, and expected outputs, along with viva questions for assessment. The manual serves as a practical guide for students to understand compiler design concepts through hands-on coding exercises.

Uploaded by

Safgbkj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 32

Compiler Design Lab Manual MRITS

EXPERIMENT 1
1. Problem Statement: Implement the Lexical analyzer using JLex, flex or other lexical
Analyzer generating tools.

AIM: Write a LEX Program to scan reserved word & Identifiers of C Language

ALGORITHM / PROCEDURE:
Input : LEX specification files for the token
Output : Produces the source code for the Lexical Analyzer with the name lex.yy.c
and displays reserved word & Identifiers from an input file.
1. Start
2. Open a file in texteditor
3. Create a Lex specifications file to accept keywords, identifiers, constants, operators
and relational operators in the followingformat.
a) %{
Definition of constant /header files
%}
b) RegularExpressions
%%
Transition rules
%%
c) Auxiliary Procedure (main( )function)
4. Save file with .l extension e.g.mylex.l

5. Calllextoolontheterminale.g.[root@localhost]#lexmylex.l.Thislextoolwill

convert

“.l” file into “.c” language code file i.e., lex.yy.c


6. Compile the file lex.yy.c using C / C++ compiler. e.g. gcc lex.yy.c. After compilation

the file lex.yy.c, the output file is ina.out


7. Run the file a.out giving an input(text/file) e.g../a.out.

8. Upon processing, the sequence of tokens will be displayed asoutput.

9. Stop

1
Compiler Design Lab Manual MRITS

LEX SPECIFICATION PROGRAM / SOURCE CODE (identifier.l) :

// ********* LEX Tool program to scan Identifiers *****************//

%{
#include<stdio.h>
%}

letter [a-zA-Z_]
digit [0-9]
special [;:./\,&'$#^@~?]

%%

(auto|break|case|char|const|continue|default|do|double|else|enum|extern|float|for|goto|if|
int|long|register|return|short|signed|sizeof|static|struct|switch|typedef|union|unsigned|
void|volatile|while)* {printf("\n%s is not an Identifier\nReason: Cannot be a
Keyword!",yytext);}

{letter}({letter}|{digit})* {printf("\n%s is an identifier",yytext);}

{digit}({letter}|{digit})* {printf("\n%s is not an identifier\nReason:Cannot start with a


digit",yytext);}

({special}|{letter}|{digit})({special}|{letter}|{digit})* {printf("\n%s is not an identifier\


nReason:Cannot contain a special charcter!",yytext);}

%%

int main()
{
yylex();
}
int yywrap()
{
return 0;
}

Output:

2
Compiler Design Lab Manual MRITS

LEX SPECIFICATION PROGRAM / SOURCE CODE (reserveword.l) :

// ********* LEX Tool program to scan reserve word *****************//

%{
#include<stdio.h>
%}

letter[a-zA-Z_]

digit[0-9]

%%

(auto|break|case|char|const|continue|default|do|double|else|enum|extern|float|for|
goto|if|int|long|register|return|short|signed|sizeof|static|struct|switch|typedef|
union|unsigned|void|volatile|while)* {printf("\n%s is a keyword!",yytext);}

({letter}|{digit})({letter}|{digit})* {printf("\n%s is not a keyword",yytext);}

%%
int main()
{
yylex();
}
int yywrap()
{
return 0;
}
Output:

Viva Questions:
1. List the different sections available in LEX compiler?
2. What is an auxiliary definition?
3. How can we define the translation rules?
4. What is regular expression?
5. What is finite automaton?
6. What is Jlex?
7. What is Flex?
3
Compiler Design Lab Manual MRITS

8. What is lexical analyzer generator?


9. What is the input for LEX Compiler?
10. What is the output of LEX compiler?
EXPERIMENT 2
2.Problem Statement : Design Predictive Parser for the following grammar
ETA
A+TA/Ꜫ
TFB
B*FB/Ꜫ
F(E)/i
AIM: To write a ‘C’ Program to implement for the Predictive Parser (Non Recursive
Descent parser) for the given grammar

Given the parse Table:


i + * ( ) $
E ETA ETA
A A +TA AꜪ AꜪ
T TFB TFB
B BꜪ B*FB BꜪ BꜪ
F F i F(E)

ALGORITHM / PROCEDURE :

Input:string w$, Predictive Parsing table M


Output:

Step1: Start
Step2: Declare a character array w[10] and Z asan array
Step3: Enter the string with $ at theend
Step4:

if(A(w[z])thenincrementzandcheckfor(B(w[z]))andifsatisfiesincrementzandch
eckfor ‘d’ifdispresentthenincrementandcheckfor(D(w[z]))
Step5: if step 4 is satisfied then the string isaccepted Else string isnot
Step6: Exit
SOURCE CODE :

// ***IMPLEMENTATION OF PREDICTIVE PARSING *****//


#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void push(char);
void pop();
char input[10];
char stk[20];
int top=-1;
int ip=0;
void push(char c)
{ 4
Compiler Design Lab Manual MRITS

if(top>=20)
{
printf("stack overflow");
}
else
{
stk[++top]=c;
}
}

void pop()
{
if(top==-1)
{
printf("stack underflow");
}
else
top--;
}
void display()
{
int i;
for(i=0;i<=top;i++)
printf("%c",stk[i]);
}
void inputdisplay()
{
int i;
i=ip;
while(input[i]!='\0')
printf("%c",input[i++]);
}

void main()
{
int flag=0;
clrscr();
printf("\nEnter the input to be parsed with the delimiter $");
scanf("%s",input);
push('$');
push('E');
printf("STACK INPUTDATA");
while(1)
{
printf("\n");
display();
printf(" ------------------------------------- ");
inputdisplay();
if(stk[top]=='$'&&input[ip]=='$')
{
flag=1;
printf("\nSuccessful parser");
break;
} 5
Compiler Design Lab Manual MRITS

else if(stk[top]==input[ip])
{
ip++;
pop();
}
else if(stk[top]=='E')
{
if(input[ip]=='i'|| '(')
{
pop();
push('A');
push('T');
}
else
break;

}
else if(stk[top]=='A')
{
if(input[ip]=='+')
{
pop();
push('A');
push('T');
push('+');
}
else if(input[ip]==')'||'$')
{
pop();
}
else
break;
}
else if(stk[top]=='T')
{
if(input[ip]=='i'||'(')
{
pop();
push('B');
push('F');
}
else
break;
}
else if(stk[top]=='B')
{
if(input[ip]=='*')
{
pop();
push('B');
push('F');
push('*');
}
else if(input[ip]=='+'||')'||'$')
6
Compiler Design Lab Manual MRITS

{
pop();
}
else
break;
}
else if(stk[top]=='F')
{
if(input[ip]=='i')
{
pop();
push('i');
}
else if(input[ip]=='(')
{
pop();
push(')');
push('E');
push('(');
}
else
break;
}
else
break;
}
if(flag==0)
printf("\nIt is an invalid input");
getch();
}

INPUT: i+i$
OUTPUT:
-----------------------
Stack Input
-----------------------
$E i+i$
$AT i+i$
$ABF i+i$
$ABi i+i$
$AB +i$
$A +i$
$AT+ +i$
$AT i$
$ABF i$
$ABi i$
$A $
$ $
SUCCESSFULLY PARSED

Viva Questions:
1. What is top-down parsing?
2. What are the disadvantages of brute force method?
3. What is context free grammar? 7
Compiler Design Lab Manual MRITS

4. What is parse tree?


5. What is ambiguous grammar?
6. What are the derivation methods to generate a string for the given grammar?
7. What is the output of parse tree?
8. What is Predictive parser?
9. How many types of analysis can we do using Parser?
10. What is Recursive Decent Parser?

8
Compiler Design Lab Manual MRITS

EXPERIMENT 3
3.Problem Statement: Write a C program to generate three address code.

AIM: To write a ‘C’ Program to generate three address code


SOURCE CODE :

#include<stdio.h>
#include<string.h>
void pm();
void plus();
void div();
int i,ch,j,l,addr=100;
char ex[10], exp[10] ,exp1[10],exp2[10],id1[5],op[5],id2[5];
void main()
{
clrscr();
while(1)
{
printf("\n1.assignment\n2.arithmetic\n3.relational\n4.Exit\nEnter the choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("\nEnter the expression with assignment operator:");
scanf("%s",exp);
l=strlen(exp);
exp2[0]='\0';
i=0;
while(exp[i]!='=')
{
i++;
}
strncat(exp2,exp,i);
strrev(exp);
exp1[0]='\0';
strncat(exp1,exp,l-(i+1));
strrev(exp1);
printf("Three address code:\ntemp=%s\n%s=temp\n",exp1,exp2);
break;

case 2:
printf("\nEnter the expression with arithmetic operator:");
scanf("%s",ex);
strcpy(exp,ex);
l=strlen(exp);
exp1[0]='\0';

for(i=0;i<l;i++)
{
if(exp[i]=='+'||exp[i]=='-')
{
9
Compiler Design Lab Manual MRITS

if(exp[i+2]=='/'||exp[i+2]=='*')
{
pm();
break;
}
else
{
plus();
break;
}
}
else if(exp[i]=='/'||exp[i]=='*')
{
div();
break;
}
}
break;

case 3:
printf("Enter the expression with relational operator");
scanf("%s%s%s",&id1,&op,&id2);
if(((strcmp(op,"<")==0)||(strcmp(op,">")==0)||(strcmp(op,"<=")==0)||
(strcmp(op,">=")==0)||(strcmp(op,"==")==0)||(strcmp(op,"!=")==0))==0)
printf("Expression is error");
else
{
printf("\n%d\tif %s%s%s goto %d",addr,id1,op,id2,addr+3);
addr++;
printf("\n%d\t T:=0",addr);
addr++;
printf("\n%d\t goto %d",addr,addr+2);
addr++;
printf("\n%d\t T:=1",addr);
}
break;
case 4:
exit(0);
}
}
}
void pm()
{
strrev(exp);
j=l-i-1;
strncat(exp1,exp,j);
strrev(exp1);
printf("Three address code:\ntemp=%s\ntemp1=%c%ctemp\n",exp1,exp[j+1],exp[j]);
}
void div()
{
strncat(exp1,exp,i+2);

10
Compiler Design Lab Manual MRITS

printf("Three address code:\ntemp=%s\ntemp1=temp%c%c\n",exp1,exp[i+2],exp[i+3]);


}
void plus()
{
strncat(exp1,exp,i+2);
printf("Three address code:\ntemp=%s\ntemp1=temp%c%c\n",exp1,exp[i+2],exp[i+3]);
}

OUTPUT:

1. assignment
2. arithmetic
3. relational
4. Exit
Enter the choice:1
Enter the expression with assignment operator:
a=b
Three address code:
temp=b
a=temp

1.assignment
2.arithmetic
3.relational
4.Exit
Enter the choice:2
Enter the expression with arithmetic operator:
a+b-c
Three address code:
temp=a+b
temp1=temp-c

1.assignment
2.arithmetic
3.relational
4.Exit
Enter the choice:2
Enter the expression with arithmetic operator:
a-b/c
Three address code:
temp=b/c
temp1=a-temp

1.assignment
2.arithmetic
3.relational
4.Exit
Enter the choice:2
Enter the expression with arithmetic operator:
a*b-c
Three address code:
temp=a*b
temp1=temp-c
11
Compiler Design Lab Manual MRITS

1.assignment
2.arithmetic
3.relational
4.Exit
Enter the choice:2
Enter the expression with arithmetic operator:
a/b*c
Three address code:
temp=a/b
temp1=temp*c
temp=a/b
temp1=temp*c
1.assignment
2.arithmetic
3.relational
4.Exit
Enter the choice:3
Enter the expression with relational operator
a<=b
Three address code:
100 if a<=b goto 103
101 T:=0
102 goto 104
103 T:=1

1.assignment
2.arithmetic
3.relational
4.Exit
Enter the choice:4

Viva Questions:

1. Write the forms of Intermediate Code?


2. How Three Address Code(3AC) can be represented?
3. Write 3AC for Expressions?
4. Example for Triples?
5. Example for Quadruples?
6. Example for Indirect Triples?

12
Compiler Design Lab Manual MRITS

EXPERIMENT 4
4. Problem Statement: Design a SLR(1) Bottom Up Parser

Aim:To Design and implement an SLR(1) Bottom up Parser

ALGORITHM:
Step1: Start
Step2: Initially the parser has s0 on the stack where s0 is the initial state and w$ is in buffer
Step3: Set ip point to the first symbol of w$
Step4: repeat forever, begin
Step5: Let S be the state on top of the stack and a symbol pointed to by ip
Step6: if action [S, a] =shift S then begin
Push S1 on to the top of the stack
Advance ip to next input symbol
Step7:else if action [S, a], reduce AB then begin Pop 2* |B| symbols of the stack
Let S1 be the state now on the top of the stack
Step8: Output the production AB
End
Step9: else if action [S, a]=accepted, then return else error()
End
Step10: Stop

Source Code : SLR(1) Parser

#include<stdio.h>
#include<stdlib.h>
void push(char);
void pop();
char input[10];
char stk[30];
void error();
int top=-1;
int ip=0;
void push(char c)
{
if(top>=30)
{
printf("stack overflow");
}
else
{
stk[++top]=c;
}
}
void pop()
{
if(top==-1)
{
printf("stack underflow");
}
else
13
Compiler Design Lab Manual MRITS

top--;
}
void display()
{
int i;
for(i=0;i<=top;i++)
printf("%c",stk[i]);
}
void inputdisplay()
{
int i;
i=ip;
while(input[i]!='\0')
printf("%c",input[i++]);
}
void main()
{
int flag=0;
clrscr();
printf("\nEnter the input to be parsed with the delimiter $");
scanf("%s",input);
push('0');
printf("STACK INPUT");
while(1)
{
printf("\n");
display();
printf(" --------------------------- ");
inputdisplay();
switch(stk[top])
{
case '0':
if(input[ip]=='i')
{
ip++;
push('i');
push('5');
}
else if(input[ip]=='(')
{
ip++;
push('(');
push('4');
}
else
error();
break;
case '1':
if(input[ip]=='+')
{
ip++;
push('+');

14
Compiler Design Lab Manual MRITS

push('6');
}
else if(input[ip]=='$')
{
printf("successful parsed");
exit(1);
}
else
error();
break;
case '2':
if(input[ip]=='*')
{
ip++;
push('*');
push('7');
}
else if(input[ip]=='+'||')'||'$')
{
pop();
pop();
push('E');
if(stk[top-1]=='0')
push('1');
else if(stk[top-1]=='4')
push('8');
else
error();
}
else
error();
break;
case '3':
if(input[ip]=='+'||'*'||')'||'$')
{
pop();
pop();
push('T');
if(stk[top-1]=='0')
push('2');
else if(stk[top-1]=='4')
push('2');
else if(stk[top-1]=='6')
push('9');
else
error();
}
else
error();
break;
case '4':
if(input[ip]=='i')

15
Compiler Design Lab Manual MRITS

{
ip++;
push('i');
push('5');
}
else if(input[ip]=='(')
{
ip++;
push('(');
push('4');
}
else
error();
break;
case '5':
if(input[ip]=='+'||'*'||')'||'$')
{
pop();
pop();
push('F');
if(stk[top-1]=='0')
push('3');
else if(stk[top-1]=='4')
push('3');
else if(stk[top-1]=='6')
push('3');
else if(stk[top-1]=='7')
push('@');
else
error();
}
else
error();
break;
case '6':
if(input[ip]=='i')
{
ip++;
push('i');
push('5');
}
else if(input[ip]=='(')
{
ip++;
push('(');
push('4');
}
else
error();
break;
case '7':
if(input[ip]=='i')

16
Compiler Design Lab Manual MRITS

{
ip++;
push('i');
push('5');
}
else if(input[ip]=='(')
{
ip++;
push('(');
push('4');
}
else
error();
break;
case '8':
if(input[ip]=='+')
{
ip++;
push('+');
push('6');
}
else if(input[ip]==')')
{
ip++;
push(')');
push('#');
}
else
error();
break;
case '9':
if(input[ip]=='*')
{
ip++;
push('*');
push('7');
}
else if(input[ip]=='+'||')'||'$')
{
pop();
pop();
pop();
pop();
pop();
pop();
push('E');
if(stk[top-1]=='0')
push('1');
else if(stk[top-1]=='4')
push('8');
else
error();

17
Compiler Design Lab Manual MRITS

}
else
error();
break;
case '@':
if(input[ip]=='+'||'*'||')'||'$')
{
pop();
pop();
pop();
pop();
pop();
pop();
push('T');
if(stk[top-1]=='0')
push('2');
else if(stk[top-1]=='4')
push('2');
else if(stk[top-1]=='6')
push('9');
else
error();
}
else
error();
break;
case '#':
if(input[ip]=='+'||'*'||')'||'$')
{
pop();
pop();
pop();
pop();
pop();
pop();
push('F');
if(stk[top-1]=='0')
push('3');
else if(stk[top-1]=='4')
push('3');
else if(stk[top-1]=='6')
push('3');
else if(stk[top-1]=='7')
push('@');
else
error();
}
else
error();
break;
default:
error();

18
Compiler Design Lab Manual MRITS

break;
}
}
}

void error()
{
printf("invalid input");
exit(1);
}

INPUT: i*i+i$

OUTPUT:
----------------------------
STACK INPUT
----------------------------
0 i*i+i$
0i5 *i+i$
0F3 *i+i$
0T2 *i+i$
0T2*7 i+i$
0T2*7i5 +i$
0T2*7F@ +i$
0T2 +i$
0E1 +i$
0E1+6 i$
0E1+6i5 $
0E1+6F3 $
0E1+6T $
0E1 $

SUCCESSFULLY PARSED

Viva Questions:

1. Why bottom-up parsing is also called as shift reduce parsing?


2. What are the different types of bottom up parsers?
3. What is mean by LR (0) items?
4. What is SLR(1) parsing?
5. What is Shift reduced parser?
6. What are the operations of Parser?
7. What is the use of parsing table?
8. What is bottom up parsing?

19
Compiler Design Lab Manual MRITS

EXPERIMENT 5
5. Problem Statement: Design a LALR Bottom Up Parser for the given grammar.

Aim:To Design and implement an LALR bottom up Parser for checking the
syntax of the Statements in the given language.

The syntax of the language is defined by the following BNF grammar:


<program> ::= <block>
<block> ::= { <variable definition><slist> }
|{ <slist>}
<variable definition> ::= int <vardeflist> ;
<vardeflist> ::= <vardec>| <vardec>, <vardeflist>
<vardec> ::= <identifier>|<identifier> [<constant>]
<slist> ::= <statement> |<statement> ; <slist>
<statement> ::= <assignment>|<ifstatement>|<whilestatement>|<block>
|<printstatement>|<empty>
<assignment> ::= < identifier> =<expression>
|<identifier> [<expression>] = [<expression>
<ifstatement> ::= if <bexpression> then <slist> else <slist> endif
|if <bexpression> then <slist>endif
<whilestatement> ::= while <bexpression> do <slist> enddo
<printstatement> ::= print{ <expression> }
<expression> ::= <expression><addingop><term>|<term>|<addingop><term>
<bexpression> ::= <expression><relop><expression>
<relop> ::= <|<= |= = |>= |> |!=
<addingop> ::= + |-
<term> ::= <term><multop><factor>|<factor>
<multop> ::= * |/
<factor> ::= <constant>|<identifier> |<identifier> [<expression>
|(<expression>)
<constant> ::= <digit>|<digit><constant>
<identifier> ::= <identifier><letterordigit>|<letter>
<letterordigit> ::= a|b|c|….|y|z
<digit> ::= 0|1|2|3|…|8|9
<empty> ::= has the obvious meaning
Comments : zero or more characters enclosed between the standard C/Java style comment
brockets /*…*/. The language has the rudimentary support for 1-Dimensional arrays. Ex: int
a[3] declares a as an array of 3 elements, referenced as a[0],a[1],a[2].
Sample Program written in this language is :
int main()
{
int a[3],t1,t2;
t1=2;
a[0]=1; a[1]=2; a[t1]=3;
t2= -(a[2]+t1*6) / a[2]-t1);

20
Compiler Design Lab Manual MRITS

if t2>5 then
print(t2);
else
{
int t3;
t3=99
;
t2=25
;
print(-11+t2*t3); /* this is not a comment on two lines */
}
endif
}

Source Code : LALR Bottom Up Parser


#include <stdio.h>
#include<stdlib.h>
void push(char);
void pop();
char input[10];
char stk[30];
void error();
int top=-1;
int ip=0;
void push(char c)
{
if(top>=30)
printf("Stack overflow");
else
stk[++top]=c;
}
void pop()
{
if(top==-1)
printf("Stack underflow");
else
top--;
}
void display()
{
int i;
for (i=0;i<=top;i++)
printf("%c",stk[i]);
}
void inputdisplay()
{
int i;
i=ip;
while(input[i]!='\0')
printf("%c",input[i++]);
21
Compiler Design Lab Manual MRITS

}
void main()
{
int flag=0;
printf("\nEnter the input to be parsed with the delimiter $");
scanf("%s",input);
push('0');
printf("stack contents input data");
while(1)
{
printf("\n");
display();
printf("---------------------------------------------------");
inputdisplay();
switch(stk[top])
{
case '0':
if (input[ip]=='c')
{
ip++;
push('c');
push('@');
}
else if(input[ip]=='d')
{
ip++;
push('d');
push('#');
}
else
{
printf("Could not be PARSED");
error();
}
break;
case '1':
if(input[ip]=='$')
{
printf("SUCCESSFULLY PARSED");
exit(1);
}
else
{
printf("Could not be PARSED");
error();
}
break;
case '2':
if (input[ip]=='c')
{
ip++;
push('c');
push('@');
22
Compiler Design Lab Manual MRITS

}
else if(input[ip]=='d')
{
ip++;
push('d');
push('#');
}
else
{
printf("Could not be PARSED");
error();
}
break;
case '@':
if (input[ip]=='c')
{
ip++;
push('c');
push('@');
}
else if(input[ip]=='d')
{
ip++;
push('d');
push('#');
}
else
{
printf("Could not be PARSED");
error();
}
break;
case'#':
if(input[ip]=='c'||'d'||'$')
{
pop();
pop();
push('C');
if(stk[top-1]=='0')
push('2');
else if(stk[top-1]=='2')
push('5');
else if(stk[top-1]=='@')
push('&');
else
{
printf("Could not be PARSED");
error();
}
}
else
{
printf("Could not be PARSED");
23
Compiler Design Lab Manual MRITS

error();
}
break;
case'5':
if(input[ip]=='$')
{
pop();
pop();
pop();
pop();
push('S');
if(stk[top-1]=='0')
push('1');
else
{
printf("Could not be PARSED");
error();
}
}
else
{
printf("Could not be PARSED");
error();
}
break;
case'&':
if(input[ip]=='c'||'d'||'$')
{
pop();
pop();
pop();
pop();
push('C');
if(stk[top-1]=='0')
push('2');
else if(stk[top-1]=='2')
push('5');
else if(stk[top-1]=='@')
push('&');
else
{
printf("Could not be PARSED");
error();
}
}
else
{
printf("Could not be PARSED");
error();
}
break;

24
Compiler Design Lab Manual MRITS

}
}
}

OUTPUT:

Viva Questions:

1. Why bottom-up parsing is also called as shift reduce parsing?


2. What are the different types of bottom up parsers?
3. What is mean by LR (0) items?
4. Write the general form of LR(1) item?
5. What is YACC?
6. What is LALR parsing?
7. What is Shift reduced parser?
8. What are the operations of Parser?
9. What is the use of parsing table?
10. What is bottom up parsing?

25
Compiler Design Lab Manual MRITS

Additional Programs

1. Problem Statement: Implement RECURSIVE DESCENT PARSER


AIM: To Implement the RECURSIVE DESCENT PARSER for the given grammar /
language

ALGORITHM/ PROCEDURE:

Input : A string w$ , where w is a string of terminals


Output : w is accepted if it can be derived by the given grammar, else not accepted.

Step1: Start
Step2: declare w[10] as char and Z asan array
Step3: enter the string with $ at theend
Step4: if(A(w[z])thenincrementzandcheckfor(B(w[z]))and
ifsatisfiesincrementzandcheckfor
‘d’ifdispresentthenincrementandcheckfor(D(w[z]))
Step5: if step 4 is satisfied then the string isaccepted else string isnot
Step 6: For the productionScAdwrite the function S()
Step 7: For the production Aab/a write the function A()
Step 8: ifsteps7,8,9aresatisfiedaccordinglystringisaccepted else string is
notaccepted
Step 9: Stop

SOURCECODE:
#include<stdio.h>
char input[15];
int ip=0;
int S();
int A();
int S()
{
if(input[ip]=='c')
{
ip++;
if(A())
{
if(input[ip]=='d')
{
ip++;
return 1;
}
}
}
return 0;
}
int A()
{
26
Compiler Design Lab Manual MRITS

int isave=ip;
if(input[ip]=='a')
{
ip++;
if(input[ip]=='b')
{
ip++;
return 1;
}
}
ip=isave;
if(input[ip]=='a')
{
ip++;
return 1;
}
else
return 0;
}

int main()
{
int flag;
printf("Enter the input of the grammar S->cAd, A->ab/a ending with $");
scanf("%s",input);
flag=S();
if(flag==1 && input[ip]=='$')
{
printf("valid input");
}
else
printf("invalid input");
return 0;
}
INPUT:
Enter the input of the grammar S->cAd, A->ab/a ending with $
cad$
OUTPUT:
valid input

27
Compiler Design Lab Manual MRITS

2. AIM: Design a Lexical Analyzer.


Theory:

The lexical analyzer is the first phase of a compiler. Its main task is to read the input characters
and produce as output a sequence of tokens. Up on receiving a “get next token” command from the parser,
the lexical analyzer reads input characters until it can identify the next token. Token is a group of
characters having a collective meaning. Tokens are constants, identifier, keywords, operators, special
symbols.

Program:

#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<ctype.h>
void main()
{
int i,j; clrscr();
char keywords[10][10]={"BEGIN","IF","THEN","ELSE","END"};
charoperators[10][10]={"<","<=",">","=","!="};
char string[10];
int ch,l,found=0;
printf("/n enter any data of your choice");
scanf("%s",string);
l=strlen(string);
for(i=0;i<l;i++)
string[i]=toupper(string[i]);
for(i=0;i<5;i++)
{
if(strcmp(&keywords[i][0],string)==0)
{
found=1;
ch=1;
break;
}
28
Compiler Design Lab Manual MRITS

}
for(i=0;i<5;i++)
{
if(strcmp(&operators[i][0],string)==0)
{
found=1;
ch=2;
break;
}
}
switch(ch)
{
case 1: if(found==1)
printf("\n you have entered keyword"); break;
case 2: if(found==1)
printf("\n you have entered relational operator"); break;
default:printf("\n you have entered default choice");
}
getch();
}
Input:
enter any data of your choice else
Output:

you have entered keyword

VIVA QUESTIONS

1. What is lexical analyzer?


2. Which compiler is used for lexical analyzer? What is the output of Lexical analyzer?
3. What is LEX source Program?
4. What is token?
5. What is lexeme?
6. What is the difference between token and lexeme? Define phase and pass?
7. What is the difference between phase and pass?
8. What is the difference between compiler and interpreter?

29
Compiler Design Lab Manual MRITS

3. AIM: Write a LEX Program to check vowel or consonant

LEX SPECIFICATION PROGRAM / SOURCE CODE (vowel.l) :

// ********* LEX Tool program to check vowel or consonant *****************//

%{
#include<stdio.h>
#undef yywrap
#define yywrap() 1
%}

vowels[aeiouAEIOU]

letter[a-zA-Z]

%%

{vowels}* {printf("\n%s is a vowel!",yytext);}

{letter}* {printf("\n%s is a consonant!",yytext);}

%%

int main()

yylex();

INPUT 1:

OUTPUT:

a is a vowel!

INPUT 2:

OUTPUT:

zis a consonant!

30
Compiler Design Lab Manual MRITS

4. AIM: Write a LEX Program to check Operator.

LEX SPECIFICATION PROGRAM / SOURCE CODE (operator.l) :

// ********* LEX Tool program to check Operator *****************//

%{

#include<stdio.h>

%}

assg =

aop[+-/*%]

rop(>|<|">="|"<="|"=="|"!=")

bop[&^~|"|"]

lop(!|&&|"||")

shift ("<<"|">>")

inc("++")

dec("--")

other[a-zA-Z0-9_@#$.?;]

%%

{assg} {printf("\n%s is an Assignment operator!",yytext);}

{aop} {printf("\n%s is an Arithmetic operator !",yytext);}

{rop} {printf("\n%s is a Relational operator!",yytext);}

{bop} {printf("\n%s is a Bitwise operator!",yytext);}

{lop} {printf("\n%s is a Logical operator!",yytext);}

{shift} {printf("\n%s is a Shift operator!",yytext);}

{inc} {printf("\n%s is an Increment operator!",yytext);}

{dec} {printf("\n%s is a Decrement operator!",yytext);}

{other} {printf("\n%s is not an operator !",yytext);}

%%
31
Compiler Design Lab Manual MRITS

int main()

yylex();

}
INPUT 1:

==

OUTPUT:

= = is a relational operator

INPUT 2:

OUTPUT:

+is a arithmetic operator

32

You might also like