コード例 #1
0
ファイル: core.py プロジェクト: zzhgithub/mal
def first(args: List[MalExpression]) -> MalExpression:
    try:
        if isinstance(args[0], MalNil):
            return MalNil()
        return args[0].native()[0]
    except IndexError:
        return MalNil()
    except TypeError:
        raise MalInvalidArgumentException(args[0], "not a list")
コード例 #2
0
ファイル: core.py プロジェクト: zzhgithub/mal
def get(map: MalExpression, key: MalExpression) -> MalExpression:
    if isinstance(map, MalNil):
        return MalNil()
    if not isinstance(map, MalHash_map):
        raise MalInvalidArgumentException(map, "not a hash map")
    if key.native() in map.native():
        return map.native()[key.native()]
    else:
        return MalNil()
コード例 #3
0
ファイル: core.py プロジェクト: zzhgithub/mal
def vals(args: List[MalExpression]) -> MalExpression:
    if len(args) != 1:
        raise MalInvalidArgumentException(
            MalNil(), "vals requires exactly one argument")
    if not isinstance(args[0], MalHash_map):
        raise MalInvalidArgumentException(args[0], "not a hash map")
    return MalList([args[0].native()[x] for x in args[0].native()])
コード例 #4
0
ファイル: core.py プロジェクト: zzhgithub/mal
def readline(arg: MalExpression) -> Union[MalString, MalNil]:
    try:
        assert isinstance(arg, MalString)
        line = input(arg.native())
    except EOFError:
        return MalNil()
    return MalString(line)
コード例 #5
0
ファイル: core.py プロジェクト: zzhgithub/mal
def keys(args: List[MalExpression]) -> MalExpression:
    if len(args) != 1:
        raise MalInvalidArgumentException(
            MalNil(), "keys requires exactly one argument")
    if not isinstance(args[0], MalHash_map):
        raise MalInvalidArgumentException(args[0], "not a hash map")
    return MalList(
        [MalString(x, is_already_encoded=True) for x in args[0].native()])
コード例 #6
0
ファイル: core.py プロジェクト: zzhgithub/mal
def contains_q(args: List[MalExpression]) -> MalExpression:
    if len(args) < 2:
        raise MalInvalidArgumentException(MalNil(),
                                          "contains? requires two arguments")
    if not isinstance(args[0], MalHash_map):
        raise MalInvalidArgumentException(args[0], "not a hash-map")
    if not isinstance(args[1], MalString):
        return MalBoolean(False)
    return MalBoolean(args[1].native() in args[0].native())
コード例 #7
0
def EVAL(ast: MalExpression, env: Env) -> MalExpression:
    # print("EVAL: " + str(ast))
    if not isinstance(ast, MalList):
        return eval_ast(ast, env)
    if len(ast.native()) == 0:
        return ast
    first = str(ast.native()[0])
    rest = ast.native()[1:]
    if first == "def!":
        key = str(ast.native()[1])
        value = EVAL(ast.native()[2], env)
        return env.set(key, value)
    if first == "let*":
        assert len(rest) == 2
        let_env = Env(env)
        bindings = rest[0]
        assert isinstance(bindings, MalList) or isinstance(bindings, MalVector)
        bindings_list = bindings.native()
        assert len(bindings_list) % 2 == 0
        for i in range(0, len(bindings_list), 2):
            assert isinstance(bindings_list[i], MalSymbol)
            assert isinstance(bindings_list[i + 1], MalExpression)
            let_env.set(str(bindings_list[i]), EVAL(bindings_list[i + 1], let_env))
        expr = rest[1]
        return EVAL(expr, let_env)
    if first == "do":
        for x in range(0, len(rest) - 1):
            EVAL(rest[x], env)
        return EVAL(rest[len(rest) - 1], env)
    if first == "if":
        condition = EVAL(rest[0], env)

        if isinstance(condition, MalNil) or (
            isinstance(condition, MalBoolean) and condition.native() is False
        ):
            if len(rest) >= 3:
                return EVAL(rest[2], env)
            else:
                return MalNil()
        else:
            return EVAL(rest[1], env)
    if first == "fn*":

        def func_body(x):
            func_env = Env(outer=env, binds=rest[0].native(), exprs=x)
            return EVAL(rest[1], func_env)

        return MalFunctionCompiled(func_body)

    evaled_ast = eval_ast(ast, env)
    f = evaled_ast.native()[0]
    args = evaled_ast.native()[1:]
    try:
        return f.call(args)
    except AttributeError:
        raise MalInvalidArgumentException(f, "attribute error")
