codecin 7.22.10__py3-none-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (202) hide show
  1. codecin/__init__.py +27 -0
  2. codecin/aot.py +1057 -0
  3. codecin/assembler.py +619 -0
  4. codecin/cbackend.py +3024 -0
  5. codecin/cin.py +4265 -0
  6. codecin/cli.py +670 -0
  7. codecin/codecin_native.dll +0 -0
  8. codecin/config.py +50 -0
  9. codecin/console.py +183 -0
  10. codecin/cpu.py +312 -0
  11. codecin/crom.py +449 -0
  12. codecin/cvm.py +708 -0
  13. codecin/disasm.py +149 -0
  14. codecin/environment.py +176 -0
  15. codecin/errors.py +54 -0
  16. codecin/isa.py +560 -0
  17. codecin/lib/array/pic.toml +10 -0
  18. codecin/lib/array/src/array.cin +103 -0
  19. codecin/lib/bigint/pic.toml +10 -0
  20. codecin/lib/bigint/src/bigint.cin +589 -0
  21. codecin/lib/bits/pic.toml +10 -0
  22. codecin/lib/bits/src/bits.cin +143 -0
  23. codecin/lib/bitset/pic.toml +10 -0
  24. codecin/lib/bitset/src/bitset.cin +374 -0
  25. codecin/lib/codec/pic.toml +10 -0
  26. codecin/lib/codec/src/codec.cin +563 -0
  27. codecin/lib/combin/pic.toml +10 -0
  28. codecin/lib/combin/src/combin.cin +414 -0
  29. codecin/lib/conv/pic.toml +10 -0
  30. codecin/lib/conv/src/conv.cin +151 -0
  31. codecin/lib/cppstd/pic.toml +10 -0
  32. codecin/lib/cppstd/src/cppstd.cin +418 -0
  33. codecin/lib/cstd/pic.toml +10 -0
  34. codecin/lib/cstd/src/cstd.cin +424 -0
  35. codecin/lib/csv/pic.toml +10 -0
  36. codecin/lib/csv/src/csv.cin +405 -0
  37. codecin/lib/dp/pic.toml +10 -0
  38. codecin/lib/dp/src/dp.cin +325 -0
  39. codecin/lib/ffi/pic.toml +10 -0
  40. codecin/lib/ffi/src/ffi.cin +163 -0
  41. codecin/lib/fmt/pic.toml +10 -0
  42. codecin/lib/fmt/src/fmt.cin +325 -0
  43. codecin/lib/frac/pic.toml +10 -0
  44. codecin/lib/frac/src/frac.cin +252 -0
  45. codecin/lib/gostd/pic.toml +10 -0
  46. codecin/lib/gostd/src/gostd.cin +415 -0
  47. codecin/lib/graph/pic.toml +10 -0
  48. codecin/lib/graph/src/graph.cin +367 -0
  49. codecin/lib/gui/pic.toml +10 -0
  50. codecin/lib/gui/src/gui.cin +218 -0
  51. codecin/lib/hash/pic.toml +10 -0
  52. codecin/lib/hash/src/hash.cin +67 -0
  53. codecin/lib/heap/pic.toml +10 -0
  54. codecin/lib/heap/src/heap.cin +199 -0
  55. codecin/lib/io/pic.toml +10 -0
  56. codecin/lib/io/src/io.cin +141 -0
  57. codecin/lib/json/pic.toml +10 -0
  58. codecin/lib/json/src/json.cin +84 -0
  59. codecin/lib/key/pic.toml +10 -0
  60. codecin/lib/key/src/key.cin +78 -0
  61. codecin/lib/math/pic.toml +10 -0
  62. codecin/lib/math/src/math.cin +50 -0
  63. codecin/lib/matrix/pic.toml +10 -0
  64. codecin/lib/matrix/src/matrix.cin +155 -0
  65. codecin/lib/net/pic.toml +10 -0
  66. codecin/lib/net/src/net.cin +171 -0
  67. codecin/lib/path/pic.toml +10 -0
  68. codecin/lib/path/src/path.cin +372 -0
  69. codecin/lib/queue/pic.toml +10 -0
  70. codecin/lib/queue/src/queue.cin +112 -0
  71. codecin/lib/rand/pic.toml +10 -0
  72. codecin/lib/rand/src/rand.cin +46 -0
  73. codecin/lib/set/pic.toml +10 -0
  74. codecin/lib/set/src/set.cin +269 -0
  75. codecin/lib/sort/pic.toml +10 -0
  76. codecin/lib/sort/src/sort.cin +93 -0
  77. codecin/lib/stat/pic.toml +10 -0
  78. codecin/lib/stat/src/stat.cin +138 -0
  79. codecin/lib/str/pic.toml +10 -0
  80. codecin/lib/str/src/str.cin +54 -0
  81. codecin/lib/termux/pic.toml +10 -0
  82. codecin/lib/termux/src/termux.cin +118 -0
  83. codecin/lib/test/pic.toml +10 -0
  84. codecin/lib/test/src/test.cin +74 -0
  85. codecin/lib/text/pic.toml +10 -0
  86. codecin/lib/text/src/text.cin +323 -0
  87. codecin/lib/time/pic.toml +10 -0
  88. codecin/lib/time/src/time.cin +54 -0
  89. codecin/lib/token/pic.toml +10 -0
  90. codecin/lib/token/src/token.cin +183 -0
  91. codecin/lib/tree/pic.toml +10 -0
  92. codecin/lib/tree/src/tree.cin +256 -0
  93. codecin/lib/unionfind/pic.toml +10 -0
  94. codecin/lib/unionfind/src/unionfind.cin +115 -0
  95. codecin/lib/validate/pic.toml +10 -0
  96. codecin/lib/validate/src/validate.cin +148 -0
  97. codecin/lib/vec/pic.toml +10 -0
  98. codecin/lib/vec/src/vec.cin +88 -0
  99. codecin/logger.py +145 -0
  100. codecin/memory.py +306 -0
  101. codecin/mkn.py +916 -0
  102. codecin/native/aot/aot.go +114 -0
  103. codecin/native/aot/stub_main.go.txt +23 -0
  104. codecin/native/build.ps1 +33 -0
  105. codecin/native/build.sh +48 -0
  106. codecin/native/cmd/cincc/main.go +66 -0
  107. codecin/native/compiler/codegen.go +2238 -0
  108. codecin/native/compiler/compile_test.go +1069 -0
  109. codecin/native/compiler/parser.go +1331 -0
  110. codecin/native/compiler/syscalls.go +166 -0
  111. codecin/native/compiler/tokenizer.go +394 -0
  112. codecin/native/compiler/types.go +217 -0
  113. codecin/native/engine/args.go +37 -0
  114. codecin/native/engine/audio.go +402 -0
  115. codecin/native/engine/audio_other.go +105 -0
  116. codecin/native/engine/audio_test.go +279 -0
  117. codecin/native/engine/audio_windows.go +190 -0
  118. codecin/native/engine/canvas.go +271 -0
  119. codecin/native/engine/console_other.go +9 -0
  120. codecin/native/engine/console_windows.go +43 -0
  121. codecin/native/engine/crom.go +86 -0
  122. codecin/native/engine/encode.go +93 -0
  123. codecin/native/engine/engine_test.go +198 -0
  124. codecin/native/engine/ffi_nocgo.go +20 -0
  125. codecin/native/engine/ffi_registry.go +69 -0
  126. codecin/native/engine/ffi_unix.go +109 -0
  127. codecin/native/engine/ffi_windows.go +117 -0
  128. codecin/native/engine/gui.go +209 -0
  129. codecin/native/engine/gui_stub.go +13 -0
  130. codecin/native/engine/gui_test.go +148 -0
  131. codecin/native/engine/gui_windows.go +604 -0
  132. codecin/native/engine/gui_x11.go +723 -0
  133. codecin/native/engine/host_test.go +139 -0
  134. codecin/native/engine/hostcrypto.go +30 -0
  135. codecin/native/engine/hostdesktop.go +173 -0
  136. codecin/native/engine/hostnet.go +127 -0
  137. codecin/native/engine/isa_gen.go +689 -0
  138. codecin/native/engine/keyboard.go +432 -0
  139. codecin/native/engine/keyboard_other.go +94 -0
  140. codecin/native/engine/keyboard_stub.go +17 -0
  141. codecin/native/engine/keyboard_termios_darwin.go +9 -0
  142. codecin/native/engine/keyboard_termios_linux.go +9 -0
  143. codecin/native/engine/keyboard_test.go +246 -0
  144. codecin/native/engine/keyboard_windows.go +208 -0
  145. codecin/native/engine/keyboard_windows_test.go +123 -0
  146. codecin/native/engine/lineedit.go +262 -0
  147. codecin/native/engine/lineedit_test.go +105 -0
  148. codecin/native/engine/lineint_unix.go +17 -0
  149. codecin/native/engine/lineint_windows.go +19 -0
  150. codecin/native/engine/mem_other.go +37 -0
  151. codecin/native/engine/mem_windows.go +33 -0
  152. codecin/native/engine/native.go +640 -0
  153. codecin/native/engine/netsock.go +321 -0
  154. codecin/native/engine/ops_ext.go +515 -0
  155. codecin/native/engine/stdin.go +72 -0
  156. codecin/native/engine/stdin_other.go +9 -0
  157. codecin/native/engine/stdin_windows.go +60 -0
  158. codecin/native/engine/system.go +313 -0
  159. codecin/native/engine/termux.go +180 -0
  160. codecin/native/engine/version_gen.go +7 -0
  161. codecin/native/engine/vkb_darwin.go +62 -0
  162. codecin/native/engine/vkb_linux.go +95 -0
  163. codecin/native/engine/vkb_stub.go +11 -0
  164. codecin/native/engine/vm.go +1677 -0
  165. codecin/native/go.mod +3 -0
  166. codecin/native/ir/ir.go +48 -0
  167. codecin/native/main.go +448 -0
  168. codecin/native/mc/aarch64.go +165 -0
  169. codecin/native/mc/aarch64_test.go +30 -0
  170. codecin/native/mc/elf.go +88 -0
  171. codecin/native/mc/print_test.go +52 -0
  172. codecin/native/mc/x86_64.go +1262 -0
  173. codecin/native/mc/x86_64_test.go +102 -0
  174. codecin/native.py +432 -0
  175. codecin/native_codegen.py +987 -0
  176. codecin/nativegen.py +786 -0
  177. codecin/object.py +539 -0
  178. codecin/optimizer.py +236 -0
  179. codecin/packaging/__init__.py +46 -0
  180. codecin/packaging/archive.py +177 -0
  181. codecin/packaging/model.py +519 -0
  182. codecin/packaging/spec.py +193 -0
  183. codecin/packaging/store.py +372 -0
  184. codecin/packaging/toml.py +541 -0
  185. codecin/packaging/vcs.py +215 -0
  186. codecin/pic.py +1917 -0
  187. codecin/pic_api.py +374 -0
  188. codecin/pic_login.py +519 -0
  189. codecin/pic_registry.py +515 -0
  190. codecin/registers.py +130 -0
  191. codecin/sdgcc.py +493 -0
  192. codecin/stats.py +230 -0
  193. codecin/stdlib.py +138 -0
  194. codecin/toolchain.py +396 -0
  195. codecin/toolkit.py +26 -0
  196. codecin/version.py +260 -0
  197. codecin-7.22.10.dist-info/METADATA +1077 -0
  198. codecin-7.22.10.dist-info/RECORD +202 -0
  199. codecin-7.22.10.dist-info/WHEEL +5 -0
  200. codecin-7.22.10.dist-info/entry_points.txt +5 -0
  201. codecin-7.22.10.dist-info/licenses/LICENSE +7 -0
  202. codecin-7.22.10.dist-info/top_level.txt +1 -0
