rcompiler 2.1.0 → 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.
- package/CHANGELOG.md +11 -0
- package/README.md +15 -2
- package/docs/CONFIG.md +1 -1
- package/docs/NATIVE.md +110 -0
- package/exts/args.js +142 -0
- package/exts/fs.js +317 -0
- package/exts/io.js +396 -0
- package/exts/path.js +208 -0
- package/exts/process.js +416 -0
- package/package.json +1 -1
- package/src/analysis.js +8 -0
- package/src/assets.js +2 -2
- package/src/cli.js +2 -0
- package/src/emit.js +3 -3
- package/src/preludes.js +845 -122
- package/src/rcompiler.js +328 -60
- package/src/standard.js +176 -76
- package/src/web.js +0 -10
- /package/exts/{rcrcHelper.js → rcompilerExt.js} +0 -0
package/src/rcompiler.js
CHANGED
|
@@ -82,6 +82,7 @@ class rcompiler {
|
|
|
82
82
|
procdefs: [], // {proccode, parsed, names, types, target, block}
|
|
83
83
|
procbycode: new Map(), // proccode -> def
|
|
84
84
|
broadcastScripts: new Map(), // broadcastName -> [fnName]
|
|
85
|
+
broadcastFnByBlock: new Map(), // 帽块对象 -> 预分配函数名(phase 3 预注册)
|
|
85
86
|
broadcastFnTi: new Map(), // fnName -> targetIndex(任务跟踪用)
|
|
86
87
|
clonesByTarget: new Map(), // targetIndex -> [fnName]
|
|
87
88
|
cloneTargetsUsed: new Set(),
|
|
@@ -107,6 +108,8 @@ class rcompiler {
|
|
|
107
108
|
'control_run_as_sprite_menu', 'sound_sounds_menu', 'looks_costume',
|
|
108
109
|
'looks_backdrops', 'motion_pointtowards_menu', 'motion_goto_menu',
|
|
109
110
|
'motion_glideto_menu', 'sensing_touchingobjectmenu', 'sensing_keyoptions',
|
|
111
|
+
'sensing_of_object_menu', 'pen_menu_colorParam',
|
|
112
|
+
'music_menu_DRUM', 'music_menu_INSTRUMENT',
|
|
110
113
|
'control_create_clone_of_menu', 'event_whenkeypressed'],
|
|
111
114
|
inputlist: [
|
|
112
115
|
'sensing_answer', 'operator_equals', 'operator_subtract', 'operator_add',
|
|
@@ -201,8 +204,12 @@ class rcompiler {
|
|
|
201
204
|
}
|
|
202
205
|
// spawn 包裹:任务局部 warp 深度从 0 开始(克隆/广播线程不继承)
|
|
203
206
|
function spawnScript(inner) {
|
|
204
|
-
|
|
205
|
-
|
|
207
|
+
// dyn 擦除:spawn 的 async block 若直接内联被调 future 类型,相互 spawn 的
|
|
208
|
+
// 广播链(如编辑器的 render loop ↔ start workspace)会形成 opaque 类型循环
|
|
209
|
+
//(E0391);Box<dyn Future> 切断静态类型递归(gate 时再包 task_local scope)
|
|
210
|
+
const boxed = `Box::pin(async move { ${inner} }) as std::pin::Pin<Box<dyn std::future::Future<Output = ()> + Send>>`;
|
|
211
|
+
if (S.frame && S.frame.gate && multi()) return `rcompiler_script(${boxed})`;
|
|
212
|
+
return boxed;
|
|
206
213
|
}
|
|
207
214
|
|
|
208
215
|
// ============ 名称工具 ============
|
|
@@ -267,14 +274,16 @@ class rcompiler {
|
|
|
267
274
|
const b = t.blocks[bid];
|
|
268
275
|
if (!b || !b.opcode) continue;
|
|
269
276
|
if (WRITE_VAR_OPS.has(b.opcode) && b.fields && b.fields.VARIABLE) {
|
|
270
|
-
|
|
277
|
+
// 键带 target 序号:sb3 变量 id 只保证目标内唯一(本项目 base_costume/i/
|
|
278
|
+
// current_costume 等跨 3-4 个目标撞 id),全局键会让后注册目标覆盖绑定
|
|
279
|
+
const vid = ti + ':' + b.fields.VARIABLE[1];
|
|
271
280
|
S.writtenVars.add(vid);
|
|
272
281
|
let wk = S.varWriteKind.get(vid);
|
|
273
282
|
if (!wk) { wk = { num: 0, str: 0 }; S.varWriteKind.set(vid, wk); }
|
|
274
283
|
if (b.opcode === 'data_setvariableto' ? writeValIsNum(b, t, ti) : true) wk.num++;
|
|
275
284
|
else wk.str++;
|
|
276
285
|
} else if (WRITE_LIST_OPS.has(b.opcode) && b.fields && b.fields.LIST) {
|
|
277
|
-
S.writtenLists.add(b.fields.LIST[1]);
|
|
286
|
+
S.writtenLists.add(ti + ':' + b.fields.LIST[1]);
|
|
278
287
|
} else if (b.opcode === 'rcompiler_varset' || b.opcode === 'rcompiler_varcreate') {
|
|
279
288
|
// 作用域局部变量,非结构体字段
|
|
280
289
|
}
|
|
@@ -328,6 +337,9 @@ class rcompiler {
|
|
|
328
337
|
`pub const RCOMPILER_QUIT_ON_STOP: bool = ${app.quitOnStop ? 'true' : 'false'};`,
|
|
329
338
|
`pub const RCOMPILER_EXIT_KEY: u8 = ${app.exitKey === 'escape' ? 1 : (app.exitKey === 'ctrlq' ? 2 : 0)};`,
|
|
330
339
|
`pub const RCOMPILER_CLONE_LIMIT: usize = ${Number(app.cloneLimit) > 0 ? Math.round(Number(app.cloneLimit)) : 300};`,
|
|
340
|
+
// 围栏(对照 TurboWarp runtimeOptions.fencing,默认开):关闭时坐标直设不钳制、
|
|
341
|
+
// 尺寸不钳制——模拟器/测量类项目的"走到边缘测舞台"算法依赖此行为
|
|
342
|
+
`pub const RCOMPILER_FENCING: bool = ${app.fencing === false ? 'false' : 'true'};`,
|
|
331
343
|
`pub const RCOMPILER_BG_U32: u32 = 0x${bgU32.toString(16).padStart(6, '0')};`
|
|
332
344
|
].join('\n'));
|
|
333
345
|
}
|
|
@@ -337,8 +349,7 @@ class rcompiler {
|
|
|
337
349
|
|
|
338
350
|
// ============ 变量/列表表 ============
|
|
339
351
|
// 字段命名:全局 vf_<kw>/vs_<kw>/l_<kw>;私有 vf_<ti>_<kw>/...
|
|
340
|
-
const initVals = new Map();
|
|
341
|
-
// 大列表紧凑初始化运行时(按需注册)
|
|
352
|
+
const initVals = new Map(); // 大列表紧凑初始化运行时(按需注册)
|
|
342
353
|
const UNHEX_RUNTIME = [
|
|
343
354
|
'fn rcompiler_unhex(s: &str) -> Vec<f64> {',
|
|
344
355
|
'let b = s.as_bytes();',
|
|
@@ -371,11 +382,29 @@ class rcompiler {
|
|
|
371
382
|
'}',
|
|
372
383
|
'out',
|
|
373
384
|
'}'].join('\n');
|
|
374
|
-
|
|
385
|
+
const writtenFlagFor = (id) => {
|
|
386
|
+
const suffix = ':' + id;
|
|
387
|
+
for (const k of S.writtenVars) if (k.endsWith(suffix)) return true;
|
|
388
|
+
return false;
|
|
389
|
+
};
|
|
390
|
+
const writeKindFor = (id) => {
|
|
391
|
+
const suffix = ':' + id;
|
|
392
|
+
let num = 0, str = 0, any = false;
|
|
393
|
+
for (const [k, w] of S.varWriteKind) if (k.endsWith(suffix)) { num += w.num; str += w.str; any = true; }
|
|
394
|
+
return any ? { num, str } : null;
|
|
395
|
+
};
|
|
396
|
+
const writtenListFor = (id) => {
|
|
397
|
+
const suffix = ':' + id;
|
|
398
|
+
for (const k of S.writtenLists) if (k.endsWith(suffix)) return true;
|
|
399
|
+
return false;
|
|
400
|
+
};
|
|
401
|
+
targets.forEach((t, ti) => {
|
|
375
402
|
const vars = t.variables || {};
|
|
376
403
|
for (const id in vars) {
|
|
377
404
|
const val = vars[id][1];
|
|
378
|
-
|
|
405
|
+
// 键带 target 序号:sb3 的变量 id 只保证目标内唯一,本项目(Scratch 3 Emulator)
|
|
406
|
+
// 大量跨目标复用短 id(18 处冲突),全局键会让后扫描目标的初值覆盖前面目标
|
|
407
|
+
initVals.set(ti + ':' + id, typeof val === 'number' ? { num: val, str: null } : { num: null, str: val == null ? '' : String(val) });
|
|
379
408
|
}
|
|
380
409
|
});
|
|
381
410
|
// 调试模式:字段名带原变量名(vf_<原名>_<kw>),否则保持稳定短名
|
|
@@ -395,10 +424,12 @@ class rcompiler {
|
|
|
395
424
|
const vars = t.variables || {};
|
|
396
425
|
for (const id in vars) {
|
|
397
426
|
const [name] = vars[id];
|
|
398
|
-
const iv = initVals.get(id) || { num: null, str: '' };
|
|
427
|
+
const iv = initVals.get(ti + ':' + id) || { num: null, str: '' };
|
|
399
428
|
const v = {
|
|
400
429
|
id, ti, name, kw: kw(name), isGlobal,
|
|
401
|
-
|
|
430
|
+
// written/wk 聚合:全局变量可被任意目标写入(预扫描按写入方 ti:id 记键),
|
|
431
|
+
// 归属判定按 id 后缀跨键聚合(同 id 跨目标的旁路命中只会过度加锁,语义仍正确)
|
|
432
|
+
declared: null, written: writtenFlagFor(id),
|
|
402
433
|
initNum: iv.num, initStr: iv.str
|
|
403
434
|
};
|
|
404
435
|
// 类型声明解析:声明块所在 target 的同名变量,或舞台上的同名变量
|
|
@@ -409,7 +440,7 @@ class rcompiler {
|
|
|
409
440
|
// 数值读侧省去每次 String 克隆+解析(ALU 写回通道等热路径的主要残余)。
|
|
410
441
|
// 任一处写入不可证数值、或初值是非规范字符串(如 "1.50"、"0x0D")则保持 String。
|
|
411
442
|
if (dec === 'String') {
|
|
412
|
-
const wk =
|
|
443
|
+
const wk = writeKindFor(id);
|
|
413
444
|
const initN = iv.num != null ? iv.num : canonNumInit(iv.str);
|
|
414
445
|
if (wk && wk.num > 0 && wk.str === 0 && initN != null) {
|
|
415
446
|
v.declared = 'f64';
|
|
@@ -426,7 +457,7 @@ class rcompiler {
|
|
|
426
457
|
v.locked = multi() && v.written;
|
|
427
458
|
const f = buildVarField(v);
|
|
428
459
|
v.f = f.f; v.s = f.s;
|
|
429
|
-
S.vars.set(id, v);
|
|
460
|
+
S.vars.set(ti + ':' + id, v);
|
|
430
461
|
registerVarFields(v);
|
|
431
462
|
}
|
|
432
463
|
const lists = t.lists || {};
|
|
@@ -438,15 +469,166 @@ class rcompiler {
|
|
|
438
469
|
const l = {
|
|
439
470
|
id, ti, name, kw: kw(name), isGlobal,
|
|
440
471
|
declared: dec && dec !== 'String' ? dec : null, // 'f64' 等
|
|
441
|
-
written:
|
|
472
|
+
written: writtenListFor(id),
|
|
442
473
|
f: listFieldName(name, kw(name), pre)
|
|
443
474
|
};
|
|
444
475
|
l.locked = multi() && l.written; // 同变量:RcompilerCell 共享可变性
|
|
445
|
-
S.lists.set(id, l);
|
|
476
|
+
S.lists.set(ti + ':' + id, l);
|
|
446
477
|
registerListFields(l, items || []);
|
|
447
478
|
}
|
|
448
479
|
});
|
|
449
480
|
|
|
481
|
+
// 变量名 → 值 的运行时查找表(sensing_of 的"属性名=变量名"语义,对照 rCodenow
|
|
482
|
+
// fork getAttributeOf 的 lookupVariableByNameAndType)。无条件发射:preludes 的
|
|
483
|
+
// s_of 无条件引用它。读取表达式按 emit.fields 实际字段类型生成(变量/列表注册
|
|
484
|
+
// 已全部完成,字段形态准确)。变量名可含任意字符,用 JSON 字面量做键。
|
|
485
|
+
{
|
|
486
|
+
const arms = [];
|
|
487
|
+
for (const [, v] of S.vars) {
|
|
488
|
+
const t = (emit.fields.find(f => f.name === v.f) || {}).type;
|
|
489
|
+
let read = null;
|
|
490
|
+
if (t === 'std::sync::Arc<RcompilerCell<RcompilerV>>' || t === 'RcompilerV') {
|
|
491
|
+
const ref = t.startsWith('std::sync::Arc') ? `&*d.${v.f}.v.borrow()` : `&d.${v.f}`;
|
|
492
|
+
read = `match ${ref} { RcompilerV::N(v0) => rcompiler_num_str(*v0), RcompilerV::S(s) => s.clone() }`;
|
|
493
|
+
} else if (t === 'std::sync::Arc<RcompilerCell<String>>') {
|
|
494
|
+
read = `d.${v.f}.v.borrow().clone()`;
|
|
495
|
+
} else if (t === 'String') {
|
|
496
|
+
read = `d.${v.s}.clone()`;
|
|
497
|
+
} else if (t === 'bool') {
|
|
498
|
+
read = `(*d.${v.f} as i32).to_string()`;
|
|
499
|
+
} else if (t === 'f64' || t === 'i32' || t === 'usize') {
|
|
500
|
+
read = `rcompiler_num_str(d.${v.f})`;
|
|
501
|
+
}
|
|
502
|
+
if (read) arms.push(`${JSON.stringify(String(v.name))} => Some(${read})`);
|
|
503
|
+
}
|
|
504
|
+
emit.func(['pub fn rcompiler_var_by_name(d: &Default, name: &str) -> Option<String> {',
|
|
505
|
+
'match name {',
|
|
506
|
+
arms.join(',\n') + (arms.length ? ',' : ''),
|
|
507
|
+
'_ => None',
|
|
508
|
+
'}',
|
|
509
|
+
'}'].join('\n'));
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
// 诊断导出:全部变量/列表 → JSON(与真实 VM 的黄金参照快照做逐字段 diff 用)。
|
|
513
|
+
// 无头模式由 RCOMPILER_VARS_DUMP / RCOMPILER_VARS_TICKS 驱动,逐 tick 追加 JSONL。
|
|
514
|
+
// 始终发射(表体积仅数 KB):发布构建同样可诊断,不引入新依赖(手写转义)。
|
|
515
|
+
{
|
|
516
|
+
const B = String.fromCharCode(92); // 反斜杠字符(避免手写转义层级)
|
|
517
|
+
const rl = s => `'${s}'`; // Rust char 字面量
|
|
518
|
+
const rs = s => `"${s}"`; // Rust string 字面量(内容原样,由调用方预转义)
|
|
519
|
+
const rsj = s => rs(String(s).replace(/"/g, B + '"')); // JSON 片段 → 转义后的 Rust 字面量
|
|
520
|
+
emit.runtime([
|
|
521
|
+
'fn rcompiler_json_escape(s: &str) -> String {',
|
|
522
|
+
'let mut out = String::with_capacity(s.len() + 2);',
|
|
523
|
+
'for c in s.chars() {',
|
|
524
|
+
'match c {',
|
|
525
|
+
// '\'' => out.push_str("\\\"")
|
|
526
|
+
[rl(B + '"'), '=>', 'out.push_str(' + rs(B + B + B + '"') + '),'].join(' '),
|
|
527
|
+
// '\\' => out.push_str("\\\\")
|
|
528
|
+
[rl(B + B), '=>', 'out.push_str(' + rs(B + B + B + B) + '),'].join(' '),
|
|
529
|
+
// '\n' => out.push_str("\\n")
|
|
530
|
+
[rl(B + 'n'), '=>', 'out.push_str(' + rs(B + B + 'n') + '),'].join(' '),
|
|
531
|
+
[rl(B + 'r'), '=>', 'out.push_str(' + rs(B + B + 'r') + '),'].join(' '),
|
|
532
|
+
[rl(B + 't'), '=>', 'out.push_str(' + rs(B + B + 't') + '),'].join(' '),
|
|
533
|
+
'c if (c as u32) < 0x20 => out.push_str(&format!(' + rs(B + B + 'u{:x}') + ', c as u32)),',
|
|
534
|
+
'c => out.push(c),',
|
|
535
|
+
'}',
|
|
536
|
+
'}',
|
|
537
|
+
'out',
|
|
538
|
+
'}'].join('\n'));
|
|
539
|
+
emit.runtime([
|
|
540
|
+
'fn rcompiler_json_str(s: &str) -> String {',
|
|
541
|
+
'let mut out = String::with_capacity(s.len() + 2);',
|
|
542
|
+
'out.push(' + rl('"') + ');',
|
|
543
|
+
'out.push_str(&rcompiler_json_escape(s));',
|
|
544
|
+
'out.push(' + rl('"') + ');',
|
|
545
|
+
'out',
|
|
546
|
+
'}'].join('\n'));
|
|
547
|
+
emit.runtime([
|
|
548
|
+
'fn rcompiler_json_num(v: f64) -> String {',
|
|
549
|
+
'if v.is_finite() { v.to_string() } else { ' + rs('null') + '.to_string() }',
|
|
550
|
+
'}'].join('\n'));
|
|
551
|
+
|
|
552
|
+
const targetNames = targets.map(t => String(t.name || ''));
|
|
553
|
+
const byTi = new Map();
|
|
554
|
+
const gOf = ti => { if (!byTi.has(ti)) byTi.set(ti, { vars: [], lists: [] }); return byTi.get(ti); };
|
|
555
|
+
for (const [, v] of S.vars) gOf(v.ti).vars.push(v);
|
|
556
|
+
for (const [, l] of S.lists) gOf(l.ti).lists.push(l);
|
|
557
|
+
const sections = [];
|
|
558
|
+
for (let ti = 0; ti < targets.length; ti++) {
|
|
559
|
+
const g = byTi.get(ti);
|
|
560
|
+
if (!g || (g.vars.length === 0 && g.lists.length === 0)) continue;
|
|
561
|
+
const pushes = [];
|
|
562
|
+
for (const v of g.vars) {
|
|
563
|
+
const t = (emit.fields.find(f => f.name === v.f) || {}).type;
|
|
564
|
+
const key = `rcompiler_json_str(${castUnParse(String(v.name))})`;
|
|
565
|
+
let val = null;
|
|
566
|
+
if (t === 'RcompilerV') {
|
|
567
|
+
val = `match &self.${v.f} { RcompilerV::N(v0) => rcompiler_json_num(*v0), RcompilerV::S(s) => rcompiler_json_str(s) }`;
|
|
568
|
+
} else if (t === 'std::sync::Arc<RcompilerCell<RcompilerV>>') {
|
|
569
|
+
val = `match &*self.${v.f}.v.borrow() { RcompilerV::N(v0) => rcompiler_json_num(*v0), RcompilerV::S(s) => rcompiler_json_str(s) }`;
|
|
570
|
+
} else if (t === 'String') {
|
|
571
|
+
val = `rcompiler_json_str(&self.${v.s})`;
|
|
572
|
+
} else if (t === 'std::sync::Arc<RcompilerCell<String>>') {
|
|
573
|
+
val = `rcompiler_json_str(&self.${v.s}.v.borrow())`;
|
|
574
|
+
} else if (t === 'bool') {
|
|
575
|
+
val = `if self.${v.f} { "true".to_string() } else { "false".to_string() }`;
|
|
576
|
+
} else if (t === 'std::sync::Arc<RcompilerCell<bool>>') {
|
|
577
|
+
val = `if *self.${v.f}.v.borrow() { "true".to_string() } else { "false".to_string() }`;
|
|
578
|
+
} else if (t === 'f64') {
|
|
579
|
+
val = `rcompiler_json_num(self.${v.f})`;
|
|
580
|
+
} else if (t === 'std::sync::Arc<RcompilerCell<f64>>') {
|
|
581
|
+
val = `rcompiler_json_num(*self.${v.f}.v.borrow())`;
|
|
582
|
+
} else if (t === 'i32' || t === 'usize') {
|
|
583
|
+
val = `self.${v.f}.to_string()`;
|
|
584
|
+
} else if (t === 'std::sync::Arc<RcompilerCell<i32>>' || t === 'std::sync::Arc<RcompilerCell<usize>>') {
|
|
585
|
+
val = `self.${v.f}.v.borrow().to_string()`;
|
|
586
|
+
}
|
|
587
|
+
if (val) pushes.push(`parts.push(format!("{}:{}", ${key}, ${val}));`);
|
|
588
|
+
}
|
|
589
|
+
for (const l of g.lists) {
|
|
590
|
+
const t = (emit.fields.find(f => f.name === l.f) || {}).type;
|
|
591
|
+
const key = `rcompiler_json_str(${castUnParse(String(l.name))})`;
|
|
592
|
+
let val = null;
|
|
593
|
+
// 单表达式(迭代器直收集,无中间 let):val 内嵌于 format! 参数位
|
|
594
|
+
if (t === 'Vec<f64>') {
|
|
595
|
+
val = `format!("[{}]", self.${l.f}.iter().map(|x| rcompiler_json_num(*x)).collect::<Vec<String>>().join(","))`;
|
|
596
|
+
} else if (t === 'Vec<String>') {
|
|
597
|
+
val = `format!("[{}]", self.${l.f}.iter().map(|x| rcompiler_json_str(x)).collect::<Vec<String>>().join(","))`;
|
|
598
|
+
} else if (t === 'std::sync::Arc<RcompilerCell<Vec<f64>>>') {
|
|
599
|
+
val = `format!("[{}]", self.${l.f}.v.borrow().iter().map(|x| rcompiler_json_num(*x)).collect::<Vec<String>>().join(","))`;
|
|
600
|
+
} else if (t === 'std::sync::Arc<RcompilerCell<Vec<String>>>') {
|
|
601
|
+
val = `format!("[{}]", self.${l.f}.v.borrow().iter().map(|x| rcompiler_json_str(x)).collect::<Vec<String>>().join(","))`;
|
|
602
|
+
}
|
|
603
|
+
if (val) pushes.push(`lparts.push(format!("{}:{}", ${key}, ${val}));`);
|
|
604
|
+
}
|
|
605
|
+
sections.push([
|
|
606
|
+
'secs.push({',
|
|
607
|
+
'let mut parts: Vec<String> = Vec::new();',
|
|
608
|
+
'let mut lparts: Vec<String> = Vec::new();',
|
|
609
|
+
...pushes,
|
|
610
|
+
'let mut s = String::new();',
|
|
611
|
+
`s.push_str(${rsj('{"name":')});`,
|
|
612
|
+
`s.push_str(&rcompiler_json_str(${castUnParse(targetNames[ti])}));`,
|
|
613
|
+
`s.push_str(${rsj(',"vars":{')});`,
|
|
614
|
+
's.push_str(&parts.join(","));',
|
|
615
|
+
`s.push_str(${rsj('},"lists":{')});`,
|
|
616
|
+
's.push_str(&lparts.join(","));',
|
|
617
|
+
`s.push_str(${rsj('}}')});`,
|
|
618
|
+
's',
|
|
619
|
+
'});'].join('\n'));
|
|
620
|
+
}
|
|
621
|
+
emit.func(['pub fn rcompiler_vars_dump_json(&self) -> String {',
|
|
622
|
+
'let mut out = String::with_capacity(16384);',
|
|
623
|
+
'let mut secs: Vec<String> = Vec::new();',
|
|
624
|
+
...sections,
|
|
625
|
+
`out.push_str(${rsj('{"targets":[')});`,
|
|
626
|
+
'out.push_str(&secs.join(","));',
|
|
627
|
+
`out.push_str(${rsj(']}')});`,
|
|
628
|
+
'out',
|
|
629
|
+
'}'].join('\n'));
|
|
630
|
+
}
|
|
631
|
+
|
|
450
632
|
function registerVarFields(v) {
|
|
451
633
|
// 未类型化变量:单枚举存储(Scratch 的 JS 值模型——一个变量就是一个值,
|
|
452
634
|
// 数字或字符串)。相比双 vf/vs 轨:setNum/setStr 各省一次格式化/解析,
|
|
@@ -455,6 +637,8 @@ class rcompiler {
|
|
|
455
637
|
runtimeRcompilerV();
|
|
456
638
|
emit.field(v.f, v.locked ? `std::sync::Arc<RcompilerCell<RcompilerV>>` : 'RcompilerV',
|
|
457
639
|
v.locked ? `std::sync::Arc::new(RcompilerCell { v: std::cell::RefCell::new(RcompilerV::S(${initStringOf(v)})) })` : `RcompilerV::S(${initStringOf(v)})`);
|
|
640
|
+
// 克隆语义:全局锁定字段保持 Arc 共享(clone_default 按 cloneSharedFields 判定)
|
|
641
|
+
if (v.locked && v.isGlobal) emit.cloneSharedFields.add(v.f);
|
|
458
642
|
return;
|
|
459
643
|
}
|
|
460
644
|
if (v.declared === 'String') {
|
|
@@ -591,7 +775,8 @@ class rcompiler {
|
|
|
591
775
|
}
|
|
592
776
|
|
|
593
777
|
function getvar(name, id) {
|
|
594
|
-
|
|
778
|
+
// 键 ti:id;跨目标引用(全局变量)回退舞台键 0:id,再按名扫描
|
|
779
|
+
let v = (id && (S.vars.get(S.targetID + ':' + id) || S.vars.get('0:' + id))) || null;
|
|
595
780
|
if (!v) {
|
|
596
781
|
for (const [, vv] of S.vars) {
|
|
597
782
|
if (vv.name === name && (vv.ti === S.targetID || vv.isGlobal)) { v = vv; if (vv.ti === S.targetID) break; }
|
|
@@ -774,7 +959,8 @@ class rcompiler {
|
|
|
774
959
|
}
|
|
775
960
|
|
|
776
961
|
function getlist(name, id) {
|
|
777
|
-
|
|
962
|
+
// 键 ti:id;跨目标引用(全局列表)回退舞台键 0:id,再按名扫描
|
|
963
|
+
let l = (id && (S.lists.get(S.targetID + ':' + id) || S.lists.get('0:' + id))) || null;
|
|
778
964
|
if (!l) {
|
|
779
965
|
for (const [, ll] of S.lists) {
|
|
780
966
|
if (ll.name === name && (ll.ti === S.targetID || ll.isGlobal)) { l = ll; if (ll.ti === S.targetID) break; }
|
|
@@ -793,7 +979,7 @@ class rcompiler {
|
|
|
793
979
|
// 若在长表达式里直接 `.lock().unwrap()`,MutexGuard 临时值会存活到整条语句结束,
|
|
794
980
|
// 同一语句内第二次读同一列表会同线程自死锁(列表密集型项目在单条语句内多次读取同列表时即会卡死)
|
|
795
981
|
function getListField(name, id) {
|
|
796
|
-
let l = (id && S.lists.get(id)) || null;
|
|
982
|
+
let l = (id && (S.lists.get(S.targetID + ':' + id) || S.lists.get('0:' + id))) || null;
|
|
797
983
|
if (!l) {
|
|
798
984
|
for (const [, ll] of S.lists) {
|
|
799
985
|
if (ll.name === name && (ll.ti === S.targetID || ll.isGlobal)) { l = ll; if (ll.ti === S.targetID) break; }
|
|
@@ -849,7 +1035,7 @@ class rcompiler {
|
|
|
849
1035
|
|
|
850
1036
|
// 列表元信息(元素类型判定:declared === 'f64' → Vec<f64>)
|
|
851
1037
|
function listInfo(name, id) {
|
|
852
|
-
let l = (id && S.lists.get(id)) || null;
|
|
1038
|
+
let l = (id && (S.lists.get(S.targetID + ':' + id) || S.lists.get('0:' + id))) || null;
|
|
853
1039
|
if (!l) {
|
|
854
1040
|
for (const [, ll] of S.lists) {
|
|
855
1041
|
if (ll.name === name && (ll.ti === S.targetID || ll.isGlobal)) { l = ll; if (ll.ti === S.targetID) break; }
|
|
@@ -1296,7 +1482,13 @@ class rcompiler {
|
|
|
1296
1482
|
|
|
1297
1483
|
// ============ 脚本注册 ============
|
|
1298
1484
|
function scriptSig(name, kind) {
|
|
1299
|
-
if (multi())
|
|
1485
|
+
if (multi()) {
|
|
1486
|
+
// 广播接收者:boxed future 签名(对照 proc 的 hasVariants 路径)——
|
|
1487
|
+
// 相互 spawn 的广播链在 spawn 点的 `async block: Send` 转型会递归下钻对方
|
|
1488
|
+
// future 的 opaque 类型(E0391 类型循环);签名层 dyn 擦除彻底切断
|
|
1489
|
+
if (kind === 'broadcast') return `fn ${name}<'a>(mut self: std::sync::Arc<Self>) -> std::pin::Pin<std::boxed::Box<dyn std::future::Future<Output = ()> + Send + 'a>>`;
|
|
1490
|
+
return `async fn ${name}(mut self: std::sync::Arc<Self>)`;
|
|
1491
|
+
}
|
|
1300
1492
|
return `fn ${name}(${S.selfmut ? '&mut self' : '&self'})`;
|
|
1301
1493
|
}
|
|
1302
1494
|
function registerScript(name, body, kind = 'flag', info = {}) {
|
|
@@ -1304,7 +1496,11 @@ class rcompiler {
|
|
|
1304
1496
|
const kindLabel = { flag: '绿旗脚本', broadcast: '广播接收脚本', click: '点击脚本', key: '按键脚本', hat: '起动帽脚本', clone: '克隆脚本' }[kind] || (kind + ' 脚本');
|
|
1305
1497
|
const extra = info && info.broadcast != null ? ` · 广播「${info.broadcast}」` : '';
|
|
1306
1498
|
const hdr = debug ? `// rcompiler · 角色「${targetNameOf(S.targetID)}」 · ${kindLabel}${extra}\n` : '';
|
|
1307
|
-
|
|
1499
|
+
// 广播接收者(multi):boxed future 签名,hdr/inuse 全部进 Box::pin 的 async 块
|
|
1500
|
+
const boxed = multi() && kind === 'broadcast';
|
|
1501
|
+
const fn = boxed
|
|
1502
|
+
? `${scriptSig(name, kind)}{\nBox::pin(async move {\n${hdr}${inuse}${body}\n})\n}\n`
|
|
1503
|
+
: `${scriptSig(name, kind)}{\n${hdr}${inuse}${body}\n}\n`;
|
|
1308
1504
|
emit.func(fn);
|
|
1309
1505
|
// 广播帽仅在收到广播时执行,不随 runflag 启动
|
|
1310
1506
|
if (kind !== 'broadcast') emit.scripts.push({ name, kind, ti: S.targetID });
|
|
@@ -1395,6 +1591,10 @@ class rcompiler {
|
|
|
1395
1591
|
}
|
|
1396
1592
|
}
|
|
1397
1593
|
inputs[key] = comped;
|
|
1594
|
+
} else if (S.noAutoInput.includes(cb.opcode)) {
|
|
1595
|
+
// 菜单阴影块(keyoptions/of_object/colorParam/music 菜单等):值由宿主块
|
|
1596
|
+
// 经 menuInput/fields 解析,按值输入恒为空块,不得按语句链编译(避免未知块告警)
|
|
1597
|
+
inputs[key] = new T.Block('');
|
|
1398
1598
|
} else {
|
|
1399
1599
|
// 语句链(SUBSTACK 等分支输入):必须编译整条链。
|
|
1400
1600
|
// 此前用 compile_block 只编译首块——所有 if/循环体都会被截断成一条语句!
|
|
@@ -1422,8 +1622,11 @@ class rcompiler {
|
|
|
1422
1622
|
inputs = await compile_input(block, target);
|
|
1423
1623
|
}
|
|
1424
1624
|
if (S.compiles[block.opcode]) {
|
|
1425
|
-
|
|
1426
|
-
|
|
1625
|
+
// 元数据经 __scope 传递:procedures_call 的参数 id 是任意字符串,
|
|
1626
|
+
// 可能与 'scope'/'compiler' 重名(如过程参数恰好叫 scope),不得覆写已编译实参
|
|
1627
|
+
inputs.__scope = { block, target };
|
|
1628
|
+
if (inputs.scope === undefined) inputs.scope = inputs.__scope;
|
|
1629
|
+
if (inputs.compiler === undefined) inputs.compiler = '';
|
|
1427
1630
|
const r = await S.compiles[block.opcode](inputs);
|
|
1428
1631
|
const code = typeof r === 'string' ? r : ((r && r.compiler) || '');
|
|
1429
1632
|
return injectStageIdx(code);
|
|
@@ -1454,7 +1657,9 @@ class rcompiler {
|
|
|
1454
1657
|
// sequencer.stepToProcedure 的 target 语义:共享积木随调用方运行)
|
|
1455
1658
|
// 幂等:已注入(`(` 后紧跟 idx 表达式 + `,`/`)`)的调用不再二次注入——
|
|
1456
1659
|
// 嵌套栈(repeat/forever 的 SUBSTACK)会被外层 compile_block 再次处理
|
|
1457
|
-
|
|
1660
|
+
// 注入豁免名单:键与正则捕获组一致(self\.s_(capture),不含 s_ 前缀)——
|
|
1661
|
+
// 此前误存 's_switch_backdrop' 等带前缀键,永远不命中,backdrop 系列被错误注入 idx
|
|
1662
|
+
const STAGE_NOIDX = new Set(['switch_backdrop', 'next_backdrop', 'backdrop_name', 'backdrop_number']);
|
|
1458
1663
|
const reEscape = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
1459
1664
|
// 舞台桥接 idx 表达式:globalcaller 过程体 → __rcaller(调用方运行期索引);
|
|
1460
1665
|
// 克隆脚本 → self.sprite_index;广播接收脚本 → 原型/克隆各自索引;普通脚本 → 编译期索引
|
|
@@ -1584,17 +1789,20 @@ class rcompiler {
|
|
|
1584
1789
|
}
|
|
1585
1790
|
const classifyArgNum = (input, target, endef) => {
|
|
1586
1791
|
if (!input || !Array.isArray(input) || input.length < 2) return false;
|
|
1792
|
+
const tix = targets.indexOf(target);
|
|
1793
|
+
const varById = (vid) => S.vars.get(tix + ':' + vid) || S.vars.get('0:' + vid);
|
|
1794
|
+
const listById = (lid) => S.lists.get(tix + ':' + lid) || S.lists.get('0:' + lid);
|
|
1587
1795
|
const val = input[1];
|
|
1588
1796
|
if (Array.isArray(val)) {
|
|
1589
1797
|
const code = val[0];
|
|
1590
1798
|
if (code === 4 || code === 5 || code === 6) return true; // 数字字面量
|
|
1591
1799
|
if (code === 10 || code === 8 || code === 9) return false; // 文本/颜色
|
|
1592
1800
|
if (code === 12) {
|
|
1593
|
-
const v =
|
|
1801
|
+
const v = varById(String(val[2]));
|
|
1594
1802
|
return !!(v && v.declared === 'f64');
|
|
1595
1803
|
}
|
|
1596
1804
|
if (code === 13) {
|
|
1597
|
-
const l =
|
|
1805
|
+
const l = listById(String(val[2]));
|
|
1598
1806
|
return !!(l && l.declared === 'f64');
|
|
1599
1807
|
}
|
|
1600
1808
|
return false;
|
|
@@ -1609,12 +1817,12 @@ class rcompiler {
|
|
|
1609
1817
|
return true;
|
|
1610
1818
|
case 'data_variable': {
|
|
1611
1819
|
const vid = blk.fields && blk.fields.VARIABLE && blk.fields.VARIABLE[1];
|
|
1612
|
-
const v = vid &&
|
|
1820
|
+
const v = vid && varById(String(vid));
|
|
1613
1821
|
return !!(v && v.declared === 'f64');
|
|
1614
1822
|
}
|
|
1615
1823
|
case 'data_itemoflist': {
|
|
1616
1824
|
const lid = blk.fields && blk.fields.LIST && blk.fields.LIST[1];
|
|
1617
|
-
const l = lid &&
|
|
1825
|
+
const l = lid && listById(String(lid));
|
|
1618
1826
|
return !!(l && l.declared === 'f64');
|
|
1619
1827
|
}
|
|
1620
1828
|
case 'argument_reporter_string_number': {
|
|
@@ -1635,7 +1843,10 @@ class rcompiler {
|
|
|
1635
1843
|
for (const bid in (target.blocks || {})) {
|
|
1636
1844
|
const b = target.blocks[bid];
|
|
1637
1845
|
if (!b || b.opcode !== 'procedures_call' || !b.mutation) continue;
|
|
1638
|
-
|
|
1846
|
+
// 调用方视角的 def(resolveProc:本 target 定义优先,否则全局)——
|
|
1847
|
+
// 同名 proccode 可在多个 target 各有定义(procbycode 只存首个),否决
|
|
1848
|
+
// 必须落在调用方实际绑定的 def 上,否则实际发射的副本类型推断失效
|
|
1849
|
+
const def = resolveProc(String(b.mutation.proccode), targets.indexOf(target)) || S.procbycode.get(String(b.mutation.proccode));
|
|
1639
1850
|
if (!def) continue;
|
|
1640
1851
|
const endef = blockDef.get(bid) || null;
|
|
1641
1852
|
let vi = 0;
|
|
@@ -1655,6 +1866,20 @@ class rcompiler {
|
|
|
1655
1866
|
if (def.types[vi] === '&str' && def.numericArgs && def.numericArgs[vi]) def.types[vi] = 'f64';
|
|
1656
1867
|
}
|
|
1657
1868
|
}
|
|
1869
|
+
// %n 槽降级:调用点以非数值实参使用(弱类型原样传,对照 Scratch——%n 槽传字符串
|
|
1870
|
+
// 时 proc 体内按字符串用,如 letter-of/contains),保持 f64 会把实参数值化为 0
|
|
1871
|
+
// 而损坏数据(Scratch 3 Emulator 的存档解析器即因此死循环)
|
|
1872
|
+
for (const def of S.procdefs) {
|
|
1873
|
+
let vi = 0;
|
|
1874
|
+
for (let i = 0; i < def.argIds.length; i++) {
|
|
1875
|
+
const hole = def.holes[i] || '%s';
|
|
1876
|
+
if (hole === '%c' || def.branchNames.has(String(def.argNames && def.argNames[i]))) continue;
|
|
1877
|
+
if (hole === '%n' && def.types[vi] === 'f64' && def.numericArgs && def.numericArgs[vi] === false) {
|
|
1878
|
+
def.types[vi] = '&str';
|
|
1879
|
+
}
|
|
1880
|
+
vi++;
|
|
1881
|
+
}
|
|
1882
|
+
}
|
|
1658
1883
|
// ============ 过程参数数值类型推断结束 ============
|
|
1659
1884
|
|
|
1660
1885
|
// 递归(异步调用环)检测:await 边 + spawn 边;环上函数需装箱
|
|
@@ -1832,7 +2057,9 @@ class rcompiler {
|
|
|
1832
2057
|
const hole = def.holes[i] || '%s';
|
|
1833
2058
|
if (hole === '%c' || def.branchNames.has(String(def.argNames && def.argNames[i]))) continue;
|
|
1834
2059
|
const vi = vals.length;
|
|
1835
|
-
const
|
|
2060
|
+
const raw = args ? args[def.argIds[i]] : null;
|
|
2061
|
+
// 鸭子类型校验:畸形输入/元数据对象(无编译值方法)按缺失实参走默认值
|
|
2062
|
+
const v = (raw && typeof raw.Stri === 'function') ? raw : null;
|
|
1836
2063
|
if (v == null) {
|
|
1837
2064
|
const dflt = def.argDefaults ? def.argDefaults[i] : null;
|
|
1838
2065
|
if (def.types[vi] === 'bool') vals.push('false');
|
|
@@ -1915,13 +2142,22 @@ class rcompiler {
|
|
|
1915
2142
|
const inputs = preInputs || (callBlock.opcode === 'procedures_call' ? await compile_input(callBlock, target) : null);
|
|
1916
2143
|
if (!def.hasVariants) return { name: def.parsed, args: buildCallArgs(def, callBlock, inputs) };
|
|
1917
2144
|
const branches = new Map();
|
|
1918
|
-
|
|
1919
|
-
|
|
1920
|
-
|
|
1921
|
-
|
|
1922
|
-
|
|
1923
|
-
|
|
1924
|
-
|
|
2145
|
+
// 分支体里的参数报告器不得绑定当前编译上下文的过程参数(调用点嵌在其他过程体内时
|
|
2146
|
+
// 会把调用方的 pm_N 拼进被调方变体导致悬空);对照 VM getParam:执行帧无此参数名
|
|
2147
|
+
// 时回退中性值('' / false)。分支体按无过程上下文编译,拼接后在被调方作用域求值。
|
|
2148
|
+
const prevVariantProc = S.customproc;
|
|
2149
|
+
S.customproc = null;
|
|
2150
|
+
try {
|
|
2151
|
+
for (const [name, aid] of def.branchNames) {
|
|
2152
|
+
const inp = callBlock.inputs ? callBlock.inputs[aid] : null;
|
|
2153
|
+
const startId = inp && Array.isArray(inp) && typeof inp[1] === 'string' ? inp[1] : null;
|
|
2154
|
+
branches.set(name, startId ? await compile_chain(startId, target) : '');
|
|
2155
|
+
}
|
|
2156
|
+
if (callBlock.mutation && callBlock.mutation.rc_shape === 'hat') {
|
|
2157
|
+
branches.set('__hat_body__', callBlock.next ? await compile_chain(callBlock.next, target) : '');
|
|
2158
|
+
}
|
|
2159
|
+
} finally {
|
|
2160
|
+
S.customproc = prevVariantProc;
|
|
1925
2161
|
}
|
|
1926
2162
|
// 相同分支内容复用变体(循环体内的调用点只编译一次;不同调用点同分支亦复用)
|
|
1927
2163
|
const key = def.proccode + '\u0000' + [...branches.entries()].map(([k, v]) => k + '\u0001' + v).join('\u0002');
|
|
@@ -1956,9 +2192,21 @@ class rcompiler {
|
|
|
1956
2192
|
return out;
|
|
1957
2193
|
}
|
|
1958
2194
|
|
|
2195
|
+
// 孤儿过程调用(无 procedures_prototype 定义):运行时按 Scratch VM 语义静默跳过,
|
|
2196
|
+
// 但同一条 proccode 可能有几十处调用点——告警按 proccode 去重,避免刷屏
|
|
2197
|
+
const warnUndefProc = (code) => {
|
|
2198
|
+
if (S.ignore) return;
|
|
2199
|
+
if (!S.undefProcWarned) S.undefProcWarned = new Set();
|
|
2200
|
+
const key = String(code);
|
|
2201
|
+
if (!S.undefProcWarned.has(key)) {
|
|
2202
|
+
S.undefProcWarned.add(key);
|
|
2203
|
+
console.warn(`\x1b[33m未定义的函数\x1b[m: ${code}`);
|
|
2204
|
+
}
|
|
2205
|
+
};
|
|
2206
|
+
|
|
1959
2207
|
async function compile_proc_call_value(block, target) {
|
|
1960
2208
|
const def = resolveProc(String(block.mutation.proccode), S.targetID);
|
|
1961
|
-
if (!def) {
|
|
2209
|
+
if (!def) { warnUndefProc(block.mutation.proccode); return new T.Stri('String::new()'); }
|
|
1962
2210
|
if (def.ti !== S.targetID && def.scope === 'local') {
|
|
1963
2211
|
console.warn(`\x1b[33m过程 ${def.proccode} 为 local 作用域,跨角色调用已跳过\x1b[m`);
|
|
1964
2212
|
return new T.Stri('String::new()');
|
|
@@ -1988,30 +2236,35 @@ class rcompiler {
|
|
|
1988
2236
|
}
|
|
1989
2237
|
return null;
|
|
1990
2238
|
}
|
|
2239
|
+
// TurboWarp 特殊报告名:任意上下文(含过程体内、无同名参数时)恒真——
|
|
2240
|
+
// 对照 TurboWarp procedures.js:特殊名检查先于 getParam;比较统一小写
|
|
2241
|
+
const SPECIAL_BOOL_ARGS = new Set(['is turbowarp?', 'is rcodenow?', 'is compiled?', 'is rcompiler?']);
|
|
1991
2242
|
S.inputscompiles['argument_reporter_string_number'] = (args) => {
|
|
1992
2243
|
const name = String(args.scope.block.fields.VALUE[0]);
|
|
1993
2244
|
const arg = 'pm_' + kwParse(name);
|
|
1994
|
-
|
|
2245
|
+
const pty = S.customproc ? procParamType(name) : null;
|
|
2246
|
+
if (pty != null) {
|
|
1995
2247
|
S.customproc.usedArgs.add(arg);
|
|
1996
|
-
if (
|
|
2248
|
+
if (pty === 'bool') return new T.Str(`&(${arg}).to_string()`);
|
|
1997
2249
|
// f64 参数:数值上下文直用原值;字符串上下文按 JS Number→String 格式化
|
|
1998
|
-
if (
|
|
2250
|
+
if (pty === 'f64') { runtimeNumStr(); return new T.Num(arg); }
|
|
2251
|
+
return new T.Str(arg);
|
|
1999
2252
|
}
|
|
2000
|
-
|
|
2253
|
+
// 孤儿/非本过程参数的参数报告器:pm_N 不在作用域,对照 VM getParam 未命中帧 → 空串
|
|
2254
|
+
return new T.Str('String::new()');
|
|
2001
2255
|
};
|
|
2002
2256
|
S.inputscompiles['argument_reporter_boolean'] = (args) => {
|
|
2003
2257
|
const name = String(args.scope.block.fields.VALUE[0]);
|
|
2004
2258
|
const arg = 'pm_' + kwParse(name);
|
|
2005
|
-
if (
|
|
2259
|
+
if (SPECIAL_BOOL_ARGS.has(name.toLowerCase())) return new T.Bool('true');
|
|
2260
|
+
const pty = S.customproc ? procParamType(name) : null;
|
|
2261
|
+
if (pty != null) {
|
|
2006
2262
|
S.customproc.usedArgs.add(arg);
|
|
2007
|
-
if (
|
|
2008
|
-
|
|
2009
|
-
switch (name) {
|
|
2010
|
-
case 'is turbowarp?': case 'is rCodenow?': case 'is compiled?': case 'is rcompiler?':
|
|
2011
|
-
return new T.Bool('true');
|
|
2012
|
-
}
|
|
2263
|
+
if (pty === '&str') { runtimeStr2Bool(); return new T.Bool(`string_to_boolean(${arg})`); }
|
|
2264
|
+
return new T.Bool(arg);
|
|
2013
2265
|
}
|
|
2014
|
-
|
|
2266
|
+
// 孤儿/非本过程参数的布尔参数报告器:对照 VM getParam 未命中帧 → false
|
|
2267
|
+
return new T.Bool('false');
|
|
2015
2268
|
};
|
|
2016
2269
|
// %c 分支参数执行(对照 argumentCommand:执行调用方堆叠在调用块下的分支链)
|
|
2017
2270
|
S.compiles['argument_command'] = (args) => {
|
|
@@ -2029,17 +2282,17 @@ class rcompiler {
|
|
|
2029
2282
|
S.compiles['procedures_definition'] = (args) => { return ''; }; // 两遍法中单独处理
|
|
2030
2283
|
S.compiles['procedures_prototype'] = () => ''; // 原型(阴影块)不产生代码
|
|
2031
2284
|
S.compiles['procedures_call'] = async (args) => {
|
|
2032
|
-
const block = args.
|
|
2285
|
+
const block = args.__scope.block;
|
|
2033
2286
|
const def = resolveProc(String(block.mutation.proccode), S.targetID);
|
|
2034
2287
|
if (!def) {
|
|
2035
|
-
|
|
2288
|
+
warnUndefProc(block.mutation.proccode);
|
|
2036
2289
|
return '';
|
|
2037
2290
|
}
|
|
2038
2291
|
if (def.ti !== S.targetID && def.scope === 'local') {
|
|
2039
2292
|
if (!S.ignore) console.warn(`\x1b[33m过程 ${def.proccode} 为 local 作用域,跨角色调用已跳过\x1b[m`);
|
|
2040
2293
|
return '';
|
|
2041
2294
|
}
|
|
2042
|
-
const { name, args: callArgs } = await procVariant(def, args.
|
|
2295
|
+
const { name, args: callArgs } = await procVariant(def, args.__scope.target, block, args);
|
|
2043
2296
|
let call = procCallExpr(def, name, callArgs);
|
|
2044
2297
|
// “运行时不刷新屏幕”的自定义积木:调用期间进入 warp(跳过帧门控)
|
|
2045
2298
|
if (def.warp && S.frame && S.frame.gate) call = `{\nlet _wg = RcompilerWarpGuard::enter();\n${call}}`;
|
|
@@ -2060,7 +2313,7 @@ class rcompiler {
|
|
|
2060
2313
|
inWarp: () => !!(S.customproc && S.customproc.warp),
|
|
2061
2314
|
compile_chain, compile_block, compile_this, compile_input,
|
|
2062
2315
|
registerScript, scriptSig, multi, isStageMode,
|
|
2063
|
-
frameWaitStmt, spawnScript,
|
|
2316
|
+
frameWaitStmt, spawnScript, stageIdxExpr,
|
|
2064
2317
|
markWrite: () => { S.selfmut = true; },
|
|
2065
2318
|
runtimeParseF64, runtimeParseUsize, runtimeParseI32, runtimeStr2Bool, runtimeList2Var,
|
|
2066
2319
|
scanProcedures, compile_proc_bodies, loadExtensionSource, api: null
|
|
@@ -2089,7 +2342,7 @@ class rcompiler {
|
|
|
2089
2342
|
const BUNDLED = ['strings', 'utilities']; // 已并入标准表
|
|
2090
2343
|
for (const name of exts) {
|
|
2091
2344
|
if (BUNDLED.includes(name)) continue;
|
|
2092
|
-
if (name === 'rcompiler' || name === 'pen') continue; // 内置
|
|
2345
|
+
if (name === 'rcompiler' || name === 'pen' || name === 'music') continue; // 内置
|
|
2093
2346
|
// "调试→自动忽略扩展":不加载源码(含不执行其编译期代码、不注册其依赖)
|
|
2094
2347
|
if (S.ignoreExt.has(name)) { console.warn(`\x1b[33m已忽略扩展\x1b[m: ${name}`); continue; }
|
|
2095
2348
|
const url = urls[name];
|
|
@@ -2145,6 +2398,24 @@ class rcompiler {
|
|
|
2145
2398
|
|
|
2146
2399
|
// phase 3: 广播接收帽(先编译,保证发送方可引用;模组广播照常可达)
|
|
2147
2400
|
// 广播接收脚本会在原型与全部克隆实例上运行(对照 startHats)
|
|
2401
|
+
// 3a: 预分配全部接收帽函数名并注册——帽的 sb3 遍历序可能晚于发送方编译序
|
|
2402
|
+
//(如 "start workspace" 的帽先于 "menu bar" 的帽),不预注册会让
|
|
2403
|
+
// event_broadcast 查不到接收者而整段 spawn 丢失(Scratch 3 Emulator 实测)
|
|
2404
|
+
for (const target of targets) {
|
|
2405
|
+
S.targetID = targets.indexOf(target);
|
|
2406
|
+
for (const bid in (target.blocks || {})) {
|
|
2407
|
+
const b = target.blocks[bid];
|
|
2408
|
+
if (!b || b.opcode !== 'event_whenbroadcastreceived') continue;
|
|
2409
|
+
const bname = String(b.fields.BROADCAST_OPTION[0]);
|
|
2410
|
+
if (!S.broadcastScripts.has(bname)) S.broadcastScripts.set(bname, []);
|
|
2411
|
+
S.bccount++;
|
|
2412
|
+
const fname = S.fnName('bc_' + S.bccount);
|
|
2413
|
+
S.broadcastScripts.get(bname).push(fname);
|
|
2414
|
+
S.broadcastFnTi.set(fname, S.targetID);
|
|
2415
|
+
S.broadcastFnByBlock.set(b, fname);
|
|
2416
|
+
}
|
|
2417
|
+
}
|
|
2418
|
+
// 3b: 编译帽体(复用预分配函数名)
|
|
2148
2419
|
for (const target of targets) {
|
|
2149
2420
|
S.targetID = targets.indexOf(target);
|
|
2150
2421
|
S.curKind = 'broadcast';
|
|
@@ -2188,7 +2459,7 @@ class rcompiler {
|
|
|
2188
2459
|
if (!b || b.opcode !== 'procedures_call' || !b.topLevel) continue;
|
|
2189
2460
|
if (!b.mutation || b.mutation.rc_shape !== 'hat') continue;
|
|
2190
2461
|
const def = resolveProc(String(b.mutation.proccode), S.targetID);
|
|
2191
|
-
if (!def) {
|
|
2462
|
+
if (!def) { warnUndefProc(b.mutation.proccode); continue; }
|
|
2192
2463
|
S.hatcount++;
|
|
2193
2464
|
const fname = S.fnName('hatcall' + S.hatcount);
|
|
2194
2465
|
S.curKind = 'main';
|
|
@@ -2362,7 +2633,7 @@ class rcompiler {
|
|
|
2362
2633
|
profile.monitorsActive = monActive;
|
|
2363
2634
|
emit.extra(`pub static RCOMPILER_MONITORS: &[MonitorInfo] = &[${monRows.join(',')}];`);
|
|
2364
2635
|
emit.func(`pub fn rcompiler_monitor_get(&self, idx: usize) -> Vec<String> {\nmatch idx {\n${getArms.join('\n')}\n_ => Vec::new()\n}\n}`);
|
|
2365
|
-
emit.func(`pub fn rcompiler_monitor_set(&self, idx: usize, v: f64) {\nmatch idx {\n${setArms.join('\n')}\n_ => {}\n}\n}`);
|
|
2636
|
+
emit.func(`pub fn rcompiler_monitor_set(&self, idx: usize, ${setArms.length ? 'v' : '_v'}: f64) {\nmatch idx {\n${setArms.join('\n')}\n_ => {}\n}\n}`);
|
|
2366
2637
|
}
|
|
2367
2638
|
if (!profile.hasStage && Array.isArray(profile.monitors) && profile.monitors.some(m => m.visible !== false)) {
|
|
2368
2639
|
console.warn('\x1b[33m监视器需要舞台模块(当前项目未启用舞台),已跳过全部监视器\x1b[m');
|
|
@@ -2378,7 +2649,6 @@ class rcompiler {
|
|
|
2378
2649
|
for (let i = 0; i < 4; i++) words.push('0x' + (obfKeyWord(i) ^ OBF_MASKS[i]).toString(16));
|
|
2379
2650
|
const rows = S.strlist.map(s => `&${strBytes(s)}`);
|
|
2380
2651
|
arcRuntime.push(
|
|
2381
|
-
'// ---- rcompiler 抗逆向(字符串/资产密文) ----',
|
|
2382
2652
|
`pub const RCOMPILER_OBF: bool = true;`,
|
|
2383
2653
|
// 存储 = 原始密钥 ^ 掩码(避免密钥以连续明文进 .rodata);取用时先异或回掩码
|
|
2384
2654
|
`pub const RCOMPILER_OBF_KEY: [u64; 4] = [${words.join(', ')}];`,
|
|
@@ -2412,7 +2682,6 @@ class rcompiler {
|
|
|
2412
2682
|
);
|
|
2413
2683
|
} else {
|
|
2414
2684
|
arcRuntime.push(
|
|
2415
|
-
'// ---- rcompiler 抗逆向运行时(正常/调试模式为恒等实现) ----',
|
|
2416
2685
|
'pub const RCOMPILER_OBF: bool = false;',
|
|
2417
2686
|
'pub fn rcompiler_txt(data: &[u8]) -> String {',
|
|
2418
2687
|
' String::from_utf8_lossy(data).into_owned()',
|
|
@@ -2432,8 +2701,7 @@ class rcompiler {
|
|
|
2432
2701
|
if (multi()) emit.extra(preludes.taskMulti);
|
|
2433
2702
|
// 舞台多任务:克隆实例注册表(广播分发到全部克隆,对照 startHats)
|
|
2434
2703
|
if (multi() && profile.hasStage) {
|
|
2435
|
-
emit.postStruct = [
|
|
2436
|
-
pub static RCOMPILER_CLONE_TASKS: std::sync::Mutex<Vec<(usize, std::sync::Weak<Default>)>> = std::sync::Mutex::new(Vec::new());
|
|
2704
|
+
emit.postStruct = [`pub static RCOMPILER_CLONE_TASKS: std::sync::Mutex<Vec<(usize, std::sync::Weak<Default>)>> = std::sync::Mutex::new(Vec::new());
|
|
2437
2705
|
pub fn rcompiler_clone_track(me: std::sync::Arc<Default>) {
|
|
2438
2706
|
let mut t = RCOMPILER_CLONE_TASKS.lock().unwrap();
|
|
2439
2707
|
let si = me.sprite_index;
|