zx81

Emulateur Sinclair ZX81 dans le navigateur : Z80, ROM Sinclair, tout en JavaScript
git clone https://git.schurger.org/zx81.git
Log | Files | Refs | README

bas2p.py (7944B)


      1 #!/usr/bin/env python3
      2 """bas2p : convertit un listage BASIC ZX81 (texte) en fichier .P (image mémoire chargeable).
      3 
      4 Usage : bas2p.py source.bas sortie.p [--no-autorun]
      5 
      6 Syntaxe du source : une instruction par ligne, « NUMERO instruction ». Les mots-clés
      7 s'écrivent en clair (PRINT AT, INKEY$, GOTO, <=, **…) et sont tokenisés ; les espaces
      8 hors chaînes sont ignorés. Dans une chaîne, « ~ » inverse la vidéo jusqu'au prochain
      9 « ~ », et « \\xNN » insère le code ZX81 NN (par ex. \\x08 pour un pavé graphique).
     10 Par défaut, le programme démarre tout seul au chargement (NXTLIN pointe la première
     11 ligne) ; --no-autorun laisse l'utilisateur taper RUN.
     12 """
     13 import struct
     14 import sys
     15 
     16 # Jeu de caractères ZX81 (codes 0x00-0x3F). Les codes 1-10 sont des pavés graphiques.
     17 CHARS = ' ' + '\0' * 10 + '"£$:?()><=+-*/;,.0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
     18 ASCII_TO_CODE = {c: i for i, c in enumerate(CHARS) if c != '\0'}
     19 
     20 # Tokens 0xC0-0xFF, dans l'ordre de la ROM.
     21 TOKENS = ['""', 'AT', 'TAB', '?', 'CODE', 'VAL', 'LEN', 'SIN', 'COS', 'TAN', 'ASN', 'ACS',
     22           'ATN', 'LN', 'EXP', 'INT', 'SQR', 'SGN', 'ABS', 'PEEK', 'USR', 'STR$', 'CHR$',
     23           'NOT', '**', 'OR', 'AND', '<=', '>=', '<>', 'THEN', 'TO', 'STEP', 'LPRINT',
     24           'LLIST', 'STOP', 'SLOW', 'FAST', 'NEW', 'SCROLL', 'CONT', 'DIM', 'REM', 'FOR',
     25           'GOTO', 'GOSUB', 'INPUT', 'LOAD', 'LIST', 'LET', 'PAUSE', 'NEXT', 'POKE', 'PRINT',
     26           'PLOT', 'RUN', 'SAVE', 'RAND', 'IF', 'CLS', 'UNPLOT', 'CLEAR', 'RETURN', 'COPY']
     27 TOKEN_CODE = {t: 0xC0 + i for i, t in enumerate(TOKENS) if t not in ('?', '""')}
     28 TOKEN_CODE['INKEY$'] = 0x41
     29 TOKEN_CODE['PI'] = 0x42
     30 TOKEN_CODE['RND'] = 0x40
     31 # Essayer les plus longs d'abord (GOSUB avant GOTO, <= avant <, ** avant *…)
     32 KEYWORDS = sorted(TOKEN_CODE, key=len, reverse=True)
     33 # Mots-clés alphabétiques : ne pas les reconnaître à l'intérieur d'un nom de variable.
     34 WORDY = {k for k in KEYWORDS if k[0].isalpha()}
     35 
     36 NEWLINE = 0x76
     37 NUMBER = 0x7E
     38 ORG = 0x407D          # début du programme (après les variables système)
     39 DFILE_LEN = 1 + 24 * 33  # fichier d'écran étendu : 0x76 puis 24 × (32 caractères + 0x76)
     40 
     41 
     42 def zx_float(x):
     43     """Flottant ZX81 sur 5 octets : exposant+128, mantisse 32 bits (bit 31 = signe)."""
     44     if x == 0:
     45         return bytes(5)
     46     sign = x < 0
     47     x = abs(x)
     48     e = 0
     49     while x >= 1.0:
     50         x /= 2
     51         e += 1
     52     while x < 0.5:
     53         x *= 2
     54         e -= 1
     55     m = round(x * (1 << 32))
     56     if m >= (1 << 32):
     57         m >>= 1
     58         e += 1
     59     if not -128 <= e < 128:
     60         raise ValueError('nombre hors limites')
     61     m &= 0x7FFFFFFF
     62     if sign:
     63         m |= 0x80000000
     64     return bytes([e + 128]) + struct.pack('>I', m)
     65 
     66 
     67 def encode_string(s):
     68     out = bytearray()
     69     inverse = 0
     70     i = 0
     71     while i < len(s):
     72         c = s[i]
     73         if c == '~':
     74             inverse ^= 0x80
     75         elif c == '\\' and s[i + 1:i + 2] == 'x':
     76             out.append(int(s[i + 2:i + 4], 16) | inverse)
     77             i += 3
     78         else:
     79             c = c.upper()
     80             if c not in ASCII_TO_CODE:
     81                 raise ValueError(f'caractère hors ZX81 : {c!r}')
     82             out.append(ASCII_TO_CODE[c] | inverse)
     83         i += 1
     84     return bytes(out)
     85 
     86 
     87 def tokenize(stmt):
     88     out = bytearray()
     89     i = 0
     90     n = len(stmt)
     91     prev_ident = False  # le caractère précédent appartient à un identificateur
     92     while i < n:
     93         c = stmt[i]
     94         if c == ' ':
     95             i += 1
     96             prev_ident = False
     97             continue
     98         if c == '"':
     99             j = stmt.index('"', i + 1)
    100             out.append(ASCII_TO_CODE['"'])
    101             out += encode_string(stmt[i + 1:j])
    102             out.append(ASCII_TO_CODE['"'])
    103             i = j + 1
    104             prev_ident = False
    105             continue
    106         if out and out[-1] == TOKEN_CODE['REM'] and len(out) == 1:
    107             # Tout ce qui suit REM est du texte brut.
    108             out += encode_string(stmt[i:].strip())
    109             break
    110         matched = None
    111         up = stmt[i:].upper()
    112         for k in KEYWORDS:
    113             if up.startswith(k) and not (k in WORDY and prev_ident):
    114                 matched = k
    115                 break
    116         if matched:
    117             out.append(TOKEN_CODE[matched])
    118             i += len(matched)
    119             prev_ident = False
    120             continue
    121         if c.isdigit() or (c == '.' and stmt[i + 1:i + 2].isdigit()):
    122             if prev_ident:
    123                 out.append(ASCII_TO_CODE[c])
    124                 i += 1
    125                 continue
    126             j = i
    127             while j < n and (stmt[j].isdigit() or stmt[j] == '.'):
    128                 j += 1
    129             lit = stmt[i:j]
    130             out += bytes(ASCII_TO_CODE[ch] for ch in lit)
    131             out.append(NUMBER)
    132             out += zx_float(float(lit))
    133             i = j
    134             prev_ident = False
    135             continue
    136         cu = c.upper()
    137         if cu not in ASCII_TO_CODE:
    138             raise ValueError(f'caractère inconnu : {c!r} dans {stmt!r}')
    139         out.append(ASCII_TO_CODE[cu])
    140         prev_ident = cu.isalnum() or cu == '$'
    141         i += 1
    142     return bytes(out)
    143 
    144 
    145 def build(lines, autorun=True):
    146     prog = bytearray()
    147     for num, stmt in lines:
    148         body = tokenize(stmt) + bytes([NEWLINE])
    149         prog += struct.pack('>H', num) + struct.pack('<H', len(body)) + body
    150     d_file = ORG + len(prog)
    151     vars_ = d_file + DFILE_LEN
    152     e_line = vars_ + 1
    153     sysvars = bytearray(0x407D - 0x4009)
    154 
    155     def w8(addr, v): sysvars[addr - 0x4009] = v
    156 
    157     def w16(addr, v): struct.pack_into('<H', sysvars, addr - 0x4009, v)
    158 
    159     w8(0x4009, 0)                   # VERSN
    160     w16(0x400A, lines[0][0])        # E_PPC
    161     w16(0x400C, d_file)             # D_FILE
    162     w16(0x400E, d_file + 1)         # DF_CC
    163     w16(0x4010, vars_)              # VARS
    164     w16(0x4012, 0)                  # DEST
    165     w16(0x4014, e_line)             # E_LINE
    166     w16(0x4016, e_line + 4)         # CH_ADD
    167     w16(0x4018, 0)                  # X_PTR
    168     w16(0x401A, e_line + 5)         # STKBOT
    169     w16(0x401C, e_line + 5)         # STKEND
    170     w8(0x401E, 0)                   # BERG
    171     w16(0x401F, 0x405D)             # MEM
    172     w8(0x4022, 2)                   # DF_SZ
    173     w16(0x4023, lines[0][0])        # S_TOP
    174     w16(0x4025, 0xFFFF)             # LAST_K
    175     w8(0x4027, 0xFF)                # DEBOUNCE
    176     w8(0x4028, 55)                  # MARGIN (50 Hz)
    177     w16(0x4029, ORG if autorun else d_file)  # NXTLIN
    178     w16(0x402B, 0)                  # OLDPPC
    179     w8(0x402D, 0)                   # FLAGX
    180     w16(0x402E, 0)                  # STRLEN
    181     w16(0x4030, 0x0C8D)             # T_ADDR
    182     w16(0x4032, 0)                  # SEED
    183     w16(0x4034, 0xFFFF)             # FRAMES
    184     w16(0x4036, 0)                  # COORDS
    185     w8(0x4038, 0xBC)                # PR_CC
    186     w16(0x4039, 0x1821)             # S_POSN
    187     w8(0x403B, 0x40)                # CDFLAG : mode SLOW
    188     sysvars[0x403C - 0x4009:0x403C - 0x4009 + 33] = bytes(32) + bytes([NEWLINE])  # PRBUFF
    189     dfile = bytes([NEWLINE]) + (bytes(32) + bytes([NEWLINE])) * 24
    190     return bytes(sysvars) + bytes(prog) + dfile + bytes([0x80])
    191 
    192 
    193 def parse(text):
    194     lines = []
    195     for raw in text.splitlines():
    196         s = raw.strip()
    197         if not s or s.startswith('#'):
    198             continue
    199         num, _, stmt = s.partition(' ')
    200         lines.append((int(num), stmt.strip()))
    201     if lines != sorted(lines, key=lambda x: x[0]):
    202         raise ValueError('numéros de ligne non croissants')
    203     return lines
    204 
    205 
    206 def main():
    207     args = [a for a in sys.argv[1:] if not a.startswith('--')]
    208     if len(args) != 2:
    209         print(__doc__)
    210         sys.exit(2)
    211     autorun = '--no-autorun' not in sys.argv
    212     lines = parse(open(args[0], encoding='utf-8').read())
    213     data = build(lines, autorun)
    214     open(args[1], 'wb').write(data)
    215     print(f'{args[1]} : {len(lines)} lignes, {len(data)} octets, programme {len(data) - (0x407D - 0x4009) - DFILE_LEN - 1} octets')
    216 
    217 
    218 if __name__ == '__main__':
    219     main()