コード例 #8
0
ファイル: core.py プロジェクト: zzhgithub/mal
def assoc(args: List[MalExpression]) -> MalExpression:
    if len(args) == 0:
        raise MalInvalidArgumentException(MalNil(),
                                          "no arguments supplied to assoc")
    elif len(args) == 1:
        return args[0]
    if not isinstance(args[0], MalHash_map):
        raise MalInvalidArgumentException(args[0], "not a hash map")
    dict_a_copy: Dict[str, MalExpression] = args[0].native().copy()
    dict_b: Dict[str, MalExpression] = hash_map(args[1:]).native()
    for key in dict_b:
        dict_a_copy[key] = dict_b[key]
    return MalHash_map(dict_a_copy)
コード例 #9
0
ファイル: core.py プロジェクト: zzhgithub/mal
def dissoc(args: List[MalExpression]) -> MalExpression:
    if len(args) == 0:
        raise MalInvalidArgumentException(MalNil(),
                                          "no arguments supplied to dissoc")
    elif len(args) == 1:
        return args[0]
    if not isinstance(args[0], MalHash_map):
        raise MalInvalidArgumentException(args[0], "not a hash map")
    dict_a_copy: Dict[str, MalExpression] = args[0].native().copy()
    list_b: List[MalExpression] = MalList(args[1:]).native()
    for key in list_b:
        try:
            del dict_a_copy[key.unreadable_str()]
        except KeyError:
            pass
    return MalHash_map(dict_a_copy)
コード例 #10
0
ファイル: step7_quote.py プロジェクト: asarhaddon/mal
def EVAL(ast: MalExpression, env: Env) -> MalExpression:
    while True:
        dbgeval = env.get("DEBUG-EVAL")
        if (dbgeval is not None and not isinstance(dbgeval, MalNil)
                and (not isinstance(dbgeval, MalBoolean) or dbgeval.native())):
            print("EVAL: " + str(ast))
        ast_native = ast.native()
        if isinstance(ast, MalSymbol):
            key = str(ast)
            val = env.get(key)
            if val is None: raise MalUnknownSymbolException(key)
            return val
        if isinstance(ast, MalVector):
            return MalVector([EVAL(x, env) for x in ast_native])
        if isinstance(ast, MalHash_map):
            new_dict = {}  # type: Dict[str, MalExpression]
            for key in ast_native:
                new_dict[key] = EVAL(ast_native[key], env)
            return MalHash_map(new_dict)
        if not isinstance(ast, MalList):
            return ast
        elif len(ast_native) == 0:
            return ast

        first_str = str(ast_native[0])
        if first_str == "def!":
            name: str = str(ast_native[1])
            value: MalExpression = EVAL(ast_native[2], env)
            return env.set(name, value)
        elif first_str == "let*":
            assert len(ast_native) == 3
            let_env = Env(env)
            bindings: MalExpression = ast_native[1]
            assert isinstance(bindings, MalList) or isinstance(
                bindings, MalVector)
            bindings_list: List[MalExpression] = bindings.native()
            assert len(bindings_list) % 2 == 0
            for i in range(0, len(bindings_list), 2):
                assert isinstance(bindings_list[i], MalSymbol)
                assert isinstance(bindings_list[i + 1], MalExpression)
                let_env.set(str(bindings_list[i]),
                            EVAL(bindings_list[i + 1], let_env))
            env = let_env
            ast = ast_native[2]
            continue
        elif first_str == "do":
            for x in range(1, len(ast_native) - 1):
                EVAL(ast_native[x], env)
            ast = ast_native[len(ast_native) - 1]
            continue
        elif first_str == "if":
            condition = EVAL(ast_native[1], env)

            if isinstance(condition,
                          MalNil) or (isinstance(condition, MalBoolean)
                                      and condition.native() is False):
                if len(ast_native) >= 4:
                    ast = ast_native[3]
                    continue
                else:
                    return MalNil()
            else:
                ast = ast_native[2]
                continue
        elif first_str == "fn*":
            raw_ast = ast_native[2]
            raw_params = ast_native[1]

            def fn(args: List[MalExpression]) -> MalExpression:
                f_ast = raw_ast
                f_env = Env(outer=env, binds=raw_params.native(), exprs=args)
                return EVAL(f_ast, f_env)

            return MalFunctionRaw(fn=fn,
                                  ast=raw_ast,
                                  params=raw_params,
                                  env=env)
        elif first_str == "quote":
            return (MalList(ast_native[1].native()) if isinstance(
                ast_native[1], MalVector) else ast_native[1])
        elif first_str == "quasiquote":
            ast = quasiquote(ast_native[1])
            continue
        else:
            f, *args = (EVAL(form, env) for form in ast_native)
            if isinstance(f, MalFunctionRaw):
                ast = f.ast()

                env = Env(
                    outer=f.env(),
                    binds=f.params().native(),
                    exprs=args,
                )
                continue
            elif isinstance(f, MalFunctionCompiled):
                return f.call(args)
            else:
                raise MalInvalidArgumentException(f, "not a function")
