l0n0lc 0.8.4__py3-none-any.whl → 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. l0n0lc/Py/350/275/254Cpp/350/275/254/350/257/221/345/231/250.py +579 -0
  2. l0n0lc/__init__.py +75 -6
  3. l0n0lc/aot/347/274/226/350/257/221.py +679 -0
  4. l0n0lc/ast/350/256/277/351/227/256/350/200/205.py +599 -0
  5. l0n0lc/cpp/347/261/273/345/236/213.py +330 -0
  6. l0n0lc/cpp/347/274/226/350/257/221/345/231/250.py +317 -0
  7. l0n0lc/simd/344/274/230/345/214/226.py +260 -0
  8. l0n0lc/std_map.py +153 -0
  9. l0n0lc/std_set.py +185 -0
  10. l0n0lc/std_vector.py +96 -0
  11. l0n0lc//344/273/243/347/240/201/344/274/230/345/214/226.py +302 -0
  12. l0n0lc//344/273/243/347/240/201/347/224/237/346/210/220.py +546 -0
  13. l0n0lc//344/276/235/350/265/226/346/263/250/345/205/245.py +155 -0
  14. l0n0lc//345/215/263/346/227/266/347/274/226/350/257/221.py +192 -0
  15. l0n0lc//345/217/230/351/207/217/347/256/241/347/220/206/345/231/250.py +123 -0
  16. l0n0lc//345/237/272/347/241/200/346/230/240/345/260/204.py +103 -0
  17. l0n0lc//345/237/272/347/241/200/346/267/267/345/205/245.py +147 -0
  18. l0n0lc//345/256/271/345/231/250/346/236/204/345/273/272/345/231/250.py +214 -0
  19. l0n0lc//345/267/245/345/205/267.py +285 -0
  20. l0n0lc//345/271/266/350/241/214/347/274/226/350/257/221/345/231/250.py +412 -0
  21. l0n0lc//345/274/202/345/270/270.py +474 -0
  22. l0n0lc//346/225/260/347/273/204/345/257/271/350/261/241/346/261/240.py +248 -0
  23. l0n0lc//346/226/207/344/273/266/347/256/241/347/220/206/345/231/250.py +286 -0
  24. l0n0lc//346/227/245/345/277/227/345/267/245/345/205/267.py +152 -0
  25. l0n0lc//347/261/273/345/236/213/346/216/250/346/226/255/345/267/245/345/205/267.py +352 -0
  26. l0n0lc//347/261/273/345/236/213/350/275/254/346/215/242.py +210 -0
  27. l0n0lc//347/261/273/346/224/257/346/214/201.py +372 -0
  28. l0n0lc//347/274/226/350/257/221/344/270/212/344/270/213/346/226/207.py +132 -0
  29. l0n0lc//347/274/226/350/257/221/347/256/241/347/220/206/345/231/250.py +171 -0
  30. l0n0lc//350/241/250/350/276/276/345/274/217/345/244/204/347/220/206.py +462 -0
  31. l0n0lc//350/275/254/350/257/221/345/231/250/345/267/245/345/205/267.py +49 -0
  32. l0n0lc//350/277/220/350/241/214/346/227/266/345/212/240/350/275/275.py +217 -0
  33. l0n0lc//351/200/232/347/224/250/345/267/245/345/205/267.py +149 -0
  34. l0n0lc-1.0.0.dist-info/METADATA +363 -0
  35. l0n0lc-1.0.0.dist-info/RECORD +39 -0
  36. {l0n0lc-0.8.4.dist-info → l0n0lc-1.0.0.dist-info}/WHEEL +1 -1
  37. l0n0lc-1.0.0.dist-info/entry_points.txt +2 -0
  38. {l0n0lc-0.8.4.dist-info → l0n0lc-1.0.0.dist-info}/licenses/LICENSE +0 -0
  39. l0n0lc/StdList.py +0 -24
  40. l0n0lc/StdMap.py +0 -21
  41. l0n0lc/c/345/237/272/347/241/200/345/244/204/347/220/206.py +0 -207
  42. l0n0lc/jit.py +0 -604
  43. l0n0lc//347/274/226/350/257/221.py +0 -58
  44. l0n0lc//351/200/232/347/224/250.py +0 -134
  45. l0n0lc-0.8.4.dist-info/METADATA +0 -241
  46. l0n0lc-0.8.4.dist-info/RECORD +0 -12
  47. {l0n0lc-0.8.4.dist-info → l0n0lc-1.0.0.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,462 @@
1
+ import ast
2
+ import inspect
3
+ import traceback
4
+ from typing import Any, List, Callable
5
+ from .工具 import 全局上下文, 转C字符串
6
+ from .cpp类型 import (
7
+ C变量, Cpp类型, C获取下标, C获取属性,
8
+ C函数调用, C布尔,
9
+ )
10
+ from .容器构建器 import 容器构建器
11
+ from .异常 import 类型不一致错误
12
+ from .ast访问者 import *
13
+ from .基础混入 import 错误处理混入, 类型处理混入, 参数处理混入
14
+
15
+ class 表达式访问者(错误处理混入, 类型处理混入, 参数处理混入):
16
+ """处理表达式求值的访问者"""
17
+
18
+ def __init__(self, transpiler):
19
+ self.transpiler = transpiler
20
+
21
+ def 获取值(self, value, is_type_annotation=False):
22
+ """
23
+ 将 AST 节点转换为对应的值或 C++ 表达式字符串。
24
+ 处理常量、变量名、属性访问、函数调用、运算表达式等。
25
+ """
26
+ if isinstance(value, ast.Constant):
27
+ if isinstance(value.value, bool):
28
+ return C布尔(value.value)
29
+ if isinstance(value.value, str):
30
+ # 如果是类型注解上下文,返回原始字符串而不是C字符串
31
+ if is_type_annotation:
32
+ return value.value
33
+ return CString常量(value.value)
34
+ if isinstance(value.value, bytes):
35
+ return CBytes常量(value.value)
36
+ if isinstance(value.value, int):
37
+ return CInt常量(value.value)
38
+ if isinstance(value.value, float):
39
+ return CFloat常量(value.value)
40
+ return value.value
41
+
42
+ if isinstance(value, ast.Name):
43
+ # 1. 查找 Python 内置对象
44
+ v = 全局上下文.Python内置映射.get(value.id)
45
+ if v is not None:
46
+ return v
47
+ # 2. 查找本地 Python 变量 (直接执行时使用)
48
+ v = self.transpiler.本地变量.get(value.id)
49
+ if v is not None:
50
+ return v
51
+ # 3. 查找 C 变量
52
+ v = self.transpiler.获取C变量(value.id)
53
+ if v is not None:
54
+ return v
55
+ # 4. 查找参数变量
56
+ v = self.transpiler.参数变量.get(value.id)
57
+ if v is not None:
58
+ return v
59
+ # 5. 查找全局变量
60
+ v = self.transpiler.全局变量.get(value.id)
61
+ if v is not None:
62
+ return v
63
+
64
+ # 如果所有地方都找不到该变量,抛出错误
65
+ self.抛出错误(f"未定义的变量 '{value.id}'", value)
66
+
67
+ if isinstance(value, ast.Attribute):
68
+ obj = self.获取值(value.value)
69
+
70
+ # Prioritize explicitly defined methods on CVariable wrappers (e.g. standard_set.add)
71
+ if isinstance(obj, C变量) and hasattr(obj, value.attr):
72
+ attr = getattr(obj, value.attr)
73
+ if inspect.ismethod(attr):
74
+ return attr
75
+
76
+ # 检查是否是类属性访问(静态成员或静态方法)
77
+ if isinstance(value.value, ast.Name) and inspect.isclass(obj):
78
+ class_name = value.value.id
79
+ attr_name = value.attr
80
+ attr_obj = getattr(obj, attr_name, None)
81
+
82
+ # 检查这个类是否有这个静态成员
83
+ if self.transpiler.是否为类 and class_name == self.transpiler.函数名 and attr_name in self.transpiler.类静态成员:
84
+ # 返回静态成员访问:ClassName::static_member
85
+ return f"{class_name}::{attr_name}"
86
+ elif hasattr(obj, attr_name):
87
+ if inspect.isfunction(attr_obj) or inspect.ismethod(attr_obj):
88
+ # 静态方法,返回C静态调用对象
89
+ return C静态调用(class_name, attr_name)
90
+ else:
91
+ # 其他静态成员
92
+ return f"{class_name}::{attr_name}"
93
+
94
+ if isinstance(obj, (C变量, Cpp类型)):
95
+ return C获取属性(obj, value.attr)
96
+ if obj is None:
97
+ self.抛出错误(f'Name not found: {value.value}', value)
98
+ return getattr(obj, value.attr)
99
+
100
+ if isinstance(value, ast.UnaryOp):
101
+ operand = self.获取值(value.operand)
102
+ if isinstance(value.op, ast.UAdd):
103
+ return f'(+{operand})'
104
+ if isinstance(value.op, ast.USub):
105
+ return f'(-{operand})'
106
+ if isinstance(value.op, ast.Not):
107
+ return f'(!{operand})'
108
+ if isinstance(value.op, ast.Invert):
109
+ return f'(~{operand})'
110
+
111
+ if isinstance(value, ast.BoolOp):
112
+ values = [f'({self.获取值(v)})' for v in value.values]
113
+ if isinstance(value.op, ast.And):
114
+ return '&&'.join(values)
115
+ if isinstance(value.op, ast.Or):
116
+ return '||'.join(values)
117
+
118
+ if isinstance(value, ast.IfExp):
119
+ test = self.获取值(value.test)
120
+ body = self.获取值(value.body)
121
+ orelse = self.获取值(value.orelse)
122
+ return f'(({test}) ? ({body}) : ({orelse}))'
123
+
124
+ if isinstance(value, ast.Compare):
125
+ from .ast访问者 import AST访问者基类
126
+ visitor = AST访问者基类(self.transpiler)
127
+ return visitor.计算比较(value)
128
+
129
+ if isinstance(value, ast.BinOp):
130
+ from .ast访问者 import AST访问者基类
131
+ visitor = AST访问者基类(self.transpiler)
132
+ return visitor.计算二元运算(value)
133
+
134
+ # 处理 List 字面量
135
+ if isinstance(value, ast.List):
136
+ l = [self.获取值(e) for e in value.elts]
137
+ try:
138
+ return 容器构建器._从列表构建初始化列表(l)
139
+ except 类型不一致错误 as e:
140
+ self.抛出错误(str(e), value)
141
+
142
+ # 处理 Tuple 字面量
143
+ if isinstance(value, ast.Tuple):
144
+ l = [self.获取值(e) for e in value.elts]
145
+ if not self.transpiler.正在构建参数:
146
+ # Try to make a vector (homogenous)
147
+ try:
148
+ return 容器构建器._从列表构建初始化列表(l)
149
+ except 类型不一致错误:
150
+ pass
151
+
152
+ # Fallback to std::pair or std::tuple
153
+ self.transpiler.包含头文件.add('<tuple>')
154
+ self.transpiler.包含头文件.add('<utility>')
155
+ elements = [str(x) for x in l]
156
+ if len(elements) == 2:
157
+ return f'std::make_pair({elements[0]}, {elements[1]})'
158
+ return f'std::make_tuple({", ".join(elements)})'
159
+
160
+ self.transpiler.包含头文件.add('<tuple>')
161
+ self.transpiler.包含头文件.add('<utility>')
162
+ elements = [str(x) for x in l]
163
+ if len(elements) == 2:
164
+ return f'std::make_pair({elements[0]}, {elements[1]})'
165
+ return f'std::make_tuple({", ".join(elements)})'
166
+
167
+ # 处理 Dict 字面量
168
+ if isinstance(value, ast.Dict):
169
+ d = {self.获取值(k): self.获取值(v)
170
+ for k, v in zip(value.keys, value.values)}
171
+ try:
172
+ return 容器构建器._从字典构建初始化列表(d)
173
+ except 类型不一致错误 as e:
174
+ self.抛出错误(str(e), value)
175
+
176
+ if isinstance(value, ast.ListComp):
177
+ return self.visit_ListComp_Expr(value)
178
+
179
+ # 处理 Set 字面量
180
+ if isinstance(value, ast.Set):
181
+ l = [self.获取值(e) for e in value.elts]
182
+ try:
183
+ return 容器构建器._从集合构建初始化列表(set(l))
184
+ except 类型不一致错误 as e:
185
+ self.抛出错误(str(e), value)
186
+
187
+ if isinstance(value, ast.Call):
188
+ return self.处理调用(value)
189
+
190
+ if isinstance(value, ast.Subscript):
191
+ return self.获取下标(value)
192
+
193
+ return None
194
+
195
+ def 获取下标(self, node: ast.Subscript):
196
+ """处理下标访问 obj[index]"""
197
+ obj = self.获取值(node.value)
198
+ slice_node = node.slice
199
+
200
+ if isinstance(slice_node, ast.Slice):
201
+ self.抛出错误("Slicing not supported for C++ vectors yet", node)
202
+
203
+ # 特殊处理:Dict[K, V] 类型注解
204
+ # 当 slice 是 Tuple 且 obj 是 Dict 时,直接处理元组元素
205
+ from typing import Dict, List, Set, Union
206
+ if obj is Dict and isinstance(slice_node, ast.Tuple):
207
+ if len(slice_node.elts) == 2:
208
+ key_type = self.获取值(slice_node.elts[0])
209
+ val_type = self.获取值(slice_node.elts[1])
210
+ return Dict[key_type, val_type]
211
+ else:
212
+ self.抛出错误("Dict type annotation requires exactly 2 type parameters", node)
213
+
214
+ index = self.获取值(slice_node)
215
+
216
+ # 处理类型提示中的下标, 如 Union[int, float]
217
+ if obj is Union:
218
+ return Union[index]
219
+ if obj is List:
220
+ return List[index]
221
+ if obj is Set:
222
+ return Set[index]
223
+ if obj is Dict:
224
+ # Dict类型注解应该总是有两个参数:Dict[K, V]
225
+ # 如果只有一个参数,这是一个不完整的类型提示
226
+ if isinstance(index, tuple) and len(index) == 2:
227
+ return Dict[index[0], index[1]]
228
+ # 如果只有一个参数,这可能是错误的类型提示
229
+ return Dict[index, Any] # type: ignore[arg-type]
230
+
231
+ # C++ 数组/Vector 下标访问
232
+ return C获取下标(obj, index)
233
+
234
+ def 处理调用(self, node: ast.Call):
235
+ func = self.获取值(node.func)
236
+
237
+ # 0. 处理 super() 调用
238
+ if isinstance(node.func, ast.Name) and node.func.id == 'super':
239
+ from .ast访问者 import AST访问者基类
240
+ visitor = AST访问者基类(self.transpiler)
241
+ return visitor.处理super调用(node)
242
+
243
+ # 1. 类型实例化 (例如 CppVectorInt())
244
+ if inspect.isclass(func):
245
+ c_type_map = 全局上下文.类型映射表.get(func)
246
+ if c_type_map:
247
+ self.transpiler.包含头文件.update(c_type_map.包含目录)
248
+ self.transpiler.链接库.update(c_type_map.库)
249
+ self.transpiler.库搜索目录.update(c_type_map.库目录)
250
+ args_str = self.构建参数字符串(node.args)
251
+ # 构造函数调用
252
+ return C函数调用(c_type_map.目标类型, args_str, c_type_map.目标类型)
253
+
254
+ # 2. 直接调用 (例如 range(), print()) - 缓存在 GlobalContext 中
255
+ if func in 全局上下文.直接调用函数集:
256
+ args = [self.获取值(arg) for arg in node.args]
257
+ self.transpiler.正在直接调用 = True
258
+ try:
259
+ return func(*args)
260
+ except Exception as e:
261
+ # 保留原始异常信息和堆栈跟踪
262
+ error_msg = f"Error during direct call to {func.__name__}: {str(e)}"
263
+ if traceback.format_exc():
264
+ error_msg += f"\nOriginal traceback:\n{traceback.format_exc()}"
265
+ self.抛出错误(error_msg, node)
266
+
267
+ # 2b. Special builtin handling: print
268
+ if func == print:
269
+ self.transpiler.包含头文件.add('<iostream>')
270
+ arg_vals = [self.获取值(arg) for arg in node.args]
271
+
272
+ # Create a C++ expression using a lambda to print and return 0
273
+ print_stmts = []
274
+ for val in arg_vals:
275
+ print_stmts.append(f'std::cout << {val} << " ";')
276
+ print_stmts.append('std::cout << std::endl;')
277
+
278
+ joined_stmts = " ".join(print_stmts)
279
+ code = f'([&](){{ {joined_stmts} return 0; }}())'
280
+ return code
281
+
282
+ # 2c. Special builtin handling: len
283
+ if func == len:
284
+ if len(node.args) != 1:
285
+ self.抛出错误("len() takes exactly one argument", node)
286
+ arg_val = self.获取值(node.args[0])
287
+ return f'({arg_val}.size())'
288
+
289
+ # 3. 映射的 C++ 函数
290
+ mapped_func = 全局上下文.函数映射表.get(func)
291
+ if mapped_func:
292
+ args = [self.获取值(arg) for arg in node.args]
293
+ self.transpiler.包含头文件.update(mapped_func.包含目录)
294
+ self.transpiler.链接库.update(mapped_func.库)
295
+ self.transpiler.库搜索目录.update(mapped_func.库目录)
296
+
297
+ # 如果目标是可调用的 (如宏函数生成器),则直接调用生成代码
298
+ if callable(mapped_func.目标函数):
299
+ return mapped_func.目标函数(*args)
300
+ return C函数调用(mapped_func.目标函数, self.构建参数字符串(node.args))
301
+
302
+ if not callable(func) and not isinstance(func, C获取属性) and not isinstance(func, C静态调用):
303
+ self.抛出错误(
304
+ f"Cannot call object '{ast.dump(node.func)}'", node)
305
+
306
+ # Handle bound methods of CVariables (e.g. s.add(x))
307
+ if hasattr(func, '__self__') and isinstance(func.__self__, C变量): # type: ignore
308
+ args = [self.获取值(arg) for arg in node.args]
309
+ return func(*args) # type: ignore
310
+
311
+ if node.keywords:
312
+ self.抛出错误("Keyword arguments not supported in C++ translation", node)
313
+
314
+ args_str = self.构建参数字符串(node.args)
315
+
316
+ # 4. 调用其他 JIT 编译的函数
317
+ if isinstance(func, type(self.transpiler)):
318
+ self.transpiler.依赖函数.append(func)
319
+
320
+ # 确保依赖函数已被分析(用于获取列表参数映射等信息)
321
+ # 使用 tell() 检查缓冲区是否有内容
322
+ if func.代码缓冲区.tell() == 0 and not func.是否为类:
323
+ func.分析()
324
+
325
+ # 检查是否有列表参数需要特殊处理
326
+ args_list = []
327
+ for i, arg_node in enumerate(node.args):
328
+ arg_val = self.获取值(arg_node)
329
+
330
+ # 检查这个参数在目标函数中是否是列表参数
331
+ param_name = None
332
+ if i < len(func.参数名称):
333
+ param_name = func.参数名称[i]
334
+
335
+ if param_name and param_name in func.列表参数映射:
336
+ # 如果是列表参数,需要转换为指针和长度
337
+ args_list.append(f"{arg_val}.data()")
338
+ args_list.append(f"static_cast<int64_t>({arg_val}.size())")
339
+ else:
340
+ args_list.append(str(arg_val))
341
+
342
+ return C函数调用(func.C函数名, ", ".join(args_list))
343
+ # 5. C++ 对象方法调用
344
+ elif isinstance(func, C获取属性):
345
+ return C函数调用(func, args_str)
346
+ # 7. 静态方法调用
347
+ elif isinstance(func, C静态调用):
348
+ # 查找对应的类并添加为依赖
349
+ class_obj = self.transpiler.全局变量.get(func.class_name)
350
+ if class_obj and inspect.isclass(class_obj):
351
+ dep_name = func.class_name
352
+ if dep_name not in 全局上下文.编译栈:
353
+ 全局上下文.编译栈.add(dep_name)
354
+ try:
355
+ dep_compiler = type(self.transpiler)(
356
+ class_obj, self.transpiler.编译器)
357
+ dep_compiler.编译()
358
+ self.transpiler.依赖函数.append(dep_compiler)
359
+ finally:
360
+ 全局上下文.编译栈.discard(dep_name)
361
+ return C函数调用(func, args_str)
362
+ # 6. super() method calls
363
+ elif isinstance(func, SuperMethodCall):
364
+ # SuperMethodCall returns a C++ code string when called
365
+ return func(*[self.获取值(arg) for arg in node.args])
366
+ else:
367
+ # 7. 如果依赖是普通 Python 函数,尝试递归编译
368
+ try:
369
+ # 对于类构造函数调用,检查是否是当前正在编译的类
370
+ if inspect.isclass(func):
371
+ class_name = func.__name__
372
+ # 使用全局编译栈来避免递归
373
+ if class_name in 全局上下文.编译栈:
374
+ # 如果已经在编译中,直接生成构造函数调用
375
+ return C函数调用(class_name, args_str, class_name)
376
+
377
+ # 检查是否已经在编译这个函数/类(避免循环依赖)
378
+ if hasattr(func, '__name__'):
379
+ dep_name = func.__name__
380
+ elif hasattr(func, '__class__'):
381
+ dep_name = func.__class__.__name__
382
+ else:
383
+ dep_name = str(func)
384
+
385
+ # 检查是否在全局编译栈中
386
+ if dep_name in 全局上下文.编译栈:
387
+ # 如果已经在编译中,直接使用名称而不重新编译
388
+ return C函数调用(dep_name, args_str)
389
+
390
+ 全局上下文.编译栈.add(dep_name)
391
+ try:
392
+ dep_compiler = type(self.transpiler)(
393
+ func, self.transpiler.编译器)
394
+ dep_compiler.编译()
395
+ self.transpiler.依赖函数.append(dep_compiler)
396
+ return C函数调用(dep_compiler.C函数名, args_str)
397
+ finally:
398
+ 全局上下文.编译栈.discard(dep_name)
399
+ except Exception as e:
400
+ # 保留原始异常信息和堆栈跟踪
401
+ error_msg = f"Failed to compile dependency {func.__name__}: {str(e)}"
402
+ if traceback.format_exc():
403
+ error_msg += f"\nOriginal traceback:\n{traceback.format_exc()}"
404
+ self.抛出错误(error_msg, node)
405
+
406
+
407
+ def visit_ListComp_Expr(self, node: ast.ListComp):
408
+ if len(node.generators) != 1:
409
+ self.抛出错误(
410
+ "Nested List comprehensions not supported yet", node)
411
+
412
+ gen = node.generators[0]
413
+ if not isinstance(gen.target, ast.Name):
414
+ self.抛出错误(
415
+ "List comprehension target must be a simple name", node)
416
+
417
+ # 我们已经验证了gen.target是ast.Name类型,所以可以安全访问.id属性
418
+ target_name = gen.target.id # type: ignore[attr-defined]
419
+ iter_val = self.获取值(gen.iter)
420
+
421
+ # Enter scope to register loop variable for resolution (resolved as C++ lambda arg)
422
+ self.transpiler.进入作用域()
423
+ dummy_tgt = C变量('auto', target_name, False)
424
+ dummy_tgt.C名称 = target_name # Ensure C name matches lambda arg
425
+ self.transpiler.添加C变量(dummy_tgt)
426
+
427
+ elt_val = self.获取值(node.elt)
428
+
429
+ # Filter
430
+ filter_expr = 'true'
431
+ if gen.ifs:
432
+ conditions = [f'({self.获取值(cond)})' for cond in gen.ifs]
433
+ filter_expr = ' && '.join(conditions)
434
+
435
+ self.transpiler.退出作用域()
436
+
437
+ # We need type traits headers
438
+ self.transpiler.包含头文件.add('<type_traits>')
439
+ self.transpiler.包含头文件.add('<vector>')
440
+
441
+ code = f"""
442
+ ([&](){{
443
+ auto&& _iter = {iter_val};
444
+ using _IterType = std::decay_t<decltype(_iter)>;
445
+ using _InType = typename _IterType::value_type;
446
+
447
+ auto _mapper = [&](_InType {target_name}) {{ return {elt_val}; }};
448
+ auto _filter = [&](_InType {target_name}) {{ return {filter_expr}; }};
449
+
450
+ using _OutType = std::invoke_result_t<decltype(_mapper), _InType>;
451
+ std::vector<_OutType> _result;
452
+
453
+ for (auto&& _item : _iter) {{
454
+ if (_filter(_item)) {{
455
+ _result.push_back(_mapper(_item));
456
+ }}
457
+ }}
458
+ return _result;
459
+ }}())
460
+ """
461
+ # Collapse whitespace for cleaner output?
462
+ return code.replace('\n', ' ').strip()
@@ -0,0 +1,49 @@
1
+ """
2
+ 转译器工具模块
3
+
4
+ 提供转译器相关的通用工具函数。
5
+ 消除各模块中的重复代码。
6
+ """
7
+
8
+ import inspect
9
+ from typing import Optional, TYPE_CHECKING
10
+
11
+ if TYPE_CHECKING:
12
+ from .Py转Cpp转译器 import Py转Cpp转译器
13
+
14
+
15
+ def 获取当前transpiler() -> Optional["Py转Cpp转译器"]:
16
+ """
17
+ 从调用栈中获取当前转译器实例
18
+
19
+ 通过检查调用栈中的局部变量来获取 transpiler 实例。
20
+ 用于在标准库容器类(如 std_vector、std_map)中访问转译器。
21
+
22
+ Returns:
23
+ 找到的转译器实例,如果未找到返回 None
24
+ """
25
+ for frame_info in inspect.stack():
26
+ frame = frame_info.frame
27
+ if 'transpiler' in frame.f_locals:
28
+ return frame.f_locals['transpiler']
29
+ if 'self' in frame.f_locals and hasattr(frame.f_locals['self'], 'transpiler'):
30
+ return frame.f_locals['self'].transpiler
31
+ return None
32
+
33
+
34
+ def 获取当前转译器或抛出() -> "Py转Cpp转译器":
35
+ """
36
+ 从调用栈中获取当前转译器实例
37
+
38
+ 类似于 `获取当前transpiler`,但如果未找到会抛出异常。
39
+
40
+ Returns:
41
+ 找到的转译器实例
42
+
43
+ Raises:
44
+ RuntimeError: 如果未找到转译器实例
45
+ """
46
+ transpiler = 获取当前transpiler()
47
+ if transpiler is None:
48
+ raise RuntimeError("无法获取转译器实例:不在有效的转译上下文中")
49
+ return transpiler