-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGbcPyTranspiler.py
More file actions
2297 lines (2094 loc) · 76.4 KB
/
Copy pathGbcPyTranspiler.py
File metadata and controls
2297 lines (2094 loc) · 76.4 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
import ast
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional, Sequence, Set, Tuple
class GbcTranspileError(Exception):
def __init__(self, message: str, line: Optional[int] = None):
super().__init__(message)
self.message = str(message)
self.line = int(line) if isinstance(line, int) else None
@dataclass(frozen = True)
class CompilerSemanticsSpec:
version: str = 'v1'
numeric_width_bits: int = 8
signed_wraparound: bool = True
truthy_zero_is_false: bool = True
strict_compiler_mode_default: bool = True
notes: Tuple[str, ...] = (
'Frontend accepts Python AST and lowers into a restricted IR.',
'Name-bound values map to deterministic WRAM-like slots.',
'Control flow lowers to direct branch labels in generated GBZ80.',
'Unsupported syntax raises compile errors in strict mode.',
)
COMPILER_SEMANTICS_SPEC = CompilerSemanticsSpec()
_JOY_TO_PYGAME_KEY = {
'J_LEFT': 'K_LEFT',
'J_RIGHT': 'K_RIGHT',
'J_UP': 'K_UP',
'J_DOWN': 'K_DOWN',
'J_A': 'K_A',
'J_B': 'K_B',
'J_START': 'K_START',
'J_SELECT': 'K_SELECT',
}
_PYGAME_TO_JOY_KEY = dict([(v, k) for k, v in _JOY_TO_PYGAME_KEY.items()])
@dataclass
class IrExpr:
pass
@dataclass
class IrConst(IrExpr):
value: object
@dataclass
class IrName(IrExpr):
name: str
@dataclass
class IrAttr(IrExpr):
base: IrExpr
attr: str
@dataclass
class IrSubscript(IrExpr):
base: IrExpr
index: IrExpr
@dataclass
class IrList(IrExpr):
items: List[IrExpr] = field(default_factory = list)
@dataclass
class IrCall(IrExpr):
func: IrExpr
args: List[IrExpr] = field(default_factory = list)
@dataclass
class IrUnary(IrExpr):
op: str
value: IrExpr
@dataclass
class IrCompare(IrExpr):
left: IrExpr
op: str
right: IrExpr
@dataclass
class IrBoolAnd(IrExpr):
parts: List[IrExpr] = field(default_factory = list)
@dataclass
class IrBoolOr(IrExpr):
parts: List[IrExpr] = field(default_factory = list)
@dataclass
class IrBinOp(IrExpr):
left: IrExpr
op: str
right: IrExpr
@dataclass
class IrStmt:
line: int = 0
@dataclass
class IrAssign(IrStmt):
target: IrExpr = None
value: IrExpr = None
@dataclass
class IrAugAssign(IrStmt):
target: IrExpr = None
op: str = '+'
value: IrExpr = None
@dataclass
class IrExprStmt(IrStmt):
value: IrExpr = None
@dataclass
class IrIf(IrStmt):
test: IrExpr = None
body: List[IrStmt] = field(default_factory = list)
orelse: List[IrStmt] = field(default_factory = list)
@dataclass
class IrBasicBlock:
name: str
stmts: List[IrStmt] = field(default_factory = list)
next_blocks: List[str] = field(default_factory = list)
@dataclass
class IrProgram:
script_name: str
entry_block: str
blocks: Dict[str, IrBasicBlock]
class Gbz80Emitter:
def __init__ (self, base_addr: int = 0x150):
self.base_addr = int(base_addr)
self.code = bytearray()
self.labels: Dict[str, int] = {}
self.jr_fixups: List[Tuple[int, str]] = []
self.abs_fixups: List[Tuple[int, str]] = []
self.asm_lines: List[str] = []
def mark (self, label: str):
self.labels[str(label)] = len(self.code)
self.asm_lines.append(str(label) + ':')
def emit (self, *bytes_: int):
for b in bytes_:
self.code.append(int(b) & 0xFF)
def ld_a_imm (self, v: int):
self.emit(0x3E, int(v) & 0xFF)
self.asm_lines.append(' ld a, $%02x' % (int(v) & 0xFF))
def ld_hl_imm (self, v: int):
iv = int(v) & 0xFFFF
self.emit(0x21, iv & 0xFF, (iv >> 8) & 0xFF)
self.asm_lines.append(' ld hl, $%04x' % iv)
def ld_hl_a (self):
self.emit(0x77)
self.asm_lines.append(' ld [hl], a')
def ld_a_hl (self):
self.emit(0x7E)
self.asm_lines.append(' ld a, [hl]')
def add_a_imm (self, v: int):
self.emit(0xC6, int(v) & 0xFF)
self.asm_lines.append(' add a, $%02x' % (int(v) & 0xFF))
def sub_a_imm (self, v: int):
self.emit(0xD6, int(v) & 0xFF)
self.asm_lines.append(' sub a, $%02x' % (int(v) & 0xFF))
def cp_a_imm (self, v: int):
self.emit(0xFE, int(v) & 0xFF)
self.asm_lines.append(' cp a, $%02x' % (int(v) & 0xFF))
def and_a (self):
self.emit(0xA7)
self.asm_lines.append(' and a')
def xor_a_imm (self, v: int):
self.emit(0xEE, int(v) & 0xFF)
self.asm_lines.append(' xor a, $%02x' % (int(v) & 0xFF))
def jr (self, label: str):
pos = len(self.code)
self.emit(0x18, 0x00)
self.jr_fixups.append((pos + 1, str(label)))
self.asm_lines.append(' jr ' + str(label))
def jr_z (self, label: str):
pos = len(self.code)
self.emit(0x28, 0x00)
self.jr_fixups.append((pos + 1, str(label)))
self.asm_lines.append(' jr z, ' + str(label))
def jr_nz (self, label: str):
pos = len(self.code)
self.emit(0x20, 0x00)
self.jr_fixups.append((pos + 1, str(label)))
self.asm_lines.append(' jr nz, ' + str(label))
def jp (self, label: str):
pos = len(self.code)
self.emit(0xC3, 0x00, 0x00)
self.abs_fixups.append((pos + 1, str(label)))
self.asm_lines.append(' jp ' + str(label))
def resolve (self):
for at, label in self.jr_fixups:
if label not in self.labels:
raise RuntimeError('Unknown JR label: ' + str(label))
target = self.labels[label]
disp = int(target - (at + 1))
if disp < -128 or disp > 127:
raise RuntimeError('JR out of range for label: ' + str(label))
self.code[at] = disp & 0xFF
for at, label in self.abs_fixups:
if label not in self.labels:
raise RuntimeError('Unknown JP label: ' + str(label))
abs_addr = self.base_addr + int(self.labels[label])
self.code[at] = abs_addr & 0xFF
self.code[at + 1] = (abs_addr >> 8) & 0xFF
def _unsupported_error (node, what: str, strict_compiler_mode: bool):
if strict_compiler_mode:
raise GbcTranspileError(
'Unsupported syntax in strict compiler mode: ' + str(what),
getattr(node, 'lineno', None),
)
def _to_ir_expr (node, strict_compiler_mode: bool = False) -> IrExpr:
if isinstance(node, ast.Constant):
return IrConst(node.value)
if isinstance(node, ast.Name):
return IrName(node.id)
if isinstance(node, ast.Attribute):
return IrAttr(_to_ir_expr(node.value, strict_compiler_mode = strict_compiler_mode), node.attr)
if isinstance(node, ast.Subscript):
idx = node.slice
if hasattr(ast, 'Index') and isinstance(idx, ast.Index):
idx = idx.value
return IrSubscript(
_to_ir_expr(node.value, strict_compiler_mode = strict_compiler_mode),
_to_ir_expr(idx, strict_compiler_mode = strict_compiler_mode),
)
if isinstance(node, ast.List):
return IrList([_to_ir_expr(x, strict_compiler_mode = strict_compiler_mode) for x in list(node.elts or [])])
if isinstance(node, ast.Tuple):
return IrList([_to_ir_expr(x, strict_compiler_mode = strict_compiler_mode) for x in list(node.elts or [])])
if isinstance(node, ast.Call):
return IrCall(
_to_ir_expr(node.func, strict_compiler_mode = strict_compiler_mode),
[_to_ir_expr(a, strict_compiler_mode = strict_compiler_mode) for a in list(node.args or [])],
)
if isinstance(node, ast.UnaryOp):
if isinstance(node.op, ast.USub):
return IrUnary('-', _to_ir_expr(node.operand, strict_compiler_mode = strict_compiler_mode))
if isinstance(node.op, ast.UAdd):
return IrUnary('+', _to_ir_expr(node.operand, strict_compiler_mode = strict_compiler_mode))
if isinstance(node.op, ast.Not):
return IrUnary('not', _to_ir_expr(node.operand, strict_compiler_mode = strict_compiler_mode))
if isinstance(node, ast.BinOp):
op_name = None
if isinstance(node.op, ast.Add):
op_name = '+'
elif isinstance(node.op, ast.Sub):
op_name = '-'
elif isinstance(node.op, ast.Mult):
op_name = '*'
elif isinstance(node.op, ast.FloorDiv):
op_name = '//'
elif isinstance(node.op, ast.Mod):
op_name = '%'
elif isinstance(node.op, ast.BitAnd):
op_name = '&'
elif isinstance(node.op, ast.BitOr):
op_name = '|'
if op_name is not None:
return IrBinOp(
_to_ir_expr(node.left, strict_compiler_mode = strict_compiler_mode),
op_name,
_to_ir_expr(node.right, strict_compiler_mode = strict_compiler_mode),
)
_unsupported_error(node, type(node.op).__name__, strict_compiler_mode)
return IrConst(None)
if isinstance(node, ast.Compare) and len(list(node.ops or [])) >= 1 and len(list(node.comparators or [])) >= 1:
left = node.left
parts = []
for op, right in zip(list(node.ops), list(node.comparators)):
op_name = '=='
if isinstance(op, ast.Lt):
op_name = '<'
elif isinstance(op, ast.LtE):
op_name = '<='
elif isinstance(op, ast.Gt):
op_name = '>'
elif isinstance(op, ast.GtE):
op_name = '>='
elif isinstance(op, ast.NotEq):
op_name = '!='
elif not isinstance(op, ast.Eq):
_unsupported_error(node, type(op).__name__, strict_compiler_mode)
return IrConst(None)
parts.append(
IrCompare(
_to_ir_expr(left, strict_compiler_mode = strict_compiler_mode),
op_name,
_to_ir_expr(right, strict_compiler_mode = strict_compiler_mode),
),
)
left = right
return parts[0] if len(parts) == 1 else IrBoolAnd(parts = parts)
if isinstance(node, ast.BoolOp) and isinstance(node.op, ast.And):
return IrBoolAnd([_to_ir_expr(v, strict_compiler_mode = strict_compiler_mode) for v in list(node.values or [])])
if isinstance(node, ast.BoolOp) and isinstance(node.op, ast.Or):
return IrBoolOr([_to_ir_expr(v, strict_compiler_mode = strict_compiler_mode) for v in list(node.values or [])])
_unsupported_error(node, type(node).__name__, strict_compiler_mode)
return IrConst(None)
def _to_ir_stmt (stmt, strict_compiler_mode: bool = False) -> Optional[IrStmt]:
line = int(getattr(stmt, 'lineno', 0) or 0)
if isinstance(stmt, ast.Assign) and len(list(stmt.targets or [])) == 1:
return IrAssign(
line = line,
target = _to_ir_expr(stmt.targets[0], strict_compiler_mode = strict_compiler_mode),
value = _to_ir_expr(stmt.value, strict_compiler_mode = strict_compiler_mode),
)
if isinstance(stmt, ast.AugAssign):
op = '+'
if isinstance(stmt.op, ast.Sub):
op = '-'
elif isinstance(stmt.op, ast.Add):
op = '+'
else:
_unsupported_error(stmt, type(stmt.op).__name__, strict_compiler_mode)
return IrAugAssign(
line = line,
target = _to_ir_expr(stmt.target, strict_compiler_mode = strict_compiler_mode),
op = op,
value = _to_ir_expr(stmt.value, strict_compiler_mode = strict_compiler_mode),
)
if isinstance(stmt, ast.Expr):
return IrExprStmt(line = line, value = _to_ir_expr(stmt.value, strict_compiler_mode = strict_compiler_mode))
if isinstance(stmt, ast.If):
return IrIf(
line = line,
test = _to_ir_expr(stmt.test, strict_compiler_mode = strict_compiler_mode),
body = [s for s in [_to_ir_stmt(x, strict_compiler_mode = strict_compiler_mode) for x in list(stmt.body or [])] if s is not None],
orelse = [s for s in [_to_ir_stmt(x, strict_compiler_mode = strict_compiler_mode) for x in list(stmt.orelse or [])] if s is not None],
)
_unsupported_error(stmt, type(stmt).__name__, strict_compiler_mode)
return None
def _check_unsupported_nodes (tree, strict_compiler_mode: bool = False):
for node in ast.walk(tree):
if isinstance(node, (ast.Import, ast.ImportFrom)):
raise GbcTranspileError('Imports are not supported in gbc transpiler', getattr(node, 'lineno', None))
if isinstance(node, (ast.AsyncFunctionDef, ast.Await, ast.Yield, ast.YieldFrom)):
raise GbcTranspileError('Async and generators are not supported in gbc transpiler', getattr(node, 'lineno', None))
if isinstance(node, ast.Try):
raise GbcTranspileError('try/except/finally is not supported in gbc transpiler', getattr(node, 'lineno', None))
if isinstance(node, ast.Call):
if isinstance(node.func, ast.Name) and node.func.id in ('eval', 'exec', 'compile', '__import__'):
raise GbcTranspileError('Dynamic eval/exec/import is not supported in gbc transpiler', getattr(node, 'lineno', None))
if strict_compiler_mode:
if isinstance(node, ast.Call) and len(list(getattr(node, 'keywords', []) or [])) > 0:
raise GbcTranspileError('Keyword call arguments are not supported in strict compiler mode', getattr(node, 'lineno', None))
if isinstance(node, (ast.Lambda, ast.DictComp, ast.ListComp, ast.SetComp, ast.GeneratorExp)):
raise GbcTranspileError('Comprehensions/lambdas are not supported in strict compiler mode', getattr(node, 'lineno', None))
if isinstance(node, ast.With):
raise GbcTranspileError('with is not supported in strict compiler mode', getattr(node, 'lineno', None))
if isinstance(node, ast.Delete):
raise GbcTranspileError('del is not supported in strict compiler mode', getattr(node, 'lineno', None))
def build_ir_program (code: str, script_name: str = '<script>', strict_compiler_mode: bool = False) -> IrProgram:
tree = ast.parse(code or '')
_check_unsupported_nodes(tree, strict_compiler_mode = strict_compiler_mode)
entry = IrBasicBlock(name = 'entry')
for stmt in list(tree.body or []):
ir_stmt = _to_ir_stmt(stmt, strict_compiler_mode = strict_compiler_mode)
if ir_stmt is not None:
entry.stmts.append(ir_stmt)
return IrProgram(script_name = str(script_name), entry_block = 'entry', blocks = {'entry': entry})
def _small_int (expr: IrExpr, consts: Dict[str, int]) -> Optional[int]:
if isinstance(expr, IrConst):
try:
return int(round(float(expr.value)))
except Exception:
return None
if isinstance(expr, IrName):
return consts.get(expr.name)
if isinstance(expr, IrAttr) and isinstance(expr.base, IrName):
if expr.base.name == 'this':
return consts.get('this.' + str(expr.attr))
return consts.get(str(expr.base.name) + '.' + str(expr.attr))
if isinstance(expr, IrUnary) and expr.op in ('+', '-'):
v = _small_int(expr.value, consts)
if not isinstance(v, int):
return None
return v if expr.op == '+' else -v
if isinstance(expr, IrBinOp):
lv = _small_int(expr.left, consts)
rv = _small_int(expr.right, consts)
if not (isinstance(lv, int) and isinstance(rv, int)):
return None
try:
if expr.op == '+':
return int(lv + rv)
if expr.op == '-':
return int(lv - rv)
if expr.op == '*':
return int(lv * rv)
if expr.op == '//':
return int(lv // rv) if rv != 0 else None
if expr.op == '%':
return int(lv % rv) if rv != 0 else None
if expr.op == '&':
return int(lv & rv)
if expr.op == '|':
return int(lv | rv)
except Exception:
return None
return None
def _subscript_const_index (expr: IrExpr) -> Optional[int]:
if not isinstance(expr, IrSubscript):
return None
return _small_int(expr.index, {})
def _subscript_key_name (expr: IrExpr) -> Optional[str]:
if not isinstance(expr, IrSubscript):
return None
idx = expr.index
if isinstance(idx, IrAttr) and isinstance(idx.base, IrName) and idx.base.name == 'pygame':
return idx.attr
if isinstance(idx, IrName):
return _JOY_TO_PYGAME_KEY.get(str(idx.name), None)
return None
def _mask_key_name (expr: IrExpr, keys_aliases: set) -> Optional[str]:
parts = [expr]
if isinstance(expr, IrCompare):
parts = [expr.left, expr.right]
for part in parts:
if not (isinstance(part, IrBinOp) and part.op == '&'):
continue
lhs = part.left
rhs = part.right
if isinstance(lhs, IrCall) and isinstance(lhs.func, IrName) and lhs.func.name == 'joypad' and isinstance(rhs, IrName):
return _JOY_TO_PYGAME_KEY.get(str(rhs.name), None)
if isinstance(rhs, IrCall) and isinstance(rhs.func, IrName) and rhs.func.name == 'joypad' and isinstance(lhs, IrName):
return _JOY_TO_PYGAME_KEY.get(str(lhs.name), None)
if isinstance(lhs, IrName) and lhs.name in keys_aliases and isinstance(rhs, IrName):
return _JOY_TO_PYGAME_KEY.get(str(rhs.name), None)
if isinstance(rhs, IrName) and rhs.name in keys_aliases and isinstance(lhs, IrName):
return _JOY_TO_PYGAME_KEY.get(str(lhs.name), None)
return None
def _is_name (expr: IrExpr, name: str) -> bool:
return isinstance(expr, IrName) and expr.name == str(name)
def _extract_rigidbody_ref (expr: IrExpr):
if isinstance(expr, IrName):
return ('name_ref', expr.name)
if isinstance(expr, IrAttr) and isinstance(expr.base, IrName) and expr.base.name == 'this' and expr.attr == 'rb':
return ('this_id', None)
if isinstance(expr, IrCall) and isinstance(expr.func, IrName) and expr.func.name == 'get_rigidbody' and len(expr.args) >= 1:
arg0 = expr.args[0]
if isinstance(arg0, IrConst) and isinstance(arg0.value, str):
return ('key', arg0.value)
if isinstance(arg0, IrAttr) and isinstance(arg0.base, IrName) and arg0.base.name == 'this' and arg0.attr == 'id':
return ('this_id', None)
if isinstance(expr, IrSubscript) and isinstance(expr.base, IrName) and expr.base.name in ('rigidBodies', 'rigidBodiesIds'):
if isinstance(expr.index, IrConst) and isinstance(expr.index.value, str):
return ('key', expr.index.value)
return (None, None)
def _vec2_literal (expr: IrExpr, consts: Dict[str, int]):
if isinstance(expr, IrConst) and isinstance(expr.value, (tuple, list)) and len(expr.value) >= 2:
try:
return [float(expr.value[0]), float(expr.value[1])]
except Exception:
return None
if isinstance(expr, IrList) and len(expr.items) >= 2:
x = _small_int(expr.items[0], consts)
y = _small_int(expr.items[1], consts)
if isinstance(x, int) and isinstance(y, int):
return [float(x), float(y)]
return None
@dataclass
class VelocityCompileResult:
velocity_script: Optional[Dict[str, int]]
init_velocity: Optional[Tuple[int, int]]
ir: IrProgram
asm_bytes: bytes
asm_listing: List[str]
symbol_map: Dict[str, int] = field(default_factory = dict)
diagnostics: List[str] = field(default_factory = list)
def _extract_jump_guard (test_expr: IrExpr, keys_aliases: set, vel_alias_name: Optional[str], consts: Dict[str, int]):
parts = []
if isinstance(test_expr, IrBoolAnd):
parts = list(test_expr.parts)
else:
parts = [test_expr]
key_name = None
jump_vy_max = None
mask_key = _mask_key_name(test_expr, keys_aliases)
if isinstance(mask_key, str):
key_name = mask_key
for part in parts:
part_key = _subscript_key_name(part)
if part_key is not None:
if isinstance(part, IrSubscript) and isinstance(part.base, IrName) and part.base.name in keys_aliases:
key_name = part_key
continue
return (None, None)
if isinstance(part, IrCompare):
lhs = part.left
rhs = part.right
lhs_idx = _subscript_const_index(lhs)
rhs_idx = _subscript_const_index(rhs)
lhs_is_vel_y = isinstance(lhs, IrSubscript) and isinstance(lhs.base, IrName) and lhs.base.name == vel_alias_name and lhs_idx == 1
rhs_is_vel_y = isinstance(rhs, IrSubscript) and isinstance(rhs.base, IrName) and rhs.base.name == vel_alias_name and rhs_idx == 1
if lhs_is_vel_y and part.op in ('<', '<='):
c = _small_int(rhs, consts)
if isinstance(c, int):
upper = c - 1 if part.op == '<' else c
jump_vy_max = upper if jump_vy_max is None else min(jump_vy_max, upper)
continue
if rhs_is_vel_y and part.op in ('>', '>='):
c = _small_int(lhs, consts)
if isinstance(c, int):
upper = c - 1 if part.op == '>' else c
jump_vy_max = upper if jump_vy_max is None else min(jump_vy_max, upper)
continue
return (None, None)
return (key_name, jump_vy_max)
def _collect_jump_assignments (
stmt: IrIf,
vel_alias_name: Optional[str],
consts: Dict[str, int],
key_name: Optional[str],
jump_y: Optional[int],
jump_vy_max: Optional[int],
jump_release_cut: bool,
jump_edge_trigger: bool,
saw_jump_assign: bool,
unresolved_jump_assign: bool,
):
def _is_vel_y_target (_target):
if not isinstance(_target, IrSubscript):
return False
if not (isinstance(_target.base, IrName) and _target.base.name == vel_alias_name):
return False
idx = _subscript_const_index(_target)
return bool(idx == 1)
def _orelse_has_release_cut (_stmts):
for _stmt in list(_stmts or []):
if isinstance(_stmt, IrAssign):
if _is_vel_y_target(_stmt.target):
j = _small_int(_stmt.value, consts)
if isinstance(j, int) and int(j) == 0:
return True
elif isinstance(_stmt, IrIf):
if _orelse_has_release_cut(_stmt.body) or _orelse_has_release_cut(_stmt.orelse):
return True
return False
def _is_edge_guard_not_expr (_expr):
# Keep edge-trigger detection generic: any unary `not <state>` guard
# inside the jump-pressed branch can indicate "press once until release".
if not (isinstance(_expr, IrUnary) and _expr.op == 'not'):
return False
v = _expr.value
return isinstance(v, (IrAttr, IrName))
for inner in list(stmt.body):
if isinstance(inner, IrAugAssign):
continue
if isinstance(inner, IrAssign):
if not _is_vel_y_target(inner.target):
continue
if key_name == 'K_A':
saw_jump_assign = True
j = _small_int(inner.value, consts)
if isinstance(j, int) and key_name == 'K_A':
jump_y = j
elif key_name == 'K_A':
unresolved_jump_assign = True
elif isinstance(inner, IrIf):
# Support edge-trigger style:
# if jumpInput:
# if not this.prevJumpInput: vel[1] = 60
if _is_edge_guard_not_expr(inner.test):
jump_edge_trigger = True
for nested in list(inner.body):
if not isinstance(nested, IrAssign):
continue
if not isinstance(nested.target, IrSubscript):
continue
if not (isinstance(nested.target.base, IrName) and nested.target.base.name == vel_alias_name):
continue
idx = _subscript_const_index(nested.target)
if idx != 1:
continue
if key_name == 'K_A':
saw_jump_assign = True
j = _small_int(nested.value, consts)
if isinstance(j, int) and key_name == 'K_A':
jump_y = j
elif key_name == 'K_A':
unresolved_jump_assign = True
if key_name == 'K_A' and _orelse_has_release_cut(stmt.orelse):
jump_release_cut = True
return (
jump_y,
jump_vy_max,
jump_release_cut,
jump_edge_trigger,
saw_jump_assign,
unresolved_jump_assign,
)
def compile_velocity_script (
code: str,
target_keys: Sequence[str],
allow_this_id: bool = False,
script_name: str = '<script>',
strict_compiler_mode: bool = False,
symbol_constants: Optional[Dict[str, int]] = None,
) -> VelocityCompileResult:
target_keys_set = set([str(k) for k in list(target_keys or []) if isinstance(k, str) and k != ''])
ir = build_ir_program(code, script_name = script_name, strict_compiler_mode = bool(strict_compiler_mode))
aliases: Dict[str, Tuple[str, Optional[str]]] = {}
consts: Dict[str, int] = {}
if isinstance(symbol_constants, dict):
for k, v in symbol_constants.items():
if not isinstance(k, str) or k == '':
continue
try:
consts[k] = int(round(float(v)))
except Exception:
continue
keys_aliases = set()
key_bool_alias: Dict[str, str] = {}
vel_alias_name = None
vel_aliases: Dict[str, List[float]] = {}
base_vx = 0
base_vy = 0
base_vx_found = False
base_vy_found = False
left_delta = 0
right_delta = 0
up_delta = 0
down_delta = 0
jump_y = None
jump_vy_max = None
jump_release_cut = False
jump_edge_trigger = False
saw_left_assign = False
saw_right_assign = False
saw_up_assign = False
saw_down_assign = False
unresolved_left_assign = False
unresolved_right_assign = False
unresolved_up_assign = False
unresolved_down_assign = False
saw_jump_assign = False
unresolved_jump_assign = False
target_hit = False
init_velocity = None
for stmt in list(ir.blocks[ir.entry_block].stmts):
if isinstance(stmt, IrAssign):
v = _small_int(stmt.value, consts)
if isinstance(stmt.target, IrName):
name = stmt.target.name
if isinstance(v, int):
consts[name] = v
else:
consts.pop(name, None)
if isinstance(stmt.value, IrCall) and isinstance(stmt.value.func, IrAttr):
f = stmt.value.func
if isinstance(f.base, IrAttr) and isinstance(f.base.base, IrName) and f.base.base.name == 'pygame' and f.base.attr == 'key' and f.attr == 'get_pressed':
keys_aliases.add(name)
if isinstance(stmt.value, IrCall) and isinstance(stmt.value.func, IrName) and stmt.value.func.name == 'joypad':
keys_aliases.add(name)
if isinstance(stmt.value, IrList) and len(stmt.value.items) >= 2:
vel_alias_name = name
vx_candidate = _small_int(stmt.value.items[0], consts)
vy_candidate = _small_int(stmt.value.items[1], consts)
if isinstance(vx_candidate, int):
base_vx = int(vx_candidate)
base_vx_found = True
if isinstance(vy_candidate, int):
base_vy = int(vy_candidate)
base_vy_found = True
rb_kind, rb_value = _extract_rigidbody_ref(stmt.value)
if rb_kind in ('name_ref', 'key', 'this_id'):
aliases[name] = (rb_kind, rb_value)
else:
aliases.pop(name, None)
vec = _vec2_literal(stmt.value, consts)
if vec is not None:
vel_aliases[name] = [float(vec[0]), float(vec[1])]
else:
vel_aliases.pop(name, None)
if isinstance(stmt.value, IrSubscript):
k = _subscript_key_name(stmt.value)
if k is not None and isinstance(stmt.value.base, IrName) and stmt.value.base.name in keys_aliases:
key_bool_alias[name] = k
else:
key_bool_alias.pop(name, None)
elif isinstance(stmt.value, IrBinOp):
k = _mask_key_name(stmt.value, keys_aliases)
if k is not None:
key_bool_alias[name] = k
else:
key_bool_alias.pop(name, None)
elif isinstance(stmt.target, IrAttr) and isinstance(stmt.target.base, IrName):
attr_key = str(stmt.target.base.name) + '.' + str(stmt.target.attr)
if isinstance(v, int):
consts[attr_key] = v
else:
consts.pop(attr_key, None)
elif isinstance(stmt, IrAugAssign):
if isinstance(stmt.target, IrSubscript) and isinstance(stmt.target.base, IrName) and stmt.target.base.name == vel_alias_name:
d = _small_int(stmt.value, consts)
idx = _subscript_const_index(stmt.target)
if isinstance(d, int) and isinstance(idx, int) and idx in (0, 1):
if stmt.op == '-':
d = -d
# key deltas are inferred in enclosing if blocks; direct top-level
# aug-assign on vel components is treated as baseline motion.
if idx == 0:
base_vx += d
base_vx_found = True
else:
base_vy += d
base_vy_found = True
elif isinstance(stmt, IrExprStmt) and isinstance(stmt.value, IrCall):
call = stmt.value
if (
isinstance(call.func, IrAttr)
and call.func.attr in ('set_linear_velocity', 'set_rigid_body_velocity')
and isinstance(call.func.base, IrName)
and call.func.base.name in ('sim', 'physics')
):
if len(call.args) >= 2:
rb_kind, rb_value = _extract_rigidbody_ref(call.args[0])
if rb_kind == 'name_ref' and rb_value in aliases:
rb_kind, rb_value = aliases[rb_value]
target_match = False
if rb_kind == 'this_id':
target_match = bool(allow_this_id)
elif rb_kind == 'key' and isinstance(rb_value, str) and rb_value in target_keys_set:
target_match = True
if target_match:
target_hit = True
if isinstance(call.args[1], IrName):
vel_alias_name = call.args[1].name
elif isinstance(call.args[1], IrList) and len(call.args[1].items) >= 2:
vx_candidate = _small_int(call.args[1].items[0], consts)
vy_candidate = _small_int(call.args[1].items[1], consts)
if isinstance(vx_candidate, int) and isinstance(vy_candidate, int):
base_vx = int(vx_candidate)
base_vy = int(vy_candidate)
base_vx_found = True
base_vy_found = True
init_velocity = (int(base_vx), int(-base_vy))
if isinstance(call.args[1], IrName) and call.args[1].name in vel_aliases:
init_velocity = (
int(round(float(vel_aliases[call.args[1].name][0]))),
int(round(-float(vel_aliases[call.args[1].name][1]))),
)
elif isinstance(stmt, IrIf):
key_name, guard_max = _extract_jump_guard(stmt.test, keys_aliases, vel_alias_name, consts)
if key_name is None and isinstance(stmt.test, IrName):
key_name = key_bool_alias.get(stmt.test.name)
if key_name is None:
key_name = _mask_key_name(stmt.test, keys_aliases)
if key_name is None:
continue
for inner in list(stmt.body):
if isinstance(inner, IrAugAssign):
if not (isinstance(inner.target, IrSubscript) and isinstance(inner.target.base, IrName) and inner.target.base.name == vel_alias_name):
continue
idx = _subscript_const_index(inner.target)
d = _small_int(inner.value, consts)
if not isinstance(idx, int):
continue
if isinstance(d, int) and inner.op == '-':
d = -d
if idx == 0:
if key_name == 'K_LEFT':
saw_left_assign = True
if isinstance(d, int):
left_delta += d
else:
unresolved_left_assign = True
elif key_name == 'K_RIGHT':
saw_right_assign = True
if isinstance(d, int):
right_delta += d
else:
unresolved_right_assign = True
elif idx == 1:
if key_name == 'K_UP':
saw_up_assign = True
if isinstance(d, int):
up_delta += d
else:
unresolved_up_assign = True
elif key_name == 'K_DOWN':
saw_down_assign = True
if isinstance(d, int):
down_delta += d
else:
unresolved_down_assign = True
(
jump_y,
jump_vy_max,
jump_release_cut,
jump_edge_trigger,
saw_jump_assign,
unresolved_jump_assign,
) = _collect_jump_assignments(
stmt,
vel_alias_name = vel_alias_name,
consts = consts,
key_name = key_name,
jump_y = jump_y,
jump_vy_max = jump_vy_max,
jump_release_cut = jump_release_cut,
jump_edge_trigger = jump_edge_trigger,
saw_jump_assign = saw_jump_assign,
unresolved_jump_assign = unresolved_jump_assign,
)
if key_name == 'K_A' and isinstance(guard_max, int):
jump_vy_max = guard_max if jump_vy_max is None else min(int(jump_vy_max), int(guard_max))
if not target_hit:
return VelocityCompileResult(
velocity_script = None,
init_velocity = None,
ir = ir,
asm_bytes = b'',
asm_listing = [],
symbol_map = {},
diagnostics = ['No matching set_linear_velocity/set_rigid_body_velocity target found for script.'],
)
dynamic_reasons = []
if saw_left_assign and unresolved_left_assign:
dynamic_reasons.append('left_delta')
if saw_right_assign and unresolved_right_assign:
dynamic_reasons.append('right_delta')
if saw_up_assign and unresolved_up_assign:
dynamic_reasons.append('up_delta')
if saw_down_assign and unresolved_down_assign:
dynamic_reasons.append('down_delta')
if saw_jump_assign and unresolved_jump_assign:
dynamic_reasons.append('jump_y')
if dynamic_reasons != []:
return VelocityCompileResult(
velocity_script = None,
init_velocity = None,
ir = ir,
asm_bytes = b'',
asm_listing = [],
symbol_map = {},
diagnostics = [
'Velocity script uses unresolved non-constant terms for: ' + ', '.join(dynamic_reasons) + '.',
],
)
if not base_vx_found:
base_vx = 0
if not base_vy_found:
base_vy = 0
velocity_script = {
'base_vx': int(base_vx),
'base_vy': int(base_vy),
'left_delta': int(left_delta),
'right_delta': int(right_delta),
'up_delta': int(up_delta),
'down_delta': int(down_delta),
'jump_y': None if jump_y is None else int(jump_y),
'jump_vy_max': None if jump_vy_max is None else int(jump_vy_max),
'jump_release_cut': bool(jump_release_cut),
'jump_edge_trigger': bool(jump_edge_trigger),
}
if init_velocity is None:
init_velocity = (int(base_vx), int(-base_vy))
asm_bytes, asm_listing, symbol_map = lower_ir_to_gbz80(ir)
return VelocityCompileResult(
velocity_script = velocity_script,
init_velocity = init_velocity,
ir = ir,
asm_bytes = asm_bytes,
asm_listing = asm_listing,
symbol_map = symbol_map,
diagnostics = [
'Compiler spec=' + str(COMPILER_SEMANTICS_SPEC.version),
'Strict mode=' + ('on' if bool(strict_compiler_mode) else 'off'),
],
)
def _slot_addr_for_name (name: str) -> int:
return 0xC400 + (sum([ord(ch) for ch in str(name)]) & 0x7F)
def _emit_load_expr_to_a (emitter: Gbz80Emitter, expr: IrExpr, consts: Dict[str, int]) -> bool:
if isinstance(expr, IrConst):
try:
emitter.ld_a_imm(int(round(float(expr.value))))
return True
except Exception:
return False
if isinstance(expr, IrName):
slot = _slot_addr_for_name(expr.name)
emitter.ld_hl_imm(slot)
emitter.ld_a_hl()
return True
if isinstance(expr, IrUnary) and expr.op in ('+', '-'):
if not _emit_load_expr_to_a(emitter, expr.value, consts):
return False
if expr.op == '-':
# A = -A (8-bit two's complement).
emitter.xor_a_imm(0xFF)
emitter.add_a_imm(1)
return True
if isinstance(expr, IrBinOp):
rv = _small_int(expr.right, consts)
if rv is None:
return False
if not _emit_load_expr_to_a(emitter, expr.left, consts):
return False
if expr.op == '+':
emitter.add_a_imm(rv)
return True
if expr.op == '-':
emitter.sub_a_imm(rv)
return True
return False
def _emit_truthy_test (emitter: Gbz80Emitter, expr: IrExpr, consts: Dict[str, int], false_label: str):
if isinstance(expr, IrBoolAnd):
for part in list(expr.parts):
_emit_truthy_test(emitter, part, consts, false_label)
return
if isinstance(expr, IrBoolOr):
end_label = false_label + '_or_ok'
for part in list(expr.parts):
_emit_load_expr_to_a(emitter, part, consts)
emitter.and_a()
emitter.jr_nz(end_label)
emitter.jr(false_label)
emitter.mark(end_label)