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,271 @@
1
+ package engine
2
+
3
+ import (
4
+ "fmt"
5
+ "image"
6
+ "image/color"
7
+ "image/png"
8
+ "os"
9
+ "os/exec"
10
+ "path/filepath"
11
+ "runtime"
12
+ "strings"
13
+ "time"
14
+ )
15
+
16
+ // 2D 绘图画布 (Go 标准库 image/png 实现): 新建画布 → 着色 → 绘制形状/文本 → 导出 PNG。
17
+ // 宿主全局状态: 同一时刻一个「当前画布」与「当前颜色」。
18
+
19
+ var (
20
+ curCanvas *image.RGBA
21
+ curColor = color.RGBA{R: 0, G: 0, B: 0, A: 255} // 默认黑色画笔
22
+ )
23
+
24
+ func clampCoord(v uint64) int {
25
+ if v > 100000 {
26
+ return 100000
27
+ }
28
+ return int(v)
29
+ }
30
+
31
+ func (vm *vmState) canvasNew(w, h uint64) {
32
+ cw, ch := clampCoord(w), clampCoord(h)
33
+ if cw < 1 {
34
+ cw = 1
35
+ }
36
+ if ch < 1 {
37
+ ch = 1
38
+ }
39
+ curCanvas = image.NewRGBA(image.Rect(0, 0, cw, ch))
40
+ // 白色背景
41
+ for i := range curCanvas.Pix {
42
+ curCanvas.Pix[i] = 255
43
+ }
44
+ curColor = color.RGBA{R: 0, G: 0, B: 0, A: 255}
45
+ }
46
+
47
+ func (vm *vmState) canvasSetColor(rgb uint64) {
48
+ curColor = color.RGBA{
49
+ R: uint8((rgb >> 16) & 0xFF),
50
+ G: uint8((rgb >> 8) & 0xFF),
51
+ B: uint8(rgb & 0xFF),
52
+ A: 255,
53
+ }
54
+ }
55
+
56
+ func (vm *vmState) canvasRect(x, y, w, h uint64) {
57
+ if curCanvas == nil {
58
+ return
59
+ }
60
+ x0, y0 := clampCoord(x), clampCoord(y)
61
+ x1, y1 := x0+clampCoord(w), y0+clampCoord(h)
62
+ b := curCanvas.Bounds()
63
+ if x0 < b.Min.X {
64
+ x0 = b.Min.X
65
+ }
66
+ if y0 < b.Min.Y {
67
+ y0 = b.Min.Y
68
+ }
69
+ if x1 > b.Max.X {
70
+ x1 = b.Max.X
71
+ }
72
+ if y1 > b.Max.Y {
73
+ y1 = b.Max.Y
74
+ }
75
+ for py := y0; py < y1; py++ {
76
+ for px := x0; px < x1; px++ {
77
+ curCanvas.SetRGBA(px, py, curColor)
78
+ }
79
+ }
80
+ }
81
+
82
+ func (vm *vmState) canvasCircle(cx, cy, r uint64) {
83
+ if curCanvas == nil {
84
+ return
85
+ }
86
+ ccx, ccy := clampCoord(cx), clampCoord(cy)
87
+ rr := clampCoord(r)
88
+ rr2 := rr * rr
89
+ b := curCanvas.Bounds()
90
+ for py := ccy - rr; py <= ccy+rr; py++ {
91
+ for px := ccx - rr; px <= ccx+rr; px++ {
92
+ dx := px - ccx
93
+ dy := py - ccy
94
+ if dx*dx+dy*dy <= rr2 {
95
+ if px >= b.Min.X && px < b.Max.X && py >= b.Min.Y && py < b.Max.Y {
96
+ curCanvas.SetRGBA(px, py, curColor)
97
+ }
98
+ }
99
+ }
100
+ }
101
+ }
102
+
103
+ func (vm *vmState) canvasLine(x0, y0, x1, y1 uint64) {
104
+ if curCanvas == nil {
105
+ return
106
+ }
107
+ ax, ay := clampCoord(x0), clampCoord(y0)
108
+ bx, by := clampCoord(x1), clampCoord(y1)
109
+ b := curCanvas.Bounds()
110
+ // Bresenham
111
+ dx := bx - ax
112
+ if dx < 0 {
113
+ dx = -dx
114
+ }
115
+ sx := 1
116
+ if ax > bx {
117
+ sx = -1
118
+ }
119
+ dy := by - ay
120
+ if dy < 0 {
121
+ dy = -dy
122
+ }
123
+ sy := 1
124
+ if ay > by {
125
+ sy = -1
126
+ }
127
+ err := dx - dy
128
+ for {
129
+ if ax >= b.Min.X && ax < b.Max.X && ay >= b.Min.Y && ay < b.Max.Y {
130
+ curCanvas.SetRGBA(ax, ay, curColor)
131
+ }
132
+ if ax == bx && ay == by {
133
+ break
134
+ }
135
+ e2 := 2 * err
136
+ if e2 > -dy {
137
+ err -= dy
138
+ ax += sx
139
+ }
140
+ if e2 < dx {
141
+ err += dx
142
+ ay += sy
143
+ }
144
+ }
145
+ }
146
+
147
+ // font5x7: 内置 5x7 点阵字库 (ASCII 数字/大写/常用标点; 小写映射为大写)。
148
+ type glyph [7]string
149
+
150
+ var font5x7 = map[rune]glyph{
151
+ ' ': {" ", " ", " ", " ", " ", " ", " "},
152
+ '0': {" ### ", "# #", "# ##", "# # #", "## #", "# #", " ### "},
153
+ '1': {" # ", " ## ", " # ", " # ", " # ", " # ", " ### "},
154
+ '2': {" ### ", "# #", " #", " # ", " # ", " # ", "#####"},
155
+ '3': {"#####", " #", " # ", " ## ", " #", "# #", " ### "},
156
+ '4': {" # ", " ## ", " # # ", "# # ", "#####", " # ", " # "},
157
+ '5': {"#####", "# ", "#### ", " #", " #", "# #", " ### "},
158
+ '6': {" ## ", " # ", "# ", "#### ", "# #", "# #", " ### "},
159
+ '7': {"#####", " #", " # ", " # ", " # ", " # ", " # "},
160
+ '8': {" ### ", "# #", "# #", " ### ", "# #", "# #", " ### "},
161
+ '9': {" ### ", "# #", "# #", " ####", " #", " # ", " ## "},
162
+ 'A': {" ### ", "# #", "# #", "#####", "# #", "# #", "# #"},
163
+ 'B': {"#### ", "# #", "# #", "#### ", "# #", "# #", "#### "},
164
+ 'C': {" ### ", "# #", "# ", "# ", "# ", "# #", " ### "},
165
+ 'D': {"#### ", "# #", "# #", "# #", "# #", "# #", "#### "},
166
+ 'E': {"#####", "# ", "# ", "#### ", "# ", "# ", "#####"},
167
+ 'F': {"#####", "# ", "# ", "#### ", "# ", "# ", "# "},
168
+ 'G': {" ### ", "# #", "# ", "# ###", "# #", "# #", " ####"},
169
+ 'H': {"# #", "# #", "# #", "#####", "# #", "# #", "# #"},
170
+ 'I': {" ### ", " # ", " # ", " # ", " # ", " # ", " ### "},
171
+ 'J': {" #", " #", " #", " #", "# #", "# #", " ### "},
172
+ 'K': {"# #", "# # ", "# # ", "## ", "# # ", "# # ", "# #"},
173
+ 'L': {"# ", "# ", "# ", "# ", "# ", "# ", "#####"},
174
+ 'M': {"# #", "## ##", "# # #", "# # #", "# #", "# #", "# #"},
175
+ 'N': {"# #", "## #", "# # #", "# ##", "# #", "# #", "# #"},
176
+ 'O': {" ### ", "# #", "# #", "# #", "# #", "# #", " ### "},
177
+ 'P': {"#### ", "# #", "# #", "#### ", "# ", "# ", "# "},
178
+ 'Q': {" ### ", "# #", "# #", "# #", "# # #", "# # ", " ## #"},
179
+ 'R': {"#### ", "# #", "# #", "#### ", "# # ", "# # ", "# #"},
180
+ 'S': {" ####", "# ", "# ", " ### ", " #", " #", "#### "},
181
+ 'T': {"#####", " # ", " # ", " # ", " # ", " # ", " # "},
182
+ 'U': {"# #", "# #", "# #", "# #", "# #", "# #", " ### "},
183
+ 'V': {"# #", "# #", "# #", "# #", "# #", " # # ", " # "},
184
+ 'W': {"# #", "# #", "# #", "# # #", "# # #", "## ##", "# #"},
185
+ 'X': {"# #", "# #", " # # ", " # ", " # # ", "# #", "# #"},
186
+ 'Y': {"# #", "# #", " # # ", " # ", " # ", " # ", " # "},
187
+ 'Z': {"#####", " #", " # ", " # ", " # ", "# ", "#####"},
188
+ '.': {" ", " ", " ", " ", " ", " ## ", " ## "},
189
+ ',': {" ", " ", " ", " ", " ## ", " # ", " # "},
190
+ ':': {" ", " ## ", " ## ", " ", " ## ", " ## ", " "},
191
+ '-': {" ", " ", " ", "#####", " ", " ", " "},
192
+ '!': {" # ", " # ", " # ", " # ", " # ", " ", " # "},
193
+ '?': {" ### ", "# #", " #", " # ", " # ", " ", " # "},
194
+ '/': {" #", " #", " # ", " # ", " # ", "# ", "# "},
195
+ }
196
+
197
+ func (vm *vmState) canvasText(x, y uint64, s string) {
198
+ if curCanvas == nil {
199
+ return
200
+ }
201
+ ox, oy := clampCoord(x), clampCoord(y)
202
+ s = strings.ToUpper(s)
203
+ b := curCanvas.Bounds()
204
+ px := ox
205
+ for _, r := range s {
206
+ g, ok := font5x7[r]
207
+ if !ok {
208
+ g = font5x7['?']
209
+ }
210
+ for row := 0; row < 7; row++ {
211
+ for col := 0; col < 5; col++ {
212
+ if g[row][col] == '#' {
213
+ cx := px + col
214
+ cy := oy + row
215
+ if cx >= b.Min.X && cx < b.Max.X && cy >= b.Min.Y && cy < b.Max.Y {
216
+ curCanvas.SetRGBA(cx, cy, curColor)
217
+ }
218
+ }
219
+ }
220
+ }
221
+ px += 6
222
+ }
223
+ }
224
+
225
+ func (vm *vmState) canvasSave(path string) uint64 {
226
+ if curCanvas == nil {
227
+ return mask64 // -1
228
+ }
229
+ f, err := os.Create(path)
230
+ if err != nil {
231
+ return mask64
232
+ }
233
+ defer f.Close()
234
+ if err := png.Encode(f, curCanvas); err != nil {
235
+ return mask64
236
+ }
237
+ return 0
238
+ }
239
+
240
+ // canvasShow 保存当前画布到临时 PNG 并用系统查看器打开 (跨平台 "窗口")。
241
+ func (vm *vmState) canvasShow() uint64 {
242
+ if curCanvas == nil {
243
+ return mask64 // -1
244
+ }
245
+ path := filepath.Join(os.TempDir(),
246
+ fmt.Sprintf("codecin_canvas_%d.png", time.Now().UnixNano()))
247
+ f, err := os.Create(path)
248
+ if err != nil {
249
+ return mask64
250
+ }
251
+ if err := png.Encode(f, curCanvas); err != nil {
252
+ _ = f.Close()
253
+ return mask64
254
+ }
255
+ _ = f.Close()
256
+ openViewer(path)
257
+ return 0
258
+ }
259
+
260
+ func openViewer(path string) {
261
+ var cmd *exec.Cmd
262
+ switch runtime.GOOS {
263
+ case "windows":
264
+ cmd = exec.Command("cmd", "/c", "start", "", path)
265
+ case "darwin":
266
+ cmd = exec.Command("open", path)
267
+ default:
268
+ cmd = exec.Command("xdg-open", path)
269
+ }
270
+ _ = cmd.Start()
271
+ }
@@ -0,0 +1,9 @@
1
+ //go:build !windows
2
+
3
+ package engine
4
+
5
+ // 非 Windows 平台终端原生支持 ANSI/VT 与 UTF-8, 无需初始化。
6
+ func consoleInit() {}
7
+
8
+ // ConsoleInit 供 engine 包外 (aot 产物) 在打印输出前初始化终端。
9
+ func ConsoleInit() {}
@@ -0,0 +1,43 @@
1
+ //go:build windows
2
+
3
+ package engine
4
+
5
+ import (
6
+ "sync"
7
+ "unsafe"
8
+ )
9
+
10
+ // Windows 控制台输出兼容 (一次性的进程级初始化, 失败安全):
11
+ // - ENABLE_VIRTUAL_TERMINAL_PROCESSING: 让 ANSI/VT 转义序列 (颜色/清屏/
12
+ // 光标) 在传统 conhost 上与 Linux/macOS 终端行为一致;
13
+ // - SetConsoleOutputCP(65001): 输出代码页切 UTF-8。Go 恒以 UTF-8 直写
14
+ // stdout, 中文 Windows 默认 GBK 代码页下中文/Emoji 会乱码。
15
+ // 两步都允许失败: 老 conhost 不支持 VT / 只读句柄时保持原样, 输出字节不变。
16
+
17
+ var (
18
+ consoleInitOnce sync.Once
19
+ procSetConsoleOutputCP = kernel32.NewProc("SetConsoleOutputCP")
20
+ )
21
+
22
+ const (
23
+ stdOutputHandle = ^uintptr(10) // STD_OUTPUT_HANDLE = (DWORD)-11
24
+ cmEnableVTOutput = 0x0004 // ENABLE_VIRTUAL_TERMINAL_PROCESSING
25
+ consoleCodePageUTF = 65001
26
+ )
27
+
28
+ // consoleInit 幂等初始化 Windows 控制台输出 (其他平台为空操作)。
29
+ func consoleInit() {
30
+ consoleInitOnce.Do(func() {
31
+ h, _, _ := procGetStdHandle.Call(stdOutputHandle)
32
+ if h != 0 {
33
+ var mode uint32
34
+ if r, _, _ := procGetConsoleMode.Call(h, uintptr(unsafe.Pointer(&mode))); r != 0 {
35
+ _, _, _ = procSetConsoleMode.Call(h, uintptr(mode|cmEnableVTOutput))
36
+ }
37
+ }
38
+ _, _, _ = procSetConsoleOutputCP.Call(consoleCodePageUTF)
39
+ })
40
+ }
41
+
42
+ // ConsoleInit 供 engine 包外 (aot 产物) 在打印输出前初始化终端。
43
+ func ConsoleInit() { consoleInit() }
@@ -0,0 +1,86 @@
1
+ package engine
2
+
3
+ // CROM v3: magic 'CROM' + version u8 + mem_size u32 + flags u8 + crc32 u32
4
+ // + 2B reserved + payload (zlib 默认压缩, 与 Python zlib level 6 兼容)
5
+
6
+ import (
7
+ "bytes"
8
+ "compress/zlib"
9
+ "encoding/binary"
10
+ "hash/crc32"
11
+ "io"
12
+ )
13
+
14
+ const cromVersion = 3
15
+
16
+ // cromMaxTrailer 是载荷允许超出头部 mem_size 的最大余量 (MMU 页表尾部元数据)。
17
+ // 必须与 Python 侧 codecin/crom.py: CROM_MAX_TRAILER 保持一致。
18
+ const cromMaxTrailer = 4 << 20
19
+
20
+ // CromPack 打包内存镜像为 CROM 字节流 (compress=true 时 zlib 压缩)。
21
+ func CromPack(data []byte, compress bool) []byte {
22
+ var payload []byte
23
+ flags := byte(0)
24
+ if compress {
25
+ flags = 0x01
26
+ var buf bytes.Buffer
27
+ // zlib.NewWriter 使用默认压缩级别 (flate.DefaultCompression = 6)
28
+ w := zlib.NewWriter(&buf)
29
+ _, _ = w.Write(data)
30
+ _ = w.Close()
31
+ payload = buf.Bytes()
32
+ } else {
33
+ payload = data
34
+ }
35
+
36
+ out := make([]byte, 16+len(payload))
37
+ copy(out[0:4], "CROM")
38
+ out[4] = cromVersion
39
+ binary.LittleEndian.PutUint32(out[5:9], uint32(len(data)))
40
+ out[9] = flags
41
+ binary.LittleEndian.PutUint32(out[10:14], crc32.ChecksumIEEE(payload))
42
+ // [14:16] reserved 0
43
+ copy(out[16:], payload)
44
+ return out
45
+ }
46
+
47
+ // CromUnpack 解包 CROM, 返回 (raw, flags, ok)。
48
+ func CromUnpack(data []byte) ([]byte, int, bool) {
49
+ if len(data) < 16 || string(data[0:4]) != "CROM" {
50
+ return nil, 0, false
51
+ }
52
+ if data[4] != cromVersion {
53
+ return nil, 0, false
54
+ }
55
+ memSize := binary.LittleEndian.Uint32(data[5:9])
56
+ flags := data[9]
57
+ checksum := binary.LittleEndian.Uint32(data[10:14])
58
+ payload := data[16:]
59
+ if crc32.ChecksumIEEE(payload) != checksum {
60
+ return nil, 0, false
61
+ }
62
+
63
+ var raw []byte
64
+ if flags&0x01 != 0 {
65
+ r, err := zlib.NewReader(bytes.NewReader(payload))
66
+ if err != nil {
67
+ return nil, 0, false
68
+ }
69
+ // 解压上限取自文件头声明的 mem_size + MMU 尾部余量: 防止 zip bomb
70
+ // (旧实现 io.ReadAll 无上限, 65KB 的合法 CROM 可解出 64MB+)。
71
+ limit := int64(memSize) + cromMaxTrailer
72
+ limited := io.LimitReader(r, limit+1)
73
+ raw, err = io.ReadAll(limited)
74
+ _ = r.Close()
75
+ if err != nil {
76
+ return nil, 0, false
77
+ }
78
+ } else {
79
+ raw = payload
80
+ }
81
+ // mem_size 是物理内存长度; 之后允许跟一段 MMU 页表尾部元数据
82
+ if uint32(len(raw)) < memSize || len(raw) > int(memSize)+cromMaxTrailer {
83
+ return nil, 0, false
84
+ }
85
+ return raw, int(flags), true
86
+ }
@@ -0,0 +1,93 @@
1
+ package engine
2
+
3
+ import (
4
+ "encoding/binary"
5
+ "fmt"
6
+ "math"
7
+
8
+ "codecin-native/ir"
9
+ )
10
+
11
+ // UCBC 字节码编码 (与 Python codecin/native.py encode_program 严格一致)。
12
+ const (
13
+ bcMagic = "UCBC"
14
+ bcVersion = 1
15
+ )
16
+
17
+ // condCode: 条件助记符 -> 编号 (与 Python Cond.NAMES 一致)
18
+ var condCode = map[string]uint8{
19
+ "EQ": 0, "NE": 1, "CS": 2, "CC": 3, "MI": 4, "PL": 5, "VS": 6, "VC": 7,
20
+ "HI": 8, "LS": 9, "GE": 10, "LT": 11, "GT": 12, "LE": 13, "AL": 14, "NV": 15,
21
+ }
22
+
23
+ // EncodeProgram 把 IR 程序编码为 UCBC 字节码。
24
+ func EncodeProgram(prog ir.Program, entry int) ([]byte, error) {
25
+ labels := map[string]int{}
26
+ for k, v := range prog.Labels {
27
+ labels[k] = v
28
+ }
29
+ for k, v := range prog.DataLabels {
30
+ labels[k] = v
31
+ }
32
+
33
+ buf := make([]byte, 0, 13+len(prog.Instructions)*8)
34
+ buf = append(buf, bcMagic...)
35
+ buf = append(buf, bcVersion)
36
+ var tmp [8]byte
37
+ binary.LittleEndian.PutUint32(tmp[:4], uint32(entry&0xFFFFFFFF))
38
+ buf = append(buf, tmp[:4]...)
39
+ binary.LittleEndian.PutUint32(tmp[:4], uint32(len(prog.Instructions)&0xFFFFFFFF))
40
+ buf = append(buf, tmp[:4]...)
41
+
42
+ for _, ins := range prog.Instructions {
43
+ opv, ok := opcodeByName[ins.Op]
44
+ if !ok {
45
+ return nil, fmt.Errorf("unknown opcode: %s", ins.Op)
46
+ }
47
+ buf = append(buf, opv, byte(len(ins.Args)))
48
+ for _, a := range ins.Args {
49
+ kind, value, extra, err := encodeOperand(a, labels)
50
+ if err != nil {
51
+ return nil, err
52
+ }
53
+ buf = append(buf, kind)
54
+ binary.LittleEndian.PutUint64(tmp[:8], uint64(value))
55
+ buf = append(buf, tmp[:8]...)
56
+ binary.LittleEndian.PutUint64(tmp[:8], uint64(extra))
57
+ buf = append(buf, tmp[:8]...)
58
+ }
59
+ }
60
+ return buf, nil
61
+ }
62
+
63
+ func encodeOperand(op ir.Operand, labels map[string]int) (kind uint8, value, extra int64, err error) {
64
+ switch op.Kind {
65
+ case "reg":
66
+ return kindReg, op.V, 0, nil
67
+ case "imm":
68
+ return kindImm, op.V, 0, nil
69
+ case "vec":
70
+ return kindVec, op.V, 0, nil
71
+ case "veclane":
72
+ return kindVecLane, op.V, op.Off, nil
73
+ case "mem":
74
+ return kindMem, op.V, op.Off, nil
75
+ case "cond":
76
+ c, ok := condCode[op.Name]
77
+ if !ok {
78
+ return 0, 0, 0, fmt.Errorf("unknown cond: %s", op.Name)
79
+ }
80
+ return kindCond, int64(c), 0, nil
81
+ case "float":
82
+ return kindFloat, int64(math.Float64bits(op.F)), 0, nil
83
+ case "str":
84
+ return kindStr, op.V, 0, nil
85
+ case "label":
86
+ addr, ok := labels[op.Name]
87
+ if !ok {
88
+ return 0, 0, 0, fmt.Errorf("undefined label: %s", op.Name)
89
+ }
90
+ return kindImm, int64(addr), 0, nil
91
+ }
92
+ return 0, 0, 0, fmt.Errorf("unknown operand kind: %s", op.Kind)
93
+ }
@@ -0,0 +1,198 @@
1
+ package engine
2
+
3
+ import (
4
+ "bytes"
5
+ "compress/zlib"
6
+ "hash/crc32"
7
+ "strings"
8
+ "testing"
9
+
10
+ "codecin-native/ir"
11
+ )
12
+
13
+ // 锁定 docs/SUGGESTIONS.md 批次 B 的引擎侧加固:
14
+ // * decodeBytecode 不再信任不可信头部 (版本 / count / argc / opcode);
15
+ // * 步数用尽报错误而不是伪装成正常停机;
16
+ // * CROM 解压有上限 (zip bomb) 且 mem_size 必须自洽。
17
+
18
+ func tinyProgram() ir.Program {
19
+ return ir.Program{
20
+ Instructions: []ir.Instr{
21
+ {Op: "MOV", Args: []ir.Operand{ir.Reg(0), ir.Imm(42)}},
22
+ {Op: "HALT"},
23
+ },
24
+ Labels: map[string]int{"main": 0},
25
+ DataLabels: map[string]int{},
26
+ }
27
+ }
28
+
29
+ func TestEncodeRunRoundTrip(t *testing.T) {
30
+ prog := tinyProgram()
31
+ bc, err := EncodeProgram(prog, 0)
32
+ if err != nil {
33
+ t.Fatalf("encode: %v", err)
34
+ }
35
+ mem := make([]byte, 4096)
36
+ sp := int64(len(mem) - 8)
37
+ res := Run(bc, mem, 0, sp, int64(len(mem)/2), nil, 1000)
38
+ if res == nil {
39
+ t.Fatal("Run 返回 nil")
40
+ }
41
+ if res.ErrMsg != "" {
42
+ t.Fatalf("意外错误: %s", res.ErrMsg)
43
+ }
44
+ if res.Regs[0] != 42 {
45
+ t.Fatalf("R0 = %d, 期望 42", res.Regs[0])
46
+ }
47
+ }
48
+
49
+ func TestDecodeRejectsMalformedInput(t *testing.T) {
50
+ valid, err := EncodeProgram(tinyProgram(), 0)
51
+ if err != nil {
52
+ t.Fatalf("encode: %v", err)
53
+ }
54
+ if _, _, ok := decodeBytecode(valid); !ok {
55
+ t.Fatal("合法字节码被拒绝")
56
+ }
57
+
58
+ cases := []struct {
59
+ name string
60
+ bc []byte
61
+ }{
62
+ {"empty", []byte{}},
63
+ {"bad_magic", append([]byte("XXXX"), valid[4:]...)},
64
+ {"short", valid[:6]},
65
+ }
66
+ for _, c := range cases {
67
+ if _, _, ok := decodeBytecode(c.bc); ok {
68
+ t.Errorf("%s: 畸形字节码被接受", c.name)
69
+ }
70
+ }
71
+
72
+ // 版本字节
73
+ badVer := append([]byte{}, valid...)
74
+ badVer[4] = 99
75
+ if _, _, ok := decodeBytecode(badVer); ok {
76
+ t.Error("未知版本被接受")
77
+ }
78
+
79
+ // count 声明远超实际长度 (旧实现按 count 预分配 -> OOM)
80
+ huge := []byte{'U', 'C', 'B', 'C', 1, 0, 0, 0, 0, 0xFF, 0xFF, 0xFF, 0xFF}
81
+ if _, _, ok := decodeBytecode(huge); ok {
82
+ t.Error("超大 count 被接受")
83
+ }
84
+
85
+ // argc 与操作码不匹配 (MOV 需要 2 个操作数, 这里声明 0 个)
86
+ argcBad := []byte{'U', 'C', 'B', 'C', 1, 0, 0, 0, 0, 1, 0, 0, 0, opMOV, 0}
87
+ if _, _, ok := decodeBytecode(argcBad); ok {
88
+ t.Error("argc 不匹配的字节码被接受")
89
+ }
90
+
91
+ // 未定义 opcode
92
+ opBad := []byte{'U', 'C', 'B', 'C', 1, 0, 0, 0, 0, 1, 0, 0, 0, 250, 0}
93
+ if _, _, ok := decodeBytecode(opBad); ok {
94
+ t.Error("未知操作码被接受")
95
+ }
96
+ }
97
+
98
+ func TestStepLimitIsAnError(t *testing.T) {
99
+ // JMP 自身 = 死循环
100
+ prog := ir.Program{
101
+ Instructions: []ir.Instr{
102
+ {Op: "JMP", Args: []ir.Operand{ir.Label("loop")}},
103
+ {Op: "HALT"},
104
+ },
105
+ Labels: map[string]int{"loop": 0},
106
+ DataLabels: map[string]int{},
107
+ }
108
+ bc, err := EncodeProgram(prog, 0)
109
+ if err != nil {
110
+ t.Fatalf("encode: %v", err)
111
+ }
112
+ mem := make([]byte, 4096)
113
+ res := Run(bc, mem, 0, int64(len(mem)-8), int64(len(mem)/2), nil, 500)
114
+ if res == nil {
115
+ t.Fatal("Run 返回 nil")
116
+ }
117
+ if res.Status != StatusError {
118
+ t.Fatalf("步数用尽应返回 StatusError, 实际 status=%d", res.Status)
119
+ }
120
+ if !strings.Contains(res.ErrMsg, "limit") {
121
+ t.Fatalf("错误信息应提到 limit, 实际: %q", res.ErrMsg)
122
+ }
123
+ }
124
+
125
+ func TestCromRoundTrip(t *testing.T) {
126
+ data := []byte(strings.Repeat("codecin", 64))
127
+ for _, compress := range []bool{false, true} {
128
+ packed := CromPack(data, compress)
129
+ raw, flags, ok := CromUnpack(packed)
130
+ if !ok {
131
+ t.Fatalf("compress=%v: 解包失败", compress)
132
+ }
133
+ if !bytes.Equal(raw, data) {
134
+ t.Fatalf("compress=%v: 内容不一致", compress)
135
+ }
136
+ if compress && flags&0x01 == 0 {
137
+ t.Fatalf("compress=%v: flags 未标记压缩", compress)
138
+ }
139
+ }
140
+ }
141
+
142
+ func TestCromRejectsBadInput(t *testing.T) {
143
+ // magic / 版本
144
+ if _, _, ok := CromUnpack([]byte("XXXX................")); ok {
145
+ t.Error("坏 magic 被接受")
146
+ }
147
+ bad := CromPack([]byte("abc"), false)
148
+ bad[4] = 99
149
+ if _, _, ok := CromUnpack(bad); ok {
150
+ t.Error("未知版本被接受")
151
+ }
152
+ // CRC 破坏
153
+ bad2 := CromPack([]byte("abcdefgh"), true)
154
+ bad2[len(bad2)-1] ^= 0xFF
155
+ if _, _, ok := CromUnpack(bad2); ok {
156
+ t.Error("CRC 损坏被接受")
157
+ }
158
+ // zip bomb: 头部 mem_size 远小于实际解压长度
159
+ bomb := cromWithDeclaredSize(t, 1024, bytes.Repeat([]byte{0}, 8<<20))
160
+ if _, _, ok := CromUnpack(bomb); ok {
161
+ t.Error("zip bomb 被接受")
162
+ }
163
+ // mem_size 大于实际载荷
164
+ mismatch := cromWithDeclaredSize(t, 1<<20, []byte("short"))
165
+ if _, _, ok := CromUnpack(mismatch); ok {
166
+ t.Error("mem_size 与载荷不符被接受")
167
+ }
168
+ }
169
+
170
+ // cromWithDeclaredSize 手工构造头部 mem_size 与载荷不符的 CROM。
171
+ func cromWithDeclaredSize(t *testing.T, declared uint32, raw []byte) []byte {
172
+ t.Helper()
173
+ var buf bytes.Buffer
174
+ w := zlib.NewWriter(&buf)
175
+ if _, err := w.Write(raw); err != nil {
176
+ t.Fatalf("zlib write: %v", err)
177
+ }
178
+ if err := w.Close(); err != nil {
179
+ t.Fatalf("zlib close: %v", err)
180
+ }
181
+ payload := buf.Bytes()
182
+
183
+ out := make([]byte, 16+len(payload))
184
+ copy(out[0:4], "CROM")
185
+ out[4] = cromVersion
186
+ out[5] = byte(declared)
187
+ out[6] = byte(declared >> 8)
188
+ out[7] = byte(declared >> 16)
189
+ out[8] = byte(declared >> 24)
190
+ out[9] = 0x01 // 压缩
191
+ crc := crc32.ChecksumIEEE(payload)
192
+ out[10] = byte(crc)
193
+ out[11] = byte(crc >> 8)
194
+ out[12] = byte(crc >> 16)
195
+ out[13] = byte(crc >> 24)
196
+ copy(out[16:], payload)
197
+ return out
198
+ }