aboutsummaryrefslogtreecommitdiff
path: root/runner.py
blob: a2c7e998024a884180f53e5734fe51bfe2b7a2d3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
from tokens import *

def std_print(arg):
    print(arg.value)
    #return []  # TODO this should return empty list
    return NebLiteral(NebType.BOOL, True)

std = {
    "print": {
        "func": NebFunction("print", [NebType.STRING], NebType.BOOL),
        "impl": std_print }
    }

def peek(inp):
    if len(inp) == 0:
        return None
    return inp[0]

def evaluate(items, pop):
    nxt = peek(items)
    if nxt is None:
        return pop
    elif isinstance(nxt, NebLiteral):
        pop = nxt.value
        return evaluate(items[1:], pop)
    elif isinstance(nxt, NebSymbol):
        if not nxt.name in std:
            raise Exception(f"no such symbol: '{nxt.name}'")
        this_func = std[nxt.name]
        return evaluate(items[1:], this_func["impl"])
    elif isinstance(nxt, NebExpression):
        if not nxt.symbol.name in std:
            raise Exception(f"no such symbol: {nxt.symbol.name}")
        this_func = std[nxt.symbol.name]
        #expected_sig = " ".join(x.type_.name for x in nxt.args)
        #if this_func["func"].in_sig() != expected_sig:
        if this_func["func"].in_sig() != nxt.maybe_sig():
            raise Exception(f"{nxt.symbol.name} expects '{this_func['func'].in_sig()}', got '{nxt.maybe_sig()}'")
        ret = this_func["impl"](*(nxt.args))
        return evaluate(items[1:], ret)
    else:
        raise Exception("expected a literal or an expression")