帮我写一段消除普通文法的直接左递归和间接左递归的c++代码
时间: 2023-10-19 16:28:47 浏览: 91
消除普通文法的直接左递归和间接左递归的 C++ 代码如下:
```c++
// 消除直接左递归
void eliminate_direct_left_recursion(vector<string>& productions, char non_terminal) {
vector<string> new_productions;
vector<string> old_productions;
for (string production : productions) {
if (production[0] == non_terminal) {
old_productions.push_back(production);
} else {
new_productions.push_back(production);
}
}
if (old_productions.size() == 0) {
return;
}
string new_non_terminal = string(1, non_terminal) + "'";
new_productions.push_back(new_non_terminal + " -> ε");
for (string old_production : old_productions) {
string new_production = old_production.substr(1) + new_non_terminal;
new_productions.push_back(new_production);
}
new_productions.push_back(new_non_terminal + " -> " + old_productions[0].substr(1) + new_non_terminal);
productions = new_productions;
}
// 消除间接左递归
void eliminate_indirect_left_recursion(map<char, vector<string>>& grammar) {
vector<char> non_terminals;
for (auto it = grammar.begin(); it != grammar.end(); it++) {
non_terminals.push_back(it->first);
}
int n = non_terminals.size();
for (int k = 0; k < n; k++) {
char A = non_terminals[k];
for (int i = 0; i < k; i++) {
char B = non_terminals[i];
for (int j = 0; j < grammar[A].size(); j++) {
string production = grammar[A][j];
if (production[0] == B) {
vector<string> new_productions;
for (string B_production : grammar[B]) {
string new_production = B_production + production.substr(1);
new_productions.push_back(new_production);
}
grammar[A].erase(grammar[A].begin() + j);
grammar[A].insert(grammar[A].end(), new_productions.begin(), new_productions.end());
j += new_productions.size() - 1;
}
}
}
eliminate_direct_left_recursion(grammar[A], A);
}
}
```
其中,`eliminate_direct_left_recursion`函数用于消除一个非终结符的直接左递归,`eliminate_indirect_left_recursion`函数用于消除文法中的间接左递归。两个函数均接受一个文法的数据结构,`vector<string>`表示一个非终结符的产生式集合,`map<char, vector<string>>`表示整个文法。在实际使用时,需要先将文法转换成这种数据结构。
阅读全文