aboutsummaryrefslogtreecommitdiff
path: root/gen_kws.py
blob: 8ca046d50e12159d34e1a18fcc466e9d93e9678e (plain)
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
#!/usr/bin/python3
# This software disclaims copyright. Do what you want with it. Be gay, do
# crime. Originally written by Alexis Lockwood in 2021. Ⓐ

"""Generates keyword files for LittleScript.

Usage: gen_kws.py source
       gen_kws.py header
       gen_kws.py show
"""

import time
import sys

OFFSET = 0x80
MAX_HASH = 0x1F
HM_SENTINEL = 0x80

class Kw:
    def __init__(self, name, index, **kwargs):
        self.h = sum(ord(i) for i in name) & 0x1F
        self.name = name
        self.index = index

        self.op = kwargs.get("op")
        self.scanning = kwargs.get("scanning", False)
        self.noexec = kwargs.get("noexec", False)

        flags = []
        if self.op is None:
            flags.append("KWDEF_FLAG_NOT_OP")
        else:
            flags.append(f"KWDEF_FLAG_OP({self.op})")
        if self.scanning:
            flags.append("KWDEF_FLAG_SCANNING")
        if self.noexec:
            flags.append("KWDEF_FLAG_NOEXEC")

        self.flags = "|".join(flags)

        if self.noexec:
            self.fun = "NULL"
        else:
            self.fun = f"ls_kw_fun_{name}"

# These should be contiguous and may span from 0x00 to 0x7F. While this list
# is currently in alphabetical order, it doesn't need to be, and indices should
# be fixed once assigned - add new keywords at the bottom.
KEYWORDS = [
    Kw("ABS",   0x80, op="LS_OP_ABS", noexec=True),
    Kw("AND",   0x81, op="LS_OP_AND", noexec=True),
    Kw("AS",    0x82, noexec=True),
    Kw("ASC",   0x83),
    Kw("AT",    0x84, noexec=True),
    Kw("ATN",   0x85, op="LS_OP_ATN", noexec=True),
    Kw("CALL",  0x86),
    Kw("CAT",   0x87),
    Kw("CHR",   0x88),
    Kw("CLOSE", 0x89),
    Kw("COS",   0x8A, op="LS_OP_COS", noexec=True),
    Kw("COUNT", 0x8B),
    Kw("DATA",  0x8C),
    Kw("DEC",   0x8D),
    Kw("DEF",   0x8E),
    Kw("ELSE",  0x8F),
    Kw("END",   0x90),
    Kw("EQV",   0x91, op="LS_OP_EQV", noexec=True),
    Kw("ERASE", 0x92),
    Kw("ERROR", 0x93),
    Kw("FN",    0x94),
    Kw("FOR",   0x95, scanning=True),
    Kw("GOSUB", 0x96),
    Kw("GOTO",  0x97),
    Kw("HEX",   0x98),
    Kw("IF",    0x99),
    Kw("IMP",   0x9A, op="LS_OP_IMP", noexec=True),
    Kw("INPUT", 0x9B),
    Kw("LEFT",  0x9C),
    Kw("LET",   0x9D),
    Kw("LOG",   0x9E, op="LS_OP_LOG", noexec=True),
    Kw("MID",   0x9F),
    Kw("NEXT",  0xA0, scanning=True),
    Kw("NOT",   0xA1, op="LS_OP_NOT", noexec=True),
    Kw("OCT",   0xA2),
    Kw("ON",    0xA3),
    Kw("OR",    0xA4, op="LS_OP_OR", noexec=True),
    Kw("OPEN",  0xA5),
    Kw("PACK",  0xA6),
    Kw("PRINT", 0xA7),
    Kw("RANDOMIZE", 0xA8),
    Kw("READ",  0xA9),
    Kw("REM",   0xAA),
    Kw("RESTORE", 0xAB),
    Kw("RETURN", 0xAC),
    Kw("RIGHT", 0xAD),
    Kw("RND",   0xAE, op="LS_OP_RND", noexec=True),
    Kw("SIN",   0xAF, op="LS_OP_SIN", noexec=True),
    Kw("SQR",   0xB0, op="LS_OP_SQR", noexec=True),
    Kw("STEP",  0xB1),
    Kw("SWAP",  0xB2),
    Kw("TAN",   0xB3, op="LS_OP_TAN", noexec=True),
    Kw("THEN",  0xB4, noexec=True),
    Kw("TO",    0xB5, noexec=True),
    Kw("UNPACK", 0xB6),
    Kw("UNTIL", 0xB7, noexec=True),
    Kw("VAL",   0xB8),
    Kw("WEND",  0xB9, scanning=True),
    Kw("WHILE", 0xBA, scanning=True),
    Kw("WRITE", 0xBB),
    Kw("XOR",   0xBC, op="LS_OP_XOR", noexec=True),
    Kw("FLOAT", 0xBD, op="LS_OP_FLOAT", noexec=True),
    Kw("INT",   0xBE, op="LS_OP_INT", noexec=True),
    Kw("EXP",   0xBF, op="LS_OP_EXP", noexec=True),
    Kw("SGN",   0xC0, op="LS_OP_SGN", noexec=True),
]

