[lab2]implemented while, break, continue

This commit is contained in:
ladev789
2025-04-01 17:50:17 +08:00
parent 9d619b11d7
commit 9f562aa0be
3 changed files with 71 additions and 3 deletions

View File

@@ -205,6 +205,38 @@ std::any SysYIRGenerator::visitStmt(SysYParser::StmtContext* ctx) {
irStream << " br label %" << mergeLabel << "\n";
irStream << mergeLabel << ":\n";
} else if (ctx->WHILE()) {
std::string loop_cond = "while.cond." + std::to_string(tempCounter);
std::string loop_body = "while.body." + std::to_string(tempCounter);
std::string loop_end = "while.end." + std::to_string(tempCounter++);
loopStack.push({loop_end, loop_cond});
irStream << " br label %" << loop_cond << "\n";
irStream << loop_cond << ":\n";
std::string cond = std::any_cast<std::string>(ctx->cond()->accept(this));
irStream << " br i1 " << cond << ", label %" << loop_body << ", label %" << loop_end << "\n";
irStream << loop_body << ":\n";
ctx->stmt(0)->accept(this);
irStream << " br label %" << loop_cond << "\n";
irStream << loop_end << ":\n";
loopStack.pop();
} else if (ctx->BREAK()) {
if (loopStack.empty()) {
throw std::runtime_error("Break statement outside of a loop.");
}
irStream << " br label %" << loopStack.top().breakLabel << "\n";
} else if (ctx->CONTINUE()) {
if (loopStack.empty()) {
throw std::runtime_error("Continue statement outside of a loop.");
}
irStream << " br label %" << loopStack.top().continueLabel << "\n";
} else if (ctx->blockStmt()) {
ctx->blockStmt()->accept(this);
} else if (ctx->exp()) {
ctx->exp()->accept(this);
}
return nullptr;
}
@@ -289,6 +321,7 @@ std::any SysYIRGenerator::visitMulExp(SysYParser::MulExpContext* ctx) {
irStream << " " << temp << " = srem " << type << " " << left << ", " << right << "\n";
}
left = temp;
tmpTable[temp] = type;
}
return left;
}
@@ -298,6 +331,7 @@ std::any SysYIRGenerator::visitAddExp(SysYParser::AddExpContext* ctx) {
std::string left = std::any_cast<std::string>(mulExps[0]->accept(this));
for (size_t i = 1; i < mulExps.size(); ++i) {
std::string right = std::any_cast<std::string>(mulExps[i]->accept(this));
irStream << "right is " << right << "\n";
std::string op = ctx->children[2*i-1]->getText();
std::string temp = getNextTemp();
std::string type = tmpTable[left];
@@ -307,6 +341,7 @@ std::any SysYIRGenerator::visitAddExp(SysYParser::AddExpContext* ctx) {
irStream << " " << temp << " = sub nsw " << type << " " << left << ", " << right << "\n";
}
left = temp;
tmpTable[temp] = type;
}
return left;
}