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,2238 @@
1
+ package compiler
2
+
3
+ import (
4
+ "encoding/binary"
5
+ "fmt"
6
+ "math"
7
+ "os"
8
+ "path/filepath"
9
+ "regexp"
10
+ "strings"
11
+
12
+ "codecin-native/ir"
13
+ )
14
+
15
+ // hostBuiltin 宿主能力内建 (表驱动): 名称 -> (SYS 号, 参数个数, 返回类型)。
16
+ type hostBuiltin struct {
17
+ sysID int64
18
+ nargs int
19
+ ret TypeKind
20
+ }
21
+
22
+ var hostBuiltins = map[string]hostBuiltin{
23
+ // 联网音频
24
+ "audio_play": {SysAUDIOPLAY, 1, kInt},
25
+ "audio_stop": {SysAUDIOSTOP, 0, kVoid},
26
+ "audio_volume": {SysAUDIOVOL, 1, kVoid},
27
+ "audio_wait": {SysAUDIOWAIT, 0, kVoid},
28
+ // 2D 绘图画布
29
+ "canvas": {SysCANVASNEW, 2, kVoid},
30
+ "set_color": {SysCANVASSET, 1, kVoid},
31
+ "fill_rect": {SysCANVASRECT, 4, kVoid},
32
+ "fill_circle": {SysCANVASCIRC, 3, kVoid},
33
+ "draw_line": {SysCANVASLINE, 4, kVoid},
34
+ "draw_text": {SysCANVASTEXT, 3, kVoid},
35
+ "save_png": {SysCANVASSAVE, 1, kInt},
36
+ "show_canvas": {SysCANVASSHOW, 0, kInt},
37
+ // 系统原生交互 (跨平台)
38
+ "file_read": {SysFILEREAD, 1, kString},
39
+ "file_write": {SysFILEWRITE, 2, kInt},
40
+ "file_append": {SysFILEAPPEND, 2, kInt},
41
+ "file_exists": {SysFILEEXISTS, 1, kInt},
42
+ "file_delete": {SysFILEDELETE, 1, kInt},
43
+ "file_size": {SysFILESIZE, 1, kInt},
44
+ "mkdir": {SysMKDIR, 1, kInt},
45
+ "dir_list": {SysDIRLIST, 1, kString},
46
+ "exec": {SysEXEC, 1, kInt},
47
+ "exec_output": {SysEXECOUTPUT, 1, kString},
48
+ "getenv": {SysGETENV, 1, kString},
49
+ "setenv": {SysSETENV, 2, kInt},
50
+ "os_name": {SysOSNAME, 0, kString},
51
+ "hostname": {SysHOSTNAME, 0, kString},
52
+ "username": {SysUSERNAME, 0, kString},
53
+ "cwd": {SysCWD, 0, kString},
54
+ "home_dir": {SysHOMEDIR, 0, kString},
55
+ // Termux API
56
+ "termux_available": {SysTERMUXAVAIL, 0, kInt},
57
+ "termux_notify": {SysTERMUXNOTIFY, 2, kInt},
58
+ "termux_toast": {SysTERMUXTOAST, 1, kInt},
59
+ "termux_clipboard_get": {SysTERMUXCLIPGET, 0, kString},
60
+ "termux_clipboard_set": {SysTERMUXCLIPSET, 1, kInt},
61
+ "termux_battery": {SysTERMUXBATTERY, 0, kString},
62
+ "termux_vibrate": {SysTERMUXVIBRATE, 1, kInt},
63
+ "termux_tts": {SysTERMUXTTS, 1, kInt},
64
+ "termux_location": {SysTERMUXLOCATION, 0, kString},
65
+ "termux_wifi_info": {SysTERMUXWIFI, 0, kString},
66
+ "termux_dialog": {SysTERMUXDIALOG, 1, kString},
67
+ "termux_sms_send": {SysTERMUXSMS, 2, kInt},
68
+ // 路径与文件系统扩展 (跨平台)
69
+ "path_join": {SysPATHJOIN, 2, kString},
70
+ "path_basename": {SysPATHBASENAME, 1, kString},
71
+ "path_dirname": {SysPATHDIRNAME, 1, kString},
72
+ "path_abs": {SysPATHABS, 1, kString},
73
+ "file_copy": {SysFILECOPY, 2, kInt},
74
+ "file_move": {SysFILEMOVE, 2, kInt},
75
+ "dir_remove": {SysDIRREMOVE, 1, kInt},
76
+ "is_dir": {SysISDIR, 1, kInt},
77
+ "file_mtime": {SysFILEMTIME, 1, kInt},
78
+ "temp_dir": {SysTEMPDIR, 0, kString},
79
+ "chdir": {SysCHDIR, 1, kInt},
80
+ // 时间与系统信息
81
+ "time_ms": {SysTIMEMS, 0, kInt},
82
+ "time_us": {SysTIMEUS, 0, kInt},
83
+ "time_ns": {SysTIMENS, 0, kInt},
84
+ "sleep_ms": {SysSLEEPMS, 1, kInt},
85
+ "cpu_count": {SysCPUCOUNT, 0, kInt},
86
+ "arch_name": {SysARCHNAME, 0, kString},
87
+ "mem_info": {SysMEMINFO, 0, kString},
88
+ "is_android": {SysISANDROID, 0, kInt},
89
+ // 网络 (HTTP/HTTPS)
90
+ "http_get": {SysHTTPGET, 1, kString},
91
+ "http_post": {SysHTTPPOST, 2, kString},
92
+ "download": {SysDOWNLOAD, 2, kInt},
93
+ // 编码与哈希
94
+ "sha256": {SysSHA256, 1, kString},
95
+ "base64_encode": {SysBASE64ENC, 1, kString},
96
+ "base64_decode": {SysBASE64DEC, 1, kString},
97
+ // 桌面集成 (剪贴板 / 通知 / 打开 URL)
98
+ "clipboard_get": {SysCLIPGET, 0, kString},
99
+ "clipboard_set": {SysCLIPSET, 1, kInt},
100
+ "notify": {SysNOTIFY, 2, kInt},
101
+ "open_url": {SysOPENURL, 1, kInt},
102
+ // Android / Termux 扩展
103
+ "android_intent": {SysANDROIDINTENT, 2, kInt},
104
+ "termux_call": {SysTERMUXCALL, 1, kInt},
105
+ "termux_share": {SysTERMUXSHARE, 1, kInt},
106
+ "termux_torch": {SysTERMUXTORCH, 1, kInt},
107
+ "termux_volume": {SysTERMUXVOLUME, 2, kInt},
108
+ "termux_brightness": {SysTERMUXBRIGHT, 1, kInt},
109
+ "termux_camera_photo": {SysTERMUXCAMERA, 1, kInt},
110
+ "termux_fingerprint": {SysTERMUXFINGER, 0, kString},
111
+ "termux_sensor": {SysTERMUXSENSOR, 1, kString},
112
+ // 键盘输入监听 (非阻塞轮询)
113
+ "key_hit": {SysKEYHIT, 0, kInt},
114
+ "get_key": {SysKEYGET, 0, kInt},
115
+ "key_flush": {SysKEYFLUSH, 0, kInt},
116
+ // GUI 窗口 (Windows Win32 / Linux X11, 其他平台优雅失败)
117
+ "gui_new": {SysGUINEW, 3, kInt},
118
+ "gui_update": {SysGUIUPDATE, 0, kInt},
119
+ "gui_close": {SysGUICLOSE, 0, kInt},
120
+ "gui_closed": {SysGUICLOSED, 0, kInt},
121
+ "gui_active": {SysGUIACTIVE, 0, kInt},
122
+ "mouse_x": {SysMOUSEX, 0, kInt},
123
+ "mouse_y": {SysMOUSEY, 0, kInt},
124
+ "mouse_button": {SysMOUSEBTN, 0, kInt},
125
+ // 虚拟键盘 (Windows 屏幕/触摸键盘 TabTip; 其他平台 -1)
126
+ "vkb_show": {SysVKBSHOW, 0, kInt},
127
+ "vkb_hide": {SysVKBHIDE, 0, kInt},
128
+ // 音频扩展 (播放进度与蜂鸣合成)
129
+ "audio_pos": {SysAUDIOPOS, 0, kInt},
130
+ "beep": {SysAUDIOBEEP, 2, kInt},
131
+ // 音频控制增强 (查询 / 暂停恢复 / 音量读取)
132
+ "audio_duration": {SysAUDIODUR, 0, kInt},
133
+ "audio_playing": {SysAUDIOPLAYING, 0, kInt},
134
+ "audio_pause": {SysAUDIOPAUSE, 0, kInt},
135
+ "audio_resume": {SysAUDIORESUME, 0, kInt},
136
+ "audio_level": {SysAUDIOLEVEL, 0, kInt},
137
+ // 命令行参数与行输入 (跨平台一致)
138
+ "arg_count": {SysARGC, 0, kInt},
139
+ "arg": {SysARGV, 1, kString},
140
+ "input_str": {SysREADLINE, 0, kString},
141
+ // FFI 动态库调用 (dlopen/dlsym/call, 最多 8 个 int64 参数)
142
+ "dlopen": {SysDLOPEN, 1, kInt},
143
+ "dlsym": {SysDLSYM, 2, kInt},
144
+ "ffi_call": {SysFFICALL, 3, kInt},
145
+ "ffi_callf": {SysFFICALLF, 3, kFloat},
146
+ "lib_close": {SysLIBCLOSE, 1, kInt},
147
+ // 网络: HTTP 请求扩展 (GET/POST 之外的自定义方法与头部)
148
+ "http_req": {SysHTTPREQ, 4, kString},
149
+ "http_code": {SysHTTPCODE, 0, kInt},
150
+ // 网络: TCP 客户端与服务端
151
+ "tcp_dial": {SysTCPDIAL, 2, kInt},
152
+ "tcp_send": {SysTCPSEND, 3, kInt},
153
+ "tcp_recv": {SysTCPRECV, 3, kInt},
154
+ "tcp_close": {SysTCPCLOSE, 1, kInt},
155
+ "tcp_listen": {SysTCPLISTEN, 1, kInt},
156
+ "tcp_accept": {SysTCPACCEPT, 1, kInt},
157
+ // 网络: UDP 数据报
158
+ "udp_open": {SysUDPOPEN, 1, kInt},
159
+ "udp_sendto": {SysUDPSENDTO, 5, kInt},
160
+ "udp_recvfrom": {SysUDPRECVFROM, 4, kInt},
161
+ "udp_close": {SysUDPCLOSE, 1, kInt},
162
+ // 网络: DNS 解析
163
+ "dns_lookup": {SysDNSLOOKUP, 1, kString},
164
+ }
165
+
166
+ func (c *compiler) emit(op string, args ...ir.Operand) {
167
+ c.res.Instructions = append(c.res.Instructions, ir.Instr{Op: op, Args: args})
168
+ }
169
+
170
+ // failf 记录第一条语义错误 (粘性), 由 Compile 在生成结束后统一返回。
171
+ // 错误文案与 Python 编译器 (codecin/cin.py) 保持一致, 便于差分测试断言。
172
+ func (c *compiler) failf(format string, args ...interface{}) {
173
+ if c.err == nil {
174
+ c.err = fmt.Errorf(format, args...)
175
+ }
176
+ }
177
+
178
+ func (c *compiler) label(name string) {
179
+ c.res.Labels[name] = len(c.res.Instructions)
180
+ }
181
+
182
+ func (c *compiler) newLabel(hint string) string {
183
+ c.labelCounter++
184
+ return fmt.Sprintf("_%s_%d", hint, c.labelCounter)
185
+ }
186
+
187
+ func (c *compiler) reg(n int) ir.Operand { return ir.Reg(n) }
188
+ func (c *compiler) imm(v int64) ir.Operand { return ir.Imm(v) }
189
+ func (c *compiler) lab(name string) ir.Operand { return ir.Label(name) }
190
+
191
+ // ---------------- 数据段 ----------------
192
+
193
+ func (c *compiler) allocData(nbytes, align int) int {
194
+ if align > 1 {
195
+ c.dataPtr = (c.dataPtr + align - 1) &^ (align - 1)
196
+ }
197
+ addr := c.dataPtr
198
+ c.dataPtr += nbytes
199
+ return addr
200
+ }
201
+
202
+ func (c *compiler) dataString(text string) int {
203
+ if addr, ok := c.heapStr[text]; ok {
204
+ return addr
205
+ }
206
+ data := append([]byte(text), 0)
207
+ addr := c.allocData(len(data), 1)
208
+ c.res.DataWrites = append(c.res.DataWrites, ir.DataWrite{Addr: addr, Data: data})
209
+ c.res.DataLabels[fmt.Sprintf("str_%x", addr)] = addr
210
+ c.heapStr[text] = addr
211
+ return addr
212
+ }
213
+
214
+ func (c *compiler) dataQword(value int64) int {
215
+ addr := c.allocData(8, 8)
216
+ var b [8]byte
217
+ binary.LittleEndian.PutUint64(b[:], uint64(value))
218
+ c.res.DataWrites = append(c.res.DataWrites, ir.DataWrite{Addr: addr, Data: b[:]})
219
+ return addr
220
+ }
221
+
222
+ func (c *compiler) layoutGlobals(globals []*GlobalVar) {
223
+ for _, gv := range globals {
224
+ t := gv.t
225
+ if isFixedArray(t) {
226
+ addr := c.allocData(typeSlots(t)*8, 8)
227
+ c.globalsSym[gv.name] = globalVar{t: t, addr: addr, isBlock: true}
228
+ gv.addr = addr
229
+ } else {
230
+ addr := c.allocData(8, 8)
231
+ c.globalsSym[gv.name] = globalVar{t: t, addr: addr, isBlock: false}
232
+ gv.addr = addr
233
+ if isStruct(t) {
234
+ sd := c.structs[t.Name]
235
+ block := c.allocData(sd.sizeSlots*8, 8)
236
+ var b [8]byte
237
+ binary.LittleEndian.PutUint64(b[:], uint64(block))
238
+ c.res.DataWrites = append(c.res.DataWrites, ir.DataWrite{Addr: addr, Data: b[:]})
239
+ }
240
+ }
241
+ }
242
+ }
243
+
244
+ // constValue 编译期常量求值, 返回 (类型, 原始位/地址)。
245
+ func (c *compiler) constValue(n *Node) (*Type, int64, error) {
246
+ switch n.Kind {
247
+ case "num":
248
+ if n.IsFloat {
249
+ return scalarT(kFloat), int64(math.Float64bits(n.Num)), nil
250
+ }
251
+ return scalarT(kInt), n.Ival, nil
252
+ case "bool":
253
+ v := int64(0)
254
+ if n.Bool {
255
+ v = 1
256
+ }
257
+ return scalarT(kBool), v, nil
258
+ case "str":
259
+ return scalarT(kString), int64(c.dataString(n.Str)), nil
260
+ case "var":
261
+ if v, ok := c.enums[n.Name]; ok {
262
+ // 枚举成员: 编译期整数常量 (可用于全局初始化与 case 标签)
263
+ return scalarT(kInt), v, nil
264
+ }
265
+ case "neg":
266
+ inner := n.A
267
+ if inner.Kind == "num" {
268
+ if inner.IsFloat {
269
+ return scalarT(kFloat), int64(math.Float64bits(-inner.Num)), nil
270
+ }
271
+ return scalarT(kInt), -inner.Ival, nil
272
+ }
273
+ case "bitnot":
274
+ ct, raw, err := c.constValue(n.A)
275
+ if err != nil {
276
+ return nil, 0, err
277
+ }
278
+ if ct.Kind != kInt && ct.Kind != kBool {
279
+ return nil, 0, fmt.Errorf("Bitwise NOT requires integer, got: %s", typeName(ct))
280
+ }
281
+ return scalarT(kInt), ^raw, nil
282
+ }
283
+ return nil, 0, fmt.Errorf("Non-constant global initializer: %s", n.Kind)
284
+ }
285
+
286
+ // constInt 求值 case 常量: 整数常量表达式 (支持枚举成员), 返回有符号 64 位值。
287
+ // 失败时已通过 failf 记录与 Python 侧一致的错误文案, ok=false。
288
+ func (c *compiler) constInt(n *Node) (int64, bool) {
289
+ ct, raw, err := c.constValue(n)
290
+ if err != nil {
291
+ c.failf("case value must be an integer constant")
292
+ return 0, false
293
+ }
294
+ if ct == nil || (ct.Kind != kInt && ct.Kind != kBool) {
295
+ c.failf("case value must be an integer constant, got: %s", typeName(ct))
296
+ return 0, false
297
+ }
298
+ return raw, true
299
+ }
300
+
301
+ func (c *compiler) emitGlobalsInit(globals []*GlobalVar) {
302
+ for _, gv := range globals {
303
+ addr := c.globalsSym[gv.name].addr
304
+ if gv.init != nil {
305
+ _, raw, err := c.constValue(gv.init)
306
+ if err != nil {
307
+ // 与 Python 编译器一致: 非常量初始化器直接报编译错误, 不静默算 0。
308
+ c.failf("%v", err)
309
+ return
310
+ }
311
+ var b [8]byte
312
+ binary.LittleEndian.PutUint64(b[:], uint64(raw))
313
+ c.res.DataWrites = append(c.res.DataWrites, ir.DataWrite{Addr: addr, Data: b[:]})
314
+ } else if gv.arrayLit != nil {
315
+ lit := gv.arrayLit
316
+ if lit.Is2D {
317
+ for i, row := range lit.ArrayLit {
318
+ for j, elem := range row {
319
+ _, raw, err := c.constValue(elem)
320
+ if err != nil {
321
+ c.failf("%v", err)
322
+ return
323
+ }
324
+ var b [8]byte
325
+ binary.LittleEndian.PutUint64(b[:], uint64(raw))
326
+ off := addr + (i*len(row)+j)*8
327
+ c.res.DataWrites = append(c.res.DataWrites, ir.DataWrite{Addr: off, Data: b[:]})
328
+ }
329
+ }
330
+ } else {
331
+ for i, elem := range lit.ArrayLit[0] {
332
+ _, raw, err := c.constValue(elem)
333
+ if err != nil {
334
+ c.failf("%v", err)
335
+ return
336
+ }
337
+ var b [8]byte
338
+ binary.LittleEndian.PutUint64(b[:], uint64(raw))
339
+ c.res.DataWrites = append(c.res.DataWrites, ir.DataWrite{Addr: addr + i*8, Data: b[:]})
340
+ }
341
+ }
342
+ }
343
+ }
344
+ }
345
+
346
+ // ---------------- 函数生成 ----------------
347
+
348
+ // genFunctionBody 生成函数体 (locals 带名字)。
349
+ func (c *compiler) genFunctionBody(f *FuncDef) {
350
+ c.funcDef = f
351
+ c.locals = map[string]localVar{}
352
+ c.breakLbls = nil
353
+ c.continueLbls = nil
354
+
355
+ localsInfo := c.prescanLocalsWithNames(f.body)
356
+ off := 0
357
+ for _, lv := range localsInfo {
358
+ slots := typeSlots(lv.t)
359
+ c.locals[lv.name] = localVar{t: lv.t, off: -(off + slots*8), isBlock: isFixedArray(lv.t)}
360
+ off += slots * 8
361
+ }
362
+ c.frameBytes = off
363
+
364
+ nargs := len(f.params)
365
+ for k, prm := range f.params {
366
+ poff := 16 + (nargs-1-k)*8
367
+ c.locals[prm.name] = localVar{t: prm.t, off: poff, isBlock: false}
368
+ }
369
+
370
+ c.label(f.name)
371
+ c.emit("PUSH", c.reg(29))
372
+ c.emit("MOV", c.reg(29), c.reg(32))
373
+ // 帧分配走 SYS ALLOCFRAME (带栈溢出防护), 与 Python 编译器逐字节一致:
374
+ // 此前直接 ADDI SP 减帧长, 局部大数组会把 SP 推到负地址 (越界/静默破坏内存)。
375
+ if c.frameBytes != 0 {
376
+ c.emit("MOV", c.reg(0), c.imm(int64(c.frameBytes)))
377
+ c.emit("SYS", c.imm(SysALLOCFRAME))
378
+ }
379
+
380
+ // struct 局部变量: 堆分配对象
381
+ for _, lv := range c.locals {
382
+ if isStruct(lv.t) && lv.off < 0 {
383
+ sd := c.structs[lv.t.Name]
384
+ c.emit("MOV", c.reg(0), c.imm(int64(sd.sizeSlots*8)))
385
+ c.emit("SYS", c.imm(SysMALLOC))
386
+ c.emit("MOV", c.reg(2), c.reg(0))
387
+ c.addrLocal(lv.off)
388
+ c.emit("SD", c.reg(2), ir.Mem(0, 0))
389
+ }
390
+ }
391
+
392
+ c.genStmts(f.body)
393
+ c.epilogue()
394
+ }
395
+
396
+ type namedLocal struct {
397
+ name string
398
+ t *Type
399
+ }
400
+
401
+ func (c *compiler) prescanLocalsWithNames(body []*Node) []namedLocal {
402
+ var found []namedLocal
403
+ seen := map[string]bool{}
404
+ var walk func([]*Node)
405
+ walk = func(stmts []*Node) {
406
+ for _, s := range stmts {
407
+ switch s.Kind {
408
+ case "decl":
409
+ for _, item := range s.List {
410
+ if seen[item.Name] {
411
+ continue
412
+ }
413
+ seen[item.Name] = true
414
+ found = append(found, namedLocal{name: item.Name, t: item.Type})
415
+ }
416
+ case "block":
417
+ walk(s.List)
418
+ case "if":
419
+ walk([]*Node{s.B})
420
+ if s.C != nil {
421
+ walk([]*Node{s.C})
422
+ }
423
+ case "while":
424
+ walk([]*Node{s.B})
425
+ case "dowhile":
426
+ walk([]*Node{s.A})
427
+ case "switch":
428
+ for _, br := range s.List {
429
+ walk(br.List)
430
+ }
431
+ case "for":
432
+ if s.A != nil && s.A.Kind == "decl" {
433
+ for _, item := range s.A.List {
434
+ if !seen[item.Name] {
435
+ seen[item.Name] = true
436
+ found = append(found, namedLocal{name: item.Name, t: item.Type})
437
+ }
438
+ }
439
+ }
440
+ walk([]*Node{s.D})
441
+ case "rangefor":
442
+ // 登记顺序必须与 Python _prescan_locals 相同 (影响槽位偏移):
443
+ // 元素变量 -> $rf<id>p -> $rf<id>e, 然后才遍历循环体。
444
+ hidNames := []string{s.Name,
445
+ fmt.Sprintf("$rf%dp", s.RangeID),
446
+ fmt.Sprintf("$rf%de", s.RangeID)}
447
+ hidTypes := []*Type{s.Type, scalarT(kInt), scalarT(kInt)}
448
+ for k := range hidNames {
449
+ if seen[hidNames[k]] {
450
+ continue
451
+ }
452
+ seen[hidNames[k]] = true
453
+ found = append(found, namedLocal{name: hidNames[k], t: hidTypes[k]})
454
+ }
455
+ walk([]*Node{s.D})
456
+ }
457
+ }
458
+ }
459
+ walk(body)
460
+ return found
461
+ }
462
+
463
+ func (c *compiler) epilogue() {
464
+ c.emit("MOV", c.reg(6), c.reg(29))
465
+ c.emit("MOV", c.reg(32), c.reg(6))
466
+ c.emit("POP", c.reg(29))
467
+ c.emit("RET")
468
+ }
469
+
470
+ func (c *compiler) addrLocal(off int) {
471
+ if off == 0 {
472
+ c.emit("MOV", c.reg(0), c.reg(29))
473
+ } else {
474
+ c.emit("ADDI", c.reg(0), c.reg(29), c.imm(int64(off)))
475
+ }
476
+ }
477
+
478
+ func (c *compiler) addrVar(name string) error {
479
+ if lv, ok := c.locals[name]; ok {
480
+ c.addrLocal(lv.off)
481
+ return nil
482
+ }
483
+ if gv, ok := c.globalsSym[name]; ok {
484
+ c.emit("MOV", c.reg(0), c.imm(int64(gv.addr)))
485
+ return nil
486
+ }
487
+ return fmt.Errorf("Undefined variable: %s", name)
488
+ }
489
+
490
+ // mustAddrVar 是 addrVar 的报错版本: 未定义变量不再被静默吞掉。
491
+ func (c *compiler) mustAddrVar(name string) {
492
+ if err := c.addrVar(name); err != nil {
493
+ c.failf("%v", err)
494
+ }
495
+ }
496
+
497
+ func (c *compiler) varType(name string) *Type {
498
+ if lv, ok := c.locals[name]; ok {
499
+ return lv.t
500
+ }
501
+ if gv, ok := c.globalsSym[name]; ok {
502
+ return gv.t
503
+ }
504
+ return nil
505
+ }
506
+
507
+ // ---------------- 语句 ----------------
508
+
509
+ func (c *compiler) genStmts(stmts []*Node) {
510
+ for _, s := range stmts {
511
+ c.genStmt(s)
512
+ }
513
+ }
514
+
515
+ func (c *compiler) genStmt(s *Node) {
516
+ switch s.Kind {
517
+ case "block":
518
+ c.genStmts(s.List)
519
+ case "return":
520
+ if s.A != nil {
521
+ t := c.genValue(s.A)
522
+ c.convert(t, c.funcDef.retType)
523
+ }
524
+ c.epilogue()
525
+ case "if":
526
+ c.genIf(s.A, s.B, s.C)
527
+ case "while":
528
+ c.genWhile(s.A, s.B)
529
+ case "for":
530
+ c.genFor(s.A, s.B, s.C, s.D)
531
+ case "rangefor":
532
+ c.genRangeFor(s.Name, s.Type, s.A, s.D, s.RangeID)
533
+ case "dowhile":
534
+ c.genDowhile(s.A, s.B)
535
+ case "switch":
536
+ c.genSwitch(s.A, s.List)
537
+ case "break":
538
+ if len(c.breakLbls) == 0 {
539
+ c.failf("break outside loop")
540
+ return
541
+ }
542
+ c.emit("JMP", c.lab(c.breakLbls[len(c.breakLbls)-1]))
543
+ case "continue":
544
+ if len(c.continueLbls) == 0 {
545
+ c.failf("continue outside loop")
546
+ return
547
+ }
548
+ c.emit("JMP", c.lab(c.continueLbls[len(c.continueLbls)-1]))
549
+ case "decl":
550
+ c.genDecl(s.List)
551
+ case "cpu":
552
+ c.genCpuStmt(s.Name, s.Operands)
553
+ case "assert":
554
+ c.genAssert(s.A, s.B, s.Int, s.Filename)
555
+ case "expr":
556
+ c.genExprStmt(s.A)
557
+ }
558
+ }
559
+
560
+ func (c *compiler) genIf(cond, thenBody, elseBody *Node) {
561
+ lElse := c.newLabel("else")
562
+ lEnd := c.newLabel("endif")
563
+ target := lElse
564
+ if elseBody == nil {
565
+ target = lEnd
566
+ }
567
+ c.genCondJumpFalse(cond, target)
568
+ c.genStmt(thenBody)
569
+ if elseBody != nil {
570
+ c.emit("JMP", c.lab(lEnd))
571
+ c.label(lElse)
572
+ c.genStmt(elseBody)
573
+ }
574
+ c.label(lEnd)
575
+ }
576
+
577
+ func (c *compiler) genWhile(cond, body *Node) {
578
+ lStart := c.newLabel("while")
579
+ lEnd := c.newLabel("wend")
580
+ c.label(lStart)
581
+ c.genCondJumpFalse(cond, lEnd)
582
+ c.breakLbls = append(c.breakLbls, lEnd)
583
+ c.continueLbls = append(c.continueLbls, lStart)
584
+ c.genStmt(body)
585
+ c.emit("JMP", c.lab(lStart))
586
+ c.breakLbls = c.breakLbls[:len(c.breakLbls)-1]
587
+ c.continueLbls = c.continueLbls[:len(c.continueLbls)-1]
588
+ c.label(lEnd)
589
+ }
590
+
591
+ func (c *compiler) genFor(init, cond, update, body *Node) {
592
+ if init != nil {
593
+ c.genStmt(init)
594
+ }
595
+ lCond := c.newLabel("forc")
596
+ lUpdate := c.newLabel("foru")
597
+ lEnd := c.newLabel("fore")
598
+ c.label(lCond)
599
+ if cond != nil {
600
+ c.genCondJumpFalse(cond, lEnd)
601
+ }
602
+ c.breakLbls = append(c.breakLbls, lEnd)
603
+ c.continueLbls = append(c.continueLbls, lUpdate)
604
+ c.genStmt(body)
605
+ c.label(lUpdate)
606
+ if update != nil {
607
+ c.genStmt(update)
608
+ }
609
+ c.emit("JMP", c.lab(lCond))
610
+ c.breakLbls = c.breakLbls[:len(c.breakLbls)-1]
611
+ c.continueLbls = c.continueLbls[:len(c.continueLbls)-1]
612
+ c.label(lEnd)
613
+ }
614
+
615
+ // genRangeFor 生成 `for (T v : arr)` —— 遍历定长数组 (元素为 1 槽: 标量/struct/指针)。
616
+ //
617
+ // 展开为指针游走: p = &arr[0]; e = p + N*8;
618
+ // while (p < e) { v = *p; body; p += 8 }
619
+ // 指令序列必须与 Python 侧 gen_rangefor 逐字节一致。
620
+ func (c *compiler) genRangeFor(vname string, elemType *Type, arrExpr, body *Node, hid int) {
621
+ if isFixedArray(elemType) || isPtrArray(elemType) {
622
+ c.failf("range-for element type must be a scalar or struct, got: %s",
623
+ typeName(elemType))
624
+ return
625
+ }
626
+ at := c.exprType(arrExpr)
627
+ if !isFixedArray(at) {
628
+ c.failf("range-for requires a fixed-size array (element type of the "+
629
+ "iterated expression: %s)", typeName(at))
630
+ return
631
+ }
632
+ elemT, count := at.Elem, at.Size
633
+ if isFixedArray(elemT) {
634
+ c.failf("range-for over multi-dimensional arrays is not supported; " +
635
+ "use an index loop")
636
+ return
637
+ }
638
+ pname := fmt.Sprintf("$rf%dp", hid)
639
+ ename := fmt.Sprintf("$rf%de", hid)
640
+ lLoop := c.newLabel("rfloop")
641
+ lInc := c.newLabel("rfinc")
642
+ lEnd := c.newLabel("rfend")
643
+
644
+ // p = &arr[0] (定长数组取值即块地址)
645
+ c.genValue(arrExpr)
646
+ c.storeX0Local(pname)
647
+ // e = p + count*8
648
+ c.genVarValue(pname)
649
+ c.emit("ADDI", c.reg(0), c.reg(0), c.imm(int64(count*8)))
650
+ c.storeX0Local(ename)
651
+
652
+ c.label(lLoop)
653
+ // p >= e 时退出 (genCondJumpFalse 在条件为假时跳转)
654
+ loopCond := &Node{Kind: "binop", Op: "<"}
655
+ loopCond.A = &Node{Kind: "var", Name: pname}
656
+ loopCond.B = &Node{Kind: "var", Name: ename}
657
+ c.genCondJumpFalse(loopCond, lEnd)
658
+ // v = *p
659
+ c.genVarValue(pname)
660
+ c.emit("LD", c.reg(0), ir.Mem(0, 0))
661
+ c.convert(elemT, elemType)
662
+ c.storeX0Local(vname)
663
+ c.breakLbls = append(c.breakLbls, lEnd)
664
+ c.continueLbls = append(c.continueLbls, lInc)
665
+ c.genStmt(body)
666
+ c.breakLbls = c.breakLbls[:len(c.breakLbls)-1]
667
+ c.continueLbls = c.continueLbls[:len(c.continueLbls)-1]
668
+ // p += 8
669
+ c.label(lInc)
670
+ c.genVarValue(pname)
671
+ c.emit("ADDI", c.reg(0), c.reg(0), c.imm(8))
672
+ c.storeX0Local(pname)
673
+ c.emit("JMP", c.lab(lLoop))
674
+ c.label(lEnd)
675
+ }
676
+
677
+ // storeX0Local 把 x0 存入变量槽 (不破坏 x0 之外的约定)。
678
+ func (c *compiler) storeX0Local(name string) {
679
+ c.emit("MOV", c.reg(2), c.reg(0))
680
+ c.mustAddrVar(name)
681
+ c.emit("SD", c.reg(2), ir.Mem(0, 0))
682
+ }
683
+
684
+ func (c *compiler) genDowhile(body, cond *Node) {
685
+ lBody := c.newLabel("dbody")
686
+ lCond := c.newLabel("dcond")
687
+ lEnd := c.newLabel("dend")
688
+ c.label(lBody)
689
+ c.breakLbls = append(c.breakLbls, lEnd)
690
+ c.continueLbls = append(c.continueLbls, lCond)
691
+ c.genStmt(body)
692
+ c.label(lCond)
693
+ c.genCondJumpFalse(cond, lEnd)
694
+ c.emit("JMP", c.lab(lBody))
695
+ c.breakLbls = c.breakLbls[:len(c.breakLbls)-1]
696
+ c.continueLbls = c.continueLbls[:len(c.continueLbls)-1]
697
+ c.label(lEnd)
698
+ }
699
+
700
+ func (c *compiler) genSwitch(cond *Node, branches []*Node) {
701
+ selT := c.exprType(cond)
702
+ if selT == nil || (selT.Kind != kInt && selT.Kind != kBool) {
703
+ c.failf("Switch expression must be integer, got: %s", typeName(selT))
704
+ return
705
+ }
706
+ lEnd := c.newLabel("swend")
707
+ c.breakLbls = append(c.breakLbls, lEnd)
708
+ // continue 必须先把选择器弹出再跳转, 否则每轮迭代泄漏 8 字节栈直至撞堆。
709
+ // 只有在循环内 (存在外层 continue 目标) 才接管 continue, 否则保持
710
+ // "continue outside loop" 报错语义。
711
+ outerCont := ""
712
+ if n := len(c.continueLbls); n > 0 {
713
+ outerCont = c.continueLbls[n-1]
714
+ }
715
+ lCont := ""
716
+ if outerCont != "" {
717
+ lCont = c.newLabel("swcont")
718
+ c.continueLbls = append(c.continueLbls, lCont)
719
+ }
720
+ c.genValue(cond)
721
+ c.emit("PUSH", c.reg(0)) // [SP] = selector
722
+
723
+ type caseAlt struct {
724
+ isRange bool
725
+ lo, hi int64
726
+ }
727
+ type caseLabel struct {
728
+ alts []caseAlt
729
+ isDefault bool
730
+ lbl string
731
+ }
732
+ // labels 与 branches 严格一一对应: 任何分支都不会被跳过 (旧实现遇到
733
+ // 非常量 case 时 continue, 导致后续 case 的标签贴到别人的语句体上)。
734
+ labels := make([]caseLabel, 0, len(branches))
735
+ defaultLbl := ""
736
+ for _, br := range branches {
737
+ if br.Alts == nil {
738
+ lbl := c.newLabel("swdef")
739
+ defaultLbl = lbl
740
+ labels = append(labels, caseLabel{isDefault: true, lbl: lbl})
741
+ continue
742
+ }
743
+ var compiled []caseAlt
744
+ for _, alt := range br.Alts {
745
+ if alt.Kind == "caserange" {
746
+ lo, okLo := c.constInt(alt.A)
747
+ hi, okHi := c.constInt(alt.B)
748
+ if !okLo || !okHi {
749
+ continue
750
+ }
751
+ if lo > hi {
752
+ c.failf("Empty case range: %d..%d", lo, hi)
753
+ continue
754
+ }
755
+ compiled = append(compiled, caseAlt{isRange: true, lo: lo, hi: hi})
756
+ } else {
757
+ v, ok := c.constInt(alt.A)
758
+ if !ok {
759
+ continue
760
+ }
761
+ compiled = append(compiled, caseAlt{lo: v})
762
+ }
763
+ }
764
+ labels = append(labels, caseLabel{alts: compiled, lbl: c.newLabel("swcase")})
765
+ }
766
+
767
+ // 分派比较链 (多值/范围展开为多个比较, 顺序不影响语义)
768
+ for _, l := range labels {
769
+ if l.isDefault {
770
+ continue
771
+ }
772
+ for _, alt := range l.alts {
773
+ if !alt.isRange {
774
+ c.emit("LD", c.reg(0), ir.Mem(32, 0))
775
+ c.emit("MOV", c.reg(1), c.imm(alt.lo))
776
+ c.emit("CMP", c.reg(0), c.reg(1))
777
+ c.emit("B", c.lab(l.lbl), ir.Cond("EQ"))
778
+ continue
779
+ }
780
+ lSkip := c.newLabel("swrng")
781
+ c.emit("LD", c.reg(0), ir.Mem(32, 0))
782
+ c.emit("MOV", c.reg(1), c.imm(alt.lo))
783
+ c.emit("CMP", c.reg(0), c.reg(1))
784
+ c.emit("B", c.lab(lSkip), ir.Cond("LT"))
785
+ c.emit("LD", c.reg(0), ir.Mem(32, 0))
786
+ c.emit("MOV", c.reg(1), c.imm(alt.hi))
787
+ c.emit("CMP", c.reg(0), c.reg(1))
788
+ c.emit("B", c.lab(l.lbl), ir.Cond("LE"))
789
+ c.label(lSkip)
790
+ }
791
+ }
792
+ target := defaultLbl
793
+ if target == "" {
794
+ target = lEnd
795
+ }
796
+ c.emit("JMP", c.lab(target))
797
+
798
+ // case/default 体 (按文字顺序内联, C 贯穿语义)
799
+ for i, br := range branches {
800
+ c.label(labels[i].lbl)
801
+ c.genStmts(br.List)
802
+ }
803
+
804
+ // 贯穿到末尾与 break 都必须走弹出选择器的路径
805
+ c.emit("JMP", c.lab(lEnd))
806
+ if lCont != "" {
807
+ c.label(lCont)
808
+ c.emit("ADDI", c.reg(32), c.reg(32), c.imm(8))
809
+ c.emit("JMP", c.lab(outerCont))
810
+ c.continueLbls = c.continueLbls[:len(c.continueLbls)-1]
811
+ }
812
+ c.label(lEnd)
813
+ c.breakLbls = c.breakLbls[:len(c.breakLbls)-1]
814
+ c.emit("ADDI", c.reg(32), c.reg(32), c.imm(8)) // 丢 selector
815
+ }
816
+
817
+ func (c *compiler) genDecl(items []*Node) {
818
+ for _, item := range items {
819
+ if item.B != nil { // arrayLit
820
+ if item.B.Is2D {
821
+ c.genInit2dLiteral(item.Name, item.Type, item.B)
822
+ } else {
823
+ c.genInit1dLiteral(item.Name, item.Type, item.B)
824
+ }
825
+ continue
826
+ }
827
+ if item.A != nil { // init
828
+ vt := c.genValue(item.A)
829
+ c.convert(vt, item.Type)
830
+ c.emit("MOV", c.reg(2), c.reg(0))
831
+ c.mustAddrVar(item.Name)
832
+ c.emit("SD", c.reg(2), ir.Mem(0, 0))
833
+ } else if isPtrArray(item.Type) && item.Type.Elem != nil && isPtrArray(item.Type.Elem) {
834
+ c.emit("MOV", c.reg(0), c.imm(64*8))
835
+ c.emit("SYS", c.imm(SysMALLOC))
836
+ c.emit("MOV", c.reg(2), c.reg(0))
837
+ c.mustAddrVar(item.Name)
838
+ c.emit("SD", c.reg(2), ir.Mem(0, 0))
839
+ }
840
+ }
841
+ }
842
+
843
+ func (c *compiler) genInit1dLiteral(name string, t *Type, lit *Node) {
844
+ elemT := scalarT(kInt)
845
+ if isFixedArray(t) {
846
+ elemT = t.Elem
847
+ }
848
+ for i, elem := range lit.ArrayLit[0] {
849
+ vt := c.genValue(elem)
850
+ c.convert(vt, elemT)
851
+ c.emit("MOV", c.reg(2), c.reg(0))
852
+ c.mustAddrVar(name)
853
+ if i != 0 {
854
+ c.emit("ADDI", c.reg(0), c.reg(0), c.imm(int64(i*8)))
855
+ }
856
+ c.emit("SD", c.reg(2), ir.Mem(0, 0))
857
+ }
858
+ }
859
+
860
+ func (c *compiler) genInit2dLiteral(name string, t *Type, lit *Node) {
861
+ _ = t
862
+ nrows := len(lit.ArrayLit)
863
+ ncols := 0
864
+ for _, r := range lit.ArrayLit {
865
+ if len(r) > ncols {
866
+ ncols = len(r)
867
+ }
868
+ }
869
+ c.emit("MOV", c.reg(0), c.imm(int64(nrows*8)))
870
+ c.emit("SYS", c.imm(SysMALLOC))
871
+ c.emit("MOV", c.reg(4), c.reg(0))
872
+ for i, row := range lit.ArrayLit {
873
+ colCnt := ncols
874
+ if colCnt < 1 {
875
+ colCnt = 1
876
+ }
877
+ c.emit("MOV", c.reg(0), c.imm(int64(colCnt*8)))
878
+ c.emit("SYS", c.imm(SysMALLOC))
879
+ c.emit("MOV", c.reg(5), c.reg(0))
880
+ c.emit("MOV", c.reg(0), c.reg(4))
881
+ c.emit("ADDI", c.reg(0), c.reg(0), c.imm(int64(i*8)))
882
+ c.emit("SD", c.reg(5), ir.Mem(0, 0))
883
+ for j, elem := range row {
884
+ // x4 (outer) 与 x5 (当前行) 要跨元素表达式求值存活, 而元素里
885
+ // 可能有函数调用/嵌套下标 (会覆盖 x1..x6), 因此先存栈。
886
+ c.emit("PUSH", c.reg(4))
887
+ c.emit("PUSH", c.reg(5))
888
+ vt := c.genValue(elem)
889
+ c.convert(vt, scalarT(kInt))
890
+ c.emit("MOV", c.reg(2), c.reg(0)) // x2 = value
891
+ c.emit("POP", c.reg(5))
892
+ c.emit("POP", c.reg(4))
893
+ c.emit("MOV", c.reg(0), c.reg(5))
894
+ if j != 0 {
895
+ c.emit("ADDI", c.reg(0), c.reg(0), c.imm(int64(j*8)))
896
+ }
897
+ c.emit("SD", c.reg(2), ir.Mem(0, 0))
898
+ }
899
+ }
900
+ c.emit("MOV", c.reg(2), c.reg(4))
901
+ c.mustAddrVar(name)
902
+ c.emit("SD", c.reg(2), ir.Mem(0, 0))
903
+ }
904
+
905
+ func (c *compiler) genCpuStmt(op string, operands [][2]string) {
906
+ operandValue := func(kind, val string) (int64, string, bool) {
907
+ if kind == "NUMBER" {
908
+ var n int64
909
+ fmt.Sscanf(val, "%d", &n)
910
+ return n, "", true
911
+ }
912
+ if kind == "IDENT" {
913
+ return 0, val, false
914
+ }
915
+ return 0, "", false
916
+ }
917
+
918
+ if op == "increment" || op == "decrement" {
919
+ varname := operands[0][1]
920
+ c.mustAddrVar(varname)
921
+ c.emit("LD", c.reg(0), ir.Mem(0, 0))
922
+ if op == "increment" {
923
+ c.emit("INC", c.reg(0))
924
+ } else {
925
+ c.emit("DEC", c.reg(0))
926
+ }
927
+ c.emit("MOV", c.reg(2), c.reg(0))
928
+ c.mustAddrVar(varname)
929
+ c.emit("SD", c.reg(2), ir.Mem(0, 0))
930
+ return
931
+ }
932
+
933
+ varname := operands[0][1]
934
+ var rhsVal int64
935
+ rhsIsVar := false
936
+ var rhsVarName string
937
+ if len(operands) > 1 {
938
+ v, name, isNum := operandValue(operands[1][0], operands[1][1])
939
+ if isNum {
940
+ rhsVal = v
941
+ } else {
942
+ rhsIsVar = true
943
+ rhsVarName = name
944
+ }
945
+ }
946
+
947
+ if op == "set" {
948
+ if rhsIsVar {
949
+ c.genValue(&Node{Kind: "var", Name: rhsVarName})
950
+ } else {
951
+ c.emit("MOV", c.reg(0), c.imm(rhsVal))
952
+ }
953
+ } else {
954
+ c.mustAddrVar(varname)
955
+ c.emit("LD", c.reg(0), ir.Mem(0, 0))
956
+ if rhsIsVar {
957
+ c.emit("MOV", c.reg(2), c.reg(0))
958
+ c.genValue(&Node{Kind: "var", Name: rhsVarName})
959
+ c.emit("MOV", c.reg(1), c.reg(0))
960
+ c.emit("MOV", c.reg(0), c.reg(2))
961
+ } else {
962
+ c.emit("MOV", c.reg(1), c.imm(rhsVal))
963
+ }
964
+ opMap := map[string]string{"add": "ADD", "subtract": "SUB",
965
+ "multiply": "MUL", "divide": "DIV"}
966
+ if m, ok := opMap[op]; ok {
967
+ c.emit(m, c.reg(0), c.reg(1))
968
+ }
969
+ }
970
+ c.emit("MOV", c.reg(2), c.reg(0))
971
+ c.mustAddrVar(varname)
972
+ c.emit("SD", c.reg(2), ir.Mem(0, 0))
973
+ }
974
+
975
+ func (c *compiler) genExprStmt(node *Node) {
976
+ c.genValue(node)
977
+ }
978
+
979
+ func (c *compiler) runtimeAbort(text string) {
980
+ addr := c.dataString(text)
981
+ c.emit("MOV", c.reg(0), c.imm(int64(addr)))
982
+ c.emit("SYS", c.imm(SysABORT))
983
+ }
984
+
985
+ func (c *compiler) genAssert(cond, msg *Node, line int, filename string) {
986
+ lOk := c.newLabel("assertok")
987
+ c.genCondJumpTrue(cond, lOk)
988
+ if msg == nil {
989
+ fn := filename
990
+ if fn == "" {
991
+ fn = c.filename
992
+ }
993
+ c.runtimeAbort(fmt.Sprintf("%s:%d: assertion failed", fn, line))
994
+ } else {
995
+ fn := filename
996
+ if fn == "" {
997
+ fn = c.filename
998
+ }
999
+ prefix := c.dataString(fmt.Sprintf("[assert %s:%d] ", fn, line))
1000
+ c.emit("MOV", c.reg(0), c.imm(int64(prefix)))
1001
+ c.emit("PUSH", c.reg(0))
1002
+ c.genStringValue(msg)
1003
+ c.emit("MOV", c.reg(1), c.reg(0))
1004
+ c.emit("POP", c.reg(0))
1005
+ c.emit("SYS", c.imm(SysSTR_CONCAT))
1006
+ c.emit("SYS", c.imm(SysABORT))
1007
+ }
1008
+ c.label(lOk)
1009
+ }
1010
+
1011
+ // ---------------- 类型转换 ----------------
1012
+
1013
+ func sameType(a, b *Type) bool {
1014
+ if a == nil || b == nil {
1015
+ return a == b
1016
+ }
1017
+ if a.Kind != b.Kind {
1018
+ return false
1019
+ }
1020
+ switch a.Kind {
1021
+ case kArray:
1022
+ return a.Size == b.Size && sameType(a.Elem, b.Elem)
1023
+ case kPtrArray:
1024
+ return sameType(a.Elem, b.Elem)
1025
+ case kStruct:
1026
+ return a.Name == b.Name
1027
+ }
1028
+ return true
1029
+ }
1030
+
1031
+ func (c *compiler) convert(from, to *Type) {
1032
+ if to == nil || from == nil || sameType(from, to) {
1033
+ return
1034
+ }
1035
+ if from.Kind == kInt && to.Kind == kFloat {
1036
+ c.emit("SYS", c.imm(SysITOF))
1037
+ } else if from.Kind == kFloat && to.Kind == kInt {
1038
+ c.emit("SYS", c.imm(SysFTOI))
1039
+ } else if from.Kind == kBool && (to.Kind == kInt || to.Kind == kFloat) {
1040
+ if to.Kind == kFloat {
1041
+ c.emit("SYS", c.imm(SysITOF))
1042
+ }
1043
+ }
1044
+ // int->bool, string/struct/array 指针无需转换
1045
+ }
1046
+
1047
+ // ---------------- 表达式 ----------------
1048
+
1049
+ func (c *compiler) genValue(n *Node) *Type {
1050
+ switch n.Kind {
1051
+ case "num":
1052
+ if n.IsFloat {
1053
+ bits := int64(math.Float64bits(n.Num))
1054
+ c.emit("MOV", c.reg(0), c.imm(bits))
1055
+ return scalarT(kFloat)
1056
+ }
1057
+ c.emit("MOV", c.reg(0), c.imm(n.Ival))
1058
+ return scalarT(kInt)
1059
+ case "bool":
1060
+ v := int64(0)
1061
+ if n.Bool {
1062
+ v = 1
1063
+ }
1064
+ c.emit("MOV", c.reg(0), c.imm(v))
1065
+ return scalarT(kBool)
1066
+ case "str":
1067
+ c.emit("MOV", c.reg(0), c.imm(int64(c.dataString(n.Str))))
1068
+ return scalarT(kString)
1069
+ case "var":
1070
+ return c.genVarValue(n.Name)
1071
+ case "member":
1072
+ return c.genMember(n.A, n.Name, false)
1073
+ case "index":
1074
+ return c.genIndex(n.A, n.B, false)
1075
+ case "call":
1076
+ return c.genCall(n.Name, n.List)
1077
+ case "neg":
1078
+ t := c.genValue(n.A)
1079
+ c.emit("MOV", c.reg(1), c.reg(0))
1080
+ if t.Kind == kFloat {
1081
+ c.emit("MOV", c.reg(0), c.imm(0))
1082
+ c.emit("SYS", c.imm(SysITOF))
1083
+ c.emit("SYS", c.imm(SysFSUB))
1084
+ } else {
1085
+ c.emit("MOV", c.reg(0), c.imm(0))
1086
+ c.emit("SUB", c.reg(0), c.reg(1))
1087
+ }
1088
+ return t
1089
+ case "not":
1090
+ c.genValue(n.A)
1091
+ c.emit("XORI", c.reg(0), c.reg(0), c.imm(1))
1092
+ return scalarT(kBool)
1093
+ case "bitnot":
1094
+ t := c.genValue(n.A)
1095
+ if t == nil || (t.Kind != kInt && t.Kind != kBool) {
1096
+ c.failf("Bitwise NOT '~' requires an integer operand")
1097
+ return scalarT(kInt)
1098
+ }
1099
+ c.emit("MVN", c.reg(0), c.reg(0))
1100
+ return scalarT(kInt)
1101
+ case "preinc", "predec", "postinc", "postdec":
1102
+ return c.genIncdec(n.Kind, n.A)
1103
+ case "cond":
1104
+ return c.genTernary(n.A, n.B, n.C)
1105
+ case "binop":
1106
+ return c.genBinop(n.Op, n.A, n.B)
1107
+ }
1108
+ c.failf("Cannot generate code for expression: %s", n.Kind)
1109
+ return nil
1110
+ }
1111
+
1112
+ func (c *compiler) genVarValue(name string) *Type {
1113
+ if v, ok := c.enums[name]; ok {
1114
+ // 枚举成员: 编译期整数常量
1115
+ c.emit("MOV", c.reg(0), c.imm(v))
1116
+ return scalarT(kInt)
1117
+ }
1118
+ t := c.varType(name)
1119
+ if t == nil {
1120
+ return nil
1121
+ }
1122
+ isBlock := false
1123
+ if lv, ok := c.locals[name]; ok {
1124
+ isBlock = lv.isBlock
1125
+ } else if gv, ok := c.globalsSym[name]; ok {
1126
+ isBlock = gv.isBlock
1127
+ }
1128
+ if isBlock {
1129
+ c.mustAddrVar(name)
1130
+ return t
1131
+ }
1132
+ c.mustAddrVar(name)
1133
+ c.emit("LD", c.reg(0), ir.Mem(0, 0))
1134
+ return t
1135
+ }
1136
+
1137
+ func (c *compiler) genLvalueAddr(n *Node) {
1138
+ switch n.Kind {
1139
+ case "var":
1140
+ if _, ok := c.enums[n.Name]; ok {
1141
+ c.failf("Cannot assign to enum member: %s (constants are read-only)", n.Name)
1142
+ return
1143
+ }
1144
+ c.mustAddrVar(n.Name)
1145
+ case "member":
1146
+ c.genMember(n.A, n.Name, true)
1147
+ case "index":
1148
+ c.genIndex(n.A, n.B, true)
1149
+ }
1150
+ }
1151
+
1152
+ func (c *compiler) structField(structT *Type, fname string) (*Type, int, bool) {
1153
+ sd := c.structs[structT.Name]
1154
+ off, ok := sd.offsets[fname]
1155
+ if !ok {
1156
+ return nil, 0, false
1157
+ }
1158
+ for _, f := range sd.fields {
1159
+ if f.name == fname {
1160
+ return f.t, off, true
1161
+ }
1162
+ }
1163
+ return nil, 0, false
1164
+ }
1165
+
1166
+ func (c *compiler) decay(t *Type) *Type {
1167
+ if isFixedArray(t) {
1168
+ elem := t.Elem
1169
+ if isFixedArray(elem) {
1170
+ return &Type{Kind: kArray, Elem: elem, Size: t.Size}
1171
+ }
1172
+ return &Type{Kind: kPtrArray, Elem: elem}
1173
+ }
1174
+ return t
1175
+ }
1176
+
1177
+ func (c *compiler) genMember(objNode *Node, fname string, lvalue bool) *Type {
1178
+ objT := c.genValue(objNode)
1179
+ if !isStruct(objT) {
1180
+ c.failf("Member access on non-struct type: %s", typeName(objT))
1181
+ return nil
1182
+ }
1183
+ ftype, foff, ok := c.structField(objT, fname)
1184
+ if !ok {
1185
+ c.failf("Struct %s has no field %s", objT.Name, fname)
1186
+ return nil
1187
+ }
1188
+ if lvalue {
1189
+ if foff != 0 {
1190
+ c.emit("ADDI", c.reg(0), c.reg(0), c.imm(int64(foff*8)))
1191
+ }
1192
+ return nil
1193
+ }
1194
+ if isFixedArray(ftype) {
1195
+ if foff != 0 {
1196
+ c.emit("ADDI", c.reg(0), c.reg(0), c.imm(int64(foff*8)))
1197
+ }
1198
+ return c.decay(ftype)
1199
+ }
1200
+ c.emit("MOV", c.reg(1), c.reg(0))
1201
+ if foff != 0 {
1202
+ c.emit("ADDI", c.reg(1), c.reg(1), c.imm(int64(foff*8)))
1203
+ }
1204
+ c.emit("LD", c.reg(0), ir.Mem(1, 0))
1205
+ return ftype
1206
+ }
1207
+
1208
+ func (c *compiler) genIndex(baseNode, idxNode *Node, lvalue bool) *Type {
1209
+ baseT := c.genValue(baseNode)
1210
+ if baseT != nil && baseT.Kind == kString {
1211
+ if lvalue {
1212
+ c.failf("Cannot assign to string index")
1213
+ return nil
1214
+ }
1215
+ // 基址必须存栈: 下标表达式里可能有嵌套下标/函数调用, 它们会覆盖
1216
+ // x1..x6。s[B[i]] 曾因此把字符串基址弄丢, 读出错误内存。
1217
+ c.emit("PUSH", c.reg(0))
1218
+ idxT := c.genValue(idxNode)
1219
+ c.convert(idxT, scalarT(kInt)) // 下标是 int 上下文
1220
+ c.emit("POP", c.reg(3))
1221
+ c.emit("ADD", c.reg(0), c.reg(3))
1222
+ c.emit("LB", c.reg(0), ir.Mem(0, 0))
1223
+ c.emit("ANDI", c.reg(0), c.reg(0), c.imm(0xFF))
1224
+ return scalarT(kInt)
1225
+ }
1226
+ if baseT == nil || (!isFixedArray(baseT) && !isPtrArray(baseT)) {
1227
+ c.failf("Indexing non-array type: %s", typeName(baseT))
1228
+ return nil
1229
+ }
1230
+ elemT := baseT.Elem
1231
+
1232
+ // 基址必须存栈, 不能用寄存器"暂存": 下标表达式里可能有嵌套下标或函数
1233
+ // 调用, 它们会覆盖 x1..x6。此前 base 放在 x3, 于是 A[B[i]] 的内层下标
1234
+ // 把 x3 改成 B 的基址, 外层 ADD 用 B 的基址当 A 的 —— 读错地址, 写的
1235
+ // 时候直接写坏别的内存 (静默, 不报错)。
1236
+ c.emit("PUSH", c.reg(0))
1237
+ idxT := c.genValue(idxNode)
1238
+ // 下标是 int 上下文 (与赋值/传参/返回一致): float 隐式截断为 int。
1239
+ // 缺这一步时 float 的 IEEE-754 位模式会被当作字节偏移直接乘 8,
1240
+ // 产生 0x0379_8000_0000_0000 之类的高位垃圾地址 (issue #1)。
1241
+ c.convert(idxT, scalarT(kInt))
1242
+ if c.bounds && isFixedArray(baseT) {
1243
+ size := baseT.Size
1244
+ lGe := c.newLabel("bndok")
1245
+ c.emit("CMP", c.reg(0), c.imm(0))
1246
+ c.emit("B", c.lab(lGe), ir.Cond("GE"))
1247
+ c.runtimeAbort("bounds-check: negative array index")
1248
+ c.label(lGe)
1249
+ lLt := c.newLabel("bndok")
1250
+ c.emit("CMP", c.reg(0), c.imm(int64(size)))
1251
+ c.emit("B", c.lab(lLt), ir.Cond("LT"))
1252
+ c.runtimeAbort(fmt.Sprintf("bounds-check: index >= length (%d)", size))
1253
+ c.label(lLt)
1254
+ }
1255
+
1256
+ scale := typeSlots(elemT) * 8
1257
+ c.emit("MOV", c.reg(1), c.imm(int64(scale)))
1258
+ c.emit("MUL", c.reg(0), c.reg(1))
1259
+ c.emit("POP", c.reg(3)) // x3 = base (存栈时压入的)
1260
+ c.emit("ADD", c.reg(0), c.reg(3))
1261
+
1262
+ if lvalue {
1263
+ return nil
1264
+ }
1265
+ if isFixedArray(elemT) {
1266
+ return elemT
1267
+ }
1268
+ if isPtrArray(elemT) {
1269
+ c.emit("MOV", c.reg(5), c.reg(0))
1270
+ c.emit("LD", c.reg(1), ir.Mem(5, 0))
1271
+ lDone := c.newLabel("rowdone")
1272
+ c.emit("CMP", c.reg(1), c.imm(0))
1273
+ c.emit("B", c.lab(lDone), ir.Cond("NE"))
1274
+ c.emit("MOV", c.reg(0), c.imm(64*8))
1275
+ c.emit("SYS", c.imm(SysMALLOC))
1276
+ c.emit("MOV", c.reg(1), c.reg(0))
1277
+ c.emit("SD", c.reg(1), ir.Mem(5, 0))
1278
+ c.label(lDone)
1279
+ c.emit("MOV", c.reg(0), c.reg(1))
1280
+ return elemT
1281
+ }
1282
+ c.emit("LD", c.reg(0), ir.Mem(0, 0))
1283
+ return elemT
1284
+ }
1285
+
1286
+ func (c *compiler) genAssign(target, valueNode *Node) *Type {
1287
+ vt := c.genValue(valueNode)
1288
+ tt := c.exprType(target)
1289
+ c.convert(vt, tt)
1290
+ // 左值地址求值可能覆盖 x1..x6 (例如 A[f(i)] = v), 值必须存栈。
1291
+ c.emit("PUSH", c.reg(0))
1292
+ c.genLvalueAddr(target)
1293
+ c.emit("POP", c.reg(2))
1294
+ c.emit("SD", c.reg(2), ir.Mem(0, 0))
1295
+ return tt
1296
+ }
1297
+
1298
+ func (c *compiler) exprType(n *Node) *Type {
1299
+ switch n.Kind {
1300
+ case "var":
1301
+ if _, ok := c.enums[n.Name]; ok {
1302
+ return scalarT(kInt)
1303
+ }
1304
+ return c.varType(n.Name)
1305
+ case "member":
1306
+ objT := c.exprType(n.A)
1307
+ if isStruct(objT) {
1308
+ ft, _, _ := c.structField(objT, n.Name)
1309
+ return ft
1310
+ }
1311
+ case "index":
1312
+ baseT := c.exprType(n.A)
1313
+ if baseT != nil && baseT.Kind == kString {
1314
+ return scalarT(kInt)
1315
+ }
1316
+ if isFixedArray(baseT) || isPtrArray(baseT) {
1317
+ return baseT.Elem
1318
+ }
1319
+ case "call":
1320
+ if f, ok := c.functions[n.Name]; ok {
1321
+ return f.retType
1322
+ }
1323
+ if n.Name == "min" || n.Name == "max" {
1324
+ at := c.exprType(n.List[0])
1325
+ bt := c.exprType(n.List[1])
1326
+ if at != nil && at.Kind == kFloat || bt != nil && bt.Kind == kFloat {
1327
+ return scalarT(kFloat)
1328
+ }
1329
+ return scalarT(kInt)
1330
+ }
1331
+ return c.builtinRetType(n.Name)
1332
+ case "num":
1333
+ if n.IsFloat {
1334
+ return scalarT(kFloat)
1335
+ }
1336
+ return scalarT(kInt)
1337
+ case "bool":
1338
+ return scalarT(kBool)
1339
+ case "str":
1340
+ return scalarT(kString)
1341
+ case "binop":
1342
+ switch n.Op {
1343
+ case "+=", "-=", "*=", "/=", "%=", "&=", "|=", "^=", "<<=", ">>=":
1344
+ return c.exprType(n.A)
1345
+ case "&", "|", "^", "<<", ">>":
1346
+ return scalarT(kInt)
1347
+ case "+", "-", "*", "%":
1348
+ lt := c.exprType(n.A)
1349
+ rt := c.exprType(n.B)
1350
+ if lt != nil && lt.Kind == kString || rt != nil && rt.Kind == kString {
1351
+ return scalarT(kString)
1352
+ }
1353
+ if lt != nil && lt.Kind == kFloat || rt != nil && rt.Kind == kFloat {
1354
+ return scalarT(kFloat)
1355
+ }
1356
+ return scalarT(kInt)
1357
+ case "/":
1358
+ return scalarT(kFloat)
1359
+ case "==", "!=", "<", ">", "<=", ">=", "&&", "||":
1360
+ return scalarT(kBool)
1361
+ }
1362
+ case "cond":
1363
+ lt := c.exprType(n.B)
1364
+ rt := c.exprType(n.C)
1365
+ ls := lt != nil && lt.Kind == kString
1366
+ rs := rt != nil && rt.Kind == kString
1367
+ if ls != rs {
1368
+ return scalarT(kInt)
1369
+ }
1370
+ if ls {
1371
+ return scalarT(kString)
1372
+ }
1373
+ if lt != nil && lt.Kind == kFloat || rt != nil && rt.Kind == kFloat {
1374
+ return scalarT(kFloat)
1375
+ }
1376
+ return scalarT(kInt)
1377
+ case "preinc", "predec", "postinc", "postdec":
1378
+ return c.exprType(n.A)
1379
+ case "neg":
1380
+ it := c.exprType(n.A)
1381
+ if it != nil && it.Kind == kFloat {
1382
+ return scalarT(kFloat)
1383
+ }
1384
+ return scalarT(kInt)
1385
+ case "not":
1386
+ return scalarT(kBool)
1387
+ case "bitnot":
1388
+ return scalarT(kInt)
1389
+ }
1390
+ return nil
1391
+ }
1392
+
1393
+ // ---------------- 二元运算 ----------------
1394
+
1395
+ func (c *compiler) genBinop(op string, left, right *Node) *Type {
1396
+ if op == "=" {
1397
+ return c.genAssign(left, right)
1398
+ }
1399
+ if base, ok := compoundToBase[op]; ok {
1400
+ return c.genCompound(left, base, right)
1401
+ }
1402
+ if op == "&&" || op == "||" {
1403
+ return c.genLogical(op, left, right)
1404
+ }
1405
+ if op == "&" || op == "|" || op == "^" || op == "<<" || op == ">>" {
1406
+ return c.genBitwise(op, left, right)
1407
+ }
1408
+ if op == "==" || op == "!=" || op == "<" || op == ">" || op == "<=" || op == ">=" {
1409
+ // 比较作为值表达式: 条件成立得 1, 否则 0
1410
+ lFalse := c.newLabel("cmpf")
1411
+ lEnd := c.newLabel("cmpe")
1412
+ c.genCondJumpFalse(&Node{Kind: "binop", Op: op, A: left, B: right}, lFalse)
1413
+ c.emit("MOV", c.reg(0), c.imm(1))
1414
+ c.emit("JMP", c.lab(lEnd))
1415
+ c.label(lFalse)
1416
+ c.emit("MOV", c.reg(0), c.imm(0))
1417
+ c.label(lEnd)
1418
+ return scalarT(kBool)
1419
+ }
1420
+
1421
+ lt := c.exprType(left)
1422
+ rt := c.exprType(right)
1423
+ if op == "+" && (lt != nil && lt.Kind == kString || rt != nil && rt.Kind == kString) {
1424
+ c.genStringValue(left)
1425
+ c.emit("PUSH", c.reg(0))
1426
+ c.genStringValue(right)
1427
+ c.emit("MOV", c.reg(1), c.reg(0))
1428
+ c.emit("POP", c.reg(0))
1429
+ c.emit("SYS", c.imm(SysSTR_CONCAT))
1430
+ return scalarT(kString)
1431
+ }
1432
+
1433
+ floatMode := lt != nil && lt.Kind == kFloat || rt != nil && rt.Kind == kFloat || op == "/"
1434
+ c.genValue(left)
1435
+ if floatMode && lt != nil && lt.Kind == kInt {
1436
+ c.emit("SYS", c.imm(SysITOF))
1437
+ }
1438
+ if floatMode && lt != nil && lt.Kind == kBool {
1439
+ c.emit("SYS", c.imm(SysITOF))
1440
+ }
1441
+ c.emit("PUSH", c.reg(0))
1442
+ c.genValue(right)
1443
+ if floatMode && rt != nil && (rt.Kind == kInt || rt.Kind == kBool) {
1444
+ c.emit("SYS", c.imm(SysITOF))
1445
+ }
1446
+ c.emit("MOV", c.reg(1), c.reg(0))
1447
+ c.emit("POP", c.reg(0))
1448
+
1449
+ if floatMode {
1450
+ sysMap := map[string]int64{"+": SysFADD, "-": SysFSUB, "*": SysFMUL, "/": SysFDIV}
1451
+ if op == "%" {
1452
+ c.failf("Float modulo not supported")
1453
+ return scalarT(kFloat)
1454
+ }
1455
+ c.emit("SYS", c.imm(sysMap[op]))
1456
+ return scalarT(kFloat)
1457
+ }
1458
+
1459
+ if op == "%" {
1460
+ c.emit("MOV", c.reg(2), c.reg(1))
1461
+ c.emit("PUSH", c.reg(0))
1462
+ c.emit("DIV", c.reg(0), c.reg(2))
1463
+ c.emit("MUL", c.reg(0), c.reg(2))
1464
+ c.emit("MOV", c.reg(1), c.reg(0))
1465
+ c.emit("POP", c.reg(0))
1466
+ c.emit("SUB", c.reg(0), c.reg(1))
1467
+ return scalarT(kInt)
1468
+ }
1469
+
1470
+ opMap := map[string]string{"+": "ADD", "-": "SUB", "*": "MUL"}
1471
+ if m, ok := opMap[op]; ok {
1472
+ c.emit(m, c.reg(0), c.reg(1))
1473
+ return scalarT(kInt)
1474
+ }
1475
+ c.failf("Unsupported int operator: %s", op)
1476
+ return scalarT(kInt)
1477
+ }
1478
+
1479
+ var compoundToBase = map[string]string{
1480
+ "+=": "+", "-=": "-", "*=": "*", "/=": "/", "%=": "%",
1481
+ "&=": "&", "|=": "|", "^=": "^", "<<=": "<<", ">>=": ">>",
1482
+ }
1483
+
1484
+ func (c *compiler) genLogical(op string, left, right *Node) *Type {
1485
+ lTrue := c.newLabel("lt")
1486
+ lFalse := c.newLabel("lf")
1487
+ lEnd := c.newLabel("le")
1488
+ if op == "&&" {
1489
+ c.genCondJumpFalse(left, lFalse)
1490
+ c.genCondJumpFalse(right, lFalse)
1491
+ } else {
1492
+ c.genCondJumpTrue(left, lTrue)
1493
+ c.genCondJumpTrue(right, lTrue)
1494
+ c.emit("JMP", c.lab(lFalse))
1495
+ }
1496
+ c.label(lTrue)
1497
+ c.emit("MOV", c.reg(0), c.imm(1))
1498
+ c.emit("JMP", c.lab(lEnd))
1499
+ c.label(lFalse)
1500
+ c.emit("MOV", c.reg(0), c.imm(0))
1501
+ c.label(lEnd)
1502
+ return scalarT(kBool)
1503
+ }
1504
+
1505
+ func (c *compiler) genBitwise(op string, left, right *Node) *Type {
1506
+ lt := c.exprType(left)
1507
+ rt := c.exprType(right)
1508
+ if lt != nil && (lt.Kind == kFloat || lt.Kind == kString) ||
1509
+ rt != nil && (rt.Kind == kFloat || rt.Kind == kString) {
1510
+ bad := lt
1511
+ if bad == nil || (bad.Kind != kFloat && bad.Kind != kString) {
1512
+ bad = rt
1513
+ }
1514
+ c.failf("Bitwise operator '%s' requires integer operands (got: %s)",
1515
+ op, typeName(bad))
1516
+ return scalarT(kInt)
1517
+ }
1518
+ c.genValue(left)
1519
+ c.emit("PUSH", c.reg(0))
1520
+ c.genValue(right)
1521
+ c.emit("MOV", c.reg(1), c.reg(0))
1522
+ c.emit("POP", c.reg(0))
1523
+ switch op {
1524
+ case "&":
1525
+ c.emit("AND", c.reg(0), c.reg(1))
1526
+ case "|":
1527
+ c.emit("OR", c.reg(0), c.reg(1))
1528
+ case "^":
1529
+ c.emit("XOR", c.reg(0), c.reg(1))
1530
+ case "<<":
1531
+ c.emit("SHL", c.reg(0), c.reg(1))
1532
+ case ">>":
1533
+ c.emit("ASR", c.reg(0), c.reg(0), c.reg(1))
1534
+ }
1535
+ return scalarT(kInt)
1536
+ }
1537
+
1538
+ func (c *compiler) genCompound(target *Node, op string, valueNode *Node) *Type {
1539
+ tt := c.exprType(target)
1540
+ if tt == nil || (tt.Kind != kInt && tt.Kind != kBool && tt.Kind != kFloat) {
1541
+ c.failf("Cannot apply '%s=' to type: %s", op, typeName(tt))
1542
+ return nil
1543
+ }
1544
+ if tt.Kind == kFloat && op != "+" && op != "-" && op != "*" && op != "/" {
1545
+ c.failf("Cannot apply '%s=' to float", op)
1546
+ return tt
1547
+ }
1548
+ floatMode := tt.Kind == kFloat
1549
+
1550
+ c.genLvalueAddr(target)
1551
+ c.emit("PUSH", c.reg(0))
1552
+ vt := c.genValue(valueNode)
1553
+ c.convert(vt, tt)
1554
+ c.emit("MOV", c.reg(1), c.reg(0))
1555
+ c.emit("LD", c.reg(2), ir.Mem(32, 0))
1556
+ c.emit("LD", c.reg(0), ir.Mem(2, 0))
1557
+
1558
+ if floatMode {
1559
+ fmap := map[string]int64{"+": SysFADD, "-": SysFSUB, "*": SysFMUL, "/": SysFDIV}
1560
+ c.emit("SYS", c.imm(fmap[op]))
1561
+ } else {
1562
+ switch op {
1563
+ case "+":
1564
+ c.emit("ADD", c.reg(0), c.reg(1))
1565
+ case "-":
1566
+ c.emit("SUB", c.reg(0), c.reg(1))
1567
+ case "*":
1568
+ c.emit("MUL", c.reg(0), c.reg(1))
1569
+ case "/":
1570
+ c.emit("DIV", c.reg(0), c.reg(1))
1571
+ case "%":
1572
+ c.emit("MOV", c.reg(3), c.reg(1))
1573
+ c.emit("PUSH", c.reg(0))
1574
+ c.emit("DIV", c.reg(0), c.reg(3))
1575
+ c.emit("MUL", c.reg(0), c.reg(3))
1576
+ c.emit("MOV", c.reg(1), c.reg(0))
1577
+ c.emit("POP", c.reg(0))
1578
+ c.emit("SUB", c.reg(0), c.reg(1))
1579
+ case "&":
1580
+ c.emit("AND", c.reg(0), c.reg(1))
1581
+ case "|":
1582
+ c.emit("OR", c.reg(0), c.reg(1))
1583
+ case "^":
1584
+ c.emit("XOR", c.reg(0), c.reg(1))
1585
+ case "<<":
1586
+ c.emit("SHL", c.reg(0), c.reg(1))
1587
+ case ">>":
1588
+ c.emit("ASR", c.reg(0), c.reg(0), c.reg(1))
1589
+ }
1590
+ }
1591
+
1592
+ c.emit("SD", c.reg(0), ir.Mem(2, 0))
1593
+ c.emit("ADDI", c.reg(32), c.reg(32), c.imm(8))
1594
+ return tt
1595
+ }
1596
+
1597
+ func (c *compiler) genIncdec(kind string, target *Node) *Type {
1598
+ tt := c.exprType(target)
1599
+ if tt == nil || (tt.Kind != kInt && tt.Kind != kBool && tt.Kind != kFloat) {
1600
+ return nil
1601
+ }
1602
+ op := "+"
1603
+ if kind == "predec" || kind == "postdec" {
1604
+ op = "-"
1605
+ }
1606
+ postfix := kind == "postinc" || kind == "postdec"
1607
+ floatMode := tt.Kind == kFloat
1608
+
1609
+ c.genLvalueAddr(target)
1610
+ c.emit("PUSH", c.reg(0))
1611
+ c.emit("LD", c.reg(2), ir.Mem(32, 0))
1612
+ c.emit("LD", c.reg(0), ir.Mem(2, 0))
1613
+ if postfix {
1614
+ c.emit("MOV", c.reg(5), c.reg(0))
1615
+ }
1616
+ if floatMode {
1617
+ c.emit("MOV", c.reg(0), c.imm(1))
1618
+ c.emit("SYS", c.imm(SysITOF))
1619
+ c.emit("MOV", c.reg(1), c.reg(0))
1620
+ c.emit("LD", c.reg(0), ir.Mem(2, 0))
1621
+ if op == "+" {
1622
+ c.emit("SYS", c.imm(SysFADD))
1623
+ } else {
1624
+ c.emit("SYS", c.imm(SysFSUB))
1625
+ }
1626
+ } else {
1627
+ c.emit("MOV", c.reg(1), c.imm(1))
1628
+ if op == "+" {
1629
+ c.emit("ADD", c.reg(0), c.reg(1))
1630
+ } else {
1631
+ c.emit("SUB", c.reg(0), c.reg(1))
1632
+ }
1633
+ }
1634
+ c.emit("SD", c.reg(0), ir.Mem(2, 0))
1635
+ c.emit("ADDI", c.reg(32), c.reg(32), c.imm(8))
1636
+ if postfix {
1637
+ c.emit("MOV", c.reg(0), c.reg(5))
1638
+ }
1639
+ return tt
1640
+ }
1641
+
1642
+ func (c *compiler) genMinmax(name string, args []*Node) *Type {
1643
+ at := c.exprType(args[0])
1644
+ bt := c.exprType(args[1])
1645
+ if at != nil && at.Kind == kString || bt != nil && bt.Kind == kString {
1646
+ return scalarT(kInt)
1647
+ }
1648
+ tt := scalarT(kInt)
1649
+ if at != nil && at.Kind == kFloat || bt != nil && bt.Kind == kFloat {
1650
+ tt = scalarT(kFloat)
1651
+ }
1652
+
1653
+ c.genValue(args[0])
1654
+ if tt.Kind == kFloat && at != nil && (at.Kind == kInt || at.Kind == kBool) {
1655
+ c.emit("SYS", c.imm(SysITOF))
1656
+ }
1657
+ c.emit("PUSH", c.reg(0))
1658
+ c.genValue(args[1])
1659
+ if tt.Kind == kFloat && bt != nil && (bt.Kind == kInt || bt.Kind == kBool) {
1660
+ c.emit("SYS", c.imm(SysITOF))
1661
+ }
1662
+ c.emit("MOV", c.reg(1), c.reg(0))
1663
+ c.emit("POP", c.reg(0))
1664
+
1665
+ cond := "LE"
1666
+ if name == "max" {
1667
+ cond = "GE"
1668
+ }
1669
+ if tt.Kind == kFloat {
1670
+ c.emit("MOV", c.reg(2), c.reg(0))
1671
+ c.emit("MOV", c.reg(3), c.reg(1))
1672
+ c.emit("SYS", c.imm(SysFCMP))
1673
+ c.emit("CMP", c.reg(0), c.imm(0))
1674
+ lKeep := c.newLabel("mmkeep")
1675
+ lDone := c.newLabel("mmdone")
1676
+ c.emit("B", c.lab(lKeep), ir.Cond(cond))
1677
+ c.emit("MOV", c.reg(0), c.reg(3))
1678
+ c.emit("JMP", c.lab(lDone))
1679
+ c.label(lKeep)
1680
+ c.emit("MOV", c.reg(0), c.reg(2))
1681
+ c.label(lDone)
1682
+ } else {
1683
+ c.emit("CMP", c.reg(0), c.reg(1))
1684
+ lKeep := c.newLabel("mmkeep")
1685
+ c.emit("B", c.lab(lKeep), ir.Cond(cond))
1686
+ c.emit("MOV", c.reg(0), c.reg(1))
1687
+ c.label(lKeep)
1688
+ }
1689
+ return tt
1690
+ }
1691
+
1692
+ func (c *compiler) genTernary(cond, a, b *Node) *Type {
1693
+ lt := c.exprType(a)
1694
+ rt := c.exprType(b)
1695
+ ls := lt != nil && lt.Kind == kString
1696
+ rs := rt != nil && rt.Kind == kString
1697
+ if ls != rs {
1698
+ return scalarT(kInt)
1699
+ }
1700
+ tt := scalarT(kInt)
1701
+ if ls {
1702
+ tt = scalarT(kString)
1703
+ } else if lt != nil && lt.Kind == kFloat || rt != nil && rt.Kind == kFloat {
1704
+ tt = scalarT(kFloat)
1705
+ }
1706
+ lFalse := c.newLabel("cndf")
1707
+ lEnd := c.newLabel("cnde")
1708
+ c.genCondJumpFalse(cond, lFalse)
1709
+ t1 := c.genValue(a)
1710
+ c.convert(t1, tt)
1711
+ c.emit("MOV", c.reg(6), c.reg(0))
1712
+ c.emit("JMP", c.lab(lEnd))
1713
+ c.label(lFalse)
1714
+ t2 := c.genValue(b)
1715
+ c.convert(t2, tt)
1716
+ c.emit("MOV", c.reg(6), c.reg(0))
1717
+ c.label(lEnd)
1718
+ c.emit("MOV", c.reg(0), c.reg(6))
1719
+ return tt
1720
+ }
1721
+
1722
+ // ---------------- 字符串化 ----------------
1723
+
1724
+ func (c *compiler) genStringValue(n *Node) {
1725
+ t := c.genValue(n)
1726
+ switch {
1727
+ case t != nil && t.Kind == kString:
1728
+ return
1729
+ case t != nil && t.Kind == kFloat:
1730
+ c.emit("SYS", c.imm(SysFTOA))
1731
+ case t != nil && t.Kind == kBool:
1732
+ c.emit("SYS", c.imm(SysBOOL_STR))
1733
+ default:
1734
+ c.emit("SYS", c.imm(SysITOA))
1735
+ }
1736
+ }
1737
+
1738
+ func (c *compiler) genPrint(n *Node, newline bool) {
1739
+ t := c.genValue(n)
1740
+ switch {
1741
+ case t != nil && t.Kind == kString:
1742
+ case t != nil && t.Kind == kFloat:
1743
+ c.emit("SYS", c.imm(SysFTOA))
1744
+ case t != nil && t.Kind == kBool:
1745
+ c.emit("SYS", c.imm(SysBOOL_STR))
1746
+ default:
1747
+ c.emit("SYS", c.imm(SysITOA))
1748
+ }
1749
+ c.emit("SYS", c.imm(SysPRINT_STR))
1750
+ if newline {
1751
+ c.emit("OUT", c.imm(10))
1752
+ }
1753
+ }
1754
+
1755
+ // ---------------- 函数调用 ----------------
1756
+
1757
+ func (c *compiler) builtinRetType(name string) *Type {
1758
+ if hb, ok := hostBuiltins[name]; ok {
1759
+ return scalarT(hb.ret)
1760
+ }
1761
+ switch name {
1762
+ case "sin", "cos", "tan", "sqrt", "pow", "floor", "ceil", "round":
1763
+ return scalarT(kFloat)
1764
+ case "strlen", "strcmp", "rand", "time", "abs", "input", "idiv", "atoi":
1765
+ return scalarT(kInt)
1766
+ case "strcpy", "int_to_str", "itoa", "float_to_str", "ftoa", "bool_to_str",
1767
+ "substr", "upper", "lower", "trim", "ltrim", "rtrim":
1768
+ return scalarT(kString)
1769
+ }
1770
+ return nil
1771
+ }
1772
+
1773
+ // builtinMinArgs 记录各内建函数最少参数个数, 与 Python 侧
1774
+ // codecin/cin.py: BUILTIN_MIN_ARGS 必须保持一致。
1775
+ // 缺失参数旧代码会直接索引越界 panic, 现在统一走编译错误通道。
1776
+ var builtinMinArgs = func() map[string]int {
1777
+ m := map[string]int{
1778
+ "println": 0, "print": 0,
1779
+ "sqrt": 1, "sin": 1, "cos": 1, "tan": 1,
1780
+ "floor": 1, "ceil": 1, "round": 1,
1781
+ "min": 2, "max": 2,
1782
+ "idiv": 2, "pow": 2,
1783
+ "abs": 1, "strlen": 1, "strcmp": 2, "strcpy": 1,
1784
+ "rand": 0, "srand": 1,
1785
+ "int_to_str": 1, "itoa": 1,
1786
+ "float_to_str": 1, "ftoa": 1,
1787
+ "bool_to_str": 1,
1788
+ "substr": 3, "indexof": 2,
1789
+ "upper": 1, "lower": 1,
1790
+ "trim": 1, "ltrim": 1, "rtrim": 1, "atoi": 1,
1791
+ "time": 0, "input": 0,
1792
+ }
1793
+ for name, hb := range hostBuiltins {
1794
+ m[name] = hb.nargs
1795
+ }
1796
+ return m
1797
+ }()
1798
+
1799
+ func (c *compiler) genCall(name string, args []*Node) *Type {
1800
+ if minArgs, ok := builtinMinArgs[name]; ok && len(args) < minArgs {
1801
+ c.failf("%s() expects at least %d argument(s), got %d",
1802
+ name, minArgs, len(args))
1803
+ return scalarT(kVoid)
1804
+ }
1805
+ if name == "println" || name == "print" {
1806
+ // 多参数: 依次字符串化输出 (无分隔符); 无参时 println 输出空行。
1807
+ // 单参数时与旧实现逐字节一致 (字符串化 + PRINT_STR [+ OUT 10])。
1808
+ for _, a := range args {
1809
+ c.genPrint(a, false)
1810
+ }
1811
+ if name == "println" || len(args) == 0 {
1812
+ c.emit("OUT", c.imm(10))
1813
+ }
1814
+ return scalarT(kVoid)
1815
+ }
1816
+
1817
+ mathUnary := map[string]int64{"sqrt": SysSQRT, "sin": SysSIN, "cos": SysCOS, "tan": SysTAN}
1818
+ if id, ok := mathUnary[name]; ok {
1819
+ at := c.genValue(args[0])
1820
+ if at.Kind == kInt {
1821
+ c.emit("SYS", c.imm(SysITOF))
1822
+ }
1823
+ c.emit("SYS", c.imm(id))
1824
+ return scalarT(kFloat)
1825
+ }
1826
+
1827
+ roundUnary := map[string]int64{"floor": SysFLOOR, "ceil": SysCEIL, "round": SysROUND}
1828
+ if id, ok := roundUnary[name]; ok {
1829
+ at := c.genValue(args[0])
1830
+ if at.Kind == kInt || at.Kind == kBool {
1831
+ c.emit("SYS", c.imm(SysITOF))
1832
+ }
1833
+ c.emit("SYS", c.imm(id))
1834
+ return scalarT(kFloat)
1835
+ }
1836
+
1837
+ if name == "min" || name == "max" {
1838
+ return c.genMinmax(name, args)
1839
+ }
1840
+
1841
+ if name == "idiv" {
1842
+ c.genValue(args[0])
1843
+ c.emit("PUSH", c.reg(0))
1844
+ c.genValue(args[1])
1845
+ c.emit("MOV", c.reg(1), c.reg(0))
1846
+ c.emit("POP", c.reg(0))
1847
+ c.emit("DIV", c.reg(0), c.reg(1))
1848
+ return scalarT(kInt)
1849
+ }
1850
+
1851
+ if name == "pow" {
1852
+ c.argFloat(args[0])
1853
+ c.emit("PUSH", c.reg(0))
1854
+ c.argFloat(args[1])
1855
+ c.emit("MOV", c.reg(1), c.reg(0))
1856
+ c.emit("POP", c.reg(0))
1857
+ c.emit("SYS", c.imm(SysPOW))
1858
+ return scalarT(kFloat)
1859
+ }
1860
+ if name == "abs" {
1861
+ c.genValue(args[0])
1862
+ c.emit("SYS", c.imm(SysABS))
1863
+ return scalarT(kInt)
1864
+ }
1865
+ if name == "strlen" {
1866
+ c.genValue(args[0])
1867
+ c.emit("SYS", c.imm(SysSTRLEN))
1868
+ return scalarT(kInt)
1869
+ }
1870
+ if name == "strcmp" {
1871
+ c.genValue(args[0])
1872
+ c.emit("PUSH", c.reg(0))
1873
+ c.genValue(args[1])
1874
+ c.emit("MOV", c.reg(1), c.reg(0))
1875
+ c.emit("POP", c.reg(0))
1876
+ c.emit("SYS", c.imm(SysSTRCMP))
1877
+ return scalarT(kInt)
1878
+ }
1879
+ if name == "strcpy" {
1880
+ c.genValue(args[0])
1881
+ c.emit("PUSH", c.reg(0))
1882
+ c.emit("MOV", c.reg(0), c.imm(int64(c.dataString(""))))
1883
+ c.emit("MOV", c.reg(1), c.reg(0))
1884
+ c.emit("POP", c.reg(0))
1885
+ c.emit("SYS", c.imm(SysSTR_CONCAT))
1886
+ return scalarT(kString)
1887
+ }
1888
+ if name == "rand" {
1889
+ c.emit("SYS", c.imm(SysRAND))
1890
+ return scalarT(kInt)
1891
+ }
1892
+ if name == "srand" {
1893
+ c.genValue(args[0])
1894
+ c.emit("SYS", c.imm(SysSRAND))
1895
+ return scalarT(kVoid)
1896
+ }
1897
+ if name == "int_to_str" || name == "itoa" {
1898
+ c.genValue(args[0])
1899
+ c.emit("SYS", c.imm(SysITOA))
1900
+ return scalarT(kString)
1901
+ }
1902
+ if name == "float_to_str" || name == "ftoa" {
1903
+ t := c.genValue(args[0])
1904
+ if t.Kind == kInt || t.Kind == kBool {
1905
+ c.emit("SYS", c.imm(SysITOF))
1906
+ }
1907
+ c.emit("SYS", c.imm(SysFTOA))
1908
+ return scalarT(kString)
1909
+ }
1910
+ if name == "bool_to_str" {
1911
+ c.genValue(args[0])
1912
+ c.emit("SYS", c.imm(SysBOOL_STR))
1913
+ return scalarT(kString)
1914
+ }
1915
+ if name == "substr" {
1916
+ c.genStringValue(args[0])
1917
+ c.emit("PUSH", c.reg(0))
1918
+ c.genValue(args[1])
1919
+ c.emit("PUSH", c.reg(0))
1920
+ c.genValue(args[2])
1921
+ c.emit("MOV", c.reg(2), c.reg(0))
1922
+ c.emit("POP", c.reg(1))
1923
+ c.emit("POP", c.reg(0))
1924
+ c.emit("SYS", c.imm(SysSUBSTR))
1925
+ return scalarT(kString)
1926
+ }
1927
+ if name == "indexof" {
1928
+ c.genStringValue(args[0])
1929
+ c.emit("PUSH", c.reg(0))
1930
+ c.genStringValue(args[1])
1931
+ c.emit("MOV", c.reg(1), c.reg(0))
1932
+ c.emit("POP", c.reg(0))
1933
+ c.emit("SYS", c.imm(SysINDEXOF))
1934
+ return scalarT(kInt)
1935
+ }
1936
+ if name == "upper" || name == "lower" {
1937
+ c.genStringValue(args[0])
1938
+ id := int64(SysTOUPPER)
1939
+ if name == "lower" {
1940
+ id = SysTOLOWER
1941
+ }
1942
+ c.emit("SYS", c.imm(id))
1943
+ return scalarT(kString)
1944
+ }
1945
+ if name == "trim" || name == "ltrim" || name == "rtrim" {
1946
+ c.genStringValue(args[0])
1947
+ id := map[string]int64{"trim": SysTRIM, "ltrim": SysLTRIM, "rtrim": SysRTRIM}[name]
1948
+ c.emit("SYS", c.imm(id))
1949
+ return scalarT(kString)
1950
+ }
1951
+ if name == "atoi" {
1952
+ c.genValue(args[0])
1953
+ c.emit("SYS", c.imm(SysATOI))
1954
+ return scalarT(kInt)
1955
+ }
1956
+ if name == "to_int" || name == "to_float" {
1957
+ // 显式类型转换: to_int 向零截断 (与 int x = 1.9 一致), to_float 提升。
1958
+ // 与 Python 编译器 (cin.py) 的同名内建语义逐一致。
1959
+ argT := c.genValue(args[0])
1960
+ target := scalarT(kInt)
1961
+ if name == "to_float" {
1962
+ target = scalarT(kFloat)
1963
+ }
1964
+ if argT == nil || (argT.Kind != kInt && argT.Kind != kFloat && argT.Kind != kBool) {
1965
+ got := "void"
1966
+ if argT != nil {
1967
+ got = typeName(argT)
1968
+ }
1969
+ c.failf("%s() expects a numeric argument, got %s", name, got)
1970
+ return nil
1971
+ }
1972
+ c.convert(argT, target)
1973
+ return target
1974
+ }
1975
+
1976
+ // 宿主能力 (表驱动): 音频 / 画布 / 系统交互 / Termux API
1977
+ if hb, ok := hostBuiltins[name]; ok {
1978
+ n := hb.nargs
1979
+ if n > len(args) {
1980
+ n = len(args)
1981
+ }
1982
+ c.genHostSys(hb.sysID, args[:n])
1983
+ return scalarT(hb.ret)
1984
+ }
1985
+
1986
+ if name == "time" {
1987
+ c.emit("SYS", c.imm(SysTIME))
1988
+ return scalarT(kInt)
1989
+ }
1990
+ if name == "input" {
1991
+ c.emit("MOV", c.reg(0), c.imm(0))
1992
+ return scalarT(kInt)
1993
+ }
1994
+
1995
+ // 用户函数
1996
+ fdef := c.functions[name]
1997
+ if fdef == nil {
1998
+ if name == "int" || name == "float" {
1999
+ c.failf("Unknown function: %s (hint: use to_%s(x) for explicit "+
2000
+ "conversion, or rely on implicit promotion in mixed "+
2001
+ "int/float expressions)", name, name)
2002
+ return nil
2003
+ }
2004
+ c.failf("Unknown function: %s", name)
2005
+ return nil
2006
+ }
2007
+ for k, arg := range args {
2008
+ at := c.genValue(arg)
2009
+ var ptype *Type
2010
+ if k < len(fdef.params) {
2011
+ ptype = paramPromote(fdef.params[k].t)
2012
+ }
2013
+ c.convert(at, ptype)
2014
+ c.emit("PUSH", c.reg(0))
2015
+ }
2016
+ c.emit("CALL", c.lab(name))
2017
+ nargs := len(args)
2018
+ if nargs > 0 {
2019
+ c.emit("ADDI", c.reg(6), c.reg(32), c.imm(int64(nargs*8)))
2020
+ c.emit("MOV", c.reg(32), c.reg(6))
2021
+ }
2022
+ return fdef.retType
2023
+ }
2024
+
2025
+ func paramPromote(t *Type) *Type {
2026
+ if isFixedArray(t) {
2027
+ return &Type{Kind: kPtrArray, Elem: t.Elem}
2028
+ }
2029
+ return t
2030
+ }
2031
+
2032
+ func (c *compiler) argFloat(n *Node) {
2033
+ t := c.genValue(n)
2034
+ if t.Kind == kInt || t.Kind == kBool {
2035
+ c.emit("SYS", c.imm(SysITOF))
2036
+ }
2037
+ }
2038
+
2039
+ func (c *compiler) genHostSys(sysID int64, args []*Node) {
2040
+ for _, a := range args {
2041
+ c.genValue(a)
2042
+ c.emit("PUSH", c.reg(0))
2043
+ }
2044
+ for i := len(args) - 1; i >= 0; i-- {
2045
+ c.emit("POP", c.reg(i))
2046
+ }
2047
+ c.emit("SYS", c.imm(sysID))
2048
+ }
2049
+
2050
+ // ---------------- 条件跳转 ----------------
2051
+
2052
+ var condFalseJump = map[string]string{
2053
+ "==": "NE", "!=": "EQ", "<": "GE", ">": "LE", "<=": "GT", ">=": "LT",
2054
+ }
2055
+
2056
+ func (c *compiler) genCondJumpFalse(n *Node, labelFalse string) {
2057
+ switch {
2058
+ case n.Kind == "bool":
2059
+ if !n.Bool {
2060
+ c.emit("JMP", c.lab(labelFalse))
2061
+ }
2062
+ return
2063
+ case n.Kind == "binop" && n.Op == "&&":
2064
+ c.genCondJumpFalse(n.A, labelFalse)
2065
+ c.genCondJumpFalse(n.B, labelFalse)
2066
+ return
2067
+ case n.Kind == "binop" && n.Op == "||":
2068
+ lTrue := c.newLabel("ortrue")
2069
+ c.genCondJumpTrue(n.A, lTrue)
2070
+ c.genCondJumpTrue(n.B, lTrue)
2071
+ c.emit("JMP", c.lab(labelFalse))
2072
+ c.label(lTrue)
2073
+ return
2074
+ case n.Kind == "not":
2075
+ c.genCondJumpTrue(n.A, labelFalse)
2076
+ return
2077
+ case n.Kind == "binop" && condFalseJump[n.Op] != "":
2078
+ op := n.Op
2079
+ lt := c.exprType(n.A)
2080
+ rt := c.exprType(n.B)
2081
+ floatMode := lt != nil && lt.Kind == kFloat || rt != nil && rt.Kind == kFloat
2082
+ c.genValue(n.A)
2083
+ if floatMode && lt != nil && (lt.Kind == kInt || lt.Kind == kBool) {
2084
+ c.emit("SYS", c.imm(SysITOF))
2085
+ }
2086
+ c.emit("PUSH", c.reg(0))
2087
+ c.genValue(n.B)
2088
+ if floatMode && rt != nil && (rt.Kind == kInt || rt.Kind == kBool) {
2089
+ c.emit("SYS", c.imm(SysITOF))
2090
+ }
2091
+ c.emit("MOV", c.reg(1), c.reg(0))
2092
+ c.emit("POP", c.reg(0))
2093
+ if floatMode {
2094
+ c.emit("SYS", c.imm(SysFCMP))
2095
+ c.emit("CMP", c.reg(0), c.imm(0))
2096
+ } else {
2097
+ c.emit("CMP", c.reg(0), c.reg(1))
2098
+ }
2099
+ c.emit("B", c.lab(labelFalse), ir.Cond(condFalseJump[op]))
2100
+ return
2101
+ }
2102
+ c.genValue(n)
2103
+ c.emit("CMP", c.reg(0), c.imm(0))
2104
+ c.emit("JZ", c.lab(labelFalse))
2105
+ }
2106
+
2107
+ func (c *compiler) genCondJumpTrue(n *Node, labelTrue string) {
2108
+ lFalse := c.newLabel("cf")
2109
+ c.genCondJumpFalse(n, lFalse)
2110
+ c.emit("JMP", c.lab(labelTrue))
2111
+ c.label(lFalse)
2112
+ }
2113
+
2114
+ // ---------------- 入口 ----------------
2115
+
2116
+ // Compile 编译 CIN 源码字符串, 返回 IR 程序。
2117
+ func Compile(source, filename string, bounds bool) (*ir.Program, error) {
2118
+ c := newCompiler(filename, bounds)
2119
+ toks, err := tokenize(source, filename)
2120
+ if err != nil {
2121
+ return nil, err
2122
+ }
2123
+ p := &parser{
2124
+ toks: toks,
2125
+ filename: filename,
2126
+ enums: map[string]int64{},
2127
+ enumTypes: map[string]bool{},
2128
+ }
2129
+ structs, globals, functions, funcOrder, enums, err := p.parseProgram()
2130
+ if err != nil {
2131
+ return nil, err
2132
+ }
2133
+ c.structs = structs
2134
+ c.globals = globals
2135
+ c.functions = functions
2136
+ c.enums = enums
2137
+
2138
+ c.layoutGlobals(globals)
2139
+ c.emitGlobalsInit(globals)
2140
+ c.emit("CALL", c.lab("main"))
2141
+ c.emit("HALT")
2142
+ for _, name := range funcOrder {
2143
+ c.genFunctionBody(functions[name])
2144
+ }
2145
+ if c.err != nil {
2146
+ return nil, c.err
2147
+ }
2148
+ return c.res, nil
2149
+ }
2150
+
2151
+ var importRe = regexp.MustCompile(`^import\s+["']([^"']+)["']\s*;?\s*$`)
2152
+
2153
+ // CompileFile 读取 .cin 文件并展开 import, 然后编译。
2154
+ func CompileFile(path, libDir string) (*ir.Program, error) {
2155
+ source, err := loadProgramSource(path, libDir)
2156
+ if err != nil {
2157
+ return nil, err
2158
+ }
2159
+ return Compile(source, path, false)
2160
+ }
2161
+
2162
+ func loadProgramSource(path, libDir string) (string, error) {
2163
+ real, err := filepath.Abs(path)
2164
+ if err != nil {
2165
+ return "", err
2166
+ }
2167
+ real, err = filepath.EvalSymlinks(real)
2168
+ if err != nil {
2169
+ real, _ = filepath.Abs(path)
2170
+ }
2171
+ var out []string
2172
+ loaded := map[string]bool{}
2173
+ active := map[string]bool{}
2174
+ var collect func(string) error
2175
+ collect = func(rp string) error {
2176
+ key := rp
2177
+ if active[key] {
2178
+ return fmt.Errorf("Circular import: %s", rp)
2179
+ }
2180
+ if loaded[key] {
2181
+ return nil
2182
+ }
2183
+ active[key] = true
2184
+ defer delete(active, key)
2185
+ data, err := os.ReadFile(rp)
2186
+ if err != nil {
2187
+ return err
2188
+ }
2189
+ // 去掉 BOM: Windows 编辑器写出的 .cin 带 EF BB BF 时, 首行 `import ...`
2190
+ // 匹配不上 importRe, 会报与真实原因无关的解析错误。
2191
+ text := strings.TrimPrefix(strings.ReplaceAll(string(data), "\r\n", "\n"), "\ufeff")
2192
+ for _, line := range strings.Split(text, "\n") {
2193
+ m := importRe.FindStringSubmatch(line)
2194
+ if m != nil {
2195
+ target := m[1]
2196
+ var candidates []string
2197
+ candidates = append(candidates, filepath.Join(filepath.Dir(rp), target))
2198
+ if libDir != "" {
2199
+ candidates = append(candidates, filepath.Join(libDir, target))
2200
+ }
2201
+ if filepath.Base(libDir) == "lib" {
2202
+ candidates = append(candidates, filepath.Join(filepath.Dir(libDir), target))
2203
+ }
2204
+ resolved := ""
2205
+ for _, cand := range candidates {
2206
+ if fi, e := os.Stat(cand); e == nil && !fi.IsDir() {
2207
+ resolved = cand
2208
+ break
2209
+ }
2210
+ }
2211
+ if resolved == "" {
2212
+ return fmt.Errorf("Import file not found: %q", target)
2213
+ }
2214
+ rr, e := filepath.Abs(resolved)
2215
+ if e == nil {
2216
+ if r2, e2 := filepath.EvalSymlinks(rr); e2 == nil {
2217
+ rr = r2
2218
+ }
2219
+ }
2220
+ if err := collect(rr); err != nil {
2221
+ return err
2222
+ }
2223
+ continue
2224
+ }
2225
+ out = append(out, line)
2226
+ }
2227
+ loaded[key] = true
2228
+ return nil
2229
+ }
2230
+ if err := collect(real); err != nil {
2231
+ return "", err
2232
+ }
2233
+ return strings.Join(out, "\n"), nil
2234
+ }
2235
+
2236
+ // 让 unused import 不报错 (math 等)。
2237
+ var _ = math.Float64bits
2238
+ var _ = os.Stat