Typecheck break and continue correctly

This commit is contained in:
Sofia 2026-04-30 20:09:32 +03:00
parent 9f3f64e6bd
commit ddea133138
3 changed files with 16 additions and 2 deletions

View File

@ -646,6 +646,7 @@ namespace AST {
new types::FundamentalType{ false, types::FundamentalTypeKind::Bool } };
typecheck::Scope inner_scope{ scope };
inner_scope.loop_depth += 1;
if (this->m_init)
(*this->m_init)->typecheck(state, inner_scope);
@ -674,6 +675,7 @@ namespace AST {
new types::FundamentalType{ false, types::FundamentalTypeKind::Bool } };
typecheck::Scope inner_scope{ scope };
inner_scope.loop_depth += 1;
if (this->m_cond) {
auto cond_ty = (*this->m_cond)->typecheck(state, inner_scope, bool_ty).type;
@ -700,10 +702,18 @@ namespace AST {
}
void BreakStatement::typecheck_preprocess(typecheck::Scope&) {}
void BreakStatement::typecheck(typecheck::State&, typecheck::Scope&) {}
void BreakStatement::typecheck(typecheck::State& state, typecheck::Scope& scope) {
if (scope.loop_depth <= 0) {
state.errors.push_back(CompileError("Can not use break outside of a loop", this->m_meta));
}
}
void ContinueStatement::typecheck_preprocess(typecheck::Scope&) {}
void ContinueStatement::typecheck(typecheck::State&, typecheck::Scope&) {}
void ContinueStatement::typecheck(typecheck::State& state, typecheck::Scope& scope) {
if (scope.loop_depth <= 0) {
state.errors.push_back(CompileError("Can not use continue outside of a loop", this->m_meta));
}
}
void Function::typecheck_preprocess(typecheck::Scope& scope) {
this->m_return_ty = refresh_type(scope, this->m_return_ty);

View File

@ -13,6 +13,7 @@ namespace typecheck {
std::map<std::string, std::shared_ptr<types::Type>> symbols;
std::map<std::string, std::shared_ptr<types::Type>> structs;
std::optional<std::shared_ptr<types::Type>> return_ty;
int loop_depth;
};
struct State {

3
test.c
View File

@ -63,6 +63,9 @@ int main() {
printf("for-counter: %d\n", counter);
}
continue;
break;
// Test while-loops
int counter = 0;
while (1) {