コード例 #11
0
def EVAL(ast: MalExpression, env: Env) -> MalExpression:
    while True:
        ast = macroexpand(ast, env)
        ast_native = ast.native()
        if not isinstance(ast, MalList):
            return eval_ast(ast, env)
        elif len(ast_native) == 0:
            return ast

        first_str = str(ast_native[0])
        if first_str == "macroexpand":
            return macroexpand(ast.native()[1], env)
        elif first_str == "def!":
            name: str = str(ast_native[1])
            value: MalExpression = EVAL(ast_native[2], env)
            return env.set(name, value)
        if first_str == "defmacro!":
            name = str(ast_native[1])
            value = EVAL(ast_native[2], env)
            assert isinstance(value, MalFunctionCompiled) or isinstance(
                value, MalFunctionRaw)
            value.make_macro()
            return env.set(name, value)
        elif first_str == "let*":
            assert len(ast_native) == 3
            let_env = Env(env)
            bindings: MalExpression = ast_native[1]
            assert isinstance(bindings, MalList) or isinstance(
                bindings, MalVector)
            bindings_list: List[MalExpression] = bindings.native()
            assert len(bindings_list) % 2 == 0
            for i in range(0, len(bindings_list), 2):
                assert isinstance(bindings_list[i], MalSymbol)
                assert isinstance(bindings_list[i + 1], MalExpression)
                let_env.set(str(bindings_list[i]),
                            EVAL(bindings_list[i + 1], let_env))
            env = let_env
            ast = ast_native[2]
            continue
        elif first_str == "do":
            for x in range(1, len(ast_native) - 1):
                EVAL(ast_native[x], env)
            ast = ast_native[len(ast_native) - 1]
            continue
        elif first_str == "if":
            condition = EVAL(ast_native[1], env)

            if isinstance(condition,
                          MalNil) or (isinstance(condition, MalBoolean)
                                      and condition.native() is False):
                if len(ast_native) >= 4:
                    ast = ast_native[3]
                    continue
                else:
                    return MalNil()
            else:
                ast = ast_native[2]
                continue
        elif first_str == "fn*":
            raw_ast = ast_native[2]
            raw_params = ast_native[1]

            def fn(args: List[MalExpression]) -> MalExpression:
                f_ast = raw_ast
                f_env = Env(outer=env, binds=raw_params.native(), exprs=args)
                return EVAL(f_ast, f_env)

            return MalFunctionRaw(fn=fn,
                                  ast=raw_ast,
                                  params=raw_params,
                                  env=env)
        elif first_str == "quote":
            return (MalList(ast_native[1].native()) if isinstance(
                ast_native[1], MalVector) else ast_native[1])
        elif first_str == "quasiquote":
            ast = quasiquote(ast_native[1])
            continue
        elif first_str == "try*":
            try:
                return EVAL(ast_native[1], env)
            except MalException as e:
                if len(ast_native) < 3:
                    raise e
                catch_block = ast_native[2]
                assert (isinstance(catch_block, MalList)
                        and isinstance(catch_block.native()[0], MalSymbol)
                        and str(catch_block.native()[0]) == "catch*"
                        and len(catch_block.native()) == 3)
                exception_symbol = catch_block.native()[1]
                assert isinstance(exception_symbol, MalSymbol)
                env = Env(env)
                env.set(str(exception_symbol), e.native())
                ast = catch_block.native()[2]
                continue
        else:
            evaled_ast = eval_ast(ast, env)
            f = evaled_ast.native()[0]
            args = evaled_ast.native()[1:]
            if isinstance(f, MalFunctionRaw):
                ast = f.ast()

                env = Env(
                    outer=f.env(),
                    binds=f.params().native(),
                    exprs=evaled_ast.native()[1:],
                )
                continue
            elif isinstance(f, MalFunctionCompiled):
                return f.call(args)
            else:
                raise MalInvalidArgumentException(f, "not a function")
