-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinterpreter.py
More file actions
99 lines (95 loc) · 3.2 KB
/
interpreter.py
File metadata and controls
99 lines (95 loc) · 3.2 KB
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# imports
import sys
from collections import defaultdict
import math
# vars
tape = defaultdict()
lang_globals = [] # named lang_globals due to python's `globals`
functions = []
current_function = -1
code = []
def parse(toks,line):
global current_function
global code
if toks[0] == "declare":
toks.reverse()
toks.pop()
name = toks.pop()
identifier = toks.pop()
functions.append({"identifier":identifier.replace("f:",""),"name":name,"code":[]})
elif toks[0].startswith("@"):
# @main(args) do
parts = toks[0].replace("@","").split("(") # [main,args)]
parts[1] = parts[1].replace(")","")
for i in functions:
if i["identifier"] == parts[0]:
current_function = functions.index(i)
elif toks[0] == "end":
functions[current_function]["code"] = code
current_function = -1
if current_function != -1 and not toks[0].startswith("@"):
code.append(line.replace(" ","",1))
def execute(code):
stack = []
for line in code:
if line.startswith("#"):
continue
toks = line.split()
for tok in toks:
if tok.isdigit(): stack.append(int(tok))
else:
match tok:
case "set":
loc = stack.pop()
temp = stack.pop()
tape[loc] = temp
case "get":
loc = stack.pop()
temp = tape[loc]
stack.append(temp)
case "out":
print(stack.pop())
case "copy":
temp = stack.pop()
stack.append(temp)
stack.append(temp)
case "add":
a = stack.pop()
b = stack.pop()
stack.append(a+b)
case "sub":
a = stack.pop()
b = stack.pop()
stack.append(b-a)
case "mul":
a = stack.pop()
b = stack.pop()
stack.append(a*b)
case "div":
a = stack.pop()
b = stack.pop()
stack.append(b/a)
case "floor":
temp = stack.pop()
stack.append(math.floor(temp))
case "ceil":
temp = stack.pop()
stack.append(math.ceil(temp))
case "exp":
a = stack.pop()
b = stack.pop()
stack.append(math.pow(a,b))
case _:
stack.append(toks[0])
def getfunctions(code):
lines = code.split("\n")
for line in lines:
if line.startswith("#"):
continue
toks = line.split()
if len(toks) > 0: parse(toks,line)
getfunctions(open(sys.argv[1],"r").read())
for i in functions:
print(i)
if i["name"] == "Main":
execute(i["code"])