oaknut-basic 13.6.0__tar.gz → 13.7.0__tar.gz

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 (45) hide show
  1. {oaknut_basic-13.6.0/src/oaknut_basic.egg-info → oaknut_basic-13.7.0}/PKG-INFO +1 -1
  2. {oaknut_basic-13.6.0 → oaknut_basic-13.7.0}/src/oaknut/basic/__init__.py +1 -1
  3. {oaknut_basic-13.6.0 → oaknut_basic-13.7.0}/src/oaknut/basic/cli.py +21 -1
  4. oaknut_basic-13.7.0/src/oaknut/basic/crunch_v.py +414 -0
  5. {oaknut_basic-13.6.0 → oaknut_basic-13.7.0}/src/oaknut/basic/detect.py +40 -3
  6. {oaknut_basic-13.6.0 → oaknut_basic-13.7.0}/src/oaknut/basic/detokeniser.py +1 -1
  7. {oaknut_basic-13.6.0 → oaknut_basic-13.7.0}/src/oaknut/basic/dialect.py +27 -4
  8. {oaknut_basic-13.6.0 → oaknut_basic-13.7.0}/src/oaknut/basic/exceptions.py +8 -2
  9. {oaknut_basic-13.6.0 → oaknut_basic-13.7.0}/src/oaknut/basic/scanner.py +8 -5
  10. {oaknut_basic-13.6.0 → oaknut_basic-13.7.0}/src/oaknut/basic/tokeniser.py +40 -6
  11. {oaknut_basic-13.6.0 → oaknut_basic-13.7.0/src/oaknut_basic.egg-info}/PKG-INFO +1 -1
  12. {oaknut_basic-13.6.0 → oaknut_basic-13.7.0}/src/oaknut_basic.egg-info/SOURCES.txt +2 -0
  13. {oaknut_basic-13.6.0 → oaknut_basic-13.7.0}/tests/test_cli.py +23 -0
  14. {oaknut_basic-13.6.0 → oaknut_basic-13.7.0}/tests/test_detect.py +18 -0
  15. {oaknut_basic-13.6.0 → oaknut_basic-13.7.0}/tests/test_detokeniser.py +12 -0
  16. oaknut_basic-13.7.0/tests/test_tokenise_basic_v.py +126 -0
  17. {oaknut_basic-13.6.0 → oaknut_basic-13.7.0}/LICENSE +0 -0
  18. {oaknut_basic-13.6.0 → oaknut_basic-13.7.0}/README.md +0 -0
  19. {oaknut_basic-13.6.0 → oaknut_basic-13.7.0}/pyproject.toml +0 -0
  20. {oaknut_basic-13.6.0 → oaknut_basic-13.7.0}/setup.cfg +0 -0
  21. {oaknut_basic-13.6.0 → oaknut_basic-13.7.0}/src/oaknut/basic/datafile.py +0 -0
  22. {oaknut_basic-13.6.0 → oaknut_basic-13.7.0}/src/oaknut/basic/float5.py +0 -0
  23. {oaknut_basic-13.6.0 → oaknut_basic-13.7.0}/src/oaknut/basic/linenumber.py +0 -0
  24. {oaknut_basic-13.6.0 → oaknut_basic-13.7.0}/src/oaknut/basic/numbering.py +0 -0
  25. {oaknut_basic-13.6.0 → oaknut_basic-13.7.0}/src/oaknut/basic/tokens.py +0 -0
  26. {oaknut_basic-13.6.0 → oaknut_basic-13.7.0}/src/oaknut_basic.egg-info/dependency_links.txt +0 -0
  27. {oaknut_basic-13.6.0 → oaknut_basic-13.7.0}/src/oaknut_basic.egg-info/entry_points.txt +0 -0
  28. {oaknut_basic-13.6.0 → oaknut_basic-13.7.0}/src/oaknut_basic.egg-info/requires.txt +0 -0
  29. {oaknut_basic-13.6.0 → oaknut_basic-13.7.0}/src/oaknut_basic.egg-info/top_level.txt +0 -0
  30. {oaknut_basic-13.6.0 → oaknut_basic-13.7.0}/tests/test_basic.py +0 -0
  31. {oaknut_basic-13.6.0 → oaknut_basic-13.7.0}/tests/test_basic_v.py +0 -0
  32. {oaknut_basic-13.6.0 → oaknut_basic-13.7.0}/tests/test_crunch_rules.py +0 -0
  33. {oaknut_basic-13.6.0 → oaknut_basic-13.7.0}/tests/test_data_cli.py +0 -0
  34. {oaknut_basic-13.6.0 → oaknut_basic-13.7.0}/tests/test_datafile.py +0 -0
  35. {oaknut_basic-13.6.0 → oaknut_basic-13.7.0}/tests/test_float5.py +0 -0
  36. {oaknut_basic-13.6.0 → oaknut_basic-13.7.0}/tests/test_greedy_crunch.py +0 -0
  37. {oaknut_basic-13.6.0 → oaknut_basic-13.7.0}/tests/test_keyword_coverage.py +0 -0
  38. {oaknut_basic-13.6.0 → oaknut_basic-13.7.0}/tests/test_linenumber.py +0 -0
  39. {oaknut_basic-13.6.0 → oaknut_basic-13.7.0}/tests/test_numbering.py +0 -0
  40. {oaknut_basic-13.6.0 → oaknut_basic-13.7.0}/tests/test_packaging.py +0 -0
  41. {oaknut_basic-13.6.0 → oaknut_basic-13.7.0}/tests/test_rom_golden.py +0 -0
  42. {oaknut_basic-13.6.0 → oaknut_basic-13.7.0}/tests/test_rom_golden_detokenise.py +0 -0
  43. {oaknut_basic-13.6.0 → oaknut_basic-13.7.0}/tests/test_scanner.py +0 -0
  44. {oaknut_basic-13.6.0 → oaknut_basic-13.7.0}/tests/test_tokeniser.py +0 -0
  45. {oaknut_basic-13.6.0 → oaknut_basic-13.7.0}/tests/test_tokens.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: oaknut-basic
3
- Version: 13.6.0
3
+ Version: 13.7.0
4
4
  Summary: BBC BASIC tools: program tokeniser/de-tokeniser and PRINT#/INPUT# data-file reader/writer
5
5
  Author-email: Robert Smallshire <robert@smallshire.org.uk>
6
6
  License-Expression: MIT
@@ -81,7 +81,7 @@ from oaknut.basic.tokens import (
81
81
  TOKEN_TO_KEYWORD,
82
82
  )
83
83
 
84
- __version__ = "13.6.0"
84
+ __version__ = "13.7.0"
85
85
 
86
86
  # Canonical load addresses for BBC BASIC programs on each host.
87
87
  # Programs saved by *SAVE on a real machine use these by default.
@@ -224,6 +224,15 @@ def _listing_to_bytes(listing: str, encoding: str) -> bytes:
224
224
  "behind some early-1980s commercial programs, so their de-tokenised "
225
225
  "source re-tokenises byte-identically.",
226
226
  )
