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.
Files changed (47) hide show
  1. fromscratch_pycpu-0.1.0.dist-info/METADATA +232 -0
  2. fromscratch_pycpu-0.1.0.dist-info/RECORD +47 -0
  3. fromscratch_pycpu-0.1.0.dist-info/WHEEL +4 -0
  4. fromscratch_pycpu-0.1.0.dist-info/entry_points.txt +2 -0
  5. fromscratch_pycpu-0.1.0.dist-info/licenses/LICENSE +21 -0
  6. pycpu/__init__.py +11 -0
  7. pycpu/__main__.py +68 -0
  8. pycpu/_version.py +24 -0
  9. pycpu/arithmetic.py +176 -0
  10. pycpu/assembler.py +580 -0
  11. pycpu/circuit.py +359 -0
  12. pycpu/cockpit/__init__.py +8 -0
  13. pycpu/cockpit/app.py +545 -0
  14. pycpu/cockpit/code.py +161 -0
  15. pycpu/cockpit/examples/countdown.pebble +7 -0
  16. pycpu/cockpit/examples/divide-by-zero.pebble +7 -0
  17. pycpu/cockpit/examples/factorial.pebble +9 -0
  18. pycpu/cockpit/examples/greeting.pebble +4 -0
  19. pycpu/cockpit/examples/times-table.pebble +6 -0
  20. pycpu/cockpit/examples/tour.pebble +31 -0
  21. pycpu/cockpit/explain.py +660 -0
  22. pycpu/cockpit/page.html +1261 -0
  23. pycpu/cockpit/picture.py +470 -0
  24. pycpu/cockpit/session.py +778 -0
  25. pycpu/cockpit/walks/a-call-and-the-stack.toml +47 -0
  26. pycpu/cockpit/walks/many-instructions.toml +39 -0
  27. pycpu/cockpit/walks/subtracting-with-gates.toml +39 -0
  28. pycpu/cockpit/walks/where-n-lives.toml +39 -0
  29. pycpu/cockpit/walks/why-the-clock-ticks.toml +50 -0
  30. pycpu/cockpit/walks.py +518 -0
  31. pycpu/computer.py +175 -0
  32. pycpu/cpu.py +648 -0
  33. pycpu/cpu_parts.py +140 -0
  34. pycpu/fast.py +320 -0
  35. pycpu/isa.py +243 -0
  36. pycpu/logic.py +222 -0
  37. pycpu/memory.py +268 -0
  38. pycpu/proof.py +263 -0
  39. pycpu/py.typed +0 -0
  40. pycpu/simulator.py +361 -0
  41. pycpu/state.py +146 -0
  42. pycpu/translator/__init__.py +29 -0
  43. pycpu/translator/codegen.py +493 -0
  44. pycpu/translator/program.py +211 -0
  45. pycpu/translator/runtime.py +166 -0
  46. pycpu/translator/subset.py +688 -0
  47. pycpu/view.py +55 -0
