Repository navigation
Expand file tree
/
Copy pathdecode_quickbasic_mac.py
More file actions
1277 lines (1122 loc) · 39.8 KB
/
Copy pathdecode_quickbasic_mac.py
File metadata and controls
1277 lines (1122 loc) · 39.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Decode tokenized Microsoft BASIC/QuickBASIC Macintosh source files.
The files handled here are not ordinary text. They contain length-prefixed
source lines, tokenized BASIC keywords, compact numeric constants, and a
symbol table. Literal text and symbol names use MacRoman; output is UTF-8 by
default.
Requires Python 3.10 or newer.
Examples::
# Decode one file to stdout
python decode_quickbasic_mac.py "path/to/Space Invaders"
# Decode every recognized file under a directory
python decode_quickbasic_mac.py path/to/archive --recursive --output decoded/
The opcode names below are adapted from Steve Witham's "Microsoft QuickBASIC
Decoder" (2008), which is freely offered for copying and modification:
https://mac-guyver.com/switham/2008/05/Decode_MS_BASIC/
"""
# SPDX-FileCopyrightText: 2026 Christoph Haunschmidt
# SPDX-License-Identifier: MIT
from __future__ import annotations
import argparse
import math
import struct
import sys
from collections.abc import Callable, Iterable, Mapping
from dataclasses import dataclass
from enum import Enum, IntEnum, auto
from pathlib import Path
from types import MappingProxyType
class DecodeError(ValueError):
"""Raised when bytes do not conform to the supported BASIC format."""
class FormatMarker(IntEnum):
"""Identify the numeric format used by a supported document."""
IEEE = 0xF1
MICROSOFT_DECIMAL = 0xF3
class PayloadCode(IntEnum):
"""Identify structural and numeric codes inside a source-line payload."""
SYMBOL_REFERENCE = 0x01
ALTERNATE_SYMBOL_REFERENCE = 0x02
LABEL_REFERENCE = 0x03
THEN_ELSE_LOCATION = 0x08
INTEGER_CONSTANT = 0x0C
LINE_TARGET = 0x0E
SHORT_INTEGER = 0x0F
COMPACT_DIGIT_0 = 0x11
COMPACT_DIGIT_9 = 0x1A
LABEL_DEFINITION = 0x1B
ALTERNATE_INTEGER_CONSTANT = 0x1C
SINGLE_FLOAT = 0x1D
LONG_INTEGER = 0x1E
DOUBLE_FLOAT = 0x1F
class PayloadMode(Enum):
"""Track whether payload bytes are code, string, DATA, or comment text."""
NORMAL = auto()
STRING = auto()
DATA = auto()
COMMENT = auto()
class Verbosity(IntEnum):
"""Name the detail levels accepted by the command-line interface."""
QUIET = 0
PROGRESS = 1
FILE_DETAILS = 2
TOKEN_TRACE = 3
# File-layout, text, and numeric-format constants.
NUL_BYTE = 0x00
END_MARKER_LENGTH = 0x0000
ZERO_LOCATION_VALUE = 0x00000000
STRING_DELIMITER = ord('"')
STATEMENT_SEPARATOR = ord(":")
APOSTROPHE_COMMENT_SEQUENCE = b":\xaf\xe8"
SYMBOL_LENGTH_BYTE_THRESHOLD = ord("A")
TOKEN_BYTE_MIN = 0x80
CONTROL_BYTE_LIMIT = 0x20
LINE_LENGTH_MASK = 0x0FFF
LINE_NUMBER_FLAG = 0x8000
BYTE_WIDTH = 1
WORD_WIDTH = 2
LONG_WORD_WIDTH = 4
MIN_SOURCE_RECORD_LENGTH = 4
MIN_SYMBOL_LENGTH = 1
MAX_SYMBOL_LENGTH = 40
THREE_BYTE_TARGET_FLAG = 0x08
THREE_BYTE_TARGET_SIZE = 3
FOUR_BYTE_TARGET_SIZE = 4
SINGLE_FLOAT_SIZE = 4
DOUBLE_FLOAT_SIZE = 8
PACKED_DECIMAL_SIGN_MASK = 0x80
PACKED_DECIMAL_EXPONENT_MASK = 0x7F
PACKED_DECIMAL_EXPONENT_BIAS = 65
PACKED_DECIMAL_NIBBLE_SHIFT = 4
PACKED_DECIMAL_NIBBLE_MASK = 0x0F
MAX_PACKED_DECIMAL_DIGIT = 9
@dataclass(frozen=True, slots=True)
class _EncodedLine:
"""One length-prefixed source line, including its decoded payload bytes."""
offset: int
length_word: int
payload: bytes
@dataclass(frozen=True, slots=True)
class DecodedProgram:
"""A decoded listing plus a little metadata about its original file."""
version_byte: int
lines: tuple[str, ...]
@property
def arithmetic_mode(self) -> str:
"""Return the numeric representation selected by the file marker."""
return (
"Microsoft decimal"
if self.version_byte == FormatMarker.MICROSOFT_DECIMAL
else "IEEE"
)
@property
def text(self) -> str:
"""Return source with Unix line endings and a final newline."""
return self.render()
def render(self, newline: str = "\n") -> str:
"""Return source with *newline* separators and a final newline."""
return newline.join(self.lines) + (newline if self.lines else "")
# Each row is ``spelling|hex opcode``. A two-byte opcode is used for
# Macintosh-specific statement/function groups. ``<empty>`` is an internal
# no-output token used by this dialect before certain parenthesized calls.
TOKEN_MAP_DATA = r"""
# Single-byte operators and keywords
=|EA
'|E8
+|EC
-|ED
*|EE
/|EF
^|F0
>|E9
<|EB
\|F7
AND|F1
ABS|80
ASC|81
ATN|82
CALL|83
CDBL|84
CHR$|85
CINT|86
CLOSE|87
COMMON|88
COS|89
CVD|8A
CVI|8B
CVS|8C
DATA|8D
ELSE|8E
EOF|8F
EXP|90
FIELD|91
FIX|92
FN|93
FOR|94
GET|95
GOSUB|96
GOTO|97
IF|98
INKEY$|99
INPUT|9A
INT|9B
LEFT$|9C
LEN|9D
LET|9E
LINE|9F
LOC|A1
LOF|A2
LOG|A3
LSET|A4
MOD|F6
MID$|A5
MKD$|A6
MKI$|A7
MKS$|A8
NEXT|A9
NOT|E7
OR|F2
ON|AA
OPEN|AB
PRINT|AC
PUT|AD
READ|AE
REM|AF
RETURN|B0
RIGHT$|B1
RND|B2
RSET|B3
SGN|B4
SIN|B5
SPACE$|B6
SQR|B7
STR$|B8
STRING$|B9
STATIC|E3
TAN|BA
THEN|E6
TO|E5
USING|E4
VAL|BC
WEND|BD
WHILE|BE
WRITE|BF
ELSEIF|C0
CLNG|C1
CVL|C2
MKL$|C3
EQV|F4
IMP|F5
XOR|F3
# F8-prefixed statements/functions
AUTO|F8 80
CHAIN|F8 81
CLEAR|F8 82
CLS|F8 83
CONT|F8 84
CSNG|F8 85
DATE$|F8 86
DEFINT|F8 87
DEFSNG|F8 88
DEFDBL|F8 89
DEFSTR|F8 8A
DEF|F8 8B
DELETE|F8 8C
DIM|F8 8D
EDIT|F8 8E
END|F8 8F
ERASE|F8 90
ERL|F8 91
ERROR|F8 92
ERR|F8 93
FILES|F8 94
FRE|F8 95
HEX$|F8 96
INSTR|F8 97
KILL|F8 98
LIST|F8 99
LLIST|F8 9A
LOAD|F8 9B
LPOS|F8 9C
LPRINT|F8 9D
MERGE|F8 9E
NAME|F8 9F
NEW|F8 A0
OCT$|F8 A1
OPTION|F8 A2
PEEK|F8 A3
POKE|F8 A4
POS|F8 A5
RANDOMIZE|F8 A6
RENUM|F8 A7
RESTORE|F8 A8
RESUME|F8 A9
RUN|F8 AA
SAVE|F8 AB
SHELL|F8 AC
STOP|F8 AD
SWAP|F8 AE
SYSTEM|F8 AF
TIME$|F8 B0
TRON|F8 B1
TROFF|F8 B2
VARPTR|F8 B3
WIDTH|F8 B4
BEEP|F8 B5
CIRCLE|F8 B6
LCOPY|F8 B7
MOUSE|F8 B8
POINT|F8 B9
PRESET|F8 BA
PSET|F8 BB
RESET|F8 BC
TIMER|F8 BD
SUB|F8 BE
EXIT|F8 BF
SOUND|F8 C0
BUTTON|F8 C1
MENU|F8 C2
WINDOW|F8 C3
DIALOG|F8 C4
LOCATE|F8 C5
CSRLIN|F8 C6
LBOUND|F8 C7
UBOUND|F8 C8
SHARED|F8 C9
UCASE$|F8 CA
SCROLL|F8 CB
LIBRARY|F8 CC
CVSBCD|F8 CD
CVDBCD|F8 CE
MKSBCD$|F8 CF
MKDBCD$|F8 D0
<empty>|F8 D1
DEFLNG|F8 D6
SADD|F8 D7
COLOR|F8 D9
PALETTE|F8 DB
CHDIR|F8 DD
CASE|F8 E0
PRINTDIALOG|F8 E1
SCROLLBAR|F8 E2
SELECT|F8 E3
# F9-prefixed keywords and arguments
ABOUT|F9 F3
OFF|F9 F4
BREAK|F9 F5
WAIT|F9 F6
USR|F9 F7
TAB|F9 F8
STEP|F9 F9
SPC|F9 FA
OUTPUT|F9 FB
BASE|F9 FC
AS|F9 FD
APPEND|F9 FE
ALL|F9 FF
IS|F9 F2
# FA-prefixed memory, picture, and sound functions
PICTURE|FA 80
WAVE|FA 81
POKEW|FA 82
POKEL|FA 83
PEEKW|FA 84
PEEKL|FA 85
# FB-prefixed Macintosh graphics and TextEdit functions
BACKPAT|FB FF
INITCURSOR|FB FE
SETCURSOR|FB FD
HIDECURSOR|FB FC
SHOWCURSOR|FB FB
OBSCURECURSOR|FB FA
HIDEPEN|FB F9
SHOWPEN|FB F8
GETPEN|FB F7
PENSIZE|FB F6
PENMODE|FB F5
PENPAT|FB F4
PENNORMAL|FB F3
MOVETO|FB F2
MOVE|FB F1
LINETO|FB F0
TEXTFONT|FB EF
TEXTFACE|FB EE
TEXTMODE|FB ED
TEXTSIZE|FB EC
FRAMERECT|FB EB
PAINTRECT|FB EA
ERASERECT|FB E9
INVERTRECT|FB E8
FILLRECT|FB E7
FRAMEOVAL|FB E6
PAINTOVAL|FB E5
ERASEOVAL|FB E4
INVERTOVAL|FB E3
FILLOVAL|FB E2
FRAMEROUNDRECT|FB E1
PAINTROUNDRECT|FB E0
ERASEROUNDRECT|FB DF
INVERTROUNDRECT|FB DE
FILLROUNDRECT|FB DD
FRAMEARC|FB DC
PAINTARC|FB DB
ERASEARC|FB DA
INVERTARC|FB D9
FILLARC|FB D8
PTAB|FB D7
FRAMEPOLY|FB D6
PAINTPOLY|FB D5
ERASEPOLY|FB D4
INVERTPOLY|FB D3
FILLPOLY|FB D2
TESETTEXT|FB D1
TESETSELECT|FB D0
TESCROLL|FB CF
TEKEY|FB CE
TEDELETE|FB CD
TEINSERT|FB CC
TEACTIVATE|FB CB
TEDEACTIVATE|FB CA
TEUPDATE|FB C9
TECALTEXT|FB C8
"""
def _build_token_table() -> dict[tuple[int, ...], str]:
"""Build the opcode lookup table from the readable table above."""
token_table: dict[tuple[int, ...], str] = {}
for row_number, row in enumerate(TOKEN_MAP_DATA.splitlines(), start=1):
row = row.strip()
if not row or row.startswith("#"):
continue
spelling, encoded = row.split("|", maxsplit=1)
spelling = "" if spelling == "<empty>" else spelling
opcode = tuple(int(part, 16) for part in encoded.split())
if opcode in token_table:
raise RuntimeError(f"duplicate token opcode on table row {row_number}")
token_table[opcode] = spelling
return token_table
TOKEN_TABLE: Mapping[tuple[int, ...], str] = MappingProxyType(_build_token_table())
_TOKEN_PREFIXES = frozenset(opcode[0] for opcode in TOKEN_TABLE if len(opcode) == 2)
PLUS_OPERATOR_CODE = next(
opcode[0]
for opcode, spelling in TOKEN_TABLE.items()
if len(opcode) == 1 and spelling == "+"
)
class QuickBasicMacDecoder:
"""Decode one saved Macintosh QuickBASIC program.
An optional ``trace`` callback receives offset-aware token and constant
details during decoding.
"""
SUPPORTED_MARKERS = frozenset(FormatMarker)
def __init__(
self,
data: bytes,
*,
source_name: str = "<input>",
trace: Callable[[str], None] | None = None,
) -> None:
"""Initialize decoding state for one source document.
Args:
data: The complete binary document to decode.
source_name: A name included in decoding errors and trace events.
trace: An optional callback for detailed token and constant events.
"""
self._data = data
self._source_name = source_name
self._trace_callback = trace
self._position = 0
self._version_byte = 0
self._goto_target_size = 4
self._decimal_mode = False
def decode(self) -> DecodedProgram:
"""Parse the file and reconstruct its printable BASIC listing."""
if not self._data:
raise DecodeError(f"{self._source_name}: empty file")
self._version_byte = self._read_u8("format marker")
if self._version_byte not in self.SUPPORTED_MARKERS:
raise DecodeError(
f"{self._source_name}: unsupported format marker "
f"0x{self._version_byte:02X}; expected F1 or F3"
)
# The marker selects the numeric representation and target width.
self._decimal_mode = self._version_byte == FormatMarker.MICROSOFT_DECIMAL
self._goto_target_size = (
THREE_BYTE_TARGET_SIZE
if self._version_byte & THREE_BYTE_TARGET_FLAG
else FOUR_BYTE_TARGET_SIZE
)
encoded_lines = self._read_source_records()
symbols = self._read_symbol_table()
decoded_lines = tuple(
self._decode_line(record, symbols, line_index)
for line_index, record in enumerate(encoded_lines, start=1)
)
return DecodedProgram(self._version_byte, decoded_lines)
def _read_exact(self, size: int, what: str) -> bytes:
"""Read exactly *size* bytes, with an offset-rich error on truncation."""
if size < 0:
raise DecodeError(f"{self._source_name}: invalid size for {what}")
end = self._position + size
if end > len(self._data):
raise DecodeError(
f"{self._source_name}: truncated {what} at file offset "
f"0x{self._position:X} (wanted {size} byte(s))"
)
result = self._data[self._position : end]
self._position = end
return result
def _read_u8(self, what: str) -> int:
"""Read one unsigned byte from the document."""
return self._read_exact(1, what)[0]
def _read_u16(self, what: str) -> int:
"""Read one big-endian unsigned 16-bit value from the document."""
return int.from_bytes(self._read_exact(2, what), "big")
def _read_uint_from(self, payload: bytes, offset: int, size: int, what: str) -> int:
"""Read an unsigned big-endian integer from a line payload."""
end = offset + size
if end > len(payload):
raise DecodeError(f"{self._source_name}: truncated {what} in source record")
return int.from_bytes(payload[offset:end], "big")
def _read_source_records(self) -> list[_EncodedLine]:
"""Read records up to the zero-length terminator."""
records: list[_EncodedLine] = []
while True:
record_offset = self._position
length_word = self._read_u16("source-line length")
line_length = length_word & LINE_LENGTH_MASK
if line_length == END_MARKER_LENGTH:
# End marker is a zero length word followed by a zero indent.
if length_word != END_MARKER_LENGTH:
raise DecodeError(
f"{self._source_name}: invalid end marker at "
f"0x{record_offset:X}"
)
if self._read_u8("end-marker indent") != NUL_BYTE:
raise DecodeError(
f"{self._source_name}: invalid end-marker indent at "
f"0x{self._position - 1:X}"
)
return records
if line_length < MIN_SOURCE_RECORD_LENGTH:
raise DecodeError(
f"{self._source_name}: implausible source-line length "
f"{line_length} at 0x{record_offset:X}"
)
# Length counts the two-byte length field, the record body, and
# its final NUL. Keep the body minus that terminator for listing.
remainder = self._read_exact(line_length - 2, "source-line record")
if not remainder or remainder[-1] != NUL_BYTE:
raise DecodeError(
f"{self._source_name}: source line at 0x{record_offset:X} "
"does not end with NUL"
)
records.append(_EncodedLine(record_offset, length_word, remainder[:-1]))
def _read_symbol_table(self) -> list[str]:
"""Read the trailing length-prefixed variable/label name table.
Two harmless historical variations occur in the sample collection:
a single extra NUL before the table and a one-byte prefix before its
first name. Both are accepted here.
"""
if self._position == len(self._data):
return []
# Some saved files have no symbol table and end in padding NULs.
if not any(self._data[self._position :]):
self._position = len(self._data)
return []
# A few files have one extra NUL between the end marker and table.
if (
self._data[self._position] == NUL_BYTE
and self._position + 1 < len(self._data)
and MIN_SYMBOL_LENGTH <= self._data[self._position + 1] <= MAX_SYMBOL_LENGTH
):
self._position += 1
first_length = self._read_u8("first symbol length/prefix")
if first_length > MAX_SYMBOL_LENGTH:
# An undocumented flag/prefix byte seen in some Mac BASIC saves.
first_length = self._read_u8("symbol length after prefix")
symbols: list[str] = []
while True:
if not MIN_SYMBOL_LENGTH <= first_length <= MAX_SYMBOL_LENGTH:
raise DecodeError(
f"{self._source_name}: invalid symbol length "
f"{first_length} at 0x{self._position - 1:X}"
)
if not symbols:
# The first table entry has a legacy ambiguity: in some files
# the byte following the apparent length is itself the true
# length. This mirrors the observed Macintosh save variants.
first_byte = self._read_u8("first symbol byte")
if first_byte < SYMBOL_LENGTH_BYTE_THRESHOLD:
actual_length = first_byte
if not MIN_SYMBOL_LENGTH <= actual_length <= MAX_SYMBOL_LENGTH:
raise DecodeError(
f"{self._source_name}: invalid first symbol length "
f"{actual_length}"
)
name_bytes = self._read_exact(actual_length, "first symbol")
else:
name_bytes = bytes([first_byte])
if first_length > 1:
name_bytes += self._read_exact(first_length - 1, "first symbol")
else:
name_bytes = self._read_exact(first_length, "symbol")
symbols.append(name_bytes.decode("mac_roman"))
if self._position == len(self._data):
break
first_length = self._read_u8("symbol length")
return symbols
def _decode_line(
self,
record: _EncodedLine,
symbols: list[str],
line_index: int,
) -> str:
"""Decode one line's prefix, tokens, literals, and compact numbers."""
payload = record.payload
if not payload:
raise DecodeError(f"{self._source_name}: empty line record #{line_index}")
position = 0
indent = payload[position]
position += 1
pieces: list[str] = []
if record.length_word & LINE_NUMBER_FLAG:
line_number = self._read_uint_from(
payload, position, WORD_WIDTH, "line number"
)
position += WORD_WIDTH
pieces.extend((str(line_number), " "))
pieces.append(" " * indent)
pieces.append(
self._decode_payload(
payload[position:],
symbols,
record_offset=record.offset + 2 + position,
line_index=line_index,
)
)
return "".join(pieces)
def _decode_payload(
self,
payload: bytes,
symbols: list[str],
*,
record_offset: int,
line_index: int,
) -> str:
"""Decode token bytes while respecting literal strings and comments."""
pieces: list[str] = []
position = 0
mode = PayloadMode.NORMAL
data_quoted = False
while position < len(payload):
byte_offset = record_offset + position
byte = payload[position]
position += 1
# String, DATA, and comment content is raw MacRoman, not tokenized.
# This preserves umlauts and punctuation in decoded listings.
if mode is PayloadMode.COMMENT:
pieces.append(bytes([byte]).decode("mac_roman"))
continue
if mode is PayloadMode.STRING:
pieces.append(bytes([byte]).decode("mac_roman"))
if byte == STRING_DELIMITER:
mode = PayloadMode.NORMAL
continue
if (
mode is PayloadMode.NORMAL
or (mode is PayloadMode.DATA and not data_quoted)
) and payload[position - 1 : position + 2] == APOSTROPHE_COMMENT_SEQUENCE:
# Apostrophe comments use colon plus the REM-apostrophe token
# sequence AF E8 in this dialect.
pieces.append("'")
self._trace_event(
line_index,
byte_offset,
"token 3A AF E8 -> apostrophe comment",
)
position += len(APOSTROPHE_COMMENT_SEQUENCE) - 1
mode = PayloadMode.COMMENT
continue
if mode is PayloadMode.DATA:
pieces.append(bytes([byte]).decode("mac_roman"))
if byte == STRING_DELIMITER:
data_quoted = not data_quoted
elif byte == STATEMENT_SEPARATOR and not data_quoted:
mode = PayloadMode.NORMAL
continue
if byte == STRING_DELIMITER:
pieces.append('"')
mode = PayloadMode.STRING
continue
if byte >= TOKEN_BYTE_MIN:
token, position = self._decode_token(
payload,
position - 1,
byte_offset=byte_offset,
line_index=line_index,
)
pieces.append(token)
if token == "REM":
mode = PayloadMode.COMMENT
elif token == "DATA":
mode = PayloadMode.DATA
data_quoted = False
elif (
token == "WHILE"
and position < len(payload)
and payload[position] == PLUS_OPERATOR_CODE
):
position += 1
continue
match byte:
case digit_code if (
PayloadCode.COMPACT_DIGIT_0
<= digit_code
<= PayloadCode.COMPACT_DIGIT_9
):
digit = chr(ord("0") + digit_code - PayloadCode.COMPACT_DIGIT_0)
pieces.append(digit)
self._trace_event(
line_index,
byte_offset,
f"compact digit 0x{byte:02X} -> {digit}",
)
case (
PayloadCode.SYMBOL_REFERENCE
| PayloadCode.ALTERNATE_SYMBOL_REFERENCE
):
symbol_index = self._read_uint_from(
payload, position, WORD_WIDTH, "symbol reference"
)
position += WORD_WIDTH
symbol = self._symbol(symbols, symbol_index, line_index)
pieces.append(symbol)
self._trace_event(
line_index,
byte_offset,
f"symbol reference {symbol_index} -> {symbol!r}",
)
case PayloadCode.LABEL_REFERENCE:
symbol_index = self._read_uint_from(
payload, position, self._goto_target_size, "label reference"
)
position += self._goto_target_size
symbol = self._symbol(symbols, symbol_index, line_index)
pieces.append(symbol)
self._trace_event(
line_index,
byte_offset,
f"label reference {symbol_index} -> {symbol!r}",
)
case PayloadCode.THEN_ELSE_LOCATION:
# Hidden location data attached to THEN/ELSE at line ends.
position = self._skip(
payload,
position,
self._goto_target_size,
"THEN/ELSE location",
)
case (
PayloadCode.INTEGER_CONSTANT
| PayloadCode.ALTERNATE_INTEGER_CONSTANT
):
number = self._read_uint_from(
payload, position, WORD_WIDTH, "integer"
)
position += WORD_WIDTH
pieces.append(str(number))
self._trace_event(
line_index, byte_offset, f"integer constant -> {number}"
)
case PayloadCode.LINE_TARGET:
number = self._read_uint_from(
payload, position, self._goto_target_size, "line target"
)
position += self._goto_target_size
pieces.append(str(number))
self._trace_event(
line_index, byte_offset, f"line target -> {number}"
)
case PayloadCode.SHORT_INTEGER:
number = self._read_uint_from(
payload, position, BYTE_WIDTH, "short integer"
)
position += BYTE_WIDTH
pieces.append(str(number))
self._trace_event(
line_index, byte_offset, f"short integer constant -> {number}"
)
case PayloadCode.LABEL_DEFINITION:
# Label-definition marker followed by a zero location field.
value = self._read_uint_from(
payload, position, self._goto_target_size, "label marker"
)
position += self._goto_target_size
if value != ZERO_LOCATION_VALUE:
raise DecodeError(
f"{self._source_name}: nonzero label marker on source "
f"line #{line_index}"
)
self._trace_event(
line_index, byte_offset, "label definition marker"
)
case PayloadCode.SINGLE_FLOAT:
raw_float = self._take_payload(
payload, position, SINGLE_FLOAT_SIZE, "single float"
)
position += SINGLE_FLOAT_SIZE
number = self._format_float(raw_float)
pieces.append(number)
self._trace_event(
line_index,
byte_offset,
f"single-precision constant {raw_float.hex(' ')} -> {number}",
)
case PayloadCode.LONG_INTEGER:
number = self._read_uint_from(
payload, position, LONG_WORD_WIDTH, "long integer"
)
position += LONG_WORD_WIDTH
pieces.append(str(number))
self._trace_event(
line_index, byte_offset, f"long integer constant -> {number}"
)
case PayloadCode.DOUBLE_FLOAT:
raw_float = self._take_payload(
payload, position, DOUBLE_FLOAT_SIZE, "double float"
)
position += DOUBLE_FLOAT_SIZE
number = self._format_float(raw_float)
pieces.append(number)
self._trace_event(
line_index,
byte_offset,
f"double-precision constant {raw_float.hex(' ')} -> {number}",
)
case _ if byte < CONTROL_BYTE_LIMIT:
# Preserve unusual control bytes visibly rather than silently
# dropping data. Ordinary files rarely need this fallback.
pieces.append(f"\\x{byte:02X}")
case _:
pieces.append(chr(byte))
return "".join(pieces)
def _trace_event(self, line_index: int, offset: int, detail: str) -> None:
"""Send one offset-aware decode detail to the optional trace callback."""
if self._trace_callback is not None:
self._trace_callback(
f"{self._source_name}: record #{line_index}, "
f"offset 0x{offset:X}: {detail}"
)
def _decode_token(
self,
payload: bytes,
position: int,
*,
byte_offset: int,
line_index: int,
) -> tuple[str, int]:
"""Look up a one- or two-byte keyword/operator token."""
first = payload[position]
direct = TOKEN_TABLE.get((first,))
if direct is not None:
self._trace_event(
line_index,
byte_offset,
f"token {first:02X} -> {direct or '<empty>'}",
)
return direct, position + 1
if first in _TOKEN_PREFIXES:
if position + 1 >= len(payload):
raise DecodeError(
f"{self._source_name}: incomplete token 0x{first:02X} "
f"at file offset 0x{byte_offset:X} (source line #{line_index})"
)
second = payload[position + 1]
spelling = TOKEN_TABLE.get((first, second))
if spelling is not None:
self._trace_event(
line_index,
byte_offset,
f"token {first:02X} {second:02X} -> {spelling or '<empty>'}",
)
return spelling, position + 2
raise DecodeError(
f"{self._source_name}: unknown token byte 0x{first:02X} "
f"at file offset 0x{byte_offset:X} (source line #{line_index})"
)
def _symbol(self, symbols: list[str], index: int, line_index: int) -> str:
"""Resolve a symbol-table index or raise a line-specific decode error."""
if index >= len(symbols):
raise DecodeError(
f"{self._source_name}: symbol index {index} out of range "
f"on source line #{line_index} (table has {len(symbols)} entries)"
)
return symbols[index]
@staticmethod
def _take_payload(payload: bytes, position: int, size: int, what: str) -> bytes:
"""Return a payload slice, rejecting fields that extend past the line."""
end = position + size
if end > len(payload):
raise DecodeError(f"truncated {what} in source-line record")
return payload[position:end]
@staticmethod
def _skip(payload: bytes, position: int, size: int, what: str) -> int:
"""Advance over a payload field after validating its available length."""
end = position + size
if end > len(payload):
raise DecodeError(f"truncated {what} in source-line record")
return end
def _format_float(self, raw_float: bytes) -> str:
"""Format a stored IEEE or Microsoft decimal floating-point value."""
if self._decimal_mode:
return self._format_decimal_float(raw_float)
fmt = ">f" if len(raw_float) == SINGLE_FLOAT_SIZE else ">d"
value = struct.unpack(fmt, raw_float)[0]
if math.isnan(value):
return "nan"
if math.isinf(value):
return "-inf" if value < 0 else "inf"
return repr(value).replace("e", "E")
@staticmethod
def _format_decimal_float(raw_float: bytes) -> str:
"""Render Microsoft's packed-decimal BASIC float representation."""
if not raw_float or raw_float[0] == NUL_BYTE:
return "0"
sign = "-" if raw_float[0] & PACKED_DECIMAL_SIGN_MASK else ""
exponent = (
raw_float[0] & PACKED_DECIMAL_EXPONENT_MASK
) - PACKED_DECIMAL_EXPONENT_BIAS