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