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.
- codecin/__init__.py +27 -0
- codecin/aot.py +1057 -0
- codecin/assembler.py +619 -0
- codecin/cbackend.py +3024 -0
- codecin/cin.py +4265 -0
- codecin/cli.py +670 -0
- codecin/codecin_native.dll +0 -0
- codecin/config.py +50 -0
- codecin/console.py +183 -0
- codecin/cpu.py +312 -0
- codecin/crom.py +449 -0
- codecin/cvm.py +708 -0
- codecin/disasm.py +149 -0
- codecin/environment.py +176 -0
- codecin/errors.py +54 -0
- codecin/isa.py +560 -0
- codecin/lib/array/pic.toml +10 -0
- codecin/lib/array/src/array.cin +103 -0
- codecin/lib/bigint/pic.toml +10 -0
- codecin/lib/bigint/src/bigint.cin +589 -0
- codecin/lib/bits/pic.toml +10 -0
- codecin/lib/bits/src/bits.cin +143 -0
- codecin/lib/bitset/pic.toml +10 -0
- codecin/lib/bitset/src/bitset.cin +374 -0
- codecin/lib/codec/pic.toml +10 -0
- codecin/lib/codec/src/codec.cin +563 -0
- codecin/lib/combin/pic.toml +10 -0
- codecin/lib/combin/src/combin.cin +414 -0
- codecin/lib/conv/pic.toml +10 -0
- codecin/lib/conv/src/conv.cin +151 -0
- codecin/lib/cppstd/pic.toml +10 -0
- codecin/lib/cppstd/src/cppstd.cin +418 -0
- codecin/lib/cstd/pic.toml +10 -0
- codecin/lib/cstd/src/cstd.cin +424 -0
- codecin/lib/csv/pic.toml +10 -0
- codecin/lib/csv/src/csv.cin +405 -0
- codecin/lib/dp/pic.toml +10 -0
- codecin/lib/dp/src/dp.cin +325 -0
- codecin/lib/ffi/pic.toml +10 -0
- codecin/lib/ffi/src/ffi.cin +163 -0
- codecin/lib/fmt/pic.toml +10 -0
- codecin/lib/fmt/src/fmt.cin +325 -0
- codecin/lib/frac/pic.toml +10 -0
- codecin/lib/frac/src/frac.cin +252 -0
- codecin/lib/gostd/pic.toml +10 -0
- codecin/lib/gostd/src/gostd.cin +415 -0
- codecin/lib/graph/pic.toml +10 -0
- codecin/lib/graph/src/graph.cin +367 -0
- codecin/lib/gui/pic.toml +10 -0
- codecin/lib/gui/src/gui.cin +218 -0
- codecin/lib/hash/pic.toml +10 -0
- codecin/lib/hash/src/hash.cin +67 -0
- codecin/lib/heap/pic.toml +10 -0
- codecin/lib/heap/src/heap.cin +199 -0
- codecin/lib/io/pic.toml +10 -0
- codecin/lib/io/src/io.cin +141 -0
- codecin/lib/json/pic.toml +10 -0
- codecin/lib/json/src/json.cin +84 -0
- codecin/lib/key/pic.toml +10 -0
- codecin/lib/key/src/key.cin +78 -0
- codecin/lib/math/pic.toml +10 -0
- codecin/lib/math/src/math.cin +50 -0
- codecin/lib/matrix/pic.toml +10 -0
- codecin/lib/matrix/src/matrix.cin +155 -0
- codecin/lib/net/pic.toml +10 -0
- codecin/lib/net/src/net.cin +171 -0
- codecin/lib/path/pic.toml +10 -0
- codecin/lib/path/src/path.cin +372 -0
- codecin/lib/queue/pic.toml +10 -0
- codecin/lib/queue/src/queue.cin +112 -0
- codecin/lib/rand/pic.toml +10 -0
- codecin/lib/rand/src/rand.cin +46 -0
- codecin/lib/set/pic.toml +10 -0
- codecin/lib/set/src/set.cin +269 -0
- codecin/lib/sort/pic.toml +10 -0
- codecin/lib/sort/src/sort.cin +93 -0
- codecin/lib/stat/pic.toml +10 -0
- codecin/lib/stat/src/stat.cin +138 -0
- codecin/lib/str/pic.toml +10 -0
- codecin/lib/str/src/str.cin +54 -0
- codecin/lib/termux/pic.toml +10 -0
- codecin/lib/termux/src/termux.cin +118 -0
- codecin/lib/test/pic.toml +10 -0
- codecin/lib/test/src/test.cin +74 -0
- codecin/lib/text/pic.toml +10 -0
- codecin/lib/text/src/text.cin +323 -0
- codecin/lib/time/pic.toml +10 -0
- codecin/lib/time/src/time.cin +54 -0
- codecin/lib/token/pic.toml +10 -0
- codecin/lib/token/src/token.cin +183 -0
- codecin/lib/tree/pic.toml +10 -0
- codecin/lib/tree/src/tree.cin +256 -0
- codecin/lib/unionfind/pic.toml +10 -0
- codecin/lib/unionfind/src/unionfind.cin +115 -0
- codecin/lib/validate/pic.toml +10 -0
- codecin/lib/validate/src/validate.cin +148 -0
- codecin/lib/vec/pic.toml +10 -0
- codecin/lib/vec/src/vec.cin +88 -0
- codecin/logger.py +145 -0
- codecin/memory.py +306 -0
- codecin/mkn.py +916 -0
- codecin/native/aot/aot.go +114 -0
- codecin/native/aot/stub_main.go.txt +23 -0
- codecin/native/build.ps1 +33 -0
- codecin/native/build.sh +48 -0
- codecin/native/cmd/cincc/main.go +66 -0
- codecin/native/compiler/codegen.go +2238 -0
- codecin/native/compiler/compile_test.go +1069 -0
- codecin/native/compiler/parser.go +1331 -0
- codecin/native/compiler/syscalls.go +166 -0
- codecin/native/compiler/tokenizer.go +394 -0
- codecin/native/compiler/types.go +217 -0
- codecin/native/engine/args.go +37 -0
- codecin/native/engine/audio.go +402 -0
- codecin/native/engine/audio_other.go +105 -0
- codecin/native/engine/audio_test.go +279 -0
- codecin/native/engine/audio_windows.go +190 -0
- codecin/native/engine/canvas.go +271 -0
- codecin/native/engine/console_other.go +9 -0
- codecin/native/engine/console_windows.go +43 -0
- codecin/native/engine/crom.go +86 -0
- codecin/native/engine/encode.go +93 -0
- codecin/native/engine/engine_test.go +198 -0
- codecin/native/engine/ffi_nocgo.go +20 -0
- codecin/native/engine/ffi_registry.go +69 -0
- codecin/native/engine/ffi_unix.go +109 -0
- codecin/native/engine/ffi_windows.go +117 -0
- codecin/native/engine/gui.go +209 -0
- codecin/native/engine/gui_stub.go +13 -0
- codecin/native/engine/gui_test.go +148 -0
- codecin/native/engine/gui_windows.go +604 -0
- codecin/native/engine/gui_x11.go +723 -0
- codecin/native/engine/host_test.go +139 -0
- codecin/native/engine/hostcrypto.go +30 -0
- codecin/native/engine/hostdesktop.go +173 -0
- codecin/native/engine/hostnet.go +127 -0
- codecin/native/engine/isa_gen.go +689 -0
- codecin/native/engine/keyboard.go +432 -0
- codecin/native/engine/keyboard_other.go +94 -0
- codecin/native/engine/keyboard_stub.go +17 -0
- codecin/native/engine/keyboard_termios_darwin.go +9 -0
- codecin/native/engine/keyboard_termios_linux.go +9 -0
- codecin/native/engine/keyboard_test.go +246 -0
- codecin/native/engine/keyboard_windows.go +208 -0
- codecin/native/engine/keyboard_windows_test.go +123 -0
- codecin/native/engine/lineedit.go +262 -0
- codecin/native/engine/lineedit_test.go +105 -0
- codecin/native/engine/lineint_unix.go +17 -0
- codecin/native/engine/lineint_windows.go +19 -0
- codecin/native/engine/mem_other.go +37 -0
- codecin/native/engine/mem_windows.go +33 -0
- codecin/native/engine/native.go +640 -0
- codecin/native/engine/netsock.go +321 -0
- codecin/native/engine/ops_ext.go +515 -0
- codecin/native/engine/stdin.go +72 -0
- codecin/native/engine/stdin_other.go +9 -0
- codecin/native/engine/stdin_windows.go +60 -0
- codecin/native/engine/system.go +313 -0
- codecin/native/engine/termux.go +180 -0
- codecin/native/engine/version_gen.go +7 -0
- codecin/native/engine/vkb_darwin.go +62 -0
- codecin/native/engine/vkb_linux.go +95 -0
- codecin/native/engine/vkb_stub.go +11 -0
- codecin/native/engine/vm.go +1677 -0
- codecin/native/go.mod +3 -0
- codecin/native/ir/ir.go +48 -0
- codecin/native/main.go +448 -0
- codecin/native/mc/aarch64.go +165 -0
- codecin/native/mc/aarch64_test.go +30 -0
- codecin/native/mc/elf.go +88 -0
- codecin/native/mc/print_test.go +52 -0
- codecin/native/mc/x86_64.go +1262 -0
- codecin/native/mc/x86_64_test.go +102 -0
- codecin/native.py +432 -0
- codecin/native_codegen.py +987 -0
- codecin/nativegen.py +786 -0
- codecin/object.py +539 -0
- codecin/optimizer.py +236 -0
- codecin/packaging/__init__.py +46 -0
- codecin/packaging/archive.py +177 -0
- codecin/packaging/model.py +519 -0
- codecin/packaging/spec.py +193 -0
- codecin/packaging/store.py +372 -0
- codecin/packaging/toml.py +541 -0
- codecin/packaging/vcs.py +215 -0
- codecin/pic.py +1917 -0
- codecin/pic_api.py +374 -0
- codecin/pic_login.py +519 -0
- codecin/pic_registry.py +515 -0
- codecin/registers.py +130 -0
- codecin/sdgcc.py +493 -0
- codecin/stats.py +230 -0
- codecin/stdlib.py +138 -0
- codecin/toolchain.py +396 -0
- codecin/toolkit.py +26 -0
- codecin/version.py +260 -0
- codecin-7.22.10.dist-info/METADATA +1077 -0
- codecin-7.22.10.dist-info/RECORD +202 -0
- codecin-7.22.10.dist-info/WHEEL +5 -0
- codecin-7.22.10.dist-info/entry_points.txt +5 -0
- codecin-7.22.10.dist-info/licenses/LICENSE +7 -0
- codecin-7.22.10.dist-info/top_level.txt +1 -0
codecin/mkn.py
ADDED
|
@@ -0,0 +1,916 @@
|
|
|
1
|
+
"""``mkn`` —— Code CIN 的项目构建与依赖工具 (Maven 风格)。
|
|
2
|
+
|
|
3
|
+
Maven 的核心概念在 CIN 中的对应关系:
|
|
4
|
+
|
|
5
|
+
==================== ==================================================
|
|
6
|
+
Maven mkn
|
|
7
|
+
==================== ==================================================
|
|
8
|
+
``pom.xml`` ``mkn.toml`` (``[project]`` / ``[build]`` / ``[dependencies]``)
|
|
9
|
+
标准目录布局 ``src/main.cin``、``src/test/``、``target/``
|
|
10
|
+
生命周期 ``compile -> test -> package -> install -> deploy``
|
|
11
|
+
依赖坐标 ``name@version`` / Git 仓库 / 本地路径
|
|
12
|
+
本地仓库 ``$MKN_HOME/repository/<name>/<version>``
|
|
13
|
+
传递依赖 安装到项目 ``pic_modules/``, CIN 可直接 import
|
|
14
|
+
==================== ==================================================
|
|
15
|
+
|
|
16
|
+
``mkn`` 复用现有编译器与 ``pic`` 的解析/存储能力, 不重复实现包管理。
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
import argparse
|
|
20
|
+
import contextlib
|
|
21
|
+
import glob
|
|
22
|
+
import json
|
|
23
|
+
import os
|
|
24
|
+
import re
|
|
25
|
+
import shutil
|
|
26
|
+
import sys
|
|
27
|
+
from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple
|
|
28
|
+
|
|
29
|
+
from . import __version__
|
|
30
|
+
from .config import Config
|
|
31
|
+
from .packaging import archive, vcs
|
|
32
|
+
from .packaging.model import (
|
|
33
|
+
Dependency,
|
|
34
|
+
ManifestError,
|
|
35
|
+
MknManifest,
|
|
36
|
+
find_project_root,
|
|
37
|
+
load_mkn_manifest,
|
|
38
|
+
satisfies,
|
|
39
|
+
validate_name,
|
|
40
|
+
validate_version,
|
|
41
|
+
)
|
|
42
|
+
from .packaging.store import copy_package_tree, default_store
|
|
43
|
+
from .packaging.toml import dumps as toml_dumps
|
|
44
|
+
from .packaging.toml import load as toml_load
|
|
45
|
+
|
|
46
|
+
__all__ = ['main', 'build_project', 'resolve_dependencies', 'load_project']
|
|
47
|
+
|
|
48
|
+
_IGNORE = shutil.ignore_patterns(
|
|
49
|
+
'.git', '.hg', '.svn', '__pycache__', '*.pyc', '.pytest_cache',
|
|
50
|
+
'.ruff_cache', 'pic_modules', '.pic', '.mkn', 'node_modules', '.venv',
|
|
51
|
+
'venv', '*.mkn', '*.cinpkg', '*.cvm')
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class MknError(RuntimeError):
|
|
55
|
+
"""mkn 的可预期失败。"""
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _home() -> str:
|
|
59
|
+
return os.path.abspath(os.environ.get('MKN_HOME')
|
|
60
|
+
or os.path.join(os.path.expanduser('~'), '.mkn'))
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _repository_dir() -> str:
|
|
64
|
+
return os.path.join(_home(), 'repository')
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
# ==================== 项目模型 ====================
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def load_project(start: Optional[str] = None,
|
|
71
|
+
manifest: Optional[str] = None) -> MknManifest:
|
|
72
|
+
if manifest:
|
|
73
|
+
path = os.path.abspath(manifest)
|
|
74
|
+
if os.path.isdir(path):
|
|
75
|
+
path = os.path.join(path, 'mkn.toml')
|
|
76
|
+
else:
|
|
77
|
+
root = find_project_root(start or os.getcwd(), ('mkn.toml',))
|
|
78
|
+
if root is None:
|
|
79
|
+
raise MknError(
|
|
80
|
+
'找不到 mkn.toml; 请在项目根运行, 或先执行 `mkn init`')
|
|
81
|
+
path = os.path.join(root, 'mkn.toml')
|
|
82
|
+
return load_mkn_manifest(path)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _build_config(project: MknManifest, *, release: bool,
|
|
86
|
+
optimize: Optional[int], mem_size: Optional[int]
|
|
87
|
+
) -> Config:
|
|
88
|
+
build = project.build or {}
|
|
89
|
+
level = optimize
|
|
90
|
+
if level is None:
|
|
91
|
+
level = int(build.get('optimize', 0) or 0)
|
|
92
|
+
if release:
|
|
93
|
+
level = max(level, 2)
|
|
94
|
+
size = mem_size or int(build.get('mem_size', 0) or 0) or None
|
|
95
|
+
config = Config(log_level='ERROR', optimize=level)
|
|
96
|
+
if size:
|
|
97
|
+
config.mem_size = int(size)
|
|
98
|
+
config.validate()
|
|
99
|
+
return config
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _has_main(entry: str) -> bool:
|
|
103
|
+
"""入口及其 import 闭包中是否存在 ``function main(...)`` / ``main:``。"""
|
|
104
|
+
if entry.lower().endswith(('.asm', '.pl')):
|
|
105
|
+
try:
|
|
106
|
+
with open(entry, encoding='utf-8-sig') as f:
|
|
107
|
+
return re.search(r'(?im)^\s*(?:global\s+)?main\s*:', f.read()) \
|
|
108
|
+
is not None
|
|
109
|
+
except OSError:
|
|
110
|
+
return False
|
|
111
|
+
files: List[str]
|
|
112
|
+
try:
|
|
113
|
+
from .cin import collect_imported_files
|
|
114
|
+
files = collect_imported_files(entry)
|
|
115
|
+
except Exception: # noqa: BLE001 - 编译错误留给真正的编译步骤报告
|
|
116
|
+
files = [entry]
|
|
117
|
+
pattern = re.compile(r'\bfunction\s+main\s*\(')
|
|
118
|
+
for path in files:
|
|
119
|
+
if not path.endswith('.cin'):
|
|
120
|
+
continue
|
|
121
|
+
try:
|
|
122
|
+
with open(path, encoding='utf-8-sig') as f:
|
|
123
|
+
if pattern.search(f.read()):
|
|
124
|
+
return True
|
|
125
|
+
except OSError:
|
|
126
|
+
continue
|
|
127
|
+
return False
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def build_project(project: MknManifest, *,
|
|
131
|
+
output: Optional[str] = None, release: bool = False,
|
|
132
|
+
optimize: Optional[int] = None,
|
|
133
|
+
mem_size: Optional[int] = None,
|
|
134
|
+
bounds_check: bool = False,
|
|
135
|
+
resolve: bool = True,
|
|
136
|
+
single: bool = False) -> str:
|
|
137
|
+
"""编译项目入口。
|
|
138
|
+
|
|
139
|
+
可执行项目默认产出 ``.sdgcc`` (容器内 ``CODE`` 段为 BIN v3; 显式把
|
|
140
|
+
``output`` 写成 ``.bin`` 时仍产出旧格式), 库项目产出 ``.co`` 对象。
|
|
141
|
+
|
|
142
|
+
``single=False`` (默认) 为**多文件模式**: 入口 + ``import`` 闭包全部计入
|
|
143
|
+
``SRCS`` 段; ``single=True`` 只记录入口文件, 供单文件产物使用。
|
|
144
|
+
"""
|
|
145
|
+
if resolve:
|
|
146
|
+
resolve_dependencies(project)
|
|
147
|
+
entry = project.entry_path
|
|
148
|
+
config = _build_config(project, release=release, optimize=optimize,
|
|
149
|
+
mem_size=mem_size)
|
|
150
|
+
config.bounds_check = bounds_check or bool(
|
|
151
|
+
project.build.get('bounds_check', False))
|
|
152
|
+
|
|
153
|
+
if not _has_main(entry):
|
|
154
|
+
from .object import ObjectError, compile_asm_object, compile_cin_object, write_object
|
|
155
|
+
out = output or os.path.join(
|
|
156
|
+
project.target_dir, f'{project.name}-{project.version}.co')
|
|
157
|
+
out = os.path.abspath(out)
|
|
158
|
+
os.makedirs(os.path.dirname(out), exist_ok=True)
|
|
159
|
+
try:
|
|
160
|
+
if entry.lower().endswith('.cin'):
|
|
161
|
+
obj = compile_cin_object(entry, mem_size=config.mem_size)
|
|
162
|
+
else:
|
|
163
|
+
obj = compile_asm_object(entry, mem_size=config.mem_size)
|
|
164
|
+
write_object(obj, out)
|
|
165
|
+
except ObjectError:
|
|
166
|
+
raise
|
|
167
|
+
return out
|
|
168
|
+
|
|
169
|
+
from . import sdgcc
|
|
170
|
+
from .cpu import CPU
|
|
171
|
+
cpu = CPU(config, entry)
|
|
172
|
+
out = output or os.path.join(
|
|
173
|
+
project.target_dir, f'{project.name}-{project.version}.sdgcc')
|
|
174
|
+
out = os.path.abspath(out)
|
|
175
|
+
os.makedirs(os.path.dirname(out), exist_ok=True)
|
|
176
|
+
|
|
177
|
+
sources = [entry] if single else _import_closure(entry)
|
|
178
|
+
symbols = [(pc, name) for name, pc in sorted(cpu.labels.items())]
|
|
179
|
+
symbols += [(pc, name) for name, pc in sorted(cpu.data_labels.items())]
|
|
180
|
+
meta = {
|
|
181
|
+
'project': {
|
|
182
|
+
'name': project.name,
|
|
183
|
+
'version': project.version,
|
|
184
|
+
},
|
|
185
|
+
'build': {
|
|
186
|
+
'entry': project.entry,
|
|
187
|
+
'optimize': int(config.optimize),
|
|
188
|
+
'mem_size': len(cpu.memory),
|
|
189
|
+
'bin_version': 3,
|
|
190
|
+
'files': [os.path.basename(p) for p in sources],
|
|
191
|
+
},
|
|
192
|
+
}
|
|
193
|
+
sdgcc.save_program(cpu, out, multi_file=not single, meta=meta,
|
|
194
|
+
sources=sources, symbols=symbols)
|
|
195
|
+
return out
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def _import_closure(entry: str) -> List[str]:
|
|
199
|
+
"""入口文件的 ``import`` 闭包 (含自身); 解析失败时退化为单文件。"""
|
|
200
|
+
try:
|
|
201
|
+
from .cin import collect_imported_files
|
|
202
|
+
files = list(collect_imported_files(entry))
|
|
203
|
+
except Exception: # noqa: BLE001 - 编译错误留给真正的编译步骤报告
|
|
204
|
+
files = [entry]
|
|
205
|
+
return files or [entry]
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
# ==================== 依赖解析 ====================
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def _version_key(version: str):
|
|
212
|
+
try:
|
|
213
|
+
return tuple(int(part) for part in version.split('-')[0].split('.'))
|
|
214
|
+
except ValueError:
|
|
215
|
+
return (0, 0, 0)
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def _repo_versions(name: str) -> List[str]:
|
|
219
|
+
path = os.path.join(_repository_dir(), name)
|
|
220
|
+
if not os.path.isdir(path):
|
|
221
|
+
return []
|
|
222
|
+
return sorted(
|
|
223
|
+
(v for v in os.listdir(path)
|
|
224
|
+
if os.path.isdir(os.path.join(path, v))),
|
|
225
|
+
key=_version_key)
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def _install_from_repository(name: str, constraint: str,
|
|
229
|
+
target_root: str) -> Optional[str]:
|
|
230
|
+
versions = [v for v in _repo_versions(name) if satisfies(v, constraint)]
|
|
231
|
+
if not versions:
|
|
232
|
+
return None
|
|
233
|
+
version = versions[-1]
|
|
234
|
+
src = os.path.join(_repository_dir(), name, version)
|
|
235
|
+
dest = os.path.join(target_root, name)
|
|
236
|
+
copy_package_tree(src, dest)
|
|
237
|
+
meta = {'repo': f'mkn-repository:{name}', 'rev': '', 'editable': False,
|
|
238
|
+
'source': src, 'installed_by': f'mkn {__version__}'}
|
|
239
|
+
with open(os.path.join(dest, '.pic-meta.json'), 'w',
|
|
240
|
+
encoding='utf-8', newline='\n') as f:
|
|
241
|
+
json.dump(meta, f, ensure_ascii=False, indent=2)
|
|
242
|
+
f.write('\n')
|
|
243
|
+
return dest
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def _project_dep_satisfied(project: MknManifest, dep: Dependency) -> bool:
|
|
247
|
+
path = os.path.join(project.pic_modules, dep.name)
|
|
248
|
+
if not os.path.isdir(path):
|
|
249
|
+
return False
|
|
250
|
+
from .packaging.store import resolve_link
|
|
251
|
+
real = resolve_link(path)
|
|
252
|
+
try:
|
|
253
|
+
meta = load_mkn_manifest(real) if os.path.isfile(
|
|
254
|
+
os.path.join(real, 'mkn.toml')) else None
|
|
255
|
+
except ManifestError:
|
|
256
|
+
meta = None
|
|
257
|
+
if meta is None:
|
|
258
|
+
try:
|
|
259
|
+
from .packaging.model import load_package_manifest
|
|
260
|
+
pkg = load_package_manifest(real, require_entry=False)
|
|
261
|
+
except ManifestError:
|
|
262
|
+
return False
|
|
263
|
+
version = pkg.version
|
|
264
|
+
else:
|
|
265
|
+
version = meta.version
|
|
266
|
+
return satisfies(version, dep.constraint) if dep.constraint else True
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
def resolve_dependencies(project: MknManifest, *, force: bool = False
|
|
270
|
+
) -> List[str]:
|
|
271
|
+
"""把 ``[dependencies]`` 解析到 ``pic_modules/``; 返回新增包名。"""
|
|
272
|
+
target = project.pic_modules
|
|
273
|
+
os.makedirs(target, exist_ok=True)
|
|
274
|
+
installed: List[str] = []
|
|
275
|
+
seen: set = set()
|
|
276
|
+
|
|
277
|
+
def _install(dep: Dependency) -> None:
|
|
278
|
+
if dep.name in seen:
|
|
279
|
+
return
|
|
280
|
+
seen.add(dep.name)
|
|
281
|
+
if not force and _project_dep_satisfied(project, dep):
|
|
282
|
+
return
|
|
283
|
+
if dep.path:
|
|
284
|
+
from . import pic
|
|
285
|
+
pic.install_path(dep.path, default_store(), target_root=target,
|
|
286
|
+
force=force, expected_name=dep.name)
|
|
287
|
+
elif dep.git:
|
|
288
|
+
from . import pic
|
|
289
|
+
pic.install_git(dep.git, default_store(),
|
|
290
|
+
ref=dep.tag or dep.rev or None,
|
|
291
|
+
target_root=target, force=force,
|
|
292
|
+
expected_name=dep.name)
|
|
293
|
+
else:
|
|
294
|
+
if _install_from_repository(dep.name, dep.constraint or '*',
|
|
295
|
+
target) is not None:
|
|
296
|
+
installed.append(dep.name)
|
|
297
|
+
return
|
|
298
|
+
from . import pic
|
|
299
|
+
pic.install_named(dep.name, dep.constraint, default_store(),
|
|
300
|
+
target_root=target, force=force)
|
|
301
|
+
installed.append(dep.name)
|
|
302
|
+
|
|
303
|
+
for dep in project.dependencies:
|
|
304
|
+
_install(dep)
|
|
305
|
+
if project.dependencies:
|
|
306
|
+
from . import pic
|
|
307
|
+
pic.write_project_lock(project.root, target)
|
|
308
|
+
return installed
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
# ==================== 打包 ====================
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
def _project_files(project: MknManifest) -> Iterable[Tuple[str, str]]:
|
|
315
|
+
root = project.root
|
|
316
|
+
for dirpath, dirnames, filenames in os.walk(root):
|
|
317
|
+
dirnames[:] = sorted(
|
|
318
|
+
d for d in dirnames
|
|
319
|
+
if d not in ('.git', '.hg', '.svn', '__pycache__', 'target',
|
|
320
|
+
'pic_modules', '.pic', '.mkn', 'node_modules',
|
|
321
|
+
'.venv', 'venv', '.pytest_cache'))
|
|
322
|
+
for filename in sorted(filenames):
|
|
323
|
+
if filename.endswith(('.pyc', '.mkn', '.cinpkg', '.cvm')):
|
|
324
|
+
continue
|
|
325
|
+
path = os.path.join(dirpath, filename)
|
|
326
|
+
yield os.path.relpath(path, root).replace(os.sep, '/'), path
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
def _generated_pic_manifest(project: MknManifest) -> str:
|
|
330
|
+
data = {
|
|
331
|
+
'package': {
|
|
332
|
+
'name': project.name,
|
|
333
|
+
'version': project.version,
|
|
334
|
+
'description': project.description,
|
|
335
|
+
'license': project.license,
|
|
336
|
+
'entry': project.entry.replace('\\', '/'),
|
|
337
|
+
'authors': project.authors,
|
|
338
|
+
},
|
|
339
|
+
}
|
|
340
|
+
if project.repo:
|
|
341
|
+
data['package']['repo'] = project.repo
|
|
342
|
+
if project.dependencies:
|
|
343
|
+
deps: Dict[str, Any] = {}
|
|
344
|
+
for dep in project.dependencies:
|
|
345
|
+
if dep.path or dep.git or dep.optional:
|
|
346
|
+
deps[dep.name] = dep.to_dict()
|
|
347
|
+
else:
|
|
348
|
+
deps[dep.name] = dep.constraint
|
|
349
|
+
data['dependencies'] = deps
|
|
350
|
+
return toml_dumps(data)
|
|
351
|
+
|
|
352
|
+
|
|
353
|
+
def package_project(project: MknManifest, bin_path: Optional[str] = None,
|
|
354
|
+
out: Optional[str] = None) -> Tuple[str, Dict[str, str]]:
|
|
355
|
+
"""构建 ``.mkn`` 分发包 (同时含 mkn.toml / pic.toml / 源码 / 字节码)。"""
|
|
356
|
+
bin_path = bin_path or build_project(project)
|
|
357
|
+
out = out or os.path.join(
|
|
358
|
+
project.target_dir, f'{project.name}-{project.version}.mkn')
|
|
359
|
+
out = os.path.abspath(out)
|
|
360
|
+
files: Dict[str, str] = {}
|
|
361
|
+
for rel, path in _project_files(project):
|
|
362
|
+
files[rel] = path
|
|
363
|
+
files['mkn.toml'] = project.manifest_path
|
|
364
|
+
files['pic.toml'] = ':generated:'
|
|
365
|
+
files[f'target/{os.path.basename(bin_path)}'] = bin_path
|
|
366
|
+
|
|
367
|
+
entries: Dict[str, bytes] = {}
|
|
368
|
+
for rel, path in files.items():
|
|
369
|
+
if path == ':generated:':
|
|
370
|
+
entries[rel] = _generated_pic_manifest(project).encode('utf-8')
|
|
371
|
+
else:
|
|
372
|
+
with open(path, 'rb') as f:
|
|
373
|
+
entries[rel] = f.read()
|
|
374
|
+
archive.write_zip(out, archive.build_archive_entries(entries))
|
|
375
|
+
return out, {rel: archive.sha256_bytes(data)
|
|
376
|
+
for rel, data in entries.items()}
|
|
377
|
+
|
|
378
|
+
|
|
379
|
+
def install_project(project: MknManifest, bin_path: Optional[str] = None
|
|
380
|
+
) -> str:
|
|
381
|
+
"""安装到本地 mkn 仓库 ``$MKN_HOME/repository/<name>/<version>``。"""
|
|
382
|
+
bin_path = bin_path or build_project(project)
|
|
383
|
+
dest = os.path.join(_repository_dir(), project.name, project.version)
|
|
384
|
+
if os.path.isdir(dest):
|
|
385
|
+
shutil.rmtree(dest)
|
|
386
|
+
os.makedirs(dest, exist_ok=True)
|
|
387
|
+
for rel, path in _project_files(project):
|
|
388
|
+
target = os.path.join(dest, rel.replace('/', os.sep))
|
|
389
|
+
os.makedirs(os.path.dirname(target), exist_ok=True)
|
|
390
|
+
shutil.copy2(path, target)
|
|
391
|
+
with open(os.path.join(dest, 'pic.toml'), 'w', encoding='utf-8',
|
|
392
|
+
newline='\n') as f:
|
|
393
|
+
f.write(_generated_pic_manifest(project))
|
|
394
|
+
target_bin = os.path.join(dest, 'target', os.path.basename(bin_path))
|
|
395
|
+
os.makedirs(os.path.dirname(target_bin), exist_ok=True)
|
|
396
|
+
shutil.copy2(bin_path, target_bin)
|
|
397
|
+
meta = {
|
|
398
|
+
'name': project.name,
|
|
399
|
+
'version': project.version,
|
|
400
|
+
'installed_at': __import__('datetime').datetime.now().astimezone()
|
|
401
|
+
.replace(microsecond=0).isoformat(),
|
|
402
|
+
'entry': project.entry,
|
|
403
|
+
}
|
|
404
|
+
with open(os.path.join(dest, '.mkn-meta.json'), 'w', encoding='utf-8',
|
|
405
|
+
newline='\n') as f:
|
|
406
|
+
json.dump(meta, f, ensure_ascii=False, indent=2)
|
|
407
|
+
f.write('\n')
|
|
408
|
+
return dest
|
|
409
|
+
|
|
410
|
+
|
|
411
|
+
# ==================== 命令实现 ====================
|
|
412
|
+
|
|
413
|
+
|
|
414
|
+
def _project_from_args(args) -> MknManifest:
|
|
415
|
+
return load_project(getattr(args, 'path', None) or os.getcwd(),
|
|
416
|
+
getattr(args, 'manifest', None))
|
|
417
|
+
|
|
418
|
+
|
|
419
|
+
def _create_project(root: str, name: str, version: str, description: str = '',
|
|
420
|
+
force: bool = False, require_empty: bool = True) -> int:
|
|
421
|
+
validate_name(name)
|
|
422
|
+
validate_version(version)
|
|
423
|
+
root = os.path.abspath(root)
|
|
424
|
+
manifest_path = os.path.join(root, 'mkn.toml')
|
|
425
|
+
if os.path.isfile(manifest_path) and not force:
|
|
426
|
+
raise MknError(f'{manifest_path} 已存在 (使用 --force 覆盖)')
|
|
427
|
+
if require_empty and os.path.isdir(root) and os.listdir(root) \
|
|
428
|
+
and not force:
|
|
429
|
+
raise MknError(f'目录非空: {root} (使用 --force 覆盖)')
|
|
430
|
+
os.makedirs(os.path.join(root, 'src', 'test'), exist_ok=True)
|
|
431
|
+
manifest = {
|
|
432
|
+
'project': {
|
|
433
|
+
'name': name,
|
|
434
|
+
'version': version,
|
|
435
|
+
'description': description or f'{name} project',
|
|
436
|
+
'license': 'MIT',
|
|
437
|
+
'entry': 'src/main.cin',
|
|
438
|
+
'authors': [],
|
|
439
|
+
},
|
|
440
|
+
'build': {
|
|
441
|
+
'optimize': 0,
|
|
442
|
+
'format': 'sdgcc',
|
|
443
|
+
'mode': 'multi',
|
|
444
|
+
},
|
|
445
|
+
}
|
|
446
|
+
with open(os.path.join(root, 'mkn.toml'), 'w', encoding='utf-8',
|
|
447
|
+
newline='\n') as f:
|
|
448
|
+
f.write(toml_dumps(manifest))
|
|
449
|
+
main = os.path.join(root, 'src', 'main.cin')
|
|
450
|
+
if not os.path.isfile(main):
|
|
451
|
+
with open(main, 'w', encoding='utf-8', newline='\n') as f:
|
|
452
|
+
f.write(
|
|
453
|
+
'function main() -> int {\n'
|
|
454
|
+
f' println("Hello from {name}!")\n'
|
|
455
|
+
' return 0\n'
|
|
456
|
+
'}\n')
|
|
457
|
+
test = os.path.join(root, 'src', 'test', 'main_test.cin')
|
|
458
|
+
if not os.path.isfile(test):
|
|
459
|
+
with open(test, 'w', encoding='utf-8', newline='\n') as f:
|
|
460
|
+
f.write(
|
|
461
|
+
'import "test.cin"\n\n'
|
|
462
|
+
'function main() -> int {\n'
|
|
463
|
+
' t_eq_int(1 + 1, 2, "arithmetic")\n'
|
|
464
|
+
' return t_report()\n'
|
|
465
|
+
'}\n')
|
|
466
|
+
readme = os.path.join(root, 'README.md')
|
|
467
|
+
if not os.path.isfile(readme):
|
|
468
|
+
with open(readme, 'w', encoding='utf-8', newline='\n') as f:
|
|
469
|
+
f.write(f'# {name}\n\n```bash\nmkn build\nmkn run\nmkn test\n```\n')
|
|
470
|
+
gitignore = os.path.join(root, '.gitignore')
|
|
471
|
+
if not os.path.isfile(gitignore):
|
|
472
|
+
with open(gitignore, 'w', encoding='utf-8', newline='\n') as f:
|
|
473
|
+
f.write('target/\npic_modules/\n*.sdgcc\n*.bin\n*.mkn\n*.cvm\n'
|
|
474
|
+
'__pycache__/\n')
|
|
475
|
+
print(f'Created mkn project {name} {version} at {root}')
|
|
476
|
+
print(f' cd {root}')
|
|
477
|
+
print(' mkn build')
|
|
478
|
+
return 0
|
|
479
|
+
|
|
480
|
+
|
|
481
|
+
def cmd_new(args) -> int:
|
|
482
|
+
root = os.path.abspath(args.dir or args.name)
|
|
483
|
+
return _create_project(root, args.name, args.version,
|
|
484
|
+
args.description, args.force)
|
|
485
|
+
|
|
486
|
+
|
|
487
|
+
def cmd_init(args) -> int:
|
|
488
|
+
root = os.path.abspath(args.path or os.getcwd())
|
|
489
|
+
name = args.name or os.path.basename(root.rstrip('\\/')) or 'my-project'
|
|
490
|
+
name = ''.join(c if c.isalnum() or c in '_-' else '-' for c in name)
|
|
491
|
+
if not name or not name[0].isalpha():
|
|
492
|
+
name = 'project-' + name
|
|
493
|
+
return _create_project(root, name, args.version, args.description,
|
|
494
|
+
args.force, require_empty=False)
|
|
495
|
+
|
|
496
|
+
|
|
497
|
+
def cmd_build(args) -> int:
|
|
498
|
+
project = _project_from_args(args)
|
|
499
|
+
if args.clean:
|
|
500
|
+
shutil.rmtree(project.target_dir, ignore_errors=True)
|
|
501
|
+
if getattr(args, 'native', False):
|
|
502
|
+
return _build_native_project(project, args)
|
|
503
|
+
out = build_project(project, output=args.output, release=args.release,
|
|
504
|
+
optimize=args.optimize, mem_size=args.mem_size,
|
|
505
|
+
bounds_check=args.bounds_check,
|
|
506
|
+
resolve=not args.no_deps)
|
|
507
|
+
print(f'Built {project.name} {project.version}: {out}')
|
|
508
|
+
if args.package:
|
|
509
|
+
pkg, _ = package_project(project, bin_path=out)
|
|
510
|
+
print(f'Packaged: {pkg}')
|
|
511
|
+
return 0
|
|
512
|
+
|
|
513
|
+
|
|
514
|
+
def _cincc_path() -> str:
|
|
515
|
+
"""定位 Go 机器码编译器 cincc。"""
|
|
516
|
+
explicit = os.environ.get("CODECIN_CINCC")
|
|
517
|
+
if explicit and os.path.isfile(explicit):
|
|
518
|
+
return explicit
|
|
519
|
+
here = os.path.dirname(os.path.abspath(__file__))
|
|
520
|
+
for name in ("cincc.exe", "cincc"):
|
|
521
|
+
candidate = os.path.join(here, "native", name)
|
|
522
|
+
if os.path.isfile(candidate):
|
|
523
|
+
return candidate
|
|
524
|
+
found = shutil.which("cincc")
|
|
525
|
+
if found:
|
|
526
|
+
return found
|
|
527
|
+
raise MknError(
|
|
528
|
+
"未找到 cincc (Go 机器码编译器)。先构建:\n"
|
|
529
|
+
" cd codecin/native && go build -o cincc ./cmd/cincc")
|
|
530
|
+
|
|
531
|
+
|
|
532
|
+
def _build_native_project(project: MknManifest, args) -> int:
|
|
533
|
+
"""``mkn build --native``: 调用 cincc 直接出机器码 (不经 C/字节码)。"""
|
|
534
|
+
import subprocess
|
|
535
|
+
|
|
536
|
+
entry = project.entry_path
|
|
537
|
+
if not entry.lower().endswith('.cin'):
|
|
538
|
+
raise MknError('mkn build --native 目前只支持 .cin 入口')
|
|
539
|
+
out = args.output or os.path.join(
|
|
540
|
+
project.target_dir, f'{project.name}-{project.version}')
|
|
541
|
+
os.makedirs(os.path.dirname(out) or '.', exist_ok=True)
|
|
542
|
+
cmd = [_cincc_path(), '-o', out, entry]
|
|
543
|
+
target = getattr(args, 'build_target', None)
|
|
544
|
+
if target:
|
|
545
|
+
cmd += ['-target', target]
|
|
546
|
+
proc = subprocess.run(cmd, capture_output=True, text=True,
|
|
547
|
+
encoding='utf-8', errors='replace')
|
|
548
|
+
if proc.returncode != 0:
|
|
549
|
+
raise MknError((proc.stderr or proc.stdout).strip())
|
|
550
|
+
print(f'Built native {project.name} {project.version}: {out}')
|
|
551
|
+
return 0
|
|
552
|
+
|
|
553
|
+
|
|
554
|
+
def cmd_run(args) -> int:
|
|
555
|
+
project = _project_from_args(args)
|
|
556
|
+
out = build_project(project, release=args.release,
|
|
557
|
+
optimize=args.optimize, mem_size=args.mem_size,
|
|
558
|
+
resolve=not args.no_deps)
|
|
559
|
+
if out.lower().endswith('.co'):
|
|
560
|
+
raise MknError('项目没有 main 函数 (库项目); 使用 mkn package/install')
|
|
561
|
+
from .cpu import CPU
|
|
562
|
+
config = _build_config(project, release=args.release,
|
|
563
|
+
optimize=args.optimize, mem_size=args.mem_size)
|
|
564
|
+
config.program_args = list(args.args or [])
|
|
565
|
+
if config.program_args and config.program_args[0] == '--':
|
|
566
|
+
config.program_args = config.program_args[1:]
|
|
567
|
+
cpu = CPU(config, out)
|
|
568
|
+
cpu.run()
|
|
569
|
+
return 1 if getattr(cpu, 'execution_failed', False) else 0
|
|
570
|
+
|
|
571
|
+
|
|
572
|
+
def cmd_test(args) -> int:
|
|
573
|
+
project = _project_from_args(args)
|
|
574
|
+
resolve_dependencies(project)
|
|
575
|
+
patterns = [
|
|
576
|
+
os.path.join(project.root, 'src', 'test', '**', '*.cin'),
|
|
577
|
+
os.path.join(project.root, 'tests', '**', '*.cin'),
|
|
578
|
+
]
|
|
579
|
+
files: List[str] = []
|
|
580
|
+
for pattern in patterns:
|
|
581
|
+
files.extend(glob.glob(pattern, recursive=True))
|
|
582
|
+
if args.filter:
|
|
583
|
+
files = [p for p in files if args.filter in p]
|
|
584
|
+
files = sorted(set(files))
|
|
585
|
+
if not files:
|
|
586
|
+
raise MknError('没有找到测试文件 (src/test/**/*.cin 或 tests/**/*.cin)')
|
|
587
|
+
from .cpu import CPU
|
|
588
|
+
failures = 0
|
|
589
|
+
for path in files:
|
|
590
|
+
rel = os.path.relpath(path, project.root)
|
|
591
|
+
config = _build_config(project, release=False, optimize=args.optimize,
|
|
592
|
+
mem_size=args.mem_size)
|
|
593
|
+
try:
|
|
594
|
+
cpu = CPU(config, path)
|
|
595
|
+
cpu._capture_output = True # noqa: SLF001 - 捕获测试断言输出
|
|
596
|
+
cpu.run()
|
|
597
|
+
except Exception as e: # noqa: BLE001 - 单个测试失败不终止其余测试
|
|
598
|
+
failures += 1
|
|
599
|
+
print(f'FAIL {rel}: {e}')
|
|
600
|
+
continue
|
|
601
|
+
output = ''.join(getattr(cpu, 'output_buffer', []))
|
|
602
|
+
if output:
|
|
603
|
+
sys.stdout.write(output)
|
|
604
|
+
if not output.endswith('\n'):
|
|
605
|
+
sys.stdout.write('\n')
|
|
606
|
+
reported_failure = re.search(r'(?m)^(FAIL |FAILED:)', output) is not None
|
|
607
|
+
if getattr(cpu, 'execution_failed', False) or reported_failure:
|
|
608
|
+
failures += 1
|
|
609
|
+
print(f'FAIL {rel}')
|
|
610
|
+
else:
|
|
611
|
+
print(f'PASS {rel}')
|
|
612
|
+
print(f'\n{len(files) - failures} passed, {failures} failed')
|
|
613
|
+
return 1 if failures else 0
|
|
614
|
+
|
|
615
|
+
|
|
616
|
+
def cmd_package(args) -> int:
|
|
617
|
+
project = _project_from_args(args)
|
|
618
|
+
out = build_project(project, release=args.release,
|
|
619
|
+
optimize=args.optimize, mem_size=args.mem_size,
|
|
620
|
+
resolve=not args.no_deps)
|
|
621
|
+
pkg, checksums = package_project(project, bin_path=out, out=args.output)
|
|
622
|
+
print(f'Packaged {project.name} {project.version}: {pkg}')
|
|
623
|
+
print(f' files: {len(checksums)}')
|
|
624
|
+
return 0
|
|
625
|
+
|
|
626
|
+
|
|
627
|
+
def cmd_install(args) -> int:
|
|
628
|
+
project = _project_from_args(args)
|
|
629
|
+
out = build_project(project, release=args.release,
|
|
630
|
+
optimize=args.optimize, resolve=not args.no_deps)
|
|
631
|
+
dest = install_project(project, bin_path=out)
|
|
632
|
+
print(f'Installed {project.name} {project.version} -> {dest}')
|
|
633
|
+
return 0
|
|
634
|
+
|
|
635
|
+
|
|
636
|
+
def cmd_deploy(args) -> int:
|
|
637
|
+
project = _project_from_args(args)
|
|
638
|
+
code = cmd_install(args)
|
|
639
|
+
if code:
|
|
640
|
+
return code
|
|
641
|
+
if args.repo:
|
|
642
|
+
from . import pic
|
|
643
|
+
argv = ['publish', '--manifest', project.manifest_path,
|
|
644
|
+
'--repo', args.repo]
|
|
645
|
+
if args.push:
|
|
646
|
+
argv.append('--push')
|
|
647
|
+
return pic.main(argv)
|
|
648
|
+
print('提示: 未提供 --repo, 仅安装到本地 mkn 仓库')
|
|
649
|
+
return 0
|
|
650
|
+
|
|
651
|
+
|
|
652
|
+
def cmd_clean(args) -> int:
|
|
653
|
+
project = _project_from_args(args)
|
|
654
|
+
shutil.rmtree(project.target_dir, ignore_errors=True)
|
|
655
|
+
print(f'Cleaned {project.target_dir}')
|
|
656
|
+
if args.deps:
|
|
657
|
+
shutil.rmtree(project.pic_modules, ignore_errors=True)
|
|
658
|
+
lock = os.path.join(project.root, 'pic.lock')
|
|
659
|
+
if os.path.isfile(lock):
|
|
660
|
+
os.remove(lock)
|
|
661
|
+
print(f'Cleaned {project.pic_modules}')
|
|
662
|
+
return 0
|
|
663
|
+
|
|
664
|
+
|
|
665
|
+
def cmd_add(args) -> int:
|
|
666
|
+
project = _project_from_args(args)
|
|
667
|
+
validate_name(args.name, '依赖名')
|
|
668
|
+
data = toml_load(project.manifest_path)
|
|
669
|
+
deps = data.setdefault('dependencies', {})
|
|
670
|
+
if args.local_path:
|
|
671
|
+
local = args.local_path
|
|
672
|
+
if os.path.isabs(local):
|
|
673
|
+
with contextlib.suppress(ValueError):
|
|
674
|
+
local = os.path.relpath(local, project.root)
|
|
675
|
+
value: Any = {'path': local.replace(os.sep, '/')}
|
|
676
|
+
elif args.git:
|
|
677
|
+
value = {'git': args.git}
|
|
678
|
+
if args.tag:
|
|
679
|
+
value['tag'] = args.tag
|
|
680
|
+
if args.rev:
|
|
681
|
+
value['rev'] = args.rev
|
|
682
|
+
if args.version:
|
|
683
|
+
value['version'] = args.version
|
|
684
|
+
else:
|
|
685
|
+
value = args.version or '*'
|
|
686
|
+
deps[args.name] = value
|
|
687
|
+
with open(project.manifest_path, 'w', encoding='utf-8', newline='\n') as f:
|
|
688
|
+
f.write(toml_dumps(data))
|
|
689
|
+
print(f'Added dependency {args.name}')
|
|
690
|
+
if not args.no_resolve:
|
|
691
|
+
reloaded = load_mkn_manifest(project.manifest_path)
|
|
692
|
+
resolve_dependencies(reloaded)
|
|
693
|
+
return 0
|
|
694
|
+
|
|
695
|
+
|
|
696
|
+
def cmd_tree(args) -> int:
|
|
697
|
+
project = _project_from_args(args)
|
|
698
|
+
lines: List[str] = [f'{project.name}@{project.version}']
|
|
699
|
+
|
|
700
|
+
def visit(deps: Sequence[Dependency], prefix: str, depth: int,
|
|
701
|
+
seen: set) -> None:
|
|
702
|
+
for index, dep in enumerate(deps):
|
|
703
|
+
last = index == len(deps) - 1
|
|
704
|
+
branch = '└── ' if last else '├── '
|
|
705
|
+
version = ''
|
|
706
|
+
path = os.path.join(project.pic_modules, dep.name)
|
|
707
|
+
if os.path.isdir(path):
|
|
708
|
+
try:
|
|
709
|
+
from .packaging.model import load_package_manifest
|
|
710
|
+
version = load_package_manifest(
|
|
711
|
+
path, require_entry=False).version
|
|
712
|
+
except ManifestError:
|
|
713
|
+
version = '?'
|
|
714
|
+
label = f'{dep.name}@{version}' if version else dep.name
|
|
715
|
+
if dep.constraint:
|
|
716
|
+
label += f' ({dep.constraint})'
|
|
717
|
+
lines.append(prefix + branch + label)
|
|
718
|
+
if depth >= args.depth or dep.name in seen:
|
|
719
|
+
continue
|
|
720
|
+
try:
|
|
721
|
+
from .packaging.model import load_package_manifest
|
|
722
|
+
meta = load_package_manifest(path, require_entry=False)
|
|
723
|
+
child_prefix = prefix + (' ' if last else '│ ')
|
|
724
|
+
visit(meta.dependencies, child_prefix, depth + 1,
|
|
725
|
+
seen | {dep.name})
|
|
726
|
+
except (ManifestError, OSError):
|
|
727
|
+
pass
|
|
728
|
+
|
|
729
|
+
visit(project.dependencies, '', 1, set())
|
|
730
|
+
sys.stdout.write('\n'.join(lines) + '\n')
|
|
731
|
+
return 0
|
|
732
|
+
|
|
733
|
+
|
|
734
|
+
def cmd_verify(args) -> int:
|
|
735
|
+
project = _project_from_args(args)
|
|
736
|
+
problems: List[str] = []
|
|
737
|
+
try:
|
|
738
|
+
entry = project.entry_path
|
|
739
|
+
if not os.path.isfile(entry):
|
|
740
|
+
problems.append(f'入口不存在: {entry}')
|
|
741
|
+
except ManifestError as e:
|
|
742
|
+
problems.append(str(e))
|
|
743
|
+
for dep in project.dependencies:
|
|
744
|
+
if not _project_dep_satisfied(project, dep):
|
|
745
|
+
problems.append(f'依赖未解析: {dep.spec}')
|
|
746
|
+
if problems:
|
|
747
|
+
for problem in problems:
|
|
748
|
+
print(f'ERROR {problem}')
|
|
749
|
+
return 1
|
|
750
|
+
print(f'OK {project.name} {project.version} '
|
|
751
|
+
f'({len(project.dependencies)} dependencies)')
|
|
752
|
+
return 0
|
|
753
|
+
|
|
754
|
+
|
|
755
|
+
def cmd_doctor(args) -> int:
|
|
756
|
+
project = None
|
|
757
|
+
with contextlib.suppress(MknError):
|
|
758
|
+
project = _project_from_args(args)
|
|
759
|
+
print(f'mkn {__version__}')
|
|
760
|
+
print(f'home : {_home()}')
|
|
761
|
+
print(f'git : {shutil.which("git") or "NOT FOUND"}')
|
|
762
|
+
print(f'go : {shutil.which("go") or "NOT FOUND"}')
|
|
763
|
+
if project:
|
|
764
|
+
print(f'project : {project.name} {project.version}')
|
|
765
|
+
try:
|
|
766
|
+
entry = project.entry_path
|
|
767
|
+
except ManifestError:
|
|
768
|
+
entry = '(missing)'
|
|
769
|
+
print(f'entry : {entry}')
|
|
770
|
+
print(f'target : {project.target_dir}')
|
|
771
|
+
print(f'deps : {len(project.dependencies)}')
|
|
772
|
+
return 0
|
|
773
|
+
|
|
774
|
+
|
|
775
|
+
# ==================== argparse ====================
|
|
776
|
+
|
|
777
|
+
|
|
778
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
779
|
+
parser = argparse.ArgumentParser(
|
|
780
|
+
prog='mkn',
|
|
781
|
+
description='Code CIN 项目构建与依赖工具 (Maven 风格生命周期)')
|
|
782
|
+
parser.add_argument('--version', action='version',
|
|
783
|
+
version=f'mkn {__version__}')
|
|
784
|
+
sub = parser.add_subparsers(dest='command', required=True)
|
|
785
|
+
|
|
786
|
+
def project_opts(p: argparse.ArgumentParser) -> None:
|
|
787
|
+
p.add_argument('--path', help='项目目录 (默认当前目录)')
|
|
788
|
+
p.add_argument('--manifest', help='mkn.toml 路径')
|
|
789
|
+
|
|
790
|
+
p = sub.add_parser('new', help='创建标准项目骨架')
|
|
791
|
+
p.add_argument('name')
|
|
792
|
+
p.add_argument('--dir', help='目标目录 (默认 ./<name>)')
|
|
793
|
+
p.add_argument('--version', default='0.1.0')
|
|
794
|
+
p.add_argument('--description', default='')
|
|
795
|
+
p.add_argument('--force', action='store_true')
|
|
796
|
+
p.set_defaults(func=cmd_new)
|
|
797
|
+
|
|
798
|
+
p = sub.add_parser('init', help='在当前目录初始化项目')
|
|
799
|
+
p.add_argument('name', nargs='?')
|
|
800
|
+
p.add_argument('--path')
|
|
801
|
+
p.add_argument('--version', default='0.1.0')
|
|
802
|
+
p.add_argument('--description', default='')
|
|
803
|
+
p.add_argument('--force', action='store_true')
|
|
804
|
+
p.set_defaults(func=cmd_init)
|
|
805
|
+
|
|
806
|
+
p = sub.add_parser('build', aliases=['compile'], help='编译入口为 .bin')
|
|
807
|
+
project_opts(p)
|
|
808
|
+
p.add_argument('-o', '--output')
|
|
809
|
+
p.add_argument('--release', action='store_true', help='优化级别至少为 2')
|
|
810
|
+
p.add_argument('--optimize', type=int, choices=range(0, 4))
|
|
811
|
+
p.add_argument('--mem-size', type=int, dest='mem_size')
|
|
812
|
+
p.add_argument('--bounds-check', action='store_true', dest='bounds_check')
|
|
813
|
+
p.add_argument('--no-deps', action='store_true', dest='no_deps')
|
|
814
|
+
p.add_argument('--native', action='store_true',
|
|
815
|
+
help='直接用 AST→C 原生后端编译为设备本机可执行文件 '
|
|
816
|
+
'(不经过 UCPU 指令集; 超出语言子集会报错)')
|
|
817
|
+
p.add_argument('--clean', action='store_true')
|
|
818
|
+
p.add_argument('--package', action='store_true', help='编译后同时打包')
|
|
819
|
+
p.set_defaults(func=cmd_build)
|
|
820
|
+
|
|
821
|
+
p = sub.add_parser('run', help='编译并运行')
|
|
822
|
+
project_opts(p)
|
|
823
|
+
p.add_argument('--release', action='store_true')
|
|
824
|
+
p.add_argument('--optimize', type=int, choices=range(0, 4))
|
|
825
|
+
p.add_argument('--mem-size', type=int, dest='mem_size')
|
|
826
|
+
p.add_argument('--no-deps', action='store_true', dest='no_deps')
|
|
827
|
+
p.add_argument('args', nargs=argparse.REMAINDER,
|
|
828
|
+
help='传给 CIN 程序的参数 (写在 -- 之后)')
|
|
829
|
+
p.set_defaults(func=cmd_run)
|
|
830
|
+
|
|
831
|
+
p = sub.add_parser('test', help='运行 src/test 下的测试程序')
|
|
832
|
+
project_opts(p)
|
|
833
|
+
p.add_argument('--filter', help='只运行路径包含该子串的测试')
|
|
834
|
+
p.add_argument('--optimize', type=int, choices=range(0, 4))
|
|
835
|
+
p.add_argument('--mem-size', type=int, dest='mem_size')
|
|
836
|
+
p.set_defaults(func=cmd_test)
|
|
837
|
+
|
|
838
|
+
p = sub.add_parser('package', help='生成 .mkn 分发包')
|
|
839
|
+
project_opts(p)
|
|
840
|
+
p.add_argument('-o', '--output')
|
|
841
|
+
p.add_argument('--release', action='store_true')
|
|
842
|
+
p.add_argument('--optimize', type=int, choices=range(0, 4))
|
|
843
|
+
p.add_argument('--mem-size', type=int, dest='mem_size')
|
|
844
|
+
p.add_argument('--no-deps', action='store_true', dest='no_deps')
|
|
845
|
+
p.set_defaults(func=cmd_package)
|
|
846
|
+
|
|
847
|
+
p = sub.add_parser('install', help='安装到本地 mkn 仓库')
|
|
848
|
+
project_opts(p)
|
|
849
|
+
p.add_argument('--release', action='store_true')
|
|
850
|
+
p.add_argument('--optimize', type=int, choices=range(0, 4))
|
|
851
|
+
p.add_argument('--no-deps', action='store_true', dest='no_deps')
|
|
852
|
+
p.set_defaults(func=cmd_install)
|
|
853
|
+
|
|
854
|
+
p = sub.add_parser('deploy', help='安装并可发布到 Git')
|
|
855
|
+
project_opts(p)
|
|
856
|
+
p.add_argument('--repo', help='Git 仓库地址')
|
|
857
|
+
p.add_argument('--push', action='store_true')
|
|
858
|
+
p.add_argument('--release', action='store_true')
|
|
859
|
+
p.add_argument('--optimize', type=int, choices=range(0, 4))
|
|
860
|
+
p.add_argument('--no-deps', action='store_true', dest='no_deps')
|
|
861
|
+
p.set_defaults(func=cmd_deploy)
|
|
862
|
+
|
|
863
|
+
p = sub.add_parser('clean', help='删除 target/')
|
|
864
|
+
project_opts(p)
|
|
865
|
+
p.add_argument('--deps', action='store_true', help='同时删除 pic_modules/')
|
|
866
|
+
p.set_defaults(func=cmd_clean)
|
|
867
|
+
|
|
868
|
+
p = sub.add_parser('add', help='添加依赖')
|
|
869
|
+
project_opts(p)
|
|
870
|
+
p.add_argument('name')
|
|
871
|
+
p.add_argument('--version')
|
|
872
|
+
p.add_argument('--git')
|
|
873
|
+
p.add_argument('--tag')
|
|
874
|
+
p.add_argument('--rev')
|
|
875
|
+
p.add_argument('--local-path', dest='local_path',
|
|
876
|
+
help='本地路径依赖 (独立于项目的 --path)')
|
|
877
|
+
p.add_argument('--no-resolve', action='store_true', dest='no_resolve')
|
|
878
|
+
p.set_defaults(func=cmd_add)
|
|
879
|
+
|
|
880
|
+
p = sub.add_parser('tree', help='打印依赖树')
|
|
881
|
+
project_opts(p)
|
|
882
|
+
p.add_argument('--depth', type=int, default=8)
|
|
883
|
+
p.set_defaults(func=cmd_tree)
|
|
884
|
+
|
|
885
|
+
p = sub.add_parser('verify', help='校验清单/入口/依赖')
|
|
886
|
+
project_opts(p)
|
|
887
|
+
p.set_defaults(func=cmd_verify)
|
|
888
|
+
|
|
889
|
+
p = sub.add_parser('doctor', help='检查工具链环境')
|
|
890
|
+
project_opts(p)
|
|
891
|
+
p.set_defaults(func=cmd_doctor)
|
|
892
|
+
return parser
|
|
893
|
+
|
|
894
|
+
|
|
895
|
+
def main(argv: Optional[Sequence[str]] = None) -> int:
|
|
896
|
+
from .toolkit import configure_stdio
|
|
897
|
+
configure_stdio()
|
|
898
|
+
parser = build_parser()
|
|
899
|
+
args = parser.parse_args(list(sys.argv[1:] if argv is None else argv))
|
|
900
|
+
try:
|
|
901
|
+
return int(args.func(args) or 0)
|
|
902
|
+
except (MknError, ManifestError, archive.ArchiveError,
|
|
903
|
+
vcs.VcsError, OSError) as e:
|
|
904
|
+
sys.stderr.write(f'mkn: error: {e}\n')
|
|
905
|
+
return 1
|
|
906
|
+
except Exception as e: # noqa: BLE001 - 编译/链接错误统一为一行
|
|
907
|
+
from .errors import CompilerError, CPUSimulatorError
|
|
908
|
+
from .object import ObjectError
|
|
909
|
+
if isinstance(e, (CompilerError, CPUSimulatorError, ObjectError)):
|
|
910
|
+
sys.stderr.write(f'mkn: error: {e}\n')
|
|
911
|
+
return 1
|
|
912
|
+
raise
|
|
913
|
+
|
|
914
|
+
|
|
915
|
+
if __name__ == '__main__':
|
|
916
|
+
sys.exit(main())
|