-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcore.py
More file actions
5467 lines (5144 loc) · 263 KB
/
Copy pathcore.py
File metadata and controls
5467 lines (5144 loc) · 263 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
#!/usr/bin/env python3
import ast
import json
from typing import Dict, Optional, Tuple, List, Set
class TranspileError(Exception):
def __init__(self, msg: str, node: Optional[ast.AST] = None):
if node is not None and hasattr(node, 'lineno'):
msg = f"line {node.lineno}: {msg}"
super().__init__(msg)
# ----------------------------------------
# Exception mapping
# ----------------------------------------
CPP_RESERVED: Set[str] = {
"auto", "break", "case", "char", "const", "continue", "default", "do",
"double", "else", "enum", "extern", "float", "for", "goto", "if", "int",
"long", "register", "return", "short", "signed", "sizeof", "static",
"struct", "switch", "typedef", "union", "unsigned", "void", "volatile",
"while", "class", "new", "delete", "virtual", "override", "final",
"template", "typename", "namespace", "using", "public", "private",
"protected", "friend", "operator", "bool", "true", "false", "catch",
"throw", "try", "typeid", "mutable", "explicit", "export", "inline",
"this", "and", "or", "not", "bitand", "bitor", "xor", "compl",
"nullptr", "alignas", "alignof", "constexpr", "decltype", "noexcept",
"static_assert", "thread_local", "wchar_t", "char16_t", "char32_t",
"dynamic_cast", "static_cast", "reinterpret_cast", "const_cast",
"concept", "requires", "co_await", "co_return", "co_yield",
}
EXCEPTION_MAP: Dict[str, str] = {
"BaseException": "std::exception",
"Exception": "std::runtime_error",
"RuntimeError": "std::runtime_error",
"ValueError": "std::invalid_argument",
"TypeError": "std::invalid_argument",
"IndexError": "std::out_of_range",
"KeyError": "std::out_of_range",
"IOError": "std::ios_base::failure",
"OSError": "std::ios_base::failure",
"FileNotFoundError": "std::ios_base::failure",
"PermissionError": "std::ios_base::failure",
"NotImplementedError": "std::logic_error",
"OverflowError": "std::overflow_error",
"ArithmeticError": "std::overflow_error",
"StopIteration": "_StopIteration_",
"AttributeError": "std::runtime_error",
"ImportError": "std::runtime_error",
"NameError": "std::runtime_error",
"AssertionError": "std::runtime_error",
"SystemExit": "std::runtime_error",
"UnicodeError": "std::runtime_error",
"UnicodeDecodeError": "std::runtime_error",
"UnicodeEncodeError": "std::runtime_error",
}
# Base classes that are no-ops in C++ (transparent wrappers / abstract markers)
TRANSPARENT_BASES: Set[str] = {
"object", "ABC", "ABCMeta", "Generic", "Protocol",
"Enum", "IntEnum", "StrEnum", "Flag", "IntFlag",
"NamedTuple",
}
# Base classes that mark a class as an Enum
ENUM_BASES: Set[str] = {"Enum", "IntEnum", "StrEnum", "Flag", "IntFlag"}
# Dunder methods → C++ names
DUNDER_CPP: Dict[str, str] = {
"__len__": "size",
"__str__": "to_string",
"__repr__": "to_string",
"__eq__": "operator==",
"__ne__": "operator!=",
"__lt__": "operator<",
"__le__": "operator<=",
"__gt__": "operator>",
"__ge__": "operator>=",
"__add__": "operator+",
"__radd__": "operator+",
"__sub__": "operator-",
"__mul__": "operator*",
"__rmul__": "operator*",
"__truediv__": "operator/",
"__floordiv__": "operator/",
"__mod__": "operator%",
"__neg__": "operator-",
"__pos__": "operator+",
"__iadd__": "operator+=",
"__isub__": "operator-=",
"__imul__": "operator*=",
"__itruediv__": "operator/=",
"__bool__": "operator bool",
"__int__": "operator int",
"__float__": "operator double",
"__getitem__": "operator[]",
"__setitem__": "set_item",
"__contains__": "contains",
"__hash__": "_hash_",
"__iter__": "_iter_",
"__next__": "_next_",
}
# Conversion operators: explicit operator TYPE() — no return type prefix
CONVERSION_DUNDERS: Set[str] = {"__bool__", "__int__", "__float__"}
INPLACE_DUNDERS: Set[str] = {
"__iadd__", "__isub__", "__imul__", "__itruediv__",
"__ifloordiv__", "__imod__", "__setitem__",
"__iter__", "__next__",
}
AST_OP_DUNDER: Dict[type, str] = {
ast.Add: "__add__", ast.Sub: "__sub__", ast.Mult: "__mul__",
ast.Div: "__truediv__", ast.FloorDiv: "__floordiv__", ast.Mod: "__mod__",
}
AST_OP_SYMBOL: Dict[type, str] = {
ast.Add: "+", ast.Sub: "-", ast.Mult: "*",
ast.Div: "/", ast.FloorDiv: "/", ast.Mod: "%",
}
# ----------------------------------------
# Type system
# ----------------------------------------
def split_type_args(s: str) -> List[str]:
parts: List[str] = []
depth = 0
current: List[str] = []
for ch in s:
if ch == "[":
depth += 1
current.append(ch)
elif ch == "]":
depth -= 1
current.append(ch)
elif ch == "," and depth == 0:
parts.append("".join(current).strip())
current = []
else:
current.append(ch)
if current:
parts.append("".join(current).strip())
return parts
def to_cpp_type(typ: str, class_names: Optional[Set[str]] = None) -> str:
if typ == "int": return "int"
if typ == "float": return "double"
if typ == "bool": return "bool"
if typ == "string": return "std::string"
if typ == "void": return "void"
if typ == "bytes": return "std::vector<uint8_t>"
if typ == "any": return "std::any"
if typ.startswith("list["):
return f"std::vector<{to_cpp_type(typ[5:-1], class_names)}>"
if typ.startswith("deque["):
return f"std::deque<{to_cpp_type(typ[6:-1], class_names)}>"
if typ.startswith("frozenset["):
return f"std::unordered_set<{to_cpp_type(typ[10:-1], class_names)}>"
if typ.startswith("optional["):
return f"std::optional<{to_cpp_type(typ[9:-1], class_names)}>"
if typ.startswith("tuple["):
parts = split_type_args(typ[6:-1])
return f"std::tuple<{', '.join(to_cpp_type(p, class_names) for p in parts)}>"
if typ.startswith("dict["):
parts = split_type_args(typ[5:-1])
if len(parts) != 2:
raise TranspileError("dict requires exactly 2 type arguments")
return f"std::unordered_map<{to_cpp_type(parts[0], class_names)}, {to_cpp_type(parts[1], class_names)}>"
if typ.startswith("ordereddict["):
parts = split_type_args(typ[12:-1])
if len(parts) != 2:
raise TranspileError("OrderedDict requires exactly 2 type arguments")
return f"std::map<{to_cpp_type(parts[0], class_names)}, {to_cpp_type(parts[1], class_names)}>"
if typ.startswith("set["):
return f"std::unordered_set<{to_cpp_type(typ[4:-1], class_names)}>"
if typ.startswith("variant["):
parts = split_type_args(typ[8:-1])
return f"std::variant<{', '.join(to_cpp_type(p, class_names) for p in parts)}>"
if typ.startswith("vararg["):
return f"std::vector<{to_cpp_type(typ[7:-1], class_names)}>"
if typ.startswith("func["):
# func[A,B->R] → std::function<R(A,B)>
inner = typ[5:-1]
arrow = inner.rfind("->")
if arrow == -1:
raise TranspileError(f"Invalid func type: '{typ}'")
args_str = inner[:arrow]
ret_cpp = to_cpp_type(inner[arrow + 2:], class_names)
if args_str:
args_cpp = ", ".join(to_cpp_type(a, class_names) for a in split_type_args(args_str))
else:
args_cpp = ""
return f"std::function<{ret_cpp}({args_cpp})>"
if class_names and typ in class_names:
return typ
# Generic class instantiation: ClassName[T1,T2,...] → ClassName<T1,T2,...>
bracket = typ.find("[")
if bracket != -1:
base = typ[:bracket]
if class_names and base in class_names:
args = split_type_args(typ[bracket + 1:-1])
return f"{base}<{', '.join(to_cpp_type(a, class_names) for a in args)}>"
raise TranspileError(f"Unknown type: '{typ}'")
def element_type(list_type: str) -> str:
if list_type.startswith("list["):
return list_type[5:-1]
raise TranspileError(f"'{list_type}' is not a list type")
def annotation_to_type(node: ast.expr, known_classes: Optional[Set[str]] = None) -> str:
if isinstance(node, ast.Name):
mapping = {
"None": "void", "int": "int", "float": "float", "bool": "bool",
"str": "string", "bytes": "bytes", "bytearray": "bytes", "Any": "any",
}
if node.id in mapping:
return mapping[node.id]
if known_classes and node.id in known_classes:
return node.id
raise TranspileError(f"Unknown type name: '{node.id}'")
if isinstance(node, ast.Constant) and node.value is None:
return "void"
if isinstance(node, ast.Subscript) and isinstance(node.value, ast.Name):
c = node.value.id
if c == "list":
return f"list[{annotation_to_type(node.slice, known_classes)}]"
if c == "Optional":
return f"optional[{annotation_to_type(node.slice, known_classes)}]"
if c == "tuple":
if isinstance(node.slice, ast.Tuple):
elts = node.slice.elts
# Homogeneous tuple: tuple[T, ...] → list[T]
if (len(elts) == 2 and isinstance(elts[1], ast.Constant)
and elts[1].value is ...):
return f"list[{annotation_to_type(elts[0], known_classes)}]"
parts = [annotation_to_type(e, known_classes) for e in elts]
return f"tuple[{','.join(parts)}]"
return f"tuple[{annotation_to_type(node.slice, known_classes)}]"
if c == "Callable":
if isinstance(node.slice, ast.Tuple) and len(node.slice.elts) == 2:
args_node, ret_node = node.slice.elts
if not isinstance(args_node, ast.List):
raise TranspileError("Callable: first argument must be a list of types")
ret_t = annotation_to_type(ret_node, known_classes)
arg_types = [annotation_to_type(e, known_classes) for e in args_node.elts]
return f"func[{','.join(arg_types)}->{ret_t}]"
raise TranspileError("Callable[[ArgTypes...], ReturnType] expected")
if c == "dict":
if isinstance(node.slice, ast.Tuple) and len(node.slice.elts) == 2:
k = annotation_to_type(node.slice.elts[0], known_classes)
v = annotation_to_type(node.slice.elts[1], known_classes)
return f"dict[{k},{v}]"
raise TranspileError("dict[K, V] requires exactly 2 type arguments")
if c == "set":
return f"set[{annotation_to_type(node.slice, known_classes)}]"
if c == "deque":
return f"deque[{annotation_to_type(node.slice, known_classes)}]"
if c == "frozenset":
return f"frozenset[{annotation_to_type(node.slice, known_classes)}]"
if c == "defaultdict":
if isinstance(node.slice, ast.Tuple) and len(node.slice.elts) == 2:
k = annotation_to_type(node.slice.elts[0], known_classes)
v = annotation_to_type(node.slice.elts[1], known_classes)
return f"dict[{k},{v}]"
raise TranspileError("defaultdict[K, V] requires exactly 2 type arguments")
if c == "OrderedDict":
if isinstance(node.slice, ast.Tuple) and len(node.slice.elts) == 2:
k = annotation_to_type(node.slice.elts[0], known_classes)
v = annotation_to_type(node.slice.elts[1], known_classes)
return f"ordereddict[{k},{v}]"
raise TranspileError("OrderedDict[K, V] requires exactly 2 type arguments")
if c == "Counter":
elem = annotation_to_type(node.slice, known_classes)
return f"dict[{elem},int]"
if c == "Union":
if isinstance(node.slice, ast.Tuple):
args = [annotation_to_type(e, known_classes) for e in node.slice.elts]
else:
args = [annotation_to_type(node.slice, known_classes)]
return f"variant[{','.join(args)}]"
if c in ("Generator", "Iterator", "Iterable"):
# Generator[T, None, None] or Iterator[T] → list[T]
if isinstance(node.slice, ast.Tuple):
yield_t = annotation_to_type(node.slice.elts[0], known_classes)
else:
yield_t = annotation_to_type(node.slice, known_classes)
return f"list[{yield_t}]"
# Generic class instantiation: ClassName[T1,T2,...] e.g. Stack[int]
if known_classes and c in known_classes:
if isinstance(node.slice, ast.Tuple):
args = [annotation_to_type(e, known_classes) for e in node.slice.elts]
else:
args = [annotation_to_type(node.slice, known_classes)]
return f"{c}[{','.join(args)}]"
# "ClassName" — string forward reference
if isinstance(node, ast.Constant) and isinstance(node.value, str):
name = node.value
mapping = {"None": "void", "int": "int", "float": "float", "bool": "bool", "str": "string",
"bytes": "bytes", "bytearray": "bytes"}
if name in mapping:
return mapping[name]
if known_classes and name in known_classes:
return name
raise TranspileError(f"Unknown type name (forward reference): '{name}'")
# X | Y (Python 3.10+ union syntax in annotations)
if isinstance(node, ast.BinOp) and isinstance(node.op, ast.BitOr):
left = annotation_to_type(node.left, known_classes)
right = annotation_to_type(node.right, known_classes)
if left == "void":
return f"optional[{right}]"
if right == "void":
return f"optional[{left}]"
parts: List[str] = []
for t in (left, right):
if t.startswith("variant["):
parts.extend(split_type_args(t[8:-1]))
else:
parts.append(t)
return f"variant[{','.join(parts)}]"
raise TranspileError(f"Unsupported type annotation: {ast.unparse(node)}")
def types_compatible(expected: str, got: str) -> bool:
"""int→float widening; concrete type assignable to variant/optional that contains it."""
if expected == got:
return True
if expected == "any" or got == "any":
return True
if expected == "float" and got == "int":
return True
if expected.startswith("variant["):
parts = split_type_args(expected[8:-1])
return got in parts
if expected.startswith("optional["):
inner = expected[9:-1]
return got == "nullopt" or got == inner or (got == "int" and inner == "float")
return False
# ----------------------------------------
# ClassInfo
# ----------------------------------------
class ClassInfo:
def __init__(self, name: str):
self.name = name
self.parent: Optional[str] = None
self.extra_parents: List[str] = [] # additional bases beyond the first
self.fields: Dict[str, str] = {} # field -> type (insertion-ordered)
self.methods: Dict[str, Tuple[str, list]] = {} # method -> (ret, params_no_self)
self.properties: Set[str] = set() # methods decorated with @property
self.property_setters: Dict[str, str] = {} # prop_name -> value_type (@x.setter)
self.abstract_methods: Set[str] = set() # methods decorated with @abstractmethod
self.type_params: List[str] = [] # TypeVar names from Generic[T, ...]
self.is_exception: bool = False
self.is_dataclass: bool = False
self.is_frozen: bool = False # @dataclass(frozen=True)
self.is_enum: bool = False
self.is_int_enum: bool = False # IntEnum / IntFlag → values are int-compatible
self.is_str_enum: bool = False # StrEnum / string-valued Enum → struct with constexpr
self.enum_members: List[Tuple[str, str]] = [] # (member_name, cpp_value)
self.class_vars: Dict[str, Tuple[str, Optional[str]]] = {} # name → (type, cpp_init)
self.method_param_names: Dict[str, List[str]] = {} # method → param names (no self)
# ----------------------------------------
# Scope
# ----------------------------------------
class Scope:
def __init__(self, parent: Optional["Scope"] = None):
self.parent = parent
self.vars: Dict[str, str] = {}
def define(self, name: str, typ: str):
self.vars[name] = typ
def set(self, name: str, typ: str):
if name in self.vars:
self.vars[name] = typ
elif self.parent:
self.parent.set(name, typ)
else:
self.vars[name] = typ
def lookup(self, name: str) -> Optional[str]:
if name in self.vars:
return self.vars[name]
if self.parent:
return self.parent.lookup(name)
return None
# ----------------------------------------
# Transpiler
# ----------------------------------------
Param = Tuple[str, Optional[ast.expr]]
class Transpiler:
def __init__(self, modules: List[ast.Module], module_names: List[str]):
self.modules = modules
self.module_names = module_names
self.module_name_set = set(module_names)
self.lines: List[str] = []
self.indent_level = 0
self.global_scope = Scope()
self.functions: Dict[str, Tuple[str, List[Param]]] = {}
self.classes: Dict[str, ClassInfo] = {}
self.current_class: Optional[ClassInfo] = None
self.main_guard_body: Optional[List[ast.stmt]] = None
self.function_aliases: Dict[str, str] = {}
self.function_cpp_names: Dict[str, str] = {} # python name → C++ callable
self.extra_includes: List[str] = [] # injected by stubs
self.preamble_lines: List[str] = [] # injected by stubs
self._generator_yield_type: Optional[str] = None
self._narrow_counter: int = 0
self.type_aliases: Dict[str, str] = {}
self.type_vars: Set[str] = set()
self.function_param_names: Dict[str, List[str]] = {} # func → ordered param names
self._needs_stop_iteration: bool = False
self._skipped_functions: Dict[str, str] = {} # name → reason
self._skipped_classes: Dict[str, str] = {} # name → reason
self._has_kwargs: Dict[str, bool] = {} # name → has **kwargs param
# ---- emit ----
def emit(self, line: str = ""):
self.lines.append(" " * self.indent_level + line)
def _safe_name(self, name: str) -> str:
"""Append '_' to Python identifiers that collide with C++ reserved words."""
return name + "_" if name in CPP_RESERVED else name
def _is_map_type(self, typ: str) -> bool:
"""True for dict[K,V] and ordereddict[K,V] (both map-like)."""
return typ.startswith("dict[") or typ.startswith("ordereddict[")
def _map_cpp_type(self, typ: str) -> str:
"""Return C++ type for a map type, defaulting to unordered_map."""
if typ.startswith("ordereddict["):
parts = split_type_args(typ[12:-1])
return f"std::map<{to_cpp_type(parts[0], set(self.classes.keys()))}, {to_cpp_type(parts[1], set(self.classes.keys()))}>"
return self.cpp_type(typ)
def _error(self, msg: str, node: Optional[ast.AST] = None) -> str:
"""Format error message with file:line if node is provided."""
if node is not None and hasattr(node, 'lineno'):
src = getattr(node, 'end_lineno', None)
if src:
return f"{node.lineno}: {msg}"
return msg
def indent(self):
self.indent_level += 1
def dedent(self):
self.indent_level = max(0, self.indent_level - 1)
# ---- type helpers ----
def cpp_type(self, typ: str) -> str:
return to_cpp_type(typ, set(self.classes.keys()) | self.type_vars)
def ann_to_type(self, node: ast.expr) -> str:
if isinstance(node, ast.Name) and node.id in self.type_aliases:
return self.type_aliases[node.id]
known = set(self.classes.keys()) | self.type_vars
return annotation_to_type(node, known)
def exc_cpp_type(self, name: str) -> str:
if name in EXCEPTION_MAP:
return EXCEPTION_MAP[name]
if name in self.classes and self.classes[name].is_exception:
return name
raise TranspileError(f"Unknown exception type: '{name}'")
def lookup_field(self, class_name: str, field: str) -> Optional[str]:
if class_name not in self.classes:
return None
info = self.classes[class_name]
if field in info.fields:
return info.fields[field]
if info.parent:
return self.lookup_field(info.parent, field)
return None
def lookup_method(self, class_name: str, method: str) -> Optional[Tuple[str, list]]:
if class_name not in self.classes:
return None
info = self.classes[class_name]
if method in info.methods:
return info.methods[method]
if info.parent:
result = self.lookup_method(info.parent, method)
if result is not None:
return result
for extra in info.extra_parents:
result = self.lookup_method(extra, method)
if result is not None:
return result
return None
def method_is_virtual(self, class_name: str, method: str) -> bool:
for other in self.classes.values():
if other.parent == class_name and method in other.methods:
return True
return False
def _method_is_const(self, f: ast.FunctionDef, class_name: str = "") -> bool:
"""True if a method body does not mutate self (can be marked const)."""
info = self.classes.get(class_name)
for node in ast.walk(f):
if isinstance(node, ast.Assign):
for target in node.targets:
if self._is_self_attr(target):
return False
if isinstance(node, ast.AugAssign) and self._is_self_attr(node.target):
return False
# self.X.method() or self.method() calls that likely mutate
if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute):
func_val = node.func.value
# self.X.method() — mutating through field
if self._is_self_attr(func_val):
return False
# self.method() — calling own non-const method
if isinstance(func_val, ast.Name) and func_val.id == "self":
return False
return True
def _is_self_attr(self, node: ast.expr) -> bool:
return (isinstance(node, ast.Attribute) and
isinstance(node.value, ast.Name) and node.value.id == "self")
def _class_is_polymorphic(self, class_name: str) -> bool:
"""True if any subclass overrides a method of this class."""
if class_name not in self.classes:
return False
for other in self.classes.values():
if other.parent == class_name and any(
m in other.methods for m in self.classes[class_name].methods
):
return True
return False
def method_overrides(self, class_name: str, method: str) -> bool:
info = self.classes.get(class_name)
if not info or not info.parent:
return False
return self.lookup_method(info.parent, method) is not None
def _lookup_property_type(self, class_name: str, attr: str) -> Optional[str]:
if class_name not in self.classes:
return None
info = self.classes[class_name]
if attr in info.properties:
m = info.methods.get(attr)
return m[0] if m else None
if info.parent:
return self._lookup_property_type(info.parent, attr)
return None
# ---- generic / TypeVar helpers ----
def _class_of(self, typ: str) -> Optional[str]:
"""Return the base class name for plain or generic types; None if not a class."""
bracket = typ.find("[")
base = typ[:bracket] if bracket != -1 else typ
return base if base in self.classes else None
def _is_subclass(self, child: str, parent: str) -> bool:
"""Return True if child class is parent or inherits from it (direct or transitive)."""
if child == parent:
return True
if child not in self.classes:
return False
info = self.classes[child]
if info.parent and self._is_subclass(info.parent, parent):
return True
for ep in info.extra_parents:
if self._is_subclass(ep, parent):
return True
return False
def _types_compat(self, expected: str, got: str) -> bool:
"""Like types_compatible() but also allows subclass assignment."""
if types_compatible(expected, got):
return True
# subclass of a user class is assignable to parent type
gc = self._class_of(got)
ec = self._class_of(expected)
if gc and ec and self._is_subclass(gc, ec):
return True
# IntEnum / IntFlag values are compatible with int
if expected == "int" and gc and self.classes[gc].is_int_enum:
return True
# int is compatible with IntEnum parameter/variable
if got == "int" and ec and self.classes[ec].is_int_enum:
return True
# StrEnum values are compatible with string
if expected == "string" and gc and self.classes[gc].is_str_enum:
return True
if got == "string" and ec and self.classes[ec].is_str_enum:
return True
return False
def _make_substitution(self, typ: str) -> Dict[str, str]:
"""For Stack[int], build {T: int} using the class's type_params list."""
bracket = typ.find("[")
if bracket == -1:
return {}
base = typ[:bracket]
if base not in self.classes:
return {}
type_params = self.classes[base].type_params
type_args = split_type_args(typ[bracket + 1:-1])
if len(type_params) != len(type_args):
return {}
return dict(zip(type_params, type_args))
def _substitute_typevars(self, typ: str, sub: Dict[str, str]) -> str:
"""Replace TypeVar names in a type string using a substitution dict."""
if not sub:
return typ
if typ in sub:
return sub[typ]
for prefix in ("list[", "optional[", "set[", "vararg["):
if typ.startswith(prefix):
return f"{prefix[:-1]}[{self._substitute_typevars(typ[len(prefix):-1], sub)}]"
if typ.startswith("tuple["):
parts = [self._substitute_typevars(p, sub) for p in split_type_args(typ[6:-1])]
return f"tuple[{','.join(parts)}]"
if typ.startswith("dict["):
parts = [self._substitute_typevars(p, sub) for p in split_type_args(typ[5:-1])]
return f"dict[{','.join(parts)}]"
if typ.startswith("func["):
inner = typ[5:-1]
arrow = inner.rfind("->")
if arrow != -1:
args_str = inner[:arrow]
ret_str = inner[arrow + 2:]
new_ret = self._substitute_typevars(ret_str, sub)
if args_str:
new_args = ",".join(self._substitute_typevars(a, sub)
for a in split_type_args(args_str))
return f"func[{new_args}->{new_ret}]"
return f"func[->{new_ret}]"
return typ
def register_type_vars(self):
"""Detect T = TypeVar('T') at module level and register T in self.type_vars."""
for mod in self.modules:
for node in mod.body:
if not (isinstance(node, ast.Assign) and len(node.targets) == 1
and isinstance(node.targets[0], ast.Name)):
continue
name = node.targets[0].id
val = node.value
if (isinstance(val, ast.Call) and isinstance(val.func, ast.Name)
and val.func.id == "TypeVar"
and val.args and isinstance(val.args[0], ast.Constant)
and isinstance(val.args[0].value, str)):
self.type_vars.add(name)
# ---- expression inference ----
def infer_expr(self, node: ast.expr, scope: Scope,
expected_type: Optional[str] = None) -> Tuple[str, str]:
if isinstance(node, ast.Constant):
v = node.value
if v is None: return ("std::nullopt", "nullopt")
if isinstance(v, bool): return ("true" if v else "false", "bool")
if isinstance(v, int): return (str(v), "int")
if isinstance(v, float): return (repr(v), "float")
if isinstance(v, str): return (json.dumps(v), "string")
if isinstance(v, bytes):
elems = ", ".join(str(b) for b in v)
return (f"std::vector<uint8_t>{{{elems}}}", "bytes")
raise TranspileError(f"Unsupported constant: {v!r}")
if isinstance(node, ast.Name):
name = node.id
if name in self.function_aliases:
name = self.function_aliases[name]
if name == "None":
return ("std::nullopt", "nullopt")
t = scope.lookup(name)
if t is None:
if name in self.functions:
# Function used as a Callable value → build func[...] type
ret, fparams = self.functions[name]
arg_types = [pt for pt, _ in fparams if not pt.startswith("vararg[")]
return (name, f"func[{','.join(arg_types)}->{ret}]")
raise TranspileError(f"Use of undefined variable '{node.id}'")
# `self` → C++ `*this`
if name == "self" and self.current_class is not None:
return ("*this", self.current_class.name)
return (self._safe_name(name), t)
if isinstance(node, ast.Attribute):
return self._infer_attr(node, scope)
if isinstance(node, ast.UnaryOp):
if isinstance(node.op, ast.USub):
c, t = self.infer_expr(node.operand, scope)
if t not in ("int", "float"):
if t in self.classes:
m = self.lookup_method(t, "__neg__")
if m:
return (f"(-{c})", m[0])
raise TranspileError("Unary - only for numbers or classes with __neg__")
return (f"(-{c})", t)
if isinstance(node.op, ast.UAdd):
c, t = self.infer_expr(node.operand, scope)
if t not in ("int", "float"):
if t in self.classes:
m = self.lookup_method(t, "__pos__")
if m:
return (f"(+{c})", m[0])
raise TranspileError("Unary + only for numbers or classes with __pos__")
return (f"(+{c})", t)
if isinstance(node.op, ast.Invert):
c, t = self.infer_expr(node.operand, scope)
if t != "int":
raise TranspileError("~ only for int")
return (f"(~{c})", "int")
if isinstance(node.op, ast.Not):
c, t = self.infer_expr(node.operand, scope)
if t == "bool":
return (f"(!{c})", "bool")
# User class with __bool__: not obj → !(bool)obj
base_cls = self._class_of(t)
if base_cls and "__bool__" in self.classes[base_cls].methods:
return (f"(!(bool){c})", "bool")
raise TranspileError("'not' only for bool")
if isinstance(node, ast.BinOp):
lc, lt = self.infer_expr(node.left, scope)
rc, rt = self.infer_expr(node.right, scope)
# Set binary operators: | & - ^
if lt.startswith("set[") or lt.startswith("frozenset["):
elem_t = lt[4:-1] if lt.startswith("set[") else lt[10:-1]
result_t = f"set[{elem_t}]"
cpp_t = self.cpp_type(result_t)
if isinstance(node.op, ast.BitOr):
return (f"[&](){{{cpp_t} _r_={lc};for(auto& _e_:{rc})_r_.insert(_e_);return _r_;}}()", result_t)
if isinstance(node.op, ast.BitAnd):
return (f"[&](){{{cpp_t} _r_;for(auto& _e_:{lc})if({rc}.count(_e_))_r_.insert(_e_);return _r_;}}()", result_t)
if isinstance(node.op, ast.Sub):
return (f"[&](){{{cpp_t} _r_={lc};for(auto& _e_:{rc})_r_.erase(_e_);return _r_;}}()", result_t)
if isinstance(node.op, ast.BitXor):
return (f"[&](){{{cpp_t} _r_;for(auto& _e_:{lc})if(!{rc}.count(_e_))_r_.insert(_e_);for(auto& _e_:{rc})if(!{lc}.count(_e_))_r_.insert(_e_);return _r_;}}()", result_t)
if lt == rt == "string" and isinstance(node.op, ast.Add):
return (f"({lc} + {rc})", "string")
# string * int or int * string
if isinstance(node.op, ast.Mult):
if lt == "string" and rt == "int":
return (f'[&](){{std::string _r_;for(int _i=0;_i<{rc};++_i)_r_+={lc};return _r_;}}()', "string")
if lt == "int" and rt == "string":
return (f'[&](){{std::string _r_;for(int _i=0;_i<{lc};++_i)_r_+={rc};return _r_;}}()', "string")
# list * int or int * list
if lt.startswith("list[") and rt == "int":
ct = self.cpp_type(lt)
return (f'[=](){{{ct} _s_={lc};{ct} _r_;for(int _i=0;_i<{rc};++_i)for(auto _e_:_s_)_r_.push_back(_e_);return _r_;}}()', lt)
if lt == "int" and rt.startswith("list["):
ct = self.cpp_type(rt)
return (f'[=](){{{ct} _s_={rc};{ct} _r_;for(int _i=0;_i<{lc};++_i)for(auto _e_:_s_)_r_.push_back(_e_);return _r_;}}()', rt)
# list + list (concatenation)
if isinstance(node.op, ast.Add) and lt.startswith("list[") and lt == rt:
return (f"[&](){{auto _r_={lc};auto _rhs_={rc};_r_.insert(_r_.end(),_rhs_.begin(),_rhs_.end());return _r_;}}()", lt)
# bytes + bytes (concatenation)
if lt == rt == "bytes" and isinstance(node.op, ast.Add):
return (f"[&](){{auto _r_={lc};_r_.insert(_r_.end(),{rc}.begin(),{rc}.end());return _r_;}}()", "bytes")
# bytes * int / int * bytes (repetition)
if isinstance(node.op, ast.Mult):
if lt == "bytes" and rt == "int":
return (f"[&](){{decltype({lc}) _r_;for(int _i=0;_i<{rc};++_i)_r_.insert(_r_.end(),{lc}.begin(),{lc}.end());return _r_;}}()", "bytes")
if lt == "int" and rt == "bytes":
return (f"[&](){{decltype({rc}) _r_;for(int _i=0;_i<{lc};++_i)_r_.insert(_r_.end(),{rc}.begin(),{rc}.end());return _r_;}}()", "bytes")
if lt not in ("int", "float") or rt not in ("int", "float"):
# Check for user-defined operator on the left operand
dunder = AST_OP_DUNDER.get(type(node.op))
if dunder and lt in self.classes:
m = self.lookup_method(lt, dunder)
if m:
ret_t, params = m
if params and params[0][0] == rt:
sym = AST_OP_SYMBOL[type(node.op)]
return (f"({lc} {sym} {rc})", ret_t)
raise TranspileError(f"Binary op between '{lt}' and '{rt}' not supported")
res = "float" if "float" in (lt, rt) else "int"
op = node.op
if isinstance(op, ast.Add): return (f"({lc} + {rc})", res)
if isinstance(op, ast.Sub): return (f"({lc} - {rc})", res)
if isinstance(op, ast.Mult): return (f"({lc} * {rc})", res)
if isinstance(op, ast.Div): return (f"({lc} / {rc})", "float")
if isinstance(op, ast.Mod):
if res == "float": raise TranspileError("% not supported for float")
return (f"({lc} % {rc})", "int")
if isinstance(op, ast.FloorDiv):
if res == "float": raise TranspileError("// not supported for float")
return (f"({lc} / {rc})", "int")
if isinstance(op, ast.Pow):
if res == "int": return (f"((int)std::pow({lc}, {rc}))", "int")
return (f"std::pow({lc}, {rc})", "float")
if isinstance(op, ast.BitOr): return (f"({lc} | {rc})", "int")
if isinstance(op, ast.BitAnd): return (f"({lc} & {rc})", "int")
if isinstance(op, ast.BitXor): return (f"({lc} ^ {rc})", "int")
if isinstance(op, ast.LShift): return (f"({lc} << {rc})", "int")
if isinstance(op, ast.RShift): return (f"({lc} >> {rc})", "int")
raise TranspileError(f"Unsupported binary op: {type(op).__name__}")
if isinstance(node, ast.BoolOp):
op_str = "&&" if isinstance(node.op, ast.And) else "||"
parts = []
for v in node.values:
c, t = self.infer_expr(v, scope)
if t == "bool":
parts.append(c)
else:
base_cls = self._class_of(t)
if base_cls and "__bool__" in self.classes[base_cls].methods:
parts.append(f"(bool){c}")
else:
raise TranspileError("Boolean ops only on bool")
return (f"({f' {op_str} '.join(parts)})", "bool")
if isinstance(node, ast.Compare):
cmp_map = {ast.Eq:"==", ast.NotEq:"!=", ast.Lt:"<", ast.LtE:"<=", ast.Gt:">", ast.GtE:">="}
# Chained comparisons: a < b < c → (a<b && b<c)
if len(node.ops) > 1:
operands = [node.left] + node.comparators
parts = []
for i, op in enumerate(node.ops):
lc, lt = self.infer_expr(operands[i], scope)
rc, rt = self.infer_expr(operands[i + 1], scope)
op_str = cmp_map.get(type(op))
if not op_str:
raise TranspileError(f"Unsupported comparison in chain: {type(op).__name__}")
parts.append(f"({lc} {op_str} {rc})")
return ("(" + " && ".join(parts) + ")", "bool")
lc, lt = self.infer_expr(node.left, scope)
rc, rt = self.infer_expr(node.comparators[0], scope)
op = node.ops[0]
if isinstance(op, ast.Is) and rt == "nullopt":
return (f"(!{lc}.has_value())", "bool")
if isinstance(op, ast.IsNot) and rt == "nullopt":
return (f"({lc}.has_value())", "bool")
if isinstance(op, (ast.In, ast.NotIn)):
negate = isinstance(op, ast.NotIn)
if self._is_map_type(rt):
inner = rt[5:-1] if rt.startswith("dict[") else rt[12:-1]
k_t = split_type_args(inner)[0]
if lt != k_t:
raise TranspileError(f"'in' dict: key must be '{k_t}', got '{lt}'")
expr = f"({rc}.count({lc}) > 0)"
elif rt.startswith("list["):
elem_t = element_type(rt)
if lt != elem_t:
raise TranspileError(f"'in' list: element must be '{elem_t}', got '{lt}'")
expr = f"(std::find({rc}.begin(), {rc}.end(), {lc}) != {rc}.end())"
elif rt.startswith("deque["):
elem_t = rt[6:-1]
if lt != elem_t:
raise TranspileError(f"'in' deque: element must be '{elem_t}', got '{lt}'")
expr = f"(std::find({rc}.begin(), {rc}.end(), {lc}) != {rc}.end())"
elif rt.startswith("set["):
elem_t = rt[4:-1]
if lt != elem_t:
raise TranspileError(f"'in' set: element must be '{elem_t}', got '{lt}'")
expr = f"({rc}.count({lc}) > 0)"
elif rt.startswith("frozenset["):
elem_t = rt[10:-1]
if lt != elem_t:
raise TranspileError(f"'in' frozenset: element must be '{elem_t}', got '{lt}'")
expr = f"({rc}.count({lc}) > 0)"
elif rt == "string":
if lt != "string":
raise TranspileError(f"'in' string: element must be 'string', got '{lt}'")
expr = f"({rc}.find({lc}) != std::string::npos)"
else:
base_cls = self._class_of(rt)
if base_cls and "__contains__" in self.classes[base_cls].methods:
expr = f"({rc}.contains({lc}))"
else:
raise TranspileError(f"'in' not supported for type '{rt}'")
return (f"(!{expr})" if negate else expr, "bool")
op_str = cmp_map.get(type(op))
if not op_str:
raise TranspileError(f"Unsupported comparison: {type(op).__name__}")
return (f"({lc} {op_str} {rc})", "bool")
if isinstance(node, ast.List):
if not node.elts:
if expected_type and expected_type.startswith("list["):
return (f"{self.cpp_type(expected_type)}{{}}", expected_type)
raise TranspileError("Empty list literals need an explicit type annotation")
codes, elem_t = [], None
for elt in node.elts:
c, t = self.infer_expr(elt, scope)
if elem_t is None: elem_t = t
elif t != elem_t:
raise TranspileError(f"Mixed list element types: '{elem_t}' and '{t}'")
codes.append(c)
lt = f"list[{elem_t}]"
return (f"{self.cpp_type(lt)}{{{', '.join(codes)}}}", lt)
if isinstance(node, ast.Set):
if not node.elts:
raise TranspileError("Empty set literals need an explicit type annotation")
codes, elem_t = [], None
for elt in node.elts:
c, t = self.infer_expr(elt, scope)
if elem_t is None: elem_t = t
elif t != elem_t:
raise TranspileError(f"Mixed set element types: '{elem_t}' and '{t}'")
codes.append(c)
st = f"set[{elem_t}]"
return (f"{self.cpp_type(st)}{{{', '.join(codes)}}}", st)
if isinstance(node, ast.Tuple):
if not node.elts:
raise TranspileError("Empty tuples not supported")
codes, types = [], []
for elt in node.elts:
c, t = self.infer_expr(elt, scope)
codes.append(c); types.append(t)
tt = f"tuple[{','.join(types)}]"
return (f"std::make_tuple({', '.join(codes)})", tt)
if isinstance(node, ast.Dict):
if not node.keys:
raise TranspileError("Empty dict literals need an explicit type annotation")
k_codes, v_codes, k_t, v_t = [], [], None, None
for k, v in zip(node.keys, node.values):
if k is None:
raise TranspileError("Dict unpacking (**) not supported")
kc, kt = self.infer_expr(k, scope)
vc, vt = self.infer_expr(v, scope)
if k_t is None:
k_t = kt
elif kt != k_t:
raise TranspileError(f"Mixed dict key types: '{k_t}' and '{kt}'")
if v_t is None:
v_t = vt
elif vt != v_t:
raise TranspileError(f"Mixed dict value types: '{v_t}' and '{vt}'")
k_codes.append(kc)
v_codes.append(vc)
dt = f"dict[{k_t},{v_t}]"
pairs = ", ".join(f"{{{kc}, {vc}}}" for kc, vc in zip(k_codes, v_codes))
return (f"{self.cpp_type(dt)}{{{pairs}}}", dt)
if isinstance(node, ast.Subscript):
oc, ot = self.infer_expr(node.value, scope)
# Slicing (ast.Slice: lst[a:b], s[a:b], lst[::-1], etc.)
if isinstance(node.slice, ast.Slice):
sl = node.slice
def _slice_idx(expr_node, default: str, size_expr: str) -> str:
if expr_node is None: return default
c, _ = self.infer_expr(expr_node, scope)
return c
# Sentinels for omitted bounds: 1<<30 = "use step-direction default"
_SNONE = "1073741824" # lower omitted
_ENONE = "-1073741825" # upper omitted
if ot.startswith("list["):
cpp_t = self.cpp_type(ot)
lc = _SNONE if sl.lower is None else self.infer_expr(sl.lower, scope)[0]
uc = _ENONE if sl.upper is None else self.infer_expr(sl.upper, scope)[0]
if sl.step is None:
# No step: simple contiguous slice
return (
f"[&](){{{cpp_t} _r_;auto& _v={oc};int _n=(int)_v.size();"
f"int _a=({lc}>=1073741824)?0:({lc});"
f"int _b=({uc}<=-1073741825)?_n:({uc});"
f"if(_a<0)_a=std::max(0,_n+_a);else _a=std::min(_a,_n);"
f"if(_b<0)_b=std::max(0,_n+_b);else _b=std::min(_b,_n);"
f"if(_a<_b)_r_.assign(_v.begin()+_a,_v.begin()+_b);return _r_;}}()",
ot
)
sc, _ = self.infer_expr(sl.step, scope)
return (
f"[&](){{{cpp_t} _r_;auto& _v={oc};int _n=(int)_v.size();"
f"int _st=({sc});"
f"int _a=({lc}),_b=({uc});"
f"if(_a>=1073741824)_a=(_st>=0)?0:_n-1;"
f"else{{if(_a<0)_a=std::max(0,_n+_a);else _a=std::min(_a,(_st>=0)?_n:_n-1);}}"
f"if(_b<=-1073741825)_b=(_st>=0)?_n:-1;"
f"else{{if(_b<0)_b=std::max(-1,_n+_b);else _b=std::min(_b,_n);}}"
f"if(_st>0){{for(int _i=_a;_i<_b&&_i<_n;_i+=_st)_r_.push_back(_v[_i]);}}"
f"else if(_st<0){{for(int _i=_a;_i>_b&&_i>=0;_i+=_st)_r_.push_back(_v[_i]);}}"