This repository was archived by the owner on Jan 26, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpy2cpp.py
More file actions
1635 lines (1349 loc) Β· 67.6 KB
/
py2cpp.py
File metadata and controls
1635 lines (1349 loc) Β· 67.6 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
import sys
import subprocess
import platform
import time
from pathlib import Path
from typing import Any, List, Dict, Optional, Set, Tuple
from dataclasses import dataclass, field
from enum import Enum
import tokenize
from io import StringIO
try:
import typer
from typer import Typer
except ImportError:
print("β Typer required: pip install typer")
sys.exit(1)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# CONFIGURATION & CONSTANTS
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
VERSION = "0.1.1"
CPP_STANDARD = "c++20"
class OptLevel(str, Enum):
O0 = "-O0"
O1 = "-O1"
O2 = "-O2"
O3 = "-O3"
Os = "-Os"
@dataclass
class TranspileConfig:
input_file: Path
output_file: Optional[Path] = None
cpp_standard: str = "c++20"
optimize: str = "-O3"
run: bool = False
keep_cpp: bool = True
verbose: bool = False
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# C++ RUNTIME PREAMBLE (C++20 with Advanced Features)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
CPP_PREAMBLE = r"""
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// Generated by Py2Cpp Ultimate | C++20 Runtime Environment
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
#include <iostream>
#include <vector>
#include <string>
#include <memory>
#include <map>
#include <unordered_map>
#include <set>
#include <unordered_set>
#include <algorithm>
#include <functional>
#include <sstream>
#include <cmath>
#include <thread>
#include <future>
#include <chrono>
#include <format>
#include <concepts>
#include <ranges>
#include <any>
#include <stdexcept>
#include <optional>
#include <variant>
#include <type_traits>
#include <tuple>
#include <queue>
#include <stack>
#include <numeric>
#include <random>
namespace py {
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// Type Aliases
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
using str = std::string;
template<typename T> using ptr = std::shared_ptr<T>;
template<typename T> using list = std::vector<T>;
template<typename K, typename V> using dict = std::map<K, V>;
template<typename T> using set_t = std::set<T>;
template<typename T> using opt = std::optional<T>;
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// Dynamic Type (Python Any)
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
struct PyObject {
std::any value;
std::string type_name;
PyObject() : type_name("NoneType") {}
template<typename T>
PyObject(const T& v) : value(v) {
if constexpr (std::is_same_v<T, std::string>) type_name = "str";
else if constexpr (std::is_same_v<T, int>) type_name = "int";
else if constexpr (std::is_same_v<T, double>) type_name = "float";
else if constexpr (std::is_same_v<T, bool>) type_name = "bool";
else type_name = "object";
}
};
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// Print function (Python-like)
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
void print() { std::cout << std::endl; }
template <typename T, typename... Args>
void print(const T& first, const Args&... args) {
if constexpr (std::is_same_v<T, std::string>) {
std::cout << first;
} else if constexpr (std::is_same_v<T, const char*>) {
std::cout << first;
} else if constexpr (std::is_same_v<T, bool>) {
std::cout << (first ? "True" : "False");
} else {
std::cout << first;
}
if constexpr (sizeof...(args) > 0) {
std::cout << " ";
print(args...);
} else {
std::cout << std::endl;
}
}
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// String Conversion (Type Casting)
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
template<typename T>
std::string str_cast(const T& t) {
if constexpr (std::is_same_v<T, std::string>) return t;
else if constexpr (std::is_same_v<T, bool>) return t ? "True" : "False";
else if constexpr (std::is_same_v<T, int>) return std::to_string(t);
else if constexpr (std::is_same_v<T, long>) return std::to_string(t);
else if constexpr (std::is_same_v<T, double>) {
std::ostringstream oss;
oss << std::fixed << t;
return oss.str();
} else if constexpr (std::is_same_v<T, const char*>) return std::string(t);
return "unknown";
}
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// Range function (Python range)
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
inline std::vector<int> range(int start, int stop = -1, int step = 1) {
if (stop == -1) { stop = start; start = 0; }
std::vector<int> result;
if (step == 0) throw std::runtime_error("range() step cannot be 0");
if (step > 0) {
for (int i = start; i < stop; i += step) result.push_back(i);
} else {
for (int i = start; i > stop; i += step) result.push_back(i);
}
return result;
}
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// Length function
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
template<typename T>
inline int len(const std::vector<T>& v) {
return static_cast<int>(v.size());
}
inline int len(const std::string& s) {
return static_cast<int>(s.length());
}
template<typename K, typename V>
inline int len(const std::map<K, V>& m) {
return static_cast<int>(m.size());
}
template<typename T>
inline int len(const std::set<T>& s) {
return static_cast<int>(s.size());
}
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// Map, Filter, Zip (Higher-order functions)
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
template<typename Func, typename Container>
auto map_py(Func f, const Container& cont) {
std::vector<decltype(f(*cont.begin()))> result;
for (const auto& item : cont) {
result.push_back(f(item));
}
return result;
}
template<typename Func, typename Container>
auto filter_py(Func f, const Container& cont) {
Container result;
for (const auto& item : cont) {
if (f(item)) result.push_back(item);
}
return result;
}
// Zip multiple containers
template<typename T, typename U>
std::vector<std::pair<T, U>> zip(const std::vector<T>& a, const std::vector<U>& b) {
std::vector<std::pair<T, U>> result;
size_t min_size = std::min(a.size(), b.size());
for (size_t i = 0; i < min_size; ++i) {
result.push_back({a[i], b[i]});
}
return result;
}
// Enumerate
template<typename T>
std::vector<std::pair<int, T>> enumerate(const std::vector<T>& cont) {
std::vector<std::pair<int, T>> result;
for (size_t i = 0; i < cont.size(); ++i) {
result.push_back({static_cast<int>(i), cont[i]});
}
return result;
}
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// Any / All (Boolean aggregates)
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
template<typename Container>
bool any_of(const Container& cont) {
return std::any_of(cont.begin(), cont.end(), [](const auto& x) {
return static_cast<bool>(x);
});
}
template<typename Container>
bool all_of(const Container& cont) {
return std::all_of(cont.begin(), cont.end(), [](const auto& x) {
return static_cast<bool>(x);
});
}
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// Sum (reduce with addition)
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
template<typename Container>
auto sum_py(const Container& cont, typename Container::value_type init = 0) {
return std::accumulate(cont.begin(), cont.end(), init);
}
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// Input function
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
inline std::string input(const std::string& prompt = "") {
if (!prompt.empty()) std::cout << prompt << std::flush;
std::string line;
std::getline(std::cin, line);
return line;
}
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// Type checking
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
template<typename T, typename U>
bool isinstance(const U& obj) {
return std::is_same_v<T, U>;
}
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// Min / Max
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
template<typename Container>
auto min_py(const Container& cont) {
return *std::min_element(cont.begin(), cont.end());
}
template<typename Container>
auto max_py(const Container& cont) {
return *std::max_element(cont.begin(), cont.end());
}
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// Sorted
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
template<typename Container>
Container sorted_py(Container cont) {
std::sort(cont.begin(), cont.end());
return cont;
}
template<typename Container, typename Comp>
Container sorted_py(Container cont, Comp cmp) {
std::sort(cont.begin(), cont.end(), cmp);
return cont;
}
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// Reversed
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
template<typename Container>
Container reversed_py(Container cont) {
std::reverse(cont.begin(), cont.end());
return cont;
}
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// Int / Float / Bool / Str conversions
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
template<typename T>
int int_cast(const T& val) {
if constexpr (std::is_same_v<T, std::string>) {
return std::stoi(val);
} else if constexpr (std::is_same_v<T, double>) {
return static_cast<int>(val);
} else {
return static_cast<int>(val);
}
}
template<typename T>
double float_cast(const T& val) {
if constexpr (std::is_same_v<T, std::string>) {
return std::stod(val);
} else {
return static_cast<double>(val);
}
}
template<typename T>
bool bool_cast(const T& val) {
if constexpr (std::is_same_v<T, int>) return val != 0;
else if constexpr (std::is_same_v<T, double>) return val != 0.0;
else if constexpr (std::is_same_v<T, std::string>) return !val.empty();
else return static_cast<bool>(val);
}
}
using namespace py;
"""
def extract_comments(source: str) -> Dict[int, List[str]]:
"""Extract Python comments with their line numbers."""
comments: Dict[int, List[str]] = {}
try:
tokens = tokenize.generate_tokens(StringIO(source).readline)
for tok in tokens:
if tok.type == tokenize.COMMENT:
line = tok.start[0]
text = tok.string[1:].strip()
comments.setdefault(line, []).append(text)
except tokenize.TokenError:
pass
return comments
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# LOGGER
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
class Logger:
"""Comprehensive logging with timing and statistics."""
def __init__(self, verbose: bool = False):
self.verbose = verbose
self.start_time = time.time()
self.stats = {
"nodes": 0,
"errors": 0,
"warnings": 0,
"functions": 0,
"classes": 0,
"comprehensions": 0
}
def info(self, msg: str) -> None:
if self.verbose:
typer.secho(f"βΉοΈ {msg}", fg=typer.colors.BLUE)
def success(self, msg: str) -> None:
typer.secho(f"β
{msg}", fg=typer.colors.GREEN)
def warn(self, msg: str) -> None:
typer.secho(f"β οΈ {msg}", fg=typer.colors.YELLOW)
self.stats["warnings"] += 1
def error(self, msg: str) -> None:
typer.secho(f"β {msg}", fg=typer.colors.RED)
self.stats["errors"] += 1
def debug(self, msg: str) -> None:
if self.verbose:
typer.secho(f"π§ {msg}", fg=typer.colors.CYAN)
def report(self) -> Dict[str, Any]:
duration = time.time() - self.start_time
return {
"duration": f"{duration:.2f}s",
"nodes_processed": self.stats["nodes"],
"functions": self.stats["functions"],
"classes": self.stats["classes"],
"comprehensions": self.stats["comprehensions"],
"warnings": self.stats["warnings"],
"errors": self.stats["errors"],
"status": "SUCCESS" if self.stats["errors"] == 0 else "FAILED"
}
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# ADVANCED TYPE INFERENCE ENGINE
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
class TypeInferencer:
"""Advanced type inference with numeric promotion, containers, and unions."""
BUILTIN_TYPES = {
"int", "double", "bool", "std::string", "float",
"long", "unsigned int", "unsigned long", "char"
}
PYTHON_TYPE_MAP = {
"int": "int",
"float": "double",
"str": "std::string",
"bool": "bool",
"list": "std::vector<std::any>",
"dict": "std::map<std::string, std::any>",
"set": "std::set<std::any>",
"tuple": "std::tuple<std::any>",
"None": "void*",
"bytes": "std::string",
}
@staticmethod
def infer_from_value(node: ast.expr) -> str:
"""Infer C++ type from Python AST value node."""
if isinstance(node, ast.Constant):
if isinstance(node.value, bool):
return "bool"
if isinstance(node.value, int):
return "int"
if isinstance(node.value, float):
return "double"
if isinstance(node.value, str):
return "std::string"
if node.value is None:
return "void*"
return "std::any"
if isinstance(node, ast.List):
if not node.elts:
return "std::vector<std::any>"
inner = TypeInferencer.infer_from_value(node.elts[0])
if inner == "std::any":
return "std::vector<std::any>"
return f"std::vector<{inner}>"
if isinstance(node, ast.Set):
if not node.elts:
return "std::set<std::any>"
inner = TypeInferencer.infer_from_value(node.elts[0])
return f"std::set<{inner}>"
if isinstance(node, ast.Tuple):
if not node.elts:
return "std::tuple<>"
inferred = [TypeInferencer.infer_from_value(e) for e in node.elts]
return f"std::tuple<{', '.join(inferred)}>"
if isinstance(node, ast.Dict):
if not node.keys:
return "std::map<std::string, std::any>"
k_type = TypeInferencer.infer_from_value(node.keys[0]) if node.keys else "std::string" # pyright: ignore[reportArgumentType]
v_type = TypeInferencer.infer_from_value(node.values[0]) if node.values else "std::any"
return f"std::map<{k_type}, {v_type}>"
if isinstance(node, ast.BinOp):
return TypeInferencer._infer_binop(node)
if isinstance(node, ast.Call):
return TypeInferencer._infer_call(node)
if isinstance(node, ast.UnaryOp):
return TypeInferencer.infer_from_value(node.operand)
if isinstance(node, ast.ListComp) or isinstance(node, ast.SetComp):
return "std::vector<std::any>"
if isinstance(node, ast.DictComp):
return "std::map<std::string, std::any>"
return "std::any"
@staticmethod
def _infer_binop(node: ast.BinOp) -> str:
left = TypeInferencer.infer_from_value(node.left)
right = TypeInferencer.infer_from_value(node.right)
# Numeric promotion
numeric = {"int", "double", "float"}
if left in numeric and right in numeric:
if "double" in (left, right) or "float" in (left, right):
return "double"
return "int"
# String concatenation
if left == "std::string" or right == "std::string":
if isinstance(node.op, ast.Add):
return "std::string"
return "auto"
@staticmethod
def _infer_call(node: ast.Call) -> str:
if not isinstance(node.func, ast.Name):
return "std::any"
func_name = node.func.id
func_map = {
"input": "std::string",
"range": "std::vector<int>",
"str": "std::string",
"int": "int",
"float": "double",
"bool": "bool",
"list": "std::vector<std::any>",
"dict": "std::map<std::string, std::any>",
"set": "std::set<std::any>",
"tuple": "std::tuple<std::any>",
"len": "int",
"map": "std::vector<std::any>",
"filter": "std::vector<std::any>",
"zip": "std::vector<std::pair<std::any, std::any>>",
"enumerate": "std::vector<std::pair<int, std::any>>",
"sum": "double",
"min": "std::any",
"max": "std::any",
"sorted": "std::vector<std::any>",
"reversed": "std::vector<std::any>",
"any": "bool",
"all": "bool",
}
return func_map.get(func_name, func_name)
@staticmethod
def infer_from_annotation(annotation: Optional[ast.expr]) -> str:
"""Infer C++ type from Python type annotation."""
if annotation is None:
return "auto"
if isinstance(annotation, ast.Name):
return TypeInferencer.PYTHON_TYPE_MAP.get(annotation.id, "std::any")
if isinstance(annotation, ast.Subscript):
if isinstance(annotation.value, ast.Name):
base = annotation.value.id
if base in ("List", "list"):
inner = TypeInferencer.infer_from_annotation(annotation.slice)
return f"std::vector<{inner}>"
if base in ("Dict", "dict"):
return "std::map<std::string, std::any>"
if base in ("Set", "set"):
inner = TypeInferencer.infer_from_annotation(annotation.slice)
return f"std::set<{inner}>"
if base in ("Optional", "option"):
inner = TypeInferencer.infer_from_annotation(annotation.slice)
return f"std::optional<{inner}>"
if base in ("Tuple", "tuple"):
return "std::tuple<std::any>"
if isinstance(annotation, ast.UnionType): # pyright: ignore[reportAttributeAccessIssue]
return "std::variant<std::any>"
return "std::any"
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# SCOPE & SYMBOL TABLE
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
@dataclass
class Symbol:
"""Represents a symbol in the symbol table."""
name: str
cpp_type: str
is_mutable: bool = True
is_defined: bool = False
is_constant: bool = False
class Scope:
"""Manages variables and scoping."""
def __init__(self, parent: Optional["Scope"] = None, scope_type: str = "block"):
self.parent = parent
self.symbols: Dict[str, Symbol] = {}
self.scope_type = scope_type
self.captured_vars: Set[str] = set()
def define(self, name: str, cpp_type: str, is_mutable: bool = True, is_constant: bool = False) -> None:
self.symbols[name] = Symbol(name, cpp_type, is_mutable, is_defined=True, is_constant=is_constant)
def resolve(self, name: str) -> Optional[Symbol]:
if name in self.symbols:
return self.symbols[name]
return self.parent.resolve(name) if self.parent else None
def exists(self, name: str) -> bool:
return self.resolve(name) is not None
def get_type(self, name: str) -> str:
symbol = self.resolve(name)
return symbol.cpp_type if symbol else "std::any"
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# ADVANCED TRANSPILER ENGINE
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
class Transpiler(ast.NodeVisitor):
"""Advanced AST-based Python to C++20 transpiler."""
def __init__(self, source: str, logger: Logger):
self.source = source
self.logger = logger
self.buffer: List[str] = []
self.indent_level = 0
self.scopes: List[Scope] = [Scope(scope_type="module")]
self.current_class: Optional[str] = None
self.class_members: Dict[str, str] = {}
self.current_function: Optional[str] = None
self.in_function = False
self.current_return_type = "void"
self.generator_functions: Set[str] = set()
self.lambda_counter = 0
self.comprehension_counter = 0
self.try_except_counter = 0
self.comments = extract_comments(source)
self.used_comment_lines: Set[int] = set()
self.global_vars: Set[str] = set()
self.decorator_stack: List[List[str]] = []
def push_scope(self, scope_type: str = "block") -> None:
self.scopes.append(Scope(self.scopes[-1], scope_type))
def pop_scope(self) -> None:
if len(self.scopes) > 1:
self.scopes.pop()
def current_scope(self) -> Scope:
return self.scopes[-1]
def emit_comments_before(self, lineno: int) -> None:
"""Emit comments that appear before a given line number."""
for line in sorted(self.comments.keys()):
if line < lineno and line not in self.used_comment_lines:
for c in self.comments[line]:
self.emit(f"// {c}")
self.used_comment_lines.add(line)
def emit(self, code: str) -> None:
"""Emit indented C++ code."""
if code.strip():
indent = " " * self.indent_level
self.buffer.append(f"{indent}{code}")
else:
self.buffer.append("")
def transpile(self) -> str:
"""Main transpilation entry point."""
try:
tree = ast.parse(self.source)
self.visit(tree)
return "\n".join(self.buffer)
except Exception as e:
self.logger.error(f"Transpilation failed: {e}")
raise
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Module & Global Structure
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def visit_Module(self, node: ast.Module) -> None:
"""Process module: collect definitions, then generate main."""
self.logger.stats['nodes'] += 1
# First pass: collect class and function definitions
for stmt in node.body:
if isinstance(stmt, (ast.ClassDef, ast.FunctionDef)):
self.visit(stmt)
elif isinstance(stmt, ast.Global):
for name in stmt.names:
self.global_vars.add(name)
# Emit main function
self.emit("\n// βββββββββββββββββββββββββββββββββββββββββββββββββββββββ")
self.emit("// MAIN ENTRY POINT")
self.emit("// βββββββββββββββββββββββββββββββββββββββββββββββββββββββ")
self.emit("int main() {")
self.indent_level += 1
self.emit("std::ios::sync_with_stdio(false);")
self.emit("")
has_code = False
for stmt in node.body:
if not isinstance(stmt, (ast.ClassDef, ast.FunctionDef, ast.Import, ast.ImportFrom, ast.Global)):
self.visit(stmt)
has_code = True
if not has_code:
self.emit("// No executable code")
self.emit("")
self.emit("return 0;")
self.indent_level -= 1
self.emit("}")
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Class Definitions
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def visit_ClassDef(self, node: ast.ClassDef) -> None:
"""Generate C++ class definition with inheritance support."""
self.emit_comments_before(node.lineno)
self.logger.stats['nodes'] += 1
self.logger.stats['classes'] += 1
name = node.name
bases = [b.id for b in node.bases if isinstance(b, ast.Name)]
inheritance = f" : public {', public '.join(bases)}" if bases else ""
self.emit(f"class {name}{inheritance} {{")
self.emit("public:")
self.indent_level += 1
self.push_scope("class")
old_class = self.current_class
self.current_class = name
self.class_members = {}
# Scan for member variables
self._scan_class_members(node)
# Emit member variables
for member_name, member_type in sorted(self.class_members.items()):
self.emit(f"{member_type} {member_name};")
if self.class_members:
self.emit("")
# Process methods
for stmt in node.body:
if isinstance(stmt, ast.FunctionDef):
self._visit_method(stmt)
elif isinstance(stmt, ast.Pass):
pass
self.current_class = old_class
self.pop_scope()
self.indent_level -= 1
self.emit("};")
self.emit("")
def _scan_class_members(self, node: ast.ClassDef) -> None:
"""Extract member variables from __init__."""
for stmt in node.body:
if isinstance(stmt, ast.FunctionDef) and stmt.name == "__init__":
for substmt in stmt.body:
if isinstance(substmt, ast.Assign):
for target in substmt.targets:
if isinstance(target, ast.Attribute):
if isinstance(target.value, ast.Name) and target.value.id == "self":
member_name = target.attr
member_type = TypeInferencer.infer_from_value(substmt.value)
self.class_members[member_name] = member_type
def _visit_method(self, node: ast.FunctionDef) -> None:
"""Process class method."""
self.push_scope("function")
old_function = self.current_function
self.current_function = node.name
self.in_function = True
# Infer return type
ret_type = self._infer_return_type(node)
self.current_return_type = ret_type
# Process arguments
args_list = []
for arg in node.args.args:
if arg.arg != "self":
arg_type = TypeInferencer.infer_from_annotation(arg.annotation)
args_list.append(f"{arg_type} {arg.arg}")
self.current_scope().define(arg.arg, arg_type)
args_str = ", ".join(args_list)
# Emit signature
if node.name == "__init__":
self.emit(f"{self.current_class}({args_str}) {{")
else:
self.emit(f"{ret_type} {node.name}({args_str}) {{")
self.indent_level += 1
# Process body
for stmt in node.body:
self.visit(stmt)
self.indent_level -= 1
self.emit("}")
self.in_function = False
self.current_function = old_function
self.pop_scope()
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Function Definitions
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def visit_FunctionDef(self, node: ast.FunctionDef) -> None:
"""Generate standalone function."""
self.emit_comments_before(node.lineno)
if self.current_class:
return # Handled by _visit_method
self.logger.stats['nodes'] += 1
self.logger.stats['functions'] += 1
# Check if function contains yield (is a generator)
has_yield = any(isinstance(n, ast.Yield) for n in ast.walk(node))
if has_yield:
self.generator_functions.add(node.name)
self.logger.warn(f"Generator function '{node.name}' converted to regular function returning vector")
self.push_scope("function")
old_function = self.current_function
self.current_function = node.name
self.in_function = True
ret_type = self._infer_return_type(node)
self.current_return_type = ret_type
# Process arguments
args_list = []
for arg in node.args.args:
arg_type = TypeInferencer.infer_from_annotation(arg.annotation)
args_list.append(f"{arg_type} {arg.arg}")
self.current_scope().define(arg.arg, arg_type)
args_str = ", ".join(args_list)
self.emit(f"{ret_type} {node.name}({args_str}) {{")
self.indent_level += 1
for stmt in node.body:
self.visit(stmt)
self.indent_level -= 1
self.emit("}")
self.in_function = False
self.current_function = old_function
self.pop_scope()
def _infer_return_type(self, func: ast.FunctionDef) -> str:
"""Infer function return type."""
if func.returns:
return TypeInferencer.infer_from_annotation(func.returns)
return_types: Set[str] = set()
for stmt in ast.walk(func):
if isinstance(stmt, ast.Return) and stmt.value:
inferred = TypeInferencer.infer_from_value(stmt.value)
if inferred != "std::any":
return_types.add(inferred)
if return_types:
for pref in ["int", "double", "std::string", "bool"]:
if pref in return_types:
return pref
return list(return_types)[0]
return "void"
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Control Flow Statements
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def visit_If(self, node: ast.If) -> None:
"""Process if statement."""
self.emit_comments_before(node.lineno)
test = self._transpile_expr(node.test)
self.emit(f"if ({test}) {{")
self.indent_level += 1
for stmt in node.body:
self.visit(stmt)
self.indent_level -= 1
if node.orelse:
self.emit("} else {")
self.indent_level += 1
for stmt in node.orelse:
self.visit(stmt)
self.indent_level -= 1
self.emit("}")
def visit_While(self, node: ast.While) -> None:
"""Process while loop."""
self.emit_comments_before(node.lineno)
test = self._transpile_expr(node.test)
self.emit(f"while ({test}) {{")
self.indent_level += 1
for stmt in node.body:
self.visit(stmt)
self.indent_level -= 1
self.emit("}")
def visit_For(self, node: ast.For) -> None:
"""Process for loop with range optimization."""
self.emit_comments_before(node.lineno)
if not isinstance(node.target, ast.Name):
return
target = node.target.id
# Optimize: for i in range(n)
if self._is_range_call(node.iter):
args = self._get_range_args(node.iter) # pyright: ignore[reportArgumentType]
if len(args) == 1:
start, stop, step = "0", args[0], "1"
elif len(args) == 2:
start, stop, step = args[0], args[1], "1"
else:
start, stop, step = args[0], args[1], args[2]
self.current_scope().define(target, "int")
self.emit(f"for (int {target} = {start}; {target} < {stop}; {target} += {step}) {{")
else:
# Generic range-based for
iterable = self._transpile_expr(node.iter)
self.current_scope().define(target, "auto")
self.emit(f"for (auto {target} : {iterable}) {{")
self.indent_level += 1
for stmt in node.body:
self.visit(stmt)
self.indent_level -= 1
self.emit("}")
def _is_range_call(self, node: ast.expr) -> bool:
"""Check if node is a range() call."""
return (isinstance(node, ast.Call) and
isinstance(node.func, ast.Name) and
node.func.id == "range")
def _get_range_args(self, node: ast.Call) -> List[str]:
"""Extract range() arguments as strings."""
return [self._transpile_expr(a) for a in node.args]
def visit_Break(self, node: ast.Break) -> None:
self.emit_comments_before(node.lineno)
self.emit("break;")
def visit_Continue(self, node: ast.Continue) -> None:
self.emit_comments_before(node.lineno)
self.emit("continue;")
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Assignment & Variables
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def visit_Assign(self, node: ast.Assign) -> None:
self.emit_comments_before(node.lineno)
value_expr = self._transpile_expr(node.value)
inferred_type = TypeInferencer.infer_from_value(node.value)
for target in node.targets:
if isinstance(target, ast.Name):
name = target.id
sym = self.current_scope().resolve(name)
if sym is None:
self.current_scope().define(name, inferred_type)
self.emit(f"{inferred_type} {name} = {value_expr};")
else:
self.emit(f"{name} = {value_expr};")
def visit_AugAssign(self, node: ast.AugAssign) -> None: