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.
- package/CHANGELOG.md +31 -0
- package/CONTRIBUTING.md +38 -0
- package/LICENSE +15 -0
- package/README.md +170 -2
- package/SECURITY.md +27 -0
- package/assets/placeholder.png +0 -0
- package/docs/ARCHITECTURE.md +74 -0
- package/docs/CLI.md +67 -0
- package/docs/COMPATIBILITY.md +29 -0
- package/docs/CONFIG.md +73 -0
- package/docs/DEBUGGING.md +46 -0
- package/docs/NATIVE.md +110 -0
- package/docs/ROADMAP.md +12 -0
- package/docs/TESTING.md +55 -0
- package/exts/args.js +142 -0
- package/exts/freya.js +430 -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/exts/rcompilerExt.js +1396 -0
- package/exts/vartypeany.js +131 -0
- package/package.json +50 -4
- package/src/analysis.js +571 -0
- package/src/assets.js +335 -0
- package/src/cli.js +359 -0
- package/src/emit.js +353 -0
- package/src/mods.js +146 -0
- package/src/preludes.js +4174 -0
- package/src/rcompiler.js +2785 -0
- package/src/standard.js +1452 -0
- package/src/targets.js +129 -0
- package/src/web.js +1593 -0
package/src/rcompiler.js
ADDED
|
@@ -0,0 +1,2785 @@
|
|
|
1
|
+
// rCompiler V2 — 核心编译器
|
|
2
|
+
// 类型系统(TypeInput)、变量表、编译编排、扩展注册。
|
|
3
|
+
// 依赖模块:analysis(Profile) / emit(发射) / standard(标准积木表)。
|
|
4
|
+
|
|
5
|
+
'use strict';
|
|
6
|
+
const fs = require('fs');
|
|
7
|
+
const path = require('path');
|
|
8
|
+
const https = require('https');
|
|
9
|
+
const crypto = require('crypto');
|
|
10
|
+
const JSZip = require('jszip');
|
|
11
|
+
const { analyze, isIgnoredExtOp } = require('./analysis');
|
|
12
|
+
const { Emit } = require('./emit');
|
|
13
|
+
const { registerStandard } = require('./standard');
|
|
14
|
+
const { applyMods } = require('./mods');
|
|
15
|
+
const pkg = require('../package.json');
|
|
16
|
+
|
|
17
|
+
// ---------------- sb3 读取 ----------------
|
|
18
|
+
async function readProject(zipFilePath) {
|
|
19
|
+
const data = fs.readFileSync(zipFilePath);
|
|
20
|
+
if (path.extname(zipFilePath) === '.json') return JSON.parse(data.toString('utf-8'));
|
|
21
|
+
const zip = new JSZip();
|
|
22
|
+
await zip.loadAsync(data);
|
|
23
|
+
const projectJson = await zip.file('project.json');
|
|
24
|
+
if (!projectJson) throw new Error('不是有效的Scratch项目文件');
|
|
25
|
+
return JSON.parse(await projectJson.async('string'));
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
async function readZipBuffer(zipFilePath) {
|
|
29
|
+
try { return fs.readFileSync(zipFilePath); } catch (e) { return null; }
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// ---------------- 编译器类 ----------------
|
|
33
|
+
class rcompiler {
|
|
34
|
+
version() { return pkg.version; }
|
|
35
|
+
compilertype() { return 'selective'; }
|
|
36
|
+
|
|
37
|
+
async compile(jsonData, folderPath, fileName, opts = {}) {
|
|
38
|
+
const log = !!opts.log;
|
|
39
|
+
// 模组系统:展开 modconfigs.json 引用的模组包 targets(替代旧 rcompiler_import 引用系统)
|
|
40
|
+
if (opts.zipBuffer) {
|
|
41
|
+
try {
|
|
42
|
+
const loaded = await applyMods(jsonData, opts.zipBuffer);
|
|
43
|
+
if (loaded.mods.length) opts.modFiles = loaded.assetFiles;
|
|
44
|
+
} catch (e) {
|
|
45
|
+
console.warn('\x1b[33m模组加载失败\x1b[m', e.message);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
const profile = analyze(jsonData, {
|
|
49
|
+
frame: opts.frame, stage: opts.stage, frameRate: opts.frameRate,
|
|
50
|
+
interpolation: opts.interpolation, antiReverse: opts.antiReverse,
|
|
51
|
+
app: opts.app, ignoreExt: opts.ignoreExt, target: opts.target
|
|
52
|
+
});
|
|
53
|
+
// Web 后端暂不做资产混淆:资产由 JS 宿主直接读取原始文件
|
|
54
|
+
if (profile.backend === 'web' && profile.antiReverse === 'obf') {
|
|
55
|
+
console.warn('\x1b[33mWASM 后端暂不支持混淆模式,已回退 normal\x1b[m');
|
|
56
|
+
profile.antiReverse = 'normal';
|
|
57
|
+
}
|
|
58
|
+
const emit = new Emit(profile);
|
|
59
|
+
const targets = jsonData.targets || [];
|
|
60
|
+
const antiReverse = profile.antiReverse || 'normal';
|
|
61
|
+
const obf = antiReverse === 'obf';
|
|
62
|
+
const debug = antiReverse === 'debug';
|
|
63
|
+
|
|
64
|
+
// ============ 上下文 ============
|
|
65
|
+
const S = {
|
|
66
|
+
profile, emit, jsonData, targets,
|
|
67
|
+
folderPath, fileName,
|
|
68
|
+
frame: profile.frame,
|
|
69
|
+
targetID: -1,
|
|
70
|
+
curKind: 'main',
|
|
71
|
+
selfmut: false,
|
|
72
|
+
ignore: false,
|
|
73
|
+
blockcount: 0,
|
|
74
|
+
flagcount: 0, presscount: 0, proccount: 0, clonecount: 0,
|
|
75
|
+
foreachcount: 0, bccount: 0, clickcount: 0,
|
|
76
|
+
keywords: new Map(), // 原始名 -> 顺序整数
|
|
77
|
+
keywordOnlys: new Map(), // 原始名 -> 稳定 id
|
|
78
|
+
vars: new Map(), lists: new Map(),
|
|
79
|
+
writtenVars: new Set(), writtenLists: new Set(),
|
|
80
|
+
varWriteKind: new Map(), // 变量 id -> {num, str}(写值数值性预扫描,供 String 声明自动数值化)
|
|
81
|
+
autoNumVars: [], // 由 String 自动升级为 f64 的变量名(--profile 报告)
|
|
82
|
+
procdefs: [], // {proccode, parsed, names, types, target, block}
|
|
83
|
+
procbycode: new Map(), // proccode -> def
|
|
84
|
+
broadcastScripts: new Map(), // broadcastName -> [fnName]
|
|
85
|
+
broadcastFnByBlock: new Map(), // 帽块对象 -> 预分配函数名(phase 3 预注册)
|
|
86
|
+
broadcastFnTi: new Map(), // fnName -> targetIndex(任务跟踪用)
|
|
87
|
+
clonesByTarget: new Map(), // targetIndex -> [fnName]
|
|
88
|
+
cloneTargetsUsed: new Set(),
|
|
89
|
+
cloneFnsByTarget: new Map(), // targetIndex -> [fnName](预分配,供递归图)
|
|
90
|
+
cloneFnInfo: new Map(), // fnName -> {callees:Set, spawns, recursive}
|
|
91
|
+
cloneFnNameByBlock: new Map(),// 克隆帽块 id -> 预分配函数名
|
|
92
|
+
inuselist: [],
|
|
93
|
+
customproc: null, // 当前正在编译的过程(用于 argument reporter)
|
|
94
|
+
procBranches: null, // 变体编译期:参数名 -> 分支代码(%c/起动帽体)
|
|
95
|
+
stageIdxOverride: null, // 变体编译期:舞台桥接 idx 表达式覆盖(如 __rcaller)
|
|
96
|
+
variantCount: 0, hatcount: 0,
|
|
97
|
+
antiReverse, obf, debug,
|
|
98
|
+
ignoreExt: profile.ignoreExt instanceof Set ? profile.ignoreExt : new Set(),
|
|
99
|
+
strtab: new Map(), // 混淆:字符串表 value -> index
|
|
100
|
+
strlist: [], // 混淆:字符串表(按注册顺序)
|
|
101
|
+
compileEvents: [
|
|
102
|
+
'event_whenflagclicked', 'event_whenkeypressed',
|
|
103
|
+
'event_whenbroadcastreceived', 'event_whenthisspriteclicked',
|
|
104
|
+
'event_whenbackdropswitchesto',
|
|
105
|
+
'rcompiler_setmain', 'rcompiler_setruntime', 'rcompiler_extdef', 'rcompiler_func'
|
|
106
|
+
],
|
|
107
|
+
noAutoInput: ['procedures_prototype', 'control_create_clone_of_menu',
|
|
108
|
+
'control_run_as_sprite_menu', 'sound_sounds_menu', 'looks_costume',
|
|
109
|
+
'looks_backdrops', 'motion_pointtowards_menu', 'motion_goto_menu',
|
|
110
|
+
'motion_glideto_menu', 'sensing_touchingobjectmenu', 'sensing_keyoptions',
|
|
111
|
+
'sensing_of_object_menu', 'pen_menu_colorParam',
|
|
112
|
+
'music_menu_DRUM', 'music_menu_INSTRUMENT',
|
|
113
|
+
'control_create_clone_of_menu', 'event_whenkeypressed'],
|
|
114
|
+
inputlist: [
|
|
115
|
+
'sensing_answer', 'operator_equals', 'operator_subtract', 'operator_add',
|
|
116
|
+
'operator_divide', 'operator_multiply', 'operator_join', 'operator_random',
|
|
117
|
+
'operator_gt', 'operator_lt', 'operator_and', 'operator_or', 'operator_not',
|
|
118
|
+
'operator_contains', 'operator_letter_of', 'operator_length', 'operator_mod',
|
|
119
|
+
'operator_round', 'operator_mathop', 'sensing_timer', 'sensing_dayssince2000',
|
|
120
|
+
'sensing_current', 'argument_reporter_string_number', 'argument_reporter_boolean',
|
|
121
|
+
'data_itemoflist', 'data_itemnumoflist', 'data_lengthoflist',
|
|
122
|
+
'data_listcontainsitem', 'control_create_clone_of_menu', 'control_run_as_sprite_menu',
|
|
123
|
+
'rcompiler_user', 'rcompiler_compilerversion', 'rcompiler_varget', 'rcompiler_typeas', 'rcompiler_typeis',
|
|
124
|
+
'rcompiler_typechoose', 'rcompiler_typeof', 'procedures_call'
|
|
125
|
+
],
|
|
126
|
+
operatorlist: [
|
|
127
|
+
'operator_equals', 'operator_subtract', 'operator_add', 'operator_divide',
|
|
128
|
+
'operator_multiply', 'operator_join', 'operator_gt', 'operator_lt',
|
|
129
|
+
'operator_and', 'operator_or', 'operator_not', 'operator_mod'
|
|
130
|
+
],
|
|
131
|
+
compiles: {}, inputscompiles: {}
|
|
132
|
+
};
|
|
133
|
+
|
|
134
|
+
// ============ 抗逆向 / 调试工具 ============
|
|
135
|
+
const RUST_KEYWORDS = new Set(['as', 'break', 'const', 'continue', 'crate', 'dyn', 'else', 'enum',
|
|
136
|
+
'extern', 'false', 'fn', 'for', 'if', 'impl', 'in', 'let', 'loop', 'match', 'mod', 'move', 'mut',
|
|
137
|
+
'pub', 'ref', 'return', 'self', 'Self', 'static', 'struct', 'super', 'trait', 'true', 'type',
|
|
138
|
+
'unsafe', 'use', 'where', 'while', 'async', 'await', 'box', 'final', 'macro', 'override', 'priv',
|
|
139
|
+
'try', 'typeof', 'unsized', 'virtual', 'yield', 'abstract', 'become', 'do']);
|
|
140
|
+
function targetNameOf(ti) {
|
|
141
|
+
const t = targets[ti];
|
|
142
|
+
return t ? String(t.name || ('target' + ti)) : ('target' + ti);
|
|
143
|
+
}
|
|
144
|
+
function sanitizeIdent(s) {
|
|
145
|
+
let t = String(s == null ? '' : s).replace(/[^\p{L}\p{N}_]/gu, '_');
|
|
146
|
+
if (!t || /^\p{N}/u.test(t)) t = '_' + t;
|
|
147
|
+
if (RUST_KEYWORDS.has(t)) t = 'z_' + t;
|
|
148
|
+
return t;
|
|
149
|
+
}
|
|
150
|
+
// 调试模式:脚本/过程/克隆函数名带角色名与目标序号(可读且不冲突)
|
|
151
|
+
function dbgFnAt(ti, base) {
|
|
152
|
+
return debug ? `${sanitizeIdent(targetNameOf(ti))}_${ti}__${base}` : base;
|
|
153
|
+
}
|
|
154
|
+
function dbgFn(base) {
|
|
155
|
+
return dbgFnAt(S.targetID, base);
|
|
156
|
+
}
|
|
157
|
+
S.fnName = dbgFn;
|
|
158
|
+
S.fnNameAt = dbgFnAt;
|
|
159
|
+
// 字符串字面量:正常/调试 → 内联;混淆 → 密文表索引(rcompiler_str 返回 &'static str)
|
|
160
|
+
function strlit(s) {
|
|
161
|
+
const v = String(s == null ? '' : s);
|
|
162
|
+
if (!obf) return JSON.stringify(v);
|
|
163
|
+
if (!S.strtab.has(v)) { S.strtab.set(v, S.strlist.length); S.strlist.push(v); }
|
|
164
|
+
return `rcompiler_str(${S.strtab.get(v)})`;
|
|
165
|
+
}
|
|
166
|
+
S.strlit = strlit;
|
|
167
|
+
|
|
168
|
+
// ============ 混淆:密钥与逐字节加密(与 Rust 端 rcompiler_kb 严格一致) ============
|
|
169
|
+
// 密钥 32 字节按 4 个 u64 小端存放;每个 u64 再与固定掩码异或后作为常量发射,
|
|
170
|
+
// 避免密钥以连续明文出现在 .rodata。逐字节再混入位置相关值,破坏文件签名扫描。
|
|
171
|
+
const OBF_MASKS = [0x9E3779B97F4A7C15n, 0xC2B2AE3D27D4EB4Fn, 0x165667B19E3779F9n, 0x27D4EB2F165667C5n];
|
|
172
|
+
const obfKey = obf ? crypto.randomBytes(32) : null;
|
|
173
|
+
function obfKeyWord(wi) {
|
|
174
|
+
let w = 0n;
|
|
175
|
+
for (let j = 0; j < 8; j++) w |= BigInt(obfKey[wi * 8 + j]) << BigInt(8 * j);
|
|
176
|
+
return w;
|
|
177
|
+
}
|
|
178
|
+
function obfKeyByte(i) {
|
|
179
|
+
const word = obfKeyWord((i >> 3) % 4);
|
|
180
|
+
const b = Number((word >> BigInt((i % 8) * 8)) & 0xffn);
|
|
181
|
+
return b ^ (((i * 31) & 0xff) ^ 0xA5);
|
|
182
|
+
}
|
|
183
|
+
function obfEncrypt(bytes) {
|
|
184
|
+
return bytes.map((b, i) => b ^ obfKeyByte(i));
|
|
185
|
+
}
|
|
186
|
+
// 静态字节数组字面量(造型/声音/角色名;混淆时写密文)
|
|
187
|
+
function strBytes(s) {
|
|
188
|
+
const bytes = [...Buffer.from(String(s == null ? '' : s), 'utf8')];
|
|
189
|
+
const data = obf ? obfEncrypt(bytes) : bytes;
|
|
190
|
+
return `[${data.join(',')}]`;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
const multi = () => S.profile.concurrency === 'multi';
|
|
194
|
+
const isStageMode = () => S.profile.hasStage;
|
|
195
|
+
// 模组角色(mods//<模组名>//<角色名>):绿旗/起动帽/点击帽不随工程启动
|
|
196
|
+
const isModTarget = (t) => t && (t.isRcModTarget === true || String(t.name || '').startsWith('mods//'));
|
|
197
|
+
|
|
198
|
+
// ============ 帧门控代码生成 ============
|
|
199
|
+
// 循环/等待处的帧等待语句;未启用帧门控时为空(保持旧产物)
|
|
200
|
+
function frameWaitStmt() {
|
|
201
|
+
if (!S.frame || !S.frame.gate) return '';
|
|
202
|
+
if (multi()) return 'if !rcompiler_in_warp() { self.frame_wait().await; }\n';
|
|
203
|
+
return 'if !rcompiler_in_warp() { rcompiler_frame_wait(); }\n';
|
|
204
|
+
}
|
|
205
|
+
// spawn 包裹:任务局部 warp 深度从 0 开始(克隆/广播线程不继承)
|
|
206
|
+
function spawnScript(inner) {
|
|
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;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
// ============ 名称工具 ============
|
|
216
|
+
function kw(name) {
|
|
217
|
+
if (!S.keywords.has(name)) S.keywords.set(name, S.keywords.size + 1);
|
|
218
|
+
return S.keywords.get(name);
|
|
219
|
+
}
|
|
220
|
+
function kwParse(name) { return kw(name); }
|
|
221
|
+
function keywordOnly(name) {
|
|
222
|
+
if (!S.keywordOnlys.has(name)) S.keywordOnlys.set(name, S.keywordOnlys.size + 1);
|
|
223
|
+
return 'k' + S.keywordOnlys.get(name);
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
// ============ 预扫描:写变量标记 ============
|
|
227
|
+
const WRITE_VAR_OPS = new Set(['data_setvariableto', 'data_changevariableby', 'control_for_each']);
|
|
228
|
+
const WRITE_LIST_OPS = new Set(['data_addtolist', 'data_deletealloflist', 'data_deleteoflist', 'data_insertatlist', 'data_replaceitemoflist']);
|
|
229
|
+
// 写值数值性浅分类(保守,思路同过程参数 classifyArgNum):true=可证 JS 数值。
|
|
230
|
+
// 算术运算结果恒为数值;未类型化变量/字符串/未知报告器一律 false。
|
|
231
|
+
// 注意此时 S.vars 尚未注册,类型声明直接查 profile.typeDeclared(ti:name 键)。
|
|
232
|
+
const NUM_RESULT_OPS = new Set(['operator_add', 'operator_subtract', 'operator_multiply', 'operator_divide',
|
|
233
|
+
'operator_mod', 'operator_random', 'operator_mathop', 'operator_round',
|
|
234
|
+
'operator_abs', 'operator_floor', 'operator_ceiling', 'operator_sqrt',
|
|
235
|
+
'sensing_dayssince2000', 'sensing_timer', 'data_lengthoflist', 'data_itemnumoflist']);
|
|
236
|
+
const declaredNumByName = (tname, ti, isGlobal, getMap) => {
|
|
237
|
+
let dec = getMap.get(ti + ':' + tname);
|
|
238
|
+
if (!dec && !isGlobal) dec = getMap.get('0:' + tname);
|
|
239
|
+
return dec === 'f64' || dec === 'i32' || dec === 'usize';
|
|
240
|
+
};
|
|
241
|
+
const writeValIsNum = (b, t, ti) => {
|
|
242
|
+
const val = b.inputs && b.inputs.VALUE;
|
|
243
|
+
if (!val || !Array.isArray(val) || val.length < 2) return false;
|
|
244
|
+
const x = val[1];
|
|
245
|
+
if (Array.isArray(x)) {
|
|
246
|
+
const code = x[0];
|
|
247
|
+
if (code === 4 || code === 5 || code === 6) return true; // 数字字面量
|
|
248
|
+
if (code === 10 || code === 8 || code === 9) return false; // 文本/颜色
|
|
249
|
+
if (code === 12) return declaredNumByName(String(x[1]), ti, !!t.isStage, S.profile.typeDeclared);
|
|
250
|
+
if (code === 13) return declaredNumByName(String(x[1]), ti, !!t.isStage, S.profile.listTypeDeclared);
|
|
251
|
+
return false;
|
|
252
|
+
}
|
|
253
|
+
const blk = t.blocks[x];
|
|
254
|
+
if (!blk) return false;
|
|
255
|
+
if (NUM_RESULT_OPS.has(blk.opcode)) return true;
|
|
256
|
+
if (blk.opcode === 'data_variable') {
|
|
257
|
+
const nm = blk.fields && blk.fields.VARIABLE && blk.fields.VARIABLE[0];
|
|
258
|
+
return nm != null && declaredNumByName(String(nm), ti, !!t.isStage, S.profile.typeDeclared);
|
|
259
|
+
}
|
|
260
|
+
if (blk.opcode === 'data_itemoflist') {
|
|
261
|
+
const nm = blk.fields && blk.fields.LIST && blk.fields.LIST[0];
|
|
262
|
+
return nm != null && declaredNumByName(String(nm), ti, !!t.isStage, S.profile.listTypeDeclared);
|
|
263
|
+
}
|
|
264
|
+
return false;
|
|
265
|
+
};
|
|
266
|
+
// "1.50" 这类非规范字符串形态不能数值化(f64 存储会丢掉字符串形态)
|
|
267
|
+
const canonNumInit = (s) => {
|
|
268
|
+
if (typeof s !== 'string' || !/^-?(\d+\.?\d*|\.\d+)([eE][-+]?\d+)?$/.test(s)) return null;
|
|
269
|
+
const n = Number(s);
|
|
270
|
+
return (isFinite(n) && String(n) === s) ? n : null;
|
|
271
|
+
};
|
|
272
|
+
targets.forEach((t, ti) => {
|
|
273
|
+
for (const bid in (t.blocks || {})) {
|
|
274
|
+
const b = t.blocks[bid];
|
|
275
|
+
if (!b || !b.opcode) continue;
|
|
276
|
+
if (WRITE_VAR_OPS.has(b.opcode) && b.fields && b.fields.VARIABLE) {
|
|
277
|
+
// 键带 target 序号:sb3 变量 id 只保证目标内唯一(本项目 base_costume/i/
|
|
278
|
+
// current_costume 等跨 3-4 个目标撞 id),全局键会让后注册目标覆盖绑定
|
|
279
|
+
const vid = ti + ':' + b.fields.VARIABLE[1];
|
|
280
|
+
S.writtenVars.add(vid);
|
|
281
|
+
let wk = S.varWriteKind.get(vid);
|
|
282
|
+
if (!wk) { wk = { num: 0, str: 0 }; S.varWriteKind.set(vid, wk); }
|
|
283
|
+
if (b.opcode === 'data_setvariableto' ? writeValIsNum(b, t, ti) : true) wk.num++;
|
|
284
|
+
else wk.str++;
|
|
285
|
+
} else if (WRITE_LIST_OPS.has(b.opcode) && b.fields && b.fields.LIST) {
|
|
286
|
+
S.writtenLists.add(ti + ':' + b.fields.LIST[1]);
|
|
287
|
+
} else if (b.opcode === 'rcompiler_varset' || b.opcode === 'rcompiler_varcreate') {
|
|
288
|
+
// 作用域局部变量,非结构体字段
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
});
|
|
292
|
+
|
|
293
|
+
// ============ 舞台/声音字段与常量 ============
|
|
294
|
+
if (profile.hasStage) {
|
|
295
|
+
emit.field('sprite_index', 'usize', 'usize::MAX');
|
|
296
|
+
emit.field('stage', 'std::sync::Arc<StageShared>', 'StageShared::detached()');
|
|
297
|
+
const names = profile.targets.map(t => String(t.name));
|
|
298
|
+
if (obf) {
|
|
299
|
+
// 混淆:角色名密文化,运行时惰性解密(角色名仍可由撞色/碰到角色等积木使用)
|
|
300
|
+
const rows = names.map(n => `&${strBytes(n)}`);
|
|
301
|
+
emit.extra([
|
|
302
|
+
`static RCOMPILER_TARGET_NAME_DATA: &[&[u8]] = &[${rows.join(',')}];`,
|
|
303
|
+
`fn rcompiler_target_names() -> &'static Vec<String> {`,
|
|
304
|
+
` static CACHE: std::sync::OnceLock<Vec<String>> = std::sync::OnceLock::new();`,
|
|
305
|
+
` CACHE.get_or_init(|| RCOMPILER_TARGET_NAME_DATA.iter().map(|b| rcompiler_txt(b)).collect())`,
|
|
306
|
+
`}`,
|
|
307
|
+
`pub fn rcompiler_target_name(i: usize) -> &'static str { rcompiler_target_names().get(i).map(|s| s.as_str()).unwrap_or("") }`,
|
|
308
|
+
`pub fn rcompiler_target_count() -> usize { RCOMPILER_TARGET_NAME_DATA.len() }`
|
|
309
|
+
].join('\n'));
|
|
310
|
+
} else {
|
|
311
|
+
emit.extra([
|
|
312
|
+
`pub const RCOMPILER_TARGET_NAMES: &[&str] = &[${names.map(n => JSON.stringify(n)).join(',')}];`,
|
|
313
|
+
`pub fn rcompiler_target_name(i: usize) -> &'static str { RCOMPILER_TARGET_NAMES.get(i).copied().unwrap_or("") }`,
|
|
314
|
+
`pub fn rcompiler_target_count() -> usize { RCOMPILER_TARGET_NAMES.len() }`
|
|
315
|
+
].join('\n'));
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
// ============ 打包配置常量(窗口/顶栏/退出键) ============
|
|
320
|
+
if (profile.hasStage) {
|
|
321
|
+
const app = profile.app || {};
|
|
322
|
+
const appTitle = String((app.title != null && app.title !== '') ? app.title
|
|
323
|
+
: (opts.projectName || opts.name || fileName || 'rCompiler'));
|
|
324
|
+
const titleExpr = strlit(appTitle);
|
|
325
|
+
const bgHex = String(app.bg || '#000000').replace(/^#/, '');
|
|
326
|
+
const bgU32 = parseInt(bgHex, 16) || 0;
|
|
327
|
+
emit.extra([
|
|
328
|
+
`pub fn rcompiler_app_title() -> &'static str { ${titleExpr} }`,
|
|
329
|
+
`pub const RCOMPILER_WIN_RESIZABLE: bool = ${app.resizable ? 'true' : 'false'};`,
|
|
330
|
+
`pub const RCOMPILER_WIN_FULLSCREEN: bool = ${app.fullscreen ? 'true' : 'false'};`,
|
|
331
|
+
`pub const RCOMPILER_WIN_DECORATIONS: bool = ${app.decorations === false ? 'false' : 'true'};`,
|
|
332
|
+
`pub const RCOMPILER_HIDE_CURSOR: bool = ${app.hideCursor ? 'true' : 'false'};`,
|
|
333
|
+
`pub const RCOMPILER_BTN_FLAG: bool = ${app.btnFlag ? 'true' : 'false'};`,
|
|
334
|
+
`pub const RCOMPILER_BTN_PAUSE: bool = ${app.btnPause ? 'true' : 'false'};`,
|
|
335
|
+
`pub const RCOMPILER_BTN_STOP: bool = ${app.btnStop ? 'true' : 'false'};`,
|
|
336
|
+
`pub const RCOMPILER_AUTOPLAY: bool = ${app.autoplay === false ? 'false' : 'true'};`,
|
|
337
|
+
`pub const RCOMPILER_QUIT_ON_STOP: bool = ${app.quitOnStop ? 'true' : 'false'};`,
|
|
338
|
+
`pub const RCOMPILER_EXIT_KEY: u8 = ${app.exitKey === 'escape' ? 1 : (app.exitKey === 'ctrlq' ? 2 : 0)};`,
|
|
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'};`,
|
|
343
|
+
`pub const RCOMPILER_BG_U32: u32 = 0x${bgU32.toString(16).padStart(6, '0')};`
|
|
344
|
+
].join('\n'));
|
|
345
|
+
}
|
|
346
|
+
if (profile.hasSound) {
|
|
347
|
+
emit.field('audio', 'SoundMixer', 'SoundMixer::new()');
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
// ============ 变量/列表表 ============
|
|
351
|
+
// 字段命名:全局 vf_<kw>/vs_<kw>/l_<kw>;私有 vf_<ti>_<kw>/...
|
|
352
|
+
const initVals = new Map(); // 大列表紧凑初始化运行时(按需注册)
|
|
353
|
+
const UNHEX_RUNTIME = [
|
|
354
|
+
'fn rcompiler_unhex(s: &str) -> Vec<f64> {',
|
|
355
|
+
'let b = s.as_bytes();',
|
|
356
|
+
'let mut out = Vec::with_capacity(b.len() / 2);',
|
|
357
|
+
'let hv = |c: u8| -> f64 { match c { b\'0\'..=b\'9\' => (c - b\'0\') as f64, b\'a\'..=b\'f\' => (c - b\'a\' + 10) as f64, b\'A\'..=b\'F\' => (c - b\'A\' + 10) as f64, _ => 0.0 } };',
|
|
358
|
+
'let mut i = 0;',
|
|
359
|
+
'while i + 2 <= b.len() { out.push(hv(b[i]) * 16.0 + hv(b[i + 1])); i += 2; }',
|
|
360
|
+
'out',
|
|
361
|
+
'}'].join('\n');
|
|
362
|
+
const RLE_RUNTIME = [
|
|
363
|
+
'fn rcompiler_rle_f64(pairs: &[(f64, usize)]) -> Vec<f64> {',
|
|
364
|
+
'let mut out: Vec<f64> = Vec::with_capacity(pairs.iter().map(|p| p.1).sum());',
|
|
365
|
+
'for (v, cnt) in pairs { for _ in 0..*cnt { out.push(*v); } }',
|
|
366
|
+
'out',
|
|
367
|
+
'}'].join('\n');
|
|
368
|
+
const SPLIT_RUNTIME = [
|
|
369
|
+
'fn rcompiler_split_strings(s: &str, sep: char) -> Vec<String> {',
|
|
370
|
+
'if s.is_empty() { return vec![]; }',
|
|
371
|
+
's.split(sep).map(|x| x.to_string()).collect()',
|
|
372
|
+
'}'].join('\n');
|
|
373
|
+
const LEN_RUNTIME = [
|
|
374
|
+
'fn rcompiler_len_decode(s: &str) -> Vec<String> {',
|
|
375
|
+
'let mut out: Vec<String> = Vec::new();',
|
|
376
|
+
'let mut it = s.chars();',
|
|
377
|
+
'while let Some(d) = it.next() {',
|
|
378
|
+
'let n = d.to_digit(10).unwrap_or(0) as usize;',
|
|
379
|
+
'let mut item = String::with_capacity(n);',
|
|
380
|
+
'for _ in 0..n { item.push(it.next().unwrap_or(\'\\u{0}\')); }',
|
|
381
|
+
'out.push(item);',
|
|
382
|
+
'}',
|
|
383
|
+
'out',
|
|
384
|
+
'}'].join('\n');
|
|
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) => {
|
|
402
|
+
const vars = t.variables || {};
|
|
403
|
+
for (const id in vars) {
|
|
404
|
+
const val = vars[id][1];
|
|
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) });
|
|
408
|
+
}
|
|
409
|
+
});
|
|
410
|
+
// 调试模式:字段名带原变量名(vf_<原名>_<kw>),否则保持稳定短名
|
|
411
|
+
function varFieldBase(name, kwv) {
|
|
412
|
+
return debug ? `${sanitizeIdent(name)}_${kwv}` : String(kwv);
|
|
413
|
+
}
|
|
414
|
+
function buildVarField(v) {
|
|
415
|
+
const pre = v.isGlobal ? '' : (v.ti + '_');
|
|
416
|
+
const base = varFieldBase(v.name, v.kw);
|
|
417
|
+
return { f: `vf_${pre}${base}`, s: `vs_${pre}${base}` };
|
|
418
|
+
}
|
|
419
|
+
function listFieldName(name, kwv, pre) {
|
|
420
|
+
return `l_${pre}${debug ? `${sanitizeIdent(name)}_${kwv}` : kwv}`;
|
|
421
|
+
}
|
|
422
|
+
targets.forEach((t, ti) => {
|
|
423
|
+
const isGlobal = !!t.isStage;
|
|
424
|
+
const vars = t.variables || {};
|
|
425
|
+
for (const id in vars) {
|
|
426
|
+
const [name] = vars[id];
|
|
427
|
+
const iv = initVals.get(ti + ':' + id) || { num: null, str: '' };
|
|
428
|
+
const v = {
|
|
429
|
+
id, ti, name, kw: kw(name), isGlobal,
|
|
430
|
+
// written/wk 聚合:全局变量可被任意目标写入(预扫描按写入方 ti:id 记键),
|
|
431
|
+
// 归属判定按 id 后缀跨键聚合(同 id 跨目标的旁路命中只会过度加锁,语义仍正确)
|
|
432
|
+
declared: null, written: writtenFlagFor(id),
|
|
433
|
+
initNum: iv.num, initStr: iv.str
|
|
434
|
+
};
|
|
435
|
+
// 类型声明解析:声明块所在 target 的同名变量,或舞台上的同名变量
|
|
436
|
+
let dec = S.profile.typeDeclared.get(ti + ':' + name);
|
|
437
|
+
if (!dec && !isGlobal) dec = S.profile.typeDeclared.get('0:' + name);
|
|
438
|
+
// String 声明变量若"全部写入可证数值且初值已是规范数值形态",自动升级为
|
|
439
|
+
// f64——存储值恒为 rcompiler_num_str 规范形态,字符串读侧格式化产出逐字节一致,
|
|
440
|
+
// 数值读侧省去每次 String 克隆+解析(ALU 写回通道等热路径的主要残余)。
|
|
441
|
+
// 任一处写入不可证数值、或初值是非规范字符串(如 "1.50"、"0x0D")则保持 String。
|
|
442
|
+
if (dec === 'String') {
|
|
443
|
+
const wk = writeKindFor(id);
|
|
444
|
+
const initN = iv.num != null ? iv.num : canonNumInit(iv.str);
|
|
445
|
+
if (wk && wk.num > 0 && wk.str === 0 && initN != null) {
|
|
446
|
+
v.declared = 'f64';
|
|
447
|
+
v.initNum = initN;
|
|
448
|
+
v.initStr = null;
|
|
449
|
+
S.autoNumVars.push(`${t.name}:${name}`);
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
v.declared = v.declared || dec;
|
|
453
|
+
// 共享可变性:所有脚本任务共享同一个 Arc<Default>(克隆同实例),赋值需要
|
|
454
|
+
// 内部可变性——但 Mutex::lock(每次 ~20ns × 每指令 ~50 次)远贵于 RcompilerCell(RefCell)
|
|
455
|
+
// 标志检查(~3ns)。协作式单线程下借用从不跨 await(编译器锁纪律保证),
|
|
456
|
+
// RcompilerCell 冲突在结构上不可能发生。
|
|
457
|
+
v.locked = multi() && v.written;
|
|
458
|
+
const f = buildVarField(v);
|
|
459
|
+
v.f = f.f; v.s = f.s;
|
|
460
|
+
S.vars.set(ti + ':' + id, v);
|
|
461
|
+
registerVarFields(v);
|
|
462
|
+
}
|
|
463
|
+
const lists = t.lists || {};
|
|
464
|
+
for (const id in lists) {
|
|
465
|
+
const [name, items] = lists[id];
|
|
466
|
+
let dec = S.profile.listTypeDeclared.get(ti + ':' + name);
|
|
467
|
+
if (!dec && !isGlobal) dec = S.profile.listTypeDeclared.get('0:' + name);
|
|
468
|
+
const pre = isGlobal ? '' : (ti + '_');
|
|
469
|
+
const l = {
|
|
470
|
+
id, ti, name, kw: kw(name), isGlobal,
|
|
471
|
+
declared: dec && dec !== 'String' ? dec : null, // 'f64' 等
|
|
472
|
+
written: writtenListFor(id),
|
|
473
|
+
f: listFieldName(name, kw(name), pre)
|
|
474
|
+
};
|
|
475
|
+
l.locked = multi() && l.written; // 同变量:RcompilerCell 共享可变性
|
|
476
|
+
S.lists.set(ti + ':' + id, l);
|
|
477
|
+
registerListFields(l, items || []);
|
|
478
|
+
}
|
|
479
|
+
});
|
|
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
|
+
|
|
632
|
+
function registerVarFields(v) {
|
|
633
|
+
// 未类型化变量:单枚举存储(Scratch 的 JS 值模型——一个变量就是一个值,
|
|
634
|
+
// 数字或字符串)。相比双 vf/vs 轨:setNum/setStr 各省一次格式化/解析,
|
|
635
|
+
// 且严格保持非规范字符串形态(如 "1.50"、"0x0D")的原样保留。
|
|
636
|
+
if (!v.declared) {
|
|
637
|
+
runtimeRcompilerV();
|
|
638
|
+
emit.field(v.f, v.locked ? `std::sync::Arc<RcompilerCell<RcompilerV>>` : 'RcompilerV',
|
|
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);
|
|
642
|
+
return;
|
|
643
|
+
}
|
|
644
|
+
if (v.declared === 'String') {
|
|
645
|
+
emit.field(v.s, v.locked ? `std::sync::Arc<RcompilerCell<String>>` : 'String',
|
|
646
|
+
v.locked ? `std::sync::Arc::new(RcompilerCell { v: std::cell::RefCell::new(${initStringOf(v)}) })` : initStringOf(v));
|
|
647
|
+
} else if (v.declared === 'bool') {
|
|
648
|
+
emit.field(v.f, v.locked ? `std::sync::Arc<RcompilerCell<bool>>` : 'bool',
|
|
649
|
+
v.locked ? `std::sync::Arc::new(RcompilerCell { v: std::cell::RefCell::new(false) })` : 'false');
|
|
650
|
+
} else { // f64 / i32 / usize
|
|
651
|
+
emit.field(v.f, v.locked ? `std::sync::Arc<RcompilerCell<${v.declared}>>` : v.declared,
|
|
652
|
+
v.locked ? `std::sync::Arc::new(RcompilerCell { v: std::cell::RefCell::new(${numInit(v.declared, v.initNum)}) })` : numInit(v.declared, v.initNum));
|
|
653
|
+
}
|
|
654
|
+
// 克隆语义:全局锁定字段保持 Arc 共享(clone_default 按 cloneSharedFields 判定)
|
|
655
|
+
if (v.locked && v.isGlobal) emit.cloneSharedFields.add(v.declared === 'String' ? v.s : v.f);
|
|
656
|
+
}
|
|
657
|
+
// 未类型化变量的单值枚举(对照 scratch-vm:变量持有一个 JS 值)
|
|
658
|
+
// RcompilerCell:RefCell 的协作单线程安全封装。安全不变量:脚本任务全部在同一个
|
|
659
|
+
// 运行时线程协作执行,编译器发射的借用从不跨越 await/yield 点,故不可能并发
|
|
660
|
+
// 访问;Send/Sync 由此调度器不变性支持(单线程执行器同类的 soundness 论证)
|
|
661
|
+
function runtimeRcompilerV() {
|
|
662
|
+
emit.runtime([
|
|
663
|
+
'pub struct RcompilerCell<T> { pub v: std::cell::RefCell<T> }',
|
|
664
|
+
'unsafe impl<T> Send for RcompilerCell<T> where T: Send {}',
|
|
665
|
+
'unsafe impl<T> Sync for RcompilerCell<T> where T: Send {}',
|
|
666
|
+
'#[derive(Clone)]',
|
|
667
|
+
'pub enum RcompilerV {',
|
|
668
|
+
'N(f64),',
|
|
669
|
+
'S(String),',
|
|
670
|
+
'}'].join('\n'));
|
|
671
|
+
}
|
|
672
|
+
function numInit(ty, n) {
|
|
673
|
+
if (n == null) return ty === 'f64' ? '0.0' : '0';
|
|
674
|
+
if (ty === 'f64') return Number.isInteger(Number(n)) ? Number(n) + '.0' : String(Number(n));
|
|
675
|
+
return String(Math.round(Number(n)) || 0);
|
|
676
|
+
}
|
|
677
|
+
function initStringOf(v) {
|
|
678
|
+
const raw = v.initStr == null ? (v.initNum == null ? '' : castUnParse(String(v.initNum))) : castUnParse(v.initStr);
|
|
679
|
+
return `(${raw}).to_string()`;
|
|
680
|
+
}
|
|
681
|
+
function registerListFields(l, items) {
|
|
682
|
+
const isNum = l.declared === 'f64';
|
|
683
|
+
const elem = isNum ? 'f64' : 'String';
|
|
684
|
+
const inner = listInitExpr(items || [], isNum);
|
|
685
|
+
emit.field(l.f, l.locked ? `std::sync::Arc<RcompilerCell<Vec<${elem}>>>` : `Vec<${elem}>`,
|
|
686
|
+
l.locked ? `std::sync::Arc::new(RcompilerCell { v: std::cell::RefCell::new(${inner}) })` : inner);
|
|
687
|
+
if (l.locked && l.isGlobal) emit.cloneSharedFields.add(l.f);
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
// 列表初始值 → 紧凑初始化表达式(超大列表的健壮性关键:
|
|
691
|
+
// 逐项字面量会让 6400 万元素的列表生成数 GB 源码 / 编译器 OOM)
|
|
692
|
+
function listInitExpr(items, isNum) {
|
|
693
|
+
const n = items.length;
|
|
694
|
+
if (n === 0) return 'vec![]';
|
|
695
|
+
// 全等 → fill(Scratch 导入的大空表几乎都属此类)
|
|
696
|
+
const first = String(items[0]);
|
|
697
|
+
let allEq = true;
|
|
698
|
+
for (let i = 1; i < n; i++) { if (String(items[i]) !== first) { allEq = false; break; } }
|
|
699
|
+
if (allEq) {
|
|
700
|
+
if (isNum) return `vec![${numInit('f64', first)}; ${n}]`;
|
|
701
|
+
return `vec![(${castUnParse(first)}).to_string(); ${n}]`;
|
|
702
|
+
}
|
|
703
|
+
if (isNum) {
|
|
704
|
+
// 字节表(0..255 整数)→ hex 打包:源码 2 字符/项,运行时线性解码
|
|
705
|
+
if (n >= 1024) {
|
|
706
|
+
let ok = true;
|
|
707
|
+
const parts = [];
|
|
708
|
+
for (let i = 0; i < n; i++) {
|
|
709
|
+
const v = Number(items[i]);
|
|
710
|
+
if (!Number.isInteger(v) || v < 0 || v > 255) { ok = false; break; }
|
|
711
|
+
parts.push(v.toString(16).padStart(2, '0'));
|
|
712
|
+
}
|
|
713
|
+
if (ok) {
|
|
714
|
+
emit.runtime(UNHEX_RUNTIME);
|
|
715
|
+
return `rcompiler_unhex(${castUnParse(parts.join(''))})`;
|
|
716
|
+
}
|
|
717
|
+
}
|
|
718
|
+
// 游程压缩(RLE 显著短于逐项时)
|
|
719
|
+
if (n >= 4096) {
|
|
720
|
+
const pairs = [];
|
|
721
|
+
for (let i = 0; i < n;) {
|
|
722
|
+
const v = String(items[i]);
|
|
723
|
+
let j = i + 1;
|
|
724
|
+
while (j < n && String(items[j]) === v) j++;
|
|
725
|
+
pairs.push([v, j - i]);
|
|
726
|
+
i = j;
|
|
727
|
+
}
|
|
728
|
+
if (pairs.length * 2 < n) {
|
|
729
|
+
emit.runtime(RLE_RUNTIME);
|
|
730
|
+
return `rcompiler_rle_f64(&[${pairs.map(([v, c]) => `(${numInit('f64', v)},${c})`).join(',')}])`;
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
return `vec![${items.map(i => numInit('f64', i)).join(',')}]`;
|
|
734
|
+
}
|
|
735
|
+
// 字符串列表:寻找安全分隔符 → 单一字符串常量 + 运行时切分
|
|
736
|
+
if (n >= 1024) {
|
|
737
|
+
for (const sep of ['\u{1}', '\u{2}', '\u{3}', '\u{4}', '\u{5}', '\u{6}']) {
|
|
738
|
+
let bad = false;
|
|
739
|
+
for (let i = 0; i < n; i++) { if (String(items[i]).includes(sep)) { bad = true; break; } }
|
|
740
|
+
if (!bad) {
|
|
741
|
+
emit.runtime(SPLIT_RUNTIME);
|
|
742
|
+
const esc = `\\u{${sep.codePointAt(0).toString(16)}}`;
|
|
743
|
+
const joined = items.map(x => String(x)).join(sep);
|
|
744
|
+
return `rcompiler_split_strings(${castUnParse(joined)}, '${esc}')`;
|
|
745
|
+
}
|
|
746
|
+
}
|
|
747
|
+
// 无安全分隔符:长度前缀编码("3abc2xy..."),仍是单一字符串字面量——
|
|
748
|
+
// 避免 19 万个字符串表达式的 AST 撑爆 rustc
|
|
749
|
+
let maxLen = 0;
|
|
750
|
+
for (let i = 0; i < n; i++) { const l = String(items[i]).length; if (l > maxLen) maxLen = l; }
|
|
751
|
+
if (maxLen <= 9) {
|
|
752
|
+
emit.runtime(LEN_RUNTIME);
|
|
753
|
+
const packed = items.map(x => String(x).length + String(x)).join('');
|
|
754
|
+
return `rcompiler_len_decode(${castUnParse(packed)})`;
|
|
755
|
+
}
|
|
756
|
+
}
|
|
757
|
+
return `vec![${items.map(i => `(${castUnParse(String(i))}).to_string()`).join(',')}]`;
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
// ============ 变量访问器 getvar ============
|
|
761
|
+
// 锁定数值/布尔变量的“拷贝读取”访问器:
|
|
762
|
+
// 同一语句内对同一锁定变量的多次读取会各自产生 MutexGuard 临时值,
|
|
763
|
+
// Rust 临时值存活到整条语句结束 → 第二次读取同线程自死锁
|
|
764
|
+
//(如:stageHeight - (Y+1.5)*16 - stageHeight/2)。
|
|
765
|
+
// getter 立即拷贝出值,锁在方法返回时即释放。
|
|
766
|
+
function numericGetter(fN, ty) {
|
|
767
|
+
const fnName = 'get_' + fN;
|
|
768
|
+
emit.func(`fn ${fnName}(&self) -> ${ty} {\n*self.${fN}.v.borrow()\n}`);
|
|
769
|
+
return 'self.' + fnName + '()';
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
function getterFor(fname) {
|
|
773
|
+
emit.func(`fn get_${fname}(&self) -> String {\nself.${fname}.v.borrow().clone()\n}`);
|
|
774
|
+
return `self.get_${fname}()`;
|
|
775
|
+
}
|
|
776
|
+
|
|
777
|
+
function getvar(name, id) {
|
|
778
|
+
// 键 ti:id;跨目标引用(全局变量)回退舞台键 0:id,再按名扫描
|
|
779
|
+
let v = (id && (S.vars.get(S.targetID + ':' + id) || S.vars.get('0:' + id))) || null;
|
|
780
|
+
if (!v) {
|
|
781
|
+
for (const [, vv] of S.vars) {
|
|
782
|
+
if (vv.name === name && (vv.ti === S.targetID || vv.isGlobal)) { v = vv; if (vv.ti === S.targetID) break; }
|
|
783
|
+
}
|
|
784
|
+
}
|
|
785
|
+
if (!v) {
|
|
786
|
+
// 未定义变量:动态创建私有字段(调试模式沿用带原名的字段命名,与 buildVarField 一致)
|
|
787
|
+
const vid = '_dyn_' + kw(S.targetID + ':' + name);
|
|
788
|
+
v = { id: vid, ti: S.targetID, name, kw: kw(name), isGlobal: false, declared: null, written: true, locked: multi() };
|
|
789
|
+
const f = buildVarField(v);
|
|
790
|
+
v.f = f.f; v.s = f.s;
|
|
791
|
+
S.vars.set(vid, v); registerVarFields(v);
|
|
792
|
+
}
|
|
793
|
+
// rc_localvars(高级自制积木):非全局变量在本次调用中为全新空值,
|
|
794
|
+
// 调用结束丢弃(对照 thread.lookupOrCreateVariable 的 localScope 语义)
|
|
795
|
+
if (S.customproc && S.customproc.localvars && !v.isGlobal) {
|
|
796
|
+
const def = S.customproc;
|
|
797
|
+
if (!def.localShadow.has(v.id)) {
|
|
798
|
+
const n = def.localShadow.size;
|
|
799
|
+
const vn = `__lv${n}_${kwParse(v.name)}`;
|
|
800
|
+
let decl, name, numE, strE;
|
|
801
|
+
if (v.declared === 'String') {
|
|
802
|
+
decl = `let mut ${vn} = String::new();`; name = vn; numE = `get_f64_string(&${vn})`; strE = vn;
|
|
803
|
+
} else if (v.declared === 'bool') {
|
|
804
|
+
decl = `let mut ${vn} = false;`; name = vn; numE = `if ${vn} { 1.0 } else { 0.0 }`; strE = null;
|
|
805
|
+
} else if (v.declared) {
|
|
806
|
+
decl = `let mut ${vn} = ${v.declared === 'f64' ? '0.0' : '0'};`; name = vn; numE = vn; strE = null;
|
|
807
|
+
} else {
|
|
808
|
+
// 未类型化:RcompilerV 枚举(数值/字符串形态都精确保留)
|
|
809
|
+
decl = `let mut ${vn} = RcompilerV::N(0.0);`; name = vn;
|
|
810
|
+
numE = `match &${vn} { RcompilerV::N(v0) => *v0, RcompilerV::S(s) => get_f64_string(s) }`;
|
|
811
|
+
strE = null;
|
|
812
|
+
}
|
|
813
|
+
def.localShadow.set(v.id, { decl, name, numE, strE });
|
|
814
|
+
}
|
|
815
|
+
const sh = def.localShadow.get(v.id);
|
|
816
|
+
const Uloc = !v.declared;
|
|
817
|
+
return {
|
|
818
|
+
v,
|
|
819
|
+
num: () => sh.numE,
|
|
820
|
+
usize: () => `(${sh.numE}) as usize`,
|
|
821
|
+
i32: () => `(${sh.numE}) as i32`,
|
|
822
|
+
str: () => Uloc
|
|
823
|
+
? (runtimeNumStr(), `match &${sh.name} { RcompilerV::S(s) => s.clone(), RcompilerV::N(v0) => rcompiler_num_str(*v0) }`)
|
|
824
|
+
: (sh.strE ? `${sh.strE}.clone()` : (runtimeNumStr(), `rcompiler_num_str(${sh.numE})`)),
|
|
825
|
+
stu: () => Uloc
|
|
826
|
+
? (runtimeNumStr(), `&(match &${sh.name} { RcompilerV::S(s) => s.clone(), RcompilerV::N(v0) => rcompiler_num_str(*v0) })`)
|
|
827
|
+
: (sh.strE ? `&${sh.strE}` : (runtimeNumStr(), `&rcompiler_num_str(${sh.numE})`)),
|
|
828
|
+
numname: () => sh.numE,
|
|
829
|
+
strname: () => (sh.strE || sh.numE),
|
|
830
|
+
setStr: (expr) => {
|
|
831
|
+
runtimeParseF64();
|
|
832
|
+
if (v.declared === 'bool') return `${sh.name} = string_to_boolean(&(${expr}));`;
|
|
833
|
+
if (v.declared === 'String') return `${sh.name} = (${expr});`;
|
|
834
|
+
if (Uloc) return `${sh.name} = RcompilerV::S(${expr});`;
|
|
835
|
+
if (v.declared) return `${sh.name} = get_f64_string(&(${expr}));`;
|
|
836
|
+
return `${sh.strE} = (${expr}); ${sh.name} = get_f64_string(&${sh.strE});`;
|
|
837
|
+
},
|
|
838
|
+
setNum: (expr) => {
|
|
839
|
+
runtimeParseF64(); runtimeNumStr();
|
|
840
|
+
if (v.declared === 'String') return `${sh.name} = rcompiler_num_str(${expr});`;
|
|
841
|
+
if (v.declared === 'bool') return `${sh.name} = (${expr}) != 0.0;`;
|
|
842
|
+
if (Uloc) return `${sh.name} = RcompilerV::N(${expr});`;
|
|
843
|
+
if (v.declared) return `${sh.name} = ${castToTy(expr, v.declared)};`;
|
|
844
|
+
// 双轨(遗留类型组合):表达式只求值一次(同 getvar.setNum 的语义说明)
|
|
845
|
+
return `{ let __sv = (${expr}); ${sh.name} = __sv; ${sh.strE} = rcompiler_num_str(__sv); }`;
|
|
846
|
+
},
|
|
847
|
+
changeNum: (expr) => {
|
|
848
|
+
runtimeParseF64(); runtimeNumStr();
|
|
849
|
+
if (v.declared === 'String') return `${sh.name} = rcompiler_num_str(get_f64_string(&${sh.name}) + (${expr}));`;
|
|
850
|
+
if (v.declared === 'bool') return '';
|
|
851
|
+
if (Uloc) return `${sh.name} = RcompilerV::N(match &${sh.name} { RcompilerV::N(v0) => v0 + (${expr}), RcompilerV::S(s) => get_f64_string(s) + (${expr}) });`;
|
|
852
|
+
if (v.declared) return `${sh.name} += (${expr});`;
|
|
853
|
+
return `${sh.name} += (${expr}); ${sh.strE} = rcompiler_num_str(${sh.name});`;
|
|
854
|
+
}
|
|
855
|
+
};
|
|
856
|
+
}
|
|
857
|
+
const L = v.locked;
|
|
858
|
+
const fN = v.f, fS = v.s;
|
|
859
|
+
const U = !v.declared; // 未类型化 → RcompilerV 单枚举存储
|
|
860
|
+
|
|
861
|
+
function numExpr() {
|
|
862
|
+
if (v.declared === 'String') return `get_f64_string(${strBorrow()})`;
|
|
863
|
+
if (v.declared === 'bool') return L ? `(*self.${fN}.v.borrow() != 0.0)` : `if self.${fN} { 1.0 } else { 0.0 }`;
|
|
864
|
+
if (U) {
|
|
865
|
+
runtimeParseF64();
|
|
866
|
+
return L
|
|
867
|
+
? `match &*self.${fN}.v.borrow() { RcompilerV::N(v0) => *v0, RcompilerV::S(s) => get_f64_string(s) }`
|
|
868
|
+
: `match &self.${fN} { RcompilerV::N(v0) => *v0, RcompilerV::S(s) => get_f64_string(s) }`;
|
|
869
|
+
}
|
|
870
|
+
return L ? numericGetter(fN, v.declared) : `self.${fN}`;
|
|
871
|
+
}
|
|
872
|
+
function strOwned() { // String 值
|
|
873
|
+
if (v.declared === 'String') return L ? getterFor(fS) : `self.${fS}.clone()`;
|
|
874
|
+
if (v.declared === 'bool') return L ? `self.${fN}.v.borrow().to_string()` : `self.${fN}.to_string()`;
|
|
875
|
+
if (U) {
|
|
876
|
+
runtimeNumStr();
|
|
877
|
+
return L
|
|
878
|
+
? `match &*self.${fN}.v.borrow() { RcompilerV::S(s) => s.clone(), RcompilerV::N(v0) => rcompiler_num_str(*v0) }`
|
|
879
|
+
: `match &self.${fN} { RcompilerV::S(s) => s.clone(), RcompilerV::N(v0) => rcompiler_num_str(*v0) }`;
|
|
880
|
+
}
|
|
881
|
+
runtimeNumStr();
|
|
882
|
+
return `rcompiler_num_str(${numExpr()})`;
|
|
883
|
+
}
|
|
884
|
+
function strBorrow() { // &str
|
|
885
|
+
if (v.declared === 'String') return L ? `&*self.${fS}.v.borrow()` : `&self.${fS}`;
|
|
886
|
+
if (U) {
|
|
887
|
+
// 产出 owned String 再取引用——match 分支内的临时值生命周期只到 match
|
|
888
|
+
// 表达式结束,直接在分支里返回 &临时 会 E0716;先 clone/format 出
|
|
889
|
+
// owned 值,外层 & 的临时存活到整条语句结束
|
|
890
|
+
runtimeNumStr();
|
|
891
|
+
return L
|
|
892
|
+
? `&(match &*self.${fN}.v.borrow() { RcompilerV::S(s) => s.clone(), RcompilerV::N(v0) => rcompiler_num_str(*v0) })`
|
|
893
|
+
: `&(match &self.${fN} { RcompilerV::S(s) => s.clone(), RcompilerV::N(v0) => rcompiler_num_str(*v0) })`;
|
|
894
|
+
}
|
|
895
|
+
if (v.declared) return `&(${numExpr()}).to_string()`;
|
|
896
|
+
return `&self.${fS}`;
|
|
897
|
+
}
|
|
898
|
+
return {
|
|
899
|
+
v,
|
|
900
|
+
num: numExpr,
|
|
901
|
+
usize() { return `(${numExpr()}) as usize`; },
|
|
902
|
+
i32() { return `(${numExpr()}) as i32`; },
|
|
903
|
+
str: strOwned,
|
|
904
|
+
stu: strBorrow,
|
|
905
|
+
numname() { return numExpr(); },
|
|
906
|
+
strname() { return strOwned(); },
|
|
907
|
+
setStr(expr) {
|
|
908
|
+
runtimeParseF64();
|
|
909
|
+
// 共享态:RHS 先求值到局部再借——`*借_mut() = RHS` 的 LHS 守卫先于 RHS
|
|
910
|
+
// 求值建立,若 RHS 再读同一变量会立即冲突 panic
|
|
911
|
+
if (L) {
|
|
912
|
+
if (v.declared === 'bool') return `{ let __sv = string_to_boolean(&(${expr})); *self.${fN}.v.borrow_mut() = __sv; }`;
|
|
913
|
+
if (v.declared === 'String') return `{ let __sv = (${expr}); *self.${fS}.v.borrow_mut() = __sv; }`;
|
|
914
|
+
if (U) return `{ let __sv = (${expr}); *self.${fN}.v.borrow_mut() = RcompilerV::S(__sv); }`;
|
|
915
|
+
return `{ let __sv = get_f64_string(&(${expr})); *self.${fN}.v.borrow_mut() = __sv; }`;
|
|
916
|
+
}
|
|
917
|
+
if (v.declared === 'bool') return `self.${fN} = string_to_boolean(&(${expr}));`;
|
|
918
|
+
if (v.declared === 'String') return `self.${fS} = (${expr});`;
|
|
919
|
+
if (U) return `self.${fN} = RcompilerV::S(${expr});`;
|
|
920
|
+
if (v.declared) return `self.${fN} = get_f64_string(&(${expr}));`;
|
|
921
|
+
return `self.${fS} = (${expr});`;
|
|
922
|
+
},
|
|
923
|
+
setNum(expr) {
|
|
924
|
+
runtimeParseF64();
|
|
925
|
+
runtimeNumStr();
|
|
926
|
+
if (L) {
|
|
927
|
+
if (v.declared === 'String') return `{ let __sv = rcompiler_num_str(${expr}); *self.${fS}.v.borrow_mut() = __sv; }`;
|
|
928
|
+
if (v.declared === 'bool') return `{ let __sv = (${expr}) != 0.0; *self.${fN}.v.borrow_mut() = __sv; }`;
|
|
929
|
+
if (U) return `{ let __sv = (${expr}); *self.${fN}.v.borrow_mut() = RcompilerV::N(__sv); }`;
|
|
930
|
+
return `{ let __sv = (${expr}); *self.${fN}.v.borrow_mut() = ${castToTy('__sv', v.declared)}; }`;
|
|
931
|
+
}
|
|
932
|
+
if (v.declared === 'String') return `self.${fS} = rcompiler_num_str(${expr});`;
|
|
933
|
+
if (v.declared === 'bool') return `self.${fN} = (${expr}) != 0.0;`;
|
|
934
|
+
if (U) return `self.${fN} = RcompilerV::N(${expr});`;
|
|
935
|
+
if (v.declared) return `self.${fN} = ${castToTy(expr, v.declared)};`;
|
|
936
|
+
return `self.${fS} = rcompiler_num_str(${expr});`;
|
|
937
|
+
},
|
|
938
|
+
changeNum(expr) {
|
|
939
|
+
runtimeParseF64();
|
|
940
|
+
runtimeNumStr();
|
|
941
|
+
if (v.declared === 'String') return L
|
|
942
|
+
? `{ let __sv = rcompiler_num_str(get_f64_string(${strBorrow()}) + (${expr})); *self.${fS}.v.borrow_mut() = __sv; }`
|
|
943
|
+
: `self.${fS} = rcompiler_num_str(get_f64_string(${strBorrow()}) + (${expr}));`;
|
|
944
|
+
if (v.declared === 'bool') return '';
|
|
945
|
+
if (U) {
|
|
946
|
+
const rd = L ? `match &*self.${fN}.v.borrow() { RcompilerV::N(v0) => *v0, RcompilerV::S(s) => get_f64_string(s) }` : `match &self.${fN} { RcompilerV::N(v0) => *v0, RcompilerV::S(s) => get_f64_string(s) }`;
|
|
947
|
+
return `{ let __sv = (${rd}) + (${expr}); ${L ? `*self.${fN}.v.borrow_mut()` : `self.${fN}`} = RcompilerV::N(__sv); }`;
|
|
948
|
+
}
|
|
949
|
+
if (v.declared) return L
|
|
950
|
+
? `{ let __sv = (${expr}); *self.${fN}.v.borrow_mut() += __sv; }`
|
|
951
|
+
: `self.${fN} += (${expr});`;
|
|
952
|
+
return `self.${fN} += (${expr}); self.${fS} = rcompiler_num_str(self.${fN});`;
|
|
953
|
+
}
|
|
954
|
+
};
|
|
955
|
+
}
|
|
956
|
+
function castToTy(expr, ty) {
|
|
957
|
+
if (ty === 'f64') return `(${expr})`;
|
|
958
|
+
return `(${expr}) as ${ty}`;
|
|
959
|
+
}
|
|
960
|
+
|
|
961
|
+
function getlist(name, id) {
|
|
962
|
+
// 键 ti:id;跨目标引用(全局列表)回退舞台键 0:id,再按名扫描
|
|
963
|
+
let l = (id && (S.lists.get(S.targetID + ':' + id) || S.lists.get('0:' + id))) || null;
|
|
964
|
+
if (!l) {
|
|
965
|
+
for (const [, ll] of S.lists) {
|
|
966
|
+
if (ll.name === name && (ll.ti === S.targetID || ll.isGlobal)) { l = ll; if (ll.ti === S.targetID) break; }
|
|
967
|
+
}
|
|
968
|
+
}
|
|
969
|
+
if (!l) {
|
|
970
|
+
const lid = '_dyn_' + kw(S.targetID + ':' + name);
|
|
971
|
+
l = { id: lid, ti: S.targetID, name, kw: kw(name), isGlobal: false, declared: null, written: true, locked: multi(), f: listFieldName(name, kw(name), S.targetID + '_') };
|
|
972
|
+
S.lists.set(lid, l); registerListFields(l, []);
|
|
973
|
+
}
|
|
974
|
+
return l.locked ? `self.${l.f}.v.borrow_mut()` : `self.${l.f}`;
|
|
975
|
+
}
|
|
976
|
+
|
|
977
|
+
// 列表的“裸字段”访问(RcompilerList trait 的接收者)。
|
|
978
|
+
// 读取必须走 trait 的短锁方法(lget/llen/lpos/lhas/lclone)——
|
|
979
|
+
// 若在长表达式里直接 `.lock().unwrap()`,MutexGuard 临时值会存活到整条语句结束,
|
|
980
|
+
// 同一语句内第二次读同一列表会同线程自死锁(列表密集型项目在单条语句内多次读取同列表时即会卡死)
|
|
981
|
+
function getListField(name, id) {
|
|
982
|
+
let l = (id && (S.lists.get(S.targetID + ':' + id) || S.lists.get('0:' + id))) || null;
|
|
983
|
+
if (!l) {
|
|
984
|
+
for (const [, ll] of S.lists) {
|
|
985
|
+
if (ll.name === name && (ll.ti === S.targetID || ll.isGlobal)) { l = ll; if (ll.ti === S.targetID) break; }
|
|
986
|
+
}
|
|
987
|
+
}
|
|
988
|
+
if (!l) return getlist(name, id);
|
|
989
|
+
return `self.${l.f}`;
|
|
990
|
+
}
|
|
991
|
+
|
|
992
|
+
// 短锁列表 trait:Vec 与 Mutex<Vec>/Arc<Mutex<Vec>> 统一接口。
|
|
993
|
+
// 写路径(push/clear/insert/remove/get_mut)仍按“单语句单锁”内联;
|
|
994
|
+
// 读路径全部经 trait(锁只在方法内存活)
|
|
995
|
+
function runtimeRcompilerList() {
|
|
996
|
+
const lines = [
|
|
997
|
+
'pub trait RcompilerList<T> {',
|
|
998
|
+
'fn lget(&self, i: usize) -> Option<T> where T: Clone;',
|
|
999
|
+
'fn llen(&self) -> usize;',
|
|
1000
|
+
'fn lclone(&self) -> Vec<T> where T: Clone;',
|
|
1001
|
+
'fn lpos(&self, x: &T) -> f64 where T: PartialEq;',
|
|
1002
|
+
'fn lhas(&self, x: &T) -> bool where T: PartialEq;',
|
|
1003
|
+
'}',
|
|
1004
|
+
'impl<T: Clone> RcompilerList<T> for Vec<T> {',
|
|
1005
|
+
'fn lget(&self, i: usize) -> Option<T> { self.get(i).cloned() }',
|
|
1006
|
+
'fn llen(&self) -> usize { self.len() }',
|
|
1007
|
+
'fn lclone(&self) -> Vec<T> { self.clone() }',
|
|
1008
|
+
'fn lpos(&self, x: &T) -> f64 where T: PartialEq { self.iter().position(|y| y == x).map(|p| p as f64 + 1.0).unwrap_or(0.0) }',
|
|
1009
|
+
'fn lhas(&self, x: &T) -> bool where T: PartialEq { self.iter().any(|y| y == x) }',
|
|
1010
|
+
'}'];
|
|
1011
|
+
// RcompilerCell 实现:RefCell 的协作单线程安全封装。
|
|
1012
|
+
// 安全性不变量:所有脚本任务在同一个运行时线程上协作执行,借用从不跨越
|
|
1013
|
+
// await/yield 点(编译器发射的短借用模式保证),因此不可能并发访问;
|
|
1014
|
+
// Send/Sync 标注由该调度器不变性支持(与 spawn_local 型单线程执行器同类)。
|
|
1015
|
+
const anyLocked = [...S.lists.values()].some((l) => l.locked);
|
|
1016
|
+
if (anyLocked) {
|
|
1017
|
+
lines.push(
|
|
1018
|
+
'impl<T: Clone> RcompilerList<T> for RcompilerCell<Vec<T>> {',
|
|
1019
|
+
'fn lget(&self, i: usize) -> Option<T> { self.v.borrow().get(i).cloned() }',
|
|
1020
|
+
'fn llen(&self) -> usize { self.v.borrow().len() }',
|
|
1021
|
+
'fn lclone(&self) -> Vec<T> { self.v.borrow().clone() }',
|
|
1022
|
+
'fn lpos(&self, x: &T) -> f64 where T: PartialEq { self.v.borrow().iter().position(|y| y == x).map(|p| p as f64 + 1.0).unwrap_or(0.0) }',
|
|
1023
|
+
'fn lhas(&self, x: &T) -> bool where T: PartialEq { self.v.borrow().iter().any(|y| y == x) }',
|
|
1024
|
+
'}',
|
|
1025
|
+
'impl<T: Clone> RcompilerList<T> for std::sync::Arc<RcompilerCell<Vec<T>>> {',
|
|
1026
|
+
'fn lget(&self, i: usize) -> Option<T> { self.v.borrow().get(i).cloned() }',
|
|
1027
|
+
'fn llen(&self) -> usize { self.v.borrow().len() }',
|
|
1028
|
+
'fn lclone(&self) -> Vec<T> { self.v.borrow().clone() }',
|
|
1029
|
+
'fn lpos(&self, x: &T) -> f64 where T: PartialEq { self.v.borrow().iter().position(|y| y == x).map(|p| p as f64 + 1.0).unwrap_or(0.0) }',
|
|
1030
|
+
'fn lhas(&self, x: &T) -> bool where T: PartialEq { self.v.borrow().iter().any(|y| y == x) }',
|
|
1031
|
+
'}');
|
|
1032
|
+
}
|
|
1033
|
+
emit.runtime(lines.join('\n'));
|
|
1034
|
+
}
|
|
1035
|
+
|
|
1036
|
+
// 列表元信息(元素类型判定:declared === 'f64' → Vec<f64>)
|
|
1037
|
+
function listInfo(name, id) {
|
|
1038
|
+
let l = (id && (S.lists.get(S.targetID + ':' + id) || S.lists.get('0:' + id))) || null;
|
|
1039
|
+
if (!l) {
|
|
1040
|
+
for (const [, ll] of S.lists) {
|
|
1041
|
+
if (ll.name === name && (ll.ti === S.targetID || ll.isGlobal)) { l = ll; if (ll.ti === S.targetID) break; }
|
|
1042
|
+
}
|
|
1043
|
+
}
|
|
1044
|
+
return l;
|
|
1045
|
+
}
|
|
1046
|
+
|
|
1047
|
+
// ============ TypeInput(V1 兼容 API)============
|
|
1048
|
+
// Rust 字符串字面量 → 可数值化则返回 f64 字面量文本(编译期常量折叠)。
|
|
1049
|
+
// "0x100000000" 这类十六进制字面量在模拟器的地址运算里反复出现,
|
|
1050
|
+
// 每次运行时 parse 纯属浪费
|
|
1051
|
+
function rustStrLitNum(lit) {
|
|
1052
|
+
let inner = null;
|
|
1053
|
+
const m1 = /^"((?:[^"\\]|\\.)*)"$/.exec(lit);
|
|
1054
|
+
if (m1) inner = m1[1];
|
|
1055
|
+
else {
|
|
1056
|
+
const m2 = /^String::from\("((?:[^"\\]|\\.)*)"\)$/.exec(lit);
|
|
1057
|
+
if (m2) inner = m2[1];
|
|
1058
|
+
}
|
|
1059
|
+
if (inner == null) return null;
|
|
1060
|
+
let s = '', i = 0;
|
|
1061
|
+
while (i < inner.length) {
|
|
1062
|
+
const c = inner[i];
|
|
1063
|
+
if (c === '\\') {
|
|
1064
|
+
const n = inner[i + 1];
|
|
1065
|
+
if (n === 'n') { s += '\n'; i += 2; }
|
|
1066
|
+
else if (n === 't') { s += '\t'; i += 2; }
|
|
1067
|
+
else if (n === 'r') { s += '\r'; i += 2; }
|
|
1068
|
+
else if (n === '\\') { s += '\\'; i += 2; }
|
|
1069
|
+
else if (n === '"') { s += '"'; i += 2; }
|
|
1070
|
+
else if (n === "'") { s += "'"; i += 2; }
|
|
1071
|
+
else if (n === '0') { s += '\0'; i += 2; }
|
|
1072
|
+
else if (n === 'u') { const e = inner.indexOf('}', i); if (e < 0) return null; const cp = parseInt(inner.slice(i + 3, e), 16); if (!Number.isFinite(cp)) return null; s += String.fromCodePoint(cp); i = e + 1; }
|
|
1073
|
+
else return null;
|
|
1074
|
+
} else { s += c; i += 1; }
|
|
1075
|
+
}
|
|
1076
|
+
const t = s.trim();
|
|
1077
|
+
if (t === '' || !/^[+-]?(0[xX][0-9a-fA-F]+|0[oO][0-7]+|0[bB][01]+|(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?)$/.test(t)) return null;
|
|
1078
|
+
const v = Number(t);
|
|
1079
|
+
if (!Number.isFinite(v)) return null;
|
|
1080
|
+
return Number.isInteger(v) && Math.abs(v) < 1e15 ? `${v}.0` : (Object.is(v, -0) ? '-0.0' : `${v}`);
|
|
1081
|
+
}
|
|
1082
|
+
|
|
1083
|
+
const T = {
|
|
1084
|
+
Block: class {
|
|
1085
|
+
constructor(input) { this.input = input; this.type = 'Block'; }
|
|
1086
|
+
Num() { return '0.0'; } Usize() { return '0'; } i32() { return '0'; }
|
|
1087
|
+
Str() { return '""'; } Stri() { return 'String::new()'; } Stu() { return '""'; }
|
|
1088
|
+
Bool() { return 'false'; }
|
|
1089
|
+
block() { return this.input; }
|
|
1090
|
+
},
|
|
1091
|
+
Raw: class {
|
|
1092
|
+
constructor(input) { this.input = input; this.type = 'Raw'; }
|
|
1093
|
+
Str() { return castUnParse(this.input); } Stu() { return castUnParse(this.input); }
|
|
1094
|
+
Stri() { return `String::from(${castUnParse(this.input)})`; }
|
|
1095
|
+
Num() { return '0.0'; } Usize() { return '0'; } i32() { return '0'; } Bool() { return 'false'; }
|
|
1096
|
+
block() { return this.input; }
|
|
1097
|
+
},
|
|
1098
|
+
Any: class {
|
|
1099
|
+
constructor(input) { this.input = input; this.type = 'Any'; }
|
|
1100
|
+
Num() { return this.input; } Usize() { return this.input; } i32() { return this.input; }
|
|
1101
|
+
Str() { return this.input; } Stri() { return this.input; } Stu() { return this.input; }
|
|
1102
|
+
Bool() { return this.input; } block() { return this.input; }
|
|
1103
|
+
},
|
|
1104
|
+
Num: class {
|
|
1105
|
+
constructor(input) { this.input = input; this.type = 'Num'; }
|
|
1106
|
+
Num() { return this.input; }
|
|
1107
|
+
Usize() { return /^-?\d+$/.test(this.input) ? Math.round(Number(this.input)) + '_usize' : `(${this.input}) as usize`; }
|
|
1108
|
+
i32() { return /^-?\d+$/.test(this.input) ? Math.round(Number(this.input)) + '_i32' : `(${this.input}) as i32`; }
|
|
1109
|
+
// 整数值常量(含 "13.0" 形式)直接折叠为字面量字符串——
|
|
1110
|
+
// JS String(Number(x)) 对整数就是十进制整数字面量(对照 rcompiler_num_str)
|
|
1111
|
+
Str() {
|
|
1112
|
+
runtimeNumStr();
|
|
1113
|
+
if (/^-?\d+$/.test(this.input)) return `"${this.input}"`;
|
|
1114
|
+
if (/^-?\d+\.0+$/.test(this.input)) return `"${Math.round(Number(this.input))}"`;
|
|
1115
|
+
return `&(rcompiler_num_str(${this.input}))`;
|
|
1116
|
+
}
|
|
1117
|
+
Stri() {
|
|
1118
|
+
runtimeNumStr();
|
|
1119
|
+
if (/^-?\d+$/.test(this.input)) return `String::from("${this.input}")`;
|
|
1120
|
+
if (/^-?\d+\.0+$/.test(this.input)) return `String::from("${Math.round(Number(this.input))}")`;
|
|
1121
|
+
return `rcompiler_num_str(${this.input})`;
|
|
1122
|
+
}
|
|
1123
|
+
Stu() { return this.Str().replace(/^&/, ''); }
|
|
1124
|
+
Bool() { return `(${this.input} != 0.0)`; }
|
|
1125
|
+
block() { return this.input; }
|
|
1126
|
+
},
|
|
1127
|
+
Usize: class {
|
|
1128
|
+
constructor(input) { this.input = input; this.type = 'Usize'; }
|
|
1129
|
+
Num() { return `(${this.input}) as f64`; }
|
|
1130
|
+
Usize() { return /^-?\d+$/.test(this.input) ? Math.round(Number(this.input)) + '_usize' : this.input; }
|
|
1131
|
+
i32() { return /^-?\d+$/.test(this.input) ? Math.round(Number(this.input)) + '_i32' : `(${this.input}) as i32`; }
|
|
1132
|
+
Str() { runtimeNumStr(); return `&(rcompiler_num_str((${this.input}) as f64))`; }
|
|
1133
|
+
Stri() { runtimeNumStr(); return `rcompiler_num_str((${this.input}) as f64)`; }
|
|
1134
|
+
Stu() { return `rcompiler_num_str((${this.input}) as f64)`; }
|
|
1135
|
+
Bool() { return `((${this.input}) as f64 != 0.0)`; }
|
|
1136
|
+
block() { return this.input; }
|
|
1137
|
+
},
|
|
1138
|
+
i32: class {
|
|
1139
|
+
constructor(input) { this.input = input; this.type = 'i32'; }
|
|
1140
|
+
Num() { return `(${this.input}) as f64`; }
|
|
1141
|
+
Usize() { return /^-?\d+$/.test(this.input) ? Math.round(Number(this.input)) + '_usize' : `(${this.input}) as usize`; }
|
|
1142
|
+
i32() { return this.input; }
|
|
1143
|
+
Str() { runtimeNumStr(); return `&(rcompiler_num_str((${this.input}) as f64))`; }
|
|
1144
|
+
Stri() { runtimeNumStr(); return `rcompiler_num_str((${this.input}) as f64)`; }
|
|
1145
|
+
Stu() { return `rcompiler_num_str((${this.input}) as f64)`; }
|
|
1146
|
+
Bool() { return `((${this.input}) as f64 != 0.0)`; }
|
|
1147
|
+
block() { return this.input; }
|
|
1148
|
+
},
|
|
1149
|
+
Str: class {
|
|
1150
|
+
constructor(input) { this.input = input; this.type = 'Str'; }
|
|
1151
|
+
Num() {
|
|
1152
|
+
runtimeParseF64();
|
|
1153
|
+
const folded = rustStrLitNum(this.input);
|
|
1154
|
+
if (folded != null) return folded;
|
|
1155
|
+
return `get_f64_string(${this.input})`;
|
|
1156
|
+
}
|
|
1157
|
+
Usize() {
|
|
1158
|
+
runtimeParseUsize();
|
|
1159
|
+
const folded = rustStrLitNum(this.input);
|
|
1160
|
+
if (folded != null) return `(${folded}) as usize`;
|
|
1161
|
+
return `get_usize_string(${this.input})`;
|
|
1162
|
+
}
|
|
1163
|
+
i32() {
|
|
1164
|
+
runtimeParseI32();
|
|
1165
|
+
const folded = rustStrLitNum(this.input);
|
|
1166
|
+
if (folded != null) return `(${folded}) as i32`;
|
|
1167
|
+
return `get_i32_string(${this.input})`;
|
|
1168
|
+
}
|
|
1169
|
+
Str() { return this.input; }
|
|
1170
|
+
Stri() { return `String::from(${this.input})`; }
|
|
1171
|
+
Stu() { return this.input.replace(/^&/, ''); }
|
|
1172
|
+
Bool() { runtimeStr2Bool(); return `string_to_boolean(${this.input})`; }
|
|
1173
|
+
block() { return this.input; }
|
|
1174
|
+
},
|
|
1175
|
+
Stri: class {
|
|
1176
|
+
constructor(input) { this.input = input; this.type = 'Stri'; }
|
|
1177
|
+
Num() { runtimeParseF64(); const folded = rustStrLitNum(this.input); if (folded != null) return folded; return `get_f64_string(${this.input.endsWith('.clone()') ? this.input : this.input + '.clone()'})`; }
|
|
1178
|
+
Usize() { runtimeParseUsize(); const folded = rustStrLitNum(this.input); if (folded != null) return `(${folded}) as usize`; return `get_usize_string(${this.input.endsWith('.clone()') ? this.input : this.input + '.clone()'})`; }
|
|
1179
|
+
i32() { runtimeParseI32(); const folded = rustStrLitNum(this.input); if (folded != null) return `(${folded}) as i32`; return `get_i32_string(${this.input.endsWith('.clone()') ? this.input : this.input + '.clone()'})`; }
|
|
1180
|
+
Str() { return `&*(${this.input})`; }
|
|
1181
|
+
Stri() { return this.input; }
|
|
1182
|
+
Stu() { return this.input; }
|
|
1183
|
+
Bool() { runtimeStr2Bool(); return `string_to_boolean(&${this.input})`; }
|
|
1184
|
+
block() { return this.input; }
|
|
1185
|
+
},
|
|
1186
|
+
Bool: class {
|
|
1187
|
+
constructor(input) { this.input = input; this.type = 'Bool'; }
|
|
1188
|
+
Bool() { return this.input; }
|
|
1189
|
+
Num() { return `if (${this.input}) { 1.0 } else { 0.0 }`; }
|
|
1190
|
+
Usize() { return `if (${this.input}) { 1_usize } else { 0 }`; }
|
|
1191
|
+
i32() { return `if (${this.input}) { 1_i32 } else { 0 }`; }
|
|
1192
|
+
Str() { return `&(${this.input}).to_string()`; }
|
|
1193
|
+
Stri() { return `(${this.input}).to_string()`; }
|
|
1194
|
+
Stu() { return `((${this.input}).to_string())`; }
|
|
1195
|
+
block() { return this.input; }
|
|
1196
|
+
},
|
|
1197
|
+
Var: class {
|
|
1198
|
+
constructor(varname, varid) { this.varname = varname; this.varid = varid; this.type = 'Var'; }
|
|
1199
|
+
Num() { return getvar(this.varname, this.varid).num(); }
|
|
1200
|
+
Usize() { return getvar(this.varname, this.varid).usize(); }
|
|
1201
|
+
i32() { return getvar(this.varname, this.varid).i32(); }
|
|
1202
|
+
Str() { return getvar(this.varname, this.varid).stu(); }
|
|
1203
|
+
Stri() { return getvar(this.varname, this.varid).str(); }
|
|
1204
|
+
Stu() { return getvar(this.varname, this.varid).stu(); }
|
|
1205
|
+
Bool() { runtimeStr2Bool(); return `string_to_boolean(${getvar(this.varname, this.varid).stu()})`; }
|
|
1206
|
+
block() { return this.Stri(); }
|
|
1207
|
+
},
|
|
1208
|
+
ListVar: class {
|
|
1209
|
+
constructor(listname, listid) { this.listname = listname; this.listid = listid; this.type = 'ListVar'; }
|
|
1210
|
+
isNum() { const l = listInfo(this.listname, this.listid); return !!(l && l.declared === 'f64'); }
|
|
1211
|
+
acc() { return getlist(this.listname, this.listid); }
|
|
1212
|
+
numCore() {
|
|
1213
|
+
runtimeParseF64(); runtimeList2Var(); runtimeRcompilerList();
|
|
1214
|
+
const f = getListField(this.listname, this.listid);
|
|
1215
|
+
if (this.isNum()) { runtimeList2VarF64(); return `list2var_f64(${f}.lclone())`; }
|
|
1216
|
+
return `get_f64_string(list2var(${f}.lclone()))`;
|
|
1217
|
+
}
|
|
1218
|
+
Num() { return this.numCore(); }
|
|
1219
|
+
Usize() {
|
|
1220
|
+
runtimeParseUsize(); runtimeList2Var(); runtimeRcompilerList();
|
|
1221
|
+
const f = getListField(this.listname, this.listid);
|
|
1222
|
+
if (this.isNum()) { runtimeList2VarF64(); return `get_usize_string(&list2var_f64(${f}.lclone()))`; }
|
|
1223
|
+
return `get_usize_string(list2var(${f}.lclone()))`;
|
|
1224
|
+
}
|
|
1225
|
+
i32() {
|
|
1226
|
+
runtimeParseI32(); runtimeList2Var(); runtimeRcompilerList();
|
|
1227
|
+
const f = getListField(this.listname, this.listid);
|
|
1228
|
+
if (this.isNum()) { runtimeList2VarF64(); return `get_i32_string(&list2var_f64(${f}.lclone()))`; }
|
|
1229
|
+
return `get_i32_string(list2var(${f}.lclone()))`;
|
|
1230
|
+
}
|
|
1231
|
+
Str() { runtimeList2Var(); runtimeRcompilerList(); const f = getListField(this.listname, this.listid); if (this.isNum()) { runtimeList2VarF64(); return `&*list2var_f64(${f}.lclone())`; } return `&*(list2var(${f}.lclone()))`; }
|
|
1232
|
+
Stri() { runtimeList2Var(); runtimeRcompilerList(); const f = getListField(this.listname, this.listid); if (this.isNum()) { runtimeList2VarF64(); return `list2var_f64(${f}.lclone())`; } return `list2var(${f}.lclone())`; }
|
|
1233
|
+
Stu() { return this.Stri(); }
|
|
1234
|
+
Bool() { runtimeStr2Bool(); return `string_to_boolean(&${this.Stri()})`; }
|
|
1235
|
+
block() { return this.Stri(); }
|
|
1236
|
+
}
|
|
1237
|
+
};
|
|
1238
|
+
|
|
1239
|
+
// 常用 runtime 注册(文本与 standard.js 的注册保持一致,靠 Set 去重)
|
|
1240
|
+
function runtimeParseF64() {
|
|
1241
|
+
emit.runtime([
|
|
1242
|
+
'fn get_f64_string<T: AsRef<str>>(toget:T)->f64 {',
|
|
1243
|
+
'let s = toget.as_ref().trim();',
|
|
1244
|
+
'if let Some(v) = rcompiler_js_number(s) { return v; }',
|
|
1245
|
+
'match s.parse::<f64>() { Ok(parsed_num) => parsed_num, Err(_) => 0.0 }',
|
|
1246
|
+
'}'].join('\n'));
|
|
1247
|
+
}
|
|
1248
|
+
function runtimeParseUsize() {
|
|
1249
|
+
emit.runtime([
|
|
1250
|
+
'fn get_usize_string<T: AsRef<str>>(toget:T)->usize {',
|
|
1251
|
+
'let s = toget.as_ref().trim();',
|
|
1252
|
+
'if let Some(v) = rcompiler_js_number(s) { return v as usize; }',
|
|
1253
|
+
'match s.parse::<usize>() { Ok(parsed_num) => parsed_num, Err(_) => 0 }',
|
|
1254
|
+
'}'].join('\n'));
|
|
1255
|
+
}
|
|
1256
|
+
function runtimeParseI32() {
|
|
1257
|
+
emit.runtime([
|
|
1258
|
+
'fn get_i32_string<T: AsRef<str>>(toget:T)->i32 {',
|
|
1259
|
+
'let s = toget.as_ref().trim();',
|
|
1260
|
+
'if let Some(v) = rcompiler_js_number(s) { return v as i32; }',
|
|
1261
|
+
'match s.parse::<i32>() { Ok(parsed_num) => parsed_num, Err(_) => 0 }',
|
|
1262
|
+
'}'].join('\n'));
|
|
1263
|
+
}
|
|
1264
|
+
function runtimeStr2Bool() {
|
|
1265
|
+
emit.runtime([
|
|
1266
|
+
'fn string_to_boolean <T: AsRef<str>>(input: T) -> bool {',
|
|
1267
|
+
'let trimmed_input = input.as_ref().trim();',
|
|
1268
|
+
'if trimmed_input.is_empty() || trimmed_input == "0" || trimmed_input.eq_ignore_ascii_case("false") { false } else { true }',
|
|
1269
|
+
'}'].join('\n'));
|
|
1270
|
+
}
|
|
1271
|
+
function runtimeList2Var() {
|
|
1272
|
+
emit.runtime([
|
|
1273
|
+
'fn list2var(input: Vec<String>) -> String {',
|
|
1274
|
+
'let has_item_with_length_gt_1 = input.iter().any(|item| item.len() > 1);',
|
|
1275
|
+
'if has_item_with_length_gt_1 { input.join(" ") } else { input.concat() }',
|
|
1276
|
+
'}'].join('\n'));
|
|
1277
|
+
}
|
|
1278
|
+
function runtimeList2VarF64() {
|
|
1279
|
+
emit.runtime([
|
|
1280
|
+
'fn list2var_f64(input: Vec<f64>) -> String {',
|
|
1281
|
+
'let strs: Vec<String> = input.iter().map(|x| x.to_string()).collect();',
|
|
1282
|
+
'let has_item_with_length_gt_1 = strs.iter().any(|item| item.len() > 1);',
|
|
1283
|
+
'if has_item_with_length_gt_1 { strs.join(" ") } else { strs.concat() }',
|
|
1284
|
+
'}'].join('\n'));
|
|
1285
|
+
}
|
|
1286
|
+
// JS String(number) 忠实格式化:Infinity/-Infinity/NaN/-0(对照 Scratch Cast.toString)
|
|
1287
|
+
function runtimeNumStr() {
|
|
1288
|
+
emit.runtime([
|
|
1289
|
+
'fn rcompiler_num_str(x: f64) -> String {',
|
|
1290
|
+
'if x.is_nan() { return "NaN".to_string(); }',
|
|
1291
|
+
'if x == f64::INFINITY { return "Infinity".to_string(); }',
|
|
1292
|
+
'if x == f64::NEG_INFINITY { return "-Infinity".to_string(); }',
|
|
1293
|
+
'if x == 0.0 { return "0".to_string(); }',
|
|
1294
|
+
'// 整数快路径:模拟器/数值项目绝大多数赋值是整数——',
|
|
1295
|
+
'// 手写 itoa 比 format!("{}", f64) 快一个数量级(通用优化,语义同 JS Number→String)',
|
|
1296
|
+
'if x.fract() == 0.0 && x.abs() < 9.007199254740992e15 {',
|
|
1297
|
+
'let i = x as i64;',
|
|
1298
|
+
'let mut buf = [0u8; 20];',
|
|
1299
|
+
'let mut n = buf.len();',
|
|
1300
|
+
'let mut v = i.unsigned_abs();',
|
|
1301
|
+
'while v >= 10 { n -= 1; buf[n] = b\'0\' + (v % 10) as u8; v /= 10; }',
|
|
1302
|
+
'n -= 1; buf[n] = b\'0\' + v as u8;',
|
|
1303
|
+
'if i < 0 { n -= 1; buf[n] = b\'-\'; }',
|
|
1304
|
+
'return String::from_utf8_lossy(&buf[n..]).into_owned();',
|
|
1305
|
+
'}',
|
|
1306
|
+
'x.to_string()',
|
|
1307
|
+
'}'].join('\n'));
|
|
1308
|
+
}
|
|
1309
|
+
|
|
1310
|
+
// ============ Cast ============
|
|
1311
|
+
function castUnParse(parsed) {
|
|
1312
|
+
// 混淆模式:字符串常量统一进密文表,由 rcompiler_str 在运行时解密
|
|
1313
|
+
if (obf) return strlit(String(parsed));
|
|
1314
|
+
// JSON.stringify 转义 → Rust 转义:
|
|
1315
|
+
// 1) \uXXXX → \u{...}
|
|
1316
|
+
// 2) Rust 不支持的 JSON 短转义 \b \f → \u{8} \u{c}
|
|
1317
|
+
// 3) 双向文本控制码(U+202A..E / U+2066..9)字面量会被 rustc deny → 转为 \u{...}
|
|
1318
|
+
return JSON.stringify(parsed)
|
|
1319
|
+
.replace(/\\u([0-9a-fA-F]{4})/g, '\\u{$1}')
|
|
1320
|
+
.replace(/\\f/g, '\\u{c}')
|
|
1321
|
+
.replace(/\\b/g, '\\u{8}')
|
|
1322
|
+
.replace(/[\u202A-\u202E\u2066-\u2069]/g, (c) => '\\u{' + c.codePointAt(0).toString(16) + '}');
|
|
1323
|
+
}
|
|
1324
|
+
const C = {
|
|
1325
|
+
toNum(str) {
|
|
1326
|
+
if (!str) return '0.0';
|
|
1327
|
+
if (typeof str === 'number') str = str.toString();
|
|
1328
|
+
if (str.startsWith('"') && str.endsWith('"')) str = str.slice(1, -1);
|
|
1329
|
+
if (str === '') return '0.0';
|
|
1330
|
+
if (Number.isInteger(Number(str))) return String(Number(str)) + '.0';
|
|
1331
|
+
return str;
|
|
1332
|
+
},
|
|
1333
|
+
toUsize(str) {
|
|
1334
|
+
if (!str) return '0';
|
|
1335
|
+
if (str.startsWith('"') && str.endsWith('"')) str = str.slice(1, -1);
|
|
1336
|
+
if (str === '') return '0';
|
|
1337
|
+
if (str.includes('.')) return `(${str}) as usize`;
|
|
1338
|
+
if (!Number.isInteger(Number(str))) return `(${str}) as usize`;
|
|
1339
|
+
return str;
|
|
1340
|
+
},
|
|
1341
|
+
toi32(str) {
|
|
1342
|
+
if (!str) return '0';
|
|
1343
|
+
if (str.startsWith('"') && str.endsWith('"')) str = str.slice(1, -1);
|
|
1344
|
+
if (str === '') return '0';
|
|
1345
|
+
if (str.includes('.')) return `(${str}) as i32`;
|
|
1346
|
+
if (!Number.isInteger(Number(str))) return `(${str}) as i32`;
|
|
1347
|
+
return str;
|
|
1348
|
+
},
|
|
1349
|
+
toStr(num) {
|
|
1350
|
+
if (num == null || num === '') return '""';
|
|
1351
|
+
if (Number(num) || num === 0) return `"${num}"`;
|
|
1352
|
+
if (!(num.startsWith('"') && num.endsWith('"'))) return '&' + num;
|
|
1353
|
+
return num;
|
|
1354
|
+
},
|
|
1355
|
+
toStri(str) {
|
|
1356
|
+
if (!str) return 'String::new()';
|
|
1357
|
+
if (/^-?\d+(\.\d+)?$/.test(str)) return `(${str}).to_string()`;
|
|
1358
|
+
if (str.startsWith('"') && str.endsWith('"')) return `(${str}).to_string()`;
|
|
1359
|
+
if (str.startsWith('(') && str.endsWith(')')) return `(${str}).to_string()`;
|
|
1360
|
+
return str;
|
|
1361
|
+
},
|
|
1362
|
+
toCopyableStri(str) { if (!str) return 'String::new()'; return `(${str}).clone()`; },
|
|
1363
|
+
isNum(ci) { return ci && (ci.type === 'Num' || ci.type === 'i32' || ci.type === 'Usize'); },
|
|
1364
|
+
NumTest(str) {
|
|
1365
|
+
if (typeof str !== 'string') return false;
|
|
1366
|
+
if (str.startsWith('"') && str.endsWith('"')) str = str.slice(1, -1);
|
|
1367
|
+
// 排除 Infinity/NaN 等非有限值:它们在 Scratch 中是文本输入,
|
|
1368
|
+
// 生成裸标识符会导致 Rust 编译错误(如 "Infinity")
|
|
1369
|
+
if (!/^-?[0-9]/.test(str)) return false;
|
|
1370
|
+
return str !== '' && !isNaN(Number(str));
|
|
1371
|
+
},
|
|
1372
|
+
// 字面量能否安全地按数字发射:String(Number(s)) 必须与原串完全一致。
|
|
1373
|
+
// "0x0D"/"007"/"1.50" 等 JS 数值化后会改变文本形态(Scratch 中它们是字符串,
|
|
1374
|
+
// 如终端的 CR/LF 标记 "0x0D")→ 必须按字符串字面量保留
|
|
1375
|
+
NumRoundTrips(str) {
|
|
1376
|
+
if (typeof str !== 'string') return false;
|
|
1377
|
+
if (str.startsWith('"') && str.endsWith('"')) str = str.slice(1, -1);
|
|
1378
|
+
if (!/^[-+]?(\.[0-9]|[0-9])/.test(str)) return false;
|
|
1379
|
+
const num = Number(str);
|
|
1380
|
+
if (!Number.isFinite(num)) return false;
|
|
1381
|
+
return String(num) === str;
|
|
1382
|
+
},
|
|
1383
|
+
toBool(str) { if (!str || str === '') return 'false'; return str; },
|
|
1384
|
+
toChar(str) { return "'" + str.replace(/\\/g, '\\\\').replace(/'/g, "\\'") + "'"; },
|
|
1385
|
+
toKeyword(str) { if (typeof str === 'string') return str.slice(1, -1); return ''; },
|
|
1386
|
+
toPress(pressfield) {
|
|
1387
|
+
switch (pressfield) {
|
|
1388
|
+
case 'space': return "Char(' ')";
|
|
1389
|
+
case 'up arrow': return 'Up';
|
|
1390
|
+
case 'down arrow': return 'Down';
|
|
1391
|
+
case 'right arrow': return 'Right';
|
|
1392
|
+
case 'left arrow': return 'Left';
|
|
1393
|
+
case 'enter': return 'Enter';
|
|
1394
|
+
case 'any': return 'Char(c)';
|
|
1395
|
+
case 'backspace': return 'Backspace';
|
|
1396
|
+
case 'delete': return 'Delete';
|
|
1397
|
+
case 'shift': case 'control': return 'Null';
|
|
1398
|
+
case 'caps lock': return 'CapsLock';
|
|
1399
|
+
case 'scroll lock': return 'ScrollLock';
|
|
1400
|
+
case 'escape': return 'Esc';
|
|
1401
|
+
case 'insert': return 'Insert';
|
|
1402
|
+
case 'home': return 'Home';
|
|
1403
|
+
case 'end': return 'End';
|
|
1404
|
+
case 'page up': return 'PageUp';
|
|
1405
|
+
case 'page down': return 'PageD';
|
|
1406
|
+
default: return `Char(${C.toChar(String(pressfield))})`;
|
|
1407
|
+
}
|
|
1408
|
+
},
|
|
1409
|
+
unParse: castUnParse,
|
|
1410
|
+
keywordunParse(name) { return String(kwParse(String(name))); },
|
|
1411
|
+
keywordOnly,
|
|
1412
|
+
Safe(str) { if (!str) return ''; return str.block ? str.block() : String(str); },
|
|
1413
|
+
SafeBool(str) {
|
|
1414
|
+
if (!str) return 'false';
|
|
1415
|
+
if (str.type === 'Bool') return str.Bool();
|
|
1416
|
+
if (str.Stu) { runtimeStr2Bool(); return `string_to_boolean(${str.Stu()})`; }
|
|
1417
|
+
runtimeStr2Bool(); return `string_to_boolean(&(${String(str)}))`;
|
|
1418
|
+
},
|
|
1419
|
+
replaceParentheses(str) {
|
|
1420
|
+
if (!str) return str;
|
|
1421
|
+
if (str.startsWith('(') && str.endsWith(')')) return str.slice(1, -1);
|
|
1422
|
+
return str;
|
|
1423
|
+
}
|
|
1424
|
+
};
|
|
1425
|
+
|
|
1426
|
+
// ============ Tools(扩展兼容接口)============
|
|
1427
|
+
const Tools = {
|
|
1428
|
+
setlibrary(items) { (items || []).forEach(i => emit.use(i)); },
|
|
1429
|
+
setdepend(items) { (items || []).forEach(i => emit.dep(i)); },
|
|
1430
|
+
setruntime(items) { (items || []).forEach(i => emit.runtime(i)); },
|
|
1431
|
+
setfunc(items) { (items || []).forEach(i => emit.func(i)); },
|
|
1432
|
+
setstruct(items) {
|
|
1433
|
+
(items || []).forEach(([name, ty, init]) => emit.field(name, ty, init));
|
|
1434
|
+
},
|
|
1435
|
+
setmain(items) { (items || []).forEach(i => emit.main(i)); },
|
|
1436
|
+
setusedvars() { }, setclonevar() { }, setreq() { },
|
|
1437
|
+
setinuse(items) { (items || []).forEach(i => { if (!S.inuselist.includes(i)) S.inuselist.push(i); }); },
|
|
1438
|
+
setextrablockcompile(src) { loadExtensionSource(src); },
|
|
1439
|
+
setmethodcompile(extInstance) { registerExtensionInstance(extInstance); }
|
|
1440
|
+
};
|
|
1441
|
+
|
|
1442
|
+
// ============ 扩展注册 ============
|
|
1443
|
+
const BlockType = { COMMAND: 'm', CONDITIONAL: 'm', LOOP: 'm', HAT: 'm', REPORTER: 'r', BOOLEAN: 'r', LABEL: 'u', XML: 'u', BUTTON: 'u' };
|
|
1444
|
+
function registerExtensionInstance(ext) {
|
|
1445
|
+
let blocks = ext.blocks, id = ext.id;
|
|
1446
|
+
if ((!blocks || !id) && ext.getInfo) {
|
|
1447
|
+
const info = ext.getInfo();
|
|
1448
|
+
id = info.id; blocks = info.blocks;
|
|
1449
|
+
}
|
|
1450
|
+
if (!blocks || !id) return;
|
|
1451
|
+
blocks.forEach(b => {
|
|
1452
|
+
if (typeof b !== 'object' || !b.opcode) return;
|
|
1453
|
+
if (b.blockType === 'u' || b.blockType === 'LABEL' || b.blockType === 'BUTTON' || b.func) return;
|
|
1454
|
+
const opcode = id + '_' + b.opcode;
|
|
1455
|
+
const fn = ext[b.opcode];
|
|
1456
|
+
if (typeof fn !== 'function') return;
|
|
1457
|
+
S.compiles[opcode] = fn.bind(ext);
|
|
1458
|
+
if (b.blockType === 'r' || b.blockType === 'REPORTER' || b.blockType === 'BOOLEAN') {
|
|
1459
|
+
S.inputscompiles[opcode] = S.compiles[opcode];
|
|
1460
|
+
if (!S.inputlist.includes(opcode)) S.inputlist.push(opcode);
|
|
1461
|
+
}
|
|
1462
|
+
if (b.blockStart || b.blockType === 'HAT') {
|
|
1463
|
+
if (!S.compileEvents.includes(opcode)) S.compileEvents.push(opcode);
|
|
1464
|
+
}
|
|
1465
|
+
if (b.isOperator && !S.operatorlist.includes(opcode)) S.operatorlist.push(opcode);
|
|
1466
|
+
if (b.autoInput && !S.noAutoInput.includes(opcode)) S.noAutoInput.push(opcode);
|
|
1467
|
+
});
|
|
1468
|
+
}
|
|
1469
|
+
function loadExtensionSource(src) {
|
|
1470
|
+
const utilCtx = {
|
|
1471
|
+
rcompiler: null, JSZip, path, TypeInput: T, Cast: C, Tools, compile_this, BlockType,
|
|
1472
|
+
extensions: { register: (e) => registerExtensionInstance(e) },
|
|
1473
|
+
isCompiler: true,
|
|
1474
|
+
ThrowError: (e) => { throw new Error(e); }
|
|
1475
|
+
};
|
|
1476
|
+
if (S.profile.extensionStorage && S.profile.extensionStorage.config && S.profile.extensionStorage.config.AllowThis) {
|
|
1477
|
+
utilCtx.rcompiler = api;
|
|
1478
|
+
}
|
|
1479
|
+
const fn = new Function(src);
|
|
1480
|
+
fn.call(utilCtx);
|
|
1481
|
+
}
|
|
1482
|
+
|
|
1483
|
+
// ============ 脚本注册 ============
|
|
1484
|
+
function scriptSig(name, kind) {
|
|
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
|
+
}
|
|
1492
|
+
return `fn ${name}(${S.selfmut ? '&mut self' : '&self'})`;
|
|
1493
|
+
}
|
|
1494
|
+
function registerScript(name, body, kind = 'flag', info = {}) {
|
|
1495
|
+
const inuse = S.inuselist.length ? S.inuselist.join('\n') + '\n' : '';
|
|
1496
|
+
const kindLabel = { flag: '绿旗脚本', broadcast: '广播接收脚本', click: '点击脚本', key: '按键脚本', hat: '起动帽脚本', clone: '克隆脚本' }[kind] || (kind + ' 脚本');
|
|
1497
|
+
const extra = info && info.broadcast != null ? ` · 广播「${info.broadcast}」` : '';
|
|
1498
|
+
const hdr = debug ? `// rcompiler · 角色「${targetNameOf(S.targetID)}」 · ${kindLabel}${extra}\n` : '';
|
|
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`;
|
|
1504
|
+
emit.func(fn);
|
|
1505
|
+
// 广播帽仅在收到广播时执行,不随 runflag 启动
|
|
1506
|
+
if (kind !== 'broadcast') emit.scripts.push({ name, kind, ti: S.targetID });
|
|
1507
|
+
return name;
|
|
1508
|
+
}
|
|
1509
|
+
|
|
1510
|
+
// ============ 块编译 ============
|
|
1511
|
+
// 调试模式的行标记:后续 emit.rust 会把它替换成注释并记录行号→块映射,
|
|
1512
|
+
// 不增加行数,因此 cargo 报错行号可直接映射回原项目积木。
|
|
1513
|
+
function debugMarker(bid, block) {
|
|
1514
|
+
const x = Number.isFinite(Number(block.x)) ? Number(block.x) : null;
|
|
1515
|
+
const y = Number.isFinite(Number(block.y)) ? Number(block.y) : null;
|
|
1516
|
+
return `//^RC:${JSON.stringify({ t: S.targetID, b: String(bid), op: String(block.opcode || ''), x, y })}\n`;
|
|
1517
|
+
}
|
|
1518
|
+
|
|
1519
|
+
async function compile_chain(startId, target) {
|
|
1520
|
+
let out = '';
|
|
1521
|
+
let curId = startId || null;
|
|
1522
|
+
let cur = curId ? target.blocks[curId] : null;
|
|
1523
|
+
while (cur) {
|
|
1524
|
+
if (S.compileEvents.includes(cur.opcode)) break; // 事件帽不允许出现在中间
|
|
1525
|
+
const code = await compile_block(cur, target, curId);
|
|
1526
|
+
out += (debug && curId && code) ? debugMarker(curId, cur) + code : code;
|
|
1527
|
+
curId = cur.next || null;
|
|
1528
|
+
cur = curId ? target.blocks[curId] : null;
|
|
1529
|
+
}
|
|
1530
|
+
return out;
|
|
1531
|
+
}
|
|
1532
|
+
|
|
1533
|
+
async function compile_input(block, target) {
|
|
1534
|
+
const jsonObj = block.inputs || {};
|
|
1535
|
+
const inputs = {};
|
|
1536
|
+
if (S.noAutoInput.includes(block.opcode)) return inputs;
|
|
1537
|
+
// %c 分支参数不按值输入编译(由 procedures_call 编译器整体编译分支链)
|
|
1538
|
+
let branchKeys = null;
|
|
1539
|
+
if (block.opcode === 'procedures_call' && block.mutation) {
|
|
1540
|
+
const holes = parseProcHoles(String(block.mutation.proccode || ''));
|
|
1541
|
+
const ids = safeJSON(block.mutation.argumentids);
|
|
1542
|
+
branchKeys = new Set(ids.filter((id, i) => holes[i] === '%c'));
|
|
1543
|
+
}
|
|
1544
|
+
for (const key in jsonObj) {
|
|
1545
|
+
if (branchKeys && branchKeys.has(key)) continue;
|
|
1546
|
+
const val = jsonObj[key];
|
|
1547
|
+
if (!Array.isArray(val) || val.length < 2) { inputs[key] = key === 'CONDITION' ? 'false' : ''; continue; }
|
|
1548
|
+
const code = val[0];
|
|
1549
|
+
let ref;
|
|
1550
|
+
if (code === 3) {
|
|
1551
|
+
// [3, block, shadow]:块遮挡影子 —— block 在 val[1](字符串 id 或 [12]/[13]/[11] 数组)
|
|
1552
|
+
ref = val[1];
|
|
1553
|
+
} else {
|
|
1554
|
+
// [1|2, shadow] 或 [1|2, blockId](兼容)
|
|
1555
|
+
ref = val[1];
|
|
1556
|
+
}
|
|
1557
|
+
if (ref == null) { inputs[key] = key === 'CONDITION' ? 'false' : ''; continue; }
|
|
1558
|
+
if (Array.isArray(ref)) {
|
|
1559
|
+
const code = ref[0];
|
|
1560
|
+
if (code === 12) inputs[key] = new T.Var(String(ref[1]), ref[2]); // 变量
|
|
1561
|
+
else if (code === 13) inputs[key] = new T.ListVar(String(ref[1]), ref[2]); // 列表
|
|
1562
|
+
else if (code === 11) inputs[key] = new T.Raw(ref[1]); // 广播
|
|
1563
|
+
else {
|
|
1564
|
+
const s = String(ref[1] == null ? '' : ref[1]);
|
|
1565
|
+
// 仅当字面量经 JS 数值化后文本形态不变才按数字发射,
|
|
1566
|
+
// 否则保留原始字符串("0x0D" 是终端的 CR 标记,不能变成 13)
|
|
1567
|
+
if (C.NumRoundTrips(s)) inputs[key] = new T.Num(C.toNum(s));
|
|
1568
|
+
else inputs[key] = new T.Str(castUnParse(s));
|
|
1569
|
+
}
|
|
1570
|
+
continue;
|
|
1571
|
+
}
|
|
1572
|
+
if (typeof ref === 'string') {
|
|
1573
|
+
const cb = target.blocks[ref];
|
|
1574
|
+
if (!cb) { inputs[key] = key === 'CONDITION' ? 'false' : ''; continue; }
|
|
1575
|
+
// 被忽略扩展的报告器/布尔块:取中性值(数值 0 / 字符串空 / 布尔 false)
|
|
1576
|
+
if (S.ignoreExt.size && isIgnoredExtOp(cb.opcode, S.ignoreExt)) { inputs[key] = new T.Block(''); continue; }
|
|
1577
|
+
if (cb.opcode === 'procedures_call') {
|
|
1578
|
+
if (cb.mutation && cb.mutation.return) {
|
|
1579
|
+
inputs[key] = await compile_proc_call_value(cb, target);
|
|
1580
|
+
} else {
|
|
1581
|
+
// 语句调用可能位于分支链头部(如 for_each 体内),编译整条链
|
|
1582
|
+
const st = await compile_chain(ref, target);
|
|
1583
|
+
inputs[key] = new T.Block(st);
|
|
1584
|
+
}
|
|
1585
|
+
} else if (S.inputlist.includes(cb.opcode)) {
|
|
1586
|
+
let comped = await compile_input(cb, target);
|
|
1587
|
+
if (process.env.RCOMPILER_DEBUG) console.error('[dbg input]', block.opcode, key, '->', cb.opcode, comped && comped.constructor && comped.constructor.name, JSON.stringify(comped && comped.input || String(comped).slice(0,40)));
|
|
1588
|
+
if (S.operatorlist.includes(cb.opcode) && !S.operatorlist.includes(block.opcode)) {
|
|
1589
|
+
if (comped && typeof comped === 'object' && Object.prototype.hasOwnProperty.call(comped, 'input')) {
|
|
1590
|
+
comped.input = C.replaceParentheses(comped.input);
|
|
1591
|
+
}
|
|
1592
|
+
}
|
|
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('');
|
|
1598
|
+
} else {
|
|
1599
|
+
// 语句链(SUBSTACK 等分支输入):必须编译整条链。
|
|
1600
|
+
// 此前用 compile_block 只编译首块——所有 if/循环体都会被截断成一条语句!
|
|
1601
|
+
const st = await compile_chain(ref, target);
|
|
1602
|
+
inputs[key] = new T.Block(st);
|
|
1603
|
+
}
|
|
1604
|
+
}
|
|
1605
|
+
}
|
|
1606
|
+
if (block.opcode === 'procedures_call') return inputs;
|
|
1607
|
+
if (S.inputscompiles[block.opcode]) {
|
|
1608
|
+
inputs.scope = { block, target };
|
|
1609
|
+
return await S.inputscompiles[block.opcode](inputs);
|
|
1610
|
+
}
|
|
1611
|
+
return inputs;
|
|
1612
|
+
}
|
|
1613
|
+
|
|
1614
|
+
async function compile_block(block, target, bid) {
|
|
1615
|
+
if (!block) return '';
|
|
1616
|
+
// "调试→自动忽略扩展":名单中扩展的全部语句块(含帽/分支体)编译时跳过
|
|
1617
|
+
if (S.ignoreExt.size && isIgnoredExtOp(block.opcode, S.ignoreExt)) return '';
|
|
1618
|
+
S.blockcount++;
|
|
1619
|
+
try {
|
|
1620
|
+
let inputs = {};
|
|
1621
|
+
if (block.inputs && Object.keys(block.inputs).length > 0 && !S.noAutoInput.includes(block.opcode)) {
|
|
1622
|
+
inputs = await compile_input(block, target);
|
|
1623
|
+
}
|
|
1624
|
+
if (S.compiles[block.opcode]) {
|
|
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 = '';
|
|
1630
|
+
const r = await S.compiles[block.opcode](inputs);
|
|
1631
|
+
const code = typeof r === 'string' ? r : ((r && r.compiler) || '');
|
|
1632
|
+
return injectStageIdx(code);
|
|
1633
|
+
}
|
|
1634
|
+
if (!S.ignore && !S.unknownWarned) {
|
|
1635
|
+
if (!S.unknownWarned) S.unknownWarned = new Set();
|
|
1636
|
+
if (!S.unknownWarned.has(block.opcode)) {
|
|
1637
|
+
S.unknownWarned.add(block.opcode);
|
|
1638
|
+
console.warn(`\x1b[33m未知的块\x1b[m: ${block.opcode}`);
|
|
1639
|
+
}
|
|
1640
|
+
}
|
|
1641
|
+
return '';
|
|
1642
|
+
} catch (e) {
|
|
1643
|
+
// 生成期异常带上原项目定位(CLI 会打印角色/积木/块 id)
|
|
1644
|
+
if (e && !e.rcompilerCtx) {
|
|
1645
|
+
e.rcompilerCtx = {
|
|
1646
|
+
target: targetNameOf(S.targetID),
|
|
1647
|
+
opcode: String(block.opcode || ''),
|
|
1648
|
+
block: bid || null
|
|
1649
|
+
};
|
|
1650
|
+
}
|
|
1651
|
+
throw e;
|
|
1652
|
+
}
|
|
1653
|
+
}
|
|
1654
|
+
|
|
1655
|
+
// 舞台桥接 idx 注入:普通脚本 → 编译期目标索引;克隆脚本 → self.sprite_index;
|
|
1656
|
+
// globalcaller 过程体 → __rcaller(调用方运行期索引,严格对照 rCodenow
|
|
1657
|
+
// sequencer.stepToProcedure 的 target 语义:共享积木随调用方运行)
|
|
1658
|
+
// 幂等:已注入(`(` 后紧跟 idx 表达式 + `,`/`)`)的调用不再二次注入——
|
|
1659
|
+
// 嵌套栈(repeat/forever 的 SUBSTACK)会被外层 compile_block 再次处理
|
|
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']);
|
|
1663
|
+
const reEscape = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
1664
|
+
// 舞台桥接 idx 表达式:globalcaller 过程体 → __rcaller(调用方运行期索引);
|
|
1665
|
+
// 克隆脚本 → self.sprite_index;广播接收脚本 → 原型/克隆各自索引;普通脚本 → 编译期索引
|
|
1666
|
+
function stageIdxExpr() {
|
|
1667
|
+
if (S.stageIdxOverride) return S.stageIdxOverride;
|
|
1668
|
+
if (S.curKind === 'clone') return 'self.sprite_index';
|
|
1669
|
+
if (S.curKind === 'broadcast') return `self.rcompiler_self_idx(${S.targetID})`;
|
|
1670
|
+
return String(S.targetID);
|
|
1671
|
+
}
|
|
1672
|
+
function injectStageIdx(code) {
|
|
1673
|
+
if (!S.profile.hasStage || !code || code.indexOf('self.s_') === -1) return code;
|
|
1674
|
+
const idxExpr = stageIdxExpr();
|
|
1675
|
+
const idxRe = reEscape(idxExpr);
|
|
1676
|
+
const re = new RegExp('self\\.s_([a-z_]+)\\((\\s*)(?!' + idxRe + '\\s*,)(?!' + idxRe + '\\s*\\))', 'g');
|
|
1677
|
+
return code.replace(re, (m, name, ws, offset, str) => {
|
|
1678
|
+
if (STAGE_NOIDX.has(name)) return m;
|
|
1679
|
+
// `(` 后紧跟 `)` → 无参:注入 `idx`(原 `)` 保留收尾);否则注入 `idx, `
|
|
1680
|
+
if (str[offset + m.length] === ')') return `self.s_${name}(${ws}${idxExpr}`;
|
|
1681
|
+
return `self.s_${name}(${ws}${idxExpr}, `;
|
|
1682
|
+
});
|
|
1683
|
+
}
|
|
1684
|
+
|
|
1685
|
+
function compile_this(block, target) {
|
|
1686
|
+
return compile_chain(block && block.next, target);
|
|
1687
|
+
}
|
|
1688
|
+
|
|
1689
|
+
// ============ 过程(自定义积木 / 高级自制积木)============
|
|
1690
|
+
function parseProcHoles(proccode) {
|
|
1691
|
+
const out = [];
|
|
1692
|
+
const re = /%[snbci]/g;
|
|
1693
|
+
let m;
|
|
1694
|
+
while ((m = re.exec(String(proccode))) !== null) out.push(m[0]);
|
|
1695
|
+
return out;
|
|
1696
|
+
}
|
|
1697
|
+
|
|
1698
|
+
function scanProcedures() {
|
|
1699
|
+
targets.forEach((target, ti) => {
|
|
1700
|
+
for (const bid in (target.blocks || {})) {
|
|
1701
|
+
const b = target.blocks[bid];
|
|
1702
|
+
if (!b || b.opcode !== 'procedures_definition') continue;
|
|
1703
|
+
S.proccount++;
|
|
1704
|
+
const parsed = dbgFnAt(ti, 'proc' + S.proccount);
|
|
1705
|
+
const protoId = b.inputs && b.inputs.custom_block ? b.inputs.custom_block[1] : null;
|
|
1706
|
+
const proto = protoId ? target.blocks[protoId] : null;
|
|
1707
|
+
const mut = (proto && proto.mutation) || {};
|
|
1708
|
+
const holes = parseProcHoles(String(mut.proccode || ''));
|
|
1709
|
+
const argIds = safeJSON(mut.argumentids);
|
|
1710
|
+
const argNames = safeJSON(mut.argumentnames);
|
|
1711
|
+
const argDefaults = safeJSON(mut.argumentdefaults);
|
|
1712
|
+
// 原型输入影子块类型:argument_reporter_boolean → bool;argument_command → 分支
|
|
1713
|
+
const shadowOpcode = (aid) => {
|
|
1714
|
+
const inp = proto && proto.inputs ? proto.inputs[aid] : null;
|
|
1715
|
+
if (inp && Array.isArray(inp) && typeof inp[1] === 'string') {
|
|
1716
|
+
const ab = target.blocks[inp[1]];
|
|
1717
|
+
if (ab) return ab.opcode;
|
|
1718
|
+
}
|
|
1719
|
+
return null;
|
|
1720
|
+
};
|
|
1721
|
+
const def = {
|
|
1722
|
+
proccode: mut.proccode || '', parsed, ti, block: b, proto,
|
|
1723
|
+
scope: ['globalcaller', 'globalowner'].includes(mut.rc_scope) ? mut.rc_scope : 'local',
|
|
1724
|
+
shape: ['hat', 'cap', 'return', 'boolreturn'].includes(mut.rc_shape) ? mut.rc_shape : 'stack',
|
|
1725
|
+
warp: mut.warp === 'true' || mut.warp === true,
|
|
1726
|
+
localvars: mut.rc_localvars === 'true' || mut.rc_localvars === true,
|
|
1727
|
+
holes, argIds, argNames, argDefaults,
|
|
1728
|
+
names: [], types: [], // 值参数(按洞序,跳过 %c)
|
|
1729
|
+
branchNames: new Map(), // 参数名 -> argId(%c)
|
|
1730
|
+
hasReturn: false, recursive: false,
|
|
1731
|
+
bodyHasStage: false, takesCaller: false,
|
|
1732
|
+
procCallees: new Set(), spawnsClones: false,
|
|
1733
|
+
usedArgs: null, localShadow: null,
|
|
1734
|
+
hasVariants: holes.includes('%c') || mut.rc_shape === 'hat'
|
|
1735
|
+
};
|
|
1736
|
+
argIds.forEach((aid, i) => {
|
|
1737
|
+
const hole = holes[i] || '%s';
|
|
1738
|
+
const name = (argNames && argNames[i]) ? String(argNames[i]) : ('arg' + i);
|
|
1739
|
+
if (hole === '%c' || shadowOpcode(aid) === 'argument_command') {
|
|
1740
|
+
def.branchNames.set(name, aid);
|
|
1741
|
+
return;
|
|
1742
|
+
}
|
|
1743
|
+
const ty = (hole === '%b' || shadowOpcode(aid) === 'argument_reporter_boolean') ? 'bool' : '&str';
|
|
1744
|
+
def.types.push(ty);
|
|
1745
|
+
def.names.push(name);
|
|
1746
|
+
});
|
|
1747
|
+
// 返回值预扫描(修复:调用点先于过程体编译时的 hasReturn 未知问题)
|
|
1748
|
+
// 及 过程调用图 / 舞台桥接使用预扫描(供 __rcaller 与递归判定)
|
|
1749
|
+
prescanDef(def, target);
|
|
1750
|
+
S.procdefs.push(def);
|
|
1751
|
+
if (!S.procbycode.has(def.proccode)) S.procbycode.set(def.proccode, def);
|
|
1752
|
+
}
|
|
1753
|
+
});
|
|
1754
|
+
// __rcaller 传播定点:调用“需要调用方 idx 的过程”的过程同样需要
|
|
1755
|
+
// (仅在舞台模块启用时有意义——舞台桥接调用才需要运行期目标索引)
|
|
1756
|
+
let changed = true;
|
|
1757
|
+
while (changed) {
|
|
1758
|
+
changed = false;
|
|
1759
|
+
for (const def of S.procdefs) {
|
|
1760
|
+
if (def.takesCaller) continue;
|
|
1761
|
+
const need = (def.bodyHasStage && S.profile.hasStage) ||
|
|
1762
|
+
[...def.procCallees].some(code => { const d = S.procbycode.get(code); return d && d.takesCaller; });
|
|
1763
|
+
if (need) { def.takesCaller = true; changed = true; }
|
|
1764
|
+
}
|
|
1765
|
+
}
|
|
1766
|
+
|
|
1767
|
+
// ============ 过程参数数值类型推断(通用) ============
|
|
1768
|
+
// 全调用点实参静态可证为数值 → 参数以 f64 传递:调用端省 rcompiler_num_str 格式化,
|
|
1769
|
+
// 过程体端省逐次 get_f64_string 解析——热路径每条语句可能经过 10+ 个过程调用,
|
|
1770
|
+
// 字符串形参是残余瓶颈的主项。分类保守:非确定数值的实参(动态/字符串/未类型化
|
|
1771
|
+
// 变量)都会使参数退回 &str(现状语义)。
|
|
1772
|
+
const blockDef = new Map(); // blockId -> 所属 def(过程体内的块归属)
|
|
1773
|
+
for (const def of S.procdefs) {
|
|
1774
|
+
const target = targets[def.ti];
|
|
1775
|
+
const seen2 = new Set();
|
|
1776
|
+
const visitAttr = (id) => {
|
|
1777
|
+
if (!id || seen2.has(id)) return;
|
|
1778
|
+
seen2.add(id);
|
|
1779
|
+
blockDef.set(id, def);
|
|
1780
|
+
const b = target.blocks[id];
|
|
1781
|
+
if (!b || typeof b !== 'object') return;
|
|
1782
|
+
if (b.next) visitAttr(b.next);
|
|
1783
|
+
if (b.inputs) for (const key in b.inputs) {
|
|
1784
|
+
const val = b.inputs[key];
|
|
1785
|
+
if (Array.isArray(val) && typeof val[1] === 'string') visitAttr(val[1]);
|
|
1786
|
+
}
|
|
1787
|
+
};
|
|
1788
|
+
visitAttr(def.block.next);
|
|
1789
|
+
}
|
|
1790
|
+
const classifyArgNum = (input, target, endef) => {
|
|
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);
|
|
1795
|
+
const val = input[1];
|
|
1796
|
+
if (Array.isArray(val)) {
|
|
1797
|
+
const code = val[0];
|
|
1798
|
+
if (code === 4 || code === 5 || code === 6) return true; // 数字字面量
|
|
1799
|
+
if (code === 10 || code === 8 || code === 9) return false; // 文本/颜色
|
|
1800
|
+
if (code === 12) {
|
|
1801
|
+
const v = varById(String(val[2]));
|
|
1802
|
+
return !!(v && v.declared === 'f64');
|
|
1803
|
+
}
|
|
1804
|
+
if (code === 13) {
|
|
1805
|
+
const l = listById(String(val[2]));
|
|
1806
|
+
return !!(l && l.declared === 'f64');
|
|
1807
|
+
}
|
|
1808
|
+
return false;
|
|
1809
|
+
}
|
|
1810
|
+
const blk = target.blocks[val];
|
|
1811
|
+
if (!blk) return false;
|
|
1812
|
+
switch (blk.opcode) {
|
|
1813
|
+
case 'operator_add': case 'operator_subtract': case 'operator_multiply':
|
|
1814
|
+
case 'operator_divide': case 'operator_mod': case 'operator_random':
|
|
1815
|
+
case 'operator_mathop': case 'sensing_dayssince2000': case 'sensing_timer':
|
|
1816
|
+
case 'data_lengthoflist': case 'data_itemnumoflist':
|
|
1817
|
+
return true;
|
|
1818
|
+
case 'data_variable': {
|
|
1819
|
+
const vid = blk.fields && blk.fields.VARIABLE && blk.fields.VARIABLE[1];
|
|
1820
|
+
const v = vid && varById(String(vid));
|
|
1821
|
+
return !!(v && v.declared === 'f64');
|
|
1822
|
+
}
|
|
1823
|
+
case 'data_itemoflist': {
|
|
1824
|
+
const lid = blk.fields && blk.fields.LIST && blk.fields.LIST[1];
|
|
1825
|
+
const l = lid && listById(String(lid));
|
|
1826
|
+
return !!(l && l.declared === 'f64');
|
|
1827
|
+
}
|
|
1828
|
+
case 'argument_reporter_string_number': {
|
|
1829
|
+
// 转发所在过程的 f64 参数(定点传播)
|
|
1830
|
+
const nm = blk.fields && blk.fields.VALUE && String(blk.fields.VALUE[0]);
|
|
1831
|
+
if (!endef) return false;
|
|
1832
|
+
const idx = endef.names.indexOf(nm);
|
|
1833
|
+
return idx >= 0 ? !!endef.numericArgs[idx] : false;
|
|
1834
|
+
}
|
|
1835
|
+
default: return false;
|
|
1836
|
+
}
|
|
1837
|
+
};
|
|
1838
|
+
for (const def of S.procdefs) def.numericArgs = def.names.map(() => true);
|
|
1839
|
+
let passNum = 0, changedNum = true;
|
|
1840
|
+
while (changedNum && passNum < 8) {
|
|
1841
|
+
changedNum = false; passNum++;
|
|
1842
|
+
for (const target of targets) {
|
|
1843
|
+
for (const bid in (target.blocks || {})) {
|
|
1844
|
+
const b = target.blocks[bid];
|
|
1845
|
+
if (!b || b.opcode !== 'procedures_call' || !b.mutation) continue;
|
|
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));
|
|
1850
|
+
if (!def) continue;
|
|
1851
|
+
const endef = blockDef.get(bid) || null;
|
|
1852
|
+
let vi = 0;
|
|
1853
|
+
for (let i = 0; i < def.argIds.length; i++) {
|
|
1854
|
+
const hole = def.holes[i] || '%s';
|
|
1855
|
+
if (hole === '%c' || def.branchNames.has(String(def.argNames && def.argNames[i]))) continue;
|
|
1856
|
+
if (def.numericArgs[vi] && !classifyArgNum(b.inputs[def.argIds[i]], target, endef)) {
|
|
1857
|
+
def.numericArgs[vi] = false; changedNum = true; // 否决单调传播至定点
|
|
1858
|
+
}
|
|
1859
|
+
vi++;
|
|
1860
|
+
}
|
|
1861
|
+
}
|
|
1862
|
+
}
|
|
1863
|
+
}
|
|
1864
|
+
for (const def of S.procdefs) {
|
|
1865
|
+
for (let vi = 0; vi < def.types.length; vi++) {
|
|
1866
|
+
if (def.types[vi] === '&str' && def.numericArgs && def.numericArgs[vi]) def.types[vi] = 'f64';
|
|
1867
|
+
}
|
|
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
|
+
}
|
|
1883
|
+
// ============ 过程参数数值类型推断结束 ============
|
|
1884
|
+
|
|
1885
|
+
// 递归(异步调用环)检测:await 边 + spawn 边;环上函数需装箱
|
|
1886
|
+
// (这正是“不循环克隆的角色”的自动侦测:克隆脚本若不自克隆/不成环
|
|
1887
|
+
// 则保持零装箱直连调用,性能最佳)
|
|
1888
|
+
const edges = new Map(); // nodeKey -> Set(nodeKey)
|
|
1889
|
+
for (const def of S.procdefs) {
|
|
1890
|
+
const k = 'p:' + def.parsed;
|
|
1891
|
+
if (!edges.has(k)) edges.set(k, new Set());
|
|
1892
|
+
for (const code of def.procCallees) {
|
|
1893
|
+
const d = S.procbycode.get(code);
|
|
1894
|
+
if (d) edges.get(k).add('p:' + d.parsed);
|
|
1895
|
+
}
|
|
1896
|
+
if (def.spawnsClones) for (const [ti2, fns] of S.cloneFnsByTarget) {
|
|
1897
|
+
for (const f of fns) edges.get(k).add('c:' + f);
|
|
1898
|
+
}
|
|
1899
|
+
}
|
|
1900
|
+
for (const [ti2, fns] of S.cloneFnsByTarget) {
|
|
1901
|
+
for (const f of fns) {
|
|
1902
|
+
const k = 'c:' + f;
|
|
1903
|
+
if (!edges.has(k)) edges.set(k, new Set());
|
|
1904
|
+
const info = S.cloneFnInfo.get(f);
|
|
1905
|
+
if (info) {
|
|
1906
|
+
for (const code of info.callees) {
|
|
1907
|
+
const d = S.procbycode.get(code);
|
|
1908
|
+
if (d) edges.get(k).add('p:' + d.parsed);
|
|
1909
|
+
}
|
|
1910
|
+
if (info.spawns) for (const [, fns2] of S.cloneFnsByTarget) for (const f2 of fns2) edges.get(k).add('c:' + f2);
|
|
1911
|
+
}
|
|
1912
|
+
}
|
|
1913
|
+
}
|
|
1914
|
+
const reachesSelf = (start) => {
|
|
1915
|
+
const seen = new Set();
|
|
1916
|
+
const stack = [...(edges.get(start) || [])];
|
|
1917
|
+
while (stack.length) {
|
|
1918
|
+
const n = stack.pop();
|
|
1919
|
+
if (n === start) return true;
|
|
1920
|
+
if (seen.has(n)) continue;
|
|
1921
|
+
seen.add(n);
|
|
1922
|
+
for (const nx of (edges.get(n) || [])) if (!seen.has(nx)) stack.push(nx);
|
|
1923
|
+
}
|
|
1924
|
+
return false;
|
|
1925
|
+
};
|
|
1926
|
+
for (const def of S.procdefs) def.recursive = reachesSelf('p:' + def.parsed);
|
|
1927
|
+
for (const [ti2, fns] of S.cloneFnsByTarget) {
|
|
1928
|
+
for (const f of fns) S.cloneFnInfo.get(f).recursive = reachesSelf('c:' + f);
|
|
1929
|
+
}
|
|
1930
|
+
}
|
|
1931
|
+
|
|
1932
|
+
// 过程体静态预扫描:procedures_return(返回值)、procedures_call 边、
|
|
1933
|
+
// 舞台桥接积木、克隆生成。分支输入(%c,shape 2)属于调用方,不深入。
|
|
1934
|
+
const STAGE_BODY_OPS = (() => {
|
|
1935
|
+
const looks = new Set(['say', 'think', 'sayforsecs', 'thinkforsecs', 'switchcostumeto', 'nextcostume',
|
|
1936
|
+
'switchbackdropto', 'nextbackdrop', 'changesizeby', 'setsizeto', 'changeeffectby', 'seteffectto',
|
|
1937
|
+
'cleargraphiceffects', 'show', 'hide', 'gotofrontback', 'gobacknlayers', 'costumenumbername', 'backdropnumbername']);
|
|
1938
|
+
const sensing = new Set(['touchingobject', 'distanceto', 'keypressed', 'mousedown', 'mousex', 'mousey']);
|
|
1939
|
+
return { looks, sensing };
|
|
1940
|
+
})();
|
|
1941
|
+
function blockTouchesStage(op) {
|
|
1942
|
+
if (op.startsWith('motion_') || op.startsWith('pen_')) return true;
|
|
1943
|
+
if (op.startsWith('looks_')) return STAGE_BODY_OPS.looks.has(op.slice(6));
|
|
1944
|
+
if (op.startsWith('sensing_')) return STAGE_BODY_OPS.sensing.has(op.slice(8));
|
|
1945
|
+
return false;
|
|
1946
|
+
}
|
|
1947
|
+
function prescanDef(def, target) {
|
|
1948
|
+
const seen = new Set();
|
|
1949
|
+
const visit = (id) => {
|
|
1950
|
+
if (!id || seen.has(id)) return;
|
|
1951
|
+
seen.add(id);
|
|
1952
|
+
const b = target.blocks[id];
|
|
1953
|
+
if (!b || typeof b !== 'object') return;
|
|
1954
|
+
if (b.opcode === 'procedures_return') def.hasReturn = true;
|
|
1955
|
+
if (blockTouchesStage(b.opcode)) def.bodyHasStage = true;
|
|
1956
|
+
if (b.opcode === 'procedures_call' && b.mutation) def.procCallees.add(String(b.mutation.proccode));
|
|
1957
|
+
if (b.opcode === 'control_create_clone_of' || b.opcode === 'rcompiler_cloneandwait') def.spawnsClones = true;
|
|
1958
|
+
if (b.next) visit(b.next);
|
|
1959
|
+
if (b.inputs) {
|
|
1960
|
+
for (const key in b.inputs) {
|
|
1961
|
+
const val = b.inputs[key];
|
|
1962
|
+
if (!Array.isArray(val) || val.length < 2) continue;
|
|
1963
|
+
// 分支输入(shape 2)属调用方语义,另由调用点变体编译
|
|
1964
|
+
if (b.opcode === 'procedures_call' && val[0] === 2) continue;
|
|
1965
|
+
if (typeof val[1] === 'string') visit(val[1]);
|
|
1966
|
+
}
|
|
1967
|
+
}
|
|
1968
|
+
};
|
|
1969
|
+
visit(def.block.next);
|
|
1970
|
+
}
|
|
1971
|
+
|
|
1972
|
+
// 克隆脚本预扫描:预分配函数名并收集 调用边/自克隆 信息
|
|
1973
|
+
// ("不循环克隆的角色"自动侦测:与过程调用图合并做环检测,
|
|
1974
|
+
// 处于 spawn 环上的克隆函数才需要装箱,其余保持零开销直连)
|
|
1975
|
+
function prescanClones() {
|
|
1976
|
+
targets.forEach((target, ti) => {
|
|
1977
|
+
for (const bid in (target.blocks || {})) {
|
|
1978
|
+
const b = target.blocks[bid];
|
|
1979
|
+
if (!b || b.opcode !== 'control_start_as_clone') continue;
|
|
1980
|
+
S.clonecount++;
|
|
1981
|
+
const fname = dbgFnAt(ti, 'start_clone_' + S.clonecount);
|
|
1982
|
+
S.cloneFnNameByBlock.set(bid, fname);
|
|
1983
|
+
// 调用点(事件/过程编译,先于克隆体)即可引用克隆函数
|
|
1984
|
+
if (!S.clonesByTarget.has(ti)) S.clonesByTarget.set(ti, []);
|
|
1985
|
+
S.clonesByTarget.get(ti).push(fname);
|
|
1986
|
+
if (!S.cloneFnsByTarget.has(ti)) S.cloneFnsByTarget.set(ti, []);
|
|
1987
|
+
S.cloneFnsByTarget.get(ti).push(fname);
|
|
1988
|
+
const info = { callees: new Set(), spawns: false, recursive: false };
|
|
1989
|
+
const seen = new Set();
|
|
1990
|
+
const visit = (id) => {
|
|
1991
|
+
if (!id || seen.has(id)) return;
|
|
1992
|
+
seen.add(id);
|
|
1993
|
+
const blk = target.blocks[id];
|
|
1994
|
+
if (!blk || typeof blk !== 'object') return;
|
|
1995
|
+
if (blk.opcode === 'procedures_call' && blk.mutation) info.callees.add(String(blk.mutation.proccode));
|
|
1996
|
+
if (blk.opcode === 'control_create_clone_of' || blk.opcode === 'rcompiler_cloneandwait') info.spawns = true;
|
|
1997
|
+
if (blk.next) visit(blk.next);
|
|
1998
|
+
if (blk.inputs) {
|
|
1999
|
+
for (const key in blk.inputs) {
|
|
2000
|
+
const val = blk.inputs[key];
|
|
2001
|
+
if (!Array.isArray(val) || val.length < 2) continue;
|
|
2002
|
+
if (blk.opcode === 'procedures_call' && val[0] === 2) continue;
|
|
2003
|
+
if (typeof val[1] === 'string') visit(val[1]);
|
|
2004
|
+
}
|
|
2005
|
+
}
|
|
2006
|
+
};
|
|
2007
|
+
visit(b.next);
|
|
2008
|
+
S.cloneFnInfo.set(fname, info);
|
|
2009
|
+
}
|
|
2010
|
+
});
|
|
2011
|
+
}
|
|
2012
|
+
|
|
2013
|
+
function safeJSON(s) { try { return JSON.parse(s || '[]'); } catch (e) { return []; } }
|
|
2014
|
+
|
|
2015
|
+
// 过程解析(对照 stepToProcedure + getProcedureDefinition):
|
|
2016
|
+
// 本角色定义优先(任意 scope),否则首个 global(globalcaller/globalowner)定义
|
|
2017
|
+
function resolveProc(code, callerTi) {
|
|
2018
|
+
let local = null, global = null;
|
|
2019
|
+
for (const def of S.procdefs) {
|
|
2020
|
+
if (def.proccode !== code) continue;
|
|
2021
|
+
if (def.ti === callerTi) { if (!local) local = def; }
|
|
2022
|
+
else if (def.scope !== 'local' && !global) global = def;
|
|
2023
|
+
}
|
|
2024
|
+
return local || global || null;
|
|
2025
|
+
}
|
|
2026
|
+
|
|
2027
|
+
// 过程体编译(供本体与调用点变体共用)
|
|
2028
|
+
// 过程体始终在定义方 target 上编译(块的容器/变量属于定义方,对照
|
|
2029
|
+
// sequencer.stepToProcedure:frame.blockContainer = owner 的 blocks)
|
|
2030
|
+
// branches: Map<参数名|'__hat_body__', code> —— argument_command / procedures_rc_body 注入点
|
|
2031
|
+
async function compileProcBody(def, target, branches) {
|
|
2032
|
+
const owner = targets[def.ti] || target;
|
|
2033
|
+
const prevProc = S.customproc, prevBranches = S.procBranches, prevOverride = S.stageIdxOverride;
|
|
2034
|
+
const prevTargetID = S.targetID;
|
|
2035
|
+
S.customproc = def;
|
|
2036
|
+
def.usedArgs = new Set();
|
|
2037
|
+
def.localShadow = new Map();
|
|
2038
|
+
S.procBranches = branches || null;
|
|
2039
|
+
S.targetID = def.ti;
|
|
2040
|
+
if (def.scope === 'globalcaller' && def.takesCaller) S.stageIdxOverride = '__rcaller';
|
|
2041
|
+
const body = await compile_chain(def.block.next, owner);
|
|
2042
|
+
S.procBranches = null;
|
|
2043
|
+
S.stageIdxOverride = null;
|
|
2044
|
+
S.targetID = prevTargetID;
|
|
2045
|
+
S.customproc = prevProc;
|
|
2046
|
+
S.procBranches = prevBranches;
|
|
2047
|
+
S.stageIdxOverride = prevOverride;
|
|
2048
|
+
return body;
|
|
2049
|
+
}
|
|
2050
|
+
|
|
2051
|
+
function procValueParams(def, args, owned) {
|
|
2052
|
+
// 值参数实参表达式(对照 call: pushParam(args[id]) → argumentdefaults)
|
|
2053
|
+
// owned=true(multi 模式):产出**拥有所有权的 String/bool 表达式**,
|
|
2054
|
+
// 由 procCallExpr 绑定到局部——MutexGuard 临时值在 await 前释放(future Send 要求)
|
|
2055
|
+
const vals = [];
|
|
2056
|
+
for (let i = 0; i < def.argIds.length; i++) {
|
|
2057
|
+
const hole = def.holes[i] || '%s';
|
|
2058
|
+
if (hole === '%c' || def.branchNames.has(String(def.argNames && def.argNames[i]))) continue;
|
|
2059
|
+
const vi = vals.length;
|
|
2060
|
+
const raw = args ? args[def.argIds[i]] : null;
|
|
2061
|
+
// 鸭子类型校验:畸形输入/元数据对象(无编译值方法)按缺失实参走默认值
|
|
2062
|
+
const v = (raw && typeof raw.Stri === 'function') ? raw : null;
|
|
2063
|
+
if (v == null) {
|
|
2064
|
+
const dflt = def.argDefaults ? def.argDefaults[i] : null;
|
|
2065
|
+
if (def.types[vi] === 'bool') vals.push('false');
|
|
2066
|
+
else if (def.types[vi] === 'f64') { runtimeParseF64(); vals.push(`get_f64_string(&${castUnParse(dflt == null ? '0' : String(dflt))})`); }
|
|
2067
|
+
else vals.push(owned ? `(${castUnParse(dflt == null ? '' : String(dflt))}).to_string()` : castUnParse(dflt == null ? '' : String(dflt)));
|
|
2068
|
+
} else {
|
|
2069
|
+
if (def.types[vi] === 'bool') vals.push(C.SafeBool(v));
|
|
2070
|
+
else if (def.types[vi] === 'f64') vals.push(v.Num());
|
|
2071
|
+
else vals.push(owned ? v.Stri() : v.Str());
|
|
2072
|
+
}
|
|
2073
|
+
}
|
|
2074
|
+
return vals;
|
|
2075
|
+
}
|
|
2076
|
+
|
|
2077
|
+
function procCallExpr(def, variantName, args) {
|
|
2078
|
+
// multi 模式过程收 Arc<Self>(过程体内可 spawn 广播/克隆任务,语义对照
|
|
2079
|
+
// rCodenow:广播/克隆在过程内与脚本内一致可用);调用点克隆一份 Arc。
|
|
2080
|
+
// 参数先绑定局部:实参里的列表锁在 .await 前析构(MutexGuard 非 Send)
|
|
2081
|
+
const awaitKw = multi() ? '.await' : '';
|
|
2082
|
+
if (!multi()) {
|
|
2083
|
+
const params = procValueParams(def, args, false);
|
|
2084
|
+
const all = [...(def.takesCaller ? [stageIdxExpr()] : []), ...params];
|
|
2085
|
+
return `self.${variantName}(${all.join(',')})${awaitKw}`;
|
|
2086
|
+
}
|
|
2087
|
+
const params = procValueParams(def, args, true);
|
|
2088
|
+
const idxExpr = def.takesCaller ? stageIdxExpr() : null;
|
|
2089
|
+
const binds = params.map((e, i) => `let __pa${i} = (${e});`).join('\n');
|
|
2090
|
+
const callArgs = [
|
|
2091
|
+
...(idxExpr ? [idxExpr] : []),
|
|
2092
|
+
...params.map((_, i) => (def.types[i] === '&str' ? `&__pa${i}` : `__pa${i}`))
|
|
2093
|
+
].join(',');
|
|
2094
|
+
return `{\n${binds}\nlet __s = std::sync::Arc::clone(&self);\n__s.${variantName}(${callArgs})${awaitKw}\n}`;
|
|
2095
|
+
}
|
|
2096
|
+
|
|
2097
|
+
function emitProcFn(def, variantName, body) {
|
|
2098
|
+
const name = variantName || def.parsed;
|
|
2099
|
+
const params = [];
|
|
2100
|
+
if (def.takesCaller) params.push('__rcaller: usize');
|
|
2101
|
+
let vi = 0;
|
|
2102
|
+
for (let i = 0; i < def.argIds.length; i++) {
|
|
2103
|
+
const hole = def.holes[i] || '%s';
|
|
2104
|
+
if (hole === '%c' || def.branchNames.has(String(def.argNames && def.argNames[i]))) continue;
|
|
2105
|
+
const used = def.usedArgs && def.usedArgs.has('pm_' + kwParse(def.names[vi]));
|
|
2106
|
+
params.push(`${used ? '' : '_'}pm_${kwParse(def.names[vi])}: ${def.types[vi]}`);
|
|
2107
|
+
vi++;
|
|
2108
|
+
}
|
|
2109
|
+
const paramsStr = params.length ? ',' + params.join(',') : '';
|
|
2110
|
+
// localvars 影子声明(对照 thread.lookupOrCreateVariable:全新空值,结束丢弃)
|
|
2111
|
+
let shadowDecl = '';
|
|
2112
|
+
if (def.localvars && def.localShadow && def.localShadow.size) {
|
|
2113
|
+
shadowDecl = [...def.localShadow.values()].map(sh => sh.decl).join('\n') + '\n';
|
|
2114
|
+
}
|
|
2115
|
+
const tail = def.hasReturn ? 'String::new()\n' : '';
|
|
2116
|
+
if (multi() && def.recursive) {
|
|
2117
|
+
// 异步递归(调用环上的函数):手工装箱打断 future 大小循环,避免外部依赖。
|
|
2118
|
+
// &str 参数绑定显式生命周期(装箱 future 借用调用方参数)
|
|
2119
|
+
const out = def.hasReturn ? 'String' : '()';
|
|
2120
|
+
const boxParams = params.map(p => p.replace(/: &str$/, ": &'a str"));
|
|
2121
|
+
const boxParamsStr = boxParams.length ? ',' + boxParams.join(',') : '';
|
|
2122
|
+
emit.func(`fn ${name}<'a>(mut self: std::sync::Arc<Default>${boxParamsStr}) -> std::pin::Pin<std::boxed::Box<dyn std::future::Future<Output = ${out}> + Send + 'a>> {\nBox::pin(async move {\n${shadowDecl}${body}${tail}})\n}\n`);
|
|
2123
|
+
} else {
|
|
2124
|
+
const selfSig = multi() ? 'mut self: std::sync::Arc<Default>' : (S.selfmut ? '&mut self' : '&self');
|
|
2125
|
+
const asyncKw = multi() ? 'async ' : '';
|
|
2126
|
+
emit.func(`${asyncKw}fn ${name}(${selfSig}${paramsStr})${def.hasReturn ? ' -> String' : ''}{\n${shadowDecl}${body}${tail}}\n`);
|
|
2127
|
+
}
|
|
2128
|
+
}
|
|
2129
|
+
|
|
2130
|
+
async function compile_proc_bodies(target, ti) {
|
|
2131
|
+
for (const def of S.procdefs) {
|
|
2132
|
+
if (def.ti !== ti) continue;
|
|
2133
|
+
if (def.hasVariants) continue; // %c/帽 过程由调用点变体生成
|
|
2134
|
+
const body = await compileProcBody(def, target, null);
|
|
2135
|
+
emitProcFn(def, null, body);
|
|
2136
|
+
}
|
|
2137
|
+
}
|
|
2138
|
+
|
|
2139
|
+
// 调用点变体:为每个含 %c 分支/起动帽体的调用生成一份内联分支的过程副本。
|
|
2140
|
+
// preInputs: 语句路径已编译的输入(procedures_call 编译器传入),避免重复编译
|
|
2141
|
+
async function procVariant(def, target, callBlock, preInputs) {
|
|
2142
|
+
const inputs = preInputs || (callBlock.opcode === 'procedures_call' ? await compile_input(callBlock, target) : null);
|
|
2143
|
+
if (!def.hasVariants) return { name: def.parsed, args: buildCallArgs(def, callBlock, inputs) };
|
|
2144
|
+
const branches = new Map();
|
|
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;
|
|
2161
|
+
}
|
|
2162
|
+
// 相同分支内容复用变体(循环体内的调用点只编译一次;不同调用点同分支亦复用)
|
|
2163
|
+
const key = def.proccode + '\u0000' + [...branches.entries()].map(([k, v]) => k + '\u0001' + v).join('\u0002');
|
|
2164
|
+
if (!S.variantCache) S.variantCache = new Map();
|
|
2165
|
+
let vname = S.variantCache.get(key);
|
|
2166
|
+
if (!vname) {
|
|
2167
|
+
const body = await compileProcBody(def, target, branches);
|
|
2168
|
+
S.variantCount++;
|
|
2169
|
+
vname = `${def.parsed}_v${S.variantCount}`;
|
|
2170
|
+
emitProcFn(def, vname, body);
|
|
2171
|
+
S.variantCache.set(key, vname);
|
|
2172
|
+
}
|
|
2173
|
+
return { name: vname, args: buildCallArgs(def, callBlock, inputs) };
|
|
2174
|
+
}
|
|
2175
|
+
|
|
2176
|
+
function buildCallArgs(def, callBlock, inputs) {
|
|
2177
|
+
// 菜单参数(rc_argtags menu):值存于调用块 FIELD(参数 id 命名)或 rc_argvals
|
|
2178
|
+
let argvals = null;
|
|
2179
|
+
if (callBlock.mutation && callBlock.mutation.rc_argvals) {
|
|
2180
|
+
try { argvals = JSON.parse(callBlock.mutation.rc_argvals); } catch (e) { argvals = null; }
|
|
2181
|
+
}
|
|
2182
|
+
const out = {};
|
|
2183
|
+
for (let i = 0; i < def.argIds.length; i++) {
|
|
2184
|
+
const aid = def.argIds[i];
|
|
2185
|
+
const hole = def.holes[i] || '%s';
|
|
2186
|
+
if (hole === '%c' || def.branchNames.has(String(def.argNames && def.argNames[i]))) continue;
|
|
2187
|
+
if (callBlock.fields && callBlock.fields[aid] != null) { out[aid] = new T.Str(castUnParse(String(callBlock.fields[aid][0]))); continue; }
|
|
2188
|
+
if (argvals && argvals[aid] != null) { out[aid] = new T.Str(castUnParse(String(argvals[aid]))); continue; }
|
|
2189
|
+
const v = inputs ? inputs[aid] : null;
|
|
2190
|
+
if (v != null) out[aid] = v;
|
|
2191
|
+
}
|
|
2192
|
+
return out;
|
|
2193
|
+
}
|
|
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
|
+
|
|
2207
|
+
async function compile_proc_call_value(block, target) {
|
|
2208
|
+
const def = resolveProc(String(block.mutation.proccode), S.targetID);
|
|
2209
|
+
if (!def) { warnUndefProc(block.mutation.proccode); return new T.Stri('String::new()'); }
|
|
2210
|
+
if (def.ti !== S.targetID && def.scope === 'local') {
|
|
2211
|
+
console.warn(`\x1b[33m过程 ${def.proccode} 为 local 作用域,跨角色调用已跳过\x1b[m`);
|
|
2212
|
+
return new T.Stri('String::new()');
|
|
2213
|
+
}
|
|
2214
|
+
const { name, args } = await procVariant(def, target, block, null);
|
|
2215
|
+
if (!def.hasReturn) {
|
|
2216
|
+
console.warn(`\x1b[33m过程 ${def.proccode} 无返回值,报告器调用返回空串\x1b[m`);
|
|
2217
|
+
return new T.Stri('String::new()');
|
|
2218
|
+
}
|
|
2219
|
+
let expr = procCallExpr(def, name, args);
|
|
2220
|
+
if (def.warp && S.frame && S.frame.gate) expr = `{ let _wg = RcompilerWarpGuard::enter(); ${expr} }`;
|
|
2221
|
+
return new T.Stri(expr);
|
|
2222
|
+
}
|
|
2223
|
+
|
|
2224
|
+
// argument reporters(body 编译期使用)
|
|
2225
|
+
// 值参数 Rust 类型(&str/bool),供类型适配(bool 参数被当值读 → to_string)
|
|
2226
|
+
function procParamType(name) {
|
|
2227
|
+
const def = S.customproc;
|
|
2228
|
+
if (!def) return null;
|
|
2229
|
+
let vi = 0;
|
|
2230
|
+
for (let i = 0; i < def.argIds.length; i++) {
|
|
2231
|
+
const hole = def.holes[i] || '%s';
|
|
2232
|
+
const nm = String((def.argNames && def.argNames[i]) || '');
|
|
2233
|
+
if (hole === '%c' || def.branchNames.has(nm)) continue; // 分支参数无值索引
|
|
2234
|
+
if (nm === String(name)) return def.types[vi] || '&str';
|
|
2235
|
+
vi++;
|
|
2236
|
+
}
|
|
2237
|
+
return null;
|
|
2238
|
+
}
|
|
2239
|
+
// TurboWarp 特殊报告名:任意上下文(含过程体内、无同名参数时)恒真——
|
|
2240
|
+
// 对照 TurboWarp procedures.js:特殊名检查先于 getParam;比较统一小写
|
|
2241
|
+
const SPECIAL_BOOL_ARGS = new Set(['is turbowarp?', 'is rcodenow?', 'is compiled?', 'is rcompiler?']);
|
|
2242
|
+
S.inputscompiles['argument_reporter_string_number'] = (args) => {
|
|
2243
|
+
const name = String(args.scope.block.fields.VALUE[0]);
|
|
2244
|
+
const arg = 'pm_' + kwParse(name);
|
|
2245
|
+
const pty = S.customproc ? procParamType(name) : null;
|
|
2246
|
+
if (pty != null) {
|
|
2247
|
+
S.customproc.usedArgs.add(arg);
|
|
2248
|
+
if (pty === 'bool') return new T.Str(`&(${arg}).to_string()`);
|
|
2249
|
+
// f64 参数:数值上下文直用原值;字符串上下文按 JS Number→String 格式化
|
|
2250
|
+
if (pty === 'f64') { runtimeNumStr(); return new T.Num(arg); }
|
|
2251
|
+
return new T.Str(arg);
|
|
2252
|
+
}
|
|
2253
|
+
// 孤儿/非本过程参数的参数报告器:pm_N 不在作用域,对照 VM getParam 未命中帧 → 空串
|
|
2254
|
+
return new T.Str('String::new()');
|
|
2255
|
+
};
|
|
2256
|
+
S.inputscompiles['argument_reporter_boolean'] = (args) => {
|
|
2257
|
+
const name = String(args.scope.block.fields.VALUE[0]);
|
|
2258
|
+
const arg = 'pm_' + kwParse(name);
|
|
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) {
|
|
2262
|
+
S.customproc.usedArgs.add(arg);
|
|
2263
|
+
if (pty === '&str') { runtimeStr2Bool(); return new T.Bool(`string_to_boolean(${arg})`); }
|
|
2264
|
+
return new T.Bool(arg);
|
|
2265
|
+
}
|
|
2266
|
+
// 孤儿/非本过程参数的布尔参数报告器:对照 VM getParam 未命中帧 → false
|
|
2267
|
+
return new T.Bool('false');
|
|
2268
|
+
};
|
|
2269
|
+
// %c 分支参数执行(对照 argumentCommand:执行调用方堆叠在调用块下的分支链)
|
|
2270
|
+
S.compiles['argument_command'] = (args) => {
|
|
2271
|
+
if (S.procBranches && args.scope && args.scope.block) {
|
|
2272
|
+
const name = String(args.scope.block.fields.VALUE[0]);
|
|
2273
|
+
if (S.procBranches.has(name)) return S.procBranches.get(name);
|
|
2274
|
+
}
|
|
2275
|
+
return '';
|
|
2276
|
+
};
|
|
2277
|
+
// 起动帽体占位(对照 procedures_rc_body:帽调用把积木拼入此位置)
|
|
2278
|
+
S.compiles['procedures_rc_body'] = () => {
|
|
2279
|
+
if (S.procBranches && S.procBranches.has('__hat_body__')) return S.procBranches.get('__hat_body__');
|
|
2280
|
+
return '';
|
|
2281
|
+
};
|
|
2282
|
+
S.compiles['procedures_definition'] = (args) => { return ''; }; // 两遍法中单独处理
|
|
2283
|
+
S.compiles['procedures_prototype'] = () => ''; // 原型(阴影块)不产生代码
|
|
2284
|
+
S.compiles['procedures_call'] = async (args) => {
|
|
2285
|
+
const block = args.__scope.block;
|
|
2286
|
+
const def = resolveProc(String(block.mutation.proccode), S.targetID);
|
|
2287
|
+
if (!def) {
|
|
2288
|
+
warnUndefProc(block.mutation.proccode);
|
|
2289
|
+
return '';
|
|
2290
|
+
}
|
|
2291
|
+
if (def.ti !== S.targetID && def.scope === 'local') {
|
|
2292
|
+
if (!S.ignore) console.warn(`\x1b[33m过程 ${def.proccode} 为 local 作用域,跨角色调用已跳过\x1b[m`);
|
|
2293
|
+
return '';
|
|
2294
|
+
}
|
|
2295
|
+
const { name, args: callArgs } = await procVariant(def, args.__scope.target, block, args);
|
|
2296
|
+
let call = procCallExpr(def, name, callArgs);
|
|
2297
|
+
// “运行时不刷新屏幕”的自定义积木:调用期间进入 warp(跳过帧门控)
|
|
2298
|
+
if (def.warp && S.frame && S.frame.gate) call = `{\nlet _wg = RcompilerWarpGuard::enter();\n${call}}`;
|
|
2299
|
+
let out = call + ';\n';
|
|
2300
|
+
// cap 形状:调用后结束当前脚本(对照 stop [this script])
|
|
2301
|
+
if (def.shape === 'cap') out += 'return;\n';
|
|
2302
|
+
return out;
|
|
2303
|
+
};
|
|
2304
|
+
S.compiles['procedures_return'] = (args) => {
|
|
2305
|
+
if (S.customproc) S.customproc.hasReturn = true;
|
|
2306
|
+
return `return (${args.VALUE ? args.VALUE.Stri() : 'String::new()'});\n`;
|
|
2307
|
+
};
|
|
2308
|
+
|
|
2309
|
+
// ============ 标准积木注册 ============
|
|
2310
|
+
const ctx = {
|
|
2311
|
+
S, T, C, Tools, emit,
|
|
2312
|
+
getvar, getlist, getListField, runtimeRcompilerList, runtimeNumStr, listInfo, kwParse, keywordOnly, safeJSON,
|
|
2313
|
+
inWarp: () => !!(S.customproc && S.customproc.warp),
|
|
2314
|
+
compile_chain, compile_block, compile_this, compile_input,
|
|
2315
|
+
registerScript, scriptSig, multi, isStageMode,
|
|
2316
|
+
frameWaitStmt, spawnScript, stageIdxExpr,
|
|
2317
|
+
markWrite: () => { S.selfmut = true; },
|
|
2318
|
+
runtimeParseF64, runtimeParseUsize, runtimeParseI32, runtimeStr2Bool, runtimeList2Var,
|
|
2319
|
+
scanProcedures, compile_proc_bodies, loadExtensionSource, api: null
|
|
2320
|
+
};
|
|
2321
|
+
ctx.prescanClones = prescanClones;
|
|
2322
|
+
|
|
2323
|
+
const api = {
|
|
2324
|
+
version: () => '2',
|
|
2325
|
+
compilertype: () => 'selective',
|
|
2326
|
+
compile: null,
|
|
2327
|
+
ctx
|
|
2328
|
+
};
|
|
2329
|
+
ctx.api = api;
|
|
2330
|
+
|
|
2331
|
+
registerStandard(ctx);
|
|
2332
|
+
|
|
2333
|
+
// 报告器处理器自动进入 inputlist(否则会按语句块编译)
|
|
2334
|
+
for (const k in S.inputscompiles) {
|
|
2335
|
+
if (!S.inputlist.includes(k)) S.inputlist.push(k);
|
|
2336
|
+
}
|
|
2337
|
+
|
|
2338
|
+
// ============ 项目扩展加载(jsonData.extensions)============
|
|
2339
|
+
async function loadProjectExtensions() {
|
|
2340
|
+
const exts = jsonData.extensions || [];
|
|
2341
|
+
const urls = jsonData.extensionURLs || {};
|
|
2342
|
+
const BUNDLED = ['strings', 'utilities']; // 已并入标准表
|
|
2343
|
+
for (const name of exts) {
|
|
2344
|
+
if (BUNDLED.includes(name)) continue;
|
|
2345
|
+
if (name === 'rcompiler' || name === 'pen' || name === 'music') continue; // 内置
|
|
2346
|
+
// "调试→自动忽略扩展":不加载源码(含不执行其编译期代码、不注册其依赖)
|
|
2347
|
+
if (S.ignoreExt.has(name)) { console.warn(`\x1b[33m已忽略扩展\x1b[m: ${name}`); continue; }
|
|
2348
|
+
const url = urls[name];
|
|
2349
|
+
try {
|
|
2350
|
+
let src = null;
|
|
2351
|
+
if (url && /^https?:\/\//.test(url)) src = await httpsGet(url);
|
|
2352
|
+
else {
|
|
2353
|
+
const localCandidates = [path.join(process.cwd(), 'exts', name + '.js'), path.join(__dirname, '..', 'exts', name + '.js'), name + '.js'];
|
|
2354
|
+
for (const p of localCandidates) { if (fs.existsSync(p)) { src = fs.readFileSync(p, 'utf-8'); break; } }
|
|
2355
|
+
}
|
|
2356
|
+
if (src) loadExtensionSource(src);
|
|
2357
|
+
else console.warn(`\x1b[33m找不到扩展\x1b[m: ${name}`);
|
|
2358
|
+
} catch (e) {
|
|
2359
|
+
console.warn(`\x1b[33m扩展加载失败\x1b[m: ${name} (${e.message})`);
|
|
2360
|
+
}
|
|
2361
|
+
}
|
|
2362
|
+
}
|
|
2363
|
+
function httpsGet(url) {
|
|
2364
|
+
return new Promise((resolve, reject) => {
|
|
2365
|
+
const req = https.get(url, (res) => {
|
|
2366
|
+
if (res.statusCode !== 200) { res.resume(); reject(new Error('HTTP ' + res.statusCode)); return; }
|
|
2367
|
+
let d = ''; res.on('data', c => d += c); res.on('end', () => resolve(d));
|
|
2368
|
+
});
|
|
2369
|
+
req.on('error', reject);
|
|
2370
|
+
req.setTimeout(15000, () => { req.destroy(new Error('连接超时')); });
|
|
2371
|
+
});
|
|
2372
|
+
}
|
|
2373
|
+
|
|
2374
|
+
// ============ 事件帽处理器(standard.js 注册核心;此处注册帽子包装)============
|
|
2375
|
+
// (standard.js 内部通过 ctx.registerScript 完成注册)
|
|
2376
|
+
|
|
2377
|
+
// ============ 主编译流程 ============
|
|
2378
|
+
emit.projectpub = false;
|
|
2379
|
+
await (async () => {
|
|
2380
|
+
// phase 0: 项目扩展
|
|
2381
|
+
await loadProjectExtensions();
|
|
2382
|
+
|
|
2383
|
+
// phase 1: 克隆脚本预分配 + 过程定义扫描(含调用图/递归/__rcaller 定点)
|
|
2384
|
+
ctx.prescanClones();
|
|
2385
|
+
ctx.scanProcedures();
|
|
2386
|
+
|
|
2387
|
+
// phase 2: rcompiler_import(旧"引用"系统,已被模组系统替代;仅为旧项目保留)
|
|
2388
|
+
for (const target of targets) {
|
|
2389
|
+
S.targetID = targets.indexOf(target);
|
|
2390
|
+
for (const bid in (target.blocks || {})) {
|
|
2391
|
+
const b = target.blocks[bid];
|
|
2392
|
+
if (b.opcode === 'rcompiler_import') {
|
|
2393
|
+
console.warn('\x1b[33mrcompiler_import(导入)已由 rCodenow 模组系统替代,请改用模组管理器\x1b[m');
|
|
2394
|
+
await ctx.compile_block(b, target, bid);
|
|
2395
|
+
}
|
|
2396
|
+
}
|
|
2397
|
+
}
|
|
2398
|
+
|
|
2399
|
+
// phase 3: 广播接收帽(先编译,保证发送方可引用;模组广播照常可达)
|
|
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: 编译帽体(复用预分配函数名)
|
|
2419
|
+
for (const target of targets) {
|
|
2420
|
+
S.targetID = targets.indexOf(target);
|
|
2421
|
+
S.curKind = 'broadcast';
|
|
2422
|
+
for (const bid in (target.blocks || {})) {
|
|
2423
|
+
const b = target.blocks[bid];
|
|
2424
|
+
if (b.opcode === 'event_whenbroadcastreceived') await ctx.compile_block(b, target, bid);
|
|
2425
|
+
}
|
|
2426
|
+
}
|
|
2427
|
+
S.curKind = 'main';
|
|
2428
|
+
|
|
2429
|
+
// phase 4: 其他事件
|
|
2430
|
+
// 模组角色:绿旗/点击帽不随工程启动执行(runtime._startupHatsRunOn);
|
|
2431
|
+
// 按键帽/广播接收照常(对照 startHats 的过滤范围)
|
|
2432
|
+
for (const target of targets) {
|
|
2433
|
+
S.targetID = targets.indexOf(target);
|
|
2434
|
+
for (const opcode of S.compileEvents) {
|
|
2435
|
+
if (opcode === 'event_whenbroadcastreceived') continue;
|
|
2436
|
+
if (isModTarget(target) &&
|
|
2437
|
+
(opcode === 'event_whenflagclicked' || opcode === 'event_whenthisspriteclicked')) continue;
|
|
2438
|
+
for (const bid in (target.blocks || {})) {
|
|
2439
|
+
const b = target.blocks[bid];
|
|
2440
|
+
if (b.opcode === opcode) await ctx.compile_block(b, target, bid);
|
|
2441
|
+
}
|
|
2442
|
+
}
|
|
2443
|
+
}
|
|
2444
|
+
|
|
2445
|
+
// phase 5: 过程体
|
|
2446
|
+
for (const target of targets) {
|
|
2447
|
+
S.targetID = targets.indexOf(target);
|
|
2448
|
+
await ctx.compile_proc_bodies(target, targets.indexOf(target));
|
|
2449
|
+
}
|
|
2450
|
+
|
|
2451
|
+
// phase 5.5: 起动帽形状的自制积木调用(rc_shape=hat)
|
|
2452
|
+
// 对照 rCodenow:顶层帽调用重复执行其定义体(thread.hatLoop/repeatHat),
|
|
2453
|
+
// 堆叠在帽下的积木经 procedures_rc_body 拼入定义体;模组角色的帽不启动
|
|
2454
|
+
for (const target of targets) {
|
|
2455
|
+
if (isModTarget(target)) continue;
|
|
2456
|
+
S.targetID = targets.indexOf(target);
|
|
2457
|
+
for (const bid in (target.blocks || {})) {
|
|
2458
|
+
const b = target.blocks[bid];
|
|
2459
|
+
if (!b || b.opcode !== 'procedures_call' || !b.topLevel) continue;
|
|
2460
|
+
if (!b.mutation || b.mutation.rc_shape !== 'hat') continue;
|
|
2461
|
+
const def = resolveProc(String(b.mutation.proccode), S.targetID);
|
|
2462
|
+
if (!def) { warnUndefProc(b.mutation.proccode); continue; }
|
|
2463
|
+
S.hatcount++;
|
|
2464
|
+
const fname = S.fnName('hatcall' + S.hatcount);
|
|
2465
|
+
S.curKind = 'main';
|
|
2466
|
+
const { name: vname, args: callArgs } = await procVariant(def, target, b, null);
|
|
2467
|
+
let call = procCallExpr(def, vname, callArgs);
|
|
2468
|
+
if (def.warp && S.frame && S.frame.gate) call = `{\nlet _wg = RcompilerWarpGuard::enter();\n${call}}`;
|
|
2469
|
+
// repeatHat 无条件让出(对照 sequencer:hat 循环与 forever 一样逐 tick 让出)
|
|
2470
|
+
const yieldStmt = (S.frame && S.frame.gate)
|
|
2471
|
+
? (multi() ? 'self.frame_wait().await;' : 'rcompiler_frame_wait();')
|
|
2472
|
+
: (multi() ? 'tokio::task::yield_now().await;' : 'std::thread::yield_now();');
|
|
2473
|
+
const body = `loop {\n${call};\n${yieldStmt}\n}\n`;
|
|
2474
|
+
if (multi()) {
|
|
2475
|
+
emit.func(`async fn ${fname}(mut self: std::sync::Arc<Self>){\n${body}\n}\n`);
|
|
2476
|
+
emit.scripts.push({ name: fname, kind: 'hat', ti: S.targetID });
|
|
2477
|
+
} else {
|
|
2478
|
+
const sig = S.selfmut ? '&mut self' : '&self';
|
|
2479
|
+
emit.func(`fn ${fname}(${sig}){\n${body}\n}\n`);
|
|
2480
|
+
emit.scripts.push({ name: fname, kind: 'hat', ti: S.targetID });
|
|
2481
|
+
}
|
|
2482
|
+
}
|
|
2483
|
+
}
|
|
2484
|
+
|
|
2485
|
+
// phase 6: 克隆启动帽(函数名已在 prescanClones 预分配;
|
|
2486
|
+
// 处于 spawn 环上的克隆函数装箱——"不循环克隆的角色"自动侦测的结果)
|
|
2487
|
+
for (const target of targets) {
|
|
2488
|
+
S.targetID = targets.indexOf(target);
|
|
2489
|
+
for (const bid in (target.blocks || {})) {
|
|
2490
|
+
const b = target.blocks[bid];
|
|
2491
|
+
if (b.opcode === 'control_start_as_clone') {
|
|
2492
|
+
S.targetID = targets.indexOf(target);
|
|
2493
|
+
const id = targets.indexOf(target);
|
|
2494
|
+
const fname = S.cloneFnNameByBlock.get(bid);
|
|
2495
|
+
S.curKind = 'clone';
|
|
2496
|
+
const body = await ctx.compile_chain(b.next, target);
|
|
2497
|
+
S.curKind = 'main';
|
|
2498
|
+
const inuse = S.inuselist.length ? S.inuselist.join('\n') + '\n' : '';
|
|
2499
|
+
const info = S.cloneFnInfo.get(fname);
|
|
2500
|
+
// 克隆任务自登记(供广播分发到克隆实例)
|
|
2501
|
+
const track = multi() && S.profile.hasStage ? 'rcompiler_clone_track(std::sync::Arc::clone(&self));\n' : '';
|
|
2502
|
+
if (multi() && info && info.recursive) {
|
|
2503
|
+
emit.func(`fn ${fname}(mut self: std::sync::Arc<Self>) -> std::pin::Pin<std::boxed::Box<dyn std::future::Future<Output = ()> + Send>> {\nBox::pin(async move {\n${track}${inuse}${body}})\n}\n`);
|
|
2504
|
+
} else {
|
|
2505
|
+
emit.func(`async fn ${fname}(mut self: std::sync::Arc<Self>){\n${track}${inuse}${body}\n}\n`);
|
|
2506
|
+
}
|
|
2507
|
+
}
|
|
2508
|
+
}
|
|
2509
|
+
}
|
|
2510
|
+
})();
|
|
2511
|
+
|
|
2512
|
+
// ============ 资产常量 ============
|
|
2513
|
+
if (profile.hasStage || profile.hasSound) {
|
|
2514
|
+
const { buildAssetConsts } = require('./assets');
|
|
2515
|
+
await buildAssetConsts(profile, emit, Object.assign({}, opts, {
|
|
2516
|
+
obf,
|
|
2517
|
+
strBytes,
|
|
2518
|
+
encryptBuf: obf ? ((buf) => {
|
|
2519
|
+
const out = Buffer.allocUnsafe(buf.length);
|
|
2520
|
+
for (let i = 0; i < buf.length; i++) out[i] = buf[i] ^ obfKeyByte(i);
|
|
2521
|
+
return out;
|
|
2522
|
+
}) : null
|
|
2523
|
+
}));
|
|
2524
|
+
}
|
|
2525
|
+
|
|
2526
|
+
// ============ 输出 ============
|
|
2527
|
+
emit.selfmut = S.selfmut;
|
|
2528
|
+
if (multi() && profile.backend !== 'web') {
|
|
2529
|
+
emit.dep('tokio = { version = "1", features = ["full"] }');
|
|
2530
|
+
}
|
|
2531
|
+
if (profile.backend === 'web') {
|
|
2532
|
+
// rand 0.8 在 wasm32-unknown-unknown 上需要 getrandom 的 js 后端
|
|
2533
|
+
emit.dep('getrandom = { version = "0.2", features = ["js"] }');
|
|
2534
|
+
}
|
|
2535
|
+
|
|
2536
|
+
// ============ 目标运行时选择 ============
|
|
2537
|
+
// native:现有 skia/winit/rodio(preludes.js)
|
|
2538
|
+
// web:wasm-bindgen + scratch-render JS 宿主(web.js)
|
|
2539
|
+
const P = require('./preludes');
|
|
2540
|
+
const preludes = profile.backend === 'web'
|
|
2541
|
+
? require('./web').build(profile, P)
|
|
2542
|
+
: P.build(profile);
|
|
2543
|
+
|
|
2544
|
+
// ============ 帧模型运行时 ============
|
|
2545
|
+
if (profile.frame && profile.frame.gate) {
|
|
2546
|
+
if (multi()) {
|
|
2547
|
+
emit.runtime(preludes.warpMulti);
|
|
2548
|
+
if (!profile.hasStage) {
|
|
2549
|
+
emit.runtime(preludes.clockMulti);
|
|
2550
|
+
emit.extra(`pub const RCOMPILER_TPS: f64 = ${Number(profile.frame.tps > 0 ? profile.frame.tps : 60).toFixed(1)};`);
|
|
2551
|
+
// Default 上的 frame_wait(无舞台项目无 stage 句柄,走全局时钟)
|
|
2552
|
+
emit.func('pub async fn frame_wait(&self) {\nif let Some(__c) = RCOMPILER_CLOCK.get() {\nlet mut __rx = __c.tx.subscribe();\nlet _ = __rx.changed().await;\n}\n}');
|
|
2553
|
+
}
|
|
2554
|
+
} else {
|
|
2555
|
+
emit.runtime(preludes.warpSingle);
|
|
2556
|
+
if (!profile.hasStage) {
|
|
2557
|
+
emit.runtime(preludes.clockSingle);
|
|
2558
|
+
emit.extra(`pub const RCOMPILER_TPS: f64 = ${Number(profile.frame.tps > 0 ? profile.frame.tps : 60).toFixed(1)};`);
|
|
2559
|
+
}
|
|
2560
|
+
}
|
|
2561
|
+
}
|
|
2562
|
+
|
|
2563
|
+
// ============ 监视器(可见项;对照 scratch-monitor 的变量/列表/侦测监视器) ============
|
|
2564
|
+
// 值快照经监视器任务在脚本线程读取(RcompilerCell 仅脚本线程可借),渲染线程只读快照。
|
|
2565
|
+
// RCOMPILER_MONITORS 静态表与 get/set 方法在舞台项目恒定发射(无监视器时为空表/空匹配),
|
|
2566
|
+
// 保证 preludes 的监视器任务/绘制代码在任何组合下都可解析。
|
|
2567
|
+
if (profile.hasStage) {
|
|
2568
|
+
const flit = (n) => { const v = Number(n) || 0; return Number.isInteger(v) ? v.toFixed(1) : String(v); };
|
|
2569
|
+
const KINDS = { default: 0, large: 1, slider: 2, list: 3 };
|
|
2570
|
+
const CUR_ZH = { year: '年', month: '月', date: '日', dayofweek: '星期', hour: '时', minute: '分', second: '秒' };
|
|
2571
|
+
const monitorLabelOf = (m) => {
|
|
2572
|
+
switch (m.opcode) {
|
|
2573
|
+
case 'data_variable': return String(m.params.VARIABLE || '');
|
|
2574
|
+
case 'data_listcontents': return String(m.params.LIST || '');
|
|
2575
|
+
case 'sensing_timer': return '计时器';
|
|
2576
|
+
case 'sensing_answer': return '回答';
|
|
2577
|
+
case 'sensing_loudness': return '响度';
|
|
2578
|
+
case 'sensing_username': return '用户名';
|
|
2579
|
+
case 'sensing_dayssince2000': return '2000年至今天数';
|
|
2580
|
+
case 'sensing_mousedown': return '鼠标按下';
|
|
2581
|
+
case 'sensing_mousex': return '鼠标 x';
|
|
2582
|
+
case 'sensing_mousey': return '鼠标 y';
|
|
2583
|
+
case 'sensing_current': return '当前 ' + (CUR_ZH[m.params.CURRENTMENU] || m.params.CURRENTMENU || '');
|
|
2584
|
+
default: return String(m.opcode);
|
|
2585
|
+
}
|
|
2586
|
+
};
|
|
2587
|
+
const monRows = [], getArms = [], setArms = [], monActive = [];
|
|
2588
|
+
for (const m of (Array.isArray(profile.monitors) ? profile.monitors : [])) {
|
|
2589
|
+
const i = monRows.length;
|
|
2590
|
+
let valueExpr = null, setStmt = null, listRows = false;
|
|
2591
|
+
if (m.opcode === 'data_variable' || m.opcode === 'data_listcontents') {
|
|
2592
|
+
const isList = m.opcode === 'data_listcontents';
|
|
2593
|
+
const table = isList ? S.lists : S.vars;
|
|
2594
|
+
let entry = table.get(m.id) || null;
|
|
2595
|
+
if (!entry) {
|
|
2596
|
+
// id 未命中(旧项目/跨编辑器)→ 按名称 + spriteName 回退
|
|
2597
|
+
const name = String((isList ? m.params.LIST : m.params.VARIABLE) || '');
|
|
2598
|
+
const ti = m.spriteName != null ? profile.targets.findIndex(t => t.name === m.spriteName) : -1;
|
|
2599
|
+
for (const [, e] of table) {
|
|
2600
|
+
if (e.name !== name) continue;
|
|
2601
|
+
if (m.spriteName == null ? e.isGlobal : (!e.isGlobal && e.ti === ti)) { entry = e; break; }
|
|
2602
|
+
}
|
|
2603
|
+
}
|
|
2604
|
+
if (!entry) {
|
|
2605
|
+
console.warn(`\x1b[33m监视器目标不存在,已跳过\x1b[m: ${m.params.VARIABLE || m.params.LIST || m.id}`);
|
|
2606
|
+
continue;
|
|
2607
|
+
}
|
|
2608
|
+
if (isList) {
|
|
2609
|
+
runtimeRcompilerList();
|
|
2610
|
+
const f = getListField(entry.name, entry.id);
|
|
2611
|
+
if (entry.declared === 'f64') { runtimeNumStr(); valueExpr = `${f}.lclone().iter().map(|x| rcompiler_num_str(*x)).collect::<Vec<String>>()`; }
|
|
2612
|
+
else valueExpr = `${f}.lclone()`;
|
|
2613
|
+
listRows = true;
|
|
2614
|
+
} else {
|
|
2615
|
+
const acc = getvar(entry.name, entry.id);
|
|
2616
|
+
valueExpr = acc.str();
|
|
2617
|
+
if (m.mode === 'slider') setStmt = acc.setNum('v');
|
|
2618
|
+
}
|
|
2619
|
+
} else {
|
|
2620
|
+
const gen = S.inputscompiles[m.opcode];
|
|
2621
|
+
if (typeof gen !== 'function') { continue; }
|
|
2622
|
+
const fields = m.opcode === 'sensing_current' ? { CURRENTMENU: [String(m.params.CURRENTMENU || 'year')] } : {};
|
|
2623
|
+
const t = gen({ scope: { block: { fields } } });
|
|
2624
|
+
valueExpr = t ? t.Stri() : null;
|
|
2625
|
+
}
|
|
2626
|
+
if (valueExpr == null) continue;
|
|
2627
|
+
monActive.push(m);
|
|
2628
|
+
monRows.push(`MonitorInfo { kind: ${KINDS[m.mode] != null ? KINDS[m.mode] : 0}, label: &${strBytes(monitorLabelOf(m))}, x: ${flit(m.x)}, y: ${flit(m.y)}, width: ${flit(m.width)}, height: ${flit(m.height)}, slider_min: ${flit(m.sliderMin)}, slider_max: ${flit(m.sliderMax)}, discrete: ${m.isDiscrete ? 'true' : 'false'} }`);
|
|
2629
|
+
// 列表监视器的值表达式已是 Vec<String>,不套 vec![]
|
|
2630
|
+
getArms.push(listRows ? ` ${i} => ${valueExpr},` : ` ${i} => vec![${valueExpr}],`);
|
|
2631
|
+
if (setStmt) setArms.push(` ${i} => { ${setStmt} }`);
|
|
2632
|
+
}
|
|
2633
|
+
profile.monitorsActive = monActive;
|
|
2634
|
+
emit.extra(`pub static RCOMPILER_MONITORS: &[MonitorInfo] = &[${monRows.join(',')}];`);
|
|
2635
|
+
emit.func(`pub fn rcompiler_monitor_get(&self, idx: usize) -> Vec<String> {\nmatch idx {\n${getArms.join('\n')}\n_ => Vec::new()\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}`);
|
|
2637
|
+
}
|
|
2638
|
+
if (!profile.hasStage && Array.isArray(profile.monitors) && profile.monitors.some(m => m.visible !== false)) {
|
|
2639
|
+
console.warn('\x1b[33m监视器需要舞台模块(当前项目未启用舞台),已跳过全部监视器\x1b[m');
|
|
2640
|
+
}
|
|
2641
|
+
|
|
2642
|
+
// ============ 抗逆向运行时(字符串解密 / 资产解密) ============
|
|
2643
|
+
// 正常模式:恒等实现(零开销,保持现状);混淆模式:密钥分字掩码存放,
|
|
2644
|
+
// 逐字节解密,字符串表只在首次使用时展开并泄漏为 &'static str。
|
|
2645
|
+
emit.extra('pub static RCOMPILER_PAUSED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);');
|
|
2646
|
+
const arcRuntime = [];
|
|
2647
|
+
if (obf) {
|
|
2648
|
+
const words = [];
|
|
2649
|
+
for (let i = 0; i < 4; i++) words.push('0x' + (obfKeyWord(i) ^ OBF_MASKS[i]).toString(16));
|
|
2650
|
+
const rows = S.strlist.map(s => `&${strBytes(s)}`);
|
|
2651
|
+
arcRuntime.push(
|
|
2652
|
+
`pub const RCOMPILER_OBF: bool = true;`,
|
|
2653
|
+
// 存储 = 原始密钥 ^ 掩码(避免密钥以连续明文进 .rodata);取用时先异或回掩码
|
|
2654
|
+
`pub const RCOMPILER_OBF_KEY: [u64; 4] = [${words.join(', ')}];`,
|
|
2655
|
+
`pub const RCOMPILER_OBF_MASK: [u64; 4] = [${OBF_MASKS.map(m => '0x' + m.toString(16)).join(', ')}];`,
|
|
2656
|
+
'#[inline]',
|
|
2657
|
+
'fn rcompiler_key_byte(i: usize) -> u8 {',
|
|
2658
|
+
' let wi = (i >> 3) % 4;',
|
|
2659
|
+
' let w = RCOMPILER_OBF_KEY[wi] ^ RCOMPILER_OBF_MASK[wi];',
|
|
2660
|
+
' let b = ((w >> ((i % 8) * 8)) & 0xff) as u8;',
|
|
2661
|
+
' b ^ ((((i * 31) & 0xff) as u8) ^ 0xA5)',
|
|
2662
|
+
'}',
|
|
2663
|
+
'pub fn rcompiler_decrypt(data: &[u8]) -> Vec<u8> {',
|
|
2664
|
+
' let mut out = Vec::with_capacity(data.len());',
|
|
2665
|
+
' for (i, &b) in data.iter().enumerate() { out.push(b ^ rcompiler_key_byte(i)); }',
|
|
2666
|
+
' out',
|
|
2667
|
+
'}',
|
|
2668
|
+
'pub fn rcompiler_txt(data: &[u8]) -> String {',
|
|
2669
|
+
' String::from_utf8_lossy(&rcompiler_decrypt(data)).into_owned()',
|
|
2670
|
+
'}',
|
|
2671
|
+
'pub fn rcompiler_name(data: &[u8]) -> String { rcompiler_txt(data) }',
|
|
2672
|
+
'pub fn rcompiler_name_eq(data: &[u8], name: &str) -> bool { rcompiler_txt(data) == name }',
|
|
2673
|
+
'pub fn rcompiler_asset_bytes(d: &\'static [u8]) -> std::borrow::Cow<\'static, [u8]> {',
|
|
2674
|
+
' std::borrow::Cow::Owned(rcompiler_decrypt(d))',
|
|
2675
|
+
'}',
|
|
2676
|
+
`static RCOMPILER_STR_TAB: &[&[u8]] = &[${rows.join(', ')}];`,
|
|
2677
|
+
'pub fn rcompiler_str(i: usize) -> &\'static str {',
|
|
2678
|
+
' static CACHE: std::sync::OnceLock<Vec<&\'static str>> = std::sync::OnceLock::new();',
|
|
2679
|
+
' let v = CACHE.get_or_init(|| RCOMPILER_STR_TAB.iter().map(|b| Box::leak(rcompiler_txt(b).into_boxed_str()) as &\'static str).collect());',
|
|
2680
|
+
' v.get(i).copied().unwrap_or("")',
|
|
2681
|
+
'}'
|
|
2682
|
+
);
|
|
2683
|
+
} else {
|
|
2684
|
+
arcRuntime.push(
|
|
2685
|
+
'pub const RCOMPILER_OBF: bool = false;',
|
|
2686
|
+
'pub fn rcompiler_txt(data: &[u8]) -> String {',
|
|
2687
|
+
' String::from_utf8_lossy(data).into_owned()',
|
|
2688
|
+
'}',
|
|
2689
|
+
'pub fn rcompiler_name(data: &[u8]) -> String {',
|
|
2690
|
+
' String::from_utf8_lossy(data).into_owned()',
|
|
2691
|
+
'}',
|
|
2692
|
+
'pub fn rcompiler_name_eq(data: &[u8], name: &str) -> bool { data == name.as_bytes() }',
|
|
2693
|
+
'pub fn rcompiler_asset_bytes(d: &\'static [u8]) -> std::borrow::Cow<\'static, [u8]> {',
|
|
2694
|
+
' std::borrow::Cow::Borrowed(d)',
|
|
2695
|
+
'}'
|
|
2696
|
+
);
|
|
2697
|
+
}
|
|
2698
|
+
emit.extra(arcRuntime.join('\n'));
|
|
2699
|
+
|
|
2700
|
+
// 多任务模式:脚本任务注册表(stop all / stop other scripts 依赖)
|
|
2701
|
+
if (multi()) emit.extra(preludes.taskMulti);
|
|
2702
|
+
// 舞台多任务:克隆实例注册表(广播分发到全部克隆,对照 startHats)
|
|
2703
|
+
if (multi() && profile.hasStage) {
|
|
2704
|
+
emit.postStruct = [`pub static RCOMPILER_CLONE_TASKS: std::sync::Mutex<Vec<(usize, std::sync::Weak<Default>)>> = std::sync::Mutex::new(Vec::new());
|
|
2705
|
+
pub fn rcompiler_clone_track(me: std::sync::Arc<Default>) {
|
|
2706
|
+
let mut t = RCOMPILER_CLONE_TASKS.lock().unwrap();
|
|
2707
|
+
let si = me.sprite_index;
|
|
2708
|
+
t.retain(|(i, w)| w.strong_count() > 0 && *i != si);
|
|
2709
|
+
t.push((si, std::sync::Arc::downgrade(&me)));
|
|
2710
|
+
}
|
|
2711
|
+
pub fn rcompiler_clone_get(idx: usize) -> Option<std::sync::Arc<Default>> {
|
|
2712
|
+
let t = RCOMPILER_CLONE_TASKS.lock().unwrap();
|
|
2713
|
+
for (i, w) in t.iter() { if *i == idx { return w.upgrade(); } }
|
|
2714
|
+
None
|
|
2715
|
+
}`];
|
|
2716
|
+
}
|
|
2717
|
+
let rust = emit.rust(fileName, preludes);
|
|
2718
|
+
// 调试模式:把行内标记替换为可读注释(保持行号不变),并生成行号→积木映射
|
|
2719
|
+
let map = null;
|
|
2720
|
+
if (debug) {
|
|
2721
|
+
const names = profile.targets.map(t => String(t.name));
|
|
2722
|
+
const lns = rust.split('\n');
|
|
2723
|
+
const entries = [];
|
|
2724
|
+
for (let i = 0; i < lns.length; i++) {
|
|
2725
|
+
const m = /^\/\/\^RC:(.+)$/.exec(lns[i]);
|
|
2726
|
+
if (!m) continue;
|
|
2727
|
+
let e;
|
|
2728
|
+
try { e = JSON.parse(m[1]); } catch (_) { continue; }
|
|
2729
|
+
e.line = i + 1;
|
|
2730
|
+
entries.push(e);
|
|
2731
|
+
lns[i] = `// rcompiler · 角色「${names[e.t] != null ? names[e.t] : e.t}」 · 积木 ${e.op}${e.b ? ` · 块 ${e.b}` : ''}`;
|
|
2732
|
+
}
|
|
2733
|
+
rust = lns.join('\n');
|
|
2734
|
+
map = {
|
|
2735
|
+
version: 1,
|
|
2736
|
+
targets: names,
|
|
2737
|
+
lines: entries,
|
|
2738
|
+
vars: [...S.vars.values()].map(v => ({ f: v.f, s: v.s, name: v.name, ti: v.ti, global: !!v.isGlobal }))
|
|
2739
|
+
.concat([...S.lists.values()].map(l => ({ f: l.f, name: l.name, ti: l.ti, global: !!l.isGlobal, list: true }))),
|
|
2740
|
+
funcs: emit.scripts.map(s => ({ name: s.name, kind: s.kind, ti: s.ti }))
|
|
2741
|
+
.concat(S.procdefs.map(d => ({ name: d.parsed, proc: d.proccode, ti: d.ti })))
|
|
2742
|
+
};
|
|
2743
|
+
}
|
|
2744
|
+
const cargo = emit.cargo(opts.name || fileName, opts.ver || '1.0.0');
|
|
2745
|
+
|
|
2746
|
+
if (folderPath && opts.write !== false) {
|
|
2747
|
+
if (!fs.existsSync(folderPath)) fs.mkdirSync(folderPath, { recursive: true });
|
|
2748
|
+
const web = profile.backend === 'web';
|
|
2749
|
+
const rustName = web ? 'lib.rs' : 'main.rs';
|
|
2750
|
+
const stale = path.join(folderPath, web ? 'main.rs' : 'lib.rs');
|
|
2751
|
+
if (fs.existsSync(stale)) fs.rmSync(stale, { force: true });
|
|
2752
|
+
fs.writeFileSync(path.join(folderPath, rustName), rust);
|
|
2753
|
+
// Windows EXE 图标资源(仅当成功生成 app_icon.ico 时;Cargo.toml 同时启用 build.rs)。
|
|
2754
|
+
// Cargo 会自动拾取包根目录的 build.rs,因此图标被移除/生成失败时必须清掉旧脚本,
|
|
2755
|
+
// 否则下一次构建仍会尝试 winresource(依赖已不再写入 Cargo.toml)。
|
|
2756
|
+
const buildRsPath = path.join(folderPath, '..', 'build.rs');
|
|
2757
|
+
if (emit.hasIcon && !web) {
|
|
2758
|
+
const buildRs = [
|
|
2759
|
+
'fn main() {',
|
|
2760
|
+
' #[cfg(windows)]',
|
|
2761
|
+
' {',
|
|
2762
|
+
' let mut res = winresource::WindowsResource::new();',
|
|
2763
|
+
' res.set_icon("assets/app_icon.ico");',
|
|
2764
|
+
' if let Err(e) = res.compile() { eprintln!("rcompiler: 写入 Windows 图标失败: {e}"); }',
|
|
2765
|
+
' }',
|
|
2766
|
+
'}',
|
|
2767
|
+
''
|
|
2768
|
+
].join('\n');
|
|
2769
|
+
fs.writeFileSync(buildRsPath, buildRs);
|
|
2770
|
+
} else if (fs.existsSync(buildRsPath)) {
|
|
2771
|
+
const old = fs.readFileSync(buildRsPath, 'utf8');
|
|
2772
|
+
if (old.includes('winresource::WindowsResource')) fs.unlinkSync(buildRsPath);
|
|
2773
|
+
}
|
|
2774
|
+
}
|
|
2775
|
+
if (log) console.log(rust);
|
|
2776
|
+
|
|
2777
|
+
profile.autoNumVars = S.autoNumVars;
|
|
2778
|
+
if (S.ignoreExt.size) {
|
|
2779
|
+
console.warn(`\x1b[33m已忽略扩展\x1b[m: ${[...S.ignoreExt].join('、')}(预扫描跳过 ${profile.ignoredBlocks} 块)`);
|
|
2780
|
+
}
|
|
2781
|
+
return { rust, cargo, deplist: [...emit.deps.keys()], profile, ctx: S, map };
|
|
2782
|
+
}
|
|
2783
|
+
}
|
|
2784
|
+
|
|
2785
|
+
module.exports = { rcompiler, readProject, readZipBuffer };
|