-
Notifications
You must be signed in to change notification settings - Fork 0
/
test.py
140 lines (133 loc) · 2.98 KB
/
test.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
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
from typing import List
from compiler import Add, Addr, Call, Compare, Context, Instrument, Nop, Read, Sub, Write, header
from optimizer import optimize
from yacc import parser
tests = [
# """main = do {
# write read;
# main
# }""",
# """main = do {
# a <- read;
# b <- read;
# if gt a b
# then write a
# else write b;
# main
# }"""
# """main = do {
# x <- read;
# y <- read;
# if lt x 0
# then if lt y 0
# then write (addr 4)
# else write (addr 5)
# else if gt y 0
# then write (addr 4)
# else write (addr 5);
# main
# }""",
# """main = do {
# x <- read;
# if gt x 0
# then print_dn x
# else print_up x;
# main
# }
# print_dn x
# | eq x 0 = write x
# | gt x 0 = do {
# write x;
# print_dn (sub x 1)
# }
# print_up x
# | eq x 0 = write x
# | lt x 0 = do {
# write x;
# print_up (add x 1)
# }""",
# """main = do {
# x <- read;
# if gt x 0
# then print_dn x
# else print_up x;
# main
# }
# print_dn x = if eq x 0
# then write x
# else do {
# write x;
# print_dn (sub x 1)
# }
# print_up x = if eq x 0
# then write x
# else do {
# write x;
# print_up (add x 1)
# }""",
# """main = do {
# write (mul read read (addr 9));
# main
# }
# mul a b acc
# | eq a 0 = addr 9
# | eq b 0 = addr 9
# | gt b 0 = mul a (sub b 1) (add acc a)""",
"""main = do {
fib (addr 9) (add (addr 9) 1) read;
main
}
fib a b x
| le b x = do {
write b;
fib b (add a b) x
}""",
# """main = do {
# write (addr read);
# main
# }
# """,
# """main = do {
# pt read;
# main
# }
# pt x = if neq (addr x) 0
# then do {
# write (addr x);
# pt (add x 1)
# }
# else nop
# """
]
def print_code(insts: List[Instrument]) -> None:
insts = '\n'.join(str(i) for i in insts)
print(f"{header}\n{insts}")
if __name__ == "__main__":
for test in tests:
print(test)
funcs = parser.parse(test)
entry = Call("main", [])
context = Context(
[
Addr(),
Write(),
Add(), Sub(),
Compare("gt", False, True, False),
Compare("ge", True, True, False),
Compare("lt", False, True, True, True),
Compare("le", True, True, True, True),
Compare("eq", True, False, False, True),
Compare("neq", True, False, False, False)
],
[Read(), Nop()],
funcs
)
try:
hrm = entry.emit(context)
print_code(hrm)
opt = True
while opt:
opt, hrm = optimize(hrm)
print_code(hrm)
except Exception as e:
print(e)