Ss Lab 3
Ss Lab 3
1. Left Recursion
2. Left Factoring
3. First() set of NTs
4. Follow() set of NTs
5. Build parsing table
6. Validate input string using stack
CODE : -
#include <iostream>
#include <vector>
#include <map>
#include <set>
#include <algorithm>
if (!recursive.empty()) {
char A_prime = getUniqueNonTerminal(grammar, newGrammar); newGrammar[A] =
nonRecursive;
for (string& production : newGrammar[A]) {
production += string(1, A_prime);
}
newGrammar[A_prime] = recursive;
for (string& production : newGrammar[A_prime]) {
production += string(1, A_prime);
}
newGrammar[A_prime].push_back("epsilon"); // Store epsilon as a string
}
}
}
return newGrammar;
}
if (!commonPrefix.empty()) {
char newNT = getUniqueNonTerminal(grammar, factoredGrammar); vector<string>
newProductions;
vector<string> factoredPart;
if (factoredPart.empty()) {
factoredPart.push_back("epsilon");
}
factoredGrammar[nonTerminal] = newProductions;
factoredGrammar[nonTerminal].push_back(commonPrefix + string(1, newNT));
factoredGrammar[newNT] = factoredPart;
} else {
factoredGrammar[nonTerminal] = productions;
}
}
return factoredGrammar;
}
int main() {
map<char, vector<string>> grammar;
return 0;
}
OUTPUT : -
#include <iostream>
#include <vector>
#include <map>
#include <set>
#include <stack>
#include <algorithm>
#include <iomanip>
if (!recursive.empty()) {
char A_prime = getUniqueNonTerminal(grammar, newGrammar); newGrammar[A] =
nonRecursive;
for (string& production : newGrammar[A]) {
production += string(1, A_prime);
}
newGrammar[A_prime] = recursive;
for (string& production : newGrammar[A_prime]) {
production += string(1, A_prime);
}
newGrammar[A_prime].push_back("epsilon");
}
}
}
return newGrammar;
}
if (nonTerminal == 'R') {
followSets[nonTerminal].insert("$");
}
input += '$';
int index = 0;
if (top == input[index]) {
cout << "Match " << top << endl;
index++;
} else if (isupper(top)) {
if (parsingTable.count({top, input[index]})) {
string production = parsingTable[{top, input[index]}]; cout
<< top << " -> " << production << endl;
if (production != "epsilon") {
for (int i = production.size() - 1; i >= 0; i--) {
parseStack.push(production[i]);
}
}
} else {
cout << "Error: No rule found!" << endl;
return false;
}
} else {
cout << "Error: Mismatch!" << endl;
return false;
}
}
int main() {
map<char, vector<string>> grammar;
grammar['R'] = {"TCA", "TCDA"};
grammar['T'] = {"T*F", "F"};
grammar['F'] = {"(E)", "x"};
string input;
cout << "\nEnter a string to verify: "; cin
>> input;
if (parseString(parsingTable, input)) {
cout << "String is ACCEPTED by the grammar.\n";
} else {
cout << "String is REJECTED by the grammar.\n";
}
return 0;
}
OUTPUT : -