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,515 @@
1
+ """pic 中央注册/分发服务器客户端。
2
+
3
+ 服务器: ``https://package.codecin.org.cn`` (可配置)
4
+ 认证: Cdifit ``https://www.cdifit.cn`` 的 AccessToken (Bearer)
5
+
6
+ 客户端只把 **元数据 + .cinpkg 制品** 上传到 package.codecin.org.cn;
7
+ Cdifit 仅用于登录/身份校验, 不再用于包存储。
8
+ """
9
+
10
+ import contextlib
11
+ import hashlib
12
+ import json
13
+ import os
14
+ import urllib.error
15
+ import urllib.parse
16
+ import urllib.request
17
+ from typing import Any, Dict, Iterable, List, Optional, Tuple
18
+
19
+ from .packaging.model import PackageMeta, satisfies, validate_name
20
+ from .packaging.toml import dumps as toml_dumps
21
+
22
+ try: # 尽量避免为了版本号在独立部署场景引入整个包
23
+ from . import __version__ as _PIC_VERSION
24
+ except Exception: # pragma: no cover
25
+ _PIC_VERSION = '0'
26
+
27
+ __all__ = [
28
+ 'DEFAULT_REGISTRY_URL', 'DIGEST_ALGORITHM', 'RegistryClient',
29
+ 'RegistryError', 'iter_package_files', 'manifest_digest',
30
+ 'package_modules', 'source_digest',
31
+ ]
32
+
33
+ DEFAULT_REGISTRY_URL = 'https://package.codecin.org.cn'
34
+ DIGEST_ALGORITHM = 'sha256'
35
+
36
+ _IGNORED_DIRS = frozenset({
37
+ '.git', '.hg', '.svn', '__pycache__', '.pytest_cache', '.ruff_cache',
38
+ 'dist', 'build', 'target', 'pic_modules', '.pic', '.mkn',
39
+ 'node_modules', '.venv', 'venv', 'META-INF',
40
+ })
41
+
42
+
43
+ class RegistryError(RuntimeError):
44
+ """中央服务器读写/校验失败。"""
45
+
46
+ def __init__(self, message: str, *, status: int = 0,
47
+ code: str = '', data: Any = None):
48
+ super().__init__(message)
49
+ self.status = status
50
+ self.code = code
51
+ self.data = data
52
+
53
+
54
+ def iter_package_files(root: str) -> Iterable[Tuple[str, str]]:
55
+ """遍历包内文件 (与 ``pic build`` 使用同一排除规则)。"""
56
+ root = os.path.abspath(root)
57
+ for dirpath, dirnames, filenames in os.walk(root):
58
+ dirnames[:] = sorted(d for d in dirnames if d not in _IGNORED_DIRS)
59
+ for filename in sorted(filenames):
60
+ if filename.endswith(('.pyc', '.cinpkg', '.mkn', '.cvm')):
61
+ continue
62
+ path = os.path.join(dirpath, filename)
63
+ rel = os.path.relpath(path, root).replace(os.sep, '/')
64
+ yield rel, path
65
+
66
+
67
+ def source_digest(root: str) -> str:
68
+ """源码树摘要: 路径 + 长度 + 内容 (换行归一) 的 SHA-256。"""
69
+ h = hashlib.sha256()
70
+ for rel, path in iter_package_files(root):
71
+ if rel in ('pic.toml', '.pic-meta.json', '.mkn-meta.json'):
72
+ continue
73
+ try:
74
+ with open(path, 'rb') as f:
75
+ data = f.read()
76
+ except OSError as e:
77
+ raise RegistryError(f'读取源码文件失败: {path}: {e}') from e
78
+ normalized = data.replace(b'\r\n', b'\n')
79
+ h.update(rel.encode('utf-8'))
80
+ h.update(b'\0')
81
+ h.update(str(len(normalized)).encode('ascii'))
82
+ h.update(b'\0')
83
+ h.update(normalized)
84
+ return h.hexdigest()
85
+
86
+
87
+ def manifest_digest(meta: PackageMeta) -> str:
88
+ """规范化清单摘要 (忽略 repo/tag 等发布位置字段)。"""
89
+ data = meta.to_dict()
90
+ package = data.get('package')
91
+ if isinstance(package, dict):
92
+ package.pop('repo', None)
93
+ package.pop('tag', None)
94
+ text = toml_dumps(data)
95
+ return hashlib.sha256(text.encode('utf-8')).hexdigest()
96
+
97
+
98
+ def package_modules(root: str) -> List[str]:
99
+ """列出包内可导入的模块名 (供搜索/后台/``pic modules`` 使用)。"""
100
+ modules: List[str] = []
101
+ for rel, _path in iter_package_files(root):
102
+ if not rel.endswith('.cin'):
103
+ continue
104
+ name = rel[:-4].replace(os.sep, '/')
105
+ if name.startswith('src/'):
106
+ name = name[len('src/'):]
107
+ parts = name.split('/')
108
+ if any(part in ('test', 'tests', '__tests__', 'demo', 'demos',
109
+ 'example', 'examples') for part in parts[:-1]):
110
+ continue
111
+ base = parts[-1]
112
+ if base in ('main', 'test', 'demo') or base.endswith(
113
+ ('_demo', '_test', '_main')):
114
+ continue
115
+ modules.append(name)
116
+ return sorted(set(modules))
117
+
118
+
119
+ def _file_sha256(path: str) -> str:
120
+ h = hashlib.sha256()
121
+ with open(path, 'rb') as f:
122
+ for chunk in iter(lambda: f.read(1 << 20), b''):
123
+ h.update(chunk)
124
+ return h.hexdigest()
125
+
126
+
127
+ def _version_key(version: str) -> Tuple[int, int, int]:
128
+ try:
129
+ return tuple(int(part) for part in version.split('-')[0].split('.'))
130
+ except ValueError:
131
+ return (0, 0, 0)
132
+
133
+
134
+ def _highest(versions: Iterable[str]) -> str:
135
+ return max(versions, key=_version_key)
136
+
137
+
138
+ class RegistryClient:
139
+ """package.codecin.org.cn API 客户端。"""
140
+
141
+ def __init__(self, base_url: str = DEFAULT_REGISTRY_URL,
142
+ token: Optional[str] = None, timeout: int = 30,
143
+ user_agent: str = f'pic/{_PIC_VERSION}'):
144
+ self.base_url = (base_url or DEFAULT_REGISTRY_URL).rstrip('/')
145
+ self.token = token
146
+ self.timeout = timeout
147
+ self.user_agent = user_agent
148
+
149
+ @property
150
+ def api(self) -> str:
151
+ return self.base_url + '/api/v1'
152
+
153
+ def _url(self, path: str) -> str:
154
+ return self.api + path if path.startswith('/') else self.api + '/' + path
155
+
156
+ def _headers(self, auth: bool, content_type: str = '') -> Dict[str, str]:
157
+ headers = {'Accept': 'application/json',
158
+ 'User-Agent': self.user_agent}
159
+ if content_type:
160
+ headers['Content-Type'] = content_type
161
+ if auth and self.token:
162
+ headers['Authorization'] = 'Bearer ' + self.token
163
+ return headers
164
+
165
+ def _request(self, method: str, path: str,
166
+ body: Optional[Dict[str, Any]] = None, *,
167
+ auth: bool = False, raw: bool = False,
168
+ content_type: str = 'application/json') -> Any:
169
+ data = None
170
+ if body is not None:
171
+ data = json.dumps(body, ensure_ascii=False).encode('utf-8')
172
+ request = urllib.request.Request(
173
+ self._url(path), data=data, method=method,
174
+ headers=self._headers(auth, content_type if data is not None else ''))
175
+ try:
176
+ with urllib.request.urlopen(request, timeout=self.timeout) as resp:
177
+ payload = resp.read()
178
+ status = resp.status
179
+ except urllib.error.HTTPError as e:
180
+ payload = e.read()
181
+ status = e.code
182
+ except urllib.error.URLError as e:
183
+ raise RegistryError(
184
+ f'无法连接中央注册服务器 {self.base_url}: {e.reason}') from e
185
+ except OSError as e:
186
+ raise RegistryError(
187
+ f'无法连接中央注册服务器 {self.base_url}: {e}') from e
188
+
189
+ if raw:
190
+ if status >= 400:
191
+ raise RegistryError(
192
+ f'中央服务器返回 HTTP {status}', status=status)
193
+ return payload
194
+ try:
195
+ envelope = json.loads(payload.decode('utf-8')) if payload else {}
196
+ except (ValueError, UnicodeDecodeError):
197
+ text = payload.decode('utf-8', 'replace')[:300]
198
+ raise RegistryError(
199
+ f'中央服务器返回非 JSON (HTTP {status}): {text}',
200
+ status=status) from None
201
+ if not isinstance(envelope, dict):
202
+ raise RegistryError(f'中央服务器响应格式错误 (HTTP {status})',
203
+ status=status)
204
+ if status >= 400 or not envelope.get('ok'):
205
+ error = envelope.get('error') or {}
206
+ message = error.get('message') if isinstance(error, dict) else None
207
+ code = error.get('code') if isinstance(error, dict) else ''
208
+ raise RegistryError(
209
+ message or f'中央服务器请求失败 (HTTP {status})',
210
+ status=status, code=str(code or ''), data=envelope.get('data'))
211
+ return envelope.get('data', {})
212
+
213
+ # ---------------- 读 ----------------
214
+
215
+ def health(self) -> Dict[str, Any]:
216
+ return self._request('GET', '/health')
217
+
218
+ def list_packages(self, query: str = '', **params: Any
219
+ ) -> List[Dict[str, Any]]:
220
+ """搜索/列表; 额外参数直接作为查询串传给服务端。"""
221
+ query_params: Dict[str, Any] = {}
222
+ if query:
223
+ query_params['q'] = query
224
+ for key, value in params.items():
225
+ if value is None or value == '' or value is False:
226
+ continue
227
+ query_params[key] = 'true' if value is True else value
228
+ path = '/packages'
229
+ if query_params:
230
+ path += '?' + urllib.parse.urlencode(query_params)
231
+ data = self._request('GET', path)
232
+ return self._package_list(data)
233
+
234
+ def search(self, query: str = '', **params: Any) -> Dict[str, Any]:
235
+ """返回包含 ``packages`` / ``total`` / ``count`` 的完整结果。"""
236
+ query_params: Dict[str, Any] = {}
237
+ if query:
238
+ query_params['q'] = query
239
+ for key, value in params.items():
240
+ if value is None or value == '' or value is False:
241
+ continue
242
+ query_params[key] = 'true' if value is True else value
243
+ path = '/packages'
244
+ if query_params:
245
+ path += '?' + urllib.parse.urlencode(query_params)
246
+ data = self._request('GET', path)
247
+ if not isinstance(data, dict):
248
+ return {'packages': [], 'total': 0, 'count': 0}
249
+ data = dict(data)
250
+ packages = data.get('packages')
251
+ data['packages'] = packages if isinstance(packages, list) else []
252
+ data.setdefault('total', len(data['packages']))
253
+ data.setdefault('count', len(data['packages']))
254
+ return data
255
+
256
+ @staticmethod
257
+ def _package_list(data: Any) -> List[Dict[str, Any]]:
258
+ packages = data.get('packages') if isinstance(data, dict) else None
259
+ return packages if isinstance(packages, list) else []
260
+
261
+ def get_package(self, name: str) -> Optional[Dict[str, Any]]:
262
+ validate_name(name)
263
+ try:
264
+ data = self._request('GET', f'/packages/{name}')
265
+ except RegistryError as e:
266
+ if e.status == 404:
267
+ return None
268
+ raise
269
+ return data if isinstance(data, dict) else None
270
+
271
+ def get_version(self, name: str, version: str) -> Optional[Dict[str, Any]]:
272
+ validate_name(name)
273
+ try:
274
+ data = self._request('GET', f'/packages/{name}/{version}')
275
+ except RegistryError as e:
276
+ if e.status == 404:
277
+ return None
278
+ raise
279
+ if not isinstance(data, dict):
280
+ return None
281
+ entry = data.get('version')
282
+ return entry if isinstance(entry, dict) else None
283
+
284
+ def resolve(self, name: str, constraint: str = ''
285
+ ) -> Tuple[str, str, Dict[str, Any]]:
286
+ record = self.get_package(name)
287
+ if record is None:
288
+ raise RegistryError(f'中央注册服务器未找到包: {name}')
289
+ versions = record.get('versions') or {}
290
+ pointer = str(record.get('latest') or '')
291
+ latest_only = not str(constraint or '').strip() \
292
+ or str(constraint).strip() in ('*', 'latest', 'any')
293
+ # `pic install <name>` 默认最新: 优先使用服务端的 latest 指针,
294
+ # 否则在满足约束的未撤回版本中取最高版本。
295
+ if latest_only and pointer:
296
+ entry = versions.get(pointer)
297
+ if isinstance(entry, dict) and not entry.get('yanked'):
298
+ repo = str(record.get('repo') or entry.get('repo') or '')
299
+ if not repo:
300
+ raise RegistryError(f'包 {name} 的记录缺少 Git 仓库地址')
301
+ return repo, pointer, entry
302
+ candidates = []
303
+ for version, entry in versions.items():
304
+ if not isinstance(entry, dict) or entry.get('yanked'):
305
+ continue
306
+ try:
307
+ if satisfies(version, constraint or '*'):
308
+ candidates.append((version, entry))
309
+ except Exception: # noqa: BLE001 - 跳过非法历史记录
310
+ continue
311
+ if not candidates:
312
+ available = ', '.join(sorted(versions)) or '(无)'
313
+ raise RegistryError(
314
+ f'包 {name} 没有满足约束 {constraint or "*"} 的版本; '
315
+ f'可用: {available}')
316
+ version, entry = max(candidates, key=lambda item: _version_key(item[0]))
317
+ repo = str(record.get('repo') or entry.get('repo') or '')
318
+ if not repo:
319
+ raise RegistryError(f'包 {name} 的记录缺少 Git 仓库地址')
320
+ return repo, version, entry
321
+
322
+ # ---------------- 写 ----------------
323
+
324
+ def publish(self, meta: PackageMeta, *, repo: str, tag: str, rev: str,
325
+ archive_path: str) -> Dict[str, Any]:
326
+ """提交元数据并上传 .cinpkg 制品。"""
327
+ if not repo:
328
+ raise RegistryError('发布需要 Git 仓库地址')
329
+ if not os.path.isfile(archive_path):
330
+ raise RegistryError(f'包归档不存在: {archive_path}')
331
+ source = source_digest(meta.root)
332
+ manifest = manifest_digest(meta)
333
+ archive_sha = _file_sha256(archive_path)
334
+ size = os.path.getsize(archive_path)
335
+ package_table = (meta.raw or {}).get('package')
336
+ if not isinstance(package_table, dict):
337
+ package_table = {}
338
+ metadata = {
339
+ 'name': meta.name,
340
+ 'version': meta.version,
341
+ 'repo': repo,
342
+ 'tag': tag,
343
+ 'rev': rev,
344
+ 'source_sha256': source,
345
+ 'manifest_sha256': manifest,
346
+ 'archive_sha256': archive_sha,
347
+ 'archive_size': size,
348
+ 'description': meta.description,
349
+ 'keywords': list(meta.keywords),
350
+ 'license': meta.license,
351
+ 'homepage': str(package_table.get('homepage')
352
+ or package_table.get('website') or ''),
353
+ 'entry': meta.entry_rel,
354
+ 'modules': package_modules(meta.root),
355
+ }
356
+ published = self._request(
357
+ 'PUT', f'/packages/{meta.name}/{meta.version}', metadata,
358
+ auth=True)
359
+ artifact = self._upload_artifact(
360
+ meta.name, meta.version, archive_path, archive_sha)
361
+ result = dict(published) if isinstance(published, dict) else {}
362
+ result['artifact'] = artifact
363
+ result['source_sha256'] = source
364
+ result['manifest_sha256'] = manifest
365
+ result['archive_sha256'] = archive_sha
366
+ result['archive_size'] = size
367
+ return result
368
+
369
+ def _upload_artifact(self, name: str, version: str, path: str,
370
+ digest: str) -> Dict[str, Any]:
371
+ with open(path, 'rb') as f:
372
+ data = f.read()
373
+ query = urllib.parse.urlencode({'sha256': digest})
374
+ request = urllib.request.Request(
375
+ self._url(f'/packages/{name}/{version}/artifact?' + query),
376
+ data=data, method='POST',
377
+ headers=self._headers(True, 'application/octet-stream'))
378
+ try:
379
+ with urllib.request.urlopen(request, timeout=self.timeout) as resp:
380
+ payload = resp.read()
381
+ status = resp.status
382
+ except urllib.error.HTTPError as e:
383
+ payload = e.read()
384
+ status = e.code
385
+ except urllib.error.URLError as e:
386
+ raise RegistryError(
387
+ f'上传制品失败 (网络): {e.reason}') from e
388
+ try:
389
+ envelope = json.loads(payload.decode('utf-8')) if payload else {}
390
+ except (ValueError, UnicodeDecodeError):
391
+ raise RegistryError(
392
+ f'上传制品返回非 JSON (HTTP {status})', status=status) from None
393
+ if status >= 400 or not envelope.get('ok'):
394
+ error = envelope.get('error') or {}
395
+ message = error.get('message') if isinstance(error, dict) else None
396
+ raise RegistryError(message or f'上传制品失败 (HTTP {status})',
397
+ status=status,
398
+ code=str((error or {}).get('code') or ''))
399
+ return envelope.get('data') or {}
400
+
401
+ def download_artifact(self, name: str, version: str, dest: str,
402
+ expected_sha256: str = '') -> Tuple[str, str]:
403
+ """下载制品到 ``dest``; 返回 (路径, 实际 sha256)。"""
404
+ os.makedirs(os.path.dirname(os.path.abspath(dest)), exist_ok=True)
405
+ request = urllib.request.Request(
406
+ self._url(f'/packages/{name}/{version}/artifact'),
407
+ headers={'User-Agent': self.user_agent})
408
+ h = hashlib.sha256()
409
+ try:
410
+ with urllib.request.urlopen(request, timeout=self.timeout) as resp, \
411
+ open(dest, 'wb') as out:
412
+ while True:
413
+ chunk = resp.read(1 << 20)
414
+ if not chunk:
415
+ break
416
+ out.write(chunk)
417
+ h.update(chunk)
418
+ except urllib.error.HTTPError as e:
419
+ raise RegistryError(
420
+ f'下载制品失败 (HTTP {e.code}): {name}@{version}',
421
+ status=e.code) from e
422
+ except urllib.error.URLError as e:
423
+ raise RegistryError(f'下载制品失败: {e.reason}') from e
424
+ actual = h.hexdigest()
425
+ if expected_sha256 and actual != expected_sha256:
426
+ with contextlib.suppress(OSError):
427
+ os.remove(dest)
428
+ raise RegistryError(
429
+ f'制品 SHA-256 不匹配: 期望 {expected_sha256[:16]}…, '
430
+ f'实际 {actual[:16]}…')
431
+ return dest, actual
432
+
433
+ def yank(self, name: str, version: str, yanked: bool = True) -> Dict[str, Any]:
434
+ data = self._request('POST', f'/packages/{name}/{version}/yank',
435
+ {'yanked': yanked}, auth=True)
436
+ return data if isinstance(data, dict) else {}
437
+
438
+ def set_latest(self, name: str, version: str) -> Dict[str, Any]:
439
+ data = self._request('POST', f'/packages/{name}/{version}/latest',
440
+ {'latest': True}, auth=True)
441
+ return data if isinstance(data, dict) else {}
442
+
443
+ def delete_version(self, name: str, version: str) -> Dict[str, Any]:
444
+ data = self._request('DELETE', f'/packages/{name}/{version}',
445
+ auth=True)
446
+ return data if isinstance(data, dict) else {}
447
+
448
+ def delete_package(self, name: str) -> Dict[str, Any]:
449
+ data = self._request('DELETE', f'/packages/{name}', auth=True)
450
+ return data if isinstance(data, dict) else {}
451
+
452
+ def stats(self) -> Dict[str, Any]:
453
+ data = self._request('GET', '/stats')
454
+ return data if isinstance(data, dict) else {}
455
+
456
+ def me(self) -> Dict[str, Any]:
457
+ data = self._request('GET', '/me', auth=True)
458
+ return data if isinstance(data, dict) else {}
459
+
460
+ def version_list(self, name: str) -> List[Dict[str, Any]]:
461
+ record = self.get_package(name)
462
+ if record is None:
463
+ return []
464
+ rows = self.version_rows(record)
465
+ versions = record.get('versions') or {}
466
+ latest = str(record.get('latest') or '')
467
+ out = []
468
+ for version, tag, yanked in rows:
469
+ entry = versions.get(version) or {}
470
+ out.append({
471
+ 'version': version,
472
+ 'tag': tag,
473
+ 'yanked': yanked == 'yanked',
474
+ 'latest': version == latest,
475
+ 'published_at': entry.get('published_at') or '',
476
+ 'publisher': entry.get('publisher') or {},
477
+ 'archive_size': entry.get('archive_size') or 0,
478
+ 'archive_sha256': entry.get('archive_sha256') or '',
479
+ 'downloads': entry.get('downloads') or 0,
480
+ })
481
+ return out
482
+
483
+ # ---------------- 校验 ----------------
484
+
485
+ @staticmethod
486
+ def verify_install(meta: PackageMeta, entry: Dict[str, Any], *,
487
+ rev: str = '') -> None:
488
+ expected_source = str(entry.get('source_sha256') or '')
489
+ expected_manifest = str(entry.get('manifest_sha256') or '')
490
+ if expected_source:
491
+ actual = source_digest(meta.root)
492
+ if actual != expected_source:
493
+ raise RegistryError(
494
+ f'安全校验失败: {meta.name} {meta.version} 源码摘要不匹配 '
495
+ f'(期望 {expected_source[:16]}…, 实际 {actual[:16]}…)')
496
+ if expected_manifest:
497
+ actual = manifest_digest(meta)
498
+ if actual != expected_manifest:
499
+ raise RegistryError(
500
+ f'安全校验失败: {meta.name} {meta.version} 清单摘要不匹配')
501
+ expected_rev = str(entry.get('rev') or '')
502
+ if rev and expected_rev and rev != expected_rev:
503
+ raise RegistryError(
504
+ f'安全校验失败: {meta.name} {meta.version} Git 提交不匹配 '
505
+ f'(期望 {expected_rev[:12]}…, 实际 {rev[:12]}…)')
506
+
507
+ @staticmethod
508
+ def version_rows(record: Dict[str, Any]) -> List[Tuple[str, str, str]]:
509
+ rows = []
510
+ for version in sorted(record.get('versions') or {},
511
+ key=_version_key, reverse=True):
512
+ entry = record['versions'][version]
513
+ rows.append((version, str(entry.get('tag') or ''),
514
+ 'yanked' if entry.get('yanked') else ''))
515
+ return rows
codecin/registers.py ADDED
@@ -0,0 +1,130 @@
1
+ from typing import Any, Dict, List, Optional
2
+
3
+ from .console import Console, Table
4
+ from .errors import ExecutionError
5
+ from .isa import Constants
6
+
7
+ MASK64 = 0xFFFFFFFFFFFFFFFF
8
+
9
+
10
+ class RegisterFile:
11
+ def __init__(self, console: Optional[Console] = None,
12
+ num_regs: int = Constants.NUM_REGISTERS):
13
+ self.console = console or Console()
14
+ self.num_regs = num_regs
15
+ self._regs = [0] * num_regs
16
+
17
+ def read(self, idx: int) -> int:
18
+ if idx == 31:
19
+ return 0
20
+ if not 0 <= idx < self.num_regs:
21
+ raise ExecutionError(f"Invalid register index: X{idx}")
22
+ return self._regs[idx]
23
+
24
+ def write(self, idx: int, value: int, pc: int = 0) -> None:
25
+ if idx == 31:
26
+ return
27
+ if not 0 <= idx < self.num_regs:
28
+ raise ExecutionError(f"Invalid register index: X{idx}")
29
+ self._regs[idx] = value & MASK64
30
+
31
+ def get_all(self) -> List[int]:
32
+ return self._regs.copy()
33
+
34
+ def set_all(self, values: List[int]) -> None:
35
+ for i, v in enumerate(values[:self.num_regs]):
36
+ self._regs[i] = v & MASK64
37
+
38
+ def reset(self) -> None:
39
+ self._regs = [0] * self.num_regs
40
+
41
+ def display_registers(self, title: str = "Registers",
42
+ extra_info: Optional[Dict[str, Any]] = None,
43
+ console: Optional[Console] = None) -> None:
44
+ if console is None:
45
+ console = self.console
46
+ table = Table(title=title)
47
+ table.add_column("Register")
48
+ table.add_column("Value (Dec)")
49
+ table.add_column("Value (Hex)")
50
+ for i in range(16):
51
+ val = self._regs[i]
52
+ table.add_row(f"X{i}", str(val), f"0x{val:x}")
53
+ table.add_row("", "", "")
54
+ for i in range(16, 31):
55
+ val = self._regs[i]
56
+ table.add_row(f"X{i}", str(val), f"0x{val:x}")
57
+ table.add_row("XZR", "0", "0x0")
58
+ if extra_info:
59
+ for key, value in extra_info.items():
60
+ table.add_row(key, str(value),
61
+ f"0x{value:x}" if isinstance(value, int) else "")
62
+ console.print(str(table))
63
+
64
+
65
+ class VectorRegisterFile:
66
+
67
+ def __init__(self, num_regs: int = Constants.NUM_VECTOR_REGISTERS,
68
+ lanes: int = Constants.VECTOR_LANES):
69
+ self.num_regs = num_regs
70
+ self.lanes = lanes
71
+ self._regs = [[0.0] * lanes for _ in range(num_regs)]
72
+
73
+ def read_vector(self, idx: int) -> List[float]:
74
+ if idx == 31:
75
+ return [0.0] * self.lanes
76
+ if not 0 <= idx < self.num_regs:
77
+ raise ExecutionError(f"Invalid vector register index: V{idx}")
78
+ return self._regs[idx].copy()
79
+
80
+ def write_vector(self, idx: int, values: List[float]) -> None:
81
+ if idx == 31:
82
+ return
83
+ if not 0 <= idx < self.num_regs:
84
+ raise ExecutionError(f"Invalid vector register index: V{idx}")
85
+ if len(values) != self.lanes:
86
+ raise ExecutionError(f"Need {self.lanes} values, got {len(values)}")
87
+ self._regs[idx] = list(values)
88
+
89
+ def read_scalar(self, idx: int, lane: int = 0) -> float:
90
+ if idx == 31:
91
+ return 0.0
92
+ if not 0 <= idx < self.num_regs:
93
+ raise ExecutionError(f"Invalid vector register index: V{idx}")
94
+ if not 0 <= lane < self.lanes:
95
+ raise ExecutionError(f"Invalid lane index: {lane}")
96
+ return self._regs[idx][lane]
97
+
98
+ def write_scalar(self, idx: int, value: float, lane: int = 0) -> None:
99
+ if idx == 31:
100
+ return
101
+ if not 0 <= idx < self.num_regs:
102
+ raise ExecutionError(f"Invalid vector register index: V{idx}")
103
+ if not 0 <= lane < self.lanes:
104
+ raise ExecutionError(f"Invalid lane index: {lane}")
105
+ self._regs[idx][lane] = float(value)
106
+
107
+ def get_all(self) -> List[List[float]]:
108
+ return [v.copy() for v in self._regs]
109
+
110
+ def set_all(self, values: List[List[float]]) -> None:
111
+ for i, v in enumerate(values[:self.num_regs]):
112
+ self._regs[i] = [float(x) for x in v[:self.lanes]]
113
+
114
+ def reset(self) -> None:
115
+ self._regs = [[0.0] * self.lanes for _ in range(self.num_regs)]
116
+
117
+ def display_vector_registers(self, title: str = "Vector Registers",
118
+ console: Optional[Console] = None) -> None:
119
+ if console is None:
120
+ return
121
+ table = Table(title=title)
122
+ table.add_column("Register")
123
+ for lane in range(self.lanes):
124
+ table.add_column(f"Lane {lane}")
125
+ for i in range(self.num_regs):
126
+ vec = self._regs[i]
127
+ if any(v != 0.0 for v in vec):
128
+ table.add_row(f"V{i}", *[f"{v:.4g}" for v in vec])
129
+ if table.rows:
130
+ console.print(str(table))