feat: add basic closures
This commit is contained in:
17
examples/14_closure.peb
Normal file
17
examples/14_closure.peb
Normal 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())
|
||||||
2
main.py
2
main.py
@@ -7,7 +7,7 @@ from src.token import Token
|
|||||||
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
path: str = "examples/13_return.peb"
|
path: str = "examples/14_closure.peb"
|
||||||
source: str = ""
|
source: str = ""
|
||||||
with open(path, "r") as f:
|
with open(path, "r") as f:
|
||||||
source = f.read()
|
source = f.read()
|
||||||
|
|||||||
@@ -12,14 +12,15 @@ if TYPE_CHECKING:
|
|||||||
|
|
||||||
|
|
||||||
class PebbleFunction(PebbleCallable):
|
class PebbleFunction(PebbleCallable):
|
||||||
def __init__(self, declaration: FunctionStmt):
|
def __init__(self, declaration: FunctionStmt, closure: Environment):
|
||||||
self.declaration: FunctionStmt = declaration
|
self.declaration: FunctionStmt = declaration
|
||||||
|
self.closure: Environment = closure
|
||||||
|
|
||||||
def arity(self) -> int:
|
def arity(self) -> int:
|
||||||
return len(self.declaration.params)
|
return len(self.declaration.params)
|
||||||
|
|
||||||
def call(self, interpreter: Interpreter, arguments: list[Any]) -> Any:
|
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):
|
for i, param in enumerate(self.declaration.params):
|
||||||
env.define(param.lexeme, arguments[i])
|
env.define(param.lexeme, arguments[i])
|
||||||
|
|
||||||
|
|||||||
@@ -146,7 +146,7 @@ class Interpreter(Expr.Visitor[Any], Stmt.Visitor[None]):
|
|||||||
self.evaluate(stmt.expression)
|
self.evaluate(stmt.expression)
|
||||||
|
|
||||||
def visit_function_stmt(self, stmt: FunctionStmt) -> None:
|
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)
|
self.env.define(stmt.name.lexeme, function)
|
||||||
|
|
||||||
def visit_if_stmt(self, stmt: IfStmt) -> None:
|
def visit_if_stmt(self, stmt: IfStmt) -> None:
|
||||||
|
|||||||
Reference in New Issue
Block a user