@@ -0,0 +1,148 @@
1
+ // Code CIN 官方标准库: 字符/字符串校验 (validate)
2
+ // 用法: import "validate.cin"
3
+ //
4
+ // 与 str.cin 互补: str.cin 做变换 (大小写/裁剪/包含),
5
+ // 本库做**判定与安全解析** (字符类别、整数字符串、标识符、限幅)。
6
+
7
+ // 字符类别 (参数为字符的字节值, 如 'a' 或 s[i])
8
+ function val_is_digit(int c) -> int {
9
+ if (c >= '0' && c <= '9') { return 1 }
10
+ return 0
11
+ }
12
+
13
+ function val_is_upper(int c) -> int {
14
+ if (c >= 'A' && c <= 'Z') { return 1 }
15
+ return 0
16
+ }
17
+
18
+ function val_is_lower(int c) -> int {
19
+ if (c >= 'a' && c <= 'z') { return 1 }
20
+ return 0
21
+ }
22
+
23
+ function val_is_alpha(int c) -> int {
24
+ if (val_is_upper(c) == 1 || val_is_lower(c) == 1) { return 1 }
25
+ return 0
26
+ }
27
+
28
+ function val_is_alnum(int c) -> int {
29
+ if (val_is_alpha(c) == 1 || val_is_digit(c) == 1) { return 1 }
30
+ return 0
31
+ }
32
+
33
+ function val_is_hex(int c) -> int {
34
+ if (val_is_digit(c) == 1) { return 1 }
35
+ if (c >= 'a' && c <= 'f') { return 1 }
36
+ if (c >= 'A' && c <= 'F') { return 1 }
37
+ return 0
38
+ }
39
+
40
+ function val_is_space(int c) -> int {
41
+ if (c == ' ' || c == '\t' || c == '\n' || c == '\r') { return 1 }
42
+ return 0
43
+ }
44
+
45
+ // 整数字符串: 可选 +/-, 至少一位数字, 其余全是数字
46
+ function val_is_int(string s) -> int {
47
+ int n = strlen(s)
48
+ if (n == 0) { return 0 }
49
+ int i = 0
50
+ if (s[0] == '+' || s[0] == '-') {
51
+ if (n == 1) { return 0 }
52
+ i = 1
53
+ }
54
+ while (i < n) {
55
+ if (val_is_digit(s[i]) == 0) { return 0 }
56
+ i = i + 1
57
+ }
58
+ return 1
59
+ }
60
+
61
+ // 浮点字符串: 数字 + 至多一个小数点 (不校验指数形式)
62
+ function val_is_float(string s) -> int {
63
+ int n = strlen(s)
64
+ if (n == 0) { return 0 }
65
+ int i = 0
66
+ int dots = 0
67
+ int digits = 0
68
+ if (s[0] == '+' || s[0] == '-') {
69
+ if (n == 1) { return 0 }
70
+ i = 1
71
+ }
72
+ while (i < n) {
73
+ int c = s[i]
74
+ if (c == '.') {
75
+ dots = dots + 1
76
+ if (dots > 1) { return 0 }
77
+ } else {
78
+ if (val_is_digit(c) == 0) { return 0 }
79
+ digits = digits + 1
80
+ }
81
+ i = i + 1
82
+ }
83
+ if (digits == 0) { return 0 }
84
+ return 1
85
+ }
86
+
87
+ // 标识符: [A-Za-z_][A-Za-z0-9_]*
88
+ function val_is_ident(string s) -> int {
89
+ int n = strlen(s)
90
+ if (n == 0) { return 0 }
91
+ int c0 = s[0]
92
+ if (val_is_alpha(c0) == 0 && c0 != '_') { return 0 }
93
+ for (int i = 1; i < n; i = i + 1) {
94
+ int c = s[i]
95
+ if (val_is_alnum(c) == 0 && c != '_') { return 0 }
96
+ }
97
+ return 1
98
+ }
99
+
100
+ // 出现次数
101
+ function val_count_char(string s, int c) -> int {
102
+ int n = strlen(s)
103
+ int k = 0
104
+ for (int i = 0; i < n; i = i + 1) {
105
+ if (s[i] == c) { k = k + 1 }
106
+ }
107
+ return k
108
+ }
109
+
110
+ // 去掉首尾空白后是否为空
111
+ function val_is_blank(string s) -> int {
112
+ int n = strlen(s)
113
+ for (int i = 0; i < n; i = i + 1) {
114
+ if (val_is_space(s[i]) == 0) { return 0 }
115
+ }
116
+ return 1
117
+ }
118
+
119
+ // 限幅到 [lo, hi]
120
+ function val_clamp_int(int v, int lo, int hi) -> int {
121
+ if (lo > hi) { return v }
122
+ if (v < lo) { return lo }
123
+ if (v > hi) { return hi }
124
+ return v
125
+ }
126
+
127
+ // 安全解析: 非法时返回 fallback
128
+ function val_parse_int(string s, int fallback) -> int {
129
+ if (val_is_int(s) == 0) { return fallback }
130
+ return atoi(s)
131
+ }
132
+
133
+ // 是否为 3/6 位十六进制颜色 (#RRGGBB 或 RRGGBB)
134
+ function val_is_hex_color(string s) -> int {
135
+ int n = strlen(s)
136
+ int start = 0
137
+ if (n > 0 && s[0] == '#') {
138
+ start = 1
139
+ n = n - 1
140
+ }
141
+ if (n != 3 && n != 6) { return 0 }
142
+ int i = start
143
+ while (i < strlen(s)) {
144
+ if (val_is_hex(s[i]) == 0) { return 0 }
145
+ i = i + 1
146
+ }
147
+ return 1
148
+ }
@@ -0,0 +1,10 @@
1
+ # 由 script/sync_stdlib_packages.py 生成,请勿手工编辑。
2
+ [package]
3
+ name = "vec"
4
+ version = "7.22.10"
5
+ description = "Code CIN 官方标准库: 浮点向量与统计"
6
+ license = "MIT"
7
+ authors = ["ByUsi Studio"]
8
+ entry = "src/vec.cin"
9
+ repo = "https://gitee.com/codecin/internal-libraries"
10
+ keywords = ["codecin", "stdlib", "vec"]
@@ -0,0 +1,88 @@
1
+ // Code CIN 官方标准库: 浮点向量与统计 (vec)
2
+ // 用法: import "vec.cin"
3
+
4
+ // 求和
5
+ function v_sum(float[] a, int n) -> float {
6
+ float s = 0.0
7
+ for (int i = 0; i < n; i = i + 1) { s = s + a[i] }
8
+ return s
9
+ }
10
+
11
+ // 均值
12
+ function v_mean(float[] a, int n) -> float {
13
+ if (n <= 0) { return 0.0 }
14
+ return v_sum(a, n) / n
15
+ }
16
+
17
+ // 样本方差
18
+ function v_var(float[] a, int n) -> float {
19
+ if (n <= 1) { return 0.0 }
20
+ float m = v_mean(a, n)
21
+ float s = 0.0
22
+ for (int i = 0; i < n; i = i + 1) {
23
+ float d = a[i] - m
24
+ s = s + d * d
25
+ }
26
+ return s / (n - 1)
27
+ }
28
+
29
+ // 样本标准差
30
+ function v_std(float[] a, int n) -> float {
31
+ return sqrt(v_var(a, n))
32
+ }
33
+
34
+ // 点积
35
+ function v_dot(float[] a, float[] b, int n) -> float {
36
+ float s = 0.0
37
+ for (int i = 0; i < n; i = i + 1) { s = s + a[i] * b[i] }
38
+ return s
39
+ }
40
+
41
+ // 最小值
42
+ function v_min(float[] a, int n) -> float {
43
+ if (n <= 0) { return 0.0 }
44
+ float m = a[0]
45
+ for (int i = 1; i < n; i = i + 1) { if (a[i] < m) { m = a[i] } }
46
+ return m
47
+ }
48
+
49
+ // 最大值
50
+ function v_max(float[] a, int n) -> float {
51
+ if (n <= 0) { return 0.0 }
52
+ float m = a[0]
53
+ for (int i = 1; i < n; i = i + 1) { if (a[i] > m) { m = a[i] } }
54
+ return m
55
+ }
56
+
57
+ // 逐元素相加 (结果写入 dst)
58
+ function v_add(float[] a, float[] b, float[] dst, int n) -> void {
59
+ for (int i = 0; i < n; i = i + 1) { dst[i] = a[i] + b[i] }
60
+ }
61
+
62
+ // 逐元素缩放 (结果写入 dst)
63
+ function v_scale(float[] a, float k, float[] dst, int n) -> void {
64
+ for (int i = 0; i < n; i = i + 1) { dst[i] = a[i] * k }
65
+ }
66
+
67
+ // 原地归一化到 [0, 1] (按 min/max)
68
+ function v_normalize(float[] a, int n) -> void {
69
+ if (n <= 0) { return }
70
+ float lo = v_min(a, n)
71
+ float hi = v_max(a, n)
72
+ float span = hi - lo
73
+ if (span == 0.0) {
74
+ for (int i = 0; i < n; i = i + 1) { a[i] = 0.0 }
75
+ return
76
+ }
77
+ for (int i = 0; i < n; i = i + 1) { a[i] = (a[i] - lo) / span }
78
+ }
79
+
80
+ // 欧几里得范数
81
+ function v_norm(float[] a, int n) -> float {
82
+ return sqrt(v_dot(a, a, n))
83
+ }
84
+
85
+ // 一维线性插值
86
+ function v_lerp(float a, float b, float t) -> float {
87
+ return a + (b - a) * t
88
+ }
codecin/logger.py ADDED
@@ -0,0 +1,145 @@
1
+ import io
2
+ import logging
3
+ import os
4
+ from typing import Any, Dict, Optional
5
+
6
+ from rich.logging import RichHandler
7
+ from rich.table import Table as RichTable
8
+
9
+ from .console import Console
10
+
11
+ _FORMAT = '%(message)s'
12
+
13
+
14
+ def _render_plain(renderable) -> str:
15
+ """将 rich 渲染对象渲染为纯文本 (用于日志消息)。"""
16
+ buf = io.StringIO()
17
+ from rich.console import Console as RC
18
+ rc = RC(file=buf, highlight=False, emoji=False, markup=False, width=120)
19
+ rc.print(renderable)
20
+ return buf.getvalue().rstrip('\n')
21
+
22
+
23
+ class Logger:
24
+
25
+ LEVELS = {'DEBUG': 0, 'INFO': 1, 'WARNING': 2, 'ERROR': 3, 'CRITICAL': 4}
26
+
27
+ def __init__(self, console: Optional[Console] = None, level: str = 'INFO'):
28
+ self.console = console or Console()
29
+ self.level = self._parse_level(level)
30
+
31
+ self._log = logging.getLogger('codecin')
32
+ self._log.propagate = False
33
+ self._log.setLevel(logging.DEBUG) # handler 负责过滤
34
+ # 本类独占 'codecin' logger, 避免重复 handler
35
+ for h in list(self._log.handlers):
36
+ self._log.removeHandler(h)
37
+
38
+ self._handler = RichHandler(
39
+ console=self.console.rich,
40
+ show_time=True,
41
+ show_level=True,
42
+ show_path=False,
43
+ rich_tracebacks=True,
44
+ tracebacks_show_locals=False,
45
+ markup=False,
46
+ log_time_format='%H:%M:%S',
47
+ )
48
+ self._handler.setFormatter(logging.Formatter(_FORMAT))
49
+ self._handler.setLevel(self._to_logging_level(self.level))
50
+ self._log.addHandler(self._handler)
51
+
52
+ self._file_handler: Optional[logging.FileHandler] = None
53
+ self.log_file: Optional[str] = None
54
+
55
+ # ---------------- 级别控制 ----------------
56
+
57
+ @staticmethod
58
+ def _to_logging_level(codecin_level: int) -> int:
59
+ # codecin: DEBUG=0..CRITICAL=4 -> logging: 10..50
60
+ return (codecin_level + 1) * 10
61
+
62
+ def _parse_level(self, level: str) -> int:
63
+ return self.LEVELS.get(str(level).upper(), 1)
64
+
65
+ def set_level(self, level: str) -> None:
66
+ self.level = self._parse_level(level)
67
+ self._handler.setLevel(self._to_logging_level(self.level))
68
+
69
+ @property
70
+ def is_debug(self) -> bool:
71
+ return self.level <= self.LEVELS['DEBUG']
72
+
73
+ def set_log_file(self, filename: str) -> None:
74
+ self.log_file = filename
75
+ if self._file_handler is not None:
76
+ self._log.removeHandler(self._file_handler)
77
+ self._file_handler.close()
78
+ os.makedirs(os.path.dirname(os.path.abspath(filename)) or '.',
79
+ exist_ok=True)
80
+ fh = logging.FileHandler(filename, mode='w', encoding='utf-8')
81
+ fh.setFormatter(logging.Formatter(
82
+ '[%(asctime)s] [%(levelname)s] %(message)s', datefmt='%H:%M:%S'))
83
+ fh.setLevel(logging.DEBUG) # 文件记录全量
84
+ self._log.addHandler(fh)
85
+ self._file_handler = fh
86
+
87
+ # ---------------- 标准级别 ----------------
88
+
89
+ def debug(self, msg: str) -> None:
90
+ self._log.debug(msg)
91
+
92
+ def info(self, msg: str) -> None:
93
+ self._log.info(msg)
94
+
95
+ def warning(self, msg: str) -> None:
96
+ self._log.warning(msg)
97
+
98
+ def error(self, msg: str, exc_info: Any = None) -> None:
99
+ self._log.error(msg, exc_info=exc_info)
100
+
101
+ def critical(self, msg: str, exc_info: Any = None) -> None:
102
+ self._log.critical(msg, exc_info=exc_info)
103
+
104
+ def exception(self, msg: str) -> None:
105
+ """rich 彩色堆栈回溯输出。"""
106
+ self._log.error(msg, exc_info=True)
107
+
108
+ # ---------------- 超详细调试辅助 ----------------
109
+
110
+ def trace(self, msg: str) -> None:
111
+ """逐指令级追踪 (仅 DEBUG)。"""
112
+ self._log.debug(msg)
113
+
114
+ def dump(self, title: str, fields: Dict[str, Any]) -> None:
115
+ """以表格输出调试快照 (仅 DEBUG)。"""
116
+ if not self.is_debug:
117
+ return
118
+ t = RichTable(title=title, show_header=False, border_style='dim',
119
+ padding=(0, 1), highlight=False)
120
+ t.add_column(style='bold cyan', no_wrap=True)
121
+ t.add_column()
122
+ for k, v in fields.items():
123
+ t.add_row(str(k), str(v))
124
+ self._log.debug(_render_plain(t))
125
+
126
+ def hexdump(self, title: str, addr: int, data: bytes,
127
+ width: int = 16) -> None:
128
+ """内存十六进制转储 (仅 DEBUG)。"""
129
+ if not self.is_debug:
130
+ return
131
+ lines = []
132
+ for off in range(0, min(len(data), 256), width):
133
+ chunk = data[off:off + width]
134
+ hexs = ' '.join(f'{b:02x}' for b in chunk)
135
+ asc = ''.join(chr(b) if 32 <= b < 127 else '.' for b in chunk)
136
+ lines.append(f' {addr + off:06x} {hexs:<{width * 3}} {asc}')
137
+ if len(data) > 256:
138
+ lines.append(f' ... ({len(data)} bytes total)')
139
+ self._log.debug(f'{title}\n' + '\n'.join(lines))
140
+
141
+ def close(self) -> None:
142
+ if self._file_handler is not None:
143
+ self._log.removeHandler(self._file_handler)
144
+ self._file_handler.close()
145
+ self._file_handler = None
codecin/memory.py ADDED
@@ -0,0 +1,306 @@
1
+ import struct
2
+ from typing import Dict, List, Optional, Tuple
3
+
4
+ from .console import Console, Table
5
+ from .errors import MemoryAccessError
6
+
7
+ # ==================== 稀疏内存 ====================
8
+ # 程序内存按需分配: 逻辑大小可达 1 GiB, 只有被写过的 4 KiB 页才占真实内存。
9
+ # 这与 Go 原生引擎的 make([]byte, memSize) (OS 懒提交) 行为一致:
10
+ # 读未写过的地址返回 0, 写入时才真正落页。
11
+
12
+
13
+ class FastMemory:
14
+ PAGE_BITS = 12
15
+ PAGE_SIZE = 1 << PAGE_BITS
16
+ PAGE_MASK = PAGE_SIZE - 1
17
+
18
+ def __init__(self, size: int = 1 << 30):
19
+ self._size = size
20
+ self._pages: Dict[int, bytearray] = {}
21
+ self._protection: Dict[int, str] = {}
22
+ # 调试日志钩子 (DEBUG 级别记录每次读写)
23
+ self._log = None
24
+
25
+ # ---------------- 页管理 ----------------
26
+
27
+ def _page(self, idx: int) -> Optional[bytearray]:
28
+ return self._pages.get(idx)
29
+
30
+ def _ensure_page(self, idx: int) -> bytearray:
31
+ page = self._pages.get(idx)
32
+ if page is None:
33
+ page = bytearray(self.PAGE_SIZE)
34
+ self._pages[idx] = page
35
+ return page
36
+
37
+ def attach_logger(self, logger) -> None:
38
+ """挂接日志器, DEBUG 级别下记录所有内存读写。"""
39
+ self._log = logger
40
+
41
+ @property
42
+ def _mem_trace(self) -> bool:
43
+ return self._log is not None and self._log.is_debug
44
+
45
+ def _trace_mem(self, op: str, addr: int, value, width: int) -> None:
46
+ vs = f"0x{value:x}" if isinstance(value, int) else repr(value)
47
+ self._log.trace(f" MEM {op:<5} @0x{addr:04x} w={width} value={vs}")
48
+
49
+ def __len__(self) -> int:
50
+ return self._size
51
+
52
+ @property
53
+ def size(self) -> int:
54
+ return self._size
55
+
56
+ @property
57
+ def resident_bytes(self) -> int:
58
+ """实际占用的物理内存字节数 (已分配页)。"""
59
+ return len(self._pages) * self.PAGE_SIZE
60
+
61
+ def reset(self, size: Optional[int] = None) -> None:
62
+ if size is not None:
63
+ self._size = size
64
+ self._pages.clear()
65
+ self._protection.clear()
66
+
67
+ def resize(self, new_size: int) -> None:
68
+ if new_size <= self._size:
69
+ return
70
+ self._size = new_size
71
+
72
+ def set_protection(self, addr: int, perms: str, size: int = 1) -> None:
73
+ for i in range(size):
74
+ self._protection[addr + i] = perms
75
+
76
+ def check_access(self, addr: int, access: str) -> bool:
77
+ perm = self._protection.get(addr, 'rwx')
78
+ return access in perm
79
+
80
+ def _check_bounds(self, addr: int, size: int = 1) -> None:
81
+ if not 0 <= addr <= self._size - size:
82
+ hint = ""
83
+ if addr >= (1 << 63):
84
+ # 按位模 2^64 后为负数: 典型成因是栈溢出 (SP 被推到负地址)
85
+ # 或野指针。可读性提示, 与 Go 引擎 vm.go 的文案保持一致。
86
+ hint = " (negative address: stack overflow or bad pointer?)"
87
+ raise MemoryAccessError(
88
+ f"Address 0x{addr:x} out of bounds (memory size 0x{self._size:x}, "
89
+ f"access width {size}){hint}")
90
+
91
+ def _check_protection(self, addr: int, access: str) -> None:
92
+ if not self.check_access(addr, access):
93
+ raise MemoryAccessError(
94
+ f"Memory protection violation at 0x{addr:x} for '{access}'")
95
+
96
+ def _check_protection_range(self, addr: int, size: int, access: str) -> None:
97
+ """对 [addr, addr+size) 内每个被保护字节做访问检查 (块读写统一入口)。"""
98
+ if not self._protection:
99
+ return
100
+ end = addr + size
101
+ for paddr, perms in self._protection.items():
102
+ if addr <= paddr < end and access not in perms:
103
+ raise MemoryAccessError(
104
+ f"Memory protection violation at 0x{paddr:x} "
105
+ f"for '{access}' (range 0x{addr:x}+{size})")
106
+
107
+ # ---------------- 单字节 ----------------
108
+
109
+ def read_byte(self, addr: int) -> int:
110
+ self._check_bounds(addr)
111
+ self._check_protection(addr, 'r')
112
+ page = self._page(addr >> self.PAGE_BITS)
113
+ v = page[addr & self.PAGE_MASK] if page is not None else 0
114
+ if self._mem_trace:
115
+ self._trace_mem('RD', addr, v, 1)
116
+ return v
117
+
118
+ def write_byte(self, addr: int, value: int) -> None:
119
+ self._check_bounds(addr)
120
+ self._check_protection(addr, 'w')
121
+ self._ensure_page(addr >> self.PAGE_BITS)[addr & self.PAGE_MASK] = value & 0xFF
122
+ if self._mem_trace:
123
+ self._trace_mem('WR', addr, value & 0xFF, 1)
124
+
125
+ # ---------------- 定宽多字节 (4 KiB 页内不跨页的问题与旧实现一致) ----------------
126
+
127
+ def read_word(self, addr: int) -> int:
128
+ self._check_bounds(addr, 2)
129
+ self._check_protection(addr, 'r')
130
+ return self._read_into(addr, 2, '<H')
131
+
132
+ def write_word(self, addr: int, value: int) -> None:
133
+ self._check_bounds(addr, 2)
134
+ self._check_protection(addr, 'w')
135
+ self._write_from(addr, 2, struct.pack('<H', value & 0xFFFF))
136
+
137
+ def read_dword(self, addr: int) -> int:
138
+ self._check_bounds(addr, 4)
139
+ self._check_protection(addr, 'r')
140
+ return self._read_into(addr, 4, '<I')
141
+
142
+ def write_dword(self, addr: int, value: int) -> None:
143
+ self._check_bounds(addr, 4)
144
+ self._check_protection(addr, 'w')
145
+ self._write_from(addr, 4, struct.pack('<I', value & 0xFFFFFFFF))
146
+
147
+ def read_qword(self, addr: int) -> int:
148
+ self._check_bounds(addr, 8)
149
+ self._check_protection(addr, 'r')
150
+ return self._read_into(addr, 8, '<Q')
151
+
152
+ def write_qword(self, addr: int, value: int) -> None:
153
+ self._check_bounds(addr, 8)
154
+ self._check_protection(addr, 'w')
155
+ self._write_from(addr, 8, struct.pack('<Q', value & 0xFFFFFFFFFFFFFFFF))
156
+
157
+ def read_float(self, addr: int) -> float:
158
+ self._check_bounds(addr, 4)
159
+ self._check_protection(addr, 'r')
160
+ return struct.unpack('<f', self._raw_read(addr, 4))[0]
161
+
162
+ def write_float(self, addr: int, value: float) -> None:
163
+ self._check_bounds(addr, 4)
164
+ self._check_protection(addr, 'w')
165
+ self._write_from(addr, 4, struct.pack('<f', value))
166
+
167
+ def read_double(self, addr: int) -> float:
168
+ self._check_bounds(addr, 8)
169
+ self._check_protection(addr, 'r')
170
+ return struct.unpack('<d', self._raw_read(addr, 8))[0]
171
+
172
+ def write_double(self, addr: int, value: float) -> None:
173
+ self._check_bounds(addr, 8)
174
+ self._check_protection(addr, 'w')
175
+ self._write_from(addr, 8, struct.pack('<d', value))
176
+
177
+ def _raw_read(self, addr: int, size: int) -> bytes:
178
+ """读 [addr, addr+size); 未分配页返回 0。"""
179
+ out = bytearray(size)
180
+ pos = 0
181
+ while pos < size:
182
+ a = addr + pos
183
+ page = self._page(a >> self.PAGE_BITS)
184
+ if page is not None:
185
+ off = a & self.PAGE_MASK
186
+ n = min(self.PAGE_SIZE - off, size - pos)
187
+ out[pos:pos + n] = page[off:off + n]
188
+ pos += n
189
+ else:
190
+ pos += self.PAGE_SIZE - (a & self.PAGE_MASK)
191
+ return bytes(out)
192
+
193
+ def _raw_write(self, addr: int, data: bytes) -> None:
194
+ """写 [addr, addr+len(data)); 按需分配页。"""
195
+ pos = 0
196
+ while pos < len(data):
197
+ a = addr + pos
198
+ page = self._ensure_page(a >> self.PAGE_BITS)
199
+ off = a & self.PAGE_MASK
200
+ n = min(self.PAGE_SIZE - off, len(data) - pos)
201
+ page[off:off + n] = data[pos:pos + n]
202
+ pos += n
203
+
204
+ def _read_into(self, addr: int, width: int, fmt: str) -> int:
205
+ return struct.unpack(fmt, self._raw_read(addr, width))[0]
206
+
207
+ def _write_from(self, addr: int, width: int, raw: bytes) -> None:
208
+ self._raw_write(addr, raw)
209
+
210
+ # ---------------- 块 / 字符串 ----------------
211
+
212
+ def read_block(self, addr: int, size: int) -> bytes:
213
+ self._check_bounds(addr, size)
214
+ self._check_protection_range(addr, size, 'r')
215
+ return self._raw_read(addr, size)
216
+
217
+ def write_block(self, addr: int, data) -> None:
218
+ size = len(data)
219
+ self._check_bounds(addr, size)
220
+ self._check_protection_range(addr, size, 'w')
221
+ self._raw_write(addr, bytes(data))
222
+
223
+ def read_string(self, addr: int, max_len: int = 4096) -> str:
224
+ chars = []
225
+ for _ in range(max_len):
226
+ b = self.read_byte(addr)
227
+ if b == 0:
228
+ break
229
+ chars.append(b)
230
+ addr += 1
231
+ return bytes(chars).decode('utf-8', errors='replace')
232
+
233
+ def read_cstr_bytes(self, addr: int, max_len: int = 4096) -> bytes:
234
+ """读 NUL 结尾的**原始字节** (不做 UTF-8 解码)。
235
+
236
+ CIN 的字符串是字节序列: `strlen` / `substr` / `s[i]` 都是字节语义。
237
+ 用 ``read_string`` 再 ``encode`` 会经过一次 UTF-8 编解码, 非法字节序列
238
+ 会被替换成 U+FFFD (每个 3 字节), 于是与 Go 原生 VM 的字节结果不一致。
239
+ 需要字节级语义的地方一律用本方法。
240
+ """
241
+ chars = []
242
+ for _ in range(max_len):
243
+ b = self.read_byte(addr)
244
+ if b == 0:
245
+ break
246
+ chars.append(b)
247
+ addr += 1
248
+ return bytes(chars)
249
+
250
+ def write_string(self, addr: int, text: str) -> int:
251
+ data = text.encode('utf-8') + b'\x00'
252
+ self.write_block(addr, data)
253
+ return len(data)
254
+
255
+ def load_bytes(self, addr: int, data) -> None:
256
+ self.write_block(addr, bytes(data))
257
+
258
+ def snapshot_segments(self) -> List[Tuple[int, bytes]]:
259
+ """返回全部已分配内容为 (页起始地址, 数据) 列表, 按地址升序。
260
+
261
+ 段式格式 (CROM v4 / bin v3 / native v2 ABI) 的统一出口。
262
+ """
263
+ segs = []
264
+ for idx in sorted(self._pages):
265
+ segs.append((idx << self.PAGE_BITS, bytes(self._pages[idx])))
266
+ return segs
267
+
268
+ def load_segments(self, segs: List[Tuple[int, bytes]]) -> None:
269
+ """用 (addr, data) 列表恢复内容 (不清空现有页)。"""
270
+ for addr, data in segs:
271
+ self.write_block(addr, data)
272
+
273
+ def get_snapshot(self, start: int = 0, count: int = -1) -> bytes:
274
+ """读取一段连续内容 (未分配页为 0)。
275
+
276
+ count < 0 时读到最后一个已写字节为止 (稀疏友好: 不会输出
277
+ 整个逻辑空间的零填充, 与旧的整块快照在测试语义上兼容)。
278
+ """
279
+ if count >= 0:
280
+ return self._raw_read(start, count)
281
+ end = start
282
+ for idx in self._pages:
283
+ page_end = (idx << self.PAGE_BITS) + self.PAGE_SIZE
284
+ if page_end > end:
285
+ end = page_end
286
+ if end <= start:
287
+ return b''
288
+ return self._raw_read(start, end - start)
289
+
290
+ def display_memory(self, title: str = "Memory Dump", start: int = 0,
291
+ count: int = 32, console: Optional[Console] = None) -> None:
292
+ if console is None:
293
+ return
294
+ table = Table(title=title)
295
+ table.add_column("Address")
296
+ table.add_column("Hex")
297
+ table.add_column("ASCII")
298
+ table.add_column("Prot")
299
+ end = min(start + count, self._size)
300
+ for i in range(start, end, 16):
301
+ chunk = self._raw_read(i, min(16, end - i))
302
+ hex_str = ' '.join(f'{b:02X}' for b in chunk)
303
+ ascii_str = ''.join(chr(b) if 32 <= b <= 126 else '.' for b in chunk)
304
+ perm = self._protection.get(i, 'rwx')
305
+ table.add_row(f"{i:04X}", hex_str, ascii_str, perm)
306
+ console.print(str(table))