|
|
#include "irgen/IRGen.h"
|
|
|
|
|
|
#include <stdexcept>
|
|
|
|
|
|
#include "SysYParser.h"
|
|
|
#include "ir/IR.h"
|
|
|
#include "utils/Log.h"
|
|
|
|
|
|
// 语句生成当前只实现了最小子集。
|
|
|
// 目前支持:
|
|
|
// - return <exp>;
|
|
|
//
|
|
|
// 还未支持:
|
|
|
// - 赋值语句
|
|
|
// - if / while 等控制流
|
|
|
// - 空语句、块语句嵌套分发之外的更多语句形态
|
|
|
|
|
|
std::any IRGenImpl::visitStmt(SysYParser::StmtContext* ctx) {
|
|
|
if (!ctx) {
|
|
|
throw std::runtime_error(FormatError("irgen", "缺少语句"));
|
|
|
}
|
|
|
|
|
|
// return 语句 - 通过 Return() 关键字判断
|
|
|
if (ctx->Return()) {
|
|
|
return HandleReturnStmt(ctx);
|
|
|
}
|
|
|
|
|
|
// 块语句
|
|
|
if (ctx->block()) {
|
|
|
return ctx->block()->accept(this);
|
|
|
}
|
|
|
|
|
|
// 空语句或表达式语句(先计算表达式)
|
|
|
if (ctx->exp()) {
|
|
|
EvalExpr(*ctx->exp());
|
|
|
return BlockFlow::Continue;
|
|
|
}
|
|
|
|
|
|
throw std::runtime_error(FormatError("irgen", "暂不支持的语句类型"));
|
|
|
}
|
|
|
|
|
|
IRGenImpl::BlockFlow IRGenImpl::HandleReturnStmt(SysYParser::StmtContext* ctx) {
|
|
|
if (!ctx) {
|
|
|
throw std::runtime_error(FormatError("irgen", "缺少 return 语句"));
|
|
|
}
|
|
|
|
|
|
ir::Value* retValue = nullptr;
|
|
|
if (ctx->exp()) {
|
|
|
retValue = EvalExpr(*ctx->exp());
|
|
|
}
|
|
|
// 如果没有表达式,返回0(对于int main)
|
|
|
if (!retValue) {
|
|
|
retValue = builder_.CreateConstInt(0);
|
|
|
}
|
|
|
|
|
|
builder_.CreateRet(retValue);
|
|
|
return BlockFlow::Terminated;
|
|
|
}
|
|
|
|
|
|
// if语句(待实现)
|
|
|
IRGenImpl::BlockFlow IRGenImpl::HandleIfStmt(SysYParser::StmtContext* ctx) {
|
|
|
// TODO: 实现if语句
|
|
|
throw std::runtime_error(FormatError("irgen", "if语句暂未实现"));
|
|
|
}
|
|
|
|
|
|
// while语句(待实现)
|
|
|
IRGenImpl::BlockFlow IRGenImpl::HandleWhileStmt(SysYParser::StmtContext* ctx) {
|
|
|
// TODO: 实现while语句
|
|
|
throw std::runtime_error(FormatError("irgen", "while语句暂未实现"));
|
|
|
}
|
|
|
|
|
|
// break语句(待实现)
|
|
|
IRGenImpl::BlockFlow IRGenImpl::HandleBreakStmt(SysYParser::StmtContext* ctx) {
|
|
|
// TODO: 实现break
|
|
|
throw std::runtime_error(FormatError("irgen", "break语句暂未实现"));
|
|
|
}
|
|
|
|
|
|
// continue语句(待实现)
|
|
|
IRGenImpl::BlockFlow IRGenImpl::HandleContinueStmt(SysYParser::StmtContext* ctx) {
|
|
|
// TODO: 实现continue
|
|
|
throw std::runtime_error(FormatError("irgen", "continue语句暂未实现"));
|
|
|
}
|
|
|
|
|
|
// 赋值语句(待实现)
|
|
|
IRGenImpl::BlockFlow IRGenImpl::HandleAssignStmt(SysYParser::StmtContext* ctx) {
|
|
|
// TODO: 实现赋值
|
|
|
throw std::runtime_error(FormatError("irgen", "赋值语句暂未实现"));
|
|
|
}
|