From a072842248fe7324574bc7733a8c4255af56c855 Mon Sep 17 00:00:00 2001 From: mryouse Date: Thu, 16 Jun 2022 04:09:26 +0000 Subject: refactor: take type hints from user in function args --- interpreter.py | 26 ++++++++++++++++++++++---- 1 file changed, 22 insertions(+), 4 deletions(-) (limited to 'interpreter.py') diff --git a/interpreter.py b/interpreter.py index 7f28c63..e66deab 100644 --- a/interpreter.py +++ b/interpreter.py @@ -2,6 +2,7 @@ from structs import * from exceptions import * from lexer import lex from parser import parse +from typeclass import TypeEnum, is_subtype_of from pathlib import Path from glob import glob from collections import namedtuple @@ -99,8 +100,26 @@ class UserFunction(Function): def __init__(self, name, params, body): # TODO this doesn't do type checking, or optional, or lazy - args = [Arg(p.name, TypeEnum.ANY, False, False) for p in params] - super().__init__(name, params, body, args) + newparams, args = self.process_params(name, params) + super().__init__(name, newparams, body, args) + + def process_params(self, name, params): + newparams = [] + args = [] + prev_type = False + first = True + for param in params: + if isinstance(param, Symbol): + newparams.append(param) + args.append(Arg(param.name, TypeEnum.ANY, False, False)) + prev_type = False + elif isinstance(param, Type) and not prev_type and not first: + args[-1].type_ = TypeEnum.__getattr__(param.name[1:].upper()) + prev_type = True + else: + raise NebPanic("invalid :func signature", param) + first = False + return newparams, args def call(self, expr, env, ns): self.arity_check(expr.args[0], expr.args[1:]) @@ -108,7 +127,6 @@ class UserFunction(Function): this_env = Environment(env) for idx, param in enumerate(self.params): this_env.register(param.name, evaluated_args[idx]) - #return interpret(self.body, this_env, ns) return interpret(self.body, env=this_env, ns=ns) class Environment: @@ -159,7 +177,7 @@ def interpret(exprs, *, env=GLOBALS, ns=None): return ret def evaluate(expr, env, ns=None): - if isinstance(expr, Literal) or isinstance(expr, Function): + if isinstance(expr, Literal) or isinstance(expr, Function) or isinstance(expr, Type): #return expr.value return expr elif isinstance(expr, Symbol): -- cgit v1.2.3