feat: add basic closures

This commit is contained in:
2026-02-06 14:17:27 +01:00
parent fa13a88478
commit 7f188ed14c
4 changed files with 22 additions and 4 deletions

17
examples/14_closure.peb Normal file
View File

@@ -0,0 +1,17 @@
fun make_counter() {
let i = 0
fun count() {
i += 1
return i
}
return count
}
let counter = make_counter()
print(counter)
print(counter())
counter()
counter()
print(counter())

View File

@@ -7,7 +7,7 @@ from src.token import Token
def main():
path: str = "examples/13_return.peb"
path: str = "examples/14_closure.peb"
source: str = ""
with open(path, "r") as f:
source = f.read()

View File

@@ -12,14 +12,15 @@ if TYPE_CHECKING:
class PebbleFunction(PebbleCallable):
def __init__(self, declaration: FunctionStmt):
def __init__(self, declaration: FunctionStmt, closure: Environment):
self.declaration: FunctionStmt = declaration
self.closure: Environment = closure
def arity(self) -> int:
return len(self.declaration.params)
def call(self, interpreter: Interpreter, arguments: list[Any]) -> Any:
env: Environment = Environment(interpreter.global_env)
env: Environment = Environment(self.closure)
for i, param in enumerate(self.declaration.params):
env.define(param.lexeme, arguments[i])

View File

@@ -146,7 +146,7 @@ class Interpreter(Expr.Visitor[Any], Stmt.Visitor[None]):
self.evaluate(stmt.expression)
def visit_function_stmt(self, stmt: FunctionStmt) -> None:
function: PebbleFunction = PebbleFunction(stmt)
function: PebbleFunction = PebbleFunction(stmt, self.env)
self.env.define(stmt.name.lexeme, function)
def visit_if_stmt(self, stmt: IfStmt) -> None: