working scopes

This commit is contained in:
uan
2026-02-04 08:45:05 +01:00
parent 969de6a59b
commit 52c92386d7
2 changed files with 19 additions and 9 deletions

View File

@@ -260,7 +260,7 @@ fn (mut p Parser) parse_statement() Stmt {
.kw_let {return p.parse_var_decl()} .kw_let {return p.parse_var_decl()}
.kw_return {return p.parse_return_stmt()} .kw_return {return p.parse_return_stmt()}
.kw_fn {return p.parse_func_decl()} .kw_fn {return p.parse_func_decl()}
.lbracket {return p.parse_block()} .lbracket {return p.parse_block(false)}
else {return p.parse_expr_stmt()} else {return p.parse_expr_stmt()}
} }
} }
@@ -275,7 +275,7 @@ fn (mut p Parser) parse_var_decl() VarDecl {
type_tok := p.next() type_tok := p.next()
if type_tok.type != .type { if type_tok.type != .type {
parse_error("Expected variable type after name") parse_error("Expected variable type after name when declaring ${name_tok.text}")
} }
p.expect(.equals) p.expect(.equals)
@@ -306,18 +306,21 @@ fn (mut p Parser) parse_func_decl() FuncDecl {
name_tok := p.next() name_tok := p.next()
if name_tok.type != .identifier { if name_tok.type != .identifier {
parse_error("Expected variable name after let") parse_error("Expected function name after let")
} }
p.expect(.lparen) p.expect(.lparen)
p.expect(.rparen) p.expect(.rparen)
p.dump_token()
type_tok := p.next() type_tok := p.next()
if type_tok.type != .type { if type_tok.type != .type {
parse_error("Expected variable type after name") parse_error("Expected function return type after name when declaring ${name_tok.text}")
} }
block := p.parse_block() p.symbols.variable_scopes << map[string]VarSymbolInfo{}
block := p.parse_block(true)
return_stmts := p.get_return_stmts_recursive(block) return_stmts := p.get_return_stmts_recursive(block)
@@ -328,6 +331,8 @@ fn (mut p Parser) parse_func_decl() FuncDecl {
} }
} }
p.symbols.variable_scopes.delete_last()
p.symbols.define_func(name_tok.text, type_tok.text) p.symbols.define_func(name_tok.text, type_tok.text)
return FuncDecl { return FuncDecl {
@@ -369,12 +374,15 @@ fn (mut p Parser) parse_expr_stmt() ExprStmt {
} }
} }
fn (mut p Parser) parse_block() Block { fn (mut p Parser) parse_block(no_scope bool) Block {
p.expect(.lbracket) p.expect(.lbracket)
mut statements := []Stmt{} mut statements := []Stmt{}
if !no_scope {
p.symbols.variable_scopes << map[string]VarSymbolInfo{} p.symbols.variable_scopes << map[string]VarSymbolInfo{}
}
$if debug { $if debug {
println("entering scope") println("entering scope")
} }
@@ -391,7 +399,9 @@ fn (mut p Parser) parse_block() Block {
parse_error("Unexpected use of return. Unreachable code") parse_error("Unexpected use of return. Unreachable code")
} }
if !no_scope {
p.symbols.variable_scopes.delete_last() p.symbols.variable_scopes.delete_last()
}
$if debug { $if debug {
println("exiting scope") println("exiting scope")

View File

@@ -4,6 +4,6 @@ fn foo() int {
return y; return y;
} }
fn bar() float { fn bar() real {
return 5.5; return 5.5;
} }