-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathExp9.cpp
155 lines (145 loc) · 2.57 KB
/
Exp9.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
// Write a program to implement recursive descent parser
// Parser is made for the following grammar:
/**
* E->TE'
* E'->+TE'|-TE'|null
* T-> FT'
* T'->*FT'|/FT'|null
* F-> id|num|(E)
**/
#include <iostream>
using namespace std;
bool E(string &str, int &i);
bool Ed(string &str, int &i);
bool T(string &str, int &i);
bool Td(string &str, int &i);
bool F(string &str, int &i);
bool E(string &str, int &i)
{
cout << "E->TE'" << endl;
if (!T(str, i))
return false;
if (!Ed(str, i))
return false;
return true;
}
bool Ed(string &str, int &i)
{
if (i >= str.length())
{
cout << "E'->null" << endl;
}
if (str[i] == '+')
{
i++;
cout << "E'->+TE'" << endl;
if (!T(str, i))
return false;
if (!Ed(str, i))
return false;
}
else if (str[i] == '-')
{
i++;
cout << "E'->-TE'" << endl;
if (!T(str, i))
return false;
if (!Ed(str, i))
return false;
}
else
{
cout << "E'->null" << endl;
}
return true;
}
bool T(string &str, int &i)
{
cout << "T->FT'" << endl;
if (!F(str, i))
return false;
if (!Td(str, i))
return false;
return true;
}
bool Td(string &str, int &i)
{
if (i >= str.length())
{
cout << "T'->null" << endl;
}
if (str[i] == '*')
{
i++;
cout << "T'->*FT'" << endl;
if (!F(str, i))
return false;
if (!Td(str, i))
return false;
}
else if (str[i] == '/')
{
i++;
cout << "T'->/FT'" << endl;
if (!F(str, i))
return false;
if (!Td(str, i))
return false;
}
else
{
cout << "T'->null" << endl;
}
return true;
}
bool F(string &str, int &i)
{
if (i >= str.length())
return false;
if (isalpha(str[i]))
{
i++;
cout << "F->id" << endl;
}
else if (isdigit(str[i]))
{
i++;
cout << "F->digit" << endl;
}
else if (str[i] == '(')
{
i++;
cout << "F->(E)" << endl;
if (!E(str, i))
return false;
if (i >= str.length() or str[i] != ')')
return false;
i++;
}
else
{
return false;
}
return true;
}
void parseString(string &str)
{
int i = 0;
if (!E(str, i) or i != str.length())
cout << "Rejected" << endl;
else
cout << "Accepted" << endl;
}
int main()
{
string str;
char ch = 'y';
while (ch == 'y' || ch == 'Y')
{
cout << "\nEnter the input string to be parsed: ";
cin >> str;
parseString(str);
cout << "\nDo you want to parse more? (y/n) ";
cin >> ch;
}
}