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
codecin/cin.py ADDED
@@ -0,0 +1,4265 @@
1
+ """CIN 高级语言编译器。
2
+
3
+ 将 CIN 源码 (类 C 语法: 函数/struct/多维数组/字符串/浮点/控制流)
4
+ 编译为 Code CIN 字节码 IR。
5
+
6
+ 语法扩展 (2026):
7
+ - 语句: break/continue, do-while, switch/case/default (case 常量表达式)
8
+ - 表达式: ?: 三目 (短路), ++/-- 前缀与后缀, 复合赋值 += -= *= /= %=
9
+ - 字面量/类型: 0x/0b/0o 进制与 u/L/f 后缀、数字下划线、字符字面量 'a';
10
+ char/short/long/unsigned 类型别名 (64 位槽模型, 与 int 同宽)
11
+ - 内建: int_to_str/itoa, float_to_str/ftoa, bool_to_str
12
+
13
+ 运行时约定:
14
+ - 所有值均为 64 位槽: int 为有符号整数; float 为 float64 位模式;
15
+ bool 为 0/1; string/struct/数组为内存指针。
16
+ - 浮点运算经 SYS 宿主调用 (FADD/FSUB/...), 数学函数同理。
17
+ - 栈帧: [参数...][返回地址][局部变量/数组...] , SP 指向帧内最低地址。
18
+ - struct 采用浅拷贝语义 (变量保存对象指针, 堆分配, 不回收)。
19
+ - 定长数组就地存放 (数据段/栈帧); int[][] 为指向行指针数组的指针。
20
+ """
21
+
22
+ import fnmatch
23
+ import os
24
+ import re
25
+ import struct
26
+ from dataclasses import dataclass, field
27
+ from typing import Any, Dict, List, Optional, Set, Tuple
28
+
29
+ from .console import Console
30
+ from .errors import CompilerError
31
+ from .isa import Syscall
32
+
33
+ # ---------------- 类型表示 ----------------
34
+ # 'int' / 'float' / 'bool' / 'string' / 'void'
35
+ # ('struct', Name)
36
+ # ('array', elem_type, size) 定长数组 (多维: elem 仍为 array)
37
+ # ('ptrarray', elem_type) 动态/参数数组 (int[] / int[][])
38
+
39
+ SCALARS = {'int', 'float', 'bool', 'string', 'void'}
40
+
41
+ Operand = Tuple[Any, ...]
42
+ Instruction = Tuple[str, List[Operand]]
43
+
44
+
45
+ def _is_scalar(t) -> bool:
46
+ return isinstance(t, str)
47
+
48
+
49
+ def _is_struct(t) -> bool:
50
+ return isinstance(t, tuple) and t[0] == 'struct'
51
+
52
+
53
+ def _is_fixed_array(t) -> bool:
54
+ return isinstance(t, tuple) and t[0] == 'array'
55
+
56
+
57
+ def _is_ptr_array(t) -> bool:
58
+ return isinstance(t, tuple) and t[0] == 'ptrarray'
59
+
60
+
61
+ def _array_elem(t):
62
+ return t[1]
63
+
64
+
65
+ def _type_slots(t) -> int:
66
+ """类型占据的 qword 槽数。"""
67
+ if _is_fixed_array(t):
68
+ elem, size = t[1], t[2]
69
+ return size * _type_slots(elem)
70
+ return 1 # 标量/struct指针/ptrarray 均为 1 槽
71
+
72
+
73
+ def _has_struct(t) -> bool:
74
+ """类型内部是否含 struct (数组元素递归)。"""
75
+ if _is_struct(t):
76
+ return True
77
+ if _is_fixed_array(t):
78
+ return _has_struct(t[1])
79
+ return False
80
+
81
+
82
+ def _struct_slots(t, structs) -> int:
83
+ """struct **字段**占用的 qword 槽数。
84
+
85
+ 与 :func:`_type_slots` 不同: 变量槽里的 struct 值是指针(1 槽), 而结构体
86
+ 内部的嵌套 struct 字段是**按值内嵌**的, 必须按内层对象大小推进偏移。
87
+ 此前这里误用 1 槽, 导致 `struct Out { In i; int c }` 的 `c` 压到 `i.b` 上。
88
+ """
89
+ if _is_fixed_array(t):
90
+ return t[2] * _struct_slots(t[1], structs)
91
+ if _is_struct(t):
92
+ sd = structs.get(t[1])
93
+ if sd is None:
94
+ raise CompilerError(
95
+ f"Struct field of unknown type '{t[1]}'; the nested struct "
96
+ f"must be defined before it is used as a field type")
97
+ return sd.size_slots
98
+ return 1
99
+
100
+
101
+ def _trunc_div(a: int, b: int) -> int:
102
+ """向零截断的整数除法 (与字节码 DIV 语义一致)。"""
103
+ q = abs(a) // abs(b)
104
+ return q if (a < 0) == (b < 0) else -q
105
+
106
+
107
+ # ==================== 词法分析 ====================
108
+
109
+ _KEYWORDS = {
110
+ 'struct', 'function', 'return', 'if', 'else', 'while', 'for', 'do',
111
+ 'switch', 'case', 'default', 'break', 'continue', 'true', 'false',
112
+ 'int', 'float', 'bool', 'string', 'void', 'char', 'short', 'long',
113
+ 'unsigned', 'enum', 'extern',
114
+ 'set', 'add', 'subtract', 'multiply', 'divide', 'increment', 'decrement',
115
+ }
116
+
117
+ # 声明起始的标量类型词 (含新支持的类型别名, 均映射到 64 位槽 int 模型)
118
+ BASE_TYPE_WORDS = ('int', 'float', 'bool', 'string', 'char', 'short', 'long',
119
+ 'unsigned')
120
+
121
+ # 复合赋值: 词法 token -> C 风格运算符
122
+ _COMPOUND_ASSIGN = {
123
+ 'PLUSEQ': '+=', 'MINUSEQ': '-=', 'STAREQ': '*=',
124
+ 'SLASHEQ': '/=', 'PERCENTEQ': '%=',
125
+ 'ANDEQ': '&=', 'OREQ': '|=', 'XOREQ': '^=',
126
+ 'SHLEQ': '<<=', 'SHREQ': '>>=',
127
+ }
128
+
129
+ _SINGLE_OPS = {
130
+ '{': 'LBRACE', '}': 'RBRACE', '(': 'LPAREN', ')': 'RPAREN',
131
+ '[': 'LBRACKET', ']': 'RBRACKET', ',': 'COMMA', ';': 'SEMI',
132
+ '+': 'PLUS', '-': 'MINUS', '*': 'STAR', '/': 'SLASH', '%': 'PERCENT',
133
+ '=': 'ASSIGN', '<': 'LT', '>': 'GT', '!': 'BANG', '.': 'DOT',
134
+ '?': 'QUESTION', ':': 'COLON',
135
+ '&': 'AMP', '|': 'PIPE', '^': 'CARET', '~': 'TILDE',
136
+ }
137
+
138
+ # 复合赋值运算符 -> 底层运算符
139
+ _COMPOUND_TO_BASE = {
140
+ '+=': '+', '-=': '-', '*=': '*', '/=': '/', '%=': '%',
141
+ '&=': '&', '|=': '|', '^=': '^', '<<=': '<<', '>>=': '>>',
142
+ }
143
+
144
+ # 字符串/字符字面量的单字符转义 (含控制字符)
145
+ _STR_ESCAPES = {
146
+ 'n': '\n', 't': '\t', 'r': '\r', '0': '\0', 'a': '\a', 'b': '\b',
147
+ 'f': '\f', 'v': '\v', '"': '"', "'": "'", '\\': '\\',
148
+ }
149
+
150
+ _HEX_DIGITS = '0123456789abcdefABCDEF'
151
+
152
+ # 宿主能力内建 (表驱动): 名称 -> (SYS 功能号, 参数个数, 返回类型)。
153
+ # 全部由 Go 原生引擎实现; --sandbox 下宿主 SYS 被拦截并报明确错误。
154
+ HOST_BUILTINS = {
155
+ # 联网音频
156
+ 'audio_play': (Syscall.AUDIOPLAY, 1, 'int'),
157
+ 'audio_stop': (Syscall.AUDIOSTOP, 0, 'void'),
158
+ 'audio_volume': (Syscall.AUDIOVOL, 1, 'void'),
159
+ 'audio_wait': (Syscall.AUDIOWAIT, 0, 'void'),
160
+ # 2D 绘图画布
161
+ 'canvas': (Syscall.CANVASNEW, 2, 'void'),
162
+ 'set_color': (Syscall.CANVASSET, 1, 'void'),
163
+ 'fill_rect': (Syscall.CANVASRECT, 4, 'void'),
164
+ 'fill_circle': (Syscall.CANVASCIRC, 3, 'void'),
165
+ 'draw_line': (Syscall.CANVASLINE, 4, 'void'),
166
+ 'draw_text': (Syscall.CANVASTEXT, 3, 'void'),
167
+ 'save_png': (Syscall.CANVASSAVE, 1, 'int'),
168
+ 'show_canvas': (Syscall.CANVASSHOW, 0, 'int'),
169
+ # 系统原生交互 (跨平台)
170
+ 'file_read': (Syscall.FILEREAD, 1, 'string'),
171
+ 'file_write': (Syscall.FILEWRITE, 2, 'int'),
172
+ 'file_append': (Syscall.FILEAPPEND, 2, 'int'),
173
+ 'file_exists': (Syscall.FILEEXISTS, 1, 'int'),
174
+ 'file_delete': (Syscall.FILEDELETE, 1, 'int'),
175
+ 'file_size': (Syscall.FILESIZE, 1, 'int'),
176
+ 'mkdir': (Syscall.MKDIR, 1, 'int'),
177
+ 'dir_list': (Syscall.DIRLIST, 1, 'string'),
178
+ 'exec': (Syscall.EXEC, 1, 'int'),
179
+ 'exec_output': (Syscall.EXECOUTPUT, 1, 'string'),
180
+ 'getenv': (Syscall.GETENV, 1, 'string'),
181
+ 'setenv': (Syscall.SETENV, 2, 'int'),
182
+ 'os_name': (Syscall.OSNAME, 0, 'string'),
183
+ 'hostname': (Syscall.HOSTNAME, 0, 'string'),
184
+ 'username': (Syscall.USERNAME, 0, 'string'),
185
+ 'cwd': (Syscall.CWD, 0, 'string'),
186
+ 'home_dir': (Syscall.HOMEDIR, 0, 'string'),
187
+ # Termux API
188
+ 'termux_available': (Syscall.TERMUXAVAIL, 0, 'int'),
189
+ 'termux_notify': (Syscall.TERMUXNOTIFY, 2, 'int'),
190
+ 'termux_toast': (Syscall.TERMUXTOAST, 1, 'int'),
191
+ 'termux_clipboard_get': (Syscall.TERMUXCLIPGET, 0, 'string'),
192
+ 'termux_clipboard_set': (Syscall.TERMUXCLIPSET, 1, 'int'),
193
+ 'termux_battery': (Syscall.TERMUXBATTERY, 0, 'string'),
194
+ 'termux_vibrate': (Syscall.TERMUXVIBRATE, 1, 'int'),
195
+ 'termux_tts': (Syscall.TERMUXTTS, 1, 'int'),
196
+ 'termux_location': (Syscall.TERMUXLOCATION, 0, 'string'),
197
+ 'termux_wifi_info': (Syscall.TERMUXWIFI, 0, 'string'),
198
+ 'termux_dialog': (Syscall.TERMUXDIALOG, 1, 'string'),
199
+ 'termux_sms_send': (Syscall.TERMUXSMS, 2, 'int'),
200
+ # 路径与文件系统扩展 (跨平台)
201
+ 'path_join': (Syscall.PATHJOIN, 2, 'string'),
202
+ 'path_basename': (Syscall.PATHBASENAME, 1, 'string'),
203
+ 'path_dirname': (Syscall.PATHDIRNAME, 1, 'string'),
204
+ 'path_abs': (Syscall.PATHABS, 1, 'string'),
205
+ 'file_copy': (Syscall.FILECOPY, 2, 'int'),
206
+ 'file_move': (Syscall.FILEMOVE, 2, 'int'),
207
+ 'dir_remove': (Syscall.DIRREMOVE, 1, 'int'),
208
+ 'is_dir': (Syscall.ISDIR, 1, 'int'),
209
+ 'file_mtime': (Syscall.FILEMTIME, 1, 'int'),
210
+ 'temp_dir': (Syscall.TEMPDIR, 0, 'string'),
211
+ 'chdir': (Syscall.CHDIR, 1, 'int'),
212
+ # 时间与系统信息
213
+ 'time_ms': (Syscall.TIMEMS, 0, 'int'),
214
+ 'time_us': (Syscall.TIMEUS, 0, 'int'),
215
+ 'time_ns': (Syscall.TIMENS, 0, 'int'),
216
+ 'sleep_ms': (Syscall.SLEEPMS, 1, 'int'),
217
+ 'cpu_count': (Syscall.CPUCOUNT, 0, 'int'),
218
+ 'arch_name': (Syscall.ARCHNAME, 0, 'string'),
219
+ 'mem_info': (Syscall.MEMINFO, 0, 'string'),
220
+ 'is_android': (Syscall.ISANDROID, 0, 'int'),
221
+ # 网络 (HTTP/HTTPS)
222
+ 'http_get': (Syscall.HTTPGET, 1, 'string'),
223
+ 'http_post': (Syscall.HTTPPOST, 2, 'string'),
224
+ 'download': (Syscall.DOWNLOAD, 2, 'int'),
225
+ # 编码与哈希
226
+ 'sha256': (Syscall.SHA256, 1, 'string'),
227
+ 'base64_encode': (Syscall.BASE64ENC, 1, 'string'),
228
+ 'base64_decode': (Syscall.BASE64DEC, 1, 'string'),
229
+ # 桌面集成 (剪贴板 / 通知 / 打开 URL)
230
+ 'clipboard_get': (Syscall.CLIPGET, 0, 'string'),
231
+ 'clipboard_set': (Syscall.CLIPSET, 1, 'int'),
232
+ 'notify': (Syscall.NOTIFY, 2, 'int'),
233
+ 'open_url': (Syscall.OPENURL, 1, 'int'),
234
+ # Android / Termux 扩展
235
+ 'android_intent': (Syscall.ANDROIDINTENT, 2, 'int'),
236
+ 'termux_call': (Syscall.TERMUXCALL, 1, 'int'),
237
+ 'termux_share': (Syscall.TERMUXSHARE, 1, 'int'),
238
+ 'termux_torch': (Syscall.TERMUXTORCH, 1, 'int'),
239
+ 'termux_volume': (Syscall.TERMUXVOLUME, 2, 'int'),
240
+ 'termux_brightness': (Syscall.TERMUXBRIGHT, 1, 'int'),
241
+ 'termux_camera_photo': (Syscall.TERMUXCAMERA, 1, 'int'),
242
+ 'termux_fingerprint': (Syscall.TERMUXFINGER, 0, 'string'),
243
+ 'termux_sensor': (Syscall.TERMUXSENSOR, 1, 'string'),
244
+ # 键盘输入监听 (非阻塞轮询)
245
+ 'key_hit': (Syscall.KEYHIT, 0, 'int'),
246
+ 'get_key': (Syscall.KEYGET, 0, 'int'),
247
+ 'key_flush': (Syscall.KEYFLUSH, 0, 'int'),
248
+ # GUI 窗口 (Windows Win32 / Linux X11, 其他平台优雅失败)
249
+ 'gui_new': (Syscall.GUINEW, 3, 'int'),
250
+ 'gui_update': (Syscall.GUIUPDATE, 0, 'int'),
251
+ 'gui_close': (Syscall.GUICLOSE, 0, 'int'),
252
+ 'gui_closed': (Syscall.GUICLOSED, 0, 'int'),
253
+ 'gui_active': (Syscall.GUIACTIVE, 0, 'int'),
254
+ 'mouse_x': (Syscall.MOUSEX, 0, 'int'),
255
+ 'mouse_y': (Syscall.MOUSEY, 0, 'int'),
256
+ 'mouse_button': (Syscall.MOUSEBTN, 0, 'int'),
257
+ # 虚拟键盘 (Windows 屏幕/触摸键盘 TabTip; 其他平台 -1)
258
+ 'vkb_show': (Syscall.VKBSHOW, 0, 'int'),
259
+ 'vkb_hide': (Syscall.VKBHIDE, 0, 'int'),
260
+ # 音频扩展 (播放进度与蜂鸣合成)
261
+ 'audio_pos': (Syscall.AUDIOPOS, 0, 'int'),
262
+ 'beep': (Syscall.AUDIOBEEP, 2, 'int'),
263
+ # 音频控制增强 (查询 / 暂停恢复 / 音量读取)
264
+ 'audio_duration': (Syscall.AUDIODUR, 0, 'int'),
265
+ 'audio_playing': (Syscall.AUDIOPLAYING, 0, 'int'),
266
+ 'audio_pause': (Syscall.AUDIOPAUSE, 0, 'int'),
267
+ 'audio_resume': (Syscall.AUDIORESUME, 0, 'int'),
268
+ 'audio_level': (Syscall.AUDIOLEVEL, 0, 'int'),
269
+ # 命令行参数与行输入 (跨平台一致)
270
+ 'arg_count': (Syscall.ARGC, 0, 'int'),
271
+ 'arg': (Syscall.ARGV, 1, 'string'),
272
+ 'input_str': (Syscall.READLINE, 0, 'string'),
273
+ # FFI 动态库调用 (dlopen/dlsym/call, 最多 8 个 int64 参数)
274
+ 'dlopen': (Syscall.DLOPEN, 1, 'int'),
275
+ 'dlsym': (Syscall.DLSYM, 2, 'int'),
276
+ 'ffi_call': (Syscall.FFICALL, 3, 'int'),
277
+ 'ffi_callf': (Syscall.FFICALLF, 3, 'float'),
278
+ 'lib_close': (Syscall.LIBCLOSE, 1, 'int'),
279
+ # 网络: HTTP 请求扩展 (GET/POST 之外的自定义方法与头部)
280
+ 'http_req': (Syscall.HTTPREQ, 4, 'string'),
281
+ 'http_code': (Syscall.HTTPCODE, 0, 'int'),
282
+ # 网络: TCP 客户端与服务端
283
+ 'tcp_dial': (Syscall.TCPDIAL, 2, 'int'),
284
+ 'tcp_send': (Syscall.TCPSEND, 3, 'int'),
285
+ 'tcp_recv': (Syscall.TCPRECV, 3, 'int'),
286
+ 'tcp_close': (Syscall.TCPCLOSE, 1, 'int'),
287
+ 'tcp_listen': (Syscall.TCPLISTEN, 1, 'int'),
288
+ 'tcp_accept': (Syscall.TCPACCEPT, 1, 'int'),
289
+ # 网络: UDP 数据报
290
+ 'udp_open': (Syscall.UDPOPEN, 1, 'int'),
291
+ 'udp_sendto': (Syscall.UDPSENDTO, 5, 'int'),
292
+ 'udp_recvfrom': (Syscall.UDPRECVFROM, 4, 'int'),
293
+ 'udp_close': (Syscall.UDPCLOSE, 1, 'int'),
294
+ # 网络: DNS 解析
295
+ 'dns_lookup': (Syscall.DNSLOOKUP, 1, 'string'),
296
+ }
297
+
298
+ BUILTIN_MIN_ARGS = {
299
+ 'println': 0, 'print': 0,
300
+ 'sqrt': 1, 'sin': 1, 'cos': 1, 'tan': 1,
301
+ 'floor': 1, 'ceil': 1, 'round': 1,
302
+ 'min': 2, 'max': 2,
303
+ 'idiv': 2, 'pow': 2,
304
+ 'abs': 1, 'strlen': 1, 'strcmp': 2, 'strcpy': 1,
305
+ 'rand': 0, 'srand': 1,
306
+ 'int_to_str': 1, 'itoa': 1,
307
+ 'float_to_str': 1, 'ftoa': 1,
308
+ 'bool_to_str': 1,
309
+ 'substr': 3, 'indexof': 2,
310
+ 'upper': 1, 'lower': 1,
311
+ 'trim': 1, 'ltrim': 1, 'rtrim': 1, 'atoi': 1,
312
+ 'time': 0, 'input': 0,
313
+ }
314
+ BUILTIN_MIN_ARGS.update({k: v[1] for k, v in HOST_BUILTINS.items()})
315
+
316
+
317
+ @dataclass
318
+ class Token:
319
+ kind: str
320
+ value: Any
321
+ line: int
322
+ filename: Optional[str] = None
323
+
324
+
325
+ def tokenize(source: str,
326
+ origin: Optional[List[Optional[Tuple[str, int]]]] = None
327
+ ) -> List[Token]:
328
+ tokens: List[Token] = []
329
+ i, line, n = 0, 1, len(source)
330
+
331
+ def at_loc(ln: int) -> str:
332
+ if origin and 0 < ln < len(origin):
333
+ ent = origin[ln]
334
+ if ent is not None:
335
+ f, lineno = ent
336
+ return f"{f}:{lineno}"
337
+ return f"line {ln}"
338
+
339
+ def skip_comment_block():
340
+ nonlocal i, line
341
+ i += 2
342
+ while i < n - 1 and not (source[i] == '*' and source[i + 1] == '/'):
343
+ if source[i] == '\n':
344
+ line += 1
345
+ i += 1
346
+ i += 2
347
+
348
+ while i < n:
349
+ c = source[i]
350
+ if c == '\n':
351
+ tokens.append(Token('NL', '\n', line))
352
+ line += 1
353
+ i += 1
354
+ elif c in ' \t\r\ufeff':
355
+ i += 1
356
+ elif c == '/' and i + 1 < n and source[i + 1] == '/':
357
+ while i < n and source[i] != '\n':
358
+ i += 1
359
+ elif c == '/' and i + 1 < n and source[i + 1] == '*':
360
+ skip_comment_block()
361
+ elif c == '"':
362
+ start_line = line
363
+ i += 1
364
+ buf = []
365
+ while i < n and source[i] != '"':
366
+ if source[i] == '\\' and i + 1 < n:
367
+ esc = source[i + 1]
368
+ i += 2
369
+ if esc in _STR_ESCAPES:
370
+ buf.append(_STR_ESCAPES[esc])
371
+ elif esc == 'x':
372
+ # \xH 或 \xHH (1-2 位十六进制) —— 原始字节 (C 语义)。
373
+ # >= 0x80 的字节用代理转义码位承载, 由 _data_string 原样
374
+ # 写回, 从而与 Go 侧 "逐字节追加" 完全一致。
375
+ digits = ''
376
+ while len(digits) < 2 and i < n and \
377
+ source[i] in _HEX_DIGITS:
378
+ digits += source[i]
379
+ i += 1
380
+ if not digits:
381
+ raise CompilerError(
382
+ f"\\x escape needs at least one hex digit at "
383
+ f"{at_loc(line)}")
384
+ code = int(digits, 16)
385
+ buf.append(chr(code) if code < 0x80
386
+ else chr(0xDC00 + code))
387
+ elif esc in ('u', 'U'):
388
+ # \uHHHH (4 位) / \UHHHHHHHH (8 位) Unicode 码点
389
+ width = 4 if esc == 'u' else 8
390
+ digits = source[i:i + width]
391
+ if len(digits) < width or any(
392
+ ch not in _HEX_DIGITS for ch in digits):
393
+ raise CompilerError(
394
+ f"\\{esc} escape needs exactly {width} hex "
395
+ f"digits at {at_loc(line)}")
396
+ code = int(digits, 16)
397
+ if code > 0x10FFFF:
398
+ raise CompilerError(
399
+ f"\\{esc} escape out of Unicode range at "
400
+ f"{at_loc(line)}")
401
+ buf.append(chr(code))
402
+ i += width
403
+ else:
404
+ buf.append(esc)
405
+ else:
406
+ if source[i] == '\n':
407
+ line += 1
408
+ buf.append(source[i])
409
+ i += 1
410
+ i += 1
411
+ tokens.append(Token('STRING', ''.join(buf), start_line))
412
+ elif c.isdigit() or (c == '.' and i + 1 < n and source[i + 1].isdigit()):
413
+ start = i
414
+ is_float = False
415
+ if c == '0' and i + 1 < n and source[i + 1] in 'xXbBoO':
416
+ # 进制前缀: 0x/0X 16, 0b/0B 2, 0o/0O 8
417
+ base = {'x': 16, 'X': 16, 'b': 2, 'B': 2,
418
+ 'o': 8, 'O': 8}[source[i + 1]]
419
+ i += 2
420
+ dstart = i
421
+ allowed = ('0123456789abcdefABCDEF_' if base == 16 else
422
+ ('01_' if base == 2 else '01234567_'))
423
+ while i < n and source[i] in allowed:
424
+ i += 1
425
+ if i == dstart or not any(ch != '_' for ch in
426
+ source[dstart:i]):
427
+ raise CompilerError(f"Malformed numeric literal at "
428
+ f"{at_loc(line)}")
429
+ dend = i
430
+ # 后缀 (u/U/l/L, f/F): 64 位槽模型忽略宽度差异。
431
+ # 注意: 数值文本必须在吃后缀"之前"截取, 否则 0xFFu 会整段
432
+ # 交给 int() 而抛裸 ValueError。
433
+ while i < n and source[i] in 'uUlL':
434
+ i += 1
435
+ if i < n and source[i] in 'fF':
436
+ is_float = True
437
+ i += 1
438
+ text = source[start:dend]
439
+ norm = '0' + text[1].lower() + text[2:]
440
+ try:
441
+ value = int(norm.replace('_', ''), 0)
442
+ except ValueError:
443
+ raise CompilerError(f"Malformed numeric literal at "
444
+ f"{at_loc(line)}") from None
445
+ if value > 0xFFFFFFFFFFFFFFFF:
446
+ raise CompilerError(
447
+ f"Numeric literal out of 64-bit range at "
448
+ f"{at_loc(line)}")
449
+ else:
450
+ while i < n and (source[i].isdigit() or source[i] == '.'
451
+ or source[i] == '_'):
452
+ if source[i] == '.':
453
+ # 小数点最多一个; '..' 是 case 范围运算符, 不属于数字
454
+ if is_float or (i + 1 < n and source[i + 1] == '.'):
455
+ break
456
+ is_float = True
457
+ i += 1
458
+ if i < n and source[i] in 'eE':
459
+ is_float = True
460
+ i += 1
461
+ if i < n and source[i] in '+-':
462
+ i += 1
463
+ while i < n and (source[i].isdigit() or source[i] == '_'):
464
+ i += 1
465
+ dend = i
466
+ # 同上: 先截取数值文本, 再吃后缀
467
+ while i < n and source[i] in 'uUlL':
468
+ i += 1
469
+ if i < n and source[i] in 'fF':
470
+ is_float = True
471
+ i += 1
472
+ text = source[start:dend].replace('_', '')
473
+ try:
474
+ value = float(text) if is_float else int(text)
475
+ except ValueError:
476
+ raise CompilerError(f"Malformed numeric literal at "
477
+ f"{at_loc(line)}") from None
478
+ if not is_float and value > 0x7FFFFFFFFFFFFFFF:
479
+ raise CompilerError(
480
+ f"Numeric literal out of 64-bit range at "
481
+ f"{at_loc(line)}")
482
+ tokens.append(Token('FLOAT', float(value), line) if is_float
483
+ else Token('NUMBER', int(value), line))
484
+ elif c.isalpha() or c == '_':
485
+ start = i
486
+ while i < n and (source[i].isalnum() or source[i] == '_'):
487
+ i += 1
488
+ word = source[start:i]
489
+ tokens.append(Token('IDENT', word, line))
490
+ elif c == '-' and i + 1 < n and source[i + 1] == '>':
491
+ tokens.append(Token('ARROW', '->', line))
492
+ i += 2
493
+ elif c == '.' and i + 1 < n and source[i + 1] == '.':
494
+ # case 范围: case 1..5:
495
+ tokens.append(Token('DOTDOT', '..', line))
496
+ i += 2
497
+ elif c == "'": # 字符字面量: 'a' '\n' '\'' ...
498
+ start_line = line
499
+ i += 1
500
+ if i >= n:
501
+ raise CompilerError(f"Unterminated char literal at "
502
+ f"{at_loc(start_line)}")
503
+ if source[i] == '\\' and i + 1 < n:
504
+ esc = source[i + 1]
505
+ val = {'n': 10, 't': 9, 'r': 13, '0': 0, 'a': 7, 'b': 8,
506
+ 'f': 12, 'v': 11, "'": 39, '"': 34,
507
+ '\\': 92}.get(esc, ord(esc))
508
+ i += 2
509
+ else:
510
+ val = ord(source[i])
511
+ i += 1
512
+ if i >= n or source[i] != "'":
513
+ raise CompilerError(f"Unterminated char literal at "
514
+ f"{at_loc(start_line)}")
515
+ i += 1
516
+ tokens.append(Token('NUMBER', val, line))
517
+ elif c in ('+', '-', '*', '/', '%') and i + 1 < n and source[i + 1] == '=':
518
+ kind = {'+': 'PLUSEQ', '-': 'MINUSEQ', '*': 'STAREQ',
519
+ '/': 'SLASHEQ', '%': 'PERCENTEQ'}[c]
520
+ tokens.append(Token(kind, c + '=', line))
521
+ i += 2
522
+ elif c in ('&', '|', '^') and i + 1 < n and source[i + 1] == '=':
523
+ kind = {'&': 'ANDEQ', '|': 'OREQ', '^': 'XOREQ'}[c]
524
+ tokens.append(Token(kind, c + '=', line))
525
+ i += 2
526
+ elif c in ('<', '>') and i + 2 < n and source[i + 1] == c \
527
+ and source[i + 2] == '=':
528
+ tokens.append(Token('SHLEQ' if c == '<' else 'SHREQ',
529
+ c + c + '=', line))
530
+ i += 3
531
+ elif c in ('<', '>') and i + 1 < n and source[i + 1] == c:
532
+ tokens.append(Token('SHL' if c == '<' else 'SHR', c + c, line))
533
+ i += 2
534
+ elif c == '+' and i + 1 < n and source[i + 1] == '+':
535
+ tokens.append(Token('INC', '++', line))
536
+ i += 2
537
+ elif c == '-' and i + 1 < n and source[i + 1] == '-':
538
+ tokens.append(Token('DEC', '--', line))
539
+ i += 2
540
+ elif c == '=' and i + 1 < n and source[i + 1] == '=':
541
+ tokens.append(Token('EQ', '==', line))
542
+ i += 2
543
+ elif c == '!' and i + 1 < n and source[i + 1] == '=':
544
+ tokens.append(Token('NEQ', '!=', line))
545
+ i += 2
546
+ elif c == '<' and i + 1 < n and source[i + 1] == '=':
547
+ tokens.append(Token('LE', '<=', line))
548
+ i += 2
549
+ elif c == '>' and i + 1 < n and source[i + 1] == '=':
550
+ tokens.append(Token('GE', '>=', line))
551
+ i += 2
552
+ elif c == '&' and i + 1 < n and source[i + 1] == '&':
553
+ tokens.append(Token('AND', '&&', line))
554
+ i += 2
555
+ elif c == '|' and i + 1 < n and source[i + 1] == '|':
556
+ tokens.append(Token('OR', '||', line))
557
+ i += 2
558
+ elif c in _SINGLE_OPS:
559
+ tokens.append(Token(_SINGLE_OPS[c], c, line))
560
+ i += 1
561
+ else:
562
+ raise CompilerError(f"Unexpected character {c!r} at {at_loc(line)}")
563
+
564
+ # 行连接: 圆/方括号深度内或行尾为运算符时 NL 无效;
565
+ # 花括号 {} 块内的 NL 必须保留 (语句以换行终止)
566
+ filtered: List[Token] = []
567
+ depth = 0
568
+ open_kw = {'LPAREN', 'LBRACKET'}
569
+ close_kw = {'RPAREN', 'RBRACKET'}
570
+ continue_ops = {'PLUS', 'MINUS', 'STAR', 'SLASH', 'PERCENT', 'ASSIGN',
571
+ 'LT', 'GT', 'LE', 'GE', 'EQ', 'NEQ', 'AND', 'OR', 'COMMA',
572
+ 'ARROW', 'DOT', 'DOTDOT', 'PLUSEQ', 'MINUSEQ', 'STAREQ', 'SLASHEQ',
573
+ 'PERCENTEQ', 'INC', 'DEC',
574
+ 'AMP', 'PIPE', 'CARET', 'TILDE', 'SHL', 'SHR',
575
+ 'ANDEQ', 'OREQ', 'XOREQ', 'SHLEQ', 'SHREQ'}
576
+ for tok in tokens:
577
+ if tok.kind in open_kw:
578
+ depth += 1
579
+ elif tok.kind in close_kw:
580
+ depth = max(0, depth - 1)
581
+ if tok.kind == 'NL':
582
+ if depth > 0:
583
+ continue
584
+ prev = filtered[-1] if filtered else None
585
+ if prev is not None and prev.kind in continue_ops:
586
+ continue
587
+ if filtered and filtered[-1].kind == 'NL':
588
+ continue
589
+ filtered.append(tok)
590
+ filtered.append(Token('EOF', None, line))
591
+ return filtered
592
+
593
+
594
+ # ==================== import 预处理 (B3) ====================
595
+ # import "path.cin" 仅在文件顶部/列首识别。解析规则:
596
+ # * "./x.cin" / "../x.cin" -> 相对当前 .cin 文件所在目录;
597
+ # * 其余形式 -> 依次查找 codecin 内置标准库、项目依赖目录、
598
+ # CIN_PATH、已安装的 pic 包;
599
+ # * 包名 (无 .cin 后缀) 直接 import 该包的入口 (v6.2.0)。
600
+ # 同一文件每个编译仅包含一次, 循环引用报错。
601
+
602
+ _IMPORT_RE = re.compile(r'^import\s+["\']([^"\']+)["\']\s*;?\s*$')
603
+
604
+ _CODECIN_ROOT = os.path.dirname(os.path.abspath(__file__))
605
+
606
+ #: 内置标准库目录 (随包分发: codecin/lib/<name>/src/<name>.cin)
607
+ _LIB_DIR = os.path.join(_CODECIN_ROOT, 'lib')
608
+
609
+ #: 相对引用的前缀: 必须以 "." 开头
610
+ _RELATIVE_PREFIXES = ('./', '../', '.\\', '..\\')
611
+
612
+ #: 项目内依赖目录 (按优先级): mkn / pic --project / 旧式隐藏目录
613
+ _PROJECT_DEP_DIRS = ('pic_modules', os.path.join('.mkn', 'deps'),
614
+ os.path.join('.pic', 'packages'))
615
+
616
+ #: 包名合法性 (与 packaging.model 保持一致, 这里不 import 以避免启动开销)
617
+ _PKG_NAME_RE = re.compile(r'^[A-Za-z][A-Za-z0-9_-]{0,63}$')
618
+
619
+
620
+ def _is_relative_import(name: str) -> bool:
621
+ """``import "./x.cin"`` / ``import "../x.cin"`` 视为相对引用。"""
622
+ return name.startswith(_RELATIVE_PREFIXES)
623
+
624
+
625
+ def _cin_path_dirs() -> List[str]:
626
+ """``CIN_PATH`` 环境变量中的 import 搜索目录 (``os.pathsep`` 分隔)。"""
627
+ raw = os.environ.get('CIN_PATH', '')
628
+ return [os.path.abspath(p) for p in raw.split(os.pathsep) if p.strip()]
629
+
630
+
631
+ def _project_roots(source_dir: str) -> List[str]:
632
+ """从源文件目录向上收集包含 mkn.toml / pic.toml 的项目根 (近到远)。"""
633
+ roots: List[str] = []
634
+ path = os.path.abspath(source_dir)
635
+ while True:
636
+ if (os.path.isfile(os.path.join(path, 'mkn.toml'))
637
+ or os.path.isfile(os.path.join(path, 'pic.toml'))):
638
+ roots.append(path)
639
+ parent = os.path.dirname(path)
640
+ if parent == path:
641
+ break
642
+ path = parent
643
+ return roots
644
+
645
+
646
+ def _package_roots(source_dir: str) -> List[str]:
647
+ """候选包根目录 (按优先级): 项目依赖 -> CIN_PATH -> 全局 pic 存储。"""
648
+ roots: List[str] = []
649
+ for project in _project_roots(source_dir):
650
+ for rel in _PROJECT_DEP_DIRS:
651
+ candidate = os.path.join(project, rel)
652
+ if os.path.isdir(candidate):
653
+ roots.append(candidate)
654
+ roots.extend(_cin_path_dirs())
655
+
656
+ home = os.environ.get('PIC_HOME') or os.path.join(
657
+ os.path.expanduser('~'), '.pic')
658
+ packages = os.path.join(home, 'packages')
659
+ if os.path.isdir(packages):
660
+ # 全局存储是 <name>/<version>/; 默认选择最高已安装版本
661
+ roots.append(packages)
662
+ return roots
663
+
664
+
665
+ def _entry_from_package(pkg_dir: str, pkg: str,
666
+ hinted_file: Optional[str] = None) -> Optional[str]:
667
+ """在包目录中解析入口文件: pic.toml 的 entry 优先, 再按约定回退。"""
668
+ base = pkg_dir
669
+ link = os.path.join(base, '.pic-link')
670
+ if os.path.isfile(link):
671
+ try:
672
+ with open(link, encoding='utf-8') as f:
673
+ target = f.read().strip()
674
+ if target:
675
+ base = os.path.abspath(target)
676
+ except OSError:
677
+ pass
678
+ if not os.path.isdir(base):
679
+ return None
680
+
681
+ if hinted_file:
682
+ for rel in (hinted_file, os.path.join('src', hinted_file)):
683
+ candidate = os.path.normpath(os.path.join(base, rel))
684
+ if os.path.isfile(candidate):
685
+ return candidate
686
+
687
+ manifest = os.path.join(base, 'pic.toml')
688
+ if os.path.isfile(manifest):
689
+ try:
690
+ from .packaging.model import load_package_manifest
691
+ meta = load_package_manifest(base, require_entry=False)
692
+ if meta.entry_path:
693
+ return meta.entry_path
694
+ except Exception:
695
+ # 清单损坏不应让 import 变成不可诊断的异常:
696
+ # 继续按目录约定查找, 最终在找不到时给出统一错误
697
+ pass
698
+
699
+ mkn_manifest = os.path.join(base, 'mkn.toml')
700
+ if os.path.isfile(mkn_manifest):
701
+ try:
702
+ from .packaging.model import load_mkn_manifest
703
+ project = load_mkn_manifest(base)
704
+ entry = project.entry_path
705
+ if entry:
706
+ return entry
707
+ except Exception:
708
+ pass
709
+
710
+ for rel in (os.path.join('src', f'{pkg}.cin'), f'{pkg}.cin',
711
+ os.path.join('src', 'main.cin'), 'main.cin'):
712
+ candidate = os.path.normpath(os.path.join(base, rel))
713
+ if os.path.isfile(candidate):
714
+ return candidate
715
+ return None
716
+
717
+
718
+ def _semver_key(version: str) -> Tuple[int, int, int, int, str]:
719
+ """版本排序键: 稳定版高于同号预发布版。"""
720
+ base = version.split('+', 1)[0]
721
+ core, _, pre = base.partition('-')
722
+ parts = core.split('.')
723
+ out: List[int] = []
724
+ for index in range(3):
725
+ try:
726
+ out.append(int(parts[index]))
727
+ except (IndexError, ValueError):
728
+ out.append(0)
729
+ return out[0], out[1], out[2], 0 if pre else 1, pre
730
+
731
+
732
+ def _version_dirs(pkg_dir: str) -> List[str]:
733
+ """全局存储 ``<name>/<version>`` 下的版本目录。
734
+
735
+ v6.4.x 起 **最高版本优先**:CIN 的 ``import "pkg"`` 默认使用最新
736
+ 已安装版本,而不是 ``index.json`` 里的 ``current`` 指针(``current``
737
+ 仍供 ``pic show`` / ``pic use`` 等本地命令使用)。
738
+ """
739
+ try:
740
+ versions = [
741
+ v for v in os.listdir(pkg_dir)
742
+ if os.path.isdir(os.path.join(pkg_dir, v))
743
+ and re.fullmatch(r'\d+\.\d+\.\d+(?:[-+].*)?', v)
744
+ ]
745
+ except OSError:
746
+ return []
747
+ versions.sort(key=lambda value: (_semver_key(value), value), reverse=True)
748
+ return [os.path.join(pkg_dir, v) for v in versions]
749
+
750
+
751
+ #: 分块导入 ``pkg:*`` 时跳过的目录: 测试/示例/私有模块不参与通配
752
+ _PACKAGE_WILDCARD_SKIP_DIRS = frozenset({
753
+ 'internal', 'private', 'test', 'tests', '__tests__', 'demo', 'demos',
754
+ 'example', 'examples', 'dist', 'build', 'target', 'node_modules',
755
+ '__pycache__', '.git', '.hg', '.svn', 'pic_modules', '.pic', '.mkn',
756
+ })
757
+
758
+
759
+ def _package_version(base: str) -> Optional[str]:
760
+ """读取包目录 ``pic.toml`` / ``mkn.toml`` 的版本; 非包目录返回 None。"""
761
+ if not os.path.isdir(base):
762
+ return None
763
+ try:
764
+ from .packaging.model import load_mkn_manifest, load_package_manifest
765
+ if os.path.isfile(os.path.join(base, 'pic.toml')):
766
+ return load_package_manifest(base, require_entry=False).version
767
+ if os.path.isfile(os.path.join(base, 'mkn.toml')):
768
+ return load_mkn_manifest(base).version
769
+ except Exception: # noqa: BLE001 - 清单损坏时按"不是包"处理
770
+ return None
771
+ return None
772
+
773
+
774
+ def _package_bases(pkg_dir: str) -> List[str]:
775
+ """一个包名目录下可用的包根 (项目目录本身 / 全局版本目录)。"""
776
+ bases: List[str] = []
777
+ if _package_version(pkg_dir) is not None:
778
+ bases.append(pkg_dir)
779
+ for version_dir in _version_dirs(pkg_dir):
780
+ if version_dir not in bases and _package_version(version_dir) is not None:
781
+ bases.append(version_dir)
782
+ return bases
783
+
784
+
785
+ def _iter_package_cin_files(base: str) -> List[Tuple[str, str]]:
786
+ """返回包内全部 ``.cin`` (相对路径, 绝对路径), 按路径排序。"""
787
+ out: List[Tuple[str, str]] = []
788
+ for dirpath, dirnames, filenames in os.walk(base):
789
+ dirnames[:] = sorted(
790
+ d for d in dirnames
791
+ if d not in _PACKAGE_WILDCARD_SKIP_DIRS
792
+ and not d.startswith('.'))
793
+ for filename in sorted(filenames):
794
+ if not filename.endswith('.cin'):
795
+ continue
796
+ path = os.path.join(dirpath, filename)
797
+ rel = os.path.relpath(path, base).replace(os.sep, '/')
798
+ out.append((rel, path))
799
+ out.sort(key=lambda item: item[0])
800
+ return out
801
+
802
+
803
+ def _module_defines_main(path: str) -> bool:
804
+ try:
805
+ with open(path, encoding='utf-8-sig', errors='replace') as f:
806
+ text = f.read(1 << 20)
807
+ except OSError:
808
+ return False
809
+ return re.search(r'\bfunction\s+main\s*\(', text) is not None
810
+
811
+
812
+ def _module_is_internal(rel: str) -> bool:
813
+ lower = rel.lower()
814
+ return any(part in ('internal', 'private', 'test', 'tests', 'demo',
815
+ 'demos', 'example', 'examples')
816
+ for part in lower.split('/')[:-1])
817
+
818
+
819
+ def _module_display(rel: str) -> str:
820
+ text = rel[:-4] if rel.endswith('.cin') else rel
821
+ return text[4:] if text.startswith('src/') else text
822
+
823
+
824
+ def _available_modules(base: str) -> List[str]:
825
+ return [_module_display(rel) for rel, _path in _iter_package_cin_files(base)
826
+ if os.path.basename(rel) not in ('main.cin', 'test.cin')]
827
+
828
+
829
+ def _match_module(base: str, selector: str) -> List[str]:
830
+ """把 ``table`` / ``internal/table.cin`` / ``table*`` 解析为包内文件。"""
831
+ files = _iter_package_cin_files(base)
832
+ if not files:
833
+ return []
834
+ selector = selector.strip().replace('\\', '/')
835
+ if not selector:
836
+ return []
837
+ want = selector if selector.endswith('.cin') else selector + '.cin'
838
+ has_glob = any(ch in selector for ch in '*?[')
839
+
840
+ if has_glob:
841
+ matches = []
842
+ for rel, path in files:
843
+ stem = rel[:-4] if rel.endswith('.cin') else rel
844
+ display = _module_display(rel)
845
+ if fnmatch.fnmatch(rel, want) or fnmatch.fnmatch(stem, selector) \
846
+ or fnmatch.fnmatch(display, selector) \
847
+ or fnmatch.fnmatch(os.path.basename(stem), selector):
848
+ matches.append((_module_is_internal(rel), len(rel), rel, path))
849
+ matches.sort()
850
+ return [path for _internal, _size, _rel, path in matches]
851
+
852
+ # 快路径: 常见位置直接命中
853
+ for rel in (want, 'src/' + want, 'src/internal/' + want,
854
+ 'internal/' + want, 'lib/' + want):
855
+ path = os.path.normpath(os.path.join(base, rel))
856
+ if os.path.isfile(path):
857
+ return [path]
858
+
859
+ fuzzy = []
860
+ for rel, path in files:
861
+ stem = rel[:-4] if rel.endswith('.cin') else rel
862
+ display = _module_display(rel)
863
+ if rel == want or rel.endswith('/' + want) or stem == selector \
864
+ or display == selector or display.endswith('/' + selector) \
865
+ or (('/' not in selector)
866
+ and os.path.basename(stem) == selector):
867
+ fuzzy.append((_module_is_internal(rel), len(rel), rel, path))
868
+ fuzzy.sort()
869
+ return [path for _internal, _size, _rel, path in fuzzy]
870
+
871
+
872
+ class _PackageModuleNotFound(CompilerError):
873
+ def __init__(self, base: str, selector: str):
874
+ self.base = base
875
+ self.selector = selector
876
+ available = ', '.join(_available_modules(base)) or '(无)'
877
+ super().__init__(
878
+ f"Import module not found: {selector!r} in {base}; "
879
+ f"可用模块: {available}")
880
+
881
+
882
+ def _path_is_internal(base: str, path: str) -> bool:
883
+ rel = os.path.relpath(path, base).replace(os.sep, '/')
884
+ return _module_is_internal(rel)
885
+
886
+
887
+ def _package_chunks(base: str, pkg: str,
888
+ spec) -> List[str]:
889
+ """按规格收集包内文件; ``*`` 返回入口 + 全部公开模块。"""
890
+ entry = _entry_from_package(base, pkg)
891
+ if not spec.has_selector:
892
+ if entry is None:
893
+ raise _PackageModuleNotFound(base, '(entry)')
894
+ return [entry]
895
+
896
+ if spec.is_all:
897
+ targets: List[str] = []
898
+ seen: Set[str] = set()
899
+
900
+ def add(path: str) -> None:
901
+ real = os.path.realpath(path)
902
+ if real not in seen:
903
+ seen.add(real)
904
+ targets.append(path)
905
+
906
+ if entry:
907
+ add(entry)
908
+ for rel, path in _iter_package_cin_files(base):
909
+ if _module_is_internal(rel):
910
+ continue
911
+ if os.path.basename(rel) in ('main.cin', 'test.cin'):
912
+ continue
913
+ if _module_defines_main(path):
914
+ continue
915
+ add(path)
916
+ if not targets and entry is None:
917
+ raise _PackageModuleNotFound(base, '*')
918
+ return targets
919
+
920
+ targets = []
921
+ seen = set()
922
+ needs_entry = False
923
+ for module in spec.modules:
924
+ matches = _match_module(base, module)
925
+ if not matches:
926
+ raise _PackageModuleNotFound(base, module)
927
+ if any(_path_is_internal(base, path) for path in matches):
928
+ # 私有模块可能依赖入口统一导入的内部符号 (如 rich 的
929
+ # internal/table.cin 使用 style.cin 的 rich_markup); 先展开
930
+ # 入口保证符号完整, 再由 loaded 去重。
931
+ needs_entry = True
932
+ for path in matches:
933
+ real = os.path.realpath(path)
934
+ if real not in seen:
935
+ seen.add(real)
936
+ targets.append(path)
937
+ if needs_entry and entry:
938
+ real = os.path.realpath(entry)
939
+ if real not in seen:
940
+ targets.insert(0, entry)
941
+ return targets
942
+
943
+
944
+ def _resolve_package_chunks(spec, source_dir: str) -> Optional[List[str]]:
945
+ """按包规格解析 import; 没有同名包时返回 None。"""
946
+ found = False
947
+ version_mismatch: List[str] = []
948
+ module_errors: List[_PackageModuleNotFound] = []
949
+ for root in _package_roots(source_dir):
950
+ pkg_dir = os.path.join(root, spec.name)
951
+ if not os.path.isdir(pkg_dir):
952
+ continue
953
+ bases = _package_bases(pkg_dir)
954
+ if not bases:
955
+ continue
956
+ found = True
957
+ if spec.version:
958
+ matching = [base for base in bases
959
+ if _package_version(base) == spec.version]
960
+ if not matching:
961
+ versions = sorted(
962
+ (v for v in (_package_version(b) for b in bases) if v),
963
+ reverse=True)
964
+ version_mismatch.append(
965
+ f'{spec.name}: 已安装 {", ".join(versions) or "(未知)"}')
966
+ continue
967
+ bases = matching
968
+ for base in bases:
969
+ try:
970
+ return _package_chunks(base, spec.name, spec)
971
+ except _PackageModuleNotFound as e:
972
+ module_errors.append(e)
973
+
974
+ if not found:
975
+ return None
976
+ if version_mismatch and not module_errors:
977
+ detail = '; '.join(dict.fromkeys(version_mismatch))
978
+ raise CompilerError(
979
+ f"Import file not found: {spec.display!r} (已安装版本不匹配: "
980
+ f"{detail})。可运行 `pic install {spec.name}@{spec.version}` 安装该版本。")
981
+ if module_errors:
982
+ error = module_errors[0]
983
+ raise CompilerError(
984
+ f"Import file not found: {spec.display!r} ({error}); "
985
+ f"先运行 `pic install {spec.name}`,再用 `pic modules {spec.name}` "
986
+ f"查看可导入的模块。")
987
+ raise CompilerError(
988
+ f"Import file not found: {spec.display!r} (包目录存在但无法读取入口文件)")
989
+
990
+
991
+ def _resolve_package_import(name: str,
992
+ source_dir: str) -> Optional[str]:
993
+ """按包名/相对包内路径解析 import (旧写法); 找不到返回 None。"""
994
+ normalized = name.replace('\\', '/')
995
+ parts = [p for p in normalized.split('/') if p]
996
+ if not parts:
997
+ return None
998
+
999
+ pkg = parts[0]
1000
+ hinted: Optional[str] = None
1001
+ if len(parts) == 1 and pkg.endswith('.cin'):
1002
+ # `import "hello.cin"` 也允许命中名为 hello 的包
1003
+ pkg = pkg[:-4]
1004
+ hinted = parts[0]
1005
+ if not _PKG_NAME_RE.match(pkg):
1006
+ return None
1007
+ sub = '/'.join(parts[1:]) if len(parts) > 1 else ''
1008
+
1009
+ for root in _package_roots(source_dir):
1010
+ pkg_dir = os.path.join(root, pkg)
1011
+ if not os.path.isdir(pkg_dir):
1012
+ continue
1013
+ version_dirs = _version_dirs(pkg_dir)
1014
+ if sub:
1015
+ for base in [pkg_dir, os.path.join(pkg_dir, 'src'),
1016
+ *(os.path.join(v, 'src') for v in version_dirs),
1017
+ *version_dirs]:
1018
+ candidate = os.path.normpath(
1019
+ os.path.join(base, *sub.split('/')))
1020
+ if os.path.isfile(candidate):
1021
+ return candidate
1022
+ continue
1023
+ entry = _entry_from_package(pkg_dir, pkg, hinted)
1024
+ if entry:
1025
+ return entry
1026
+ for version_dir in version_dirs:
1027
+ entry = _entry_from_package(version_dir, pkg, hinted)
1028
+ if entry:
1029
+ return entry
1030
+ return None
1031
+
1032
+
1033
+ def _bundled_library_candidates(name: str) -> List[str]:
1034
+ """把 import 目标映射到内置库的 pic 包布局。
1035
+
1036
+ ``codecin/lib/<name>/src/<name>.cin`` 是每个内置库的入口;``lib/`` 前缀
1037
+ 仍作为兼容写法。例如 ``math.cin`` / ``lib/math.cin`` / ``math`` 都映射到
1038
+ ``codecin/lib/math/src/math.cin``,``math/util.cin`` 映射到
1039
+ ``codecin/lib/math/src/util.cin``。
1040
+ """
1041
+ rel = name.replace('\\', '/')
1042
+ if rel.startswith('lib/'):
1043
+ rel = rel[len('lib/'):]
1044
+ parts = [part for part in rel.split('/') if part]
1045
+ if not parts:
1046
+ return []
1047
+ head = parts[0]
1048
+ package = head[:-4] if head.endswith('.cin') else head
1049
+ if len(parts) == 1:
1050
+ module = head if head.endswith('.cin') else head + '.cin'
1051
+ return [os.path.join(_LIB_DIR, package, 'src', module)]
1052
+ return [os.path.join(_LIB_DIR, package, 'src', *parts[1:])]
1053
+
1054
+
1055
+ def _resolve_import(name: str, source_dir: str) -> List[str]:
1056
+ """解析 import 目标 (可能多个文件, 用于分块导入)。
1057
+
1058
+ 规则 (B3 + v6.2.x 包导入):
1059
+ * ``import "./x.cin"`` / ``import "../x.cin"`` —— 相对**当前 .cin 文件**所在目录;
1060
+ * 包规格 ``rich`` / ``rich:*`` / ``rich:table`` / ``rich::1.1.1:*``
1061
+ 按模块分块解析 (见 :mod:`codecin.packaging.spec`);
1062
+ * 其余形式先查 **codecin 内置标准库** ``codecin/lib/<name>/src/``
1063
+ (``lib/`` 前缀保留为兼容写法), 保持 "裸名字不会命中兄弟文件" 的既有语义;
1064
+ * 再查项目依赖目录 (``pic_modules`` / ``.mkn/deps`` / ``.pic/packages``)、
1065
+ ``CIN_PATH`` 与全局 pic 包存储; ``import "hello"`` 直接导入包入口,
1066
+ ``import "hello/util.cin"`` 导入包内文件。
1067
+ """
1068
+ if _is_relative_import(name):
1069
+ cand = os.path.normpath(os.path.join(source_dir, name))
1070
+ if os.path.isfile(cand):
1071
+ return [cand]
1072
+ raise CompilerError(
1073
+ f"Import file not found: {name!r} (相对引用, 已查找 {cand})")
1074
+
1075
+ if ':' in name:
1076
+ from .packaging.spec import SpecError, parse_package_spec
1077
+ try:
1078
+ spec = parse_package_spec(name)
1079
+ except SpecError:
1080
+ spec = None
1081
+ if spec is not None:
1082
+ targets = _resolve_package_chunks(spec, source_dir)
1083
+ if targets:
1084
+ return targets
1085
+ raise CompilerError(
1086
+ f"Import file not found: {name!r} (未找到包 {spec.name!r})。"
1087
+ f"先运行 `pic install {spec.name}`;指定版本用 "
1088
+ f"`import \"{spec.name}::<版本>:*\"`。")
1089
+
1090
+ candidates = [os.path.join(_LIB_DIR, name)]
1091
+ if name.startswith('lib/'):
1092
+ candidates.append(os.path.join(_LIB_DIR, name[len('lib/'):]))
1093
+ candidates.extend(_bundled_library_candidates(name))
1094
+ for cand in candidates:
1095
+ if os.path.isfile(cand):
1096
+ return [cand]
1097
+
1098
+ package = _resolve_package_import(name, source_dir)
1099
+ if package:
1100
+ return [package]
1101
+
1102
+ bundled = _bundled_library_candidates(name)
1103
+ bundled_hint = bundled[0] if bundled else os.path.join(_LIB_DIR, name)
1104
+ raise CompilerError(
1105
+ f"Import file not found: {name!r} (内置标准库已查找 "
1106
+ f"{bundled_hint}; 也未在项目 pic_modules/"
1107
+ f"CIN_PATH/已安装 pic 包中找到)。"
1108
+ f"如需导入第三方包, 先运行 `pic install <name>`。")
1109
+
1110
+
1111
+ def _collect_module_lines(path: str, loaded: set, active: set,
1112
+ out: List[Tuple[str, str]]) -> None:
1113
+ """深度优先收集 (源文件, 文本行) 序列 (import 处内联展开)。
1114
+
1115
+ 防重复: 每个 realpath 每编译一次仅包含一次; 循环引用报错。
1116
+ """
1117
+ real = os.path.realpath(os.path.abspath(path))
1118
+ if real in active:
1119
+ raise CompilerError(f"Circular import: {path} ({real})")
1120
+ if real in loaded:
1121
+ return
1122
+ active.add(real)
1123
+ with open(real, encoding='utf-8-sig') as f:
1124
+ # utf-8-sig: 容忍 Windows 编辑器写出的 BOM, 否则首行 `import ...`
1125
+ # 匹配不上 _IMPORT_RE, 会报一个与真实原因无关的解析错误
1126
+ lines = f.read().split('\n')
1127
+ for line in lines:
1128
+ m = _IMPORT_RE.match(line)
1129
+ if m:
1130
+ targets = _resolve_import(m.group(1), os.path.dirname(real))
1131
+ for target in targets:
1132
+ _collect_module_lines(target, loaded, active, out)
1133
+ continue
1134
+ out.append((real, line))
1135
+ active.discard(real)
1136
+ loaded.add(real)
1137
+
1138
+
1139
+ def load_program_source_mapped(path: str) -> Tuple[str, List[Optional[Tuple[str, int]]]]:
1140
+ """读取 CIN 并展开 import, 返回 (文本, 行来源表)。
1141
+
1142
+ origin[merged_line] = (源文件 realpath, 源文件内行号); origin[0] = None。
1143
+ """
1144
+ real = os.path.realpath(os.path.abspath(path))
1145
+ out: List[Tuple[str, str]] = []
1146
+ _collect_module_lines(real, set(), set(), out)
1147
+ counters: Dict[str, int] = {}
1148
+ origin: List[Optional[Tuple[str, int]]] = [None]
1149
+ for fname, _line in out:
1150
+ counters[fname] = counters.get(fname, 0) + 1
1151
+ origin.append((fname, counters[fname]))
1152
+ text = '\n'.join(line for _f, line in out)
1153
+ return text, origin
1154
+
1155
+
1156
+ def load_program_source(path: str) -> str:
1157
+ """读取 CIN 文件并展开 import (返回可直接 tokenize 的源码文本)。"""
1158
+ text, _origin = load_program_source_mapped(path)
1159
+ return text
1160
+
1161
+
1162
+ def collect_imported_files(path: str) -> List[str]:
1163
+ """返回 ``path`` 及其 import 闭包涉及的全部 .cin 真实路径。
1164
+
1165
+ 第一个元素恒为 ``path`` 自身, 其余为依赖模块 (去重保序)。供 AOT/打包等
1166
+ 需要在编译前检查依赖完整性的场景使用; import 缺失或循环引用时抛
1167
+ :class:`CompilerError`。
1168
+ """
1169
+ real = os.path.realpath(os.path.abspath(path))
1170
+ out: List[Tuple[str, str]] = []
1171
+ _collect_module_lines(real, set(), set(), out)
1172
+ files: List[str] = []
1173
+ for fname, _line in out:
1174
+ if fname not in files:
1175
+ files.append(fname)
1176
+ # 深度优先展开会让被依赖模块排在前面, 这里把主程序固定到首位
1177
+ if real in files:
1178
+ files.remove(real)
1179
+ return [real, *files]
1180
+
1181
+
1182
+ def _remap_tokens(tokens: List[Token], origin: List[Optional[Tuple[str, int]]]
1183
+ ) -> None:
1184
+ """把拼合文本中的 token 行号重定位到源文件 (file, line)。"""
1185
+ for tok in tokens:
1186
+ if 0 < tok.line < len(origin):
1187
+ ent = origin[tok.line]
1188
+ if ent is not None:
1189
+ tok.filename, tok.line = ent[0], ent[1]
1190
+
1191
+
1192
+ # ==================== 语法分析 ====================
1193
+
1194
+ @dataclass
1195
+ class StructDef:
1196
+ name: str
1197
+ fields: List[Tuple[str, Any]] = field(default_factory=list) # (name, type)
1198
+ offsets: Dict[str, int] = field(default_factory=dict) # qword 偏移
1199
+ size_slots: int = 0
1200
+
1201
+
1202
+ @dataclass
1203
+ class FuncDef:
1204
+ name: str
1205
+ params: List[Tuple[str, Any]]
1206
+ ret_type: Any
1207
+ body: list
1208
+ line: int
1209
+ extern: bool = False
1210
+
1211
+
1212
+ @dataclass
1213
+ class GlobalVar:
1214
+ name: str
1215
+ vtype: Any
1216
+ addr: int
1217
+ init: Optional[list] = None # AST 表达式
1218
+ array_lit: Optional[list] = None # 数组字面量行
1219
+ extern: bool = False
1220
+
1221
+
1222
+ class Parser:
1223
+ def __init__(self, tokens: List[Token]):
1224
+ self.toks = tokens
1225
+ self.pos = 0
1226
+ # 枚举: 成员名 -> 值 (编译期常量), 类型名集合 (等价 int)
1227
+ self.enums: Dict[str, int] = {}
1228
+ self.enum_types: Set[str] = set()
1229
+ # const 命名常量: 名字 -> (类型, Python 值); 纯编译期, 不占用数据段
1230
+ self.consts: Dict[str, Tuple[str, Any]] = {}
1231
+ self._range_id = 0
1232
+
1233
+ def peek(self, k: int = 0) -> Token:
1234
+ return self.toks[min(self.pos + k, len(self.toks) - 1)]
1235
+
1236
+ def next(self) -> Token:
1237
+ t = self.toks[self.pos]
1238
+ self.pos += 1
1239
+ return t
1240
+
1241
+ def accept(self, kind: str) -> Optional[Token]:
1242
+ if self.peek().kind == kind:
1243
+ return self.next()
1244
+ return None
1245
+
1246
+ def expect(self, kind: str) -> Token:
1247
+ t = self.peek()
1248
+ if t.kind != kind:
1249
+ raise CompilerError(f"Expected {kind} but got {t.kind} ({t.value!r}) "
1250
+ f"at {self._loc(t)}")
1251
+ return self.next()
1252
+
1253
+ def skip_nl(self) -> None:
1254
+ while self.accept('NL'):
1255
+ pass
1256
+
1257
+ def _loc(self, tok: Optional[Token] = None) -> str:
1258
+ """token 的 'file:line' 定位 (import 展开后为真实源文件)。"""
1259
+ t = tok if tok is not None else self.peek()
1260
+ return f"{t.filename or '<cin>'}:{t.line}"
1261
+
1262
+ # ---------------- 类型 ----------------
1263
+
1264
+ def parse_type(self) -> Any:
1265
+ t = self.expect('IDENT')
1266
+ base = t.value
1267
+ if base == 'unsigned':
1268
+ # unsigned [char|short|int|long]; 缺省为 int
1269
+ nxt = self.peek()
1270
+ if nxt.kind == 'IDENT' and nxt.value in ('char', 'short', 'int', 'long'):
1271
+ self.next()
1272
+ vtype = 'int'
1273
+ elif base in self.enum_types:
1274
+ # 枚举类型名等价于 int (成员是编译期整数常量)
1275
+ vtype = 'int'
1276
+ elif base in ('int', 'float', 'bool', 'string', 'void', 'char', 'short',
1277
+ 'long'):
1278
+ # char/short/long 为整数别名 (64 位槽模型, 与 int 同宽)
1279
+ vtype = 'int' if base in ('char', 'short', 'long') else base
1280
+ else:
1281
+ vtype = ('struct', base)
1282
+ # int[] / int[][] 形式 (后缀在类型名上)
1283
+ while self.peek().kind == 'LBRACKET' and self.peek(1).kind == 'RBRACKET':
1284
+ self.next()
1285
+ self.next()
1286
+ vtype = ('ptrarray', vtype)
1287
+ return vtype
1288
+
1289
+ def _is_decl_start(self) -> bool:
1290
+ """当前是否处于类型声明起始 (基础类型 / unsigned / struct 类型名)。"""
1291
+ t = self.peek()
1292
+ if t.kind != 'IDENT':
1293
+ return False
1294
+ v = t.value
1295
+ if v in BASE_TYPE_WORDS:
1296
+ return True
1297
+ if v == 'const':
1298
+ return True
1299
+ # struct 类型名 (裸标识符) 后跟另一个标识符 = 声明
1300
+ return v not in _KEYWORDS and self.peek(1).kind == 'IDENT'
1301
+
1302
+ def parse_dims(self) -> List[int]:
1303
+ """数组维度: 接受整型常量表达式 (`[4]`、`[N]`、`[2 + 3]`)。"""
1304
+ dims = []
1305
+ while self.peek().kind == 'LBRACKET':
1306
+ self.next()
1307
+ if self.peek().kind == 'RBRACKET':
1308
+ self.next()
1309
+ dims.append(0) # T[] 指针形式 (无尺寸)
1310
+ continue
1311
+ node = self.parse_expr()
1312
+ self.expect('RBRACKET')
1313
+ ctype, value = self._const_value_ast(node)
1314
+ if ctype not in ('int', 'bool'):
1315
+ raise CompilerError(
1316
+ f"array size must be an integer constant, got {ctype} "
1317
+ f"at {self._loc()}")
1318
+ n = int(value)
1319
+ if n < 0:
1320
+ raise CompilerError(
1321
+ f"array size must be non-negative, got {n}")
1322
+ dims.append(n)
1323
+ return dims
1324
+
1325
+ # ---------------- 程序 ----------------
1326
+
1327
+ def parse_program(self):
1328
+ structs: Dict[str, StructDef] = {}
1329
+ globals_: List[GlobalVar] = []
1330
+ functions: Dict[str, FuncDef] = {}
1331
+
1332
+ self.skip_nl()
1333
+ while self.peek().kind != 'EOF':
1334
+ if self.peek().kind == 'IDENT' and self.peek().value == 'struct':
1335
+ self._parse_struct(structs)
1336
+ elif self.peek().kind == 'IDENT' and self.peek().value == 'enum':
1337
+ self._parse_enum()
1338
+ elif self.peek().kind == 'IDENT' and self.peek().value == 'const':
1339
+ self._parse_const_decl()
1340
+ elif self.peek().kind == 'IDENT' and self.peek().value == 'function':
1341
+ f = self._parse_function()
1342
+ functions[f.name] = f
1343
+ elif self.peek().kind == 'IDENT' and self.peek().value == 'extern':
1344
+ if (self.peek(1).kind == 'IDENT'
1345
+ and self.peek(1).value == 'function'):
1346
+ f = self._parse_extern_function()
1347
+ functions[f.name] = f
1348
+ else:
1349
+ self._parse_extern_global(globals_)
1350
+ else:
1351
+ self._parse_global(globals_)
1352
+ self.skip_nl()
1353
+ return structs, globals_, functions, self.enums
1354
+
1355
+ # ---------------- 枚举 ----------------
1356
+
1357
+ def _parse_enum(self) -> None:
1358
+ """enum Name { A, B = 3, C } —— 成员为编译期整数常量 (自动递增)。"""
1359
+ tok = self.next() # enum
1360
+ name = self.expect('IDENT').value
1361
+ if name in _KEYWORDS or name in self.enum_types:
1362
+ raise CompilerError(f"Invalid enum name: {name} at {self._loc(tok)}")
1363
+ self.expect('LBRACE')
1364
+ self.skip_nl()
1365
+ value = 0
1366
+ count = 0
1367
+ while self.peek().kind not in ('RBRACE', 'EOF'):
1368
+ self.skip_nl()
1369
+ if self.peek().kind == 'RBRACE':
1370
+ break
1371
+ mtok = self.peek()
1372
+ mname = self.expect('IDENT').value
1373
+ if mname in self.enums:
1374
+ raise CompilerError(f"Duplicate enum member: {mname} at "
1375
+ f"{self._loc(mtok)}")
1376
+ if self.accept('ASSIGN'):
1377
+ value = self._eval_enum_const(self.parse_expr(), mname)
1378
+ if not (-(1 << 63) <= value <= (1 << 63) - 1):
1379
+ raise CompilerError(
1380
+ f"Enum member {mname} out of 64-bit range at "
1381
+ f"{self._loc(mtok)}")
1382
+ self.enums[mname] = value
1383
+ value += 1
1384
+ count += 1
1385
+ if not self.accept('COMMA'):
1386
+ break
1387
+ self.skip_nl()
1388
+ if count == 0:
1389
+ raise CompilerError(f"Empty enum {name} at {self._loc(tok)}")
1390
+ self.skip_nl() # 最后一个成员无尾逗号时, 先跳过换行再收 RBRACE
1391
+ self.expect('RBRACE')
1392
+ self.accept('SEMI')
1393
+ self.enum_types.add(name)
1394
+
1395
+ def _eval_enum_const(self, node, mname: str) -> int:
1396
+ """枚举成员初始值: 整数常量表达式 (可引用已定义的枚举成员)。"""
1397
+ kind = node[0]
1398
+ if kind == 'num' and not node[2]:
1399
+ return int(node[1])
1400
+ if kind == 'var':
1401
+ if node[1] in self.enums:
1402
+ return self.enums[node[1]]
1403
+ raise CompilerError(
1404
+ f"Enum member {mname} initializer must be an integer constant "
1405
+ f"(unknown name: {node[1]}) at {self._loc()}")
1406
+ if kind == 'neg':
1407
+ return -self._eval_enum_const(node[1], mname)
1408
+ if kind == 'bitnot':
1409
+ return ~self._eval_enum_const(node[1], mname)
1410
+ if kind == 'binop':
1411
+ op = node[1]
1412
+ if op not in ('+', '-', '*', '/', '%', '<<', '>>', '&', '|', '^'):
1413
+ raise CompilerError(
1414
+ f"Enum member {mname} initializer must be an integer "
1415
+ f"constant expression at {self._loc()}")
1416
+ a = self._eval_enum_const(node[2], mname)
1417
+ b = self._eval_enum_const(node[3], mname)
1418
+ if op in ('/', '%') and b == 0:
1419
+ raise CompilerError(
1420
+ f"Enum member {mname} initializer divides by zero")
1421
+ if op == '+':
1422
+ return a + b
1423
+ if op == '-':
1424
+ return a - b
1425
+ if op == '*':
1426
+ return a * b
1427
+ if op == '/':
1428
+ return _trunc_div(a, b)
1429
+ if op == '%':
1430
+ return a - _trunc_div(a, b) * b
1431
+ if op == '<<':
1432
+ return a << b
1433
+ if op == '>>':
1434
+ return a >> b
1435
+ if op == '&':
1436
+ return a & b
1437
+ if op == '|':
1438
+ return a | b
1439
+ return a ^ b
1440
+ raise CompilerError(
1441
+ f"Enum member {mname} initializer must be an integer constant "
1442
+ f"expression at {self._loc()}")
1443
+
1444
+ def _const_value_ast(self, node) -> Tuple[str, Any]:
1445
+ """编译期常量求值, 返回 (类型, Python 值)。
1446
+
1447
+ 供 `const` 声明、数组维度与枚举之外的常量上下文使用。
1448
+ 支持 int / float / bool / string 以及它们的算术与位运算 (字符串仅 `+`)。
1449
+ """
1450
+ kind = node[0]
1451
+ if kind == 'num':
1452
+ return ('float', float(node[1])) if node[2] else ('int', int(node[1]))
1453
+ if kind == 'bool':
1454
+ return ('bool', bool(node[1]))
1455
+ if kind == 'str':
1456
+ return ('string', node[1])
1457
+ if kind == 'var':
1458
+ if node[1] in self.consts:
1459
+ return self.consts[node[1]]
1460
+ if node[1] in self.enums:
1461
+ return ('int', self.enums[node[1]])
1462
+ raise CompilerError(
1463
+ f"Constant expression uses non-constant name '{node[1]}' "
1464
+ f"at {self._loc()} "
1465
+ "(hint: array lengths must be compile-time constants; "
1466
+ f"declare it as `const int {node[1]} = ...`; "
1467
+ "variable-length arrays are not supported — use a fixed-size "
1468
+ "array plus a count variable)")
1469
+ if kind == 'neg':
1470
+ ctype, value = self._const_value_ast(node[1])
1471
+ if ctype == 'string':
1472
+ raise CompilerError("Cannot negate a string constant")
1473
+ return (ctype, -value)
1474
+ if kind == 'bitnot':
1475
+ ctype, value = self._const_value_ast(node[1])
1476
+ if ctype not in ('int', 'bool'):
1477
+ raise CompilerError(
1478
+ f"Bitwise NOT requires an integer constant, got {ctype}")
1479
+ return ('int', ~int(value))
1480
+ if kind == 'binop':
1481
+ op = node[1]
1482
+ if op not in ('+', '-', '*', '/', '%', '<<', '>>', '&', '|', '^'):
1483
+ raise CompilerError(
1484
+ f"Operator '{op}' is not allowed in a constant expression "
1485
+ f"at {self._loc()}")
1486
+ at, av = self._const_value_ast(node[2])
1487
+ bt, bv = self._const_value_ast(node[3])
1488
+ if at == 'string' or bt == 'string':
1489
+ if op == '+' and at == 'string' and bt == 'string':
1490
+ return ('string', av + bv)
1491
+ raise CompilerError(
1492
+ "String constants only support the '+' operator")
1493
+ if at == 'float' or bt == 'float':
1494
+ if op not in ('+', '-', '*', '/'):
1495
+ raise CompilerError(
1496
+ f"Operator '{op}' requires integer constants")
1497
+ a, b = float(av), float(bv)
1498
+ if op == '+':
1499
+ return ('float', a + b)
1500
+ if op == '-':
1501
+ return ('float', a - b)
1502
+ if op == '*':
1503
+ return ('float', a * b)
1504
+ if b == 0.0:
1505
+ raise CompilerError("Constant expression divides by zero")
1506
+ return ('float', a / b)
1507
+ a, b = int(av), int(bv)
1508
+ if op in ('/', '%') and b == 0:
1509
+ raise CompilerError("Constant expression divides by zero")
1510
+ if op == '+':
1511
+ return ('int', a + b)
1512
+ if op == '-':
1513
+ return ('int', a - b)
1514
+ if op == '*':
1515
+ return ('int', a * b)
1516
+ if op == '/':
1517
+ return ('int', _trunc_div(a, b))
1518
+ if op == '%':
1519
+ return ('int', a - _trunc_div(a, b) * b)
1520
+ if op == '<<':
1521
+ return ('int', a << b)
1522
+ if op == '>>':
1523
+ return ('int', a >> b)
1524
+ if op == '&':
1525
+ return ('int', a & b)
1526
+ if op == '|':
1527
+ return ('int', a | b)
1528
+ return ('int', a ^ b)
1529
+ raise CompilerError(
1530
+ f"Not a constant expression at {self._loc()}")
1531
+
1532
+ def _parse_const_decl(self) -> list:
1533
+ """`const <类型> 名字 = <常量表达式> [, ...]` (全局或局部)。
1534
+
1535
+ 命名常量是**纯编译期**的: 不占用数据段、不产生任何指令, 因此可以用在
1536
+ 数组维度、全局初始化器与任意表达式里。
1537
+ """
1538
+ self.next() # const
1539
+ if self.peek().kind != 'IDENT' or self.peek().value not in BASE_TYPE_WORDS:
1540
+ t = self.peek()
1541
+ raise CompilerError(
1542
+ f"const needs a scalar type (int/float/bool/string) at "
1543
+ f"{self._loc(t)}")
1544
+ vtype = self.parse_type()
1545
+ while True:
1546
+ ntok = self.peek()
1547
+ name = self.expect('IDENT').value
1548
+ if name in _KEYWORDS:
1549
+ raise CompilerError(
1550
+ f"Invalid const name '{name}' at {self._loc(ntok)}")
1551
+ if name in self.enums:
1552
+ raise CompilerError(
1553
+ f"Name '{name}' is already an enum member at "
1554
+ f"{self._loc(ntok)}")
1555
+ if name in self.consts:
1556
+ raise CompilerError(
1557
+ f"Duplicate const: {name} at {self._loc(ntok)}")
1558
+ self.expect('ASSIGN')
1559
+ ctype, value = self._const_value_ast(self.parse_assign())
1560
+ # 按声明的类型规范化 (int←float 向零截断、bool←非零、float←数值提升)
1561
+ if vtype == 'string':
1562
+ if ctype != 'string':
1563
+ raise CompilerError(
1564
+ f"const string {name} must be initialized with a string")
1565
+ elif vtype == 'float':
1566
+ if ctype == 'string':
1567
+ raise CompilerError(
1568
+ f"const float {name} must be initialized with a number")
1569
+ ctype, value = 'float', float(value)
1570
+ elif vtype == 'bool':
1571
+ if ctype == 'string':
1572
+ raise CompilerError(
1573
+ f"const bool {name} must be initialized with a number")
1574
+ ctype, value = 'bool', bool(value)
1575
+ else:
1576
+ if ctype == 'string':
1577
+ raise CompilerError(
1578
+ f"const int {name} must be initialized with a number")
1579
+ ctype, value = 'int', int(value)
1580
+ self.consts[name] = (ctype, value)
1581
+ if not self.accept('COMMA'):
1582
+ break
1583
+ return []
1584
+
1585
+ def _parse_struct(self, structs: Dict[str, StructDef]) -> None:
1586
+ self.next() # struct
1587
+ name = self.expect('IDENT').value
1588
+ self.expect('LBRACE')
1589
+ self.skip_nl()
1590
+ sd = StructDef(name=name)
1591
+ off = 0
1592
+ while self.peek().kind != 'RBRACE':
1593
+ ftype = self.parse_type()
1594
+ fname = self.expect('IDENT').value
1595
+ dims = self.parse_dims()
1596
+ t = ftype
1597
+ for d in reversed(dims):
1598
+ t = ('array', t, d) if d else ('ptrarray', t)
1599
+ if _is_fixed_array(t) and _has_struct(t[1]):
1600
+ raise CompilerError(
1601
+ f'struct array field {name}.{fname} is not supported '
1602
+ f'(elements would need separate objects); use a fixed '
1603
+ f'array of struct variables instead')
1604
+ sd.fields.append((fname, t))
1605
+ sd.offsets[fname] = off
1606
+ off += _struct_slots(t, structs)
1607
+ self.accept('SEMI')
1608
+ self.skip_nl()
1609
+ self.expect('RBRACE')
1610
+ sd.size_slots = off
1611
+ structs[name] = sd
1612
+ self.accept('SEMI')
1613
+
1614
+ def _parse_function(self) -> FuncDef:
1615
+ line = self.next().line # function
1616
+ name = self.expect('IDENT').value
1617
+ self.expect('LPAREN')
1618
+ params: List[Tuple[str, Any]] = []
1619
+ while self.peek().kind != 'RPAREN':
1620
+ ptype = self.parse_type()
1621
+ pname = self.expect('IDENT').value
1622
+ dims = self.parse_dims()
1623
+ for d in reversed(dims):
1624
+ ptype = ('array', ptype, d) if d else ('ptrarray', ptype)
1625
+ params.append((pname, ptype))
1626
+ if not self.accept('COMMA'):
1627
+ break
1628
+ self.expect('RPAREN')
1629
+ ret_type: Any = 'void'
1630
+ if self.accept('ARROW'):
1631
+ ret_type = self.parse_type()
1632
+ self.expect('LBRACE')
1633
+ body = self.parse_block_body(RBRACE_TOKENS)
1634
+ self.expect('RBRACE')
1635
+ return FuncDef(name, params, ret_type, body, line)
1636
+
1637
+ def _parse_extern_function(self) -> FuncDef:
1638
+ """extern function name(params) -> type —— 只声明, 由链接器解析符号。"""
1639
+ line = self.next().line # extern
1640
+ kw = self.expect('IDENT')
1641
+ if kw.value != 'function':
1642
+ raise CompilerError(
1643
+ f"Expected 'function' after 'extern' at {self._loc(kw)}")
1644
+ name = self.expect('IDENT').value
1645
+ self.expect('LPAREN')
1646
+ params: List[Tuple[str, Any]] = []
1647
+ while self.peek().kind != 'RPAREN':
1648
+ ptype = self.parse_type()
1649
+ pname = self.expect('IDENT').value
1650
+ dims = self.parse_dims()
1651
+ for d in reversed(dims):
1652
+ ptype = ('array', ptype, d) if d else ('ptrarray', ptype)
1653
+ params.append((pname, ptype))
1654
+ if not self.accept('COMMA'):
1655
+ break
1656
+ self.expect('RPAREN')
1657
+ ret_type: Any = 'void'
1658
+ if self.accept('ARROW'):
1659
+ ret_type = self.parse_type()
1660
+ self.accept('SEMI')
1661
+ return FuncDef(name, params, ret_type, [], line, extern=True)
1662
+
1663
+ def _parse_global(self, globals_: List[GlobalVar]) -> None:
1664
+ vtype = self.parse_type()
1665
+ while True:
1666
+ name_tok = self.peek()
1667
+ name = self.expect('IDENT').value
1668
+ if name in self.enums or name in _KEYWORDS:
1669
+ raise CompilerError(f"Name '{name}' is already used as an enum "
1670
+ f"member or keyword at {self._loc(name_tok)}")
1671
+ if name in self.consts:
1672
+ raise CompilerError(
1673
+ f"Name '{name}' is already a const at "
1674
+ f"{self._loc(name_tok)}")
1675
+ dims = self.parse_dims()
1676
+ t = vtype
1677
+ for d in reversed(dims):
1678
+ t = ('array', t, d) if d else ('ptrarray', t)
1679
+ gv = GlobalVar(name=name, vtype=t, addr=0)
1680
+ if self.accept('ASSIGN'):
1681
+ if self.peek().kind == 'LBRACE':
1682
+ gv.array_lit = self.parse_array_literal()
1683
+ else:
1684
+ gv.init = self.parse_expr()
1685
+ globals_.append(gv)
1686
+ if not self.accept('COMMA'):
1687
+ break
1688
+ self.accept('SEMI')
1689
+
1690
+ def _parse_extern_global(self, globals_: List[GlobalVar]) -> None:
1691
+ """extern <type> name —— 只声明全局符号, 由链接器解析。"""
1692
+ self.next() # extern
1693
+ vtype = self.parse_type()
1694
+ while True:
1695
+ name = self.expect('IDENT').value
1696
+ dims = self.parse_dims()
1697
+ t = vtype
1698
+ for d in reversed(dims):
1699
+ t = ('array', t, d) if d else ('ptrarray', t)
1700
+ globals_.append(GlobalVar(name=name, vtype=t, addr=0,
1701
+ extern=True))
1702
+ if not self.accept('COMMA'):
1703
+ break
1704
+ self.accept('SEMI')
1705
+
1706
+ def parse_array_literal(self) -> list:
1707
+ self.expect('LBRACE')
1708
+ rows: list = []
1709
+ current: list = []
1710
+ while self.peek().kind != 'RBRACE':
1711
+ if self.accept('LBRACE'):
1712
+ inner = []
1713
+ while self.peek().kind != 'RBRACE':
1714
+ inner.append(self.parse_expr())
1715
+ if not self.accept('COMMA'):
1716
+ break
1717
+ self.expect('RBRACE')
1718
+ rows.append(inner)
1719
+ else:
1720
+ current.append(self.parse_expr())
1721
+ if not self.accept('COMMA'):
1722
+ break
1723
+ self.expect('RBRACE')
1724
+ if rows:
1725
+ # 混合写法 {{1, 2}, 7}: 尾部的平铺元素也必须保留, 否则会被静默丢弃
1726
+ # (旧实现 `return rows if rows else current` 让 7 凭空消失)。
1727
+ if current:
1728
+ rows.append(current)
1729
+ return rows
1730
+ return current
1731
+
1732
+ # ---------------- 语句 ----------------
1733
+
1734
+ def parse_block_body(self, _unused=None) -> list:
1735
+ stmts = []
1736
+ self.skip_nl()
1737
+ while self.peek().kind not in ('RBRACE', 'EOF'):
1738
+ stmts.append(self.parse_stmt())
1739
+ self.skip_nl()
1740
+ return stmts
1741
+
1742
+ def parse_stmt(self):
1743
+ t = self.peek()
1744
+ if t.kind == 'LBRACE':
1745
+ self.next()
1746
+ body = self.parse_block_body()
1747
+ self.expect('RBRACE')
1748
+ return ('block', body)
1749
+ if t.kind == 'IDENT' and t.value == 'assert':
1750
+ return self.parse_assert()
1751
+ if t.kind == 'IDENT' and t.value == 'return':
1752
+ self.next()
1753
+ expr = None if self.peek().kind in ('NL', 'SEMI', 'RBRACE') else self.parse_expr()
1754
+ self.accept('SEMI')
1755
+ return ('return', expr)
1756
+ if t.kind == 'IDENT' and t.value == 'if':
1757
+ return self.parse_if()
1758
+ if t.kind == 'IDENT' and t.value == 'while':
1759
+ self.next()
1760
+ cond = self.parse_paren_expr()
1761
+ body = self.parse_stmt()
1762
+ return ('while', cond, body)
1763
+ if t.kind == 'IDENT' and t.value == 'for':
1764
+ return self.parse_for()
1765
+ if t.kind == 'IDENT' and t.value == 'do':
1766
+ return self.parse_do()
1767
+ if t.kind == 'IDENT' and t.value == 'switch':
1768
+ return self.parse_switch()
1769
+ if t.kind == 'IDENT' and t.value == 'break':
1770
+ self.next()
1771
+ self.accept('SEMI')
1772
+ return ('break',)
1773
+ if t.kind == 'IDENT' and t.value == 'continue':
1774
+ self.next()
1775
+ self.accept('SEMI')
1776
+ return ('continue',)
1777
+ if self._is_decl_start():
1778
+ return self.parse_decl()
1779
+ if t.kind == 'IDENT' and t.value in ('set', 'add', 'subtract', 'multiply',
1780
+ 'divide', 'increment', 'decrement'):
1781
+ return self.parse_cpu_stmt()
1782
+ # 表达式语句 / 赋值
1783
+ expr = self.parse_assign()
1784
+ self.accept('SEMI')
1785
+ return ('expr', expr)
1786
+
1787
+ def parse_assign(self):
1788
+ target = self.parse_expr()
1789
+ t = self.peek().kind
1790
+ if t == 'ASSIGN':
1791
+ self.next()
1792
+ value = self.parse_assign()
1793
+ return ('binop', '=', target, value)
1794
+ if t in _COMPOUND_ASSIGN:
1795
+ self.next()
1796
+ value = self.parse_assign()
1797
+ return ('binop', _COMPOUND_ASSIGN[t], target, value)
1798
+ return target
1799
+
1800
+ def parse_do(self):
1801
+ self.next() # do
1802
+ body = self.parse_stmt()
1803
+ self.skip_nl()
1804
+ if not (self.peek().kind == 'IDENT' and self.peek().value == 'while'):
1805
+ raise CompilerError("Expected 'while' after do body at "
1806
+ f"{self._loc()}")
1807
+ self.next()
1808
+ cond = self.parse_paren_expr()
1809
+ self.accept('SEMI')
1810
+ return ('dowhile', body, cond)
1811
+
1812
+ def parse_switch(self):
1813
+ self.next() # switch
1814
+ cond = self.parse_paren_expr()
1815
+ self.expect('LBRACE')
1816
+ self.skip_nl()
1817
+ # branches: [('case', const_expr|None, [stmt,...])] (None = default)
1818
+ branches = []
1819
+ cur: Optional[Tuple[Any, list]] = None
1820
+ while self.peek().kind not in ('RBRACE', 'EOF'):
1821
+ self.skip_nl()
1822
+ t = self.peek()
1823
+ if t.kind == 'IDENT' and t.value == 'case':
1824
+ if cur is not None:
1825
+ branches.append(cur)
1826
+ self.next()
1827
+ alts = self._parse_case_alts()
1828
+ self.expect('COLON')
1829
+ cur = ('case', alts, [])
1830
+ elif t.kind == 'IDENT' and t.value == 'default':
1831
+ if cur is not None:
1832
+ branches.append(cur)
1833
+ self.next()
1834
+ self.expect('COLON')
1835
+ cur = ('case', None, [])
1836
+ else:
1837
+ if cur is None:
1838
+ raise CompilerError(
1839
+ "Statement before first case in switch at "
1840
+ f"{self._loc(t)}")
1841
+ cur[2].append(self.parse_stmt())
1842
+ self.skip_nl()
1843
+ if cur is not None:
1844
+ branches.append(cur)
1845
+ self.expect('RBRACE')
1846
+ if not branches:
1847
+ raise CompilerError(f"Empty switch at {self._loc()}")
1848
+ return ('switch', cond, branches)
1849
+
1850
+ def _parse_case_alts(self) -> list:
1851
+ """case 值列表: 单值 / 范围 1..5 / 多值 1, 2, 7..9 (逗号分隔)。"""
1852
+ alts: list = []
1853
+ while True:
1854
+ low = self.parse_expr()
1855
+ if self.accept('DOTDOT'):
1856
+ high = self.parse_expr()
1857
+ alts.append(('range', low, high))
1858
+ else:
1859
+ alts.append(('val', low))
1860
+ if not self.accept('COMMA'):
1861
+ break
1862
+ return alts
1863
+
1864
+ def parse_assert(self):
1865
+ tok = self.peek()
1866
+ self.next() # assert
1867
+ self.expect('LPAREN')
1868
+ cond = self.parse_expr()
1869
+ msg = None
1870
+ if self.accept('COMMA'):
1871
+ msg = self.parse_expr()
1872
+ self.expect('RPAREN')
1873
+ self.accept('SEMI')
1874
+ return ('assert', cond, msg, tok.line, tok.filename)
1875
+
1876
+ def parse_if(self):
1877
+ self.next()
1878
+ cond = self.parse_paren_expr()
1879
+ then_body = self.parse_stmt()
1880
+ else_body = None
1881
+ self.skip_nl()
1882
+ if self.peek().kind == 'IDENT' and self.peek().value == 'else':
1883
+ self.next()
1884
+ self.skip_nl()
1885
+ else_body = self.parse_stmt()
1886
+ return ('if', cond, then_body, else_body)
1887
+
1888
+ def parse_for(self):
1889
+ self.next() # for
1890
+ self.expect('LPAREN')
1891
+ if self._is_range_for():
1892
+ return self._parse_range_for()
1893
+ # init
1894
+ init = None
1895
+ if self.peek().kind != 'SEMI':
1896
+ if self._is_decl_start():
1897
+ init = self.parse_decl(no_semi=True)
1898
+ else:
1899
+ # 允许赋值表达式作初始化子句: for (i = 0; ...)
1900
+ init = ('expr', self.parse_assign())
1901
+ self.expect('SEMI')
1902
+ cond = None
1903
+ if self.peek().kind != 'SEMI':
1904
+ cond = self.parse_expr()
1905
+ self.expect('SEMI')
1906
+ update = None
1907
+ if self.peek().kind != 'RPAREN':
1908
+ update = ('expr', self.parse_assign())
1909
+ self.expect('RPAREN')
1910
+ body = self.parse_stmt()
1911
+ return ('for', init, cond, update, body)
1912
+
1913
+ def _is_range_for(self) -> bool:
1914
+ """判定 for (T v : arr) 形式 (LPAREN 已消费)。"""
1915
+ if self.peek().kind != 'IDENT':
1916
+ return False
1917
+ v = self.peek().value
1918
+ if v == 'unsigned':
1919
+ return (self.peek(1).kind == 'IDENT'
1920
+ and self.peek(1).value in ('char', 'short', 'int', 'long')
1921
+ and self.peek(2).kind == 'IDENT'
1922
+ and self.peek(3).kind == 'COLON')
1923
+ if v in BASE_TYPE_WORDS:
1924
+ return self.peek(1).kind == 'IDENT' and self.peek(2).kind == 'COLON'
1925
+ if v in _KEYWORDS:
1926
+ return False
1927
+ return self.peek(1).kind == 'IDENT' and self.peek(2).kind == 'COLON'
1928
+
1929
+ def _parse_range_for(self):
1930
+ """for (T v : arr) —— 遍历定长数组元素 (元素类型为标量/struct)。"""
1931
+ elem_type = self.parse_type()
1932
+ vname = self.expect('IDENT').value
1933
+ if vname in self.enums:
1934
+ raise CompilerError(f"Invalid range-for variable: {vname} at "
1935
+ f"{self._loc()}")
1936
+ self.expect('COLON')
1937
+ arr = self.parse_expr()
1938
+ self.expect('RPAREN')
1939
+ body = self.parse_stmt()
1940
+ self._range_id += 1
1941
+ return ('rangefor', vname, elem_type, arr, body, self._range_id)
1942
+
1943
+ def parse_decl(self, no_semi: bool = False):
1944
+ if self.peek().kind == 'IDENT' and self.peek().value == 'const':
1945
+ # 局部 const: 注册为编译期常量, 不产生存储与指令
1946
+ self._parse_const_decl()
1947
+ if not no_semi:
1948
+ self.accept('SEMI')
1949
+ return ('decl', [])
1950
+ vtype = self.parse_type()
1951
+ decls = []
1952
+ while True:
1953
+ name = self.expect('IDENT').value
1954
+ dims = self.parse_dims()
1955
+ t = vtype
1956
+ for d in reversed(dims):
1957
+ t = ('array', t, d) if d else ('ptrarray', t)
1958
+ init = None
1959
+ array_lit = None
1960
+ if self.accept('ASSIGN'):
1961
+ if self.peek().kind == 'LBRACE':
1962
+ array_lit = self.parse_array_literal()
1963
+ else:
1964
+ init = self.parse_expr()
1965
+ decls.append((name, t, init, array_lit))
1966
+ if not self.accept('COMMA'):
1967
+ break
1968
+ if not no_semi:
1969
+ self.accept('SEMI')
1970
+ return ('decl', decls)
1971
+
1972
+ def parse_cpu_stmt(self):
1973
+ op = self.next().value
1974
+ operands = []
1975
+ while self.peek().kind not in ('NL', 'SEMI', 'EOF'):
1976
+ tok = self.next()
1977
+ operands.append((tok.kind, tok.value))
1978
+ self.accept('SEMI')
1979
+ return ('cpu', op, operands)
1980
+
1981
+ def parse_paren_expr(self):
1982
+ self.expect('LPAREN')
1983
+ e = self.parse_expr()
1984
+ self.expect('RPAREN')
1985
+ return e
1986
+
1987
+ # ---------------- 表达式 ----------------
1988
+
1989
+ def parse_expr(self):
1990
+ e = self.parse_or()
1991
+ if self.accept('QUESTION'):
1992
+ a = self.parse_assign()
1993
+ self.expect('COLON')
1994
+ b = self.parse_assign()
1995
+ return ('cond', e, a, b)
1996
+ return e
1997
+
1998
+ def parse_or(self):
1999
+ left = self.parse_and()
2000
+ while self.peek().kind == 'OR':
2001
+ self.next()
2002
+ right = self.parse_and()
2003
+ left = ('binop', '||', left, right)
2004
+ return left
2005
+
2006
+ def parse_and(self):
2007
+ left = self.parse_bit_or()
2008
+ while self.peek().kind == 'AND':
2009
+ self.next()
2010
+ right = self.parse_bit_or()
2011
+ left = ('binop', '&&', left, right)
2012
+ return left
2013
+
2014
+ def parse_bit_or(self):
2015
+ left = self.parse_bit_xor()
2016
+ while self.peek().kind == 'PIPE':
2017
+ self.next()
2018
+ right = self.parse_bit_xor()
2019
+ left = ('binop', '|', left, right)
2020
+ return left
2021
+
2022
+ def parse_bit_xor(self):
2023
+ left = self.parse_bit_and()
2024
+ while self.peek().kind == 'CARET':
2025
+ self.next()
2026
+ right = self.parse_bit_and()
2027
+ left = ('binop', '^', left, right)
2028
+ return left
2029
+
2030
+ def parse_bit_and(self):
2031
+ left = self.parse_equality()
2032
+ while self.peek().kind == 'AMP':
2033
+ self.next()
2034
+ right = self.parse_equality()
2035
+ left = ('binop', '&', left, right)
2036
+ return left
2037
+
2038
+ def parse_equality(self):
2039
+ left = self.parse_relational()
2040
+ while self.peek().kind in ('EQ', 'NEQ'):
2041
+ op = '==' if self.next().kind == 'EQ' else '!='
2042
+ right = self.parse_relational()
2043
+ left = ('binop', op, left, right)
2044
+ return left
2045
+
2046
+ def parse_relational(self):
2047
+ left = self.parse_shift()
2048
+ while self.peek().kind in ('LT', 'GT', 'LE', 'GE'):
2049
+ tok = self.next()
2050
+ op = {'LT': '<', 'GT': '>', 'LE': '<=', 'GE': '>='}[tok.kind]
2051
+ right = self.parse_shift()
2052
+ left = ('binop', op, left, right)
2053
+ return left
2054
+
2055
+ def parse_shift(self):
2056
+ left = self.parse_additive()
2057
+ while self.peek().kind in ('SHL', 'SHR'):
2058
+ op = '<<' if self.next().kind == 'SHL' else '>>'
2059
+ right = self.parse_additive()
2060
+ left = ('binop', op, left, right)
2061
+ return left
2062
+
2063
+ def parse_additive(self):
2064
+ left = self.parse_multiplicative()
2065
+ while self.peek().kind in ('PLUS', 'MINUS'):
2066
+ op = '+' if self.next().kind == 'PLUS' else '-'
2067
+ right = self.parse_multiplicative()
2068
+ left = ('binop', op, left, right)
2069
+ return left
2070
+
2071
+ def parse_multiplicative(self):
2072
+ left = self.parse_unary()
2073
+ while self.peek().kind in ('STAR', 'SLASH', 'PERCENT'):
2074
+ tok = self.next()
2075
+ op = {'STAR': '*', 'SLASH': '/', 'PERCENT': '%'}[tok.kind]
2076
+ right = self.parse_unary()
2077
+ left = ('binop', op, left, right)
2078
+ return left
2079
+
2080
+ def parse_unary(self):
2081
+ if self.peek().kind == 'BANG':
2082
+ self.next()
2083
+ return ('not', self.parse_unary())
2084
+ if self.peek().kind == 'TILDE':
2085
+ self.next()
2086
+ return ('bitnot', self.parse_unary())
2087
+ if self.peek().kind == 'MINUS':
2088
+ self.next()
2089
+ return ('neg', self.parse_unary())
2090
+ if self.peek().kind == 'INC':
2091
+ self.next()
2092
+ return ('preinc', self.parse_unary())
2093
+ if self.peek().kind == 'DEC':
2094
+ self.next()
2095
+ return ('predec', self.parse_unary())
2096
+ return self.parse_postfix()
2097
+
2098
+ def parse_postfix(self):
2099
+ e = self.parse_primary()
2100
+ while True:
2101
+ if self.peek().kind == 'LBRACKET':
2102
+ self.next()
2103
+ idx = self.parse_expr()
2104
+ self.expect('RBRACKET')
2105
+ e = ('index', e, idx)
2106
+ elif self.peek().kind == 'DOT':
2107
+ self.next()
2108
+ name = self.expect('IDENT').value
2109
+ e = ('member', e, name)
2110
+ elif self.peek().kind == 'INC':
2111
+ self.next()
2112
+ e = ('postinc', e)
2113
+ elif self.peek().kind == 'DEC':
2114
+ self.next()
2115
+ e = ('postdec', e)
2116
+ else:
2117
+ break
2118
+ return e
2119
+
2120
+ def parse_primary(self):
2121
+ t = self.peek()
2122
+ if t.kind == 'NUMBER':
2123
+ self.next()
2124
+ return ('num', t.value, False)
2125
+ if t.kind == 'FLOAT':
2126
+ self.next()
2127
+ return ('num', t.value, True)
2128
+ if t.kind == 'STRING':
2129
+ self.next()
2130
+ return ('str', t.value)
2131
+ if t.kind == 'IDENT' and t.value == 'true':
2132
+ self.next()
2133
+ return ('bool', True)
2134
+ if t.kind == 'IDENT' and t.value == 'false':
2135
+ self.next()
2136
+ return ('bool', False)
2137
+ if t.kind == 'LPAREN':
2138
+ return self.parse_paren_expr()
2139
+ if t.kind == 'IDENT':
2140
+ name = self.next().value
2141
+ if self.peek().kind == 'LPAREN':
2142
+ self.next()
2143
+ args = []
2144
+ while self.peek().kind != 'RPAREN':
2145
+ args.append(self.parse_expr())
2146
+ if not self.accept('COMMA'):
2147
+ break
2148
+ self.expect('RPAREN')
2149
+ return ('call', name, args)
2150
+ return ('var', name)
2151
+ raise CompilerError(f"Unexpected token {t.kind} ({t.value!r}) "
2152
+ f"at {self._loc(t)}")
2153
+
2154
+
2155
+ RBRACE_TOKENS = None
2156
+
2157
+
2158
+ # ==================== 代码生成 ====================
2159
+
2160
+ class CompileResult:
2161
+ def __init__(self):
2162
+ self.instructions: List[Instruction] = []
2163
+ self.labels: Dict[str, int] = {}
2164
+ self.data_labels: Dict[str, int] = {}
2165
+ self.data_writes: List[Tuple[int, bytes]] = []
2166
+ self.data_relocations: List[Tuple[int, int, str, int]] = []
2167
+
2168
+
2169
+ class CINCompiler:
2170
+ def __init__(self, console: Optional[Console] = None, logger=None):
2171
+ self.console = console or Console()
2172
+ self.logger = logger
2173
+
2174
+ def compile(self, filename: str, bounds_check: bool = False,
2175
+ relocatable: bool = False) -> CompileResult:
2176
+ source, origin = load_program_source_mapped(filename)
2177
+ return self.compile_source(source, filename,
2178
+ bounds_check=bounds_check, origin=origin,
2179
+ relocatable=relocatable)
2180
+
2181
+ def compile_source(self, source: str, filename: str = '<cin>',
2182
+ bounds_check: bool = False,
2183
+ origin: Optional[List[Optional[Tuple[str, int]]]] = None,
2184
+ relocatable: bool = False
2185
+ ) -> CompileResult:
2186
+ dbg = self.logger.debug if (self.logger and self.logger.is_debug) \
2187
+ else (lambda msg: None)
2188
+ tokens = tokenize(source, origin)
2189
+ if origin:
2190
+ _remap_tokens(tokens, origin)
2191
+ dbg(f"CIN tokenize: {len(tokens)} tokens")
2192
+ parser = Parser(tokens)
2193
+ structs, globals_, functions, enums = parser.parse_program()
2194
+ dbg(f"CIN parse: {len(structs)} structs, {len(globals_)} globals, "
2195
+ f"{len(functions)} functions "
2196
+ f"({', '.join(list(functions)[:8])}"
2197
+ f"{', ...' if len(functions) > 8 else ''})")
2198
+ if enums:
2199
+ dbg(f"CIN enums: {len(enums)} members")
2200
+ for name, fn in functions.items():
2201
+ dbg(f"CIN function {name}: {len(fn.params)} params")
2202
+
2203
+ gen = CodeGen(structs, functions, filename=filename,
2204
+ bounds_check=bounds_check, enums=enums,
2205
+ consts=parser.consts, relocatable=relocatable)
2206
+ gen.layout_globals(globals_)
2207
+ for name, (typ, addr, block) in gen.globals.items():
2208
+ dbg(f"CIN global '{name}': type={typ} addr=0x{addr:x} block={block}")
2209
+ result = gen.generate(globals_, functions)
2210
+ for name in functions:
2211
+ dbg(f"CIN codegen function '{name}' done")
2212
+ dbg(f"CIN codegen total: {len(result.instructions)} instructions, "
2213
+ f"{sum(len(d) for _, d in result.data_writes)} data bytes, "
2214
+ f"{len(result.labels)} labels, {len(result.data_writes)} data writes")
2215
+ return result
2216
+
2217
+
2218
+ class CodeGen:
2219
+ def __init__(self, structs: Dict[str, StructDef],
2220
+ functions: Dict[str, FuncDef], filename: str = '<cin>',
2221
+ bounds_check: bool = False,
2222
+ enums: Optional[Dict[str, int]] = None,
2223
+ consts: Optional[Dict[str, Tuple[str, Any]]] = None,
2224
+ relocatable: bool = False):
2225
+ self.structs = structs
2226
+ self.functions = functions
2227
+ self.enums: Dict[str, int] = dict(enums or {})
2228
+ self.consts: Dict[str, Tuple[str, Any]] = dict(consts or {})
2229
+ self.res = CompileResult()
2230
+ self._filename = filename
2231
+ self._bounds = bounds_check
2232
+ self.relocatable = relocatable
2233
+
2234
+ self.data_ptr = 0
2235
+ self.heap_strings: Dict[str, int] = {}
2236
+
2237
+ # 函数生成上下文
2238
+ self.func: Optional[FuncDef] = None
2239
+ self.locals: Dict[str, Tuple[Any, int, bool]] = {} # name -> (type, off, is_block)
2240
+ self.frame_bytes = 0
2241
+ self.break_labels: List[str] = []
2242
+ self.continue_labels: List[str] = []
2243
+ self.label_counter = 0
2244
+
2245
+ self.globals: Dict[str, Tuple[Any, int, bool]] = {} # name -> (type, addr, is_block)
2246
+ self.extern_globals: Dict[str, Any] = {}
2247
+ #: 全局 struct 变量的堆对象地址 (单 struct 一个, struct 数组每元素一个)
2248
+ self.struct_blocks: Dict[str, List[int]] = {}
2249
+
2250
+ # ---------------- 发射辅助 ----------------
2251
+
2252
+ def emit(self, op: str, *args: Operand) -> int:
2253
+ self.res.instructions.append((op, list(args)))
2254
+ return len(self.res.instructions) - 1
2255
+
2256
+ def label(self, name: str) -> None:
2257
+ self.res.labels[name] = len(self.res.instructions)
2258
+
2259
+ def new_label(self, hint: str) -> str:
2260
+ self.label_counter += 1
2261
+ return f"_{hint}_{self.label_counter}"
2262
+
2263
+ @staticmethod
2264
+ def reg(n: int) -> Operand:
2265
+ return ('reg', n)
2266
+
2267
+ @staticmethod
2268
+ def imm(v: int) -> Operand:
2269
+ return ('imm', v & 0xFFFFFFFFFFFFFFFF)
2270
+
2271
+ def lab(self, name: str) -> Operand:
2272
+ return ('label', name)
2273
+
2274
+ # ---------------- 数据段 ----------------
2275
+
2276
+ def _alloc_data(self, nbytes: int, align: int = 8) -> int:
2277
+ if align > 1:
2278
+ self.data_ptr = (self.data_ptr + align - 1) & ~(align - 1)
2279
+ addr = self.data_ptr
2280
+ self.data_ptr += nbytes
2281
+ return addr
2282
+
2283
+ def _data_string(self, text: str) -> int:
2284
+ if text in self.heap_strings:
2285
+ return self.heap_strings[text]
2286
+ # surrogateescape: \xNN (0x80-0xFF) 以代理码位承载, 原样写回单字节
2287
+ data = text.encode('utf-8', 'surrogateescape') + b'\x00'
2288
+ addr = self._alloc_data(len(data), align=1)
2289
+ self.res.data_writes.append((addr, data))
2290
+ self.res.data_labels[f'str_{addr:x}'] = addr
2291
+ self.heap_strings[text] = addr
2292
+ return addr
2293
+
2294
+ def _data_operand(self, addr: int):
2295
+ """数据地址操作数: 普通编译为 imm, 对象模式保留可重定位符号。"""
2296
+ if not self.relocatable:
2297
+ return self.imm(addr)
2298
+ return ('reloc', self._data_symbol(addr), 0)
2299
+
2300
+ def _data_symbol(self, addr: int) -> str:
2301
+ for name, value in self.res.data_labels.items():
2302
+ if value == addr:
2303
+ return name
2304
+ name = f'data_{addr:x}'
2305
+ self.res.data_labels[name] = addr
2306
+ return name
2307
+
2308
+ def _write_pointer(self, addr: int, target: int) -> None:
2309
+ """写入 8 字节数据指针; 对象模式下登记数据内重定位。"""
2310
+ if self.relocatable:
2311
+ self.res.data_writes.append((addr, b'\x00' * 8))
2312
+ self.res.data_relocations.append(
2313
+ (addr, 8, self._data_symbol(target), 0))
2314
+ else:
2315
+ self.res.data_writes.append(
2316
+ (addr, struct.pack('<Q', target & 0xFFFFFFFFFFFFFFFF)))
2317
+
2318
+ def _write_const(self, addr: int, ftype, ctype: str, raw: int) -> None:
2319
+ if ctype == 'string' or ftype == 'string':
2320
+ self._write_pointer(addr, raw)
2321
+ return
2322
+ self.res.data_writes.append(
2323
+ (addr, struct.pack('<Q', self._coerce_const(ftype, ctype, raw))))
2324
+
2325
+ def _data_qword(self, value: int) -> int:
2326
+ addr = self._alloc_data(8)
2327
+ self.res.data_writes.append((addr, struct.pack('<Q', value & 0xFFFFFFFFFFFFFFFF)))
2328
+ return addr
2329
+
2330
+ def layout_globals(self, globals_: List[GlobalVar]) -> None:
2331
+ for gv in globals_:
2332
+ if gv.extern:
2333
+ self.extern_globals[gv.name] = gv.vtype
2334
+ self.globals[gv.name] = (gv.vtype, 0, False)
2335
+ continue
2336
+ t = gv.vtype
2337
+ if _is_fixed_array(t):
2338
+ addr = self._alloc_data(_type_slots(t) * 8)
2339
+ self.globals[gv.name] = (t, addr, True)
2340
+ gv.addr = addr
2341
+ self.res.data_labels[f'global_{gv.name}'] = addr
2342
+ if self._contains_struct(t[1]):
2343
+ # 定长 struct 数组: 每个元素槽存一个堆对象指针
2344
+ self._layout_struct_array(t, addr, gv.name)
2345
+ else:
2346
+ addr = self._alloc_data(8)
2347
+ self.globals[gv.name] = (t, addr, False)
2348
+ gv.addr = addr
2349
+ self.res.data_labels[f'global_{gv.name}'] = addr
2350
+ if _is_struct(t):
2351
+ sd = self.structs[t[1]]
2352
+ block = self._alloc_data(sd.size_slots * 8)
2353
+ self.struct_blocks[gv.name] = [block]
2354
+ self._write_pointer(addr, block)
2355
+
2356
+ def _layout_struct_array(self, t, addr: int, name: str) -> None:
2357
+ """为全局定长 struct 数组的每个元素分配堆对象并写入指针槽。"""
2358
+ elem = t[1]
2359
+ if not _is_struct(elem):
2360
+ raise CompilerError(
2361
+ f'multi-dimensional struct array {name} is not supported; '
2362
+ f'flatten to a one-dimensional array')
2363
+ sd = self.structs[elem[1]]
2364
+ blocks: List[int] = []
2365
+ for i in range(t[2]):
2366
+ block = self._alloc_data(max(sd.size_slots, 1) * 8)
2367
+ blocks.append(block)
2368
+ self._write_pointer(addr + i * 8, block)
2369
+ self.struct_blocks[name] = blocks
2370
+
2371
+ # ---------------- 初始化数据 ----------------
2372
+
2373
+ def _const_value(self, node) -> Tuple[Any, int]:
2374
+ """编译期常量 (全局初始化用): 返回 (type, raw_bits/addr)。"""
2375
+ kind = node[0]
2376
+ if kind == 'num':
2377
+ if node[2]:
2378
+ return 'float', struct.unpack('<Q', struct.pack('<d', node[1]))[0]
2379
+ return 'int', node[1] & 0xFFFFFFFFFFFFFFFF
2380
+ if kind == 'bool':
2381
+ return 'bool', 1 if node[1] else 0
2382
+ if kind == 'var' and node[1] in self.consts:
2383
+ # const 命名常量可用于全局初始化器
2384
+ ctype, value = self.consts[node[1]]
2385
+ if ctype == 'float':
2386
+ return 'float', struct.unpack('<Q', struct.pack('<d', float(value)))[0]
2387
+ if ctype == 'string':
2388
+ return 'string', self._data_string(value)
2389
+ if ctype == 'bool':
2390
+ return 'bool', 1 if value else 0
2391
+ return 'int', int(value) & 0xFFFFFFFFFFFFFFFF
2392
+ if kind == 'var' and node[1] in self.enums:
2393
+ # 枚举成员: 编译期整数常量 (可用于全局初始化与 case 标签)
2394
+ return 'int', self.enums[node[1]] & 0xFFFFFFFFFFFFFFFF
2395
+ if kind == 'str':
2396
+ return 'string', self._data_string(node[1])
2397
+ if kind == 'neg' and node[1][0] == 'num':
2398
+ inner = node[1]
2399
+ if inner[2]:
2400
+ return 'float', struct.unpack('<Q', struct.pack('<d', -inner[1]))[0]
2401
+ return 'int', (-inner[1]) & 0xFFFFFFFFFFFFFFFF
2402
+ if kind == 'bitnot':
2403
+ ctype, raw = self._const_value(node[1])
2404
+ if ctype not in ('int', 'bool'):
2405
+ raise CompilerError(f"Bitwise NOT requires integer, got: {ctype}")
2406
+ return 'int', (~raw) & 0xFFFFFFFFFFFFFFFF
2407
+ raise CompilerError(f"Non-constant global initializer: {kind}")
2408
+
2409
+ def _const_int(self, node) -> int:
2410
+ """case 常量: 整数常量表达式 (支持枚举成员), 返回有符号 64 位值。"""
2411
+ try:
2412
+ ctype, raw = self._const_value(node)
2413
+ except CompilerError:
2414
+ raise CompilerError(
2415
+ "case value must be an integer constant") from None
2416
+ if ctype not in ('int', 'bool'):
2417
+ raise CompilerError(
2418
+ f"case value must be an integer constant, got: {ctype}")
2419
+ raw &= 0xFFFFFFFFFFFFFFFF
2420
+ return raw - (1 << 64) if raw >= (1 << 63) else raw
2421
+
2422
+ @staticmethod
2423
+ def _decode_const(ctype: str, raw: int):
2424
+ if ctype == 'float':
2425
+ return struct.unpack('<d', struct.pack('<Q', raw))[0]
2426
+ if ctype == 'bool':
2427
+ return bool(raw)
2428
+ if ctype == 'string':
2429
+ return int(raw) & 0xFFFFFFFFFFFFFFFF
2430
+ return raw if raw < (1 << 63) else raw - (1 << 64)
2431
+
2432
+ def _coerce_const(self, ftype: str, ctype: str, raw: int) -> int:
2433
+ """把编译期常量按字段类型重新编码 (float→int 向零截断等)。"""
2434
+ if ftype == 'string':
2435
+ if ctype != 'string':
2436
+ raise CompilerError(
2437
+ 'struct initializer for a string field must be a string')
2438
+ return int(raw) & 0xFFFFFFFFFFFFFFFF
2439
+ if ctype == 'string':
2440
+ raise CompilerError(
2441
+ f'struct initializer for a {ftype} field must be numeric')
2442
+ value = self._decode_const(ctype, raw)
2443
+ if ftype == 'float':
2444
+ return struct.unpack('<Q', struct.pack('<d', float(value)))[0]
2445
+ if ftype == 'bool':
2446
+ return 1 if value else 0
2447
+ return int(value) & 0xFFFFFFFFFFFFFFFF
2448
+
2449
+ def _emit_struct_const_init(self, block: int, sname: str, leaves,
2450
+ items) -> None:
2451
+ """把全局 struct 的常量初始化器写进它的堆对象 (布局期已定址)。"""
2452
+ if len(items) > len(leaves):
2453
+ raise CompilerError(
2454
+ f'Too many initializers for struct {sname}: got {len(items)}, '
2455
+ f'expected at most {len(leaves)}')
2456
+ for idx, elem in enumerate(items):
2457
+ off, ftype = leaves[idx]
2458
+ ctype, raw = self._const_value(elem)
2459
+ self._write_const(block + off * 8, ftype, ctype, raw)
2460
+
2461
+ def emit_globals_init(self, globals_: List[GlobalVar]) -> None:
2462
+ for gv in globals_:
2463
+ if gv.extern:
2464
+ continue
2465
+ t, addr, is_block = self.globals[gv.name]
2466
+ if gv.init is not None:
2467
+ ctype, raw = self._const_value(gv.init)
2468
+ self._write_const(addr, t, ctype, raw)
2469
+ elif gv.array_lit is not None:
2470
+ if _is_struct(t):
2471
+ self._emit_struct_const_init(
2472
+ self.struct_blocks[gv.name][0], t[1],
2473
+ self._struct_leaf_slots(t),
2474
+ self._flatten_literal(gv.array_lit))
2475
+ continue
2476
+ if _is_fixed_array(t) and _is_struct(t[1]):
2477
+ elem = t[1]
2478
+ leaves = self._struct_leaf_slots(elem)
2479
+ rows = gv.array_lit if (gv.array_lit
2480
+ and isinstance(gv.array_lit[0], list)) \
2481
+ else [gv.array_lit]
2482
+ blocks = self.struct_blocks.get(gv.name, [])
2483
+ if len(rows) > len(blocks):
2484
+ raise CompilerError(
2485
+ f'Too many initializers for struct array {gv.name}: '
2486
+ f'got {len(rows)}, expected at most {len(blocks)}')
2487
+ for i, row in enumerate(rows):
2488
+ self._emit_struct_const_init(
2489
+ blocks[i], elem[1], leaves,
2490
+ self._flatten_literal(row))
2491
+ continue
2492
+ rows = gv.array_lit
2493
+ if rows and isinstance(rows[0], list):
2494
+ # 2D 字面量: 仅 ptrarray 有意义 (int[][] mat1 = ...)
2495
+ # 全局 2D 定长数组按行写入
2496
+ for i, row in enumerate(rows):
2497
+ for j, elem in enumerate(row):
2498
+ ctype, raw = self._const_value(elem)
2499
+ self._write_const(
2500
+ addr + (i * len(row) + j) * 8,
2501
+ t[1], ctype, raw)
2502
+ else:
2503
+ for i, elem in enumerate(rows):
2504
+ ctype, raw = self._const_value(elem)
2505
+ self._write_const(addr + i * 8, t[1], ctype, raw)
2506
+
2507
+ # ---------------- 主生成 ----------------
2508
+
2509
+ def generate(self, globals_: List[GlobalVar],
2510
+ functions: Dict[str, FuncDef]) -> CompileResult:
2511
+ self.emit_globals_init(globals_)
2512
+
2513
+ # 入口: CALL main; HALT
2514
+ self.emit('CALL', self.lab('main'))
2515
+ self.emit('HALT')
2516
+
2517
+ for _fname, fdef in functions.items():
2518
+ if fdef.extern:
2519
+ continue
2520
+ self.gen_function(fdef)
2521
+
2522
+ return self.res
2523
+
2524
+ # ---------------- 栈帧 ----------------
2525
+
2526
+ def _prescan_locals(self, body: list) -> List[Tuple[str, Any, int]]:
2527
+ """收集函数内所有局部声明 (含 for 初始化), 返回 (name,type,slots)。"""
2528
+ found: List[Tuple[str, Any, int]] = []
2529
+ seen = set()
2530
+
2531
+ def walk(stmts):
2532
+ for s in stmts:
2533
+ kind = s[0]
2534
+ if kind == 'decl':
2535
+ for name, t, _init, _al in s[1]:
2536
+ if name in seen:
2537
+ continue
2538
+ seen.add(name)
2539
+ found.append((name, t, _type_slots(t)))
2540
+ elif kind == 'block':
2541
+ walk(s[1])
2542
+ elif kind == 'if':
2543
+ walk([s[2]])
2544
+ if s[3]:
2545
+ walk([s[3]])
2546
+ elif kind == 'while':
2547
+ walk([s[2]])
2548
+ elif kind == 'dowhile':
2549
+ walk([s[1]])
2550
+ elif kind == 'switch':
2551
+ for _bk, _const, stmts in s[2]:
2552
+ walk(stmts)
2553
+ elif kind == 'for':
2554
+ if s[1] is not None and s[1][0] == 'decl':
2555
+ for name, t, _i, _a in s[1][1]:
2556
+ if name not in seen:
2557
+ seen.add(name)
2558
+ found.append((name, t, _type_slots(t)))
2559
+ walk([s[4]])
2560
+ elif kind == 'rangefor':
2561
+ _vname, _etype, _arr, _rbody, hid = (s[1], s[2], s[3],
2562
+ s[4], s[5])
2563
+ for nm, ty in ((_vname, _etype),
2564
+ (f'$rf{hid}p', 'int'),
2565
+ (f'$rf{hid}e', 'int')):
2566
+ if nm in seen:
2567
+ continue
2568
+ seen.add(nm)
2569
+ found.append((nm, ty, _type_slots(ty)))
2570
+ walk([_rbody])
2571
+ walk(body)
2572
+ return found
2573
+
2574
+ def gen_function(self, f: FuncDef) -> None:
2575
+ self.func = f
2576
+ self.locals = {}
2577
+ self.break_labels = []
2578
+ self.continue_labels = []
2579
+
2580
+ # 局部变量布局 (自 FP 向下分配):
2581
+ # 标量槽地址 = fp-(8+off); 数组块基址 = fp-(off+slots*8)
2582
+ # (元素从基址向高地址生长, 不与后续变量冲突)
2583
+ locals_info = self._prescan_locals(f.body)
2584
+ off = 0
2585
+ for name, t, slots in locals_info:
2586
+ self.locals[name] = (t, -(off + slots * 8), _is_fixed_array(t))
2587
+ off += slots * 8
2588
+ self.frame_bytes = off
2589
+
2590
+ # 参数位置 (相对 FP): fp+16 为第一个压栈参数 (最左)
2591
+ # 帧布局: [参数...][返回地址(fp+8)][保存的FP(fp)][局部...]
2592
+ nargs = len(f.params)
2593
+ for k, (pname, ptype) in enumerate(f.params):
2594
+ poff = 16 + (nargs - 1 - k) * 8
2595
+ self.locals[pname] = (ptype, poff, False)
2596
+
2597
+ self.label(f.name)
2598
+ # prologue: 保存调用方 FP, 建立帧指针, 分配局部空间。
2599
+ # 帧分配走 SYS ALLOCFRAME (带栈溢出防护): 此前直接 ADDI SP 减帧长,
2600
+ # 局部大数组会把 SP 推到负地址 —— 轻则报晦涩的越界地址
2601
+ # (如 address ffff...c6f8), 重则静默覆盖全局/堆内存。
2602
+ self.emit('PUSH', self.reg(29))
2603
+ self.emit('MOV', self.reg(29), self.reg(32)) # FP = SP
2604
+ if self.frame_bytes:
2605
+ self.emit('MOV', self.reg(0), self.imm(self.frame_bytes))
2606
+ self.emit('SYS', self.imm(Syscall.ALLOCFRAME))
2607
+
2608
+ # struct 局部变量: 堆分配对象 (槽里存对象指针, 与全局 struct 同一模型)
2609
+ for _name, (t, loff, _is_block) in list(self.locals.items()):
2610
+ if loff >= 0: # 参数槽不拥有对象
2611
+ continue
2612
+ if _is_struct(t):
2613
+ self._alloc_struct_slot(t, loff)
2614
+ elif _is_fixed_array(t) and self._contains_struct(t[1]):
2615
+ self._alloc_struct_array_slots(t, loff)
2616
+
2617
+ self.gen_stmts(f.body)
2618
+
2619
+ # epilogue
2620
+ self._epilogue()
2621
+
2622
+ def _epilogue(self) -> None:
2623
+ # 不得破坏 x0 (返回值)
2624
+ self.emit('MOV', self.reg(6), self.reg(29)) # SP = FP
2625
+ self.emit('MOV', self.reg(32), self.reg(6))
2626
+ self.emit('POP', self.reg(29)) # 恢复调用方 FP
2627
+ self.emit('RET')
2628
+
2629
+ def _addr_local(self, off: int) -> None:
2630
+ """x0 = FP + off (局部 off 为负, 参数 off 为正)。"""
2631
+ if off == 0:
2632
+ self.emit('MOV', self.reg(0), self.reg(29))
2633
+ else:
2634
+ self.emit('ADDI', self.reg(0), self.reg(29), self.imm(off))
2635
+
2636
+ def _addr_var(self, name: str) -> None:
2637
+ """x0 = 变量槽地址。"""
2638
+ if name in self.locals:
2639
+ _t, off, _is_block = self.locals[name]
2640
+ self._addr_local(off)
2641
+ elif name in self.extern_globals:
2642
+ if not self.relocatable:
2643
+ raise CompilerError(
2644
+ f"extern global '{name}' requires object/link compilation")
2645
+ self.emit('MOV', self.reg(0), ('reloc', f'global_{name}', 0))
2646
+ elif name in self.globals:
2647
+ _t, addr, _is_block = self.globals[name]
2648
+ self.emit('MOV', self.reg(0), self._data_operand(addr))
2649
+ else:
2650
+ raise CompilerError(f"Undefined variable: {name}")
2651
+
2652
+ def _var_type(self, name: str):
2653
+ if name in self.locals:
2654
+ return self.locals[name][0]
2655
+ if name in self.globals:
2656
+ return self.globals[name][0]
2657
+ return None
2658
+
2659
+ # ---------------- 语句 ----------------
2660
+
2661
+ def gen_stmts(self, stmts: list) -> None:
2662
+ for s in stmts:
2663
+ self.gen_stmt(s)
2664
+
2665
+ def gen_stmt(self, s) -> None:
2666
+ kind = s[0]
2667
+ if kind == 'block':
2668
+ self.gen_stmts(s[1])
2669
+ elif kind == 'return':
2670
+ if s[1] is not None:
2671
+ t = self.gen_value(s[1])
2672
+ self._convert(t, self.func.ret_type)
2673
+ self._epilogue()
2674
+ elif kind == 'if':
2675
+ self.gen_if(s[1], s[2], s[3])
2676
+ elif kind == 'while':
2677
+ self.gen_while(s[1], s[2])
2678
+ elif kind == 'for':
2679
+ self.gen_for(s[1], s[2], s[3], s[4])
2680
+ elif kind == 'rangefor':
2681
+ self.gen_rangefor(s[1], s[2], s[3], s[4], s[5])
2682
+ elif kind == 'dowhile':
2683
+ self.gen_dowhile(s[1], s[2])
2684
+ elif kind == 'switch':
2685
+ self.gen_switch(s[1], s[2])
2686
+ elif kind == 'break':
2687
+ if not self.break_labels:
2688
+ raise CompilerError("break outside loop")
2689
+ self.emit('JMP', self.lab(self.break_labels[-1]))
2690
+ elif kind == 'continue':
2691
+ if not self.continue_labels:
2692
+ raise CompilerError("continue outside loop")
2693
+ self.emit('JMP', self.lab(self.continue_labels[-1]))
2694
+ elif kind == 'decl':
2695
+ self.gen_decl(s[1])
2696
+ elif kind == 'cpu':
2697
+ self.gen_cpu_stmt(s[1], s[2])
2698
+ elif kind == 'assert':
2699
+ self.gen_assert(s[1], s[2], s[3],
2700
+ s[4] if len(s) > 4 else self._filename)
2701
+ elif kind == 'expr':
2702
+ self.gen_expr_stmt(s[1])
2703
+
2704
+ def gen_if(self, cond, then_body, else_body) -> None:
2705
+ l_else = self.new_label('else')
2706
+ l_end = self.new_label('endif')
2707
+ target = l_else if else_body is not None else l_end
2708
+ self.gen_cond_jump_false(cond, target)
2709
+ self.gen_stmt(then_body)
2710
+ if else_body is not None:
2711
+ self.emit('JMP', self.lab(l_end))
2712
+ self.label(l_else)
2713
+ self.gen_stmt(else_body)
2714
+ self.label(l_end)
2715
+
2716
+ def gen_while(self, cond, body) -> None:
2717
+ l_start = self.new_label('while')
2718
+ l_end = self.new_label('wend')
2719
+ self.label(l_start)
2720
+ self.gen_cond_jump_false(cond, l_end)
2721
+ self.break_labels.append(l_end)
2722
+ self.continue_labels.append(l_start)
2723
+ self.gen_stmt(body)
2724
+ self.emit('JMP', self.lab(l_start))
2725
+ self.break_labels.pop()
2726
+ self.continue_labels.pop()
2727
+ self.label(l_end)
2728
+
2729
+ def gen_for(self, init, cond, update, body) -> None:
2730
+ if init is not None:
2731
+ self.gen_stmt(init)
2732
+ l_cond = self.new_label('forc')
2733
+ l_update = self.new_label('foru')
2734
+ l_end = self.new_label('fore')
2735
+ self.label(l_cond)
2736
+ if cond is not None:
2737
+ self.gen_cond_jump_false(cond, l_end)
2738
+ self.break_labels.append(l_end)
2739
+ self.continue_labels.append(l_update)
2740
+ self.gen_stmt(body)
2741
+ self.label(l_update)
2742
+ if update is not None:
2743
+ self.gen_stmt(update)
2744
+ self.emit('JMP', self.lab(l_cond))
2745
+ self.break_labels.pop()
2746
+ self.continue_labels.pop()
2747
+ self.label(l_end)
2748
+
2749
+ def gen_rangefor(self, vname, elem_type, arrexpr, body, hid) -> None:
2750
+ """for (T v : arr) —— 遍历定长数组 (元素为 1 槽: 标量/struct/指针)。
2751
+
2752
+ 展开为指针游走: p = &arr[0]; e = p + N*8;
2753
+ while (p < e) { v = *p; body; p += 8 }
2754
+ """
2755
+ if _is_fixed_array(elem_type) or _is_ptr_array(elem_type):
2756
+ raise CompilerError(
2757
+ "range-for element type must be a scalar or struct, got: "
2758
+ f"{elem_type}")
2759
+ at = self._expr_type(arrexpr)
2760
+ if not _is_fixed_array(at):
2761
+ raise CompilerError(
2762
+ f"range-for requires a fixed-size array (element type of the "
2763
+ f"iterated expression: {at})")
2764
+ elem_t, count = at[1], at[2]
2765
+ if _is_fixed_array(elem_t):
2766
+ raise CompilerError(
2767
+ "range-for over multi-dimensional arrays is not supported; "
2768
+ "use an index loop")
2769
+ pname = f'$rf{hid}p'
2770
+ ename = f'$rf{hid}e'
2771
+ l_loop = self.new_label('rfloop')
2772
+ l_inc = self.new_label('rfinc')
2773
+ l_end = self.new_label('rfend')
2774
+
2775
+ # p = &arr[0] (定长数组取值即块地址)
2776
+ self.gen_value(arrexpr)
2777
+ self._store_x0_local(pname)
2778
+ # e = p + count*8
2779
+ self._gen_var_value(pname)
2780
+ self.emit('ADDI', self.reg(0), self.reg(0), self.imm(count * 8))
2781
+ self._store_x0_local(ename)
2782
+
2783
+ self.label(l_loop)
2784
+ # p >= e 时退出 (gen_cond_jump_false 在条件为假时跳转)
2785
+ self.gen_cond_jump_false(('binop', '<', ('var', pname), ('var', ename)),
2786
+ l_end)
2787
+ # v = *p
2788
+ self._gen_var_value(pname)
2789
+ self.emit('LD', self.reg(0), ('mem', 0, 0))
2790
+ self._convert(elem_t, elem_type)
2791
+ self._store_x0_local(vname)
2792
+ self.break_labels.append(l_end)
2793
+ self.continue_labels.append(l_inc)
2794
+ self.gen_stmt(body)
2795
+ self.break_labels.pop()
2796
+ self.continue_labels.pop()
2797
+ # p += 8
2798
+ self.label(l_inc)
2799
+ self._gen_var_value(pname)
2800
+ self.emit('ADDI', self.reg(0), self.reg(0), self.imm(8))
2801
+ self._store_x0_local(pname)
2802
+ self.emit('JMP', self.lab(l_loop))
2803
+ self.label(l_end)
2804
+
2805
+ def _store_x0_local(self, name: str) -> None:
2806
+ """把 x0 存入局部变量槽 (不破坏 x0 之外的约定)。"""
2807
+ self.emit('MOV', self.reg(2), self.reg(0))
2808
+ self._addr_var(name)
2809
+ self.emit('SD', self.reg(2), ('mem', 0, 0))
2810
+
2811
+ def gen_dowhile(self, body, cond) -> None:
2812
+ l_body = self.new_label('dbody')
2813
+ l_cond = self.new_label('dcond')
2814
+ l_end = self.new_label('dend')
2815
+ self.label(l_body)
2816
+ self.break_labels.append(l_end)
2817
+ self.continue_labels.append(l_cond)
2818
+ self.gen_stmt(body)
2819
+ self.label(l_cond)
2820
+ self.gen_cond_jump_false(cond, l_end)
2821
+ self.emit('JMP', self.lab(l_body))
2822
+ self.break_labels.pop()
2823
+ self.continue_labels.pop()
2824
+ self.label(l_end)
2825
+
2826
+ def gen_switch(self, cond, branches) -> None:
2827
+ """switch: 选择器压栈, CMP 链分派, case 体按文字顺序内联 (C 贯穿语义)。"""
2828
+ sel_t = self._expr_type(cond)
2829
+ if sel_t not in ('int', 'bool'):
2830
+ raise CompilerError(
2831
+ f"Switch expression must be integer, got: {sel_t}")
2832
+ l_end = self.new_label('swend')
2833
+ self.break_labels.append(l_end)
2834
+ # continue 必须先把选择器弹出再跳, 否则每轮迭代泄漏 8 字节栈直至撞堆。
2835
+ # 只有在循环内 (存在外层 continue 目标) 才接管 continue, 否则保持
2836
+ # "continue outside loop" 报错语义。
2837
+ outer_cont = self.continue_labels[-1] if self.continue_labels else None
2838
+ l_cont = None
2839
+ if outer_cont is not None:
2840
+ l_cont = self.new_label('swcont')
2841
+ self.continue_labels.append(l_cont)
2842
+ self.gen_value(cond)
2843
+ self.emit('PUSH', self.reg(0)) # [SP] = selector
2844
+
2845
+ labels: List[Tuple[Optional[list], str]] = []
2846
+ default_lbl: Optional[str] = None
2847
+ for _kind, alts, _stmts in branches:
2848
+ if alts is None:
2849
+ lbl = self.new_label('swdef')
2850
+ default_lbl = lbl
2851
+ labels.append((None, lbl))
2852
+ continue
2853
+ compiled: List[Tuple[str, int, int]] = []
2854
+ for alt in alts:
2855
+ if alt[0] == 'range':
2856
+ low = self._const_int(alt[1])
2857
+ high = self._const_int(alt[2])
2858
+ if low > high:
2859
+ raise CompilerError(
2860
+ f"Empty case range: {low}..{high}")
2861
+ compiled.append(('range', low, high))
2862
+ else:
2863
+ compiled.append(('val', self._const_int(alt[1]), 0))
2864
+ labels.append((compiled, self.new_label('swcase')))
2865
+
2866
+ # 分派比较链 (多值/范围展开为多个比较, 顺序不影响语义)
2867
+ for compiled, lbl in labels:
2868
+ if compiled is None:
2869
+ continue
2870
+ for item in compiled:
2871
+ if item[0] == 'val':
2872
+ self.emit('LD', self.reg(0), ('mem', 32, 0))
2873
+ self.emit('MOV', self.reg(1), self.imm(item[1]))
2874
+ self.emit('CMP', self.reg(0), self.reg(1))
2875
+ self.emit('B', self.lab(lbl), ('cond', 'EQ'))
2876
+ else:
2877
+ l_skip = self.new_label('swrng')
2878
+ self.emit('LD', self.reg(0), ('mem', 32, 0))
2879
+ self.emit('MOV', self.reg(1), self.imm(item[1]))
2880
+ self.emit('CMP', self.reg(0), self.reg(1))
2881
+ self.emit('B', self.lab(l_skip), ('cond', 'LT'))
2882
+ self.emit('LD', self.reg(0), ('mem', 32, 0))
2883
+ self.emit('MOV', self.reg(1), self.imm(item[2]))
2884
+ self.emit('CMP', self.reg(0), self.reg(1))
2885
+ self.emit('B', self.lab(lbl), ('cond', 'LE'))
2886
+ self.label(l_skip)
2887
+ self.emit('JMP', self.lab(default_lbl if default_lbl is not None
2888
+ else l_end))
2889
+
2890
+ # case/default 体 (inline, 贯穿)
2891
+ for idx, (_kind, _const, stmts) in enumerate(branches):
2892
+ self.label(labels[idx][1])
2893
+ self.gen_stmts(stmts)
2894
+
2895
+ # 贯穿到末尾与 break 都必须走弹出选择器的路径
2896
+ self.emit('JMP', self.lab(l_end))
2897
+ if l_cont is not None:
2898
+ self.label(l_cont)
2899
+ self.emit('ADDI', self.reg(32), self.reg(32), self.imm(8))
2900
+ self.emit('JMP', self.lab(outer_cont))
2901
+ self.continue_labels.pop()
2902
+ self.label(l_end)
2903
+ self.break_labels.pop()
2904
+ self.emit('ADDI', self.reg(32), self.reg(32), self.imm(8)) # 丢 selector
2905
+
2906
+ # ---------------- struct 存储模型 ----------------
2907
+ #
2908
+ # struct 值在槽里恒为"堆对象指针"(局部与全局一致); 定长 struct 数组的
2909
+ # 每个元素槽同样存指针。此前数组元素被当作"值内嵌", 而成员访问又会把元素槽
2910
+ # 当指针解引用, 于是 `ps[0].y = 1` 实际写到绝对地址 8, 静默破坏数据段。
2911
+
2912
+ def _contains_struct(self, t) -> bool:
2913
+ """类型内部是否含 struct (数组元素递归)。"""
2914
+ return _has_struct(t)
2915
+
2916
+ def _alloc_struct_slot(self, t, loff: int) -> None:
2917
+ """为 struct 槽分配堆对象、清零, 并把对象指针写入槽。
2918
+
2919
+ 文档承诺 struct 字段默认为类型默认值, 但 MALLOC 并不清零
2920
+ (Python 与 Go 侧一致), 所以这里显式清零, 不再依赖"堆恰好是新的"。
2921
+ """
2922
+ sd = self.structs[t[1]]
2923
+ self.emit('MOV', self.reg(0), self.imm(sd.size_slots * 8))
2924
+ self.emit('SYS', self.imm(Syscall.MALLOC))
2925
+ self.emit('MOV', self.reg(3), self.reg(0)) # x3 = 对象基址
2926
+ if sd.size_slots:
2927
+ self.emit('MOV', self.reg(1), self.imm(0)) # x1 = 0
2928
+ self.emit('MOV', self.reg(2), self.reg(0)) # x2 = 清零游标
2929
+ for k in range(sd.size_slots):
2930
+ if k:
2931
+ self.emit('ADDI', self.reg(2), self.reg(2), self.imm(8))
2932
+ self.emit('SD', self.reg(1), ('mem', 2, 0))
2933
+ self._addr_local(loff) # x0 = &槽
2934
+ self.emit('SD', self.reg(3), ('mem', 0, 0))
2935
+
2936
+ def _alloc_struct_array_slots(self, t, loff: int) -> None:
2937
+ """定长 struct 数组: 每个元素一个堆对象, 元素槽存指针。"""
2938
+ elem = t[1]
2939
+ if not _is_struct(elem):
2940
+ raise CompilerError(
2941
+ 'multi-dimensional struct arrays are not supported; '
2942
+ 'flatten to a one-dimensional array')
2943
+ for i in range(t[2]):
2944
+ self._alloc_struct_slot(elem, loff + i * 8)
2945
+
2946
+ def _struct_leaf_slots(self, t, base: int = 0) -> List[Tuple[int, Any]]:
2947
+ """把 struct 摊平成 (槽偏移, 标量类型) 列表 (声明顺序, 递归嵌套数组)。"""
2948
+ sd = self.structs[t[1]]
2949
+ out: List[Tuple[int, Any]] = []
2950
+ for fname, ftype in sd.fields:
2951
+ foff = base + sd.offsets[fname]
2952
+ if _is_struct(ftype):
2953
+ out.extend(self._struct_leaf_slots(ftype, foff))
2954
+ elif _is_fixed_array(ftype):
2955
+ if _is_struct(ftype[1]):
2956
+ raise CompilerError(
2957
+ f'struct array field {t[1]}.{fname} cannot be aggregate-'
2958
+ f'initialized; assign it in a function instead')
2959
+ for k in range(ftype[2]):
2960
+ out.append((foff + k, ftype[1]))
2961
+ else:
2962
+ out.append((foff, ftype))
2963
+ return out
2964
+
2965
+ @staticmethod
2966
+ def _flatten_literal(lit: list) -> list:
2967
+ """把 {{1, 2}, 3} 这类嵌套花括号初始化器摊平成一维。"""
2968
+ out: list = []
2969
+ for item in lit:
2970
+ if isinstance(item, list):
2971
+ out.extend(CodeGen._flatten_literal(item))
2972
+ else:
2973
+ out.append(item)
2974
+ return out
2975
+
2976
+ def _struct_literal_stores(self, sname: str, leaves, items) -> None:
2977
+ """x0 = 对象基址; 按 leaves 顺序把 items 写入字段 (值语义初始化)。"""
2978
+ if len(items) > len(leaves):
2979
+ raise CompilerError(
2980
+ f'Too many initializers for struct {sname}: got {len(items)}, '
2981
+ f'expected at most {len(leaves)}')
2982
+ self.emit('PUSH', self.reg(0)) # [SP] = 对象基址
2983
+ for idx, item in enumerate(items):
2984
+ off, ftype = leaves[idx]
2985
+ vt = self.gen_value(item)
2986
+ self._convert(vt, ftype)
2987
+ self.emit('MOV', self.reg(4), self.reg(0)) # x4 = 值
2988
+ self.emit('LD', self.reg(1), ('mem', 32, 0)) # x1 = 对象基址
2989
+ if off:
2990
+ self.emit('ADDI', self.reg(1), self.reg(1), self.imm(off * 8))
2991
+ self.emit('SD', self.reg(4), ('mem', 1, 0))
2992
+ self.emit('ADDI', self.reg(32), self.reg(32), self.imm(8)) # 弹掉基址
2993
+
2994
+ def gen_init_struct_literal(self, name: str, t, lit: list) -> None:
2995
+ """`P p = {3, 4}` —— 写进堆对象, 而不是覆盖指针槽 (旧实现会写坏 FP)。"""
2996
+ leaves = self._struct_leaf_slots(t)
2997
+ items = self._flatten_literal(lit)
2998
+ self._addr_var(name)
2999
+ self.emit('LD', self.reg(0), ('mem', 0, 0)) # x0 = 对象指针
3000
+ self._struct_literal_stores(t[1], leaves, items)
3001
+
3002
+ def gen_init_struct_array_literal(self, name: str, t, lit: list) -> None:
3003
+ """`P ps[2] = {{1, 2}, {3, 4}}` —— 逐元素写进各自的堆对象。"""
3004
+ elem, n = t[1], t[2]
3005
+ leaves = self._struct_leaf_slots(elem)
3006
+ rows = lit if (lit and isinstance(lit[0], list)) else [lit]
3007
+ if len(rows) > n:
3008
+ raise CompilerError(
3009
+ f'Too many initializers for struct array {name}: '
3010
+ f'got {len(rows)}, expected at most {n}')
3011
+ for i, row in enumerate(rows):
3012
+ self._addr_var(name) # x0 = 块基址
3013
+ if i:
3014
+ self.emit('ADDI', self.reg(0), self.reg(0), self.imm(i * 8))
3015
+ self.emit('LD', self.reg(0), ('mem', 0, 0)) # x0 = 元素对象指针
3016
+ self._struct_literal_stores(elem[1], leaves,
3017
+ self._flatten_literal(row))
3018
+
3019
+ # ---------------- struct 值拷贝 (值语义) ----------------
3020
+ #
3021
+ # docs/language/structs.md 承诺「整体赋值 P b = a | 值拷贝 (逐槽复制), 之后
3022
+ # 互不影响」。修复前槽里存的只是对象指针, 所以 `P b = a` / `b = a` /
3023
+ # `ps[1] = ps[0]` 全都是**指针别名**: `b.x = 7` 会改到 `a.x` (解释器与原生
3024
+ # VM 一致地错, 不是差分)。下面两个辅助方法把"指针槽传递"变成"对象逐槽复制"。
3025
+ #
3026
+ # 注意: 传参 / 数组参数元素刻意保持**引用可见** (文档 154/161 行), 因此
3027
+ # `_gen_call` 与函数序言都不做拷贝。
3028
+
3029
+ def _gen_struct_obj_addr(self, target, tt) -> None:
3030
+ """求 struct 左值所指向的**对象地址**到 x0 (不是槽地址)。
3031
+
3032
+ 左值形态与 `_gen_lvalue_addr` 返回的东西并不一致, 这里逐一区分:
3033
+ * `v` -> 槽地址, 槽里存对象指针 => 需要 LD
3034
+ * `a[i]` (struct 数组元素) -> 槽地址, 槽里存对象指针 => 需要 LD
3035
+ * `o.f` (嵌套 struct 字段) -> **字段地址**, 即对象本身 => 不能 LD
3036
+ * `a[i][j]` (多维 struct 数组) -> 子数组地址, 元素槽存指针 => 需要 LD
3037
+ """
3038
+ kind = target[0]
3039
+ if kind == 'member':
3040
+ self._gen_member(target[1], target[2], lvalue=True)
3041
+ ftype, _off = self._struct_field(self._expr_type(target[1]),
3042
+ target[2])
3043
+ if not _is_struct(ftype):
3044
+ # 字段必须自身是 struct (不含数组退化) —— 否则下面的拷贝会
3045
+ # 把"字段地址"当对象用, 静默写坏父对象。
3046
+ raise CompilerError(
3047
+ f"Cannot copy-assign aggregate to field of type {ftype}")
3048
+ return
3049
+ if kind == 'var':
3050
+ if target[1] in self.consts or target[1] in self.enums:
3051
+ raise CompilerError(
3052
+ f"Cannot assign to {target[1]} (constants are read-only)")
3053
+ self._addr_var(target[1])
3054
+ elif kind == 'index':
3055
+ base_t = self._expr_type(target[1])
3056
+ elem = _array_elem(base_t) if (_is_fixed_array(base_t)
3057
+ or _is_ptr_array(base_t)) else None
3058
+ if _is_struct(elem):
3059
+ # 定长 struct 数组 / 动态 struct 数组: 元素槽里存对象指针,
3060
+ # 所以 `_gen_index(lvalue=True)` 给的是**槽地址**, 需再 LD。
3061
+ self._gen_index(target[1], target[2], lvalue=True)
3062
+ elif _is_fixed_array(elem):
3063
+ # 多维 struct 数组的子数组: 元素槽里同样存指针。
3064
+ self._gen_index(target[1], target[2], lvalue=True)
3065
+ else:
3066
+ raise CompilerError(
3067
+ f"Cannot copy-assign into element of array type {base_t}")
3068
+ else:
3069
+ raise CompilerError(f"Invalid assignment target: {kind}")
3070
+ self.emit('LD', self.reg(0), ('mem', 0, 0)) # x0 = 对象地址
3071
+
3072
+ def _struct_assign_copy(self, nslots: int) -> None:
3073
+ """把 x7 指向对象逐槽复制到**栈顶槽所记**的目标对象。
3074
+
3075
+ 栈协议 (进入时): [SP] = 目标对象地址, [SP+8] = 源对象指针 (也是 x7)。
3076
+ 退出时: 两槽都已弹出, x0 = 源对象指针。
3077
+
3078
+ 为什么用栈而不是寄存器带着目标地址穿过 `_gen_lvalue_addr`: 被赋值对象
3079
+ 可能是 `temp[f(i)]`, 求目标地址时的下标表达式 / 函数调用会覆盖 x1..x6;
3080
+ 用栈把基址带过去就不会丢 (与现有代码 PUSH/POP 跨求值的做法一致)。
3081
+ 循环里只用 x5(目标基址) / x7(源基址) / x8(字节游标) / x9(临时值) 与
3082
+ x0/x1 (仅在本段内使用), 且每一轮都从基址重新 ADD。
3083
+ """
3084
+ if nslots <= 0:
3085
+ raise CompilerError(
3086
+ 'internal error: struct value copy of an empty struct')
3087
+ self.emit('LD', self.reg(5), ('mem', 32, 0)) # x5 = 目标对象基址
3088
+ self.emit('LD', self.reg(7), ('mem', 32, 8)) # x7 = 源对象基址
3089
+ if nslots == 1:
3090
+ self.emit('LD', self.reg(9), ('mem', 7, 0))
3091
+ self.emit('SD', self.reg(9), ('mem', 5, 0))
3092
+ else:
3093
+ self.emit('MOV', self.reg(8), self.imm(0)) # x8 = 字节游标
3094
+ l_loop = self.new_label('scpy')
3095
+ l_end = self.new_label('scpye')
3096
+ self.label(l_loop)
3097
+ self.emit('CMP', self.reg(8), self.imm(nslots * 8))
3098
+ self.emit('B', self.lab(l_end), ('cond', 'GE'))
3099
+ self.emit('MOV', self.reg(0), self.reg(5))
3100
+ self.emit('ADD', self.reg(0), self.reg(8)) # x0 = 目标 + off
3101
+ self.emit('MOV', self.reg(1), self.reg(7))
3102
+ self.emit('ADD', self.reg(1), self.reg(8)) # x1 = 源 + off
3103
+ self.emit('LD', self.reg(9), ('mem', 1, 0))
3104
+ self.emit('SD', self.reg(9), ('mem', 0, 0))
3105
+ self.emit('ADDI', self.reg(8), self.reg(8), self.imm(8))
3106
+ self.emit('JMP', self.lab(l_loop))
3107
+ self.label(l_end)
3108
+ self.emit('ADDI', self.reg(32), self.reg(32), self.imm(16)) # 弹两槽
3109
+ self.emit('MOV', self.reg(0), self.reg(7)) # 赋值表达式的值
3110
+
3111
+ def _struct_assign(self, target, stype) -> None:
3112
+ """struct 整体赋值 / 声明即初始化的值拷贝公共路径。
3113
+
3114
+ 调用约定: 进入时 x0 = 源对象指针; 返回后 x0 = 该指针 (与原来 `SD` 存
3115
+ 指针后 x0 仍持值的约定一致), 但 `target` 对象已被逐槽覆盖。
3116
+ """
3117
+ nslots = self.structs[stype[1]].size_slots
3118
+ self.emit('PUSH', self.reg(0)) # [SP] = 源对象指针
3119
+ self._gen_struct_obj_addr(target, stype) # x0 = 目标对象地址
3120
+ self.emit('PUSH', self.reg(0)) # [SP] = 目标对象地址
3121
+ self._struct_assign_copy(nslots)
3122
+
3123
+ def gen_decl(self, decls) -> None:
3124
+ for name, t, init, array_lit in decls:
3125
+ if array_lit is not None:
3126
+ if _is_struct(t):
3127
+ self.gen_init_struct_literal(name, t, array_lit)
3128
+ continue
3129
+ if _is_fixed_array(t) and _is_struct(t[1]):
3130
+ self.gen_init_struct_array_literal(name, t, array_lit)
3131
+ continue
3132
+ if array_lit and isinstance(array_lit[0], list):
3133
+ self.gen_init_2d_literal(name, t, array_lit)
3134
+ else:
3135
+ self.gen_init_1d_literal(name, t, array_lit)
3136
+ continue
3137
+ if init is not None:
3138
+ if _is_struct(t):
3139
+ # `P b = a`: b 的对象已在序言里分配好, 这里必须**复制 a 的
3140
+ # 字段**, 不能把 a 的指针写进 b 的槽 (那是别名, 违背文档的
3141
+ # 整体赋值值拷贝承诺)。b 的对象指针要重新 LD 出来。
3142
+ vt = self.gen_value(init) # x0 = 源对象指针
3143
+ if not _is_struct(vt):
3144
+ raise CompilerError(
3145
+ f"Cannot initialize struct {name} from value of "
3146
+ f"type {vt}")
3147
+ if vt[1] != t[1]:
3148
+ raise CompilerError(
3149
+ f"Cannot initialize struct {name} of type {t[1]} "
3150
+ f"from struct {vt[1]}")
3151
+ self._struct_assign(('var', name), t)
3152
+ else:
3153
+ vt = self.gen_value(init)
3154
+ self._convert(vt, t)
3155
+ # x0 = value; 存到变量槽
3156
+ self.emit('MOV', self.reg(2), self.reg(0))
3157
+ self._addr_var(name)
3158
+ self.emit('SD', self.reg(2), ('mem', 0, 0))
3159
+ elif _is_ptr_array(t) and _is_ptr_array(_array_elem(t)):
3160
+ # int[][] result (无尺寸): 预分配 64 个行指针
3161
+ self.emit('MOV', self.reg(0), self.imm(64 * 8))
3162
+ self.emit('SYS', self.imm(Syscall.MALLOC))
3163
+ self.emit('MOV', self.reg(2), self.reg(0))
3164
+ self._addr_var(name)
3165
+ self.emit('SD', self.reg(2), ('mem', 0, 0))
3166
+
3167
+ def gen_init_1d_literal(self, name: str, t, elems: list) -> None:
3168
+ # 定长 1D 数组: 就地写入 (每轮重新取基址, 避免地址累加)
3169
+ elem_t = _array_elem(t) if _is_fixed_array(t) else 'int'
3170
+ for i, elem in enumerate(elems):
3171
+ vt = self.gen_value(elem)
3172
+ self._convert(vt, elem_t)
3173
+ self.emit('MOV', self.reg(2), self.reg(0)) # value
3174
+ self._addr_var(name) # x0 = base
3175
+ if i:
3176
+ self.emit('ADDI', self.reg(0), self.reg(0), self.imm(i * 8))
3177
+ self.emit('SD', self.reg(2), ('mem', 0, 0))
3178
+
3179
+ def gen_init_2d_literal(self, name: str, t, rows: list) -> None:
3180
+ # int[][] mat1 = {{...},{...}}: 堆分配行指针数组 + 每行
3181
+ nrows = len(rows)
3182
+ ncols = max(len(r) for r in rows)
3183
+ # 外层: nrows 个指针
3184
+ self.emit('MOV', self.reg(0), self.imm(nrows * 8))
3185
+ self.emit('SYS', self.imm(Syscall.MALLOC))
3186
+ self.emit('MOV', self.reg(4), self.reg(0)) # outer
3187
+ for i, row in enumerate(rows):
3188
+ self.emit('MOV', self.reg(0), self.imm(max(ncols, 1) * 8))
3189
+ self.emit('SYS', self.imm(Syscall.MALLOC))
3190
+ self.emit('MOV', self.reg(5), self.reg(0)) # row ptr
3191
+ # outer[i] = row ptr
3192
+ self.emit('MOV', self.reg(0), self.reg(4))
3193
+ self.emit('ADDI', self.reg(0), self.reg(0), self.imm(i * 8))
3194
+ self.emit('SD', self.reg(5), ('mem', 0, 0))
3195
+ for j, elem in enumerate(row):
3196
+ # x4 (outer) 与 x5 (当前行) 要跨元素表达式求值存活, 而元素里
3197
+ # 可能有函数调用/嵌套下标 (会覆盖 x1..x6), 因此先存栈。
3198
+ self.emit('PUSH', self.reg(4))
3199
+ self.emit('PUSH', self.reg(5))
3200
+ vt = self.gen_value(elem)
3201
+ self._convert(vt, 'int')
3202
+ self.emit('MOV', self.reg(2), self.reg(0)) # x2 = value
3203
+ self.emit('POP', self.reg(5)) # 恢复当前行
3204
+ self.emit('POP', self.reg(4)) # 恢复 outer
3205
+ self.emit('MOV', self.reg(0), self.reg(5))
3206
+ if j:
3207
+ self.emit('ADDI', self.reg(0), self.reg(0), self.imm(j * 8))
3208
+ self.emit('SD', self.reg(2), ('mem', 0, 0))
3209
+ # 保存 outer 到变量槽
3210
+ self.emit('MOV', self.reg(2), self.reg(4))
3211
+ self._addr_var(name)
3212
+ self.emit('SD', self.reg(2), ('mem', 0, 0))
3213
+
3214
+ def gen_cpu_stmt(self, op: str, operands: list) -> None:
3215
+ def operand_value(operand):
3216
+ kind, val = operand
3217
+ if kind == 'NUMBER':
3218
+ return val
3219
+ if kind == 'IDENT':
3220
+ return ('var', val)
3221
+ raise CompilerError(f"Bad CPU-style operand: {operand}")
3222
+
3223
+ if op in ('increment', 'decrement'):
3224
+ varname = operands[0][1]
3225
+ self._addr_var(varname)
3226
+ self.emit('LD', self.reg(0), ('mem', 0, 0))
3227
+ self.emit('INC' if op == 'increment' else 'DEC', self.reg(0))
3228
+ self.emit('MOV', self.reg(2), self.reg(0))
3229
+ self._addr_var(varname)
3230
+ self.emit('SD', self.reg(2), ('mem', 0, 0))
3231
+ return
3232
+
3233
+ varname = operands[0][1]
3234
+ rhs = operand_value(operands[1]) if len(operands) > 1 else None
3235
+
3236
+ if op == 'set':
3237
+ if isinstance(rhs, tuple):
3238
+ self.gen_value(rhs)
3239
+ else:
3240
+ self.emit('MOV', self.reg(0), self.imm(int(rhs)))
3241
+ else:
3242
+ # add/subtract/multiply/divide: var = var op rhs (整数)
3243
+ self._addr_var(varname)
3244
+ self.emit('LD', self.reg(0), ('mem', 0, 0))
3245
+ if isinstance(rhs, tuple):
3246
+ self.emit('MOV', self.reg(2), self.reg(0))
3247
+ self.gen_value(rhs)
3248
+ self.emit('MOV', self.reg(1), self.reg(0))
3249
+ self.emit('MOV', self.reg(0), self.reg(2))
3250
+ else:
3251
+ self.emit('MOV', self.reg(1), self.imm(int(rhs)))
3252
+ op_map = {'add': 'ADD', 'subtract': 'SUB',
3253
+ 'multiply': 'MUL', 'divide': 'DIV'}
3254
+ self.emit(op_map[op], self.reg(0), self.reg(1))
3255
+ self.emit('MOV', self.reg(2), self.reg(0))
3256
+ self._addr_var(varname)
3257
+ self.emit('SD', self.reg(2), ('mem', 0, 0))
3258
+
3259
+ def gen_expr_stmt(self, node) -> None:
3260
+ # 赋值
3261
+ if node[0] == 'binop' and node[1] == '=':
3262
+ pass
3263
+ # parse 不产生 '=' binop; 赋值在 parse 层未处理, 这里检测 call/var 链
3264
+ self.gen_value(node)
3265
+
3266
+ # ---------------- 运行时断言 / 中止 (A1) ----------------
3267
+
3268
+ def _runtime_abort(self, text: str) -> None:
3269
+ """SYS ABORT: 加载静态消息指针并抛出运行时错误。"""
3270
+ addr = self._data_string(text)
3271
+ self.emit('MOV', self.reg(0), self._data_operand(addr))
3272
+ self.emit('SYS', self.imm(Syscall.ABORT))
3273
+
3274
+ def gen_assert(self, cond, msg, line: int,
3275
+ filename: Optional[str] = None) -> None:
3276
+ """assert(cond [, msg]) → 条件不成立时运行时中止 (定位: filename:line)。"""
3277
+ l_ok = self.new_label('assertok')
3278
+ self.gen_cond_jump_true(cond, l_ok)
3279
+ if msg is None:
3280
+ self._runtime_abort(
3281
+ f"{(filename or self._filename)}:{line}: assertion failed")
3282
+ else:
3283
+ # [prefix] + 消息 (消息支持任意表达式, 自动字符串化)
3284
+ prefix = self._data_string(
3285
+ f"[assert {(filename or self._filename)}:{line}] ")
3286
+ self.emit('MOV', self.reg(0), self.imm(prefix))
3287
+ self.emit('PUSH', self.reg(0))
3288
+ self._gen_string_value(msg)
3289
+ self.emit('MOV', self.reg(1), self.reg(0))
3290
+ self.emit('POP', self.reg(0))
3291
+ self.emit('SYS', self.imm(Syscall.STR_CONCAT))
3292
+ self.emit('SYS', self.imm(Syscall.ABORT))
3293
+ self.label(l_ok)
3294
+
3295
+ # ---------------- 类型转换 ----------------
3296
+
3297
+ def _convert(self, from_type, to_type) -> None:
3298
+ """将 x0 从 from_type 转换为 to_type (原地)。"""
3299
+ if to_type is None or from_type is None:
3300
+ return
3301
+ if from_type == to_type:
3302
+ return
3303
+ if from_type == 'int' and to_type == 'float':
3304
+ self.emit('SYS', self.imm(Syscall.ITOF))
3305
+ elif from_type == 'float' and to_type == 'int':
3306
+ self.emit('SYS', self.imm(Syscall.FTOI))
3307
+ elif from_type == 'bool' and to_type in ('int', 'float'):
3308
+ if to_type == 'float':
3309
+ self.emit('SYS', self.imm(Syscall.ITOF))
3310
+ elif from_type == 'int' and to_type == 'bool':
3311
+ pass
3312
+ # string/struct/array 指针无需转换
3313
+
3314
+ # ---------------- 表达式 ----------------
3315
+
3316
+ def gen_value(self, node) -> Any:
3317
+ """求值表达式到 x0, 返回 CIN 类型。"""
3318
+ kind = node[0]
3319
+ if kind == 'num':
3320
+ if node[2]:
3321
+ bits = struct.unpack('<Q', struct.pack('<d', float(node[1])))[0]
3322
+ self.emit('MOV', self.reg(0), self.imm(bits))
3323
+ return 'float'
3324
+ self.emit('MOV', self.reg(0), self.imm(int(node[1])))
3325
+ return 'int'
3326
+ if kind == 'bool':
3327
+ self.emit('MOV', self.reg(0), self.imm(1 if node[1] else 0))
3328
+ return 'bool'
3329
+ if kind == 'str':
3330
+ self.emit('MOV', self.reg(0),
3331
+ self._data_operand(self._data_string(node[1])))
3332
+ return 'string'
3333
+ if kind == 'var':
3334
+ return self._gen_var_value(node[1])
3335
+ if kind == 'member':
3336
+ return self._gen_member(node[1], node[2], lvalue=False)
3337
+ if kind == 'index':
3338
+ return self._gen_index(node[1], node[2], lvalue=False)
3339
+ if kind == 'call':
3340
+ return self._gen_call(node[1], node[2])
3341
+ if kind == 'neg':
3342
+ t = self.gen_value(node[1])
3343
+ self.emit('MOV', self.reg(1), self.reg(0))
3344
+ if t == 'float':
3345
+ # 浮点: 0.0 - x (x1 为 float64 位模式)
3346
+ self.emit('MOV', self.reg(0), self.imm(0))
3347
+ self.emit('SYS', self.imm(Syscall.ITOF))
3348
+ self.emit('SYS', self.imm(Syscall.FSUB))
3349
+ else:
3350
+ self.emit('MOV', self.reg(0), self.imm(0))
3351
+ self.emit('SUB', self.reg(0), self.reg(1))
3352
+ return t
3353
+ if kind == 'not':
3354
+ t = self.gen_value(node[1])
3355
+ self.emit('XORI', self.reg(0), self.reg(0), self.imm(1))
3356
+ return 'bool'
3357
+ if kind == 'bitnot':
3358
+ t = self.gen_value(node[1])
3359
+ if t in ('float', 'string'):
3360
+ raise CompilerError("Bitwise NOT '~' requires an integer operand")
3361
+ self.emit('MVN', self.reg(0), self.reg(0))
3362
+ return 'int'
3363
+ if kind in ('preinc', 'predec', 'postinc', 'postdec'):
3364
+ return self._gen_incdec(kind, node[1])
3365
+ if kind == 'cond':
3366
+ return self._gen_ternary(node[1], node[2], node[3])
3367
+ if kind == 'binop':
3368
+ return self._gen_binop(node[1], node[2], node[3])
3369
+ raise CompilerError(f"Cannot generate code for expression: {kind}")
3370
+
3371
+ def _gen_var_value(self, name: str) -> Any:
3372
+ t = self._var_type(name)
3373
+ if t is None:
3374
+ # 不是已声明的变量 -> 编译期常量 (局部变量可以遮蔽 const)
3375
+ if name in self.consts:
3376
+ ctype, value = self.consts[name]
3377
+ if ctype == 'float':
3378
+ bits = struct.unpack('<Q', struct.pack('<d', float(value)))[0]
3379
+ self.emit('MOV', self.reg(0), self.imm(bits))
3380
+ return 'float'
3381
+ if ctype == 'string':
3382
+ self.emit('MOV', self.reg(0),
3383
+ self._data_operand(self._data_string(value)))
3384
+ return 'string'
3385
+ self.emit('MOV', self.reg(0),
3386
+ self.imm(int(value) & 0xFFFFFFFFFFFFFFFF))
3387
+ return 'bool' if ctype == 'bool' else 'int'
3388
+ if name in self.enums:
3389
+ # 枚举成员: 编译期整数常量
3390
+ self.emit('MOV', self.reg(0), self.imm(self.enums[name]))
3391
+ return 'int'
3392
+ raise CompilerError(f"Undefined variable: {name}")
3393
+ is_block = False
3394
+ if name in self.locals:
3395
+ is_block = self.locals[name][2]
3396
+ elif name in self.globals:
3397
+ is_block = self.globals[name][2]
3398
+ if is_block:
3399
+ # 定长数组: 值 = 块地址
3400
+ self._addr_var(name)
3401
+ return t
3402
+ self._addr_var(name)
3403
+ self.emit('LD', self.reg(0), ('mem', 0, 0))
3404
+ return t
3405
+
3406
+ def _gen_lvalue_addr(self, node) -> None:
3407
+ """求值左值地址到 x0。"""
3408
+ kind = node[0]
3409
+ if kind == 'var':
3410
+ if node[1] in self.consts:
3411
+ raise CompilerError(
3412
+ f"Cannot assign to const: {node[1]} (constants are "
3413
+ f"read-only)")
3414
+ if node[1] in self.enums:
3415
+ raise CompilerError(
3416
+ f"Cannot assign to enum member: {node[1]} (constants are "
3417
+ f"read-only)")
3418
+ self._addr_var(node[1])
3419
+ return
3420
+ if kind == 'member':
3421
+ self._gen_member(node[1], node[2], lvalue=True)
3422
+ return
3423
+ if kind == 'index':
3424
+ self._gen_index(node[1], node[2], lvalue=True)
3425
+ return
3426
+ raise CompilerError(f"Invalid assignment target: {kind}")
3427
+
3428
+ def _struct_field(self, struct_type, fname: str) -> Tuple[Any, int]:
3429
+ sd = self.structs[struct_type[1]]
3430
+ if fname not in sd.offsets:
3431
+ raise CompilerError(f"Struct {struct_type[1]} has no field {fname}")
3432
+ ftype = dict(sd.fields)[fname]
3433
+ return ftype, sd.offsets[fname]
3434
+
3435
+ def _gen_member(self, obj_node, fname: str, lvalue: bool):
3436
+ obj_t = self.gen_value(obj_node) # x0 = struct 指针
3437
+ if not _is_struct(obj_t):
3438
+ raise CompilerError(f"Member access on non-struct type: {obj_t}")
3439
+ ftype, foff = self._struct_field(obj_t, fname)
3440
+ if lvalue:
3441
+ if foff:
3442
+ self.emit('ADDI', self.reg(0), self.reg(0), self.imm(foff * 8))
3443
+ return None
3444
+ # 值
3445
+ if _is_fixed_array(ftype):
3446
+ # 内联数组: 值 = 字段地址, 类型退化为指针视图
3447
+ if foff:
3448
+ self.emit('ADDI', self.reg(0), self.reg(0), self.imm(foff * 8))
3449
+ return self._decay(ftype)
3450
+ if _is_struct(ftype):
3451
+ # 嵌套 struct 按值内嵌在父对象里: 值 = 字段地址 (不是解引用)。
3452
+ # 旧实现会 LD 该槽, 把内嵌字段的前 8 字节当成指针用。
3453
+ if foff:
3454
+ self.emit('ADDI', self.reg(0), self.reg(0), self.imm(foff * 8))
3455
+ return ftype
3456
+ self.emit('MOV', self.reg(1), self.reg(0))
3457
+ if foff:
3458
+ self.emit('ADDI', self.reg(1), self.reg(1), self.imm(foff * 8))
3459
+ self.emit('LD', self.reg(0), ('mem', 1, 0))
3460
+ return ftype
3461
+
3462
+ @staticmethod
3463
+ def _decay(t):
3464
+ """定长数组作为指针值时的类型视图。"""
3465
+ if _is_fixed_array(t):
3466
+ elem = t[1]
3467
+ if _is_fixed_array(elem):
3468
+ return ('array', elem, t[2]) # 多维: 子数组仍定长
3469
+ return ('ptrarray', elem)
3470
+ return t
3471
+
3472
+ def _gen_index(self, base_node, idx_node, lvalue: bool):
3473
+ base_t = self.gen_value(base_node) # 定长数组=块地址; ptrarray=指针; string=ptr
3474
+ if base_t == 'string':
3475
+ if lvalue:
3476
+ raise CompilerError(
3477
+ "Cannot assign to string element (strings are immutable)")
3478
+ # 基址必须存栈: 下标表达式里可能有嵌套下标/函数调用, 它们会覆盖
3479
+ # x1..x6。s[B[i]] 曾因此把字符串基址弄丢, 读出错误内存。
3480
+ self.emit('PUSH', self.reg(0)) # 保存字符串基址
3481
+ idx_t = self.gen_value(idx_node) # x0 = index
3482
+ self._convert(idx_t, 'int') # 下标是 int 上下文
3483
+ self.emit('POP', self.reg(3)) # x3 = 字符串基址
3484
+ self.emit('ADD', self.reg(0), self.reg(3)) # x0 = base + i (字节偏移)
3485
+ self.emit('LB', self.reg(0), ('mem', 0, 0)) # 读 1 字节 (符号扩展)
3486
+ self.emit('ANDI', self.reg(0), self.reg(0), self.imm(0xFF)) # 0..255
3487
+ return 'int'
3488
+ if _is_fixed_array(base_t) or _is_ptr_array(base_t):
3489
+ elem_t = _array_elem(base_t)
3490
+ else:
3491
+ raise CompilerError(f"Indexing non-array type: {base_t}")
3492
+
3493
+ # x0 = base pointer; 计算 elem 地址。
3494
+ # 基址必须存栈, 不能用寄存器"暂存": 下标表达式里可能有嵌套下标或函数
3495
+ # 调用, 它们会覆盖 x1..x6。此前 base 放在 x3, 于是 A[B[i]] 的内层下标
3496
+ # 把 x3 改成 B 的基址, 外层 ADD 用 B 的基址当 A 的 —— 读错地址, 写的
3497
+ # 时候直接写坏别的内存 (静默, 不报错)。
3498
+ self.emit('PUSH', self.reg(0)) # 保存 base
3499
+ idx_t = self.gen_value(idx_node) # x0 = index
3500
+ # 下标是 int 上下文 (与赋值/传参/返回一致): float 隐式截断为 int。
3501
+ # 缺这一步时 float 的 IEEE-754 位模式会被当作字节偏移直接乘 8,
3502
+ # 产生 0x0379_8000_0000_0000 之类的高位垃圾地址 (issue #1)。
3503
+ self._convert(idx_t, 'int')
3504
+
3505
+ # A1 --bounds-check: 定长数组索引 0 <= i < size
3506
+ if self._bounds and _is_fixed_array(base_t):
3507
+ size = base_t[2]
3508
+ l_ge = self.new_label('bndok')
3509
+ self.emit('CMP', self.reg(0), self.imm(0))
3510
+ self.emit('B', self.lab(l_ge), ('cond', 'GE'))
3511
+ self._runtime_abort("bounds-check: negative array index")
3512
+ self.label(l_ge)
3513
+ l_lt = self.new_label('bndok')
3514
+ self.emit('CMP', self.reg(0), self.imm(size))
3515
+ self.emit('B', self.lab(l_lt), ('cond', 'LT'))
3516
+ self._runtime_abort(f"bounds-check: index >= length ({size})")
3517
+ self.label(l_lt)
3518
+
3519
+ scale = _type_slots(elem_t) * 8
3520
+ self.emit('MOV', self.reg(1), self.imm(scale))
3521
+ self.emit('MUL', self.reg(0), self.reg(1)) # x0 = index * scale
3522
+ self.emit('POP', self.reg(3)) # x3 = base (存栈时压入的)
3523
+ self.emit('ADD', self.reg(0), self.reg(3)) # x0 = elem 地址
3524
+
3525
+ if lvalue:
3526
+ return None
3527
+
3528
+ if _is_fixed_array(elem_t):
3529
+ return elem_t # 子数组: 值 = 地址
3530
+ if _is_ptr_array(elem_t):
3531
+ # 行指针 (int[][] 的 a[i]): 若为空则延迟分配 64 元素行
3532
+ self.emit('MOV', self.reg(5), self.reg(0)) # x5 = elem 地址
3533
+ self.emit('LD', self.reg(1), ('mem', 5, 0)) # x1 = 行指针
3534
+ l_done = self.new_label('rowdone')
3535
+ self.emit('CMP', self.reg(1), self.imm(0))
3536
+ self.emit('B', self.lab(l_done), ('cond', 'NE'))
3537
+ self.emit('MOV', self.reg(0), self.imm(64 * 8))
3538
+ self.emit('SYS', self.imm(Syscall.MALLOC))
3539
+ self.emit('MOV', self.reg(1), self.reg(0)) # x1 = 新行指针
3540
+ self.emit('SD', self.reg(1), ('mem', 5, 0)) # 写回 elem 槽
3541
+ self.label(l_done)
3542
+ self.emit('MOV', self.reg(0), self.reg(1))
3543
+ return elem_t
3544
+ # 标量元素
3545
+ self.emit('LD', self.reg(0), ('mem', 0, 0))
3546
+ return elem_t
3547
+
3548
+ # ---------------- 赋值 (在 gen_value 中拦截 binop '=') ----------------
3549
+
3550
+ def _gen_assign(self, target, value_node):
3551
+ tt = self._expr_type(target)
3552
+ if _is_struct(tt):
3553
+ # struct 整体赋值 = **值拷贝** (docs/language/structs.md 157 行):
3554
+ # `b = a` / `ps[1] = ps[0]` / `o.i = other` 都逐槽复制, 之后互不
3555
+ # 影响。修复前这里是 `SD` 存指针 => 别名。
3556
+ vt = self.gen_value(value_node) # x0 = 源对象指针
3557
+ if not _is_struct(vt):
3558
+ raise CompilerError(
3559
+ f"Cannot assign value of type {vt} to struct {tt[1]}")
3560
+ if vt[1] != tt[1]:
3561
+ raise CompilerError(
3562
+ f"Cannot assign struct {vt[1]} to struct {tt[1]} "
3563
+ f"(different struct types)")
3564
+ self._struct_assign(target, tt)
3565
+ return tt
3566
+ vt = self.gen_value(value_node)
3567
+ if _is_struct(vt):
3568
+ # struct 值是指向堆对象的指针; 静默把它写进标量槽 (例如
3569
+ # `int a[2]; P p; a[0] = p`) 只会得到一个假整数, 必须编译期报错。
3570
+ raise CompilerError(
3571
+ f"Cannot assign struct value of type {vt} to target of type "
3572
+ f"{tt}; assign a field or a whole struct variable instead")
3573
+ self._convert(vt, tt)
3574
+ self.emit('PUSH', self.reg(0)) # 保存 value
3575
+ self._gen_lvalue_addr(target) # x0 = addr
3576
+ self.emit('POP', self.reg(2)) # x2 = value
3577
+ self.emit('SD', self.reg(2), ('mem', 0, 0))
3578
+ return tt
3579
+
3580
+ def _expr_type(self, node):
3581
+ kind = node[0]
3582
+ if kind == 'var':
3583
+ vt = self._var_type(node[1])
3584
+ if vt is not None:
3585
+ return vt # 变量遮蔽同名的 const / enum 成员
3586
+ if node[1] in self.consts:
3587
+ return self.consts[node[1]][0]
3588
+ if node[1] in self.enums:
3589
+ return 'int'
3590
+ return None
3591
+ if kind == 'member':
3592
+ obj_t = self._expr_type(node[1])
3593
+ if _is_struct(obj_t):
3594
+ ftype, _ = self._struct_field(obj_t, node[2])
3595
+ return ftype
3596
+ if kind == 'index':
3597
+ base_t = self._expr_type(node[1])
3598
+ if base_t == 'string':
3599
+ return 'int'
3600
+ elem = _array_elem(base_t) if _is_fixed_array(base_t) or _is_ptr_array(base_t) else None
3601
+ if _is_fixed_array(elem):
3602
+ return elem
3603
+ return elem
3604
+ if kind == 'call':
3605
+ f = self.functions.get(node[1])
3606
+ if f:
3607
+ return f.ret_type
3608
+ if node[1] in ('min', 'max'):
3609
+ at = self._expr_type(node[2][0])
3610
+ bt = self._expr_type(node[2][1])
3611
+ return 'float' if (at == 'float' or bt == 'float') else 'int'
3612
+ return self._builtin_ret_type(node[1])
3613
+ if kind == 'num':
3614
+ return 'float' if node[2] else 'int'
3615
+ if kind == 'bool':
3616
+ return 'bool'
3617
+ if kind == 'str':
3618
+ return 'string'
3619
+ if kind == 'binop':
3620
+ if node[1] in ('+=', '-=', '*=', '/=', '%=',
3621
+ '&=', '|=', '^=', '<<=', '>>='):
3622
+ return self._expr_type(node[2])
3623
+ if node[1] in ('&', '|', '^', '<<', '>>'):
3624
+ return 'int'
3625
+ if node[1] in ('+', '-', '*', '%'):
3626
+ lt = self._expr_type(node[2])
3627
+ rt = self._expr_type(node[3])
3628
+ if lt == 'string' or rt == 'string':
3629
+ return 'string'
3630
+ return 'float' if lt == 'float' or rt == 'float' else 'int'
3631
+ if node[1] == '/':
3632
+ return 'float'
3633
+ if node[1] in ('==', '!=', '<', '>', '<=', '>=', '&&', '||'):
3634
+ return 'bool'
3635
+ if kind == 'cond':
3636
+ lt = self._expr_type(node[2])
3637
+ rt = self._expr_type(node[3])
3638
+ if (lt == 'string') != (rt == 'string'):
3639
+ return 'int'
3640
+ return 'string' if lt == 'string' else \
3641
+ ('float' if lt == 'float' or rt == 'float' else 'int')
3642
+ if kind in ('preinc', 'predec', 'postinc', 'postdec'):
3643
+ return self._expr_type(node[1])
3644
+ if kind == 'neg':
3645
+ it = self._expr_type(node[1])
3646
+ return 'float' if it == 'float' else 'int'
3647
+ if kind == 'not':
3648
+ return 'bool'
3649
+ if kind == 'bitnot':
3650
+ return 'int'
3651
+ return None
3652
+
3653
+ # ---------------- 二元运算 ----------------
3654
+
3655
+ def _gen_binop(self, op, left, right):
3656
+ if op == '=':
3657
+ return self._gen_assign(left, right)
3658
+ if op in _COMPOUND_TO_BASE:
3659
+ return self._gen_compound(left, _COMPOUND_TO_BASE[op], right)
3660
+ if op == '&&' or op == '||':
3661
+ return self._gen_logical(op, left, right)
3662
+ if op in ('&', '|', '^', '<<', '>>'):
3663
+ return self._gen_bitwise(op, left, right)
3664
+ if op in ('==', '!=', '<', '>', '<=', '>='):
3665
+ # 比较作为值表达式: 条件成立得 1, 否则 0
3666
+ l_false = self.new_label('cmpf')
3667
+ l_end = self.new_label('cmpe')
3668
+ self.gen_cond_jump_false(('binop', op, left, right), l_false)
3669
+ self.emit('MOV', self.reg(0), self.imm(1))
3670
+ self.emit('JMP', self.lab(l_end))
3671
+ self.label(l_false)
3672
+ self.emit('MOV', self.reg(0), self.imm(0))
3673
+ self.label(l_end)
3674
+ return 'bool'
3675
+
3676
+ lt = self._expr_type(left)
3677
+ rt = self._expr_type(right)
3678
+ if op == '+' and (lt == 'string' or rt == 'string'):
3679
+ self._gen_string_value(left)
3680
+ self.emit('PUSH', self.reg(0))
3681
+ self._gen_string_value(right)
3682
+ self.emit('MOV', self.reg(1), self.reg(0))
3683
+ self.emit('POP', self.reg(0))
3684
+ self.emit('SYS', self.imm(Syscall.STR_CONCAT))
3685
+ return 'string'
3686
+
3687
+ float_mode = (lt == 'float' or rt == 'float') or op == '/'
3688
+ # 左操作数
3689
+ self.gen_value(left)
3690
+ if float_mode and lt == 'int':
3691
+ self.emit('SYS', self.imm(Syscall.ITOF))
3692
+ if float_mode and lt == 'bool':
3693
+ self.emit('SYS', self.imm(Syscall.ITOF))
3694
+ self.emit('PUSH', self.reg(0))
3695
+ # 右操作数
3696
+ self.gen_value(right)
3697
+ if float_mode and rt in ('int', 'bool'):
3698
+ self.emit('SYS', self.imm(Syscall.ITOF))
3699
+ self.emit('MOV', self.reg(1), self.reg(0))
3700
+ self.emit('POP', self.reg(0))
3701
+
3702
+ if float_mode:
3703
+ sys_map = {'+': Syscall.FADD, '-': Syscall.FSUB,
3704
+ '*': Syscall.FMUL, '/': Syscall.FDIV}
3705
+ if op == '%':
3706
+ raise CompilerError("Float modulo not supported")
3707
+ self.emit('SYS', self.imm(sys_map[op]))
3708
+ return 'float'
3709
+
3710
+ if op == '%':
3711
+ # x0 = a - (a/b)*b
3712
+ self.emit('MOV', self.reg(2), self.reg(1)) # b
3713
+ self.emit('PUSH', self.reg(0)) # a
3714
+ self.emit('DIV', self.reg(0), self.reg(2)) # a/b
3715
+ self.emit('MUL', self.reg(0), self.reg(2)) # (a/b)*b
3716
+ self.emit('MOV', self.reg(1), self.reg(0))
3717
+ self.emit('POP', self.reg(0))
3718
+ self.emit('SUB', self.reg(0), self.reg(1))
3719
+ return 'int'
3720
+
3721
+ op_map = {'+': 'ADD', '-': 'SUB', '*': 'MUL'}
3722
+ if op not in op_map:
3723
+ raise CompilerError(f"Unsupported int operator: {op}")
3724
+ self.emit(op_map[op], self.reg(0), self.reg(1))
3725
+ return 'int'
3726
+
3727
+ def _gen_logical(self, op, left, right):
3728
+ l_true = self.new_label('lt')
3729
+ l_false = self.new_label('lf')
3730
+ l_end = self.new_label('le')
3731
+ if op == '&&':
3732
+ self.gen_cond_jump_false(left, l_false)
3733
+ self.gen_cond_jump_false(right, l_false)
3734
+ else: # ||
3735
+ self.gen_cond_jump_true(left, l_true)
3736
+ self.gen_cond_jump_true(right, l_true)
3737
+ self.emit('JMP', self.lab(l_false))
3738
+ self.label(l_true)
3739
+ self.emit('MOV', self.reg(0), self.imm(1))
3740
+ self.emit('JMP', self.lab(l_end))
3741
+ self.label(l_false)
3742
+ self.emit('MOV', self.reg(0), self.imm(0))
3743
+ self.label(l_end)
3744
+ return 'bool'
3745
+
3746
+ def _gen_bitwise(self, op, left, right) -> Any:
3747
+ """位运算 & | ^ << >> (整数); >> 为算术右移 (保留符号)。"""
3748
+ lt = self._expr_type(left)
3749
+ rt = self._expr_type(right)
3750
+ if lt in ('float', 'string') or rt in ('float', 'string'):
3751
+ raise CompilerError(
3752
+ f"Bitwise operator '{op}' requires integer operands "
3753
+ f"(got {lt} and {rt})")
3754
+ self.gen_value(left)
3755
+ self.emit('PUSH', self.reg(0))
3756
+ self.gen_value(right)
3757
+ self.emit('MOV', self.reg(1), self.reg(0))
3758
+ self.emit('POP', self.reg(0))
3759
+ if op == '&':
3760
+ self.emit('AND', self.reg(0), self.reg(1))
3761
+ elif op == '|':
3762
+ self.emit('OR', self.reg(0), self.reg(1))
3763
+ elif op == '^':
3764
+ self.emit('XOR', self.reg(0), self.reg(1))
3765
+ elif op == '<<':
3766
+ self.emit('SHL', self.reg(0), self.reg(1))
3767
+ else: # '>>'
3768
+ self.emit('ASR', self.reg(0), self.reg(0), self.reg(1))
3769
+ return 'int'
3770
+
3771
+ # ---------------- 复合赋值 / 自增自减 / 三目 ----------------
3772
+
3773
+ def _gen_compound(self, target, op: str, value_node) -> Any:
3774
+ """target op= value (op ∈ + - * / % & | ^ << >>); 左值地址只求值一次。"""
3775
+ tt = self._expr_type(target)
3776
+ if tt == 'string':
3777
+ # 字符串只支持 +=: 读出旧串 + 右侧 (自动字符串化) + 写回新串
3778
+ if op != '+':
3779
+ raise CompilerError(f"Cannot apply '{op}=' to type: string")
3780
+ self._gen_lvalue_addr(target)
3781
+ self.emit('PUSH', self.reg(0)) # [SP] = 目标地址
3782
+ self.emit('LD', self.reg(0), ('mem', 0, 0)) # x0 = 旧字符串
3783
+ self.emit('PUSH', self.reg(0))
3784
+ self._gen_string_value(value_node) # x0 = rhs 字符串
3785
+ self.emit('MOV', self.reg(1), self.reg(0))
3786
+ self.emit('POP', self.reg(0)) # x0 = 旧串
3787
+ self.emit('SYS', self.imm(Syscall.STR_CONCAT))
3788
+ self.emit('POP', self.reg(2)) # x2 = 目标地址
3789
+ self.emit('SD', self.reg(0), ('mem', 2, 0))
3790
+ return 'string'
3791
+ if tt not in ('int', 'bool', 'float'):
3792
+ raise CompilerError(f"Cannot apply '{op}=' to type: {tt}")
3793
+ if tt == 'float' and op not in ('+', '-', '*', '/'):
3794
+ raise CompilerError(f"Cannot apply '{op}=' to float")
3795
+ float_mode = tt == 'float'
3796
+
3797
+ self._gen_lvalue_addr(target)
3798
+ self.emit('PUSH', self.reg(0)) # [SP] = addr
3799
+ vt = self.gen_value(value_node) # x0 = rhs
3800
+ self._convert(vt, tt)
3801
+ self.emit('MOV', self.reg(1), self.reg(0)) # b = rhs
3802
+ self.emit('LD', self.reg(2), ('mem', 32, 0)) # x2 = addr
3803
+ self.emit('LD', self.reg(0), ('mem', 2, 0)) # a = old
3804
+
3805
+ if float_mode:
3806
+ fmap = {'+': Syscall.FADD, '-': Syscall.FSUB,
3807
+ '*': Syscall.FMUL, '/': Syscall.FDIV}
3808
+ self.emit('SYS', self.imm(fmap[op]))
3809
+ elif op == '+':
3810
+ self.emit('ADD', self.reg(0), self.reg(1))
3811
+ elif op == '-':
3812
+ self.emit('SUB', self.reg(0), self.reg(1))
3813
+ elif op == '*':
3814
+ self.emit('MUL', self.reg(0), self.reg(1))
3815
+ elif op == '/':
3816
+ self.emit('DIV', self.reg(0), self.reg(1))
3817
+ elif op == '%':
3818
+ self.emit('MOV', self.reg(3), self.reg(1)) # 除数备份
3819
+ self.emit('PUSH', self.reg(0))
3820
+ self.emit('DIV', self.reg(0), self.reg(3))
3821
+ self.emit('MUL', self.reg(0), self.reg(3))
3822
+ self.emit('MOV', self.reg(1), self.reg(0))
3823
+ self.emit('POP', self.reg(0))
3824
+ self.emit('SUB', self.reg(0), self.reg(1))
3825
+ elif op == '&':
3826
+ self.emit('AND', self.reg(0), self.reg(1))
3827
+ elif op == '|':
3828
+ self.emit('OR', self.reg(0), self.reg(1))
3829
+ elif op == '^':
3830
+ self.emit('XOR', self.reg(0), self.reg(1))
3831
+ elif op == '<<':
3832
+ self.emit('SHL', self.reg(0), self.reg(1))
3833
+ elif op == '>>':
3834
+ self.emit('ASR', self.reg(0), self.reg(0), self.reg(1))
3835
+ else:
3836
+ raise CompilerError(f"Unsupported compound operator: {op}=")
3837
+
3838
+ self.emit('SD', self.reg(0), ('mem', 2, 0))
3839
+ self.emit('ADDI', self.reg(32), self.reg(32), self.imm(8))
3840
+ return tt
3841
+
3842
+ def _gen_incdec(self, kind: str, target) -> Any:
3843
+ """++/-- (前缀与后缀); 后缀返回旧值, 前缀返回新值。"""
3844
+ tt = self._expr_type(target)
3845
+ if tt not in ('int', 'bool', 'float'):
3846
+ raise CompilerError(f"Cannot {kind} value of type: {tt}")
3847
+ op = '+' if 'inc' in kind else '-'
3848
+ postfix = kind.startswith('post')
3849
+ float_mode = tt == 'float'
3850
+
3851
+ self._gen_lvalue_addr(target)
3852
+ self.emit('PUSH', self.reg(0)) # [SP] = addr
3853
+ self.emit('LD', self.reg(2), ('mem', 32, 0)) # x2 = addr
3854
+ self.emit('LD', self.reg(0), ('mem', 2, 0)) # a = old
3855
+ if postfix:
3856
+ self.emit('MOV', self.reg(5), self.reg(0)) # 保存旧值
3857
+ if float_mode:
3858
+ self.emit('MOV', self.reg(0), self.imm(1))
3859
+ self.emit('SYS', self.imm(Syscall.ITOF)) # b = 1.0
3860
+ self.emit('MOV', self.reg(1), self.reg(0))
3861
+ self.emit('LD', self.reg(0), ('mem', 2, 0)) # a 回填
3862
+ self.emit('SYS', self.imm(Syscall.FADD if op == '+'
3863
+ else Syscall.FSUB))
3864
+ else:
3865
+ self.emit('MOV', self.reg(1), self.imm(1))
3866
+ self.emit('ADD' if op == '+' else 'SUB',
3867
+ self.reg(0), self.reg(1))
3868
+ self.emit('SD', self.reg(0), ('mem', 2, 0))
3869
+ self.emit('ADDI', self.reg(32), self.reg(32), self.imm(8))
3870
+ if postfix:
3871
+ self.emit('MOV', self.reg(0), self.reg(5))
3872
+ return tt
3873
+
3874
+ def _gen_minmax(self, name: str, args) -> Any:
3875
+ """min/max(a, b): int/float 数值最值 (bool 视作 int)。"""
3876
+ at = self._expr_type(args[0])
3877
+ bt = self._expr_type(args[1])
3878
+ if at == 'string' or bt == 'string':
3879
+ raise CompilerError(f"{name} does not accept string operands")
3880
+ tt = 'float' if (at == 'float' or bt == 'float') else 'int'
3881
+
3882
+ self.gen_value(args[0])
3883
+ if tt == 'float' and at in ('int', 'bool'):
3884
+ self.emit('SYS', self.imm(Syscall.ITOF))
3885
+ self.emit('PUSH', self.reg(0)) # [SP] = a
3886
+ self.gen_value(args[1])
3887
+ if tt == 'float' and bt in ('int', 'bool'):
3888
+ self.emit('SYS', self.imm(Syscall.ITOF))
3889
+ self.emit('MOV', self.reg(1), self.reg(0)) # x1 = b
3890
+ self.emit('POP', self.reg(0)) # x0 = a
3891
+
3892
+ # min: a<=b 取 a; max: a>=b 取 a
3893
+ cond = 'LE' if name == 'min' else 'GE'
3894
+ if tt == 'float':
3895
+ self.emit('MOV', self.reg(2), self.reg(0)) # 备份 a
3896
+ self.emit('MOV', self.reg(3), self.reg(1)) # 备份 b
3897
+ self.emit('SYS', self.imm(Syscall.FCMP)) # x0 = cmp(a,b) ∈ {-1,0,1}
3898
+ self.emit('CMP', self.reg(0), self.imm(0))
3899
+ l_keep = self.new_label('mmkeep')
3900
+ l_done = self.new_label('mmdone')
3901
+ self.emit('B', self.lab(l_keep), ('cond', cond))
3902
+ self.emit('MOV', self.reg(0), self.reg(3)) # result = b
3903
+ self.emit('JMP', self.lab(l_done))
3904
+ self.label(l_keep)
3905
+ self.emit('MOV', self.reg(0), self.reg(2)) # result = a
3906
+ self.label(l_done)
3907
+ else:
3908
+ self.emit('CMP', self.reg(0), self.reg(1))
3909
+ l_keep = self.new_label('mmkeep')
3910
+ self.emit('B', self.lab(l_keep), ('cond', cond))
3911
+ self.emit('MOV', self.reg(0), self.reg(1)) # result = b
3912
+ self.label(l_keep)
3913
+ return tt
3914
+
3915
+ def _gen_ternary(self, cond, a, b) -> Any:
3916
+ lt = self._expr_type(a)
3917
+ rt = self._expr_type(b)
3918
+ if (lt == 'string') != (rt == 'string'):
3919
+ raise CompilerError("Cannot mix string and numeric in '?:'")
3920
+ tt = 'string' if lt == 'string' else \
3921
+ ('float' if (lt == 'float' or rt == 'float') else 'int')
3922
+ l_false = self.new_label('cndf')
3923
+ l_end = self.new_label('cnde')
3924
+ self.gen_cond_jump_false(cond, l_false)
3925
+ t1 = self.gen_value(a)
3926
+ self._convert(t1, tt)
3927
+ self.emit('MOV', self.reg(6), self.reg(0))
3928
+ self.emit('JMP', self.lab(l_end))
3929
+ self.label(l_false)
3930
+ t2 = self.gen_value(b)
3931
+ self._convert(t2, tt)
3932
+ self.emit('MOV', self.reg(6), self.reg(0))
3933
+ self.label(l_end)
3934
+ self.emit('MOV', self.reg(0), self.reg(6))
3935
+ return tt
3936
+
3937
+ # ---------------- 字符串化 (print/concat) ----------------
3938
+
3939
+ def _gen_string_value(self, node) -> None:
3940
+ """求值表达式并将 x0 转为字符串指针。"""
3941
+ t = self.gen_value(node)
3942
+ if t == 'string':
3943
+ return
3944
+ if t == 'float':
3945
+ self.emit('SYS', self.imm(Syscall.FTOA))
3946
+ elif t == 'bool':
3947
+ self.emit('SYS', self.imm(Syscall.BOOL_STR))
3948
+ else:
3949
+ self.emit('SYS', self.imm(Syscall.ITOA))
3950
+
3951
+ def gen_print(self, node, newline: bool) -> None:
3952
+ t = self.gen_value(node)
3953
+ if t == 'string':
3954
+ pass
3955
+ elif t == 'float':
3956
+ self.emit('SYS', self.imm(Syscall.FTOA))
3957
+ elif t == 'bool':
3958
+ self.emit('SYS', self.imm(Syscall.BOOL_STR))
3959
+ else:
3960
+ self.emit('SYS', self.imm(Syscall.ITOA))
3961
+ self.emit('SYS', self.imm(Syscall.PRINT_STR))
3962
+ if newline:
3963
+ self.emit('OUT', self.imm(10))
3964
+
3965
+ # ---------------- 函数调用 ----------------
3966
+
3967
+ def _builtin_ret_type(self, name: str):
3968
+ host = HOST_BUILTINS.get(name)
3969
+ if host is not None:
3970
+ return None if host[2] == 'void' else host[2]
3971
+ if name == 'exit' and name not in self.functions:
3972
+ return 'void'
3973
+ if name in ('sin', 'cos', 'tan', 'sqrt', 'pow', 'floor', 'ceil', 'round'):
3974
+ return 'float'
3975
+ if name in ('strlen', 'strcmp', 'rand', 'time', 'abs', 'input',
3976
+ 'idiv', 'atoi'):
3977
+ return 'int'
3978
+ if name in ('strcpy', 'int_to_str', 'itoa', 'float_to_str', 'ftoa',
3979
+ 'bool_to_str', 'substr', 'upper', 'lower',
3980
+ 'trim', 'ltrim', 'rtrim'):
3981
+ return 'string'
3982
+ return None
3983
+
3984
+ def _gen_host_sys(self, sys_id: int, args: list) -> None:
3985
+ """求值 args (左到右) 并放入 x0..x(n-1), 发射 SYS sys_id。"""
3986
+ for a in args:
3987
+ self.gen_value(a)
3988
+ self.emit('PUSH', self.reg(0))
3989
+ for i in range(len(args) - 1, -1, -1):
3990
+ self.emit('POP', self.reg(i))
3991
+ self.emit('SYS', self.imm(sys_id))
3992
+
3993
+ def _gen_call(self, name: str, args: list):
3994
+ # 用户自定义函数**优先于同名内建** (含宿主能力内建)。
3995
+ # 此前内建先分派, 结果: 用户定义的 `path_join` / `file_read` / `abs` …
3996
+ # 永远不会被调用 —— 无原生库时直接报 "host builtins … require the
3997
+ # native Go runtime", 原生路径下静默走宿主实现, 于是同一程序两条路径结论不同。
3998
+ fdef = self.functions.get(name)
3999
+ if fdef is not None:
4000
+ for k, arg in enumerate(args):
4001
+ at = self.gen_value(arg)
4002
+ ptype = fdef.params[k][1] if k < len(fdef.params) else None
4003
+ self._convert(at, self._param_promote(ptype))
4004
+ self.emit('PUSH', self.reg(0))
4005
+ self.emit('CALL', self.lab(name))
4006
+ # 调用方清理参数 (不得使用 x0, 它持有返回值)
4007
+ nargs = len(args)
4008
+ if nargs:
4009
+ self.emit('ADDI', self.reg(6), self.reg(32), self.imm(nargs * 8))
4010
+ self.emit('MOV', self.reg(32), self.reg(6))
4011
+ return fdef.ret_type
4012
+
4013
+ min_args = BUILTIN_MIN_ARGS.get(name)
4014
+ if min_args is not None and len(args) < min_args:
4015
+ raise CompilerError(
4016
+ f"{name}() expects at least {min_args} argument(s), "
4017
+ f"got {len(args)}")
4018
+ if name in ('println', 'print'):
4019
+ # 多参数: 依次字符串化输出 (无分隔符); 无参时 println 输出空行
4020
+ for a in args:
4021
+ self.gen_print(a, newline=False)
4022
+ if name == 'println' or not args:
4023
+ self.emit('OUT', self.imm(10))
4024
+ return 'void'
4025
+
4026
+ if name == 'exit' and name not in self.functions:
4027
+ # exit(code): 立即以 code 结束程序 (与 main 的返回值同一出口)。
4028
+ # 发出 MOV x0, code + HALT —— 入口就是 CALL main; HALT, 三路径一致。
4029
+ if len(args) != 1:
4030
+ raise CompilerError(
4031
+ f'exit() expects exactly 1 argument, got {len(args)}')
4032
+ at = self.gen_value(args[0])
4033
+ self._convert(at, 'int')
4034
+ self.emit('HALT')
4035
+ return 'void'
4036
+
4037
+ math_unary = {'sqrt': Syscall.SQRT, 'sin': Syscall.SIN,
4038
+ 'cos': Syscall.COS, 'tan': Syscall.TAN}
4039
+ if name in math_unary:
4040
+ at = self.gen_value(args[0])
4041
+ if at == 'int':
4042
+ self.emit('SYS', self.imm(Syscall.ITOF))
4043
+ self.emit('SYS', self.imm(math_unary[name]))
4044
+ return 'float'
4045
+
4046
+ round_unary = {'floor': Syscall.FLOOR, 'ceil': Syscall.CEIL,
4047
+ 'round': Syscall.ROUND}
4048
+ if name in round_unary:
4049
+ at = self.gen_value(args[0])
4050
+ if at in ('int', 'bool'):
4051
+ self.emit('SYS', self.imm(Syscall.ITOF))
4052
+ self.emit('SYS', self.imm(round_unary[name]))
4053
+ return 'float'
4054
+
4055
+ if name in ('min', 'max'):
4056
+ return self._gen_minmax(name, args)
4057
+
4058
+ if name == 'idiv':
4059
+ at = self._expr_type(args[0])
4060
+ bt = self._expr_type(args[1])
4061
+ if at in ('float', 'string') or bt in ('float', 'string'):
4062
+ raise CompilerError("idiv requires integer operands")
4063
+ self.gen_value(args[0])
4064
+ self.emit('PUSH', self.reg(0))
4065
+ self.gen_value(args[1])
4066
+ self.emit('MOV', self.reg(1), self.reg(0))
4067
+ self.emit('POP', self.reg(0))
4068
+ self.emit('DIV', self.reg(0), self.reg(1))
4069
+ return 'int'
4070
+
4071
+ if name == 'pow':
4072
+ self._arg_float(args[0])
4073
+ self.emit('PUSH', self.reg(0))
4074
+ self._arg_float(args[1])
4075
+ self.emit('MOV', self.reg(1), self.reg(0))
4076
+ self.emit('POP', self.reg(0))
4077
+ self.emit('SYS', self.imm(Syscall.POW))
4078
+ return 'float'
4079
+ if name == 'abs':
4080
+ self.gen_value(args[0])
4081
+ self.emit('SYS', self.imm(Syscall.ABS))
4082
+ return 'int'
4083
+ if name == 'strlen':
4084
+ self.gen_value(args[0])
4085
+ self.emit('SYS', self.imm(Syscall.STRLEN))
4086
+ return 'int'
4087
+ if name == 'strcmp':
4088
+ self.gen_value(args[0])
4089
+ self.emit('PUSH', self.reg(0))
4090
+ self.gen_value(args[1])
4091
+ self.emit('MOV', self.reg(1), self.reg(0))
4092
+ self.emit('POP', self.reg(0))
4093
+ self.emit('SYS', self.imm(Syscall.STRCMP))
4094
+ return 'int'
4095
+ if name == 'strcpy':
4096
+ self.gen_value(args[0])
4097
+ self.emit('PUSH', self.reg(0))
4098
+ self.emit('MOV', self.reg(0),
4099
+ self._data_operand(self._data_string("")))
4100
+ self.emit('MOV', self.reg(1), self.reg(0))
4101
+ self.emit('POP', self.reg(0))
4102
+ self.emit('SYS', self.imm(Syscall.STR_CONCAT))
4103
+ return 'string'
4104
+ if name == 'rand':
4105
+ self.emit('SYS', self.imm(Syscall.RAND))
4106
+ return 'int'
4107
+ if name == 'srand':
4108
+ self.gen_value(args[0])
4109
+ self.emit('SYS', self.imm(Syscall.SRAND))
4110
+ return 'void'
4111
+ if name in ('int_to_str', 'itoa'):
4112
+ self.gen_value(args[0])
4113
+ self.emit('SYS', self.imm(Syscall.ITOA))
4114
+ return 'string'
4115
+ if name in ('float_to_str', 'ftoa'):
4116
+ t = self.gen_value(args[0])
4117
+ if t in ('int', 'bool'):
4118
+ self.emit('SYS', self.imm(Syscall.ITOF))
4119
+ self.emit('SYS', self.imm(Syscall.FTOA))
4120
+ return 'string'
4121
+ if name in ('bool_to_str',):
4122
+ self.gen_value(args[0])
4123
+ self.emit('SYS', self.imm(Syscall.BOOL_STR))
4124
+ return 'string'
4125
+ if name == 'substr':
4126
+ self._gen_string_value(args[0])
4127
+ self.emit('PUSH', self.reg(0))
4128
+ self.gen_value(args[1])
4129
+ self.emit('PUSH', self.reg(0))
4130
+ self.gen_value(args[2])
4131
+ self.emit('MOV', self.reg(2), self.reg(0))
4132
+ self.emit('POP', self.reg(1))
4133
+ self.emit('POP', self.reg(0))
4134
+ self.emit('SYS', self.imm(Syscall.SUBSTR))
4135
+ return 'string'
4136
+ if name == 'indexof':
4137
+ self._gen_string_value(args[0])
4138
+ self.emit('PUSH', self.reg(0))
4139
+ self._gen_string_value(args[1])
4140
+ self.emit('MOV', self.reg(1), self.reg(0))
4141
+ self.emit('POP', self.reg(0))
4142
+ self.emit('SYS', self.imm(Syscall.INDEXOF))
4143
+ return 'int'
4144
+ if name in ('upper', 'lower'):
4145
+ self._gen_string_value(args[0])
4146
+ self.emit('SYS', self.imm(Syscall.TOUPPER if name == 'upper'
4147
+ else Syscall.TOLOWER))
4148
+ return 'string'
4149
+ if name in ('trim', 'ltrim', 'rtrim'):
4150
+ self._gen_string_value(args[0])
4151
+ sys_id = {'trim': Syscall.TRIM, 'ltrim': Syscall.LTRIM,
4152
+ 'rtrim': Syscall.RTRIM}[name]
4153
+ self.emit('SYS', self.imm(sys_id))
4154
+ return 'string'
4155
+ if name in ('to_int', 'to_float'):
4156
+ # 显式类型转换: to_int(x) 向零截断 (与 int x = 1.9 一致),
4157
+ # to_float(x) 整数提升为浮点。参数类型静态已知, 非数值报编译错。
4158
+ t = self.gen_value(args[0])
4159
+ target = 'int' if name == 'to_int' else 'float'
4160
+ if t not in ('int', 'float', 'bool'):
4161
+ raise CompilerError(
4162
+ f"{name}() expects a numeric argument, got {t} "
4163
+ f"at {self._loc()}"
4164
+ + (" (hint: use atoi() to parse a string)" if t == 'string' else ""))
4165
+ self._convert(t, target)
4166
+ return target
4167
+ if name == 'atoi':
4168
+ self.gen_value(args[0])
4169
+ self.emit('SYS', self.imm(Syscall.ATOI))
4170
+ return 'int'
4171
+ # ---- 宿主能力 (表驱动): 音频 / 画布 / 系统交互 / Termux API ----
4172
+ host = HOST_BUILTINS.get(name)
4173
+ if host is not None:
4174
+ sys_id, nargs, ret = host
4175
+ self._gen_host_sys(sys_id, args[:nargs])
4176
+ return ret
4177
+ if name == 'time':
4178
+ self.emit('SYS', self.imm(Syscall.TIME))
4179
+ return 'int'
4180
+ if name == 'input':
4181
+ # 读入一行并解析为整数 (失败为 0); 走 IN 指令, 三条执行路径语义一致。
4182
+ self.emit('IN', self.reg(0))
4183
+ return 'int'
4184
+
4185
+ # 用户函数 (已在 _gen_call 开头优先分派; 走到这里说明名字未知)
4186
+ if name in ('int', 'float'):
4187
+ # 常见迁移习惯: C/Python 风格的显式转换函数。给出可操作的替代写法。
4188
+ raise CompilerError(
4189
+ f"Unknown function: {name} (hint: use "
4190
+ f"to_{name}(x) for explicit conversion, or rely on implicit "
4191
+ "promotion in mixed int/float expressions)")
4192
+ raise CompilerError(f"Unknown function: {name}")
4193
+
4194
+ @staticmethod
4195
+ def _param_promote(ptype):
4196
+ # 数组参数衰减
4197
+ if _is_fixed_array(ptype):
4198
+ return ('ptrarray', _array_elem(ptype))
4199
+ return ptype
4200
+
4201
+ def _arg_float(self, node) -> None:
4202
+ t = self.gen_value(node)
4203
+ if t == 'int' or t == 'bool':
4204
+ self.emit('SYS', self.imm(Syscall.ITOF))
4205
+
4206
+ # ---------------- 条件跳转 ----------------
4207
+
4208
+ _COND_FALSE_JUMP = {
4209
+ '==': 'NE', '!=': 'EQ',
4210
+ '<': 'GE', '>': 'LE',
4211
+ '<=': 'GT', '>=': 'LT',
4212
+ }
4213
+
4214
+ def gen_cond_jump_false(self, node, label_false: str) -> None:
4215
+ kind = node[0]
4216
+ if kind == 'bool':
4217
+ if not node[1]:
4218
+ self.emit('JMP', self.lab(label_false))
4219
+ return
4220
+ if kind == 'binop' and node[1] == '&&':
4221
+ self.gen_cond_jump_false(node[2], label_false)
4222
+ self.gen_cond_jump_false(node[3], label_false)
4223
+ return
4224
+ if kind == 'binop' and node[1] == '||':
4225
+ l_true = self.new_label('ortrue')
4226
+ self.gen_cond_jump_true(node[2], l_true)
4227
+ self.gen_cond_jump_true(node[3], l_true)
4228
+ self.emit('JMP', self.lab(label_false))
4229
+ self.label(l_true)
4230
+ return
4231
+ if kind == 'not':
4232
+ self.gen_cond_jump_true(node[1], label_false)
4233
+ return
4234
+ if kind == 'binop' and node[1] in self._COND_FALSE_JUMP:
4235
+ op = node[1]
4236
+ lt = self._expr_type(node[2])
4237
+ rt = self._expr_type(node[3])
4238
+ float_mode = lt == 'float' or rt == 'float'
4239
+ self.gen_value(node[2])
4240
+ if float_mode and lt in ('int', 'bool'):
4241
+ self.emit('SYS', self.imm(Syscall.ITOF))
4242
+ self.emit('PUSH', self.reg(0))
4243
+ self.gen_value(node[3])
4244
+ if float_mode and rt in ('int', 'bool'):
4245
+ self.emit('SYS', self.imm(Syscall.ITOF))
4246
+ self.emit('MOV', self.reg(1), self.reg(0))
4247
+ self.emit('POP', self.reg(0))
4248
+ if float_mode:
4249
+ self.emit('SYS', self.imm(Syscall.FCMP))
4250
+ self.emit('CMP', self.reg(0), self.imm(0))
4251
+ else:
4252
+ self.emit('CMP', self.reg(0), self.reg(1))
4253
+ self.emit('B', self.lab(label_false),
4254
+ ('cond', self._COND_FALSE_JUMP[op]))
4255
+ return
4256
+ # 普通布尔值
4257
+ self.gen_value(node)
4258
+ self.emit('CMP', self.reg(0), self.imm(0))
4259
+ self.emit('JZ', self.lab(label_false))
4260
+
4261
+ def gen_cond_jump_true(self, node, label_true: str) -> None:
4262
+ l_false = self.new_label('cf')
4263
+ self.gen_cond_jump_false(node, l_false)
4264
+ self.emit('JMP', self.lab(label_true))
4265
+ self.label(l_false)