if len(sys.argv) == 2 and sys.argv[1] == "source":
    TARGET = "source"
elif len(sys.argv) == 2 and sys.argv[1] == "header":
    TARGET = "header"
elif len(sys.argv) == 2 and sys.argv[1] == "show":
    TARGET = "show"
else:
    print(__doc__)
    sys.exit()

ind = 0x7F
for i in KEYWORDS:
    if i.index != ind + 1:
        raise Exception(f"keyword list not contiguous! break at: {i.name}")
    ind = i.index

hashmap = []
indices = []

for h in range(MAX_HASH + 1):
    kws = [i.index - OFFSET for i in KEYWORDS if i.h == h]

    if kws:
        #kws[-1] |= HM_SENTINEL
        kws[-1] = f"0x80 | {kws[-1]}" # Easier to read
        indices.append(len(hashmap))
        hashmap.extend(kws)
    else:
        indices.append("LS_HASHMAP_NULL_VALUE")

if TARGET == "show":
    for i in KEYWORDS:
        print(f"{i.name:<12}: hash = {i.h:2}, same hash: ", end='')
        for j in KEYWORDS:
            if j.h == i.h:
                print(j.name, end=' ')
        print()
    sys.exit()

print("// This code was generated by gen_kws.py at",
    time.strftime("%a %d %b %Y %I:%M:%S %p %Z")) # like date(1)

if TARGET == "source":
    #print('#include "ls_kws.h"')
    print('#include "ls_internal.h"')
    print()

    print('const LS_PROGMEM uint8_t ls_kw_hashmap_indices[] = {')
    for n, i in enumerate(indices):
        print(f'    /* {n} */ {i},')
    print('};')
    print()
    print('const LS_PROGMEM uint8_t ls_kw_hashmap[] = {')
    for n, i in enumerate(hashmap):
        print(f'    /* {n} */ {i},')
    print('};')
    print()

    for i in KEYWORDS:
        print(f'static const LS_PROGMEM char _kw_name_{i.name}[] = '
              f'"{i.name}";')

    print()
    print('const LS_PROGMEM ls_kwdef_t ls_kwmap[] = {')
    for n, i in enumerate(KEYWORDS):
        print(f'    /* {n} */ {{_kw_name_{i.name}, '
              f'{i.fun}, {i.flags} }},')
    print('};')

    sys.exit()

if TARGET == "header":
    print('#ifndef LS_TYPES_H')
    print('#  error "ls_kws.h should not be included directly! Include ls_types.h instead."')
    print('#endif')
    print('#ifndef LS_KWS_H')
    print('#define LS_KWS_H')
    for i in KEYWORDS:
        if not i.noexec:
            print(f'LS_KW_FUN({i.name});')
    print('typedef enum {')
    top = max(i.index for i in KEYWORDS)
    for i in range(OFFSET, top + 1):
        match = [j for j in KEYWORDS if j.index == i]
        assert len(match) == 1
        assert match[0].index == i
        print(f'    LS_KW_{match[0].name} = 0x{i:02X},')
    print('    LS_MAX_KWS')
    print('} ls_kw_t;')

    print('#define LS_NOT_A_KW LS_MAX_KWS')
    print(f'#define LS_KW_OFFSET 0x{OFFSET:X}')
    print('#endif // !defined(LS_INTERNAL_H)')