Files
pebble/src/core/function.py

41 lines
1.2 KiB
Python

from __future__ import annotations
from enum import Enum, auto
from typing import Any, TYPE_CHECKING
from src.ast.stmt import FunctionStmt
from src.core.callable import PebbleCallable
from src.interpreter.environment import Environment
from src.interpreter.exceptions import ReturnException
if TYPE_CHECKING:
from src.interpreter.interpreter import Interpreter
class FunctionType(Enum):
NONE = auto()
FUNCTION = auto()
class PebbleFunction(PebbleCallable):
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(self.closure)
for i, param in enumerate(self.declaration.params):
env.define(param.lexeme, arguments[i])
try:
interpreter.execute_block(self.declaration.body, env)
except ReturnException as ret:
return ret.value
return None
def __str__(self):
return f"<function {self.declaration.name.lexeme}>"