-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcpl_compiler.py
More file actions
384 lines (314 loc) · 14.5 KB
/
Copy pathcpl_compiler.py
File metadata and controls
384 lines (314 loc) · 14.5 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
"""CPL (ChromaPlex Language) compiler.
Dette er en begrænset parser til demo-syntaks. Den accepterer kun de understøttede
konstruktioner eksplicit og ignorerer ikke ukendt kode lydløst.
"""
from __future__ import annotations
import re
from dataclasses import dataclass
from .utils import number_to_exponent_remainder
_MAX_SOURCE_LENGTH = 1_000_000
_MAX_STRING_LENGTH = 4_096
_IDENT = r"[A-Za-z_ÆØÅæøå][\wÆØÅæøå]*"
_ALLOWED_COLORS = {"rød", "grøn", "blå", "violet", "uv"}
@dataclass(frozen=True)
class _Symbol:
kind: str
value: int | str
def _parse_int(value: str) -> int:
try:
parsed = int(value, 0)
except ValueError as exc:
raise SyntaxError(f"Forventede heltal, fik: {value}") from exc
if parsed < 0:
raise SyntaxError("Negative heltal understøttes ikke i denne demo-compiler")
return parsed
def _string_to_number(value: str) -> int:
"""Konverter en tekst til et deterministisk heltal via UTF-8 bytes."""
if len(value) > _MAX_STRING_LENGTH:
raise ValueError("Streng er for lang")
return int.from_bytes(value.encode("utf-8"), "big") if value else 0
def _demo_pixel_at(x: int, y: int) -> dict[str, int]:
"""Deterministisk demo-pixelgenerator til full_potential_demo."""
return {
"rød": (x * 23 + y * 17) % 256,
"grøn": (x * 11 + y * 29 + 64) % 256,
"blå": (x * 7 + y * 13 + 128) % 256,
}
def _resolve_numeric(symbols: dict[str, _Symbol], token: str, lineno: int) -> int:
token = token.strip()
if token.isdigit():
return _parse_int(token)
pixel_match = re.fullmatch(rf"({_IDENT})\.(rød|grøn|blå)", token)
if pixel_match:
name, channel = pixel_match.groups()
symbol = symbols.get(name)
if symbol is None or not isinstance(symbol.value, dict):
raise SyntaxError(f"Ukendt pixelvariabel '{name}' på linje {lineno}")
try:
return int(symbol.value[channel])
except KeyError as exc:
raise SyntaxError(f"Ukendt pixelkanal '{channel}' på linje {lineno}") from exc
symbol = symbols.get(token)
if symbol is None:
raise SyntaxError(f"Ukendt variabel '{token}' på linje {lineno}")
if not isinstance(symbol.value, int):
raise SyntaxError(f"Variablen '{token}' er ikke numerisk på linje {lineno}")
return symbol.value
def _eval_tal_expr(symbols: dict[str, _Symbol], expr: str, lineno: int) -> int:
expr = expr.strip()
match = re.fullmatch(rf"potens_til_tal\((.+?)\s*,\s*(.+?)\)", expr)
if match:
exponent = _resolve_numeric(symbols, match.group(1), lineno)
rest = _resolve_numeric(symbols, match.group(2), lineno)
return (2 ** exponent) + rest
match = re.fullmatch(rf"strengTilTal\(({_IDENT})\)", expr)
if match:
name = match.group(1)
symbol = symbols.get(name)
if symbol is None or not isinstance(symbol.value, str):
raise SyntaxError(f"strengTilTal kræver en kendt streng på linje {lineno}")
return _string_to_number(symbol.value)
match = re.fullmatch(rf"({_IDENT}|\d+)\s*-\s*\(2\^({_IDENT}|\d+)\)", expr)
if match:
left = _resolve_numeric(symbols, match.group(1), lineno)
exponent = _resolve_numeric(symbols, match.group(2), lineno)
value = left - (2**exponent)
if value < 0:
raise SyntaxError(f"Udtryk giver negativ værdi på linje {lineno}")
return value
return _resolve_numeric(symbols, expr, lineno)
def _eval_potens_expr(symbols: dict[str, _Symbol], expr: str, lineno: int) -> int:
expr = expr.strip()
match = re.fullmatch(rf"findEksponent\(({_IDENT}|\d+)\)", expr)
if match:
value = _resolve_numeric(symbols, match.group(1), lineno)
exponent, _ = number_to_exponent_remainder(value)
return exponent
return _resolve_numeric(symbols, expr, lineno)
def _eval_bound_expr(symbols: dict[str, _Symbol], expr: str, lineno: int) -> int:
expr = expr.strip()
match = re.fullmatch(rf"({_IDENT}|\d+)\s*-\s*(\d+)", expr)
if match:
left = _resolve_numeric(symbols, match.group(1), lineno)
right = _parse_int(match.group(2))
value = left - right
if value < 0:
raise SyntaxError(f"For-grænse giver negativ værdi på linje {lineno}")
return value
return _resolve_numeric(symbols, expr, lineno)
def _expand_compile_time_for_loops(cpl_code: str) -> str:
"""Udvid simple compile-time for-loops til gentagne linjer.
Understøttet form:
for x = 0 to BREDDE-1 {
...
}
Dette er bevidst en tidlig, sikker løsning til demoer med konstante grænser.
"""
symbols: dict[str, _Symbol] = {}
source_lines = cpl_code.splitlines()
output: list[str] = []
stack: list[dict[str, Any]] = []
for lineno, raw_line in enumerate(source_lines, 1):
line = raw_line.split("//", 1)[0].strip()
const_match = re.fullmatch(rf"konstant\s+({_IDENT})\s*=\s*(.+?)\s*;?", line)
if const_match and not stack:
name, expr = const_match.groups()
symbols[name] = _Symbol("konstant", _eval_tal_expr(symbols, expr, lineno))
output.append(raw_line)
continue
for_match = re.fullmatch(rf"for\s+({_IDENT})\s*=\s*(\d+)\s+to\s+(.+?)\s*\{{", line)
if for_match:
name, start_text, end_expr = for_match.groups()
stack.append({
"name": name,
"start": _parse_int(start_text),
"end": _eval_bound_expr(symbols, end_expr, lineno),
"body": [],
"line": lineno,
})
continue
if line == "}" and stack:
frame = stack.pop()
expanded: list[str] = []
for value in range(frame["start"], frame["end"] + 1):
for body_line in frame["body"]:
expanded.append(re.sub(rf"\b{re.escape(frame['name'])}\b", str(value), body_line))
if stack:
stack[-1]["body"].extend(expanded)
else:
output.extend(expanded)
continue
if stack:
stack[-1]["body"].append(raw_line)
else:
output.append(raw_line)
if stack:
frame = stack[-1]
raise SyntaxError(f"Uafsluttet for-loop startet på linje {frame['line']}")
return "\n".join(output)
def compile_cpl(cpl_code: str) -> str:
"""Compile en begrænset CPL-dialekt til CPA assembler."""
if not isinstance(cpl_code, str):
raise TypeError("cpl_code skal være en tekststreng")
if len(cpl_code) > _MAX_SOURCE_LENGTH:
raise ValueError("CPL-kilde er for stor")
cpl_code = _expand_compile_time_for_loops(cpl_code)
cpa_lines = ["; === CPL → CPA kompilering ===", ""]
symbols: dict[str, _Symbol] = {}
current_coords: tuple[str, str, str] | None = None
for lineno, raw_line in enumerate(cpl_code.splitlines(), 1):
line = raw_line.split("//", 1)[0].strip()
if not line:
continue
if line == "}":
current_coords = None
continue
match = re.fullmatch(rf"streng\s+({_IDENT})\s*=\s*\"([^\"]{{0,{_MAX_STRING_LENGTH}}})\"\s*;?", line)
if match:
name, value = match.groups()
symbols[name] = _Symbol("streng", value)
safe_value = value.replace("\\", "\\\\").replace('"', '\\"')
cpa_lines.append(f"; streng {name} = \"{safe_value}\"")
continue
match = re.fullmatch(rf"konstant\s+({_IDENT})\s*=\s*(.+?)\s*;?", line)
if match:
name, expr = match.groups()
value = _eval_tal_expr(symbols, expr, lineno)
symbols[name] = _Symbol("konstant", value)
cpa_lines.append(f"; konstant {name} = {value}")
continue
match = re.fullmatch(rf"tal\s+({_IDENT})\s*=\s*(.+?)\s*;?", line)
if match:
name, expr = match.groups()
value = _eval_tal_expr(symbols, expr, lineno)
symbols[name] = _Symbol("tal", value)
cpa_lines.append(f"; tal {name} = {value}")
continue
match = re.fullmatch(rf"pixel\s+({_IDENT})\s*=\s*hent_pixel\((\d+)\s*,\s*(\d+)\)\s*;?", line)
if match:
name, x_text, y_text = match.groups()
pixel = _demo_pixel_at(_parse_int(x_text), _parse_int(y_text))
symbols[name] = _Symbol("pixel", pixel)
cpa_lines.append(f"; pixel {name} = hent_pixel({x_text}, {y_text}) -> {pixel}")
continue
match = re.fullmatch(
rf"potens\s+({_IDENT})\s*,\s*rest\s+({_IDENT})\s*=\s*komponent_til_potens\((.+?)\)\s*;?",
line,
)
if match:
exp_name, rest_name, expr = match.groups()
value = _resolve_numeric(symbols, expr, lineno)
exponent, rest = number_to_exponent_remainder(value)
symbols[exp_name] = _Symbol("potens", exponent)
symbols[rest_name] = _Symbol("rest", rest)
cpa_lines.append(
f"; komponent_til_potens {expr} -> {exp_name}={exponent}, {rest_name}={rest}"
)
continue
match = re.fullmatch(rf"potens\s+({_IDENT})\s*=\s*(.+?)\s*;?", line)
if match:
name, expr = match.groups()
value = _eval_potens_expr(symbols, expr, lineno)
symbols[name] = _Symbol("potens", value)
cpa_lines.append(f"; potens {name} = {value}")
continue
match = re.fullmatch(r"skriv_voxel\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)\s*\{?", line)
if match:
current_coords = match.groups()
cpa_lines.append(f"; skriv voxel ({','.join(current_coords)})")
continue
match = re.fullmatch(
rf"kanal\s+({_IDENT})\s*=\s*({_IDENT}|\d+)"
rf"(?:\s*,\s*rest\s*=\s*({_IDENT}|\d+))?\s*;?",
line,
)
if match:
if current_coords is None:
raise SyntaxError(f"kanal må kun bruges inde i skriv_voxel-blok på linje {lineno}")
color, exponent_token, rest_token = match.groups()
color = color.lower()
if color not in _ALLOWED_COLORS:
raise SyntaxError(f"Ukendt farvekanal '{color}' på linje {lineno}")
exponent = _resolve_numeric(symbols, exponent_token, lineno)
rest = _resolve_numeric(symbols, rest_token, lineno) if rest_token else 0
coords = ",".join(current_coords)
cpa_lines.append(f"LOAD.PAIR {color}, {exponent}, {rest}")
cpa_lines.append(f"STORE.C ({coords}), {color}, {color}")
continue
match = re.fullmatch(rf"hologram\s*=\s*opret_hologram\((.+?)\s*,\s*(.+?)\)\s*;?", line)
if match:
width = _resolve_numeric(symbols, match.group(1), lineno)
height = _resolve_numeric(symbols, match.group(2), lineno)
symbols["hologram"] = _Symbol("hologram", {"bredde": width, "højde": height, "pixels": {}})
cpa_lines.append(f"; hologram = opret_hologram({width}, {height})")
continue
match = re.fullmatch(
rf"læs_voxel\((.+?)\s*,\s*(.+?)\s*,\s*(.+?)\)\s*->\s*"
rf"kanal\s+rød:\s*({_IDENT})\s*,\s*({_IDENT})\s*;\s*"
rf"kanal\s+grøn:\s*({_IDENT})\s*,\s*({_IDENT})\s*;\s*"
rf"kanal\s+blå:\s*({_IDENT})\s*,\s*({_IDENT})\s*;?",
line,
)
if match:
x_expr, y_expr, z_expr, r_e, r_rest, g_e, g_rest, b_e, b_rest = match.groups()
x = _resolve_numeric(symbols, x_expr, lineno)
y = _resolve_numeric(symbols, y_expr, lineno)
z = _resolve_numeric(symbols, z_expr, lineno)
cpa_lines.append(f"LOAD.C rød, ({x},{y},{z}), rød")
cpa_lines.append(f"LOAD.C grøn, ({x},{y},{z}), grøn")
cpa_lines.append(f"LOAD.C blå, ({x},{y},{z}), blå")
symbols[r_e] = _Symbol("potens", 0)
symbols[r_rest] = _Symbol("rest", 0)
symbols[g_e] = _Symbol("potens", 0)
symbols[g_rest] = _Symbol("rest", 0)
symbols[b_e] = _Symbol("potens", 0)
symbols[b_rest] = _Symbol("rest", 0)
cpa_lines.append(f"; læs_voxel ({x},{y},{z}) -> {r_e},{r_rest},{g_e},{g_rest},{b_e},{b_rest}")
continue
match = re.fullmatch(rf"({_IDENT})\s*=\s*potens_til_tal\((.+?)\s*,\s*(.+?)\)\s*;?", line)
if match:
name, exp_expr, rest_expr = match.groups()
exponent = _resolve_numeric(symbols, exp_expr, lineno)
rest = _resolve_numeric(symbols, rest_expr, lineno)
value = (2 ** exponent) + rest
symbols[name] = _Symbol("tal", value)
cpa_lines.append(f"; {name} = potens_til_tal({exponent}, {rest}) -> {value}")
continue
match = re.fullmatch(rf"hologram\.sæt_pixel\((.+?)\s*,\s*(.+?)\s*,\s*(.+?)\s*,\s*(.+?)\s*,\s*(.+?)\)\s*;?", line)
if match:
x_expr, y_expr, r_expr, g_expr, b_expr = match.groups()
x = _resolve_numeric(symbols, x_expr, lineno)
y = _resolve_numeric(symbols, y_expr, lineno)
r = _resolve_numeric(symbols, r_expr, lineno)
g = _resolve_numeric(symbols, g_expr, lineno)
b = _resolve_numeric(symbols, b_expr, lineno)
h = symbols.get("hologram")
if h is not None and isinstance(h.value, dict):
h.value.setdefault("pixels", {})[(x, y)] = (r, g, b)
cpa_lines.append(f"; hologram.sæt_pixel({x}, {y}, {r}, {g}, {b})")
continue
match = re.fullmatch(r"vis_hologram\(hologram\)\s*;?", line)
if match:
cpa_lines.append("; vis_hologram(hologram)")
continue
if line.startswith(("for ",)):
raise SyntaxError(
f"Ikke-understøttet CPL på linje {lineno}: '{line}'. "
"Denne compiler understøtter kun streng/tal/potens/skriv_voxel/kanal-demo-syntaks."
)
raise SyntaxError(f"Ikke-understøttet CPL på linje {lineno}: {line}")
if current_coords is not None:
raise SyntaxError("Uafsluttet skriv_voxel-blok")
cpa_lines.append("")
cpa_lines.append("HALT")
return "\n".join(cpa_lines)
def main_compile() -> None:
import argparse
parser = argparse.ArgumentParser(description="Compile en begrænset CPL-fil til CPA")
parser.add_argument("file", help="Sti til .cpl fil")
args = parser.parse_args()
with open(args.file, encoding="utf-8") as f:
cpl = f.read()
print(compile_cpl(cpl))
if __name__ == "__main__":
main_compile()