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,688 @@
1
+ """The subset check: a customs desk that looks in every suitcase before it boards.
2
+
3
+ Before a Pebble program is translated, every one of its bytecode instructions walks past
4
+ this desk. Most are waved through. A few carry something PyCPU cannot handle yet, such
5
+ as a decimal number, a list or a piece of text stored in a variable, and those are
6
+ stopped with a polite note that says what the thing is and which Pebble line it is on.
7
+
8
+ The desk also does a little bookkeeping that the translator needs later. It plays the
9
+ program through without running it, keeping track of what *kind* of thing (a number,
10
+ true/false, text, nothing) sits in each slot of Pebble's stack, so it knows, for
11
+ example, whether a `print` is printing a number or a piece of text. It notes every
12
+ variable a piece of code stores, so each one can get a place in memory, and the deepest
13
+ the stack ever gets, so the program can check there is room before it starts.
14
+ """
15
+
16
+ from collections.abc import Mapping, Sequence
17
+ from dataclasses import dataclass
18
+ from enum import Enum, auto
19
+
20
+ from pebble import CodeObject, CompiledProgram, Instruction, OpCode, SourceLocation
21
+
22
+ INT_MIN = -32768
23
+ INT_MAX = 32767
24
+ MAX_VARIABLES = 32
25
+ # A function's parameter i of N sits at [r7 + 2 + (N - 1 - i)], and a `load` reaches only
26
+ # [r7+31]. The contract keeps one word spare and allows 29.
27
+ MAX_PARAMETERS = 29
28
+ WORD_MAX = 0xFFFF
29
+
30
+ # The feature names the friendly errors use (see the Pebble Subset Contract).
31
+ DIVIDE = "the / operator (it always makes a decimal number; use // for whole numbers)"
32
+ DECIMALS = "decimal numbers"
33
+ POWER = "the ** operator"
34
+ BITWISE = "bitwise operators"
35
+ TEXT_BRACES = "text with {} inside it"
36
+ TEXT_OUTSIDE_PRINT = "text outside print"
37
+ LISTS = "lists"
38
+ DICTIONARIES = "dictionaries"
39
+ STRUCTS = "structs, classes and enums"
40
+ METHODS = "methods like .upper()"
41
+ FUNCTIONS_AS_VALUES = "functions used as values"
42
+ TRY_CATCH = "try, catch and throw"
43
+ GENERATORS = "generators and async"
44
+ RANGE_STEP = "range with a step"
45
+ # Pebble lowers `for i in range(a, b, step)` with a hidden `$for_step_N` variable (and a
46
+ # THROW guarding against a step of 0); `range(n)` and `range(a, b)` need neither.
47
+ _RANGE_STEP_PREFIX = "$for_step_"
48
+ NUMBER_RANGE = "numbers bigger than 32767 or smaller than -32768"
49
+ BOOL_OUTSIDE_CONDITIONS = "true and false outside if and while"
50
+ NULL_VALUES = "null values"
51
+ NULL_USED = "using the result of a function that does not always return a number"
52
+ OUTSIDE_VARIABLES = "variables from outside a function"
53
+ TOO_MANY_VARIABLES = f"more than {MAX_VARIABLES} variables in one function"
54
+ TOO_MANY_PARAMETERS = f"more than {MAX_PARAMETERS} parameters"
55
+ BIG_CHARACTERS = "emoji and other characters too big for one 16-bit word"
56
+ ZERO_CHARACTER = "the \\0 character inside text"
57
+ TOO_BIG = "programs too big to fit in memory with room for the stack"
58
+
59
+ _SINGULAR = frozenset({TEXT_BRACES, TEXT_OUTSIDE_PRINT, NULL_USED, RANGE_STEP})
60
+
61
+ _OPCODE_FEATURES: dict[str, str] = {
62
+ OpCode.DIVIDE: DIVIDE,
63
+ OpCode.POWER: POWER,
64
+ **dict.fromkeys(
65
+ (
66
+ OpCode.BIT_AND,
67
+ OpCode.BIT_OR,
68
+ OpCode.BIT_XOR,
69
+ OpCode.BIT_NOT,
70
+ OpCode.LEFT_SHIFT,
71
+ OpCode.RIGHT_SHIFT,
72
+ ),
73
+ BITWISE,
74
+ ),
75
+ OpCode.BUILD_STRING: TEXT_BRACES,
76
+ **dict.fromkeys(
77
+ (
78
+ OpCode.BUILD_LIST,
79
+ OpCode.INDEX_GET,
80
+ OpCode.INDEX_SET,
81
+ OpCode.SLICE_GET,
82
+ OpCode.LIST_APPEND,
83
+ OpCode.UNPACK_SEQUENCE,
84
+ OpCode.GET_ITER,
85
+ OpCode.FOR_ITER,
86
+ ),
87
+ LISTS,
88
+ ),
89
+ OpCode.BUILD_DICT: DICTIONARIES,
90
+ **dict.fromkeys(
91
+ (
92
+ OpCode.GET_FIELD,
93
+ OpCode.SET_FIELD,
94
+ OpCode.CALL_INSTANCE_METHOD,
95
+ OpCode.LOAD_ENUM_VARIANT,
96
+ ),
97
+ STRUCTS,
98
+ ),
99
+ OpCode.CALL_METHOD: METHODS,
100
+ **dict.fromkeys(
101
+ (OpCode.MAKE_CLOSURE, OpCode.LOAD_CELL, OpCode.STORE_CELL), FUNCTIONS_AS_VALUES
102
+ ),
103
+ **dict.fromkeys((OpCode.SETUP_TRY, OpCode.POP_TRY, OpCode.THROW), TRY_CATCH),
104
+ **dict.fromkeys((OpCode.YIELD, OpCode.AWAIT), GENERATORS),
105
+ }
106
+
107
+ ARITHMETIC = frozenset(
108
+ {OpCode.ADD, OpCode.SUBTRACT, OpCode.MULTIPLY, OpCode.FLOOR_DIVIDE, OpCode.MODULO}
109
+ )
110
+ COMPARISONS = frozenset(
111
+ {
112
+ OpCode.LESS_THAN,
113
+ OpCode.LESS_EQUAL,
114
+ OpCode.GREATER_THAN,
115
+ OpCode.GREATER_EQUAL,
116
+ OpCode.EQUAL,
117
+ OpCode.NOT_EQUAL,
118
+ }
119
+ )
120
+ # `and` and `or`: jump keeping the value if it decides the answer, else pop it.
121
+ KEEP_OR_POP = frozenset({OpCode.JUMP_IF_FALSE_OR_POP, OpCode.JUMP_IF_TRUE_OR_POP})
122
+ JUMPS = frozenset({OpCode.JUMP, OpCode.JUMP_IF_FALSE, *KEEP_OR_POP})
123
+ _SUPPORTED = frozenset(
124
+ {
125
+ OpCode.LOAD_CONST,
126
+ OpCode.LOAD_NAME,
127
+ OpCode.STORE_NAME,
128
+ OpCode.NEGATE,
129
+ OpCode.POP,
130
+ OpCode.PRINT,
131
+ OpCode.CHECK_TYPE,
132
+ OpCode.HALT,
133
+ OpCode.RETURN,
134
+ OpCode.NOT,
135
+ OpCode.CALL,
136
+ *ARITHMETIC,
137
+ *COMPARISONS,
138
+ *JUMPS,
139
+ }
140
+ )
141
+ # Refused instructions whose effect on the stack we still follow, so the kind check
142
+ # can carry on past them (a refused name still pushes one value).
143
+ _KEEP_WALKING = frozenset({OpCode.LOAD_NAME, OpCode.CHECK_TYPE})
144
+
145
+
146
+ def builtin_function(name: str) -> str:
147
+ """Return the feature name for calling the built-in or library function `name`."""
148
+ return f"the built-in function {name}()"
149
+
150
+
151
+ class PebbleCPUError(Exception):
152
+ """Say that a Pebble program cannot run on PyCPU. Every translator error is one of these."""
153
+
154
+
155
+ class UnsupportedFeature(PebbleCPUError): # noqa: N818 - the plan fixes this name; it names a feature
156
+ """Say that a Pebble program uses something PyCPU cannot do yet, and where.
157
+
158
+ The message reads like a sentence, for example `lists are not supported on PyCPU
159
+ yet at line 1, column 9`.
160
+
161
+ Attributes:
162
+ feature: What the program used, in plain words, such as `decimal numbers`.
163
+ line: The Pebble line it is on (1-based), or None if nobody knows.
164
+ column: The column on that line (1-based), or None if nobody knows.
165
+
166
+ """
167
+
168
+ def __init__(self, feature: str, line: int | None = None, column: int | None = None) -> None:
169
+ """Remember the feature and its place, and build the message."""
170
+ verb = "is" if feature in _SINGULAR or feature.startswith("the ") else "are"
171
+ place = f" at line {line}, column {column}" if line is not None else ""
172
+ super().__init__(f"{feature} {verb} not supported on PyCPU yet{place}")
173
+ self.feature = feature
174
+ self.line = line
175
+ self.column = column
176
+
177
+
178
+ class Kind(Enum):
179
+ """What kind of thing sits in one slot of Pebble's stack."""
180
+
181
+ INT = auto()
182
+ BOOL = auto()
183
+ TEXT = auto()
184
+ NULL = auto()
185
+ MAYBE = auto()
186
+
187
+
188
+ @dataclass(frozen=True)
189
+ class CheckedCode:
190
+ """One piece of Pebble code (main or a function) that passed the check.
191
+
192
+ Attributes:
193
+ name: `main`, or the function's name.
194
+ code: Pebble's compiled code for it.
195
+ variables: The names it stores, in the order they first appear; each one
196
+ gets a slot in memory.
197
+ prints_text: The positions of its `PRINT` instructions that print text
198
+ rather than a number.
199
+ deepest: The most slots Pebble's stack ever holds while it runs.
200
+ returns: What its `return`s may give back: `Kind.INT` for a number,
201
+ `Kind.NULL` for nothing. Both means "maybe a number"; neither means it
202
+ never comes back at all (like a function that calls itself forever).
203
+
204
+ """
205
+
206
+ name: str
207
+ code: CodeObject
208
+ variables: tuple[str, ...]
209
+ prints_text: frozenset[int]
210
+ deepest: int
211
+ returns: frozenset[Kind] = frozenset()
212
+
213
+
214
+ @dataclass(frozen=True)
215
+ class CheckedProgram:
216
+ """A whole Pebble program that passed the check: main and its functions."""
217
+
218
+ main: CheckedCode
219
+ functions: dict[str, CheckedCode]
220
+
221
+
222
+ @dataclass(frozen=True)
223
+ class _Problem:
224
+ """One thing the check found, with the place it was found."""
225
+
226
+ feature: str
227
+ location: SourceLocation | None
228
+
229
+ def key(self) -> tuple[int, int]:
230
+ """Sort problems by place in the source; ones with no place go last."""
231
+ if self.location is None:
232
+ return (WORD_MAX, WORD_MAX)
233
+ return (self.location.line, self.location.column)
234
+
235
+
236
+ @dataclass(frozen=True)
237
+ class _Slot:
238
+ """One slot of Pebble's stack: its kind, and where the value in it was made.
239
+
240
+ `mixed` is True when paths that brought different kinds met in this slot, such as
241
+ the number and the text in `1 or "a"`: such a value cannot be printed as text.
242
+ `never` is True for the answer of a call that, as far as we know so far, never
243
+ comes back, so returning it tells the caller nothing new.
244
+ """
245
+
246
+ kind: Kind
247
+ made_at: SourceLocation | None
248
+ null_literal: bool = False
249
+ mixed: bool = False
250
+ never: bool = False
251
+
252
+
253
+ # How "awkward" each kind is. Where two paths meet, the more awkward kind wins, so a
254
+ # value that might be text is treated as text and refused wherever text is refused.
255
+ _AWKWARDNESS = {Kind.INT: 0, Kind.BOOL: 1, Kind.NULL: 2, Kind.MAYBE: 3, Kind.TEXT: 4}
256
+
257
+ type _Stack = tuple[_Slot, ...]
258
+
259
+ # What a `return` of each kind of slot tells a caller it may get back.
260
+ _GIVES = {
261
+ Kind.INT: {Kind.INT},
262
+ Kind.NULL: {Kind.NULL},
263
+ Kind.MAYBE: {Kind.INT, Kind.NULL},
264
+ Kind.BOOL: set[Kind](),
265
+ Kind.TEXT: set[Kind](),
266
+ }
267
+
268
+
269
+ def _place_key(place: SourceLocation | None) -> tuple[int, int]:
270
+ """Sort places in the source; no place goes last."""
271
+ return (WORD_MAX, WORD_MAX) if place is None else (place.line, place.column)
272
+
273
+
274
+ def _meet(first: _Slot, second: _Slot) -> _Slot:
275
+ """Mix two slots that arrive at the same instruction by different paths.
276
+
277
+ Two numbers stay a number; a number and a true/false make a true/false (the
278
+ contract's rule for `and`/`or`); otherwise the more awkward kind wins. The value is
279
+ said to be made at the earliest place either path made it, so errors point at the
280
+ start of an `and`/`or` rather than its end.
281
+ """
282
+ if first == second:
283
+ return first
284
+ winner = max(first, second, key=lambda slot: _AWKWARDNESS[slot.kind])
285
+ made_at = winner.made_at
286
+ if first.kind is second.kind:
287
+ made_at = min(first.made_at, second.made_at, key=_place_key)
288
+ return _Slot(
289
+ winner.kind,
290
+ made_at,
291
+ null_literal=first.null_literal or second.null_literal,
292
+ mixed=first.mixed or second.mixed or first.kind is not second.kind,
293
+ never=first.never and second.never,
294
+ )
295
+
296
+
297
+ def first_place(places: Sequence[SourceLocation | None]) -> SourceLocation | None:
298
+ """Return the first place in the list that is not None, or None if there is none."""
299
+ return next((place for place in places if place is not None), None)
300
+
301
+
302
+ def located(instructions: Sequence[Instruction]) -> list[SourceLocation | None]:
303
+ """Give each instruction a place in the source, borrowing one if it has none.
304
+
305
+ The compiler makes some instructions itself (like the final `HALT`), and those have
306
+ no place. Each borrows the place of the last instruction before it that has one, so
307
+ a fault there is still reported at a sensible line.
308
+ """
309
+ places: list[SourceLocation | None] = []
310
+ last: SourceLocation | None = None
311
+ for instruction in instructions:
312
+ last = instruction.location or last
313
+ places.append(last)
314
+ return places
315
+
316
+
317
+ class _CodeChecker:
318
+ """Check one code object: follow every path, keeping the kind of every stack slot.
319
+
320
+ It works like a to-do list. Start with instruction 0 and an empty stack. Playing an
321
+ instruction gives the stack each next instruction will see (two of them after a jump
322
+ that may or may not be taken); a next instruction goes on the list the first time it
323
+ is reached, and again whenever a new path changes what it sees. When the list is
324
+ empty, every path has been followed.
325
+ """
326
+
327
+ def __init__(
328
+ self,
329
+ name: str,
330
+ code: CodeObject,
331
+ program: CompiledProgram,
332
+ returns: Mapping[str, frozenset[Kind]],
333
+ ) -> None:
334
+ """Get ready to check `code`, which belongs to `program`.
335
+
336
+ `returns` is our best guess so far of what every function gives back.
337
+ """
338
+ self.name = name
339
+ self.code = code
340
+ self.program = program
341
+ self.returns_so_far = returns
342
+ self.returns: set[Kind] = set()
343
+ self.places = located(code.instructions)
344
+ self.stored = {str(i.operand) for i in code.instructions if i.opcode == OpCode.STORE_NAME}
345
+ self.problems: list[_Problem] = []
346
+ self.stack: list[_Slot] = []
347
+ self.variables: list[str] = []
348
+ self.prints_text: set[int] = set()
349
+ self.deepest = 0
350
+
351
+ def check(self) -> CheckedCode:
352
+ """Check every instruction and every path, and return what the translator needs."""
353
+ self.examine()
354
+ if self.problems:
355
+ first = min(self.problems, key=_Problem.key)
356
+ location = first.location
357
+ raise UnsupportedFeature(
358
+ first.feature,
359
+ location.line if location else None,
360
+ location.column if location else None,
361
+ )
362
+ return CheckedCode(
363
+ self.name,
364
+ self.code,
365
+ tuple(self.variables),
366
+ frozenset(self.prints_text),
367
+ self.deepest,
368
+ frozenset(self.returns),
369
+ )
370
+
371
+ def examine(self) -> None:
372
+ """Look at every instruction and every path, noting problems and what comes back."""
373
+ if len(self.code.parameters) > MAX_PARAMETERS:
374
+ # A frame has no place of its own in the source, so use its first line.
375
+ first = first_place(self.places)
376
+ # With no line to point at (an empty body), name the function instead.
377
+ where = "" if first is not None else f" (in {self.name})"
378
+ self._problem(TOO_MANY_PARAMETERS + where, first)
379
+ for index, instruction in enumerate(self.code.instructions):
380
+ feature = self._opcode_problem(instruction)
381
+ if feature is not None:
382
+ self._problem(feature, self.places[index])
383
+ if instruction.opcode == OpCode.STORE_NAME:
384
+ name = str(instruction.operand)
385
+ if name.startswith(_RANGE_STEP_PREFIX):
386
+ self._problem(RANGE_STEP, self.places[index])
387
+ self._store(name, self.places[index])
388
+ self._follow_every_path()
389
+
390
+ def _follow_every_path(self) -> None:
391
+ """Play the code along every path, mixing kinds where paths meet."""
392
+ instructions = self.code.instructions
393
+ seen: dict[int, _Stack] = {0: ()} if instructions else {}
394
+ todo = set(seen)
395
+ while todo:
396
+ index = min(todo)
397
+ todo.remove(index)
398
+ instruction = instructions[index]
399
+ # A refused instruction's effect on the stack is not followed (most are
400
+ # refused precisely because PyCPU has no idea what they would do).
401
+ if self._opcode_problem(instruction) and instruction.opcode not in _KEEP_WALKING:
402
+ continue
403
+ self.stack = list(seen[index])
404
+ for target, stack in self._step(index, instruction, self.places[index]):
405
+ if self._arrive(target, stack, seen):
406
+ todo.add(target)
407
+
408
+ def _arrive(self, target: int, stack: _Stack, seen: dict[int, _Stack]) -> bool:
409
+ """Bring a stack to instruction `target`; return True if what it sees changed."""
410
+ if not 0 <= target < len(self.code.instructions):
411
+ msg = (
412
+ f"translator bug: a jump in {self.name} goes to instruction {target}, "
413
+ "past its last instruction (Pebble >=0.4.1 never does this)"
414
+ )
415
+ raise PebbleCPUError(msg)
416
+ before = seen.get(target)
417
+ if before is None:
418
+ seen[target] = stack
419
+ return True
420
+ if len(before) != len(stack):
421
+ # Pebble's compiler promises this never happens, so it is our bug or Pebble's.
422
+ msg = (
423
+ f"translator bug: two paths reach instruction {target} of {self.name} "
424
+ f"with different stack depths ({len(before)} and {len(stack)})"
425
+ )
426
+ raise PebbleCPUError(msg)
427
+ after = tuple(_meet(old, new) for old, new in zip(before, stack, strict=True))
428
+ seen[target] = after
429
+ return after != before
430
+
431
+ def _problem(self, feature: str, place: SourceLocation | None) -> None:
432
+ """Note one problem; the earliest in the source is reported in the end."""
433
+ self.problems.append(_Problem(feature, place))
434
+
435
+ def _opcode_problem(self, instruction: Instruction) -> str | None:
436
+ """Return the feature an instruction itself uses that we cannot do, if any."""
437
+ opcode, operand = instruction.opcode, instruction.operand
438
+ if opcode in _OPCODE_FEATURES:
439
+ return _OPCODE_FEATURES[opcode]
440
+ if opcode in (OpCode.CALL, OpCode.LOAD_NAME):
441
+ return self._name_problem(opcode, str(operand))
442
+ if opcode == OpCode.CHECK_TYPE and operand != "Int":
443
+ return f"the {operand} type"
444
+ return None if opcode in _SUPPORTED else f"the {opcode} instruction"
445
+
446
+ def _name_problem(self, opcode: str, name: str) -> str | None:
447
+ """Return what is wrong with a call or a name lookup, if anything."""
448
+ is_function = name in self.program.functions
449
+ if opcode == OpCode.CALL:
450
+ if is_function:
451
+ return None
452
+ # Calling one of this code object's own variables, like `x()`, treats a
453
+ # number as if it were a function; it is not a built-in.
454
+ if name in self.stored or name in self.code.parameters:
455
+ return FUNCTIONS_AS_VALUES
456
+ # Pebble's built-in and library functions are lower case; a capital
457
+ # letter means a struct or class being made, like `Point(1, 2)`.
458
+ return STRUCTS if name[:1].isupper() else builtin_function(name)
459
+ if is_function:
460
+ return FUNCTIONS_AS_VALUES
461
+ if name not in self.stored and name not in self.code.parameters:
462
+ return OUTSIDE_VARIABLES
463
+ return None
464
+
465
+ def _pop(self) -> _Slot:
466
+ """Take the top slot off the imagined stack."""
467
+ return self.stack.pop()
468
+
469
+ def _push(
470
+ self,
471
+ kind: Kind,
472
+ place: SourceLocation | None,
473
+ *,
474
+ null_literal: bool = False,
475
+ never: bool = False,
476
+ ) -> None:
477
+ """Put a slot on the imagined stack and remember the deepest it has been."""
478
+ self.stack.append(_Slot(kind, place, null_literal, never=never))
479
+ self.deepest = max(self.deepest, len(self.stack))
480
+
481
+ def _need_number(self, slot: _Slot) -> None:
482
+ """Complain unless a slot holds a number, naming where its value was made."""
483
+ refusals = {
484
+ Kind.BOOL: BOOL_OUTSIDE_CONDITIONS,
485
+ Kind.TEXT: TEXT_OUTSIDE_PRINT,
486
+ Kind.NULL: NULL_USED,
487
+ Kind.MAYBE: NULL_USED,
488
+ }
489
+ if slot.null_literal:
490
+ self._problem(NULL_VALUES, slot.made_at)
491
+ elif slot.kind in refusals:
492
+ self._problem(refusals[slot.kind], slot.made_at)
493
+
494
+ def _need_condition(self, slot: _Slot) -> None:
495
+ """Complain unless a slot can steer a jump: a number or a true/false.
496
+
497
+ Any word can be tested against 0, so both are fine. Text cannot: its word is an
498
+ address, never 0, but Pebble calls empty text false.
499
+ """
500
+ if slot.kind is not Kind.BOOL:
501
+ self._need_number(slot)
502
+
503
+ def _step(
504
+ self, index: int, instruction: Instruction, place: SourceLocation | None
505
+ ) -> list[tuple[int, _Stack]]:
506
+ """Play one instruction; return each instruction that may come next, with its stack."""
507
+ opcode, target = instruction.opcode, instruction.operand
508
+ if opcode in (OpCode.HALT, OpCode.RETURN):
509
+ self._play(index, instruction, place)
510
+ return []
511
+ if opcode == OpCode.JUMP:
512
+ return [(int(target or 0), tuple(self.stack))]
513
+ if opcode == OpCode.JUMP_IF_FALSE:
514
+ self._need_condition(self._pop())
515
+ stack = tuple(self.stack)
516
+ return [(index + 1, stack), (int(target or 0), stack)]
517
+ if opcode in KEEP_OR_POP:
518
+ # The value decides the answer: jump, keeping it. Otherwise: pop it, go on.
519
+ slot = self._pop()
520
+ self._need_condition(slot)
521
+ stack = tuple(self.stack)
522
+ return [(index + 1, stack), (int(target or 0), (*stack, slot))]
523
+ self._play(index, instruction, place)
524
+ return [(index + 1, tuple(self.stack))]
525
+
526
+ def _play(self, index: int, instruction: Instruction, place: SourceLocation | None) -> None:
527
+ """Play the stack effect of one instruction that is not a jump."""
528
+ opcode = instruction.opcode
529
+ if opcode == OpCode.LOAD_CONST:
530
+ self._load_constant(int(instruction.operand or 0), place, self._negated_next(index))
531
+ elif opcode == OpCode.LOAD_NAME:
532
+ self._push(Kind.INT, place)
533
+ elif opcode in (OpCode.STORE_NAME, OpCode.POP):
534
+ slot = self._pop()
535
+ if opcode == OpCode.STORE_NAME:
536
+ self._need_number(slot)
537
+ elif opcode in ARITHMETIC or opcode in COMPARISONS:
538
+ right, left = self._pop(), self._pop()
539
+ self._need_number(left)
540
+ self._need_number(right)
541
+ self._push(Kind.INT if opcode in ARITHMETIC else Kind.BOOL, place)
542
+ elif opcode == OpCode.NEGATE:
543
+ self._need_number(self._pop())
544
+ self._push(Kind.INT, place)
545
+ elif opcode == OpCode.NOT:
546
+ self._need_condition(self._pop())
547
+ self._push(Kind.BOOL, place)
548
+ elif opcode == OpCode.PRINT:
549
+ slot = self._pop()
550
+ if slot.kind is Kind.TEXT and not slot.mixed:
551
+ self.prints_text.add(index)
552
+ else:
553
+ self._need_number(slot)
554
+ elif opcode == OpCode.CALL:
555
+ self._call(str(instruction.operand), place)
556
+ elif opcode == OpCode.RETURN:
557
+ self._return(self._pop())
558
+
559
+ def _return(self, slot: _Slot) -> None:
560
+ """Play a `return`: note what kind of thing it gives back to the caller."""
561
+ if slot.kind is Kind.NULL and not slot.mixed:
562
+ self.returns.add(Kind.NULL)
563
+ elif not slot.never: # `return f()`, where f never comes back, adds nothing.
564
+ self._need_number(slot)
565
+ # A maybe passed along is refused, but still means "maybe" to callers.
566
+ self.returns.update(_GIVES[slot.kind])
567
+
568
+ def _call(self, name: str, place: SourceLocation | None) -> None:
569
+ """Play a call to our own function: its arguments go, its answer comes.
570
+
571
+ Pebble's `CALL` does not say how many arguments it takes, so we count the
572
+ function's parameters (a default value is filled in by the caller, so the count
573
+ is always the same). Every argument must be a number.
574
+ """
575
+ for _ in self.program.functions[name].parameters:
576
+ self._need_number(self._pop())
577
+ gives = self.returns_so_far[name]
578
+ if gives == frozenset({Kind.NULL}):
579
+ self._push(Kind.NULL, place)
580
+ elif Kind.NULL in gives:
581
+ self._push(Kind.MAYBE, place)
582
+ else:
583
+ # A number, or (so far) nothing ever comes back, so nobody can use it.
584
+ self._push(Kind.INT, place, never=not gives)
585
+
586
+ def _negated_next(self, index: int) -> bool:
587
+ """Say whether the instruction after `index` is a `NEGATE`."""
588
+ following = index + 1
589
+ instructions = self.code.instructions
590
+ return following < len(instructions) and instructions[following].opcode == OpCode.NEGATE
591
+
592
+ def _load_constant(self, number: int, place: SourceLocation | None, negated: bool) -> None:
593
+ """Push a constant's kind, complaining about values PyCPU cannot hold.
594
+
595
+ `negated` says the very next instruction flips the constant's sign. Pebble's
596
+ compiler usually folds `-32768` into one constant, but not when a jump lands
597
+ on it (just after a block), and then it arrives as 32768 followed by `NEGATE`.
598
+ On 16 bits 32768 is the same bit pattern as -32768, and negating it gives
599
+ that pattern back, so the pair is exactly -32768 and is allowed.
600
+ """
601
+ value = self.code.constants[number]
602
+ if isinstance(value, bool):
603
+ self._push(Kind.BOOL, place)
604
+ elif isinstance(value, int):
605
+ smallest_negated = negated and value == -INT_MIN
606
+ if not INT_MIN <= value <= INT_MAX and not smallest_negated:
607
+ self._problem(NUMBER_RANGE, place)
608
+ self._push(Kind.INT, place)
609
+ elif isinstance(value, float):
610
+ self._problem(DECIMALS, place)
611
+ self._push(Kind.INT, place)
612
+ elif isinstance(value, str):
613
+ if any(ord(char) > WORD_MAX for char in value):
614
+ self._problem(BIG_CHARACTERS, place)
615
+ if "\0" in value:
616
+ self._problem(ZERO_CHARACTER, place)
617
+ self._push(Kind.TEXT, place)
618
+ elif value is None: # a literal `null`
619
+ self._push(Kind.NULL, place, null_literal=True)
620
+ else:
621
+ self._problem(f"values like {value!r}", place)
622
+ self._push(Kind.INT, place)
623
+
624
+ def _store(self, name: str, place: SourceLocation | None) -> None:
625
+ """Give a newly stored name the next slot, if there is one left."""
626
+ if name in self.variables or name in self.code.parameters:
627
+ return
628
+ if len(self.variables) == MAX_VARIABLES:
629
+ self._problem(TOO_MANY_VARIABLES, place)
630
+ self.variables.append(name)
631
+
632
+
633
+ def check_program(compiled: CompiledProgram) -> CheckedProgram:
634
+ """Check a whole compiled Pebble program against the PyCPU subset.
635
+
636
+ Every code object is checked, and the problem nearest the top of the source wins.
637
+
638
+ Args:
639
+ compiled: What `pebble.compile_source(...).compiled` gives.
640
+
641
+ Returns:
642
+ Each code object with its variables, its text prints and its deepest stack.
643
+
644
+ Raises:
645
+ UnsupportedFeature: If anything in the program is outside the subset.
646
+
647
+ """
648
+ codes = [("main", compiled.main), *compiled.functions.items()]
649
+ returns = _return_kinds(compiled)
650
+ problems: list[UnsupportedFeature] = []
651
+ checked: list[CheckedCode] = []
652
+ for name, code in codes:
653
+ try:
654
+ checked.append(_CodeChecker(name, code, compiled, returns).check())
655
+ except UnsupportedFeature as error:
656
+ problems.append(error)
657
+ if problems:
658
+ raise min(problems, key=_error_key)
659
+ return CheckedProgram(checked[0], {code.name: code for code in checked[1:]})
660
+
661
+
662
+ def _return_kinds(compiled: CompiledProgram) -> dict[str, frozenset[Kind]]:
663
+ """Work out what every function may give back, going round until nothing changes.
664
+
665
+ What `f` gives back can depend on what `g` gives back, and `g` on `f`, or `f` on
666
+ itself. So start by guessing that no function ever comes back, play every function
667
+ with that guess, and note what its `return`s give. Then play them all again with
668
+ the new guesses. A guess only ever grows (nothing, then a number, then maybe null),
669
+ and there are only so many kinds, so it soon stops changing.
670
+ """
671
+ returns = {name: frozenset[Kind]() for name in compiled.functions}
672
+ while True:
673
+ found = dict(returns)
674
+ for name, code in compiled.functions.items():
675
+ checker = _CodeChecker(name, code, compiled, returns)
676
+ checker.examine()
677
+ found[name] = returns[name] | checker.returns
678
+ if found == returns:
679
+ return returns
680
+ returns = found
681
+
682
+
683
+ def _error_key(error: UnsupportedFeature) -> tuple[int, int]:
684
+ """Sort errors by place in the source; ones with no place go last."""
685
+ return (
686
+ WORD_MAX if error.line is None else error.line,
687
+ WORD_MAX if error.column is None else error.column,
688
+ )