-
Notifications
You must be signed in to change notification settings - Fork 4
/
interpreter.py
55 lines (40 loc) · 1.71 KB
/
interpreter.py
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
44
45
46
47
48
49
50
51
52
53
54
55
from typing import Any
from structure import structure
from tokenizer import tokenize
from parse import parse
from context import Context
from unpack import unpack
class Interprete:
def main(self, tokens: list[Any], ctx):
if len(tokens) == 1 and not callable(tokens[0]):
# If tokens is a single literal wrapped in a list, the interpreter will crash
# So if tokens[0] is a literal, then unwrap it
tokens = tokens[0]
self.output = []
main_output = self.interprete(tokens, ctx)
self.output.insert(0, main_output) if main_output != None else None
return self.output
def interprete(self, tokens: list[Any], ctx) -> Any:
if type(tokens) is list: # If tokens are grouped
if type(tokens[0]) is list: # If the func part actually is a list
# then there are more tokens in the stack to be outputted
# Example: "+2 3 4"
for token in tokens:
output = self.interprete(token, ctx=ctx)
self.output.append(output)
else:
func = tokens[0]
# Exit if func does not exist
if not func:
return [None]
args = [] # Interprete every argument, recursive case
for token in tokens[1:]:
args.append(self.interprete(token, ctx=ctx))
args.append(ctx)
# Call func on every interpreted argument
output = func(*list(args))
return output
else:
return tokens
def run(text, ctx=Context()):
return Interprete().main(parse(unpack(structure(tokenize(text)))), ctx)