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/assembler.py ADDED
@@ -0,0 +1,619 @@
1
+ import os
2
+ import re
3
+ from typing import Any, Dict, List, Optional, Set, Tuple
4
+
5
+ from .console import Console
6
+ from .errors import AssemblerError
7
+ from .isa import Constants
8
+ from .memory import FastMemory
9
+
10
+ Operand = Tuple[Any, ...]
11
+ Instruction = Tuple[str, List[Operand]]
12
+
13
+ _RE_XREG = re.compile(r'^[xXrRwW]([0-9]|[12][0-9]|3[01])$')
14
+ _RE_VREG = re.compile(r'^[vV]([0-9]|[12][0-9]|3[01])(?:\.([0-3]))?$')
15
+ _RE_LABEL = re.compile(r'^[a-zA-Z_.$][a-zA-Z0-9_.$]*$')
16
+ _RE_RELOC = re.compile(
17
+ r'^\s*([a-zA-Z_.$][a-zA-Z0-9_.$]*)\s*(?:([+-])\s*(\d+))?\s*$')
18
+ _RE_EXPR_NAME = re.compile(r'\b[a-zA-Z_.$][a-zA-Z0-9_.$]*\b')
19
+ _RE_EQU_DIRECTIVE = {'EQU', 'SET'}
20
+ # 表达式只允许: 数字 / 已定义符号 / + - * / % ( ) 空白
21
+ _RE_EXPR_OK = re.compile(r'^[0-9+\-*/%()\s]+$')
22
+ # 表达式内的数值字面量 (十进制 / 0x / 0b / 0o, 允许下划线)
23
+ _RE_EXPR_NUM = re.compile(
24
+ r'0[xX][0-9a-fA-F_]+|0[bB][01_]+|0[oO][0-7_]+|\d[\d_]*')
25
+
26
+
27
+ def _eval_expr(text: str, symbols: Dict[str, int]) -> Optional[int]:
28
+ """求值简单算术表达式 (数值/已定义符号/四则/取模/括号/一元符号)。
29
+
30
+ 失败返回 None (调用方回退其它解析路径)。
31
+ """
32
+ text = text.strip().lstrip('#')
33
+ if not text:
34
+ return None
35
+
36
+ # 先把数值字面量替换为整数字符串, 避免 0xFF 中的字母与符号名混淆
37
+ def repl_num(match):
38
+ raw = match.group(0).replace('_', '')
39
+ if len(raw) > 1 and raw[:2].lower() in ('0x', '0b', '0o'):
40
+ raw = '0' + raw[1].lower() + raw[2:]
41
+ return str(int(raw, 0)) # 非法字面量 (如 0x_) 抛 ValueError -> 整体求值失败
42
+
43
+ try:
44
+ text = _RE_EXPR_NUM.sub(repl_num, text)
45
+ except ValueError:
46
+ return None
47
+
48
+ def repl_name(match):
49
+ name = match.group(0)
50
+ if name not in symbols:
51
+ raise KeyError(name)
52
+ return str(symbols[name])
53
+
54
+ try:
55
+ expr = _RE_EXPR_NAME.sub(repl_name, text)
56
+ except KeyError:
57
+ return None
58
+ if not _RE_EXPR_OK.match(expr):
59
+ return None
60
+ try:
61
+ return int(eval(expr, {'__builtins__': {}}, {})) # noqa: S307 - 本地汇编器输入
62
+ except Exception:
63
+ return None
64
+
65
+
66
+ class Assembler:
67
+ def __init__(self, memory: FastMemory, console: Optional[Console] = None,
68
+ strict: bool = False, logger=None,
69
+ preserve_labels: bool = False):
70
+ self.memory = memory
71
+ self.console = console or Console()
72
+ self.strict = strict
73
+ self.logger = logger
74
+ self.preserve_labels = preserve_labels
75
+ self.instructions: List[Instruction] = []
76
+ self.labels: Dict[str, int] = {}
77
+ self.data_labels: Dict[str, int] = {}
78
+ self.data_relocations: List[Tuple[int, int, str, int]] = []
79
+ self.equ: Dict[str, int] = {} # .equ/.set 常量
80
+
81
+ def _dbg(self, msg: str) -> None:
82
+ if self.logger is not None:
83
+ self.logger.debug(msg)
84
+
85
+ def assemble_file(self, filename: str) -> Tuple[List[Instruction], Dict[str, int], Dict[str, int]]:
86
+ lines = self._preprocess(filename, set())
87
+ self._dbg(f"ASM preprocess: {len(lines)} lines from {filename}")
88
+ result = self._assemble_lines(lines, filename)
89
+ self._dbg(f"ASM assembled: {len(result[0])} instructions, "
90
+ f"{len(result[1])} labels, {len(result[2])} data labels")
91
+ return result
92
+
93
+ def assemble_source(self, source: str, filename: str = '<source>'
94
+ ) -> Tuple[List[Instruction], Dict[str, int], Dict[str, int]]:
95
+ lines = []
96
+ for line_num, raw in enumerate(source.splitlines(), 1):
97
+ cleaned = self._strip_comment(raw)
98
+ if cleaned.strip():
99
+ lines.append((cleaned.strip(), line_num, filename))
100
+ return self._assemble_lines(lines, filename)
101
+
102
+ def _strip_comment(self, raw: str) -> str:
103
+ for marker in (';', '//'):
104
+ idx = raw.find(marker)
105
+ if idx >= 0:
106
+ raw = raw[:idx]
107
+ result = []
108
+ i = 0
109
+ while i < len(raw):
110
+ ch = raw[i]
111
+ if ch == '"':
112
+ result.append(ch)
113
+ i += 1
114
+ while i < len(raw):
115
+ result.append(raw[i])
116
+ if raw[i] == '"' and raw[i - 1] != '\\':
117
+ i += 1
118
+ break
119
+ i += 1
120
+ continue
121
+ if ch == '#':
122
+ at_start = len(''.join(result).strip()) == 0
123
+ rest = raw[i + 1:]
124
+ if at_start:
125
+ if rest.startswith('include'):
126
+ result.append(raw[i:])
127
+ return ''.join(result)
128
+ break
129
+ prev = raw[i - 1] if i > 0 else ' '
130
+ if prev in ' \t' and (rest == '' or rest[0] in ' \t'):
131
+ break
132
+ result.append(ch)
133
+ i += 1
134
+ return ''.join(result)
135
+
136
+ def _preprocess(self, filename: str, loaded: Set[str]) -> List[Tuple[str, int, str]]:
137
+ abs_path = os.path.abspath(filename)
138
+ if abs_path in loaded:
139
+ return []
140
+ loaded.add(abs_path)
141
+ dir_path = os.path.dirname(abs_path)
142
+
143
+ if not os.path.exists(abs_path):
144
+ raise AssemblerError('', f"File '{filename}' not found", filename=filename)
145
+
146
+ out: List[Tuple[str, int, str]] = []
147
+ with open(abs_path, encoding='utf-8') as f:
148
+ for line_num, raw in enumerate(f, 1):
149
+ stripped = raw.strip()
150
+ if stripped.startswith('#include'):
151
+ parts = stripped.split(None, 1)
152
+ if len(parts) < 2:
153
+ raise AssemblerError(stripped, "#include format error",
154
+ line_num, filename)
155
+ inc_file = parts[1].strip().strip('"<>')
156
+ inc_path = os.path.join(dir_path, inc_file)
157
+ if not os.path.exists(inc_path):
158
+ raise AssemblerError(stripped,
159
+ f"Include file '{inc_file}' not found",
160
+ line_num, filename)
161
+ out.extend(self._preprocess(inc_path, loaded))
162
+ continue
163
+ cleaned = self._strip_comment(raw)
164
+ if cleaned.strip():
165
+ out.append((cleaned.strip(), line_num, filename))
166
+ return out
167
+
168
+ def _parse_equ(self, line: str, line_num: int, fname: str) -> None:
169
+ """.equ/.set NAME <expr> (名称/值/四则/括号/已定义符号)。"""
170
+ head = line.split(None, 1)
171
+ rest = (head[1] if len(head) > 1 else '').lstrip(',').strip()
172
+ m = re.match(r'^([A-Za-z_.$][A-Za-z0-9_.$]*)\s*(?:=\s*)?(.*)$', rest)
173
+ if not m or not m.group(2).strip():
174
+ raise AssemblerError(
175
+ line, ".equ format: .equ NAME <expr> (例: .equ N, 8*4)",
176
+ line_num, fname)
177
+ name, expr = m.group(1), m.group(2).strip().lstrip(',').strip()
178
+ sym = dict(self.equ)
179
+ sym.update(self.labels)
180
+ sym.update(self.data_labels)
181
+ val = _eval_expr(expr, sym)
182
+ if val is None:
183
+ raise AssemblerError(line, f"Bad .equ expression: {expr!r}",
184
+ line_num, fname)
185
+ self.equ[name] = val
186
+
187
+ def _assemble_lines(self, lines: List[Tuple[str, int, str]], filename: str
188
+ ) -> Tuple[List[Instruction], Dict[str, int], Dict[str, int]]:
189
+ self.instructions = []
190
+ self.labels = {}
191
+ self.data_labels = {}
192
+ self.data_relocations = []
193
+ self.equ = {}
194
+ instr_index = 0
195
+ data_addr = 0
196
+ section = 'TEXT'
197
+ text_lines: List[Tuple[str, int, int, str]] = []
198
+
199
+ i = 0
200
+ while i < len(lines):
201
+ line, line_num, fname = lines[i]
202
+
203
+ upper = line.upper()
204
+ if upper in ('.TEXT', '.CODE', 'TEXT', 'CODE'):
205
+ section = 'TEXT'
206
+ i += 1
207
+ continue
208
+ if upper in ('.DATA', 'DATA'):
209
+ section = 'DATA'
210
+ i += 1
211
+ continue
212
+
213
+ # .equ/.set 常量定义 (需带点前缀, 避免与 PL 关键字 'set' 冲突)
214
+ head_tok = line.split(None, 1)
215
+ if head_tok and head_tok[0].lower() in ('.equ', '.set'):
216
+ self._parse_equ(line, line_num, fname)
217
+ i += 1
218
+ continue
219
+
220
+ rest_line = line
221
+ if ':' in line and not line.startswith('['):
222
+ before, after = line.split(':', 1)
223
+ label = before.strip()
224
+ if _RE_LABEL.match(label):
225
+ if section == 'TEXT':
226
+ self.labels[label] = instr_index
227
+ else:
228
+ self.data_labels[label] = data_addr
229
+ rest_line = after.strip()
230
+ if not rest_line:
231
+ i += 1
232
+ continue
233
+ else:
234
+ raise AssemblerError(line, f"Invalid label: {label}", line_num, fname)
235
+
236
+ if section == 'DATA':
237
+ sym = dict(self.equ)
238
+ sym.update(self.labels)
239
+ sym.update(self.data_labels)
240
+ data_addr = self._handle_data(rest_line, data_addr, line_num,
241
+ fname, sym)
242
+ i += 1
243
+ continue
244
+
245
+ text_lines.append((rest_line, instr_index, line_num, fname))
246
+ instr_index += 1
247
+ i += 1
248
+
249
+ # 指令二次解析: 符号表 = 标签 + 数据标签 + .equ (标签优先)
250
+ sym_final = dict(self.equ)
251
+ sym_final.update(self.labels)
252
+ sym_final.update(self.data_labels)
253
+ for line, _idx, line_num, fname in text_lines:
254
+ instr = self._parse_instruction(line, sym_final, line_num, fname)
255
+ self.instructions.append(instr)
256
+
257
+ return self.instructions, self.labels, self.data_labels
258
+
259
+ def _handle_data(self, line: str, data_addr: int, line_num: int, fname: str,
260
+ symbols: Optional[Dict[str, int]] = None) -> int:
261
+ # 先按空白拆出指令名 (如 ASCIZ "..."), 其余按逗号拆分
262
+ head_tokens = line.split(None, 1)
263
+ if not head_tokens:
264
+ return data_addr
265
+ directive = head_tokens[0].upper().lstrip('.')
266
+ rest = head_tokens[1] if len(head_tokens) > 1 else ''
267
+ parts = [directive] + self._split_operands(rest)
268
+ if not parts:
269
+ return data_addr
270
+ if directive in ('BYTE',):
271
+ directive = 'DB'
272
+ elif directive in ('WORD',):
273
+ directive = 'DW'
274
+ elif directive in ('DWORD',):
275
+ directive = 'DD'
276
+ elif directive in ('QWORD',):
277
+ directive = 'DQ'
278
+ if directive not in Constants.DATA_DIRECTIVES:
279
+ raise AssemblerError(line, f"Unknown data directive: {parts[0]}",
280
+ line_num, fname)
281
+
282
+ width = {'DB': 1, 'DW': 2, 'DD': 4, 'DQ': 8}.get(directive)
283
+
284
+ for val_str in parts[1:]:
285
+ val_str = val_str.strip()
286
+ if not val_str:
287
+ continue
288
+ if directive in ('ASCII', 'ASCIZ', 'STRING'):
289
+ text = self._unquote(val_str)
290
+ raw = text.encode('utf-8')
291
+ self.memory.write_block(data_addr, raw)
292
+ data_addr += len(raw)
293
+ if directive in ('ASCIZ', 'STRING'):
294
+ self.memory.write_byte(data_addr, 0)
295
+ data_addr += 1
296
+ continue
297
+ for piece in val_str.split(','):
298
+ piece = piece.strip()
299
+ if not piece:
300
+ continue
301
+ reloc = None
302
+ if self.preserve_labels and width in (2, 4, 8):
303
+ reloc = self._reloc_operand(piece, symbols or {},
304
+ allow_external=True)
305
+ if reloc is not None:
306
+ name = reloc[1]
307
+ addend = int(reloc[2]) if reloc[0] == 'reloc' else 0
308
+ if width == 2:
309
+ self.memory.write_word(data_addr, 0)
310
+ elif width == 4:
311
+ self.memory.write_dword(data_addr, 0)
312
+ else:
313
+ self.memory.write_qword(data_addr, 0)
314
+ self.data_relocations.append(
315
+ (data_addr, width, name, addend))
316
+ data_addr += width
317
+ continue
318
+ values = self._parse_data_values(piece, line, line_num, fname,
319
+ symbols)
320
+ for val in values:
321
+ if width == 1:
322
+ self.memory.write_byte(data_addr, val & 0xFF)
323
+ elif width == 2:
324
+ self.memory.write_word(data_addr, val & 0xFFFF)
325
+ elif width == 4:
326
+ self.memory.write_dword(data_addr, val & 0xFFFFFFFF)
327
+ else:
328
+ self.memory.write_qword(data_addr, val & 0xFFFFFFFFFFFFFFFF)
329
+ data_addr += width
330
+ return data_addr
331
+
332
+ def _parse_data_values(self, token: str, line: str, line_num: int,
333
+ fname: str,
334
+ symbols: Optional[Dict[str, int]] = None) -> List[int]:
335
+ token = token.strip().rstrip(',')
336
+ if token.startswith("'") and token.endswith("'") and len(token) >= 3:
337
+ body = token[1:-1]
338
+ if body.startswith('\\'):
339
+ return [{'n': 10, 't': 9, 'r': 13, '0': 0, '\\': 92,
340
+ "'": 39, '"': 34}.get(body[1], ord(body[1]))]
341
+ return [ord(body[0])]
342
+ if token.startswith('"') and token.endswith('"'):
343
+ vals = list(token[1:-1].encode('utf-8'))
344
+ vals.append(0)
345
+ return vals
346
+ try:
347
+ return [self.parse_immediate(token)]
348
+ except ValueError:
349
+ val = _eval_expr(token, symbols or {})
350
+ if val is not None:
351
+ return [val]
352
+ raise AssemblerError(line, f"Invalid data value: {token}",
353
+ line_num, fname) from None
354
+
355
+ @staticmethod
356
+ def _unquote(token: str) -> str:
357
+ token = token.strip()
358
+ if len(token) >= 2 and token[0] == '"' and token[-1] == '"':
359
+ return token[1:-1].encode('utf-8').decode('unicode_escape')
360
+ return token
361
+
362
+ @staticmethod
363
+ def parse_immediate(val: str) -> int:
364
+ val = val.strip().lstrip('#').replace('_', '')
365
+ if not val:
366
+ raise ValueError("empty immediate")
367
+ neg = False
368
+ if val[0] in '+-':
369
+ neg = val[0] == '-'
370
+ val = val[1:]
371
+ if not val:
372
+ raise ValueError("empty immediate")
373
+ lower = val.lower()
374
+ if lower.startswith('0x') or lower.startswith('0b') or lower.startswith('0o'):
375
+ # 进制前缀字面量: u/U/l/L 不是任何受支持进制的数字, 可安全剥离;
376
+ # 但 f/F 是合法的十六进制数字, 绝不能剥离
377
+ # (否则 #0x1F 会被截成 0x1, #0xABCDEF 会被截成 0xABCD)。
378
+ end = len(val)
379
+ while end > 0 and val[end - 1] in 'uUlL':
380
+ end -= 1
381
+ body = val[:end]
382
+ if lower.startswith('0x'):
383
+ n = int(body, 16)
384
+ elif lower.startswith('0b'):
385
+ n = int(body[2:], 2)
386
+ else:
387
+ n = int(body[2:], 8)
388
+ else:
389
+ # 十进制: f/F 只能是类型后缀, 在 64 位槽模型下无宽度差异, 直接忽略
390
+ while val and val[-1] in 'uUlLfF':
391
+ val = val[:-1]
392
+ if not val:
393
+ raise ValueError("empty immediate")
394
+ n = int(val)
395
+ return -n if neg else n
396
+
397
+ def _split_operands(self, text: str) -> List[str]:
398
+ parts = []
399
+ depth = 0
400
+ current = []
401
+ in_str = False
402
+ for ch in text:
403
+ if ch == '"':
404
+ in_str = not in_str
405
+ current.append(ch)
406
+ elif not in_str and ch == '[':
407
+ depth += 1
408
+ current.append(ch)
409
+ elif not in_str and ch == ']':
410
+ depth -= 1
411
+ current.append(ch)
412
+ elif ch == ',' and depth == 0 and not in_str:
413
+ parts.append(''.join(current).strip())
414
+ current = []
415
+ else:
416
+ current.append(ch)
417
+ tail = ''.join(current).strip()
418
+ if tail:
419
+ parts.append(tail)
420
+ return parts
421
+
422
+ def _parse_instruction(self, line: str, symbols: Dict[str, int],
423
+ line_num: int, fname: str) -> Instruction:
424
+ tokens = line.split(None, 1)
425
+ mnemonic_raw = tokens[0]
426
+ rest = tokens[1] if len(tokens) > 1 else ''
427
+
428
+ cond_prefix = None
429
+ mnemonic = mnemonic_raw
430
+ if '.' in mnemonic_raw:
431
+ base, suffix = mnemonic_raw.split('.', 1)
432
+ suffix_up = suffix.upper()
433
+ if suffix_up in Constants.CONDITIONS:
434
+ mnemonic = base
435
+ cond_prefix = suffix_up
436
+
437
+ keyword = mnemonic.lower()
438
+ if keyword in Constants.PL_KEYWORDS:
439
+ opcode = Constants.PL_KEYWORDS[keyword]
440
+ else:
441
+ opcode = mnemonic.upper()
442
+ if opcode not in Constants.OPCODE_NAME_TO_ENUM:
443
+ raise AssemblerError(line, f"Unknown instruction: {mnemonic_raw}",
444
+ line_num, fname)
445
+
446
+ operands: List[Operand] = []
447
+ if cond_prefix:
448
+ operands.append(('cond', cond_prefix))
449
+
450
+ for tok in self._split_operands(rest):
451
+ operands.append(self._parse_operand(tok, symbols, line, line_num, fname))
452
+
453
+ if self.strict:
454
+ expected = Constants.ARG_COUNTS.get(Constants.OPCODE_NAME_TO_ENUM[opcode], -1)
455
+ if expected >= 0 and len(operands) != expected:
456
+ raise AssemblerError(
457
+ line,
458
+ f"Argument count mismatch for {opcode}: expected {expected}, "
459
+ f"got {len(operands)}", line_num, fname)
460
+
461
+ return (opcode, operands)
462
+
463
+ def _parse_operand(self, tok: str, symbols: Dict[str, int], line: str,
464
+ line_num: int, fname: str) -> Operand:
465
+ tok = tok.strip()
466
+ if not tok:
467
+ raise AssemblerError(line, "Empty operand", line_num, fname)
468
+
469
+ if tok.startswith('['):
470
+ if not tok.endswith(']'):
471
+ raise AssemblerError(line, f"Malformed memory operand: {tok}",
472
+ line_num, fname)
473
+ return self._parse_mem(tok[1:-1], symbols, line, line_num, fname)
474
+
475
+ m = _RE_VREG.match(tok)
476
+ if m:
477
+ reg = int(m.group(1))
478
+ if m.group(2) is not None:
479
+ return ('veclane', reg, int(m.group(2)))
480
+ return ('vec', reg)
481
+
482
+ if _RE_XREG.match(tok):
483
+ return ('reg', int(tok[1:]))
484
+ if tok.lower() == 'sp':
485
+ return ('reg', Constants.SP_REG)
486
+ if tok.lower() in ('fp',):
487
+ return ('reg', 29)
488
+ if tok.lower() in ('lr',):
489
+ return ('reg', 30)
490
+ if tok.lower() == 'xzr':
491
+ return ('reg', 31)
492
+
493
+ if tok.upper() in Constants.CONDITIONS:
494
+ return ('cond', tok.upper())
495
+
496
+ if re.match(r'^[+-]?\d+\.\d+([eE][+-]?\d+)?$', tok):
497
+ return ('float', float(tok))
498
+
499
+ if tok.startswith('='):
500
+ name = tok[1:].strip()
501
+ if name in symbols:
502
+ return self._symbol_operand(name, symbols)
503
+ reloc = self._reloc_operand(name, symbols, allow_external=True)
504
+ if reloc is not None:
505
+ return reloc
506
+ val = _eval_expr(name, symbols)
507
+ if val is not None:
508
+ return ('imm', val)
509
+ if self.preserve_labels and _RE_LABEL.match(name):
510
+ return ('label', name)
511
+ raise AssemblerError(line, f"Undefined symbol: {name}", line_num, fname)
512
+
513
+ if tok.startswith('#'):
514
+ inner = tok[1:].strip()
515
+ try:
516
+ return ('imm', self.parse_immediate(tok))
517
+ except ValueError:
518
+ if inner in symbols:
519
+ return self._symbol_operand(inner, symbols)
520
+ reloc = self._reloc_operand(inner, symbols,
521
+ allow_external=True)
522
+ if reloc is not None:
523
+ return reloc
524
+ val = _eval_expr(inner, symbols)
525
+ if val is not None:
526
+ return ('imm', val)
527
+ if self.preserve_labels and _RE_LABEL.match(inner):
528
+ return ('label', inner)
529
+ raise AssemblerError(line, f"Bad immediate: {tok}",
530
+ line_num, fname) from None
531
+
532
+ try:
533
+ return ('imm', self.parse_immediate(tok))
534
+ except ValueError:
535
+ pass
536
+
537
+ # 可重定位对象模式: 裸标签/标签+偏移保持符号名, 交给链接器解析。
538
+ if self.preserve_labels:
539
+ reloc = self._reloc_operand(tok, symbols, allow_external=True)
540
+ if reloc is not None:
541
+ return reloc
542
+
543
+ # 表达式立即数 / 符号算术: 8+4*2 / SIZE-1 / loop+4 / 等
544
+ val = _eval_expr(tok, symbols)
545
+ if val is not None:
546
+ return ('imm', val)
547
+
548
+ if _RE_LABEL.match(tok):
549
+ if tok in symbols:
550
+ return self._symbol_operand(tok, symbols)
551
+ if self.preserve_labels:
552
+ return ('label', tok)
553
+ raise AssemblerError(line, f"Undefined label: {tok}", line_num, fname)
554
+
555
+ raise AssemblerError(line, f"Cannot parse operand: {tok}", line_num, fname)
556
+
557
+ def _symbol_operand(self, name: str,
558
+ symbols: Dict[str, int]) -> Operand:
559
+ """符号操作数: 默认为立即数; 可重定位对象模式保留标签名。"""
560
+ if self.preserve_labels:
561
+ return ('label', name)
562
+ return ('imm', symbols[name])
563
+
564
+ def _reloc_operand(self, expr: str, symbols: Dict[str, int],
565
+ allow_external: bool = False) -> Optional[Operand]:
566
+ """对象模式下的简单重定位: NAME / NAME+N / NAME-N。"""
567
+ if not self.preserve_labels:
568
+ return None
569
+ m = _RE_RELOC.match(expr)
570
+ if not m:
571
+ return None
572
+ name = m.group(1)
573
+ if name in self.equ:
574
+ return None # .equ 常量按立即数处理
575
+ if name not in symbols and not allow_external:
576
+ return None
577
+ addend = 0
578
+ if m.group(2):
579
+ addend = int(m.group(3))
580
+ if m.group(2) == '-':
581
+ addend = -addend
582
+ if addend:
583
+ return ('reloc', name, addend)
584
+ return ('label', name)
585
+
586
+ def _parse_mem(self, inner: str, symbols: Dict[str, int], line: str,
587
+ line_num: int, fname: str) -> Operand:
588
+ parts = [p.strip() for p in self._split_operands(inner) if p.strip()]
589
+ if not parts:
590
+ raise AssemblerError(line, "Empty memory operand", line_num, fname)
591
+
592
+ base = -1
593
+ offset = 0
594
+
595
+ first = parts[0]
596
+ if _RE_XREG.match(first) or first.lower() == 'sp':
597
+ base = Constants.SP_REG if first.lower() == 'sp' else int(first[1:])
598
+ else:
599
+ try:
600
+ offset = self.parse_immediate(first)
601
+ except ValueError:
602
+ val = _eval_expr(first.lstrip('#'), symbols)
603
+ if val is None:
604
+ raise AssemblerError(line, f"Bad memory base: {first}",
605
+ line_num, fname) from None
606
+ offset = val
607
+
608
+ if len(parts) > 1:
609
+ second = parts[1]
610
+ try:
611
+ offset += self.parse_immediate(second)
612
+ except ValueError:
613
+ val = _eval_expr(second.lstrip('#'), symbols)
614
+ if val is None:
615
+ raise AssemblerError(line, f"Bad memory offset: {second}",
616
+ line_num, fname) from None
617
+ offset += val
618
+
619
+ return ('mem', base, offset)