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/cli.py
ADDED
|
@@ -0,0 +1,670 @@
|
|
|
1
|
+
"""命令行入口: argparse 参数解析 -> 加载程序 -> 运行。
|
|
2
|
+
|
|
3
|
+
建议 3: 采用 argparse 统一参数表 (不再三份手写解析), 全部选项由
|
|
4
|
+
build_parser() 单一来源定义, --help 与解析行为自动保持一致。
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import argparse
|
|
8
|
+
import contextlib
|
|
9
|
+
import os
|
|
10
|
+
import sys
|
|
11
|
+
import time
|
|
12
|
+
from typing import List, Optional
|
|
13
|
+
|
|
14
|
+
from . import __version__
|
|
15
|
+
from .config import Config
|
|
16
|
+
from .console import Colors, Console, Panel
|
|
17
|
+
|
|
18
|
+
HELP_INTRO = f"""{Colors.colorize(f'Code CIN v{__version__}', Colors.CYAN, True)}
|
|
19
|
+
|
|
20
|
+
{Colors.colorize('Usage:', Colors.YELLOW)}
|
|
21
|
+
codecin [options] <program.[cin|pl|asm|bin]> [args...]
|
|
22
|
+
|
|
23
|
+
{Colors.colorize('Program arguments:', Colors.YELLOW)}
|
|
24
|
+
program 之后的裸参数原样传给 CIN 程序 (arg_count()/arg(i) 读取);
|
|
25
|
+
CLI 选项放在 program 之前或之后均可识别, 形如选项的参数请用 `--` 显式分隔。
|
|
26
|
+
|
|
27
|
+
{Colors.colorize('Supported formats:', Colors.YELLOW)}
|
|
28
|
+
.cin CIN 高级语言 (函数/struct/数组/浮点/字符串)
|
|
29
|
+
.pl Code CIN 汇编语言 (PL 关键字风格)
|
|
30
|
+
.asm Code CIN 汇编
|
|
31
|
+
.bin UCBC 字节码 (由 --compile 生成)
|
|
32
|
+
|
|
33
|
+
{Colors.colorize('Toolchain (v6.2.0):', Colors.YELLOW)}
|
|
34
|
+
mkn 项目构建/依赖 (Maven 风格)
|
|
35
|
+
pic 去中心化包管理 (pip 风格, 安装后可直接 import)
|
|
36
|
+
cvm CVM 虚拟机/模块运行时 (JVM 风格)
|
|
37
|
+
"""
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _stdout_is_tty() -> bool:
|
|
41
|
+
"""stdout 是否为真实终端 (仅此时打印运行前进度状态)。"""
|
|
42
|
+
try:
|
|
43
|
+
return bool(sys.stdout is not None and sys.stdout.isatty())
|
|
44
|
+
except (OSError, ValueError, AttributeError):
|
|
45
|
+
return False
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
49
|
+
"""参数表单一来源 (与 Config 字段一一对应)。"""
|
|
50
|
+
p = argparse.ArgumentParser(
|
|
51
|
+
prog='codecin',
|
|
52
|
+
description='Code CIN - 高级语言与运行时 (CIN/PL/ASM 工具链 + 多执行路径)',
|
|
53
|
+
add_help=False,
|
|
54
|
+
)
|
|
55
|
+
p.add_argument('program', nargs='?', default=None,
|
|
56
|
+
metavar='program.[cin|pl|asm|bin]',
|
|
57
|
+
help='程序源文件/字节码/镜像')
|
|
58
|
+
p.add_argument('--help', '-h', action='store_true', dest='show_help',
|
|
59
|
+
help='显示帮助')
|
|
60
|
+
from . import __version__
|
|
61
|
+
p.add_argument('--version', '-V', action='version',
|
|
62
|
+
version=f'Code CIN {__version__}',
|
|
63
|
+
help='显示版本号并退出')
|
|
64
|
+
p.add_argument('--build-info', action='store_true', dest='build_info',
|
|
65
|
+
help='显示构建/运行环境信息 (版本、解释器、平台、原生库、'
|
|
66
|
+
'包路径) 后退出; 与 --json 合用输出机器可读 JSON')
|
|
67
|
+
p.add_argument('--json', action='store_true', dest='json_output',
|
|
68
|
+
help='配合 --build-info 输出 JSON (需与 --build-info 同时使用)')
|
|
69
|
+
p.add_argument('--libs', action='store_true', dest='list_libs',
|
|
70
|
+
help='列出内置标准库并标注执行路径要求 '
|
|
71
|
+
'(纯 CIN / C·C++·Go 兼容层 / 需原生运行时) 后退出')
|
|
72
|
+
|
|
73
|
+
# 日志与调试
|
|
74
|
+
p.add_argument('--debug', action='store_true',
|
|
75
|
+
help='调试模式 (强制 DEBUG 日志, 执行结束输出 CPU 状态与统计, '
|
|
76
|
+
'异常打印完整堆栈)')
|
|
77
|
+
p.add_argument('--log-level', choices=['DEBUG', 'INFO', 'WARNING', 'ERROR',
|
|
78
|
+
'CRITICAL'],
|
|
79
|
+
help='日志级别 (默认 INFO)')
|
|
80
|
+
p.add_argument('--log-file', metavar='FILE', help='日志输出到文件')
|
|
81
|
+
p.add_argument('--sandbox', action='store_true',
|
|
82
|
+
help='沙箱模式 (在 Go 引擎侧拦截全部宿主能力系统调用)')
|
|
83
|
+
|
|
84
|
+
# 资源限制
|
|
85
|
+
p.add_argument('--mem-size', type=int, metavar='BYTES',
|
|
86
|
+
help='内存大小 (默认 1073741824 = 1 GiB, 动态分配, '
|
|
87
|
+
'只占实际写入的物理内存)')
|
|
88
|
+
# --max-instructions 已弃用: 默认不限制指令数 (保留为隐藏参数以免破坏脚本)
|
|
89
|
+
p.add_argument('--max-instructions', type=int, metavar='N',
|
|
90
|
+
help=argparse.SUPPRESS)
|
|
91
|
+
|
|
92
|
+
# 编译 / CROM
|
|
93
|
+
p.add_argument('--compile', action='store_true', dest='compile_to_bin',
|
|
94
|
+
help='编译为 .sdgcc 产物后继续执行')
|
|
95
|
+
p.add_argument('--compile-only', action='store_true',
|
|
96
|
+
help='仅编译为 .sdgcc 不执行')
|
|
97
|
+
p.add_argument('-o', '--output', metavar='FILE',
|
|
98
|
+
help='指定输出文件 (.crom/.sdgcc/.bin)')
|
|
99
|
+
p.add_argument('--crom', metavar='FILE', help='加载指定 .crom 内存镜像')
|
|
100
|
+
p.add_argument('--save', action='store_true', dest='auto_save_crom',
|
|
101
|
+
help='执行后保存 .crom 内存镜像')
|
|
102
|
+
p.add_argument('--no-compress', action='store_false', dest='compress_crom',
|
|
103
|
+
help='.crom 不压缩 (默认压缩)')
|
|
104
|
+
p.add_argument('--sdgcc-compress', action='store_true', dest='sdgcc_compress',
|
|
105
|
+
help='.sdgcc 的 META/SYMS/SRCS 段启用 zlib 压缩 (版本升为 2)')
|
|
106
|
+
|
|
107
|
+
# 语言/汇编
|
|
108
|
+
p.add_argument('--optimize', type=int, metavar='0-3',
|
|
109
|
+
help='IR 优化级别 (0 关闭; 1 窥孔; 2 常量折叠; '
|
|
110
|
+
'3 不可达代码删除; 默认 0)')
|
|
111
|
+
p.add_argument('--strict', action='store_true', help='严格汇编模式')
|
|
112
|
+
|
|
113
|
+
# 运行时行为 (A1/A2)
|
|
114
|
+
p.add_argument('--seed', type=int, default=None, metavar='N',
|
|
115
|
+
help='随机种子 (确定性执行; 默认随机)')
|
|
116
|
+
p.add_argument('--bounds-check', action='store_true',
|
|
117
|
+
help='CIN 数组越界运行时检查 (编译期注入)')
|
|
118
|
+
p.add_argument('--disasm', action='store_true',
|
|
119
|
+
help='反汇编 .bin 字节码为文本清单后退出')
|
|
120
|
+
p.add_argument('--emit-object', action='store_true', dest='emit_object',
|
|
121
|
+
help='仅把 CIN/ASM/PL 编译为可重定位对象 (.co) 后退出')
|
|
122
|
+
p.add_argument('--link', action='append', metavar='INPUT', default=None,
|
|
123
|
+
help='链接 .cin/.asm/.pl/.co/.colib 输入为可执行文件 (可重复)')
|
|
124
|
+
p.add_argument('--emit-archive', action='store_true', dest='emit_archive',
|
|
125
|
+
help='把 --link 输入打包为 .colib 静态库归档')
|
|
126
|
+
p.add_argument('--gc-sections', action='store_true', dest='gc_sections',
|
|
127
|
+
help='链接时删除不可达函数/代码段 (默认关闭)')
|
|
128
|
+
|
|
129
|
+
# AOT: 编译成独立静态可执行文件
|
|
130
|
+
p.add_argument('--native', action='store_true',
|
|
131
|
+
help='直接用 AST→C 原生后端编译为设备本机可执行文件并运行 '
|
|
132
|
+
'(不经过 UCPU 指令集); 超出语言子集会明确报错')
|
|
133
|
+
p.add_argument('--native-out', metavar='OUT', default=None,
|
|
134
|
+
help='同 --native, 但只构建不运行, 产物写到 OUT')
|
|
135
|
+
p.add_argument('--build-exe', nargs='?', const='', default=None,
|
|
136
|
+
metavar='OUT',
|
|
137
|
+
help='把 CIN/ASM/PL/BIN/CO 编译成独立静态可执行文件 '
|
|
138
|
+
'(不依赖 Python/动态库) 后退出; '
|
|
139
|
+
'省略路径时输出到 <程序名>[.exe]')
|
|
140
|
+
p.add_argument('--build-target', default=None, metavar='OS/ARCH',
|
|
141
|
+
help='AOT 交叉编译目标 (默认当前平台): '
|
|
142
|
+
'windows/amd64, linux/amd64, linux/arm64, '
|
|
143
|
+
'darwin/amd64, darwin/arm64')
|
|
144
|
+
p.add_argument('--build-keep-temp', action='store_true',
|
|
145
|
+
help='AOT 构建时保留临时目录 (排查 go build 失败)')
|
|
146
|
+
p.add_argument('--build-static', action='store_true', dest='build_static',
|
|
147
|
+
help='C 后端产物静态链接 (macOS 目标会自动忽略)')
|
|
148
|
+
p.add_argument('--build-strip', action='store_true', dest='build_strip',
|
|
149
|
+
help='C 后端产物去掉符号表 (体积更小)')
|
|
150
|
+
p.add_argument('--build-keep-c', action='store_true', dest='build_keep_c',
|
|
151
|
+
help='保留 C 后端生成的 program.c (<产物>.c)')
|
|
152
|
+
p.add_argument('--build-verify', action='store_true', dest='build_verify',
|
|
153
|
+
help='构建后校验 ELF/PE 头部与目标架构是否一致')
|
|
154
|
+
p.add_argument('--build-backend', choices=['auto', 'c', 'native', 'vm'],
|
|
155
|
+
default='auto',
|
|
156
|
+
help='AOT 后端: auto = 优先 C 后端, 不支持时回退 Go/VM (默认); '
|
|
157
|
+
'c = 生成 C 并由 GCC/Clang 编译 (不依赖 Go); '
|
|
158
|
+
'native = 旧 Go 代码生成后端; '
|
|
159
|
+
'vm = 内嵌 UCBC 字节码由 Go VM 执行')
|
|
160
|
+
p.add_argument('--no-build-cache', action='store_false', dest='build_cache',
|
|
161
|
+
default=True,
|
|
162
|
+
help='禁用 AOT 增量构建缓存 (默认启用)')
|
|
163
|
+
p.add_argument('--build-debug', action='store_true', dest='build_debug',
|
|
164
|
+
help='保留符号表/DWARF (不传 -s -w), 便于调试')
|
|
165
|
+
return p
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def _apply_namespace(config: Config, ns: argparse.Namespace) -> None:
|
|
169
|
+
"""把 argparse Namespace 映射到 Config 字段。"""
|
|
170
|
+
config.sandbox_mode = ns.sandbox
|
|
171
|
+
config.debug_mode = ns.debug
|
|
172
|
+
config.auto_save_crom = ns.auto_save_crom
|
|
173
|
+
config.compress_crom = ns.compress_crom
|
|
174
|
+
config.sdgcc_compress = ns.sdgcc_compress
|
|
175
|
+
config.compile_to_bin = ns.compile_to_bin
|
|
176
|
+
config.compile_only = ns.compile_only
|
|
177
|
+
config.output_file = ns.output
|
|
178
|
+
config.strict_mode = ns.strict
|
|
179
|
+
config.seed = ns.seed
|
|
180
|
+
config.bounds_check = ns.bounds_check
|
|
181
|
+
|
|
182
|
+
if ns.log_level is not None:
|
|
183
|
+
config.log_level = ns.log_level
|
|
184
|
+
if ns.log_file is not None:
|
|
185
|
+
config.log_file = ns.log_file
|
|
186
|
+
if ns.mem_size is not None:
|
|
187
|
+
config.mem_size = ns.mem_size
|
|
188
|
+
if ns.max_instructions is not None:
|
|
189
|
+
config.max_instructions = ns.max_instructions
|
|
190
|
+
if ns.optimize is not None:
|
|
191
|
+
config.optimize = ns.optimize
|
|
192
|
+
|
|
193
|
+
# --debug 是比 --log-level 更强的开关: 与旧版一致, 始终强制 DEBUG
|
|
194
|
+
if config.debug_mode:
|
|
195
|
+
config.log_level = 'DEBUG'
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def _find_cincc():
|
|
199
|
+
"""定位 Go 原生编译器 cincc (Python 只负责调用)。"""
|
|
200
|
+
import shutil
|
|
201
|
+
explicit = os.environ.get("CODECIN_CINCC")
|
|
202
|
+
if explicit and os.path.isfile(explicit):
|
|
203
|
+
return explicit
|
|
204
|
+
here = os.path.dirname(os.path.abspath(__file__))
|
|
205
|
+
for name in ("cincc.exe", "cincc"):
|
|
206
|
+
candidate = os.path.join(here, "native", name)
|
|
207
|
+
if os.path.isfile(candidate):
|
|
208
|
+
return candidate
|
|
209
|
+
return shutil.which("cincc")
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def _run_native(ns: argparse.Namespace, console, program_file: str,
|
|
213
|
+
config) -> int:
|
|
214
|
+
"""--native / --native-out: 调用 Go 编译器 cincc 直接出机器码。"""
|
|
215
|
+
import subprocess
|
|
216
|
+
import tempfile
|
|
217
|
+
|
|
218
|
+
cincc = _find_cincc()
|
|
219
|
+
if cincc is None:
|
|
220
|
+
console.print(Panel(
|
|
221
|
+
"未找到 cincc (Go 机器码编译器)。先构建:\n"
|
|
222
|
+
" cd codecin/native && go build -o cincc ./cmd/cincc",
|
|
223
|
+
title="Native Build Error", border_style="red"))
|
|
224
|
+
return 1
|
|
225
|
+
|
|
226
|
+
target = None
|
|
227
|
+
if ns.build_target:
|
|
228
|
+
mapping = {"linux/amd64": "x86_64-linux",
|
|
229
|
+
"linux/x86_64": "x86_64-linux"}
|
|
230
|
+
target = mapping.get(ns.build_target)
|
|
231
|
+
if target is None:
|
|
232
|
+
console.print(Panel(f"cincc 暂不支持目标 {ns.build_target}",
|
|
233
|
+
title="Build Error", border_style="red"))
|
|
234
|
+
return 1
|
|
235
|
+
|
|
236
|
+
build_only = ns.native_out is not None
|
|
237
|
+
if build_only:
|
|
238
|
+
out = ns.native_out or (os.path.splitext(program_file)[0] + ".exe")
|
|
239
|
+
else:
|
|
240
|
+
tmpdir = tempfile.mkdtemp(prefix=".native-")
|
|
241
|
+
out = os.path.join(tmpdir, os.path.splitext(
|
|
242
|
+
os.path.basename(program_file))[0])
|
|
243
|
+
|
|
244
|
+
cmd = [cincc, "-o", out, program_file]
|
|
245
|
+
if target:
|
|
246
|
+
cmd += ["-target", target]
|
|
247
|
+
proc = subprocess.run(cmd, capture_output=True, text=True,
|
|
248
|
+
encoding="utf-8", errors="replace")
|
|
249
|
+
if proc.returncode != 0:
|
|
250
|
+
console.print(Panel((proc.stderr or proc.stdout).strip(),
|
|
251
|
+
title="Native Build Error", border_style="red"))
|
|
252
|
+
return 1
|
|
253
|
+
|
|
254
|
+
if build_only:
|
|
255
|
+
console.print(Colors.colorize(f"Built native: {out}", Colors.GREEN))
|
|
256
|
+
return 0
|
|
257
|
+
|
|
258
|
+
argv = [out] + list(config.program_args)
|
|
259
|
+
if os.name == "nt" and target != "x86_64-windows":
|
|
260
|
+
import shutil as _shutil
|
|
261
|
+
wsl = _shutil.which("wsl")
|
|
262
|
+
if not wsl:
|
|
263
|
+
console.print(Panel(
|
|
264
|
+
"产物是 Linux ELF,Windows 无法直接运行。\n"
|
|
265
|
+
"用 --native-out 保留产物并在 WSL/Linux 中执行,或安装 WSL。",
|
|
266
|
+
title="Run Error", border_style="red"))
|
|
267
|
+
return 1
|
|
268
|
+
drive = out[0].lower()
|
|
269
|
+
wsl_path = "/mnt/" + drive + out[2:].replace("\\", "/")
|
|
270
|
+
argv = [wsl, "-e", wsl_path] + list(config.program_args)
|
|
271
|
+
try:
|
|
272
|
+
run = subprocess.run(argv)
|
|
273
|
+
return int(run.returncode)
|
|
274
|
+
except OSError as e:
|
|
275
|
+
console.print(Panel(str(e), title="Run Error", border_style="red"))
|
|
276
|
+
return 1
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def toolchain_error():
|
|
280
|
+
from .toolchain import ToolchainError
|
|
281
|
+
return ToolchainError
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def _run_aot_build(ns: argparse.Namespace, console, program_file: str,
|
|
285
|
+
config) -> int:
|
|
286
|
+
"""AOT: 把 CIN/ASM/PL/BIN/CO 编译成独立静态可执行文件 (--build-exe)。"""
|
|
287
|
+
from . import aot
|
|
288
|
+
from .errors import CPUSimulatorError
|
|
289
|
+
|
|
290
|
+
if not os.path.isfile(program_file):
|
|
291
|
+
console.print(Panel(f"File '{program_file}' not found",
|
|
292
|
+
title='Build Error', border_style='red'))
|
|
293
|
+
return 1
|
|
294
|
+
|
|
295
|
+
target = ns.build_target or aot.host_target()
|
|
296
|
+
try:
|
|
297
|
+
goos, _goarch = aot.parse_target(target)
|
|
298
|
+
except aot.AotError as e:
|
|
299
|
+
console.print(Panel(str(e), title='Build Error', border_style='red'))
|
|
300
|
+
return 1
|
|
301
|
+
|
|
302
|
+
out = ns.build_exe or (os.path.splitext(program_file)[0]
|
|
303
|
+
+ aot.exe_suffix(goos))
|
|
304
|
+
console.print(Colors.colorize(
|
|
305
|
+
f"AOT build: {program_file} -> {out} "
|
|
306
|
+
f"(静态链接, 目标 {target}, 后端 {ns.build_backend})",
|
|
307
|
+
Colors.CYAN))
|
|
308
|
+
try:
|
|
309
|
+
# 依赖检查与嵌入由 build_program 内部完成; 这里先把清单展示给用户
|
|
310
|
+
deps = aot.program_dependencies(program_file)
|
|
311
|
+
embedded = [os.path.basename(p) for p in deps[1:]]
|
|
312
|
+
if embedded:
|
|
313
|
+
console.print(Colors.colorize(
|
|
314
|
+
f"依赖库 {len(embedded)} 个 (编译期嵌入产物): "
|
|
315
|
+
f"{', '.join(embedded)}", Colors.CYAN))
|
|
316
|
+
built = aot.build_program(program_file, out=out, target=target,
|
|
317
|
+
keep_temp=ns.build_keep_temp,
|
|
318
|
+
mem_size=config.mem_size,
|
|
319
|
+
backend=ns.build_backend,
|
|
320
|
+
max_instructions=config.max_instructions,
|
|
321
|
+
optimize=config.optimize,
|
|
322
|
+
use_cache=ns.build_cache,
|
|
323
|
+
debug=ns.build_debug,
|
|
324
|
+
c_static=ns.build_static,
|
|
325
|
+
c_strip=ns.build_strip,
|
|
326
|
+
c_keep_c=ns.build_keep_c)
|
|
327
|
+
except (aot.AotError, CPUSimulatorError) as e:
|
|
328
|
+
console.print(Panel(str(e), title='Build Error', border_style='red'))
|
|
329
|
+
return 1
|
|
330
|
+
except Exception as e: # 兜底: 不再向上抛裸 traceback
|
|
331
|
+
console.print(Panel(str(e), title='Build Error', border_style='red'))
|
|
332
|
+
if config.debug_mode or config.log_level.upper() == 'DEBUG':
|
|
333
|
+
console.print_exception()
|
|
334
|
+
return 1
|
|
335
|
+
if getattr(ns, 'build_verify', False):
|
|
336
|
+
from . import cbackend
|
|
337
|
+
try:
|
|
338
|
+
info = cbackend.inspect_binary(built, target)
|
|
339
|
+
except ValueError as e:
|
|
340
|
+
console.print(Panel(str(e), title='Verify Error', border_style='red'))
|
|
341
|
+
return 1
|
|
342
|
+
console.print(Colors.colorize(
|
|
343
|
+
'Verify OK: ' + ' '.join(f'{k}={v}' for k, v in info.items()),
|
|
344
|
+
Colors.GREEN))
|
|
345
|
+
console.print(Colors.colorize(f"AOT build 完成: {built}", Colors.GREEN))
|
|
346
|
+
return 0
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
def _extract_program_args(args: List[str], parser: argparse.ArgumentParser):
|
|
350
|
+
"""把程序文件之后的裸参数透传给 CIN 程序 (arg_count()/arg(i))。
|
|
351
|
+
|
|
352
|
+
规则 (向后兼容): 第一个非选项 token 是程序文件; 此后遇到已知 CLI 选项
|
|
353
|
+
(及其取值) 仍归 CLI 解析, 其余裸 token 归程序参数。`--` 分隔的参数已在
|
|
354
|
+
main 里摘出, 优先级更高。返回 (cli_args, program_args)。
|
|
355
|
+
"""
|
|
356
|
+
takes_value = {}
|
|
357
|
+
for act in parser._actions: # noqa: SLF001 - argparse 无公开枚举接口
|
|
358
|
+
for s in getattr(act, 'option_strings', []):
|
|
359
|
+
takes_value[s] = getattr(act, 'nargs', None) != 0
|
|
360
|
+
cli_args: List[str] = []
|
|
361
|
+
prog_args: List[str] = []
|
|
362
|
+
seen_prog = False
|
|
363
|
+
i, n = 0, len(args)
|
|
364
|
+
while i < n:
|
|
365
|
+
tok = args[i]
|
|
366
|
+
# --opt=value 形式按其选项名识别
|
|
367
|
+
optname = tok.split('=', 1)[0] if tok.startswith('--') else tok
|
|
368
|
+
if optname in takes_value:
|
|
369
|
+
cli_args.append(tok)
|
|
370
|
+
if takes_value[optname] and '=' not in tok:
|
|
371
|
+
i += 1
|
|
372
|
+
if i < n:
|
|
373
|
+
cli_args.append(args[i])
|
|
374
|
+
i += 1
|
|
375
|
+
continue
|
|
376
|
+
if not seen_prog:
|
|
377
|
+
cli_args.append(tok)
|
|
378
|
+
seen_prog = True
|
|
379
|
+
i += 1
|
|
380
|
+
continue
|
|
381
|
+
prog_args.append(tok)
|
|
382
|
+
i += 1
|
|
383
|
+
return cli_args, prog_args
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
def main(argv: Optional[List[str]] = None) -> int:
|
|
387
|
+
args = list(sys.argv[1:] if argv is None else argv)
|
|
388
|
+
|
|
389
|
+
# `--` 之后的参数原样传给 CIN 程序 (arg_count()/arg(i) 读取), 不参与
|
|
390
|
+
# CLI 自身解析; 与 Go `os.Args[1:]`、C `argv[1..]` 的习惯一致。
|
|
391
|
+
if '--' in args:
|
|
392
|
+
sep = args.index('--')
|
|
393
|
+
program_args = args[sep + 1:]
|
|
394
|
+
args = args[:sep]
|
|
395
|
+
else:
|
|
396
|
+
program_args = []
|
|
397
|
+
|
|
398
|
+
# 中文 Windows 默认 stdout/stderr 是 GBK, 输出非 GBK 字符 (emoji 等) 会直接
|
|
399
|
+
# UnicodeEncodeError; 且重定向产物字节与 Go 路径 (恒 UTF-8) 不一致。
|
|
400
|
+
# 统一切成 UTF-8, 无法编码的字符以 ? 替换而不是崩溃。
|
|
401
|
+
for _stream in (sys.stdout, sys.stderr):
|
|
402
|
+
if hasattr(_stream, 'reconfigure'):
|
|
403
|
+
with contextlib.suppress(ValueError, OSError):
|
|
404
|
+
_stream.reconfigure(encoding='utf-8', errors='replace')
|
|
405
|
+
|
|
406
|
+
if '--help' in args or '-h' in args:
|
|
407
|
+
sys.stdout.write(HELP_INTRO + "\n")
|
|
408
|
+
sys.stdout.write(build_parser().format_help())
|
|
409
|
+
return 0
|
|
410
|
+
|
|
411
|
+
console = Console()
|
|
412
|
+
parser = build_parser()
|
|
413
|
+
|
|
414
|
+
# 程序文件之后的裸参数透传给 CIN 程序 (问题反馈 #3): 已知 CLI 选项
|
|
415
|
+
# (含取值) 仍归 argparse, 其余 token 归 arg_count()/arg(i)。
|
|
416
|
+
cli_args, direct_args = _extract_program_args(args, parser)
|
|
417
|
+
if direct_args:
|
|
418
|
+
for tok in direct_args:
|
|
419
|
+
if tok.startswith('-') and tok not in ('-',) \
|
|
420
|
+
and not tok.lstrip('-').split('=')[0].isdigit():
|
|
421
|
+
sys.stderr.write(
|
|
422
|
+
f"note: {tok!r} 不是 CLI 选项, 已作为程序参数传递 "
|
|
423
|
+
f"(arg_count/arg); 如需强制传参请用 `-- {tok}`\n")
|
|
424
|
+
|
|
425
|
+
try:
|
|
426
|
+
ns = parser.parse_args(cli_args)
|
|
427
|
+
except SystemExit as e:
|
|
428
|
+
# argparse 错误 (未知选项/非法数值): 已打印 usage, 返回其退出码
|
|
429
|
+
return int(e.code) if e.code is not None else 2
|
|
430
|
+
|
|
431
|
+
# 版本设施 (workstream C): --build-info 不需要程序文件, 输出后立刻退出。
|
|
432
|
+
# 用 sys.stdout 直写: JSON 必须机器可读, 不能混入 rich 的 ANSI 装饰。
|
|
433
|
+
if ns.json_output and not ns.build_info:
|
|
434
|
+
sys.stderr.write("--json 只能与 --build-info 一起使用。\n")
|
|
435
|
+
return 2
|
|
436
|
+
if ns.build_info:
|
|
437
|
+
from .version import build_info_json, format_build_info
|
|
438
|
+
if ns.json_output:
|
|
439
|
+
sys.stdout.write(build_info_json() + "\n")
|
|
440
|
+
else:
|
|
441
|
+
sys.stdout.write(format_build_info() + "\n")
|
|
442
|
+
return 0
|
|
443
|
+
|
|
444
|
+
if ns.list_libs:
|
|
445
|
+
from .stdlib import format_library_report
|
|
446
|
+
sys.stdout.write(format_library_report() + "\n")
|
|
447
|
+
return 0
|
|
448
|
+
|
|
449
|
+
if ns.emit_archive:
|
|
450
|
+
if not ns.link:
|
|
451
|
+
console.print(Panel("--emit-archive 需要至少一个 --link 对象",
|
|
452
|
+
title='Error', border_style='red'))
|
|
453
|
+
return 1
|
|
454
|
+
from .object import ObjectError, read_input_object, write_archive
|
|
455
|
+
config = Config()
|
|
456
|
+
_apply_namespace(config, ns)
|
|
457
|
+
config.validate()
|
|
458
|
+
try:
|
|
459
|
+
objects = [read_input_object(p) for p in ns.link]
|
|
460
|
+
out = config.output_file or (
|
|
461
|
+
os.path.splitext(ns.link[0])[0] + '.colib')
|
|
462
|
+
written = write_archive(objects, out)
|
|
463
|
+
except (ObjectError, OSError) as e:
|
|
464
|
+
console.print(Panel(str(e), title='Archive Error',
|
|
465
|
+
border_style='red'))
|
|
466
|
+
return 1
|
|
467
|
+
console.print(Colors.colorize(f"Archive: {written}", Colors.GREEN))
|
|
468
|
+
return 0
|
|
469
|
+
|
|
470
|
+
if ns.link:
|
|
471
|
+
from . import aot
|
|
472
|
+
from .object import ObjectError, link_files
|
|
473
|
+
config = Config()
|
|
474
|
+
_apply_namespace(config, ns)
|
|
475
|
+
config.validate()
|
|
476
|
+
try:
|
|
477
|
+
linked = link_files(ns.link, gc_sections=ns.gc_sections)
|
|
478
|
+
except (ObjectError, OSError) as e:
|
|
479
|
+
console.print(Panel(str(e), title='Link Error', border_style='red'))
|
|
480
|
+
return 1
|
|
481
|
+
out = config.output_file
|
|
482
|
+
if not out:
|
|
483
|
+
target = ns.build_target or aot.host_target()
|
|
484
|
+
goos, _ = aot.parse_target(target)
|
|
485
|
+
out = (os.path.splitext(ns.link[0])[0]
|
|
486
|
+
+ aot.exe_suffix(goos))
|
|
487
|
+
try:
|
|
488
|
+
cache_key = None
|
|
489
|
+
if ns.build_cache:
|
|
490
|
+
cache_key = aot.link_cache_key(
|
|
491
|
+
ns.link, ns.build_target, ns.build_backend,
|
|
492
|
+
config.optimize, linked['mem_size'],
|
|
493
|
+
config.max_instructions, debug=ns.build_debug,
|
|
494
|
+
gc_sections=ns.gc_sections)
|
|
495
|
+
built = aot.build_from_ir(
|
|
496
|
+
linked['instructions'], linked['labels'],
|
|
497
|
+
linked['data_labels'], linked['segments'],
|
|
498
|
+
entry_pc=linked['entry_pc'],
|
|
499
|
+
mem_size=linked['mem_size'],
|
|
500
|
+
sp=linked['sp'], heap_base=linked['heap_base'],
|
|
501
|
+
out=out, target=ns.build_target,
|
|
502
|
+
backend=ns.build_backend,
|
|
503
|
+
max_instructions=config.max_instructions,
|
|
504
|
+
optimize=config.optimize,
|
|
505
|
+
program_name='linked',
|
|
506
|
+
keep_temp=ns.build_keep_temp,
|
|
507
|
+
debug=ns.build_debug,
|
|
508
|
+
use_cache=(ns.build_cache and not (ns.build_static
|
|
509
|
+
or ns.build_strip
|
|
510
|
+
or ns.build_keep_c)),
|
|
511
|
+
cache_key=cache_key,
|
|
512
|
+
c_static=ns.build_static,
|
|
513
|
+
c_strip=ns.build_strip,
|
|
514
|
+
c_keep_c=ns.build_keep_c,
|
|
515
|
+
logger=None)
|
|
516
|
+
except (aot.AotError, OSError) as e:
|
|
517
|
+
console.print(Panel(str(e), title='Link Error', border_style='red'))
|
|
518
|
+
return 1
|
|
519
|
+
if getattr(ns, 'build_verify', False):
|
|
520
|
+
from . import cbackend
|
|
521
|
+
try:
|
|
522
|
+
info = cbackend.inspect_binary(
|
|
523
|
+
built, ns.build_target or aot.host_target())
|
|
524
|
+
except ValueError as e:
|
|
525
|
+
console.print(Panel(str(e), title='Verify Error',
|
|
526
|
+
border_style='red'))
|
|
527
|
+
return 1
|
|
528
|
+
console.print(Colors.colorize(
|
|
529
|
+
'Verify OK: ' + ' '.join(f'{k}={v}' for k, v in info.items()),
|
|
530
|
+
Colors.GREEN))
|
|
531
|
+
console.print(Colors.colorize(f"Link 完成: {built}", Colors.GREEN))
|
|
532
|
+
return 0
|
|
533
|
+
|
|
534
|
+
if ns.emit_object:
|
|
535
|
+
if ns.program is None:
|
|
536
|
+
console.print(Panel("--emit-object 需要 CIN/ASM/PL 源文件",
|
|
537
|
+
title='Error', border_style='red'))
|
|
538
|
+
return 1
|
|
539
|
+
ext = os.path.splitext(ns.program)[1].lower()
|
|
540
|
+
if ext not in ('.cin', '.asm', '.pl'):
|
|
541
|
+
console.print(Panel("--emit-object 仅支持 .cin/.asm/.pl",
|
|
542
|
+
title='Error', border_style='red'))
|
|
543
|
+
return 1
|
|
544
|
+
from .object import ObjectError, compile_asm_object, compile_cin_object, write_object
|
|
545
|
+
try:
|
|
546
|
+
if ext == '.cin':
|
|
547
|
+
obj = compile_cin_object(ns.program)
|
|
548
|
+
else:
|
|
549
|
+
obj = compile_asm_object(ns.program)
|
|
550
|
+
out = ns.output or os.path.splitext(ns.program)[0] + '.co'
|
|
551
|
+
written = write_object(obj, out)
|
|
552
|
+
except (ObjectError, OSError) as e:
|
|
553
|
+
console.print(Panel(str(e), title='Object Error',
|
|
554
|
+
border_style='red'))
|
|
555
|
+
return 1
|
|
556
|
+
console.print(Colors.colorize(f"Object: {written}", Colors.GREEN))
|
|
557
|
+
return 0
|
|
558
|
+
|
|
559
|
+
if ns.program is None:
|
|
560
|
+
console.print(Panel("No program file specified.\n"
|
|
561
|
+
"Use --help for usage information.",
|
|
562
|
+
title="Error", border_style='red'))
|
|
563
|
+
return 1
|
|
564
|
+
|
|
565
|
+
config = Config()
|
|
566
|
+
_apply_namespace(config, ns)
|
|
567
|
+
# 直传参数与 `--` 后参数合并 (直传在前, 位置顺序与命令行一致)
|
|
568
|
+
config.program_args = direct_args + program_args
|
|
569
|
+
config.validate()
|
|
570
|
+
|
|
571
|
+
program_file = ns.program
|
|
572
|
+
crom_file = ns.crom
|
|
573
|
+
default_ext = '.sdgcc'
|
|
574
|
+
output_file = (config.output_file
|
|
575
|
+
or os.path.splitext(program_file)[0] + default_ext)
|
|
576
|
+
|
|
577
|
+
if ns.disasm:
|
|
578
|
+
from .disasm import disassemble_file
|
|
579
|
+
try:
|
|
580
|
+
lines = disassemble_file(program_file)
|
|
581
|
+
except Exception as e:
|
|
582
|
+
from .errors import CPUSimulatorError
|
|
583
|
+
title = ("Disasm Error" if isinstance(e, CPUSimulatorError)
|
|
584
|
+
else "Error")
|
|
585
|
+
console.print(Panel(str(e), title=title, border_style='red'))
|
|
586
|
+
return 1
|
|
587
|
+
sys.stdout.write("\n".join(lines))
|
|
588
|
+
return 0
|
|
589
|
+
|
|
590
|
+
if ns.native or ns.native_out:
|
|
591
|
+
return _run_native(ns, console, program_file, config)
|
|
592
|
+
|
|
593
|
+
if ns.build_exe is not None:
|
|
594
|
+
return _run_aot_build(ns, console, program_file, config)
|
|
595
|
+
|
|
596
|
+
# 运行前进度/状态只在真实终端且未静音 (log-level ERROR) 时显示,
|
|
597
|
+
# 管道/重定向与"保持示例输出干净"的场景不受影响。
|
|
598
|
+
tty = _stdout_is_tty() and config.log_level.upper() not in ('ERROR', 'CRITICAL')
|
|
599
|
+
if tty:
|
|
600
|
+
console.print(Colors.colorize(
|
|
601
|
+
f"Loading {os.path.basename(program_file)} ...", Colors.CYAN))
|
|
602
|
+
load_started = time.perf_counter()
|
|
603
|
+
try:
|
|
604
|
+
from .cpu import CPU
|
|
605
|
+
cpu = CPU(config, program_file, crom_file=crom_file)
|
|
606
|
+
except Exception as e:
|
|
607
|
+
from .errors import CPUSimulatorError
|
|
608
|
+
if isinstance(e, CPUSimulatorError):
|
|
609
|
+
console.print(Panel(str(e), title="Load Error", border_style='red'))
|
|
610
|
+
else:
|
|
611
|
+
console.print(Panel(str(e), title="Error", border_style='red'))
|
|
612
|
+
if config.debug_mode or config.log_level.upper() == 'DEBUG':
|
|
613
|
+
# 超详细: rich 彩色完整堆栈
|
|
614
|
+
console.print_exception()
|
|
615
|
+
return 1
|
|
616
|
+
|
|
617
|
+
if tty:
|
|
618
|
+
console.print(Colors.colorize(
|
|
619
|
+
f"Loaded {len(cpu.instructions)} instructions in "
|
|
620
|
+
f"{(time.perf_counter() - load_started) * 1000:.1f} ms",
|
|
621
|
+
Colors.GREEN))
|
|
622
|
+
|
|
623
|
+
try:
|
|
624
|
+
# 管道/重定向输入预读到 input_buffer: 让 input() 在原生与解释器路径下
|
|
625
|
+
# 都能读到 `"42" | codecin t.cin` 这样的标准输入 (交互 TTY 不预读)。
|
|
626
|
+
try:
|
|
627
|
+
if sys.stdin is not None and not sys.stdin.isatty():
|
|
628
|
+
cpu.input_buffer = sys.stdin.read() or ""
|
|
629
|
+
except (OSError, ValueError, AttributeError):
|
|
630
|
+
pass # pytest 等捕获环境禁止读 stdin, 保持为空
|
|
631
|
+
|
|
632
|
+
if config.compile_to_bin or config.compile_only:
|
|
633
|
+
from . import sdgcc as sdgcc_mod
|
|
634
|
+
sdgcc_mod.save_program(cpu, output_file, multi_file=False,
|
|
635
|
+
sources=[program_file],
|
|
636
|
+
compress=bool(config.sdgcc_compress),
|
|
637
|
+
meta={'build': {
|
|
638
|
+
'entry': os.path.basename(program_file),
|
|
639
|
+
'optimize': int(config.optimize),
|
|
640
|
+
'mem_size': len(cpu.memory),
|
|
641
|
+
'bin_version': 3,
|
|
642
|
+
}})
|
|
643
|
+
console.print(Colors.colorize(
|
|
644
|
+
f"Compiled to {output_file}", Colors.GREEN))
|
|
645
|
+
if config.compile_only:
|
|
646
|
+
return 0
|
|
647
|
+
|
|
648
|
+
if tty:
|
|
649
|
+
console.print(Colors.colorize("Running ...", Colors.CYAN))
|
|
650
|
+
sys.stdout.flush() # 状态行先落盘, 程序实时输出紧随其后
|
|
651
|
+
cpu.run()
|
|
652
|
+
except KeyboardInterrupt:
|
|
653
|
+
pass
|
|
654
|
+
except Exception as e:
|
|
655
|
+
from .errors import CPUSimulatorError
|
|
656
|
+
if isinstance(e, CPUSimulatorError):
|
|
657
|
+
console.print(Panel(str(e), title="Error", border_style='red'))
|
|
658
|
+
else:
|
|
659
|
+
console.print(Panel(str(e), title="Unexpected Error",
|
|
660
|
+
border_style='red'))
|
|
661
|
+
console.print_exception()
|
|
662
|
+
return 1
|
|
663
|
+
# CPU.run 内部会捕获执行期异常并记录日志, 这里据失败标志决定退出码
|
|
664
|
+
if getattr(cpu, 'execution_failed', False):
|
|
665
|
+
return 1
|
|
666
|
+
return 0
|
|
667
|
+
|
|
668
|
+
|
|
669
|
+
if __name__ == '__main__':
|
|
670
|
+
sys.exit(main())
|
|
Binary file
|