aboutsummaryrefslogtreecommitdiff
path: root/runner.py
blob: 0d8560e208c6658f9a907bdc5adda9dc18bc34a2 (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
from tokens import *
from std import STD


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[list(this_func.keys())[0]].impl) # TODO show all
    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]

        # evaluate inner expressions
        for idx, arg in enumerate(nxt.args):
            if isinstance(arg, NebExpression):
                nxt.args[idx] = evaluate([arg], pop)

        if nxt.maybe_sig() not in this_func:
            raise Exception(f"'{nxt.symbol.name}' called with unknown signature: '{nxt.maybe_sig()}'")
        ret = this_func[nxt.maybe_sig()].impl(*(nxt.args))
        return evaluate(items[1:], ret)
    else:
        raise Exception("expected a literal or an expression")