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.
- l0n0lc/Py/350/275/254Cpp/350/275/254/350/257/221/345/231/250.py +579 -0
- l0n0lc/__init__.py +75 -6
- l0n0lc/aot/347/274/226/350/257/221.py +679 -0
- l0n0lc/ast/350/256/277/351/227/256/350/200/205.py +599 -0
- l0n0lc/cpp/347/261/273/345/236/213.py +330 -0
- l0n0lc/cpp/347/274/226/350/257/221/345/231/250.py +317 -0
- l0n0lc/simd/344/274/230/345/214/226.py +260 -0
- l0n0lc/std_map.py +153 -0
- l0n0lc/std_set.py +185 -0
- l0n0lc/std_vector.py +96 -0
- l0n0lc//344/273/243/347/240/201/344/274/230/345/214/226.py +302 -0
- l0n0lc//344/273/243/347/240/201/347/224/237/346/210/220.py +546 -0
- l0n0lc//344/276/235/350/265/226/346/263/250/345/205/245.py +155 -0
- l0n0lc//345/215/263/346/227/266/347/274/226/350/257/221.py +192 -0
- l0n0lc//345/217/230/351/207/217/347/256/241/347/220/206/345/231/250.py +123 -0
- l0n0lc//345/237/272/347/241/200/346/230/240/345/260/204.py +103 -0
- l0n0lc//345/237/272/347/241/200/346/267/267/345/205/245.py +147 -0
- l0n0lc//345/256/271/345/231/250/346/236/204/345/273/272/345/231/250.py +214 -0
- l0n0lc//345/267/245/345/205/267.py +285 -0
- l0n0lc//345/271/266/350/241/214/347/274/226/350/257/221/345/231/250.py +412 -0
- l0n0lc//345/274/202/345/270/270.py +474 -0
- l0n0lc//346/225/260/347/273/204/345/257/271/350/261/241/346/261/240.py +248 -0
- l0n0lc//346/226/207/344/273/266/347/256/241/347/220/206/345/231/250.py +286 -0
- l0n0lc//346/227/245/345/277/227/345/267/245/345/205/267.py +152 -0
- l0n0lc//347/261/273/345/236/213/346/216/250/346/226/255/345/267/245/345/205/267.py +352 -0
- l0n0lc//347/261/273/345/236/213/350/275/254/346/215/242.py +210 -0
- l0n0lc//347/261/273/346/224/257/346/214/201.py +372 -0
- l0n0lc//347/274/226/350/257/221/344/270/212/344/270/213/346/226/207.py +132 -0
- l0n0lc//347/274/226/350/257/221/347/256/241/347/220/206/345/231/250.py +171 -0
- l0n0lc//350/241/250/350/276/276/345/274/217/345/244/204/347/220/206.py +462 -0
- l0n0lc//350/275/254/350/257/221/345/231/250/345/267/245/345/205/267.py +49 -0
- l0n0lc//350/277/220/350/241/214/346/227/266/345/212/240/350/275/275.py +217 -0
- l0n0lc//351/200/232/347/224/250/345/267/245/345/205/267.py +149 -0
- l0n0lc-1.0.0.dist-info/METADATA +363 -0
- l0n0lc-1.0.0.dist-info/RECORD +39 -0
- {l0n0lc-0.8.4.dist-info → l0n0lc-1.0.0.dist-info}/WHEEL +1 -1
- l0n0lc-1.0.0.dist-info/entry_points.txt +2 -0
- {l0n0lc-0.8.4.dist-info → l0n0lc-1.0.0.dist-info}/licenses/LICENSE +0 -0
- l0n0lc/StdList.py +0 -24
- l0n0lc/StdMap.py +0 -21
- l0n0lc/c/345/237/272/347/241/200/345/244/204/347/220/206.py +0 -207
- l0n0lc/jit.py +0 -604
- l0n0lc//347/274/226/350/257/221.py +0 -58
- l0n0lc//351/200/232/347/224/250.py +0 -134
- l0n0lc-0.8.4.dist-info/METADATA +0 -241
- l0n0lc-0.8.4.dist-info/RECORD +0 -12
- {l0n0lc-0.8.4.dist-info → l0n0lc-1.0.0.dist-info}/top_level.txt +0 -0
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
"""
|
|
2
|
+
基础混入类模块 - 提供可重用的功能混入
|
|
3
|
+
用于统一错误处理、类型处理等通用功能
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import ast
|
|
7
|
+
from typing import Any, Union
|
|
8
|
+
from .通用工具 import (
|
|
9
|
+
统一抛出错误, 解析自定义类型, 统一异常处理,
|
|
10
|
+
构建参数字符串, 处理函数参数, 生成函数调用,
|
|
11
|
+
验证AST节点类型, 获取节点行号
|
|
12
|
+
)
|
|
13
|
+
from .异常 import 错误处理器
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class 错误处理混入:
|
|
17
|
+
"""错误处理混入类 - 提供统一的错误处理功能"""
|
|
18
|
+
|
|
19
|
+
def 抛出错误(self, message: str, node: Union[ast.stmt, ast.expr, ast.arg, ast.arguments]):
|
|
20
|
+
"""
|
|
21
|
+
抛出带行号的编译错误
|
|
22
|
+
|
|
23
|
+
Args:
|
|
24
|
+
message: 错误消息
|
|
25
|
+
node: AST节点,用于获取行号
|
|
26
|
+
"""
|
|
27
|
+
# 获取源代码
|
|
28
|
+
源代码 = getattr(self, '源代码', None)
|
|
29
|
+
# 使用统一的错误处理器
|
|
30
|
+
错误处理器.抛出错误(message, node, 源代码)
|
|
31
|
+
|
|
32
|
+
def 处理异常(self, e: Exception, node: Union[ast.stmt, ast.expr, ast.arg, ast.arguments], context_msg: str = ""):
|
|
33
|
+
"""
|
|
34
|
+
统一异常处理
|
|
35
|
+
|
|
36
|
+
Args:
|
|
37
|
+
e: 异常对象
|
|
38
|
+
node: AST节点
|
|
39
|
+
context_msg: 上下文消息
|
|
40
|
+
"""
|
|
41
|
+
统一异常处理(e, self, node, context_msg)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class 类型处理混入:
|
|
45
|
+
"""类型处理混入类 - 提供统一的类型处理功能"""
|
|
46
|
+
|
|
47
|
+
def 解析类型(self, py_type) -> str:
|
|
48
|
+
"""
|
|
49
|
+
解析Python类型为C++类型
|
|
50
|
+
|
|
51
|
+
Args:
|
|
52
|
+
py_type: Python类型对象
|
|
53
|
+
|
|
54
|
+
Returns:
|
|
55
|
+
str: C++类型名称
|
|
56
|
+
"""
|
|
57
|
+
return 解析自定义类型(py_type, self)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class 参数处理混入:
|
|
61
|
+
"""参数处理混入类 - 提供统一的参数处理功能"""
|
|
62
|
+
|
|
63
|
+
def 构建参数字符串(self, args: list) -> str:
|
|
64
|
+
"""
|
|
65
|
+
构建参数字符串
|
|
66
|
+
|
|
67
|
+
Args:
|
|
68
|
+
args: 参数列表
|
|
69
|
+
|
|
70
|
+
Returns:
|
|
71
|
+
str: 逗号分隔的参数字符串
|
|
72
|
+
"""
|
|
73
|
+
获取值函数 = getattr(self, '获取值', None)
|
|
74
|
+
if 获取值函数 is None:
|
|
75
|
+
获取值函数 = getattr(getattr(self, 'transpiler', None), '获取值', None)
|
|
76
|
+
|
|
77
|
+
if 获取值函数 is None:
|
|
78
|
+
raise AttributeError("无法找到'获取值'函数,请确保在类或transpiler中定义了此方法")
|
|
79
|
+
|
|
80
|
+
return 构建参数字符串(args, 获取值函数)
|
|
81
|
+
|
|
82
|
+
def 处理函数参数(self, node_args) -> list:
|
|
83
|
+
"""
|
|
84
|
+
处理函数参数
|
|
85
|
+
|
|
86
|
+
Args:
|
|
87
|
+
node_args: AST参数节点
|
|
88
|
+
|
|
89
|
+
Returns:
|
|
90
|
+
list: 处理后的参数列表
|
|
91
|
+
"""
|
|
92
|
+
获取值函数 = getattr(self, '获取值', None)
|
|
93
|
+
if 获取值函数 is None:
|
|
94
|
+
获取值函数 = getattr(getattr(self, 'transpiler', None), '获取值', None)
|
|
95
|
+
|
|
96
|
+
if 获取值函数 is None:
|
|
97
|
+
raise AttributeError("无法找到'获取值'函数,请确保在类或transpiler中定义了此方法")
|
|
98
|
+
|
|
99
|
+
return 处理函数参数(node_args, 获取值函数)
|
|
100
|
+
|
|
101
|
+
def 生成函数调用(self, func_name: str, args_str: str):
|
|
102
|
+
"""
|
|
103
|
+
生成函数调用
|
|
104
|
+
|
|
105
|
+
Args:
|
|
106
|
+
func_name: 函数名
|
|
107
|
+
args_str: 参数字符串
|
|
108
|
+
|
|
109
|
+
Returns:
|
|
110
|
+
C函数调用对象
|
|
111
|
+
"""
|
|
112
|
+
return 生成函数调用(func_name, args_str)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
class AST验证混入:
|
|
116
|
+
"""AST验证混入类 - 提供AST节点验证功能"""
|
|
117
|
+
|
|
118
|
+
def 验证节点类型(self, node, expected_type, error_msg: str):
|
|
119
|
+
"""
|
|
120
|
+
验证AST节点类型
|
|
121
|
+
|
|
122
|
+
Args:
|
|
123
|
+
node: AST节点
|
|
124
|
+
expected_type: 期望的类型
|
|
125
|
+
error_msg: 错误消息
|
|
126
|
+
"""
|
|
127
|
+
验证AST节点类型(node, expected_type, self, error_msg)
|
|
128
|
+
|
|
129
|
+
def 获取行号(self, node) -> str:
|
|
130
|
+
"""
|
|
131
|
+
获取节点行号
|
|
132
|
+
|
|
133
|
+
Args:
|
|
134
|
+
node: AST节点
|
|
135
|
+
|
|
136
|
+
Returns:
|
|
137
|
+
str: 行号字符串
|
|
138
|
+
"""
|
|
139
|
+
return 获取节点行号(node)
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
class 通用访问者混入(错误处理混入, 类型处理混入, 参数处理混入, AST验证混入):
|
|
143
|
+
"""
|
|
144
|
+
通用访问者混入类 - 组合所有常用功能
|
|
145
|
+
适用于大多数AST访问者类
|
|
146
|
+
"""
|
|
147
|
+
pass
|
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
"""
|
|
2
|
+
容器构建器模块 - 统一处理容器初始化逻辑
|
|
3
|
+
消除从列表、字典、集合构建初始化列表的重复代码
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from typing import List, Dict, Set, Any, Union
|
|
7
|
+
from .类型转换 import 类型转换器
|
|
8
|
+
from .异常 import 类型不一致错误
|
|
9
|
+
|
|
10
|
+
# 安全限制配置
|
|
11
|
+
MAX_CONTAINER_SIZE = 10**6 # 最大容器大小
|
|
12
|
+
MAX_STRING_LENGTH = 10**4 # 最大字符串长度
|
|
13
|
+
MAX_NESTING_DEPTH = 100 # 最大嵌套深度
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class 容器构建器:
|
|
17
|
+
"""统一的容器构建器类"""
|
|
18
|
+
|
|
19
|
+
@staticmethod
|
|
20
|
+
def 构建初始化列表(container: Union[List[Any], Dict[Any, Any], Set[Any]], container_type: str):
|
|
21
|
+
"""
|
|
22
|
+
统一的容器初始化列表构建逻辑
|
|
23
|
+
|
|
24
|
+
Args:
|
|
25
|
+
container: 容器对象(list、dict、set)
|
|
26
|
+
container_type: 容器类型("list"、"dict"、"set")
|
|
27
|
+
|
|
28
|
+
Returns:
|
|
29
|
+
对应的初始化列表对象
|
|
30
|
+
"""
|
|
31
|
+
# 验证输入参数
|
|
32
|
+
if container is None:
|
|
33
|
+
raise ValueError(f"{container_type} container cannot be None")
|
|
34
|
+
|
|
35
|
+
# 检查容器大小限制
|
|
36
|
+
container_size = len(container)
|
|
37
|
+
if container_size > MAX_CONTAINER_SIZE:
|
|
38
|
+
raise ValueError(
|
|
39
|
+
f"{container_type} size {container_size} exceeds maximum limit {MAX_CONTAINER_SIZE}"
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
# 递归检查嵌套深度
|
|
43
|
+
容器构建器._检查嵌套深度(container, current_depth=0)
|
|
44
|
+
|
|
45
|
+
if container_type == "list":
|
|
46
|
+
return 容器构建器._从列表构建初始化列表(list(container))
|
|
47
|
+
elif container_type == "dict":
|
|
48
|
+
return 容器构建器._从字典构建初始化列表(dict(container))
|
|
49
|
+
elif container_type == "set":
|
|
50
|
+
return 容器构建器._从集合构建初始化列表(set(container))
|
|
51
|
+
else:
|
|
52
|
+
raise ValueError(f"Unsupported container type: {container_type}")
|
|
53
|
+
|
|
54
|
+
@staticmethod
|
|
55
|
+
def _从列表构建初始化列表(value: List[Any]):
|
|
56
|
+
"""
|
|
57
|
+
将 Python List 转换为 C++ 初始化列表字符串
|
|
58
|
+
"""
|
|
59
|
+
from .cpp类型 import 列表初始化列表
|
|
60
|
+
|
|
61
|
+
if not value:
|
|
62
|
+
return 列表初始化列表("{}", "auto", 0)
|
|
63
|
+
|
|
64
|
+
data_types = []
|
|
65
|
+
init_items = []
|
|
66
|
+
for v in value:
|
|
67
|
+
dtype = type(v)
|
|
68
|
+
data_types.append(dtype)
|
|
69
|
+
init_items.append(str(v))
|
|
70
|
+
|
|
71
|
+
# 构建初始化列表字符串
|
|
72
|
+
init_list_str = "{" + ",".join(init_items) + "}"
|
|
73
|
+
|
|
74
|
+
# 一致性检查
|
|
75
|
+
容器构建器._检查类型一致性(data_types, "List elements")
|
|
76
|
+
|
|
77
|
+
type_name = 容器构建器._推断元素类型(value, data_types[0])
|
|
78
|
+
|
|
79
|
+
from .cpp类型 import 列表初始化列表
|
|
80
|
+
return 列表初始化列表(init_list_str, type_name, len(value))
|
|
81
|
+
|
|
82
|
+
@staticmethod
|
|
83
|
+
def _从字典构建初始化列表(value: Dict[Any, Any]):
|
|
84
|
+
"""
|
|
85
|
+
将 Python Dict 转换为 C++ 初始化列表字符串
|
|
86
|
+
"""
|
|
87
|
+
from .cpp类型 import 字典初始化列表
|
|
88
|
+
|
|
89
|
+
if not value:
|
|
90
|
+
return 字典初始化列表("{}", "auto", "auto")
|
|
91
|
+
|
|
92
|
+
code_items = []
|
|
93
|
+
key_types = []
|
|
94
|
+
value_types = []
|
|
95
|
+
|
|
96
|
+
# 需要捕获第一个 key/value 实例来解析类型
|
|
97
|
+
first_key = None
|
|
98
|
+
first_value = None
|
|
99
|
+
|
|
100
|
+
for i, (k, v) in enumerate(value.items()):
|
|
101
|
+
if i == 0:
|
|
102
|
+
first_key = k
|
|
103
|
+
first_value = v
|
|
104
|
+
key_type = type(k)
|
|
105
|
+
value_type = type(v)
|
|
106
|
+
key_types.append(key_type)
|
|
107
|
+
value_types.append(value_type)
|
|
108
|
+
code_items.append(f"{{ {k}, {v} }}")
|
|
109
|
+
|
|
110
|
+
# 一致性检查
|
|
111
|
+
容器构建器._检查类型一致性(key_types, "Dict keys")
|
|
112
|
+
容器构建器._检查类型一致性(value_types, "Dict values")
|
|
113
|
+
|
|
114
|
+
# 推断 key 和 value 的 C++ 类型
|
|
115
|
+
key_type_name = 容器构建器._推断元素类型([first_key], type(first_key))
|
|
116
|
+
value_type_name = 容器构建器._推断元素类型([first_value], type(first_value))
|
|
117
|
+
|
|
118
|
+
init_list_str = "{" + ",".join(code_items) + "}"
|
|
119
|
+
|
|
120
|
+
from .cpp类型 import 字典初始化列表
|
|
121
|
+
return 字典初始化列表(init_list_str, key_type_name, value_type_name)
|
|
122
|
+
|
|
123
|
+
@staticmethod
|
|
124
|
+
def _从集合构建初始化列表(value: Set[Any]):
|
|
125
|
+
"""
|
|
126
|
+
将 Python Set 转换为 C++ 初始化列表字符串
|
|
127
|
+
"""
|
|
128
|
+
from .cpp类型 import 集合初始化列表
|
|
129
|
+
|
|
130
|
+
if not value:
|
|
131
|
+
return 集合初始化列表("{}", "auto")
|
|
132
|
+
|
|
133
|
+
init_items = []
|
|
134
|
+
data_types = []
|
|
135
|
+
for v in value:
|
|
136
|
+
data_types.append(type(v))
|
|
137
|
+
init_items.append(str(v))
|
|
138
|
+
|
|
139
|
+
# 一致性检查
|
|
140
|
+
容器构建器._检查类型一致性(data_types, "Set elements")
|
|
141
|
+
|
|
142
|
+
type_name = 容器构建器._推断元素类型(value, data_types[0])
|
|
143
|
+
|
|
144
|
+
init_list_str = "{" + ",".join(init_items) + "}"
|
|
145
|
+
|
|
146
|
+
from .cpp类型 import 集合初始化列表
|
|
147
|
+
return 集合初始化列表(init_list_str, type_name)
|
|
148
|
+
|
|
149
|
+
@staticmethod
|
|
150
|
+
def _检查类型一致性(data_types: List[type], error_context: str):
|
|
151
|
+
"""
|
|
152
|
+
检查类型一致性
|
|
153
|
+
|
|
154
|
+
Args:
|
|
155
|
+
data_types: 类型列表
|
|
156
|
+
error_context: 错误上下文信息
|
|
157
|
+
"""
|
|
158
|
+
if not data_types:
|
|
159
|
+
return
|
|
160
|
+
|
|
161
|
+
first_type = data_types[0]
|
|
162
|
+
if not all(t == first_type for t in data_types):
|
|
163
|
+
raise 类型不一致错误(
|
|
164
|
+
f"{error_context} must have same type, got {set(data_types)}"
|
|
165
|
+
)
|
|
166
|
+
|
|
167
|
+
@staticmethod
|
|
168
|
+
def _检查嵌套深度(container: Any, current_depth: int = 0) -> None:
|
|
169
|
+
"""
|
|
170
|
+
递归检查容器嵌套深度,防止过深嵌套导致栈溢出
|
|
171
|
+
|
|
172
|
+
Args:
|
|
173
|
+
container: 要检查的容器对象
|
|
174
|
+
current_depth: 当前嵌套深度
|
|
175
|
+
|
|
176
|
+
Raises:
|
|
177
|
+
ValueError: 当嵌套深度超过限制时
|
|
178
|
+
"""
|
|
179
|
+
if current_depth > MAX_NESTING_DEPTH:
|
|
180
|
+
raise ValueError(f"容器嵌套深度 {current_depth} 超过限制 {MAX_NESTING_DEPTH}")
|
|
181
|
+
|
|
182
|
+
# 如果是字符串,检查长度限制
|
|
183
|
+
if isinstance(container, str):
|
|
184
|
+
if len(container) > MAX_STRING_LENGTH:
|
|
185
|
+
raise ValueError(f"字符串长度 {len(container)} 超过限制 {MAX_STRING_LENGTH}")
|
|
186
|
+
return
|
|
187
|
+
|
|
188
|
+
# 如果是容器类型,递归检查嵌套
|
|
189
|
+
if isinstance(container, (list, tuple, set)):
|
|
190
|
+
for item in container:
|
|
191
|
+
容器构建器._检查嵌套深度(item, current_depth + 1)
|
|
192
|
+
elif isinstance(container, dict):
|
|
193
|
+
for key, value in container.items():
|
|
194
|
+
容器构建器._检查嵌套深度(key, current_depth + 1)
|
|
195
|
+
容器构建器._检查嵌套深度(value, current_depth + 1)
|
|
196
|
+
|
|
197
|
+
@staticmethod
|
|
198
|
+
def _推断元素类型(container: Union[List[Any], Set[Any]], first_type: type) -> str:
|
|
199
|
+
"""
|
|
200
|
+
推断元素的C++类型
|
|
201
|
+
|
|
202
|
+
Args:
|
|
203
|
+
container: 容器对象
|
|
204
|
+
first_type: 第一个元素的类型
|
|
205
|
+
|
|
206
|
+
Returns:
|
|
207
|
+
str: C++类型名称
|
|
208
|
+
"""
|
|
209
|
+
if not container:
|
|
210
|
+
return "auto"
|
|
211
|
+
|
|
212
|
+
# 根据第一个元素值推断 C++ 类型
|
|
213
|
+
first_val = next(iter(container)) if isinstance(container, set) else container[0]
|
|
214
|
+
return 类型转换器.Python类型转C类型(first_type, first_val)
|
|
@@ -0,0 +1,285 @@
|
|
|
1
|
+
import re
|
|
2
|
+
import os
|
|
3
|
+
import ctypes
|
|
4
|
+
import inspect
|
|
5
|
+
import threading
|
|
6
|
+
from typing import List, Optional, Any, Dict, Set, Callable, Union
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def 十进制转进制(value: int, base: int, digits="0123456789ABCDEF") -> str:
|
|
10
|
+
"""将十进制整数转换为任意进制字符串"""
|
|
11
|
+
if value == 0:
|
|
12
|
+
return "0"
|
|
13
|
+
result = ""
|
|
14
|
+
is_negative = value < 0
|
|
15
|
+
value = abs(value)
|
|
16
|
+
while value > 0:
|
|
17
|
+
value, remainder = divmod(value, base)
|
|
18
|
+
result = digits[remainder] + result
|
|
19
|
+
return ("-" if is_negative else "") + result
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class Cpp函数映射:
|
|
23
|
+
"""
|
|
24
|
+
存储 Python 函数到 C++ 函数的映射关系。
|
|
25
|
+
包含目标函数名(或代码生成器)、头文件依赖和库文件依赖。
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
def __init__(
|
|
29
|
+
self, 目标函数: Union[str, Callable],
|
|
30
|
+
包含目录: Optional[List[str]] = None,
|
|
31
|
+
库: Optional[List[str]] = None,
|
|
32
|
+
库目录: Optional[List[str]] = None) -> None:
|
|
33
|
+
self.目标函数 = 目标函数
|
|
34
|
+
self.包含目录 = 包含目录 or []
|
|
35
|
+
self.库 = 库 or []
|
|
36
|
+
self.库目录 = 库目录 or []
|
|
37
|
+
|
|
38
|
+
def __str__(self) -> str:
|
|
39
|
+
if callable(self.目标函数):
|
|
40
|
+
return f"<function {self.目标函数.__name__}>"
|
|
41
|
+
return str(self.目标函数)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class Cpp类型映射:
|
|
45
|
+
"""
|
|
46
|
+
存储 Python 类型到 C++ 类型的映射关系。
|
|
47
|
+
包含目标类型名、ctypes 类型以及相关的编译依赖。
|
|
48
|
+
"""
|
|
49
|
+
|
|
50
|
+
def __init__(
|
|
51
|
+
self, 目标类型: str,
|
|
52
|
+
包含目录: Optional[List[str]] = None,
|
|
53
|
+
库: Optional[List[str]] = None,
|
|
54
|
+
库目录: Optional[List[str]] = None,
|
|
55
|
+
ctypes类型=None) -> None:
|
|
56
|
+
self.目标类型 = 目标类型
|
|
57
|
+
self.包含目录 = 包含目录 or []
|
|
58
|
+
self.库 = 库 or []
|
|
59
|
+
self.库目录 = 库目录 or []
|
|
60
|
+
self.ctypes类型 = ctypes类型
|
|
61
|
+
|
|
62
|
+
def __str__(self) -> str:
|
|
63
|
+
return self.目标类型
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class 全局上下文:
|
|
67
|
+
"""
|
|
68
|
+
全局上下文,存储所有的函数/类型映射配置、内置函数列表以及全局编译设置。
|
|
69
|
+
|
|
70
|
+
线程安全说明:
|
|
71
|
+
- JIT 编译过程通常是单线程的,全局上下文主要用于管理和清理状态
|
|
72
|
+
- 清理() 方法是线程安全的,可用于测试环境
|
|
73
|
+
- 直接访问静态变量不是线程安全的,多线程环境需要外部同步
|
|
74
|
+
"""
|
|
75
|
+
|
|
76
|
+
直接调用函数集: Set = set() # 直接在 Python 端执行的函数集合 (如 range)
|
|
77
|
+
函数映射表: Dict[Any, Cpp函数映射] = {} # 函数映射表
|
|
78
|
+
类型映射表: Dict[Any, Cpp类型映射] = {} # 类型映射表
|
|
79
|
+
反向类型映射表: Dict[Any, Any] = {} # 类型映射表
|
|
80
|
+
包含集合: Set = set()
|
|
81
|
+
链接库集合: Set = set()
|
|
82
|
+
最大变量ID = 0
|
|
83
|
+
Python内置映射 = {}
|
|
84
|
+
使用Unicode = True
|
|
85
|
+
工作目录 = './l0n0lcoutput' # 编译输出目录
|
|
86
|
+
编译栈: Set = set() # 全局编译栈,用于防止循环编译
|
|
87
|
+
|
|
88
|
+
@staticmethod
|
|
89
|
+
def 缓存直接调用():
|
|
90
|
+
全局上下文.直接调用函数集.add(range)
|
|
91
|
+
|
|
92
|
+
@staticmethod
|
|
93
|
+
def 添加内置映射(v):
|
|
94
|
+
全局上下文.Python内置映射[v.__name__] = v
|
|
95
|
+
|
|
96
|
+
@staticmethod
|
|
97
|
+
def 初始化内置():
|
|
98
|
+
"""初始化常用的 Python 内置函数映射"""
|
|
99
|
+
# 初始化常用的 Python 内置函数映射
|
|
100
|
+
for v in [int, float, bytes, str, bool, range, complex, set, tuple, list, dict,
|
|
101
|
+
print, input, abs, round, pow, divmod, sum, min, max,
|
|
102
|
+
isinstance, len, open, Exception, BaseException]:
|
|
103
|
+
全局上下文.添加内置映射(v)
|
|
104
|
+
|
|
105
|
+
@staticmethod
|
|
106
|
+
def 清理():
|
|
107
|
+
"""
|
|
108
|
+
清理全局状态,重置所有集合和映射。
|
|
109
|
+
|
|
110
|
+
线程安全:使用锁保护,可在多线程环境中调用。
|
|
111
|
+
|
|
112
|
+
用于测试或需要重置全局状态的场景。
|
|
113
|
+
注意:这会清除所有已注册的映射和配置(不包括内置映射)。
|
|
114
|
+
"""
|
|
115
|
+
with 全局上下文._lock:
|
|
116
|
+
全局上下文.直接调用函数集.clear()
|
|
117
|
+
全局上下文.函数映射表.clear()
|
|
118
|
+
全局上下文.类型映射表.clear()
|
|
119
|
+
全局上下文.反向类型映射表.clear()
|
|
120
|
+
全局上下文.包含集合.clear()
|
|
121
|
+
全局上下文.链接库集合.clear()
|
|
122
|
+
全局上下文.编译栈.clear()
|
|
123
|
+
全局上下文.最大变量ID = 0
|
|
124
|
+
# 注意:不清空 Python内置映射 和工作目录,这些是配置
|
|
125
|
+
|
|
126
|
+
# 类变量(仅用于清理方法)
|
|
127
|
+
_lock = threading.RLock() # 使用可重入锁
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
全局上下文.初始化内置()
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def 可直接调用(fn):
|
|
134
|
+
"""
|
|
135
|
+
装饰器:注册一个 Python 函数为"直接调用"模式。
|
|
136
|
+
转译器遇到此函数时不会尝试转换为 C++ 调用,而是回调 Python 解释器执行。
|
|
137
|
+
"""
|
|
138
|
+
全局上下文.直接调用函数集.add(fn)
|
|
139
|
+
return fn
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def 映射函数(
|
|
143
|
+
mapped_function,
|
|
144
|
+
包含目录: Optional[List[str]] = None,
|
|
145
|
+
库: Optional[List[str]] = None,
|
|
146
|
+
库目录: Optional[List[str]] = None):
|
|
147
|
+
"""
|
|
148
|
+
装饰器:将 Python 函数映射到 C++ 代码片段或函数。
|
|
149
|
+
|
|
150
|
+
:param mapped_function: 被映射的原 Python 函数
|
|
151
|
+
:param 包含目录: 需要包含的头文件
|
|
152
|
+
"""
|
|
153
|
+
def decorator(target):
|
|
154
|
+
全局上下文.函数映射表[mapped_function] = Cpp函数映射(target, 包含目录, 库, 库目录)
|
|
155
|
+
return target
|
|
156
|
+
return decorator
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def 映射类型(mapped_type,
|
|
160
|
+
包含目录: Optional[List[str]] = None,
|
|
161
|
+
库: Optional[List[str]] = None,
|
|
162
|
+
库目录: Optional[List[str]] = None,
|
|
163
|
+
ctypes类型=None):
|
|
164
|
+
"""
|
|
165
|
+
装饰器:将 Python 类型映射到 C++ 类型。
|
|
166
|
+
"""
|
|
167
|
+
def decorator(target):
|
|
168
|
+
类型映射 = Cpp类型映射(mapped_type, 包含目录, 库, 库目录, ctypes类型)
|
|
169
|
+
全局上下文.类型映射表[target] = 类型映射
|
|
170
|
+
全局上下文.反向类型映射表[mapped_type] = target
|
|
171
|
+
return target
|
|
172
|
+
return decorator
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def 含非ASCII字符(s: str) -> bool:
|
|
176
|
+
"""检查字符串是否包含非 ASCII 字符(如中文)"""
|
|
177
|
+
return bool(re.search(r'[^A-Za-z0-9_]', s))
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def 生成变量ID(original_name: Optional[str] = None) -> str:
|
|
181
|
+
"""
|
|
182
|
+
生成合法的 C++ 变量/函数标识符。
|
|
183
|
+
如果 original_name 是 ASCII 且 use_unicode=True 则直接使用,
|
|
184
|
+
否则生成唯一的临时 ID。
|
|
185
|
+
"""
|
|
186
|
+
if original_name is not None and (全局上下文.使用Unicode or not 含非ASCII字符(original_name)):
|
|
187
|
+
return original_name
|
|
188
|
+
ret = f'_{全局上下文.最大变量ID}'
|
|
189
|
+
全局上下文.最大变量ID += 1
|
|
190
|
+
return ret
|
|
191
|
+
|
|
192
|
+
def 转C字符串(v) -> str:
|
|
193
|
+
"""将 Python 值转换为 C++ 字符串表示"""
|
|
194
|
+
if isinstance(v, (str, bytes)):
|
|
195
|
+
return f'u8"{v}"'
|
|
196
|
+
return str(v)
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
# ==================== 优化后的映射函数实现 ====================
|
|
202
|
+
|
|
203
|
+
def 映射函数到(
|
|
204
|
+
cpp: str,
|
|
205
|
+
headers: Optional[List[str]] = None,
|
|
206
|
+
libraries: Optional[List[str]] = None,
|
|
207
|
+
library_dirs: Optional[List[str]] = None,
|
|
208
|
+
validate: bool = True,
|
|
209
|
+
**kwargs
|
|
210
|
+
):
|
|
211
|
+
"""
|
|
212
|
+
优化的函数映射装饰器
|
|
213
|
+
|
|
214
|
+
Args:
|
|
215
|
+
cpp: C++代码模板,使用{参数名}作为占位符
|
|
216
|
+
headers: 需要包含的头文件列表
|
|
217
|
+
libraries: 需要链接的库列表
|
|
218
|
+
library_dirs: 库搜索目录列表
|
|
219
|
+
validate: 是否验证参数匹配
|
|
220
|
+
**kwargs: 额外的模板变量,如模板参数T等
|
|
221
|
+
|
|
222
|
+
Example:
|
|
223
|
+
@映射到(
|
|
224
|
+
cpp='strlen({text})',
|
|
225
|
+
headers=['<cstring>']
|
|
226
|
+
)
|
|
227
|
+
def strlen(text: bytes) -> int:
|
|
228
|
+
\"\"\"计算字符串长度\"\"\"
|
|
229
|
+
pass
|
|
230
|
+
"""
|
|
231
|
+
def decorator(func):
|
|
232
|
+
# 获取函数签名
|
|
233
|
+
sig = inspect.signature(func)
|
|
234
|
+
param_names = list(sig.parameters.keys())
|
|
235
|
+
|
|
236
|
+
# 参数验证
|
|
237
|
+
if validate:
|
|
238
|
+
# 从模板中提取参数引用
|
|
239
|
+
template_refs = set(re.findall(r'\{(\w+)\}', cpp))
|
|
240
|
+
|
|
241
|
+
# 分离函数参数和额外参数
|
|
242
|
+
func_params = set(param_names)
|
|
243
|
+
extra_params = set(kwargs.keys())
|
|
244
|
+
|
|
245
|
+
# 检查模板中引用的参数
|
|
246
|
+
missing = template_refs - func_params - extra_params
|
|
247
|
+
if missing:
|
|
248
|
+
raise ValueError(
|
|
249
|
+
f"模板引用了未定义的参数: {missing}. "
|
|
250
|
+
f"可用参数: 函数参数={func_params}, 额外参数={extra_params}"
|
|
251
|
+
)
|
|
252
|
+
|
|
253
|
+
# 创建代码生成函数
|
|
254
|
+
def code_generator(*args, **call_kwargs):
|
|
255
|
+
# 合并函数参数和额外参数
|
|
256
|
+
all_kwargs = {}
|
|
257
|
+
all_kwargs.update(kwargs) # 额外参数如T='int'
|
|
258
|
+
|
|
259
|
+
# 添加调用时的函数参数
|
|
260
|
+
for i, arg in enumerate(args):
|
|
261
|
+
if i < len(param_names):
|
|
262
|
+
all_kwargs[param_names[i]] = arg
|
|
263
|
+
|
|
264
|
+
# 添加关键字参数
|
|
265
|
+
all_kwargs.update(call_kwargs)
|
|
266
|
+
|
|
267
|
+
# 替换模板
|
|
268
|
+
result = cpp
|
|
269
|
+
for name, value in all_kwargs.items():
|
|
270
|
+
result = result.replace(f'{{{name}}}', str(value))
|
|
271
|
+
|
|
272
|
+
return result
|
|
273
|
+
|
|
274
|
+
# 注册到全局上下文
|
|
275
|
+
全局上下文.函数映射表[func] = Cpp函数映射(
|
|
276
|
+
code_generator,
|
|
277
|
+
headers or [],
|
|
278
|
+
libraries or [],
|
|
279
|
+
library_dirs or []
|
|
280
|
+
)
|
|
281
|
+
|
|
282
|
+
return func
|
|
283
|
+
|
|
284
|
+
return decorator
|
|
285
|
+
|