Complete Lab2 IR generation and document process
This commit is contained in:
@@ -1,30 +1,40 @@
|
||||
// 基于语法树的语义检查与名称绑定。
|
||||
#pragma once
|
||||
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
#include "SysYParser.h"
|
||||
|
||||
class SemanticContext {
|
||||
public:
|
||||
void BindVarUse(SysYParser::VarContext* use,
|
||||
SysYParser::VarDefContext* decl) {
|
||||
var_uses_[use] = decl;
|
||||
void BindLValue(SysYParser::LValueContext* use,
|
||||
antlr4::ParserRuleContext* def) {
|
||||
lvalue_defs_[use] = def;
|
||||
}
|
||||
|
||||
SysYParser::VarDefContext* ResolveVarUse(
|
||||
const SysYParser::VarContext* use) const {
|
||||
auto it = var_uses_.find(use);
|
||||
return it == var_uses_.end() ? nullptr : it->second;
|
||||
void BindFuncCall(SysYParser::FuncCallExpContext* use,
|
||||
SysYParser::FuncDefContext* def) {
|
||||
funccall_defs_[use] = def;
|
||||
}
|
||||
|
||||
antlr4::ParserRuleContext* ResolveLValue(
|
||||
const SysYParser::LValueContext* use) const {
|
||||
auto it = lvalue_defs_.find(const_cast<SysYParser::LValueContext*>(use));
|
||||
return it == lvalue_defs_.end() ? nullptr : it->second;
|
||||
}
|
||||
|
||||
SysYParser::FuncDefContext* ResolveFuncCall(
|
||||
const SysYParser::FuncCallExpContext* use) const {
|
||||
auto it = funccall_defs_.find(const_cast<SysYParser::FuncCallExpContext*>(use));
|
||||
return it == funccall_defs_.end() ? nullptr : it->second;
|
||||
}
|
||||
|
||||
private:
|
||||
std::unordered_map<const SysYParser::VarContext*,
|
||||
SysYParser::VarDefContext*>
|
||||
var_uses_;
|
||||
std::unordered_map<SysYParser::LValueContext*, antlr4::ParserRuleContext*>
|
||||
lvalue_defs_;
|
||||
std::unordered_map<SysYParser::FuncCallExpContext*,
|
||||
SysYParser::FuncDefContext*>
|
||||
funccall_defs_;
|
||||
};
|
||||
|
||||
// 目前仅检查:
|
||||
// - 变量先声明后使用
|
||||
// - 局部变量不允许重复定义
|
||||
SemanticContext RunSema(SysYParser::CompUnitContext& comp_unit);
|
||||
|
||||
Reference in New Issue
Block a user