codecin 7.22.10__py3-none-win_amd64.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 (202) hide show
  1. codecin/__init__.py +27 -0
  2. codecin/aot.py +1057 -0
  3. codecin/assembler.py +619 -0
  4. codecin/cbackend.py +3024 -0
  5. codecin/cin.py +4265 -0
  6. codecin/cli.py +670 -0
  7. codecin/codecin_native.dll +0 -0
  8. codecin/config.py +50 -0
  9. codecin/console.py +183 -0
  10. codecin/cpu.py +312 -0
  11. codecin/crom.py +449 -0
  12. codecin/cvm.py +708 -0
  13. codecin/disasm.py +149 -0
  14. codecin/environment.py +176 -0
  15. codecin/errors.py +54 -0
  16. codecin/isa.py +560 -0
  17. codecin/lib/array/pic.toml +10 -0
  18. codecin/lib/array/src/array.cin +103 -0
  19. codecin/lib/bigint/pic.toml +10 -0
  20. codecin/lib/bigint/src/bigint.cin +589 -0
  21. codecin/lib/bits/pic.toml +10 -0
  22. codecin/lib/bits/src/bits.cin +143 -0
  23. codecin/lib/bitset/pic.toml +10 -0
  24. codecin/lib/bitset/src/bitset.cin +374 -0
  25. codecin/lib/codec/pic.toml +10 -0
  26. codecin/lib/codec/src/codec.cin +563 -0
  27. codecin/lib/combin/pic.toml +10 -0
  28. codecin/lib/combin/src/combin.cin +414 -0
  29. codecin/lib/conv/pic.toml +10 -0
  30. codecin/lib/conv/src/conv.cin +151 -0
  31. codecin/lib/cppstd/pic.toml +10 -0
  32. codecin/lib/cppstd/src/cppstd.cin +418 -0
  33. codecin/lib/cstd/pic.toml +10 -0
  34. codecin/lib/cstd/src/cstd.cin +424 -0
  35. codecin/lib/csv/pic.toml +10 -0
  36. codecin/lib/csv/src/csv.cin +405 -0
  37. codecin/lib/dp/pic.toml +10 -0
  38. codecin/lib/dp/src/dp.cin +325 -0
  39. codecin/lib/ffi/pic.toml +10 -0
  40. codecin/lib/ffi/src/ffi.cin +163 -0
  41. codecin/lib/fmt/pic.toml +10 -0
  42. codecin/lib/fmt/src/fmt.cin +325 -0
  43. codecin/lib/frac/pic.toml +10 -0
  44. codecin/lib/frac/src/frac.cin +252 -0
  45. codecin/lib/gostd/pic.toml +10 -0
  46. codecin/lib/gostd/src/gostd.cin +415 -0
  47. codecin/lib/graph/pic.toml +10 -0
  48. codecin/lib/graph/src/graph.cin +367 -0
  49. codecin/lib/gui/pic.toml +10 -0
  50. codecin/lib/gui/src/gui.cin +218 -0
  51. codecin/lib/hash/pic.toml +10 -0
  52. codecin/lib/hash/src/hash.cin +67 -0
  53. codecin/lib/heap/pic.toml +10 -0
  54. codecin/lib/heap/src/heap.cin +199 -0
  55. codecin/lib/io/pic.toml +10 -0
  56. codecin/lib/io/src/io.cin +141 -0
  57. codecin/lib/json/pic.toml +10 -0
  58. codecin/lib/json/src/json.cin +84 -0
  59. codecin/lib/key/pic.toml +10 -0
  60. codecin/lib/key/src/key.cin +78 -0
  61. codecin/lib/math/pic.toml +10 -0
  62. codecin/lib/math/src/math.cin +50 -0
  63. codecin/lib/matrix/pic.toml +10 -0
  64. codecin/lib/matrix/src/matrix.cin +155 -0
  65. codecin/lib/net/pic.toml +10 -0
  66. codecin/lib/net/src/net.cin +171 -0
  67. codecin/lib/path/pic.toml +10 -0
  68. codecin/lib/path/src/path.cin +372 -0
  69. codecin/lib/queue/pic.toml +10 -0
  70. codecin/lib/queue/src/queue.cin +112 -0
  71. codecin/lib/rand/pic.toml +10 -0
  72. codecin/lib/rand/src/rand.cin +46 -0
  73. codecin/lib/set/pic.toml +10 -0
  74. codecin/lib/set/src/set.cin +269 -0
  75. codecin/lib/sort/pic.toml +10 -0
  76. codecin/lib/sort/src/sort.cin +93 -0
  77. codecin/lib/stat/pic.toml +10 -0
  78. codecin/lib/stat/src/stat.cin +138 -0
  79. codecin/lib/str/pic.toml +10 -0
  80. codecin/lib/str/src/str.cin +54 -0
  81. codecin/lib/termux/pic.toml +10 -0
  82. codecin/lib/termux/src/termux.cin +118 -0
  83. codecin/lib/test/pic.toml +10 -0
  84. codecin/lib/test/src/test.cin +74 -0
  85. codecin/lib/text/pic.toml +10 -0
  86. codecin/lib/text/src/text.cin +323 -0
  87. codecin/lib/time/pic.toml +10 -0
  88. codecin/lib/time/src/time.cin +54 -0
  89. codecin/lib/token/pic.toml +10 -0
  90. codecin/lib/token/src/token.cin +183 -0
  91. codecin/lib/tree/pic.toml +10 -0
  92. codecin/lib/tree/src/tree.cin +256 -0
  93. codecin/lib/unionfind/pic.toml +10 -0
  94. codecin/lib/unionfind/src/unionfind.cin +115 -0
  95. codecin/lib/validate/pic.toml +10 -0
  96. codecin/lib/validate/src/validate.cin +148 -0
  97. codecin/lib/vec/pic.toml +10 -0
  98. codecin/lib/vec/src/vec.cin +88 -0
  99. codecin/logger.py +145 -0
  100. codecin/memory.py +306 -0
  101. codecin/mkn.py +916 -0
  102. codecin/native/aot/aot.go +114 -0
  103. codecin/native/aot/stub_main.go.txt +23 -0
  104. codecin/native/build.ps1 +33 -0
  105. codecin/native/build.sh +48 -0
  106. codecin/native/cmd/cincc/main.go +66 -0
  107. codecin/native/compiler/codegen.go +2238 -0
  108. codecin/native/compiler/compile_test.go +1069 -0
  109. codecin/native/compiler/parser.go +1331 -0
  110. codecin/native/compiler/syscalls.go +166 -0
  111. codecin/native/compiler/tokenizer.go +394 -0
  112. codecin/native/compiler/types.go +217 -0
  113. codecin/native/engine/args.go +37 -0
  114. codecin/native/engine/audio.go +402 -0
  115. codecin/native/engine/audio_other.go +105 -0
  116. codecin/native/engine/audio_test.go +279 -0
  117. codecin/native/engine/audio_windows.go +190 -0
  118. codecin/native/engine/canvas.go +271 -0
  119. codecin/native/engine/console_other.go +9 -0
  120. codecin/native/engine/console_windows.go +43 -0
  121. codecin/native/engine/crom.go +86 -0
  122. codecin/native/engine/encode.go +93 -0
  123. codecin/native/engine/engine_test.go +198 -0
  124. codecin/native/engine/ffi_nocgo.go +20 -0
  125. codecin/native/engine/ffi_registry.go +69 -0
  126. codecin/native/engine/ffi_unix.go +109 -0
  127. codecin/native/engine/ffi_windows.go +117 -0
  128. codecin/native/engine/gui.go +209 -0
  129. codecin/native/engine/gui_stub.go +13 -0
  130. codecin/native/engine/gui_test.go +148 -0
  131. codecin/native/engine/gui_windows.go +604 -0
  132. codecin/native/engine/gui_x11.go +723 -0
  133. codecin/native/engine/host_test.go +139 -0
  134. codecin/native/engine/hostcrypto.go +30 -0
  135. codecin/native/engine/hostdesktop.go +173 -0
  136. codecin/native/engine/hostnet.go +127 -0
  137. codecin/native/engine/isa_gen.go +689 -0
  138. codecin/native/engine/keyboard.go +432 -0
  139. codecin/native/engine/keyboard_other.go +94 -0
  140. codecin/native/engine/keyboard_stub.go +17 -0
  141. codecin/native/engine/keyboard_termios_darwin.go +9 -0
  142. codecin/native/engine/keyboard_termios_linux.go +9 -0
  143. codecin/native/engine/keyboard_test.go +246 -0
  144. codecin/native/engine/keyboard_windows.go +208 -0
  145. codecin/native/engine/keyboard_windows_test.go +123 -0
  146. codecin/native/engine/lineedit.go +262 -0
  147. codecin/native/engine/lineedit_test.go +105 -0
  148. codecin/native/engine/lineint_unix.go +17 -0
  149. codecin/native/engine/lineint_windows.go +19 -0
  150. codecin/native/engine/mem_other.go +37 -0
  151. codecin/native/engine/mem_windows.go +33 -0
  152. codecin/native/engine/native.go +640 -0
  153. codecin/native/engine/netsock.go +321 -0
  154. codecin/native/engine/ops_ext.go +515 -0
  155. codecin/native/engine/stdin.go +72 -0
  156. codecin/native/engine/stdin_other.go +9 -0
  157. codecin/native/engine/stdin_windows.go +60 -0
  158. codecin/native/engine/system.go +313 -0
  159. codecin/native/engine/termux.go +180 -0
  160. codecin/native/engine/version_gen.go +7 -0
  161. codecin/native/engine/vkb_darwin.go +62 -0
  162. codecin/native/engine/vkb_linux.go +95 -0
  163. codecin/native/engine/vkb_stub.go +11 -0
  164. codecin/native/engine/vm.go +1677 -0
  165. codecin/native/go.mod +3 -0
  166. codecin/native/ir/ir.go +48 -0
  167. codecin/native/main.go +448 -0
  168. codecin/native/mc/aarch64.go +165 -0
  169. codecin/native/mc/aarch64_test.go +30 -0
  170. codecin/native/mc/elf.go +88 -0
  171. codecin/native/mc/print_test.go +52 -0
  172. codecin/native/mc/x86_64.go +1262 -0
  173. codecin/native/mc/x86_64_test.go +102 -0
  174. codecin/native.py +432 -0
  175. codecin/native_codegen.py +987 -0
  176. codecin/nativegen.py +786 -0
  177. codecin/object.py +539 -0
  178. codecin/optimizer.py +236 -0
  179. codecin/packaging/__init__.py +46 -0
  180. codecin/packaging/archive.py +177 -0
  181. codecin/packaging/model.py +519 -0
  182. codecin/packaging/spec.py +193 -0
  183. codecin/packaging/store.py +372 -0
  184. codecin/packaging/toml.py +541 -0
  185. codecin/packaging/vcs.py +215 -0
  186. codecin/pic.py +1917 -0
  187. codecin/pic_api.py +374 -0
  188. codecin/pic_login.py +519 -0
  189. codecin/pic_registry.py +515 -0
  190. codecin/registers.py +130 -0
  191. codecin/sdgcc.py +493 -0
  192. codecin/stats.py +230 -0
  193. codecin/stdlib.py +138 -0
  194. codecin/toolchain.py +396 -0
  195. codecin/toolkit.py +26 -0
  196. codecin/version.py +260 -0
  197. codecin-7.22.10.dist-info/METADATA +1077 -0
  198. codecin-7.22.10.dist-info/RECORD +202 -0
  199. codecin-7.22.10.dist-info/WHEEL +5 -0
  200. codecin-7.22.10.dist-info/entry_points.txt +5 -0
  201. codecin-7.22.10.dist-info/licenses/LICENSE +7 -0
  202. codecin-7.22.10.dist-info/top_level.txt +1 -0
