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/state.py
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
"""The machine state: everything a computer remembers, written on one sheet of paper.
|
|
2
|
+
|
|
3
|
+
Imagine freezing a kitchen mid-recipe and writing down exactly what is where: which
|
|
4
|
+
card the cook's finger is on, what is in every bowl, what is on every shelf of the
|
|
5
|
+
pantry. Anyone with that sheet could rebuild the kitchen and carry on cooking.
|
|
6
|
+
`MachineState` is that sheet for a PyCPU computer. Both engines, the fast one and the
|
|
7
|
+
gate one, can write their state onto it and read one back, which is how they are
|
|
8
|
+
compared, and how a paused computer is carried from one engine to the other.
|
|
9
|
+
|
|
10
|
+
This file only holds values. It works nothing out.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from collections.abc import Sequence
|
|
14
|
+
from dataclasses import dataclass, replace
|
|
15
|
+
from typing import NamedTuple
|
|
16
|
+
|
|
17
|
+
from pycpu.memory import RAM_WORDS, WORD_BITS
|
|
18
|
+
|
|
19
|
+
REGISTER_COUNT = 8
|
|
20
|
+
WORD_MASK = (1 << WORD_BITS) - 1 # the biggest 16-bit number: 65535
|
|
21
|
+
BYTE_MASK = 0xFF
|
|
22
|
+
HALT_CODE_MAX = 0xFF # HALT carries an 8-bit code, so every halt code fits in a byte
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class Flags(NamedTuple):
|
|
26
|
+
"""The four lamps that describe the last sum: each one is 0 or 1.
|
|
27
|
+
|
|
28
|
+
Attributes:
|
|
29
|
+
zero: 1 when the result was 0.
|
|
30
|
+
negative: 1 when the top bit of the result was 1.
|
|
31
|
+
carry: 1 when a bit fell off the end (see `pycpu.arithmetic.alu`).
|
|
32
|
+
overflow: 1 when a signed add or subtract gave an answer that does not fit.
|
|
33
|
+
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
zero: int
|
|
37
|
+
negative: int
|
|
38
|
+
carry: int
|
|
39
|
+
overflow: int
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass(frozen=True)
|
|
43
|
+
class MachineState:
|
|
44
|
+
"""One frozen moment of a computer: every value it would need to carry on.
|
|
45
|
+
|
|
46
|
+
Attributes:
|
|
47
|
+
pc: The program counter, the address of the next instruction.
|
|
48
|
+
sp: The stack pointer.
|
|
49
|
+
registers: The eight registers `r0` to `r7`.
|
|
50
|
+
flags: The four flag lamps.
|
|
51
|
+
memory: Every word of RAM.
|
|
52
|
+
halted: True once the machine has stopped.
|
|
53
|
+
halt_code: Why it stopped: 0 for normal, otherwise a `Fault` or a program's own
|
|
54
|
+
code; always 0 to `HALT_CODE_MAX` (255), because `HALT` carries 8 bits.
|
|
55
|
+
output: Every word the program has sent to the output port, in order.
|
|
56
|
+
|
|
57
|
+
"""
|
|
58
|
+
|
|
59
|
+
pc: int
|
|
60
|
+
sp: int
|
|
61
|
+
registers: tuple[int, ...]
|
|
62
|
+
flags: Flags
|
|
63
|
+
memory: tuple[int, ...]
|
|
64
|
+
halted: bool
|
|
65
|
+
halt_code: int
|
|
66
|
+
output: tuple[int, ...]
|
|
67
|
+
|
|
68
|
+
@property
|
|
69
|
+
def output_text(self) -> str:
|
|
70
|
+
"""The output as text: the low byte of each output word, as a character."""
|
|
71
|
+
return "".join(chr(word & BYTE_MASK) for word in self.output)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def power_on(words: int = RAM_WORDS) -> MachineState:
|
|
75
|
+
"""Return the state of a computer the moment it is switched on.
|
|
76
|
+
|
|
77
|
+
Everything is 0, except the stack pointer, which starts at `words` (one past
|
|
78
|
+
the last word of RAM) so that the first push lands on the top word.
|
|
79
|
+
|
|
80
|
+
Args:
|
|
81
|
+
words: How many words of RAM the computer has.
|
|
82
|
+
|
|
83
|
+
"""
|
|
84
|
+
return MachineState(
|
|
85
|
+
pc=0,
|
|
86
|
+
sp=words,
|
|
87
|
+
registers=(0,) * REGISTER_COUNT,
|
|
88
|
+
flags=Flags(0, 0, 0, 0),
|
|
89
|
+
memory=(0,) * words,
|
|
90
|
+
halted=False,
|
|
91
|
+
halt_code=0,
|
|
92
|
+
output=(),
|
|
93
|
+
)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def program_state(program: Sequence[int], words: int = RAM_WORDS) -> MachineState:
|
|
97
|
+
"""Return a freshly powered-on state with `program` copied in from address 0.
|
|
98
|
+
|
|
99
|
+
Both engines load programs this way, so they start from the very same sheet.
|
|
100
|
+
|
|
101
|
+
Args:
|
|
102
|
+
program: The 16-bit words to put at the start of memory.
|
|
103
|
+
words: How many words of RAM the computer has.
|
|
104
|
+
|
|
105
|
+
Raises:
|
|
106
|
+
ValueError: If the program is bigger than memory or holds a non-word.
|
|
107
|
+
|
|
108
|
+
"""
|
|
109
|
+
if len(program) > words:
|
|
110
|
+
msg = f"a program of {len(program)} words does not fit in {words} words of memory"
|
|
111
|
+
raise ValueError(msg)
|
|
112
|
+
for word in program:
|
|
113
|
+
if not 0 <= word <= WORD_MASK:
|
|
114
|
+
msg = f"program word {word} is not a 16-bit number"
|
|
115
|
+
raise ValueError(msg)
|
|
116
|
+
start = power_on(words)
|
|
117
|
+
return replace(start, memory=(*program, *start.memory[len(program) :]))
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def validate_state(state: MachineState, words: int) -> None:
|
|
121
|
+
"""Raise a ValueError unless `state` is a state a machine of `words` words could hold."""
|
|
122
|
+
if len(state.memory) != words:
|
|
123
|
+
msg = f"memory has {len(state.memory)} words, but this machine has {words}"
|
|
124
|
+
raise ValueError(msg)
|
|
125
|
+
if len(state.registers) != REGISTER_COUNT:
|
|
126
|
+
msg = f"there must be {REGISTER_COUNT} registers, not {len(state.registers)}"
|
|
127
|
+
raise ValueError(msg)
|
|
128
|
+
numbers = {
|
|
129
|
+
"pc": [state.pc],
|
|
130
|
+
"sp": [state.sp],
|
|
131
|
+
"register": state.registers,
|
|
132
|
+
"memory word": state.memory,
|
|
133
|
+
"output word": state.output,
|
|
134
|
+
}
|
|
135
|
+
for name, values in numbers.items():
|
|
136
|
+
for value in values:
|
|
137
|
+
if not 0 <= value <= WORD_MASK:
|
|
138
|
+
msg = f"{name} {value} is not a 16-bit number"
|
|
139
|
+
raise ValueError(msg)
|
|
140
|
+
if not 0 <= state.halt_code <= HALT_CODE_MAX:
|
|
141
|
+
msg = f"halt code {state.halt_code} must be from 0 to {HALT_CODE_MAX}"
|
|
142
|
+
raise ValueError(msg)
|
|
143
|
+
for name, flag in zip(Flags._fields, state.flags, strict=True):
|
|
144
|
+
if flag not in (0, 1):
|
|
145
|
+
msg = f"flag {name} must be 0 or 1, not {flag}"
|
|
146
|
+
raise ValueError(msg)
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""The translator: a phrasebook that turns Pebble sentences into PyCPU machine talk.
|
|
2
|
+
|
|
3
|
+
Imagine a traveller who speaks Pebble and has to talk to a computer that only knows
|
|
4
|
+
adding, shifting and jumping. The traveller needs a phrasebook, and also a few
|
|
5
|
+
ready-made phrases for things the computer cannot say in one word, like "multiply".
|
|
6
|
+
This package is both. `translate` looks up every Pebble instruction and writes the
|
|
7
|
+
PyCPU assembly for it (`subset.py` checks the program first, `codegen.py` writes the
|
|
8
|
+
assembly), and `run_pebble` runs the result on the fast engine. The ready-made
|
|
9
|
+
phrases, the multiply, divide and print routines, live in `runtime.py`.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from pycpu.translator.codegen import FRAME_POINTER, FrameLayout, Slot
|
|
13
|
+
from pycpu.translator.program import PebbleRun, TranslatedProgram, run_pebble, translate
|
|
14
|
+
from pycpu.translator.runtime import RUNTIME, RUNTIME_STACK_WORDS
|
|
15
|
+
from pycpu.translator.subset import PebbleCPUError, UnsupportedFeature
|
|
16
|
+
|
|
17
|
+
__all__ = [
|
|
18
|
+
"FRAME_POINTER",
|
|
19
|
+
"RUNTIME",
|
|
20
|
+
"RUNTIME_STACK_WORDS",
|
|
21
|
+
"FrameLayout",
|
|
22
|
+
"PebbleCPUError",
|
|
23
|
+
"PebbleRun",
|
|
24
|
+
"Slot",
|
|
25
|
+
"TranslatedProgram",
|
|
26
|
+
"UnsupportedFeature",
|
|
27
|
+
"run_pebble",
|
|
28
|
+
"translate",
|
|
29
|
+
]
|
|
@@ -0,0 +1,493 @@
|
|
|
1
|
+
"""The code generator: a translator who writes a few number cards for every line of a recipe.
|
|
2
|
+
|
|
3
|
+
Pebble's compiler has already broken the program into tiny bytecode steps such as "put 6
|
|
4
|
+
on the stack" or "multiply the top two". This file takes the steps one at a time and
|
|
5
|
+
writes the PyCPU assembly that does the same thing, the way a translator turns each line
|
|
6
|
+
of a recipe into a few cards the cook can read. On the back of every card it pencils the
|
|
7
|
+
Pebble line the card came from, which becomes the source map.
|
|
8
|
+
|
|
9
|
+
The rules it follows are the same for every step. Pebble's stack is PyCPU's real stack:
|
|
10
|
+
"put 6 on the stack" is `push`, "take the top two" is two `pop`s. No value is kept in a
|
|
11
|
+
register from one step to the next. `r0` always holds 0, `r1` to `r6` are scratch paper,
|
|
12
|
+
and `r7` is the **frame pointer**: it points at the frame, the block of memory that holds
|
|
13
|
+
this piece of code's variables, and a variable is always found at the same distance
|
|
14
|
+
below it. See the Variables in Memory page for the picture.
|
|
15
|
+
|
|
16
|
+
Jumps work like page numbers in a choose-your-own-adventure book. Every bytecode
|
|
17
|
+
instruction that some jump goes to gets a label named after its position, such as
|
|
18
|
+
`__main_7`, and a Pebble jump becomes a `jmp` to that label (see If and While as Jumps).
|
|
19
|
+
|
|
20
|
+
Each Pebble function gets the same treatment as main, starting at its own label such
|
|
21
|
+
as `__fn_double`. A call is "leave the arguments on the stack, `call`, then tidy the
|
|
22
|
+
arguments away and push the answer from `r1`" (see How a Function Call Really Works).
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
from dataclasses import dataclass
|
|
26
|
+
|
|
27
|
+
from pebble import Instruction, OpCode
|
|
28
|
+
|
|
29
|
+
from pycpu.translator.runtime import RUNTIME, RUNTIME_STACK_WORDS
|
|
30
|
+
from pycpu.translator.subset import (
|
|
31
|
+
COMPARISONS,
|
|
32
|
+
JUMPS,
|
|
33
|
+
CheckedCode,
|
|
34
|
+
CheckedProgram,
|
|
35
|
+
PebbleCPUError,
|
|
36
|
+
first_place,
|
|
37
|
+
located,
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
BYTE_MAX = 255
|
|
41
|
+
COLUMN = 24
|
|
42
|
+
MAIN_LABEL = "__main"
|
|
43
|
+
FUNCTION_PREFIX = "__fn_"
|
|
44
|
+
# A `call` pushes one word, the return address, before the called function's prologue
|
|
45
|
+
# checks for room. That word lands in the room the caller set aside for the routines.
|
|
46
|
+
RETURN_ADDRESS_WORDS = 1
|
|
47
|
+
_ASCII_LETTERS_AND_DIGITS = frozenset(
|
|
48
|
+
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
|
|
49
|
+
)
|
|
50
|
+
END_LABEL = "__end"
|
|
51
|
+
FRAME_POINTER = 7 # r7 holds the frame pointer: the address of the running code's frame
|
|
52
|
+
_ALU = {OpCode.ADD: "add", OpCode.SUBTRACT: "sub"}
|
|
53
|
+
# Each comparison, the signed branch condition that says "yes", and how to say it.
|
|
54
|
+
_BRANCHES: dict[str, tuple[str, str]] = {
|
|
55
|
+
OpCode.LESS_THAN: ("lt", "<"),
|
|
56
|
+
OpCode.LESS_EQUAL: ("le", "<="),
|
|
57
|
+
OpCode.GREATER_THAN: ("gt", ">"),
|
|
58
|
+
OpCode.GREATER_EQUAL: ("ge", ">="),
|
|
59
|
+
OpCode.EQUAL: ("eq", "=="),
|
|
60
|
+
OpCode.NOT_EQUAL: ("ne", "!="),
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
@dataclass(frozen=True)
|
|
65
|
+
class Slot:
|
|
66
|
+
"""One named pigeonhole in a frame: where a parameter or variable lives.
|
|
67
|
+
|
|
68
|
+
Attributes:
|
|
69
|
+
name: The name, as Pebble knows it.
|
|
70
|
+
offset: How far from `r7` it sits: parameter i of N is at `2 + (N - 1 - i)`
|
|
71
|
+
(above the saved `r7` and the return address), variable j at `-1 - j`.
|
|
72
|
+
kind: `"parameter"` or `"variable"`.
|
|
73
|
+
hidden: True for a name the compiler made up, such as `$for_limit_0`, which
|
|
74
|
+
is not a name a Pebble program could write.
|
|
75
|
+
|
|
76
|
+
"""
|
|
77
|
+
|
|
78
|
+
name: str
|
|
79
|
+
offset: int
|
|
80
|
+
kind: str
|
|
81
|
+
hidden: bool
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
@dataclass(frozen=True)
|
|
85
|
+
class FrameLayout:
|
|
86
|
+
"""The slots of one piece of code's frame, so its names can be found from `r7`.
|
|
87
|
+
|
|
88
|
+
Attributes:
|
|
89
|
+
function: The function's name, or None for the top-level program.
|
|
90
|
+
slots: Its parameters (in order), then its variables (in slot order).
|
|
91
|
+
|
|
92
|
+
"""
|
|
93
|
+
|
|
94
|
+
function: str | None
|
|
95
|
+
slots: tuple[Slot, ...]
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
@dataclass(frozen=True)
|
|
99
|
+
class Assembly:
|
|
100
|
+
"""The assembly text for a whole program, and the Pebble line of each text line.
|
|
101
|
+
|
|
102
|
+
Attributes:
|
|
103
|
+
text: The assembly, ready for `pycpu.assembler.assemble`.
|
|
104
|
+
lines: For each line of `text` (the first is index 0), the Pebble line it was
|
|
105
|
+
written for, or None for the runtime routines, the text data and headings.
|
|
106
|
+
frames: For each line of `text`, the frame layout that `r7` points at when the
|
|
107
|
+
line's instruction is about to run, or None where the frame is not ready:
|
|
108
|
+
the prologue, the `ret` of a return, the runtime routines and the data.
|
|
109
|
+
|
|
110
|
+
"""
|
|
111
|
+
|
|
112
|
+
text: str
|
|
113
|
+
lines: tuple[int | None, ...]
|
|
114
|
+
frames: tuple[FrameLayout | None, ...]
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def frame_words(checked: CheckedCode) -> int:
|
|
118
|
+
"""Count the stack words a piece of code may need: old r7, variables, stack, routines.
|
|
119
|
+
|
|
120
|
+
The deepest stack already counts the arguments it pushes for a call. On top of
|
|
121
|
+
that, a call to a routine needs `RUNTIME_STACK_WORDS` and a call to a Pebble
|
|
122
|
+
function needs just its return address, so the larger of the two is set aside; the
|
|
123
|
+
called function checks the room for its own frame in its own prologue.
|
|
124
|
+
"""
|
|
125
|
+
calls = max(RUNTIME_STACK_WORDS, RETURN_ADDRESS_WORDS)
|
|
126
|
+
return 1 + len(checked.variables) + checked.deepest + calls
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def function_label(name: str) -> str:
|
|
130
|
+
"""Return the label where the Pebble function `name` starts, such as `__fn_double`.
|
|
131
|
+
|
|
132
|
+
A Pebble name may hold letters from any language, but a label may only hold the
|
|
133
|
+
plain letters A to Z, digits and `_`. So plain letters and digits stay, `_` is
|
|
134
|
+
written twice, and any other character becomes `_x`, its number in hex, and `_`
|
|
135
|
+
(`café` becomes `__fn_caf_xe9_`). The other labels of the function add `_` and a
|
|
136
|
+
number or a word to this one. Read a label left to right after `__fn_`: a letter
|
|
137
|
+
or digit is itself; a `_` followed by `_` is an underscore; a `_` followed by `x`
|
|
138
|
+
starts an escape, which runs over hex digits to its closing `_`. Any other `_` must
|
|
139
|
+
be the start of an addition, because none of them begin with `_` or `x`. So every
|
|
140
|
+
label reads back in exactly one way, and no label of one function can ever be
|
|
141
|
+
spelled the same as a label of another.
|
|
142
|
+
"""
|
|
143
|
+
pieces = [
|
|
144
|
+
char if char in _ASCII_LETTERS_AND_DIGITS else "__" if char == "_" else f"_x{ord(char):x}_"
|
|
145
|
+
for char in name
|
|
146
|
+
]
|
|
147
|
+
return FUNCTION_PREFIX + "".join(pieces)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def is_pebble_name(name: str) -> bool:
|
|
151
|
+
"""Say whether `name` could be written in a Pebble program (a letter or `_`, then more)."""
|
|
152
|
+
return (
|
|
153
|
+
bool(name)
|
|
154
|
+
and (name[0].isalpha() or name[0] == "_")
|
|
155
|
+
and all(char.isalnum() or char == "_" for char in name)
|
|
156
|
+
)
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _quote(text: str) -> str:
|
|
160
|
+
"""Write text in double quotes the way the assembler's `.string` reads it back."""
|
|
161
|
+
escapes = {"\\": "\\\\", '"': '\\"', "\n": "\\n", "\t": "\\t"}
|
|
162
|
+
return '"' + "".join(escapes.get(char, char) for char in text) + '"'
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
class _Writer:
|
|
166
|
+
"""Collect assembly lines, each tagged with the Pebble line it belongs to."""
|
|
167
|
+
|
|
168
|
+
def __init__(self) -> None:
|
|
169
|
+
"""Start with no lines and no text."""
|
|
170
|
+
self.lines: list[str] = []
|
|
171
|
+
self.pebble: list[int | None] = []
|
|
172
|
+
self.frames: list[FrameLayout | None] = []
|
|
173
|
+
# The frame that is ready for the lines being written now, if any.
|
|
174
|
+
self.frame: FrameLayout | None = None
|
|
175
|
+
self.texts: dict[str, str] = {}
|
|
176
|
+
|
|
177
|
+
def raw(self, text: str, line: int | None = None) -> None:
|
|
178
|
+
"""Add one or more lines exactly as written."""
|
|
179
|
+
for piece in text.split("\n"):
|
|
180
|
+
self.lines.append(piece)
|
|
181
|
+
self.pebble.append(line)
|
|
182
|
+
self.frames.append(self.frame)
|
|
183
|
+
|
|
184
|
+
def op(self, instruction: str, comment: str, line: int | None) -> None:
|
|
185
|
+
"""Add one indented instruction with a comment lined up beside it."""
|
|
186
|
+
# A long instruction still gets one space before its comment.
|
|
187
|
+
self.raw(f" {instruction:<{COLUMN - 1}} ; {comment}", line)
|
|
188
|
+
|
|
189
|
+
def text_label(self, text: str) -> str:
|
|
190
|
+
"""Return the label of a piece of text, giving it a new one the first time."""
|
|
191
|
+
return self.texts.setdefault(text, f"__str_{len(self.texts)}")
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
class _CodeWriter:
|
|
195
|
+
"""Write the assembly for one piece of Pebble code: main or one function."""
|
|
196
|
+
|
|
197
|
+
def __init__(
|
|
198
|
+
self, writer: _Writer, checked: CheckedCode, label: str, program: CheckedProgram
|
|
199
|
+
) -> None:
|
|
200
|
+
"""Get ready to write `checked`, whose code starts at `label`."""
|
|
201
|
+
self.out = writer
|
|
202
|
+
self.checked = checked
|
|
203
|
+
self.code = checked.code
|
|
204
|
+
self.label = label
|
|
205
|
+
self.program = program
|
|
206
|
+
# Variables sit below r7; parameters above it, where the caller pushed them,
|
|
207
|
+
# the last one nearest: parameter i of N is at [r7 + 2 + (N - 1 - i)].
|
|
208
|
+
count = len(self.code.parameters)
|
|
209
|
+
self.slots = {name: 2 + (count - 1 - i) for i, name in enumerate(self.code.parameters)}
|
|
210
|
+
self.slots.update({name: -1 - j for j, name in enumerate(checked.variables)})
|
|
211
|
+
kinds = [(name, "parameter") for name in self.code.parameters]
|
|
212
|
+
kinds += [(name, "variable") for name in checked.variables]
|
|
213
|
+
self.layout = FrameLayout(
|
|
214
|
+
None if label == MAIN_LABEL else checked.name,
|
|
215
|
+
tuple(
|
|
216
|
+
Slot(name, self.slots[name], kind, not is_pebble_name(name)) for name, kind in kinds
|
|
217
|
+
),
|
|
218
|
+
)
|
|
219
|
+
self.places = located(self.code.instructions)
|
|
220
|
+
first = first_place(self.places)
|
|
221
|
+
self.first_line = first.line if first is not None else None
|
|
222
|
+
# Every instruction some jump goes to gets a label: its "page number".
|
|
223
|
+
self.targets = {int(i.operand or 0) for i in self.code.instructions if i.opcode in JUMPS}
|
|
224
|
+
|
|
225
|
+
def write(self) -> None:
|
|
226
|
+
"""Write the prologue, then the cards for every bytecode instruction.
|
|
227
|
+
|
|
228
|
+
The prologue's words have no ready frame (`r7` still points at the caller's
|
|
229
|
+
until `getsp r7`, and the variables are not made until the last `push r0`);
|
|
230
|
+
from just after it, the frame is this code's.
|
|
231
|
+
"""
|
|
232
|
+
self.out.frame = None
|
|
233
|
+
self._prologue()
|
|
234
|
+
self.out.frame = self.layout
|
|
235
|
+
for index, instruction in enumerate(self.code.instructions):
|
|
236
|
+
place = self.places[index]
|
|
237
|
+
line = place.line if place else None
|
|
238
|
+
if index in self.targets:
|
|
239
|
+
self.out.raw(f"{self._page(index)}:", line)
|
|
240
|
+
self.out.raw(f" ; {self._describe(instruction, line)}", line)
|
|
241
|
+
self._instruction(index, instruction, line)
|
|
242
|
+
|
|
243
|
+
def _page(self, index: int) -> str:
|
|
244
|
+
"""Return the label of instruction `index`, such as `__main_7`."""
|
|
245
|
+
return f"{self.label}_{index}"
|
|
246
|
+
|
|
247
|
+
def _describe(self, instruction: Instruction, line: int | None) -> str:
|
|
248
|
+
"""Say which Pebble instruction the next few lines come from, for a reader."""
|
|
249
|
+
operand = instruction.operand
|
|
250
|
+
if instruction.opcode == OpCode.LOAD_CONST:
|
|
251
|
+
value = self.code.constants[int(operand or 0)]
|
|
252
|
+
operand = _quote(value) if isinstance(value, str) else value
|
|
253
|
+
words = f"{instruction.opcode}" if operand is None else f"{instruction.opcode} {operand}"
|
|
254
|
+
return f"line {line}: {words}" if line is not None else words
|
|
255
|
+
|
|
256
|
+
def _prologue(self) -> None:
|
|
257
|
+
"""Check there is room on the stack, then build the frame and zero the variables."""
|
|
258
|
+
line, out, label = self.first_line, self.out, self.label
|
|
259
|
+
count = len(self.checked.variables)
|
|
260
|
+
need = frame_words(self.checked)
|
|
261
|
+
out.raw(f"{label}:", line)
|
|
262
|
+
out.raw(
|
|
263
|
+
f" ; make the frame: 1 word for the old r7, {count} for variables, "
|
|
264
|
+
f"{self.checked.deepest} for the stack, {RUNTIME_STACK_WORDS} for the routines",
|
|
265
|
+
line,
|
|
266
|
+
)
|
|
267
|
+
out.op("getsp r1", "r1 = the top of the stack, where the frame starts", line)
|
|
268
|
+
out.op(f"set r2, {END_LABEL}", "r2 = the first free word after the program", line)
|
|
269
|
+
load = "li " if need <= BYTE_MAX else "set "
|
|
270
|
+
out.op(f"{load} r3, {need}", f"r3 = the {need} words this code may need", line)
|
|
271
|
+
out.op("add r2, r2, r3", "r2 = the lowest the stack may start from", line)
|
|
272
|
+
out.op("cmp r1, r2", "is there room?", line)
|
|
273
|
+
out.op(f"br geu, {label}_room", "yes: carry on", line)
|
|
274
|
+
out.op("halt 2", "no: STACK_OVERFLOW, before anything is overwritten", line)
|
|
275
|
+
out.raw(f"{label}_room:", line)
|
|
276
|
+
out.op("push r7", "keep the old frame pointer", line)
|
|
277
|
+
out.op("getsp r7", "r7 = the frame pointer: variables sit just below it", line)
|
|
278
|
+
for name in self.checked.variables:
|
|
279
|
+
out.op("push r0", f"{name} = 0, at [r7{self.slots[name]}]", line)
|
|
280
|
+
|
|
281
|
+
def _instruction(self, index: int, instruction: Instruction, line: int | None) -> None:
|
|
282
|
+
"""Write the cards for one bytecode instruction."""
|
|
283
|
+
out, opcode = self.out, instruction.opcode
|
|
284
|
+
if opcode == OpCode.LOAD_CONST:
|
|
285
|
+
self._load_constant(int(instruction.operand or 0), line)
|
|
286
|
+
elif opcode in (OpCode.LOAD_NAME, OpCode.STORE_NAME):
|
|
287
|
+
self._variable(opcode, str(instruction.operand), line)
|
|
288
|
+
elif opcode in (*_ALU, OpCode.MULTIPLY, OpCode.FLOOR_DIVIDE, OpCode.MODULO):
|
|
289
|
+
self._arithmetic(index, opcode, line)
|
|
290
|
+
elif opcode in COMPARISONS:
|
|
291
|
+
self._compare(index, opcode, line)
|
|
292
|
+
elif opcode == OpCode.NOT:
|
|
293
|
+
self._not(index, line)
|
|
294
|
+
elif opcode in JUMPS:
|
|
295
|
+
self._jump(index, opcode, int(instruction.operand or 0), line)
|
|
296
|
+
elif opcode in (OpCode.NEGATE, OpCode.POP, OpCode.PRINT):
|
|
297
|
+
self._one_value(index, opcode, line)
|
|
298
|
+
elif opcode in (OpCode.HALT, OpCode.RETURN):
|
|
299
|
+
self._leave(opcode, line)
|
|
300
|
+
elif opcode == OpCode.CALL:
|
|
301
|
+
self._call(str(instruction.operand), line)
|
|
302
|
+
elif opcode == OpCode.CHECK_TYPE:
|
|
303
|
+
out.raw(" ; (no code: Pebble has already checked this is a number)", line)
|
|
304
|
+
else:
|
|
305
|
+
# The subset check should have refused it; writing nothing would be wrong code.
|
|
306
|
+
msg = f"translator bug: no code for {opcode}"
|
|
307
|
+
raise PebbleCPUError(msg)
|
|
308
|
+
|
|
309
|
+
def _one_value(self, index: int, opcode: OpCode, line: int | None) -> None:
|
|
310
|
+
"""Write `NEGATE`, `POP` or `PRINT`, which each take one value off the stack."""
|
|
311
|
+
out = self.out
|
|
312
|
+
if opcode == OpCode.NEGATE:
|
|
313
|
+
out.op("pop r1", "r1 = the number", line)
|
|
314
|
+
out.op("sub r1, r0, r1", "r1 = 0 - r1", line)
|
|
315
|
+
out.op("push r1", "the answer goes on the stack", line)
|
|
316
|
+
elif opcode == OpCode.POP:
|
|
317
|
+
out.op("pop r1", "the value is not needed: throw it away", line)
|
|
318
|
+
else:
|
|
319
|
+
routine = "__print_text" if index in self.checked.prints_text else "__print_int"
|
|
320
|
+
out.op("pop r1", "r1 = the thing to print", line)
|
|
321
|
+
out.op(f"call {routine}", "print it and a newline", line)
|
|
322
|
+
|
|
323
|
+
def _leave(self, opcode: OpCode, line: int | None) -> None:
|
|
324
|
+
"""Write `HALT` (stop the machine) or `RETURN` (give a value back to the caller)."""
|
|
325
|
+
out = self.out
|
|
326
|
+
if opcode == OpCode.HALT:
|
|
327
|
+
out.op("halt 0", "the program has finished", line)
|
|
328
|
+
return
|
|
329
|
+
out.op("pop r1", "r1 = the value to give back", line)
|
|
330
|
+
out.op("setsp r7", "drop the variables and the stack in one go", line)
|
|
331
|
+
out.op("pop r7", "get the caller's frame pointer back", line)
|
|
332
|
+
# `r7` is the caller's now, but `pc` is still in this code: no frame is ready.
|
|
333
|
+
out.frame = None
|
|
334
|
+
out.op("ret", "go back to the caller", line)
|
|
335
|
+
out.frame = self.layout
|
|
336
|
+
|
|
337
|
+
def _call(self, name: str, line: int | None) -> None:
|
|
338
|
+
"""Write a call to a Pebble function, whose arguments are already on the stack.
|
|
339
|
+
|
|
340
|
+
The function leaves its answer in `r1`. Afterwards the arguments are still on
|
|
341
|
+
the stack, so the stack pointer is moved up past them in one go.
|
|
342
|
+
"""
|
|
343
|
+
out = self.out
|
|
344
|
+
count = len(self.program.functions[name].code.parameters)
|
|
345
|
+
where = "leaving the return address on the stack"
|
|
346
|
+
out.op(f"call {function_label(name)}", f"go to {name}, {where}", line)
|
|
347
|
+
if count:
|
|
348
|
+
words = "the argument is" if count == 1 else f"the {count} arguments are"
|
|
349
|
+
plural = "" if count == 1 else "s"
|
|
350
|
+
out.op("getsp r2", "r2 = the top of the stack", line)
|
|
351
|
+
out.op(f"addi r2, {count}", f"step over the {count} argument{plural}", line)
|
|
352
|
+
out.op("setsp r2", f"{words} thrown away", line)
|
|
353
|
+
out.op("push r1", f"the answer {name} gave back goes on the stack", line)
|
|
354
|
+
|
|
355
|
+
def _variable(self, opcode: OpCode, name: str, line: int | None) -> None:
|
|
356
|
+
"""Write `LOAD_NAME` or `STORE_NAME`: copy between the stack and the name's slot."""
|
|
357
|
+
out, slot = self.out, f"[r7{self.slots[name]:+d}]"
|
|
358
|
+
if opcode == OpCode.LOAD_NAME:
|
|
359
|
+
out.op(f"load r1, {slot}", f"r1 = {name}", line)
|
|
360
|
+
out.op("push r1", "onto the stack", line)
|
|
361
|
+
else:
|
|
362
|
+
out.op("pop r1", "r1 = the value on top of the stack", line)
|
|
363
|
+
out.op(f"store r1, {slot}", f"{name} = r1", line)
|
|
364
|
+
|
|
365
|
+
def _arithmetic(self, index: int, opcode: OpCode, line: int | None) -> None:
|
|
366
|
+
"""Write `+`, `-` and `*` here; `//` and `%` need a divide-by-zero check first."""
|
|
367
|
+
out = self.out
|
|
368
|
+
if opcode in (OpCode.FLOOR_DIVIDE, OpCode.MODULO):
|
|
369
|
+
self._divide(index, opcode, line)
|
|
370
|
+
return
|
|
371
|
+
self._two_numbers(line)
|
|
372
|
+
if opcode in _ALU:
|
|
373
|
+
out.op(f"{_ALU[opcode]} r1, r1, r2", "work it out", line)
|
|
374
|
+
else:
|
|
375
|
+
out.op("call __mul", "r1 = r1 * r2", line)
|
|
376
|
+
out.op("push r1", "the answer goes on the stack", line)
|
|
377
|
+
|
|
378
|
+
def _load_constant(self, number: int, line: int | None) -> None:
|
|
379
|
+
"""Write the cards that put a number, or the address of a text, on the stack."""
|
|
380
|
+
value = self.code.constants[number]
|
|
381
|
+
if value is None:
|
|
382
|
+
self.out.op("push r0", "null is stored as 0", line)
|
|
383
|
+
return
|
|
384
|
+
if isinstance(value, str):
|
|
385
|
+
label = self.out.text_label(value)
|
|
386
|
+
self.out.op(f"set r1, {label}", "r1 = the address of the text", line)
|
|
387
|
+
elif isinstance(value, bool): # before int: in Python, True is also an int
|
|
388
|
+
word = int(value)
|
|
389
|
+
self.out.op(f"li r1, {word}", f"{str(value).lower()} is {word} (0 means false)", line)
|
|
390
|
+
elif isinstance(value, int): # the subset check let only these kinds through
|
|
391
|
+
load = "li " if 0 <= value <= BYTE_MAX else "set "
|
|
392
|
+
self.out.op(f"{load} r1, {value}", f"r1 = {value}", line)
|
|
393
|
+
self.out.op("push r1", "onto the stack", line)
|
|
394
|
+
|
|
395
|
+
def _two_numbers(self, line: int | None) -> None:
|
|
396
|
+
"""Pop the two numbers an operator works on: the right one is on top."""
|
|
397
|
+
self.out.op("pop r2", "r2 = the right-hand number", line)
|
|
398
|
+
self.out.op("pop r1", "r1 = the left-hand number", line)
|
|
399
|
+
|
|
400
|
+
def _compare(self, index: int, opcode: OpCode, line: int | None) -> None:
|
|
401
|
+
"""Write a comparison: `cmp` lights the flags, a signed branch reads them."""
|
|
402
|
+
out, yes = self.out, f"{self.label}_yes_{index}"
|
|
403
|
+
condition, symbol = _BRANCHES[opcode]
|
|
404
|
+
self._two_numbers(line)
|
|
405
|
+
out.op("li r3, 1", "r3 = 1 (true), unless we find otherwise", line)
|
|
406
|
+
out.op("cmp r1, r2", "work out r1 - r2, keeping only the flags", line)
|
|
407
|
+
out.op(f"br {condition}, {yes}", f"is r1 {symbol} r2? then keep the 1", line)
|
|
408
|
+
out.op("li r3, 0", "no: r3 = 0 (false)", line)
|
|
409
|
+
out.raw(f"{yes}:", line)
|
|
410
|
+
out.op("push r3", "true or false goes on the stack", line)
|
|
411
|
+
|
|
412
|
+
def _not(self, index: int, line: int | None) -> None:
|
|
413
|
+
"""Write `not`: 0 (false) becomes 1, and anything else becomes 0."""
|
|
414
|
+
out, yes = self.out, f"{self.label}_yes_{index}"
|
|
415
|
+
out.op("pop r1", "r1 = the condition", line)
|
|
416
|
+
out.op("li r3, 1", "r3 = 1 (true), unless we find otherwise", line)
|
|
417
|
+
out.op("cmp r1, r0", "is the condition 0 (false)?", line)
|
|
418
|
+
out.op(f"br eq, {yes}", "yes: not false is true, keep the 1", line)
|
|
419
|
+
out.op("li r3, 0", "no: not true is false", line)
|
|
420
|
+
out.raw(f"{yes}:", line)
|
|
421
|
+
out.op("push r3", "true or false goes on the stack", line)
|
|
422
|
+
|
|
423
|
+
def _jump(self, index: int, opcode: OpCode, target: int, line: int | None) -> None:
|
|
424
|
+
"""Write a jump to instruction `target`.
|
|
425
|
+
|
|
426
|
+
A `br` only reaches 255 words forwards or 256 back, and a loop can be longer, so
|
|
427
|
+
a jump that depends on a condition branches *over* a `jmp`, which reaches anywhere.
|
|
428
|
+
"""
|
|
429
|
+
out, page, go_on = self.out, self._page(target), f"{self.label}_go_on_{index}"
|
|
430
|
+
if opcode == OpCode.JUMP:
|
|
431
|
+
out.op(f"jmp {page}", f"go to instruction {target}", line)
|
|
432
|
+
return
|
|
433
|
+
if opcode == OpCode.JUMP_IF_FALSE:
|
|
434
|
+
out.op("pop r1", "r1 = the condition", line)
|
|
435
|
+
out.op("cmp r1, r0", "is it 0 (false)?", line)
|
|
436
|
+
out.op(f"br ne, {go_on}", "no, it is true: carry on", line)
|
|
437
|
+
out.op(f"jmp {page}", f"yes, false: go to instruction {target}", line)
|
|
438
|
+
else:
|
|
439
|
+
# `and` stops at a false left side, `or` at a true one; either way that
|
|
440
|
+
# value is the answer, so it goes back on the stack before the jump.
|
|
441
|
+
decides = "false" if opcode == OpCode.JUMP_IF_FALSE_OR_POP else "true"
|
|
442
|
+
other = "eq" if decides == "true" else "ne"
|
|
443
|
+
out.op("pop r1", "r1 = the left-hand side", line)
|
|
444
|
+
out.op("cmp r1, r0", "is it 0 (false)?", line)
|
|
445
|
+
out.op(f"br {other}, {go_on}", "the right-hand side decides: work it out", line)
|
|
446
|
+
out.op("push r1", f"it is {decides}, so it is the answer: keep it", line)
|
|
447
|
+
out.op(f"jmp {page}", f"and skip to instruction {target}", line)
|
|
448
|
+
out.raw(f"{go_on}:", line)
|
|
449
|
+
|
|
450
|
+
def _divide(self, index: int, opcode: str, line: int | None) -> None:
|
|
451
|
+
"""Write `//` or `%`: check the divisor is not 0, then call `__divmod`."""
|
|
452
|
+
out, ok = self.out, f"{self.label}_divisor_ok_{index}"
|
|
453
|
+
self._two_numbers(line)
|
|
454
|
+
out.op("cmp r2, r0", "is the divisor 0?", line)
|
|
455
|
+
out.op(f"br ne, {ok}", "no: go ahead and divide", line)
|
|
456
|
+
out.op("halt 3", "yes: DIVIDE_BY_ZERO", line)
|
|
457
|
+
out.raw(f"{ok}:", line)
|
|
458
|
+
out.op("call __divmod", "r1 = r1 // r2, r2 = r1 % r2", line)
|
|
459
|
+
keep = "r1" if opcode == OpCode.FLOOR_DIVIDE else "r2"
|
|
460
|
+
out.op(f"push {keep}", "the answer goes on the stack", line)
|
|
461
|
+
|
|
462
|
+
|
|
463
|
+
def generate(program: CheckedProgram) -> Assembly:
|
|
464
|
+
"""Write the assembly for a checked Pebble program.
|
|
465
|
+
|
|
466
|
+
The layout from address 0 is: main (ending in `halt 0`), each function, the runtime
|
|
467
|
+
routines, the text data, then the label `__end`, the first word the stack must
|
|
468
|
+
never reach.
|
|
469
|
+
|
|
470
|
+
Args:
|
|
471
|
+
program: A program that passed `check_program`.
|
|
472
|
+
|
|
473
|
+
Returns:
|
|
474
|
+
The assembly text and the Pebble line of each of its lines.
|
|
475
|
+
|
|
476
|
+
"""
|
|
477
|
+
out = _Writer()
|
|
478
|
+
out.raw("; ==== main: the Pebble program's own code ====")
|
|
479
|
+
_CodeWriter(out, program.main, MAIN_LABEL, program).write()
|
|
480
|
+
for name, checked in program.functions.items():
|
|
481
|
+
out.frame = None
|
|
482
|
+
parameters = ", ".join(checked.code.parameters)
|
|
483
|
+
out.raw(f"; ==== function {name}({parameters}): its own frame, like main's ====")
|
|
484
|
+
_CodeWriter(out, checked, function_label(name), program).write()
|
|
485
|
+
out.frame = None
|
|
486
|
+
out.raw("; ==== runtime: the ready-made routines for multiply, divide and print ====")
|
|
487
|
+
out.raw(RUNTIME.strip("\n"))
|
|
488
|
+
out.raw("; ==== text: every piece of text, one character per word, ending in 0 ====")
|
|
489
|
+
for text, label in out.texts.items():
|
|
490
|
+
out.raw(f"{label}: .string {_quote(text)}")
|
|
491
|
+
out.raw(f"; ==== the end of the program: the stack must never grow down to {END_LABEL} ====")
|
|
492
|
+
out.raw(f"{END_LABEL}:")
|
|
493
|
+
return Assembly("\n".join(out.lines) + "\n", tuple(out.pebble), tuple(out.frames))
|