@@ -0,0 +1,211 @@
1
+ """Translate and run: the front desk where a Pebble program goes in and its output comes out.
2
+
3
+ Think of a translation agency. You hand a recipe over the counter; behind the counter,
4
+ one person checks it for anything the cook cannot make (the subset check), another
5
+ writes the cards (the code generator), and a third turns the written cards into the
6
+ cook's number code (the assembler). You get back the finished pile, with a note on each
7
+ card saying which line of your recipe it came from.
8
+
9
+ `translate` is that counter. `run_pebble` goes one step further: it hands the pile to
10
+ the fast engine, lets the cook work, and tells you what was printed and, if something
11
+ went wrong, which Pebble line was running.
12
+ """
13
+
14
+ from dataclasses import dataclass
15
+ from typing import Self
16
+
17
+ from pebble import compile_source
18
+
19
+ from pycpu.assembler import Program, ProgramTooLongError, assemble
20
+ from pycpu.fast import FastMachine
21
+ from pycpu.isa import Fault
22
+ from pycpu.memory import RAM_WORDS
23
+ from pycpu.state import MachineState
24
+ from pycpu.translator.codegen import END_LABEL, FrameLayout, frame_words, generate
25
+ from pycpu.translator.subset import TOO_BIG, UnsupportedFeature, check_program
26
+
27
+
28
+ @dataclass(frozen=True)
29
+ class TranslatedProgram:
30
+ """A Pebble program turned into PyCPU machine code, with its source map.
31
+
32
+ Attributes:
33
+ source: The Pebble program as written.
34
+ assembly: The assembly the translator wrote for it, comments and all.
35
+ program: The assembled machine code, its labels and the assembly line of each word.
36
+ pebble_lines: For every machine word, the Pebble line that made it, or None
37
+ for the runtime routines and the text data.
38
+ main_frame_words: The stack words the top-level code needs for its own frame.
39
+ frames: For every machine word, the layout of the frame `r7` points at just
40
+ before that word runs, or None where no frame is ready: the runtime
41
+ routines, the text data, every prologue word and each return's `ret`.
42
+
43
+ """
44
+
45
+ source: str
46
+ assembly: str
47
+ program: Program
48
+ pebble_lines: tuple[int | None, ...]
49
+ main_frame_words: int
50
+ frames: tuple[FrameLayout | None, ...]
51
+
52
+ @property
53
+ def memory_needed(self) -> int:
54
+ """Count the words of memory the program, its text and main's first frame need."""
55
+ return self.program.labels[END_LABEL] + self.main_frame_words
56
+
57
+ def line_at(self, address: int) -> int | None:
58
+ """Return the Pebble line of the word at `address`, or None if it has none."""
59
+ if 0 <= address < len(self.pebble_lines):
60
+ return self.pebble_lines[address]
61
+ return None
62
+
63
+
64
+ @dataclass(frozen=True)
65
+ class PebbleRun:
66
+ """What happened when a Pebble program ran on PyCPU.
67
+
68
+ Attributes:
69
+ output: Everything it printed.
70
+ halted: True if the machine stopped by itself; False if it ran out of steps.
71
+ fault: Why it stopped, if it stopped because something went wrong.
72
+ line: The Pebble line that was running when the fault happened, else None.
73
+ steps: How many instructions the machine carried out.
74
+ by_call: For a stack overflow, True if a call that found no room is to blame;
75
+ False when main's own first frame did not fit, so no call is involved.
76
+
77
+ """
78
+
79
+ output: str
80
+ halted: bool
81
+ fault: Fault | None
82
+ line: int | None
83
+ steps: int
84
+ by_call: bool = True
85
+
86
+ @classmethod
87
+ def from_state(cls, translated: TranslatedProgram, state: MachineState, steps: int) -> Self:
88
+ """Read how a run of `translated` went from the machine it ran on.
89
+
90
+ Either engine's state will do: `run_pebble` passes the fast engine's, and the
91
+ Cockpit passes the gate engine's.
92
+
93
+ Args:
94
+ translated: The program that was running.
95
+ state: The machine as it is now.
96
+ steps: How many instructions it has carried out, stored as given. A
97
+ caller that does not count (the Cockpit) passes 0; `describe` only
98
+ mentions the count for a run that has not halted.
99
+
100
+ Returns:
101
+ The output, whether it halted, any fault, and the Pebble line to blame.
102
+
103
+ """
104
+ fault = Fault(state.halt_code) if state.halted and state.halt_code else None
105
+ line = None
106
+ if fault is not None:
107
+ line = _fault_line(translated, state, fault)
108
+ # Each output word is one character's code, kept whole (not cut to a byte).
109
+ output = "".join(chr(code) for code in state.output)
110
+ # With an empty stack there is no return address, so main's own frame overflowed.
111
+ by_call = not (fault is Fault.STACK_OVERFLOW and state.sp >= len(state.memory))
112
+ return cls(output, state.halted, fault, line, steps, by_call)
113
+
114
+ def describe(self) -> str:
115
+ """Say in one friendly sentence how the run ended.
116
+
117
+ Returns:
118
+ For example "Division by zero at line 3", or "The program finished". When
119
+ the Pebble line is unknown, the sentence leaves it out.
120
+
121
+ """
122
+ if self.fault is None:
123
+ if self.halted:
124
+ return "The program finished"
125
+ return f"The program was still running after {self.steps} steps"
126
+ where = "" if self.line is None else f" at line {self.line}"
127
+ if self.fault is Fault.DIVIDE_BY_ZERO:
128
+ return f"Division by zero{where}"
129
+ if self.fault is Fault.STACK_OVERFLOW:
130
+ if not self.by_call:
131
+ return f"The program needs more stack room than there is{where}"
132
+ return (
133
+ f"The stack ran out of room{where} (the call on that line found no room "
134
+ "for another frame; does a function keep calling itself?)"
135
+ )
136
+ return f"The program used a memory address that does not exist{where}"
137
+
138
+
139
+ def translate(source: str) -> TranslatedProgram:
140
+ """Turn a Pebble program into PyCPU machine code.
141
+
142
+ Pebble compiles it to bytecode, the subset check looks at every instruction, the
143
+ code generator writes assembly, and the assembler turns that into words.
144
+
145
+ Args:
146
+ source: The Pebble program.
147
+
148
+ Returns:
149
+ The assembly, the machine code and the Pebble line of every word.
150
+
151
+ Raises:
152
+ pebble.PebbleError: If Pebble itself finds a mistake in the program.
153
+ UnsupportedFeature: If the program uses something PyCPU cannot do yet.
154
+
155
+ """
156
+ checked = check_program(compile_source(source).compiled)
157
+ assembly = generate(checked)
158
+ try:
159
+ program = assemble(assembly.text, words=RAM_WORDS)
160
+ except ProgramTooLongError as error:
161
+ raise UnsupportedFeature(TOO_BIG) from error
162
+ lines = tuple(assembly.lines[line - 1] for line in program.lines)
163
+ frames = tuple(assembly.frames[line - 1] for line in program.lines)
164
+ translated = TranslatedProgram(
165
+ source, assembly.text, program, lines, frame_words(checked.main), frames
166
+ )
167
+ # The prologue would stop the machine with STACK_OVERFLOW before printing anything,
168
+ # so a program with no room left for main's frame is refused here instead.
169
+ if translated.memory_needed > RAM_WORDS:
170
+ raise UnsupportedFeature(TOO_BIG)
171
+ return translated
172
+
173
+
174
+ def _fault_line(translated: TranslatedProgram, state: MachineState, fault: Fault) -> int | None:
175
+ """Find the Pebble line to blame for a fault.
176
+
177
+ A stack overflow is blamed on the call that needed one more frame than there was
178
+ room for. The room check comes before the prologue's `push r7`, so nothing has been
179
+ pushed yet and the top of the stack still holds the return address `call` left; the
180
+ call instruction is the word just before it. Main has no caller (the stack is still
181
+ empty), so its own first line is used. Any other fault is blamed on the faulting
182
+ word: `pc - 1` for an execute fault, `pc` for a fetch fault.
183
+ """
184
+ words = len(state.memory)
185
+ if fault is Fault.STACK_OVERFLOW and state.sp < words:
186
+ return translated.line_at(state.memory[state.sp] - 1)
187
+ # A fetch fault leaves pc on the bad address; any other fault has moved past it.
188
+ return translated.line_at(state.pc if state.pc >= words else state.pc - 1)
189
+
190
+
191
+ def run_pebble(source: str, max_steps: int = 1_000_000) -> PebbleRun:
192
+ """Translate a Pebble program and run it on the fast engine.
193
+
194
+ Args:
195
+ source: The Pebble program.
196
+ max_steps: The most instructions to carry out before giving up.
197
+
198
+ Returns:
199
+ The output, whether it halted, any fault, the Pebble line of the fault, and
200
+ the number of steps.
201
+
202
+ Raises:
203
+ pebble.PebbleError: If Pebble itself finds a mistake in the program.
204
+ UnsupportedFeature: If the program uses something PyCPU cannot do yet.
205
+
206
+ """
207
+ translated = translate(source)
208
+ machine = FastMachine()
209
+ machine.load_program(translated.program.words)
210
+ steps = machine.run(max_steps)
211
+ return PebbleRun.from_state(translated, machine.state(), steps)
@@ -0,0 +1,166 @@
1
+ """The runtime: a drawer of ready-made recipes the translated program can call.
2
+
3
+ Imagine a kitchen with a card that says "to whisk eggs, do these twelve steps". Every
4
+ recipe that needs whisked eggs just says "whisk (see card)" instead of repeating the
5
+ twelve steps. The CPU has no multiply or divide instruction, so these cards are the
6
+ twelve steps: `__mul` multiplies by shifting and adding, and `__divmod` divides by
7
+ shifting and subtracting. A second pair of cards, `__print_int` and `__print_text`, post
8
+ characters one at a time through the output port, like a cash register with a slot for
9
+ one letter, so a number is broken into digits first. They are plain PyCPU assembly text
10
+ in `RUNTIME`, to be pasted after any program's code, so they run on the machine like
11
+ everything else and the Cockpit can show them.
12
+
13
+ The calling rules: put the inputs in `r1` and `r2` (`__print_int` and `__print_text`
14
+ take just `r1`), `call` the routine, and find the answer in `r1` (and `r2`). `r0`
15
+ (always 0) and `r7` (the frame pointer) are never changed; `r1` to `r6` may be. Every
16
+ label starts with two underscores, so it can never clash with a label a translator
17
+ generates.
18
+ """
19
+
20
+ # The deepest case is __print_int on a 5-digit negative number: 1 word for its return
21
+ # address, 1 for the sentinel, 4 digits already waiting while the 5th is being worked
22
+ # out, 1 for the return address of the `call __divmod`, and 2 pushes inside __divmod.
23
+ # A test measures the real deepest use of every routine and checks this number.
24
+ RUNTIME_STACK_WORDS = 9
25
+
26
+ RUNTIME = """
27
+ ; ---------------------------------------------------------------------------
28
+ ; __mul: r1 = (r1 * r2) mod 65536, by shift and add (long multiplication).
29
+ ; Uses r3 (the running total), r4 (the constant 1), r5 (scratch).
30
+ ; ---------------------------------------------------------------------------
31
+ __mul:
32
+ li r3, 0 ; total = 0: nothing added up yet
33
+ li r4, 1 ; r4 = 1, so we can pick out the lowest bit of r2
34
+ __mul_loop:
35
+ cmp r2, r0 ; is the bottom number used up (all zero bits left)?
36
+ br eq, __mul_done ; yes: the total is the answer
37
+ and r5, r2, r4 ; r5 = the lowest bit of r2: 1 means "add a row"
38
+ br eq, __mul_skip ; the bit was 0: this row is nothing, skip the add
39
+ add r3, r3, r1 ; the bit was 1: add the (shifted) top number to the total
40
+ __mul_skip:
41
+ shl r1, r1 ; slide the top number one place left (double it)
42
+ shr r2, r2 ; move on to the next bit of the bottom number
43
+ jmp __mul_loop ; and do the next row
44
+ __mul_done:
45
+ mov r1, r3 ; hand the total back in r1
46
+ ret ; return to whoever called us
47
+
48
+ ; ---------------------------------------------------------------------------
49
+ ; __divmod: r1 = floor(r1 / r2), r2 = r1 - r2 * floor(r1 / r2), signed 16-bit.
50
+ ; The caller never passes r2 = 0. Uses r3 to r6, and 2 words of stack.
51
+ ; Plan: divide the sizes (ignoring signs) by long division, then fix the signs.
52
+ ; ---------------------------------------------------------------------------
53
+ __divmod:
54
+ push r1 ; keep the original top number (we need its sign later)
55
+ push r2 ; keep the original divisor too
56
+ cmp r1, r0 ; is the top number negative?
57
+ br ge, __divmod_a ; no: leave it alone
58
+ sub r1, r0, r1 ; yes: r1 = 0 - r1, its size without the minus sign
59
+ __divmod_a:
60
+ cmp r2, r0 ; is the divisor negative?
61
+ br ge, __divmod_b ; no: leave it alone
62
+ sub r2, r0, r2 ; yes: take its size too
63
+ __divmod_b:
64
+ li r4, 0 ; r4 = the leftover so far (the remainder), starts at 0
65
+ li r5, 0 ; r5 = the answer so far (the quotient), starts at 0
66
+ li r6, 16 ; r6 = bits still to do: one round for each of 16 bits
67
+ __divmod_loop:
68
+ shl r4, r4 ; make room at the bottom of the leftover
69
+ shl r1, r1 ; slide out the top bit of the number: it lands in carry
70
+ br ltu, __divmod_nobit ; carry is 0: the bit was 0, nothing to bring down
71
+ addi r4, 1 ; the bit was 1: bring it down into the leftover
72
+ __divmod_nobit:
73
+ shl r5, r5 ; make room for a new bit of the answer
74
+ cmp r4, r2 ; does the divisor fit into the leftover?
75
+ br ltu, __divmod_nofit ; no (leftover < divisor): answer bit stays 0
76
+ sub r4, r4, r2 ; yes: take one divisor out of the leftover
77
+ addi r5, 1 ; and write a 1 in the answer
78
+ __divmod_nofit:
79
+ addi r6, -1 ; one bit done
80
+ br ne, __divmod_loop ; more bits left: go round again
81
+ pop r2 ; get the original divisor back
82
+ pop r1 ; get the original top number back
83
+ xor r3, r1, r2 ; r3 is negative exactly when the two signs differ
84
+ cmp r1, r0 ; was the top number negative?
85
+ br ge, __divmod_rem ; no: the leftover stays positive
86
+ sub r4, r0, r4 ; yes: the leftover takes the top number's sign
87
+ __divmod_rem:
88
+ cmp r3, r0 ; do the signs differ?
89
+ br ge, __divmod_done ; no: the answer is already right
90
+ sub r5, r0, r5 ; yes: the answer is negative
91
+ cmp r4, r0 ; was there a leftover?
92
+ br eq, __divmod_done ; no: it divided exactly, nothing to fix
93
+ addi r5, -1 ; yes: floor rounds down, one step further from zero
94
+ add r4, r4, r2 ; and the leftover moves to the divisor's side of 0
95
+ __divmod_done:
96
+ mov r1, r5 ; the quotient goes back in r1
97
+ mov r2, r4 ; the remainder goes back in r2
98
+ ret ; return to whoever called us
99
+
100
+ ; ---------------------------------------------------------------------------
101
+ ; __print_int: print r1 as a signed decimal number, then a newline ("\\n").
102
+ ; Divides by ten again and again with __divmod; each remainder is the next digit,
103
+ ; found last digit first, so the digits wait on the stack and come back reversed.
104
+ ; Uses r1 to r6, and up to 9 words of stack, counting its return address.
105
+ ; ---------------------------------------------------------------------------
106
+ __print_int:
107
+ push r0 ; sentinel: a 0 on the stack marks "no more digits"
108
+ cmp r1, r0 ; is the number negative?
109
+ br ge, __print_int_digits ; no: go straight to the digits loop
110
+ li r3, '-' ; yes: first print the minus sign
111
+ li r6, 0 ; r6 = 0 ...
112
+ addi r6, -1 ; ... minus 1 = 0xFFFF, the address of the output port
113
+ store r3, [r6] ; post the '-' card through the slot
114
+ li r2, 10 ; divide the negative number itself by ten (floor division)
115
+ call __divmod ; r1 = quotient (rounded down), r2 = remainder (0 to 9)
116
+ cmp r2, r0 ; was it an exact multiple of ten?
117
+ br eq, __print_int_exact ; yes: last digit is 0 and the quotient is right already
118
+ li r3, 10 ; no: rounding down went one step too far, so
119
+ sub r2, r3, r2 ; the last digit of the size is 10 - remainder
120
+ addi r1, 1 ; and the quotient steps back one
121
+ __print_int_exact:
122
+ sub r1, r0, r1 ; r1 = the rest of the number, now without its minus sign
123
+ addi r2, 48 ; digit + 48 = the character code of that digit
124
+ push r2 ; keep it on the stack for later
125
+ cmp r1, r0 ; is there anything left to print?
126
+ br eq, __print_int_out ; no: a one-digit number, go and print what we have
127
+ __print_int_digits:
128
+ li r2, 10 ; divide by ten ...
129
+ call __divmod ; ... r1 = what is left, r2 = the last digit (0 to 9)
130
+ addi r2, 48 ; digit + 48 = the character code of that digit
131
+ push r2 ; stack it: last digit goes in first, so it comes out last
132
+ cmp r1, r0 ; has the number run out?
133
+ br ne, __print_int_digits ; no: peel off the next digit (a 0 still prints once)
134
+ __print_int_out:
135
+ li r6, 0 ; r6 = 0 ...
136
+ addi r6, -1 ; ... minus 1 = 0xFFFF, the output port
137
+ __print_int_pop:
138
+ pop r3 ; take the top card: the leftmost digit not yet printed
139
+ cmp r3, r0 ; is it the sentinel 0?
140
+ br eq, __print_int_end ; yes: every digit is out
141
+ store r3, [r6] ; no: post it through the output port
142
+ jmp __print_int_pop ; and take the next card
143
+ __print_int_end:
144
+ li r3, 10 ; 10 is the character code of a newline
145
+ store r3, [r6] ; post the newline
146
+ ret ; return to whoever called us
147
+
148
+ ; ---------------------------------------------------------------------------
149
+ ; __print_text: print the 0-terminated words starting at address r1, then a newline.
150
+ ; Uses r1 (stepped along the text), r3 and r6. No stack beyond the return address.
151
+ ; ---------------------------------------------------------------------------
152
+ __print_text:
153
+ li r6, 0 ; r6 = 0 ...
154
+ addi r6, -1 ; ... minus 1 = 0xFFFF, the output port
155
+ __print_text_loop:
156
+ load r3, [r1] ; r3 = the next character code of the text
157
+ cmp r3, r0 ; is it the 0 that ends the text?
158
+ br eq, __print_text_end ; yes: stop
159
+ store r3, [r6] ; no: post it through the output port
160
+ addi r1, 1 ; step on to the next character
161
+ jmp __print_text_loop ; and go round again
162
+ __print_text_end:
163
+ li r3, 10 ; 10 is the character code of a newline
164
+ store r3, [r6] ; post the newline
165
+ ret ; return to whoever called us
166
+ """