227
+ @click.option(
228
+ "--dialect",
229
+ type=click.Choice(["ii", "2", "v", "5"]),
230
+ default="ii",
231
+ show_default=True,
232
+ help='BBC BASIC dialect, as a Roman or Arabic numeral. Use "v" (or "5") to '
233
+ "crunch as Archimedes / RISC OS BASIC does: its &C6/&C7/&C8 escape tokens "
234
+ "(CASE, SYS, ORIGIN, ...) and line numbers up to 65279.",
235
+ )
227
236
  def tokenise(
228
237
  input_stream,
229
238
  output_stream,
@@ -231,6 +240,7 @@ def tokenise(
231
240
  start: int | None,
232
241
  step: int | None,
233
242
  crunch: str,
243
+ dialect: str,
234
244
  ) -> None:
235
245
  """Tokenise BBC BASIC source text into a stored program.
236
246
 
@@ -254,14 +264,24 @@ def tokenise(
254
264
  ``rom`` is byte-exact to the BBC BASIC ROM. Use it only to regenerate
255
265
  such a program byte-for-byte from its de-tokenised source.
256
266
 
267
+ Pass ``--dialect v`` (or ``--dialect 5``) for Archimedes / RISC OS
268
+ BASIC V, crunched as the RISC OS BASIC module does; a listing made with
269
+ ``detokenise --dialect v`` re-tokenises to the original bytes.
270
+
257
271
  INPUT is read in --encoding (``utf-8`` by default, for source authored
258
272
  in a modern editor; pass ``acorn`` for the BBC character set, e.g.
259
273
  source taken straight off a disc image).
260
274
  """
275
+ from oaknut.basic import BASIC_II, BASIC_V
261
276
  from oaknut.basic import tokenise as tokenise_source
262
277
 
278
+ if crunch != "rom" and dialect in ("v", "5"):
279
+ raise click.UsageError("--crunch greedy is a BASIC II tokeniser; it cannot crunch BASIC V")
280
+ selected_dialect = BASIC_V if dialect in ("v", "5") else BASIC_II
263
281
  source = _source_to_code_points(input_stream.read(), encoding)
264
- output_stream.write(tokenise_source(source, start=start, step=step, crunch=crunch))
282
+ output_stream.write(
283
+ tokenise_source(source, start=start, step=step, crunch=crunch, dialect=selected_dialect)
284
+ )
265
285
 
266
286
 
267
287
  @cli.command()
@@ -0,0 +1,414 @@
1
+ """Crunching BBC BASIC V source, as the RISC OS BASIC module does.
2
+
3
+ BBC BASIC V tokenises with its own lexical analyser, not BASIC II's: the
4
+ ``MATCH`` routine and keyword table in the RISC OS BASIC module's
5
+ ``s/Lexical``, transcribed here from the RISC OS 3.60 import of that
6
+ source (RISC OS Open's ``RiscOS/Sources/Programmer/BASIC``, commit
7
+ ``9a232a3``), which is the version nearest the Arthur and RISC OS 3
8
+ programs it must reproduce. Later releases changed a few rules (``QUIT``
9
+ became a statement that switches mode, ``TRACE`` stopped arming a line
10
+ number on the right of an expression, and ``VDU P.`` gained a special
11
+ case for a VFP opcode); those are not followed.
12
+
13
+ The keyword table lists each keyword, in matching order within its first
14
+ letter, with its token and its *job* byte. The job's bits drive the
15
+ crunch, as ``MATCH`` reads them:
16
+
17
+ - bit 0 — conditional: not a keyword if a name character follows;
18
+ - bit 1 — switch to *right* mode (within an expression);
19
+ - bit 2 — switch to *left* mode (start of a statement); with bit 3, the
20
+ extended token is a function (``&C6``);
21
+ - bit 3 — a two-byte token: ``&C7`` (command), ``&C8`` with bit 6
22
+ (statement) or ``&C6`` with bit 2 (function), then the listed byte;
23
+ - bit 4 — arm: the next number is a line-number reference;
24
+ - bit 5 — give up: copy the rest of the line literally (``REM``, ``DATA``);
25
+ - bit 6 — on a single-byte token, polymorphic: ``+&40`` in left mode
26
+ (``TIME`` → ``TIME=``);
27
+ - bit 7 — the keyword carries its own bracket (``INSTR(``).
28
+
29
+ The table was generated from the source and checked against the
30
+ de-tokeniser's :data:`~oaknut.basic.BASIC_V` tables; ``COLOR`` is the
31
+ American spelling of ``COLOUR``'s token.
32
+ """
33
+
34
+ from __future__ import annotations
35
+
36
+ from oaknut.basic.tokens import LINE_NUMBER_TOKEN
37
+
38
+ #: The highest line number BASIC V stores (``MATCH`` rejects a constant of
39
+ #: 65280 or more).
40
+ BASIC_V_MAX_LINE_NUMBER = 65279
41
+
42
+ #: ``ELSE`` (single-byte) and the multi-line ``ELSE`` that line entry
43
+ #: (``INSRT`` in ``s/Basic``) substitutes when it opens a line.
44
+ ELSE_TOKEN = 0x8B
45
+ LINE_ELSE_TOKEN = 0xCC
46
+
47
+ _FN_TOKEN = 0xA4
48
+ _PROC_TOKEN = 0xF2
49
+ _POLYMORPHIC_OFFSET = 0x40
50
+
51
+ _JOB_CONDITIONAL = 0x01
52
+ _JOB_RIGHT = 0x02
53
+ _JOB_LEFT = 0x04
54
+ _JOB_TWO_BYTE = 0x08
55
+ _JOB_ARM = 0x10
56
+ _JOB_GIVE_UP = 0x20
57
+ _JOB_POLYMORPHIC = 0x40
58
+
59
+ #: (keyword, token bytes, job), in ``s/Lexical`` order.
60
+ KEYWORDS_V: tuple[tuple[str, bytes, int], ...] = (
61
+ ("AND", bytes.fromhex("80"), 2),
62
+ ("ABS", bytes.fromhex("94"), 0),
63
+ ("ACS", bytes.fromhex("95"), 0),
64
+ ("ADVAL", bytes.fromhex("96"), 0),
65
+ ("ASC", bytes.fromhex("97"), 0),
66
+ ("ASN", bytes.fromhex("98"), 0),
67
+ ("ATN", bytes.fromhex("99"), 0),
68
+ ("AUTO", bytes.fromhex("c78f"), 24),
69
+ ("APPEND", bytes.fromhex("c78e"), 10),
70
+ ("BGET", bytes.fromhex("9a"), 1),
71
+ ("BPUT", bytes.fromhex("d5"), 3),
72
+ ("BEATS", bytes.fromhex("c89e"), 74),
73
+ ("BEAT", bytes.fromhex("c68f"), 14),
74
+ ("COLOUR", bytes.fromhex("fb"), 2),
75
+ ("CALL", bytes.fromhex("d6"), 2),
76
+ ("CASE", bytes.fromhex("c88e"), 74),
77
+ ("CHAIN", bytes.fromhex("d7"), 2),
78
+ ("CHR$", bytes.fromhex("bd"), 0),
79
+ ("CLEAR", bytes.fromhex("d8"), 1),
80
+ ("CLOSE", bytes.fromhex("d9"), 3),
81
+ ("CLG", bytes.fromhex("da"), 1),
82
+ ("CLS", bytes.fromhex("db"), 1),
83
+ ("COS", bytes.fromhex("9b"), 0),
84
+ ("COUNT", bytes.fromhex("9c"), 1),
85
+ ("CIRCLE", bytes.fromhex("c88f"), 74),
86
+ ("CRUNCH", bytes.fromhex("c790"), 10),
87
+ ("COLOR", bytes.fromhex("fb"), 2),
88
+ ("DATA", bytes.fromhex("dc"), 32),
89
+ ("DEG", bytes.fromhex("9d"), 0),
90
+ ("DEF", bytes.fromhex("dd"), 0),
91
+ ("DELETE", bytes.fromhex("c791"), 24),
92
+ ("DIV", bytes.fromhex("81"), 0),
93
+ ("DIM", bytes.fromhex("de"), 2),
94
+ ("DRAW", bytes.fromhex("df"), 2),
95
+ ("ENDPROC", bytes.fromhex("e1"), 1),
96
+ ("EDIT", bytes.fromhex("c792"), 40),
97
+ ("ENDWHILE", bytes.fromhex("ce"), 1),
98
+ ("ENDCASE", bytes.fromhex("cb"), 1),
99
+ ("ENDIF", bytes.fromhex("cd"), 1),
100
+ ("END", bytes.fromhex("e0"), 1),
101
+ ("ENVELOPE", bytes.fromhex("e2"), 2),
102
+ ("ELSE", bytes.fromhex("8b"), 20),
103
+ ("EVAL", bytes.fromhex("a0"), 0),
104
+ ("ERL", bytes.fromhex("9e"), 1),
105
+ ("ERROR", bytes.fromhex("85"), 4),
106
+ ("EOF", bytes.fromhex("c5"), 1),
107
+ ("EOR", bytes.fromhex("82"), 2),
108
+ ("ERR", bytes.fromhex("9f"), 1),
109
+ ("EXP", bytes.fromhex("a1"), 0),
110
+ ("EXT", bytes.fromhex("a2"), 1),
111
+ ("ELLIPSE", bytes.fromhex("c89d"), 74),
112
+ ("FOR", bytes.fromhex("e3"), 2),
113
+ ("FALSE", bytes.fromhex("a3"), 1),
114
+ ("FILL", bytes.fromhex("c890"), 74),
115
+ ("FN", bytes.fromhex("a4"), 2),
116
+ ("GOTO", bytes.fromhex("e5"), 18),
117
+ ("GET$", bytes.fromhex("be"), 0),
118
+ ("GET", bytes.fromhex("a5"), 0),
119
+ ("GOSUB", bytes.fromhex("e4"), 18),
120
+ ("GCOL", bytes.fromhex("e6"), 2),
121
+ ("HIMEM", bytes.fromhex("93"), 67),
122
+ ("HELP", bytes.fromhex("c793"), 9),
123
+ ("INPUT", bytes.fromhex("e8"), 2),
124
+ ("IF", bytes.fromhex("e7"), 2),
125
+ ("INKEY$", bytes.fromhex("bf"), 0),
126
+ ("INKEY", bytes.fromhex("a6"), 0),
127
+ ("INT", bytes.fromhex("a8"), 0),
128
+ ("INSTR(", bytes.fromhex("a7"), 128),
129
+ ("INSTALL", bytes.fromhex("c79f"), 10),
130
+ ("LIST", bytes.fromhex("c794"), 24),
131
+ ("LINE", bytes.fromhex("86"), 2),
132
+ ("LOAD", bytes.fromhex("c795"), 10),
133
+ ("LOMEM", bytes.fromhex("92"), 67),
134
+ ("LOCAL", bytes.fromhex("ea"), 2),
135
+ ("LEFT$(", bytes.fromhex("c0"), 128),
136
+ ("LEN", bytes.fromhex("a9"), 0),
137
+ ("LET", bytes.fromhex("e9"), 4),
138
+ ("LOG", bytes.fromhex("ab"), 0),
139
+ ("LN", bytes.fromhex("aa"), 0),
140
+ ("LIBRARY", bytes.fromhex("c89b"), 74),
141
+ ("LVAR", bytes.fromhex("c796"), 9),
142
+ ("MID$(", bytes.fromhex("c1"), 128),
143
+ ("MODE", bytes.fromhex("eb"), 2),
144
+ ("MOD", bytes.fromhex("83"), 0),
145
+ ("MOVE", bytes.fromhex("ec"), 2),
146
+ ("MOUSE", bytes.fromhex("c897"), 74),
147
+ ("NEXT", bytes.fromhex("ed"), 2),
148
+ ("NEW", bytes.fromhex("c797"), 9),
149
+ ("NOT", bytes.fromhex("ac"), 0),
150
+ ("OLD", bytes.fromhex("c798"), 9),
151
+ ("ON", bytes.fromhex("ee"), 2),
152
+ ("OFF", bytes.fromhex("87"), 0),
153
+ ("OF", bytes.fromhex("ca"), 0),
154
+ ("ORIGIN", bytes.fromhex("c891"), 74),
155
+ ("OR", bytes.fromhex("84"), 2),
156
+ ("OPENIN", bytes.fromhex("8e"), 0),
157
+ ("OPENOUT", bytes.fromhex("ae"), 0),
158
+ ("OPENUP", bytes.fromhex("ad"), 0),
159
+ ("OSCLI", bytes.fromhex("ff"), 2),
160
+ ("OTHERWISE", bytes.fromhex("7f"), 4),
161
+ ("OVERLAY", bytes.fromhex("c8a3"), 74),
162
+ ("PRINT", bytes.fromhex("f1"), 2),
163
+ ("PAGE", bytes.fromhex("90"), 67),
164
+ ("PTR", bytes.fromhex("8f"), 67),
165
+ ("PI", bytes.fromhex("af"), 1),
166
+ ("PLOT", bytes.fromhex("f0"), 2),
167
+ ("POINT(", bytes.fromhex("b0"), 128),
168
+ ("POINT", bytes.fromhex("c892"), 74),
169
+ ("PROC", bytes.fromhex("f2"), 2),
170
+ ("POS", bytes.fromhex("b1"), 1),
171
+ ("QUIT", bytes.fromhex("c898"), 73),
172
+ ("RETURN", bytes.fromhex("f8"), 1),
173
+ ("REPEAT", bytes.fromhex("f5"), 0),
174
+ ("REPORT", bytes.fromhex("f6"), 1),
175
+ ("READ", bytes.fromhex("f3"), 2),
176
+ ("REM", bytes.fromhex("f4"), 32),
177
+ ("RUN", bytes.fromhex("f9"), 1),
178
+ ("RAD", bytes.fromhex("b2"), 0),
179
+ ("RESTORE", bytes.fromhex("f7"), 18),
180
+ ("RIGHT$(", bytes.fromhex("c2"), 128),
181
+ ("RND", bytes.fromhex("b3"), 1),
182
+ ("RECTANGLE", bytes.fromhex("c893"), 74),
183
+ ("RENUMBER", bytes.fromhex("c799"), 24),
184
+ ("STEP", bytes.fromhex("88"), 0),
185
+ ("SAVE", bytes.fromhex("c79a"), 10),
186
+ ("SGN", bytes.fromhex("b4"), 0),
187
+ ("SIN", bytes.fromhex("b5"), 0),
188
+ ("SQR", bytes.fromhex("b6"), 0),
189
+ ("SOUND", bytes.fromhex("d4"), 2),
190
+ ("SPC", bytes.fromhex("89"), 0),
191
+ ("STR$", bytes.fromhex("c3"), 0),
192
+ ("STRING$(", bytes.fromhex("c4"), 128),
193
+ ("STOP", bytes.fromhex("fa"), 1),
194
+ ("STEREO", bytes.fromhex("c8a2"), 74),
195
+ ("SUM", bytes.fromhex("c68e"), 14),
196
+ ("SWAP", bytes.fromhex("c894"), 74),
197
+ ("SYS", bytes.fromhex("c899"), 74),
198
+ ("TAN", bytes.fromhex("b7"), 0),
199
+ ("TAB(", bytes.fromhex("8a"), 128),
200
+ ("TEMPO", bytes.fromhex("c89f"), 74),
201
+ ("TEXTLOAD", bytes.fromhex("c79b"), 10),
202
+ ("TEXTSAVE", bytes.fromhex("c79c"), 10),
203
+ ("THEN", bytes.fromhex("8c"), 20),
204
+ ("TIME", bytes.fromhex("91"), 67),
205
+ ("TINT", bytes.fromhex("c89c"), 74),
206
+ ("TO", bytes.fromhex("b8"), 0),
207
+ ("TRACE", bytes.fromhex("fc"), 18),
208
+ ("TRUE", bytes.fromhex("b9"), 1),
209
+ ("TWINO", bytes.fromhex("c79e"), 10),
210
+ ("TWIN", bytes.fromhex("c79d"), 9),
211
+ ("UNTIL", bytes.fromhex("fd"), 2),
212
+ ("USR", bytes.fromhex("ba"), 0),
213
+ ("VDU", bytes.fromhex("ef"), 2),
214
+ ("VAL", bytes.fromhex("bb"), 0),
215
+ ("VPOS", bytes.fromhex("bc"), 1),
216
+ ("VOICES", bytes.fromhex("c8a0"), 74),
217
+ ("VOICE", bytes.fromhex("c8a1"), 74),
218
+ ("WHILE", bytes.fromhex("c895"), 74),
219
+ ("WHEN", bytes.fromhex("c9"), 2),
220
+ ("WAIT", bytes.fromhex("c896"), 73),
221
+ ("WIDTH", bytes.fromhex("fe"), 2),
222
+ )
223
+
224
+ _KEYWORDS_V_BY_FIRST: dict[str, list[tuple[str, bytes, int]]] = {}
225
+ for _keyword, _token, _job in KEYWORDS_V:
226
+ _KEYWORDS_V_BY_FIRST.setdefault(_keyword[0], []).append((_keyword, _token, _job))
227
+
228
+
229
+ def _is_word_char(c: str) -> bool:
230
+ """``WORDCQ``: digits, ``A``-``Z``, and everything from ``_`` to ``z``."""
231
+ return ("0" <= c <= "9") or ("A" <= c <= "Z") or ("_" <= c <= "z")
232
+
233
+
234
+ def _is_hex_digit(c: str) -> bool:
235
+ return ("0" <= c <= "9") or ("A" <= c <= "F") or ("a" <= c <= "f")
236
+
237
+
238
+ def _is_number_char(c: str) -> bool:
239
+ """``NUMBCQ``: a digit or a decimal point."""
240
+ return ("0" <= c <= "9") or c == "."
241
+
242
+
243
+ def encode_line_reference(line_number: int) -> bytes:
244
+ """The three bytes after ``&8D`` for *line_number*, as ``CONSTI`` writes them.
245
+
246
+ ``CONSTI`` keeps six bits of each byte and gathers the top two of both
247
+ into the control byte, so every line number up to 65279 survives. For
248
+ line numbers up to 32767 the bytes are those BASIC II writes.
249
+ """
250
+ lo = line_number & 0xFF
251
+ hi = (line_number >> 8) & 0xFF
252
+ control = (((hi >> 4) & 0x0C) | ((lo & 0xC0) >> 2)) ^ 0x54
253
+ return bytes((control, (lo & 0x3F) | 0x40, (hi & 0x3F) | 0x40))
254
+
255
+
256
+ def _copy_while(text: str, i: int, out: bytearray, wanted) -> tuple[int, str | None]:
257
+ """Copy characters from ``text[i]`` while *wanted*; then copy the next one too.
258
+
259
+ Returns the index after it and that next character, which ``MATCH``
260
+ has copied but not yet examined (``None`` at the end of the line).
261
+ """
262
+ n = len(text)
263
+ while i < n and wanted(text[i]):
264
+ out.append(ord(text[i]))
265
+ i += 1
266
+ if i >= n:
267
+ return i, None
268
+ out.append(ord(text[i]))
269
+ return i + 1, text[i]
270
+
271
+
272
+ def _match_keyword(text: str, i: int) -> tuple[bytes, int, int] | None:
273
+ """The keyword ``MATCH`` finds at ``text[i]``: ``(token, end, job)``, or ``None``.
274
+
275
+ Entries for the first letter are tried in table order, and the first
276
+ to match in full, or up to a ``.`` abbreviation, wins; *end* indexes
277
+ the character after it (after the ``.``). A conditional keyword with a
278
+ name character after it ends the search: the word is then a name.
279
+ """
280
+ n = len(text)
281
+ for keyword, token, job in _KEYWORDS_V_BY_FIRST.get(text[i], ()):
282
+ j = i + 1
283
+ matched = True
284
+ for keyword_char in keyword[1:]:
285
+ source_char = text[j] if j < n else ""
286
+ if source_char == keyword_char:
287
+ j += 1
288
+ elif source_char == ".":
289
+ j += 1 # abbreviated
290
+ break
291
+ else:
292
+ matched = False
293
+ break
294
+ if not matched:
295
+ continue
296
+ if job & _JOB_CONDITIONAL and j < n and _is_word_char(text[j]):
297
+ return None
298
+ return token, j, job
299
+ return None
300
+
301
+
302
+ def tokenise_body_v(text: str) -> bytearray:
303
+ """Crunch one line's statement text (after its line number) as ``MATCH`` does.
304
+
305
+ The text starts in left mode with a line-number reference armed, as
306
+ ``MATCH`` leaves them after reading the line number. A constant too
307
+ large for a line number (65280 or more) is left as its digits.
308
+ """
309
+ out = bytearray()
310
+ n = len(text)
311
+ i = 0
312
+ left = True # MODE 0: at the start of a statement
313
+ armed = True # CONSTA: the next number is a line-number reference
314
+ in_quotes = False
315
+ give_up = False # the rest of the line is copied literally
316
+ pending: str | None = None # a character already copied, still to examine
317
+
318
+ while True:
319
+ if pending is not None:
320
+ c, pending = pending, None
321
+ else:
322
+ if i >= n:
323
+ break
324
+ c = text[i]
325
+ i += 1
326
+ out.append(ord(c))
327
+
328
+ if c == " ":
329
+ continue
330
+ if c == '"':
331
+ in_quotes = not in_quotes
332
+ if in_quotes or give_up:
333
+ continue
334
+
335
+ if c == "&": # a hex constant: copied, and leaves the mode alone
336
+ while i < n and _is_hex_digit(text[i]):
337
+ out.append(ord(text[i]))
338
+ i += 1
339
+ if i < n:
340
+ pending = text[i]
341
+ out.append(ord(pending))
342
+ i += 1
343
+ continue
344
+
345
+ if c == ":":
346
+ left, armed = True, False
347
+ continue
348
+ if c == ",":
349
+ continue
350
+ if c == "*":
351
+ if left:
352
+ give_up = True # OSCLI: the rest of the line is the command
353
+ else:
354
+ left, armed = False, False
355
+ continue
356
+
357
+ if c == "." or ("0" <= c <= "9" and not armed): # MATCHZ: a number
358
+ i, pending = _copy_while(text, i, out, _is_number_char)
359
+ left, armed = False, False
360
+ continue
361
+
362
+ if "0" <= c <= "9": # armed: a line-number reference, if small enough
363
+ j = i
364
+ value = ord(c) - ord("0")
365
+ while j < n and "0" <= text[j] <= "9":
366
+ value = value * 10 + ord(text[j]) - ord("0")
367
+ j += 1
368
+ if value > BASIC_V_MAX_LINE_NUMBER:
369
+ break
370
+ if value > BASIC_V_MAX_LINE_NUMBER: # too large: an ordinary number
371
+ i, pending = _copy_while(text, i, out, _is_number_char)
372
+ left, armed = False, False
373
+ continue
374
+ del out[-1]
375
+ out.append(LINE_NUMBER_TOKEN)
376
+ out += encode_line_reference(value)
377
+ i = j
378
+ continue # the mode and the arm are left as they were
379
+
380
+ if c < "A":
381
+ left, armed = False, False
382
+ continue
383
+
384
+ if c > "W":
385
+ if _is_word_char(c): # MATCHH: a name
386
+ i, pending = _copy_while(text, i, out, _is_word_char)
387
+ left, armed = False, False
388
+ continue
389
+
390
+ match = _match_keyword(text, i - 1)
391
+ if match is None: # not a keyword: a name
392
+ i, pending = _copy_while(text, i, out, _is_word_char)
393
+ left, armed = False, False
394
+ continue
395
+ token, i, job = match
396
+ if not job & _JOB_TWO_BYTE and job & _JOB_POLYMORPHIC and left:
397
+ token = bytes((token[0] + _POLYMORPHIC_OFFSET,))
398
+ del out[-1]
399
+ out += token
400
+ if job & _JOB_RIGHT:
401
+ left, armed = False, False
402
+ # On a two-byte token bit 2 chose the &C6 prefix and is cleared.
403
+ if job & _JOB_LEFT and not job & _JOB_TWO_BYTE:
404
+ left, armed = True, False
405
+ if len(token) == 1 and token[0] in (_FN_TOKEN, _PROC_TOKEN):
406
+ while i < n and _is_word_char(text[i]):
407
+ out.append(ord(text[i]))
408
+ i += 1
409
+ if job & _JOB_ARM:
410
+ armed = True
411
+ if job & _JOB_GIVE_UP:
412
+ give_up = True
413
+
414
+ return out
@@ -38,11 +38,14 @@ from oaknut.basic.tokens import HEADER_LENGTH
38
38
 
39
39
  _CR = 0x0D
40
40
 
41
- # A stored line number is 0-32767 (see oaknut.basic.linenumber.MAX_LINE_NUMBER),
41
+ # A BASIC II line number is 0-32767 (see oaknut.basic.linenumber.MAX_LINE_NUMBER),
42
42
  # so its high byte is always <= &7F — top bit clear. The end-of-program
43
43
  # terminator's second byte has the top bit set (&FF, or a tampered &80-&FE).
44
44
  # Testing the top bit therefore tells a terminator from a line-number high
45
- # byte, exactly as the ROM's LIST loop does.
45
+ # byte, exactly as the ROM's LIST loop does. BASIC V stores line numbers up
46
+ # to 65279, though, so a top-bit byte other than &FF may instead begin a
47
+ # line: it does when well-formed, ascending lines follow it all the way to
48
+ # a &0D &FF terminator (see _continues_to_ff).
46
49
  _TERMINATOR_TOP_BIT = 0x80
47
50
 
48
51
 
@@ -155,7 +158,15 @@ def detect(data: bytes | bytearray) -> Detection:
155
158
  return broke(f"truncated after &0D at offset {pos}")
156
159
 
157
160
  marker = data[pos + 1]
158
- if marker & _TERMINATOR_TOP_BIT:
161
+ basic_v_line = (
162
+ marker & _TERMINATOR_TOP_BIT
163
+ and marker != 0xFF
164
+ and line_count > 0
165
+ and _continues_to_ff(data, pos, last_line)
166
+ )
167
+ if basic_v_line and not any("above 32767" in note for note in notes):
168
+ notes.append("line numbers above 32767 — BASIC V")
169
+ if marker & _TERMINATOR_TOP_BIT and not basic_v_line:
159
170
  # A terminator before any line parsed means the leading &0D was
160
171
  # a coincidence (e.g. a View document opening &0D &80), not an
161
172
  # empty program — real type-ins always have at least one line.
@@ -206,3 +217,29 @@ def detect(data: bytes | bytearray) -> Detection:
206
217
  last_line = line_no
207
218
  line_count += 1
208
219
  pos += length
220
+
221
+
222
+ def _continues_to_ff(data: bytes | bytearray, pos: int, last_line: int | None) -> bool:
223
+ """Whether lines starting at *pos* run, well-formed and ascending, to ``&0D &FF``.
224
+
225
+ The test for a BASIC V line number above 32767, whose high byte has its
226
+ top bit set like a BASIC II terminator's: data appended after a
227
+ tampered terminator does not go on to form such lines.
228
+ """
229
+ n = len(data)
230
+ previous = last_line
231
+ while pos + 1 < n and data[pos] == _CR:
232
+ marker = data[pos + 1]
233
+ if marker == 0xFF:
234
+ return True
235
+ if pos + HEADER_LENGTH > n:
236
+ return False
237
+ line_no = (marker << 8) | data[pos + 2]
238
+ length = data[pos + 3]
239
+ if length < HEADER_LENGTH or pos + length > n:
240
+ return False
241
+ if previous is not None and line_no <= previous:
242
+ return False
243
+ previous = line_no
244
+ pos += length
245
+ return False
@@ -1,4 +1,4 @@
1
- """De-tokenise BBC BASIC II bytes into source text.
1
+ """De-tokenise BBC BASIC bytes into source text.
2
2
 
3
3
  The de-tokeniser is the *text projection* of the token scanner
4
4
  (:mod:`oaknut.basic.scanner`): :func:`detokenise` mirrors the ROM's
@@ -1,4 +1,4 @@
1
- """BBC BASIC dialects for de-tokenisation.
1
+ """BBC BASIC dialects for tokenising and de-tokenising.
2
2
 
3
3
  The :mod:`~oaknut.basic.tokens` table is **BBC BASIC II** — the BBC
4
4
  Micro's 8-bit language ROM. BBC BASIC V (the Archimedes / RISC OS ARM
@@ -19,10 +19,16 @@ BASIC V program with the BASIC II table corrupts every extended keyword:
19
19
  keywords ``WHEN``/``OF``/``ENDCASE``/``ELSE``/``ENDIF``/``ENDWHILE``
20
20
  (the command spellings move into the ``&C7`` escape table).
21
21
 
22
+ BASIC V also stores line numbers up to 65279, where BASIC II stops at
23
+ 32767. A stored line number's high byte therefore has its top bit set in
24
+ BASIC V, so BASIC V ends a program only at ``&0D &FF``, while BASIC II's
25
+ ROM ends it at ``&0D`` and any byte with the top bit set.
26
+
22
27
  A :class:`Dialect` bundles the single-byte token map with the escape
23
- tables, so the scanner and de-tokeniser can target either language with
24
- one parameter. :data:`BASIC_II` is the default everywhere — code that
25
- does not name a dialect keeps its existing BASIC II behaviour.
28
+ tables and the line-number range, so the scanner, de-tokeniser and
29
+ tokeniser can target either language with one parameter. :data:`BASIC_II`
30
+ is the default everywhere — code that does not name a dialect keeps its
31
+ existing BASIC II behaviour.
26
32
 
27
33
  The token values were cross-checked against two independent
28
34
  implementations: Justin Fletcher's de-tokeniser tables (the
@@ -36,8 +42,13 @@ from collections.abc import Mapping
36
42
  from dataclasses import dataclass
37
43
  from types import MappingProxyType
38
44
 
45
+ from oaknut.basic.linenumber import MAX_LINE_NUMBER
39
46
  from oaknut.basic.tokens import TOKEN_TO_KEYWORD
40
47
 
48
+ #: BASIC V's highest line number (the RISC OS BASIC reference manual's
49
+ #: limit, and what its tokeniser accepts).
50
+ BASIC_V_MAX_LINE_NUMBER = 65279
51
+
41
52
 
42
53
  @dataclass(frozen=True)
43
54
  class Dialect:
@@ -51,11 +62,21 @@ class Dialect:
51
62
  escape: Maps a two-byte escape *prefix* (``&C6``/``&C7``/``&C8``
52
63
  in BASIC V) to a table from the *following* byte to its
53
64
  extended keyword. Empty for dialects without escape tokens.
65
+ max_line_number: The highest line number the dialect stores.
66
+ end_marker_is_ff: Whether a program ends only at ``&0D &FF``
67
+ (BASIC V, whose line numbers fill the high byte), rather than at
68
+ ``&0D`` and any byte with the top bit set (BASIC II).
54
69
  """
55
70
 
56
71
  name: str
57
72
  single_byte: Mapping[int, str]
58
73
  escape: Mapping[int, Mapping[int, str]]
74
+ max_line_number: int = MAX_LINE_NUMBER
75
+ end_marker_is_ff: bool = False
76
+
77
+ def ends_program(self, marker: int) -> bool:
78
+ """Whether *marker*, the byte after a line's ``&0D``, ends the program."""
79
+ return marker == 0xFF if self.end_marker_is_ff else bool(marker & 0x80)
59
80
 
60
81
 
61
82
  # --- BBC BASIC II -----------------------------------------------------------
@@ -159,4 +180,6 @@ BASIC_V = Dialect(
159
180
  0xC8: _extended_table(_EXTENDED_STATEMENTS),
160
181
  }
161
182
  ),
