fromscratch-pycpu 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- fromscratch_pycpu-0.1.0.dist-info/METADATA +232 -0
- fromscratch_pycpu-0.1.0.dist-info/RECORD +47 -0
- fromscratch_pycpu-0.1.0.dist-info/WHEEL +4 -0
- fromscratch_pycpu-0.1.0.dist-info/entry_points.txt +2 -0
- fromscratch_pycpu-0.1.0.dist-info/licenses/LICENSE +21 -0
- pycpu/__init__.py +11 -0
- pycpu/__main__.py +68 -0
- pycpu/_version.py +24 -0
- pycpu/arithmetic.py +176 -0
- pycpu/assembler.py +580 -0
- pycpu/circuit.py +359 -0
- pycpu/cockpit/__init__.py +8 -0
- pycpu/cockpit/app.py +545 -0
- pycpu/cockpit/code.py +161 -0
- pycpu/cockpit/examples/countdown.pebble +7 -0
- pycpu/cockpit/examples/divide-by-zero.pebble +7 -0
- pycpu/cockpit/examples/factorial.pebble +9 -0
- pycpu/cockpit/examples/greeting.pebble +4 -0
- pycpu/cockpit/examples/times-table.pebble +6 -0
- pycpu/cockpit/examples/tour.pebble +31 -0
- pycpu/cockpit/explain.py +660 -0
- pycpu/cockpit/page.html +1261 -0
- pycpu/cockpit/picture.py +470 -0
- pycpu/cockpit/session.py +778 -0
- pycpu/cockpit/walks/a-call-and-the-stack.toml +47 -0
- pycpu/cockpit/walks/many-instructions.toml +39 -0
- pycpu/cockpit/walks/subtracting-with-gates.toml +39 -0
- pycpu/cockpit/walks/where-n-lives.toml +39 -0
- pycpu/cockpit/walks/why-the-clock-ticks.toml +50 -0
- pycpu/cockpit/walks.py +518 -0
- pycpu/computer.py +175 -0
- pycpu/cpu.py +648 -0
- pycpu/cpu_parts.py +140 -0
- pycpu/fast.py +320 -0
- pycpu/isa.py +243 -0
- pycpu/logic.py +222 -0
- pycpu/memory.py +268 -0
- pycpu/proof.py +263 -0
- pycpu/py.typed +0 -0
- pycpu/simulator.py +361 -0
- pycpu/state.py +146 -0
- pycpu/translator/__init__.py +29 -0
- pycpu/translator/codegen.py +493 -0
- pycpu/translator/program.py +211 -0
- pycpu/translator/runtime.py +166 -0
- pycpu/translator/subset.py +688 -0
- pycpu/view.py +55 -0
pycpu/assembler.py
ADDED
|
@@ -0,0 +1,580 @@
|
|
|
1
|
+
"""The assembler: a helper who turns a recipe written in words into the cook's number cards.
|
|
2
|
+
|
|
3
|
+
Writing `0xE2FF` by hand is miserable, so people write `addi r1, -1` and let a
|
|
4
|
+
helper translate. The helper also keeps sticky-tab bookmarks (labels): write
|
|
5
|
+
`loop:` once, say `br ne, loop` anywhere, and the helper works out which card
|
|
6
|
+
number the tab is on. This file is that helper, and its mirror image, the
|
|
7
|
+
disassembler, who reads a number card back out as the words you would have written.
|
|
8
|
+
|
|
9
|
+
The assembler reads the text twice. Pass 1 only counts how many words each line
|
|
10
|
+
becomes, so it knows where every label sits. Pass 2 writes the words, using
|
|
11
|
+
`encode` from `isa.py`, which is still the only place that knows what a number means.
|
|
12
|
+
Every mistake becomes an `AssemblyError` that says which line and what would be right.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
import re
|
|
16
|
+
from collections.abc import Callable
|
|
17
|
+
from dataclasses import dataclass
|
|
18
|
+
|
|
19
|
+
from pycpu.arithmetic import AluOp
|
|
20
|
+
from pycpu.isa import (
|
|
21
|
+
ADDR12_BITS,
|
|
22
|
+
IMM8_BITS,
|
|
23
|
+
OFF6_BITS,
|
|
24
|
+
OFF9_BITS,
|
|
25
|
+
WORD_MASK,
|
|
26
|
+
Condition,
|
|
27
|
+
Instruction,
|
|
28
|
+
Opcode,
|
|
29
|
+
decode,
|
|
30
|
+
encode,
|
|
31
|
+
)
|
|
32
|
+
from pycpu.memory import RAM_WORDS, WORD_BITS
|
|
33
|
+
from pycpu.state import REGISTER_COUNT
|
|
34
|
+
|
|
35
|
+
SIGNED_WORD_MIN = -(1 << (WORD_BITS - 1))
|
|
36
|
+
BYTE_MAX = (1 << IMM8_BITS) - 1
|
|
37
|
+
IMM8_SIGNED_MIN = -(1 << (IMM8_BITS - 1))
|
|
38
|
+
IMM8_SIGNED_MAX = (1 << (IMM8_BITS - 1)) - 1
|
|
39
|
+
OFF6_MIN = -(1 << (OFF6_BITS - 1))
|
|
40
|
+
OFF6_MAX = (1 << (OFF6_BITS - 1)) - 1
|
|
41
|
+
OFF9_MIN = -(1 << (OFF9_BITS - 1))
|
|
42
|
+
OFF9_MAX = (1 << (OFF9_BITS - 1)) - 1
|
|
43
|
+
MIN_CHAR_LITERAL = 3
|
|
44
|
+
MIN_QUOTED = 2
|
|
45
|
+
MAX_DIGITS = 20
|
|
46
|
+
MAX_ADDRESS = (1 << WORD_BITS) - 1
|
|
47
|
+
ADDR12_MAX = (1 << ADDR12_BITS) - 1
|
|
48
|
+
|
|
49
|
+
_NAME = r"[A-Za-z_][A-Za-z0-9_]*"
|
|
50
|
+
_REGISTER_NAMES = ", ".join(f"r{n}" for n in range(REGISTER_COUNT - 1))
|
|
51
|
+
_REGISTER_LIST = f"{_REGISTER_NAMES} and r{REGISTER_COUNT - 1}"
|
|
52
|
+
_ESCAPES = {"n": "\n", "t": "\t", "0": "\0", "\\": "\\", '"': '"', "'": "'"}
|
|
53
|
+
|
|
54
|
+
# The ALU mnemonics and the operands each one takes (all but `mov` and the shifts take three).
|
|
55
|
+
_ALU_NAMES = {
|
|
56
|
+
"add": AluOp.ADD,
|
|
57
|
+
"sub": AluOp.SUB,
|
|
58
|
+
"and": AluOp.AND,
|
|
59
|
+
"or": AluOp.OR,
|
|
60
|
+
"xor": AluOp.XOR,
|
|
61
|
+
}
|
|
62
|
+
_SHIFT_NAMES = {"shl": AluOp.SHL, "shr": AluOp.SHR}
|
|
63
|
+
|
|
64
|
+
# Every instruction word's shape: the operand kinds, and an example for error messages.
|
|
65
|
+
_SHAPES: dict[str, tuple[tuple[str, ...], str]] = {
|
|
66
|
+
**dict.fromkeys(_ALU_NAMES, (("reg", "reg", "reg"), "{} r3, r1, r2")),
|
|
67
|
+
**dict.fromkeys(_SHIFT_NAMES, (("reg", "reg"), "{} r3, r1")),
|
|
68
|
+
"mov": (("reg", "reg"), "mov r3, r2"),
|
|
69
|
+
"cmp": (("reg", "reg"), "cmp r1, r2"),
|
|
70
|
+
"li": (("reg", "num"), "li r1, 5"),
|
|
71
|
+
"lhi": (("reg", "num"), "lhi r1, 18"),
|
|
72
|
+
"set": (("reg", "val"), "set r1, 1000"),
|
|
73
|
+
"load": (("reg", "mem"), "load r1, [r2+1]"),
|
|
74
|
+
"store": (("reg", "mem"), "store r1, [r2+1]"),
|
|
75
|
+
"jmp": (("val",), "jmp start"),
|
|
76
|
+
"call": (("val",), "call start"),
|
|
77
|
+
"br": (("cond", "val"), "br ne, loop"),
|
|
78
|
+
"ret": ((), "ret"),
|
|
79
|
+
"push": (("reg",), "push r1"),
|
|
80
|
+
"pop": (("reg",), "pop r1"),
|
|
81
|
+
"getsp": (("reg",), "getsp r1"),
|
|
82
|
+
"setsp": (("reg",), "setsp r1"),
|
|
83
|
+
"addi": (("reg", "num"), "addi r1, -1"),
|
|
84
|
+
}
|
|
85
|
+
_SIMPLE_OPCODES = {
|
|
86
|
+
"cmp": Opcode.CMP,
|
|
87
|
+
"li": Opcode.LI,
|
|
88
|
+
"lhi": Opcode.LHI,
|
|
89
|
+
"load": Opcode.LOAD,
|
|
90
|
+
"store": Opcode.STORE,
|
|
91
|
+
"jmp": Opcode.JMP,
|
|
92
|
+
"call": Opcode.CALL,
|
|
93
|
+
"ret": Opcode.RET,
|
|
94
|
+
"push": Opcode.PUSH,
|
|
95
|
+
"pop": Opcode.POP,
|
|
96
|
+
"getsp": Opcode.GETSP,
|
|
97
|
+
"setsp": Opcode.SETSP,
|
|
98
|
+
"addi": Opcode.ADDI,
|
|
99
|
+
}
|
|
100
|
+
_DIRECTIVES = (".word", ".string")
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
class AssemblyError(ValueError):
|
|
104
|
+
"""Say that the assembly text has a mistake, naming the line and how to fix it.
|
|
105
|
+
|
|
106
|
+
The message always starts `line N:`, so a learner can find the spot at once.
|
|
107
|
+
|
|
108
|
+
Attributes:
|
|
109
|
+
line: The 1-based line number of the mistake.
|
|
110
|
+
|
|
111
|
+
"""
|
|
112
|
+
|
|
113
|
+
def __init__(self, line: int, problem: str) -> None:
|
|
114
|
+
"""Remember the line and build the `line N: ...` message."""
|
|
115
|
+
super().__init__(f"line {line}: {problem}")
|
|
116
|
+
self.line = line
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
class ProgramTooLongError(AssemblyError):
|
|
120
|
+
"""Say that the program does not fit in the memory it was assembled for."""
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
@dataclass(frozen=True)
|
|
124
|
+
class Program:
|
|
125
|
+
"""The finished stack of number cards, plus the bookmarks and where each came from.
|
|
126
|
+
|
|
127
|
+
Attributes:
|
|
128
|
+
words: The machine code, one 16-bit word per address, starting at address 0.
|
|
129
|
+
labels: Each label's name, mapped to the address it marks.
|
|
130
|
+
lines: For each word, the 1-based source line it came from.
|
|
131
|
+
|
|
132
|
+
"""
|
|
133
|
+
|
|
134
|
+
words: tuple[int, ...]
|
|
135
|
+
labels: dict[str, int]
|
|
136
|
+
lines: tuple[int, ...]
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
@dataclass(frozen=True)
|
|
140
|
+
class _Item:
|
|
141
|
+
"""One source line after pass 1: what it says, where it sits, how many words it takes."""
|
|
142
|
+
|
|
143
|
+
line: int
|
|
144
|
+
address: int
|
|
145
|
+
name: str
|
|
146
|
+
operands: tuple[str, ...]
|
|
147
|
+
size: int
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _strip_comment(text: str, line: int) -> str:
|
|
151
|
+
"""Cut off a `;` comment, but not a `;` inside quotes; refuse an unclosed quote."""
|
|
152
|
+
quote = ""
|
|
153
|
+
index = 0
|
|
154
|
+
while index < len(text):
|
|
155
|
+
char = text[index]
|
|
156
|
+
if quote:
|
|
157
|
+
if char == "\\":
|
|
158
|
+
index += 1
|
|
159
|
+
elif char == quote:
|
|
160
|
+
quote = ""
|
|
161
|
+
elif char in "\"'":
|
|
162
|
+
quote = char
|
|
163
|
+
elif char == ";":
|
|
164
|
+
return text[:index]
|
|
165
|
+
index += 1
|
|
166
|
+
if quote:
|
|
167
|
+
kind = "string" if quote == '"' else "character"
|
|
168
|
+
raise AssemblyError(
|
|
169
|
+
line,
|
|
170
|
+
f"a {kind} starting with {quote} never ends: add a closing quote ({quote}) on the same line",
|
|
171
|
+
)
|
|
172
|
+
return text
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _split_operands(text: str) -> list[str]:
|
|
176
|
+
"""Split on commas that are not inside quotes. The quotes were already checked."""
|
|
177
|
+
parts: list[str] = []
|
|
178
|
+
current = ""
|
|
179
|
+
quote = ""
|
|
180
|
+
index = 0
|
|
181
|
+
while index < len(text):
|
|
182
|
+
char = text[index]
|
|
183
|
+
if quote:
|
|
184
|
+
current += char
|
|
185
|
+
if char == "\\" and index + 1 < len(text):
|
|
186
|
+
index += 1
|
|
187
|
+
current += text[index]
|
|
188
|
+
elif char == quote:
|
|
189
|
+
quote = ""
|
|
190
|
+
elif char in "\"'":
|
|
191
|
+
quote = char
|
|
192
|
+
current += char
|
|
193
|
+
elif char == ",":
|
|
194
|
+
parts.append(current.strip())
|
|
195
|
+
current = ""
|
|
196
|
+
else:
|
|
197
|
+
current += char
|
|
198
|
+
index += 1
|
|
199
|
+
parts.append(current.strip())
|
|
200
|
+
return parts if text.strip() else []
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def _unescape(body: str, line: int) -> str:
|
|
204
|
+
"""Turn the inside of a quoted text into characters, understanding backslash escapes."""
|
|
205
|
+
out = ""
|
|
206
|
+
index = 0
|
|
207
|
+
while index < len(body):
|
|
208
|
+
char = body[index]
|
|
209
|
+
if char == "\\":
|
|
210
|
+
index += 1
|
|
211
|
+
escape = body[index] if index < len(body) else ""
|
|
212
|
+
if escape not in _ESCAPES:
|
|
213
|
+
raise AssemblyError(
|
|
214
|
+
line,
|
|
215
|
+
f"I do not know the escape \\{escape}: use \\n, \\t, \\0, \\\\, \\\" or \\'",
|
|
216
|
+
)
|
|
217
|
+
char = _ESCAPES[escape]
|
|
218
|
+
out += char
|
|
219
|
+
index += 1
|
|
220
|
+
return out
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def _check_letters(text: str, line: int) -> None:
|
|
224
|
+
"""Refuse a character that does not fit in one 16-bit word."""
|
|
225
|
+
for char in text:
|
|
226
|
+
if ord(char) > WORD_MASK:
|
|
227
|
+
raise AssemblyError(
|
|
228
|
+
line, f"the character {char!r} is too big to fit in one 16-bit word"
|
|
229
|
+
)
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def _register(text: str, line: int) -> int:
|
|
233
|
+
"""Read `r0` to `r7` (any case) as a register number."""
|
|
234
|
+
match = re.fullmatch(r"[rR]([0-9]+)", text)
|
|
235
|
+
if match and int(match.group(1)) < REGISTER_COUNT and len(match.group(1)) == 1:
|
|
236
|
+
return int(match.group(1))
|
|
237
|
+
if match:
|
|
238
|
+
raise AssemblyError(line, f"{text} is not a register. The registers are {_REGISTER_LIST}.")
|
|
239
|
+
raise AssemblyError(
|
|
240
|
+
line,
|
|
241
|
+
f"I expected a register like r1 here, but found {text!r}. The registers are {_REGISTER_LIST}.",
|
|
242
|
+
)
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def _number(text: str, line: int) -> int:
|
|
246
|
+
"""Read a decimal, `-` decimal, `0x` hex or `'A'` character as a number."""
|
|
247
|
+
if re.fullmatch(r"-?[0-9]+", text, flags=re.ASCII):
|
|
248
|
+
sign, digits = (-1, text[1:]) if text[0] == "-" else (1, text)
|
|
249
|
+
return sign * _decimal(digits, 10, line)
|
|
250
|
+
if re.fullmatch(r"-?0[xX][0-9a-fA-F]+", text):
|
|
251
|
+
sign, digits = (-1, text[1:]) if text[0] == "-" else (1, text)
|
|
252
|
+
return sign * _decimal(digits[2:], 16, line)
|
|
253
|
+
if len(text) >= MIN_CHAR_LITERAL and text[0] == text[-1] == "'":
|
|
254
|
+
letters = _unescape(text[1:-1], line)
|
|
255
|
+
if len(letters) != 1:
|
|
256
|
+
raise AssemblyError(line, f"{text} should hold exactly one letter, like 'A'")
|
|
257
|
+
_check_letters(letters, line)
|
|
258
|
+
return ord(letters)
|
|
259
|
+
raise AssemblyError(
|
|
260
|
+
line,
|
|
261
|
+
f"{text!r} is not a number. Write it like 12, -3, 0x1F or a letter in quotes like 'A'.",
|
|
262
|
+
)
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def _decimal(digits: str, base: int, line: int) -> int:
|
|
266
|
+
"""Convert digits, refusing absurdly long ones before Python is asked to convert them."""
|
|
267
|
+
if len(digits.lstrip("0")) > MAX_DIGITS:
|
|
268
|
+
raise AssemblyError(
|
|
269
|
+
line, f"that number has more than {MAX_DIGITS} digits, which is far too big for a word"
|
|
270
|
+
)
|
|
271
|
+
return int(digits, base)
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def _within(value: int, low: int, high: int, what: str, line: int) -> int:
|
|
275
|
+
"""Return `value` if it is from `low` to `high`, else explain the allowed range."""
|
|
276
|
+
if not low <= value <= high:
|
|
277
|
+
raise AssemblyError(
|
|
278
|
+
line, f"{value} does not fit in {what}: use a number from {low} to {high}"
|
|
279
|
+
)
|
|
280
|
+
return value
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def _memory(text: str, line: int) -> tuple[int, int]:
|
|
284
|
+
"""Read `[ra]`, `[ra+n]` or `[ra-n]` into (register, offset)."""
|
|
285
|
+
if not (text.startswith("[") and text.endswith("]")):
|
|
286
|
+
raise AssemblyError(
|
|
287
|
+
line,
|
|
288
|
+
f"I expected a memory spot in square brackets like [r2], [r2+3] or [r2-1], but found {text!r}",
|
|
289
|
+
)
|
|
290
|
+
inside = text[1:-1].strip()
|
|
291
|
+
cut = min((i for i in (inside.find("+"), inside.find("-")) if i > 0), default=-1)
|
|
292
|
+
if cut < 0:
|
|
293
|
+
return _register(inside, line), 0
|
|
294
|
+
offset_text = inside[cut + 1 :].strip()
|
|
295
|
+
if not offset_text or offset_text[0] in "+-":
|
|
296
|
+
raise AssemblyError(
|
|
297
|
+
line, f"I expected a plain number after {inside[cut]} in {text}, like [r2+3]"
|
|
298
|
+
)
|
|
299
|
+
offset = _number(offset_text, line) * (1 if inside[cut] == "+" else -1)
|
|
300
|
+
offset = _within(offset, OFF6_MIN, OFF6_MAX, "a memory offset", line)
|
|
301
|
+
return _register(inside[:cut].strip(), line), offset
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def _parse_line(text: str) -> tuple[list[str], str, list[str]]:
|
|
305
|
+
"""Split a tidy line into (labels, name, operands). The name is lower case; it may be empty."""
|
|
306
|
+
labels: list[str] = []
|
|
307
|
+
while match := re.match(r"\s*([^\s:]+)\s*:", text):
|
|
308
|
+
labels.append(match.group(1))
|
|
309
|
+
text = text[match.end() :]
|
|
310
|
+
text = text.strip()
|
|
311
|
+
parts = re.split(r"\s+", text, maxsplit=1)
|
|
312
|
+
name, rest = parts[0], (parts[1] if len(parts) > 1 else "")
|
|
313
|
+
return labels, name.lower(), _split_operands(rest.strip())
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
def _size(name: str, operands: list[str], line: int) -> int:
|
|
317
|
+
"""Count the words a line will become, for pass 1."""
|
|
318
|
+
if name == "set":
|
|
319
|
+
return 2
|
|
320
|
+
if name == ".word":
|
|
321
|
+
return max(len(operands), 1)
|
|
322
|
+
if name == ".string":
|
|
323
|
+
return len(_string_text(operands, line)) + 1
|
|
324
|
+
if name in _SHAPES or name == "halt":
|
|
325
|
+
return 1
|
|
326
|
+
raise AssemblyError(
|
|
327
|
+
line,
|
|
328
|
+
f"I do not know the instruction {name!r}. Check the spelling against the Instruction Set page.",
|
|
329
|
+
)
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
def _string_text(operands: list[str], line: int) -> str:
|
|
333
|
+
"""Read the one quoted text that `.string` needs."""
|
|
334
|
+
if len(operands) != 1 or not (
|
|
335
|
+
len(operands[0]) >= MIN_QUOTED and operands[0][0] == operands[0][-1] == '"'
|
|
336
|
+
):
|
|
337
|
+
raise AssemblyError(
|
|
338
|
+
line, '.string needs one piece of text in double quotes, like .string "Hi"'
|
|
339
|
+
)
|
|
340
|
+
letters = _unescape(operands[0][1:-1], line)
|
|
341
|
+
_check_letters(letters, line)
|
|
342
|
+
return letters
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
def _pass_one(source: str, words: int) -> tuple[list[_Item], dict[str, int]]:
|
|
346
|
+
"""Walk the text once, finding where every label is and how big every line is."""
|
|
347
|
+
items: list[_Item] = []
|
|
348
|
+
labels: dict[str, int] = {}
|
|
349
|
+
address = 0
|
|
350
|
+
for number, raw in enumerate(source.split("\n"), start=1):
|
|
351
|
+
code = _strip_comment(raw, number)
|
|
352
|
+
found, name, operands = _parse_line(code)
|
|
353
|
+
for label in found:
|
|
354
|
+
_define(label, address, labels, number)
|
|
355
|
+
if not name:
|
|
356
|
+
continue
|
|
357
|
+
size = _size(name, operands, number)
|
|
358
|
+
if address + size > words:
|
|
359
|
+
raise ProgramTooLongError(
|
|
360
|
+
number,
|
|
361
|
+
f"the program is too long: it must fit in {words} words of memory, and this line goes past the end",
|
|
362
|
+
)
|
|
363
|
+
items.append(_Item(number, address, name, tuple(operands), size))
|
|
364
|
+
address += size
|
|
365
|
+
return items, labels
|
|
366
|
+
|
|
367
|
+
|
|
368
|
+
def _define(label: str, address: int, labels: dict[str, int], line: int) -> None:
|
|
369
|
+
"""Record a label, refusing bad names, register names, and repeats."""
|
|
370
|
+
if not re.fullmatch(_NAME, label, flags=re.ASCII):
|
|
371
|
+
raise AssemblyError(
|
|
372
|
+
line,
|
|
373
|
+
f"{label!r} is not a good label name: use letters, digits and _, and do not start with a digit",
|
|
374
|
+
)
|
|
375
|
+
if re.fullmatch(r"[rR][0-7]", label):
|
|
376
|
+
raise AssemblyError(
|
|
377
|
+
line, f"{label} is a register name, so it cannot also be a label: pick another name"
|
|
378
|
+
)
|
|
379
|
+
if label in labels:
|
|
380
|
+
raise AssemblyError(
|
|
381
|
+
line, f"the label {label} is already used: every label needs its own name"
|
|
382
|
+
)
|
|
383
|
+
labels[label] = address
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
def _value(text: str, labels: dict[str, int], line: int) -> int:
|
|
387
|
+
"""Read a label or a number (an address, or a value for `set` and `.word`)."""
|
|
388
|
+
if re.fullmatch(_NAME, text, flags=re.ASCII):
|
|
389
|
+
if text not in labels:
|
|
390
|
+
raise AssemblyError(
|
|
391
|
+
line,
|
|
392
|
+
f"I do not know a label called {text}: write {text}: on the line it should mark",
|
|
393
|
+
)
|
|
394
|
+
return labels[text]
|
|
395
|
+
return _number(text, line)
|
|
396
|
+
|
|
397
|
+
|
|
398
|
+
def _condition(text: str, line: int) -> Condition:
|
|
399
|
+
"""Read a branch condition name such as `eq` or `NE`."""
|
|
400
|
+
try:
|
|
401
|
+
return Condition[text.upper()]
|
|
402
|
+
except KeyError:
|
|
403
|
+
names = ", ".join(c.name.lower() for c in Condition)
|
|
404
|
+
raise AssemblyError(
|
|
405
|
+
line, f"{text!r} is not a branch condition. Use one of: {names}"
|
|
406
|
+
) from None
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
def _expand(item: _Item, labels: dict[str, int]) -> list[int]:
|
|
410
|
+
"""Turn one source line into its machine words (pass 2)."""
|
|
411
|
+
line, name, ops = item.line, item.name, list(item.operands)
|
|
412
|
+
if name == ".string":
|
|
413
|
+
return [*(ord(c) for c in _string_text(ops, line)), 0]
|
|
414
|
+
if name == ".word":
|
|
415
|
+
if not ops or not all(ops):
|
|
416
|
+
raise AssemblyError(line, ".word needs a number or a label, like .word 7")
|
|
417
|
+
return [
|
|
418
|
+
_within(_value(op, labels, line), SIGNED_WORD_MIN, WORD_MASK, "a 16-bit word", line)
|
|
419
|
+
& WORD_MASK
|
|
420
|
+
for op in ops
|
|
421
|
+
]
|
|
422
|
+
if name == "halt":
|
|
423
|
+
if len(ops) > 1 or (ops and not ops[0]):
|
|
424
|
+
raise AssemblyError(line, "halt takes at most one number, like halt or halt 3")
|
|
425
|
+
code = _within(_number(ops[0], line), 0, BYTE_MAX, "a halt code", line) if ops else 0
|
|
426
|
+
return [encode(Opcode.HALT, imm=code)]
|
|
427
|
+
shape, example = _SHAPES[name]
|
|
428
|
+
if len(ops) != len(shape) or not all(ops):
|
|
429
|
+
raise AssemblyError(
|
|
430
|
+
line,
|
|
431
|
+
f"{name} needs {len(shape)} thing{'s' if len(shape) != 1 else ''} after it, "
|
|
432
|
+
f"like {example.format(name)}, but I found {len(ops) if all(ops) else 'a missing one'}",
|
|
433
|
+
)
|
|
434
|
+
return [_encode(item, shape, labels)] if name != "set" else _encode_set(ops, labels, line)
|
|
435
|
+
|
|
436
|
+
|
|
437
|
+
def _encode_set(ops: list[str], labels: dict[str, int], line: int) -> list[int]:
|
|
438
|
+
"""Expand `set rd, value` into `li` (low byte) then `lhi` (high byte)."""
|
|
439
|
+
rd = _register(ops[0], line)
|
|
440
|
+
value = _within(_value(ops[1], labels, line), SIGNED_WORD_MIN, WORD_MASK, "a 16-bit word", line)
|
|
441
|
+
value &= WORD_MASK
|
|
442
|
+
return [
|
|
443
|
+
encode(Opcode.LI, rd=rd, imm=value & BYTE_MAX),
|
|
444
|
+
encode(Opcode.LHI, rd=rd, imm=value >> IMM8_BITS),
|
|
445
|
+
]
|
|
446
|
+
|
|
447
|
+
|
|
448
|
+
def _encode(item: _Item, shape: tuple[str, ...], labels: dict[str, int]) -> int:
|
|
449
|
+
"""Encode one ordinary instruction whose operand count is already right."""
|
|
450
|
+
line, name, ops = item.line, item.name, item.operands
|
|
451
|
+
reads: dict[str, Callable[[str], int]] = {
|
|
452
|
+
"reg": lambda t: _register(t, line),
|
|
453
|
+
"num": lambda t: _number(t, line),
|
|
454
|
+
"val": lambda t: _value(t, labels, line),
|
|
455
|
+
"cond": lambda t: _condition(t, line),
|
|
456
|
+
}
|
|
457
|
+
if "mem" in shape:
|
|
458
|
+
register, base = _register(ops[0], line), _memory(ops[1], line)
|
|
459
|
+
return encode(_SIMPLE_OPCODES[name], rd=register, ra=base[0], imm=base[1])
|
|
460
|
+
values = [reads[kind](op) for kind, op in zip(shape, ops, strict=True)]
|
|
461
|
+
first = values[0] if values else 0
|
|
462
|
+
match name:
|
|
463
|
+
case _ if name in _ALU_NAMES:
|
|
464
|
+
word = encode(Opcode.ALU, rd=first, ra=values[1], rb=values[2], fn=_ALU_NAMES[name])
|
|
465
|
+
case _ if name in _SHIFT_NAMES:
|
|
466
|
+
word = encode(Opcode.ALU, rd=first, ra=values[1], fn=_SHIFT_NAMES[name])
|
|
467
|
+
case "mov":
|
|
468
|
+
word = encode(Opcode.ALU, rd=first, rb=values[1], fn=AluOp.PASS_B)
|
|
469
|
+
case "cmp":
|
|
470
|
+
word = encode(Opcode.CMP, ra=first, rb=values[1])
|
|
471
|
+
case "br":
|
|
472
|
+
word = encode(Opcode.BR, rd=first, imm=_branch_offset(values[1], item.address, line))
|
|
473
|
+
case "jmp" | "call":
|
|
474
|
+
word = encode(
|
|
475
|
+
_SIMPLE_OPCODES[name], imm=_within(first, 0, ADDR12_MAX, "a jump address", line)
|
|
476
|
+
)
|
|
477
|
+
case "li" | "lhi":
|
|
478
|
+
word = encode(
|
|
479
|
+
_SIMPLE_OPCODES[name], rd=first, imm=_within(values[1], 0, BYTE_MAX, "8 bits", line)
|
|
480
|
+
)
|
|
481
|
+
case "addi":
|
|
482
|
+
imm = _within(values[1], IMM8_SIGNED_MIN, IMM8_SIGNED_MAX, "addi", line)
|
|
483
|
+
word = encode(Opcode.ADDI, rd=first, imm=imm)
|
|
484
|
+
case _:
|
|
485
|
+
word = encode(_SIMPLE_OPCODES[name], rd=first)
|
|
486
|
+
return word
|
|
487
|
+
|
|
488
|
+
|
|
489
|
+
def _branch_offset(target: int, address: int, line: int) -> int:
|
|
490
|
+
"""Work out how far a `br` at `address` must hop to reach `target`."""
|
|
491
|
+
if not 0 <= target <= MAX_ADDRESS:
|
|
492
|
+
raise AssemblyError(
|
|
493
|
+
line, f"{target} is not an address: use a number from 0 to {MAX_ADDRESS}"
|
|
494
|
+
)
|
|
495
|
+
distance = ((target - (address + 1) + (1 << (WORD_BITS - 1))) & WORD_MASK) - (
|
|
496
|
+
1 << (WORD_BITS - 1)
|
|
497
|
+
)
|
|
498
|
+
if not OFF9_MIN <= distance <= OFF9_MAX:
|
|
499
|
+
raise AssemblyError(
|
|
500
|
+
line,
|
|
501
|
+
f"that target is {distance} words from the next instruction, which is too far for br: "
|
|
502
|
+
f"branch over a jmp instead (br reaches {OFF9_MIN} to {OFF9_MAX})",
|
|
503
|
+
)
|
|
504
|
+
return distance
|
|
505
|
+
|
|
506
|
+
|
|
507
|
+
def assemble(source: str, words: int = RAM_WORDS) -> Program:
|
|
508
|
+
"""Turn assembly text into machine code.
|
|
509
|
+
|
|
510
|
+
Pass 1 finds every label; pass 2 writes the words. See the module docstring
|
|
511
|
+
and the Assembly Language page for the syntax.
|
|
512
|
+
|
|
513
|
+
Args:
|
|
514
|
+
source: The assembly text, one instruction per line.
|
|
515
|
+
words: How many words of memory the program must fit in.
|
|
516
|
+
|
|
517
|
+
Returns:
|
|
518
|
+
The words, the labels and the source line of every word.
|
|
519
|
+
|
|
520
|
+
Raises:
|
|
521
|
+
AssemblyError: On any mistake in the text; the message starts `line N:`.
|
|
522
|
+
|
|
523
|
+
"""
|
|
524
|
+
items, labels = _pass_one(source, words)
|
|
525
|
+
machine_words: list[int] = []
|
|
526
|
+
lines: list[int] = []
|
|
527
|
+
for item in items:
|
|
528
|
+
expanded = _expand(item, labels)
|
|
529
|
+
machine_words.extend(expanded)
|
|
530
|
+
lines.extend([item.line] * len(expanded))
|
|
531
|
+
return Program(tuple(machine_words), labels, tuple(lines))
|
|
532
|
+
|
|
533
|
+
|
|
534
|
+
def _memory_text(register: int, offset: int) -> str:
|
|
535
|
+
"""Write a memory operand the way the assembler reads it."""
|
|
536
|
+
sign = "" if offset == 0 else f"{'+' if offset > 0 else '-'}{abs(offset)}"
|
|
537
|
+
return f"[r{register}{sign}]"
|
|
538
|
+
|
|
539
|
+
|
|
540
|
+
def disassemble(word: int, address: int) -> str:
|
|
541
|
+
"""Turn one machine word back into assembly text the assembler accepts.
|
|
542
|
+
|
|
543
|
+
The text is always in the same neat shape (lower case, `[r2-1]`). A `br`
|
|
544
|
+
shows its absolute target, so this needs the `address` the word sits at.
|
|
545
|
+
Labels and comments cannot come back: the word never held them.
|
|
546
|
+
|
|
547
|
+
Args:
|
|
548
|
+
word: The 16-bit machine word.
|
|
549
|
+
address: Where the word sits in memory.
|
|
550
|
+
|
|
551
|
+
"""
|
|
552
|
+
i: Instruction = decode(word)
|
|
553
|
+
rd, ra, rb = f"r{i.rd}", f"r{i.ra}", f"r{i.rb}"
|
|
554
|
+
text: str
|
|
555
|
+
names = {**{v: k for k, v in _ALU_NAMES.items()}, **{v: k for k, v in _SHIFT_NAMES.items()}}
|
|
556
|
+
match i.opcode:
|
|
557
|
+
case Opcode.ALU if i.fn == AluOp.PASS_B:
|
|
558
|
+
text = f"mov {rd}, {rb}"
|
|
559
|
+
case Opcode.ALU if i.fn in _SHIFT_NAMES.values():
|
|
560
|
+
text = f"{names[AluOp(i.fn)]} {rd}, {ra}"
|
|
561
|
+
case Opcode.ALU:
|
|
562
|
+
text = f"{names[AluOp(i.fn)]} {rd}, {ra}, {rb}"
|
|
563
|
+
case Opcode.CMP:
|
|
564
|
+
text = f"cmp {ra}, {rb}"
|
|
565
|
+
case Opcode.LOAD | Opcode.STORE:
|
|
566
|
+
text = f"{i.opcode.name.lower()} {rd}, {_memory_text(i.ra, i.imm)}"
|
|
567
|
+
case Opcode.BR:
|
|
568
|
+
target = (address + 1 + i.imm) & WORD_MASK
|
|
569
|
+
return f"br {Condition(i.rd).name.lower()}, {target}"
|
|
570
|
+
case Opcode.RET:
|
|
571
|
+
text = "ret"
|
|
572
|
+
case Opcode.JMP | Opcode.CALL:
|
|
573
|
+
text = f"{i.opcode.name.lower()} {i.imm}"
|
|
574
|
+
case Opcode.HALT:
|
|
575
|
+
text = "halt" if i.imm == 0 else f"halt {i.imm}"
|
|
576
|
+
case Opcode.PUSH | Opcode.POP | Opcode.GETSP | Opcode.SETSP:
|
|
577
|
+
text = f"{i.opcode.name.lower()} {rd}"
|
|
578
|
+
case _:
|
|
579
|
+
text = f"{i.opcode.name.lower()} {rd}, {i.imm}"
|
|
580
|
+
return text
|