codecin/aot.py ADDED
@@ -0,0 +1,1057 @@
1
+ """AOT 构建: 把 CIN 程序编译成**独立静态可执行文件** (Windows / Linux / macOS)。
2
+
3
+ 两种后端 (默认 ``auto`` 按指令数选择):
4
+ * ``native``: 把指令流直接生成 Go 源码, 核心指令不再经过
5
+ UCBC 解码/opcode dispatch, 由 Go 编译器产出 x86-64/ARM64 机器码;
6
+ * ``vm``: 内嵌 UCBC 字节码与初始内存镜像, 由内置 Go VM 执行。
7
+
8
+ 产物均 `CGO_ENABLED=0` 静态链接, 不依赖 Python、Go 工具链、libc 或任何
9
+ 动态库; 可用 ``--build-target`` 交叉编译。
10
+
11
+ 实现说明: VM 后端的 main.go 模板与 Go 侧 `codecin/native/aot` 共用同一份
12
+ 文件 (``stub_main.go.txt``); native 后端的源码由 ``codecin/native_codegen.py``
13
+ 生成。临时包建在 ``codecin-native`` 模块内的 ``.aotbuild-*`` 目录, 受限
14
+ 环境下改用可写的 Go module + replace。
15
+
16
+ 临时目录的生命周期 (加固, 见 docs/SUGGESTIONS_NEXT.md §3.3):
17
+ * 每次 :func:`build` 之前先调用 :func:`sweep_stale_build_dirs` 清理**陈旧**残留,
18
+ 避免受限环境 (沙箱 / 只读 ACL) 下删不掉的目录无限累积;
19
+ * ``finally`` 里的 ``rmtree`` 失败**不再静默**: 有 logger 就 ``warning``,
20
+ 没有 logger 时退回模块级 stdlib logger (``codecin.aot``), 绝不吞掉;
21
+ * 只清理 ``codecin/native/`` **本目录下**、名字带 ``.aotbuild-`` /
22
+ ``.aotprobe-`` 前缀、且**不是符号链接**的目录, 绝不递归删除别处。
23
+ """
24
+
25
+ import functools
26
+ import hashlib
27
+ import logging
28
+ import os
29
+ import platform
30
+ import secrets
31
+ import shutil
32
+ import struct
33
+ import subprocess
34
+ import sys
35
+ import time
36
+ from typing import Dict, List, NamedTuple, Optional, Tuple
37
+
38
+ #: 仓库内 codecin-native 模块目录 (含 go.mod)。
39
+ _NATIVE_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'native')
40
+
41
+ #: 模块级 logger: 调用方没有传 logger 时的兜底 (绝不能因为"没人接"就静默)。
42
+ #: 它是 ``codecin`` logger 的子 logger, 因此 CLI 构造的 Logger (RichHandler) 会
43
+ #: 照常渲染它; 完全没配置 logging 时 stdlib 的 lastResort 也会打到 stderr。
44
+ _LOGGER = logging.getLogger(__name__)
45
+
46
+ #: AOT 临时目录名前缀 (``.aotprobe-`` 是历史遗留, 一并纳入守卫)。
47
+ TEMP_DIR_PREFIXES = ('.aotbuild-', '.aotprobe-')
48
+
49
+ #: 陈旧残留的默认容忍时长 (6 小时): 远大于任何一次 go build, 因此不会误删
50
+ #: 并发构建中的临时目录。
51
+ DEFAULT_STALE_AGE_SECONDS = 6 * 3600
52
+
53
+ #: 生成的 main.go 模板 (与 Go 侧共用)。
54
+ STUB_PATH = os.path.join(_NATIVE_DIR, 'aot', 'stub_main.go.txt')
55
+
56
+ #: 默认内存大小 (1 GiB): 与解释器 / Go CLI 一致; 由 VM 按需分配 (OS 懒提交)。
57
+ DEFAULT_MEM_SIZE = 1 << 30
58
+
59
+ #: 栈槽位 (与 isa.Constants.STACK_SLOT 一致, 避免循环导入)。
60
+ _STACK_SLOT = 8
61
+
62
+ #: auto 后端切换到 native 的指令数上限。native 后端把每条指令展开成
63
+ #: Go 语句, 数万条指令的程序 (如 basic.cin) 会让 go build 极慢; 超过阈值
64
+ #: 自动回退到 VM 后端。显式 ``--build-backend native`` 仍可强制 native。
65
+ NATIVE_INSTRUCTION_LIMIT = 20000
66
+
67
+
68
+ def resolve_backend(backend: str, instruction_count: int) -> str:
69
+ """把 ``auto|native|vm`` 解析成实际后端。"""
70
+ if backend == 'auto':
71
+ return ('native' if int(instruction_count) <= NATIVE_INSTRUCTION_LIMIT
72
+ else 'vm')
73
+ if backend not in ('native', 'vm'):
74
+ raise AotError(f'未知 AOT 后端: {backend} (可选 auto / native / vm)')
75
+ return backend
76
+
77
+
78
+ # ==================== 增量构建缓存 ====================
79
+
80
+ def _cache_root() -> str:
81
+ """AOT 缓存目录 (可用 CODECIN_AOT_CACHE 覆盖)。"""
82
+ explicit = os.environ.get('CODECIN_AOT_CACHE')
83
+ if explicit:
84
+ return os.path.abspath(explicit)
85
+ system = platform.system()
86
+ if system == 'Windows':
87
+ base = os.environ.get('LOCALAPPDATA') or os.path.join(
88
+ os.path.expanduser('~'), 'AppData', 'Local')
89
+ elif system == 'Darwin':
90
+ base = os.path.join(os.path.expanduser('~'), 'Library', 'Caches')
91
+ else:
92
+ base = os.environ.get('XDG_CACHE_HOME') or os.path.join(
93
+ os.path.expanduser('~'), '.cache')
94
+ return os.path.join(base, 'codecin', 'aot')
95
+
96
+
97
+ def _toolchain_fingerprint() -> str:
98
+ """AOT 产物相关工具链/代码生成器的指纹。"""
99
+ return _toolchain_fingerprint_for(_NATIVE_DIR)
100
+
101
+
102
+ @functools.lru_cache(maxsize=4)
103
+ def _toolchain_fingerprint_for(native_dir: str) -> str:
104
+ h = hashlib.sha256()
105
+ py_dir = os.path.dirname(os.path.abspath(__file__))
106
+ # 前端/运行时 Python 源码也参与指纹: CIN 编译器、汇编器、内存等变更
107
+ # 即使源码相同也可能改变产物。
108
+ for dirpath, dirnames, filenames in os.walk(py_dir):
109
+ dirnames[:] = sorted(d for d in dirnames
110
+ if d not in ('__pycache__', 'native', 'lib'))
111
+ for name in sorted(filenames):
112
+ if not name.endswith('.py'):
113
+ continue
114
+ path = os.path.join(dirpath, name)
115
+ try:
116
+ with open(path, 'rb') as f:
117
+ h.update(os.path.relpath(path, py_dir).encode()
118
+ + b'\0' + f.read())
119
+ except OSError:
120
+ pass
121
+ for dirpath, dirnames, filenames in os.walk(native_dir):
122
+ dirnames[:] = sorted(d for d in dirnames
123
+ if d not in ('__pycache__', '.git')
124
+ and not d.startswith('.aotbuild-'))
125
+ for name in sorted(filenames):
126
+ if not (name.endswith('.go') or name in ('go.mod', 'go.sum')):
127
+ continue
128
+ path = os.path.join(dirpath, name)
129
+ try:
130
+ with open(path, 'rb') as f:
131
+ h.update(os.path.relpath(path, native_dir).encode()
132
+ + b'\0' + f.read())
133
+ except OSError:
134
+ pass
135
+ try:
136
+ proc = subprocess.run(['go', 'version'], capture_output=True,
137
+ text=True, encoding='utf-8', errors='replace',
138
+ timeout=10)
139
+ h.update(b'go\0' + (proc.stdout or proc.stderr).encode())
140
+ except Exception: # noqa: BLE001
141
+ pass
142
+ h.update(f'{platform.system()}\0{platform.machine()}\0'
143
+ f'{sys.version}'.encode())
144
+ return h.hexdigest()
145
+
146
+
147
+ def build_cache_key(program_file: str,
148
+ target: Optional[str],
149
+ backend: str,
150
+ optimize: int,
151
+ mem_size: Optional[int],
152
+ max_instructions: int,
153
+ debug: bool = False) -> Optional[str]:
154
+ """计算 AOT 增量缓存键; 源/依赖不可读时返回 None (不缓存)。"""
155
+ try:
156
+ deps = program_dependencies(program_file)
157
+ except Exception: # noqa: BLE001
158
+ return None
159
+ h = hashlib.sha256()
160
+ for path in deps:
161
+ try:
162
+ with open(path, 'rb') as f:
163
+ data = f.read()
164
+ except OSError:
165
+ return None
166
+ h.update(os.path.basename(path).encode() + b'\0' + data)
167
+ goos, goarch = parse_target(target) if target else parse_target(
168
+ host_target())
169
+ total = int(mem_size) if mem_size else DEFAULT_MEM_SIZE
170
+ total = max(256, total)
171
+ opts = (f'{goos}/{goarch}\0{backend}\0{int(optimize or 0)}\0'
172
+ f'{total}\0{int(max_instructions)}\0{int(bool(debug))}\0'
173
+ f'{_toolchain_fingerprint()}')
174
+ h.update(opts.encode())
175
+ return h.hexdigest()
176
+
177
+
178
+ def link_cache_key(paths,
179
+ target: Optional[str],
180
+ backend: str,
181
+ optimize: int,
182
+ mem_size: int,
183
+ max_instructions: int,
184
+ debug: bool = False,
185
+ gc_sections: bool = False) -> Optional[str]:
186
+ """对象/归档链接的增量缓存键; 输入不可读时返回 None。"""
187
+ h = hashlib.sha256()
188
+ for path in paths:
189
+ try:
190
+ with open(path, 'rb') as f:
191
+ data = f.read()
192
+ except OSError:
193
+ return None
194
+ h.update(os.path.basename(path).encode() + b'\0' + data)
195
+ goos, goarch = parse_target(target) if target else parse_target(
196
+ host_target())
197
+ opts = (f'{goos}/{goarch}\0{backend}\0{int(optimize or 0)}\0'
198
+ f'{int(mem_size)}\0{int(max_instructions)}\0{int(bool(debug))}\0'
199
+ f'{int(bool(gc_sections))}\0{_toolchain_fingerprint()}')
200
+ h.update(opts.encode())
201
+ return h.hexdigest()
202
+
203
+
204
+ def _cache_path(key: str, goos: str) -> str:
205
+ suffix = '.exe' if goos == 'windows' else ''
206
+ return os.path.join(_cache_root(), key + suffix)
207
+
208
+
209
+ def _cache_lookup(key: str, goos: str, out: str, logger=None) -> bool:
210
+ path = _cache_path(key, goos)
211
+ try:
212
+ if not os.path.isfile(path) or os.path.getsize(path) == 0:
213
+ return False
214
+ os.makedirs(os.path.dirname(os.path.abspath(out)) or '.',
215
+ exist_ok=True)
216
+ shutil.copyfile(path, out)
217
+ if goos != 'windows':
218
+ os.chmod(out, 0o755)
219
+ except OSError as e:
220
+ if logger:
221
+ logger.debug(f'AOT cache: 命中但复制失败 ({e})')
222
+ return False
223
+ if logger:
224
+ logger.info(f'AOT cache hit: {key[:12]} -> {out}')
225
+ return True
226
+
227
+
228
+ def _cache_store(key: str, goos: str, built: str, logger=None) -> None:
229
+ path = _cache_path(key, goos)
230
+ tmp = f'{path}.tmp-{os.getpid()}'
231
+ try:
232
+ os.makedirs(os.path.dirname(path), exist_ok=True)
233
+ shutil.copyfile(built, tmp)
234
+ os.replace(tmp, path)
235
+ except OSError as e:
236
+ if logger:
237
+ logger.debug(f'AOT cache: 写入失败 ({e})')
238
+ try:
239
+ if os.path.exists(tmp):
240
+ os.remove(tmp)
241
+ except OSError:
242
+ pass
243
+ else:
244
+ if logger:
245
+ logger.debug(f'AOT cache store: {key[:12]}')
246
+
247
+
248
+ def pack_seg_file(mem_size: int, sp: int, heap_base: int,
249
+ segs: List[Tuple[int, bytes]]) -> bytes:
250
+ """打包段文件 (program.segs), 由 aot.Main 解析:
251
+ seg_count u32 | mem_size u64 | sp u64 | heap_base u64 |
252
+ 每段: addr u64 + len u32 + data
253
+ """
254
+ out = bytearray()
255
+ out += struct.pack('<I', len(segs))
256
+ out += struct.pack('<QQQ', mem_size, sp, heap_base)
257
+ for addr, data in segs:
258
+ out += struct.pack('<QI', addr, len(data))
259
+ out += data
260
+ return bytes(out)
261
+
262
+ #: 常用交叉编译目标 (go 本身支持更多组合)。
263
+ SUPPORTED_TARGETS = [
264
+ 'windows/amd64', 'windows/arm64',
265
+ 'linux/amd64', 'linux/arm64',
266
+ 'darwin/amd64', 'darwin/arm64',
267
+ ]
268
+
269
+ #: go 的 GOOS 取值与 Python platform.system() 的对应
270
+ _GOOS_BY_SYSTEM = {'Windows': 'windows', 'Linux': 'linux', 'Darwin': 'darwin'}
271
+ _GOARCH_BY_MACHINE = {
272
+ 'x86_64': 'amd64', 'AMD64': 'amd64', 'amd64': 'amd64',
273
+ 'aarch64': 'arm64', 'arm64': 'arm64', 'ARM64': 'arm64',
274
+ 'i386': '386', 'i686': '386',
275
+ 'armv7l': 'arm', 'armv6l': 'arm',
276
+ }
277
+
278
+
279
+ class AotError(Exception):
280
+ """AOT 构建失败。"""
281
+
282
+
283
+ def host_target() -> str:
284
+ """返回当前平台的 ``os/arch``。"""
285
+ goos = _GOOS_BY_SYSTEM.get(platform.system(), platform.system().lower())
286
+ machine = platform.machine()
287
+ goarch = _GOARCH_BY_MACHINE.get(machine, machine.lower())
288
+ return f'{goos}/{goarch}'
289
+
290
+
291
+ def parse_target(target: str) -> tuple:
292
+ """把 ``os/arch`` 解析为 (goos, goarch); 非法时抛 AotError。"""
293
+ parts = target.split('/')
294
+ if len(parts) != 2 or not parts[0] or not parts[1]:
295
+ raise AotError(
296
+ f"--target 格式应为 os/arch (例如 linux/amd64); 支持: "
297
+ f"{', '.join(SUPPORTED_TARGETS)}")
298
+ return parts[0], parts[1]
299
+
300
+
301
+ def exe_suffix(goos: str) -> str:
302
+ """目标平台的可执行文件后缀。"""
303
+ return '.exe' if goos == 'windows' else ''
304
+
305
+
306
+ def module_dir() -> str:
307
+ """返回 codecin-native 模块目录 (含 go.mod)。"""
308
+ if os.path.isfile(os.path.join(_NATIVE_DIR, 'go.mod')):
309
+ return _NATIVE_DIR
310
+ raise AotError(
311
+ f'找不到 Go 模块目录 {_NATIVE_DIR} (AOT 构建需要仓库中的 Go 源码)')
312
+
313
+
314
+ def stub_source() -> str:
315
+ """读取生成的 main.go 模板。"""
316
+ try:
317
+ with open(STUB_PATH, encoding='utf-8') as f:
318
+ return f.read()
319
+ except OSError as e:
320
+ raise AotError(
321
+ f'找不到 AOT 模板 {STUB_PATH}; --build-exe 需要包含 '
322
+ f'codecin/native/ 的源码树') from e
323
+
324
+
325
+ def _cache_fallback_dir(mod_dir: str) -> str:
326
+ """仓库内的构建缓存目录 (install 脚本同款; 已被 .gitignore 忽略)。"""
327
+ root = os.path.dirname(os.path.dirname(os.path.abspath(mod_dir)))
328
+ return os.path.join(root, '.gocache')
329
+
330
+
331
+ def _looks_like_cache_denied(text: str) -> bool:
332
+ low = text.lower()
333
+ if 'go-build' not in low and 'gocache' not in low and 'cache' not in low:
334
+ return False
335
+ return ('access is denied' in low or 'permission denied' in low
336
+ or 'operation not permitted' in low)
337
+
338
+
339
+ def _run_go_build(cmd, mod, env, logger):
340
+ """执行 go build; 默认构建缓存不可写时自动回退到仓库内缓存重试一次。
341
+
342
+ 受限环境 (沙箱 / 只读 HOME / 部分 CI) 下 Go 默认的
343
+ ``$LOCALAPPDATA/go-build`` 或 ``~/.cache/go-build`` 可能不可写,
344
+ 此时直接用用户环境会得到一个难以理解的 "Access is denied"。
345
+ """
346
+ proc = subprocess.run(cmd, cwd=mod, env=env, capture_output=True,
347
+ text=True, encoding='utf-8', errors='replace',
348
+ timeout=1800)
349
+ detail = (proc.stderr or proc.stdout or '').strip()
350
+ if proc.returncode != 0 and _looks_like_cache_denied(detail) \
351
+ and 'GOCACHE' not in os.environ:
352
+ cache = _cache_fallback_dir(mod)
353
+ os.makedirs(cache, exist_ok=True)
354
+ if logger:
355
+ logger.info(f'AOT: 默认 Go 构建缓存不可写, 回退到 {cache} 重试')
356
+ retry_env = dict(env)
357
+ retry_env['GOCACHE'] = cache
358
+ proc = subprocess.run(cmd, cwd=mod, env=retry_env, capture_output=True,
359
+ text=True, encoding='utf-8', errors='replace',
360
+ timeout=1800)
361
+ detail = (proc.stderr or proc.stdout or '').strip()
362
+ return proc, detail
363
+
364
+
365
+ class SweepResult(NamedTuple):
366
+ """:func:`sweep_stale_build_dirs` 的结果 (两个绝对路径列表)。"""
367
+
368
+ #: 成功删除的目录
369
+ removed: List[str]
370
+ #: 判定为残留但删除/读取失败的目录 (调用方应提示用户手动处理)
371
+ failed: List[str]
372
+
373
+
374
+ def _warn(logger, message: str) -> None:
375
+ """记一条 warning; 没有 logger 时退回模块级 stdlib logger (绝不静默)。
376
+
377
+ 日志本身出问题不能掩盖构建结果 (本函数常在 ``finally`` 里被调用),
378
+ 因此这里再包一层兜底。
379
+ """
380
+ try:
381
+ if logger is not None:
382
+ logger.warning(message)
383
+ else:
384
+ _LOGGER.warning(message)
385
+ except Exception: # noqa: BLE001 - 日志失败不得影响构建
386
+ pass
387
+
388
+
389
+ def _debug(logger, message: str) -> None:
390
+ """记一条 debug (同样带兜底)。"""
391
+ try:
392
+ if logger is not None:
393
+ logger.debug(message)
394
+ else:
395
+ _LOGGER.debug(message)
396
+ except Exception: # noqa: BLE001
397
+ pass
398
+
399
+
400
+ def _manual_removal_hint(path: str) -> str:
401
+ """给用户的「怎么手动删掉它」提示 (Windows + POSIX 各一条)。"""
402
+ return (f'请手动删除该目录 —— Windows PowerShell: '
403
+ f'Remove-Item -LiteralPath "{path}" -Recurse -Force ; '
404
+ f'Linux/macOS: rm -rf "{path}"')
405
+
406
+
407
+ def _is_temp_dir_name(name: str) -> bool:
408
+ """名字是否是本模块自己产生的临时目录名 (只认前缀, 不做任何路径解析)。
409
+
410
+ 显式拒绝 ``.``/``..``、含路径分隔符的名字以及绝对路径 —— 这些都不可能是
411
+ ``secrets.token_hex`` 的产物, 一旦出现就说明有人往我们手里塞了别的东西。
412
+ """
413
+ if not name or name in ('.', '..'):
414
+ return False
415
+ if name != os.path.basename(name): # 含 / 或 \ -> 不是直接子项
416
+ return False
417
+ if os.sep in name or (os.altsep and os.altsep in name):
418
+ return False
419
+ if os.path.isabs(name):
420
+ return False
421
+ return name.startswith(TEMP_DIR_PREFIXES)
422
+
423
+
424
+ def sweep_stale_build_dirs(max_age_seconds: float = DEFAULT_STALE_AGE_SECONDS,
425
+ logger=None) -> SweepResult:
426
+ """删除 ``codecin/native/`` 下**陈旧**的 AOT 临时构建目录。
427
+
428
+ 只处理 ``codecin/native/`` 的**直接子目录** (不递归), 名字必须带
429
+ ``.aotbuild-`` / ``.aotprobe-`` 前缀, 且 mtime 早于 ``max_age_seconds``;
430
+ 符号链接与普通文件一律跳过。任何失败都不会抛异常, 只记录日志并把路径
431
+ 放进 :attr:`SweepResult.failed`。
432
+
433
+ :param max_age_seconds: 容忍时长 (默认 6 小时)。``0`` 表示删除所有匹配目录
434
+ —— 并发构建时不要这么做。
435
+ :param logger: 可选 logger; 缺省时用模块级 stdlib logger。
436
+ :return: 被删除的路径与清理失败的路径
437
+ """
438
+ removed: List[str] = []
439
+ failed: List[str] = []
440
+
441
+ root = os.path.abspath(_NATIVE_DIR)
442
+ try:
443
+ names = os.listdir(root)
444
+ except OSError as e: # 目录不存在 / 不可读: 尽力而为
445
+ _warn(logger, f'AOT: 无法扫描临时目录所在位置 {root} ({e}); 跳过清理')
446
+ return SweepResult(removed, failed)
447
+
448
+ try:
449
+ max_age = max(0.0, float(max_age_seconds))
450
+ except (TypeError, ValueError):
451
+ max_age = float(DEFAULT_STALE_AGE_SECONDS)
452
+
453
+ now = time.time()
454
+ for name in names:
455
+ if not _is_temp_dir_name(name):
456
+ continue
457
+ path = os.path.join(root, name)
458
+ # 双保险: 解析后必须仍然是 root 的直接子项 (防 '..' / 绝对路径混入)
459
+ if os.path.dirname(os.path.abspath(path)) != root:
460
+ _warn(logger, f'AOT: 跳过可疑的临时目录路径: {path}')
461
+ continue
462
+ if os.path.islink(path) or not os.path.isdir(path):
463
+ _debug(logger, f'AOT: 跳过非普通目录的临时项: {path}')
464
+ continue
465
+
466
+ try:
467
+ age = now - os.path.getmtime(path)
468
+ except OSError as e:
469
+ failed.append(path)
470
+ _warn(logger, f'AOT: 无法读取残留临时目录的时间戳: {path} ({e}); '
471
+ f'{_manual_removal_hint(path)}')
472
+ continue
473
+
474
+ if age < max_age:
475
+ _debug(logger, f'AOT: 临时目录仍然新鲜, 保留: {path} '
476
+ f'({age / 3600:.1f} 小时前)')
477
+ continue
478
+
479
+ try:
480
+ shutil.rmtree(path)
481
+ except OSError as e:
482
+ failed.append(path)
483
+ _warn(logger, f'AOT: 残留临时目录清理失败: {path} '
484
+ f'({age / 3600:.1f} 小时前, {e}); '
485
+ f'{_manual_removal_hint(path)}')
486
+ continue
487
+
488
+ removed.append(path)
489
+ _debug(logger, f'AOT: 已清理陈旧临时目录: {path} '
490
+ f'({age / 3600:.1f} 小时前)')
491
+
492
+ if removed:
493
+ _debug(logger, f'AOT: 陈旧临时目录清理完成, 共 {len(removed)} 个')
494
+ return SweepResult(removed, failed)
495
+
496
+
497
+ def _remove_temp_dir(tmp: str, logger) -> None:
498
+ """删除本次构建的临时目录; 失败时告警而不是静默吞掉 (§3.3)。
499
+
500
+ ``shutil.rmtree(ignore_errors=True)`` 会让「删不掉」完全静默, 于是残留
501
+ 在受限环境 (沙箱 / 异常 ACL) 里不断累积, 最终让任何遍历仓库的工具报
502
+ Access is denied。这里改为: 失败 -> warning (含绝对路径与手动删除提示)。
503
+ """
504
+ try:
505
+ shutil.rmtree(tmp)
506
+ except FileNotFoundError:
507
+ pass # 目录已不存在: 目的已达成
508
+ except Exception as e: # noqa: BLE001 - rmtree 正常只抛 OSError,
509
+ # 但这里处于 finally, 任何异常都不能掩盖构建结果, 一律降级为 warning。
510
+ _warn(logger, f'AOT: 临时构建目录清理失败, 残留目录: '
511
+ f'{os.path.abspath(tmp)} (原因: {e}); '
512
+ f'{_manual_removal_hint(tmp)}')
513
+
514
+
515
+ def build(bytecode: bytes,
516
+ seg_file: bytes,
517
+ out: str,
518
+ target: Optional[str] = None,
519
+ keep_temp: bool = False,
520
+ debug: bool = False,
521
+ logger=None) -> str:
522
+ """构建独立静态可执行文件, 返回产物的绝对路径。
523
+
524
+ :param bytecode: UCBC 字节码 (codecin.native.encode_program 的产物)
525
+ :param seg_file: 段文件 (pack_seg_file 的产物; 初始内存段 + mem_size/sp/heap)
526
+ :param out: 输出路径
527
+ :param target: ``os/arch``, 默认当前平台
528
+ :param keep_temp: 保留临时构建目录 (排查失败用)
529
+ :param logger: 可选 logger (记录 go build 输出)
530
+ """
531
+ if not bytecode:
532
+ raise AotError('字节码为空')
533
+ goos, goarch = parse_target(target) if target else parse_target(host_target())
534
+ mod = module_dir()
535
+
536
+ # 先清掉上一次留下的陈旧残留 (默认 > 6 小时), 再建新目录: 受限环境下
537
+ # rmtree 可能失败, 没有这一步残留就会无限累积。
538
+ # 清理是尽力而为 —— 任何异常都必须吞掉, 绝不能因此让构建失败。
539
+ try:
540
+ sweep_stale_build_dirs(logger=logger)
541
+ except Exception as e: # noqa: BLE001
542
+ _debug(logger, f'AOT: 陈旧临时目录清理跳过 ({e})')
543
+
544
+ # 注意: 这里用 os.makedirs 而不是 tempfile.mkdtemp —— mkdtemp 会创建 0700
545
+ # 目录, 在受限环境 (沙箱 / 部分 CI 安全策略) 下随后向其中写文件会被拒绝。
546
+ # 模块目录不可写时 (只读安装 / 受限 ACL) 回退到可写临时 module + replace。
547
+ temp_module = False
548
+ tmp = os.path.join(mod, '.aotbuild-' + secrets.token_hex(6))
549
+ try:
550
+ os.makedirs(tmp, exist_ok=False)
551
+ except OSError:
552
+ temp_module = True
553
+ tmp = os.path.join(_native_build_root(),
554
+ '.aotbuild-' + secrets.token_hex(6))
555
+ os.makedirs(tmp, exist_ok=False)
556
+ try:
557
+ with open(os.path.join(tmp, 'main.go'), 'w', encoding='utf-8',
558
+ newline='\n') as f:
559
+ f.write(stub_source())
560
+ with open(os.path.join(tmp, 'program.ucbc'), 'wb') as f:
561
+ f.write(bytecode)
562
+ with open(os.path.join(tmp, 'program.segs'), 'wb') as f:
563
+ f.write(seg_file)
564
+ if temp_module:
565
+ native_dir = _NATIVE_DIR.replace(os.sep, '/')
566
+ with open(os.path.join(tmp, 'go.mod'), 'w', encoding='utf-8',
567
+ newline='\n') as f:
568
+ f.write('module codecin-aot-vm\n\n')
569
+ f.write(f'go {_module_go_version()}\n\n')
570
+ f.write('require codecin-native v0.0.0\n\n')
571
+ f.write(f'replace codecin-native => "{native_dir}"\n')
572
+
573
+ out_abs = os.path.abspath(out)
574
+ os.makedirs(os.path.dirname(out_abs) or '.', exist_ok=True)
575
+
576
+ env = dict(os.environ)
577
+ env['CGO_ENABLED'] = '0' # 关键: 静态链接
578
+ env['GOOS'] = goos
579
+ env['GOARCH'] = goarch
580
+ build_cwd = mod
581
+ pkg_arg = '.' + os.sep + os.path.basename(tmp)
582
+ if temp_module:
583
+ build_cwd = tmp
584
+ pkg_arg = '.'
585
+ go_tmp = os.path.join(tmp, '.gotmp')
586
+ os.makedirs(go_tmp, exist_ok=True)
587
+ env['GOTMPDIR'] = go_tmp
588
+ env['TMP'] = go_tmp
589
+ env['TEMP'] = go_tmp
590
+ if 'GOCACHE' not in env:
591
+ cache = os.path.join(os.path.dirname(tmp), '.gocache')
592
+ try:
593
+ os.makedirs(cache, exist_ok=True)
594
+ env['GOCACHE'] = cache
595
+ except OSError:
596
+ pass
597
+ # -trimpath 去掉本机路径; 默认 -s -w 去掉符号表, --build-debug 保留。
598
+ ldflags = [] if debug else ['-ldflags', '-s -w']
599
+ cmd = ['go', 'build', '-trimpath',
600
+ '-tags', 'netgo,osusergo',
601
+ *ldflags,
602
+ '-o', out_abs,
603
+ pkg_arg]
604
+ if logger:
605
+ logger.debug(f'AOT build: {cmd} (cwd={build_cwd}, GOOS={goos}, '
606
+ f'GOARCH={goarch}, CGO_ENABLED=0)')
607
+ try:
608
+ proc, detail = _run_go_build(cmd, build_cwd, env, logger)
609
+ except FileNotFoundError as e:
610
+ from .environment import missing_tool_message
611
+ raise AotError(missing_tool_message(
612
+ 'go', 'AOT 构建独立可执行文件')) from e
613
+ except subprocess.TimeoutExpired as e:
614
+ raise AotError('go build 超时') from e
615
+ if proc.returncode != 0:
616
+ if _looks_like_cache_denied(detail) and 'GOCACHE' not in os.environ:
617
+ detail += ('\n提示: 默认 Go 构建缓存不可写且回退失败; '
618
+ '可显式设置 GOCACHE 指向可写目录后重试')
619
+ raise AotError(f'go build 失败 (目标 {goos}/{goarch}): {detail}')
620
+ if not os.path.isfile(out_abs):
621
+ raise AotError(f'go build 未产出文件: {out_abs}')
622
+ return out_abs
623
+ finally:
624
+ if keep_temp:
625
+ if logger:
626
+ logger.info(f'AOT 临时目录保留: {tmp}')
627
+ else:
628
+ _remove_temp_dir(tmp, logger)
629
+
630
+
631
+ def _native_build_root() -> str:
632
+ """返回 native 后端可写的临时构建根目录。
633
+
634
+ 优先使用源码树根 (workspace), 受限安装环境回退到模块目录/当前目录。
635
+ 这里刻意使用 ``os.makedirs`` 而不是 ``tempfile.mkdtemp``: 后者在 Windows
636
+ 受限 ACL 下会创建 0700 目录, 随后写文件被拒绝。
637
+ """
638
+ candidates = [
639
+ os.path.dirname(os.path.dirname(_NATIVE_DIR)),
640
+ os.path.dirname(_NATIVE_DIR),
641
+ _NATIVE_DIR,
642
+ os.getcwd(),
643
+ ]
644
+ for root in candidates:
645
+ try:
646
+ os.makedirs(root, exist_ok=True)
647
+ probe = os.path.join(root, '.aotwrite-' + secrets.token_hex(4))
648
+ os.makedirs(probe, exist_ok=False)
649
+ os.rmdir(probe)
650
+ return root
651
+ except OSError:
652
+ continue
653
+ return os.getcwd()
654
+
655
+
656
+ def _module_go_version() -> str:
657
+ """读取 codecin-native/go.mod 的 go 指令 (拿不到时用 1.26)。"""
658
+ try:
659
+ with open(os.path.join(_NATIVE_DIR, 'go.mod'), encoding='utf-8') as f:
660
+ for line in f:
661
+ parts = line.split()
662
+ if len(parts) == 2 and parts[0] == 'go':
663
+ return parts[1]
664
+ except OSError:
665
+ pass
666
+ return '1.26'
667
+
668
+
669
+ def build_native(go_source: str,
670
+ out: str,
671
+ target: Optional[str] = None,
672
+ keep_temp: bool = False,
673
+ debug: bool = False,
674
+ logger=None) -> str:
675
+ """用 native 代码生成产物构建独立静态可执行文件。
676
+
677
+ 与 :func:`build` 的区别: 临时模块包含生成好的 main.go (无 UCBC/段文件),
678
+ 通过 ``replace codecin-native => <源码树>`` 复用 engine 运行时。
679
+ """
680
+ if not go_source.strip():
681
+ raise AotError('native 代码生成结果为空')
682
+ goos, goarch = parse_target(target) if target else parse_target(host_target())
683
+ root = _native_build_root()
684
+ tmp = os.path.join(root, '.aotbuild-' + secrets.token_hex(6))
685
+ os.makedirs(tmp, exist_ok=False)
686
+ try:
687
+ with open(os.path.join(tmp, 'main.go'), 'w', encoding='utf-8',
688
+ newline='\n') as f:
689
+ f.write(go_source)
690
+ native_dir = _NATIVE_DIR.replace(os.sep, '/')
691
+ with open(os.path.join(tmp, 'go.mod'), 'w', encoding='utf-8',
692
+ newline='\n') as f:
693
+ f.write('module codecin-aot\n\n')
694
+ f.write(f'go {_module_go_version()}\n\n')
695
+ f.write('require codecin-native v0.0.0\n\n')
696
+ f.write(f'replace codecin-native => "{native_dir}"\n')
697
+
698
+ out_abs = os.path.abspath(out)
699
+ os.makedirs(os.path.dirname(out_abs) or '.', exist_ok=True)
700
+
701
+ env = dict(os.environ)
702
+ env['CGO_ENABLED'] = '0'
703
+ env['GOOS'] = goos
704
+ env['GOARCH'] = goarch
705
+ # 编译子进程的临时目录: 受限 Windows ACL 下系统 TMP 可能不可写。
706
+ go_tmp = os.path.join(tmp, '.gotmp')
707
+ os.makedirs(go_tmp, exist_ok=True)
708
+ env['GOTMPDIR'] = go_tmp
709
+ env['TMP'] = go_tmp
710
+ env['TEMP'] = go_tmp
711
+ if 'GOCACHE' not in env:
712
+ cache = os.path.join(root, '.gocache')
713
+ try:
714
+ os.makedirs(cache, exist_ok=True)
715
+ env['GOCACHE'] = cache
716
+ except OSError:
717
+ pass
718
+ ldflags = [] if debug else ['-ldflags', '-s -w']
719
+ cmd = ['go', 'build', '-trimpath',
720
+ '-tags', 'netgo,osusergo',
721
+ *ldflags,
722
+ '-o', out_abs, '.']
723
+ if logger:
724
+ logger.debug(f'AOT native build: {cmd} (cwd={tmp}, '
725
+ f'GOOS={goos}, GOARCH={goarch}, CGO_ENABLED=0)')
726
+ try:
727
+ proc, detail = _run_go_build(cmd, tmp, env, logger)
728
+ except FileNotFoundError as e:
729
+ from .environment import missing_tool_message
730
+ raise AotError(missing_tool_message(
731
+ 'go', 'AOT native 构建')) from e
732
+ except subprocess.TimeoutExpired as e:
733
+ raise AotError('go build 超时') from e
734
+ if proc.returncode != 0:
735
+ if _looks_like_cache_denied(detail) and 'GOCACHE' not in os.environ:
736
+ detail += ('\n提示: 默认 Go 构建缓存不可写且回退失败; '
737
+ '可显式设置 GOCACHE 指向可写目录后重试')
738
+ raise AotError(f'go build 失败 (native, 目标 {goos}/{goarch}): '
739
+ f'{detail}')
740
+ if not os.path.isfile(out_abs):
741
+ raise AotError(f'go build 未产出文件: {out_abs}')
742
+ return out_abs
743
+ finally:
744
+ if keep_temp:
745
+ if logger:
746
+ logger.info(f'AOT native 临时目录保留: {tmp}')
747
+ else:
748
+ _remove_temp_dir(tmp, logger)
749
+
750
+
751
+ def program_dependencies(program_file: str) -> List[str]:
752
+ """返回程序依赖的全部 .cin 文件 (含自身, 去重保序)。
753
+
754
+ ASM/PL/BIN 没有 import 闭包, 返回自身; CIN 与 ``build_program`` 使用同一
755
+ 套解析规则。
756
+ """
757
+ if os.path.splitext(program_file)[1].lower() != '.cin':
758
+ return [program_file]
759
+ from .cin import collect_imported_files
760
+ return collect_imported_files(program_file)
761
+
762
+
763
+ def _compile_program(program_file: str,
764
+ total: int,
765
+ optimize: int,
766
+ logger=None) -> dict:
767
+ """把 CIN/ASM/PL/BIN 统一装载成 AOT 需要的指令与内存段。"""
768
+ ext = os.path.splitext(program_file)[1].lower()
769
+ from .errors import CompilerError
770
+
771
+ if ext == '.cin':
772
+ from .cin import CINCompiler, collect_imported_files
773
+ try:
774
+ deps = collect_imported_files(program_file)
775
+ except CompilerError as e:
776
+ raise AotError(f'依赖检查失败: {e}') from e
777
+ missing = [p for p in deps if not os.path.isfile(p)]
778
+ if missing:
779
+ raise AotError('依赖库缺失: ' + ', '.join(missing))
780
+ try:
781
+ res = CINCompiler().compile(program_file)
782
+ except CompilerError as e:
783
+ raise AotError(f'编译失败: {e}') from e
784
+ labels = dict(res.labels)
785
+ entry_pc = getattr(res, 'entry_pc', 0) or 0
786
+ instructions = list(res.instructions)
787
+ if int(optimize or 0) > 0:
788
+ from .optimizer import optimize as optimize_ir
789
+ instructions, labels, entry_pc = optimize_ir(
790
+ instructions, labels, int(optimize), int(entry_pc))
791
+ oob = []
792
+ for addr, data in res.data_writes:
793
+ end = addr + len(data)
794
+ if addr < 0 or end > total:
795
+ oob.append((addr, len(data)))
796
+ if oob:
797
+ raise AotError(
798
+ f'数据段超出内存大小 {total} 字节: '
799
+ + ', '.join(f'addr=0x{a:x} size={n}' for a, n in oob[:4])
800
+ + '; 用 --mem-size 增大后重试')
801
+ segs: List[Tuple[int, bytes]] = []
802
+ if res.data_writes:
803
+ end_max = max(addr + len(data) for addr, data in res.data_writes)
804
+ buf = bytearray(end_max)
805
+ for addr, data in res.data_writes:
806
+ buf[addr:addr + len(data)] = data
807
+ segs.append((0, bytes(buf)))
808
+ return {
809
+ 'instructions': instructions,
810
+ 'labels': labels,
811
+ 'data_labels': dict(res.data_labels),
812
+ 'entry_pc': entry_pc,
813
+ 'mem_size': total,
814
+ 'sp': total - _STACK_SLOT,
815
+ 'heap_base': total // 2,
816
+ 'segments': segs,
817
+ 'deps': deps,
818
+ }
819
+
820
+ if ext == '.co':
821
+ from .object import ObjectError, read_object
822
+ try:
823
+ obj = read_object(program_file)
824
+ except ObjectError as e:
825
+ raise AotError(str(e)) from e
826
+ return {
827
+ 'instructions': list(obj['instructions']),
828
+ 'labels': dict(obj.get('labels', {})),
829
+ 'data_labels': dict(obj.get('data_labels', {})),
830
+ 'entry_pc': int(obj.get('entry_pc', 0)),
831
+ 'mem_size': int(obj.get('mem_size', total)),
832
+ 'sp': int(obj.get('sp', total - _STACK_SLOT)),
833
+ 'heap_base': int(obj.get('heap_base', total // 2)),
834
+ 'segments': list(obj.get('segments', [])),
835
+ 'deps': [program_file],
836
+ }
837
+
838
+ if ext not in ('.asm', '.pl', '.bin', '.sdgcc'):
839
+ raise AotError(f'不支持 AOT 输入格式: {ext or "(无扩展名)"}')
840
+
841
+ # ASM/PL 由 Assembler 装载; BIN/SDGCC 由 crom.load_bin 解码。
842
+ from . import Config
843
+ from .cpu import CPU
844
+ from .errors import CPUSimulatorError
845
+ try:
846
+ cpu = CPU(Config(log_level='ERROR', mem_size=total,
847
+ optimize=optimize), program_file)
848
+ except (CPUSimulatorError, CompilerError, OSError) as e:
849
+ raise AotError(f'编译失败: {e}') from e
850
+ return {
851
+ 'instructions': list(cpu.instructions),
852
+ 'labels': dict(cpu.labels),
853
+ 'data_labels': dict(cpu.data_labels),
854
+ 'entry_pc': cpu.entry_pc,
855
+ 'mem_size': len(cpu.memory),
856
+ 'sp': cpu.sp,
857
+ 'heap_base': cpu.heap_ptr,
858
+ 'segments': list(cpu.memory.snapshot_segments()),
859
+ 'deps': [program_file],
860
+ }
861
+
862
+
863
+ def build_from_ir(instructions,
864
+ labels: Dict[str, int],
865
+ data_labels: Dict[str, int],
866
+ segments: List[Tuple[int, bytes]],
867
+ entry_pc: int,
868
+ mem_size: int,
869
+ sp: int,
870
+ heap_base: int,
871
+ out: str,
872
+ target: Optional[str] = None,
873
+ backend: str = 'auto',
874
+ max_instructions: int = 0,
875
+ optimize: int = 0,
876
+ program_name: str = 'linked',
877
+ keep_temp: bool = False,
878
+ debug: bool = False,
879
+ use_cache: bool = False,
880
+ cache_key: Optional[str] = None,
881
+ c_static: bool = False,
882
+ c_strip: bool = False,
883
+ c_keep_c: bool = False,
884
+ logger=None) -> str:
885
+ """从已解析的指令流/内存段构建 AOT 产物 (供 linker 复用)。"""
886
+ from .native import encode_program
887
+
888
+ if int(optimize or 0) > 0:
889
+ from .optimizer import optimize as optimize_ir
890
+ instructions, labels, entry_pc = optimize_ir(
891
+ list(instructions), dict(labels), int(optimize), int(entry_pc))
892
+
893
+ all_labels = dict(labels)
894
+ all_labels.update(data_labels)
895
+ bytecode = encode_program(instructions, entry_pc, all_labels)
896
+ seg_file = pack_seg_file(mem_size, sp, heap_base, segments)
897
+
898
+ goos, _goarch = parse_target(target) if target else \
899
+ parse_target(host_target())
900
+ if not out:
901
+ out = program_name + exe_suffix(goos)
902
+ if goos == 'windows' and not out.lower().endswith('.exe'):
903
+ out += '.exe'
904
+
905
+ if use_cache and cache_key and _cache_lookup(cache_key, goos, out, logger):
906
+ return os.path.abspath(out)
907
+
908
+ from . import cbackend
909
+ c_ok, c_reason = cbackend.supports(instructions)
910
+ if backend == 'c':
911
+ if not c_ok:
912
+ raise AotError(f'C 后端不支持该程序: {c_reason}')
913
+ effective = 'c'
914
+ elif backend == 'auto':
915
+ effective = 'c' if c_ok else resolve_backend('auto',
916
+ len(instructions))
917
+ if not c_ok and logger:
918
+ logger.info(f'AOT: C 后端不适用 ({c_reason}), '
919
+ f'改走 {effective} 后端')
920
+ else:
921
+ effective = resolve_backend(backend, len(instructions))
922
+
923
+ if effective == 'c':
924
+ goos2, goarch2 = parse_target(target) if target else \
925
+ parse_target(host_target())
926
+ try:
927
+ cname = cbackend.c_target(goos2, goarch2)
928
+ except cbackend.CBackendError as e:
929
+ raise AotError(str(e)) from e
930
+ try:
931
+ built = cbackend.compile_instructions(
932
+ instructions, labels, segments, entry_pc, mem_size, sp,
933
+ heap_base, out, target=cname, optimize=optimize,
934
+ keep_c=c_keep_c, static_link=c_static,
935
+ strip_binary=c_strip)
936
+ except cbackend.CBackendError as e:
937
+ raise AotError(f'C 后端编译失败: {e}') from e
938
+ elif effective == 'vm':
939
+ built = build(bytes(bytecode), seg_file, out, target=target,
940
+ keep_temp=keep_temp, debug=debug, logger=logger)
941
+ else:
942
+ if effective != 'native':
943
+ raise AotError(
944
+ f'未知 AOT 后端: {backend} (可选 auto / c / native / vm)')
945
+
946
+ from .native_codegen import NativeCodegenError, generate_go_source
947
+ try:
948
+ source = generate_go_source(
949
+ instructions,
950
+ labels,
951
+ segments,
952
+ entry_pc=entry_pc,
953
+ mem_size=mem_size,
954
+ sp=sp,
955
+ heap_base=heap_base,
956
+ max_steps=max_instructions,
957
+ program_name=program_name,
958
+ )
959
+ except NativeCodegenError as e:
960
+ raise AotError(f'native 代码生成失败: {e}') from e
961
+ built = build_native(source, out, target=target, keep_temp=keep_temp,
962
+ debug=debug, logger=logger)
963
+ if use_cache and cache_key:
964
+ _cache_store(cache_key, goos, built, logger)
965
+ return built
966
+
967
+
968
+ def build_program(program_file: str,
969
+ out: Optional[str] = None,
970
+ target: Optional[str] = None,
971
+ keep_temp: bool = False,
972
+ mem_size: Optional[int] = None,
973
+ backend: str = 'auto',
974
+ max_instructions: int = 0,
975
+ optimize: int = 0,
976
+ use_cache: bool = True,
977
+ debug: bool = False,
978
+ c_static: bool = False,
979
+ c_strip: bool = False,
980
+ c_keep_c: bool = False,
981
+ logger=None) -> str:
982
+ """便捷入口: 由 .cin/.asm/.pl/.bin 构建可执行文件。
983
+
984
+ CIN 构建前会解析 import 闭包做**依赖完整性检查** (缺失/循环 ->
985
+ :class:`AotError`), 再把全部依赖模块在编译期展开并**嵌入**产物。
986
+ ASM/PL 由汇编器装载, BIN 由 crom.load_bin 解码。
987
+
988
+ ``backend='auto'`` (默认) 在指令数不超过 :data:`NATIVE_INSTRUCTION_LIMIT`
989
+ 时使用 native 后端, 否则回退 VM; ``'native'``/``'vm'`` 可强制指定。
990
+ """
991
+ if not os.path.isfile(program_file):
992
+ raise AotError(f'找不到程序文件: {program_file}')
993
+
994
+ goos, _goarch = parse_target(target) if target else \
995
+ parse_target(host_target())
996
+
997
+ total = int(mem_size) if mem_size else DEFAULT_MEM_SIZE
998
+ if total < 256:
999
+ total = 256
1000
+
1001
+ if not out:
1002
+ out = os.path.splitext(program_file)[0] + exe_suffix(goos)
1003
+ if goos == 'windows' and not out.lower().endswith('.exe'):
1004
+ out += '.exe' # README: Windows 目标自动补 .exe
1005
+
1006
+ cache_key = None
1007
+ if c_static or c_strip or c_keep_c:
1008
+ use_cache = False # 这些选项会改变产物, 不走共享缓存
1009
+ if use_cache:
1010
+ cache_key = build_cache_key(program_file, target, backend, optimize,
1011
+ mem_size, max_instructions, debug=debug)
1012
+ if cache_key and _cache_lookup(cache_key, goos, out, logger):
1013
+ return os.path.abspath(out)
1014
+
1015
+ compiled = _compile_program(program_file, total, optimize, logger)
1016
+ instructions = compiled['instructions']
1017
+ labels = compiled['labels']
1018
+ total = compiled['mem_size']
1019
+ deps = compiled['deps']
1020
+
1021
+ if logger:
1022
+ extra = [os.path.basename(p) for p in deps[1:]]
1023
+ if extra:
1024
+ logger.info(f'AOT: 已嵌入 {len(extra)} 个依赖库: '
1025
+ f'{", ".join(extra)}')
1026
+ else:
1027
+ logger.info('AOT: 无外部依赖 (单文件程序)')
1028
+
1029
+ built = build_from_ir(
1030
+ instructions,
1031
+ labels,
1032
+ compiled['data_labels'],
1033
+ compiled['segments'],
1034
+ entry_pc=compiled['entry_pc'],
1035
+ mem_size=total,
1036
+ sp=compiled['sp'],
1037
+ heap_base=compiled['heap_base'],
1038
+ out=out,
1039
+ target=target,
1040
+ backend=backend,
1041
+ max_instructions=max_instructions,
1042
+ program_name=os.path.basename(program_file),
1043
+ keep_temp=keep_temp,
1044
+ debug=debug,
1045
+ c_static=c_static,
1046
+ c_strip=c_strip,
1047
+ c_keep_c=c_keep_c,
1048
+ logger=logger,
1049
+ )
1050
+ if cache_key:
1051
+ _cache_store(cache_key, goos, built, logger)
1052
+ return built
1053
+
1054
+
1055
+ def supported_targets() -> List[str]:
1056
+ """文档/帮助用: 常用目标列表。"""
1057
+ return list(SUPPORTED_TARGETS)