Converting the provided Python implementation of an SLR(1) parser to C++ involves translating Python-specific constructs to their C++ equivalents. Below is a comprehensive C++ program that mirrors the functionality of your Python code. It includes:
- Grammar Augmentation: Adding an augmented start rule.
- Closure and GOTO Functions: Building LR(0) items.
- FIRST and FOLLOW Sets: Computing these essential sets for parsing.
- Parse Table Construction: Building ACTION and GOTO tables.
- Parsing Strings: Using the parse table to parse input strings.
- Utility Functions: For handling grammar rules and displaying results.
Note: This C++ program uses the Standard Template Library (STL) extensively for data structures like vector, map, set, and queue. It also uses basic I/O for interaction. For table formatting, the program uses simple spacing; however, for more advanced table displays, you might consider integrating a library or enhancing the formatting logic.
Ensure you compile the program with a C++11 or later compliant compiler.
#include <bits/stdc++.h>
using namespace std;
// Structure to represent a production rule
struct Rule {
string lhs;
vector<string> rhs;
};
// Function to split a string by delimiter and return a vector of tokens
vector<string> split(const string& s, char delimiter) {
vector<string> tokens;
string token;
// Using a stringstream to split the string
stringstream ss(s);
while (getline(ss, token, delimiter)) {
tokens.push_back(token);
}
return tokens;
}
// Function to perform grammar augmentation
vector<Rule> grammarAugmentation(const vector<string>& rules, const vector<string>& nonterm_userdef, const string& start_symbol) {
vector<Rule> newRules;
string newChar = start_symbol + "'";
// Ensure the new start symbol is unique
while (find(nonterm_userdef.begin(), nonterm_userdef.end(), newChar) != nonterm_userdef.end()) {
newChar += "'";
}
// Adding augmented start rule with a dot at the beginning
Rule augmentedRule;
augmentedRule.lhs = newChar;
augmentedRule.rhs = {".", start_symbol};
newRules.push_back(augmentedRule);
// Process existing rules
for (const auto& rule_str : rules) {
// Split the rule into LHS and RHS
size_t pos = rule_str.find("->");
if (pos == string::npos) continue; // Invalid rule format
string lhs = rule_str.substr(0, pos);
lhs.erase(remove(lhs.begin(), lhs.end(), ' '), lhs.end()); // Remove spaces
string rhs = rule_str.substr(pos + 2);
// Split RHS by '|'
vector<string> multirhs = split(rhs, '|');
for (auto& rhs1 : multirhs) {
// Split RHS by spaces
vector<string> symbols;
stringstream ss(rhs1);
string sym;
while (ss >> sym) {
symbols.push_back(sym);
}
// Insert dot at the beginning
symbols.insert(symbols.begin(), ".");
Rule newRule;
newRule.lhs = lhs;
newRule.rhs = symbols;
newRules.push_back(newRule);
}
}
return newRules;
}
// Function to print rules
void printRules(const vector<Rule>& rules) {
for (const auto& rule : rules) {
cout << rule.lhs << " -> ";
for (size_t i = 0; i < rule.rhs.size(); ++i) {
cout << rule.rhs[i];
if (i != rule.rhs.size() - 1) cout << " ";
}
cout << endl;
}
}
// Function to find closure
vector<Rule> findClosure(const vector<Rule>& items, const vector<Rule>& separatedRulesList, const vector<string>& nonterm_userdef) {
vector<Rule> closureSet = items; // Start with the current items
bool added = true;
while (added) {
added = false;
vector<Rule> new_items;
for (const auto& rule : closureSet) {
// Check if there's a dot in RHS
auto it = find(rule.rhs.begin(), rule.rhs.end(), ".");
if (it != rule.rhs.end()) {
int dot_pos = distance(rule.rhs.begin(), it);
// Check if dot is not at the end
if (dot_pos < (int)(rule.rhs.size() - 1)) {
string symbol_after_dot = rule.rhs[dot_pos + 1];
// If the symbol after dot is a non-terminal
if (find(nonterm_userdef.begin(), nonterm_userdef.end(), symbol_after_dot) != nonterm_userdef.end()) {
// Add all productions of that non-terminal if not already in closureSet
for (const auto& prod : separatedRulesList) {
if (prod.lhs == symbol_after_dot) {
// Check if prod is already in closureSet or new_items
bool exists = false;
for (const auto& existing_rule : closureSet) {
if (existing_rule.lhs == prod.lhs && existing_rule.rhs == prod.rhs) {
exists = true;
break;
}
}
if (!exists) {
for (const auto& new_rule : new_items) {
if (new_rule.lhs == prod.lhs && new_rule.rhs == prod.rhs) {
exists = true;
break;
}
}
}
if (!exists) {
new_items.push_back(prod);
added = true;
}
}
}
}
}
}
}
// Add any new items found
for (const auto& new_item : new_items) {
closureSet.push_back(new_item);
}
}
return closureSet;
}
// Function to compute GOTO
vector<Rule> compute_GOTO(const vector<Rule>& current_items, const string& symbol, const vector<Rule>& separatedRulesList, const vector<string>& nonterm_userdef) {
vector<Rule> moved;
for (const auto& rule : current_items) {
// Find the dot
auto it = find(rule.rhs.begin(), rule.rhs.end(), ".");
if (it != rule.rhs.end()) {
int dot_pos = distance(rule.rhs.begin(), it);
// Check if symbol matches
if (dot_pos < (int)(rule.rhs.size() - 1) && rule.rhs[dot_pos + 1] == symbol) {
// Move the dot past the symbol
Rule moved_rule = rule;
swap(moved_rule.rhs[dot_pos], moved_rule.rhs[dot_pos + 1]);
moved.push_back(moved_rule);
}
}
}
// Get the closure of the moved items
if (!moved.empty()) {
return findClosure(moved, separatedRulesList, nonterm_userdef);
}
return {};
}
// Function to compute FIRST set
set<string> compute_first(const string& symbol, const map<string, vector<vector<string>>>& diction, const vector<string>& term_userdef, map<string, set<string>>& firsts, set<string>& visited) {
if (find(term_userdef.begin(), term_userdef.end(), symbol) != term_userdef.end()) {
// Terminal symbol
return {symbol};
}
if (visited.find(symbol) != visited.end()) {
return {};
}
visited.insert(symbol);
set<string> result;
if (diction.find(symbol) != diction.end()) {
for (const auto& rule_rhs : diction.at(symbol)) {
if (rule_rhs.empty()) continue;
if (rule_rhs[0] == "#") { // Epsilon
result.insert("#");
} else {
bool all_nullable = true;
for (const auto& sym : rule_rhs) {
set<string> first_sym = compute_first(sym, diction, term_userdef, firsts, visited);
// Add FIRST(sym) - {epsilon} to result
for (const auto& f : first_sym) {
if (f != "#") result.insert(f);
}
if (first_sym.find("#") == first_sym.end()) {
all_nullable = false;
break;
}
}
if (all_nullable) {
result.insert("#");
}
}
}
}
return result;
}
// Function to compute FOLLOW sets
set<string> follow_symbol(const string& symbol, const map<string, vector<vector<string>>>& diction, const vector<string>& nonterm_userdef, const vector<string>& term_userdef, const map<string, set<string>>& firsts, map<string, set<string>>& follows, const string& start_symbol_augmented) {
// If FOLLOW(symbol) is already computed and not empty, return it
if (!follows[symbol].empty()) {
return follows[symbol];
}
// If symbol is the augmented start symbol, add '$'
if (symbol == start_symbol_augmented) {
follows[symbol].insert("$");
}
// Iterate over all productions to find occurrences of symbol
for (const auto& [lhs, productions] : diction) {
for (const auto& rhs : productions) {
for (size_t i = 0; i < rhs.size(); ++i) {
if (rhs[i] == symbol) {
// If symbol is not the last symbol in RHS
if (i + 1 < rhs.size()) {
string next_sym = rhs[i + 1];
if (find(term_userdef.begin(), term_userdef.end(), next_sym) != term_userdef.end()) {
follows[symbol].insert(next_sym);
} else {
// Add FIRST(next_sym) - {epsilon} to FOLLOW(symbol)
for (const auto& fst : firsts.at(next_sym)) {
if (fst != "#") follows[symbol].insert(fst);
}
// If FIRST(next_sym) contains epsilon, add FOLLOW(lhs) to FOLLOW(symbol)
if (firsts.at(next_sym).find("#") != firsts.at(next_sym).end()) {
// Recursive call to add FOLLOW(lhs)
if (lhs != symbol) {
set<string> follow_lhs = follow_symbol(lhs, diction, nonterm_userdef, term_userdef, firsts, follows, start_symbol_augmented);
follows[symbol].insert(follow_lhs.begin(), follow_lhs.end());
}
}
}
} else {
// If symbol is at the end, add FOLLOW(lhs) to FOLLOW(symbol)
if (lhs != symbol) {
set<string> follow_lhs = follow_symbol(lhs, diction, nonterm_userdef, term_userdef, firsts, follows, start_symbol_augmented);
follows[symbol].insert(follow_lhs.begin(), follow_lhs.end());
}
}
}
}
}
}
return follows[symbol];
}
// Function to compute FIRST and FOLLOW sets
pair<map<string, set<string>>, map<string, set<string>>> compute_first_follow(const map<string, vector<vector<string>>>& diction, const vector<string>& nonterm_userdef, const vector<string>& term_userdef, const string& start_symbol_augmented) {
map<string, set<string>> firsts;
// Compute FIRST sets
for (const auto& nt : nonterm_userdef) {
set<string> visited;
firsts[nt] = compute_first(nt, diction, term_userdef, firsts, visited);
}
// Compute FOLLOW sets
map<string, set<string>> follows;
for (const auto& nt : nonterm_userdef) {
follow_symbol(nt, diction, nonterm_userdef, term_userdef, firsts, follows, start_symbol_augmented);
}
return {firsts, follows};
}
// Function to create the parse table
tuple<map<int, map<string, string>>, map<int, map<string, string>>, map<int, pair<string, vector<string>>>> createParseTable(
const map<int, vector<Rule>>& statesDict,
const map<vector<pair<string, vector<string>>>, int>& stateMap,
const vector<Rule>& separatedRulesList,
const map<string, vector<vector<string>>>& diction,
const map<string, set<string>>& firsts,
const map<string, set<string>>& follows,
const vector<string>& term_userdef,
const vector<string>& nonterm_userdef,
const string& start_symbol_augmented) {
map<int, map<string, string>> action_table;
map<int, map<string, string>> goto_table;
map<int, pair<string, vector<string>>> prod_num; // Production number mapping
int num = 1; // Start numbering from 1, 0 reserved for augmented production
// Number the productions (skip augmented start rule at 0)
for (size_t i = 0; i < separatedRulesList.size(); ++i) {
const auto& rule = separatedRulesList[i];
if (rule.lhs == start_symbol_augmented) {
// Production 0
vector<string> production_rhs;
for (const auto& sym : rule.rhs) {
if (sym != ".") production_rhs.push_back(sym);
}
prod_num[0] = {rule.lhs, production_rhs};
} else {
// Other productions
vector<string> production_rhs;
for (const auto& sym : rule.rhs) {
if (sym != ".") production_rhs.push_back(sym);
}
prod_num[num] = {rule.lhs, production_rhs};
num++;
}
}
// Iterate through each state to fill ACTION and GOTO tables
for (const auto& [state, rules] : statesDict) {
for (const auto& rule : rules) {
string lhs = rule.lhs;
vector<string> rhs = rule.rhs;
// If rule is of the form A -> alpha.
if (!rhs.empty() && rhs.back() == ".") {
if (lhs == start_symbol_augmented) {
action_table[state]["$"] = "ACC";
} else {
// Find the production number
vector<string> production_rhs;
for (const auto& sym : rhs) {
if (sym != ".") production_rhs.push_back(sym);
}
int prod_number = -1;
for (const auto& [p_num, prod] : prod_num) {
if (prod.first == lhs && prod.second == production_rhs) {
prod_number = p_num;
break;
}
}
if (prod_number == -1) {
throw runtime_error("Production not found for reduction.");
}
// Add reduce actions for all symbols in FOLLOW(lhs)
if (follows.find(lhs) != follows.end()) {
for (const auto& terminal : follows.at(lhs)) {
if (action_table[state].find(terminal) != action_table[state].end()) {
// Handle conflicts by appending
action_table[state][terminal] += "/R" + to_string(prod_number);
} else {
action_table[state][terminal] = "R" + to_string(prod_number);
}
}
}
}
} else {
// If dot is not at the end, handle Shift or GOTO
auto it = find(rhs.begin(), rhs.end(), ".");
if (it != rhs.end()) {
int dot_pos = distance(rhs.begin(), it);
if (dot_pos < (int)(rhs.size() - 1)) {
string symbol = rhs[dot_pos + 1];
if (find(term_userdef.begin(), term_userdef.end(), symbol) != term_userdef.end()) {
// Shift action
// Compute GOTO on this symbol
vector<Rule> goto_result = compute_GOTO(rules, symbol, separatedRulesList, nonterm_userdef);
if (!goto_result.empty()) {
// Create a key for the stateMap
vector<pair<string, vector<string>>> goto_key_pairs;
for (const auto& r : goto_result) {
goto_key_pairs.emplace_back(make_pair(r.lhs, r.rhs));
}
// Sort for consistent ordering
sort(goto_key_pairs.begin(), goto_key_pairs.end());
// Check if this goto_key exists in stateMap
auto it_map = stateMap.find(goto_key_pairs);
if (it_map != stateMap.end()) {
int next_state = it_map->second;
if (action_table[state].find(symbol) != action_table[state].end()) {
// Handle conflicts
action_table[state][symbol] += "/S" + to_string(next_state);
} else {
action_table[state][symbol] = "S" + to_string(next_state);
}
}
}
} else if (find(nonterm_userdef.begin(), nonterm_userdef.end(), symbol) != nonterm_userdef.end()) {
// GOTO table
vector<Rule> goto_result = compute_GOTO(rules, symbol, separatedRulesList, nonterm_userdef);
if (!goto_result.empty()) {
// Create a key for the stateMap
vector<pair<string, vector<string>>> goto_key_pairs;
for (const auto& r : goto_result) {
goto_key_pairs.emplace_back(make_pair(r.lhs, r.rhs));
}
// Sort for consistent ordering
sort(goto_key_pairs.begin(), goto_key_pairs.end());
// Check if this goto_key exists in stateMap
auto it_map = stateMap.find(goto_key_pairs);
if (it_map != stateMap.end()) {
int goto_state = it_map->second;
goto_table[state][symbol] = to_string(goto_state);
}
}
}
}
}
}
}
}
return make_tuple(action_table, goto_table, prod_num);
}
// Function to print the parse table
void printParseTable(const map<int, map<string, string>>& action_table,
const map<int, map<string, string>>& goto_table,
const vector<string>& term_userdef,
const vector<string>& nonterm_userdef) {
// Prepare headers
vector<string> headers = {"State"};
for (const auto& term : term_userdef) {
headers.push_back(term);
}
headers.push_back("$");
for (const auto& nonterm : nonterm_userdef) {
headers.push_back(nonterm);
}
// Compute column widths for formatting
map<string, int> col_width;
for (const auto& header : headers) {
col_width[header] = header.length();
}
// Update column widths based on table content
for (const auto& [state, actions] : action_table) {
for (const auto& [symbol, action] : actions) {
if (col_width[symbol] < (int)action.length()) {
col_width[symbol] = action.length();
}
}
}
for (const auto& [state, gotos] : goto_table) {
for (const auto& [symbol, goto_state] : gotos) {
if (col_width[symbol] < (int)goto_state.length()) {
col_width[symbol] = goto_state.length();
}
}
}
// Print headers
for (size_t i = 0; i < headers.size(); ++i) {
cout << left << setw(col_width[headers[i]] + 2) << headers[i];
}
cout << endl;
// Print separator
for (size_t i = 0; i < headers.size(); ++i) {
cout << left << setw(col_width[headers[i]] + 2) << string(col_width[headers[i]], '-');
}
cout << endl;
// Print each row
// Assuming states are numbered from 0 to n
// Find the maximum state number
int max_state = -1;
for (const auto& [state, _] : action_table) {
if (state > max_state) max_state = state;
}
for (int state = 0; state <= max_state; ++state) {
// State ID
cout << left << setw(col_width["State"] + 2) << ("I" + to_string(state)));
// Terminals
for (const auto& term : term_userdef) {
if (action_table.find(state) != action_table.end() &&
action_table.at(state).find(term) != action_table.at(state).end()) {
cout << left << setw(col_width[term] + 2) << action_table.at(state).at(term);
} else {
cout << left << setw(col_width[term] + 2) << "";
}
}
// End marker $
if (action_table.find(state) != action_table.end() &&
action_table.at(state).find("$") != action_table.at(state).end()) {
cout << left << setw(col_width["$"] + 2) << action_table.at(state).at("$");
} else {
cout << left << setw(col_width["$"] + 2) << "";
}
// Non-terminals
for (const auto& nonterm : nonterm_userdef) {
if (goto_table.find(state) != goto_table.end() &&
goto_table.at(state).find(nonterm) != goto_table.at(state).end()) {
cout << left << setw(col_width[nonterm] + 2) << goto_table.at(state).at(nonterm);
} else {
cout << left << setw(col_width[nonterm] + 2) << "";
}
}
cout << endl;
}
}
// Function to print parsing steps
bool parseString(const string& string_input,
const map<int, map<string, string>>& action_table,
const map<int, map<string, string>>& goto_table,
const map<int, pair<string, vector<string>>>& prod_num,
const map<string, vector<vector<string>>>& diction) {
// Initialize stack with state 0
vector<pair<string, int>> stack; // Pair of symbol and state
stack.emplace_back("#", 0); // Using '#' as initial stack symbol
// Split the input string into tokens
vector<string> symbol_list;
string token;
stringstream ss(string_input);
while (ss >> token) {
symbol_list.push_back(token);
}
symbol_list.push_back("$"); // Append end marker
int pointer = 0;
bool accepted = false;
// Prepare headers for parsing steps
cout << "\nParsing Steps:\n";
cout << left << setw(20) << "Stack" << setw(20) << "Input" << setw(30) << "Action" << endl;
cout << string(70, '-') << endl;
while (true) {
// Get current state
int current_state = stack.back().second;
// Get current symbol
string current_symbol = (pointer < (int)symbol_list.size()) ? symbol_list[pointer] : "$";
// Get action
string action = "";
if (action_table.find(current_state) != action_table.end() &&
action_table.at(current_state).find(current_symbol) != action_table.at(current_state).end()) {
action = action_table.at(current_state).at(current_symbol);
}
// Prepare stack content
string stack_content = "";
for (const auto& elem : stack) {
stack_content += elem.first + " " + to_string(elem.second) + " ";
}
// Prepare input remaining
string input_remaining = "";
for (int i = pointer; i < (int)symbol_list.size(); ++i) {
input_remaining += symbol_list[i] + " ";
}
// Handle multiple actions (conflicts) by choosing the first action
if (action.find('/') != string::npos) {
size_t pos = action.find('/');
action = action.substr(0, pos);
}
if (action.empty()) {
// Error
cout << left << setw(20) << stack_content << setw(20) << input_remaining << setw(30) << "Error" << endl;
break;
}
if (action == "ACC") {
// Accept
cout << left << setw(20) << stack_content << setw(20) << input_remaining << setw(30) << "Accept" << endl;
accepted = true;
break;
}
else if (action[0] == 'S') {
// Shift
int next_state = stoi(action.substr(1));
cout << left << setw(20) << stack_content << setw(20) << input_remaining << setw(30) << ("Shift to state " + to_string(next_state)) << endl;
// Push the symbol and state to stack
stack.emplace_back(current_symbol, next_state);
pointer++;
}
else if (action[0] == 'R') {
// Reduce
int prod_number = stoi(action.substr(1));
if (prod_num.find(prod_number) == prod_num.end()) {
cout << left << setw(20) << stack_content << setw(20) << input_remaining << setw(30) << ("Unknown Production R" + to_string(prod_number)) << endl;
break;
}
pair<string, vector<string>> production = prod_num.at(prod_number);
string lhs = production.first;
vector<string> rhs = production.second;
// Print the production used for reduction
string production_str = lhs + " -> ";
if (rhs.size() == 1 && rhs[0] == "#") {
production_str += "#";
} else {
for (size_t i = 0; i < rhs.size(); ++i) {
production_str += rhs[i];
if (i != rhs.size() - 1) production_str += " ";
}
}
cout << left << setw(20) << stack_content << setw(20) << input_remaining << setw(30) << ("Reduce using " + to_string(prod_number) + ": " + production_str) << endl;
// Pop 2 * |rhs| items from stack
if (!(rhs.size() == 1 && rhs[0] == "#")) {
for (size_t i = 0; i < rhs.size(); ++i) {
if (stack.empty()) break;
stack.pop_back();
}
}
// After popping, get the current state
int current_state_after_pop = stack.back().second;
// Push lhs
// Find GOTO(current_state_after_pop, lhs)
string goto_state_str = "";
if (goto_table.find(current_state_after_pop) != goto_table.end() &&
goto_table.at(current_state_after_pop).find(lhs) != goto_table.at(current_state_after_pop).end()) {
goto_state_str = goto_table.at(current_state_after_pop).at(lhs);
}
if (goto_state_str.empty()) {
cout << left << setw(20) << stack_content << setw(20) << input_remaining << setw(30) << ("Error: No GOTO state for " + lhs) << endl;
break;
}
int goto_state = stoi(goto_state_str);
stack.emplace_back(lhs, goto_state);
}
else {
// Unknown action
cout << left << setw(20) << stack_content << setw(20) << input_remaining << setw(30) << ("Error: Unknown action " + action) << endl;
break;
}
}
return accepted;
}
int main() {
// Example sample set 01
vector<string> rules = {
"E -> E + T | T",
"T -> T * F | F",
"F -> ( E ) | id"
};
// Example sample set 02 (Uncomment to test)
/*
vector<string> rules = {
"S -> a Xd | byda Ye | bXe",
"X -> c",
"Y -> c"
};
*/
// Define non-terminals and terminals
vector<string> nonterm_userdef = {"E", "T", "F"};
vector<string> term_userdef = {"id", "+", "*", "(", ")"};
string start_symbol = nonterm_userdef[0];
// Uncomment for sample set 02
/*
nonterm_userdef = {"S", "X", "Y"};
term_userdef = {"a", "b", "c", "d", "e"};
start_symbol = nonterm_userdef[0];
*/
cout << "\nOriginal Grammar Input:\n" << endl;
for (const auto& rule : rules) {
cout << rule << endl;
}
// Perform grammar augmentation
vector<Rule> separatedRulesList = grammarAugmentation(rules, nonterm_userdef, start_symbol);
cout << "\nGrammar after Augmentation:\n" << endl;
printRules(separatedRulesList);
// Initialize statesDict and stateMap
map<int, vector<Rule>> statesDict;
map<vector<pair<string, vector<string>>>, int> stateMap; // Using vector of pairs as key
// Find the augmented start symbol
string start_symbol_augmented = separatedRulesList[0].lhs;
// Find closure for the initial state
vector<Rule> initial_items = {separatedRulesList[0]};
vector<Rule> closure_result = findClosure(initial_items, separatedRulesList, nonterm_userdef);
statesDict[0] = closure_result;
// Create a key for the stateMap
vector<pair<string, vector<string>>> closure_key_pairs;
for (const auto& r : closure_result) {
closure_key_pairs.emplace_back(make_pair(r.lhs, r.rhs));
}
// Sort for consistent ordering
sort(closure_key_pairs.begin(), closure_key_pairs.end());
stateMap[closure_key_pairs] = 0;
int stateCount = 1;
// Generate states
while (true) {
bool added_new_state = false;
// Iterate over existing states
for (auto it = statesDict.begin(); it != statesDict.end(); ++it) {
int state = it->first;
const vector<Rule>& current_items = it->second;
// Find all possible symbols after a dot
set<string> symbols;
for (const auto& rule : current_items) {
auto it_dot = find(rule.rhs.begin(), rule.rhs.end(), ".");
if (it_dot != rule.rhs.end()) {
int dot_pos = distance(rule.rhs.begin(), it_dot);
if (dot_pos < (int)(rule.rhs.size() - 1)) {
symbols.insert(rule.rhs[dot_pos + 1]);
}
}
}
for (const auto& symbol : symbols) {
// Compute GOTO for this symbol
vector<Rule> goto_result = compute_GOTO(current_items, symbol, separatedRulesList, nonterm_userdef);
if (goto_result.empty()) continue;
// Create a key for the stateMap
vector<pair<string, vector<string>>> goto_key_pairs;
for (const auto& r : goto_result) {
goto_key_pairs.emplace_back(make_pair(r.lhs, r.rhs));
}
// Sort for consistent ordering
sort(goto_key_pairs.begin(), goto_key_pairs.end());
// Check if this state already exists
if (stateMap.find(goto_key_pairs) == stateMap.end()) {
// Add new state
statesDict[stateCount] = goto_result;
stateMap[goto_key_pairs] = stateCount;
stateCount++;
added_new_state = true;
}
}
}
if (!added_new_state) break;
}
// Print generated states
cout << "\nStates Generated:\n" << endl;
for (const auto& [state, rules] : statesDict) {
cout << "State I" << state << ":\n";
printRules(rules);
cout << endl;
}
// Create dictionary for productions
map<string, vector<vector<string>>> diction;
for (const auto& rule : separatedRulesList) {
diction[rule.lhs].emplace_back(rule.rhs);
}
// Compute FIRST and FOLLOW sets
pair<map<string, set<string>>, map<string, set<string>>> first_follow = compute_first_follow(diction, nonterm_userdef, term_userdef, start_symbol_augmented);
map<string, set<string>> firsts = first_follow.first;
map<string, set<string>> follows = first_follow.second;
// Create parse table
map<int, map<string, string>> action_table;
map<int, map<string, string>> goto_table;
map<int, pair<string, vector<string>>> prod_num;
try {
tie(action_table, goto_table, prod_num) = createParseTable(statesDict, stateMap, separatedRulesList, diction, firsts, follows, term_userdef, nonterm_userdef, start_symbol_augmented);
}
catch (const exception& e) {
cout << "\nError while creating parse table: " << e.what() << endl;
return 1;
}
// Print parse table
printParseTable(action_table, goto_table, term_userdef, nonterm_userdef);
// Input string to parse
cout << "\nEnter the string to be parsed (tokens separated by space): ";
string input_string;
getline(cin, input_string);
// Parsing the string
bool accepted = parseString(input_string, action_table, goto_table, prod_num, diction);
if (accepted) {
cout << "\nThe string is parsable and accepted!" << endl;
} else {
cout << "\nThe string is not parsable and is rejected." << endl;
}
return 0;
}
Explanation of the C++ Code:
-
Data Structures:
- Rule Structure: Represents a production rule with a left-hand side (
lhs) and a right-hand side (rhs), which is a vector of symbols.
- Split Function: A utility function to split strings based on a delimiter, used for parsing grammar rules.
-
Grammar Augmentation (grammarAugmentation):
- Adds an augmented start symbol (
S') to the grammar to facilitate parsing.
- Inserts a dot (
.) at the beginning of each production's right-hand side to denote the initial position for LR parsing.
-
Closure Calculation (findClosure):
- Computes the closure of a set of LR items by adding relevant productions whenever a non-terminal appears immediately after a dot.
-
GOTO Function (compute_GOTO):
- Determines the transition from one set of LR items to another based on a given grammar symbol.
-
FIRST and FOLLOW Sets (compute_first and follow_symbol):
- FIRST: Determines the set of terminals that begin the strings derivable from a non-terminal.
- FOLLOW: Determines the set of terminals that can appear immediately to the right of a non-terminal in some "sentential" form.
-
Parse Table Construction (createParseTable):
- Builds ACTION and GOTO tables based on the constructed LR(0) items and computed FIRST and FOLLOW sets.
- Handles shift, reduce, and accept actions.
-
Printing Functions (printRules, printParseTable):
- Outputs the grammar rules and the constructed parse tables in a readable format.
-
Parsing Strings (parseString):
- Simulates the parsing process using the ACTION and GOTO tables.
- Displays each step, including stack content, remaining input, and actions taken (shift, reduce, accept, or error).
-
Main Function:
- Initializes the grammar rules, non-terminals, and terminals.
Compilation and Execution:
-
Compilation:
-
Execution:
- Run the compiled program:
./slr_parser
- Input the string you wish to parse when prompted, ensuring tokens are separated by spaces. For example:
id + id * id
- The program will display the parsing steps and indicate whether the string is accepted or rejected.
Sample Output:
Original Grammar Input:
E -> E + T | T
T -> T * F | F
F -> ( E ) | id
Grammar after Augmentation:
E' -> . E
E -> . E + T
E -> . T
T -> . T * F
T -> . F
F -> . ( E )
F -> . id
States Generated:
State I0:
E' -> . E
E -> . E + T
E -> . T
T -> . T * F
T -> . F
F -> . ( E )
F -> . id
State I1:
E' -> E .
E -> E . + T
State I2:
E -> T .
...
SLR(1) Parsing Table:
State | id | + | * | ( | ) | $ | E | T | F
-----------------------------------------------------------------------------
I0 S5 S4 S6 S7 | S1 I2 I3
I1 R1 ACC
...
Enter the string to be parsed (tokens separated by space): id + id * id
Parsing Steps:
Stack Input Action
----------------------------------------------------------------------
# 0 id + id * id $ Shift to state 5
# 0 id 5 + id * id $ Reduce using 5: F -> id
# 0 F 5 + id * id $ GOTO state 3
# 0 F 5 T 3 + id * id $ Reduce using 3: T -> F
# 0 T 3 + id * id $ GOTO state 2
# 0 T 3 E 2 + id * id $ Reduce using 2: E -> T
# 0 E 2 + id * id $ GOTO state 1
# 0 E 2 + 1 id * id $ Shift to state 5
# 0 E 2 + 1 id 5 * id $ Reduce using 5: F -> id
# 0 E 2 + 1 F 5 * id $ GOTO state 3
# 0 E 2 + 1 F 5 * 3 id $ Shift to state 5
# 0 E 2 + 1 F 5 * 3 id 5 $ Reduce using 5: F -> id
# 0 E 2 + 1 F 5 * 3 F 5 $ GOTO state 4
# 0 E 2 + 1 F 5 * 3 F 5 * 4 $ Reduce using 4: T -> T * F
# 0 E 2 + 1 T 4 $ GOTO state 2
# 0 E 2 + 1 T 4 $ Reduce using 2: E -> T
# 0 E 2 + 1 E 2 $ GOTO state 1
# 0 E 2 + 1 E 2 $ Shift to state 7
# 0 E 2 + 1 E 2 $ + 7 id $ Error: No GOTO state for +
The string is not parsable and is rejected.
Note: The sample output is illustrative. The actual states and actions depend on the complete parse table generated by the program.
Final Remarks:
-
Error Handling: The C++ program includes basic error handling, such as reporting unknown actions or missing productions. You can enhance this by providing more detailed error messages or recovery mechanisms.
-
Extensibility: The program is designed to handle SLR(1) grammars. For more complex parsing techniques like LR(1) or LALR(1), additional logic would be required.
-
Input Method: The program expects the grammar to be predefined within the code. For a more dynamic approach, you can modify the program to accept grammar rules from user input or external files.
-
Table Formatting: For better visualization of the parse tables, consider integrating advanced formatting techniques or libraries.
This C++ implementation provides a robust foundation for an SLR(1) parser and can be further expanded or optimized based on specific requirements or use cases.