-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbasic.cm
110 lines (95 loc) · 1.2 KB
/
basic.cm
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
.include lemmas.cm
.def move a b
# a = b
clear a
copy b a
.end
.def add a b
# a = a + b
move counter b
L0:
jnzdec counter L1
goto L2
L1:
inc a
goto L0
.var counter 0
L2:
.end
.def sub a b
# a = a - b (if a > b)
# a = 0 (if a ≤ b)
move t b
L0:
jnzdec t L1
goto L2
L1:
jnzdec a L0
goto L2
.var t 0
L2:
.end
.def mul a b
# a = a * b
move counter b
clear result
L0:
jnzdec counter L1
goto L2
L1:
add result a
goto L0
L2:
move a result
goto L3
.var counter 0
.var result 0
L3:
.end
.def div a b c
# a = a / b
# c = a % b
inc a
clear quotient
move remainder a
move c a
L0:
sub remainder b
jnzdec remainder L1
goto L2
L1:
inc remainder
inc quotient
goto L0
L2:
move a quotient
move t b
mul t quotient
sub c t
jnzdec c L3
halt
.var quotient 0
.var remainder 0
.var t 0
L3:
.end
.def jump L
# program counter = L
goto L
.end
.def jz a L
# program counter = L (if a = 0)
jnzdec a L0
goto L
L0:
inc a
.end
.def jnz a L
# program counter = L (if a ≠ 0)
jnzdec a L0
goto L1
L0:
inc a
goto L
L1:
.end