考研 408 × 求职面试
知识点 · 编译原理 · 基础
每日一题 · 编译原理
解析
面试小贴士 · 编译原理
代码实现 · C++
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
int main() {
vector<string> tok = {"int","x","=","@",";","y","=","x","+"};
vector<string> declared = {"x"};
// 词法阶段:发现非法字符并跳过
for (auto &s : tok)
if (s == "@") cout << "词法错误:@非法,跳过恢复" << endl;
// 语法阶段:检查括号配对,用恐慌模式恢复
int bal = 0;
for (auto &s : tok) { if (s=="(") bal++; if (s==")") bal--; }
if (bal != 0) cout << "语法错误:括号不匹配,跳到分号恢复" << endl;
// 语义阶段:检查未声明变量,假定声明后继续
for (auto &s : tok)
if (s == "y" && find(declared.begin(), declared.end(), s) == declared.end())
cout << "语义错误:y未声明,插入声明并继续" << endl;
cout << "局部恢复后继续分析,可报告更多错误" << endl;
return 0;
}