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
@@ -0,0 +1,519 @@
1
+ """包/项目清单模型与语义化版本约束。
2
+
3
+ 两个清单文件:
4
+
5
+ ``pic.toml`` (包)
6
+ ``[package]`` 段描述 ``name`` / ``version`` / ``entry`` / ``repo`` 等;
7
+ ``[dependencies]`` 段描述依赖 (字符串版本或内联表)。
8
+
9
+ ``mkn.toml`` (项目)
10
+ ``[project]`` 段 (也接受 ``[package]`` 别名), ``[build]`` 段与
11
+ ``[dependencies]`` 段。
12
+
13
+ 依赖值支持两种写法::
14
+
15
+ [dependencies]
16
+ mathx = "1.2.0" # 版本约束 (通过注册表 / 本地仓库解析)
17
+
18
+ [dependencies.mathx]
19
+ git = "https://github.com/u/cin-mathx"
20
+ tag = "v1.2.0" # 或 rev = "<commit>"
21
+ path = "../mathx" # 本地路径依赖 (优先级最高)
22
+
23
+ 本模块只做**解析与校验**, 不访问网络, 也不复制文件。
24
+ """
25
+
26
+ import os
27
+ import re
28
+ from dataclasses import dataclass, field
29
+ from typing import Any, Dict, List, Optional, Tuple
30
+
31
+ from .toml import TomlError
32
+ from .toml import load as _load_toml
33
+
34
+ __all__ = [
35
+ 'Dependency', 'ManifestError', 'MknManifest', 'PackageMeta',
36
+ 'find_project_root', 'load_mkn_manifest', 'load_package_manifest',
37
+ 'parse_version', 'satisfies', 'validate_name', 'validate_version',
38
+ ]
39
+
40
+ _NAME_RE = re.compile(r'^[A-Za-z][A-Za-z0-9_-]{0,63}$')
41
+ _VERSION_RE = re.compile(r'^[vV]?(\d+)\.(\d+)\.(\d+)'
42
+ r'(?:[-+][0-9A-Za-z.+-]+)?$')
43
+
44
+ PIC_MANIFEST = 'pic.toml'
45
+ MKN_MANIFEST = 'mkn.toml'
46
+
47
+
48
+ class ManifestError(ValueError):
49
+ """清单缺失/字段非法/版本约束非法。"""
50
+
51
+
52
+ class VersionError(ManifestError):
53
+ """版本号或版本约束无法解析。"""
54
+
55
+
56
+ def validate_name(name: Any, what: str = '包名') -> str:
57
+ text = str(name or '').strip()
58
+ if not _NAME_RE.match(text):
59
+ raise ManifestError(
60
+ f'{what}非法: {name!r} (需以字母开头, 仅含字母/数字/下划线/连字符, '
61
+ f'长度 1..64)')
62
+ return text
63
+
64
+
65
+ def validate_version(version: Any) -> str:
66
+ text = str(version or '').strip()
67
+ if not _VERSION_RE.match(text):
68
+ raise ManifestError(
69
+ f'版本号非法: {version!r} (需为 x.y.z, 可带 -预发布/+构建 后缀)')
70
+ return text
71
+
72
+
73
+ def parse_version(version: Any) -> Tuple[int, int, int]:
74
+ text = str(version or '').strip()
75
+ m = _VERSION_RE.match(text)
76
+ if not m:
77
+ raise VersionError(f'版本号非法: {version!r} (需为 x.y.z)')
78
+ return int(m.group(1)), int(m.group(2)), int(m.group(3))
79
+
80
+
81
+ _LOOSE_RE = re.compile(
82
+ r'^[vV]?(\d+)(?:\.(\d+|[xX*]))?(?:\.(\d+|[xX*]))?(?:[-+].*)?$')
83
+
84
+
85
+ def _parse_loose(version: Any) -> Tuple[Tuple[int, int, int], int]:
86
+ """约束里的版本: 允许 ``1`` / ``1.2`` / ``1.x`` / ``1.2.x``。
87
+
88
+ 返回 ``(数值三元组, 通配级别)``; 通配级别 1 表示 ``1.x``, 2 表示
89
+ ``1.2.x``, 0 表示精确三段。
90
+ """
91
+ text = str(version or '').strip()
92
+ m = _LOOSE_RE.match(text)
93
+ if not m:
94
+ raise VersionError(f'版本号非法: {version!r}')
95
+ wildcard = 0
96
+ values: List[int] = []
97
+ for idx, part in enumerate((m.group(1), m.group(2), m.group(3))):
98
+ if part is None:
99
+ values.append(0)
100
+ continue
101
+ if part in ('x', 'X', '*'):
102
+ wildcard = idx
103
+ values.append(0)
104
+ continue
105
+ values.append(int(part))
106
+ return (values[0], values[1], values[2]), wildcard
107
+
108
+
109
+ def _next_major(v: Tuple[int, int, int]) -> Tuple[int, int, int]:
110
+ return (v[0] + 1, 0, 0)
111
+
112
+
113
+ def _next_minor(v: Tuple[int, int, int]) -> Tuple[int, int, int]:
114
+ return (v[0], v[1] + 1, 0)
115
+
116
+
117
+ def _next_patch(v: Tuple[int, int, int]) -> Tuple[int, int, int]:
118
+ return (v[0], v[1], v[2] + 1)
119
+
120
+
121
+ def _satisfies_one(version: Tuple[int, int, int], cond: str) -> bool:
122
+ cond = cond.strip()
123
+ if not cond or cond in ('*', 'latest', 'any'):
124
+ return True
125
+ if cond.startswith('^'):
126
+ base, _ = _parse_loose(cond[1:])
127
+ upper = _next_major(base) if base[0] > 0 else (
128
+ _next_minor(base) if base[1] > 0 else _next_patch(base))
129
+ return base <= version < upper
130
+ if cond.startswith('~'):
131
+ base, _ = _parse_loose(cond[1:])
132
+ return base <= version < _next_minor(base)
133
+ for op in ('>=', '<=', '==', '!=', '>', '<', '='):
134
+ if cond.startswith(op):
135
+ base, wildcard = _parse_loose(cond[len(op):])
136
+ if wildcard:
137
+ return _satisfies_one(version, cond[len(op):])
138
+ if op == '>=':
139
+ return version >= base
140
+ if op == '<=':
141
+ return version <= base
142
+ if op == '>':
143
+ return version > base
144
+ if op == '<':
145
+ return version < base
146
+ if op == '!=':
147
+ return version != base
148
+ return version == base
149
+ base, wildcard = _parse_loose(cond)
150
+ if wildcard == 1: # 1.x
151
+ return (base[0], 0, 0) <= version < (base[0] + 1, 0, 0)
152
+ if wildcard == 2: # 1.2.x
153
+ lower = (base[0], base[1], 0)
154
+ return lower <= version < (base[0], base[1] + 1, 0)
155
+ return version == base
156
+
157
+
158
+ def satisfies(version: Any, constraint: Optional[str]) -> bool:
159
+ """版本是否满足约束。
160
+
161
+ 支持 ``*`` / 精确版本 / ``^1.2.0`` / ``~1.2.0`` / ``>=1.0,<2.0`` /
162
+ ``1.x`` / ``1.2.x`` / ``||`` 组合。空约束视为任意版本。
163
+ """
164
+ ver = parse_version(version)
165
+ text = str(constraint or '').strip()
166
+ if not text or text in ('*', 'latest', 'any'):
167
+ return True
168
+ for clause in text.split('||'):
169
+ parts = [p for p in re.split(r'[,\s]+', clause.strip()) if p]
170
+ if parts and all(_satisfies_one(ver, p) for p in parts):
171
+ return True
172
+ return False
173
+
174
+
175
+ @dataclass
176
+ class Dependency:
177
+ """一条依赖声明。"""
178
+
179
+ name: str
180
+ constraint: str = ''
181
+ git: str = ''
182
+ tag: str = ''
183
+ rev: str = ''
184
+ path: str = ''
185
+ optional: bool = False
186
+
187
+ def __post_init__(self) -> None:
188
+ self.name = validate_name(self.name, '依赖名')
189
+
190
+ @property
191
+ def is_path(self) -> bool:
192
+ return bool(self.path)
193
+
194
+ @property
195
+ def is_git(self) -> bool:
196
+ return bool(self.git)
197
+
198
+ @property
199
+ def spec(self) -> str:
200
+ """用于展示/安装的单行规格。"""
201
+ if self.path:
202
+ return f'path:{self.path}'
203
+ if self.git:
204
+ ref = self.tag or self.rev
205
+ return f'git:{self.git}' + (f'@{ref}' if ref else '')
206
+ return f'{self.name}@{self.constraint}' if self.constraint else self.name
207
+
208
+ def to_dict(self) -> Dict[str, Any]:
209
+ data: Dict[str, Any] = {}
210
+ if self.constraint:
211
+ data['version'] = self.constraint
212
+ if self.git:
213
+ data['git'] = self.git
214
+ if self.tag:
215
+ data['tag'] = self.tag
216
+ if self.rev:
217
+ data['rev'] = self.rev
218
+ if self.path:
219
+ data['path'] = self.path
220
+ if self.optional:
221
+ data['optional'] = True
222
+ return data
223
+
224
+
225
+ def _dependency_from(name: str, value: Any, base_dir: str) -> Dependency:
226
+ if isinstance(value, str):
227
+ return Dependency(name=name, constraint=value.strip())
228
+ if isinstance(value, bool):
229
+ raise ManifestError(f'依赖 {name!r} 的值非法: 需要版本字符串或表')
230
+ if not isinstance(value, dict):
231
+ raise ManifestError(f'依赖 {name!r} 的值非法: {value!r}')
232
+ constraint = str(value.get('version') or value.get('constraint') or '').strip()
233
+ git = str(value.get('git') or value.get('repo') or '').strip()
234
+ tag = str(value.get('tag') or '').strip()
235
+ rev = str(value.get('rev') or value.get('revision') or '').strip()
236
+ path = str(value.get('path') or '').strip()
237
+ if path and not os.path.isabs(path):
238
+ path = os.path.normpath(os.path.join(base_dir, path))
239
+ optional = bool(value.get('optional') or False)
240
+ if not (constraint or git or path):
241
+ raise ManifestError(
242
+ f'依赖 {name!r} 需要 version / git / path 中的至少一项')
243
+ return Dependency(name=name, constraint=constraint, git=git, tag=tag,
244
+ rev=rev, path=path, optional=optional)
245
+
246
+
247
+ @dataclass
248
+ class PackageMeta:
249
+ """``pic.toml`` 的包元数据。"""
250
+
251
+ root: str
252
+ manifest_path: str
253
+ name: str
254
+ version: str
255
+ description: str = ''
256
+ license: str = ''
257
+ authors: List[str] = field(default_factory=list)
258
+ entry: str = ''
259
+ repo: str = ''
260
+ tag: str = ''
261
+ keywords: List[str] = field(default_factory=list)
262
+ dependencies: List[Dependency] = field(default_factory=list)
263
+ raw: Dict[str, Any] = field(default_factory=dict)
264
+
265
+ @property
266
+ def entry_path(self) -> Optional[str]:
267
+ """解析后的入口文件绝对路径 (不存在时为 None)。"""
268
+ return _resolve_entry(self.root, self.entry, self.name)
269
+
270
+ @property
271
+ def entry_rel(self) -> str:
272
+ path = self.entry_path
273
+ if path is None:
274
+ return self.entry
275
+ return os.path.relpath(path, self.root).replace(os.sep, '/')
276
+
277
+ def to_dict(self) -> Dict[str, Any]:
278
+ package: Dict[str, Any] = {
279
+ 'name': self.name,
280
+ 'version': self.version,
281
+ }
282
+ for key in ('description', 'license', 'entry', 'repo', 'tag'):
283
+ value = getattr(self, key)
284
+ if value:
285
+ package[key] = value
286
+ if self.authors:
287
+ package['authors'] = list(self.authors)
288
+ if self.keywords:
289
+ package['keywords'] = list(self.keywords)
290
+ data: Dict[str, Any] = {'package': package}
291
+ if self.dependencies:
292
+ deps: Dict[str, Any] = {}
293
+ for dep in self.dependencies:
294
+ if dep.path or dep.git or dep.optional or dep.constraint:
295
+ deps[dep.name] = dep.to_dict() if (
296
+ dep.path or dep.git or dep.optional) else dep.constraint
297
+ data['dependencies'] = deps
298
+ return data
299
+
300
+
301
+ @dataclass
302
+ class MknManifest:
303
+ """``mkn.toml`` 的项目模型。"""
304
+
305
+ root: str
306
+ manifest_path: str
307
+ name: str
308
+ version: str
309
+ description: str = ''
310
+ license: str = ''
311
+ authors: List[str] = field(default_factory=list)
312
+ entry: str = 'src/main.cin'
313
+ repo: str = ''
314
+ tag: str = ''
315
+ dependencies: List[Dependency] = field(default_factory=list)
316
+ dev_dependencies: List[Dependency] = field(default_factory=list)
317
+ build: Dict[str, Any] = field(default_factory=dict)
318
+ raw: Dict[str, Any] = field(default_factory=dict)
319
+
320
+ @property
321
+ def entry_path(self) -> str:
322
+ path = _resolve_entry(self.root, self.entry, self.name)
323
+ if path is None:
324
+ raise ManifestError(
325
+ f'项目入口文件不存在: {self.entry!r} (项目根 {self.root})')
326
+ return path
327
+
328
+ @property
329
+ def target_dir(self) -> str:
330
+ return os.path.join(self.root, 'target')
331
+
332
+ @property
333
+ def pic_modules(self) -> str:
334
+ return os.path.join(self.root, 'pic_modules')
335
+
336
+ def build_option(self, key: str, default: Any = None) -> Any:
337
+ return self.build.get(key, default)
338
+
339
+ def to_dict(self) -> Dict[str, Any]:
340
+ project: Dict[str, Any] = {
341
+ 'name': self.name,
342
+ 'version': self.version,
343
+ 'entry': self.entry,
344
+ }
345
+ for key in ('description', 'license', 'repo', 'tag'):
346
+ value = getattr(self, key)
347
+ if value:
348
+ project[key] = value
349
+ if self.authors:
350
+ project['authors'] = list(self.authors)
351
+ data: Dict[str, Any] = {'project': project}
352
+ if self.build:
353
+ data['build'] = dict(self.build)
354
+ if self.dependencies:
355
+ deps: Dict[str, Any] = {}
356
+ for dep in self.dependencies:
357
+ if dep.path or dep.git or dep.optional:
358
+ deps[dep.name] = dep.to_dict()
359
+ else:
360
+ deps[dep.name] = dep.constraint
361
+ data['dependencies'] = deps
362
+ return data
363
+
364
+
365
+ def _within(root: str, path: str) -> bool:
366
+ root_abs = os.path.abspath(root)
367
+ path_abs = os.path.abspath(path)
368
+ try:
369
+ return os.path.commonpath([root_abs, path_abs]) == root_abs
370
+ except ValueError: # 不同盘符
371
+ return False
372
+
373
+
374
+ def _resolve_entry(root: str, entry: str, name: str) -> Optional[str]:
375
+ candidates = []
376
+ if entry:
377
+ candidates.append(entry)
378
+ candidates += [f'src/{name}.cin', f'{name}.cin', 'src/main.cin', 'main.cin']
379
+ seen = set()
380
+ for rel in candidates:
381
+ rel = rel.replace('/', os.sep)
382
+ path = os.path.normpath(os.path.join(root, rel))
383
+ if path in seen:
384
+ continue
385
+ seen.add(path)
386
+ if not _within(root, path):
387
+ continue
388
+ if os.path.isfile(path):
389
+ return path
390
+ return None
391
+
392
+
393
+ def find_project_root(start: str,
394
+ names: Tuple[str, ...] = (MKN_MANIFEST, PIC_MANIFEST)
395
+ ) -> Optional[str]:
396
+ """从 ``start`` 向上查找包含清单文件的目录。"""
397
+ path = os.path.abspath(start)
398
+ if os.path.isfile(path):
399
+ path = os.path.dirname(path)
400
+ while True:
401
+ for name in names:
402
+ if os.path.isfile(os.path.join(path, name)):
403
+ return path
404
+ parent = os.path.dirname(path)
405
+ if parent == path:
406
+ return None
407
+ path = parent
408
+
409
+
410
+ def _manifest_path(path_or_root: str, filename: str) -> str:
411
+ path = os.path.abspath(path_or_root)
412
+ if os.path.isdir(path):
413
+ candidate = os.path.join(path, filename)
414
+ if not os.path.isfile(candidate):
415
+ raise ManifestError(f'找不到清单文件: {candidate}')
416
+ return candidate
417
+ if not os.path.isfile(path):
418
+ raise ManifestError(f'清单文件不存在: {path}')
419
+ return path
420
+
421
+
422
+ def _load(path: str) -> Dict[str, Any]:
423
+ try:
424
+ return _load_toml(path)
425
+ except TomlError as e:
426
+ raise ManifestError(f'{path}: {e}') from e
427
+
428
+
429
+ def _require_text(table: Dict[str, Any], key: str, path: str,
430
+ what: str) -> str:
431
+ value = table.get(key)
432
+ if not isinstance(value, str) or not value.strip():
433
+ raise ManifestError(f'{path}: {what} 缺少字符串字段 {key!r}')
434
+ return value.strip()
435
+
436
+
437
+ def load_package_manifest(path_or_root: str,
438
+ require_entry: bool = True) -> PackageMeta:
439
+ """读取 ``pic.toml``; ``path_or_root`` 可为文件或包目录。"""
440
+ path = _manifest_path(path_or_root, PIC_MANIFEST)
441
+ root = os.path.dirname(path)
442
+ data = _load(path)
443
+ table = data.get('package')
444
+ if not isinstance(table, dict):
445
+ raise ManifestError(f'{path}: 缺少 [package] 表')
446
+ name = validate_name(_require_text(table, 'name', path, '[package]'))
447
+ version = validate_version(_require_text(table, 'version', path, '[package]'))
448
+ entry = str(table.get('entry') or '').strip()
449
+ authors = table.get('authors') or []
450
+ if isinstance(authors, str):
451
+ authors = [authors]
452
+ keywords = table.get('keywords') or []
453
+ if isinstance(keywords, str):
454
+ keywords = [keywords]
455
+ meta = PackageMeta(
456
+ root=root, manifest_path=path, name=name, version=version,
457
+ description=str(table.get('description') or '').strip(),
458
+ license=str(table.get('license') or '').strip(),
459
+ authors=[str(a) for a in authors],
460
+ entry=entry,
461
+ repo=str(table.get('repo') or table.get('repository') or '').strip(),
462
+ tag=str(table.get('tag') or '').strip(),
463
+ keywords=[str(k) for k in keywords],
464
+ raw=data,
465
+ )
466
+ deps_table = data.get('dependencies') or {}
467
+ if not isinstance(deps_table, dict):
468
+ raise ManifestError(f'{path}: [dependencies] 必须是表')
469
+ meta.dependencies = [
470
+ _dependency_from(name, value, root)
471
+ for name, value in deps_table.items()
472
+ ]
473
+ if require_entry and meta.entry_path is None:
474
+ raise ManifestError(
475
+ f'{path}: 包入口文件不存在 (entry={entry!r}; 已尝试 '
476
+ f'src/{name}.cin, {name}.cin, src/main.cin)')
477
+ return meta
478
+
479
+
480
+ def load_mkn_manifest(path_or_root: str) -> MknManifest:
481
+ """读取 ``mkn.toml``; ``[project]`` 与 ``[package]`` 均可。"""
482
+ path = _manifest_path(path_or_root, MKN_MANIFEST)
483
+ root = os.path.dirname(path)
484
+ data = _load(path)
485
+ table = data.get('project') or data.get('package')
486
+ if not isinstance(table, dict):
487
+ raise ManifestError(f'{path}: 缺少 [project] 表')
488
+ name = validate_name(_require_text(table, 'name', path, '[project]'))
489
+ version = validate_version(_require_text(table, 'version', path, '[project]'))
490
+ authors = table.get('authors') or []
491
+ if isinstance(authors, str):
492
+ authors = [authors]
493
+ manifest = MknManifest(
494
+ root=root, manifest_path=path, name=name, version=version,
495
+ description=str(table.get('description') or '').strip(),
496
+ license=str(table.get('license') or '').strip(),
497
+ authors=[str(a) for a in authors],
498
+ entry=str(table.get('entry') or 'src/main.cin').strip(),
499
+ repo=str(table.get('repo') or table.get('repository') or '').strip(),
500
+ tag=str(table.get('tag') or '').strip(),
501
+ build=dict(data.get('build') or {}),
502
+ raw=data,
503
+ )
504
+ deps_table = data.get('dependencies') or {}
505
+ dev_table = data.get('dev-dependencies') or {}
506
+ if not isinstance(deps_table, dict):
507
+ raise ManifestError(f'{path}: [dependencies] 必须是表')
508
+ if not isinstance(dev_table, dict):
509
+ raise ManifestError(f'{path}: [dev-dependencies] 必须是表')
510
+ manifest.dependencies = [
511
+ _dependency_from(name, value, root)
512
+ for name, value in deps_table.items()
513
+ ]
514
+ manifest.dev_dependencies = [
515
+ _dependency_from(name, value, root)
516
+ for name, value in dev_table.items()
517
+ ]
518
+ # 入口延迟到 build 时检查: 这样 `mkn init` 之后即使手写 entry 也能先验清单
519
+ return manifest