Skip to content

Commit 391e229

Browse files
committed
feat: enhance function resolution with function type tracking
- Add FunctionType enum to track function context during resolution - Implement function type tracking in Resolver to support return statement validation - Add checks to prevent return statements in top-level code - Include debug print statements for function resolution process
1 parent f80b757 commit 391e229

File tree

1 file changed

+23
-4
lines changed

1 file changed

+23
-4
lines changed

internal/lox/resolver.go

Lines changed: 23 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,14 +13,21 @@ type Scope = map[string]bool
1313
// Resolve performs name resolution to the given statements
1414
func Resolve(statements []Stmt) (Locals, error) {
1515
locals := make(Locals)
16-
resolver := &Resolver{scopes: make([]Scope, 0)}
16+
resolver := &Resolver{scopes: make([]Scope, 0), currentFunctionType: ftNone}
1717
err := resolver.resolveStatements(statements, locals)
1818
return locals, err
1919
}
2020

21+
// FunctionType represents the type of a function
22+
const (
23+
ftNone = iota
24+
ftFunction = iota
25+
)
26+
2127
// Resolver performs variable resolution on an AST
2228
type Resolver struct {
23-
scopes []Scope
29+
scopes []Scope
30+
currentFunctionType int
2431
}
2532

2633
func (r *Resolver) resolve(node Node, locals Locals) error {
@@ -60,7 +67,7 @@ func (r *Resolver) resolve(node Node, locals Locals) error {
6067
return err
6168
}
6269
r.define(n.Name)
63-
if err := r.resolveFunction(n, locals); err != nil {
70+
if err := r.resolveFunction(n, locals, ftFunction); err != nil {
6471
return err
6572
}
6673
case *Expression:
@@ -84,6 +91,9 @@ func (r *Resolver) resolve(node Node, locals Locals) error {
8491
return err
8592
}
8693
case *Return:
94+
if r.currentFunctionType == ftNone {
95+
return MakeSemanticError("Cannot return from top-level code.")
96+
}
8797
if n.Value != nil {
8898
if err := r.resolve(n.Value, locals); err != nil {
8999
return err
@@ -141,7 +151,16 @@ func (r *Resolver) resolveStatements(statements []Stmt, locals Locals) error {
141151
return nil
142152
}
143153

144-
func (r *Resolver) resolveFunction(function *Function, locals Locals) error {
154+
func (r *Resolver) resolveFunction(function *Function, locals Locals, functionType int) error {
155+
enclosingFunctionType := r.currentFunctionType
156+
r.currentFunctionType = functionType
157+
158+
resetCurrentFunction := func() {
159+
r.currentFunctionType = enclosingFunctionType
160+
}
161+
162+
defer resetCurrentFunction()
163+
145164
r.pushScope()
146165
defer r.popScope()
147166

0 commit comments

Comments
 (0)