-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathxp2cpp.py
More file actions
2072 lines (1977 loc) · 103 KB
/
xp2cpp.py
File metadata and controls
2072 lines (1977 loc) · 103 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 argparse
import ast
import difflib
import subprocess
import sys
import time
from pathlib import Path
class CppTranspiler:
def __init__(self) -> None:
self.indent_level = 0
self.lines: list[str] = []
self.function_return_types: dict[str, str] = {}
self.function_local_types: dict[str, dict[str, str]] = {}
self.function_arg_names: dict[str, list[str]] = {}
self.function_arg_defaults: dict[str, dict[str, ast.AST]] = {}
self.function_cpp_names: dict[str, str] = {}
self.struct_fields: dict[str, dict[str, str]] = {}
self.function_struct_types: dict[str, str] = {}
self.argparse_specs: dict[str, dict[str, object]] = {}
def emit(self, line: str = "") -> None:
self.lines.append(" " * self.indent_level + line)
def transpile(self, tree: ast.Module) -> str:
self.collect_function_types(tree)
self.emit("#include <algorithm>")
self.emit("#include <cctype>")
self.emit("#include <cmath>")
self.emit("#include <iomanip>")
self.emit("#include <iostream>")
self.emit("#include <limits>")
self.emit("#include <map>")
self.emit("#include <random>")
self.emit("#include <sstream>")
self.emit("#include <stdexcept>")
self.emit("#include <string>")
self.emit("#include <tuple>")
self.emit("#include <vector>")
self.emit('#include "pycpp_array.hpp"')
self.emit()
self.emit("std::string trim_copy(const std::string& value) {")
self.indent_level += 1
self.emit('const std::string whitespace = " \\t\\n\\r";')
self.emit("const auto first = value.find_first_not_of(whitespace);")
self.emit("if (first == std::string::npos) {")
self.indent_level += 1
self.emit('return "";')
self.indent_level -= 1
self.emit("}")
self.emit("const auto last = value.find_last_not_of(whitespace);")
self.emit("return value.substr(first, last - first + 1);")
self.indent_level -= 1
self.emit("}")
self.emit()
self.emit("std::string lower_copy(std::string value) {")
self.indent_level += 1
self.emit("std::transform(value.begin(), value.end(), value.begin(), [](unsigned char ch) {")
self.indent_level += 1
self.emit("return static_cast<char>(std::tolower(ch));")
self.indent_level -= 1
self.emit("});")
self.emit("return value;")
self.indent_level -= 1
self.emit("}")
self.emit()
self.emit("std::string format_double(double value, const std::string& spec) {")
self.indent_level += 1
self.emit("std::ostringstream oss;")
self.emit('if (spec.size() >= 3 && spec[0] == \'.\' && spec.back() == \'f\') {')
self.indent_level += 1
self.emit("const int precision = std::stoi(spec.substr(1, spec.size() - 2));")
self.emit("oss << std::fixed << std::setprecision(precision) << value;")
self.indent_level -= 1
self.emit('} else if (spec.size() >= 3 && spec[0] == \'.\' && spec.back() == \'e\') {')
self.indent_level += 1
self.emit("const int precision = std::stoi(spec.substr(1, spec.size() - 2));")
self.emit("oss << std::scientific << std::setprecision(precision) << value;")
self.indent_level -= 1
self.emit("} else {")
self.indent_level += 1
self.emit("oss << value;")
self.indent_level -= 1
self.emit("}")
self.emit("return oss.str();")
self.indent_level -= 1
self.emit("}")
self.emit()
self.emit("std::mt19937 make_rng(int seed) {")
self.indent_level += 1
self.emit("return std::mt19937(seed);")
self.indent_level -= 1
self.emit("}")
self.emit()
self.emit("double normal_sample(std::mt19937& rng, double mean, double stddev) {")
self.indent_level += 1
self.emit("std::normal_distribution<double> dist(mean, stddev);")
self.emit("return dist(rng);")
self.indent_level -= 1
self.emit("}")
self.emit()
self.emit("std::vector<double> concat_vectors(std::vector<double> left, const std::vector<double>& right) {")
self.indent_level += 1
self.emit("left.insert(left.end(), right.begin(), right.end());")
self.emit("return left;")
self.indent_level -= 1
self.emit("}")
self.emit()
for struct_name, fields in self.struct_fields.items():
self.emit(f"struct {struct_name} {{")
self.indent_level += 1
for field_name, field_type in fields.items():
self.emit(f"{field_type} {field_name}{self.default_initializer(field_type)};")
self.indent_level -= 1
self.emit("};")
self.emit()
self.emit("std::vector<std::string> sys_argv;")
self.emit()
self.emit("std::ostream& operator<<(std::ostream& os, const std::tuple<int>& value) {")
self.indent_level += 1
self.emit('os << "(" << std::get<0>(value) << ",)";')
self.emit("return os;")
self.indent_level -= 1
self.emit("}")
self.emit()
self.emit("std::ostream& operator<<(std::ostream& os, const std::tuple<int, int>& value) {")
self.indent_level += 1
self.emit('os << "(" << std::get<0>(value) << ", " << std::get<1>(value) << ")";')
self.emit("return os;")
self.indent_level -= 1
self.emit("}")
self.emit()
for spec in self.argparse_specs.values():
struct_name = spec["struct_name"]
fields = spec["fields"]
self.emit(f"{struct_name} parse_{struct_name}(const std::vector<std::string>& argv) {{")
self.indent_level += 1
self.emit(f"{struct_name} args;")
positional_name = None
positional_default = None
positional_type = None
for field in fields:
if field["kind"] == "positional":
positional_name = field["name"]
positional_default = field["default_expr"]
positional_type = field["type"]
else:
self.emit(f'args.{field["name"]} = {field["default_expr"]};')
if positional_name is not None:
self.emit(f"args.{positional_name} = {positional_default};")
self.emit("for (int i = 1; i < static_cast<int>(argv.size()); ++i) {")
self.indent_level += 1
self.emit("const std::string& arg = argv[i];")
first = True
for field in fields:
if field["kind"] != "option":
continue
prefix = "if" if first else "else if"
self.emit(f'{prefix} (arg == "{field["flag"]}") {{')
self.indent_level += 1
self.emit("if (i + 1 >= static_cast<int>(argv.size())) {")
self.indent_level += 1
self.emit(f'throw std::runtime_error("missing value for {field["flag"]}");')
self.indent_level -= 1
self.emit("}")
parse_expr = "argv[++i]"
if field["type"] == "int":
parse_expr = "std::stoi(argv[++i])"
elif field["type"] == "double":
parse_expr = "std::stod(argv[++i])"
self.emit(f'args.{field["name"]} = {parse_expr};')
self.indent_level -= 1
self.emit("}")
first = False
if positional_name is not None:
prefix = "if" if first else "else if"
self.emit(f"{prefix} (!arg.empty() && arg[0] != '-') {{")
self.indent_level += 1
assign_expr = "arg"
if positional_type == "int":
assign_expr = "std::stoi(arg)"
elif positional_type == "double":
assign_expr = "std::stod(arg)"
self.emit(f"args.{positional_name} = {assign_expr};")
self.indent_level -= 1
self.emit("}")
first = False
self.emit("else {")
self.indent_level += 1
self.emit('throw std::runtime_error("unsupported command-line argument: " + arg);')
self.indent_level -= 1
self.emit("}")
self.indent_level -= 1
self.emit("}")
self.emit("return args;")
self.indent_level -= 1
self.emit("}")
self.emit()
for node in tree.body:
if isinstance(node, ast.FunctionDef):
self.emit_function(node)
self.emit()
main_block = self.find_main_block(tree)
self.emit("int main(int argc, char* argv[]) {")
self.indent_level += 1
self.emit("sys_argv.clear();")
self.emit("for (int i = 0; i < argc; ++i) {")
self.indent_level += 1
self.emit("sys_argv.emplace_back(argv[i]);")
self.indent_level -= 1
self.emit("}")
if main_block is not None:
local_types: dict[str, str] = {}
for stmt in main_block:
self.collect_stmt_types(stmt, local_types)
declared: set[str] = set()
for name, cpp_type in local_types.items():
self.emit(f"{cpp_type} {name}{self.default_initializer(cpp_type)};")
declared.add(name)
for stmt in main_block:
self.emit_stmt(stmt, local_types, declared)
self.emit("return 0;")
self.indent_level -= 1
self.emit("}")
return "\n".join(self.lines) + "\n"
def collect_function_types(self, tree: ast.Module) -> None:
for node in tree.body:
if not isinstance(node, ast.FunctionDef):
continue
self.function_cpp_names[node.name] = "py_main" if node.name == "main" else node.name
self.extract_argparse_spec(node)
arg_names = [arg.arg for arg in node.args.args]
self.function_arg_names[node.name] = arg_names
defaults: dict[str, ast.AST] = {}
if node.args.defaults:
offset = len(arg_names) - len(node.args.defaults)
for name, default_node in zip(arg_names[offset:], node.args.defaults):
defaults[name] = default_node
self.function_arg_defaults[node.name] = defaults
local_types = {}
for arg in node.args.args:
local_types[arg.arg] = self.cpp_type_from_annotation(arg.annotation, arg.arg, defaults.get(arg.arg))
for stmt in node.body:
self.collect_stmt_types(stmt, local_types)
for arg in node.args.args:
if local_types.get(arg.arg) == "double":
inferred = self.infer_arg_type_from_usage(node, arg.arg, local_types)
if inferred != "double":
local_types[arg.arg] = inferred
rescanned_types = {arg.arg: local_types[arg.arg] for arg in node.args.args}
for stmt in node.body:
self.collect_stmt_types(stmt, rescanned_types)
local_types = rescanned_types
self.function_local_types[node.name] = local_types
self.function_return_types[node.name] = self.infer_function_return_type(node, local_types)
def infer_function_return_type(self, node: ast.FunctionDef, local_types: dict[str, str]) -> str:
annotated = self.cpp_type_from_annotation(node.returns)
if node.returns is not None:
return annotated
return_types: list[str] = []
for inner in ast.walk(node):
if isinstance(inner, ast.Return) and inner.value is not None:
if isinstance(inner.value, ast.Dict):
struct_name = f"{self.function_cpp_names.get(node.name, node.name)}_result"
fields: dict[str, str] = {}
for key, value in zip(inner.value.keys, inner.value.values):
if not isinstance(key, ast.Constant) or not isinstance(key.value, str):
raise NotImplementedError("dict return keys must be string literals")
fields[key.value] = self.infer_expr_type(value, local_types)
self.struct_fields[struct_name] = fields
self.function_struct_types[node.name] = struct_name
return struct_name
return_types.append(self.infer_expr_type(inner.value, local_types))
if not return_types:
return "void"
unique_types: list[str] = []
for item in return_types:
if item not in unique_types:
unique_types.append(item)
if len(unique_types) == 1:
return unique_types[0]
if set(unique_types) == {"pycpp::Array1D<double>", "pycpp::Array2D<double>"}:
return "pycpp::Array2D<double>"
return unique_types[0]
def collect_stmt_types(self, stmt: ast.stmt, local_types: dict[str, str]) -> None:
if isinstance(stmt, ast.Assign) and len(stmt.targets) == 1 and isinstance(stmt.targets[0], ast.Name):
name = stmt.targets[0].id
if (
isinstance(stmt.value, ast.Call)
and isinstance(stmt.value.func, ast.Attribute)
and stmt.value.func.attr == "parse_args"
and isinstance(stmt.value.func.value, ast.Name)
):
for spec in self.argparse_specs.values():
if stmt.value.func.value.id == spec["parser_var"]:
local_types[name] = spec["struct_name"]
return
inferred = self.infer_expr_type(stmt.value, local_types)
current = local_types.get(name)
if current is None or (current == "double" and inferred != "double"):
local_types[name] = inferred
elif isinstance(stmt, ast.Assign) and len(stmt.targets) == 1 and isinstance(stmt.targets[0], (ast.Tuple, ast.List)):
target = stmt.targets[0]
inferred = self.infer_expr_type(stmt.value, local_types)
tuple_items = self.tuple_inner_types(inferred)
if tuple_items and len(tuple_items) == len(target.elts):
for elt, item_type in zip(target.elts, tuple_items):
if isinstance(elt, ast.Name):
local_types[elt.id] = item_type
elif isinstance(stmt, ast.If):
for inner in stmt.body:
self.collect_stmt_types(inner, local_types)
for inner in stmt.orelse:
self.collect_stmt_types(inner, local_types)
elif isinstance(stmt, ast.For):
if isinstance(stmt.target, ast.Name):
local_types.setdefault(stmt.target.id, "int")
for inner in stmt.body:
self.collect_stmt_types(inner, local_types)
for inner in stmt.orelse:
self.collect_stmt_types(inner, local_types)
def infer_expr_type(self, expr: ast.AST, local_types: dict[str, str]) -> str:
if isinstance(expr, ast.Constant):
if isinstance(expr.value, bool):
return "bool"
if isinstance(expr.value, int):
return "int"
if isinstance(expr.value, float):
return "double"
if isinstance(expr.value, str):
return "std::string"
if isinstance(expr, ast.Name):
return local_types.get(expr.id, "double")
if isinstance(expr, ast.Attribute) and expr.attr == "shape":
base_type = self.infer_expr_type(expr.value, local_types)
if base_type == "pycpp::Array2D<double>":
return "std::tuple<int, int>"
if base_type in {"pycpp::Array1D<double>", "pycpp::Array1D<int>"}:
return "std::tuple<int>"
if isinstance(expr, ast.Tuple):
inner = ", ".join(self.infer_expr_type(elt, local_types) for elt in expr.elts)
return f"std::tuple<{inner}>"
if isinstance(expr, ast.Call):
if isinstance(expr.func, ast.Name):
if expr.func.id in {"abs", "float"}:
return "double"
if expr.func.id == "int":
return "int"
if expr.func.id == "len":
return "int"
if expr.func.id in {"min", "max"} and len(expr.args) == 2:
left_type = self.infer_expr_type(expr.args[0], local_types)
right_type = self.infer_expr_type(expr.args[1], local_types)
if left_type == right_type == "int":
return "int"
return "double"
if expr.func.id in {"print"}:
return "void"
return self.function_return_types.get(expr.func.id, "double")
if isinstance(expr.func, ast.Attribute):
if self.is_string_method_call(expr):
return "std::string"
if self.attr_chain(expr.func)[:2] == ["argparse", "ArgumentParser"]:
return "pycpp::ArgParser"
if self.attr_chain(expr.func)[:2] == ["math", "erf"]:
return "double"
if self.attr_chain(expr.func)[:2] == ["random", "Random"]:
return "std::mt19937"
if self.attr_chain(expr.func)[:3] == ["np", "random", "default_rng"]:
return "std::mt19937"
if expr.func.attr == "choice":
return "pycpp::Array1D<int>"
if expr.func.attr == "normal":
return "pycpp::Array1D<double>"
if self.attr_chain(expr.func)[:2] == ["np", "array"]:
arg_type = self.infer_expr_type(expr.args[0], local_types) if expr.args else "double"
if arg_type == "std::vector<pycpp::Array2D<double>>":
return arg_type
if expr.args and isinstance(expr.args[0], ast.List) and expr.args[0].elts and isinstance(expr.args[0].elts[0], ast.List):
return "pycpp::Array2D<double>"
return "pycpp::Array1D<double>"
if self.attr_chain(expr.func)[:2] == ["np", "asarray"]:
arg_type = self.infer_expr_type(expr.args[0], local_types) if expr.args else "double"
return arg_type if arg_type.startswith("pycpp::Array") else "pycpp::Array1D<double>"
if self.attr_chain(expr.func)[:2] == ["np", "full"]:
if expr.args and isinstance(expr.args[0], ast.Tuple):
return "pycpp::Array2D<double>"
return "pycpp::Array1D<double>"
if self.attr_chain(expr.func)[:2] == ["np", "empty"]:
if expr.args and isinstance(expr.args[0], ast.Tuple):
return "pycpp::Array2D<double>"
return "pycpp::Array1D<double>"
if self.attr_chain(expr.func)[:2] == ["np", "maximum"]:
arg_type = self.infer_expr_type(expr.args[0], local_types) if expr.args else "double"
return arg_type if arg_type.startswith("pycpp::Array") else "pycpp::Array1D<double>"
if self.attr_chain(expr.func)[:2] == ["np", "sqrt"]:
arg_type = self.infer_expr_type(expr.args[0], local_types) if expr.args else "double"
return arg_type if arg_type.startswith("pycpp::Array") else "pycpp::Array1D<double>"
if self.attr_chain(expr.func)[:2] == ["np", "log"]:
arg_type = self.infer_expr_type(expr.args[0], local_types) if expr.args else "double"
return arg_type if arg_type.startswith("pycpp::Array") else "double"
if self.attr_chain(expr.func)[:2] == ["np", "exp"]:
arg_type = self.infer_expr_type(expr.args[0], local_types) if expr.args else "double"
return arg_type if arg_type.startswith("pycpp::Array") else "double"
if self.attr_chain(expr.func)[:2] == ["np", "sum"]:
if any(keyword.arg == "axis" for keyword in expr.keywords):
keepdims = next((kw.value for kw in expr.keywords if kw.arg == "keepdims"), None)
return "pycpp::Array2D<double>" if isinstance(keepdims, ast.Constant) and keepdims.value else "pycpp::Array1D<double>"
return "double"
if self.attr_chain(expr.func)[:2] == ["np", "var"]:
return "double"
if self.attr_chain(expr.func)[:2] == ["np", "argsort"]:
return "pycpp::Array1D<int>"
if self.attr_chain(expr.func)[:2] == ["np", "eye"]:
return "pycpp::Array2D<double>"
if self.attr_chain(expr.func)[:2] == ["np", "ndim"]:
return "int"
if self.attr_chain(expr.func)[:2] == ["np", "cov"]:
return "pycpp::Array2D<double>"
if self.attr_chain(expr.func)[:2] == ["np", "atleast_2d"]:
return "pycpp::Array2D<double>"
if self.attr_chain(expr.func)[:2] == ["np", "loadtxt"]:
return "pycpp::Array2D<double>"
if self.attr_chain(expr.func)[:3] == ["np", "linalg", "slogdet"]:
return "std::tuple<double, double>"
if self.attr_chain(expr.func)[:3] == ["np", "linalg", "inv"]:
return "pycpp::Array2D<double>"
if self.attr_chain(expr.func)[:2] == ["np", "einsum"]:
return "pycpp::Array1D<double>"
if self.attr_chain(expr.func)[:2] == ["np", "where"]:
return "std::tuple<pycpp::Array1D<int>>"
if self.attr_chain(expr.func)[:2] == ["np", "column_stack"]:
return "pycpp::Array2D<double>"
if self.attr_chain(expr.func)[:2] == ["np", "max"]:
if any(keyword.arg == "axis" for keyword in expr.keywords):
keepdims = next((kw.value for kw in expr.keywords if kw.arg == "keepdims"), None)
return "pycpp::Array2D<double>" if isinstance(keepdims, ast.Constant) and keepdims.value else "pycpp::Array1D<double>"
return "double"
if self.attr_chain(expr.func)[:2] == ["np", "squeeze"]:
return "pycpp::Array1D<double>"
if expr.func.attr in {"sum", "copy", "ravel"}:
base_type = self.infer_expr_type(expr.func.value, local_types)
if expr.func.attr == "sum":
if any(keyword.arg == "axis" for keyword in expr.keywords):
return "pycpp::Array1D<double>"
return "double"
return base_type
if expr.func.attr == "size":
return "int"
if expr.func.attr == "reshape":
base_type = self.infer_expr_type(expr.func.value, local_types)
if len(expr.args) == 1:
if base_type == "pycpp::Array2D<double>":
return "pycpp::Array1D<double>"
return base_type
return "pycpp::Array2D<double>"
if expr.func.attr == "gauss":
return "double"
if expr.func.attr == "multivariate_normal":
return "pycpp::Array2D<double>"
if expr.func.attr == "parse_args" and isinstance(expr.func.value, ast.Name):
spec = self.argparse_specs.get(self.current_function_name(local_types))
if spec is not None and expr.func.value.id == spec["parser_var"]:
return spec["struct_name"]
if isinstance(expr, ast.BinOp):
if (
isinstance(expr.op, ast.Mult)
and isinstance(expr.left, ast.List)
and len(expr.left.elts) == 1
):
return "std::vector<double>"
left_type = self.infer_expr_type(expr.left, local_types)
right_type = self.infer_expr_type(expr.right, local_types)
if left_type.startswith("pycpp::Array") and right_type in {"double", "int"}:
return left_type
if right_type.startswith("pycpp::Array") and left_type in {"double", "int"}:
return right_type
if isinstance(expr.op, ast.MatMult):
if left_type == "pycpp::Array2D<double>" and right_type == "pycpp::Array2D<double>":
return "pycpp::Array2D<double>"
if left_type == "pycpp::Array2D<double>" and right_type == "pycpp::Array1D<double>":
return "pycpp::Array1D<double>"
if (
isinstance(expr.op, ast.Add)
and left_type == "std::vector<double>"
and right_type == "std::vector<double>"
):
return "std::vector<double>"
if left_type.startswith("pycpp::Array") and right_type.startswith("pycpp::Array"):
return left_type
if left_type == right_type == "int":
return "int"
return "double"
if isinstance(expr, ast.UnaryOp):
return self.infer_expr_type(expr.operand, local_types)
if isinstance(expr, ast.Compare):
return "bool"
if isinstance(expr, ast.BoolOp):
return "bool"
if isinstance(expr, ast.IfExp):
body_type = self.infer_expr_type(expr.body, local_types)
else_type = self.infer_expr_type(expr.orelse, local_types)
if body_type == else_type:
return body_type
if "std::string" in {body_type, else_type}:
return "std::string"
if body_type.startswith("pycpp::Array"):
return body_type
if else_type.startswith("pycpp::Array"):
return else_type
if body_type == else_type == "int":
return "int"
return "double"
if isinstance(expr, ast.Dict):
return "std::map<std::string, double>"
if isinstance(expr, ast.Subscript):
if (
isinstance(expr.value, ast.Call)
and isinstance(expr.value.func, ast.Attribute)
and self.attr_chain(expr.value.func)[:2] == ["np", "where"]
and isinstance(expr.slice, ast.Constant)
and expr.slice.value == 0
):
return "pycpp::Array1D<int>"
value_type = self.infer_expr_type(expr.value, local_types)
if value_type in self.struct_fields and isinstance(expr.slice, ast.Constant) and isinstance(expr.slice.value, str):
return self.struct_fields[value_type][expr.slice.value]
if (
isinstance(expr.value, ast.Attribute)
and expr.value.attr == "shape"
and isinstance(expr.slice, ast.Constant)
and isinstance(expr.slice.value, int)
):
return "int"
if isinstance(expr.slice, ast.Tuple) and value_type == "pycpp::Array1D<double>":
return "pycpp::Array2D<double>"
if value_type == "std::vector<double>":
return "double"
if value_type == "std::vector<pycpp::Array2D<double>>":
index_type = self.infer_expr_type(expr.slice, local_types)
if index_type == "pycpp::Array1D<int>":
return "std::vector<pycpp::Array2D<double>>"
return "pycpp::Array2D<double>"
if value_type == "pycpp::Array1D<double>":
index_type = self.infer_expr_type(expr.slice, local_types)
if index_type == "pycpp::Array1D<int>":
return "pycpp::Array1D<double>"
return "double"
if value_type == "pycpp::Array1D<int>":
index_type = self.infer_expr_type(expr.slice, local_types)
if index_type == "pycpp::Array1D<int>":
return "pycpp::Array1D<int>"
return "int"
if value_type == "pycpp::Array2D<double>":
index_type = self.infer_expr_type(expr.slice, local_types)
if index_type == "pycpp::Array1D<int>":
return "pycpp::Array2D<double>"
return "pycpp::Array1D<double>"
return "double"
if isinstance(expr, ast.List):
if expr.elts:
element_type = self.infer_expr_type(expr.elts[0], local_types)
if element_type == "pycpp::Array2D<double>":
return "std::vector<pycpp::Array2D<double>>"
return "std::vector<double>"
if isinstance(expr, ast.ListComp):
element_type = self.infer_expr_type(expr.elt, local_types)
if element_type == "pycpp::Array2D<double>":
return "std::vector<pycpp::Array2D<double>>"
return "std::vector<double>"
return "double"
def cpp_type_from_annotation(self, annotation: ast.AST | None, arg_name: str | None = None, default_node: ast.AST | None = None) -> str:
if annotation is None:
if arg_name == "axis":
return "int"
if arg_name in {"keepdims", "replace"}:
return "bool"
if isinstance(default_node, ast.Constant):
if isinstance(default_node.value, bool):
return "bool"
if isinstance(default_node.value, int):
return "int"
if isinstance(default_node.value, float):
return "double"
return "double"
if isinstance(annotation, ast.Constant) and annotation.value is None:
return "void"
if isinstance(annotation, ast.Name):
if annotation.id == "float":
return "double"
if annotation.id == "int":
return "int"
if annotation.id == "str":
return "std::string"
if annotation.id == "bool":
return "bool"
if annotation.id == "None":
return "void"
if isinstance(annotation, ast.Subscript):
base = annotation.value
if isinstance(base, ast.Name) and base.id == "dict":
return "std::map<std::string, double>"
if isinstance(base, ast.Name) and base.id == "tuple":
sub = annotation.slice
if isinstance(sub, ast.Tuple):
inner = ", ".join(self.cpp_type_from_annotation(elt) for elt in sub.elts)
return f"std::tuple<{inner}>"
if isinstance(base, ast.Name) and base.id == "list":
if isinstance(annotation.slice, ast.Name) and annotation.slice.id == "str":
return "std::vector<std::string>"
return "std::vector<double>"
return "double"
def emit_function(self, node: ast.FunctionDef) -> None:
return_type = self.function_return_types[node.name]
local_types = self.function_local_types[node.name]
args = []
for arg in node.args.args:
args.append(f"{local_types.get(arg.arg, self.cpp_type_from_annotation(arg.annotation, arg.arg, self.function_arg_defaults[node.name].get(arg.arg)))} {arg.arg}")
cpp_name = self.function_cpp_names.get(node.name, node.name)
self.emit(f"{return_type} {cpp_name}({', '.join(args)}) {{")
self.indent_level += 1
declared = set(arg.arg for arg in node.args.args)
for name, cpp_type in local_types.items():
if name in declared:
continue
self.emit(f"{cpp_type} {name}{self.default_initializer(cpp_type)};")
declared.add(name)
for stmt in node.body:
if self.is_docstring_stmt(stmt):
continue
self.emit_stmt(stmt, local_types, declared)
self.indent_level -= 1
self.emit("}")
def emit_stmt(self, stmt: ast.stmt, local_types: dict[str, str], declared: set[str]) -> None:
if isinstance(stmt, ast.Assign):
self.emit_assign(stmt, local_types, declared)
return
if isinstance(stmt, ast.AugAssign):
self.emit_augassign(stmt, local_types, declared)
return
if isinstance(stmt, ast.Return):
if stmt.value is None:
self.emit("return;")
else:
if isinstance(stmt.value, ast.Dict):
struct_type = self.function_return_types.get(self.current_function_name(local_types), "")
if struct_type in self.struct_fields:
values = [self.expr(value, local_types) for value in stmt.value.values]
self.emit(f"return {struct_type}{{{', '.join(values)}}};")
else:
self.emit(f"return {self.expr(stmt.value, local_types)};")
else:
self.emit(f"return {self.expr(stmt.value, local_types)};")
return
if isinstance(stmt, ast.If):
self.emit(f"if ({self.expr(stmt.test, local_types)}) {{")
self.indent_level += 1
for inner in stmt.body:
self.emit_stmt(inner, local_types, declared)
self.indent_level -= 1
if stmt.orelse:
self.emit("} else {")
self.indent_level += 1
for inner in stmt.orelse:
self.emit_stmt(inner, local_types, declared)
self.indent_level -= 1
self.emit("}")
return
if isinstance(stmt, ast.Raise):
message = "runtime error"
if isinstance(stmt.exc, ast.Call) and stmt.exc.args:
message = self.string_literal_value(stmt.exc.args[0])
self.emit(f'throw std::runtime_error("{self.escape_cpp_string(message)}");')
return
if isinstance(stmt, ast.Expr) and isinstance(stmt.value, ast.Call):
if isinstance(stmt.value.func, ast.Name) and stmt.value.func.id == "print":
self.emit_print(stmt.value, local_types)
return
if (
isinstance(stmt.value.func, ast.Attribute)
and stmt.value.func.attr == "add_argument"
and isinstance(stmt.value.func.value, ast.Name)
):
spec = self.argparse_specs.get(self.current_function_name(local_types))
if spec is not None and stmt.value.func.value.id == spec["parser_var"]:
return
if isinstance(stmt.value.func, ast.Attribute) and stmt.value.func.attr == "append":
self.emit_append(stmt.value, local_types)
return
self.emit(f"{self.expr(stmt.value, local_types)};")
return
if isinstance(stmt, ast.For):
self.emit_for(stmt, local_types, declared)
return
if isinstance(stmt, ast.Break):
self.emit("break;")
return
if isinstance(stmt, ast.Continue):
self.emit("continue;")
return
if isinstance(stmt, ast.Pass):
return
raise NotImplementedError(f"unsupported statement: {ast.dump(stmt)}")
def emit_assign(self, stmt: ast.Assign, local_types: dict[str, str], declared: set[str]) -> None:
target = stmt.targets[0]
if isinstance(target, ast.Subscript):
value = self.expr(stmt.value, local_types)
base_type = self.infer_expr_type(target.value, local_types)
index_type = self.infer_expr_type(target.slice, local_types)
if base_type == "pycpp::Array2D<double>" and index_type == "pycpp::Array1D<int>":
self.emit(f"pycpp::set_rows({self.expr(target.value, local_types)}, {self.expr(target.slice, local_types)}, {value});")
return
if base_type == "pycpp::Array2D<double>" and isinstance(target.slice, (ast.Constant, ast.Name, ast.UnaryOp, ast.BinOp, ast.Call, ast.Attribute, ast.Subscript)):
slice_type = self.infer_expr_type(target.slice, local_types)
if slice_type == "int":
self.emit(f"pycpp::set_row({self.expr(target.value, local_types)}, {self.expr(target.slice, local_types)}, {value});")
return
if (
base_type == "pycpp::Array2D<double>"
and isinstance(target.slice, ast.Tuple)
and len(target.slice.elts) == 2
and isinstance(target.slice.elts[0], ast.Slice)
and target.slice.elts[0].lower is None
and target.slice.elts[0].upper is None
):
self.emit(
f"pycpp::set_col({self.expr(target.value, local_types)}, "
f"{self.expr(target.slice.elts[1], local_types)}, {value});"
)
return
target_expr = self.subscript_expr(target, local_types)
self.emit(f"{target_expr} = {value};")
return
if isinstance(target, (ast.Tuple, ast.List)):
names = []
for elt in target.elts:
if not isinstance(elt, ast.Name):
raise NotImplementedError("only simple tuple targets are supported")
names.append(elt.id)
for name in names:
if name not in declared:
cpp_type = local_types.get(name, "double")
self.emit(f"{cpp_type} {name};")
declared.add(name)
tie_targets = ", ".join(names)
self.emit(f"std::tie({tie_targets}) = {self.expr(stmt.value, local_types)};")
return
if not isinstance(target, ast.Name):
raise NotImplementedError("only simple assignments are supported")
name = target.id
value = self.expr(stmt.value, local_types)
if name in declared:
target_type = local_types.get(name, "double")
value_type = self.infer_expr_type(stmt.value, local_types)
if target_type == "pycpp::Array2D<double>" and value_type == "pycpp::Array1D<double>":
axis = self.squeeze_axis_expr(stmt.value, local_types)
self.emit(f"{name} = pycpp::unsqueeze({value}, {axis});")
else:
self.emit(f"{name} = {value};")
else:
cpp_type = local_types.get(name, self.infer_expr_type(stmt.value, local_types))
self.emit(f"{cpp_type} {name} = {value};")
declared.add(name)
def emit_augassign(self, stmt: ast.AugAssign, local_types: dict[str, str], declared: set[str]) -> None:
if (
isinstance(stmt.target, ast.Subscript)
and isinstance(stmt.target.value, ast.Attribute)
and stmt.target.value.attr == "flat"
and isinstance(stmt.target.value.value, ast.Subscript)
and isinstance(stmt.op, ast.Add)
):
self.emit(f"pycpp::add_diag({self.expr(stmt.target.value.value, local_types)}, {self.expr(stmt.value, local_types)});")
return
if not isinstance(stmt.target, ast.Name):
raise NotImplementedError("only simple augmented assignments are supported")
op = self.binop(stmt.op)
self.emit(f"{stmt.target.id} {op}= {self.expr(stmt.value, local_types)};")
def emit_for(self, stmt: ast.For, local_types: dict[str, str], declared: set[str]) -> None:
if (
isinstance(stmt.target, ast.Tuple)
and len(stmt.target.elts) == 2
and all(isinstance(elt, ast.Name) for elt in stmt.target.elts)
and isinstance(stmt.iter, ast.Call)
and isinstance(stmt.iter.func, ast.Name)
and stmt.iter.func.id == "enumerate"
and len(stmt.iter.args) == 1
):
index_name = stmt.target.elts[0].id
value_name = stmt.target.elts[1].id
vector_expr = self.expr(stmt.iter.args[0], local_types)
if index_name not in declared:
self.emit(f"for (int {index_name} = 0; {index_name} < static_cast<int>({vector_expr}.size()); ++{index_name}) {{")
declared.add(index_name)
else:
self.emit(f"for ({index_name} = 0; {index_name} < static_cast<int>({vector_expr}.size()); ++{index_name}) {{")
self.indent_level += 1
value_type = local_types.get(value_name, "double")
if value_name not in declared:
self.emit(f"{value_type} {value_name} = {vector_expr}[{index_name}];")
declared.add(value_name)
else:
self.emit(f"{value_name} = {vector_expr}[{index_name}];")
for inner in stmt.body:
self.emit_stmt(inner, local_types, declared)
self.indent_level -= 1
self.emit("}")
return
if not isinstance(stmt.target, ast.Name):
raise NotImplementedError("only simple for-loop targets are supported")
if not (
isinstance(stmt.iter, ast.Call)
and isinstance(stmt.iter.func, ast.Name)
and stmt.iter.func.id == "range"
):
raise NotImplementedError("only for ... in range(...) is supported")
loop_var = stmt.target.id
if len(stmt.iter.args) == 1:
start_expr = "0"
stop_expr = self.expr(stmt.iter.args[0], local_types)
step_expr = "1"
elif len(stmt.iter.args) == 2:
start_expr = self.expr(stmt.iter.args[0], local_types)
stop_expr = self.expr(stmt.iter.args[1], local_types)
step_expr = "1"
elif len(stmt.iter.args) == 3:
start_expr = self.expr(stmt.iter.args[0], local_types)
stop_expr = self.expr(stmt.iter.args[1], local_types)
step_expr = self.expr(stmt.iter.args[2], local_types)
else:
raise NotImplementedError("range supports one, two, or three arguments only")
condition = f"{loop_var} < {stop_expr}"
if len(stmt.iter.args) == 3 and self.is_negative_expr(stmt.iter.args[2]):
condition = f"{loop_var} > {stop_expr}"
if loop_var not in declared:
declared.add(loop_var)
self.emit(f"for (int {loop_var} = {start_expr}; {condition}; {loop_var} += {step_expr}) {{")
else:
self.emit(f"for ({loop_var} = {start_expr}; {condition}; {loop_var} += {step_expr}) {{")
self.indent_level += 1
for inner in stmt.body:
self.emit_stmt(inner, local_types, declared)
self.indent_level -= 1
self.emit("}")
def emit_print(self, call: ast.Call, local_types: dict[str, str]) -> None:
if len(call.args) == 0:
self.emit('std::cout << "\\n";')
return
if len(call.args) > 1:
pieces = [self.expr(arg, local_types) for arg in call.args]
self.emit("std::cout << " + ' << " " << '.join(pieces) + ' << "\\n";')
return
expr = call.args[0]
if isinstance(expr, ast.JoinedStr):
parts = []
for value in expr.values:
if isinstance(value, ast.Constant) and isinstance(value.value, str):
parts.append(f'"{self.escape_cpp_string(value.value)}"')
elif isinstance(value, ast.FormattedValue):
fmt = ""
if value.format_spec is not None:
fmt = self.joined_str_literal(value.format_spec)
inner = self.expr(value.value, local_types)
if fmt:
parts.append(f'format_double({inner}, "{self.escape_cpp_string(fmt)}")')
else:
parts.append(f"({inner})")
else:
raise NotImplementedError("unsupported f-string component")
self.emit("std::cout << " + " << ".join(parts) + ' << "\\n";')
return
self.emit(f"std::cout << {self.expr(expr, local_types)} << \"\\n\";")
def emit_append(self, call: ast.Call, local_types: dict[str, str]) -> None:
if len(call.args) != 1 or not isinstance(call.func, ast.Attribute):
raise NotImplementedError("append requires one argument")
target = self.expr(call.func.value, local_types)
value = self.expr(call.args[0], local_types)
self.emit(f"{target}.push_back({value});")
def expr(self, node: ast.AST, local_types: dict[str, str]) -> str:
if isinstance(node, ast.Constant):
if isinstance(node.value, str):
return f'"{self.escape_cpp_string(node.value)}"'
if isinstance(node.value, bool):
return "true" if node.value else "false"
if node.value is None:
return "nullptr"
return repr(node.value)
if isinstance(node, ast.Name):
return node.id
if isinstance(node, ast.BinOp):
if (
isinstance(node.op, ast.Mult)
and isinstance(node.left, ast.List)
and len(node.left.elts) == 1
):
fill_value = self.expr(node.left.elts[0], local_types)
count_expr = self.expr(node.right, local_types)
return f"std::vector<double>({count_expr}, {fill_value})"
if (
isinstance(node.op, ast.Add)
and self.infer_expr_type(node.left, local_types) == "std::vector<double>"
and self.infer_expr_type(node.right, local_types) == "std::vector<double>"
):
left_expr = self.expr(node.left, local_types)
right_expr = self.expr(node.right, local_types)
return f"concat_vectors({left_expr}, {right_expr})"
if isinstance(node.op, ast.Pow):
left_type = self.infer_expr_type(node.left, local_types)
if left_type.startswith("pycpp::Array"):
return f"pycpp::pow({self.expr(node.left, local_types)}, {self.expr(node.right, local_types)})"
return f"std::pow({self.expr(node.left, local_types)}, {self.expr(node.right, local_types)})"
if isinstance(node.op, ast.MatMult):
return f"pycpp::matmul({self.expr(node.left, local_types)}, {self.expr(node.right, local_types)})"
op = self.binop(node.op)
return f"({self.expr(node.left, local_types)} {op} {self.expr(node.right, local_types)})"
if isinstance(node, ast.UnaryOp):
if isinstance(node.op, ast.UAdd):
return f"(+{self.expr(node.operand, local_types)})"
if isinstance(node.op, ast.USub):
return f"(-{self.expr(node.operand, local_types)})"
if isinstance(node.op, ast.Not):
return f"(!{self.expr(node.operand, local_types)})"
raise NotImplementedError(f"unsupported unary operator: {type(node.op).__name__}")
if isinstance(node, ast.Compare):
return self.compare_expr(node, local_types)
if isinstance(node, ast.BoolOp):
op = "&&" if isinstance(node.op, ast.And) else "||"
return "(" + f" {op} ".join(self.expr(v, local_types) for v in node.values) + ")"
if isinstance(node, ast.IfExp):
return (
"("
+ self.expr(node.test, local_types)
+ " ? "
+ self.expr(node.body, local_types)
+ " : "
+ self.expr(node.orelse, local_types)
+ ")"
)
if isinstance(node, ast.Call):
return self.call_expr(node, local_types)
if isinstance(node, ast.Tuple):
return "std::make_tuple(" + ", ".join(self.expr(elt, local_types) for elt in node.elts) + ")"
if isinstance(node, ast.List):
if node.elts and isinstance(node.elts[0], ast.Constant) and isinstance(node.elts[0].value, str):
return "std::vector<std::string>{" + ", ".join(self.expr(elt, local_types) for elt in node.elts) + "}"
if node.elts and self.infer_expr_type(node.elts[0], local_types) == "pycpp::Array2D<double>":
return "std::vector<pycpp::Array2D<double>>{" + ", ".join(self.expr(elt, local_types) for elt in node.elts) + "}"
return "std::vector<double>{" + ", ".join(self.expr(elt, local_types) for elt in node.elts) + "}"
if isinstance(node, ast.ListComp):
return self.list_comp_expr(node, local_types)
if isinstance(node, ast.Dict):
items = []
for key, value in zip(node.keys, node.values):
items.append("{" + f"{self.expr(key, local_types)}, {self.expr(value, local_types)}" + "}")
return "std::map<std::string, double>{" + ", ".join(items) + "}"
if isinstance(node, ast.Subscript):
return self.subscript_expr(node, local_types)
if isinstance(node, ast.Set):
raise NotImplementedError("set literals are only supported in membership tests")
if isinstance(node, ast.Attribute):
chain = self.attr_chain(node)
if chain == ["math", "pi"]:
return "3.14159265358979323846"
if chain == ["np", "pi"]:
return "3.14159265358979323846"
if chain == ["np", "inf"]:
return "std::numeric_limits<double>::infinity()"
if chain == ["sys", "argv"]:
return "sys_argv"
base_type = self.infer_expr_type(node.value, local_types)
if base_type in self.struct_fields:
return f"{self.expr(node.value, local_types)}.{node.attr}"
if node.attr == "T":
if base_type == "pycpp::Array2D<double>":
return f"pycpp::transpose({self.expr(node.value, local_types)})"
if node.attr == "shape":
base_type = self.infer_expr_type(node.value, local_types)
if base_type == "pycpp::Array2D<double>":
base = self.expr(node.value, local_types)
return f"std::make_tuple(static_cast<int>({base}.rows()), static_cast<int>({base}.cols()))"
if base_type in {"pycpp::Array1D<double>", "pycpp::Array1D<int>"}: