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/config.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""运行配置与命令行参数解析 (native-only)。"""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass, field
|
|
4
|
+
from typing import List, Optional
|
|
5
|
+
|
|
6
|
+
# 默认程序内存: 1 GiB (Go 引擎 make([]byte, memSize), OS 懒提交;
|
|
7
|
+
# Python 侧稀疏内存按 4 KiB 页按需分配)。只有真正写入的部分才占用
|
|
8
|
+
# 物理内存, 因此默认值可以放心放大。
|
|
9
|
+
DEFAULT_MEM_SIZE = 1 << 30
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@dataclass
|
|
13
|
+
class Config:
|
|
14
|
+
mem_size: int = DEFAULT_MEM_SIZE
|
|
15
|
+
auto_save_crom: bool = False
|
|
16
|
+
# 0 = 不限制指令数 (默认); 字段保留用于兼容旧调用方
|
|
17
|
+
max_instructions: int = 0
|
|
18
|
+
sandbox_mode: bool = False
|
|
19
|
+
# 调试模式: 强制 DEBUG 日志, 执行结束输出 CPU 状态与统计, 异常完整堆栈
|
|
20
|
+
debug_mode: bool = False
|
|
21
|
+
log_level: str = 'INFO'
|
|
22
|
+
log_file: Optional[str] = None
|
|
23
|
+
strict_mode: bool = False
|
|
24
|
+
output_file: Optional[str] = None
|
|
25
|
+
optimize: int = 0
|
|
26
|
+
compress_crom: bool = True
|
|
27
|
+
sdgcc_compress: bool = False
|
|
28
|
+
compile_to_bin: bool = False
|
|
29
|
+
compile_only: bool = False
|
|
30
|
+
# A2: 确定性随机种子 (None = 随机; 0 亦表示随机)
|
|
31
|
+
seed: Optional[int] = None
|
|
32
|
+
# A1: CIN 运行时断言/边界检查开关 (编译期注入)
|
|
33
|
+
bounds_check: bool = False
|
|
34
|
+
# 传给 CIN 程序的命令行参数 (cli 里 `--` 之后的参数; 供 arg_count()/arg(i))
|
|
35
|
+
program_args: List[str] = field(default_factory=list)
|
|
36
|
+
|
|
37
|
+
# 命令行解析请使用 codecin/cli.py build_parser() (argparse, 单一来源)。
|
|
38
|
+
# Config 仅承载运行配置, 由 cli._apply_namespace 填充。
|
|
39
|
+
|
|
40
|
+
def validate(self) -> None:
|
|
41
|
+
if self.mem_size < 256:
|
|
42
|
+
self.mem_size = 256
|
|
43
|
+
if self.mem_size > (1 << 40):
|
|
44
|
+
self.mem_size = 1 << 40
|
|
45
|
+
if self.max_instructions < 0:
|
|
46
|
+
self.max_instructions = 0
|
|
47
|
+
if self.optimize < 0:
|
|
48
|
+
self.optimize = 0
|
|
49
|
+
if self.optimize > 3:
|
|
50
|
+
self.optimize = 3
|
codecin/console.py
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
import re
|
|
2
|
+
from typing import Any, Optional
|
|
3
|
+
|
|
4
|
+
from rich import box as _box_mod
|
|
5
|
+
from rich.console import Console as RichConsole
|
|
6
|
+
from rich.panel import Panel as RichPanel
|
|
7
|
+
from rich.table import Table as RichTable
|
|
8
|
+
from rich.text import Text
|
|
9
|
+
|
|
10
|
+
_ANSI_RE = re.compile(r'\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])')
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _to_renderable(obj: Any) -> Any:
|
|
14
|
+
"""将任意对象转换为 rich 可渲染对象。
|
|
15
|
+
|
|
16
|
+
str 含 ANSI 时转 Text (rich 渲染时按终端能力自动上/去色)。
|
|
17
|
+
"""
|
|
18
|
+
if isinstance(obj, str):
|
|
19
|
+
if '\x1b' in obj:
|
|
20
|
+
return Text.from_ansi(obj)
|
|
21
|
+
return obj
|
|
22
|
+
if hasattr(obj, '__rich_console__'):
|
|
23
|
+
return obj
|
|
24
|
+
return str(obj)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class Colors:
|
|
28
|
+
"""ANSI 颜色码 (历史 API, 输出层自动转换为 rich Text)。"""
|
|
29
|
+
|
|
30
|
+
RESET = '\033[0m'
|
|
31
|
+
BOLD = '\033[1m'
|
|
32
|
+
DIM = '\033[2m'
|
|
33
|
+
|
|
34
|
+
BLACK = '\033[30m'
|
|
35
|
+
RED = '\033[31m'
|
|
36
|
+
GREEN = '\033[32m'
|
|
37
|
+
YELLOW = '\033[33m'
|
|
38
|
+
BLUE = '\033[34m'
|
|
39
|
+
MAGENTA = '\033[35m'
|
|
40
|
+
CYAN = '\033[36m'
|
|
41
|
+
WHITE = '\033[37m'
|
|
42
|
+
|
|
43
|
+
BG_BLACK = '\033[40m'
|
|
44
|
+
BG_RED = '\033[41m'
|
|
45
|
+
BG_GREEN = '\033[42m'
|
|
46
|
+
BG_YELLOW = '\033[43m'
|
|
47
|
+
BG_BLUE = '\033[44m'
|
|
48
|
+
BG_MAGENTA = '\033[45m'
|
|
49
|
+
BG_CYAN = '\033[46m'
|
|
50
|
+
BG_WHITE = '\033[47m'
|
|
51
|
+
|
|
52
|
+
@staticmethod
|
|
53
|
+
def strip(text: str) -> str:
|
|
54
|
+
return _ANSI_RE.sub('', text)
|
|
55
|
+
|
|
56
|
+
@staticmethod
|
|
57
|
+
def colorize(text: str, color: str, bold: bool = False) -> str:
|
|
58
|
+
return f"{Colors.BOLD if bold else ''}{color}{text}{Colors.RESET}"
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class Console:
|
|
62
|
+
"""rich 控制台封装。"""
|
|
63
|
+
|
|
64
|
+
def __init__(self, force_color: Optional[bool] = None):
|
|
65
|
+
kwargs: dict = {}
|
|
66
|
+
if force_color is not None:
|
|
67
|
+
kwargs['force_terminal'] = force_color
|
|
68
|
+
kwargs['color_system'] = 'truecolor' if force_color else None
|
|
69
|
+
self._rc = RichConsole(
|
|
70
|
+
highlight=False, emoji=False, markup=False,
|
|
71
|
+
soft_wrap=False, **kwargs)
|
|
72
|
+
|
|
73
|
+
@property
|
|
74
|
+
def rich(self) -> RichConsole:
|
|
75
|
+
"""底层 rich Console (供 logger/异常渲染复用)。"""
|
|
76
|
+
return self._rc
|
|
77
|
+
|
|
78
|
+
@property
|
|
79
|
+
def color_support(self) -> bool:
|
|
80
|
+
return self._rc.color_system is not None
|
|
81
|
+
|
|
82
|
+
def width(self) -> int:
|
|
83
|
+
return self._rc.width
|
|
84
|
+
|
|
85
|
+
def print(self, *args, **kwargs) -> None:
|
|
86
|
+
objs = [_to_renderable(a) for a in args]
|
|
87
|
+
self._rc.print(*objs, sep=kwargs.pop('sep', ' '),
|
|
88
|
+
markup=False, highlight=False, **kwargs)
|
|
89
|
+
|
|
90
|
+
def print_exception(self, **kwargs) -> None:
|
|
91
|
+
"""rich 彩色堆栈回溯。"""
|
|
92
|
+
self._rc.print_exception(word_wrap=True, **kwargs)
|
|
93
|
+
|
|
94
|
+
def clear(self) -> None:
|
|
95
|
+
self._rc.clear()
|
|
96
|
+
|
|
97
|
+
def rule(self, title: str = "", style: str = "cyan") -> None:
|
|
98
|
+
self._rc.rule(Text.from_ansi(title) if '\x1b' in title else title,
|
|
99
|
+
style=style, align='center')
|
|
100
|
+
|
|
101
|
+
def clear_line(self) -> None:
|
|
102
|
+
self._rc.print('\r' + ' ' * 80 + '\r', end='')
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
class Panel:
|
|
106
|
+
"""rich Panel 适配器, 兼容 str(Panel(...)) 用法。"""
|
|
107
|
+
|
|
108
|
+
def __init__(self, content, title: str = "", border_style: str = "",
|
|
109
|
+
box=None):
|
|
110
|
+
self._content = content
|
|
111
|
+
self._title = title
|
|
112
|
+
self._border_style = border_style or 'cyan'
|
|
113
|
+
self._box = box or _box_mod.ROUNDED
|
|
114
|
+
|
|
115
|
+
def build(self) -> RichPanel:
|
|
116
|
+
content = _to_renderable(self._content)
|
|
117
|
+
title = Text.from_ansi(self._title) if '\x1b' in self._title \
|
|
118
|
+
else self._title
|
|
119
|
+
return RichPanel(content, title=title, border_style=self._border_style,
|
|
120
|
+
box=self._box, expand=False)
|
|
121
|
+
|
|
122
|
+
def __rich_console__(self, console, options):
|
|
123
|
+
return self.build().__rich_console__(console, options)
|
|
124
|
+
|
|
125
|
+
def __str__(self) -> str:
|
|
126
|
+
import io
|
|
127
|
+
buf = io.StringIO()
|
|
128
|
+
c = RichConsole(file=buf, width=80, highlight=False, emoji=False,
|
|
129
|
+
markup=False)
|
|
130
|
+
c.print(self.build())
|
|
131
|
+
return buf.getvalue().rstrip('\n')
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
class Table:
|
|
135
|
+
"""rich Table 适配器, 兼容旧 add_column/add_row API。
|
|
136
|
+
|
|
137
|
+
print(table) 时按 rich 全彩渲染; str(table) 输出纯文本。
|
|
138
|
+
"""
|
|
139
|
+
|
|
140
|
+
def __init__(self, title: str = "", box=None, border_style: str = "",
|
|
141
|
+
show_lines: bool = False):
|
|
142
|
+
self._title = title
|
|
143
|
+
self._box = box or _box_mod.ROUNDED
|
|
144
|
+
self._border_style = border_style or 'cyan'
|
|
145
|
+
self._show_lines = show_lines
|
|
146
|
+
self._cols: list = []
|
|
147
|
+
self._rows: list = []
|
|
148
|
+
|
|
149
|
+
def add_column(self, name, style: str = "", width: int = 0, **kw) -> None:
|
|
150
|
+
self._cols.append((str(name), style or None, width or None, kw))
|
|
151
|
+
|
|
152
|
+
def add_row(self, *args) -> None:
|
|
153
|
+
self._rows.append([_to_renderable(a) if isinstance(a, str) else a
|
|
154
|
+
for a in args])
|
|
155
|
+
|
|
156
|
+
@property
|
|
157
|
+
def rows(self) -> list:
|
|
158
|
+
return self._rows
|
|
159
|
+
|
|
160
|
+
@property
|
|
161
|
+
def headers(self) -> list:
|
|
162
|
+
return [name for name, _, _, _ in self._cols]
|
|
163
|
+
|
|
164
|
+
def build(self) -> RichTable:
|
|
165
|
+
t = RichTable(title=self._title or None, box=self._box,
|
|
166
|
+
border_style=self._border_style,
|
|
167
|
+
show_lines=self._show_lines, highlight=False)
|
|
168
|
+
for name, style, width, kw in self._cols:
|
|
169
|
+
t.add_column(name, style=style, width=width, **kw)
|
|
170
|
+
for row in self._rows:
|
|
171
|
+
t.add_row(*row)
|
|
172
|
+
return t
|
|
173
|
+
|
|
174
|
+
def __rich_console__(self, console, options):
|
|
175
|
+
return self.build().__rich_console__(console, options)
|
|
176
|
+
|
|
177
|
+
def __str__(self) -> str:
|
|
178
|
+
import io
|
|
179
|
+
buf = io.StringIO()
|
|
180
|
+
c = RichConsole(file=buf, width=80, highlight=False, emoji=False,
|
|
181
|
+
markup=False)
|
|
182
|
+
c.print(self.build())
|
|
183
|
+
return buf.getvalue().rstrip('\n')
|
codecin/cpu.py
ADDED
|
@@ -0,0 +1,312 @@
|
|
|
1
|
+
"""CPU: native-only 执行编排。
|
|
2
|
+
|
|
3
|
+
v5.9.0 起纯 Python 解释器与 JIT 已删除, 全部程序由 Go 原生引擎
|
|
4
|
+
(codecin-native 动态库 / AOT 静态可执行文件) 执行:
|
|
5
|
+
- CPU 负责编译/装载 (.cin/.asm/.pl/.bin/.crom) 与执行编排;
|
|
6
|
+
- 内存为稀疏分页 FastMemory (逻辑 1 GiB, 按需分配 4 KiB 页);
|
|
7
|
+
- 执行结果 (寄存器/向量/NZCV/脏内存段/输出) 由原生库一次性回传。
|
|
8
|
+
|
|
9
|
+
动态库缺失时抛 CPUSimulatorError, 提示重建原生库 (不再有解释器回退)。
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
import contextlib
|
|
13
|
+
import os
|
|
14
|
+
import sys
|
|
15
|
+
from typing import Any, Dict, List, Optional, Tuple
|
|
16
|
+
|
|
17
|
+
from .assembler import Assembler
|
|
18
|
+
from .console import Colors, Console, Panel
|
|
19
|
+
from .errors import CPUSimulatorError, ExecutionError
|
|
20
|
+
from .isa import Constants
|
|
21
|
+
from .logger import Logger
|
|
22
|
+
from .memory import FastMemory
|
|
23
|
+
from .registers import RegisterFile, VectorRegisterFile
|
|
24
|
+
from .stats import Statistics
|
|
25
|
+
|
|
26
|
+
Operand = Tuple[Any, ...]
|
|
27
|
+
Instruction = Tuple[str, List[Operand]]
|
|
28
|
+
|
|
29
|
+
MASK64 = 0xFFFFFFFFFFFFFFFF
|
|
30
|
+
|
|
31
|
+
NATIVE_HINT = (
|
|
32
|
+
"原生引擎不可用: 未找到 codecin-native 动态库。\n"
|
|
33
|
+
"请先构建原生库: 运行 codecin/native/build.ps1 (Windows) "
|
|
34
|
+
"或 codecin/native/build.sh (Linux/Termux/macOS), 然后重试。")
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _stdout_is_tty() -> bool:
|
|
38
|
+
"""stdout 是否为真实终端 (决定是否请求实时输出)。"""
|
|
39
|
+
try:
|
|
40
|
+
return bool(sys.stdout is not None and sys.stdout.isatty())
|
|
41
|
+
except (OSError, ValueError, AttributeError):
|
|
42
|
+
return False
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class CPU:
|
|
46
|
+
def __init__(self, config, filename: Optional[str] = None,
|
|
47
|
+
crom_file: Optional[str] = None,
|
|
48
|
+
from_bin: bool = False,
|
|
49
|
+
console: Optional[Console] = None):
|
|
50
|
+
|
|
51
|
+
self.console = console or Console()
|
|
52
|
+
self.config = config
|
|
53
|
+
self.filename = filename
|
|
54
|
+
|
|
55
|
+
# 调试模式强制 DEBUG 级别 (超详细日志); 这里兜底程序化构造的 Config
|
|
56
|
+
if config.debug_mode and config.log_level.upper() != 'DEBUG':
|
|
57
|
+
config.log_level = 'DEBUG'
|
|
58
|
+
self.logger = Logger(self.console, config.log_level)
|
|
59
|
+
if config.log_file:
|
|
60
|
+
self.logger.set_log_file(config.log_file)
|
|
61
|
+
# 内存访问日志 (DEBUG 级别生效)
|
|
62
|
+
self.memory = FastMemory(config.mem_size)
|
|
63
|
+
self.memory.attach_logger(self.logger)
|
|
64
|
+
|
|
65
|
+
self.regs = RegisterFile(self.console)
|
|
66
|
+
self.vec_regs = VectorRegisterFile()
|
|
67
|
+
|
|
68
|
+
self.pstate: Dict[str, bool] = {'N': False, 'Z': False,
|
|
69
|
+
'C': False, 'V': False}
|
|
70
|
+
self.pc = 0
|
|
71
|
+
self.sp = (config.mem_size - Constants.STACK_SLOT) & ~0x7
|
|
72
|
+
self.heap_base = config.mem_size // 2
|
|
73
|
+
self.heap_ptr = self.heap_base
|
|
74
|
+
|
|
75
|
+
self.logger.dump("CPU 初始化", {
|
|
76
|
+
'memory': f"0x{config.mem_size:x} bytes (sparse)",
|
|
77
|
+
'sp_init': f"0x{self.sp:x}",
|
|
78
|
+
'heap_base': f"0x{self.heap_ptr:x}",
|
|
79
|
+
'sandbox': config.sandbox_mode,
|
|
80
|
+
'log_level': config.log_level,
|
|
81
|
+
})
|
|
82
|
+
|
|
83
|
+
self.instructions: List[Instruction] = []
|
|
84
|
+
self.labels: Dict[str, int] = {}
|
|
85
|
+
self.data_labels: Dict[str, int] = {}
|
|
86
|
+
self.entry_pc = 0
|
|
87
|
+
|
|
88
|
+
self.stats = Statistics()
|
|
89
|
+
self.running = False
|
|
90
|
+
|
|
91
|
+
self.input_buffer: str = ""
|
|
92
|
+
self._input_pos = 0
|
|
93
|
+
self.output_buffer: List[str] = []
|
|
94
|
+
self._capture_output = False
|
|
95
|
+
self.native_engine = None
|
|
96
|
+
self.native_used = False
|
|
97
|
+
# 执行期是否发生过错误 (供 CLI 决定退出码)
|
|
98
|
+
self.execution_failed = False
|
|
99
|
+
|
|
100
|
+
if filename:
|
|
101
|
+
self.load_program(filename, crom_file=crom_file, from_bin=from_bin)
|
|
102
|
+
|
|
103
|
+
# ==================== 程序装载 ====================
|
|
104
|
+
|
|
105
|
+
def load_program(self, filename: str, crom_file: Optional[str] = None,
|
|
106
|
+
from_bin: bool = False) -> None:
|
|
107
|
+
if not os.path.exists(filename):
|
|
108
|
+
raise CPUSimulatorError(f"File '{filename}' not found")
|
|
109
|
+
|
|
110
|
+
ext = os.path.splitext(filename)[1].lower()
|
|
111
|
+
|
|
112
|
+
if ext == '.cin':
|
|
113
|
+
from .cin import CINCompiler
|
|
114
|
+
compiler = CINCompiler(self.console, logger=self.logger)
|
|
115
|
+
result = compiler.compile(filename,
|
|
116
|
+
bounds_check=self.config.bounds_check)
|
|
117
|
+
self.instructions = result.instructions
|
|
118
|
+
self.labels = result.labels
|
|
119
|
+
self.data_labels = result.data_labels
|
|
120
|
+
for addr, data in result.data_writes:
|
|
121
|
+
self.memory.write_block(addr, data)
|
|
122
|
+
# pc 0 为 bootstrap (CALL main; HALT), main 标签为函数体入口
|
|
123
|
+
self.entry_pc = 0
|
|
124
|
+
if self.config.optimize > 0:
|
|
125
|
+
from .optimizer import optimize
|
|
126
|
+
self.instructions, self.labels, self.entry_pc = optimize(
|
|
127
|
+
self.instructions, self.labels, self.config.optimize,
|
|
128
|
+
self.entry_pc)
|
|
129
|
+
self.pc = self.entry_pc
|
|
130
|
+
self.logger.info(f"CIN compiled: {len(self.instructions)} instructions")
|
|
131
|
+
return
|
|
132
|
+
|
|
133
|
+
if from_bin or ext in ('.bin', '.sdgcc'):
|
|
134
|
+
from . import crom as crom_mod
|
|
135
|
+
crom_mod.load_bin(self, filename)
|
|
136
|
+
self.logger.info(f"Binary loaded: {len(self.instructions)} instructions")
|
|
137
|
+
return
|
|
138
|
+
|
|
139
|
+
# .pl / .asm
|
|
140
|
+
if crom_file is None:
|
|
141
|
+
base = os.path.splitext(filename)[0]
|
|
142
|
+
candidate = base + '.crom'
|
|
143
|
+
if os.path.exists(candidate):
|
|
144
|
+
crom_file = candidate
|
|
145
|
+
if crom_file and os.path.exists(crom_file):
|
|
146
|
+
from . import crom as crom_mod
|
|
147
|
+
crom_mod.load_crom(self.memory, crom_file, self.logger)
|
|
148
|
+
|
|
149
|
+
asm = Assembler(self.memory, self.console, strict=self.config.strict_mode,
|
|
150
|
+
logger=self.logger)
|
|
151
|
+
self.instructions, self.labels, self.data_labels = asm.assemble_file(filename)
|
|
152
|
+
self.entry_pc = self.labels.get('main', 0)
|
|
153
|
+
if self.config.optimize > 0:
|
|
154
|
+
from .optimizer import optimize
|
|
155
|
+
self.instructions, self.labels, self.entry_pc = optimize(
|
|
156
|
+
self.instructions, self.labels, self.config.optimize,
|
|
157
|
+
self.entry_pc)
|
|
158
|
+
self.pc = self.entry_pc
|
|
159
|
+
self.logger.info(f"Assembly successful: {len(self.instructions)} instructions")
|
|
160
|
+
if self.logger.is_debug:
|
|
161
|
+
self.logger.dump("汇编标签表", {name: f"0x{pc:x}"
|
|
162
|
+
for name, pc in
|
|
163
|
+
sorted(self.labels.items())})
|
|
164
|
+
|
|
165
|
+
# ==================== I/O ====================
|
|
166
|
+
|
|
167
|
+
def _emit_text(self, text: str) -> None:
|
|
168
|
+
if self._capture_output:
|
|
169
|
+
self.output_buffer.append(text)
|
|
170
|
+
else:
|
|
171
|
+
sys.stdout.write(text)
|
|
172
|
+
sys.stdout.flush()
|
|
173
|
+
|
|
174
|
+
# ==================== 执行 ====================
|
|
175
|
+
|
|
176
|
+
def _try_native_run(self) -> bool:
|
|
177
|
+
"""使用 Go 原生库执行整个程序。
|
|
178
|
+
|
|
179
|
+
解释器与 JIT 已删除: 这里是唯一执行路径。动态库缺失时抛
|
|
180
|
+
CPUSimulatorError (带重建提示), 不再静默回退。
|
|
181
|
+
"""
|
|
182
|
+
try:
|
|
183
|
+
from . import native
|
|
184
|
+
except Exception as e: # pragma: no cover - 平台相关加载失败
|
|
185
|
+
raise CPUSimulatorError(f"{NATIVE_HINT}\n(加载失败: {e})") from e
|
|
186
|
+
engine = native.get_engine(self.logger)
|
|
187
|
+
if engine is None:
|
|
188
|
+
raise CPUSimulatorError(NATIVE_HINT)
|
|
189
|
+
|
|
190
|
+
from .native import encode_program
|
|
191
|
+
all_labels = dict(self.labels)
|
|
192
|
+
all_labels.update(self.data_labels)
|
|
193
|
+
bytecode = encode_program(self.instructions, self.entry_pc, all_labels)
|
|
194
|
+
segments = self.memory.snapshot_segments()
|
|
195
|
+
import time as _time
|
|
196
|
+
# 真实终端 + 非捕获模式: 请求原生引擎边执行边输出 (输出缓存仍会回传)。
|
|
197
|
+
stream = (not self._capture_output) and _stdout_is_tty()
|
|
198
|
+
if stream:
|
|
199
|
+
with contextlib.suppress(OSError, ValueError):
|
|
200
|
+
sys.stdout.flush() # 先落盘 Python 侧日志, 保证输出顺序
|
|
201
|
+
t0 = _time.perf_counter()
|
|
202
|
+
result = engine.run_v2(
|
|
203
|
+
bytecode=bytecode,
|
|
204
|
+
segments=segments,
|
|
205
|
+
entry=self.entry_pc,
|
|
206
|
+
sp=self.sp,
|
|
207
|
+
heap_base=self.heap_ptr,
|
|
208
|
+
mem_size=len(self.memory),
|
|
209
|
+
input_data=self.input_buffer.encode('utf-8'),
|
|
210
|
+
max_steps=self.config.max_instructions,
|
|
211
|
+
args=list(self.config.program_args),
|
|
212
|
+
seed=self.config.seed,
|
|
213
|
+
sandbox=self.config.sandbox_mode,
|
|
214
|
+
stream_output=stream,
|
|
215
|
+
)
|
|
216
|
+
elapsed = _time.perf_counter() - t0
|
|
217
|
+
if result is None:
|
|
218
|
+
raise CPUSimulatorError(
|
|
219
|
+
"原生引擎返回空结果 (库版本不匹配? 请重建原生库)")
|
|
220
|
+
|
|
221
|
+
self.native_used = True
|
|
222
|
+
self.logger.debug(
|
|
223
|
+
f"Native result: status={result.get('status')} "
|
|
224
|
+
f"steps={result.get('steps')} pc={result.get('pc')} "
|
|
225
|
+
f"elapsed={elapsed * 1000:.2f}ms error={result.get('error')}")
|
|
226
|
+
|
|
227
|
+
self._apply_native_state(result)
|
|
228
|
+
if result.get('output'):
|
|
229
|
+
if result.get('streamed'):
|
|
230
|
+
# 终端已实时显示; 这里只把完整输出放进缓存供调用方读取
|
|
231
|
+
self.output_buffer.append(result['output'])
|
|
232
|
+
else:
|
|
233
|
+
self._emit_text(result['output'])
|
|
234
|
+
if result.get('error'):
|
|
235
|
+
raise ExecutionError(result['error'])
|
|
236
|
+
return False
|
|
237
|
+
|
|
238
|
+
def _apply_native_state(self, result: dict) -> None:
|
|
239
|
+
"""把原生执行结果同步回 Python 侧对象 (寄存器/内存/统计)。"""
|
|
240
|
+
if 'regs' in result:
|
|
241
|
+
self.regs.set_all(list(result['regs'])[:32])
|
|
242
|
+
if 'vec_regs' in result:
|
|
243
|
+
self.vec_regs.set_all(result['vec_regs'])
|
|
244
|
+
if 'flags' in result:
|
|
245
|
+
self.pstate.update(result['flags'])
|
|
246
|
+
if 'sp' in result:
|
|
247
|
+
self.sp = result['sp'] & MASK64
|
|
248
|
+
if 'pc' in result:
|
|
249
|
+
self.pc = result['pc']
|
|
250
|
+
if 'heap_ptr' in result:
|
|
251
|
+
self.heap_ptr = result['heap_ptr'] & MASK64
|
|
252
|
+
if 'segments' in result:
|
|
253
|
+
# 脏段写回稀疏内存 (只触碰被写过的页)
|
|
254
|
+
for addr, data in result['segments']:
|
|
255
|
+
self.memory.write_block(addr, data)
|
|
256
|
+
if 'steps' in result:
|
|
257
|
+
# 原生 VM 整程序执行完毕: 统计一次性批量写入
|
|
258
|
+
steps = int(result.get('steps') or 0)
|
|
259
|
+
limit = self.config.max_instructions
|
|
260
|
+
counted = steps if limit <= 0 else min(steps, limit)
|
|
261
|
+
self.stats.instruction_count = steps
|
|
262
|
+
self.stats.opcode_count.clear()
|
|
263
|
+
self.stats.hot_instructions['?'] += counted
|
|
264
|
+
self.stats.inst_profiler.cycles['?'] += counted
|
|
265
|
+
self.stats.performance_counters.counters['instructions'] += counted
|
|
266
|
+
|
|
267
|
+
def run(self) -> None:
|
|
268
|
+
self.running = True
|
|
269
|
+
self.stats.start()
|
|
270
|
+
self.logger.info("Starting program execution (Go native engine)")
|
|
271
|
+
try:
|
|
272
|
+
self._try_native_run()
|
|
273
|
+
self.logger.info("HALT (native)")
|
|
274
|
+
except KeyboardInterrupt:
|
|
275
|
+
self.logger.info("User interrupt")
|
|
276
|
+
self.console.print(f"\n{Colors.colorize('User interrupt', Colors.YELLOW)}")
|
|
277
|
+
except ExecutionError as e:
|
|
278
|
+
self.execution_failed = True
|
|
279
|
+
self.logger.error(f"Execution error: {e}")
|
|
280
|
+
self.console.print(Panel(
|
|
281
|
+
f"{e}", title="Execution Error", border_style='red'))
|
|
282
|
+
except Exception as e:
|
|
283
|
+
self.execution_failed = True
|
|
284
|
+
self.logger.exception(f"Execution error: {e}")
|
|
285
|
+
title = "Error" if isinstance(e, CPUSimulatorError) else "Execution Error"
|
|
286
|
+
self.console.print(Panel(f"{e}", title=title, border_style='red'))
|
|
287
|
+
finally:
|
|
288
|
+
self.running = False
|
|
289
|
+
self.stats.stop()
|
|
290
|
+
self.logger.info("Program execution finished")
|
|
291
|
+
|
|
292
|
+
# 与旧版 --debug 一致: 收尾输出寄存器现场与执行统计
|
|
293
|
+
if self.config.debug_mode:
|
|
294
|
+
self.display_state("Execution Complete")
|
|
295
|
+
self.stats.display_summary(self.console,
|
|
296
|
+
native_used=self.native_used)
|
|
297
|
+
|
|
298
|
+
if self.config.auto_save_crom and self.filename:
|
|
299
|
+
from . import crom as crom_mod
|
|
300
|
+
crom_file = os.path.splitext(self.filename)[0] + '.crom'
|
|
301
|
+
crom_mod.save_crom(self.memory, crom_file,
|
|
302
|
+
compress=self.config.compress_crom,
|
|
303
|
+
logger=self.logger)
|
|
304
|
+
|
|
305
|
+
# ==================== 状态显示 ====================
|
|
306
|
+
|
|
307
|
+
def display_state(self, title: str = "CPU State",
|
|
308
|
+
opcode: Optional[str] = None,
|
|
309
|
+
args: Optional[List[Operand]] = None) -> None:
|
|
310
|
+
extra = {'PC': self.pc, 'SP': self.sp, 'Heap': self.heap_ptr}
|
|
311
|
+
self.regs.display_registers(title, extra_info=extra, console=self.console)
|
|
312
|
+
self.vec_regs.display_vector_registers(console=self.console)
|