183
+ max_line_number=BASIC_V_MAX_LINE_NUMBER,
184
+ end_marker_is_ff=True,
162
185
  )
@@ -94,9 +94,15 @@ class LineNumberRangeError(TokeniseError):
94
94
  line_number: The out-of-range line number.
95
95
  """
96
96
 
97
- def __init__(self, line_index: int, line_number: int, line_text: str) -> None:
97
+ def __init__(
98
+ self,
99
+ line_index: int,
100
+ line_number: int,
101
+ line_text: str,
102
+ maximum: int = MAX_LINE_NUMBER,
103
+ ) -> None:
98
104
  super().__init__(
99
- f"line {line_index}: line number {line_number} is out of range (0-{MAX_LINE_NUMBER})",
105
+ f"line {line_index}: line number {line_number} is out of range (0-{maximum})",
100
106
  line_index=line_index,
101
107
  line_text=line_text,
102
108
  )
@@ -1,4 +1,4 @@
1
- """Scan tokenised BBC BASIC II bytes into a position-aware token stream.
1
+ """Scan tokenised BBC BASIC bytes into a position-aware token stream.
2
2
 
3
3
  De-tokenising to text is lossy for keyword adjacency: the body
4
4
  ``?Q <PLOT> ?Q`` renders as the text ``?QPLOT?Q``, which the ROM
@@ -36,7 +36,6 @@ from oaknut.basic.linenumber import decode_line_number
36
36
  from oaknut.basic.tokens import HEADER_LENGTH, LINE_NUMBER_TOKEN
37
37
 
38
38
  _CR = 0x0D
39
- _END_MARKER = 0xFF
40
39
  _QUOTE = 0x22
41
40
 
42
41
 
@@ -175,7 +174,11 @@ def scan_program(data: bytes, *, dialect: Dialect = BASIC_II) -> Iterator[LineRe
175
174
 
176
175
  Args:
177
176
  data: A tokenised program as stored on disc or in memory,
178
- terminated by the ``&0D &FF`` end marker.
177
+ terminated by the ``&0D &FF`` end marker. Under BASIC II, as
178
+ its ROM does, ``&0D`` followed by any byte with its top bit set
179
+ also ends it; BASIC V's line numbers reach 65279, so only
180
+ ``&FF`` ends a BASIC V program (see :meth:`Dialect.ends_program`).
181
+ Bytes after the end marker are ignored.
179
182
  dialect: The BBC BASIC variant whose token tables to use, passed
180
183
  through to :func:`scan`. Defaults to
181
184
  :data:`~oaknut.basic.BASIC_II`.
@@ -196,8 +199,8 @@ def scan_program(data: bytes, *, dialect: Dialect = BASIC_II) -> Iterator[LineRe
196
199
  raise MissingLineMarkerError(offset=i, found=data[i])
197
200
  if i + 1 >= n:
198
201
  raise TruncatedProgramError(offset=i, detail="line marker with no line number")
199
- if data[i + 1] == _END_MARKER:
200
- break
202
+ if dialect.ends_program(data[i + 1]):
203
+ break # anything after the end marker is not program
201
204
  if i + HEADER_LENGTH > n:
202
205
  raise TruncatedProgramError(offset=i, detail="incomplete line header")
203
206
  line_number = (data[i + 1] << 8) | data[i + 2]
@@ -1,6 +1,8 @@
1
- """Tokenise BBC BASIC II source text into a stored program.
1
+ """Tokenise BBC BASIC source text into a stored program.
2
2
 
3
- This reproduces the ROM's line-input "crunch": each numbered source line
3
+ BBC BASIC II is the default; ``dialect=BASIC_V`` crunches as the RISC OS
4
+ BASIC module does instead (see :mod:`oaknut.basic.crunch_v`). For BASIC
5
+ II this reproduces the ROM's line-input "crunch": each numbered source line
4
6
  is framed into a ``&0D <hi> <lo> <length>`` record whose body is the
5
7
  tokenised statement text. The body crunch is a small state machine over
6
8
  two pieces of state, matching the disassembly:
@@ -29,6 +31,8 @@ from __future__ import annotations
29
31
 
30
32
  from typing import Literal
31
33
 
34
+ from oaknut.basic.crunch_v import ELSE_TOKEN, LINE_ELSE_TOKEN, tokenise_body_v
35
+ from oaknut.basic.dialect import BASIC_II, BASIC_V, Dialect
32
36
  from oaknut.basic.exceptions import (
33
37
  AlreadyNumberedError,
34
38
  LineNumberOrderError,
@@ -86,8 +90,9 @@ def tokenise(
86
90
  start: int | None = None,
87
91
  step: int | None = None,
88
92
  crunch: Crunch = "rom",
93
+ dialect: Dialect = BASIC_II,
89
94
  ) -> bytes:
90
- """Tokenise BBC BASIC II source text into a stored program.
95
+ """Tokenise BBC BASIC source text into a stored program.
91
96
 
92
97
  Args:
93
98
  source: BBC BASIC source. By default every non-blank line must
@@ -117,6 +122,16 @@ def tokenise(
117
122
  ``STOP`` before ``ELSE`` tokenises while ``NEW`` in
118
123
  ``NEWKEY%`` stays literal.
119
124
 
125
+ The greedy crunch is a BASIC II tokeniser; it is refused with
126
+ any other *dialect*.
127
+ dialect: The BBC BASIC variant to crunch for: :data:`BASIC_II`
128
+ (the default) or :data:`BASIC_V`, which crunches as the RISC OS
129
+ BASIC module does — its extended two-byte tokens, its own
130
+ keyword table and rules, line numbers up to 65279, and the
131
+ multi-line ``ELSE`` (``&CC``) for an ``ELSE`` that opens a line.
132
+ Spaces at the end of a line are kept, so a stored program's
133
+ listing re-tokenises to its own bytes.
134
+
120
135
  Returns:
121
136
  The tokenised program bytes, terminated by ``&0D &FF``.
122
137
 
@@ -126,6 +141,10 @@ def tokenise(
126
141
  out of range or out of order, or a line that tokenises beyond
127
142
  the maximum storable length.
128
143
  """
