rcompiler 0.0.0-stage → 2.1.0

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.
@@ -0,0 +1,1352 @@
1
+ // rCompiler V2 — 标准积木编译表
2
+ // 覆盖全部标准 Scratch 类别:events/control/sensing/operators/data/looks/motion/sound/pen
3
+ // 选择性架构:motion/looks/pen 依赖舞台模块(isStageMode),sound 依赖声音模块(hasSound),
4
+ // 未加载对应模块时降级为控制台语义或编译期警告。
5
+
6
+ 'use strict';
7
+ const pkg = require('../package.json');
8
+
9
+ function registerStandard(ctx) {
10
+ const { S, T, C, Tools, emit, getvar, getlist, kwParse, compile_chain, registerScript, multi, isStageMode, frameWaitStmt, spawnScript, runtimeNumStr } = ctx;
11
+ const compiles = S.compiles;
12
+ const inputs = S.inputscompiles;
13
+
14
+ const RT = (code) => Tools.setruntime([code]);
15
+ const DEP = (d) => Tools.setdepend([d]);
16
+ const USE = (u) => Tools.setlibrary([u]);
17
+ const warnOnceSet = new Set();
18
+ const warnOnce = (msg) => { if (!warnOnceSet.has(msg)) { warnOnceSet.add(msg); console.warn('\x1b[33m' + msg + '\x1b[m'); } };
19
+ const awaitKw = () => multi() ? '.await' : '';
20
+ const web = S.profile && S.profile.backend === 'web';
21
+ const instantTy = () => web ? 'RcompilerInstant' : 'Instant';
22
+ const instantNow = () => web ? 'RcompilerInstant::now()' : 'Instant::now()';
23
+ // 字符串字面量:正常/调试内联,混淆走 rcompiler_str;isStrLit 判断结果是否为 &str 表达式
24
+ const sl = (s) => S.strlit(String(s));
25
+ const isStrLit = (e) => e.startsWith('"') || e.startsWith('rcompiler_str(');
26
+ // 事件帽轮询间隔:帧门控时按逻辑 tick 轮询(输入延迟 ≤ 1 tick);否则沿用旧轮询
27
+ const hatPoll = (ms) => {
28
+ if (S.frame && S.frame.gate) return multi() ? 'self.frame_wait().await;' : 'rcompiler_frame_wait();';
29
+ if (multi()) return web
30
+ ? `rcompiler_sleep(${ms}.0 / 1000.0).await;`
31
+ : `tokio::time::sleep(std::time::Duration::from_millis(${ms})).await;`;
32
+ return web
33
+ ? `rcompiler_sleep_sync(${ms}.0 / 1000.0);`
34
+ : `std::thread::sleep(std::time::Duration::from_millis(${ms}));`;
35
+ };
36
+ // 输入值安全取值(空输入/字符串兜底;注意 V1 兼容 API 方法名为大写)
37
+ const stuOf = (x) => (x && typeof x.Stu === 'function') ? x.Stu() : ((typeof x === 'string' && x) ? x : '""');
38
+ const striOf = (x) => (x && typeof x.Stri === 'function') ? x.Stri() : ((typeof x === 'string' && x) ? x : 'String::new()');
39
+ const numOf = (x) => (x && typeof x.Num === 'function') ? x.Num() : '0.0';
40
+ const sleepCall = (secsExpr) => multi()
41
+ ? (web ? `rcompiler_sleep(${secsExpr}).await;\n`
42
+ : `tokio::time::sleep(std::time::Duration::from_secs_f64(${secsExpr})).await;\n`)
43
+ : (web ? `rcompiler_sleep_sync(${secsExpr});\n`
44
+ : `std::thread::sleep(std::time::Duration::from_secs_f64(${secsExpr}));\n`);
45
+
46
+ // ================= 运行时辅助 =================
47
+ // JS Number() 忠实解析:0x/0o/0b 前缀按进制、空白容忍、Infinity/NaN(Rust parse 原生支持)。
48
+ // 模拟器项目(如 Linux rv32ima)以 "0x41" 形式传递字符码——JS 数值语义是正确性的关键
49
+ RT([
50
+ 'fn rcompiler_js_number(s: &str) -> Option<f64> {',
51
+ 'let t = s.trim();',
52
+ 'if t.is_empty() { return None; }',
53
+ 'let (sign, body) = match t.strip_prefix(\'-\') { Some(b) => (-1.0f64, b), None => (1.0f64, t.strip_prefix(\'+\').unwrap_or(t)) };',
54
+ // 快路径:纯十进制(数字/./e/E)免分配直 parse——模拟器热路径的字符串全是
55
+ // 这种形态,省掉 to_ascii_lowercase 的堆副本。失败即 None(与 JS NaN 一致),
56
+ // 含任何其它字符(0x 前缀、Infinity、空白、下划线…)落回慢路径保持 JS 语义。
57
+ 'let plain = !body.is_empty() && body.bytes().all(|c| c.is_ascii_digit() || c == b\'.\' || c == b\'e\' || c == b\'E\');',
58
+ 'if plain { return body.parse::<f64>().ok().map(|v| sign * v); }',
59
+ 'let lower = body.to_ascii_lowercase();',
60
+ 'let prefixed = if let Some(hex) = lower.strip_prefix("0x") {',
61
+ 'u128::from_str_radix(hex, 16).ok().map(|v| v as f64)',
62
+ '} else if let Some(oct) = lower.strip_prefix("0o") {',
63
+ 'u128::from_str_radix(oct, 8).ok().map(|v| v as f64)',
64
+ '} else if let Some(bin) = lower.strip_prefix("0b") {',
65
+ 'u128::from_str_radix(bin, 2).ok().map(|v| v as f64)',
66
+ '} else { None };',
67
+ 'match prefixed { Some(v) => Some(sign * v), None => body.parse::<f64>().ok().map(|v| sign * v) }',
68
+ '}'].join('\n'));
69
+ RT([
70
+ 'fn get_f64_string<T: AsRef<str>>(toget:T)->f64 {',
71
+ 'let s = toget.as_ref().trim();',
72
+ 'if let Some(v) = rcompiler_js_number(s) { return v; }',
73
+ 'match s.parse::<f64>() { Ok(parsed_num) => parsed_num, Err(_) => 0.0 }',
74
+ '}'].join('\n'));
75
+ RT([
76
+ 'fn get_usize_string<T: AsRef<str>>(toget:T)->usize {',
77
+ 'let s = toget.as_ref().trim();',
78
+ 'if let Some(v) = rcompiler_js_number(s) { return v as usize; }',
79
+ 'match s.parse::<usize>() { Ok(parsed_num) => parsed_num, Err(_) => 0 }',
80
+ '}'].join('\n'));
81
+ RT([
82
+ 'fn get_i32_string<T: AsRef<str>>(toget:T)->i32 {',
83
+ 'let s = toget.as_ref().trim();',
84
+ 'if let Some(v) = rcompiler_js_number(s) { return v as i32; }',
85
+ 'match s.parse::<i32>() { Ok(parsed_num) => parsed_num, Err(_) => 0 }',
86
+ '}'].join('\n'));
87
+ RT([
88
+ 'fn scratch_equals(a: &str, b: &str) -> bool {',
89
+ 'if let (Some(x), Some(y)) = (rcompiler_js_number(a), rcompiler_js_number(b)) { x == y }',
90
+ 'else { a.trim().eq_ignore_ascii_case(b.trim()) }',
91
+ '}'].join('\n'));
92
+ RT([
93
+ 'fn scratch_compare(a: &str, b: &str) -> std::cmp::Ordering {',
94
+ 'if let (Some(x), Some(y)) = (rcompiler_js_number(a), rcompiler_js_number(b)) { x.partial_cmp(&y).unwrap_or(std::cmp::Ordering::Equal) }',
95
+ 'else { a.trim().to_lowercase().cmp(&b.trim().to_lowercase()) }',
96
+ '}'].join('\n'));
97
+ RT([
98
+ 'fn scratch_contains(a: &str, b: &str) -> bool {',
99
+ 'a.to_lowercase().contains(&b.to_lowercase())',
100
+ '}'].join('\n'));
101
+ // 循环协作让出(对照 scratch-vm/TW 编译器:非 warp 循环每 tick 轮转,其他线程
102
+ // 每 ~33ms 被调度一次)。单线程协作运行时下这是公平性的关键——不能只按固定次数
103
+ // 分频(长批循环会让键盘/计时脚本饿到数秒),改按时间片:最多 ~8ms 让出一次。
104
+ // 原子计数每 64 次才查一次时钟(~20ns),吞吐无损;compare_exchange 只让一个
105
+ // 调用点真正让出。
106
+ if (multi()) {
107
+ if (web) {
108
+ // WASM:按 64 次让出一次(时间源不可用;JS 宿主按帧调度)
109
+ RT([
110
+ 'pub async fn rcompiler_loop_yield() {',
111
+ 'static C: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);',
112
+ 'if C.fetch_add(1, std::sync::atomic::Ordering::Relaxed) % 64 == 0 {',
113
+ 'tokio::task::yield_now().await;',
114
+ '}',
115
+ 'while RCOMPILER_PAUSED.load(std::sync::atomic::Ordering::Relaxed) { rcompiler_sleep(0.02).await; }',
116
+ '}'].join('\n'));
117
+ } else {
118
+ RT([
119
+ 'pub async fn rcompiler_loop_yield() {',
120
+ 'static C: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);',
121
+ 'static LAST: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);',
122
+ 'static T0: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new();',
123
+ 'let t0 = *T0.get_or_init(std::time::Instant::now);',
124
+ 'if C.fetch_add(1, std::sync::atomic::Ordering::Relaxed) % 64 == 0 {',
125
+ 'let now = t0.elapsed().as_millis() as u64;',
126
+ 'let last = LAST.load(std::sync::atomic::Ordering::Relaxed);',
127
+ 'if now.saturating_sub(last) >= 8 && LAST.compare_exchange(last, now, std::sync::atomic::Ordering::Relaxed, std::sync::atomic::Ordering::Relaxed).is_ok() {',
128
+ 'tokio::task::yield_now().await;',
129
+ '}',
130
+ '}',
131
+ 'while RCOMPILER_PAUSED.load(std::sync::atomic::Ordering::Relaxed) { tokio::time::sleep(std::time::Duration::from_millis(20)).await; }',
132
+ '}'].join('\n'));
133
+ }
134
+ } else {
135
+ if (web) {
136
+ RT([
137
+ 'fn rcompiler_loop_yield() {',
138
+ 'while RCOMPILER_PAUSED.load(std::sync::atomic::Ordering::Relaxed) { rcompiler_sleep_sync(0.02); }',
139
+ '}'].join('\n'));
140
+ } else {
141
+ RT([
142
+ 'fn rcompiler_loop_yield() {',
143
+ 'static C: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);',
144
+ 'static LAST: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);',
145
+ 'static T0: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new();',
146
+ 'let t0 = *T0.get_or_init(std::time::Instant::now);',
147
+ 'if C.fetch_add(1, std::sync::atomic::Ordering::Relaxed) % 64 == 0 {',
148
+ 'let now = t0.elapsed().as_millis() as u64;',
149
+ 'let last = LAST.load(std::sync::atomic::Ordering::Relaxed);',
150
+ 'if now.saturating_sub(last) >= 8 && LAST.compare_exchange(last, now, std::sync::atomic::Ordering::Relaxed, std::sync::atomic::Ordering::Relaxed).is_ok() {',
151
+ 'std::thread::yield_now();',
152
+ '}',
153
+ '}',
154
+ 'while RCOMPILER_PAUSED.load(std::sync::atomic::Ordering::Relaxed) { std::thread::sleep(std::time::Duration::from_millis(20)); }',
155
+ '}'].join('\n'));
156
+ }
157
+ }
158
+ // warp(运行时不刷新屏幕)过程体内的循环不 yielding——保持过程原子性
159
+ const loopYield = () => {
160
+ if (ctx.inWarp && ctx.inWarp()) return '';
161
+ return multi() ? 'rcompiler_loop_yield().await;\n' : 'rcompiler_loop_yield();\n';
162
+ };
163
+ RT([
164
+ 'fn scratch_mod(a: f64, b: f64) -> f64 {',
165
+ 'if b == 0.0 { return 0.0; }',
166
+ 'let r = a % b;',
167
+ 'if r != 0.0 && ((r < 0.0) != (b < 0.0)) { r + b } else { r }',
168
+ '}'].join('\n'));
169
+ RT([
170
+ 'fn get_char_at<T: AsRef<str>>(s: T, index: f64) -> String {',
171
+ 's.as_ref().chars().nth(((index - 1.0).max(0.0)) as usize).map(|c| c.to_string()).unwrap_or_default()',
172
+ '}'].join('\n'));
173
+
174
+ // ================= 运算符 =================
175
+ inputs['operator_add'] = (a) => new T.Num(`(${numOf(a.NUM1)} + ${numOf(a.NUM2)})`);
176
+ inputs['operator_subtract'] = (a) => new T.Num(`(${numOf(a.NUM1)} - ${numOf(a.NUM2)})`);
177
+ inputs['operator_multiply'] = (a) => new T.Num(`(${numOf(a.NUM1)} * ${numOf(a.NUM2)})`);
178
+ inputs['operator_divide'] = (a) => new T.Num(`(${numOf(a.NUM1)} / ${numOf(a.NUM2)})`);
179
+ inputs['operator_random'] = (a) => {
180
+ DEP('rand = "0.8"'); USE('use rand::Rng;');
181
+ RT([
182
+ 'fn operator_random(num1: f64, num2: f64) -> f64 {',
183
+ 'let mut rng = rand::thread_rng();',
184
+ 'let both_int = num1.fract() == 0.0 && num2.fract() == 0.0;',
185
+ 'if both_int { let (lo, hi) = if num1 <= num2 { (num1 as i64, num2 as i64) } else { (num2 as i64, num1 as i64) };',
186
+ 'return rng.gen_range(lo..=hi) as f64; }',
187
+ 'if rng.gen_bool(0.5) { return num1; } return num2;',
188
+ '}'].join('\n'));
189
+ return new T.Num(`operator_random(${numOf(a.FROM)},${numOf(a.TO)})`);
190
+ };
191
+ // JS Number() 的编译期版本:判断字面量能否数值化(用于等值/比较的 f64 快速路径)。
192
+ // 仅接受确定可数值化的形式;Infinity/NaN 文本不参与(保持字符串比较语义)
193
+ function jsNumConst(s) {
194
+ const t = String(s).trim();
195
+ if (t === '') return null;
196
+ if (!/^[+-]?(0[xX][0-9a-fA-F]+|0[oO][0-7]+|0[bB][01]+|(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?)$/.test(t)) return null;
197
+ const v = Number(t);
198
+ return Number.isFinite(v) ? v : null;
199
+ }
200
+ // Rust f64 字面量文本(整数补 .0;-0 特判)
201
+ function f64Lit(v) {
202
+ return Number.isInteger(v) && Math.abs(v) < 1e15 ? `${v}.0` : (Object.is(v, -0) ? '-0.0' : `${v}`);
203
+ }
204
+ // 反转义 Rust 字符串字面量(castUnParse 的逆),失败返回 null
205
+ function rustStrUnescape(lit) {
206
+ if (lit.length < 2 || lit[0] !== '"' || lit[lit.length - 1] !== '"') return null;
207
+ const body = lit.slice(1, -1);
208
+ let out = '', i = 0;
209
+ while (i < body.length) {
210
+ const c = body[i];
211
+ if (c === '\\') {
212
+ const n = body[i + 1];
213
+ if (n === 'n') { out += '\n'; i += 2; }
214
+ else if (n === 't') { out += '\t'; i += 2; }
215
+ else if (n === 'r') { out += '\r'; i += 2; }
216
+ else if (n === '\\') { out += '\\'; i += 2; }
217
+ else if (n === '"') { out += '"'; i += 2; }
218
+ else if (n === '\'') { out += '\''; i += 2; }
219
+ else if (n === '0') { out += '\0'; i += 2; }
220
+ else if (n === 'u') {
221
+ const end = body.indexOf('}', i);
222
+ if (end < 0) return null;
223
+ const cp = parseInt(body.slice(i + 3, end), 16);
224
+ if (!Number.isFinite(cp)) return null;
225
+ out += String.fromCodePoint(cp); i = end + 1;
226
+ } else return null;
227
+ } else { out += c; i += 1; }
228
+ }
229
+ return out;
230
+ }
231
+ // 操作数是否确定为 f64 表达式(T.Num;或声明为数值类型的变量)
232
+ function numOfOperand(t) {
233
+ if (t.type === 'Num') return t.Num();
234
+ if (t.type === 'Var') {
235
+ try {
236
+ const v = getvar(String(t.varname), t.varid);
237
+ if (v.v && v.v.declared && v.v.declared !== 'String' && v.v.declared !== 'bool') return t.Num();
238
+ } catch (e) { /* 动态变量场景回退普通路径 */ }
239
+ }
240
+ return null;
241
+ }
242
+ function strLitOf(t) {
243
+ if (t.type === 'Str') {
244
+ const raw = rustStrUnescape(t.input);
245
+ if (raw != null) return raw;
246
+ }
247
+ return null;
248
+ }
249
+ // 等值/比较快速路径:一侧为数值表达式、另一侧为可数值化字面量 →
250
+ // JS 语义此时必为数值比较(Cast.compare 双方可数值化即按数值),
251
+ // 直接生成 f64 比较,省去 to_string 分配与运行时解析(性能敏感项目的
252
+ // opcode 分发每条指令要做十余次此类比较)
253
+ // 数值比较辅助的运行时定义:NaN 按 JS 语义退化字符串比较(scratch_equals_num 的
254
+ // 双 NaN 相等、scratch_compare_num 的字符串序),常见路径零分配零解析
255
+ RT([
256
+ 'fn scratch_equals_num(a: f64, b: f64) -> bool {',
257
+ 'if a.is_nan() && b.is_nan() { return true; } // JS: "NaN"=="NaN" 字符串相等',
258
+ 'a == b',
259
+ '}'].join('\n'));
260
+ if (runtimeNumStr) runtimeNumStr(); // NaN 路径需要 rcompiler_num_str
261
+ RT([
262
+ 'fn scratch_compare_num(a: f64, b: f64) -> std::cmp::Ordering {',
263
+ 'if a.is_nan() || b.is_nan() { return scratch_compare(&rcompiler_num_str(a), &rcompiler_num_str(b)); }',
264
+ 'a.partial_cmp(&b).unwrap_or(std::cmp::Ordering::Equal)',
265
+ '}'].join('\n'));
266
+ function fastCmp(a, b, ordering) {
267
+ const n1 = numOfOperand(a), n2 = numOfOperand(b);
268
+ const s1 = strLitOf(a), s2 = strLitOf(b);
269
+ // 整数补 .0 —— Rust 的 f64 比较要求右操作数是浮点字面量
270
+ const f64lit = (v) => Number.isInteger(v) && Math.abs(v) < 1e15 ? `${v}.0` : (Object.is(v, -0) ? '-0.0' : `${v}`);
271
+ // 双侧均为数值表达式 → 免分配数值比较(NaN 语义由 helper 精确保持;
272
+ // 热点分发路径每指令多次此类比较)
273
+ if (n1 != null && n2 != null) {
274
+ if (ordering === 'eq') return new T.Bool(`scratch_equals_num((${n1}),(${n2}))`);
275
+ return new T.Bool(`scratch_compare_num((${n1}),(${n2})) == std::cmp::Ordering::${ordering === 'gt' ? 'Greater' : 'Less'}`);
276
+ }
277
+ if (n1 != null && s2 != null) {
278
+ const v = jsNumConst(s2);
279
+ if (v != null) {
280
+ const lit = f64lit(v);
281
+ if (ordering === 'eq') return new T.Bool(`scratch_equals_num((${n1}),${lit})`);
282
+ return new T.Bool(`scratch_compare_num((${n1}),${lit}) == std::cmp::Ordering::${ordering === 'gt' ? 'Greater' : 'Less'}`);
283
+ }
284
+ }
285
+ if (n2 != null && s1 != null) {
286
+ const v = jsNumConst(s1);
287
+ if (v != null) {
288
+ const lit = f64lit(v);
289
+ if (ordering === 'eq') return new T.Bool(`scratch_equals_num((${n2}),${lit})`);
290
+ return new T.Bool(`scratch_compare_num((${n2}),${lit}) == std::cmp::Ordering::${ordering === 'gt' ? 'Less' : 'Greater'}`);
291
+ }
292
+ }
293
+ return null;
294
+ }
295
+ inputs['operator_equals'] = (a) => fastCmp(a.OPERAND1, a.OPERAND2, 'eq')
296
+ || new T.Bool(`scratch_equals(&${stuOf(a.OPERAND1)},&${stuOf(a.OPERAND2)})`);
297
+ inputs['operator_gt'] = (a) => fastCmp(a.OPERAND1, a.OPERAND2, 'gt')
298
+ || new T.Bool(`scratch_compare(&${stuOf(a.OPERAND1)},&${stuOf(a.OPERAND2)}) == std::cmp::Ordering::Greater`);
299
+ inputs['operator_lt'] = (a) => fastCmp(a.OPERAND1, a.OPERAND2, 'lt')
300
+ || new T.Bool(`scratch_compare(&${stuOf(a.OPERAND1)},&${stuOf(a.OPERAND2)}) == std::cmp::Ordering::Less`);
301
+ inputs['operator_and'] = (a) => new T.Bool(`(${C.SafeBool(a.OPERAND1)} && ${C.SafeBool(a.OPERAND2)})`);
302
+ inputs['operator_or'] = (a) => new T.Bool(`(${C.SafeBool(a.OPERAND1)} || ${C.SafeBool(a.OPERAND2)})`);
303
+ inputs['operator_not'] = (a) => new T.Bool(`(!(${C.SafeBool(a.OPERAND)}))`);
304
+ inputs['operator_join'] = (a) => new T.Stri(`((${stuOf(a.STRING1)}).to_owned()+&(${stuOf(a.STRING2)}).to_owned())`);
305
+ inputs['operator_letter_of'] = (a) => new T.Stri(`get_char_at(${stuOf(a.STRING)},${numOf(a.LETTER)})`);
306
+ inputs['operator_length'] = (a) => new T.Num(`((${stuOf(a.STRING)}).chars().count() as f64)`);
307
+ inputs['operator_contains'] = (a) => new T.Bool(`scratch_contains(&${stuOf(a.STRING1)},&${stuOf(a.STRING2)})`);
308
+ inputs['operator_mod'] = (a) => new T.Num(`scratch_mod(${numOf(a.NUM1)},${numOf(a.NUM2)})`);
309
+ inputs['operator_round'] = (a) => new T.Num(`((${numOf(a.NUM)}) as f64).round()`);
310
+ inputs['operator_mathop'] = (a) => {
311
+ const op = a.scope.block.fields.OPERATOR[0];
312
+ const x = `(${numOf(a.NUM)}) as f64`;
313
+ switch (op) {
314
+ case 'abs': return new T.Num(`(${x}).abs()`);
315
+ case 'floor': return new T.Num(`(${x}).floor()`);
316
+ case 'ceiling': return new T.Num(`(${x}).ceil()`);
317
+ case 'sqrt': return new T.Num(`(${x}).max(0.0).sqrt()`);
318
+ case 'sin': return new T.Num(`(((${x}).to_radians()).sin())`);
319
+ case 'cos': return new T.Num(`(((${x}).to_radians()).cos())`);
320
+ case 'tan': return new T.Num(`(((${x}).to_radians()).tan())`);
321
+ case 'ln': return new T.Num(`if (${x}) > 0.0 { (${x}).ln() } else { 0.0 }`);
322
+ case 'log': return new T.Num(`if (${x}) > 0.0 { (${x}).log10() } else { 0.0 }`);
323
+ case 'e ^': return new T.Num(`((${x}).exp())`);
324
+ case '10 ^': return new T.Num(`(10.0f64.powf(${x}))`);
325
+ default:
326
+ warnOnce(`operator_mathop 暂不支持: ${op}`);
327
+ return new T.Num('0.0');
328
+ }
329
+ };
330
+
331
+ // ================= 数据:变量 =================
332
+ compiles['data_setvariableto'] = (a) => {
333
+ ctx.markWrite();
334
+ const [name, id] = a.scope.block.fields.VARIABLE;
335
+ const v = getvar(String(name), id);
336
+ // 数值表达式直走 setNum:省去 String(Number(v)) 的格式化+回解析往返。
337
+ // 语义等价——JS 里 x = <JS数值> 对 f64 / RcompilerV::N / String 声明(rcompiler_num_str
338
+ // 规范形态)三种存储一致;未类型化变量(RcompilerV)的"非规范字符串形态保留"
339
+ // 语义只涉及字符串写入,数值写入本就该是 N 形态(对照 scratch-vm 单 JS 值模型)。
340
+ // 判定保守:仅数字字面量与"声明为数值类型的变量";未类型化/字符串变量可能
341
+ // 运行期持有字符串,不可数值化。
342
+ const valIsNum = a.VALUE && (
343
+ a.VALUE.type === 'Num' ||
344
+ (a.VALUE.type === 'Var' && a.VALUE.varid != null && (() => {
345
+ const sv = getvar(String(a.VALUE.varname), a.VALUE.varid);
346
+ const d = sv && sv.v && sv.v.declared;
347
+ return d === 'f64' || d === 'i32' || d === 'usize';
348
+ })())
349
+ );
350
+ // 数值声明目标:无论源是什么(变量/字符串/数值),落库值恒为
351
+ // get_f64_string(字符串形态)——setNum(VALUE.Num()) 与旧 setStr 路径逐字节
352
+ // 一致,且 Var 源的 Num() 走 RefCell 借阅直 parse,省一次 String 堆克隆。
353
+ // Bool 源例外(Num()=1.0/0.0,旧路径 "true"→parse→0.0,不等价),不在此列。
354
+ const td = v.v && v.v.declared;
355
+ const numDecl = td === 'f64' || td === 'i32' || td === 'usize';
356
+ const valStrLike = a.VALUE && ['Num', 'Str', 'Stri', 'Var'].includes(a.VALUE.type);
357
+ if (valIsNum || (numDecl && valStrLike)) return v.setNum(a.VALUE.Num()) + '\n';
358
+ return v.setStr(a.VALUE.Stri()) + '\n';
359
+ };
360
+ compiles['data_changevariableby'] = (a) => {
361
+ ctx.markWrite();
362
+ const [name, id] = a.scope.block.fields.VARIABLE;
363
+ const v = getvar(String(name), id);
364
+ return v.changeNum(a.VALUE.Num()) + '\n';
365
+ };
366
+ inputs['data_variable'] = (a) => {
367
+ const [name, id] = a.scope.block.fields.VARIABLE;
368
+ return new T.Var(String(name), id);
369
+ };
370
+ compiles['data_showvariable'] = (a) => `// showvariable ${a.scope.block.fields.VARIABLE[0]}\n`;
371
+ compiles['data_hidevariable'] = (a) => `// hidevariable ${a.scope.block.fields.VARIABLE[0]}\n`;
372
+
373
+ // ================= 数据:列表 =================
374
+ // 列表元素类型:declared==='f64' → Vec<f64>(固定类型优化:零字符串转换);
375
+ // 否则 Vec<String>(Scratch 原生动态类型语义)
376
+ const listIsNum = (name, id) => {
377
+ const l = ctx.listInfo ? ctx.listInfo(String(name), id) : null;
378
+ return !!(l && l.declared === 'f64');
379
+ };
380
+ const f64Helpers = () => {
381
+ ctx.runtimeRcompilerList();
382
+ RT(['fn list_item_num_f64<L: RcompilerList<f64>>(v: &L, item: &str) -> f64 {',
383
+ 'let n = v.llen(); let mut i = 0usize;',
384
+ 'while i < n { if let Some(x) = v.lget(i) { if scratch_equals(&x.to_string(), item) { return i as f64 + 1.0 } } i += 1; }',
385
+ '0.0',
386
+ '}'].join('\n'));
387
+ RT(['fn list_contains_f64<L: RcompilerList<f64>>(v: &L, item: &str) -> bool {',
388
+ 'let n = v.llen(); let mut i = 0usize;',
389
+ 'while i < n { if let Some(x) = v.lget(i) { if scratch_equals(&x.to_string(), item) { return true } } i += 1; }',
390
+ 'false',
391
+ '}'].join('\n'));
392
+ };
393
+ inputs['data_listcontents'] = (a) => {
394
+ const [name, id] = a.scope.block.fields.LIST;
395
+ return new T.ListVar(String(name), id);
396
+ };
397
+ inputs['data_itemoflist'] = (a) => {
398
+ const [name, id] = a.scope.block.fields.LIST;
399
+ const field = ctx.getListField(String(name), id);
400
+ const idx = a.INDEX == '"last"' ? `${field}.llen()` : `(${a.INDEX.Usize()})`;
401
+ ctx.runtimeRcompilerList();
402
+ // 短锁读取:锁只在 lget 内存活——同一语句多次读同一列表不会自死锁
403
+ const base = `${field}.lget(if let Some(r) = ${idx}.checked_sub(1) { r } else { 0 })`;
404
+ if (listIsNum(name, id)) {
405
+ // f64 列表:数值上下文直用,字符串上下文由类型适配器 to_string()
406
+ return new T.Num(`${base}.unwrap_or(0.0)`);
407
+ }
408
+ return new T.Stri(`${base}.map(|x: String| x).unwrap_or_default()`);
409
+ };
410
+ inputs['data_itemnumoflist'] = (a) => {
411
+ const [name, id] = a.scope.block.fields.LIST;
412
+ const field = ctx.getListField(String(name), id);
413
+ if (listIsNum(name, id)) {
414
+ f64Helpers();
415
+ return new T.Num(`list_item_num_f64(&${field}, ${stuOf(a.ITEM)})`);
416
+ }
417
+ ctx.runtimeRcompilerList();
418
+ return new T.Num(`${field}.lpos(&${a.ITEM.Stri()})`);
419
+ };
420
+ inputs['data_lengthoflist'] = (a) => {
421
+ const [name, id] = a.scope.block.fields.LIST;
422
+ ctx.runtimeRcompilerList();
423
+ return new T.Num(`(${ctx.getListField(String(name), id)}.llen() as f64)`);
424
+ };
425
+ inputs['data_listcontainsitem'] = (a) => {
426
+ const [name, id] = a.scope.block.fields.LIST;
427
+ const field = ctx.getListField(String(name), id);
428
+ if (listIsNum(name, id)) {
429
+ f64Helpers();
430
+ return new T.Bool(`list_contains_f64(&${field}, ${stuOf(a.ITEM)})`);
431
+ }
432
+ ctx.runtimeRcompilerList();
433
+ return new T.Bool(`${field}.lhas(&${C.toCopyableStri(a.ITEM.Stri())})`);
434
+ };
435
+ compiles['data_addtolist'] = (a) => {
436
+ ctx.markWrite();
437
+ const [name, id] = a.scope.block.fields.LIST;
438
+ // 先把元素求值到局部再 push——Rust 中 `recv.push(arg)` 的接收者锁先于 arg 求值,
439
+ // 若 arg 内再读同一列表会同线程自死锁
440
+ if (listIsNum(name, id)) {
441
+ // 元素已是数值表达式时直用(T.Num 经 stuOf 会格式化成字符串再解析回来——纯往返)
442
+ const addin = a.ITEM.type === 'Num' ? a.ITEM.Num() : `get_f64_string(&(${stuOf(a.ITEM)}))`;
443
+ if (a.ITEM.type !== 'Num') ctx.runtimeParseF64();
444
+ return `let __addin = (${addin});\n${getlist(String(name), id)}.push(__addin);\n`;
445
+ }
446
+ return `let __addin = ${C.toCopyableStri(a.ITEM.Stri())};\n${getlist(String(name), id)}.push(__addin);\n`;
447
+ };
448
+ compiles['data_deletealloflist'] = (a) => {
449
+ ctx.markWrite();
450
+ const [name, id] = a.scope.block.fields.LIST;
451
+ return `${getlist(String(name), id)}.clear();\n`;
452
+ };
453
+ compiles['data_deleteoflist'] = (a) => {
454
+ ctx.markWrite();
455
+ const [name, id] = a.scope.block.fields.LIST;
456
+ const acc = getlist(String(name), id);
457
+ const field = ctx.getListField(String(name), id);
458
+ ctx.runtimeRcompilerList();
459
+ // 先用短锁 llen 求长度再写——条件里的 acc.lock() 临时值会存活到整个 if 结束,
460
+ // 与 remove 的锁形成同线程自死锁
461
+ const idx = a.INDEX == '"last"' ? `${field}.llen()` : `(${a.INDEX.Usize()})`;
462
+ return `if let Some(__ri) = ${idx}.checked_sub(1) { let __ln = ${field}.llen(); if __ri < __ln { ${acc}.remove(__ri); } }\n`;
463
+ };
464
+ compiles['data_insertatlist'] = (a) => {
465
+ ctx.markWrite();
466
+ const [name, id] = a.scope.block.fields.LIST;
467
+ const acc = getlist(String(name), id);
468
+ const field = ctx.getListField(String(name), id);
469
+ ctx.runtimeRcompilerList();
470
+ const idx = a.INDEX == '"last"' ? `${field}.llen()` : `(${a.INDEX.Usize()})`;
471
+ // 同 data_deleteoflist:长度用短锁 llen,写锁单独存活
472
+ if (listIsNum(name, id)) {
473
+ const item = a.ITEM.type === 'Num' ? a.ITEM.Num() : `get_f64_string(&(${stuOf(a.ITEM)}))`;
474
+ if (a.ITEM.type !== 'Num') ctx.runtimeParseF64();
475
+ return `let __ii = (${item});\nif let Some(__at) = ${idx}.checked_sub(1) { let __ln = ${field}.llen(); if __at <= __ln { ${acc}.insert(__at, __ii); } }\n`;
476
+ }
477
+ return `let __ii = ${C.toCopyableStri(a.ITEM.Stri())};\nif let Some(__at) = ${idx}.checked_sub(1) { let __ln = ${field}.llen(); if __at <= __ln { ${acc}.insert(__at, __ii); } }\n`;
478
+ };
479
+ compiles['data_replaceitemoflist'] = (a) => {
480
+ ctx.markWrite();
481
+ const [name, id] = a.scope.block.fields.LIST;
482
+ const acc = getlist(String(name), id);
483
+ const field = ctx.getListField(String(name), id);
484
+ ctx.runtimeRcompilerList();
485
+ const idx = a.INDEX == '"last"' ? `${field}.llen()` : `(${a.INDEX.Usize()})`;
486
+ if (listIsNum(name, id)) {
487
+ const item = a.ITEM.type === 'Num' ? a.ITEM.Num() : `get_f64_string(&(${stuOf(a.ITEM)}))`;
488
+ if (a.ITEM.type !== 'Num') ctx.runtimeParseF64();
489
+ return `let __ri2 = (${item});\nif let Some(__at2) = ${idx}.checked_sub(1) { if let Some(it) = ${acc}.get_mut(__at2) { *it = __ri2; } }\n`;
490
+ }
491
+ return `let __ri2 = (${a.ITEM.Str()}).to_string();\nif let Some(__at2) = ${idx}.checked_sub(1) { if let Some(it) = ${acc}.get_mut(__at2) { *it = __ri2; } }\n`;
492
+ };
493
+
494
+ // ================= 事件 =================
495
+ compiles['event_whenflagclicked'] = async (a) => {
496
+ S.flagcount++;
497
+ const name = S.fnName('flag' + S.flagcount);
498
+ const body = await compile_chain(a.scope.block.next, a.scope.target);
499
+ registerScript(name, body, 'flag');
500
+ return '';
501
+ };
502
+ compiles['event_whenbroadcastreceived'] = async (a) => {
503
+ const bname = a.scope.block.fields.BROADCAST_OPTION[0];
504
+ S.bccount++;
505
+ const fname = S.fnName('bc_' + S.bccount);
506
+ const body = await compile_chain(a.scope.block.next, a.scope.target);
507
+ registerScript(fname, body, 'broadcast', { broadcast: String(bname) });
508
+ if (!S.broadcastScripts.has(String(bname))) S.broadcastScripts.set(String(bname), []);
509
+ S.broadcastScripts.get(String(bname)).push(fname);
510
+ S.broadcastFnTi.set(fname, S.targetID);
511
+ return '';
512
+ };
513
+ const spawnTracked = (ti, inner) => `{ let __s = self.clone(); let __h = tokio::spawn(${spawnScript(`async move { __s.${inner} }`)}); rcompiler_track_task(${ti}, &__h); }`;
514
+ // 广播分发:原型实例 + 全部存活克隆实例(对照 startHats 遍历全部 targets/clones)
515
+ const spawnClonesOf = (ti, f) => isStageMode()
516
+ ? `for __ci in self.stage.clone_indices(${ti}) { if let Some(__cs) = rcompiler_clone_get(__ci) { let __h = tokio::spawn(${spawnScript(`async move { __cs.${f}().await; }`)}); rcompiler_track_task(${ti}, &__h); } }\n`
517
+ : '';
518
+ compiles['event_broadcast'] = (a) => {
519
+ if (!multi()) return '';
520
+ const bname = a.BROADCAST_INPUT && a.BROADCAST_INPUT.input != null ? String(a.BROADCAST_INPUT.input) : '';
521
+ const list = S.broadcastScripts.get(bname);
522
+ if (!list) return '';
523
+ return list.map(f => spawnTracked(S.broadcastFnTi.get(f) ?? 0, `${f}().await;`) + spawnClonesOf(S.broadcastFnTi.get(f) ?? 0, f)).join('');
524
+ };
525
+ compiles['event_broadcastandwait'] = (a) => {
526
+ if (!multi()) return '';
527
+ const bname = a.BROADCAST_INPUT && a.BROADCAST_INPUT.input != null ? String(a.BROADCAST_INPUT.input) : '';
528
+ const list = S.broadcastScripts.get(bname);
529
+ if (!list) return '';
530
+ let out = `let mut __bhs: Vec<tokio::task::JoinHandle<()>> = vec![`;
531
+ out += list.map(f => `{ let __s = self.clone(); let __h = tokio::spawn(${spawnScript(`async move { __s.${f}().await; }`)}); rcompiler_track_task(${S.broadcastFnTi.get(f) ?? 0}, &__h); __h }`).join(', ');
532
+ out += '];\n';
533
+ if (isStageMode()) {
534
+ for (const f of list) {
535
+ const ti = S.broadcastFnTi.get(f) ?? 0;
536
+ out += `for __ci in self.stage.clone_indices(${ti}) { if let Some(__cs) = rcompiler_clone_get(__ci) { __bhs.push(tokio::spawn(${spawnScript(`async move { __cs.${f}().await; }`)})); } }\n`;
537
+ }
538
+ }
539
+ out += 'for __h in __bhs { let _ = __h.await; }\n';
540
+ return out;
541
+ };
542
+ compiles['event_whenthisspriteclicked'] = async (a) => {
543
+ if (!isStageMode()) { warnOnce('角色点击帽需要舞台模块(项目未使用舞台积木),已跳过'); return ''; }
544
+ S.clickcount++;
545
+ const name = S.fnName('clicked' + S.clickcount);
546
+ const body = await compile_chain(a.scope.block.next, a.scope.target);
547
+ // 独立事件游标:点击克隆视同点击原型;多帽不互相吞事件(对照 startHats 分发)
548
+ const loop = `let mut __cc = self.stage.click_seq();\nloop {\nif self.stage.next_click(&mut __cc, ${S.targetID}) {\n${body}\n}\n${hatPoll(10)}}`;
549
+ const fn = `async fn ${name}(mut self: std::sync::Arc<Self>){\n${loop}\n}\n`;
550
+ emit.func(fn);
551
+ emit.scripts.push({ name, kind: 'click', ti: S.targetID });
552
+ return '';
553
+ };
554
+
555
+ compiles['event_whenstageclicked'] = async (a) => {
556
+ if (!isStageMode()) { warnOnce('舞台点击帽需要舞台模块,已跳过'); return ''; }
557
+ S.clickcount++;
558
+ const name = S.fnName('clicked' + S.clickcount);
559
+ const body = await compile_chain(a.scope.block.next, a.scope.target);
560
+ const loop = `let mut __cc = self.stage.click_seq();\nloop {\nif self.stage.next_click(&mut __cc, usize::MAX) {\n${body}\n}\n${hatPoll(10)}}`;
561
+ const fn = `async fn ${name}(mut self: std::sync::Arc<Self>){\n${loop}\n}\n`;
562
+ emit.func(fn);
563
+ emit.scripts.push({ name, kind: 'click', ti: S.targetID });
564
+ return '';
565
+ };
566
+ compiles['event_whenkeypressed'] = async (a) => {
567
+ S.presscount++;
568
+ const name = S.fnName('press' + S.presscount);
569
+ const body = await compile_chain(a.scope.block.next, a.scope.target);
570
+ const keyName = String(a.scope.block.fields.KEY_OPTION[0]);
571
+ if (web && !isStageMode()) {
572
+ warnOnce('WASM 无舞台项目的按键帽暂不支持,已跳过');
573
+ return '';
574
+ }
575
+ if (isStageMode()) {
576
+ // 独立事件游标:具体键帽与 “任意” 帽互不吞事件(对照 startHats 双分发)
577
+ const loop = [
578
+ `let mut __kc = self.stage.key_seq();`,
579
+ 'loop {',
580
+ `if self.stage.next_key(&mut __kc, ${sl(keyName)}) {`,
581
+ body,
582
+ '}',
583
+ hatPoll(5),
584
+ '}'
585
+ ].join('\n');
586
+ const fn = `async fn ${name}(mut self: std::sync::Arc<Self>){\n${loop}\n}\n`;
587
+ emit.func(fn);
588
+ emit.scripts.push({ name, kind: 'key', ti: S.targetID });
589
+ return '';
590
+ }
591
+ // 控制台:crossterm 轮询
592
+ emit.dep('crossterm = "0.27.0"');
593
+ emit.use('use crossterm::event::{self, Event, KeyCode};');
594
+ const pressing = C.toPress(keyName);
595
+ const loop = [
596
+ 'loop {',
597
+ 'if event::poll(std::time::Duration::from_millis(5)).unwrap() {',
598
+ 'if let Event::Key(__e) = event::read().unwrap() {',
599
+ 'match __e.code {',
600
+ `KeyCode::${pressing} => {`,
601
+ body,
602
+ '},',
603
+ '_ => (),',
604
+ '}',
605
+ '}',
606
+ '}',
607
+ hatPoll(5),
608
+ '}'
609
+ ].join('\n');
610
+ const fn = `async fn ${name}(mut self: std::sync::Arc<Self>){\n${loop}\n}\n`;
611
+ emit.func(fn);
612
+ emit.scripts.push({ name, kind: 'key', ti: S.targetID });
613
+ return '';
614
+ };
615
+ // 背景切换帽(对照 _startBackdropScripts:每次背景切换后触发对应脚本)
616
+ compiles['event_whenbackdropswitchesto'] = async (a) => {
617
+ if (!isStageMode()) { warnOnce('背景切换帽需要舞台模块,已跳过'); return ''; }
618
+ S.clickcount++;
619
+ const name = S.fnName('bdrop' + S.clickcount);
620
+ const body = await compile_chain(a.scope.block.next, a.scope.target);
621
+ const bname = String(a.scope.block.fields.BACKDROP[0]);
622
+ const loop = `let mut __bc = self.stage.backdrop_seq();\nloop {\nif self.stage.next_backdrop_switch(&mut __bc, ${sl(bname)}) {\n${body}\n}\n${hatPoll(10)}}`;
623
+ const fn = `async fn ${name}(mut self: std::sync::Arc<Self>){\n${loop}\n}\n`;
624
+ emit.func(fn);
625
+ emit.scripts.push({ name, kind: 'backdrop', ti: S.targetID });
626
+ return '';
627
+ };
628
+
629
+ // ================= 控制 =================
630
+ compiles['control_wait'] = (a) => {
631
+ const secs = a.DURATION.Num();
632
+ if (S.frame && S.frame.gate) {
633
+ // 至少跨 1 个逻辑 tick,且墙钟到点;tick 边界恢复(Scratch 语义)
634
+ if (multi()) {
635
+ return `{\nlet __t0 = ${instantNow()};\nlet __secs = (${secs}) as f64;\nself.frame_wait().await;\nwhile __t0.elapsed().as_secs_f64() < __secs { self.frame_wait().await; }\n}\n`;
636
+ }
637
+ return `{\nlet __t0 = ${instantNow()};\nlet __secs = (${secs}) as f64;\nrcompiler_frame_wait();\nwhile __t0.elapsed().as_secs_f64() < __secs { rcompiler_frame_wait(); }\n}\n`;
638
+ }
639
+ if (multi()) {
640
+ // 无帧门控:wait 0 在 Scratch 中仍跨 1 帧(30fps)——此处以 1ms 最小延时
641
+ // 保持“让其他线程推进一批”的语义,避免 run-frame 类循环与写入者竞态
642
+ if (web) return `rcompiler_sleep(((${secs}) as f64).max(0.001)).await;\n`;
643
+ DEP('tokio = { version = "1", features = ["full"] }');
644
+ return `tokio::time::sleep(std::time::Duration::from_secs_f64(((${secs}) as f64).max(0.001))).await;\n`;
645
+ }
646
+ if (web) return `rcompiler_sleep_sync(((${secs}) as f64).max(0.001));\n`;
647
+ USE('use std::time::Duration;'); USE('use std::thread;');
648
+ return `std::thread::sleep(Duration::from_secs_f64(((${secs}) as f64).max(0.001)));\n`;
649
+ };
650
+ // repeat:次数先求值到局部——次数中的列表/变量锁(MutexGuard 临时值)
651
+ // 会在 for 的 range 表达式里存活到循环结束,跨 await 破坏 future Send
652
+ compiles['control_repeat'] = (a) => {
653
+ S.repeatcount = (S.repeatcount || 0) + 1;
654
+ const n = S.repeatcount;
655
+ return `{\nlet __rn${n} = (${a.TIMES.Usize()});\nfor __rep${n} in 0..__rn${n} {\n${C.Safe(a.SUBSTACK)}${frameWaitStmt()}${loopYield()}}\n}\n`;
656
+ };
657
+ compiles['control_forever'] = (a) => `loop {\n${C.Safe(a.SUBSTACK)}${frameWaitStmt()}${loopYield()}}\n`;
658
+ // if/if_else:条件先求值到局部——条件中的列表锁(MutexGuard 临时值)会存活
659
+ // 到整个 if 语句结束(Rust 临时值规则),体内再次锁同一列表会同线程死锁
660
+ compiles['control_if'] = (a) => {
661
+ S.condcount = (S.condcount || 0) + 1;
662
+ const n = S.condcount;
663
+ return `{\nlet __cu${n} = (${C.SafeBool(a.CONDITION)});\nif __cu${n} {\n${C.Safe(a.SUBSTACK)}\n}\n}\n`;
664
+ };
665
+ compiles['control_if_else'] = (a) => {
666
+ S.condcount = (S.condcount || 0) + 1;
667
+ const n = S.condcount;
668
+ return `{\nlet __cu${n} = (${C.SafeBool(a.CONDITION)});\nif __cu${n} {\n${C.Safe(a.SUBSTACK)}\n}\nelse {\n${C.Safe(a.SUBSTACK2)}\n}\n}\n`;
669
+ };
670
+ compiles['control_wait_until'] = (a) => {
671
+ if (S.frame && S.frame.gate) {
672
+ if (multi()) return `loop {\nlet __cu = (${C.SafeBool(a.CONDITION)});\nif __cu { break; }\nself.frame_wait().await; }\n`;
673
+ return `loop {\nlet __cu = (${C.SafeBool(a.CONDITION)});\nif __cu { break; }\nrcompiler_frame_wait(); }\n`;
674
+ }
675
+ if (multi()) return web
676
+ ? `loop {\nlet __cu = (${C.SafeBool(a.CONDITION)});\nif __cu { break; }\nrcompiler_sleep(0.01).await; }\n`
677
+ : `loop {\nlet __cu = (${C.SafeBool(a.CONDITION)});\nif __cu { break; }\ntokio::time::sleep(std::time::Duration::from_millis(10)).await; }\n`;
678
+ return web
679
+ ? `loop {\nlet __cu = (${C.SafeBool(a.CONDITION)});\nif __cu { break; }\nrcompiler_sleep_sync(0.001); }\n`
680
+ : `loop {\nlet __cu = (${C.SafeBool(a.CONDITION)});\nif __cu { break; }\nstd::thread::sleep(std::time::Duration::from_millis(1)); }\n`;
681
+ };
682
+ // repeat_until/while/wait_until:条件每轮先求值到局部再判断——
683
+ // 条件中的列表锁(MutexGuard 临时值)在循环体 await 前释放(future Send 要求)
684
+ compiles['control_repeat_until'] = (a) => `loop {\nlet __cu = (${C.SafeBool(a.CONDITION)});\nif __cu { break; }\n${C.Safe(a.SUBSTACK)}${frameWaitStmt()}${loopYield()}}\n`;
685
+ compiles['control_while'] = (a) => `loop {\nlet __cu = (${C.SafeBool(a.CONDITION)});\nif !__cu { break; }\n${C.Safe(a.SUBSTACK)}${frameWaitStmt()}${loopYield()}}\n`;
686
+ compiles['control_all_at_once'] = (a) => C.Safe(a.SUBSTACK);
687
+ compiles['control_for_each'] = (a) => {
688
+ ctx.markWrite();
689
+ S.foreachcount++;
690
+ const n = S.foreachcount;
691
+ const [name, id] = a.scope.block.fields.VARIABLE;
692
+ const v = getvar(String(name), id);
693
+ const dec = v.v ? v.v.declared : null;
694
+ // 声明类型的变量没有双轨字段:统一经 setNum/setStr 适配(含锁),循环计数写主轨。
695
+ // 双轨(未声明)变量按原语义分别保存/恢复两条轨(字符串轨可能与 to_string(num) 不同)。
696
+ const dual = !dec;
697
+ const isStr = dec === 'String';
698
+ return [
699
+ `let __fe0_${n} = (${isStr ? v.str() : v.num()});`,
700
+ dual ? `let __fe1_${n} = (${v.str()});` : null,
701
+ `let __fet_${n} = ${a.VALUE.Usize()};`,
702
+ v.setNum('0.0'),
703
+ dual ? v.setStr('String::from("0")') : null,
704
+ `let mut __fei_${n}: usize = 1;`,
705
+ `while __fei_${n} <= __fet_${n} {`,
706
+ v.setNum(`__fei_${n} as f64`),
707
+ C.Safe(a.SUBSTACK),
708
+ `__fei_${n} += 1;`,
709
+ frameWaitStmt(),
710
+ loopYield(),
711
+ `}`,
712
+ dual ? v.setNum(`__fe0_${n}`) : (isStr ? v.setStr(`__fe0_${n}`) : v.setNum(`__fe0_${n}`)),
713
+ dual ? v.setStr(`__fe1_${n}`) : null
714
+ ].filter(Boolean).join('\n') + '\n';
715
+ };
716
+ compiles['control_stop'] = (a) => {
717
+ const opt = a.scope.block.fields.STOP_OPTION[0];
718
+ // 过程体内 stop [this script] = 从过程返回(对照 stopThisScript 的栈回退)
719
+ const procRet = S.customproc && S.customproc.hasReturn ? 'String::new()' : null;
720
+ if (web) {
721
+ // WASM 没有进程退出:stop all 在当前协作调度器内终止其他任务/返回。
722
+ if (opt === 'all') {
723
+ if (multi()) return `rcompiler_stop_tasks(None);\n${procRet ? `return ${procRet};\n` : 'return;\n'}`;
724
+ return procRet ? `return ${procRet};\n` : 'return;\n';
725
+ }
726
+ if (opt === 'other scripts in sprite' && multi()) {
727
+ return `rcompiler_stop_tasks(Some(${S.targetID}));\n`;
728
+ }
729
+ return procRet ? `return ${procRet};\n` : 'return;\n';
730
+ }
731
+ switch (opt) {
732
+ case 'all':
733
+ // 舞台项目:终止全部脚本/克隆/气泡,窗口继续渲染(对照 runtime.stopAll)
734
+ if (isStageMode() && multi()) {
735
+ return `self.rcompiler_stop_all().await;\n${procRet ? `return ${procRet};\n` : 'return;\n'}`;
736
+ }
737
+ USE('use std::process;'); return 'std::process::exit(0);\n';
738
+ case 'this script': return procRet ? `return ${procRet};\n` : 'return;\n';
739
+ case 'other scripts in sprite':
740
+ // 舞台项目:终止该角色的其他脚本线程(对照 stopForTarget)
741
+ if (isStageMode() && multi()) {
742
+ return `self.rcompiler_stop_other_scripts(${S.targetID});\n`;
743
+ }
744
+ USE('use std::process;'); return 'std::process::exit(0);\n';
745
+ default: USE('use std::process;'); return 'std::process::exit(0);\n';
746
+ }
747
+ };
748
+ compiles['control_create_clone_of'] = (a) => {
749
+ if (!multi()) { warnOnce('克隆积木出现在单进程项目中(不应发生)'); return ''; }
750
+ const opt = typeof a.CLONE_OPTION === 'string' ? a.CLONE_OPTION : (a.CLONE_OPTION && a.CLONE_OPTIONS);
751
+ let ti = S.targetID;
752
+ if (opt !== '_myself_' && opt != null) {
753
+ const found = S.targets.findIndex(t => t.name === opt);
754
+ if (found >= 0) ti = found;
755
+ }
756
+ const fns = S.clonesByTarget.get(ti) || [];
757
+ emit.needsCloneDefault = true;
758
+ let out = '';
759
+ for (const f of fns) {
760
+ // 克隆上限 300(对照 clonesAvailable;需舞台模块的克隆注册表);
761
+ // 克隆任务登记供 stop all 终止
762
+ out += isStageMode() ? `if self.stage.can_clone() {\n` : '{\n';
763
+ out += `let mut __c = self.clone_default();\n`;
764
+ if (isStageMode()) out += `__c.rcompiler_clone_init(self.sprite_index);\n`;
765
+ out += `let __c = std::sync::Arc::new(__c); let __s = __c.clone(); let __h = tokio::spawn(${spawnScript(`async move { __s.${f}().await; }`)}); rcompiler_track_task(${ti}, &__h); }\n`;
766
+ }
767
+ return out;
768
+ };
769
+ // 删除克隆(对照 control_delete_this_clone → disposeTarget)
770
+ // rcompiler_self_idx:克隆实例删自身;原型实例删原型(广播接收在两类实例上都运行)
771
+ compiles['control_delete_this_clone'] = (a) =>
772
+ (isStageMode() && multi())
773
+ ? `self.s_delete_clone(self.rcompiler_self_idx(${S.targetID}));\nreturn;\n`
774
+ : 'return;\n';
775
+
776
+ // ================= 侦测 =================
777
+ inputs['sensing_timer'] = (a) => {
778
+ if (!web) USE('use std::time::Instant;');
779
+ if (multi()) {
780
+ emit.field('timer_start', `std::sync::Mutex<${instantTy()}>`, `std::sync::Mutex::new(${instantNow()})`);
781
+ emit.func('fn sensing_timer(&self) -> f64 {\nself.timer_start.lock().unwrap().elapsed().as_secs_f64()\n}');
782
+ } else {
783
+ emit.field('timer_start', instantTy(), instantNow());
784
+ emit.func('fn sensing_timer(&self) -> f64 {\nself.timer_start.elapsed().as_secs_f64()\n}');
785
+ }
786
+ return new T.Num('self.sensing_timer()');
787
+ };
788
+ compiles['sensing_resettimer'] = (a) => {
789
+ if (!web) USE('use std::time::Instant;');
790
+ if (multi()) {
791
+ emit.field('timer_start', `std::sync::Mutex<${instantTy()}>`, `std::sync::Mutex::new(${instantNow()})`);
792
+ return `*self.timer_start.lock().unwrap() = ${instantNow()};\n`;
793
+ }
794
+ emit.field('timer_start', instantTy(), instantNow());
795
+ return `self.timer_start = ${instantNow()};\n`;
796
+ };
797
+ inputs['sensing_dayssince2000'] = (a) => {
798
+ if (web) {
799
+ RT([
800
+ 'fn sensing_dayssince2000() -> f64 {',
801
+ 'let now_ms = js_sys::Date::now();',
802
+ '(now_ms - 946684800000.0) / 86400000.0',
803
+ '}'].join('\n'));
804
+ } else {
805
+ USE('use std::time::{SystemTime, UNIX_EPOCH};');
806
+ RT([
807
+ 'fn sensing_dayssince2000() -> f64 {',
808
+ '// 毫秒精度(对照 scratch-vm:JS Date.now() 差值 / 86400000)——',
809
+ '// 天数取整会丢失亚秒精度,破坏模拟器微秒计时',
810
+ 'let now_ms = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_millis()).unwrap_or(0) as f64;',
811
+ '(now_ms - 946684800000.0) / 86400000.0',
812
+ '}'].join('\n'));
813
+ }
814
+ return new T.Num('sensing_dayssince2000()');
815
+ };
816
+ inputs['sensing_current'] = (a) => {
817
+ const menu = a.scope.block.fields.CURRENTMENU[0];
818
+ if (web) {
819
+ RT([
820
+ 'fn rcompiler_current(menu: &str) -> f64 {',
821
+ 'let d = js_sys::Date::new_0();',
822
+ 'match menu {',
823
+ '"year" => d.get_full_year() as f64,',
824
+ '"month" => (d.get_month() + 1) as f64,',
825
+ '"date" => d.get_date() as f64,',
826
+ '"dayofweek" => d.get_day() as f64,',
827
+ '"hour" => d.get_hours() as f64,',
828
+ '"minute" => d.get_minutes() as f64,',
829
+ '"second" => d.get_seconds() as f64,',
830
+ '_ => 0.0,',
831
+ '}',
832
+ '}'].join('\n'));
833
+ return new T.Num(`rcompiler_current(${sl(menu)})`);
834
+ }
835
+ DEP('chrono = "0.4"'); USE('use chrono::Local;');
836
+ const f = { 'year': 'year', 'month': 'month', 'date': 'day', 'dayofweek': 'num_days_from_sunday', 'hour': 'hour', 'minute': 'minute', 'second': 'second' }[menu];
837
+ if (menu === 'dayofweek') return new T.Num(`(Local::now().${f}() as f64)`);
838
+ return new T.Num(`(Local::now().${f}() as f64)`);
839
+ };
840
+ inputs['sensing_answer'] = (a) => {
841
+ // 舞台模式:回答是全局运行时状态(对照 scratch3_sensing._answer),所有角色共享
842
+ if (isStageMode()) return new T.Stri('self.stage.ask_answer()');
843
+ if (multi()) {
844
+ emit.field('sensing_answer', 'std::sync::Mutex<String>', 'std::sync::Mutex::new(String::new())');
845
+ return new T.Stri('self.sensing_answer.lock().unwrap().clone()');
846
+ }
847
+ emit.field('sensing_answer', 'String', 'String::new()');
848
+ return new T.Stri('self.sensing_answer.clone()');
849
+ };
850
+ compiles['sensing_askandwait'] = (a) => {
851
+ if (isStageMode()) {
852
+ // 舞台询问:进入共享询问队列,等待窗口/DOM 输入框回答(无窗口时运行时回退 stdin)
853
+ // 首参 idx 由编译器的 stage 桥接注入(injectStageIdx)
854
+ const q = a.QUESTION.Stri();
855
+ const isStageTarget = (a.scope.target && a.scope.target.isStage) ? 'true' : 'false';
856
+ return `self.s_ask_and_wait(${q}, ${isStageTarget}).await;\n`;
857
+ }
858
+ if (web) {
859
+ const q = a.QUESTION.Stu();
860
+ let out = `let __ans = host_ask(&(${q}));\n`;
861
+ if (multi()) {
862
+ emit.field('sensing_answer', 'std::sync::Mutex<String>', 'std::sync::Mutex::new(String::new())');
863
+ out += `*self.sensing_answer.lock().unwrap() = __ans;\n`;
864
+ } else {
865
+ emit.field('sensing_answer', 'String', 'String::new()');
866
+ ctx.markWrite();
867
+ out += `self.sensing_answer = __ans;\n`;
868
+ }
869
+ return out;
870
+ }
871
+ USE('use std::io::{self, Write};');
872
+ let out = `print!("{}",${a.QUESTION.Stu()});\nio::stdout().flush().unwrap();\nlet mut __ans = String::new();\nio::stdin().read_line(&mut __ans).unwrap();\nlet __ans = __ans.trim().to_owned();\n`;
873
+ if (multi()) {
874
+ emit.field('sensing_answer', 'std::sync::Mutex<String>', 'std::sync::Mutex::new(String::new())');
875
+ out += `*self.sensing_answer.lock().unwrap() = __ans;\n`;
876
+ warnOnce('ask 块在多任务模式下会阻塞当前工作线程(stdin 同步读取)');
877
+ } else {
878
+ emit.field('sensing_answer', 'String', 'String::new()');
879
+ ctx.markWrite();
880
+ out += `self.sensing_answer = __ans;\n`;
881
+ }
882
+ return out;
883
+ };
884
+ inputs['sensing_loudness'] = () => new T.Num('-1.0'); // 无麦克风
885
+ inputs['sensing_username'] = () => new T.Str('""');
886
+ compiles['sensing_setdragmode'] = () => '';
887
+ inputs['sensing_keypressed'] = (a) => {
888
+ const key = a.scope.block.fields.KEY_OPTION[0];
889
+ if (!isStageMode()) { warnOnce('sensing_keypressed 控制台模式返回 false(键盘检测需 crossterm 轮询或舞台模块)'); return new T.Bool('false'); }
890
+ return new T.Bool(`self.stage.key_down(${sl(key)})`);
891
+ };
892
+ inputs['sensing_mousedown'] = () => {
893
+ if (!isStageMode()) return new T.Bool('false');
894
+ return new T.Bool('self.stage.mouse_down()');
895
+ };
896
+ inputs['sensing_mousex'] = () => isStageMode() ? new T.Num('self.stage.mouse_x()') : new T.Num('0.0');
897
+ inputs['sensing_mousey'] = () => isStageMode() ? new T.Num('self.stage.mouse_y()') : new T.Num('0.0');
898
+ inputs['sensing_distanceto'] = (a) => {
899
+ if (!isStageMode()) return new T.Num('0.0');
900
+ const menu = menuInput(a, 'DISTANCETOMENU', 'DISTANCETOMENU');
901
+ if (menu == null) return new T.Num('0.0');
902
+ return new T.Num(`self.s_distance_to(${menu})`);
903
+ };
904
+ // 菜单输入统一读取:字段 / 被遮挡的菜单影子 / 动态表达式
905
+ const menuInput = (a, key, fieldKey) => {
906
+ if (a.scope.block.fields[fieldKey]) return sl(a.scope.block.fields[fieldKey][0]);
907
+ if (a[key] && a[key].type !== 'Block' && typeof a[key].Stu === 'function') {
908
+ const expr = stuOf(a[key]);
909
+ return isStrLit(expr) ? expr : `&(${expr})`;
910
+ }
911
+ const inp = a.scope.block.inputs[key];
912
+ if (Array.isArray(inp) && typeof inp[2] === 'string') {
913
+ const sh = a.scope.target.blocks[inp[2]];
914
+ if (sh && sh.fields && sh.fields[fieldKey]) return sl(sh.fields[fieldKey][0]);
915
+ }
916
+ return null;
917
+ };
918
+ inputs['sensing_touchingobject'] = (a) => {
919
+ if (!isStageMode()) return new T.Bool('false');
920
+ const menu = menuInput(a, 'TOUCHINGOBJECTMENU', 'TOUCHINGOBJECTMENU');
921
+ if (menu == null) return new T.Bool('false');
922
+ return new T.Bool(`self.s_touching(${menu})`);
923
+ };
924
+ inputs['sensing_touchingcolor'] = () => { warnOnce('sensing_touchingcolor 暂以 false 近似(像素级碰撞待实现)'); return new T.Bool('false'); };
925
+ inputs['sensing_coloristouchingcolor'] = () => { warnOnce('sensing_coloristouchingcolor 暂以 false 近似'); return new T.Bool('false'); };
926
+
927
+ // ================= 外观(控制台回退)=================
928
+ compiles['looks_say'] = (a) => {
929
+ if (isStageMode()) return `self.s_say(${a.MESSAGE.Stri()});\n`;
930
+ if (web) return `host_log(&(${a.MESSAGE.Stu()}));\n`;
931
+ return `println!("{}",${a.MESSAGE.Stu()});\n`;
932
+ };
933
+ compiles['looks_think'] = (a) => {
934
+ if (isStageMode()) return `self.s_think(${a.MESSAGE.Stri()});\n`;
935
+ if (web) return `host_log(&(${a.MESSAGE.Stu()}));\n`;
936
+ return `println!("{}",${a.MESSAGE.Stu()});\n`;
937
+ };
938
+ compiles['looks_sayforsecs'] = (a) => {
939
+ if (isStageMode()) {
940
+ // 参数先绑定到局部(列表锁在 await 前释放,保证 future Send)
941
+ return `{\nlet __msg = (${a.MESSAGE.Stri()});\nself.s_say_for(${a.SECS.Num()}, __msg)${awaitKw()};\n}\n`;
942
+ }
943
+ if (web) return `host_log(&(${a.MESSAGE.Stu()}));\n` + sleepCall(a.SECS.Num());
944
+ return `println!("{}",${a.MESSAGE.Stu()});\n` + sleepCall(a.SECS.Num());
945
+ };
946
+ compiles['looks_thinkforsecs'] = (a) => {
947
+ if (isStageMode()) {
948
+ return `{\nlet __msg = (${a.MESSAGE.Stri()});\nself.s_think_for(${a.SECS.Num()}, __msg)${awaitKw()};\n}\n`;
949
+ }
950
+ if (web) return `host_log(&(${a.MESSAGE.Stu()}));\n` + sleepCall(a.SECS.Num());
951
+ return `println!("{}",${a.MESSAGE.Stu()});\n` + sleepCall(a.SECS.Num());
952
+ };
953
+ const stageOnlyLooks = (fn) => (a) => {
954
+ if (!isStageMode()) { warnOnce('外观积木需要舞台模块(项目未使用舞台/运动/画笔积木),已跳过: ' + fn); return ''; }
955
+ return null; // 由舞台分支填充
956
+ };
957
+ compiles['looks_switchcostumeto'] = (a) => {
958
+ if (!isStageMode()) { warnOnce('looks_switchcostumeto 需要舞台模块,已跳过'); return ''; }
959
+ // 造型输入三种形态:菜单字段 / 菜单影子(可被表达式遮挡)/ 动态表达式。
960
+ // 数字或数字字符串按序号(round+wrap,对照 _setCostume),其余按名称——运行时 s_switch_costume 解析
961
+ let expr = null;
962
+ if (a.scope.block.fields.COSTUME) {
963
+ expr = sl(a.scope.block.fields.COSTUME[0]);
964
+ } else if (a.COSTUME && a.COSTUME.type !== 'Block' && typeof a.COSTUME.Stu === 'function') {
965
+ expr = stuOf(a.COSTUME);
966
+ } else {
967
+ // 遮挡块是菜单本身(无法求值)→ 取影子里保存的造型名
968
+ const inp = a.scope.block.inputs.COSTUME;
969
+ let cname = '';
970
+ if (Array.isArray(inp) && typeof inp[2] === 'string') {
971
+ const sh = a.scope.target.blocks[inp[2]];
972
+ if (sh && sh.fields && sh.fields.COSTUME) cname = String(sh.fields.COSTUME[0]);
973
+ }
974
+ expr = sl(cname);
975
+ }
976
+ // 动态表达式可能是 String 值(&str 形参需借用)
977
+ if (!isStrLit(expr)) expr = `&(${expr})`;
978
+ return `self.s_switch_costume(${expr});\n`;
979
+ };
980
+ compiles['looks_nextcostume'] = () => isStageMode() ? 'self.s_next_costume();\n' : (warnOnce('looks_nextcostume 需要舞台模块,已跳过'), '');
981
+ compiles['looks_switchbackdropto'] = (a) => {
982
+ if (!isStageMode()) { warnOnce('looks_switchbackdropto 需要舞台模块,已跳过'); return ''; }
983
+ let expr = null;
984
+ if (a.scope.block.fields.BACKDROP) expr = sl(a.scope.block.fields.BACKDROP[0]);
985
+ else if (a.BACKDROP && a.BACKDROP.type !== 'Block' && typeof a.BACKDROP.Stu === 'function') expr = stuOf(a.BACKDROP);
986
+ else {
987
+ const inp = a.scope.block.inputs.BACKDROP;
988
+ let bname = '';
989
+ if (Array.isArray(inp) && typeof inp[2] === 'string') {
990
+ const sh = a.scope.target.blocks[inp[2]];
991
+ if (sh && sh.fields && sh.fields.BACKDROP) bname = String(sh.fields.BACKDROP[0]);
992
+ }
993
+ expr = sl(bname);
994
+ }
995
+ if (!isStrLit(expr)) expr = `&(${expr})`;
996
+ return `self.s_switch_backdrop(${expr});\n`;
997
+ };
998
+ compiles['looks_nextbackdrop'] = () => isStageMode() ? 'self.s_next_backdrop();\n' : (warnOnce('looks_nextbackdrop 需要舞台模块,已跳过'), '');
999
+ compiles['looks_changesizeby'] = (a) => isStageMode() ? `self.s_change_size(${a.CHANGE.Num()});\n` : (warnOnce('looks_changesizeby 需要舞台模块,已跳过'), '');
1000
+ compiles['looks_setsizeto'] = (a) => isStageMode() ? `self.s_set_size(${a.SIZE.Num()});\n` : (warnOnce('looks_setsizeto 需要舞台模块,已跳过'), '');
1001
+ inputs['looks_size'] = () => isStageMode() ? new T.Num('self.s_get_size()') : new T.Num('100.0');
1002
+ compiles['looks_changeeffectby'] = (a) => {
1003
+ if (!isStageMode()) { warnOnce('looks_changeeffectby 需要舞台模块,已跳过'); return ''; }
1004
+ const eff = a.scope.block.fields.EFFECT[0];
1005
+ if (eff === 'ghost') return `self.s_change_alpha(-(${a.CHANGE.Num()}));\n`;
1006
+ return `// effect ${eff} 未支持\n`;
1007
+ };
1008
+ compiles['looks_seteffectto'] = (a) => {
1009
+ if (!isStageMode()) { warnOnce('looks_seteffectto 需要舞台模块,已跳过'); return ''; }
1010
+ const eff = a.scope.block.fields.EFFECT[0];
1011
+ if (eff === 'ghost') return `self.s_set_alpha(${a.VALUE.Num()});\n`;
1012
+ return `// effect ${eff} 未支持\n`;
1013
+ };
1014
+ compiles['looks_cleargraphiceffects'] = () => isStageMode() ? 'self.s_clear_effects();\n' : '';
1015
+ compiles['looks_show'] = () => isStageMode() ? 'self.s_show();\n' : (warnOnce('looks_show 需要舞台模块,已跳过'), '');
1016
+ compiles['looks_hide'] = () => isStageMode() ? 'self.s_hide();\n' : (warnOnce('looks_hide 需要舞台模块,已跳过'), '');
1017
+ compiles['looks_gotofrontback'] = (a) => {
1018
+ if (!isStageMode()) return '';
1019
+ const fb = a.scope.block.fields.FRONT_BACK[0];
1020
+ return fb === 'front' ? 'self.s_goto_front();\n' : 'self.s_goto_back();\n';
1021
+ };
1022
+ compiles['looks_gobacknlayers'] = (a) => isStageMode() ? `self.s_go_back_layers(${a.NUM.Usize()});\n` : '';
1023
+ inputs['looks_costumenumbername'] = (a) => {
1024
+ if (!isStageMode()) return new T.Num('0.0');
1025
+ const nn = a.scope.block.fields.NUMBER_NAME[0];
1026
+ return nn === 'name' ? new T.Str('self.s_costume_name()') : new T.Num('self.s_costume_number()');
1027
+ };
1028
+ inputs['looks_backdropnumbername'] = (a) => {
1029
+ if (!isStageMode()) return new T.Num('0.0');
1030
+ const nn = a.scope.block.fields.NUMBER_NAME[0];
1031
+ return nn === 'name' ? new T.Str('self.s_backdrop_name()') : new T.Num('self.s_backdrop_number()');
1032
+ };
1033
+
1034
+ // ================= 运动(需舞台)=================
1035
+ const needStage = (op) => {
1036
+ warnOnce(`运动积木 ${op} 需要舞台模块(项目未使用舞台/外观/画笔积木),已跳过`);
1037
+ return '';
1038
+ };
1039
+ compiles['motion_movesteps'] = (a) => isStageMode() ? `self.s_move_steps(${a.STEPS.Num()});\n` : needStage('movesteps');
1040
+ compiles['motion_turnright'] = (a) => isStageMode() ? `self.s_turn((${a.DEGREES.Num()}));\n` : needStage('turnright');
1041
+ compiles['motion_turnleft'] = (a) => isStageMode() ? `self.s_turn(-(${a.DEGREES.Num()}));\n` : needStage('turnleft');
1042
+ compiles['motion_gotoxy'] = (a) => isStageMode() ? `self.s_set_xy(${a.X.Num()},${a.Y.Num()});\n` : needStage('gotoxy');
1043
+ compiles['motion_goto'] = (a) => {
1044
+ if (!isStageMode()) return needStage('goto');
1045
+ const menu = a.scope.block.fields.TO ? a.scope.block.fields.TO[0] : (a.TO && a.TO.input != null ? String(a.TO.input) : '_random_');
1046
+ return `self.s_goto(${sl(menu)});\n`;
1047
+ };
1048
+ compiles['motion_glidesecstoxy'] = (a) => {
1049
+ if (!isStageMode()) return needStage('glidesecstoxy');
1050
+ // 坐标可能含列表锁 → 先绑定到局部,await 前释放
1051
+ return `{\nlet __gx = (${a.X.Num()});\nlet __gy = (${a.Y.Num()});\nself.s_glide(${a.SECS.Num()}, __gx, __gy)${awaitKw()};\n}\n`;
1052
+ };
1053
+ compiles['motion_glideto'] = (a) => {
1054
+ if (!isStageMode()) return needStage('glideto');
1055
+ const menu = a.scope.block.fields.TO ? a.scope.block.fields.TO[0] : (a.TO && a.TO.input != null ? String(a.TO.input) : '_random_');
1056
+ return `{\nlet __gtx = (${a.SECS.Num()});\nself.s_glide_to(__gtx, ${sl(menu)})${awaitKw()};\n}\n`;
1057
+ };
1058
+ compiles['motion_pointindirection'] = (a) => isStageMode() ? `self.s_set_direction(${a.DIRECTION.Num()});\n` : needStage('pointindirection');
1059
+ compiles['motion_pointtowards'] = (a) => {
1060
+ if (!isStageMode()) return needStage('pointtowards');
1061
+ const menu = a.scope.block.fields.TOWARDS ? a.scope.block.fields.TOWARDS[0] : (a.TOWARDS && a.TOWARDS.input != null ? String(a.TOWARDS.input) : '_mouse_');
1062
+ return `self.s_point_towards(${sl(menu)});\n`;
1063
+ };
1064
+ compiles['motion_changexby'] = (a) => isStageMode() ? `self.s_change_x(${a.DX.Num()});\n` : needStage('changexby');
1065
+ compiles['motion_setx'] = (a) => isStageMode() ? `self.s_set_x(${a.X.Num()});\n` : needStage('setx');
1066
+ compiles['motion_changeyby'] = (a) => isStageMode() ? `self.s_change_y(${a.DY.Num()});\n` : needStage('changeyby');
1067
+ compiles['motion_sety'] = (a) => isStageMode() ? `self.s_set_y(${a.Y.Num()});\n` : needStage('sety');
1068
+ compiles['motion_ifonedgebounce'] = () => isStageMode() ? 'self.s_if_on_edge_bounce();\n' : needStage('ifonedgebounce');
1069
+ compiles['motion_setrotationstyle'] = (a) => {
1070
+ if (!isStageMode()) return needStage('setrotationstyle');
1071
+ const style = a.scope.block.fields.STYLE[0];
1072
+ return `self.s_set_rotation_style(${sl(style)});\n`;
1073
+ };
1074
+ inputs['motion_xposition'] = () => isStageMode() ? new T.Num('self.s_get_x()') : new T.Num('0.0');
1075
+ inputs['motion_yposition'] = () => isStageMode() ? new T.Num('self.s_get_y()') : new T.Num('0.0');
1076
+ inputs['motion_direction'] = () => isStageMode() ? new T.Num('self.s_get_direction()') : new T.Num('90.0');
1077
+
1078
+ // ================= 声音(F 阶段填充预lude;此处生成桥接)=================
1079
+ compiles['sound_play'] = (a) => {
1080
+ if (!S.profile.hasSound) return '';
1081
+ const name = a.scope.block.fields.SOUND_MENU ? a.scope.block.fields.SOUND_MENU[0] : (a.SOUND_MENU && a.SOUND_MENU.input != null ? String(a.SOUND_MENU.input) : '');
1082
+ return `let _ = self.snd_play(${sl(name)});\n`;
1083
+ };
1084
+ compiles['sound_playuntildone'] = (a) => {
1085
+ if (!S.profile.hasSound) return '';
1086
+ const name = sl(a.scope.block.fields.SOUND_MENU ? a.scope.block.fields.SOUND_MENU[0] : (a.SOUND_MENU && a.SOUND_MENU.input != null ? String(a.SOUND_MENU.input) : ''));
1087
+ if (multi()) {
1088
+ return `{ if let Some(__s) = self.snd_play(${name}) { while !__s.empty() { tokio::time::sleep(std::time::Duration::from_millis(50)).await; } } }\n`;
1089
+ }
1090
+ return `{ if let Some(__s) = self.snd_play(${name}) { while !__s.empty() { std::thread::sleep(std::time::Duration::from_millis(50)); } } }\n`;
1091
+ };
1092
+ compiles['sound_stopallsounds'] = () => S.profile.hasSound ? 'self.snd_stop_all();\n' : '';
1093
+ compiles['sound_setvolumeto'] = (a) => S.profile.hasSound ? `self.snd_set_volume(${a.VOLUME.Num()});\n` : '';
1094
+ compiles['sound_changevolumeby'] = (a) => S.profile.hasSound ? `self.snd_change_volume(${a.VOLUME.Num()});\n` : '';
1095
+ inputs['sound_volume'] = () => S.profile.hasSound ? new T.Num('self.snd_volume()') : new T.Num('100.0');
1096
+ compiles['sound_changeeffectby'] = () => '';
1097
+ compiles['sound_seteffectto'] = () => '';
1098
+ compiles['sound_cleareffects'] = () => '';
1099
+
1100
+ // ================= 画笔(需舞台)=================
1101
+ compiles['pen_clear'] = () => isStageMode() ? 'self.stage.pen_clear();\n' : (warnOnce('pen_clear 需要舞台模块,已跳过'), '');
1102
+ compiles['pen_penDown'] = () => isStageMode() ? 'self.s_pen_down();\n' : (warnOnce('画笔需舞台模块,已跳过'), '');
1103
+ compiles['pen_penUp'] = () => isStageMode() ? 'self.s_pen_up();\n' : (warnOnce('画笔需舞台模块,已跳过'), '');
1104
+ compiles['pen_setPenColorToColor'] = (a) => {
1105
+ if (!isStageMode()) return '';
1106
+ // 颜色输入:字面量([9,"#xx"])或动态表达式(变量/列表项,如 "#FFFFFF")
1107
+ let expr = null;
1108
+ if (a.COLOR && a.COLOR.type !== 'Block' && typeof a.COLOR.Stu === 'function') {
1109
+ expr = stuOf(a.COLOR);
1110
+ } else {
1111
+ let col = '';
1112
+ const inp = a.scope.block.inputs.COLOR;
1113
+ if (Array.isArray(inp)) {
1114
+ const ref = inp[1];
1115
+ if (Array.isArray(ref)) col = String(ref[1] == null ? '' : ref[1]);
1116
+ else if (typeof ref === 'string') {
1117
+ const sh = inp[2] != null && a.scope.target.blocks[inp[2]];
1118
+ if (sh && sh.fields && sh.fields.COLOR) col = String(sh.fields.COLOR[0]);
1119
+ }
1120
+ }
1121
+ expr = sl(col);
1122
+ }
1123
+ if (!isStrLit(expr)) expr = `&(${expr})`;
1124
+ return `self.s_pen_set_color(${expr});\n`;
1125
+ };
1126
+ compiles['pen_changePenColorBy'] = () => '';
1127
+ // 画笔参数(对照 scratch-pen setPenColorParamTo):transparency → alpha;
1128
+ // color/saturation/brightness 涉及 HSV 变换,暂不支持(警告一次)
1129
+ compiles['pen_setPenColorParamTo'] = (a) => {
1130
+ if (!isStageMode()) return '';
1131
+ const inp = a.scope.block.inputs.COLOR_PARAM;
1132
+ let param = null;
1133
+ if (a.scope.block.fields.COLOR_PARAM) param = String(a.scope.block.fields.COLOR_PARAM[0]);
1134
+ else if (Array.isArray(inp)) {
1135
+ const sid = inp[2] != null ? inp[2] : inp[1];
1136
+ if (typeof sid === 'string') {
1137
+ const sh = a.scope.target.blocks[sid];
1138
+ if (sh && sh.fields && sh.fields.colorParam) param = String(sh.fields.colorParam[0]);
1139
+ }
1140
+ }
1141
+ if (param == null) { warnOnce('画笔参数菜单无法解析,已跳过'); return ''; }
1142
+ if (param !== 'transparency') {
1143
+ warnOnce(`画笔参数 ${param} 暂不支持(仅 transparency)`);
1144
+ return '';
1145
+ }
1146
+ return `self.s_pen_set_param("transparency", ${a.VALUE.Num()});\n`;
1147
+ };
1148
+ compiles['pen_setPenSizeTo'] = (a) => isStageMode() ? `self.s_pen_set_size(${a.SIZE.Num()});\n` : '';
1149
+ compiles['pen_changePenSizeBy'] = (a) => isStageMode() ? `self.s_pen_change_size(${a.SIZE.Num()});\n` : '';
1150
+ compiles['pen_stamp'] = () => isStageMode() ? 'self.s_pen_stamp();\n' : '';
1151
+
1152
+ // ================= strings 扩展(原仓库扩展,并入标准表)=================
1153
+ inputs['strings_letters_of'] = (a) => {
1154
+ RT(['fn substring_range<T: AsRef<str>>(s: T, a: f64, b: f64) -> String {',
1155
+ 'let ch: Vec<char> = s.as_ref().chars().collect();',
1156
+ 'let a = (a.max(1.0)) as usize; let b = (b as usize).min(ch.len());',
1157
+ 'if a == 0 || a > b { return String::new(); }',
1158
+ 'ch[(a - 1)..b].iter().collect()',
1159
+ '}'].join('\n'));
1160
+ return new T.Stri(`substring_range(${stuOf(a.STRING)},${numOf(a.LETTER1)},${numOf(a.LETTER2)})`);
1161
+ };
1162
+ inputs['strings_split'] = (a) => {
1163
+ RT(['fn split_at_index<T: AsRef<str>>(input: T, sep: T, index: usize) -> String {',
1164
+ 'if index == 0 { return String::new(); }',
1165
+ 'let parts: Vec<&str> = input.as_ref().split(sep.as_ref()).collect();',
1166
+ 'parts.get(index - 1).map(|s| s.to_string()).unwrap_or_default()',
1167
+ '}'].join('\n'));
1168
+ return new T.Stri(`split_at_index(${stuOf(a.STRING)},${stuOf(a.SPLIT)},${numOf(a.ITEM)} as usize)`);
1169
+ };
1170
+ inputs['strings_count'] = (a) => new T.Num(`((${stuOf(a.STRING)}).matches(${stuOf(a.SUBSTRING)}).count() as f64)`);
1171
+ inputs['strings_indexof'] = (a) => {
1172
+ RT(['fn find_subbytes(h: &str, n: &str) -> usize {',
1173
+ 'match h.find(n) { Some(i) => i, None => 0 }',
1174
+ '}'].join('\n'));
1175
+ return new T.Usize(`find_subbytes(${stuOf(a.STRING)},${stuOf(a.SUBSTRING)})`);
1176
+ };
1177
+ inputs['strings_replace'] = (a) => new T.Stri(`(${stuOf(a.STRING)}).replace(${stuOf(a.SUBSTRING)}, ${stuOf(a.REPLACE)})`);
1178
+ inputs['strings_repeat'] = (a) => {
1179
+ RT(['fn repeat_str<T: AsRef<str>>(s: T, times: usize) -> String {',
1180
+ 'let mut r = String::new();',
1181
+ 'for _ in 0..times { r.push_str(s.as_ref()); }',
1182
+ 'r',
1183
+ '}'].join('\n'));
1184
+ return new T.Stri(`repeat_str(${stuOf(a.STRING)},${numOf(a.REPEAT)} as usize)`);
1185
+ };
1186
+ inputs['strings_unicodeof'] = (a) => {
1187
+ RT(['fn unicodeof<T: AsRef<str>>(input: T) -> String {',
1188
+ 'let v: Vec<String> = input.as_ref().chars().map(|c| (c as u32).to_string()).collect();',
1189
+ 'v.join(" ")',
1190
+ '}'].join('\n'));
1191
+ return new T.Stri(`unicodeof(${stuOf(a.STRING)})`);
1192
+ };
1193
+ inputs['strings_unicodefrom'] = (a) => {
1194
+ RT(['fn unicodefrom(input: f64) -> String {',
1195
+ 'std::char::from_u32(input as u32).map(|c| c.to_string()).unwrap_or_default()',
1196
+ '}'].join('\n'));
1197
+ return new T.Stri(`unicodefrom(${numOf(a.NUM)})`);
1198
+ };
1199
+ inputs['strings_identical'] = (a) => new T.Bool(`((${striOf(a.OPERAND1)}) == (${striOf(a.OPERAND2)}))`);
1200
+
1201
+ // ================= utilities 扩展(并入标准表)=================
1202
+ inputs['utilities_isLessOrEqual'] = (a) => new T.Bool(`((${numOf(a.A)})<=(${numOf(a.B)}))`);
1203
+ inputs['utilities_isMoreOrEqual'] = (a) => new T.Bool(`((${numOf(a.A)})>=(${numOf(a.B)}))`);
1204
+ inputs['utilities_stringToBoolean'] = (a) => {
1205
+ ctx.runtimeStr2Bool();
1206
+ return new T.Bool(`string_to_boolean(${stuOf(a.STRING)})`);
1207
+ };
1208
+ inputs['utilities_ternaryOperator'] = (a) => new T.Stri(`if ${C.SafeBool(a.A)} { ${striOf(a.B)} } else { ${striOf(a.C)} }`);
1209
+
1210
+ // ================= rcompiler 内部积木 =================
1211
+ compiles['rcompiler_setmain'] = (a) => { emit.main(C.Safe(a.SUBSTACK)); return ''; };
1212
+ compiles['rcompiler_setruntime'] = (a) => { emit.runtime(C.Safe(a.SUBSTACK)); return ''; };
1213
+ compiles['rcompiler_setinuse'] = (a) => { Tools.setinuse([C.Safe(a.SUBSTACK)]); return ''; };
1214
+ compiles['rcompiler_setdepend'] = (a) => { Tools.setdepend([a.scope.block.fields.HEADER[0]]); return ''; };
1215
+ compiles['rcompiler_setlibrary'] = (a) => { Tools.setlibrary([a.scope.block.fields.HEADER[0]]); return ''; };
1216
+ compiles['rcompiler_outcompiler'] = (a) => a.scope.block.fields.HEADER[0] + '\n';
1217
+ compiles['rcompiler_outcompilerr'] = (a) => a.scope.block.fields.HEADER[0] + '\n';
1218
+ compiles['rcompiler_outcompileb'] = (a) => a.scope.block.fields.HEADER[0] + '\n';
1219
+ compiles['rcompiler_ignore'] = (a) => { S.ignore = true; return ''; };
1220
+ compiles['rcompiler_varcreate'] = (a) => {
1221
+ ctx.markWrite();
1222
+ const v = kwParse(a.scope.block.fields.HEADER[0]);
1223
+ return `let mut _scopevar_${v} = String::new();\n`;
1224
+ };
1225
+ compiles['rcompiler_varset'] = (a) => {
1226
+ const v = kwParse(a.scope.block.fields.HEADER[0]);
1227
+ return `_scopevar_${v} = ${a.thing.Stri()};\n`;
1228
+ };
1229
+ inputs['rcompiler_varget'] = (a) => {
1230
+ const v = kwParse(a.scope.block.fields.HEADER[0]);
1231
+ ctx.runtimeParseF64(); ctx.runtimeParseUsize(); ctx.runtimeParseI32();
1232
+ const cls = class ScopeVar {
1233
+ constructor(n) { this.n = n; this.type = 'ScopeVar'; }
1234
+ Num() { return `get_f64_string(&_scopevar_${this.n})`; }
1235
+ Usize() { return `get_usize_string(&_scopevar_${this.n})`; }
1236
+ i32() { return `get_i32_string(&_scopevar_${this.n})`; }
1237
+ Str() { return `&_scopevar_${this.n}`; }
1238
+ Stri() { return `_scopevar_${this.n}.clone()`; }
1239
+ Stu() { return `&_scopevar_${this.n}`; }
1240
+ Bool() { ctx.runtimeStr2Bool(); return `string_to_boolean(&_scopevar_${this.n})`; }
1241
+ block() { return this.Stri(); }
1242
+ };
1243
+ return new cls(v);
1244
+ };
1245
+ inputs['rcompiler_typeas'] = (a) => {
1246
+ const ty = a.scope.block.fields.type[0];
1247
+ const map = { Stu: 'Str', Str: 'Str', Bool: 'Bool', Num: 'Num', Usize: 'Usize', i32: 'i32', Stri: 'Stri' };
1248
+ const cls = map[ty];
1249
+ if (cls && a.thing && typeof a.thing[ty] === 'function') return new T[cls](a.thing[ty]());
1250
+ return a.thing;
1251
+ };
1252
+ inputs['rcompiler_typeis'] = (a) => a.thing;
1253
+ inputs['rcompiler_typechoose'] = (a) => new T.Bool(a.thing.type === a.scope.block.fields.type[0]);
1254
+ inputs['rcompiler_typeof'] = (a) => new T.Str(sl(a.thing.type));
1255
+ inputs['rcompiler_compilerversion'] = () => new T.Num(pkg.version.split('.').slice(0, 2).join('.'));
1256
+ compiles['rcompiler_func'] = (a) => { emit.projectpub = true; return ''; };
1257
+ compiles['rcompiler_cloneandwait'] = (a) => {
1258
+ if (!multi()) return '';
1259
+ const opt = typeof a.CLONE_OPTION === 'string' ? a.CLONE_OPTION : '';
1260
+ let ti = S.targetID;
1261
+ if (opt !== '_myself_' && opt) { const f = S.targets.findIndex(t => t.name === opt); if (f >= 0) ti = f; }
1262
+ const fns = S.clonesByTarget.get(ti) || [];
1263
+ emit.needsCloneDefault = true;
1264
+ let out = '';
1265
+ for (const f of fns) {
1266
+ out += `if self.stage.can_clone() {\nlet mut __c = self.clone_default();\n`;
1267
+ if (isStageMode()) out += `__c.rcompiler_clone_init(self.sprite_index);\n`;
1268
+ out += `let __s = std::sync::Arc::new(__c); __s.${f}().await; }\n`;
1269
+ }
1270
+ return out;
1271
+ };
1272
+ compiles['rcompiler_use'] = (a) => rcompilerUserCall(a, ';\n');
1273
+ compiles['rcompiler_flaguse'] = (a) => {
1274
+ const from = a.scope.block.fields.from[0];
1275
+ if (from) {
1276
+ const m = 'm_' + kwParse(from);
1277
+ Tools.setstruct([[m, `md_${kwParse(from)}`, `md_${kwParse(from)}::new()`]]);
1278
+ return `self.${m}.runflag();\n`;
1279
+ }
1280
+ return `self.runflag();\n`;
1281
+ };
1282
+ function rcompilerUserCall(a, tail) {
1283
+ const from = a.scope.block.fields.from[0];
1284
+ const hsm = a.scope.block.fields.hsm[0];
1285
+ const argKeys = Object.keys(a).filter(k => k.startsWith('ADD'));
1286
+ const Args = argKeys.map(k => a[k].Stri ? a[k].Stri() : String(a[k]));
1287
+ if (from) {
1288
+ const m = 'm_' + kwParse(from);
1289
+ Tools.setstruct([[m, `md_${kwParse(from)}`, `md_${kwParse(from)}::new()`]]);
1290
+ return `self.${m}.procpub${ctx.keywordOnly(hsm)}(${Args.join(',')})${tail}`;
1291
+ }
1292
+ return `self.procpub${ctx.keywordOnly(hsm)}(${Args.join(',')})${tail}`;
1293
+ }
1294
+ inputs['rcompiler_user'] = (a) => new T.Stri(rcompilerUserCall(a, ''));
1295
+ compiles['rcompiler_extdef'] = (a) => {
1296
+ const name = a.scope.block.fields.ffm[0];
1297
+ const type = a.scope.block.fields.type[0];
1298
+ const start = a.scope.block.fields.startornot && a.scope.block.fields.startornot[0];
1299
+ if (type === '流程块') {
1300
+ compiles[name] = (args) => args.compiler || '';
1301
+ } else if (type === '输入块') {
1302
+ inputs[name] = async (args) => {
1303
+ Tools.setfunc([C.Safe(args.SUBSTACK)]);
1304
+ const keys = Object.keys(args).filter(k => !['scope', 'compiler', 'SUBSTACK'].includes(k));
1305
+ const vals = keys.map(k => C.SafeBool(args[k]));
1306
+ return new T.Stri(`self.proc${S.proccount}(${vals.join(',')})`);
1307
+ };
1308
+ S.inputlist.push(name);
1309
+ }
1310
+ if (start === '启动' && !S.compileEvents.includes(name)) S.compileEvents.push(name);
1311
+ return '';
1312
+ };
1313
+ compiles['rcompiler_import'] = async (a) => {
1314
+ const mod = a.scope.block.fields.HEADER[0];
1315
+ // 已并入标准表的扩展静默跳过
1316
+ const stripped = mod.replace(/^\.\//, '');
1317
+ if (['strings', 'utilities'].includes(stripped)) return '';
1318
+ if (ctx.loadExtensionSource) {
1319
+ const candidates = [
1320
+ path2(process.cwd(), stripped + '.js'),
1321
+ path2(process.cwd(), 'exts', stripped + '.js'),
1322
+ path2(__dirnameSafe(), '..', 'exts', stripped + '.js'),
1323
+ process.cwd() + '/' + mod + '.js'
1324
+ ];
1325
+ for (const p of candidates) {
1326
+ if (fs.existsSync(p)) { ctx.loadExtensionSource(fs.readFileSync(p, 'utf-8')); return ''; }
1327
+ }
1328
+ // 尝试 .sb3 / .json 模块
1329
+ for (const suffix of ['.sb3', '.json']) {
1330
+ for (const p of [path2(process.cwd(), stripped + suffix), path2(process.cwd(), 'exts', stripped + suffix)]) {
1331
+ if (fs.existsSync(p)) {
1332
+ const { readProject } = require('./rcompiler');
1333
+ const sub = await readProject(p);
1334
+ const subRcompiler = new (require('./rcompiler').rcompiler)();
1335
+ const r = await subRcompiler.compile(sub, null, stripped, { log: false, write: false });
1336
+ r.deplist.forEach(d => Tools.setdepend([d]));
1337
+ return '';
1338
+ }
1339
+ }
1340
+ }
1341
+ warnOnce(`rcompiler_import 找不到本地模块: ${mod}`);
1342
+ }
1343
+ return '';
1344
+ };
1345
+
1346
+ const fs = require('fs');
1347
+ const path2 = (...p) => require('path').join(...p);
1348
+ const __dirnameSafe = () => require('path').dirname(__filenameV2());
1349
+ function __filenameV2() { try { return require('path').resolve('src/standard.js'); } catch (e) { return 'src/standard.js'; } }
1350
+ }
1351
+
1352
+ module.exports = { registerStandard };