femo-plugin 1.0.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/LICENSE +201 -0
- package/README.md +627 -0
- package/femo2host/__init__.py +4 -0
- package/femo2host/femoToolcall/chronica.py +156 -0
- package/femo2host/femoToolcall/femo-chat.mjs +69 -0
- package/femo2host/femoToolcall/femo_debugger.py +1515 -0
- package/femo2host/femo_api.py +437 -0
- package/femo2host/femo_gen_api.jsx +77 -0
- package/femoBridges/ContextExample.py +555 -0
- package/femoBridges/MemoryExample.py +163 -0
- package/femoBridges/__init__.py +1 -0
- package/femoBridges/getDir/get_dir.py +56 -0
- package/femoBridges/getDir//344/275/240/345/217/257/344/273/245/350/256/276/345/256/232/344/273/273/346/204/217/346/226/207/344/273/266/345/244/271/344/270/272/347/224/250/346/210/267/346/225/260/346/215/256/346/226/207/344/273/266/345/244/271.txt +10 -0
- package/femoBridges/llmBridge.py +247 -0
- package/femoBridges/llmProviders.py +308 -0
- package/femoCompiler/FEMO_CLIrenderer.py +198 -0
- package/femoCompiler/FEMO_config.py +35 -0
- package/femoCompiler/FEMO_errors.py +278 -0
- package/femoCompiler/FEMO_interpreter.py +163 -0
- package/femoCompiler/FEMO_normalizer.py +396 -0
- package/femoCompiler/FEMO_parser.py +2468 -0
- package/femoCompiler/FEMO_runtime.py +3630 -0
- package/femoCompiler/FEMO_scope_resolver.py +209 -0
- package/femoCompiler/__init__.py +1 -0
- package/femoCompiler/actor_resolver.py +86 -0
- package/femoCompiler/block_collector.py +441 -0
- package/femoCompiler/db_utils.py +485 -0
- package/femoCompiler/femoAsync.py +401 -0
- package/femoCompiler/host_manifest.py +68 -0
- package/femoCompiler/job_manager.py +767 -0
- package/femoCompiler/protocol.py +126 -0
- package/femoCompiler/save_dialog.py +402 -0
- package/femoCompiler/task_world.py +544 -0
- package/femoCompiler/vars/__init__.py +19 -0
- package/femoCompiler/vars/checkpoint.py +113 -0
- package/femoCompiler/vars/env.py +686 -0
- package/femoCompiler/vars/evaluator.py +567 -0
- package/femoCompiler/vars/join.py +303 -0
- package/femoCompiler/vars/merge.py +157 -0
- package/femoCompiler/vars/model.py +245 -0
- package/femoExamples/AI/345/211/252/350/247/206/351/242/221/AI/345/211/252/350/247/206/351/242/221.femo +192 -0
- package/femoExamples/AI/350/201/212/345/244/251/345/256/244/group-chat.femo +42 -0
- package/femoExamples/AI/350/201/212/345/244/251/345/256/244/random_wait_time.py +10 -0
- package/femoExamples/LuxFiat/luxfiat.femo +38 -0
- package/femoExamples/LuxFiat/wait.py +29 -0
- package/femoExamples/debug/347/245/236/345/231/250/debug/347/245/236/345/231/250.femo +222 -0
- package/femoExamples/discussion.femo +70 -0
- package/femoExamples/goal-mode.femo +23 -0
- package/femoExamples//345/270/270/347/224/250/345/267/245/345/205/267python/wait.py +29 -0
- package/femoExamples//347/213/274/344/272/272/346/235/200/werewolf_utils.py +205 -0
- package/femoExamples//347/213/274/344/272/272/346/235/200/werewolf_utils2.py +324 -0
- package/femoExamples//347/213/274/344/272/272/346/235/200//347/213/274/344/272/272/346/235/200-/350/255/246/351/225/277/347/211/210.femo +544 -0
- package/femoExamples//347/213/274/344/272/272/346/235/200//347/213/274/344/272/272/346/235/200.femo +331 -0
- package/femoExamples//350/260/201/346/230/257/345/215/247/345/272/225/undercover_utils.py +683 -0
- package/femoExamples//350/260/201/346/230/257/345/215/247/345/272/225//350/260/201/346/230/257/345/215/247/345/272/225-/350/217/234/345/270/202/345/234/272/345/261/200.femo +348 -0
- package/femoExamples//350/260/201/346/230/257/345/215/247/345/272/225//350/260/201/346/230/257/345/215/247/345/272/225.femo +392 -0
- package/femoGen/document_ch.html +2352 -0
- package/femoGen/document_en.html +2279 -0
- package/femoGen/index.html +19 -0
- package/femoGen/intro_ch.html +942 -0
- package/femoGen/intro_en.html +932 -0
- package/femoGen/package-lock.json +1698 -0
- package/femoGen/package.json +19 -0
- package/femoGen/public/character_need.ttf +0 -0
- package/femoGen/public/favicon.ico +0 -0
- package/femoGen/public/femo-logo-slogan.svg +83 -0
- package/femoGen/public/femo-logo.svg +55 -0
- package/femoGen/public/logo-fullsize.ico +0 -0
- package/femoGen/src/FemoWorAuto.jsx +5444 -0
- package/femoGen/src/actionModal.jsx +358 -0
- package/femoGen/src/bubbleOverlay.jsx +701 -0
- package/femoGen/src/canvasNodes.jsx +608 -0
- package/femoGen/src/common.jsx +715 -0
- package/femoGen/src/debugPanel.jsx +530 -0
- package/femoGen/src/faIcons.jsx +84 -0
- package/femoGen/src/femoDiagnostics.js +122 -0
- package/femoGen/src/femoFileList.jsx +357 -0
- package/femoGen/src/femoGenerator.jsx +1198 -0
- package/femoGen/src/femoLog.js +107 -0
- package/femoGen/src/femoParser.jsx +2255 -0
- package/femoGen/src/femoPreview.jsx +297 -0
- package/femoGen/src/graphBuilder.jsx +358 -0
- package/femoGen/src/libPanel.jsx +519 -0
- package/femoGen/src/main.jsx +22 -0
- package/femoGen/src/mobileView.jsx +2796 -0
- package/femoGen/src/projectPanel.jsx +529 -0
- package/femoGen/src/soulModal.jsx +162 -0
- package/femoGen/src/styles/font.css +10 -0
- package/femoGen/src/themes.js +465 -0
- package/femoGen/src/useCanvasInteraction.jsx +319 -0
- package/femoGen/vite.config.js +28 -0
- package/femoGen//347/222/207/345/255/230/346/247/221.txt +15 -0
- package/hostAdapter/dshAdapter/README.md +68 -0
- package/hostAdapter/dshAdapter/build.mjs +75 -0
- package/hostAdapter/dshAdapter/client/client-ui/chat-node.tsx +339 -0
- package/hostAdapter/dshAdapter/client/client-ui/composer.tsx +997 -0
- package/hostAdapter/dshAdapter/client/client-ui/editor-page.tsx +726 -0
- package/hostAdapter/dshAdapter/client/client-ui/editor-view.tsx +88 -0
- package/hostAdapter/dshAdapter/client/client-ui/femo-stream-live.tsx +264 -0
- package/hostAdapter/dshAdapter/client/client-ui/proj2/frame-router.ts +282 -0
- package/hostAdapter/dshAdapter/client/client-ui/proj2/index.ts +44 -0
- package/hostAdapter/dshAdapter/client/client-ui/proj2/ledger.ts +329 -0
- package/hostAdapter/dshAdapter/client/client-ui/proj2/turn-view.tsx +211 -0
- package/hostAdapter/dshAdapter/client/client-ui/proj2/window-id.ts +28 -0
- package/hostAdapter/dshAdapter/client/client-ui/stream-store.ts +550 -0
- package/hostAdapter/dshAdapter/client/client-ui/styles.ts +144 -0
- package/hostAdapter/dshAdapter/client/client-ui/view-button.tsx +572 -0
- package/hostAdapter/dshAdapter/client/client-ui/view-state.ts +61 -0
- package/hostAdapter/dshAdapter/client/client.tsx +518 -0
- package/hostAdapter/dshAdapter/client/fa-icons.tsx +112 -0
- package/hostAdapter/dshAdapter/client/femo-reasoning-row.tsx +103 -0
- package/hostAdapter/dshAdapter/client/lineage-fork-native.jsx +624 -0
- package/hostAdapter/dshAdapter/client/lineage-fork.jsx +585 -0
- package/hostAdapter/dshAdapter/cordis.patch.yml +8 -0
- package/hostAdapter/dshAdapter/dshPatch/DSH-0.1.2-fork/344/277/256/346/224/271/351/234/200/346/261/202.md +184 -0
- package/hostAdapter/dshAdapter/dshPatch/MEOW_MODIFICATIONS.md +3105 -0
- package/hostAdapter/dshAdapter/dshPatch/patch-dsh-0.1.2-alpha.1.py +313 -0
- package/hostAdapter/dshAdapter/host/api-retry.ts +141 -0
- package/hostAdapter/dshAdapter/host/bridge.ts +224 -0
- package/hostAdapter/dshAdapter/host/config.ts +124 -0
- package/hostAdapter/dshAdapter/host/debug-log.ts +29 -0
- package/hostAdapter/dshAdapter/host/debug-run.ts +793 -0
- package/hostAdapter/dshAdapter/host/diag-feed.ts +56 -0
- package/hostAdapter/dshAdapter/host/engine-events.ts +891 -0
- package/hostAdapter/dshAdapter/host/engine-transcript.ts +122 -0
- package/hostAdapter/dshAdapter/host/femo-files.ts +210 -0
- package/hostAdapter/dshAdapter/host/god-mirror.ts +234 -0
- package/hostAdapter/dshAdapter/host/host-log.ts +101 -0
- package/hostAdapter/dshAdapter/host/http.ts +66 -0
- package/hostAdapter/dshAdapter/host/index.ts +633 -0
- package/hostAdapter/dshAdapter/host/list-cache.ts +183 -0
- package/hostAdapter/dshAdapter/host/main-actor.ts +853 -0
- package/hostAdapter/dshAdapter/host/main-delivery-queue.ts +115 -0
- package/hostAdapter/dshAdapter/host/native-state.ts +21 -0
- package/hostAdapter/dshAdapter/host/node-retry.ts +246 -0
- package/hostAdapter/dshAdapter/host/persona.ts +146 -0
- package/hostAdapter/dshAdapter/host/pre-step-gate.ts +95 -0
- package/hostAdapter/dshAdapter/host/proj-trace.ts +49 -0
- package/hostAdapter/dshAdapter/host/projection-input.ts +238 -0
- package/hostAdapter/dshAdapter/host/projection.ts +742 -0
- package/hostAdapter/dshAdapter/host/routes.ts +1196 -0
- package/hostAdapter/dshAdapter/host/run-control.ts +641 -0
- package/hostAdapter/dshAdapter/host/safe-steer.ts +33 -0
- package/hostAdapter/dshAdapter/host/section-gate.ts +108 -0
- package/hostAdapter/dshAdapter/host/session-events.ts +45 -0
- package/hostAdapter/dshAdapter/host/state-files.ts +301 -0
- package/hostAdapter/dshAdapter/host/stream-frames.ts +229 -0
- package/hostAdapter/dshAdapter/host/subagent-native.ts +997 -0
- package/hostAdapter/dshAdapter/host/subagent.ts +1205 -0
- package/hostAdapter/dshAdapter/host/tools.ts +486 -0
- package/hostAdapter/dshAdapter/host/windowing-native.ts +294 -0
- package/hostAdapter/dshAdapter/host.manifest.json +6 -0
- package/hostAdapter/dshAdapter/lib/client.js +19161 -0
- package/hostAdapter/dshAdapter/lib/client.js.map +7 -0
- package/hostAdapter/dshAdapter/lib/index.js +8173 -0
- package/hostAdapter/dshAdapter/lib/index.js.map +7 -0
- package/hostAdapter/dshAdapter/package-lock.json +500 -0
- package/hostAdapter/dshAdapter/package.json +55 -0
- package/hostAdapter/dshAdapter/pnpm-lock.yaml +596 -0
- package/hostAdapter/dshAdapter/pnpm-workspace.yaml +2 -0
- package/hostAdapter/dshAdapter/python/dev-bridge-test.py +43 -0
- package/hostAdapter/dshAdapter/python/femo_bridge.py +533 -0
- package/hostAdapter/dshAdapter/tsconfig.host.json +9 -0
- package/hostAdapter/dshAdapter/tsconfig.json +21 -0
- package/package.json +40 -0
- package//350/257/255/346/263/225/346/226/207/346/241/243.md +1136 -0
|
@@ -0,0 +1,2255 @@
|
|
|
1
|
+
// ═══════════════════════════════════════════════════════════════
|
|
2
|
+
// ═══ femoParser.jsx ═══
|
|
3
|
+
// ═══════════════════════════════════════════════════════════════
|
|
4
|
+
|
|
5
|
+
import { TYPES, SPECIAL_COLORS, actionId } from './common';
|
|
6
|
+
// ═══ 统一报错链路(2026-09-07 解耦)═══
|
|
7
|
+
// parser 内所有语法检查点不再各自 throw new Error(手拼字符串),统一调
|
|
8
|
+
// reporter(femoDiagnostics.js):error 阻断(抛 FEMOSyntaxError)、warning
|
|
9
|
+
// 仅提醒(挂 result.warnings)。每条诊断固定携带 行号/出错行/信息/区域。
|
|
10
|
+
import { createReporter } from './femoDiagnostics';
|
|
11
|
+
|
|
12
|
+
// actor thinking 档位词汇全集(与 Python 编译器 FEMO_parser.THINKING_LEVELS 对齐,
|
|
13
|
+
// = pi-ai 的 ModelThinkingLevel;无 default 词——「默认」由不带 thinking 声明表达,
|
|
14
|
+
// 与 dsh 模型选择器 Default 项同语义:不发 reasoning_effort 字段,服务器自选)。
|
|
15
|
+
export const THINKING_LEVELS = ['off', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'];
|
|
16
|
+
|
|
17
|
+
function normalizeSymbols(str, context = 'global') {
|
|
18
|
+
let s = str;
|
|
19
|
+
// ═══ 全角符号标准化(注释剥离已由全局 stripComments 完成,此处不再处理注释)═══
|
|
20
|
+
if (context !== 'prompt') {
|
|
21
|
+
s = s
|
|
22
|
+
.replace(/:/g, ':')
|
|
23
|
+
.replace(/,/g, ',')
|
|
24
|
+
.replace(/“/g, '"')
|
|
25
|
+
.replace(/”/g, '"')
|
|
26
|
+
.replace(/(/g, '(')
|
|
27
|
+
.replace(/)/g, ')')
|
|
28
|
+
.replace(/【/g, '[')
|
|
29
|
+
.replace(/】/g, ']')
|
|
30
|
+
.replace(/|/g, '|');
|
|
31
|
+
}
|
|
32
|
+
// flow 区域额外:-- 替换为 ->
|
|
33
|
+
if (context === 'flow') {
|
|
34
|
+
s = s.replace(/--/g, '->');
|
|
35
|
+
}
|
|
36
|
+
return s;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// ═══════════════════════════════════════════════════════════════
|
|
40
|
+
// ═══ 全局注释剥离(编译第一步)═══
|
|
41
|
+
// ═══════════════════════════════════════════════════════════════
|
|
42
|
+
// 除 prompt 文本块内部与字符串引号内部外,所有 `#` 与 `//` 连同其后内容
|
|
43
|
+
// 清空到行尾。行首缩进保留(块结构依赖缩进)。
|
|
44
|
+
|
|
45
|
+
// 引号感知的行级注释剥离
|
|
46
|
+
function stripLineComments(line) {
|
|
47
|
+
let out = '';
|
|
48
|
+
let quote = null;
|
|
49
|
+
for (let i = 0; i < line.length; i++) {
|
|
50
|
+
const c = line[i];
|
|
51
|
+
if (quote) {
|
|
52
|
+
out += c;
|
|
53
|
+
if (c === '\\' && i + 1 < line.length) {
|
|
54
|
+
out += line[i + 1];
|
|
55
|
+
i++;
|
|
56
|
+
continue;
|
|
57
|
+
}
|
|
58
|
+
if (c === quote) quote = null;
|
|
59
|
+
continue;
|
|
60
|
+
}
|
|
61
|
+
if (c === '"' || c === "'") {
|
|
62
|
+
quote = c;
|
|
63
|
+
out += c;
|
|
64
|
+
continue;
|
|
65
|
+
}
|
|
66
|
+
if (c === '#') {
|
|
67
|
+
break;
|
|
68
|
+
}
|
|
69
|
+
if (c === '/' && line[i + 1] === '/') break;
|
|
70
|
+
out += c;
|
|
71
|
+
}
|
|
72
|
+
return out;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// 找出所有多行文本块 [start, end) 行区间:
|
|
76
|
+
// prompt: | / showprompt: |(action)以及 key = |(meta:system_safety 等)
|
|
77
|
+
function findPromptRanges(lines) {
|
|
78
|
+
const ranges = [];
|
|
79
|
+
let i = 0;
|
|
80
|
+
while (i < lines.length) {
|
|
81
|
+
const trimmed = lines[i].trim();
|
|
82
|
+
// 允许行尾带注释(全局剥离后该行会先被清成 prompt: |,此处宽松匹配)
|
|
83
|
+
const isMultiStart =
|
|
84
|
+
/^(?:prompt|showprompt):\s*[||]\s*(?:#.*)?$/.test(trimmed) ||
|
|
85
|
+
/^(?:@|\$@|\$)?[\w\u4e00-\u9fff]+\s*=\s*[||]\s*(?:#.*)?$/.test(trimmed);
|
|
86
|
+
if (isMultiStart) {
|
|
87
|
+
const fieldIndent = lines[i].length - lines[i].trimStart().length;
|
|
88
|
+
let j = i + 1;
|
|
89
|
+
while (j < lines.length) {
|
|
90
|
+
const t2 = lines[j].trim();
|
|
91
|
+
if (!t2) { j++; continue; } // 空行算 prompt 内容
|
|
92
|
+
const ind2 = lines[j].length - lines[j].trimStart().length;
|
|
93
|
+
if (ind2 <= fieldIndent) break; // 缩进回到字段层 → 块结束
|
|
94
|
+
j++;
|
|
95
|
+
}
|
|
96
|
+
ranges.push([i + 1, j]);
|
|
97
|
+
i = j;
|
|
98
|
+
continue;
|
|
99
|
+
}
|
|
100
|
+
i++;
|
|
101
|
+
}
|
|
102
|
+
return ranges;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// ═══════════════════════════════════════════════════════════════
|
|
106
|
+
// ═══ #sketch 注释块还原(编译第零步,必须先于 stripComments)═══
|
|
107
|
+
// ═══════════════════════════════════════════════════════════════
|
|
108
|
+
// 生成端把 sketch 块写成注释(每行行首加 #);这里检测 #sketch 标志,
|
|
109
|
+
// 把整个块取出、每行剥掉行首一个 #(# 后的空格即原缩进),还原为
|
|
110
|
+
// 普通 sketch: 块,再走正常链路解析。块内残余 #(手写注释)交由
|
|
111
|
+
// stripComments 正常去掉。
|
|
112
|
+
function extractHashSketch(lines) {
|
|
113
|
+
const out = [];
|
|
114
|
+
let i = 0;
|
|
115
|
+
while (i < lines.length) {
|
|
116
|
+
const raw = lines[i];
|
|
117
|
+
if (/^#\s*sketch\s*:/.test(raw)) {
|
|
118
|
+
out.push(raw.replace(/^#/, '')); // 标志行剥一个 # → sketch:
|
|
119
|
+
i++;
|
|
120
|
+
while (i < lines.length && /^#/.test(lines[i])) {
|
|
121
|
+
out.push(lines[i].replace(/^#/, '')); // 块内容行同样剥一个 #
|
|
122
|
+
i++;
|
|
123
|
+
}
|
|
124
|
+
} else {
|
|
125
|
+
out.push(raw);
|
|
126
|
+
i++;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
return out;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// 全局注释剥离:parseFEMO 的第一步
|
|
133
|
+
function stripComments(lines) {
|
|
134
|
+
const ranges = findPromptRanges(lines);
|
|
135
|
+
return lines.map((raw, i) => {
|
|
136
|
+
for (const [s, e] of ranges) {
|
|
137
|
+
if (i >= s && i < e) return raw; // prompt 文本块:原样保留
|
|
138
|
+
}
|
|
139
|
+
return stripLineComments(raw);
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
// rep:统一报错链路入口(femoDiagnostics.createReporter 产物)。可外部传入
|
|
144
|
+
// 以收集诊断;缺省时内部自建。error → 抛 FEMOSyntaxError(阻断);warning →
|
|
145
|
+
// 汇入 result.warnings(不阻断)。
|
|
146
|
+
function parseFEMO(text, rep = null) {
|
|
147
|
+
rep = rep || createReporter();
|
|
148
|
+
// 编译第负一步:捕获 meta: 之前的文件头原文(作者的架构说明 / ⚠️ 备忘等注释)。
|
|
149
|
+
// 下一步 stripComments 会全局剥注释,preamble 必须抢在它之前从原文截取;
|
|
150
|
+
// buildFEMO 生成时原样回写到文件头(2026-09-12:编辑器保存曾把文件头注释剥掉)。
|
|
151
|
+
// 只认顶格的 meta: 行(模块内的 meta: 有缩进,不会误命中)。
|
|
152
|
+
const rawLines = text.split('\n');
|
|
153
|
+
const metaLineIdx = rawLines.findIndex((l) => /^meta:\s*$/.test(l));
|
|
154
|
+
const preamble = metaLineIdx > 0
|
|
155
|
+
? rawLines.slice(0, metaLineIdx).join('\n').replace(/\s+$/, '')
|
|
156
|
+
: '';
|
|
157
|
+
// 编译第零步:#sketch 注释块还原(必须先于全局去注释)
|
|
158
|
+
// 编译第一步:内存版全局去注释(# 和 // 到行尾;prompt 块与引号内豁免)
|
|
159
|
+
// 只处理内存副本,用户原文/窗口文本不受影响
|
|
160
|
+
const lines = stripComments(extractHashSketch(rawLines));
|
|
161
|
+
const blocks = splitTopBlocks(lines);
|
|
162
|
+
|
|
163
|
+
const result = {
|
|
164
|
+
meta: {
|
|
165
|
+
name: '',
|
|
166
|
+
version: '1.0',
|
|
167
|
+
owner: '',
|
|
168
|
+
database: '',
|
|
169
|
+
session: '',
|
|
170
|
+
system_safety: '',
|
|
171
|
+
output_style: '',
|
|
172
|
+
},
|
|
173
|
+
code: [],
|
|
174
|
+
context: [],
|
|
175
|
+
memory: [],
|
|
176
|
+
preamble, // meta: 之前的文件头原文(注释等),buildFEMO 原样回写
|
|
177
|
+
vars: [],
|
|
178
|
+
actors: [],
|
|
179
|
+
warnings: [], // 非阻断提示(rep.warnings 诊断:行号/出错行/信息/区域)——与引擎 script.warnings 对齐
|
|
180
|
+
actions: [],
|
|
181
|
+
modules: [],
|
|
182
|
+
mainflow: { nodeDecls: [], edges: [] },
|
|
183
|
+
};
|
|
184
|
+
|
|
185
|
+
let mainflowSketch = null; // 容错:顶层 sketch: 块(与 mainflow 同级)
|
|
186
|
+
|
|
187
|
+
for (const block of blocks) {
|
|
188
|
+
const h = block.header;
|
|
189
|
+
if (h === 'meta:') {
|
|
190
|
+
result.meta = parseMetaBlock(block.contentLines, rep);
|
|
191
|
+
} else if (h === 'code:') {
|
|
192
|
+
result.code = parseCodeBlock(block.contentLines, rep);
|
|
193
|
+
} else if (h === 'vars:') {
|
|
194
|
+
result.vars = parseVarsBlock(block.contentLines, rep);
|
|
195
|
+
} else if (h === 'actors:') {
|
|
196
|
+
result.actors = parseActorsBlock(block.contentLines, rep);
|
|
197
|
+
} else if (h.startsWith('memory ')) {
|
|
198
|
+
result.memory.push(
|
|
199
|
+
parseMemoryOrContextBlock(h, block.contentLines, 'memory', rep, block.headerLineNum)
|
|
200
|
+
);
|
|
201
|
+
} else if (h.startsWith('context ')) {
|
|
202
|
+
result.context.push(
|
|
203
|
+
parseMemoryOrContextBlock(h, block.contentLines, 'context', rep, block.headerLineNum)
|
|
204
|
+
);
|
|
205
|
+
} else if (h.startsWith('action ')) {
|
|
206
|
+
result.actions.push(parseActionBlock(h, block.contentLines, rep, block.headerLineNum));
|
|
207
|
+
} else if (h.startsWith('module ')) {
|
|
208
|
+
result.modules.push(parseModuleBlock(h, block.contentLines, rep, block.headerLineNum));
|
|
209
|
+
} else if (h === 'sketch:') {
|
|
210
|
+
// 暂存顶层草图,待 mainflow 解析后合并
|
|
211
|
+
mainflowSketch = parseLayoutBlock(block.contentLines);
|
|
212
|
+
} else if (h === 'mainflow:' || h === 'flow:') {
|
|
213
|
+
// flow: 与 mainflow: 等价(编译器 build_blocks 均归为 flow 块)
|
|
214
|
+
result.mainflow = parseMainflowBlock(block.contentLines, rep);
|
|
215
|
+
// 如果有与 mainflow 同级的 sketch 块,合并布局(外部覆盖内部)
|
|
216
|
+
if (mainflowSketch) {
|
|
217
|
+
result.mainflow.layout = { ...result.mainflow.layout, ...mainflowSketch };
|
|
218
|
+
mainflowSketch = null;
|
|
219
|
+
}
|
|
220
|
+
} else {
|
|
221
|
+
rep.fail(
|
|
222
|
+
`未识别的顶层块: "${h}"。期望: meta:, code:, vars:, actors:, context:, memory:, action ..., module ..., mainflow:`,
|
|
223
|
+
{ line: (block.headerLineNum ?? -1) + 1, lineText: h, where: '顶层' }
|
|
224
|
+
);
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
// 如果 sketch 在 mainflow 之前就已经读到,但 mainflow 始终未出现,则丢弃(不报错)
|
|
229
|
+
// 如果 mainflow 已解析但之后还有 sketch 块,同样合并
|
|
230
|
+
if (mainflowSketch && result.mainflow) {
|
|
231
|
+
result.mainflow.layout = { ...result.mainflow.layout, ...mainflowSketch };
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
// 展平嵌套模块,为每个模块生成层级 path(从 mainflow 起)
|
|
235
|
+
const topModules = result.modules;
|
|
236
|
+
result.modules = [];
|
|
237
|
+
function flattenModules(mods, parentPath) {
|
|
238
|
+
for (const m of mods) {
|
|
239
|
+
const path = [...parentPath, m.name];
|
|
240
|
+
m.path = path;
|
|
241
|
+
result.modules.push(m);
|
|
242
|
+
if (m.subModules) {
|
|
243
|
+
flattenModules(m.subModules, path);
|
|
244
|
+
delete m.subModules; // 清理临时字段
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
flattenModules(topModules, ['mainflow']);
|
|
249
|
+
|
|
250
|
+
// ═══ 变量声明校验:编译器原则,未声明必须报错,不静默兜底 ═══
|
|
251
|
+
validateDeclarations(result, rep);
|
|
252
|
+
|
|
253
|
+
// ═══ 动作/作用域硬校验(2026-09-07 五类,与引擎 validate_action_syntax 对齐)═══
|
|
254
|
+
validateActionSyntax(result, rep);
|
|
255
|
+
|
|
256
|
+
// ═══ join 在环上警告(与引擎 validate_join_on_cycle 对齐,非阻断)═══
|
|
257
|
+
validateJoinOnCycle(result, text, rep);
|
|
258
|
+
|
|
259
|
+
// 报错链路收口:warning 全量挂 result.warnings({severity,line,lineText,
|
|
260
|
+
// message,where},其中 where/message 与引擎 script.warnings 两键对齐);
|
|
261
|
+
// error 若有(校验期聚合未抛的)在此统一抛出。
|
|
262
|
+
result.warnings = rep.warnings;
|
|
263
|
+
rep.throwIfErrors();
|
|
264
|
+
|
|
265
|
+
return result;
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
// join(all)/join(N) 的引擎现状是"等全部(N 个)上游到齐再放行"。若 join 的
|
|
269
|
+
// 目标节点位于流程环路上(能从目标出发绕回目标自己),环上的 fork 会先于
|
|
270
|
+
// join 发生、又只有 join 放行后才会再发生——等待集永远凑不齐,剧本必然无声
|
|
271
|
+
// 卡死(实锤:警长版被"图到文本"自动加 join(all) 后 DayPhase 永远进不去)。
|
|
272
|
+
// ⚠️ 前端图模型不建 join 节点(join(...) 按文档等价于普通多线,解析期摊平
|
|
273
|
+
// 成普通边),所以这里从**原文**扫描 join(...) 块拿目标节点,再到解析后的
|
|
274
|
+
// 图里查环。非阻断 warning:与引擎 add_warning 同语义,走统一报错链路
|
|
275
|
+
// (rep.warning),随 result.warnings 供 UI 展示;等引擎 join 语义修正
|
|
276
|
+
// (下一轮)后本警告可随之退役。
|
|
277
|
+
function validateJoinOnCycle(result, text, rep = null) {
|
|
278
|
+
rep = rep || createReporter();
|
|
279
|
+
const flows = [];
|
|
280
|
+
if (result.mainflow) flows.push({ edges: result.mainflow.edges, where: 'mainflow' });
|
|
281
|
+
for (const m of result.modules || []) {
|
|
282
|
+
flows.push({ edges: m.edges, where: `module ${m.name}` });
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
function onCycle(targetLabel, edges) {
|
|
286
|
+
// 正向 BFS:从目标的后继出发,看能否绕回目标自己
|
|
287
|
+
const frontier = (edges || [])
|
|
288
|
+
.filter((e) => e.srcLabel === targetLabel)
|
|
289
|
+
.map((e) => e.tgtLabel);
|
|
290
|
+
const visited = new Set(frontier);
|
|
291
|
+
while (frontier.length) {
|
|
292
|
+
const nid = frontier.pop();
|
|
293
|
+
if (nid === targetLabel) return true;
|
|
294
|
+
for (const e of edges || []) {
|
|
295
|
+
if (e.srcLabel === nid && !visited.has(e.tgtLabel)) {
|
|
296
|
+
visited.add(e.tgtLabel);
|
|
297
|
+
frontier.push(e.tgtLabel);
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
return false;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
const joinBlock = /join\s*\(([^)]*)\)\s*:\s*([\s\S]*?)to\s*\[([^\]]+)\]/g;
|
|
305
|
+
let m;
|
|
306
|
+
while ((m = joinBlock.exec(String(text || '')) ) !== null) {
|
|
307
|
+
const target = m[3].trim();
|
|
308
|
+
for (const f of flows) {
|
|
309
|
+
const known = new Set((f.edges || []).flatMap((e) => [e.srcLabel, e.tgtLabel]));
|
|
310
|
+
if (known.has(target) && onCycle(target, f.edges)) {
|
|
311
|
+
// 从命中位置反推 1-based 行号与出错行(原文正则扫描,无行对象可用)
|
|
312
|
+
const before = String(text || '').slice(0, m.index);
|
|
313
|
+
const line = before.split('\n').length;
|
|
314
|
+
const lineText = (text.slice(m.index).split('\n')[0] || '').trim();
|
|
315
|
+
rep.warning(
|
|
316
|
+
`join(...) 的目标 [${target}] 位于流程环路上(从它出发能绕回它自己)。` +
|
|
317
|
+
'当前引擎的 join 会等待上游到齐,而环路里的一部分上游只有 join 放行之后才会发生,' +
|
|
318
|
+
'这会让剧本永远等待下去。请把循环里的合流改成普通多线汇入' +
|
|
319
|
+
'(逐条 [A] -> [next],到即走),不要用 join(...):。',
|
|
320
|
+
{ line, lineText, where: f.where }
|
|
321
|
+
);
|
|
322
|
+
break; // 每个 join 块只报一条
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
// ── 变量声明校验 ────────────────────────────────────────────
|
|
329
|
+
// 规则(与引擎一致):
|
|
330
|
+
// 1. for 循环变量必须已在 vars: 声明(如 @hero = "")
|
|
331
|
+
// 2. 条件表达式里的裸标识符必须是已声明变量 / actor / 循环变量,
|
|
332
|
+
// 字符串字面量必须带引号(== "ai" 而非 == ai)
|
|
333
|
+
const _RESERVED_WORDS = new Set([
|
|
334
|
+
'and', 'or', 'not', 'in', 'is',
|
|
335
|
+
'True', 'False', 'None', 'true', 'false', 'TRUE', 'FALSE',
|
|
336
|
+
]);
|
|
337
|
+
|
|
338
|
+
function _extractCondIdentifiers(cond) {
|
|
339
|
+
// 剥离字符串字面量(带引号的文本不算标识符)
|
|
340
|
+
const noStr = cond.replace(/"[^"]*"|'[^']*'/g, '""');
|
|
341
|
+
return noStr.match(/@?[\w\u4e00-\u9fff]+(?:\.[\w\u4e00-\u9fff]+)*/g) || [];
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
function _mainIdent(ident) {
|
|
345
|
+
const dot = ident.indexOf('.');
|
|
346
|
+
return dot >= 0 ? ident.slice(0, dot) : ident;
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
function _declName(raw) {
|
|
350
|
+
// 规范名:剥 $ 前缀、@ 保留(与后端编译器 split_spec_name 完全一致:
|
|
351
|
+
// '$x'→'x','$@a'→'@a','@a'→'@a','x'→'x')。
|
|
352
|
+
// 条件/for 提取(_extractCondIdentifiers 等)产出的是不带 $ 的裸标识符,
|
|
353
|
+
// 声明表若保留 $ 前缀会两头对不上——造成 "$game_over 已声明却被报
|
|
354
|
+
// 引用了未声明的变量 game_over" 的误报。声明名必须过此函数归一。
|
|
355
|
+
return raw.startsWith('$') ? raw.slice(1) : raw;
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
function validateDeclarations(result, rep = null) {
|
|
359
|
+
rep = rep || createReporter();
|
|
360
|
+
const topVars = new Set((result.vars || []).map((v) => _declName(v.name)));
|
|
361
|
+
const actors = new Set((result.actors || []).map((a) => a.name));
|
|
362
|
+
const moduleVars = new Map();
|
|
363
|
+
for (const m of result.modules || []) {
|
|
364
|
+
moduleVars.set(m.name, new Set((m.vars || []).map((v) => _declName(v.name))));
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
function validateFlow(nodeDecls, edges, ctxName, moduleName) {
|
|
368
|
+
const scopeVars = new Set(topVars);
|
|
369
|
+
if (moduleName && moduleVars.has(moduleName)) {
|
|
370
|
+
for (const n of moduleVars.get(moduleName)) scopeVars.add(n);
|
|
371
|
+
}
|
|
372
|
+
const loopVars = new Set();
|
|
373
|
+
|
|
374
|
+
// 1) for 循环变量与迭代器声明检查
|
|
375
|
+
for (const d of nodeDecls || []) {
|
|
376
|
+
if (d.specialType === 'FOR' && d.forCondition) {
|
|
377
|
+
const m = d.forCondition.match(/^(@?[\w\u4e00-\u9fff]+)\s+in\s+(.+)$/);
|
|
378
|
+
if (!m) {
|
|
379
|
+
rep.fail(
|
|
380
|
+
`for 条件格式错误: "${d.forCondition}"。期望: for @var in list`,
|
|
381
|
+
{ where: ctxName }
|
|
382
|
+
);
|
|
383
|
+
}
|
|
384
|
+
const loopVar = m[1];
|
|
385
|
+
if (!scopeVars.has(loopVar)) {
|
|
386
|
+
rep.fail(
|
|
387
|
+
`for 循环变量 "${loopVar}" 未在 vars: 中声明(for 条件: "${d.forCondition}")。` +
|
|
388
|
+
`所有循环变量必须在 vars: 中预先声明,例如: ${loopVar} = ""`,
|
|
389
|
+
{ where: ctxName }
|
|
390
|
+
);
|
|
391
|
+
}
|
|
392
|
+
loopVars.add(loopVar);
|
|
393
|
+
const iterable = m[2].trim();
|
|
394
|
+
if (/^@?[\w\u4e00-\u9fff]+$/.test(iterable) && !scopeVars.has(iterable)) {
|
|
395
|
+
rep.fail(
|
|
396
|
+
`for 迭代器 "${iterable}" 未在 vars: 中声明(for 条件: "${d.forCondition}")`,
|
|
397
|
+
{ where: ctxName }
|
|
398
|
+
);
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
// 2) 条件表达式里的裸标识符检查
|
|
404
|
+
const known = new Set([...scopeVars, ...actors, ...loopVars]);
|
|
405
|
+
for (const e of edges || []) {
|
|
406
|
+
if (!e.cond) continue;
|
|
407
|
+
for (const ident of _extractCondIdentifiers(e.cond)) {
|
|
408
|
+
if (_RESERVED_WORDS.has(ident)) continue;
|
|
409
|
+
const main = _mainIdent(ident);
|
|
410
|
+
if (/^\d+(\.\d+)?$/.test(main)) continue; // 数字字面量
|
|
411
|
+
if (main.startsWith('@')) {
|
|
412
|
+
if (!actors.has(main) && !scopeVars.has(main) && !loopVars.has(main)) {
|
|
413
|
+
rep.fail(
|
|
414
|
+
`条件 "${e.cond}" 引用了未声明的 actor/变量 "${main}"(边 ${e.srcLabel} -> ${e.tgtLabel})`,
|
|
415
|
+
{ where: ctxName }
|
|
416
|
+
);
|
|
417
|
+
}
|
|
418
|
+
} else if (!known.has(main)) {
|
|
419
|
+
rep.fail(
|
|
420
|
+
`条件 "${e.cond}" 引用了未声明的变量 "${main}"(边 ${e.srcLabel} -> ${e.tgtLabel})。` +
|
|
421
|
+
`字符串字面量请加引号,如 == "ai";所有变量须在 vars: 中声明`,
|
|
422
|
+
{ where: ctxName }
|
|
423
|
+
);
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
// 3) 回流检测:回到「多条无条件出边」的节点会导致分支数爆炸——
|
|
429
|
+
// 每次回到这里往下运行都会从一变成多分支。条件出边(if 分流)
|
|
430
|
+
// 回流是安全的(只走为真的分支),不检测;for/par/fork/join 网关
|
|
431
|
+
// 的多出边是迭代/并发语义,跳过;重复边去重(par 出口链可能重复)。
|
|
432
|
+
const seenEdges = new Set();
|
|
433
|
+
const uniqEdges = (edges || []).filter((e) => {
|
|
434
|
+
const key = `${e.srcLabel}\u0000${e.tgtLabel}\u0000${e.cond || ''}`;
|
|
435
|
+
if (seenEdges.has(key)) return false;
|
|
436
|
+
seenEdges.add(key);
|
|
437
|
+
return true;
|
|
438
|
+
});
|
|
439
|
+
// 「回到」= 入边来自流程内部;入口启动边([START]/[IN] 出发)不算。
|
|
440
|
+
// 【2026-09-06 修复】边 label 存的是剥括号形态('IN'/'START',见
|
|
441
|
+
// chainMatch/resolveTarget),原先按 '[IN]'/'[START]' 带括号比较恒不
|
|
442
|
+
// 相等 → 入口排除成死代码,「入口直连多出边」这一最常见形态全部误报
|
|
443
|
+
// (module chat 的 [hub] 即此误报)。比较前统一剥括号,两种形态都兜住。
|
|
444
|
+
const entrySrc = (s) => String(s ?? '').replace(/^\[|\]$/g, '');
|
|
445
|
+
const hasIn = new Set(
|
|
446
|
+
uniqEdges
|
|
447
|
+
.filter((e) => entrySrc(e.srcLabel) !== 'START' && entrySrc(e.srcLabel) !== 'IN')
|
|
448
|
+
.map((e) => e.tgtLabel)
|
|
449
|
+
);
|
|
450
|
+
const gatewayNames = new Set(
|
|
451
|
+
(nodeDecls || [])
|
|
452
|
+
.filter((d) => d.specialType === 'FOR' || d.specialType === 'PAR' || d.specialType === 'FORK' || d.specialType === 'JOIN')
|
|
453
|
+
.map((d) => d.label)
|
|
454
|
+
);
|
|
455
|
+
const unconditionalOuts = new Map();
|
|
456
|
+
for (const e of uniqEdges) {
|
|
457
|
+
if (!e.cond) {
|
|
458
|
+
const list = unconditionalOuts.get(e.srcLabel) || [];
|
|
459
|
+
list.push(e.tgtLabel);
|
|
460
|
+
unconditionalOuts.set(e.srcLabel, list);
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
for (const [src, tgts] of unconditionalOuts) {
|
|
464
|
+
if (gatewayNames.has(src)) continue;
|
|
465
|
+
if (tgts.length >= 2 && hasIn.has(src)) {
|
|
466
|
+
// 【2026-09-07 用户拍板】编译期不再阻断回流(分支数爆炸)场景:
|
|
467
|
+
// 原为 throw 拦截前端解析/画布恢复/运行,现改为不阻断——用户坚持运行则应能跑。
|
|
468
|
+
// 以后改成 warning(提示但不阻断);保留原报错信息留档,勿删。
|
|
469
|
+
// throw new Error(
|
|
470
|
+
// `${ctxName}: 节点 [${src}] 有多个出边,不能回到这种节点。` +
|
|
471
|
+
// `原因是,每次回到这里往下运行都会从一变成多分支,分支数会爆炸。` +
|
|
472
|
+
// `建议在本节点之后的分支中加空节点,让他们回到空节点。`
|
|
473
|
+
// );
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
validateFlow(result.mainflow.nodeDecls, result.mainflow.edges, 'mainflow', null);
|
|
479
|
+
for (const m of result.modules || []) {
|
|
480
|
+
validateFlow(m.nodeDecls, m.edges, `module ${m.name}`, m.name);
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
// ── 动作/作用域硬校验(2026-09-07,与引擎 FEMO_parser.validate_action_syntax 逐条对齐)──
|
|
485
|
+
// 五类此前被静默吞掉的语法错误,前端直接判 error 提示(前端与引擎是两份独立的
|
|
486
|
+
// 语法检查:前端不带引擎可出图,引擎不带前端可跑,两边都要报、不遗漏):
|
|
487
|
+
// ① @func 缺少"模块别名.函数名"(@func: / @func() / @func(别名))
|
|
488
|
+
// ② in: 项缺 "= 变量表达式" 映射(裸项,多行/单行都查)
|
|
489
|
+
// ③ scope 引用不存在的角色(@名 不在 actors 也不是已声明变量)
|
|
490
|
+
// ④ scope 格式错误(self 与其他目标混用;多目标未加方括号)
|
|
491
|
+
// ⑤ 变量名与 Python 保留字冲突(vars:/out: 目标/in: 左侧/for·par 循环变量)
|
|
492
|
+
|
|
493
|
+
const _PY_KEYWORDS = new Set([
|
|
494
|
+
'False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await',
|
|
495
|
+
'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except',
|
|
496
|
+
'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is',
|
|
497
|
+
'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return',
|
|
498
|
+
'try', 'while', 'with', 'yield',
|
|
499
|
+
]);
|
|
500
|
+
|
|
501
|
+
function _stripSpecName(name) {
|
|
502
|
+
// 剥 $/@ 前缀('$alive'→'alive','@狼人'→'狼人'),与引擎 _strip_spec_name 一致
|
|
503
|
+
return String(name || '').replace(/^[$@]+/, '').trim();
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
function _outTargetRoot(raw) {
|
|
507
|
+
// out: 项原文 → 赋值目标根名('day += 1'→'day';'hp.@x(string,"xx")'→'hp')
|
|
508
|
+
let t = String(raw || '').trim().replace(/,+$/, '').trim();
|
|
509
|
+
t = t.replace(/\([^)]*\)\s*$/, '').trim(); // 剥尾部类型标签
|
|
510
|
+
t = t.split(/\+=|-=|=(?!=)/)[0].trim(); // 剥赋值运算符及右侧
|
|
511
|
+
return _stripSpecName(t);
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
function _splitInItems(inMappings) {
|
|
515
|
+
// inMappings 是字符串(多行用 \n 连接,单行可能逗号分隔)→ 项数组
|
|
516
|
+
const items = [];
|
|
517
|
+
for (const line of String(inMappings || '').split('\n')) {
|
|
518
|
+
for (const piece of line.split(',')) {
|
|
519
|
+
const t = piece.trim().replace(/,+$/, '').trim();
|
|
520
|
+
if (t) items.push(t);
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
return items;
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
function validateActionSyntax(result, rep = null) {
|
|
527
|
+
rep = rep || createReporter();
|
|
528
|
+
const actors = new Set((result.actors || []).map((a) => a.name));
|
|
529
|
+
const topScopeVars = new Set((result.vars || []).map((v) => _stripSpecName(v.name)));
|
|
530
|
+
|
|
531
|
+
function checkScope(rawScope, scopeVars, ctx) {
|
|
532
|
+
const s = String(rawScope || '').trim();
|
|
533
|
+
if (!s || s.toLowerCase() === 'all' || s.toLowerCase() === 'self') return;
|
|
534
|
+
// ② self 与其他目标混用
|
|
535
|
+
if (/\bself\b/i.test(s)) {
|
|
536
|
+
rep.error(
|
|
537
|
+
`${ctx}: scope: ${s} → "self" 只能单独使用(scope: self = 仅发言者可见);` +
|
|
538
|
+
`多目标请写成方括号列表,如 scope: [@上帝, @player]`,
|
|
539
|
+
{ where: 'action 校验' }
|
|
540
|
+
);
|
|
541
|
+
return;
|
|
542
|
+
}
|
|
543
|
+
for (const part of s.split('+')) {
|
|
544
|
+
const p = part.trim();
|
|
545
|
+
if (!p) continue;
|
|
546
|
+
if (p.startsWith('[')) {
|
|
547
|
+
if (!p.endsWith(']')) {
|
|
548
|
+
rep.error(`${ctx}: scope: ${s} → 方括号不闭合,请检查列表格式`, { where: 'action 校验' });
|
|
549
|
+
continue;
|
|
550
|
+
}
|
|
551
|
+
for (const item of p.slice(1, -1).split(/[,,]/)) {
|
|
552
|
+
const it = item.trim();
|
|
553
|
+
if (!it) continue;
|
|
554
|
+
if (it.startsWith('{') && it.endsWith('}')) continue; // 花括号动态项交运行期
|
|
555
|
+
if (it.startsWith('@')) {
|
|
556
|
+
// ③ 引用不存在的角色/变量
|
|
557
|
+
if (!actors.has(it) && !scopeVars.has(_stripSpecName(it))) {
|
|
558
|
+
rep.error(
|
|
559
|
+
`${ctx}: scope: ${s} → "${it}" 不是已声明的角色,也不是已声明的变量。` +
|
|
560
|
+
`可用角色:${[...actors].sort().join(' / ') || '(无)'}`,
|
|
561
|
+
{ where: 'action 校验' }
|
|
562
|
+
);
|
|
563
|
+
}
|
|
564
|
+
} else if (!scopeVars.has(it)) {
|
|
565
|
+
rep.error(
|
|
566
|
+
`${ctx}: scope: ${s} → "${it}" 未在 vars: 中声明` +
|
|
567
|
+
`(scope 列表里的名字必须是角色 @名 或已声明变量)`,
|
|
568
|
+
{ where: 'action 校验' }
|
|
569
|
+
);
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
} else if (/[,,]/.test(p)) {
|
|
573
|
+
// ② 多目标未加方括号
|
|
574
|
+
const suggestion = '[' + p.split(/[,,]/).map((x) => x.trim()).join(', ') + ']';
|
|
575
|
+
rep.error(
|
|
576
|
+
`${ctx}: scope: ${s} → 多个目标必须用方括号列表包裹,请写成 scope: ${suggestion}`,
|
|
577
|
+
{ where: 'action 校验' }
|
|
578
|
+
);
|
|
579
|
+
} else if (!scopeVars.has(p) && !scopeVars.has(_stripSpecName(p))) {
|
|
580
|
+
rep.error(
|
|
581
|
+
`${ctx}: scope: ${s} → "${p}" 未在 vars: 中声明` +
|
|
582
|
+
`(裸名按变量解析,必须先在 vars: 声明;角色请带 @)`,
|
|
583
|
+
{ where: 'action 校验' }
|
|
584
|
+
);
|
|
585
|
+
}
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
function checkAction(action, scopeVars, ctx) {
|
|
590
|
+
// ① @func 必须带 模块别名.函数名
|
|
591
|
+
if (action.executorType === 'func') {
|
|
592
|
+
const param = String(action.executorActor || '').trim();
|
|
593
|
+
if (!/^[\w\u4e00-\u9fff]+\.[\w\u4e00-\u9fff]+$/.test(param)) {
|
|
594
|
+
rep.error(
|
|
595
|
+
`action "${action.name}"(${ctx})→ @func 缺少"模块别名.函数名"。` +
|
|
596
|
+
`必须写成 @func(模块别名.函数名),别名在 code: 区声明。示例:@func(werewolf_utils.get_order)`,
|
|
597
|
+
{ where: 'action 校验' }
|
|
598
|
+
);
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
// ⑥ @notice 分级校验(与引擎 validate_action_syntax 镜像):
|
|
602
|
+
// error = 静默错误行为;warning = 惰性死配置
|
|
603
|
+
if (action.executorType === 'notice') {
|
|
604
|
+
if (!String(action.prompt || '').trim()) {
|
|
605
|
+
rep.error(
|
|
606
|
+
`action "${action.name}"(${ctx})→ @notice 的 prompt 为空。` +
|
|
607
|
+
`公告节点必须要有 prompt(它就是注入上下文的公告本体)`,
|
|
608
|
+
{ where: 'action 校验' }
|
|
609
|
+
);
|
|
610
|
+
}
|
|
611
|
+
if (String(action.outVars || '').trim()) {
|
|
612
|
+
rep.error(
|
|
613
|
+
`action "${action.name}"(${ctx})→ @notice 不支持 out:。` +
|
|
614
|
+
`公告节点没有回答者,out 声明的变量永远不会被赋值,赋值请用 @assign 或让 AI/human 输出`,
|
|
615
|
+
{ where: 'action 校验' }
|
|
616
|
+
);
|
|
617
|
+
}
|
|
618
|
+
if (String(action.resolve || '').trim()) {
|
|
619
|
+
rep.error(
|
|
620
|
+
`action "${action.name}"(${ctx})→ @notice 不支持 resolve:。` +
|
|
621
|
+
`公告节点没有回答者,校验函数永远不会被调用`,
|
|
622
|
+
{ where: 'action 校验' }
|
|
623
|
+
);
|
|
624
|
+
}
|
|
625
|
+
const inert = [];
|
|
626
|
+
if (String(action.memory || '').trim()) inert.push('memory:');
|
|
627
|
+
if (String(action.context || '').trim()) inert.push('context:');
|
|
628
|
+
if (String(action.showprompt || '').trim()) inert.push('showprompt:');
|
|
629
|
+
if (action.max_retries) inert.push('max_retries:');
|
|
630
|
+
if (String(action.fallback || '').trim()) inert.push('fallback:');
|
|
631
|
+
if (inert.length) {
|
|
632
|
+
rep.warning(
|
|
633
|
+
`action "${action.name}"(${ctx})→ @notice 的 ${inert.join(' / ')} 不生效:` +
|
|
634
|
+
`公告节点无回答者(惰性死配置,知情即可)`,
|
|
635
|
+
{ where: 'action 校验' }
|
|
636
|
+
);
|
|
637
|
+
}
|
|
638
|
+
if (String(action.scope || '').trim().toLowerCase() === 'self') {
|
|
639
|
+
rep.warning(
|
|
640
|
+
`action "${action.name}"(${ctx})→ @notice 的 scope: self = 仅 meta.owner 可见(公告无发言者)`,
|
|
641
|
+
{ where: 'action 校验' }
|
|
642
|
+
);
|
|
643
|
+
}
|
|
644
|
+
if (String(action.executorActor || '').trim()) {
|
|
645
|
+
rep.warning(
|
|
646
|
+
`action "${action.name}"(${ctx})→ @notice 的执行者参数被整体忽略(公告没有发言者),导出时会剥掉`,
|
|
647
|
+
{ where: 'action 校验' }
|
|
648
|
+
);
|
|
649
|
+
}
|
|
650
|
+
}
|
|
651
|
+
// ② in: 裸项 + ⑤ in: 左侧保留字
|
|
652
|
+
const items = _splitInItems(action.inMappings);
|
|
653
|
+
const bare = items.filter((it) => !it.includes('='));
|
|
654
|
+
if (bare.length > 0) {
|
|
655
|
+
rep.error(
|
|
656
|
+
`action "${action.name}"(${ctx})→ in: 项缺少 "= 变量表达式" 映射:` +
|
|
657
|
+
`${bare.join(', ')}。in: 的每一项必须是 "参数名 = 变量表达式",例如 in: from_ = speak_from`,
|
|
658
|
+
{ where: 'action 校验' }
|
|
659
|
+
);
|
|
660
|
+
}
|
|
661
|
+
for (const it of items) {
|
|
662
|
+
const left = it.split('=')[0].trim();
|
|
663
|
+
if (_PY_KEYWORDS.has(_stripSpecName(left))) {
|
|
664
|
+
rep.error(
|
|
665
|
+
`action "${action.name}"(${ctx})→ in: 参数名 "${_stripSpecName(left)}" ` +
|
|
666
|
+
`是 Python 保留字,不能用作参数名,请改名`,
|
|
667
|
+
{ where: 'action 校验' }
|
|
668
|
+
);
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
// ⑤ out: 目标保留字
|
|
672
|
+
for (const line of String(action.outVars || '').split('\n')) {
|
|
673
|
+
for (const item of line.split(',')) {
|
|
674
|
+
const target = _outTargetRoot(item);
|
|
675
|
+
if (_PY_KEYWORDS.has(target)) {
|
|
676
|
+
rep.error(
|
|
677
|
+
`action "${action.name}"(${ctx})→ out: 目标 "${target}" ` +
|
|
678
|
+
`是 Python 保留字,不能用作变量名,请改名`,
|
|
679
|
+
{ where: 'action 校验' }
|
|
680
|
+
);
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
// ③④ scope
|
|
685
|
+
checkScope(action.scope, scopeVars, `action "${action.name}"(${ctx})`);
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
for (const action of result.actions || []) {
|
|
689
|
+
checkAction(action, topScopeVars, '顶层');
|
|
690
|
+
}
|
|
691
|
+
for (const m of result.modules || []) {
|
|
692
|
+
const scopeVars = new Set([...topScopeVars, ...((m.vars || []).map((v) => _stripSpecName(v.name)))]);
|
|
693
|
+
const ctx = `module ${m.name}`;
|
|
694
|
+
for (const action of m.actions || []) {
|
|
695
|
+
checkAction(action, scopeVars, ctx);
|
|
696
|
+
}
|
|
697
|
+
// ⑤ for/par 循环变量保留字
|
|
698
|
+
for (const d of m.nodeDecls || []) {
|
|
699
|
+
if ((d.specialType === 'FOR' || d.specialType === 'PAR') && d.forCondition) {
|
|
700
|
+
const match = d.forCondition.match(/^(@?[\w\u4e00-\u9fff]+)\s+in\s+/);
|
|
701
|
+
if (match && _PY_KEYWORDS.has(_stripSpecName(match[1]))) {
|
|
702
|
+
rep.error(
|
|
703
|
+
`${ctx} 循环变量 "${_stripSpecName(match[1])}" 是 Python 保留字,不能用作循环变量名,请改名`,
|
|
704
|
+
{ where: 'action 校验' }
|
|
705
|
+
);
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
}
|
|
709
|
+
}
|
|
710
|
+
// ⑤ 顶层 for/par 循环变量保留字
|
|
711
|
+
for (const d of (result.mainflow && result.mainflow.nodeDecls) || []) {
|
|
712
|
+
if ((d.specialType === 'FOR' || d.specialType === 'PAR') && d.forCondition) {
|
|
713
|
+
const match = d.forCondition.match(/^(@?[\w\u4e00-\u9fff]+)\s+in\s+/);
|
|
714
|
+
if (match && _PY_KEYWORDS.has(_stripSpecName(match[1]))) {
|
|
715
|
+
rep.error(
|
|
716
|
+
`mainflow 循环变量 "${_stripSpecName(match[1])}" 是 Python 保留字,不能用作循环变量名,请改名`,
|
|
717
|
+
{ where: 'action 校验' }
|
|
718
|
+
);
|
|
719
|
+
}
|
|
720
|
+
}
|
|
721
|
+
}
|
|
722
|
+
// ⑤ vars: 声明保留字
|
|
723
|
+
const varDecls = [...(result.vars || [])];
|
|
724
|
+
for (const m of result.modules || []) {
|
|
725
|
+
for (const v of m.vars || []) varDecls.push(v);
|
|
726
|
+
}
|
|
727
|
+
for (const v of varDecls) {
|
|
728
|
+
if (_PY_KEYWORDS.has(_stripSpecName(v.name))) {
|
|
729
|
+
rep.error(
|
|
730
|
+
`vars: 变量名 "${_stripSpecName(v.name)}" 是 Python 保留字,不能用作变量名,请换一个不冲突的名字`,
|
|
731
|
+
{ where: 'action 校验' }
|
|
732
|
+
);
|
|
733
|
+
}
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
// 收集到的 error 聚合抛出(一条则单条直抛,多条带计数头)
|
|
737
|
+
rep.throwIfErrors('编译错误:剧本语法检查未通过');
|
|
738
|
+
}
|
|
739
|
+
|
|
740
|
+
function splitTopBlocks(lines) {
|
|
741
|
+
const blocks = [];
|
|
742
|
+
let current = null;
|
|
743
|
+
for (let i = 0; i < lines.length; i++) {
|
|
744
|
+
const line = lines[i];
|
|
745
|
+
const trimmed = line.trim();
|
|
746
|
+
const indent = line.length - line.trimStart().length;
|
|
747
|
+
|
|
748
|
+
// 空白行:如果当前正在某个块内,保留它
|
|
749
|
+
if (!trimmed) {
|
|
750
|
+
if (current) {
|
|
751
|
+
current.contentLines.push({
|
|
752
|
+
indent,
|
|
753
|
+
text: '',
|
|
754
|
+
lineNum: i,
|
|
755
|
+
raw: line,
|
|
756
|
+
});
|
|
757
|
+
}
|
|
758
|
+
continue;
|
|
759
|
+
}
|
|
760
|
+
|
|
761
|
+
if (indent === 0) {
|
|
762
|
+
// 顶层注释行(# 或 //)不构成块,直接跳过
|
|
763
|
+
if (trimmed.startsWith('#') || trimmed.startsWith('//')) {
|
|
764
|
+
continue;
|
|
765
|
+
}
|
|
766
|
+
if (current) blocks.push(current);
|
|
767
|
+
current = {
|
|
768
|
+
header: normalizeSymbols(trimmed),
|
|
769
|
+
headerLineNum: i,
|
|
770
|
+
contentLines: [],
|
|
771
|
+
};
|
|
772
|
+
} else if (current) {
|
|
773
|
+
current.contentLines.push({
|
|
774
|
+
indent,
|
|
775
|
+
text: trimmed,
|
|
776
|
+
lineNum: i,
|
|
777
|
+
raw: line,
|
|
778
|
+
});
|
|
779
|
+
}
|
|
780
|
+
}
|
|
781
|
+
if (current) blocks.push(current);
|
|
782
|
+
return blocks;
|
|
783
|
+
}
|
|
784
|
+
|
|
785
|
+
function parseMetaBlock(cls, rep = null) {
|
|
786
|
+
rep = rep || createReporter();
|
|
787
|
+
const meta = {}; // 不再预设空字段,全部由用户定义
|
|
788
|
+
let i = 0;
|
|
789
|
+
while (i < cls.length) {
|
|
790
|
+
const cl = cls[i];
|
|
791
|
+
// 跳过空行与整行注释
|
|
792
|
+
const _t = cl.text.trim();
|
|
793
|
+
if (!_t || _t.startsWith('#')) {
|
|
794
|
+
i++;
|
|
795
|
+
continue;
|
|
796
|
+
}
|
|
797
|
+
const line = normalizeSymbols(cl.text);
|
|
798
|
+
|
|
799
|
+
// 检查是否为多行字符串定义: key = |
|
|
800
|
+
const multiMatch = line.match(/^([\w\u4e00-\u9fff]+)\s*=\s*\|$/);
|
|
801
|
+
if (multiMatch) {
|
|
802
|
+
const key = multiMatch[1];
|
|
803
|
+
i++;
|
|
804
|
+
const valueLines = [];
|
|
805
|
+
while (i < cls.length && cls[i].indent > cl.indent) {
|
|
806
|
+
valueLines.push(cls[i].text);
|
|
807
|
+
i++;
|
|
808
|
+
}
|
|
809
|
+
const value = valueLines.join('\n');
|
|
810
|
+
// 与编译器一致:任意 key 都收(不限于 system_safety/output_style)
|
|
811
|
+
meta[key] = value;
|
|
812
|
+
continue;
|
|
813
|
+
}
|
|
814
|
+
|
|
815
|
+
// 普通单行键值对
|
|
816
|
+
const m = line.match(/^([\w\u4e00-\u9fff]+)\s*=\s*(.+)$/);
|
|
817
|
+
if (!m)
|
|
818
|
+
rep.fail(
|
|
819
|
+
`meta 字段格式错误: "${cl.text}"。期望: key = value 或 key = |`,
|
|
820
|
+
{ line: cl.lineNum + 1, lineText: cl.raw || cl.text, where: 'meta:' }
|
|
821
|
+
);
|
|
822
|
+
const [, key, val] = m;
|
|
823
|
+
let v = val.trim();
|
|
824
|
+
|
|
825
|
+
// ═══ 新增:去除首尾配对引号 & 尝试转为数字 ═══
|
|
826
|
+
if ((v.startsWith('"') && v.endsWith('"')) || (v.startsWith("'") && v.endsWith("'"))) {
|
|
827
|
+
v = v.slice(1, -1);
|
|
828
|
+
}
|
|
829
|
+
|
|
830
|
+
// 规范化常用字段,其他字段直接以原始键名存储
|
|
831
|
+
switch (key) {
|
|
832
|
+
case 'id':
|
|
833
|
+
meta.id = v;
|
|
834
|
+
break;
|
|
835
|
+
case 'name':
|
|
836
|
+
meta.name = v;
|
|
837
|
+
break;
|
|
838
|
+
case 'version':
|
|
839
|
+
meta.version = v;
|
|
840
|
+
break;
|
|
841
|
+
case 'owner':
|
|
842
|
+
meta.owner = String(v).replace(/^\[|\]$/g, '');
|
|
843
|
+
break;
|
|
844
|
+
case 'database':
|
|
845
|
+
meta.database = v;
|
|
846
|
+
break;
|
|
847
|
+
case 'session':
|
|
848
|
+
meta.session = v;
|
|
849
|
+
break;
|
|
850
|
+
case 'system_safety':
|
|
851
|
+
meta.system_safety = typeof v === 'string' ? v.replace(/^"|"$/g, '') : v;
|
|
852
|
+
break;
|
|
853
|
+
case 'output_style':
|
|
854
|
+
meta.output_style = typeof v === 'string' ? v.replace(/^"|"$/g, '') : v;
|
|
855
|
+
break;
|
|
856
|
+
case 'max_steps':
|
|
857
|
+
meta.max_steps = Number(v);
|
|
858
|
+
break;
|
|
859
|
+
case 'delay':
|
|
860
|
+
meta.delay = Number(v);
|
|
861
|
+
break;
|
|
862
|
+
default:
|
|
863
|
+
// 与编译器一致:未知字段保留原始键名,不报错
|
|
864
|
+
meta[key] = v;
|
|
865
|
+
break;
|
|
866
|
+
}
|
|
867
|
+
i++;
|
|
868
|
+
}
|
|
869
|
+
|
|
870
|
+
// ⚡ 删除所有默认值设置,直接返回解析到的字段
|
|
871
|
+
return meta;
|
|
872
|
+
}
|
|
873
|
+
|
|
874
|
+
function parseLayoutBlock(cls) {
|
|
875
|
+
const layout = {};
|
|
876
|
+
for (const cl of cls) {
|
|
877
|
+
const line = normalizeSymbols(cl.text);
|
|
878
|
+
const m = line.match(/^(\[.+?\])\s*=\s*(-?\d+(?:\.\d+)?)\s*,\s*(-?\d+(?:\.\d+)?)$/);
|
|
879
|
+
if (m) {
|
|
880
|
+
layout[m[1]] = { dx: Math.round(parseFloat(m[2])), dy: Math.round(parseFloat(m[3])) };
|
|
881
|
+
}
|
|
882
|
+
}
|
|
883
|
+
return layout;
|
|
884
|
+
}
|
|
885
|
+
|
|
886
|
+
function parseVarsBlock(cls, rep = null) {
|
|
887
|
+
rep = rep || createReporter();
|
|
888
|
+
const vars = [];
|
|
889
|
+
let i = 0;
|
|
890
|
+
while (i < cls.length) {
|
|
891
|
+
const cl = cls[i];
|
|
892
|
+
const _t = cl.text.trim();
|
|
893
|
+
if (!_t || _t.startsWith('#')) { i++; continue; } // 跳过空行与注释
|
|
894
|
+
const line = normalizeSymbols(cl.text);
|
|
895
|
+
|
|
896
|
+
// 多行值:key = |(与编译器 _eval_kv_block 一致)
|
|
897
|
+
const multiMatch = line.match(/^((?:@|\$@|\$)?[\w\u4e00-\u9fff]+)\s*=\s*\|$/);
|
|
898
|
+
if (multiMatch) {
|
|
899
|
+
const key = multiMatch[1];
|
|
900
|
+
i++;
|
|
901
|
+
const valueLines = [];
|
|
902
|
+
while (i < cls.length && cls[i].indent > cl.indent) {
|
|
903
|
+
valueLines.push(cls[i].text);
|
|
904
|
+
i++;
|
|
905
|
+
}
|
|
906
|
+
vars.push({ name: key, defaultValue: valueLines.join('\n') });
|
|
907
|
+
continue;
|
|
908
|
+
}
|
|
909
|
+
|
|
910
|
+
const m = line.match(/^((?:@|\$@|\$)?[\w\u4e00-\u9fff]+)\s*=\s*(.*)$/);
|
|
911
|
+
if (!m)
|
|
912
|
+
rep.fail(
|
|
913
|
+
`vars 字段格式错误: "${cl.text}"。期望: varname = "value"`,
|
|
914
|
+
{ line: cl.lineNum + 1, lineText: cl.raw || cl.text, where: 'vars:' }
|
|
915
|
+
);
|
|
916
|
+
vars.push({ name: m[1], defaultValue: m[2].trim() });
|
|
917
|
+
i++;
|
|
918
|
+
}
|
|
919
|
+
return vars;
|
|
920
|
+
}
|
|
921
|
+
|
|
922
|
+
function parseCodeBlock(cls, rep = null) {
|
|
923
|
+
rep = rep || createReporter();
|
|
924
|
+
const code = [];
|
|
925
|
+
for (const cl of cls) {
|
|
926
|
+
const _t = cl.text.trim();
|
|
927
|
+
if (!_t || _t.startsWith('#')) continue; // 跳过空行与注释
|
|
928
|
+
const line = normalizeSymbols(cl.text);
|
|
929
|
+
const m = line.match(/^(@?[\w\u4e00-\u9fff]+)\s*=\s*(.*)$/);
|
|
930
|
+
if (!m)
|
|
931
|
+
rep.fail(
|
|
932
|
+
`code 字段格式错误: "${cl.text}"。期望: name = value`,
|
|
933
|
+
{ line: cl.lineNum + 1, lineText: cl.raw || cl.text, where: 'code:' }
|
|
934
|
+
);
|
|
935
|
+
let val = m[2].trim();
|
|
936
|
+
// 如果格式为 file:"xxx",只取内部路径
|
|
937
|
+
const fm = val.match(/^file:"(.*)"$/);
|
|
938
|
+
if (fm) val = fm[1];
|
|
939
|
+
code.push({ name: m[1], value: val });
|
|
940
|
+
}
|
|
941
|
+
return code;
|
|
942
|
+
}
|
|
943
|
+
|
|
944
|
+
function parseActorsBlock(cls, rep = null) {
|
|
945
|
+
rep = rep || createReporter();
|
|
946
|
+
const actors = [];
|
|
947
|
+
let i = 0;
|
|
948
|
+
while (i < cls.length) {
|
|
949
|
+
const cl = cls[i];
|
|
950
|
+
const _t = cl.text.trim();
|
|
951
|
+
if (!_t || _t.startsWith('#')) { i++; continue; } // 跳过空行与注释
|
|
952
|
+
const line = normalizeSymbols(cl.text);
|
|
953
|
+
|
|
954
|
+
// blueprint 块(与编译器一致):blueprint name: + 缩进属性 source/tools
|
|
955
|
+
const bpMatch = line.match(/^blueprint\s+(@?[\w\u4e00-\u9fff]+)\s*:\s*$/);
|
|
956
|
+
if (bpMatch) {
|
|
957
|
+
const bpName = bpMatch[1];
|
|
958
|
+
let source = null;
|
|
959
|
+
let tools = null;
|
|
960
|
+
let thinking = null;
|
|
961
|
+
i++;
|
|
962
|
+
while (i < cls.length && cls[i].indent > cl.indent) {
|
|
963
|
+
const al = normalizeSymbols(cls[i].text).trim();
|
|
964
|
+
if (al.startsWith('source:')) {
|
|
965
|
+
source = al.slice(7).trim();
|
|
966
|
+
} else if (al.startsWith('thinking')) {
|
|
967
|
+
const thStr = al.replace(/^thinking\s*[:=]\s*/, '').trim().toLowerCase();
|
|
968
|
+
// `default` 显式值 ≡ 未声明(归一化为空串,与不传字段完全等效)
|
|
969
|
+
if (thStr !== 'default' && !THINKING_LEVELS.includes(thStr)) {
|
|
970
|
+
rep.fail(
|
|
971
|
+
`thinking 档位不合法: "${thStr}"(允许: default/${THINKING_LEVELS.join('/')})`,
|
|
972
|
+
{ line: cls[i].lineNum + 1, lineText: cls[i].raw || cls[i].text, where: `blueprint ${bpName}` }
|
|
973
|
+
);
|
|
974
|
+
}
|
|
975
|
+
thinking = thStr === 'default' ? '' : thStr;
|
|
976
|
+
} else if (al.startsWith('tools')) {
|
|
977
|
+
const toolsStr = al.replace(/^tools\s*[:=]\s*/, '').trim();
|
|
978
|
+
if (toolsStr.startsWith('[') && toolsStr.endsWith(']')) {
|
|
979
|
+
tools = toolsStr.slice(1, -1).split(',').map(s => s.trim()).filter(Boolean);
|
|
980
|
+
// 显式空列表 [] ≡ 明确禁用(与 Python 编译器语义对齐)
|
|
981
|
+
if (!tools.length) tools = false;
|
|
982
|
+
} else if (toolsStr === 'true' || toolsStr === 'false') {
|
|
983
|
+
tools = toolsStr === 'true';
|
|
984
|
+
} else {
|
|
985
|
+
rep.fail(
|
|
986
|
+
`tools 格式错误,应为 tools = [tool1, tool2] 或 tools: true/false`,
|
|
987
|
+
{ line: cls[i].lineNum + 1, lineText: cls[i].raw || cls[i].text, where: `blueprint ${bpName}` }
|
|
988
|
+
);
|
|
989
|
+
}
|
|
990
|
+
}
|
|
991
|
+
i++;
|
|
992
|
+
}
|
|
993
|
+
actors.push({ type: 'blueprint', name: bpName, soul: '', source: source ?? '', tools: tools, thinking: thinking ?? '' });
|
|
994
|
+
continue;
|
|
995
|
+
}
|
|
996
|
+
|
|
997
|
+
const prefixMatch = line.match(
|
|
998
|
+
/^(ai|human)\s+(@?[\w\u4e00-\u9fff]+)\s*=\s*(.*)$/
|
|
999
|
+
);
|
|
1000
|
+
// 裸 actor:`ai|human @名`(无 `=`、无属性)→ soul/source 缺省。
|
|
1001
|
+
// 与 Python 编译器 FEMO_parser.py eval_actors 的裸 actor 分支对齐(soul 非必须,
|
|
1002
|
+
// 无 soul 角色 = 无角色设定的裸执行者)。
|
|
1003
|
+
const bareMatch = !prefixMatch ? line.match(/^(ai|human)\s+(@?[\w\u4e00-\u9fff]+)\s*$/) : null;
|
|
1004
|
+
if (bareMatch) {
|
|
1005
|
+
actors.push({ type: bareMatch[1], name: bareMatch[2], soul: '', source: '', tools: [] });
|
|
1006
|
+
i++;
|
|
1007
|
+
continue;
|
|
1008
|
+
}
|
|
1009
|
+
if (!prefixMatch)
|
|
1010
|
+
rep.fail(
|
|
1011
|
+
`actors 格式错误: "${cl.text}"。期望: ai|human @name = soul:X, source:Y, tools:[...],或裸写法 ai|human @name`,
|
|
1012
|
+
{ line: cl.lineNum + 1, lineText: cl.raw || cl.text, where: 'actors:' }
|
|
1013
|
+
);
|
|
1014
|
+
const type = prefixMatch[1];
|
|
1015
|
+
const name = prefixMatch[2];
|
|
1016
|
+
const rest = prefixMatch[3];
|
|
1017
|
+
|
|
1018
|
+
// 初始化字段(全部 null 表示未设置,最终再给默认值)
|
|
1019
|
+
let soul = null;
|
|
1020
|
+
let source = null;
|
|
1021
|
+
let tools = null;
|
|
1022
|
+
let thinking = null;
|
|
1023
|
+
|
|
1024
|
+
// 分割属性部分:逗号或空格分隔均可,但 tools 中有逗号,所以用逗号分割再处理
|
|
1025
|
+
const parts = rest.split(',').map(p => p.trim()).filter(Boolean);
|
|
1026
|
+
for (let pi = 0; pi < parts.length; pi++) {
|
|
1027
|
+
const part = parts[pi];
|
|
1028
|
+
if (part.startsWith('soul:')) {
|
|
1029
|
+
const val = part.slice(5).trim();
|
|
1030
|
+
if (!val) rep.fail(`soul 字段缺少值,例如 soul:1`, { line: cl.lineNum + 1, lineText: cl.raw || cl.text, where: 'actors:' });
|
|
1031
|
+
soul = val;
|
|
1032
|
+
} else if (part.startsWith('source:')) {
|
|
1033
|
+
const val = part.slice(7).trim();
|
|
1034
|
+
if (!val) rep.fail(`source 字段缺少值,例如 source:01A`, { line: cl.lineNum + 1, lineText: cl.raw || cl.text, where: 'actors:' });
|
|
1035
|
+
source = val;
|
|
1036
|
+
} else if (part.startsWith('thinking')) {
|
|
1037
|
+
// thinking: <档位>(off/minimal/low/medium/high/xhigh/max,编译期词汇校验);
|
|
1038
|
+
// `default` 显式值 ≡ 未声明(归一化为空串,与不传字段完全等效)
|
|
1039
|
+
const thStr = part.replace(/^thinking\s*[:=]\s*/, '').trim().toLowerCase();
|
|
1040
|
+
if (thStr !== 'default' && !THINKING_LEVELS.includes(thStr)) {
|
|
1041
|
+
rep.fail(
|
|
1042
|
+
`thinking 档位不合法: "${thStr}"(允许: default/${THINKING_LEVELS.join('/')})`,
|
|
1043
|
+
{ line: cl.lineNum + 1, lineText: cl.raw || cl.text, where: `actor ${name}` }
|
|
1044
|
+
);
|
|
1045
|
+
}
|
|
1046
|
+
thinking = thStr === 'default' ? '' : thStr;
|
|
1047
|
+
} else if (part.startsWith('tools')) {
|
|
1048
|
+
// 允许 tools = [...] / tools:[...] / tools: true|false(布尔=全部/禁用)
|
|
1049
|
+
let toolsStr = part.replace(/^tools\s*[:=]\s*/, '').trim();
|
|
1050
|
+
// 列表内部含逗号会被上面的 split 切碎成多段:仅列表([ 开头)才拼接
|
|
1051
|
+
// 到方括号闭合——布尔值绝不拼接,否则 tools: false 后面的属性(如
|
|
1052
|
+
// thinking: default)会被吞进 tools 造成「tools 格式错误」假警报
|
|
1053
|
+
// (2026-08-30 实证:与 thinking 标签共存时必炸)。
|
|
1054
|
+
if (toolsStr.startsWith('[')) {
|
|
1055
|
+
while (!toolsStr.endsWith(']') && pi + 1 < parts.length) {
|
|
1056
|
+
pi += 1;
|
|
1057
|
+
toolsStr += ',' + parts[pi];
|
|
1058
|
+
}
|
|
1059
|
+
}
|
|
1060
|
+
if (toolsStr.startsWith('[') && toolsStr.endsWith(']')) {
|
|
1061
|
+
toolsStr = toolsStr.slice(1, -1);
|
|
1062
|
+
tools = toolsStr.split(',').map(s => s.trim()).filter(Boolean);
|
|
1063
|
+
// 显式空白名单 [] ≡ 明确禁用(与 Python 编译器 2026-09-12 语义对齐;
|
|
1064
|
+
// 「不写 tools」= null = 宿主默认全开,两者严格区分)
|
|
1065
|
+
if (!tools.length) tools = false;
|
|
1066
|
+
} else if (toolsStr === 'true' || toolsStr === 'false') {
|
|
1067
|
+
tools = toolsStr === 'true';
|
|
1068
|
+
} else {
|
|
1069
|
+
rep.fail(
|
|
1070
|
+
`tools 格式错误,应为 tools = [tool1, tool2] 或 tools: true/false`,
|
|
1071
|
+
{ line: cl.lineNum + 1, lineText: cl.raw || cl.text, where: `actor ${name}` }
|
|
1072
|
+
);
|
|
1073
|
+
}
|
|
1074
|
+
} else {
|
|
1075
|
+
// 其他字段直接报错
|
|
1076
|
+
rep.fail(
|
|
1077
|
+
`不支持的字段 "${part}"。合法字段: soul, source, thinking, tools`,
|
|
1078
|
+
{ line: cl.lineNum + 1, lineText: cl.raw || cl.text, where: 'actors:' }
|
|
1079
|
+
);
|
|
1080
|
+
}
|
|
1081
|
+
}
|
|
1082
|
+
|
|
1083
|
+
// 最后赋予默认值(不兜底修改原值)。soul 缺省 = 空串(裸 actor 语义:
|
|
1084
|
+
// soul 非必须,序列化时对空 soul 保持沉默,绝不伪造数字 soul)。
|
|
1085
|
+
if (soul === null) soul = '';
|
|
1086
|
+
if (source === null) source = '';
|
|
1087
|
+
// tools 缺省保持 null(未声明 = 宿主默认全开)——禁止归一成 []:
|
|
1088
|
+
// [] 是「显式空白名单 ≡ 明确禁用」,与「未声明」是两种语义,混了会把
|
|
1089
|
+
// 没写 tools 的 actor 在保存时写上 tools: false(禁用)(2026-09-12 修正)。
|
|
1090
|
+
if (thinking === null) thinking = '';
|
|
1091
|
+
|
|
1092
|
+
actors.push({ type, name, soul, source, tools, thinking });
|
|
1093
|
+
i++;
|
|
1094
|
+
}
|
|
1095
|
+
return actors;
|
|
1096
|
+
}
|
|
1097
|
+
|
|
1098
|
+
function parseMemoryOrContextBlock(header, cls, blockType, rep = null, headerLineNum = null) {
|
|
1099
|
+
rep = rep || createReporter();
|
|
1100
|
+
// 解析 memory name(fileRef): 或 context name(fileRef):
|
|
1101
|
+
const hm = header.match(
|
|
1102
|
+
new RegExp(`^${blockType}\\s+([\\w\\u4e00-\\u9fff]+)\\((.+?)\\):$`)
|
|
1103
|
+
);
|
|
1104
|
+
if (!hm)
|
|
1105
|
+
rep.fail(
|
|
1106
|
+
`${blockType} 声明格式错误: "${header}"。期望: ${blockType} name(fileRef):`,
|
|
1107
|
+
{ line: (headerLineNum ?? -1) + 1, lineText: header, where: `${blockType} 区` }
|
|
1108
|
+
);
|
|
1109
|
+
const block = {
|
|
1110
|
+
name: hm[1],
|
|
1111
|
+
fileRef: hm[2],
|
|
1112
|
+
in: '',
|
|
1113
|
+
out: '',
|
|
1114
|
+
};
|
|
1115
|
+
for (const cl of cls) {
|
|
1116
|
+
const _t = cl.text.trim();
|
|
1117
|
+
if (!_t || _t.startsWith('#')) continue; // 跳过空行与注释
|
|
1118
|
+
const line = normalizeSymbols(cl.text);
|
|
1119
|
+
if (line.startsWith('in:')) {
|
|
1120
|
+
const after = line.slice(3).trim();
|
|
1121
|
+
block.in =
|
|
1122
|
+
after ||
|
|
1123
|
+
cls
|
|
1124
|
+
.filter((l) => l.indent > cl.indent)
|
|
1125
|
+
.map((l) => normalizeSymbols(l.text))
|
|
1126
|
+
.join('\n');
|
|
1127
|
+
} else if (line.startsWith('out:')) {
|
|
1128
|
+
const after = line.slice(4).trim();
|
|
1129
|
+
block.out =
|
|
1130
|
+
after ||
|
|
1131
|
+
cls
|
|
1132
|
+
.filter((l) => l.indent > cl.indent)
|
|
1133
|
+
.map((l) => normalizeSymbols(l.text))
|
|
1134
|
+
.join(', ');
|
|
1135
|
+
}
|
|
1136
|
+
}
|
|
1137
|
+
return block;
|
|
1138
|
+
}
|
|
1139
|
+
|
|
1140
|
+
function parseActionBlock(header, cls, rep = null, headerLineNum = null) {
|
|
1141
|
+
rep = rep || createReporter();
|
|
1142
|
+
// 先标准化 header
|
|
1143
|
+
const normalizedHeader = normalizeSymbols(header);
|
|
1144
|
+
const hm = normalizedHeader.match(
|
|
1145
|
+
/^action\s+([\w\u4e00-\u9fff]+)\s+(@[\w\u4e00-\u9fff]+)(?:\((@?[\w\u4e00-\u9fff.]+)\))?(?:\s+as\s*\((@?[\w\u4e00-\u9fff.]+)\))?\s*:\s*$/
|
|
1146
|
+
);
|
|
1147
|
+
if (!hm)
|
|
1148
|
+
rep.fail(
|
|
1149
|
+
`Action 声明格式错误: "${header}"。期望: action name @type(@actor):`,
|
|
1150
|
+
{ line: (headerLineNum ?? -1) + 1, lineText: header, where: 'action 区' }
|
|
1151
|
+
);
|
|
1152
|
+
const action = {
|
|
1153
|
+
name: hm[1],
|
|
1154
|
+
executorType: hm[2].replace('@', ''),
|
|
1155
|
+
executorActor: hm[3] || '',
|
|
1156
|
+
asActor: hm[4] || '',
|
|
1157
|
+
prompt: '',
|
|
1158
|
+
resolve: '',
|
|
1159
|
+
scope: '',
|
|
1160
|
+
outVars: '',
|
|
1161
|
+
inMappings: '',
|
|
1162
|
+
memory: '',
|
|
1163
|
+
context: '',
|
|
1164
|
+
max_retries: 0,
|
|
1165
|
+
fallback: '',
|
|
1166
|
+
interrupt: '',
|
|
1167
|
+
};
|
|
1168
|
+
|
|
1169
|
+
let i = 0;
|
|
1170
|
+
while (i < cls.length) {
|
|
1171
|
+
const cl = cls[i];
|
|
1172
|
+
|
|
1173
|
+
// ★ 非 prompt 上下文:跳过空白行
|
|
1174
|
+
const isPromptContext =
|
|
1175
|
+
cl.text.startsWith('prompt:') ||
|
|
1176
|
+
cl.text.startsWith('showprompt:') ||
|
|
1177
|
+
(i > 0 &&
|
|
1178
|
+
(cls[i - 1].text === 'prompt: |' || cls[i - 1].text === 'showprompt: |') &&
|
|
1179
|
+
cl.indent > cls[i - 1].indent);
|
|
1180
|
+
|
|
1181
|
+
if (!isPromptContext && (!cl.text.trim() || cl.text.trim().startsWith('#'))) {
|
|
1182
|
+
i++;
|
|
1183
|
+
continue;
|
|
1184
|
+
}
|
|
1185
|
+
|
|
1186
|
+
const line = isPromptContext ? cl.text : normalizeSymbols(cl.text);
|
|
1187
|
+
if (line === 'prompt: |') {
|
|
1188
|
+
i++;
|
|
1189
|
+
const pl = [];
|
|
1190
|
+
while (i < cls.length && cls[i].indent > cl.indent) {
|
|
1191
|
+
pl.push(cls[i].text);
|
|
1192
|
+
i++;
|
|
1193
|
+
}
|
|
1194
|
+
action.prompt = pl.join('\n');
|
|
1195
|
+
continue;
|
|
1196
|
+
}
|
|
1197
|
+
if (line.startsWith('prompt:') && !line.endsWith('|')) {
|
|
1198
|
+
const after = line.slice(7).trim();
|
|
1199
|
+
action.prompt = after;
|
|
1200
|
+
i++;
|
|
1201
|
+
continue;
|
|
1202
|
+
}
|
|
1203
|
+
if (line === 'showprompt: |') {
|
|
1204
|
+
i++;
|
|
1205
|
+
const spl = [];
|
|
1206
|
+
while (i < cls.length && cls[i].indent > cl.indent) {
|
|
1207
|
+
spl.push(cls[i].text);
|
|
1208
|
+
i++;
|
|
1209
|
+
}
|
|
1210
|
+
action.showprompt = spl.join('\n');
|
|
1211
|
+
continue;
|
|
1212
|
+
}
|
|
1213
|
+
if (line.startsWith('showprompt:')) {
|
|
1214
|
+
const after = line.slice(11).trim();
|
|
1215
|
+
action.showprompt = after;
|
|
1216
|
+
i++;
|
|
1217
|
+
continue;
|
|
1218
|
+
}
|
|
1219
|
+
if (line.startsWith('in:')) {
|
|
1220
|
+
const after = line.slice(3).trim();
|
|
1221
|
+
if (after) {
|
|
1222
|
+
action.inMappings = after;
|
|
1223
|
+
i++; // 单行模式必须推进索引,否则死循环
|
|
1224
|
+
} else {
|
|
1225
|
+
i++;
|
|
1226
|
+
const il = [];
|
|
1227
|
+
let guard = 0;
|
|
1228
|
+
while (i < cls.length && cls[i].indent > cl.indent) {
|
|
1229
|
+
if (++guard > 500)
|
|
1230
|
+
rep.fail(`in 字段解析陷入死循环`, { line: cl.lineNum + 1, lineText: cl.raw || cl.text, where: `action ${action.name}` });
|
|
1231
|
+
il.push(normalizeSymbols(cls[i].text));
|
|
1232
|
+
i++;
|
|
1233
|
+
}
|
|
1234
|
+
action.inMappings = il.join('\n');
|
|
1235
|
+
}
|
|
1236
|
+
continue;
|
|
1237
|
+
}
|
|
1238
|
+
if (line.startsWith('out:')) {
|
|
1239
|
+
const after = line.slice(4).trim();
|
|
1240
|
+
if (after) {
|
|
1241
|
+
action.outVars = after;
|
|
1242
|
+
i++; // 单行模式必须推进索引
|
|
1243
|
+
// 单行 out 后的缩进续行也并入(out: x += 1 后接缩进的 y = {})
|
|
1244
|
+
const ol = [];
|
|
1245
|
+
while (i < cls.length && cls[i].indent > cl.indent) {
|
|
1246
|
+
const t2 = normalizeSymbols(cls[i].text).trim();
|
|
1247
|
+
if (t2 && !t2.startsWith('#')) ol.push(t2);
|
|
1248
|
+
i++;
|
|
1249
|
+
}
|
|
1250
|
+
if (ol.length > 0) action.outVars = after + '\n' + ol.join('\n');
|
|
1251
|
+
} else {
|
|
1252
|
+
i++;
|
|
1253
|
+
const ol = [];
|
|
1254
|
+
while (i < cls.length && cls[i].indent > cl.indent) {
|
|
1255
|
+
ol.push(normalizeSymbols(cls[i].text));
|
|
1256
|
+
i++;
|
|
1257
|
+
}
|
|
1258
|
+
action.outVars = ol.join('\n');
|
|
1259
|
+
}
|
|
1260
|
+
continue;
|
|
1261
|
+
}
|
|
1262
|
+
if (line.startsWith('scope:')) {
|
|
1263
|
+
action.scope = line.slice(6).trim();
|
|
1264
|
+
i++;
|
|
1265
|
+
continue;
|
|
1266
|
+
}
|
|
1267
|
+
if (line.startsWith('memory:')) {
|
|
1268
|
+
action.memory = line.slice(7).trim();
|
|
1269
|
+
i++;
|
|
1270
|
+
continue;
|
|
1271
|
+
}
|
|
1272
|
+
if (line.startsWith('context:')) {
|
|
1273
|
+
action.context = line.slice(8).trim();
|
|
1274
|
+
i++;
|
|
1275
|
+
continue;
|
|
1276
|
+
}
|
|
1277
|
+
if (line.startsWith('resolve:')) {
|
|
1278
|
+
action.resolve = line.slice(8).trim();
|
|
1279
|
+
i++;
|
|
1280
|
+
continue;
|
|
1281
|
+
}
|
|
1282
|
+
if (line.startsWith('max_retries:')) {
|
|
1283
|
+
action.max_retries = Number(line.slice(12).trim());
|
|
1284
|
+
i++;
|
|
1285
|
+
continue;
|
|
1286
|
+
}
|
|
1287
|
+
if (line.startsWith('fallback:')) {
|
|
1288
|
+
action.fallback = line.slice(9).trim();
|
|
1289
|
+
i++;
|
|
1290
|
+
continue;
|
|
1291
|
+
}
|
|
1292
|
+
if (line.startsWith('interrupt:')) {
|
|
1293
|
+
action.interrupt = line.slice(10).trim();
|
|
1294
|
+
i++;
|
|
1295
|
+
continue;
|
|
1296
|
+
}
|
|
1297
|
+
rep.fail(
|
|
1298
|
+
`未识别的 action 子字段: "${cl.text}"。合法: prompt:, in:, out:, scope:, memory:, context:, resolve:, max_retries:, fallback:, interrupt:`,
|
|
1299
|
+
{ line: cl.lineNum + 1, lineText: cl.raw || cl.text, where: `action ${action.name}` }
|
|
1300
|
+
);
|
|
1301
|
+
}
|
|
1302
|
+
return action;
|
|
1303
|
+
}
|
|
1304
|
+
|
|
1305
|
+
function parseModuleBlock(header, cls, rep = null, headerLineNum = null) {
|
|
1306
|
+
rep = rep || createReporter();
|
|
1307
|
+
const hm = header.match(/^module\s+([\w\u4e00-\u9fff]+)(?:\s*\(([^)]*)\))?\s*:?\s*$/);
|
|
1308
|
+
if (!hm)
|
|
1309
|
+
rep.fail(
|
|
1310
|
+
`Module 声明格式错误: "${header}"。期望: module Name:`,
|
|
1311
|
+
{ line: (headerLineNum ?? -1) + 1, lineText: header, where: 'module 区' }
|
|
1312
|
+
);
|
|
1313
|
+
const mod = {
|
|
1314
|
+
name: hm[1],
|
|
1315
|
+
params: hm[2] ? hm[2].split(',').map((s) => s.trim()).filter(Boolean) : [],
|
|
1316
|
+
meta: {},
|
|
1317
|
+
code: [],
|
|
1318
|
+
vars: [],
|
|
1319
|
+
actions: [],
|
|
1320
|
+
nodeDecls: [],
|
|
1321
|
+
edges: [],
|
|
1322
|
+
};
|
|
1323
|
+
|
|
1324
|
+
// 子块按最小缩进切分(兼容 2 空格 / 4 空格等任意统一缩进)
|
|
1325
|
+
const subBlocks = [];
|
|
1326
|
+
let cur = null;
|
|
1327
|
+
const nonEmpty = cls.filter((cl) => cl.text.trim());
|
|
1328
|
+
const baseIndent = nonEmpty.length > 0
|
|
1329
|
+
? Math.min(...nonEmpty.map((cl) => cl.indent))
|
|
1330
|
+
: 0;
|
|
1331
|
+
for (const cl of cls) {
|
|
1332
|
+
// 跳过空行,防止生成空 header 的子块
|
|
1333
|
+
if (!cl.text.trim()) continue;
|
|
1334
|
+
|
|
1335
|
+
if (cl.indent === baseIndent) {
|
|
1336
|
+
if (cur) subBlocks.push(cur);
|
|
1337
|
+
const headerText = cl.text.trim();
|
|
1338
|
+
if (headerText.startsWith('//') || headerText.startsWith('#')) {
|
|
1339
|
+
cur = null;
|
|
1340
|
+
} else {
|
|
1341
|
+
cur = { header: cl.text, headerLineNum: cl.lineNum, contentLines: [] };
|
|
1342
|
+
}
|
|
1343
|
+
} else if (cur && cl.indent > baseIndent) {
|
|
1344
|
+
cur.contentLines.push({ ...cl, indent: cl.indent - baseIndent });
|
|
1345
|
+
}
|
|
1346
|
+
}
|
|
1347
|
+
if (cur) subBlocks.push(cur);
|
|
1348
|
+
|
|
1349
|
+
for (const sb of subBlocks) {
|
|
1350
|
+
const hdr = normalizeSymbols(sb.header);
|
|
1351
|
+
if (hdr === 'vars:') {
|
|
1352
|
+
mod.vars = parseVarsBlock(sb.contentLines, rep);
|
|
1353
|
+
} else if (hdr === 'meta:') {
|
|
1354
|
+
mod.meta = parseMetaBlock(sb.contentLines, rep);
|
|
1355
|
+
} else if (hdr === 'code:') {
|
|
1356
|
+
mod.code = parseCodeBlock(sb.contentLines, rep);
|
|
1357
|
+
} else if (hdr.startsWith('action ')) {
|
|
1358
|
+
mod.actions.push(
|
|
1359
|
+
parseActionBlock(normalizeSymbols(sb.header), sb.contentLines, rep, sb.headerLineNum)
|
|
1360
|
+
);
|
|
1361
|
+
} else if (hdr === 'flow:') {
|
|
1362
|
+
const { nodeDecls, edges } = parseFlowSection(sb.contentLines, [], rep);
|
|
1363
|
+
mod.nodeDecls = nodeDecls;
|
|
1364
|
+
mod.edges = edges;
|
|
1365
|
+
} else if (hdr === 'sketch:') {
|
|
1366
|
+
mod.layout = parseLayoutBlock(sb.contentLines);
|
|
1367
|
+
} else if (hdr.startsWith('module ')) {
|
|
1368
|
+
// 递归解析嵌套子模块
|
|
1369
|
+
const subMod = parseModuleBlock(hdr, sb.contentLines, rep, sb.headerLineNum);
|
|
1370
|
+
if (!mod.subModules) mod.subModules = [];
|
|
1371
|
+
mod.subModules.push(subMod);
|
|
1372
|
+
} else {
|
|
1373
|
+
rep.fail(
|
|
1374
|
+
`Module 内未识别的子块: "${sb.header}"。合法: vars:, meta:, code:, action ..., module ..., flow:`,
|
|
1375
|
+
{ line: (sb.headerLineNum ?? -1) + 1, lineText: sb.header, where: `module ${mod.name}` }
|
|
1376
|
+
);
|
|
1377
|
+
}
|
|
1378
|
+
}
|
|
1379
|
+
return mod;
|
|
1380
|
+
}
|
|
1381
|
+
|
|
1382
|
+
function parseMainflowBlock(cls, rep = null) {
|
|
1383
|
+
rep = rep || createReporter();
|
|
1384
|
+
// 计算最小缩进(跳过空行和注释)
|
|
1385
|
+
const nonCommentLines = cls.filter(l => {
|
|
1386
|
+
const t = normalizeSymbols(l.text).trim();
|
|
1387
|
+
return t && !t.startsWith('//') && !t.startsWith('#');
|
|
1388
|
+
});
|
|
1389
|
+
if (nonCommentLines.length === 0) {
|
|
1390
|
+
return { nodeDecls: [], edges: [], layout: {} };
|
|
1391
|
+
}
|
|
1392
|
+
const baseIndent = Math.min(...nonCommentLines.map(l => l.indent));
|
|
1393
|
+
|
|
1394
|
+
// 按 baseIndent 分组(mainflow 内部子块)
|
|
1395
|
+
const groups = [];
|
|
1396
|
+
let currentGroup = null;
|
|
1397
|
+
for (const cl of cls) {
|
|
1398
|
+
if (cl.indent === baseIndent) {
|
|
1399
|
+
if (currentGroup) groups.push(currentGroup);
|
|
1400
|
+
currentGroup = { header: cl, lines: [] };
|
|
1401
|
+
} else if (currentGroup && cl.indent > baseIndent) {
|
|
1402
|
+
currentGroup.lines.push(cl);
|
|
1403
|
+
}
|
|
1404
|
+
// 缩进小于 baseIndent 的异常行忽略
|
|
1405
|
+
}
|
|
1406
|
+
if (currentGroup) groups.push(currentGroup);
|
|
1407
|
+
|
|
1408
|
+
let flowLines = [];
|
|
1409
|
+
let layout = {};
|
|
1410
|
+
|
|
1411
|
+
for (const group of groups) {
|
|
1412
|
+
const headerText = normalizeSymbols(group.header.text);
|
|
1413
|
+
if (headerText === 'sketch:') {
|
|
1414
|
+
// 收集 sketch 块内的坐标行
|
|
1415
|
+
layout = parseLayoutBlock(group.lines);
|
|
1416
|
+
} else {
|
|
1417
|
+
// 其他行(节点声明、连线)原样放入 flowLines
|
|
1418
|
+
flowLines.push(group.header);
|
|
1419
|
+
flowLines.push(...group.lines);
|
|
1420
|
+
}
|
|
1421
|
+
}
|
|
1422
|
+
|
|
1423
|
+
// 如果没有分组(所有行缩进相同),则直接作为 flow 行
|
|
1424
|
+
if (groups.length === 0) {
|
|
1425
|
+
flowLines = cls;
|
|
1426
|
+
}
|
|
1427
|
+
|
|
1428
|
+
const result = parseFlowSection(flowLines, [], rep);
|
|
1429
|
+
result.layout = layout;
|
|
1430
|
+
return result;
|
|
1431
|
+
}
|
|
1432
|
+
|
|
1433
|
+
function parseFlowSection(flowLines, existingLabels, rep = null) {
|
|
1434
|
+
rep = rep || createReporter();
|
|
1435
|
+
console.log('parseFlowSection 被调用,flowLines:');
|
|
1436
|
+
|
|
1437
|
+
const nodeDecls = [];
|
|
1438
|
+
const edges = [];
|
|
1439
|
+
let currentNode = null;
|
|
1440
|
+
const usedLabels = new Set(existingLabels || []);
|
|
1441
|
+
|
|
1442
|
+
const addEdge = (edge) => {
|
|
1443
|
+
const newCond = (edge.cond || '').trim();
|
|
1444
|
+
console.log(`[DEBUG] addEdge: src="${edge.srcLabel}" -> tgt="${edge.tgtLabel}", cond="${newCond}", isBack=${edge.isBack}`);
|
|
1445
|
+
|
|
1446
|
+
const existing = edges.filter(
|
|
1447
|
+
(e) => e.srcLabel === edge.srcLabel && e.tgtLabel === edge.tgtLabel
|
|
1448
|
+
);
|
|
1449
|
+
console.log(`[DEBUG] 已有同src→tgt边数: ${existing.length}, 现有cond列表: [${existing.map(e => JSON.stringify((e.cond||'').trim())).join(', ')}]`);
|
|
1450
|
+
|
|
1451
|
+
// Case 0: 该 src→tgt 无任何已有边 → 直接加入
|
|
1452
|
+
if (existing.length === 0) {
|
|
1453
|
+
console.log(`[addEdge] 无冲突, 直接加入`);
|
|
1454
|
+
edges.push(edge);
|
|
1455
|
+
return;
|
|
1456
|
+
}
|
|
1457
|
+
|
|
1458
|
+
// 查找完全相同的 cond
|
|
1459
|
+
const exactMatch = existing.find((e) => (e.cond || '').trim() === newCond);
|
|
1460
|
+
if (exactMatch) {
|
|
1461
|
+
console.log(`[addEdge] 完全相同 cond "${newCond}" 已存在, 跳过新边`);
|
|
1462
|
+
return;
|
|
1463
|
+
}
|
|
1464
|
+
|
|
1465
|
+
const newIsConditional = newCond !== '';
|
|
1466
|
+
const hasAnyConditional = existing.some((e) => (e.cond || '').trim() !== '');
|
|
1467
|
+
const allUnconditional = existing.every((e) => (e.cond || '').trim() === '');
|
|
1468
|
+
console.log(`[DEBUG] newIsConditional=${newIsConditional}, hasAnyConditional=${hasAnyConditional}, allUnconditional=${allUnconditional}`);
|
|
1469
|
+
|
|
1470
|
+
// 规则2a: 新边无条件,已有中存在有条件边 → 丢弃新边(保留已有的条件边)
|
|
1471
|
+
if (!newIsConditional && hasAnyConditional) {
|
|
1472
|
+
const keptCond = existing.find(e => (e.cond || '').trim() !== '').cond;
|
|
1473
|
+
console.log(`[addEdge] 规则2: 新边无条件,已有条件边 "${(keptCond||'').trim()}" → 丢弃新边`);
|
|
1474
|
+
return;
|
|
1475
|
+
}
|
|
1476
|
+
|
|
1477
|
+
// 规则2b: 新边有条件,已有全无条件 → 删除已有无条件边,加入新条件边
|
|
1478
|
+
if (newIsConditional && allUnconditional) {
|
|
1479
|
+
console.log(`[addEdge] 规则2: 新边有条件 "${newCond}",已有全无条件 → 删除已有无条件边,加入新条件边`);
|
|
1480
|
+
const indicesToRemove = existing
|
|
1481
|
+
.map(e => edges.indexOf(e))
|
|
1482
|
+
.filter(i => i !== -1)
|
|
1483
|
+
.sort((a, b) => b - a);
|
|
1484
|
+
for (const idx of indicesToRemove) {
|
|
1485
|
+
edges.splice(idx, 1);
|
|
1486
|
+
}
|
|
1487
|
+
edges.push(edge);
|
|
1488
|
+
return;
|
|
1489
|
+
}
|
|
1490
|
+
|
|
1491
|
+
// 规则4: 新边有条件,已有也有条件,且条件不同 → 报错
|
|
1492
|
+
if (newIsConditional && hasAnyConditional) {
|
|
1493
|
+
const existingConds = existing.map(e => (e.cond || '').trim());
|
|
1494
|
+
rep.fail(
|
|
1495
|
+
`边冲突: "${edge.srcLabel}" → "${edge.tgtLabel}" 已存在条件边 (条件: "${existingConds.join('", "')}"),` +
|
|
1496
|
+
` 新边条件为 "${newCond}"。同一 src→tgt 不允许同时存在两条不同条件的边,请检查流程结构`,
|
|
1497
|
+
{ where: 'flow' }
|
|
1498
|
+
);
|
|
1499
|
+
}
|
|
1500
|
+
|
|
1501
|
+
// 兜底: 新边无条件,已有也全无条件 → 实际上被 exactMatch 拦住了,不会走到这里
|
|
1502
|
+
console.log(`[addEdge] 兜底: 都无条件 (${existing.length}条已有), 加入`);
|
|
1503
|
+
edges.push(edge);
|
|
1504
|
+
};
|
|
1505
|
+
// 根据裸引用获取或创建节点标签,不产生边
|
|
1506
|
+
function ensureNodeForRef(ref) {
|
|
1507
|
+
console.log('ensureNodeForRef 被调用:', ref);
|
|
1508
|
+
if (ref.includes('->')) {
|
|
1509
|
+
console.trace('异常节点引用(含 ->):', ref);
|
|
1510
|
+
rep.fail(`ensureNodeForRef 收到非法引用: "${ref}"`, { where: 'flow' });
|
|
1511
|
+
}
|
|
1512
|
+
const trimmed = ref.trim();
|
|
1513
|
+
const bracketMatch = trimmed.match(/^\[(.+)\]$/);
|
|
1514
|
+
if (bracketMatch) {
|
|
1515
|
+
const label = bracketMatch[1];
|
|
1516
|
+
if (!usedLabels.has(label) && !nodeDecls.some(d => d.label === label)) {
|
|
1517
|
+
nodeDecls.push({ label, ref: '' });
|
|
1518
|
+
usedLabels.add(label);
|
|
1519
|
+
}
|
|
1520
|
+
return label;
|
|
1521
|
+
}
|
|
1522
|
+
const inlineMatch = trimmed.match(/^\[(.+?)\]:\s*(.*)$/);
|
|
1523
|
+
if (inlineMatch) {
|
|
1524
|
+
const label = inlineMatch[1];
|
|
1525
|
+
const refVal = inlineMatch[2].trim();
|
|
1526
|
+
if (!usedLabels.has(label) && !nodeDecls.some(d => d.label === label)) {
|
|
1527
|
+
nodeDecls.push({ label, ref: refVal });
|
|
1528
|
+
usedLabels.add(label);
|
|
1529
|
+
}
|
|
1530
|
+
return label;
|
|
1531
|
+
}
|
|
1532
|
+
let baseName = trimmed.startsWith('&') ? trimmed.substring(1) : trimmed;
|
|
1533
|
+
baseName = baseName.replace(/\(.*$/, '').trim();
|
|
1534
|
+
let label = baseName;
|
|
1535
|
+
let counter = 2;
|
|
1536
|
+
while (usedLabels.has(label) || nodeDecls.some(d => d.label === label)) {
|
|
1537
|
+
label = `${baseName}_${counter}`;
|
|
1538
|
+
counter++;
|
|
1539
|
+
}
|
|
1540
|
+
nodeDecls.push({ label, ref: trimmed });
|
|
1541
|
+
usedLabels.add(label);
|
|
1542
|
+
return label;
|
|
1543
|
+
}
|
|
1544
|
+
|
|
1545
|
+
// 统一解析目标(支持 [label]、[label]:ref、actionName、&module 等)
|
|
1546
|
+
function resolveTarget(srcLabel, targetRaw, cond) {
|
|
1547
|
+
console.log('resolveTarget:', srcLabel, '->', targetRaw, 'cond:', cond);
|
|
1548
|
+
console.log(`[DEBUG] resolveTarget: src="${srcLabel}", target="${targetRaw}", cond="${cond}"`);
|
|
1549
|
+
if (targetRaw == null) {
|
|
1550
|
+
console.trace('resolveTarget 收到空 targetRaw,srcLabel:', srcLabel);
|
|
1551
|
+
rep.fail(`resolveTarget 收到空 targetRaw,srcLabel: ${srcLabel}`, { where: 'flow' });
|
|
1552
|
+
}
|
|
1553
|
+
const trimmed = targetRaw.trim().replace(/:/g, ':');
|
|
1554
|
+
const inlineMatch = trimmed.match(/^\[(.+?)\]:\s*(.*)$/);
|
|
1555
|
+
if (inlineMatch) {
|
|
1556
|
+
const label = inlineMatch[1];
|
|
1557
|
+
const ref = inlineMatch[2].trim();
|
|
1558
|
+
if (!usedLabels.has(label) && !nodeDecls.some(d => d.label === label)) {
|
|
1559
|
+
nodeDecls.push({ label, ref });
|
|
1560
|
+
usedLabels.add(label);
|
|
1561
|
+
}
|
|
1562
|
+
addEdge({ srcLabel, tgtLabel: label, cond, isBack: false });
|
|
1563
|
+
return label;
|
|
1564
|
+
}
|
|
1565
|
+
|
|
1566
|
+
const bracketMatch = trimmed.match(/^\[(.+)\]$/);
|
|
1567
|
+
if (bracketMatch) {
|
|
1568
|
+
const label = bracketMatch[1];
|
|
1569
|
+
if (!usedLabels.has(label) && !nodeDecls.some(d => d.label === label)) {
|
|
1570
|
+
nodeDecls.push({ label, ref: '' });
|
|
1571
|
+
usedLabels.add(label);
|
|
1572
|
+
}
|
|
1573
|
+
addEdge({ srcLabel, tgtLabel: label, cond, isBack: false });
|
|
1574
|
+
return label;
|
|
1575
|
+
}
|
|
1576
|
+
|
|
1577
|
+
// 普通引用
|
|
1578
|
+
let nodeLabel = trimmed.startsWith('&') ? trimmed.substring(1) : trimmed;
|
|
1579
|
+
const baseName = nodeLabel.replace(/\(.*$/, '').trim();
|
|
1580
|
+
let label = baseName;
|
|
1581
|
+
let counter = 2;
|
|
1582
|
+
while (usedLabels.has(label) || nodeDecls.some(d => d.label === label)) {
|
|
1583
|
+
label = `${baseName}_${counter}`;
|
|
1584
|
+
counter++;
|
|
1585
|
+
}
|
|
1586
|
+
nodeDecls.push({ label, ref: trimmed.trim() });
|
|
1587
|
+
usedLabels.add(label);
|
|
1588
|
+
addEdge({ srcLabel, tgtLabel: label, cond, isBack: false });
|
|
1589
|
+
return label;
|
|
1590
|
+
}
|
|
1591
|
+
|
|
1592
|
+
// 链式入口解析:[A] -> [B] -> fork:/for:/par: 的入口串。
|
|
1593
|
+
// 先把入口链建成普通边,返回链尾节点作为控制块的入口。
|
|
1594
|
+
function resolveChainEntry(raw) {
|
|
1595
|
+
const parts = raw.split('->').map(p => p.trim()).filter(Boolean);
|
|
1596
|
+
if (parts.length <= 1) return ensureNodeForRef(parts[0] || raw.trim());
|
|
1597
|
+
let prev = ensureNodeForRef(parts[0]);
|
|
1598
|
+
for (let k = 1; k < parts.length; k++) {
|
|
1599
|
+
prev = resolveTarget(prev, parts[k], '');
|
|
1600
|
+
}
|
|
1601
|
+
return prev;
|
|
1602
|
+
}
|
|
1603
|
+
|
|
1604
|
+
// 链式出口解析:-> [FAREWELL]:farewell -> [END](for/par 出口行允许内联定义 + 链)
|
|
1605
|
+
function resolveExitChain(raw, srcLabel) {
|
|
1606
|
+
const parts = raw.split('->').map(p => p.trim()).filter(Boolean);
|
|
1607
|
+
if (parts.length === 0) return srcLabel;
|
|
1608
|
+
let cur = srcLabel;
|
|
1609
|
+
for (const part of parts) {
|
|
1610
|
+
const ifMatch = part.match(/^if\s*\((.+)\)$/);
|
|
1611
|
+
if (ifMatch) {
|
|
1612
|
+
const rest = part.slice(part.indexOf(')') + 1).trim();
|
|
1613
|
+
cur = resolveTarget(cur, rest, ifMatch[1].trim());
|
|
1614
|
+
} else {
|
|
1615
|
+
cur = resolveTarget(cur, part, '');
|
|
1616
|
+
}
|
|
1617
|
+
}
|
|
1618
|
+
return cur;
|
|
1619
|
+
}
|
|
1620
|
+
|
|
1621
|
+
// ── 第一步:全局裸引用规范化(按->切块,智能保留控制结构) ──
|
|
1622
|
+
for (const line of flowLines) {
|
|
1623
|
+
|
|
1624
|
+
let t = normalizeSymbols(line.text, 'flow');
|
|
1625
|
+
console.log('规范化前:', line.text);
|
|
1626
|
+
// 按 -> 切割成块
|
|
1627
|
+
const parts = t.split('->').map(p => {
|
|
1628
|
+
let s = p.trim();
|
|
1629
|
+
if (!s) return '';
|
|
1630
|
+
|
|
1631
|
+
// 已经是 [label] 或 [label]:ref → 原样
|
|
1632
|
+
if (s.startsWith('[')) return s;
|
|
1633
|
+
|
|
1634
|
+
// 包含冒号的定义式(如 god:god_announce) → 原样
|
|
1635
|
+
if (/^[^:]+\s*:\s*.+/.test(s)) return s;
|
|
1636
|
+
|
|
1637
|
+
// 如果块内包含控制流关键字或括号 → 整块原样保留
|
|
1638
|
+
if (
|
|
1639
|
+
/\b(if|for|while|fork|par|join|in|to|all)\b/.test(s) ||
|
|
1640
|
+
/[()]/.test(s)
|
|
1641
|
+
) {
|
|
1642
|
+
return s;
|
|
1643
|
+
}
|
|
1644
|
+
|
|
1645
|
+
// &module → 转成 [module]
|
|
1646
|
+
if (s.startsWith('&')) {
|
|
1647
|
+
const label = ensureNodeForRef(s);
|
|
1648
|
+
return `[${label}]`;
|
|
1649
|
+
}
|
|
1650
|
+
|
|
1651
|
+
// 纯标识符(如 tally, nextDay;含中文节点名如 随机等一会儿)→ 转成 [label]
|
|
1652
|
+
if (/^[\p{L}_][\p{L}\p{N}_]*$/u.test(s)) {
|
|
1653
|
+
const label = ensureNodeForRef(s);
|
|
1654
|
+
return `[${label}]`;
|
|
1655
|
+
}
|
|
1656
|
+
|
|
1657
|
+
// 其他未知结构,原样保留(安全)
|
|
1658
|
+
return s;
|
|
1659
|
+
});
|
|
1660
|
+
|
|
1661
|
+
// 用 ' -> ' 重新拼接(保证后续正则 100% 命中)
|
|
1662
|
+
line.text = parts.join(' -> ');
|
|
1663
|
+
console.log('规范化后:', line.text);
|
|
1664
|
+
}
|
|
1665
|
+
|
|
1666
|
+
let i = 0;
|
|
1667
|
+
let loopGuard = 0;
|
|
1668
|
+
while (i < flowLines.length) {
|
|
1669
|
+
|
|
1670
|
+
if (++loopGuard > flowLines.length * 20) {
|
|
1671
|
+
rep.fail(`流程解析陷入死循环`, { line: (flowLines[i]?.lineNum ?? i) + 1, lineText: flowLines[i]?.raw || '', where: 'flow' });
|
|
1672
|
+
}
|
|
1673
|
+
const cl = flowLines[i];
|
|
1674
|
+
if (!cl) break;
|
|
1675
|
+
let text = normalizeSymbols(cl.text, 'flow').trim();
|
|
1676
|
+
console.log('>>> LINE', cl.lineNum+1, JSON.stringify(text));
|
|
1677
|
+
|
|
1678
|
+
// 跳过空行和注释
|
|
1679
|
+
if (!text || text.startsWith('//')) {
|
|
1680
|
+
i++;
|
|
1681
|
+
continue;
|
|
1682
|
+
}
|
|
1683
|
+
|
|
1684
|
+
// 跳过 // 注释行
|
|
1685
|
+
if (text.startsWith('//')) { i++; continue; }
|
|
1686
|
+
|
|
1687
|
+
// 注释行(# for loop 魔法注释已废弃,一律跳过)
|
|
1688
|
+
if (text.startsWith('#')) {
|
|
1689
|
+
i++;
|
|
1690
|
+
continue;
|
|
1691
|
+
}
|
|
1692
|
+
// fork: 显式入口 [A] -> fork:(支持链式入口 [A] -> [B] -> fork:)
|
|
1693
|
+
const forkMatch = text.match(/^(.+)\s*->\s*fork:$/);
|
|
1694
|
+
if (forkMatch) {
|
|
1695
|
+
const srcLabel = resolveChainEntry(forkMatch[1].trim());
|
|
1696
|
+
i++;
|
|
1697
|
+
let forkGuard = 0;
|
|
1698
|
+
while (i < flowLines.length && flowLines[i].indent > cl.indent) {
|
|
1699
|
+
if (++forkGuard > 500) rep.fail(`fork 分支解析死循环`, { line: cl.lineNum + 1, lineText: cl.raw || cl.text, where: 'flow' });
|
|
1700
|
+
const rawLine = flowLines[i].text;
|
|
1701
|
+
const bl = normalizeSymbols(rawLine, 'flow').trim();
|
|
1702
|
+
// 分支行:-> if (cond) -> 目标 或 -> 目标 -> 目标2 ...
|
|
1703
|
+
const bm = bl.match(/^->\s*(?:if\s*\((.+?)\)\s*->\s*)?(.+)$/);
|
|
1704
|
+
if (bm) {
|
|
1705
|
+
const cond = bm[1] || '';
|
|
1706
|
+
const rest = bm[2].trim();
|
|
1707
|
+
// 把剩余部分当链式解析,从 srcLabel 出发
|
|
1708
|
+
const parts = rest.split('->').map(p => p.trim()).filter(p => p !== '');
|
|
1709
|
+
if (parts.length === 0) rep.fail(`fork 分支缺少目标`, { line: flowLines[i].lineNum + 1, lineText: flowLines[i].raw || rawLine, where: 'flow' });
|
|
1710
|
+
let curSrc = srcLabel;
|
|
1711
|
+
let first = true;
|
|
1712
|
+
for (const part of parts) {
|
|
1713
|
+
curSrc = resolveTarget(curSrc, part, first ? cond : '');
|
|
1714
|
+
first = false;
|
|
1715
|
+
}
|
|
1716
|
+
} else {
|
|
1717
|
+
rep.fail(`fork 分支格式错误: "${rawLine}"`, { line: flowLines[i].lineNum + 1, lineText: flowLines[i].raw || rawLine, where: 'flow' });
|
|
1718
|
+
}
|
|
1719
|
+
i++;
|
|
1720
|
+
}
|
|
1721
|
+
continue;
|
|
1722
|
+
}
|
|
1723
|
+
|
|
1724
|
+
|
|
1725
|
+
|
|
1726
|
+
// par 循环(与 for 完全相同的解析,但特殊类型为 PAR)
|
|
1727
|
+
const parMatch = text.match(/^(.+)\s*->\s*par\s+(.+):$/);
|
|
1728
|
+
if (parMatch) {
|
|
1729
|
+
const entryRaw = parMatch[1].trim();
|
|
1730
|
+
const condition = parMatch[2].trim();
|
|
1731
|
+
|
|
1732
|
+
const entryLabel = resolveChainEntry(entryRaw);
|
|
1733
|
+
|
|
1734
|
+
let parLabel = 'PAR';
|
|
1735
|
+
let counter = 2;
|
|
1736
|
+
while (nodeDecls.some(d => d.label === parLabel)) {
|
|
1737
|
+
parLabel = `PAR_${counter}`;
|
|
1738
|
+
counter++;
|
|
1739
|
+
}
|
|
1740
|
+
const parNodeLabel = parLabel;
|
|
1741
|
+
const parOutLabel = parLabel + '_out';
|
|
1742
|
+
|
|
1743
|
+
nodeDecls.push({
|
|
1744
|
+
label: parNodeLabel,
|
|
1745
|
+
ref: '',
|
|
1746
|
+
specialType: 'PAR',
|
|
1747
|
+
forCondition: condition,
|
|
1748
|
+
});
|
|
1749
|
+
|
|
1750
|
+
// 立即创建 par_out 节点(确保无论是否有出口行都存在)
|
|
1751
|
+
if (!nodeDecls.some(d => d.label === parOutLabel)) {
|
|
1752
|
+
nodeDecls.push({
|
|
1753
|
+
label: parOutLabel,
|
|
1754
|
+
ref: '',
|
|
1755
|
+
specialType: 'PAR_OUT',
|
|
1756
|
+
forNodeId: parNodeLabel,
|
|
1757
|
+
});
|
|
1758
|
+
}
|
|
1759
|
+
|
|
1760
|
+
addEdge({ srcLabel: entryLabel, tgtLabel: parNodeLabel, cond: '', isBack: false });
|
|
1761
|
+
|
|
1762
|
+
i++; // 跳过 par 行
|
|
1763
|
+
|
|
1764
|
+
const rawBodyLines = [];
|
|
1765
|
+
while (i < flowLines.length && flowLines[i].indent > cl.indent) {
|
|
1766
|
+
rawBodyLines.push(flowLines[i]);
|
|
1767
|
+
i++;
|
|
1768
|
+
}
|
|
1769
|
+
|
|
1770
|
+
if (rawBodyLines.length === 0) {
|
|
1771
|
+
rep.fail(`par 块不能为空`, { line: cl.lineNum + 1, lineText: cl.raw || cl.text, where: 'flow' });
|
|
1772
|
+
}
|
|
1773
|
+
|
|
1774
|
+
const pendingBackNodes = [];
|
|
1775
|
+
const cleanBodyLines = [];
|
|
1776
|
+
|
|
1777
|
+
for (const bl of rawBodyLines) {
|
|
1778
|
+
let textBody = normalizeSymbols(bl.text, 'flow').trim();
|
|
1779
|
+
let lastNodeInLine = null;
|
|
1780
|
+
|
|
1781
|
+
if (textBody.startsWith('->')) {
|
|
1782
|
+
const restAfterStart = textBody.substring(2).trim();
|
|
1783
|
+
const ifMatch = restAfterStart.match(/^if\s*\((.+?)\)\s*->\s*(.*)$/);
|
|
1784
|
+
let startCond = '';
|
|
1785
|
+
if (ifMatch) {
|
|
1786
|
+
startCond = ifMatch[1].trim();
|
|
1787
|
+
textBody = ifMatch[2].trim();
|
|
1788
|
+
} else {
|
|
1789
|
+
textBody = restAfterStart;
|
|
1790
|
+
}
|
|
1791
|
+
const parts = textBody.split('->').map(x => x.trim()).filter(Boolean);
|
|
1792
|
+
if (!parts.length) {
|
|
1793
|
+
rep.fail(`par 内部行首 -> 后面缺少目标`, { line: bl.lineNum + 1, lineText: bl.raw || bl.text, where: 'flow' });
|
|
1794
|
+
}
|
|
1795
|
+
const firstPart = parts[0];
|
|
1796
|
+
const tgtLabel = resolveTarget(parNodeLabel, firstPart, startCond);
|
|
1797
|
+
lastNodeInLine = tgtLabel;
|
|
1798
|
+
}
|
|
1799
|
+
|
|
1800
|
+
let endsWithArrow = false;
|
|
1801
|
+
if (textBody.endsWith('->')) {
|
|
1802
|
+
textBody = textBody.slice(0, -2).trim();
|
|
1803
|
+
endsWithArrow = true;
|
|
1804
|
+
}
|
|
1805
|
+
|
|
1806
|
+
if (textBody) {
|
|
1807
|
+
const parts = textBody.split('->').map(p => p.trim()).filter(p => p !== '');
|
|
1808
|
+
if (parts.length > 0) {
|
|
1809
|
+
const lastPart = parts[parts.length - 1];
|
|
1810
|
+
const labelMatch = lastPart.match(/^\[(.+?)\]/);
|
|
1811
|
+
if (labelMatch) {
|
|
1812
|
+
lastNodeInLine = labelMatch[1];
|
|
1813
|
+
} else {
|
|
1814
|
+
lastNodeInLine = ensureNodeForRef(lastPart);
|
|
1815
|
+
}
|
|
1816
|
+
}
|
|
1817
|
+
} else if (!lastNodeInLine) {
|
|
1818
|
+
rep.fail(`par 内部行缺少节点`, { line: bl.lineNum + 1, lineText: bl.raw || bl.text, where: 'flow' });
|
|
1819
|
+
}
|
|
1820
|
+
|
|
1821
|
+
if (endsWithArrow && lastNodeInLine) {
|
|
1822
|
+
pendingBackNodes.push(lastNodeInLine);
|
|
1823
|
+
}
|
|
1824
|
+
|
|
1825
|
+
if (textBody) {
|
|
1826
|
+
cleanBodyLines.push({
|
|
1827
|
+
...bl,
|
|
1828
|
+
text: textBody,
|
|
1829
|
+
});
|
|
1830
|
+
}
|
|
1831
|
+
}
|
|
1832
|
+
|
|
1833
|
+
if (cleanBodyLines.length > 0) {
|
|
1834
|
+
const minIndent = Math.min(...cleanBodyLines.map(l => l.indent));
|
|
1835
|
+
const normalizedLines = cleanBodyLines.map(l => ({
|
|
1836
|
+
...l,
|
|
1837
|
+
indent: l.indent - minIndent + 2,
|
|
1838
|
+
}));
|
|
1839
|
+
const { nodeDecls: bodyDecls, edges: bodyEdges } = parseFlowSection(
|
|
1840
|
+
normalizedLines,
|
|
1841
|
+
[...usedLabels],
|
|
1842
|
+
rep
|
|
1843
|
+
);
|
|
1844
|
+
bodyDecls.forEach(d => {
|
|
1845
|
+
if (!nodeDecls.some(existing => existing.label === d.label)) {
|
|
1846
|
+
nodeDecls.push(d);
|
|
1847
|
+
}
|
|
1848
|
+
});
|
|
1849
|
+
bodyEdges.forEach(be => addEdge(be));
|
|
1850
|
+
}
|
|
1851
|
+
|
|
1852
|
+
// 内部路径末端连向 par_out(不再是 PAR 自身)
|
|
1853
|
+
pendingBackNodes.forEach(pbLabel => {
|
|
1854
|
+
addEdge({ srcLabel: pbLabel, tgtLabel: parOutLabel, cond: '', isBack: false });
|
|
1855
|
+
});
|
|
1856
|
+
|
|
1857
|
+
// 处理出口:同缩进的 -> [ExitNode](出口行可同时是控制块入口:
|
|
1858
|
+
// -> [A] -> [B] -> fork: 时,链部分作为出口,控制块行留给主循环)
|
|
1859
|
+
if (i < flowLines.length && flowLines[i].indent === cl.indent) {
|
|
1860
|
+
const afterLine = normalizeSymbols(flowLines[i].text, 'flow').trim();
|
|
1861
|
+
const am = afterLine.match(/^->\s*(.+)$/);
|
|
1862
|
+
if (am) {
|
|
1863
|
+
const exitTargetRaw = am[1].trim();
|
|
1864
|
+
const ctrlMatch = exitTargetRaw.match(/\s*->\s*(for|par|fork|join)\b/);
|
|
1865
|
+
if (ctrlMatch) {
|
|
1866
|
+
// 出口链 + 控制块入口:链部分建出口边,不消费该行
|
|
1867
|
+
const chainPart = exitTargetRaw.slice(0, ctrlMatch.index).trim();
|
|
1868
|
+
if (chainPart) {
|
|
1869
|
+
resolveExitChain(chainPart, parOutLabel);
|
|
1870
|
+
}
|
|
1871
|
+
} else {
|
|
1872
|
+
// 纯出口链(支持内联定义:-> [FAREWELL]:farewell -> [END])
|
|
1873
|
+
resolveExitChain(exitTargetRaw, parOutLabel);
|
|
1874
|
+
i++;
|
|
1875
|
+
}
|
|
1876
|
+
}
|
|
1877
|
+
}
|
|
1878
|
+
|
|
1879
|
+
currentNode = parOutLabel;
|
|
1880
|
+
continue;
|
|
1881
|
+
}
|
|
1882
|
+
|
|
1883
|
+
// join(all):
|
|
1884
|
+
const jm = text.match(/^join\((\w+)\):$/);
|
|
1885
|
+
if (jm) {
|
|
1886
|
+
const joinParam = jm[1]; // 保留用户写的参数,如 "all", "1", "any"
|
|
1887
|
+
i++;
|
|
1888
|
+
const sources = [];
|
|
1889
|
+
while (i < flowLines.length && !flowLines[i].text.trim().startsWith('to ')) {
|
|
1890
|
+
const rawLine = flowLines[i].text;
|
|
1891
|
+
const srcLine = rawLine.trim();
|
|
1892
|
+
if (!srcLine.endsWith('->')) {
|
|
1893
|
+
rep.fail(`join 内部每行必须以 -> 结尾。当前行: "${rawLine}"`, { line: flowLines[i].lineNum + 1, lineText: flowLines[i].raw || rawLine, where: 'flow' });
|
|
1894
|
+
}
|
|
1895
|
+
// label 禁止跨括号(防回溯把多段链式吞进单个节点名)
|
|
1896
|
+
const sm = srcLine.match(/^\[([^\[\]]+?)\]\s*->$/);
|
|
1897
|
+
if (sm) {
|
|
1898
|
+
sources.push(sm[1]);
|
|
1899
|
+
} else {
|
|
1900
|
+
rep.fail(`join 源节点格式错误,期望 [节点名] ->,实际: "${rawLine}"`, { line: flowLines[i].lineNum + 1, lineText: flowLines[i].raw || rawLine, where: 'flow' });
|
|
1901
|
+
}
|
|
1902
|
+
i++;
|
|
1903
|
+
}
|
|
1904
|
+
if (i < flowLines.length && flowLines[i].text.trim().startsWith('to ')) {
|
|
1905
|
+
let targetRaw = flowLines[i].text.trim().slice(3).trim();
|
|
1906
|
+
if (!targetRaw) rep.fail(`join 目标为空`, { line: flowLines[i].lineNum + 1, lineText: flowLines[i].raw || '', where: 'flow' });
|
|
1907
|
+
if (targetRaw.endsWith('->')) {
|
|
1908
|
+
targetRaw = targetRaw.slice(0, -2).trim();
|
|
1909
|
+
}
|
|
1910
|
+
// 支持链式目标 to [A]:ref -> [B]:sources 连链首,currentNode 走链尾
|
|
1911
|
+
const parts = targetRaw.split('->').map(p => p.trim()).filter(Boolean);
|
|
1912
|
+
if (parts.length === 0) rep.fail(`join 目标为空`, { line: flowLines[i].lineNum + 1, lineText: flowLines[i].raw || '', where: 'flow' });
|
|
1913
|
+
const tgtLabel = ensureNodeForRef(parts[0]);
|
|
1914
|
+
let tail = tgtLabel;
|
|
1915
|
+
for (let k = 1; k < parts.length; k++) {
|
|
1916
|
+
tail = resolveTarget(tail, parts[k], '');
|
|
1917
|
+
}
|
|
1918
|
+
sources.forEach(s => addEdge({ srcLabel: s, tgtLabel: tgtLabel, cond: '', isBack: false }));
|
|
1919
|
+
|
|
1920
|
+
// ═══ 将 join 信息存入目标节点的声明 ═══
|
|
1921
|
+
const tgtDecl = nodeDecls.find(d => d.label === tgtLabel);
|
|
1922
|
+
if (tgtDecl) {
|
|
1923
|
+
if (!tgtDecl.joinEntries) tgtDecl.joinEntries = [];
|
|
1924
|
+
tgtDecl.joinEntries.push({ sources: sources.slice(), param: joinParam });
|
|
1925
|
+
} else {
|
|
1926
|
+
// ensureNodeForRef 应该已创建,但以防万一手动补
|
|
1927
|
+
const newDecl = { label: tgtLabel, ref: '', joinEntries: [{ sources: sources.slice(), param: joinParam }] };
|
|
1928
|
+
nodeDecls.push(newDecl);
|
|
1929
|
+
usedLabels.add(tgtLabel);
|
|
1930
|
+
}
|
|
1931
|
+
|
|
1932
|
+
currentNode = tail;
|
|
1933
|
+
i++;
|
|
1934
|
+
} else {
|
|
1935
|
+
rep.fail(`join 缺少 to 目标`, { line: (flowLines[i]?.lineNum ?? flowLines.length) + 1, lineText: flowLines[i]?.raw || '', where: 'flow' });
|
|
1936
|
+
}
|
|
1937
|
+
continue;
|
|
1938
|
+
}
|
|
1939
|
+
|
|
1940
|
+
|
|
1941
|
+
|
|
1942
|
+
// for 循环新语法: [A] -> for 条件:
|
|
1943
|
+
const forEntryMatch = text.match(/^(.+)\s*->\s*for\s+(.+):$/);
|
|
1944
|
+
if (forEntryMatch) {
|
|
1945
|
+
const entryRaw = forEntryMatch[1].trim();
|
|
1946
|
+
const condition = forEntryMatch[2].trim();
|
|
1947
|
+
|
|
1948
|
+
// 解析入口节点(支持链式入口 [A] -> [B] -> for ...)
|
|
1949
|
+
const entryLabel = resolveChainEntry(entryRaw);
|
|
1950
|
+
|
|
1951
|
+
// 生成唯一的 FOR 节点标签
|
|
1952
|
+
let forLabel = 'FOR';
|
|
1953
|
+
let counter = 2;
|
|
1954
|
+
while (nodeDecls.some(d => d.label === forLabel)) {
|
|
1955
|
+
forLabel = `FOR_${counter}`;
|
|
1956
|
+
counter++;
|
|
1957
|
+
}
|
|
1958
|
+
const forNodeLabel = forLabel;
|
|
1959
|
+
const forOutLabel = forLabel + '_out';
|
|
1960
|
+
|
|
1961
|
+
// 声明 FOR 节点
|
|
1962
|
+
nodeDecls.push({
|
|
1963
|
+
label: forNodeLabel,
|
|
1964
|
+
ref: '',
|
|
1965
|
+
specialType: 'FOR',
|
|
1966
|
+
forCondition: condition,
|
|
1967
|
+
});
|
|
1968
|
+
|
|
1969
|
+
// 入口边: entryLabel -> FOR
|
|
1970
|
+
addEdge({ srcLabel: entryLabel, tgtLabel: forNodeLabel, cond: '', isBack: false });
|
|
1971
|
+
|
|
1972
|
+
i++; // 跳过 for 行
|
|
1973
|
+
|
|
1974
|
+
// 收集缩进大于 for 行的内部行
|
|
1975
|
+
const rawBodyLines = [];
|
|
1976
|
+
while (i < flowLines.length && flowLines[i].indent > cl.indent) {
|
|
1977
|
+
rawBodyLines.push(flowLines[i]);
|
|
1978
|
+
i++;
|
|
1979
|
+
}
|
|
1980
|
+
|
|
1981
|
+
if (rawBodyLines.length === 0) {
|
|
1982
|
+
rep.fail(`for 块不能为空`, { line: cl.lineNum + 1, lineText: cl.raw || cl.text, where: 'flow' });
|
|
1983
|
+
}
|
|
1984
|
+
|
|
1985
|
+
// ---------- 剥箭头预处理 ----------
|
|
1986
|
+
const pendingBackNodes = []; // 需要回连/连出口的节点 label
|
|
1987
|
+
const cleanBodyLines = []; // 剥除箭头后的行(用于递归解析)
|
|
1988
|
+
|
|
1989
|
+
for (const bl of rawBodyLines) {
|
|
1990
|
+
let textBody = normalizeSymbols(bl.text, 'flow').trim();
|
|
1991
|
+
let lastNodeInLine = null; // 记录该行最右节点
|
|
1992
|
+
|
|
1993
|
+
// 1. 处理行首箭头:-> if (cond) -> target 或 -> target ...
|
|
1994
|
+
if (textBody.startsWith('->')) {
|
|
1995
|
+
const restAfterStart = textBody.substring(2).trim();
|
|
1996
|
+
const ifMatch = restAfterStart.match(/^if\s*\((.+?)\)\s*->\s*(.*)$/);
|
|
1997
|
+
let startCond = '';
|
|
1998
|
+
if (ifMatch) {
|
|
1999
|
+
startCond = ifMatch[1].trim();
|
|
2000
|
+
textBody = ifMatch[2].trim();
|
|
2001
|
+
} else {
|
|
2002
|
+
textBody = restAfterStart;
|
|
2003
|
+
}
|
|
2004
|
+
// 提取第一个目标节点(仅用于生成 FOR->node 边,不截断 textBody)
|
|
2005
|
+
const parts =
|
|
2006
|
+
textBody
|
|
2007
|
+
.split('->')
|
|
2008
|
+
.map(x => x.trim())
|
|
2009
|
+
.filter(Boolean);
|
|
2010
|
+
|
|
2011
|
+
if (!parts.length) {
|
|
2012
|
+
rep.fail(`for 内部行首 -> 后面缺少目标`, { line: bl.lineNum + 1, lineText: bl.raw || bl.text, where: 'flow' });
|
|
2013
|
+
}
|
|
2014
|
+
|
|
2015
|
+
const firstPart = parts[0];
|
|
2016
|
+
|
|
2017
|
+
const tgtLabel =
|
|
2018
|
+
resolveTarget(
|
|
2019
|
+
forNodeLabel,
|
|
2020
|
+
firstPart,
|
|
2021
|
+
startCond
|
|
2022
|
+
);
|
|
2023
|
+
|
|
2024
|
+
lastNodeInLine = tgtLabel;
|
|
2025
|
+
// 注意:textBody 保持不变,继续包含完整链式,以便后续行尾箭头处理和 cleanBodyLines 解析
|
|
2026
|
+
}
|
|
2027
|
+
|
|
2028
|
+
// 2. 处理行尾箭头
|
|
2029
|
+
let endsWithArrow = false;
|
|
2030
|
+
if (textBody.endsWith('->')) {
|
|
2031
|
+
textBody = textBody.slice(0, -2).trim();
|
|
2032
|
+
endsWithArrow = true;
|
|
2033
|
+
}
|
|
2034
|
+
|
|
2035
|
+
// 3. 找出该行的最右节点(用于 pendingBackNodes)
|
|
2036
|
+
if (textBody) {
|
|
2037
|
+
// 从 textBody 中提取最后一个节点 label
|
|
2038
|
+
const parts = textBody.split('->').map(p => p.trim()).filter(p => p !== '');
|
|
2039
|
+
if (parts.length > 0) {
|
|
2040
|
+
const lastPart = parts[parts.length - 1];
|
|
2041
|
+
// 尝试解析最后一个节点的 label
|
|
2042
|
+
const labelMatch = lastPart.match(/^\[(.+?)\]/);
|
|
2043
|
+
if (labelMatch) {
|
|
2044
|
+
lastNodeInLine = labelMatch[1];
|
|
2045
|
+
} else {
|
|
2046
|
+
// 裸引用,用 ensureNodeForRef 获取 label
|
|
2047
|
+
const lbl = ensureNodeForRef(lastPart);
|
|
2048
|
+
lastNodeInLine = lbl;
|
|
2049
|
+
}
|
|
2050
|
+
}
|
|
2051
|
+
} else if (!lastNodeInLine) {
|
|
2052
|
+
// textBody 为空且没有行首箭头,说明该行只有行尾箭头(不太可能,但防御)
|
|
2053
|
+
rep.fail(`for 内部行缺少节点`, { line: bl.lineNum + 1, lineText: bl.raw || bl.text, where: 'flow' });
|
|
2054
|
+
}
|
|
2055
|
+
|
|
2056
|
+
// 如果有行尾箭头,记录最右节点
|
|
2057
|
+
if (endsWithArrow && lastNodeInLine) {
|
|
2058
|
+
pendingBackNodes.push(lastNodeInLine);
|
|
2059
|
+
}
|
|
2060
|
+
|
|
2061
|
+
// 若剥完后 textBody 非空,作为普通行加入 cleanBodyLines
|
|
2062
|
+
if (textBody) {
|
|
2063
|
+
cleanBodyLines.push({
|
|
2064
|
+
...bl,
|
|
2065
|
+
text: textBody,
|
|
2066
|
+
});
|
|
2067
|
+
}
|
|
2068
|
+
}
|
|
2069
|
+
|
|
2070
|
+
// 递归解析清理后的循环体内部
|
|
2071
|
+
if (cleanBodyLines.length > 0) {
|
|
2072
|
+
const minIndent = Math.min(...cleanBodyLines.map(l => l.indent));
|
|
2073
|
+
const normalizedLines = cleanBodyLines.map(l => ({
|
|
2074
|
+
...l,
|
|
2075
|
+
indent: l.indent - minIndent + 2,
|
|
2076
|
+
}));
|
|
2077
|
+
const { nodeDecls: bodyDecls, edges: bodyEdges } = parseFlowSection(
|
|
2078
|
+
normalizedLines,
|
|
2079
|
+
[...usedLabels],
|
|
2080
|
+
rep
|
|
2081
|
+
);
|
|
2082
|
+
bodyDecls.forEach(d => {
|
|
2083
|
+
if (!nodeDecls.some(existing => existing.label === d.label)) {
|
|
2084
|
+
nodeDecls.push(d);
|
|
2085
|
+
}
|
|
2086
|
+
});
|
|
2087
|
+
bodyEdges.forEach(be => addEdge(be));
|
|
2088
|
+
}
|
|
2089
|
+
|
|
2090
|
+
// 处理出口:同缩进的 -> [ExitNode]
|
|
2091
|
+
// 无论有无出口,pendingBackNodes 都应回连 FOR 形成环
|
|
2092
|
+
pendingBackNodes.forEach(pbLabel => {
|
|
2093
|
+
addEdge({ srcLabel: pbLabel, tgtLabel: forNodeLabel, cond: '', isBack: true });
|
|
2094
|
+
});
|
|
2095
|
+
|
|
2096
|
+
console.log('FOR出口诊断:', {
|
|
2097
|
+
i,
|
|
2098
|
+
lineText: flowLines[i]?.text,
|
|
2099
|
+
lineIndent: flowLines[i]?.indent,
|
|
2100
|
+
forIndent: cl.indent,
|
|
2101
|
+
isMatch: flowLines[i]?.indent === cl.indent
|
|
2102
|
+
});
|
|
2103
|
+
if (i < flowLines.length && flowLines[i].indent === cl.indent) {
|
|
2104
|
+
const afterLine = normalizeSymbols(flowLines[i].text, 'flow').trim();
|
|
2105
|
+
const am = afterLine.match(/^->\s*(.+)$/);
|
|
2106
|
+
if (am) {
|
|
2107
|
+
// 声明 for_out 节点
|
|
2108
|
+
if (!nodeDecls.some(d => d.label === forOutLabel)) {
|
|
2109
|
+
nodeDecls.push({
|
|
2110
|
+
label: forOutLabel,
|
|
2111
|
+
ref: '',
|
|
2112
|
+
specialType: 'FOR_OUT',
|
|
2113
|
+
forNodeId: forNodeLabel,
|
|
2114
|
+
});
|
|
2115
|
+
}
|
|
2116
|
+
const exitTargetRaw = am[1].trim();
|
|
2117
|
+
const ctrlMatch = exitTargetRaw.match(/\s*->\s*(for|par|fork|join)\b/);
|
|
2118
|
+
if (ctrlMatch) {
|
|
2119
|
+
// 出口链 + 控制块入口:链部分建出口边,不消费该行
|
|
2120
|
+
const chainPart = exitTargetRaw.slice(0, ctrlMatch.index).trim();
|
|
2121
|
+
if (chainPart) {
|
|
2122
|
+
resolveExitChain(chainPart, forOutLabel);
|
|
2123
|
+
}
|
|
2124
|
+
} else {
|
|
2125
|
+
// for_out -> 出口节点(支持链:-> [X]:ref -> [Y])
|
|
2126
|
+
resolveExitChain(exitTargetRaw, forOutLabel);
|
|
2127
|
+
i++;
|
|
2128
|
+
}
|
|
2129
|
+
}
|
|
2130
|
+
}
|
|
2131
|
+
|
|
2132
|
+
// 更新 currentNode 为 for_out 标签,方便后续链
|
|
2133
|
+
currentNode = forOutLabel;
|
|
2134
|
+
continue;
|
|
2135
|
+
}
|
|
2136
|
+
|
|
2137
|
+
|
|
2138
|
+
// ⚠️ 重要:先匹配链式连接([label] -> ...),再匹配节点声明([label]: ...)
|
|
2139
|
+
// [label]:ref -> ... 链式(如 [AI_ATK]:ai_attack -> [AI_DONE])
|
|
2140
|
+
// label 用 [^\[\]] 防回溯跨箭头:否则 `[START] -> [x]:a -> [END]` 会被
|
|
2141
|
+
// 误判成声明行,把 "START] -> [x" 当成节点名(2026-08-22 flow 链式 bug 根因)。
|
|
2142
|
+
const dmChain = text.match(/^\[([^\[\]]+?)\]:\s*(\S+)\s*->\s*(.+)$/);
|
|
2143
|
+
if (dmChain) {
|
|
2144
|
+
const label = dmChain[1];
|
|
2145
|
+
const ref = dmChain[2].trim();
|
|
2146
|
+
const existing = nodeDecls.find((d) => d.label === label);
|
|
2147
|
+
if (existing) existing.ref = ref || existing.ref;
|
|
2148
|
+
else nodeDecls.push({ label, ref });
|
|
2149
|
+
i++;
|
|
2150
|
+
// 剩余链从 label 出发(复用 chainMatch 的解析逻辑)
|
|
2151
|
+
const rest = dmChain[3].trim();
|
|
2152
|
+
const rawParts = rest.split('->').map((p) => p.trim()).filter((p) => p !== '');
|
|
2153
|
+
const parts = [];
|
|
2154
|
+
let pendingCond = null;
|
|
2155
|
+
for (const part of rawParts) {
|
|
2156
|
+
const ifMatch = part.match(/^if\s*\((.+)\)$/);
|
|
2157
|
+
if (ifMatch) {
|
|
2158
|
+
pendingCond = ifMatch[1].trim();
|
|
2159
|
+
} else {
|
|
2160
|
+
parts.push({ target: part, cond: pendingCond || '' });
|
|
2161
|
+
pendingCond = null;
|
|
2162
|
+
}
|
|
2163
|
+
}
|
|
2164
|
+
if (pendingCond) {
|
|
2165
|
+
rep.fail(
|
|
2166
|
+
`条件 "if (${pendingCond})" 后面缺少目标节点`,
|
|
2167
|
+
{ line: cl.lineNum + 1, lineText: cl.raw || cl.text, where: 'flow' }
|
|
2168
|
+
);
|
|
2169
|
+
}
|
|
2170
|
+
let currentSrc = label;
|
|
2171
|
+
for (const { target, cond } of parts) {
|
|
2172
|
+
currentSrc = resolveTarget(currentSrc, target, cond);
|
|
2173
|
+
}
|
|
2174
|
+
currentNode = currentSrc;
|
|
2175
|
+
continue;
|
|
2176
|
+
}
|
|
2177
|
+
|
|
2178
|
+
const chainMatch = text.match(/^\[(.+?)\]\s*->\s*(.*)$/);
|
|
2179
|
+
if (chainMatch) {
|
|
2180
|
+
const srcLabel = chainMatch[1];
|
|
2181
|
+
let rest = chainMatch[2];
|
|
2182
|
+
i++;
|
|
2183
|
+
|
|
2184
|
+
if (!nodeDecls.some(d => d.label === srcLabel)) {
|
|
2185
|
+
nodeDecls.push({ label: srcLabel, ref: '' });
|
|
2186
|
+
}
|
|
2187
|
+
|
|
2188
|
+
const rawParts = rest.split('->').map(p => p.trim()).filter(p => p !== '');
|
|
2189
|
+
const parts = [];
|
|
2190
|
+
let pendingCond = null;
|
|
2191
|
+
for (const part of rawParts) {
|
|
2192
|
+
const ifMatch = part.match(/^if\s*\((.+)\)$/);
|
|
2193
|
+
if (ifMatch) {
|
|
2194
|
+
pendingCond = ifMatch[1].trim();
|
|
2195
|
+
} else {
|
|
2196
|
+
parts.push({ target: part, cond: pendingCond || '' });
|
|
2197
|
+
pendingCond = null;
|
|
2198
|
+
}
|
|
2199
|
+
}
|
|
2200
|
+
if (pendingCond) {
|
|
2201
|
+
rep.fail(
|
|
2202
|
+
`条件 "if (${pendingCond})" 后面缺少目标节点`,
|
|
2203
|
+
{ line: cl.lineNum + 1, lineText: cl.raw || cl.text, where: 'flow' }
|
|
2204
|
+
);
|
|
2205
|
+
}
|
|
2206
|
+
|
|
2207
|
+
let currentSrc = srcLabel;
|
|
2208
|
+
for (const { target, cond } of parts) {
|
|
2209
|
+
currentSrc = resolveTarget(currentSrc, target, cond);
|
|
2210
|
+
}
|
|
2211
|
+
currentNode = currentSrc;
|
|
2212
|
+
continue;
|
|
2213
|
+
}
|
|
2214
|
+
|
|
2215
|
+
// 单节点引用(无箭头),例如 for 内部剥箭头后只剩 [A]
|
|
2216
|
+
const soloNodeMatch = text.match(/^\[(.+?)\]\s*$/);
|
|
2217
|
+
if (soloNodeMatch && !text.includes('->') && !text.includes(':')) {
|
|
2218
|
+
ensureNodeForRef(`[${soloNodeMatch[1]}]`);
|
|
2219
|
+
i++;
|
|
2220
|
+
continue;
|
|
2221
|
+
}
|
|
2222
|
+
|
|
2223
|
+
// 节点声明 [label]: ref
|
|
2224
|
+
const dm = text.match(/^\[(.+?)\]:\s*(.*)$/);
|
|
2225
|
+
if (dm) {
|
|
2226
|
+
const label = dm[1];
|
|
2227
|
+
const ref = dm[2].trim();
|
|
2228
|
+
const existing = nodeDecls.find(d => d.label === label);
|
|
2229
|
+
if (existing) existing.ref = ref || existing.ref;
|
|
2230
|
+
else nodeDecls.push({ label, ref });
|
|
2231
|
+
currentNode = label;
|
|
2232
|
+
i++;
|
|
2233
|
+
continue;
|
|
2234
|
+
}
|
|
2235
|
+
|
|
2236
|
+
|
|
2237
|
+
|
|
2238
|
+
|
|
2239
|
+
rep.fail(
|
|
2240
|
+
`未识别的流程语法: "${text}"`,
|
|
2241
|
+
{ line: cl.lineNum + 1, lineText: cl.raw || cl.text, where: 'flow' }
|
|
2242
|
+
);
|
|
2243
|
+
}
|
|
2244
|
+
|
|
2245
|
+
return { nodeDecls, edges };
|
|
2246
|
+
}
|
|
2247
|
+
|
|
2248
|
+
export {
|
|
2249
|
+
normalizeSymbols, parseFEMO, splitTopBlocks, stripComments, stripLineComments,
|
|
2250
|
+
extractHashSketch,
|
|
2251
|
+
parseMetaBlock, parseVarsBlock, parseCodeBlock,
|
|
2252
|
+
parseActorsBlock, parseMemoryOrContextBlock,
|
|
2253
|
+
parseActionBlock, parseModuleBlock, parseMainflowBlock,
|
|
2254
|
+
parseFlowSection,
|
|
2255
|
+
};
|