Final Lab Record
Final Lab Record
1
RA1811003010955
2
Register Number: RA1811003010955
EX NO:1
Conversion from
DATE: 27/01/2021
Regular Expression to NFA
ALGORITHM:
1
Register Number: RA1811003010955
PROGRAM :
class Type:
SYMBOL = 1
CONCAT = 2
UNION = 3
KLEENE = 4
class ExpressionTree:
def constructTree(regexp):
stack = []
for c in regexp:
if c.isalpha():
stack.append(ExpressionTree(Type.SYMBOL, c))
else:
if c == "+":
z = ExpressionTree(Type.UNION)
z.right = stack.pop()
z.left = stack.pop()
elif c == ".":
z = ExpressionTree(Type.CONCAT)
z.right = stack.pop()
z.left = stack.pop()
elif c == "*":
z = ExpressionTree(Type.KLEENE)
z.left = stack.pop()
stack.append(z)
return stack[0]
def inorder(et):
if et._type == Type.SYMBOL:
2
Register Number: RA1811003010955
print(et.value)
elif et._type == Type.CONCAT:
inorder(et.left)
print(".")
inorder(et.right)
elif et._type == Type.UNION:
inorder(et.left)
print("+")
inorder(et.right)
elif et._type == Type.KLEENE:
inorder(et.left)
print("*")
def postfix(regexp):
# adding dot "." between consecutive symbols
temp = []
for i in range(len(regexp)):
if i != 0\
and (regexp[i-1].isalpha() or regexp[i-1] == ")" or regexp[i-1] == "*")\
and (regexp[i].isalpha() or regexp[i] == "("):
temp.append(".")
temp.append(regexp[i])
regexp = temp
stack = []
output = ""
for c in regexp:
if c.isalpha():
output = output + c
continue
if c == ")":
while len(stack) != 0 and stack[-1] != "(":
output = output + stack.pop()
stack.pop()
elif c == "(":
stack.append(c)
elif c == "*":
output = output + c
elif len(stack) == 0 or stack[-1] == "(" or higherPrecedence(c, stack[-1]):
stack.append(c)
else:
while len(stack) != 0 and stack[-1] != "(" and not higherPrecedence(c, stack[-1]):
output = output + stack.pop()
stack.append(c)
3
Register Number: RA1811003010955
while len(stack) != 0:
output = output + stack.pop()
return output
class FiniteAutomataState:
def init (self):
self.next_state = {}
def evalRegex(et):
# returns equivalent E-NFA for given expression tree (representing a Regular
# Expression)
if et._type == Type.SYMBOL:
return evalRegexSymbol(et)
elif et._type == Type.CONCAT:
return evalRegexConcat(et)
elif et._type == Type.UNION:
return evalRegexUnion(et)
elif et._type == Type.KLEENE:
return evalRegexKleene(et)
def evalRegexSymbol(et):
start_state = FiniteAutomataState()
end_state = FiniteAutomataState()
start_state.next_state[et.value] = [end_state]
return start_state, end_state
def evalRegexConcat(et):
left_nfa = evalRegex(et.left)
right_nfa = evalRegex(et.right)
left_nfa[1].next_state['epsilon'] = [right_nfa[0]]
return left_nfa[0], right_nfa[1]
def evalRegexUnion(et):
start_state = FiniteAutomataState()
end_state = FiniteAutomataState()
up_nfa = evalRegex(et.left)
down_nfa = evalRegex(et.right)
def evalRegexKleene(et):
start_state = FiniteAutomataState()
end_state = FiniteAutomataState()
4
Register Number: RA1811003010955
sub_nfa = evalRegex(et.left)
states_done.append(state)
print(line_output)
for ns in state.next_state[symbol]:
printStateTransitions(ns, states_done, symbol_table)
def printTransitionTable(finite_automata):
print("State\t\tSymbol\t\t\tNext state")
printStateTransitions(finite_automata[0], [], {finite_automata[0]:0})
#inorder(et)
fa = evalRegex(et)
printTransitionTable(fa)
OUTPUT
5
Register Number: RA1811003010955
RESULT: Program to convert RE to NFA was written and executed successfully using the
given example.
6
Register Number: RA1811003010955
EX NO:2
Conversion from NFA to DFA
DATE: 03/02/2021
ALGORITHM:
Step 1: Initially Q’ = ɸ.
Step 3: For each state in Q’, find the possible set of states for each input symbol using the
transition function of NFA. If this set of states is not in Q’, add it to Q’.
Step 4: Final state of DFA will be all states with contain F (final states of NFA)
PROGRAM :
import pandas as pd
1
Register Number: RA1811003010955
nfa = {}
n = int(input("No. of states : ")) #Enter total no. of states
t = int(input("No. of transitions : ")) #Enter total no. of transitions/paths eg: a,b so input 2 for a,b,c
input 3
for i in range(n):
state = input("state name : ") #Enter state name eg: A, B, C, q1, q2 ..etc
nfa[state] = {} #Creating a nested dictionary
for j in range(t):
path = input("path : ") #Enter path eg : a or b in {a,b} 0 or 1 in {0,1}
print("Enter end state from state {} travelling through path {} : ".format(state,path))
reaching_state = [x for x in input().split()] #Enter all the end states that
nfa[state][path] = reaching_state #Assigning the end states to the paths in dictionary
print("\nNFA :- \n")
print(nfa) #Printing NFA
print("\nPrinting NFA table :- ")
nfa_table = pd.DataFrame(nfa)
print(nfa_table.transpose())
###################################################
###################################################
2
Register Number: RA1811003010955
print("\nDFA :- \n")
print(dfa) #Printing the DFA created
print("\nPrinting DFA table :- ")
dfa_table = pd.DataFrame(dfa)
print(dfa_table.transpose())
dfa_states_list = list(dfa.keys())
dfa_final_states = []
for x in dfa_states_list:
for i in x:
if i in nfa_final_state:
dfa_final_states.append(x)
break
print("\nFinal states of the DFA are : ",dfa_final_states) #Printing Final states of DFA
OUTPUT
3
Register Number: RA1811003010955
RESULT: Program to convert NFA to DFA was written and executed successfully using the
given example.
4
Register Number: RA1811003010955
EX NO:3
Implementation of Lexical Analyzer
DATE: 10/02/2021
AIM : To implement a lexical analyzer based on the given problem. (Printing of lesser of 2
number)
ALGORITHM:
1. Tokenization i.e. Dividing the program into valid tokens.
3. Remove comments.
4. It also provides help in generating error messages by providing row numbers and column
numbers.
PROGRAM :
code.c
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
return flag;
}
int main(){
char ch, buffer[15], operators[] = "+-*/%=";
FILE *fp;
int i,j=0;
fp = fopen("c.txt","r");
if(fp == NULL){
printf("error while opening the file\n");
1
Register Number: RA1811003010955
exit(0);
}
if(isalnum(ch)){
buffer[j++] = ch;
}
else if((ch == ' ' || ch == '\n') && (j != 0)){
buffer[j] = '\0';
j = 0;
if(isKeyword(buffer) == 1)
printf("%s is keyword\n", buffer);
else
printf("%s is indentifier\n", buffer);
}
}
fclose(fp);
return 0;
}
c.txt:
void main ( ){
int x;
scanf("%d",&x);
if(x%2)==0{
printf("even number");
}
else
printf("odd number");
}
OUTPUT
2
Register Number: RA1811003010955
3
Register Number: RA1811003010955
EX NO: 04 -a ELIMINATION OF LEFT RECURSION
DATE: 16-02-2021
ALGORITHM:
1. Start the program.
2. Initialize the arrays for taking input from the user.
3. Prompt the user to input the no. of non-terminals having left
recursion and no. of productions for these non-terminals.
4. Prompt the user to input the right production for non-
terminals.
5. Eliminate left recursion using the following rules:-
A-
>Aα1| Aα2
|.....
|Aαm A-
>β1| β2| . . .
. .| βn
Then replace it by
A’-> βi A’ i=1,2,3,…..m
A’-> αj A’ j=1,2,3,…..n
A’-> Ɛ
6. After eliminating the left recursion by applying these rules,
display the productions without left recursion.
7. Stop.
Manual Calculation:
PROGRAM :
1
Register Number: RA1811003010955
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
int n;
cout<<"\nEnter number of non terminals: ";
cin>>n;
cout<<"\nEnter non terminals one by one: ";
int i;
vector<string> nonter(n);
vector<int> leftrecr(n,0);
for(i=0;i<n;++i) {
cout<<"\nNon terminal "<<i+1<<" : ";
cin>>nonter[i];
}
vector<vector<string> > prod;
cout<<"\nEnter '^' for null";
for(i=0;i<n;++i) {
cout<<"\nNumber of "<<nonter[i]<<" productions: ";
int k;
cin>>k;
int j;
cout<<"\nOne by one enter all "<<nonter[i]<<"
productions";
vector<string> temp(k);
for(j=0;j<k;++j) {
cout<<"\nRHS of production "<<j+1<<": ";
string abc;
cin>>abc;
temp[j]=abc;
if(nonter[i].length()<=abc.length()&&nonter[i].compare(abc
.substr(0,nonter[i].length()))==0)
leftrecr[i]=1;
}
prod.push_back(temp);
}
for(i=0;i<n;++i) {
cout<<leftrecr[i];
2
Register Number: RA1811003010955
}
for(i=0;i<n;++i) {
if(leftrecr[i]==0)
continue;
int j;
nonter.push_back(nonter[i]+"'");
vector<string> temp;
for(j=0;j<prod[i].size();++j) {
if(nonter[i].length()<=prod[i][j].length()&&nonter[i].compare
(prod[i][j].substr(0,nonter[i].length()))==0) {
string
abc=prod[i][j].substr(nonter[i].length(),prod[i][j].length()-
nonter[i].length())+nonter[i]+"'";
temp.push_back(abc);
prod[i].erase(prod[i].begin()+j);
--j;
}
else {
prod[i][j]+=nonter[i]+"'";
}
}
temp.push_back("^");
prod.push_back(temp);
}
cout<<"\n\n";
cout<<"\nNew set of non-terminals: ";
for(i=0;i<nonter.size();++i)
cout<<nonter[i]<<" ";
cout<<"\n\nNew set of productions: ";
for(i=0;i<nonter.size();++i) {
int j;
for(j=0;j<prod[i].size();++j) {
cout<<"\n"<<nonter[i]<<" -> "<<prod[i][j];
}
}
return 0;
}
OUTPUT
3
Register Number: RA1811003010955
4
Register Number: RA1811003010955
EX NO: 04-b ELIMINATION OF LEFT FACTORING
DATE:16-02-2021
Manual Calculation:
PROGRAM :
#include<stdio.h>
#include<string.h>
int main()
5
Register Number: RA1811003010955
char
gram[20],part1[20],part2[20],modifiedGram[20],newGram[20],
tempGram[20];
int i,j=0,k=0,l=0,pos;
fgets(gram,20,stdin);
for(i=0;gram[i]!='|';i++,j++)
part1[j]=gram[i];
part1[j]='\0';
for(j=++i,i=0;gram[j]!='\0';j++,i++)
part2[i]=gram[j];
part2[i]='\0';
for(i=0;i<strlen(part1)||i<strlen(part2);i++)
if(part1[i]==part2[i])
modifiedGram[k]=part1[i];
k++;
pos=i+1;
for(i=pos,j=0;part1[i]!='\0';i++,j++){
newGram[j]=part1[i];
newGram[j++]='|';
6
Register Number: RA1811003010955
for(i=pos;part2[i]!='\0';i++,j++){
newGram[j]=part2[i];
modifiedGram[k]='X';
modifiedGram[++k]='\0';
newGram[j]='\0';
printf("\n S->%s",modifiedGram);
printf("\n x->%s\n",newGram);
OUTPUT
7
Register Number: RA1811003010955
EX NO: 05 FIRST AND FOLLOW
DATE:23-02-2021
8
Register Number: RA1811003010955
PROGRAM :
#include <bits/stdc++.h>
#define max 20
int eps[10],c=0;
int n;
9
Register Number: RA1811003010955
if (nt[n] == ch)
break;
if (nt[n] == '\0')
return 1;
return n;
int IsCap(char c)
int i, flag = 0;
if (arr[i] == c)
flag = 1;
break;
if (flag != 1)
arr[strlen(arr)] = c;
10
Register Number: RA1811003010955
flag = 0;
if (s2[i] == s1[j])
flag = 1;
break;
s1[strlen(s1)] = s2[i];
break;
int i;
prod[c][0] = s[0];
11
Register Number: RA1811003010955
if (!IsCap(s[i]))
add(ter, s[i]);
prod[c][i - 2] = s[i];
prod[c][i - 2] = '\0';
add(nt, s[0]);
c++;
void findfirst()
int i, j, n, k, e, n1;
n = findpos(prod[j][0]);
if (prod[j][1] == (char)238)
eps[n] = 1;
else
12
Register Number: RA1811003010955
if (!IsCap(prod[j][k]))
e = 0;
add(first[n], prod[j][k]);
else
n1 = findpos(prod[j][k]);
addarr(first[n], first[n1]);
if (eps[n1] == 0)
e = 0;
if (e == 1)
eps[n] = 1;
void findfollow()
int i, j, k, n, e, n1;
n = findpos(prod[0][0]);
add(follow[n], '$');
13
Register Number: RA1811003010955
if (IsCap(prod[j][k]))
n = findpos(prod[j][k]);
n1 = findpos(prod[j][0]);
addarr(follow[n], follow[n1]);
n1 = findpos(prod[j][k + 1]);
addarr(follow[n], first[n1]);
if (eps[n1] == 1)
n1 = findpos(prod[j][0]);
addarr(follow[n], follow[n1]);
14
Register Number: RA1811003010955
int main()
char s[max], i;
cout << "\nEnter the productions (type 'end' at the last of the
production)\n";
cin >> s;
addprod(s);
cin >> s;
findfirst();
findfollow();
cout << "\nFIRST[" << nt[i] << "]: " << first[i];
if (eps[i] == 1)
15
Register Number: RA1811003010955
else
cout << "FOLLOW[" << nt[i] << "]: " << follow[i];
return 0;
OUTPUT
RESULT:
The FIRST and FOLLOW sets of the non-terminals of
a grammar were found successfully using C++.
16
Register Number: RA1811003010955
EX NO: 06 PREDICTIVE PARSER
DATE:02-03-2021
17
Register Number: RA1811003010955
PROGRAM :
#include<stdio.h>
#include<ctype.h>
#include<string.h>
int count,n=0;
char calc_first[10][100];
char calc_follow[10][100];
int m=0;
char production[10][10], first[10];
char f[10];
int k;
char ck;
int e;
18
Register Number: RA1811003010955
char c,ch;
printf("How many productions ? :");
scanf("%d",&count);
printf("\nEnter %d productions in form A=B where A
and B are grammar symbols :\n\n",count);
for(i=0;i<count;i++)
{
scanf("%s%c",production[i],&ch);
}
int kay;
char done[count];
int ptr = -1;
for(k=0;k<count;k++){
for(kay=0;kay<100;kay++){
calc_first[k][kay] = '!';
}
}
int point1 = 0,point2,xxx;
for(k=0;k<count;k++)
{
c=production[k][0];
point2 = 0;
xxx = 0;
for(kay = 0; kay <= ptr; kay++)
if(c == done[kay])
xxx = 1;
if (xxx == 1)
continue;
findfirst(c,0,0);
ptr+=1;
done[ptr] = c;
printf("\n First(%c)= { ",c);
calc_first[point1][point2++] = c;
for(i=0+jm;i<n;i++){
int lark = 0,chk = 0;
for(lark=0;lark<point2;lark++){
if (first[i] ==
calc_first[point1][lark]){
chk = 1;
break;
}
}
19
Register Number: RA1811003010955
if(chk == 0){
printf("%c, ",first[i]);
calc_first[point1][point2++]
= first[i];
}
}
printf("}\n");
jm=n;
point1++;
}
printf("\n");
printf("-----------------------------------------------\n\n");
char donee[count];
ptr = -1;
for(k=0;k<count;k++){
for(kay=0;kay<100;kay++){
calc_follow[k][kay] = '!';
}
}
point1 = 0;
int land = 0;
for(e=0;e<count;e++)
{
ck=production[e][0];
point2 = 0;
xxx = 0;
for(kay = 0; kay <= ptr; kay++)
if(ck == donee[kay])
xxx = 1;
if (xxx == 1)
continue;
land += 1;
follow(ck);
ptr+=1;
donee[ptr] = ck;
printf(" Follow(%c) = { ",ck);
calc_follow[point1][point2++] = ck;
for(i=0+km;i<m;i++){
int lark = 0,chk = 0;
for(lark=0;lark<point2;lark++){
if (f[i] ==
calc_follow[point1][lark]){
20
Register Number: RA1811003010955
chk = 1;
break;
}
}
if(chk == 0){
printf("%c, ",f[i]);
calc_follow[point1][point2++] = f[i];
}
}
printf(" }\n\n");
km=m;
point1++;
}
char ter[10];
for(k=0;k<10;k++){
ter[k] = '!';
}
int ap,vp,sid = 0;
for(k=0;k<count;k++){
for(kay=0;kay<count;kay++){
if(!isupper(production[k][kay]) &&
production[k][kay]!= '#' && production[k][kay] != '='
&& production[k][kay] != '\0'){
vp = 0;
for(ap = 0;ap < sid; ap++){
if(production[k][kay] == ter[ap]){
vp = 1;
break;
}
}
if(vp == 0){
ter[sid] = production[k][kay];
sid ++;
}
}
}
}
ter[sid] = '$';
sid++;
printf("\n\t\t\t\t\t\t\t The LL(1) Parsing Table for the
above grammer :-");
21
Register Number: RA1811003010955
printf("\n\t\t\t\t\t\t\t^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
^^^^^^^^^^^^^^^^^^^^^\n");
printf("\n\t\t\t=================================
============================================
========================================\n");
printf("\t\t\t\t|\t");
for(ap = 0;ap < sid; ap++){
printf("%c\t\t",ter[ap]);
}
printf("\n\t\t\t=================================
============================================
========================================\n");
char first_prod[count][sid];
for(ap=0;ap<count;ap++){
int destiny = 0;
k = 2;
int ct = 0;
char tem[100];
while(production[ap][k] != '\0'){
if(!isupper(production[ap][k])){
tem[ct++] = production[ap][k];
tem[ct++] = '_';
tem[ct++] = '\0';
k++;
break;
}
else{
int zap=0;
int tuna = 0;
for(zap=0;zap<count;zap++){
if(calc_first[zap][0] ==
production[ap][k]){
for(tuna=1;tuna<100;tuna++){
if(calc_first[zap][tuna]
!= '!'){
tem[ct++] =
calc_first[zap][tuna];
}
else
break;
}
22
Register Number: RA1811003010955
break;
}
}
tem[ct++] = '_';
}
k++;
}
int zap = 0,tuna;
for(tuna = 0;tuna<ct;tuna++){
if(tem[tuna] == '#'){
zap = 1;
}
else if(tem[tuna] == '_'){
if(zap == 1){
zap = 0;
}
else
break;
}
else{
first_prod[ap][destiny++] = tem[tuna];
}
}
}
char table[land][sid+1];
ptr = -1;
for(ap = 0; ap < land ; ap++){
for(kay = 0; kay < (sid + 1) ; kay++){
table[ap][kay] = '!';
}
}
for(ap = 0; ap < count ; ap++){
ck = production[ap][0];
xxx = 0;
for(kay = 0; kay <= ptr; kay++)
if(ck == table[kay][0])
xxx = 1;
if (xxx == 1)
continue;
else{
ptr = ptr + 1;
table[ptr][0] = ck;
23
Register Number: RA1811003010955
}
}
for(ap = 0; ap < count ; ap++){
int tuna = 0;
while(first_prod[ap][tuna] != '\0'){
int to,ni=0;
for(to=0;to<sid;to++){
if(first_prod[ap][tuna] == ter[to]){
ni = 1;
}
}
if(ni == 1){
char xz = production[ap][0];
int cz=0;
while(table[cz][0] != xz){
cz = cz + 1;
}
int vz=0;
while(ter[vz] != first_prod[ap][tuna]){
vz = vz + 1;
}
table[cz][vz+1] = (char)(ap + 65);
}
tuna++;
}
}
for(k=0;k<sid;k++){
for(kay=0;kay<100;kay++){
if(calc_first[k][kay] == '!'){
break;
}
else if(calc_first[k][kay] == '#'){
int fz = 1;
while(calc_follow[k][fz] != '!'){
char xz = production[k][0];
int cz=0;
while(table[cz][0] != xz){
cz = cz + 1;
}
int vz=0;
while(ter[vz] != calc_follow[k][fz]){
vz = vz + 1;
24
Register Number: RA1811003010955
}
table[k][vz+1] = '#';
fz++;
}
break;
}
}
}
for(ap = 0; ap < land ; ap++){
printf("\t\t\t %c\t|\t",table[ap][0]);
for(kay = 1; kay < (sid + 1) ; kay++){
if(table[ap][kay] == '!')
printf("\t\t");
else if(table[ap][kay] == '#')
printf("%c=#\t\t",table[ap][0]);
else{
int mum = (int)(table[ap][kay]);
mum -= 65;
printf("%s\t\t",production[mum]);
}
}
printf("\n");
printf("\t\t\t-------------------------------------------------------------
--------------------------------------------------------");
printf("\n");
}
int j;
printf("\n\nPlease enter the desired INPUT STRING =
");
char input[100];
scanf("%s%c",input,&ch);
printf("\n\t\t\t\t\t===============================
============================================
\n");
printf("\t\t\t\t\t\tStack\t\t\tInput\t\t\tAction");
printf("\n\t\t\t\t\t===============================
============================================
\n");
int i_ptr = 0,s_ptr = 1;
char stack[100];
stack[0] = '$';
stack[1] = table[0][0];
25
Register Number: RA1811003010955
while(s_ptr != -1){
printf("\t\t\t\t\t\t");
int vamp = 0;
for(vamp=0;vamp<=s_ptr;vamp++){
printf("%c",stack[vamp]);
}
printf("\t\t\t");
vamp = i_ptr;
while(input[vamp] != '\0'){
printf("%c",input[vamp]);
vamp++;
}
printf("\t\t\t");
char her = input[i_ptr];
char him = stack[s_ptr];
s_ptr--;
if(!isupper(him)){
if(her == him){
i_ptr++;
printf("POP ACTION\n");
}
else{
printf("\nString Not Accepted by LL(1)
Parser !!\n");
exit(0);
}
}
else{
for(i=0;i<sid;i++){
if(ter[i] == her)
break;
}
char produ[100];
for(j=0;j<land;j++){
if(him == table[j][0]){
if (table[j][i+1] == '#'){
printf("%c=#\n",table[j][0]);
produ[0] = '#';
produ[1] = '\0';
}
else if(table[j][i+1] != '!'){
int mum = (int)(table[j][i+1]);
26
Register Number: RA1811003010955
mum -= 65;
strcpy(produ,production[mum]);
printf("%s\n",produ);
}
else{
printf("\nString Not
Accepted by LL(1) Parser !!\n");
exit(0);
// break;
}
}
}
int le = strlen(produ);
le = le - 1;
if(le == 0){
continue;
}
for(j=le;j>=2;j--){
s_ptr++;
stack[s_ptr] = produ[j];
}
}
}
printf("\n\t\t\t=================================
============================================
==========================================\n
");
if (input[i_ptr] == '\0'){
printf("\t\t\t\t\t\t\t\tYOUR STRING HAS BEEN
ACCEPTED !!\n");
}
else
printf("\n\t\t\t\t\t\t\t\tYOUR STRING HAS BEEN
REJECTED !!\n");
printf("\t\t\t===================================
============================================
========================================\n");
}
void follow(char c)
{
27
Register Number: RA1811003010955
int i ,j;
if(production[0][0]==c){
f[m++]='$';
}
for(i=0;i<10;i++)
{
for(j=2;j<10;j++)
{
if(production[i][j]==c)
{
if(production[i][j+1]!='\0'){
followfirst(production[i][j+1],i,(j+2));
}
if(production[i][j+1]=='\0'&&c!=production[i][0]){
follow(production[i][0]);
}
}
}
}
}
28
Register Number: RA1811003010955
else
first[n++]='#';
}
else if(!isupper(production[j][2])){
first[n++]=production[j][2];
}
else {
findfirst(production[j][2], j, 3);
}
}
}
}
followfirst(production[c1][c2],c1,c2+1);
}
}
j++;
}
}
29
Register Number: RA1811003010955
}
OUTPUT
30
Register Number: RA1811003010955
EX NO: 07 SHIFT REDUCE PARSER
DATE:09-03-2021
Reduce y: (y is a
PRODUCTION number)
Assume that the production is of the
form A→ß Pop 2 * |ß|
symbols of the stack.
Manual Calculation:
31
Register Number: RA1811003010955
PROGRAM :
#include<stdio.h>
#include<string.h>
int k=0,z=0,i=0,j=0,c=0;
char a[16],ac[20],stk[15],act[10];
void check();
int main()
gets(a);
c=strlen(a);
strcpy(act,"SHIFT->");
32
Register Number: RA1811003010955
stk[i]=a[j];
stk[i+1]=a[j+1];
stk[i+2]='\0';
a[j]=' ';
a[j+1]=' ';
printf("\n$%s\t%s$\t%sid",stk,a,act);
check();
else
stk[i]=a[j];
stk[i+1]='\0';
a[j]=' ';
printf("\n$%s\t%s$\t%ssymbols",stk,a,act);
check();
33
Register Number: RA1811003010955
void check()
strcpy(ac,"REDUCE TO E");
stk[z]='E';
stk[z+1]='\0';
printf("\n$%s\t%s$\t%s",stk,a,ac);
j++;
stk[z]='E';
stk[z+1]='\0';
stk[z+2]='\0';
printf("\n$%s\t%s$\t%s",stk,a,ac);
i=i-2;
stk[z]='E';
34
Register Number: RA1811003010955
stk[z+1]='\0';
stk[z+1]='\0';
printf("\n$%s\t%s$\t%s",stk,a,ac);
i=i-2;
stk[z]='E';
stk[z+1]='\0';
stk[z+1]='\0';
printf("\n$%s\t%s$\t%s",stk,a,ac);
i=i-2;
OUTPUT
35
Register Number: RA1811003010955
36
Register Number: RA1811003010955
EX NO: 08 LR(0) PARSER
DATE:16-03-2021
Manual Calculation:
37
Register Number: RA1811003010955
PROGRAM :
def closure(I,nonT):
J=I
for item in J :
#print(item)
index = item[1].index('.')
38
Register Number: RA1811003010955
#print('item : ',item[1][index+1])
J.append([item[1][index+1],str('.')+str(production)])
#print([item[1][index+1],str('.')+str(production)])
return J
state = []
I = []
def setOfItems(start,nonTer,ter):
I.append(closure([['start','.'+start+'$']],nonTer))
#print(I)
ter += list(nonTer.keys())
for conI in I:
39
Register Number: RA1811003010955
if(grammar is '$'):
continue
#print("grammar : ",grammar)
goto = False
goto1 = False
shift = False
shift1 = False
reduce = False
close = []
#print("item : ",item)
if(item[1].index('.')<(len(item[1])-1) and
item[1][item[1].index('.')+1] is grammar):
close.append([item[0],item[1][:item[1].index('.')]+grammar+'.'+
item[1][item[1].index('.')+2:]])
#else:
# print(item)
#print("close : ",close)
l = closure(close,nonTer)
if(len(l) == 0):
continue
#print("closure : ", l)
if(grammar in nonTer.keys()):
goto1 = True
40
Register Number: RA1811003010955
else:
shift1 = True
if(goto1):
state.append(['g',I.index(conI)+1,len(I)+1,grammar])
goto = True
elif(shift1):
shift = True
state.append(['s',I.index(conI)+1,len(I)+1,grammar])
I.append(l)
else:
if(goto1):
goto = True
state.append(['g',I.index(conI)+1,I.index(l)+1,grammar])
elif(shift1):
shift = True
state.append(['s',I.index(conI)+1,I.index(l)+1,grammar])
# -----------------------------------------------------------------
41
Register Number: RA1811003010955
reduce = []
accept = -1
def toReduce(rule,accept,start):
s = ['start',start+'.$']
for parState in I:
#print(s,parState)
if(s in parState):
#print("here;")
accept = I.index(parState)
reduce[I.index(parState)].append(rule.index(item))
return accept
# ------------------------------------------------------------------
42
Register Number: RA1811003010955
symbolMap = dict()
parseTable = []
def createParseTable(ter):
for i in state:
parseTable[i[1]-1][symbolMap[i[3]]] = i[0]+str(i[2]-1)
parseTable[accept][symbolMap['$']] = 'a'
for i in reduce:
if(len(i)>0):
for j in ter:
parseTable[reduce.index(i)][symbolMap[j]] =
'r'+str(i[0])
class Stack:
def __init__(self):
self.__storage = []
def isEmpty(self):
43
Register Number: RA1811003010955
return len(self.__storage) == 0
def push(self,p):
self.__storage.append(p)
def pop(self):
return self.__storage.pop()
def top(self):
return self.__storage[len(self.__storage) - 1]
def length(self):
return len(self.__storage)
def __str__(self):
"""
elements.
"""
44
Register Number: RA1811003010955
#: stack instances.
def parseString(rule,string):
index = 0
flag = False
st = Stack()
st.push('0')
c = parseTable[int(st.top())][symbolMap[string[index]]][0]
if(c is 'a'):
flag = True
break
pt =
parseTable[int(st.top())][symbolMap[string[index]]][1:]
pt = int(pt)
if( c is 'r'):
l = len(rule[pt][1])
l *= 2
45
Register Number: RA1811003010955
break
else:
for i in range(l):
st.pop()
top = int(st.top())
st.push(rule[pt][0])
st.push(parseTable[top][symbolMap[st.top()]][1:])
else:
st.push(string[index])
st.push(str(pt))
index+=1
return flag
# ------------------------------------------------------------------
terminals = []
nonTerminals = dict()
46
Register Number: RA1811003010955
for i in range(n):
ch = input("NonTerminals : ").strip()
nonTerminals[ch] = rules
terminals+=['$']
print("Productions : ")
for i in nonTerminals.keys():
print(i,"-->",end=' ')
for j in nonTerminals[i]:
print()
setOfItems(S,nonTerminals,terminals)
print(count+1 , i)
47
Register Number: RA1811003010955
print(count+1, i)
rule = []
accept = -1
for i in nonTerminals.keys():
for j in nonTerminals[i]:
rule.append([i,j+str('.')])
print('rule :')
for i in rule:
print(i)
accept = toReduce(rule,accept,S)
print("reduce")
print(count+1,i)
print("accept : ",accept+1)
48
Register Number: RA1811003010955
symbols = []
symbols += terminals
symbolMap[i] = count
print(symbols)
for i in nonTerminals.keys():
terminals.remove(i)
createParseTable(terminals)
# ---Parse Table-----
print('Parse Table')
print(" \t\t",end='')
for i in symbols:
print(i,end= '\t')
print()
print(count,end='\t\t')
for i in j:
49
Register Number: RA1811003010955
print(i,end='\t')
print()
OUTPUT
50
Register Number: RA1811003010955
EX NO: 09 LEADING AND TRAILING
DATE:23-02-2021
ALGORITHM:
1. For Leading, check for the first non-terminal.
2. If found, print it.
3. Look for next production for the same non-terminal.
4. If not found, recursively call the procedure for the single
non-terminal present before the comma or End Of Production
String.
5. Include it's results in the result of this non-terminal.
6. For trailing, we compute same as leading but we start from
the end of the production to the beginning.
7. Stop
Manual Calculation:
PROGRAM :
#include<iostream>
#include<string.h>
#include<conio.h>
51
Register Number: RA1811003010955
int nt,t,top=0;
char s[50],NT[10],T[10],st[50],l[10][10],tr[50][50];
int searchnt(char a)
int count=-1,i;
for(i=0;i<nt;i++)
if(NT[i]==a)
return i;
return count;
int searchter(char a)
int count=-1,i;
for(i=0;i<t;i++)
if(T[i]==a)
return i;
return count;
void push(char a)
52
Register Number: RA1811003010955
s[top]=a;
top++;
char pop()
top--;
return s[top];
if(l[a][b]=='f')
l[a][b]='t';
push(T[b]);
push(NT[a]);
if(tr[a][b]=='f')
tr[a][b]='t';
53
Register Number: RA1811003010955
push(T[b]);
push(NT[a]);
int main()
int i,s,k,j,n;
char pr[30][30],b,c;
cin>>n;
for(i=0;i<n;i++)
cin>>pr[i];
nt=0;
t=0;
for(i=0;i<n;i++)
if((searchnt(pr[i][0]))==-1)
NT[nt++]=pr[i][0];
for(i=0;i<n;i++)
for(j=3;j<strlen(pr[i]);j++)
54
Register Number: RA1811003010955
if(searchnt(pr[i][j])==-1)
if(searchter(pr[i][j])==-1)
T[t++]=pr[i][j];
for(i=0;i<nt;i++)
for(j=0;j<t;j++)
l[i][j]='f';
for(i=0;i<nt;i++)
for(j=0;j<t;j++)
tr[i][j]='f';
for(i=0;i<nt;i++)
for(j=0;j<n;j++)
if(NT[(searchnt(pr[j][0]))]==NT[i])
55
Register Number: RA1811003010955
if(searchter(pr[j][3])!=-1)
installl(searchnt(pr[j][0]),searchter(pr[j][3]));
else
for(k=3;k<strlen(pr[j]);k++)
if(searchnt(pr[j][k])==-1)
installl(searchnt(pr[j][0]),searchter(pr[j][k]));
break;
while(top!=0)
b=pop();
c=pop();
for(s=0;s<n;s++)
if(pr[s][3]==b)
56
Register Number: RA1811003010955
installl(searchnt(pr[s][0]),searchter(c));
for(i=0;i<nt;i++)
cout<<"Leading["<<NT[i]<<"]"<<":"<<"\t{"<<" ";
for(j=0;j<t;j++)
if(l[i][j]=='t')
cout<<T[j]<<" ";
cout<<"}\n";
top=0;
for(i=0;i<nt;i++)
for(j=0;j<n;j++)
if(NT[searchnt(pr[j][0])]==NT[i])
if(searchter(pr[j][strlen(pr[j])-1])!=-1)
installt(searchnt(pr[j][0]),searchter(pr[j][strlen(pr[j])-1]));
57
Register Number: RA1811003010955
else
for(k=(strlen(pr[j])-1);k>=3;k--)
if(searchnt(pr[j][k])==-1)
installt(searchnt(pr[j][0]),searchter(pr[j][k]));
break;
while(top!=0)
b=pop();
c=pop();
for(s=0;s<n;s++)
if(pr[s][3]==b)
installt(searchnt(pr[s][0]),searchter(c));
58
Register Number: RA1811003010955
for(i=0;i<nt;i++)
cout<<"Trailing["<<NT[i]<<"]"<<":"<<"\t{"<<" ";
for(j=0;j<t;j++)
if(tr[i][j]=='t')
cout<<T[j]<<" ";
cout<<"}\n";
getch();
OUTPUT
59
EX NO:08-04-2021
DATE: 10 INTERMEDIATE CODE GENERATER
if(pr[s][3]==b)
installt(searchnt(pr[s][0]),searchter(c));
for(i=0;i<nt;i++)
cout<<"Trailing["<<NT[i]<<"]"<<":"<<"\t{"<<" ";
for(j=0;j<t;j++)
if(tr[i][j]=='t')
cout<<T[j]<<" ";
cout<<"}\n";
getch();
OUTPUT
RESULT:The C++ implementation to find the LEAD and TRAIL sets of variables of a CFG
was compiled, executed and verified successfully.
AIM: To implement a program to convert infix expression to postfix, prefix.
ALGORITHM:
Postfix:
1. Scan the infix expression from left to right.
2. If the scanned character is an operand, output it.
3. Else,
1 If the precedence of the scanned operator is greater than the precedence of the
operator in the stack(or the stack is empty or the stack contains a ‘(‘ ), push it.
2 Else, Pop all the operators from the stack which are greater than or equal to in
precedence than that of the scanned operator. After doing that Push the scanned
operator to the stack. (If you encounter parenthesis while popping then stop there and
push the scanned operator in the stack.)
4. If the scanned character is an ‘(‘, push it to the stack.
5. If the scanned character is an ‘)’, pop the stack and output it until a ‘(‘ is encountered,
and discard both the parenthesis.
6. Repeat steps 2-6 until infix expression is scanned.
7. Print the output
8. Pop and output from the stack until it is not empty.
Postfix:
1. Scan the infix expression from right to left.
2. If the scanned character is an operand, output it.
3. Else,
1 If the precedence of the scanned operator is greater than the precedence of the
operator in the stack(or the stack is empty or the stack contains a ‘(‘ ), push it.
2 Else, Pop all the operators from the stack which are greater than or equal to in
precedence than that of the scanned operator. After doing that Push the scanned
operator to the stack. (If you encounter parenthesis while popping then stop there and
push the scanned operator in the stack.)
4. If the scanned character is an ‘)‘, push it to the stack.
5. If the scanned character is an ‘(’, pop the stack and output it until a ‘)‘ is encountered,
and discard both the parenthesis.
6. Repeat steps 2-6 until infix expression is scanned.
7. Reverse the infix expression ,Print the output
8. Pop and output from the stack until it is not empty.
Manual Calculation:
PROGRAM :
class infix_to_postfix:
precedence={'^':5,'*':4,'/':4,'+':3,'-':3,'(':2,')':1}
def __init__(self):
self.items=[]
self.size=-1
def push(self,value):
self.items.append(value)
self.size+=1
def pop(self):
if self.isempty():
return 0
else:
self.size-=1
return self.items.pop()
def isempty(self):
if(self.size==-1):
return True
else:
return False
def seek(self):
if self.isempty():
return false
else:
return self.items[self.size]
def isOperand(self,i):
if i.isalpha() or i in '1234567890':
return True
else:
return False
def infixtopostfix (self,expr):
postfix=""
for i in expr:
if(len(expr)%2==0):
print("Incorrect infix expr")
return False
elif(self.isOperand(i)):
postfix +=i
elif(i in '+-*/^'):
while(len(self.items)and self.precedence[i]<=self.precedence[self.seek()]):
postfix+=self.pop()
self.push(i)
elifi is '(':
self.push(i)
elifi is ')':
o=self.pop()
while o!='(':
postfix +=o
o=self.pop()
print(postfix)
#end of for
while len(self.items):
if(self.seek()=='('):
self.pop()
else:
postfix+=self.pop()
return postfix
s=infix_to_postfix()
expr=input('enter the expression ')
result=s.infixtopostfix(expr)
if (result!=False):
print("the postfix expr of :",expr,"is",result)
class infix_to_prefix:
precedence={'^':5,'*':4,'/':4,'+':3,'-':3,'(':2,')':1}
def __init__(self):
self.items=[]
self.size=-1
def push(self,value):
self.items.append(value)
self.size+=1
def pop(self):
if self.isempty():
return 0
else:
self.size-=1
return self.items.pop()
def isempty(self):
if(self.size==-1):
return True
else:
return False
def seek(self):
if self.isempty():
return False
else:
return self.items[self.size]
def is0perand(self,i):
if i.isalpha() or i in '1234567890':
return True
else:
return False
def reverse(self,expr):
rev=""
for i in expr:
if i is '(':
i=')'
elifi is ')':
i='('
rev=i+rev
return rev
def infixtoprefix (self,expr):
prefix=""
print('\nprefix expression after every iteration is:')
for i in expr:
EX NO: 11 INTERMEDIATE CODE GENERATER
Quadruple, Triple, Indirect triple
if(len(expr)%2==0):
print("Incorrect infix expr")
return False
elif(self.is0perand(i)):
prefix +=i
elif(i in '+-*/^'):
while(len(self.items)and self.precedence[i] <self.precedence[self.seek()]):
prefix+=self.pop()
self.push(i)
elifi is '(':
self.push(i)
elifi is ')':
o=self.pop()
while o!='(':
prefix +=o
o=self.pop()
print(prefix)
#end of for
while len(self.items):
if(self.seek()=='('):
self.pop()
else:
prefix+=self.pop()
print(prefix)
return prefix
V=infix_to_prefix()
rev=""
rev=V.reverse(expr)
#print(rev)
result=V.infixtoprefix(rev)
if (result!=False):
prefix=V.reverse(result)
print("the prefix expr of :",expr,"is",prefix)
OUTPUT
PREFIX NOTATION:+*EE/EE
POSTFIX NOTATION: EE*EE/+
RESULT:The python implementation to convert infix to postfix, prefix has done successfully.
DATE: 16-04-2021
AIM: To implement a program to convert infix expression to quadruple, triple, indirect triple.
ALGORITHM:
1. Start the program
2. Convert the expression to three address code
3. Using three address code construct quadruple
4. Using quadruple construct triple
5. Construct indirect triple
6. Print output
7. End program
Manual Calculation:
PROGRAM :
# leftover
while op_stack:
op = op_stack.pop()
a = exp_stack.pop()
b = exp_stack.pop()
exp_stack.append( op+b+a )
print(f'PREFIX: {exp_stack[-1]}')
return exp_stack[-1]
def generate3AC(pos):
print("### THREE ADDRESS CODE GENERATION ###")
exp_stack = []
t=1
for i in pos:
if i not in OPERATORS:
exp_stack.append(i)
else:
print(f't{t} := {exp_stack[-2]} {i} {exp_stack[-1]}')
exp_stack=exp_stack[:-2]
exp_stack.append(f't{t}')
t+=1
x = x+1
if stack != []:
op2 = stack.pop()
op1 = stack.pop()
print("{0:^4s} | {1:^4s} | {2:^4s}|{3:4s}".format("+",op1,op2," t(%s)" %x))
stack.append("t(%s)" %x)
x = x+1
elifi == '=':
op2 = stack.pop()
op1 = stack.pop()
print("{0:^4s} | {1:^4s} | {2:^4s}|{3:4s}".format(i,op2,"(-)",op1))
else:
op1 = stack.pop()
op2 = stack.pop()
print("{0:^4s} | {1:^4s} | {2:^4s}|{3:4s}".format(i,op2,op1," t(%s)" %x))
stack.append("t(%s)" %x)
x = x+1
print("The quadruple for the expression ")
print(" OP | ARG 1 |ARG 2 |RESULT ")
Quadruple(pos)
def Triple(pos):
stack = []
op = []
x=0
for i in pos:
if i not in OPERATORS:
stack.append(i)
elifi == '-':
op1 = stack.pop()
stack.append("(%s)" %x)
print("{0:^4s} | {1:^4s} | {2:^4s}".format(i,op1,"(-)"))
x = x+1
if stack != []:
op2 = stack.pop()
op1 = stack.pop()
print("{0:^4s} | {1:^4s} | {2:^4s}".format("+",op1,op2))
stack.append("(%s)" %x)
x = x+1
elifi == '=':
op2 = stack.pop()
EX NO: 12 IMPLEMENTATION OF DAG
op1 = stack.pop()
print("{0:^4s} | {1:^4s} | {2:^4s}".format(i,op1,op2))
else:
op1 = stack.pop()
if stack != []:
op2 = stack.pop()
print("{0:^4s} | {1:^4s} | {2:^4s}".format(i,op2,op1))
stack.append("(%s)" %x)
x = x+1
print("The triple for given expression")
print(" OP | ARG 1 |ARG 2 ")
Triple(pos)
OUTPUT
INPUT THE EXPRESSION: (E*E)+(E/E)
PREFIX: +*EE/EE
POSTFIX: EE*EE/+
### THREE ADDRESS CODE GENERATION ###
t1 := E * E
t2 := E / E
t3 := t1+t2
The quadruple for the expression
OP | ARG 1 |ARG 2 |RESULT
*| E | E | t(1)
/| E |E | t(2)
+| t(1)| t(2)| t(3)
The triple for given expression
OP | ARG 1 |ARG 2
*| E | E
/| E | E
+ | (0) | (1)
ALGORITHM:
1. Start the program
2. Include all the header files
3. Check for postfix expression and construct in order dag representation.
4. Print output
5. End program
Manual Calculation:
PROGRAM :
#include<iostream>
#include<string>
#include<unordered_map>
using namespace std;
class DAG
{ public:
char label;
char data;
DAG* left;
DAG* right;
DAG(char x){
label='_';
data=x;
left=NULL;
right=NULL;
}
DAG(char lb, char x, DAG* lt, DAG* rt){
label=lb;
data=x;
left=lt;
right=rt;
}
};
int main(){
int n;
n=3;
string st[n];
st[0]="x=C/D";
st[1]="y=B+x";
st[2]="z=A*y";
unordered_map<char, DAG*>labelDAGNode;
for(int i=0;i<3;i++){
string stTemp=st[i];
for(int j=0;j<5;j++){
char tempLabel = stTemp[0];
char tempLeft = stTemp[2];
char tempData = stTemp[3];
char tempRight = stTemp[4];
DAG* leftPtr;
DAG* rightPtr;
if(labelDAGNode.count(tempLeft) == 0){
leftPtr = new DAG(tempLeft);
}
else{
leftPtr = labelDAGNode[tempLeft];
}
if(labelDAGNode.count(tempRight) == 0){
rightPtr = new DAG(tempRight);
}
else{
rightPtr = labelDAGNode[tempRight];
}
DAG* nn = new DAG(tempLabel,tempData,leftPtr,rightPtr);
labelDAGNode.insert(make_pair(tempLabel,nn));
}
}
cout<<"Label ptrleftPtrrightPtr"<<endl;
for(int i=0;i<n;i++){
DAG* x=labelDAGNode[st[i][0]];
cout<<st[i][0]<<" "<<x->data<<" ";
if(x->left->label=='_')cout<<x->left->data;
else cout<<x->left->label;
cout<<" ";
if(x->right->label=='_')cout<<x->right->data;
else cout<<x->right->label;
cout<<endl;
}
return 0;
}
OUTPUT
Label ptrleftPtrrightPtr
x * EE
y / EE
z + x y
RESULT:The C++ implementation to convert infix expression to dag representation has done
successfully.