144
+ if dialect is not BASIC_II and dialect is not BASIC_V:
145
+ raise ValueError(f"cannot tokenise {dialect.name}: only BASIC II and BASIC V")
146
+ if crunch != "rom" and dialect is not BASIC_II:
147
+ raise ValueError(f"the {crunch!r} crunch is a BASIC II tokeniser, not {dialect.name}")
129
148
  auto_number = start is not None or step is not None
130
149
  lines = _split_source_lines(source)
131
150
  if auto_number:
@@ -146,13 +165,16 @@ def tokenise(
146
165
  if split is None:
147
166
  raise UnnumberedLineError(line_index, line)
148
167
  line_number, body_text = split
149
- if line_number > MAX_LINE_NUMBER:
150
- raise LineNumberRangeError(line_index, line_number, line)
168
+ if line_number > dialect.max_line_number:
169
+ raise LineNumberRangeError(line_index, line_number, line, dialect.max_line_number)
151
170
  if previous_number is not None and line_number <= previous_number:
152
171
  raise LineNumberOrderError(line_index, line_number, previous_number, line)
153
172
  previous_number = line_number
154
173
 
155
- body = _tokenise_body(body_text, line_index=line_index, line_text=line, crunch=crunch)
174
+ if dialect is BASIC_V:
175
+ body = _line_else(tokenise_body_v(body_text))
176
+ else:
177
+ body = _tokenise_body(body_text, line_index=line_index, line_text=line, crunch=crunch)
156
178
  if len(body) > MAX_BODY_LENGTH:
157
179
  raise LineTooLongError(line_index, line_number, len(body), line)
158
180
 
@@ -165,6 +187,18 @@ def tokenise(
165
187
  return bytes(out)
166
188
 
167
189
 
190
+ def _line_else(body: bytearray) -> bytearray:
191
+ """Mark an ``ELSE`` opening a BASIC V line as the multi-line ``ELSE``.
192
+
193
+ As the RISC OS BASIC module's line entry (``INSRT``) does: the first
194
+ byte after any leading spaces, if it is ``ELSE``, becomes ``&CC``.
195
+ """
196
+ stripped = body.lstrip(b" ")
197
+ if stripped[:1] == bytes((ELSE_TOKEN,)):
198
+ body[len(body) - len(stripped)] = LINE_ELSE_TOKEN
199
+ return body
200
+
201
+
168
202
  def _reject_existing_numbers(lines: list[str]) -> None:
169
203
  """Raise if any non-blank line already carries a line number."""
170
204
  for line_index, line in enumerate(lines, start=1):
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: oaknut-basic
3
- Version: 13.6.0
3
+ Version: 13.7.0
4
4
  Summary: BBC BASIC tools: program tokeniser/de-tokeniser and PRINT#/INPUT# data-file reader/writer
5
5
  Author-email: Robert Smallshire <robert@smallshire.org.uk>
6
6
  License-Expression: MIT
@@ -3,6 +3,7 @@ README.md
3
3
  pyproject.toml
4
4
  src/oaknut/basic/__init__.py
5
5
  src/oaknut/basic/cli.py
6
+ src/oaknut/basic/crunch_v.py
6
7
  src/oaknut/basic/datafile.py
7
8
  src/oaknut/basic/detect.py
8
9
  src/oaknut/basic/detokeniser.py
@@ -37,5 +38,6 @@ tests/test_packaging.py
37
38
  tests/test_rom_golden.py
38
39
  tests/test_rom_golden_detokenise.py
39
40
  tests/test_scanner.py
41
+ tests/test_tokenise_basic_v.py
40
42
  tests/test_tokeniser.py
41
43
  tests/test_tokens.py
@@ -413,3 +413,26 @@ class TestTokeniseDetokeniseRoundTrip:
413
413
  assert listing.exit_code == 0
414
414
  # Default UTF-8 output: host-native LF line endings.
415
415
  assert listing.stdout_bytes == b"10 PRINT\n20 GOTO 10\n"
416
+
417
+
418
+ class TestTokeniseDialect:
419
+ """``tokenise --dialect v`` crunches BASIC V (#45)."""
420
+
421
+ _SYS = bytes([0x0D, 0x00, 0x0A, 0x09, 0xC8, 0x99, 0x20, 0x58, 0x25, 0x0D, 0xFF])
422
+
423
+ def test_dialect_v_writes_escape_tokens(self):
424
+ result = CliRunner().invoke(cli, ["tokenise", "--dialect", "v"], input=b"10SYS X%\n")
425
+ assert result.exit_code == 0, result.output
426
+ assert result.stdout_bytes == self._SYS
427
+
428
+ def test_detokenise_and_tokenise_round_trip(self):
429
+ listing = CliRunner().invoke(cli, ["detokenise", "--dialect", "5"], input=self._SYS)
430
+ result = CliRunner().invoke(cli, ["tokenise", "--dialect", "5"], input=listing.stdout_bytes)
431
+ assert result.stdout_bytes == self._SYS
432
+
433
+ def test_greedy_crunch_is_refused_for_basic_v(self):
434
+ result = CliRunner().invoke(
435
+ cli, ["tokenise", "--dialect", "v", "--crunch", "greedy"], input=b"10PRINT\n"
436
+ )
437
+ assert result.exit_code != 0
438
+ assert "BASIC II" in result.output
@@ -150,3 +150,21 @@ class TestNeverRaises:
150
150
  # Must classify, never throw, whatever the input.
151
151
  result = detect(blob)
152
152
  assert isinstance(result.verdict, Verdict)
153
+
154
+
155
+ class TestBasicVLineNumbers:
156
+ """BASIC V stores line numbers up to 65279, whose high byte has the top bit set."""
157
+
158
+ def test_lines_above_32767_are_lines_not_a_terminator(self):
159
+ from oaknut.basic import BASIC_V, tokenise
160
+
161
+ program = tokenise("10PRINT 1\n32770PRINT 2\n40130END\n", dialect=BASIC_V)
162
+ detection = detect(program)
163
+ assert detection.verdict is Verdict.BASIC
164
+ assert (detection.line_count, detection.last_line) == (3, 40130)
165
+ assert any("above 32767" in note for note in detection.notes)
166
+
167
+ def test_data_after_a_tampered_terminator_is_still_trailing(self):
168
+ detection = detect(b"\x0d\x00\x0a\x07\xf4\x20\x41\x0d\xf2\x99\x0d\x00")
169
+ assert detection.verdict is Verdict.BASIC_TRAILING
170
+ assert detection.trailing_length == 3
@@ -35,6 +35,18 @@ class TestLineFraming:
35
35
  # 10<space>PRINT -> body is space + PRINT token.
36
36
  assert detokenise(_program((10, b"\x20\xf1"))) == "10 PRINT\n"
37
37
 
38
+ @pytest.mark.parametrize("marker", [0x80, 0xB3, 0xE1, 0xF2, 0xFF])
39
+ def test_any_top_bit_set_byte_after_cr_ends_the_program(self, marker):
40
+ # The BASIC ROM tests only bit 7 of the byte after &0D, so a
41
+ # program ending &0D &F2 is as complete as one ending &0D &FF (#43).
42
+ program = b"\x0d\x00\x0a\x07\xf4\x20\x41\x0d" + bytes((marker,))
43
+ assert detokenise(program) == "10REM A\n"
44
+
45
+ def test_bytes_after_the_terminator_are_ignored(self):
46
+ # Data appended after the end marker is not part of the program.
47
+ program = b"\x0d\x00\x0a\x07\xf4\x20\x41\x0d\xf2\x99\x0d\x00"
48
+ assert detokenise(program) == "10REM A\n"
49
+
38
50
  def test_multiple_lines_in_order(self):
39
51
  program = _program((10, b"\x20\xf1"), (20, b"\x20\xe0"))
40
52
  assert detokenise(program) == "10 PRINT\n20 END\n"
@@ -0,0 +1,126 @@
1
+ """Tokenising BBC BASIC V, the Archimedes / RISC OS dialect (#45).
2
+
3
+ The crunch follows the RISC OS BASIC module's ``MATCH`` routine and its
4
+ keyword table (``s/Lexical``, as imported from RISC OS 3.60), and its line
5
+ entry (``INSRT`` in ``s/Basic``), which turns an ``ELSE`` opening a line
6
+ into the multi-line ``ELSE`` token &CC.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import pytest
12
+ from oaknut.basic import (
13
+ BASIC_II,
14
+ BASIC_V,
15
+ LineNumberRangeError,
16
+ decode_line_number,
17
+ detokenise,
18
+ tokenise,
19
+ )
20
+
21
+
22
+ def _body(source_line: str) -> bytes:
23
+ """The tokenised body of a single numbered line under BASIC V."""
24
+ program = tokenise(source_line, dialect=BASIC_V)
25
+ length = program[3]
26
+ return program[4:length]
27
+
28
+
29
+ class TestEscapeTokens:
30
+ def test_sys_is_the_statement_escape(self):
31
+ prog = bytes([0x0D, 0x00, 0x0A, 0x09, 0xC8, 0x99, 0x20, 0x58, 0x25, 0x0D, 0xFF])
32
+ assert tokenise("10SYS X%", dialect=BASIC_V) == prog
33
+
34
+ @pytest.mark.parametrize(
35
+ ("source", "token"),
36
+ [
37
+ ("CASE", b"\xc8\x8e"),
38
+ ("WHILE", b"\xc8\x95"),
39
+ ("SUM", b"\xc6\x8e"),
40
+ ("BEAT", b"\xc6\x8f"),
41
+ ("APPEND", b"\xc7\x8e"),
42
+ ("INSTALL", b"\xc7\x9f"),
43
+ ("LIBRARY", b"\xc8\x9b"),
44
+ ],
45
+ )
46
+ def test_extended_keywords(self, source, token):
47
+ assert _body(f"10{source}").startswith(token)
48
+
49
+ def test_round_trips_the_listing(self):
50
+ prog = bytes([0x0D, 0x00, 0x0A, 0x09, 0xC8, 0x99, 0x20, 0x58, 0x25, 0x0D, 0xFF])
51
+ listing = detokenise(prog, dialect=BASIC_V)
52
+ assert listing == "10SYS X%\n"
53
+ assert tokenise(listing, dialect=BASIC_V) == prog
54
+
55
+
56
+ class TestSingleByteTokens:
57
+ def test_else_opening_a_line_is_the_multi_line_else(self):
58
+ assert _body("10 ELSE") == b"\x20\xcc"
59
+
60
+ def test_else_within_a_line_is_the_ordinary_else(self):
61
+ assert _body("10IF X THEN Y=1 ELSE Y=2").endswith(b" \x8b Y=2")
62
+
63
+ @pytest.mark.parametrize(
64
+ ("source", "token"),
65
+ [("OTHERWISE", 0x7F), ("WHEN", 0xC9), ("ENDCASE", 0xCB), ("ENDIF", 0xCD)],
66
+ )
67
+ def test_block_keywords(self, source, token):
68
+ assert _body(f"10{source}")[0] == token
69
+
70
+ def test_colour_has_an_american_spelling(self):
71
+ assert _body("10COLOR 1") == _body("10COLOUR 1")
72
+
73
+ def test_pseudo_variable_takes_its_assignment_form_at_statement_start(self):
74
+ assert _body("10TIME=0")[0] == 0xD1
75
+ assert _body("10PRINT TIME")[-1] == 0x91
76
+
77
+ def test_a_conditional_keyword_followed_by_a_name_character_is_a_name(self):
78
+ assert _body("10TRUEX=1") == b"TRUEX=1"
79
+
80
+ def test_lower_case_is_never_a_keyword(self):
81
+ assert _body("10print") == b"print"
82
+
83
+ def test_lower_case_hex_digits_belong_to_the_constant(self):
84
+ # BASIC V reads a-f as hex digits, so "&e" is a constant and the OR
85
+ # after it a keyword; BASIC II reads "eOR1" as a name.
86
+ assert _body("10X=&eOR1") == b"X=&e\x841"
87
+ assert tokenise("10X=&eOR1")[4:-2] == b"X=&eOR1"
88
+
89
+
90
+ class TestLineNumbers:
91
+ def test_stored_line_numbers_reach_65279(self):
92
+ program = tokenise("65279PRINT\n", dialect=BASIC_V)
93
+ assert program[1:3] == b"\xfe\xff"
94
+ assert detokenise(program, dialect=BASIC_V) == "65279PRINT\n"
95
+
96
+ def test_65280_is_out_of_range(self):
97
+ with pytest.raises(LineNumberRangeError, match="0-65279"):
98
+ tokenise("65280PRINT\n", dialect=BASIC_V)
99
+
100
+ def test_basic_ii_still_stops_at_32767(self):
101
+ with pytest.raises(LineNumberRangeError, match="0-32767"):
102
+ tokenise("32768PRINT\n")
103
+
104
+ def test_a_reference_above_32767_round_trips(self):
105
+ body = _body("10GOTO 40000")
106
+ assert body[:2] == b"\xe5\x20"
107
+ assert body[2] == 0x8D
108
+ assert decode_line_number(body[3:6]) == 40000
109
+
110
+ def test_detokenising_runs_past_line_32767(self):
111
+ source = "10PRINT 1\n32770PRINT 2\n40130END\n"
112
+ program = tokenise(source, dialect=BASIC_V)
113
+ assert detokenise(program, dialect=BASIC_V) == source
114
+
115
+ def test_basic_ii_still_ends_at_any_top_bit_marker(self):
116
+ program = b"\x0d\x00\x0a\x07\xf4\x20\x41\x0d\xf2"
117
+ assert detokenise(program, dialect=BASIC_II) == "10REM A\n"
118
+
119
+
120
+ class TestDialectChoice:
121
+ def test_the_greedy_crunch_is_basic_ii_only(self):
122
+ with pytest.raises(ValueError, match="greedy"):
123
+ tokenise("10PRINT\n", dialect=BASIC_V, crunch="greedy")
124
+
125
+ def test_basic_ii_output_is_unchanged(self):
126
+ assert tokenise("10PRINT TIME\n") == tokenise("10PRINT TIME\n", dialect=BASIC_II)
File without changes
File without changes
File without changes