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/stats.py ADDED
@@ -0,0 +1,230 @@
1
+ import time
2
+ from collections import defaultdict
3
+ from typing import Any, Dict, List, Optional, Tuple
4
+
5
+ from .console import Console, Table
6
+ from .isa import Constants
7
+
8
+
9
+ class BranchPredictor:
10
+
11
+ def __init__(self):
12
+ self.saturating_counters: Dict[int, int] = {}
13
+ self.correct_predictions = 0
14
+ self.total_predictions = 0
15
+
16
+ def predict(self, pc: int) -> bool:
17
+ return self.saturating_counters.get(pc, 2) >= 2
18
+
19
+ def update(self, pc: int, taken: bool) -> None:
20
+ counter = self.saturating_counters.get(pc, 2)
21
+ counter = min(3, counter + 1) if taken else max(0, counter - 1)
22
+ self.saturating_counters[pc] = counter
23
+
24
+ def record_prediction(self, predicted: bool, actual: bool) -> None:
25
+ self.total_predictions += 1
26
+ if predicted == actual:
27
+ self.correct_predictions += 1
28
+
29
+ def get_accuracy(self) -> float:
30
+ if self.total_predictions == 0:
31
+ return 1.0
32
+ return self.correct_predictions / self.total_predictions
33
+
34
+
35
+ class PerformanceCounters:
36
+ def __init__(self):
37
+ self.counters = {
38
+ 'cycles': 0,
39
+ 'instructions': 0,
40
+ 'branches': 0,
41
+ 'branch_mispredictions': 0,
42
+ 'cache_hits': 0,
43
+ 'cache_misses': 0,
44
+ 'memory_reads': 0,
45
+ 'memory_writes': 0,
46
+ 'stalls': 0,
47
+ 'flops': 0,
48
+ }
49
+ self.branch_predictor = BranchPredictor()
50
+
51
+ def record_instruction(self, opcode: str) -> None:
52
+ self.counters['instructions'] += 1
53
+ if opcode in Constants.BRANCH_OPS:
54
+ self.counters['branches'] += 1
55
+ if opcode in Constants.FP_OPS:
56
+ self.counters['flops'] += 1
57
+
58
+ def record_branch_result(self, pc: int, taken: bool, predicted: bool) -> None:
59
+ self.branch_predictor.record_prediction(predicted, taken)
60
+ if taken != predicted:
61
+ self.counters['branch_mispredictions'] += 1
62
+ self.branch_predictor.update(pc, taken)
63
+
64
+ def record_cache(self, hit: bool) -> None:
65
+ if hit:
66
+ self.counters['cache_hits'] += 1
67
+ else:
68
+ self.counters['cache_misses'] += 1
69
+
70
+ def record_memory_read(self) -> None:
71
+ self.counters['memory_reads'] += 1
72
+
73
+ def record_memory_write(self) -> None:
74
+ self.counters['memory_writes'] += 1
75
+
76
+ def add_cycles(self, n: int) -> None:
77
+ self.counters['cycles'] += n
78
+
79
+ def get_ipc(self) -> float:
80
+ if self.counters['cycles'] == 0:
81
+ return 0
82
+ return self.counters['instructions'] / self.counters['cycles']
83
+
84
+ def get_stats(self) -> Dict[str, Any]:
85
+ stats = self.counters.copy()
86
+ stats['ipc'] = self.get_ipc()
87
+ stats['branch_accuracy'] = self.branch_predictor.get_accuracy()
88
+ total_cache = stats['cache_hits'] + stats['cache_misses']
89
+ stats['cache_hit_rate'] = stats['cache_hits'] / total_cache if total_cache > 0 else 0
90
+ return stats
91
+
92
+ def display(self, console: Console) -> None:
93
+ stats = self.get_stats()
94
+ table = Table(title="Performance Counters")
95
+ table.add_column("Metric")
96
+ table.add_column("Value")
97
+ for key, value in stats.items():
98
+ if key in ('branch_accuracy', 'cache_hit_rate'):
99
+ table.add_row(key.replace('_', ' ').title(), f"{value * 100:.1f}%")
100
+ elif key == 'ipc':
101
+ table.add_row("Instructions Per Cycle", f"{value:.2f}")
102
+ else:
103
+ table.add_row(key.replace('_', ' ').title(), str(value))
104
+ console.print(str(table))
105
+
106
+
107
+ class InstructionProfiler:
108
+
109
+ def __init__(self):
110
+ self.cycles: Dict[str, int] = defaultdict(int)
111
+ self.latency: Dict[str, int] = {
112
+ 'ADD': 1, 'SUB': 1, 'MUL': 3, 'DIV': 10,
113
+ 'LOAD': 4, 'STORE': 4, 'FADD': 3, 'FMUL': 5,
114
+ 'FDIV': 10, 'VADD': 2, 'VMUL': 4, 'VDIV': 8,
115
+ 'LSL': 1, 'LSR': 1, 'AND': 1, 'OR': 1, 'XOR': 1,
116
+ 'LD': 4, 'SD': 4, 'LDR': 4, 'STR': 4,
117
+ 'LB': 4, 'LH': 4, 'LW': 4, 'SB': 4, 'SH': 4, 'SW': 4,
118
+ }
119
+
120
+ def record(self, opcode: str) -> None:
121
+ self.cycles[opcode] += self.latency.get(opcode, 1)
122
+
123
+ def get_total_cycles(self) -> int:
124
+ return sum(self.cycles.values())
125
+
126
+ def display_report(self, console: Optional[Console] = None) -> None:
127
+ if console is None:
128
+ return
129
+ total = self.get_total_cycles()
130
+ table = Table(title="Instruction Cycle Profile")
131
+ table.add_column("Instruction")
132
+ table.add_column("Cycles")
133
+ table.add_column("Percentage")
134
+ for op, cycles in sorted(self.cycles.items(), key=lambda x: x[1], reverse=True)[:20]:
135
+ pct = (cycles / total * 100) if total > 0 else 0
136
+ table.add_row(op, str(cycles), f"{pct:.1f}%")
137
+ console.print(str(table))
138
+
139
+
140
+ class Statistics:
141
+ def __init__(self):
142
+ self.reset()
143
+
144
+ def reset(self):
145
+ self.instruction_count = 0
146
+ self.opcode_count: Dict[str, int] = defaultdict(int)
147
+ self.execution_time = 0.0
148
+ self.start_time: Optional[float] = None
149
+ self.memory_reads = 0
150
+ self.memory_writes = 0
151
+ self.inst_profiler = InstructionProfiler()
152
+ self.hot_instructions: Dict[str, int] = defaultdict(int)
153
+ self.performance_counters = PerformanceCounters()
154
+
155
+ def start(self):
156
+ self.start_time = time.time()
157
+
158
+ def stop(self):
159
+ if self.start_time:
160
+ self.execution_time = time.time() - self.start_time
161
+
162
+ def record_instruction(self, opcode: str):
163
+ self.instruction_count += 1
164
+ self.opcode_count[opcode] += 1
165
+ self.inst_profiler.record(opcode)
166
+ self.hot_instructions[opcode] += 1
167
+ self.performance_counters.record_instruction(opcode)
168
+
169
+ def record_memory_read(self):
170
+ self.memory_reads += 1
171
+ self.performance_counters.record_memory_read()
172
+
173
+ def record_memory_write(self):
174
+ self.memory_writes += 1
175
+ self.performance_counters.record_memory_write()
176
+
177
+ def record_cache(self, hit: bool):
178
+ self.performance_counters.record_cache(hit)
179
+
180
+ def record_branch(self, pc: int, taken: bool, predicted: bool):
181
+ self.performance_counters.record_branch_result(pc, taken, predicted)
182
+
183
+ def get_hot_instructions(self, top_n: int = 10) -> List[Tuple[str, int]]:
184
+ return sorted(self.hot_instructions.items(),
185
+ key=lambda x: x[1], reverse=True)[:top_n]
186
+
187
+ def display_summary(self, console: Optional[Console] = None,
188
+ cache_stats: Optional[Dict] = None,
189
+ native_used: bool = True) -> None:
190
+ if console is None:
191
+ return
192
+
193
+ table = Table(title="Execution Statistics")
194
+ table.add_column("Metric")
195
+ table.add_column("Value")
196
+ table.add_row("Engine", "Go native" if native_used else "Go native (未加载)")
197
+ table.add_row("Total Instructions", str(self.instruction_count))
198
+ table.add_row("Total Cycles", str(self.inst_profiler.get_total_cycles()))
199
+ if self.instruction_count > 0:
200
+ table.add_row("CPI (Cycles/Inst)",
201
+ f"{self.inst_profiler.get_total_cycles() / self.instruction_count:.2f}")
202
+ table.add_row("Execution Time", f"{self.execution_time:.4f}s")
203
+ if self.execution_time > 0:
204
+ table.add_row("Instructions/sec",
205
+ f"{self.instruction_count / self.execution_time:,.0f}")
206
+ table.add_row("Memory Reads", str(self.memory_reads))
207
+ table.add_row("Memory Writes", str(self.memory_writes))
208
+
209
+ perf_stats = self.performance_counters.get_stats()
210
+ table.add_row("Branch Accuracy", f"{perf_stats['branch_accuracy'] * 100:.1f}%")
211
+
212
+ if cache_stats:
213
+ table.add_row("Cache Hit Rate", f"{cache_stats.get('hit_rate', 0) * 100:.1f}%")
214
+
215
+ console.print(str(table))
216
+
217
+ if self.opcode_count:
218
+ op_table = Table(title="Instruction Usage")
219
+ op_table.add_column("Instruction")
220
+ op_table.add_column("Count")
221
+ op_table.add_column("Percentage")
222
+ total = sum(self.opcode_count.values())
223
+ for op, count in sorted(self.opcode_count.items(),
224
+ key=lambda x: x[1], reverse=True)[:20]:
225
+ pct = (count / total * 100) if total > 0 else 0
226
+ op_table.add_row(op, str(count), f"{pct:.1f}%")
227
+ console.print(str(op_table))
228
+
229
+ self.inst_profiler.display_report(console)
230
+ self.performance_counters.display(console)
codecin/stdlib.py ADDED
@@ -0,0 +1,138 @@
1
+ """内置标准库清单 (stdlib manifest): 哪些库可用于哪些执行路径。
2
+
3
+ ``codecin/lib/<name>/src/<name>.cin`` 下的官方标准库按**执行路径要求**分三类:
4
+
5
+ * 纯 CIN —— 只调用语言内建, 原生 / AOT 全部行为一致;
6
+ * 兼容层 (C/C++/Go) —— 纯 CIN 实现的三语言标准库兼容层 (cstd/cppstd/gostd),
7
+ 让 C、C++、Go 程序员以惯用名操作 CIN; 除标注的原生依赖外全路径可用;
8
+ * 需原生运行时 —— 调用了宿主能力内建 (音频/GUI/文件/网络/键盘/Termux...),
9
+ 沙箱模式下被拦截。
10
+
11
+ 分类由源码扫描得出 (是否引用 HOST_BUILTINS 内建名), 与库文件头注释保持
12
+ 单一事实来源, 避免文档漂移。对外接口::
13
+
14
+ library_report() -> List[Dict] (name/category/note/desc)
15
+ format_library_report() -> 多行纯文本表格 (无 ANSI, 可重定向)
16
+ """
17
+
18
+ import os
19
+ import re
20
+ from typing import Dict, List
21
+
22
+ LIB_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'lib')
23
+
24
+ #: C/C++/Go 三语言兼容层库 (纯 CIN, 语义对齐三语言标准库的惯用名)。
25
+ COMPAT_LIBS = {
26
+ 'cstd.cin': 'C 兼容层',
27
+ 'cppstd.cin': 'C++ 兼容层',
28
+ 'gostd.cin': 'Go 兼容层',
29
+ }
30
+
31
+ #: 分类文案。
32
+ CAT_PURE = '纯 CIN'
33
+ CAT_COMPAT = '兼容层'
34
+ CAT_NATIVE = '需原生运行时'
35
+
36
+
37
+ def _first_comment(text: str) -> str:
38
+ """返回首个 `//` 注释行的内容 (库的一句话描述)。"""
39
+ for line in text.splitlines():
40
+ s = line.strip()
41
+ if s.startswith('//'):
42
+ return s[2:].strip()
43
+ if s: # 先出现的是代码: 无头注释
44
+ return ''
45
+ return ''
46
+
47
+
48
+ def _clean_desc(desc: str) -> str:
49
+ """去掉头注释里的通用前缀与自引用路径, 留下 "xxx (模块名)" 式短描述。"""
50
+ for prefix in ('Code CIN 官方标准库:', 'Code CIN 纯 CIN ', 'Code CIN '):
51
+ if desc.startswith(prefix):
52
+ desc = desc[len(prefix):].strip()
53
+ break
54
+ # 去掉尾部 "(codecin/lib/x.cin)" 自引用
55
+ return re.sub(r'\s*\(codecin/lib/[^)]*\)\s*$', '', desc, flags=re.I).strip()
56
+
57
+
58
+ def _library_sources() -> Dict[str, str]:
59
+ """返回 ``{<name>.cin: 源文件路径}``;兼容旧平铺布局。"""
60
+ sources: Dict[str, str] = {}
61
+ if not os.path.isdir(LIB_DIR):
62
+ return sources
63
+ for entry in sorted(os.listdir(LIB_DIR)):
64
+ flat = os.path.join(LIB_DIR, entry)
65
+ if entry.endswith('.cin') and os.path.isfile(flat):
66
+ sources[entry] = flat
67
+ continue
68
+ source = os.path.join(LIB_DIR, entry, 'src', entry + '.cin')
69
+ if os.path.isfile(source):
70
+ sources[entry + '.cin'] = source
71
+ return sources
72
+
73
+
74
+ def library_report() -> List[Dict[str, str]]:
75
+ """扫描内置标准库目录, 返回按名称排序的清单。
76
+
77
+ 每项字段: ``name`` (文件名) / ``category`` (三类之一) / ``note``
78
+ (兼容层库的原生依赖标注或空) / ``desc`` (头注释一句话描述)。
79
+ """
80
+ # 惰性导入: HOST_BUILTINS 来自编译器模块, 只在真正生成清单时才需要。
81
+ from .cin import HOST_BUILTINS
82
+
83
+ sources = _library_sources()
84
+ report: List[Dict[str, str]] = []
85
+ for name in sorted(sources):
86
+ path = sources[name]
87
+ try:
88
+ with open(path, encoding='utf-8') as f:
89
+ text = f.read()
90
+ except OSError:
91
+ continue
92
+
93
+ used = [b for b in sorted(HOST_BUILTINS)
94
+ if re.search(rf'\b{re.escape(b)}\s*\(', text)]
95
+ if name in COMPAT_LIBS:
96
+ category = CAT_COMPAT
97
+ note = ('go_os_args_* 依赖原生'
98
+ if used else '')
99
+ elif used:
100
+ category = CAT_NATIVE
101
+ note = f'{len(used)} 个宿主内建'
102
+ else:
103
+ category = CAT_PURE
104
+ note = ''
105
+ report.append({
106
+ 'name': name,
107
+ 'category': category,
108
+ 'note': note,
109
+ 'desc': _first_comment(text),
110
+ })
111
+ return report
112
+
113
+
114
+ def format_library_report() -> str:
115
+ """把清单渲染成无 ANSI 的对齐文本 (与 --build-info 的输出风格一致)。"""
116
+ rows = library_report()
117
+ w_name = max([len(r['name']) for r in rows] + [len('模块')])
118
+ w_cat = max([len(r['category']) for r in rows] + [len('类别')])
119
+ # 中文描述按"显示宽度"对齐太复杂, 简单用字符数即可 (末列无需对齐)
120
+ lines = [
121
+ "Code CIN 内置标准库清单",
122
+ "",
123
+ f" {'模块'.ljust(w_name)} {'类别'.ljust(w_cat)} 说明",
124
+ f" {'-' * w_name} {'-' * w_cat} ----",
125
+ ]
126
+ for r in rows:
127
+ note = f" [{r['note']}]" if r['note'] else ''
128
+ desc = _clean_desc(r['desc']) + note
129
+ lines.append(f" {r['name'].ljust(w_name)} "
130
+ f"{r['category'].ljust(w_cat)} {desc}")
131
+ lines += [
132
+ "",
133
+ " 类别说明:",
134
+ f" {CAT_PURE} —— 原生/AOT 全路径行为一致",
135
+ f" {CAT_COMPAT} —— C/C++/Go 标准库兼容层 (纯 CIN; 兼容层内容见库头注释)",
136
+ f" {CAT_NATIVE} —— 调用宿主能力内建 (--sandbox 下被拦截)",
137
+ ]
138
+ return '\n'.join(lines)