LL1语法分析器c语言代码
时间: 2023-12-11 13:32:53 浏览: 142
以下是一个简单的LL(1)语法分析器的C++代码,用于解析给定文法的输入字符串:
```cpp
#include <iostream>
#include <stack>
#include <map>
#include <vector>
#include <string>
using namespace std;
// 定义文法规则
vector<string> grammar = {
"E->TE'",
"E'->+TE'|ε",
"T->FT'",
"T'->*FT'|ε",
"F->a|(E)"
};
// 定义预测分析表
map<pair<string, string>, string> parse_table = {
{{"E", "a"}, "TE'"},
{{"E", "("}, "TE'"},
{{"E'", "+"}, "+TE'"},
{{"E'", ")"}, "ε"},
{{"E'", "$"}, "ε"},
{{"T", "a"}, "FT'"},
{{"T", "("}, "FT'"},
{{"T'", "+"}, "ε"},
{{"T'", "*"}, "*FT'"},
{{"T'", ")"}, "ε"},
{{"T'", "$"}, "ε"},
{{"F", "a"}, "a"},
{{"F", "("}, "(E)"}
};
// 定义符号栈和输入串栈
stack<string> symbol_stack;
stack<char> input_stack;
// 初始化输入串栈
void init_input_stack(string input) {
for (int i = input.length() - 1; i >= 0; i--) {
input_stack.push(input[i]);
}
input_stack.push('$');
}
// 获取产生式右部
string get_production(string left_symbol, string input_symbol) {
if (parse_table.find({left_symbol, input_symbol}) != parse_table.end()) {
return parse_table[{left_symbol, input_symbol}];
}
return "";
}
// LL(1)语法分析
bool parse(string input) {
// 初始化符号栈和输入串栈
symbol_stack.push("$");
symbol_stack.push("E");
init_input_stack(input);
// 语法分析
while (!symbol_stack.empty()) {
string top_symbol = symbol_stack.top(); char top_input = input_stack.top();
if (top_symbol == "$" && top_input == '$') {
return true;
}
if (top_symbol == top_input || top_symbol == "ε") {
symbol_stack.pop();
input_stack.pop();
} else if (top_symbol == "a" && top_input == 'a') {
symbol_stack.pop();
input_stack.pop();
} else if (top_symbol == "(" && top_input == ')') {
symbol_stack.pop();
input_stack.pop();
} else if (top_symbol == "E" || top_symbol == "T" || top_symbol == "F") {
string production = get_production(top_symbol, string(1, top_input));
if (production == "") {
return false;
}
symbol_stack.pop();
if (production != "ε") {
for (int i = production.length() - 1; i >= 0; i--) {
symbol_stack.push(string(1, production[i]));
}
}
} else {
return false;
}
}
return true;
}
int main() {
string input = "a*(a+a)$";
if (parse(input)) {
cout << "输入串 " << input << " 符合文法规则" << endl;
} else {
cout << "输入串 " << input << " 不符合文法规则" << endl;
}
return 0;
}
```
阅读全文