コード例 #12
0
ファイル: core.py プロジェクト: zzhgithub/mal
def println(args: List[MalExpression]) -> MalNil:
    result_string = " ".join(map(lambda x: x.unreadable_str(), args))
    print(result_string)
    return MalNil()
コード例 #13
0
def EVAL(ast: MalExpression, env: Env) -> MalExpression:
    dbgeval = env.get("DEBUG-EVAL")
    if (dbgeval is not None and not isinstance(dbgeval, MalNil)
            and (not isinstance(dbgeval, MalBoolean) or dbgeval.native())):
        print("EVAL: " + str(ast))
    if isinstance(ast, MalSymbol):
        key = str(ast)
        val = env.get(key)
        if val is None: raise MalUnknownSymbolException(key)
        return val
    if isinstance(ast, MalVector):
        return MalVector([EVAL(x, env) for x in ast.native()])
    if isinstance(ast, MalHash_map):
        new_dict = {}  # type: Dict[str, MalExpression]
        for key in ast.native():
            new_dict[key] = EVAL(ast.native()[key], env)
        return MalHash_map(new_dict)
    if not isinstance(ast, MalList):
        return ast
    if len(ast.native()) == 0:
        return ast
    first = str(ast.native()[0])
    rest = ast.native()[1:]
    if first == "def!":
        key = str(ast.native()[1])
        value = EVAL(ast.native()[2], env)
        return env.set(key, value)
    if first == "let*":
        assert len(rest) == 2
        let_env = Env(env)
        bindings = rest[0]
        assert isinstance(bindings, MalList) or isinstance(bindings, MalVector)
        bindings_list = bindings.native()
        assert len(bindings_list) % 2 == 0
        for i in range(0, len(bindings_list), 2):
            assert isinstance(bindings_list[i], MalSymbol)
            assert isinstance(bindings_list[i + 1], MalExpression)
            let_env.set(str(bindings_list[i]),
                        EVAL(bindings_list[i + 1], let_env))
        expr = rest[1]
        return EVAL(expr, let_env)
    if first == "do":
        for x in range(0, len(rest) - 1):
            EVAL(rest[x], env)
        return EVAL(rest[len(rest) - 1], env)
    if first == "if":
        condition = EVAL(rest[0], env)

        if isinstance(condition, MalNil) or (isinstance(condition, MalBoolean)
                                             and condition.native() is False):
            if len(rest) >= 3:
                return EVAL(rest[2], env)
            else:
                return MalNil()
        else:
            return EVAL(rest[1], env)
    if first == "fn*":

        def func_body(x):
            func_env = Env(outer=env, binds=rest[0].native(), exprs=x)
            return EVAL(rest[1], func_env)

        return MalFunctionCompiled(func_body)

    f, *args = (EVAL(form, env) for form in ast.native())
    try:
        return f.call(args)
    except AttributeError:
        raise MalInvalidArgumentException(f, "attribute error")
コード例 #14
0
 def visit_mNil(self, node, children) -> MalNil:
     return MalNil()