From ddea1331386dbd820aafd78b448165f4ed457750 Mon Sep 17 00:00:00 2001 From: Sofia Date: Thu, 30 Apr 2026 20:09:32 +0300 Subject: [PATCH] Typecheck break and continue correctly --- src/typechecker.cpp | 14 ++++++++++++-- src/typechecker.h | 1 + test.c | 3 +++ 3 files changed, 16 insertions(+), 2 deletions(-) diff --git a/src/typechecker.cpp b/src/typechecker.cpp index e1891fd..d04f7ce 100644 --- a/src/typechecker.cpp +++ b/src/typechecker.cpp @@ -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); diff --git a/src/typechecker.h b/src/typechecker.h index 9701577..1f6b24f 100644 --- a/src/typechecker.h +++ b/src/typechecker.h @@ -13,6 +13,7 @@ namespace typecheck { std::map> symbols; std::map> structs; std::optional> return_ty; + int loop_depth; }; struct State { diff --git a/test.c b/test.c index 360eae8..879a531 100644 --- a/test.c +++ b/test.c @@ -63,6 +63,9 @@ int main() { printf("for-counter: %d\n", counter); } + continue; + break; + // Test while-loops int counter = 0; while (1) {