From 77f79dcbaff84912a60c850c32d1d72ee0277319 Mon Sep 17 00:00:00 2001 From: Lixuanwang Date: Fri, 30 May 2025 01:34:47 +0800 Subject: [PATCH] merging, fixed some bugs --- src/LLVMIRGenerator.cpp | 34 +++++++++++++++------------------- 1 file changed, 15 insertions(+), 19 deletions(-) diff --git a/src/LLVMIRGenerator.cpp b/src/LLVMIRGenerator.cpp index 7c1419d..51eaa07 100644 --- a/src/LLVMIRGenerator.cpp +++ b/src/LLVMIRGenerator.cpp @@ -219,13 +219,9 @@ std::any LLVMIRGenerator::visitBlockStmt(SysYParser::BlockStmtContext* ctx) { } std::any LLVMIRGenerator::visitAssignStmt(SysYParser::AssignStmtContext *ctx) { - irStream << "|||Start "; std::string lhsAlloca = std::any_cast(ctx->lValue()->accept(this)); - irStream << "End||| \n"; std::string lhsType = symbolTable[ctx->lValue()->Ident()->getText()].second; - irStream << "[[[Start "; std::string rhs = std::any_cast(ctx->exp()->accept(this)); - irStream << "End]]] \n"; if (lhsType == "float") { try { @@ -422,18 +418,10 @@ std::any LLVMIRGenerator::visitLValue(SysYParser::LValueContext* ctx) { std::any LLVMIRGenerator::visitPrimExp(SysYParser::PrimExpContext *ctx){ - std::cout << "Type name: " << typeid(*ctx).name() << std::endl; - irStream << " PrimExp "; - if (auto *lvalCtx = dynamic_cast(ctx)) { - // 是 LValContext,可以安全地调用 lValue() - return visit(lvalCtx->lValue()); - } - return visitChildren(ctx); -} - -std::any LLVMIRGenerator::visitPrimaryExp(SysYParser::PrimaryExpContext* ctx) { - irStream << " Primaryexp \n"; - if (auto *lvalCtx = dynamic_cast(ctx)) { + // irStream << "visitPrimExp\n"; + // std::cout << "Type name: " << typeid(*(ctx->primaryExp())).name() << std::endl; + SysYParser::PrimaryExpContext* pExpCtx = ctx->primaryExp(); + if (auto* lvalCtx = dynamic_cast(pExpCtx)) { std::string allocaPtr = std::any_cast(lvalCtx->lValue()->accept(this)); std::string varName = lvalCtx->lValue()->Ident()->getText(); std::string type = symbolTable[varName].second; @@ -441,11 +429,19 @@ std::any LLVMIRGenerator::visitPrimaryExp(SysYParser::PrimaryExpContext* ctx) { irStream << " " << temp << " = load " << type << ", " << type << "* " << allocaPtr << ", align 4\n"; tmpTable[temp] = type; return temp; - } else if (auto *numCtx = dynamic_cast(ctx)) { - return numCtx->number()->accept(this); - } else if (auto *strCtx = dynamic_cast(ctx)) { + } else if (auto* expCtx = dynamic_cast(pExpCtx)) { + return expCtx->exp()->accept(this); + } else if (auto* strCtx = dynamic_cast(pExpCtx)) { return strCtx->string()->accept(this); + } else if (auto* numCtx = dynamic_cast(pExpCtx)) { + return numCtx->number()->accept(this); + } else { + // 没有成功转换,说明 ctx->primaryExp() 不是 NumContext 或其他已知类型 + // 可能是其他类型的表达式,或者是一个空的 PrimaryExpContext + std::cout << "Unknown primary expression type." << std::endl; + throw std::runtime_error("Unknown primary expression type."); } + // return visitChildren(ctx); } std::any LLVMIRGenerator::visitParenExp(SysYParser::ParenExpContext* ctx) {