behavior-contracts 0.11.22 → 0.11.23
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/dist/behavior.d.ts +5 -0
- package/dist/behavior.d.ts.map +1 -1
- package/dist/behavior.js +11 -3
- package/dist/behavior.js.map +1 -1
- package/dist/generator/emit-shared-go-typed.d.ts +5 -78
- package/dist/generator/emit-shared-go-typed.d.ts.map +1 -1
- package/dist/generator/emit-shared-go-typed.js +8 -315
- package/dist/generator/emit-shared-go-typed.js.map +1 -1
- package/dist/generator/emit-shared-go.d.ts +12 -16
- package/dist/generator/emit-shared-go.d.ts.map +1 -1
- package/dist/generator/emit-shared-go.js +12 -1037
- package/dist/generator/emit-shared-go.js.map +1 -1
- package/dist/generator/emit-shared-rust-typed.d.ts +0 -93
- package/dist/generator/emit-shared-rust-typed.d.ts.map +1 -1
- package/dist/generator/emit-shared-rust-typed.js +7 -46
- package/dist/generator/emit-shared-rust-typed.js.map +1 -1
- package/dist/generator/emit-shared-rust.d.ts +5 -38
- package/dist/generator/emit-shared-rust.d.ts.map +1 -1
- package/dist/generator/emit-shared-rust.js +3 -1249
- package/dist/generator/emit-shared-rust.js.map +1 -1
- package/dist/generator/emit-typed-native-go.d.ts.map +1 -1
- package/dist/generator/emit-typed-native-go.js +8 -7
- package/dist/generator/emit-typed-native-go.js.map +1 -1
- package/dist/generator/emit-typed-native-rust.d.ts.map +1 -1
- package/dist/generator/emit-typed-native-rust.js +7 -1
- package/dist/generator/emit-typed-native-rust.js.map +1 -1
- package/dist/generator/straightline.d.ts +24 -6
- package/dist/generator/straightline.d.ts.map +1 -1
- package/dist/generator/straightline.js +79 -1
- package/dist/generator/straightline.js.map +1 -1
- package/package.json +1 -1
|
@@ -1,1264 +1,18 @@
|
|
|
1
|
-
import { mapTransformExpr } from "../behavior.js";
|
|
2
|
-
import { emitDocLiteralCompact } from "./literal.js";
|
|
3
|
-
import { sequentialOrder, analyzeSequentialOps, classifyExpr, isScopeFree, componentNeedsScope, } from "./straightline.js";
|
|
4
|
-
/** primitive namespace(生成コード内)。crate から `primitives` を use する。 */
|
|
5
|
-
const P = "primitives";
|
|
6
1
|
/**
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
* (呼び時点の results を読む — 決定的)を渡す。
|
|
2
|
+
* emit-shared-rust.ts — the two naming helpers the rust typed-native emitter (emit-typed-native-rust.ts) and
|
|
3
|
+
* the shared rust typed-emit helpers (emit-shared-rust-typed.ts) share. It registers no emitter.
|
|
10
4
|
*/
|
|
11
|
-
const SCOPE = "scope()";
|
|
12
|
-
/**
|
|
13
|
-
* map 本体(over/guard/ports)の要素 scope 式(生成コード内)。run_behavior の map と同じく
|
|
14
|
-
* base_scope に `as`→要素値 を足したスナップ。生成コードは map arm 内で per-element に
|
|
15
|
-
* `mscope()`(Vec<(String, Value)> を返すクロージャ)をローカル定義し、port/guard 式はそれを呼ぶ。
|
|
16
|
-
*/
|
|
17
|
-
const MAP_SCOPE = "mscope()";
|
|
18
|
-
/**
|
|
19
|
-
* 生成中 module の `json!` マクロ使用の構造的トラッカー(emitModule が emit 前に reset し、
|
|
20
|
-
* emit 後に serde_json import の要否として読む)。`json!` を emit する唯一の経路は jsonLit()
|
|
21
|
-
* なので、この関数が呼ばれた事実 = 使用。生成テキストの substring 判定(文字列リテラル
|
|
22
|
-
* 内容の "json!" に誤反応)はしない。
|
|
23
|
-
*/
|
|
24
|
-
let jsonMacroEmitted = false;
|
|
25
|
-
/**
|
|
26
|
-
* typed emitter(bc#48 rust-typed)が base straight-line モジュールを同梱し、その上に RunPlan-style の
|
|
27
|
-
* struct-native typed runner を積む場合、runner は `run_plan`/`OpSpec`/`ExecOutcome`/`RelationKind`/
|
|
28
|
-
* `json!` を参照する。bc#75 で base は逐次 component からそれらを落とすため、typed 層はこの flag で
|
|
29
|
-
* base に「RunPlan-path の import と serde_json を必ず含めよ」と要求する(typed 経路の後方互換)。
|
|
30
|
-
*/
|
|
31
|
-
let forceRunPlanImports = null;
|
|
32
|
-
export function setRustForceRunPlanImports(req) {
|
|
33
|
-
forceRunPlanImports = req;
|
|
34
|
-
}
|
|
35
|
-
/**
|
|
36
|
-
* bc: codegen は IR を出力してはならない(no-ir invariant)。
|
|
37
|
-
* かつては非脱解釈の式(obj/arr/動的ref/scalar/演算子被演算子)を `json!(<IR>)` として埋め込み、
|
|
38
|
-
* evaluate 委譲 primitive に実行時解釈させていた=インタプリタの松葉杖(=癌)。これを撤去する。
|
|
39
|
-
* ここに来る式はまだネイティブ脱解釈されていない = ネイティブコードで emit すべき(次タスク)。
|
|
40
|
-
* それまでは生成時に loud に落とす(IR は一切出力しない)。
|
|
41
|
-
*/
|
|
42
|
-
function jsonLit(node) {
|
|
43
|
-
throw new Error(`codegen no-ir invariant: refusing to emit IR literal (json!) for ${JSON.stringify(node).slice(0, 100)} — de-interpret this expression to native code (next task)`);
|
|
44
|
-
}
|
|
45
|
-
/** ref/refOpt の path がすべて string リテラルか(native 化の条件)。 */
|
|
46
|
-
function isStaticStringPath(arg) {
|
|
47
|
-
return Array.isArray(arg) && arg.length > 0 && arg.every((p) => typeof p === "string");
|
|
48
|
-
}
|
|
49
5
|
/** string を rust 文字列リテラルへ(path セグメント用。JSON エスケープで安全側)。 */
|
|
50
6
|
function rustStrLit(s) {
|
|
51
7
|
return JSON.stringify(s);
|
|
52
8
|
}
|
|
53
|
-
/**
|
|
54
|
-
* emitExpr — Expression IR ノードを rust の「scope を受けて `R`(= Result<Value, ExprFailure>)を
|
|
55
|
-
* 返す」式へ落とす。**単純式はネイティブ化**(式ツリー解釈 `evaluate` を消す — bc#39 AC#2 の
|
|
56
|
-
* 脱解釈の実体)、overflow/短絡系のみ A0 primitive SSoT を直呼びする:
|
|
57
|
-
*
|
|
58
|
-
* - `concat` → `primitives::concat_native(&[<part>?, …])`(native 連結。`evaluate` 非経由)
|
|
59
|
-
* - `ref`/`refOpt`(静的 path)→ `primitives::ref_native(&["a","b"], scope)` 等(native scope walk)
|
|
60
|
-
* - それ以外の演算子 → 対応する A0 evaluate 委譲 primitive(被演算子は未評価 IR リテラル)
|
|
61
|
-
* - スカラ/ null / bool リテラルや非静的 path・未知形 → `primitives::eval_expr(&json!(..), scope)`
|
|
62
|
-
* (同一 SSoT。型判定を生成コードに残さない)
|
|
63
|
-
*
|
|
64
|
-
* Portability Guard を通過済み(生成時検査)なので未知 operator はここに来ない。
|
|
65
|
-
* 返り値は必ず `R` 型の rust 式(呼び側が `?` で Value へ展開する)。
|
|
66
|
-
*/
|
|
67
|
-
function emitExpr(node, scopeVar) {
|
|
68
|
-
if (node !== null && typeof node === "object" && !Array.isArray(node)) {
|
|
69
|
-
const keys = Object.keys(node);
|
|
70
|
-
if (keys.length === 1) {
|
|
71
|
-
const op = keys[0];
|
|
72
|
-
const arg = node[op];
|
|
73
|
-
// ── (1) concat(native 連結。式ツリー解釈 `evaluate` 非経由)─────────────────
|
|
74
|
-
if (op === "concat" && Array.isArray(arg)) {
|
|
75
|
-
const parts = arg.map((a) => `(${emitExpr(a, scopeVar)})?`).join(", ");
|
|
76
|
-
return `${P}::concat_native(&[${parts}])`;
|
|
77
|
-
}
|
|
78
|
-
// ── (2) ref / refOpt(静的 string path のみ native scope walk)─────────────────
|
|
79
|
-
if ((op === "ref" || op === "refOpt") && isStaticStringPath(arg)) {
|
|
80
|
-
const path = arg.map(rustStrLit).join(", ");
|
|
81
|
-
const fn = op === "ref" ? "ref_native" : "ref_opt_native";
|
|
82
|
-
return `${P}::${fn}(&[${path}], &${scopeVar})`;
|
|
83
|
-
}
|
|
84
|
-
// ── (3) その他 op → native primitive / native 制御フロー(IR は出力しない)─────
|
|
85
|
-
const call = OP_PRIMITIVE[op];
|
|
86
|
-
if (call)
|
|
87
|
-
return call(arg, scopeVar);
|
|
88
|
-
}
|
|
89
|
-
}
|
|
90
|
-
// bare スカラリテラル → native Value(型付き `R` を返す primitive 経由。evaluate 非経由)。
|
|
91
|
-
if (node === null)
|
|
92
|
-
return `${P}::null_native()`;
|
|
93
|
-
if (typeof node === "boolean")
|
|
94
|
-
return `${P}::bool_native(${node ? "true" : "false"})`;
|
|
95
|
-
if (typeof node === "string")
|
|
96
|
-
return `${P}::str_native(${rustStrLit(node)})`;
|
|
97
|
-
if (typeof node === "number")
|
|
98
|
-
return `${P}::number_lit_native(${rustF64Lit(node)})`;
|
|
99
|
-
// 未知形(Portability Guard 通過済みなので通常到達しない)。IR は出力せず生成時に loud に落とす。
|
|
100
|
-
throw new Error(`straight-line rust: cannot de-interpret node to native (no IR output): ${JSON.stringify(node).slice(0, 100)}`);
|
|
101
|
-
}
|
|
102
|
-
/** JS number → rust f64 リテラル(整数表記には `.0` を補う。指数/小数はそのまま f64 型推論に載る)。 */
|
|
103
|
-
function rustF64Lit(n) {
|
|
104
|
-
const s = String(n);
|
|
105
|
-
return /[.eE]/.test(s) ? s : `${s}.0`;
|
|
106
|
-
}
|
|
107
|
-
/** 二項 op(被演算子 [a,b] を native emit → `*_native(a?, b?)`)。 */
|
|
108
|
-
function bin(fn) {
|
|
109
|
-
return (a, s) => {
|
|
110
|
-
const [x, y] = a;
|
|
111
|
-
return `${P}::${fn}((${emitExpr(x, s)})?, (${emitExpr(y, s)})?)`;
|
|
112
|
-
};
|
|
113
|
-
}
|
|
114
|
-
/** 単項 op(被演算子 [a] を native emit → `*_native(a?)`)。 */
|
|
115
|
-
function un(fn) {
|
|
116
|
-
return (a, s) => {
|
|
117
|
-
const [x] = a;
|
|
118
|
-
return `${P}::${fn}((${emitExpr(x, s)})?)`;
|
|
119
|
-
};
|
|
120
|
-
}
|
|
121
|
-
const OP_PRIMITIVE = {
|
|
122
|
-
// リテラルラッパ(int は decimal string, float は number)。
|
|
123
|
-
int: (a) => `${P}::int_lit_native(${rustStrLit(a)})`,
|
|
124
|
-
float: (a) => `${P}::float_lit_native(${rustF64Lit(a)})`,
|
|
125
|
-
// 構築(要素/フィールドは native emit した評価済み Value)。
|
|
126
|
-
obj: (a, s) => emitObj(a, s),
|
|
127
|
-
arr: (a, s) => `${P}::arr_native(vec![${a.map((e) => `(${emitExpr(e, s)})?`).join(", ")}])`,
|
|
128
|
-
// 数値・比較(二項/単項)。
|
|
129
|
-
add: bin("add_native"),
|
|
130
|
-
sub: bin("sub_native"),
|
|
131
|
-
mul: bin("mul_native"),
|
|
132
|
-
neg: un("neg_native"),
|
|
133
|
-
div: bin("div_native"),
|
|
134
|
-
mod: bin("mod_native"),
|
|
135
|
-
eq: bin("eq_native"),
|
|
136
|
-
ne: bin("ne_native"),
|
|
137
|
-
lt: bin("lt_native"),
|
|
138
|
-
le: bin("le_native"),
|
|
139
|
-
gt: bin("gt_native"),
|
|
140
|
-
ge: bin("ge_native"),
|
|
141
|
-
// bool/null(短絡: native 制御フローで採用側のみ評価。IR は渡さない)。
|
|
142
|
-
and: (a, s) => emitShortCircuit("and", a, s),
|
|
143
|
-
or: (a, s) => emitShortCircuit("or", a, s),
|
|
144
|
-
not: un("not_native"),
|
|
145
|
-
coalesce: (a, s) => {
|
|
146
|
-
const [x, y] = a;
|
|
147
|
-
return `(|| -> ${P}::R { let __a = (${emitExpr(x, s)})?; if matches!(__a, Value::Null) { ${emitExpr(y, s)} } else { Ok(__a) } })()`;
|
|
148
|
-
},
|
|
149
|
-
cond: (a, s) => {
|
|
150
|
-
const [c, t, e] = a;
|
|
151
|
-
return `(|| -> ${P}::R { if ${P}::require_bool_native((${emitExpr(c, s)})?, "cond")? { ${emitExpr(t, s)} } else { ${emitExpr(e, s)} } })()`;
|
|
152
|
-
},
|
|
153
|
-
len: un("len_native"),
|
|
154
|
-
};
|
|
155
|
-
/**
|
|
156
|
-
* 短絡 and/or を IIFE で native に綴じる。左辺は必ず評価、右辺は短絡側でのみ評価
|
|
157
|
-
* (`evaluate` の and/or アームと同一の評価順・bool 検査)。
|
|
158
|
-
* and: 左辺 false → false(右辺未評価)/ true → 右辺の bool
|
|
159
|
-
* or : 左辺 true → true (右辺未評価)/ false → 右辺の bool
|
|
160
|
-
*/
|
|
161
|
-
function emitShortCircuit(op, a, scopeVar) {
|
|
162
|
-
const [x, y] = a;
|
|
163
|
-
const guard = op === "and" ? "!__a" : "__a";
|
|
164
|
-
const shortVal = op === "and" ? "false" : "true";
|
|
165
|
-
return (`(|| -> ${P}::R { ` +
|
|
166
|
-
`let __a = ${P}::require_bool_native((${emitExpr(x, scopeVar)})?, "${op}")?; ` +
|
|
167
|
-
`if ${guard} { return Ok(Value::Bool(${shortVal})); } ` +
|
|
168
|
-
`Ok(Value::Bool(${P}::require_bool_native((${emitExpr(y, scopeVar)})?, "${op}")?)) })()`);
|
|
169
|
-
}
|
|
170
|
-
/**
|
|
171
|
-
* obj 構築を native に綴じる。`__proto__` キー無しの通常ケースは `obj_native(vec![...])` へ
|
|
172
|
-
* 平坦展開(値は左→右で `?` 評価)。`__proto__` を含む場合のみ IIFE で `evaluate` の走査順を
|
|
173
|
-
* 保存(当該キー位置で値評価前に FORBIDDEN_KEY を返す)。
|
|
174
|
-
*/
|
|
175
|
-
function emitObj(a, scopeVar) {
|
|
176
|
-
const obj = a;
|
|
177
|
-
const keys = Object.keys(obj);
|
|
178
|
-
const hasForbidden = keys.includes("__proto__");
|
|
179
|
-
if (!hasForbidden) {
|
|
180
|
-
const pairs = keys
|
|
181
|
-
.map((k) => `(${rustStrLit(k)}.to_string(), (${emitExpr(obj[k], scopeVar)})?)`)
|
|
182
|
-
.join(", ");
|
|
183
|
-
return `${P}::obj_native(vec![${pairs}])`;
|
|
184
|
-
}
|
|
185
|
-
const lines = [`let mut __o: Vec<(String, Value)> = Vec::with_capacity(${keys.length});`];
|
|
186
|
-
for (const k of keys) {
|
|
187
|
-
if (k === "__proto__") {
|
|
188
|
-
// evaluate 同順: 値評価前に fail-closed(obj_native が __proto__ で FORBIDDEN_KEY を返す)。
|
|
189
|
-
lines.push(`return ${P}::obj_native(vec![(${rustStrLit(k)}.to_string(), Value::Null)]);`);
|
|
190
|
-
break;
|
|
191
|
-
}
|
|
192
|
-
lines.push(`__o.push((${rustStrLit(k)}.to_string(), (${emitExpr(obj[k], scopeVar)})?));`);
|
|
193
|
-
}
|
|
194
|
-
return `(|| -> ${P}::R { ${lines.join(" ")} Ok(Value::Obj(__o)) })()`;
|
|
195
|
-
}
|
|
196
|
-
// ── per-node exec 分岐 / component 関数 / module の綴じ方 ──────────────────────
|
|
197
9
|
/** component 名 → rust 関数名の一部(決定的・一意は DUPLICATE_COMPONENT で保証)。 */
|
|
198
10
|
function sanitize(name) {
|
|
199
11
|
return name.replace(/[^A-Za-z0-9_]/g, "_");
|
|
200
12
|
}
|
|
201
|
-
/**
|
|
202
|
-
function emitOpsLiteral(plan) {
|
|
203
|
-
const rows = plan.opsLiteral.map((o) => {
|
|
204
|
-
const parent = o.parent === null ? "None" : `Some(${o.parent})`;
|
|
205
|
-
const bindField = o.bindField === undefined ? "None" : `Some(${rustStrLit(o.bindField)}.to_string())`;
|
|
206
|
-
const relationKind = o.relationKind === undefined
|
|
207
|
-
? "None"
|
|
208
|
-
: `Some(RelationKind::${o.relationKind === "connection" ? "Connection" : "Single"})`;
|
|
209
|
-
const policy = o.policy === undefined ? "None" : `Some(${rustStrLit(o.policy)}.to_string())`;
|
|
210
|
-
return ` OpSpec {
|
|
211
|
-
id: ${rustStrLit(o.id)}.to_string(),
|
|
212
|
-
parent: ${parent},
|
|
213
|
-
bind_field: ${bindField},
|
|
214
|
-
relation_kind: ${relationKind},
|
|
215
|
-
policy: ${policy},
|
|
216
|
-
},`;
|
|
217
|
-
});
|
|
218
|
-
return `vec![\n${rows.join("\n")}\n ]`;
|
|
219
|
-
}
|
|
220
|
-
/** map arm の要素 ports 構築式(要素 scope `mscope()` で各 port を native/primitive 評価)。 */
|
|
221
|
-
function emitMapPortsRust(op) {
|
|
222
|
-
if (op.ports.length === 0)
|
|
223
|
-
return "Ok(Vec::new())";
|
|
224
|
-
return `Ok(vec![\n${op.ports
|
|
225
|
-
.map((pt) => ` (${rustStrLit(pt.name)}.to_string(), (${pt.expr})?),`)
|
|
226
|
-
.join("\n")}\n ])`;
|
|
227
|
-
}
|
|
228
|
-
/**
|
|
229
|
-
* emitMapArm — map ノードの直線展開(要素反復・guard skip・per-element/batched handler・into
|
|
230
|
-
* zip-attach)。run_behavior の map 分岐(behavior.rs)を生成 rust へ直線展開する。op-log 等価のため
|
|
231
|
-
* exec_ctx は run_behavior と同じ ctx(非 batched は bound=Some(要素)、batched は None)・同じ ports で
|
|
232
|
-
* 呼ぶ。guard は cond primitive(strict-bool SSoT)、into は inline zip-attach
|
|
233
|
-
* (MAP_INTO_ELEMENT_NOT_OBJECT fail-closed で Failure code 一致)。要素反復は宣言どおり逐次
|
|
234
|
-
* (run_behavior が sequential run_plan を使うのと同一 — 経路等価の pin 対象)。
|
|
235
|
-
*/
|
|
236
|
-
function emitMapArm(op) {
|
|
237
|
-
const comp = rustStrLit(op.component ?? ""); // Component 形でのみ使う(純式 map は handler を呼ばない)
|
|
238
|
-
const nodeId = rustStrLit(op.id);
|
|
239
|
-
const asKey = rustStrLit(op.as);
|
|
240
|
-
const guardBlock = op.guard === undefined
|
|
241
|
-
? ""
|
|
242
|
-
: `
|
|
243
|
-
let gkeep = {
|
|
244
|
-
let mscope = || -> Vec<(String, Value)> {
|
|
245
|
-
let mut s = ${SCOPE};
|
|
246
|
-
s.push((${asKey}.to_string(), el.clone()));
|
|
247
|
-
s
|
|
248
|
-
};
|
|
249
|
-
let _ = &mscope;
|
|
250
|
-
match ${op.guard} {
|
|
251
|
-
Ok(v) => matches!(v, Value::Bool(true)),
|
|
252
|
-
Err(e) => {
|
|
253
|
-
*err_cell = Some(e.into());
|
|
254
|
-
return ExecOutcome::Error("aborted".to_string());
|
|
255
|
-
}
|
|
256
|
-
}
|
|
257
|
-
};
|
|
258
|
-
if !gkeep {
|
|
259
|
-
continue;
|
|
260
|
-
}`;
|
|
261
|
-
const portEval = `
|
|
262
|
-
let eval_ports = || -> Result<Vec<(String, Value)>, behavior_contracts::ExprFailure> {
|
|
263
|
-
let mscope = || -> Vec<(String, Value)> {
|
|
264
|
-
let mut s = ${SCOPE};
|
|
265
|
-
s.push((${asKey}.to_string(), el.clone()));
|
|
266
|
-
s
|
|
267
|
-
};
|
|
268
|
-
let _ = &mscope;
|
|
269
|
-
${emitMapPortsRust(op)}
|
|
270
|
-
};
|
|
271
|
-
let ports = match eval_ports() {
|
|
272
|
-
Ok(p) => p,
|
|
273
|
-
Err(e) => {
|
|
274
|
-
*err_cell = Some(e.into());
|
|
275
|
-
return ExecOutcome::Error("aborted".to_string());
|
|
276
|
-
}
|
|
277
|
-
};`;
|
|
278
|
-
let intoTail;
|
|
279
|
-
if (op.into === undefined) {
|
|
280
|
-
intoTail = ` results_cell.push((op.id.clone(), Value::Arr(collected.clone())));
|
|
281
|
-
return ExecOutcome::Ok(Value::Arr(collected));`;
|
|
282
|
-
}
|
|
283
|
-
else {
|
|
284
|
-
const intoKey = op.into;
|
|
285
|
-
// augmented-element build (object-check + shallow copy + into key). Shared by the kept branch and the
|
|
286
|
-
// connection guard-skip branch (#182 — skip fills into with the empty connection), so it lives ONCE.
|
|
287
|
-
const cpBuildMapArm = (intoValExpr) => ` match oel {
|
|
288
|
-
Value::Obj(pairs) => {
|
|
289
|
-
let mut next: Vec<(String, Value)> = pairs.clone();
|
|
290
|
-
let __into = ${intoValExpr};
|
|
291
|
-
if let Some(slot) = next.iter_mut().find(|(kk, _)| kk == ${rustStrLit(intoKey)}) {
|
|
292
|
-
slot.1 = __into;
|
|
293
|
-
} else {
|
|
294
|
-
next.push((${rustStrLit(intoKey)}.to_string(), __into));
|
|
295
|
-
}
|
|
296
|
-
augmented.push(Value::Obj(next));
|
|
297
|
-
}
|
|
298
|
-
_ => {
|
|
299
|
-
*err_cell = Some(behavior_contracts::BehaviorError::new(
|
|
300
|
-
"MAP_INTO_ELEMENT_NOT_OBJECT",
|
|
301
|
-
format!("map '${op.id}': 'into' requires object elements (element {mj} is not an object)"),
|
|
302
|
-
));
|
|
303
|
-
return ExecOutcome::Error("aborted".to_string());
|
|
304
|
-
}
|
|
305
|
-
}`;
|
|
306
|
-
const mapArmSkip = op.relationKind === "connection"
|
|
307
|
-
? ` } else {\n${cpBuildMapArm("behavior_contracts::skip_connection()")}\n }`
|
|
308
|
-
: ` } else {\n augmented.push(oel.clone());\n }`;
|
|
309
|
-
intoTail = ` let mut augmented: Vec<Value> = Vec::with_capacity(over_arr.len());
|
|
310
|
-
let mut mk = 0usize;
|
|
311
|
-
for (mj, oel) in over_arr.iter().enumerate() {
|
|
312
|
-
if mk < kept_idx.len() && kept_idx[mk] == mj {
|
|
313
|
-
${cpBuildMapArm("collected[mk].clone()")}
|
|
314
|
-
mk += 1;
|
|
315
|
-
${mapArmSkip}
|
|
316
|
-
}
|
|
317
|
-
results_cell.push((op.id.clone(), Value::Arr(augmented.clone())));
|
|
318
|
-
return ExecOutcome::Ok(Value::Arr(augmented));`;
|
|
319
|
-
}
|
|
320
|
-
// 純式 map(#222/#225): handler も要素ごとの outcome も無い(RunPlan 経路も同じ規律)。
|
|
321
|
-
const transformLoop = op.transform === undefined
|
|
322
|
-
? undefined
|
|
323
|
-
: ` let mut collected: Vec<Value> = Vec::with_capacity(over_arr.len());
|
|
324
|
-
for (mi, el) in over_arr.iter().enumerate() {
|
|
325
|
-
let _ = mi;${guardBlock}
|
|
326
|
-
collected.push(${op.transform});
|
|
327
|
-
}
|
|
328
|
-
results_cell.push((op.id.clone(), Value::Arr(collected.clone())));
|
|
329
|
-
return ExecOutcome::Ok(Value::Arr(collected));`;
|
|
330
|
-
const loopBody = transformLoop !== undefined
|
|
331
|
-
? transformLoop
|
|
332
|
-
: op.batched
|
|
333
|
-
? ` let mut items: Vec<Value> = Vec::new();
|
|
334
|
-
for (mi, el) in over_arr.iter().enumerate() {${guardBlock}${portEval}
|
|
335
|
-
items.push(Value::Obj(ports));
|
|
336
|
-
kept_idx.push(mi);
|
|
337
|
-
}
|
|
338
|
-
let collected: Vec<Value> = if items.is_empty() {
|
|
339
|
-
Vec::new()
|
|
340
|
-
} else {
|
|
341
|
-
let want = items.len();
|
|
342
|
-
let batch_ports = vec![("items".to_string(), Value::Arr(items))];
|
|
343
|
-
match handlers.exec_ctx(${nodeId}, ${comp}, &batch_ports, None) {
|
|
344
|
-
None => {
|
|
345
|
-
*err_cell = Some(unknown_component(${comp}));
|
|
346
|
-
return ExecOutcome::Error("aborted".to_string());
|
|
347
|
-
}
|
|
348
|
-
Some(ExecOutcome::Error(e)) => return ExecOutcome::Error(e),
|
|
349
|
-
Some(ExecOutcome::Ok(v)) => match v {
|
|
350
|
-
Value::Arr(r) if r.len() == want => r,
|
|
351
|
-
_ => {
|
|
352
|
-
*err_cell = Some(behavior_contracts::BehaviorError::new(
|
|
353
|
-
"MAP_BATCH_RESULT_MISMATCH",
|
|
354
|
-
format!("map '${op.id}': batched handler must return a list aligned to items (want {want})"),
|
|
355
|
-
));
|
|
356
|
-
return ExecOutcome::Error("aborted".to_string());
|
|
357
|
-
}
|
|
358
|
-
},
|
|
359
|
-
}
|
|
360
|
-
};
|
|
361
|
-
${intoTail}`
|
|
362
|
-
: ` let mut collected: Vec<Value> = Vec::with_capacity(over_arr.len());
|
|
363
|
-
for (mi, el) in over_arr.iter().enumerate() {${guardBlock}${portEval}
|
|
364
|
-
match handlers.exec_ctx(${nodeId}, ${comp}, &ports, Some(el)) {
|
|
365
|
-
None => {
|
|
366
|
-
*err_cell = Some(unknown_component(${comp}));
|
|
367
|
-
return ExecOutcome::Error("aborted".to_string());
|
|
368
|
-
}
|
|
369
|
-
Some(ExecOutcome::Error(e)) => return ExecOutcome::Error(e),
|
|
370
|
-
Some(ExecOutcome::Ok(v)) => collected.push(v),
|
|
371
|
-
}
|
|
372
|
-
kept_idx.push(mi);
|
|
373
|
-
}
|
|
374
|
-
${intoTail}`;
|
|
375
|
-
return ` if i == ${op.index} {
|
|
376
|
-
let over_arr: Vec<Value> = match ${op.over} {
|
|
377
|
-
Ok(Value::Arr(a)) => a,
|
|
378
|
-
Ok(_) => {
|
|
379
|
-
*err_cell = Some(behavior_contracts::BehaviorError::new(
|
|
380
|
-
"MAP_OVER_NOT_ARRAY",
|
|
381
|
-
"map '${op.id}': 'over' did not evaluate to an array".to_string(),
|
|
382
|
-
));
|
|
383
|
-
return ExecOutcome::Error("aborted".to_string());
|
|
384
|
-
}
|
|
385
|
-
Err(e) => {
|
|
386
|
-
*err_cell = Some(e.into());
|
|
387
|
-
return ExecOutcome::Error("aborted".to_string());
|
|
388
|
-
}
|
|
389
|
-
};
|
|
390
|
-
let mut kept_idx: Vec<usize> = Vec::new();
|
|
391
|
-
${loopBody}
|
|
392
|
-
}`;
|
|
393
|
-
}
|
|
394
|
-
/**
|
|
395
|
-
* 1ノードの exec 分岐本体(index で分岐 — node_kind ディスパッチではない)。生成コードは
|
|
396
|
-
* `i == <index>` で確定した分岐に入る(実行時の種別判定は無い)。
|
|
397
|
-
*/
|
|
398
|
-
function emitExecArm(op) {
|
|
399
|
-
if (op.kind === "map")
|
|
400
|
-
return emitMapArm(op);
|
|
401
|
-
if (op.kind === "cond") {
|
|
402
|
-
// cond は純 Expression。scope を渡して1式評価(handler は呼ばない)。式評価失敗は
|
|
403
|
-
// BehaviorError へ写して err_cell に載せ、run_plan を "aborted" で巻き戻す。ok 結果は
|
|
404
|
-
// results に足す(後続ノード・output が参照できるように — run_behavior と同一)。
|
|
405
|
-
return ` if i == ${op.index} {
|
|
406
|
-
match ${op.expr} {
|
|
407
|
-
Ok(v) => {
|
|
408
|
-
results_cell.push((op.id.clone(), v.clone()));
|
|
409
|
-
return ExecOutcome::Ok(v);
|
|
410
|
-
}
|
|
411
|
-
Err(e) => {
|
|
412
|
-
*err_cell = Some(e.into());
|
|
413
|
-
return ExecOutcome::Error("aborted".to_string());
|
|
414
|
-
}
|
|
415
|
-
}
|
|
416
|
-
}`;
|
|
417
|
-
}
|
|
418
|
-
// componentRef: 各 port を名前付き(native or primitive)呼びで評価 → handler 注入呼び。
|
|
419
|
-
// port 評価は `?` を使うため R を返す**名前付き**クロージャに畳む(即時実行 IIFE は
|
|
420
|
-
// clippy::redundant_closure_call になるため、宣言と呼び出しを分ける)。Err は err_cell へ写す。
|
|
421
|
-
const portRows = op.ports.length === 0
|
|
422
|
-
? " Ok(Vec::new())"
|
|
423
|
-
: ` Ok(vec![\n${op.ports
|
|
424
|
-
.map((pt) => ` (${rustStrLit(pt.name)}.to_string(), (${pt.expr})?),`)
|
|
425
|
-
.join("\n")}\n ])`;
|
|
426
|
-
return ` if i == ${op.index} {
|
|
427
|
-
let eval_ports =
|
|
428
|
-
|| -> Result<Vec<(String, Value)>, behavior_contracts::ExprFailure> {
|
|
429
|
-
${portRows}
|
|
430
|
-
};
|
|
431
|
-
let ports = match eval_ports() {
|
|
432
|
-
Ok(p) => p,
|
|
433
|
-
Err(e) => {
|
|
434
|
-
*err_cell = Some(e.into());
|
|
435
|
-
return ExecOutcome::Error("aborted".to_string());
|
|
436
|
-
}
|
|
437
|
-
};
|
|
438
|
-
let outcome = match handlers.exec_ctx(${rustStrLit(op.id)}, ${rustStrLit(op.component)}, &ports, None) {
|
|
439
|
-
Some(o) => o,
|
|
440
|
-
None => {
|
|
441
|
-
*err_cell = Some(unknown_component(${rustStrLit(op.component)}));
|
|
442
|
-
return ExecOutcome::Error("aborted".to_string());
|
|
443
|
-
}
|
|
444
|
-
};
|
|
445
|
-
if let ExecOutcome::Ok(v) = &outcome {
|
|
446
|
-
results_cell.push((op.id.clone(), v.clone()));
|
|
447
|
-
}
|
|
448
|
-
return outcome;
|
|
449
|
-
}`;
|
|
450
|
-
}
|
|
451
|
-
/** dynamic 式に渡す scope 式(scope-free なら空 scope 定数 `&[]`)。 */
|
|
452
|
-
function rSeqScope(node, ctx) {
|
|
453
|
-
if (isScopeFree(node))
|
|
454
|
-
return "sl_empty()";
|
|
455
|
-
if (ctx.mapAs)
|
|
456
|
-
return ctx.mapAs.mscopeVar;
|
|
457
|
-
if (!ctx.scopeVar)
|
|
458
|
-
throw new Error("straight-line rust: scope-reading expr in a scopeless component (analysis bug)");
|
|
459
|
-
return ctx.scopeVar;
|
|
460
|
-
}
|
|
461
|
-
/** 静的 ref の head を配線解決した rust 式片。単一 local 直読み = 生 Value(infallible)。 */
|
|
462
|
-
function rSeqRefHead(head, ctx) {
|
|
463
|
-
if (ctx.mapAs && head === ctx.mapAs.as)
|
|
464
|
-
return { expr: `${ctx.mapAs.elVar}.clone()`, fallible: false };
|
|
465
|
-
const idx = ctx.idToIndex.get(head);
|
|
466
|
-
if (idx !== undefined) {
|
|
467
|
-
const executedBefore = ctx.atOutput || ctx.pos[idx] < ctx.currentPos;
|
|
468
|
-
if (executedBefore) {
|
|
469
|
-
const meta = ctx.metas[idx];
|
|
470
|
-
const local = ctx.local.get(head);
|
|
471
|
-
if (ctx.atOutput || !(meta.canSkip || meta.alwaysSkip))
|
|
472
|
-
return { expr: `${local}.clone()`, fallible: false };
|
|
473
|
-
// 実行済みだが skip され得る: 未生成なら input の同名 key へ fall-through。UNKNOWN_BINDING は
|
|
474
|
-
// runtime SSoT(ref_native)が出す(意味論の再実装をしない)。
|
|
475
|
-
ctx.usesInput.value = true;
|
|
476
|
-
return { expr: `sl_head_or(${ctx.okFlag.get(head)}, &${local}, input, ${rustStrLit(head)})`, fallible: true };
|
|
477
|
-
}
|
|
478
|
-
}
|
|
479
|
-
// 単一 head の scope 束縛は runtime SSoT ref_native(UNKNOWN_BINDING も同一)。
|
|
480
|
-
ctx.usesInput.value = true;
|
|
481
|
-
return { expr: `${P}::ref_native(&[${rustStrLit(head)}], input)`, fallible: true };
|
|
482
|
-
}
|
|
483
|
-
/** fallible な式片を「`?` で Value 化」した式へ。 */
|
|
484
|
-
function useVal(p) {
|
|
485
|
-
return p.fallible ? `(${p.expr})?` : p.expr;
|
|
486
|
-
}
|
|
487
|
-
/** 分類済み StaticExpr を rust 式片へ(逐次経路のネイティブ inline)。 */
|
|
488
|
-
function rSeqStatic(e, ctx) {
|
|
489
|
-
switch (e.kind) {
|
|
490
|
-
case "str":
|
|
491
|
-
return { expr: `Value::Str(${rustStrLit(e.value)}.to_string())`, fallible: false };
|
|
492
|
-
case "bool":
|
|
493
|
-
return { expr: `Value::Bool(${e.value ? "true" : "false"})`, fallible: false };
|
|
494
|
-
case "null":
|
|
495
|
-
return { expr: `Value::Null`, fallible: false };
|
|
496
|
-
case "ref": {
|
|
497
|
-
const head = rSeqRefHead(e.path[0], ctx);
|
|
498
|
-
if (e.path.length === 1)
|
|
499
|
-
return head;
|
|
500
|
-
const fn = e.opt ? "ref_opt_native" : "ref_native";
|
|
501
|
-
const rest = e.path.slice(1).map(rustStrLit).join(", ");
|
|
502
|
-
// head を 1-entry scope で SSoT ref_native へ(field walk の意味論を再実装しない)。
|
|
503
|
-
return {
|
|
504
|
-
expr: `${P}::${fn}(&["__sl_head", ${rest}], &[("__sl_head".to_string(), ${useVal(head)})])`,
|
|
505
|
-
fallible: true,
|
|
506
|
-
};
|
|
507
|
-
}
|
|
508
|
-
case "concat": {
|
|
509
|
-
// concat_native は評価済み Value のスライスを受ける(closure/part 関数値は無い)。
|
|
510
|
-
const parts = e.parts.map((p) => useVal(rSeqStatic(p, ctx))).join(", ");
|
|
511
|
-
return { expr: `${P}::concat_native(&[${parts}])`, fallible: true };
|
|
512
|
-
}
|
|
513
|
-
case "dynamic":
|
|
514
|
-
return { expr: emitExpr(e.node, rSeqScope(e.node, ctx)), fallible: true };
|
|
515
|
-
}
|
|
516
|
-
}
|
|
517
|
-
/** Expression IR → rust 式片(逐次経路)。 */
|
|
518
|
-
function rSeqExpr(node, ctx) {
|
|
519
|
-
return rSeqStatic(classifyExpr(node), ctx);
|
|
520
|
-
}
|
|
521
|
-
/** node id 群 → 衝突しない決定的ローカル名。 */
|
|
522
|
-
function allocLocals(prefix, ids) {
|
|
523
|
-
const out = new Map();
|
|
524
|
-
const taken = new Set();
|
|
525
|
-
ids.forEach((id, i) => {
|
|
526
|
-
let name = `${prefix}${sanitize(id)}`;
|
|
527
|
-
if (taken.has(name))
|
|
528
|
-
name = `${name}_${i}`;
|
|
529
|
-
taken.add(name);
|
|
530
|
-
out.set(id, name);
|
|
531
|
-
});
|
|
532
|
-
return out;
|
|
533
|
-
}
|
|
534
|
-
/** 未生成表現の rust 式(single → Null / connection → 空 connection)。 */
|
|
535
|
-
function unproducedRust(relationKind, ctx) {
|
|
536
|
-
ctx.usesRelationKind.value = true;
|
|
537
|
-
// 既定(注記の不在)は None = Null。Single variant は削除済み。
|
|
538
|
-
const kind = relationKind === "connection" ? "Some(RelationKind::Connection)" : "None";
|
|
539
|
-
return `${P}::unproduced_value(${kind})`;
|
|
540
|
-
}
|
|
541
|
-
/** policy 解釈(fail/retry → OP_FAILED、continue → skip)。plan.rs interpret_outcome と code/msg 一致。 */
|
|
542
|
-
function rSeqPolicyThrow(errVar, opId, meta, ind) {
|
|
543
|
-
const msg = meta.policy === "retry"
|
|
544
|
-
? `format!("operation '{}' failed under 'retry' policy (exhausted): {}", ${rustStrLit(opId)}, ${errVar})`
|
|
545
|
-
: `format!("operation '{}' failed under 'fail' policy: {}", ${rustStrLit(opId)}, ${errVar})`;
|
|
546
|
-
return [`${ind}return Err(BehaviorError::new("OP_FAILED", ${msg}));`];
|
|
547
|
-
}
|
|
548
|
-
/** op 本体(ports 構築 + handler 呼び + policy 解釈 + 結果格納)を indent 付きで emit。 */
|
|
549
|
-
function emitRSeqExec(op, plan, ctx, lines, ind) {
|
|
550
|
-
const i = op.index;
|
|
551
|
-
const meta = ctx.metas[i];
|
|
552
|
-
const o = plan.opsLiteral[i];
|
|
553
|
-
const id = o.id;
|
|
554
|
-
const local = ctx.local.get(id);
|
|
555
|
-
const canSkip = meta.canSkip || meta.alwaysSkip;
|
|
556
|
-
const store = (valueExpr, target, sind) => {
|
|
557
|
-
if (canSkip) {
|
|
558
|
-
target.push(`${sind}${local} = ${valueExpr};`, `${sind}${ctx.okFlag.get(id)} = true;`);
|
|
559
|
-
}
|
|
560
|
-
else {
|
|
561
|
-
target.push(`${sind}let ${local}: Value = ${valueExpr};`);
|
|
562
|
-
}
|
|
563
|
-
if (ctx.scopeVar)
|
|
564
|
-
target.push(`${sind}${ctx.scopeVar}.push((${rustStrLit(id)}.to_string(), ${local}.clone()));`);
|
|
565
|
-
};
|
|
566
|
-
if (op.kind === "cond") {
|
|
567
|
-
const c = plan.component.body[i].cond;
|
|
568
|
-
const node = { cond: [c.if, c.then, c.else] };
|
|
569
|
-
const v = `v_${sanitize(id)}`;
|
|
570
|
-
lines.push(`${ind}let ${v}: Value = (${emitExpr(node, rSeqScope(node, ctx))}).map_err(BehaviorError::from)?;`);
|
|
571
|
-
store(v, lines, ind);
|
|
572
|
-
return;
|
|
573
|
-
}
|
|
574
|
-
if (op.kind === "map") {
|
|
575
|
-
emitRSeqMap(op, plan, ctx, lines, ind, store);
|
|
576
|
-
return;
|
|
577
|
-
}
|
|
578
|
-
// componentRef: ports 構築(名前付き closure で `?` 展開)→ handler 呼び → policy 解釈。
|
|
579
|
-
const savedPos = ctx.currentPos;
|
|
580
|
-
const portsFn = `eval_ports_${sanitize(id)}`;
|
|
581
|
-
const portRows = op.ports.length === 0
|
|
582
|
-
? "Ok(Vec::new())"
|
|
583
|
-
: `Ok(vec![\n${op.ports
|
|
584
|
-
.map((p) => {
|
|
585
|
-
const node = plan.component.body[i].ports[p.name];
|
|
586
|
-
return `${ind} (${rustStrLit(p.name)}.to_string(), ${useVal(rSeqExpr(node, ctx))}),`;
|
|
587
|
-
})
|
|
588
|
-
.join("\n")}\n${ind}])`;
|
|
589
|
-
ctx.currentPos = savedPos;
|
|
590
|
-
ctx.usesHandlers.value = true;
|
|
591
|
-
lines.push(`${ind}let ${portsFn} = || -> Result<Vec<(String, Value)>, behavior_contracts::ExprFailure> { ${portRows} };`);
|
|
592
|
-
lines.push(`${ind}let ports_${sanitize(id)} = ${portsFn}().map_err(BehaviorError::from)?;`);
|
|
593
|
-
const oc = `outcome_${sanitize(id)}`;
|
|
594
|
-
lines.push(`${ind}let ${oc} = match handlers.exec_ctx(${rustStrLit(id)}, ${rustStrLit(op.component)}, &ports_${sanitize(id)}, None) {`, `${ind} Some(o) => o,`, `${ind} None => return Err(unknown_component(${rustStrLit(op.component)})),`, `${ind}};`);
|
|
595
|
-
if (meta.policy === "continue") {
|
|
596
|
-
lines.push(`${ind}if let ExecOutcome::Ok(v) = ${oc} {`);
|
|
597
|
-
store("v", lines, `${ind} `);
|
|
598
|
-
lines.push(`${ind}}`);
|
|
599
|
-
}
|
|
600
|
-
else {
|
|
601
|
-
lines.push(`${ind}let ${local}_val = match ${oc} {`);
|
|
602
|
-
lines.push(`${ind} ExecOutcome::Ok(v) => v,`);
|
|
603
|
-
lines.push(`${ind} ExecOutcome::Error(e) => {`);
|
|
604
|
-
lines.push(...rSeqPolicyThrow("e", id, meta, `${ind} `));
|
|
605
|
-
lines.push(`${ind} }`);
|
|
606
|
-
lines.push(`${ind}};`);
|
|
607
|
-
store(`${local}_val`, lines, ind);
|
|
608
|
-
}
|
|
609
|
-
}
|
|
610
|
-
/** emitRSeqMap — map ノードの逐次直線展開(rust)。 */
|
|
611
|
-
function emitRSeqMap(op, plan, ctx, lines, ind, store) {
|
|
612
|
-
const i = op.index;
|
|
613
|
-
const meta = ctx.metas[i];
|
|
614
|
-
const m = plan.component.body[i].map;
|
|
615
|
-
const id = op.id;
|
|
616
|
-
const s = sanitize(id);
|
|
617
|
-
const comp = rustStrLit(op.component ?? ""); // Component 形でのみ使う(純式 map は handler を呼ばない)
|
|
618
|
-
const nodeId = rustStrLit(op.id);
|
|
619
|
-
const asKey = rustStrLit(m.as);
|
|
620
|
-
if (mapTransformExpr(m) === undefined)
|
|
621
|
-
ctx.usesHandlers.value = true; // Component map だけが handler を呼ぶ。
|
|
622
|
-
const guardIR = m.when === undefined ? undefined : { cond: [m.when, true, false] };
|
|
623
|
-
// 純式 map(Component 呼びなし)の要素式(go emitter と同じ規律)。
|
|
624
|
-
const transform = mapTransformExpr(m);
|
|
625
|
-
const mapNeedsScope = (guardIR !== undefined && !isScopeFree(guardIR)) ||
|
|
626
|
-
(transform !== undefined && !isScopeFree(transform)) ||
|
|
627
|
-
Object.keys(m.ports ?? {}).some((k) => {
|
|
628
|
-
const cls = classifyExpr(m.ports[k]);
|
|
629
|
-
const needs = (e) => e.kind === "dynamic" ? !isScopeFree(e.node) : e.kind === "concat" ? e.parts.some(needs) : false;
|
|
630
|
-
return needs(cls);
|
|
631
|
-
});
|
|
632
|
-
const elVar = `el_${s}`;
|
|
633
|
-
const mscopeVar = `mscope_${s}`;
|
|
634
|
-
const overVar = `over_${s}`;
|
|
635
|
-
const keptVar = `kept_${s}`;
|
|
636
|
-
const collected = `collected_${s}`;
|
|
637
|
-
const contFlag = meta.policy === "continue";
|
|
638
|
-
const skipVar = `skip_${s}`;
|
|
639
|
-
const baseScopeExpr = ctx.scopeVar;
|
|
640
|
-
const mapCtx = { ...ctx, mapAs: { as: m.as, elVar, mscopeVar } };
|
|
641
|
-
const overPiece = rSeqExpr(m.over, ctx);
|
|
642
|
-
const overVal = overPiece.fallible ? `(${overPiece.expr}).map_err(BehaviorError::from)?` : overPiece.expr;
|
|
643
|
-
lines.push(`${ind}let ${overVar}: Vec<Value> = match ${overVal} {`);
|
|
644
|
-
lines.push(`${ind} Value::Arr(a) => a,`);
|
|
645
|
-
lines.push(`${ind} _ => return Err(BehaviorError::new("MAP_OVER_NOT_ARRAY", "map '${id}': 'over' did not evaluate to an array".to_string())),`);
|
|
646
|
-
lines.push(`${ind}};`);
|
|
647
|
-
// kept / skip は Component 形だけが使う(生成物は clippy -D warnings を通るので未使用ローカルは出さない)。
|
|
648
|
-
if (transform === undefined)
|
|
649
|
-
lines.push(`${ind}let mut ${keptVar}: Vec<usize> = Vec::new();`);
|
|
650
|
-
lines.push(`${ind}let mut ${collected}: Vec<Value> = Vec::new();`);
|
|
651
|
-
if (contFlag && transform === undefined)
|
|
652
|
-
lines.push(`${ind}let mut ${skipVar} = false;`);
|
|
653
|
-
const mscopeLine = (ind2) => {
|
|
654
|
-
if (!mapNeedsScope)
|
|
655
|
-
return [];
|
|
656
|
-
if (!baseScopeExpr)
|
|
657
|
-
ctx.usesInput.value = true;
|
|
658
|
-
const base = baseScopeExpr ? `${baseScopeExpr}.clone()` : "input.to_vec()";
|
|
659
|
-
return [
|
|
660
|
-
`${ind2}let mut ${mscopeVar}: Vec<(String, Value)> = ${base};`,
|
|
661
|
-
`${ind2}${mscopeVar}.push((${asKey}.to_string(), ${elVar}.clone()));`,
|
|
662
|
-
];
|
|
663
|
-
};
|
|
664
|
-
const guardLine = (ind2) => {
|
|
665
|
-
if (guardIR === undefined)
|
|
666
|
-
return [];
|
|
667
|
-
const g = `g_${s}`;
|
|
668
|
-
return [
|
|
669
|
-
`${ind2}let ${g} = (${emitExpr(guardIR, isScopeFree(guardIR) ? "sl_empty()" : mscopeVar)}).map_err(BehaviorError::from)?;`,
|
|
670
|
-
`${ind2}if !matches!(${g}, Value::Bool(true)) {`,
|
|
671
|
-
`${ind2} continue;`,
|
|
672
|
-
`${ind2}}`,
|
|
673
|
-
];
|
|
674
|
-
};
|
|
675
|
-
const portsLine = (ind2, portsVar) => {
|
|
676
|
-
const rows = op.ports.length === 0
|
|
677
|
-
? "Ok(Vec::new())"
|
|
678
|
-
: `Ok(vec![\n${op.ports
|
|
679
|
-
.map((p) => `${ind2} (${rustStrLit(p.name)}.to_string(), ${useVal(rSeqExpr(m.ports[p.name], mapCtx))}),`)
|
|
680
|
-
.join("\n")}\n${ind2}])`;
|
|
681
|
-
return [
|
|
682
|
-
`${ind2}let eval_ports_${s} = || -> Result<Vec<(String, Value)>, behavior_contracts::ExprFailure> { ${rows} };`,
|
|
683
|
-
`${ind2}let ${portsVar} = eval_ports_${s}().map_err(BehaviorError::from)?;`,
|
|
684
|
-
];
|
|
685
|
-
};
|
|
686
|
-
if (transform !== undefined) {
|
|
687
|
-
// 純式 map: handler も要素ごとの outcome も無い。要素式を `as` 束縛入りスコープで評価して積むだけ。
|
|
688
|
-
lines.push(`${ind}for ${elVar} in ${overVar}.iter() {`);
|
|
689
|
-
lines.push(...mscopeLine(`${ind} `), ...guardLine(`${ind} `));
|
|
690
|
-
lines.push(`${ind} ${collected}.push(${useVal(rSeqExpr(transform, mapCtx))});`);
|
|
691
|
-
lines.push(`${ind}}`);
|
|
692
|
-
const finish = [];
|
|
693
|
-
store(`Value::Arr(${collected})`, finish, ind);
|
|
694
|
-
lines.push(...finish);
|
|
695
|
-
return;
|
|
696
|
-
}
|
|
697
|
-
if (op.batched) {
|
|
698
|
-
const items = `items_${s}`;
|
|
699
|
-
lines.push(`${ind}let mut ${items}: Vec<Value> = Vec::new();`);
|
|
700
|
-
lines.push(`${ind}for (${elVar}_idx, ${elVar}) in ${overVar}.iter().enumerate() {`);
|
|
701
|
-
lines.push(...mscopeLine(`${ind} `), ...guardLine(`${ind} `), ...portsLine(`${ind} `, `ports_${s}`));
|
|
702
|
-
lines.push(`${ind} ${items}.push(Value::Obj(ports_${s}));`, `${ind} ${keptVar}.push(${elVar}_idx);`, `${ind}}`);
|
|
703
|
-
lines.push(`${ind}if !${items}.is_empty() {`);
|
|
704
|
-
lines.push(`${ind} let want_${s} = ${items}.len();`);
|
|
705
|
-
lines.push(`${ind} let batch_ports_${s} = vec![("items".to_string(), Value::Arr(std::mem::take(&mut ${items})))];`);
|
|
706
|
-
lines.push(`${ind} match handlers.exec_ctx(${nodeId}, ${comp}, &batch_ports_${s}, None) {`);
|
|
707
|
-
lines.push(`${ind} None => return Err(unknown_component(${comp})),`);
|
|
708
|
-
if (contFlag) {
|
|
709
|
-
lines.push(`${ind} Some(ExecOutcome::Error(_)) => { ${skipVar} = true; }`);
|
|
710
|
-
}
|
|
711
|
-
else {
|
|
712
|
-
lines.push(`${ind} Some(ExecOutcome::Error(e)) => {`);
|
|
713
|
-
lines.push(...rSeqPolicyThrow("e", id, meta, `${ind} `));
|
|
714
|
-
lines.push(`${ind} }`);
|
|
715
|
-
}
|
|
716
|
-
lines.push(`${ind} Some(ExecOutcome::Ok(v)) => match v {`);
|
|
717
|
-
lines.push(`${ind} Value::Arr(r) if r.len() == want_${s} => { ${collected} = r; }`);
|
|
718
|
-
lines.push(`${ind} _ => return Err(BehaviorError::new("MAP_BATCH_RESULT_MISMATCH", format!("map '${id}': batched handler must return a list aligned to items (want {want_${s}})"))),`);
|
|
719
|
-
lines.push(`${ind} },`);
|
|
720
|
-
lines.push(`${ind} }`);
|
|
721
|
-
lines.push(`${ind}}`);
|
|
722
|
-
}
|
|
723
|
-
else {
|
|
724
|
-
lines.push(`${ind}for (${elVar}_idx, ${elVar}) in ${overVar}.iter().enumerate() {`);
|
|
725
|
-
lines.push(...mscopeLine(`${ind} `), ...guardLine(`${ind} `), ...portsLine(`${ind} `, `ports_${s}`));
|
|
726
|
-
lines.push(`${ind} match handlers.exec_ctx(${nodeId}, ${comp}, &ports_${s}, Some(${elVar})) {`);
|
|
727
|
-
lines.push(`${ind} None => return Err(unknown_component(${comp})),`);
|
|
728
|
-
if (contFlag) {
|
|
729
|
-
lines.push(`${ind} Some(ExecOutcome::Error(_)) => { ${skipVar} = true; break; }`);
|
|
730
|
-
}
|
|
731
|
-
else {
|
|
732
|
-
lines.push(`${ind} Some(ExecOutcome::Error(e)) => {`);
|
|
733
|
-
lines.push(...rSeqPolicyThrow("e", id, meta, `${ind} `));
|
|
734
|
-
lines.push(`${ind} }`);
|
|
735
|
-
}
|
|
736
|
-
lines.push(`${ind} Some(ExecOutcome::Ok(v)) => { ${collected}.push(v); ${keptVar}.push(${elVar}_idx); }`);
|
|
737
|
-
lines.push(`${ind} }`);
|
|
738
|
-
lines.push(`${ind}}`);
|
|
739
|
-
}
|
|
740
|
-
const finish = [];
|
|
741
|
-
const fInd = contFlag ? `${ind} ` : ind;
|
|
742
|
-
if (m.into === undefined) {
|
|
743
|
-
store(`Value::Arr(${collected})`, finish, fInd);
|
|
744
|
-
}
|
|
745
|
-
else {
|
|
746
|
-
const aug = `aug_${s}`;
|
|
747
|
-
const intoKey = m.into;
|
|
748
|
-
// augmented-element build (object-check + shallow copy + into key). Shared by the kept branch and
|
|
749
|
-
// the connection guard-skip branch (#182 — skip fills into with the empty connection), so ONE template.
|
|
750
|
-
const cpBuild = (intoValExpr) => [
|
|
751
|
-
`${fInd} match oel_${s} {`,
|
|
752
|
-
`${fInd} Value::Obj(pairs) => {`,
|
|
753
|
-
`${fInd} let mut next: Vec<(String, Value)> = pairs.clone();`,
|
|
754
|
-
`${fInd} let __into = ${intoValExpr};`,
|
|
755
|
-
`${fInd} if let Some(slot) = next.iter_mut().find(|(kk, _)| kk == ${rustStrLit(intoKey)}) {`,
|
|
756
|
-
`${fInd} slot.1 = __into;`,
|
|
757
|
-
`${fInd} } else {`,
|
|
758
|
-
`${fInd} next.push((${rustStrLit(intoKey)}.to_string(), __into));`,
|
|
759
|
-
`${fInd} }`,
|
|
760
|
-
`${fInd} ${aug}.push(Value::Obj(next));`,
|
|
761
|
-
`${fInd} }`,
|
|
762
|
-
`${fInd} _ => return Err(BehaviorError::new("MAP_INTO_ELEMENT_NOT_OBJECT", format!("map '${id}': 'into' requires object elements (element {mj_${s}} is not an object)"))),`,
|
|
763
|
-
`${fInd} }`,
|
|
764
|
-
];
|
|
765
|
-
finish.push(`${fInd}let mut ${aug}: Vec<Value> = Vec::with_capacity(${overVar}.len());`);
|
|
766
|
-
finish.push(`${fInd}let mut mk_${s} = 0usize;`);
|
|
767
|
-
finish.push(`${fInd}for (mj_${s}, oel_${s}) in ${overVar}.iter().enumerate() {`);
|
|
768
|
-
finish.push(`${fInd} if mk_${s} < ${keptVar}.len() && ${keptVar}[mk_${s}] == mj_${s} {`);
|
|
769
|
-
finish.push(...cpBuild(`${collected}[mk_${s}].clone()`));
|
|
770
|
-
finish.push(`${fInd} mk_${s} += 1;`);
|
|
771
|
-
if (m.relationKind === "connection") {
|
|
772
|
-
finish.push(`${fInd} } else {`, ...cpBuild("behavior_contracts::skip_connection()"), `${fInd} }`);
|
|
773
|
-
}
|
|
774
|
-
else {
|
|
775
|
-
finish.push(`${fInd} } else {`, `${fInd} ${aug}.push(oel_${s}.clone());`, `${fInd} }`);
|
|
776
|
-
}
|
|
777
|
-
finish.push(`${fInd}}`);
|
|
778
|
-
store(`Value::Arr(${aug})`, finish, fInd);
|
|
779
|
-
}
|
|
780
|
-
if (contFlag) {
|
|
781
|
-
lines.push(`${ind}if !${skipVar} {`);
|
|
782
|
-
lines.push(...finish);
|
|
783
|
-
lines.push(`${ind}}`);
|
|
784
|
-
}
|
|
785
|
-
else {
|
|
786
|
-
lines.push(...finish);
|
|
787
|
-
}
|
|
788
|
-
}
|
|
789
|
-
/**
|
|
790
|
-
* emitRSeqOp — 逐次直線化された 1 op の文列。policy 検証 → skip 判定(parent 連鎖 / bindField)→
|
|
791
|
-
* 実行 → policy 解釈 → 結果ローカル格納(+進行形 scope 書き足し)。
|
|
792
|
-
*/
|
|
793
|
-
function emitRSeqOp(op, plan, ctx, lines) {
|
|
794
|
-
const i = op.index;
|
|
795
|
-
const meta = ctx.metas[i];
|
|
796
|
-
const o = plan.opsLiteral[i];
|
|
797
|
-
const id = o.id;
|
|
798
|
-
const local = ctx.local.get(id);
|
|
799
|
-
lines.push(` // ── op '${id}' (${op.kind === "cond" ? "cond" : op.kind === "map" ? `map ${op.component}` : op.component}${o.policy ? `, policy ${JSON.stringify(o.policy)}` : ""}) ──`);
|
|
800
|
-
if (typeof meta.policy === "object") {
|
|
801
|
-
lines.push(` return Err(BehaviorError::new("UNKNOWN_POLICY", ${rustStrLit(`unknown policy kind: ${meta.policy.invalid}`)}.to_string()));`);
|
|
802
|
-
return;
|
|
803
|
-
}
|
|
804
|
-
const canSkip = meta.canSkip || meta.alwaysSkip;
|
|
805
|
-
if (canSkip) {
|
|
806
|
-
lines.push(` let mut ${local}: Value = Value::Null;`, ` let mut ${ctx.okFlag.get(id)} = false;`);
|
|
807
|
-
}
|
|
808
|
-
if (meta.alwaysSkip) {
|
|
809
|
-
lines.push(` // parent '${o.parent}' runs later — unconditional skip.`);
|
|
810
|
-
return;
|
|
811
|
-
}
|
|
812
|
-
const guards = [];
|
|
813
|
-
if (o.parent !== null) {
|
|
814
|
-
const pMeta = ctx.metas[o.parent];
|
|
815
|
-
if (pMeta.canSkip || pMeta.alwaysSkip)
|
|
816
|
-
guards.push(ctx.okFlag.get(plan.opsLiteral[o.parent].id));
|
|
817
|
-
}
|
|
818
|
-
if (o.bindField !== undefined && o.parent !== null) {
|
|
819
|
-
const pLocal = ctx.local.get(plan.opsLiteral[o.parent].id);
|
|
820
|
-
const inner = [];
|
|
821
|
-
const ind = guards.length > 0 ? " " : " ";
|
|
822
|
-
inner.push(`${ind}if let Value::Obj(bf_pairs_${sanitize(id)}) = &${pLocal} {`);
|
|
823
|
-
inner.push(`${ind} if let Some((_, bf_val_${sanitize(id)})) = bf_pairs_${sanitize(id)}.iter().find(|(kk, _)| kk == ${rustStrLit(o.bindField)}) {`);
|
|
824
|
-
inner.push(`${ind} if !matches!(bf_val_${sanitize(id)}, Value::Null) {`);
|
|
825
|
-
emitRSeqExec(op, plan, ctx, inner, `${ind} `);
|
|
826
|
-
inner.push(`${ind} }`);
|
|
827
|
-
inner.push(`${ind} }`);
|
|
828
|
-
inner.push(`${ind}}`);
|
|
829
|
-
if (guards.length > 0) {
|
|
830
|
-
lines.push(` if ${guards[0]} {`);
|
|
831
|
-
lines.push(...inner);
|
|
832
|
-
lines.push(` }`);
|
|
833
|
-
}
|
|
834
|
-
else {
|
|
835
|
-
lines.push(...inner);
|
|
836
|
-
}
|
|
837
|
-
return;
|
|
838
|
-
}
|
|
839
|
-
if (guards.length > 0) {
|
|
840
|
-
lines.push(` if ${guards[0]} {`);
|
|
841
|
-
emitRSeqExec(op, plan, ctx, lines, " ");
|
|
842
|
-
lines.push(` }`);
|
|
843
|
-
return;
|
|
844
|
-
}
|
|
845
|
-
emitRSeqExec(op, plan, ctx, lines, " ");
|
|
846
|
-
}
|
|
847
|
-
/**
|
|
848
|
-
* emitSequentialRustFn — 逐次 plan の component を素の文列として綴じる(bc#75 の核)。
|
|
849
|
-
* run_plan / OpSpec Vec / base_scope closure / exec closure / per-op ID 探索は無い。
|
|
850
|
-
*/
|
|
851
|
-
function emitSequentialRustFn(plan, order) {
|
|
852
|
-
const metas = analyzeSequentialOps(plan.opsLiteral, order, plan.component);
|
|
853
|
-
const pos = new Array(plan.opsLiteral.length);
|
|
854
|
-
order.forEach((opIdx, k) => (pos[opIdx] = k));
|
|
855
|
-
const idToIndex = new Map();
|
|
856
|
-
plan.opsLiteral.forEach((o, i) => idToIndex.set(o.id, i));
|
|
857
|
-
const needScope = componentNeedsScope(plan);
|
|
858
|
-
const ids = plan.opsLiteral.map((o) => o.id);
|
|
859
|
-
const local = allocLocals("r_", ids);
|
|
860
|
-
const okFlag = allocLocals("ok_", ids);
|
|
861
|
-
const usesInput = { value: needScope }; // needScope なら scope = input.to_vec() で input を読む。
|
|
862
|
-
const usesHandlers = { value: false };
|
|
863
|
-
const usesRelationKind = { value: false };
|
|
864
|
-
const ctx = {
|
|
865
|
-
pos,
|
|
866
|
-
idToIndex,
|
|
867
|
-
metas,
|
|
868
|
-
local,
|
|
869
|
-
okFlag,
|
|
870
|
-
scopeVar: needScope ? "scope" : null,
|
|
871
|
-
currentPos: 0,
|
|
872
|
-
atOutput: false,
|
|
873
|
-
usesInput,
|
|
874
|
-
usesHandlers,
|
|
875
|
-
usesRelationKind,
|
|
876
|
-
};
|
|
877
|
-
// 本体を先に組み、input 参照の有無を確定させてからシグネチャを綴じる。
|
|
878
|
-
const bodyLines = [];
|
|
879
|
-
const lines = [];
|
|
880
|
-
if (needScope) {
|
|
881
|
-
bodyLines.push(` let mut scope: Vec<(String, Value)> = input.to_vec();`);
|
|
882
|
-
}
|
|
883
|
-
let unreachable = false;
|
|
884
|
-
for (const k of order.keys()) {
|
|
885
|
-
const opIdx = order[k];
|
|
886
|
-
ctx.currentPos = k;
|
|
887
|
-
if (unreachable)
|
|
888
|
-
break;
|
|
889
|
-
emitRSeqOp(plan.ops[opIdx], plan, ctx, bodyLines);
|
|
890
|
-
if (typeof metas[opIdx].policy === "object")
|
|
891
|
-
unreachable = true;
|
|
892
|
-
}
|
|
893
|
-
if (!unreachable) {
|
|
894
|
-
ctx.atOutput = true;
|
|
895
|
-
for (const i of order) {
|
|
896
|
-
const meta = metas[i];
|
|
897
|
-
if (!(meta.canSkip || meta.alwaysSkip))
|
|
898
|
-
continue;
|
|
899
|
-
const id = plan.opsLiteral[i].id;
|
|
900
|
-
bodyLines.push(` if !${okFlag.get(id)} {`);
|
|
901
|
-
bodyLines.push(` ${local.get(id)} = ${unproducedRust(plan.opsLiteral[i].relationKind, ctx)};`);
|
|
902
|
-
if (needScope)
|
|
903
|
-
bodyLines.push(` scope.push((${rustStrLit(id)}.to_string(), ${local.get(id)}.clone()));`);
|
|
904
|
-
bodyLines.push(` }`);
|
|
905
|
-
}
|
|
906
|
-
const outPiece = rSeqExpr(plan.component.output, ctx);
|
|
907
|
-
bodyLines.push(outPiece.fallible ? ` (${outPiece.expr}).map_err(BehaviorError::from)` : ` Ok(${outPiece.expr})`);
|
|
908
|
-
}
|
|
909
|
-
else {
|
|
910
|
-
// 到達不能で終わる(sole/last op が UNKNOWN_POLICY): 末尾 `return Err(..);` を tail 式へ
|
|
911
|
-
// 直す(clippy::needless_return 回避)。UNKNOWN_POLICY 行は必ず fn-body 直下の最後の文。
|
|
912
|
-
const last = bodyLines[bodyLines.length - 1];
|
|
913
|
-
const m = last.match(/^(\s*)return (.*);$/);
|
|
914
|
-
if (m)
|
|
915
|
-
bodyLines[bodyLines.length - 1] = `${m[1]}${m[2]}`;
|
|
916
|
-
}
|
|
917
|
-
const inputParam = usesInput.value ? "input" : "_input";
|
|
918
|
-
const handlerParam = usesHandlers.value ? "handlers" : "_handlers";
|
|
919
|
-
if (usesRelationKind.value)
|
|
920
|
-
relationKindNeeded = true;
|
|
921
|
-
if (usesHandlers.value)
|
|
922
|
-
execOutcomeNeeded = true;
|
|
923
|
-
lines.push(`fn run_${sanitize(plan.name)}<H: ComponentExec>(`);
|
|
924
|
-
lines.push(` ${handlerParam}: &mut H,`);
|
|
925
|
-
lines.push(` ${inputParam}: &[(String, Value)],`);
|
|
926
|
-
lines.push(`) -> Result<Value, BehaviorError> {`);
|
|
927
|
-
lines.push(...bodyLines);
|
|
928
|
-
lines.push(`}`);
|
|
929
|
-
return lines.join("\n");
|
|
930
|
-
}
|
|
931
|
-
/**
|
|
932
|
-
* emitPlanDrivenRustFn — 実並行 plan(複数 op の stage)の component を run_plan primitive で綴じる。
|
|
933
|
-
* run_behavior の実行フロー(results 蓄積 + base_scope + run_plan + skipped→unproduced + output 評価)を
|
|
934
|
-
* 生成コードに直線展開する。base_scope snapshot は実並行の決定性のためこの経路だけが組む(bc#75)。
|
|
935
|
-
*/
|
|
936
|
-
function emitComponentFn(plan) {
|
|
937
|
-
relationKindNeeded = true; // RunPlan 経路は skipped→unproduced で RelationKind を使う。
|
|
938
|
-
execOutcomeNeeded = true; // RunPlan 経路の exec は ExecOutcome を返す。
|
|
939
|
-
const arms = plan.ops.map(emitExecArm).join("\n");
|
|
940
|
-
const planExpr = plan.component.plan ? emitPlanLiteral(plan.component.plan) : "None";
|
|
941
|
-
const output = emitExpr(plan.component.output, SCOPE);
|
|
942
|
-
// 既定は注記の不在(unproduced_value(None) = Null)。rust の runner は `&str` 配列を持つので、
|
|
943
|
-
// 既定は空文字ではなく **"" 以外の綴りを作らない**ため `None` 相当の空スロットとして扱う。
|
|
944
|
-
const relationKinds = plan.opsLiteral.map((o) => (o.relationKind === "connection" ? "connection" : ""));
|
|
945
|
-
const relLit = `[${relationKinds.map(rustStrLit).join(", ")}]`;
|
|
946
|
-
// handler を1つも呼ばない component(cond のみ等)では `handlers` を `_handlers` に(未使用 lint 回避)。
|
|
947
|
-
// componentRef と map(要素 handler / batched handler)は handler を呼ぶ。
|
|
948
|
-
const usesHandlers = plan.ops.some((o) => o.kind === "componentRef" || o.kind === "map");
|
|
949
|
-
const handlerParam = usesHandlers ? "handlers" : "_handlers";
|
|
950
|
-
// output が scope を参照するか(純リテラル output では scope closure を作らない)。
|
|
951
|
-
const outputUsesScope = output.includes(SCOPE);
|
|
952
|
-
const outputScope = outputUsesScope
|
|
953
|
-
? ` let scope = || -> Vec<(String, Value)> {
|
|
954
|
-
let mut s: Vec<(String, Value)> = input.to_vec();
|
|
955
|
-
s.extend(results.iter().cloned());
|
|
956
|
-
s
|
|
957
|
-
};
|
|
958
|
-
`
|
|
959
|
-
: "";
|
|
960
|
-
// RunPlan 経路の arms は buildComponentPlan 由来の op.expr(emitModule の reset より前に生成)。
|
|
961
|
-
// json! 使用は実 emit テキストで確定させる(op.expr は我々の生成した rust 式で、user 由来 string は
|
|
962
|
-
// json!(...) の内側にあるため `json!(` の出現=json 使用で安全)。
|
|
963
|
-
if (arms.includes("json!(") || output.includes("json!("))
|
|
964
|
-
jsonMacroEmitted = true;
|
|
965
|
-
return `fn run_${sanitize(plan.name)}<H: ComponentExec>(
|
|
966
|
-
${handlerParam}: &mut H,
|
|
967
|
-
input: &[(String, Value)],
|
|
968
|
-
) -> Result<Value, BehaviorError> {
|
|
969
|
-
let ops: Vec<OpSpec> = ${emitOpsLiteral(plan)};
|
|
970
|
-
let relation_kinds: [&str; ${relationKinds.length}] = ${relLit};
|
|
971
|
-
let mut results: Vec<(String, Value)> = Vec::new();
|
|
972
|
-
let mut pending_err: Option<BehaviorError> = None;
|
|
973
|
-
|
|
974
|
-
let run = {
|
|
975
|
-
let results_cell = &mut results;
|
|
976
|
-
let err_cell = &mut pending_err;
|
|
977
|
-
// 各 exec 分岐は index で確定(node_kind ディスパッチではない)。scope() は「input +
|
|
978
|
-
// それまでの ok 結果」のその時点スナップ(run_behavior の base_scope と同一・決定的)。
|
|
979
|
-
let exec = |op: &OpSpec, _bound: Option<&Value>| -> ExecOutcome {
|
|
980
|
-
if err_cell.is_some() {
|
|
981
|
-
return ExecOutcome::Error("aborted".to_string());
|
|
982
|
-
}
|
|
983
|
-
let i = match ops.iter().position(|o| o.id == op.id) {
|
|
984
|
-
Some(i) => i,
|
|
985
|
-
None => {
|
|
986
|
-
*err_cell = Some(no_exec_arm(&op.id));
|
|
987
|
-
return ExecOutcome::Error("aborted".to_string());
|
|
988
|
-
}
|
|
989
|
-
};
|
|
990
|
-
let scope = || -> Vec<(String, Value)> {
|
|
991
|
-
let mut s: Vec<(String, Value)> = input.to_vec();
|
|
992
|
-
s.extend(results_cell.iter().cloned());
|
|
993
|
-
s
|
|
994
|
-
};
|
|
995
|
-
let _ = &scope;
|
|
996
|
-
${arms}
|
|
997
|
-
*err_cell = Some(no_exec_arm(&op.id));
|
|
998
|
-
ExecOutcome::Error("aborted".to_string())
|
|
999
|
-
};
|
|
1000
|
-
run_plan(${planExpr}, &ops, exec)
|
|
1001
|
-
};
|
|
1002
|
-
|
|
1003
|
-
// exec 内で立てた BehaviorError は run_plan が返す合成 OP_FAILED に優先する。
|
|
1004
|
-
if let Some(e) = pending_err {
|
|
1005
|
-
return Err(e);
|
|
1006
|
-
}
|
|
1007
|
-
let run = run?;
|
|
1008
|
-
|
|
1009
|
-
// Skip ノードは unproduced 表現を results に足す(output が ref/coalesce できるように)。
|
|
1010
|
-
for id_val in run.skipped.iter() {
|
|
1011
|
-
if let Some(pos) = ops.iter().position(|o| &o.id == id_val) {
|
|
1012
|
-
// 既定(注記の不在)は None = Null。Single variant は削除済み(1 つの意味に 1 つの綴り)。
|
|
1013
|
-
let kind = if relation_kinds[pos] == "connection" {
|
|
1014
|
-
Some(RelationKind::Connection)
|
|
1015
|
-
} else {
|
|
1016
|
-
None
|
|
1017
|
-
};
|
|
1018
|
-
if !results.iter().any(|(k, _)| k == id_val) {
|
|
1019
|
-
results.push((id_val.clone(), ${P}::unproduced_value(kind)));
|
|
1020
|
-
}
|
|
1021
|
-
}
|
|
1022
|
-
}
|
|
1023
|
-
${outputScope}
|
|
1024
|
-
Ok(${output}?)
|
|
1025
|
-
}`;
|
|
1026
|
-
}
|
|
1027
|
-
/** plan(ExecutionPlanSpec)リテラルを rust の `Some(&ExecutionPlanSpec{..})` へ(fully-qualified)。 */
|
|
1028
|
-
function emitPlanLiteral(plan) {
|
|
1029
|
-
const p = plan;
|
|
1030
|
-
const groups = (p.groups ?? []).map((g) => `vec![${g.join(", ")}]`).join(", ");
|
|
1031
|
-
const concurrency = p.concurrency ?? 1;
|
|
1032
|
-
return `Some(&behavior_contracts::ExecutionPlanSpec { groups: vec![${groups}], concurrency: ${concurrency} })`;
|
|
1033
|
-
}
|
|
1034
|
-
function emitComponent(plan, _ctx) {
|
|
1035
|
-
const order = sequentialOrder(plan.component);
|
|
1036
|
-
if (order !== null) {
|
|
1037
|
-
seqHelpersNeeded = true;
|
|
1038
|
-
return emitSequentialRustFn(plan, order);
|
|
1039
|
-
}
|
|
1040
|
-
planDrivenNeeded = true;
|
|
1041
|
-
baseNoExecArmNeeded = true; // base が RunPlan-path exec を emit する → no_exec_arm helper を使う。
|
|
1042
|
-
return emitComponentFn(plan);
|
|
1043
|
-
}
|
|
1044
|
-
/** 逐次経路の native helper(sl_head_or/sl_empty)が要るか(構造的トラッキング)。 */
|
|
1045
|
-
let seqHelpersNeeded = false;
|
|
1046
|
-
/** RunPlan 経路の import(run_plan/OpSpec)が要るか(base plan-driven or typed force)。 */
|
|
1047
|
-
let planDrivenNeeded = false;
|
|
1048
|
-
/** no_exec_arm helper が要るか(base plan-driven exec だけが使う — typed force では立てない)。 */
|
|
1049
|
-
let baseNoExecArmNeeded = false;
|
|
1050
|
-
/** RelationKind を import すべきか(unproduced_value を使うモジュールのみ)。 */
|
|
1051
|
-
let relationKindNeeded = false;
|
|
1052
|
-
/** ExecOutcome を import すべきか(handler を呼ぶモジュールのみ — cond-only は不要)。 */
|
|
1053
|
-
let execOutcomeNeeded = false;
|
|
1054
|
-
/** rustfmt の fits-on-one-line 規則を模倣した COMPONENT_NAMES 配列 emit。 */
|
|
1055
|
-
function componentNamesConst(names) {
|
|
1056
|
-
const items = names.map(rustStrLit);
|
|
1057
|
-
const oneLine = `pub const COMPONENT_NAMES: [&str; ${names.length}] = [${items.join(", ")}];`;
|
|
1058
|
-
if (oneLine.length <= 100)
|
|
1059
|
-
return oneLine;
|
|
1060
|
-
return `pub const COMPONENT_NAMES: [&str; ${names.length}] = [\n${items.map((s) => ` ${s},`).join("\n")}\n];`;
|
|
1061
|
-
}
|
|
1062
|
-
function emitModule(plans, ctx) {
|
|
1063
|
-
const { specVersions, componentNames, runtimeImport } = ctx;
|
|
1064
|
-
// buildComponentPlan(straightline.ts)は逐次経路が使わない op.expr を先に emit するため
|
|
1065
|
-
// jsonMacroEmitted を過大に立てる。ここ(実 emit 直前)で reset し、実際に emit される
|
|
1066
|
-
// emitComponent 内の emitExpr/jsonLit 呼び出しだけが json! 使用を立てるようにする(bc#75:
|
|
1067
|
-
// 逐次経路の全静的 component は json! を出さない)。
|
|
1068
|
-
jsonMacroEmitted = false;
|
|
1069
|
-
const fns = plans.map((p) => emitComponent(p, ctx)).join("\n\n");
|
|
1070
|
-
if (forceRunPlanImports) {
|
|
1071
|
-
// typed 層(rust-typed)の struct-native runner が実際に参照する import だけを force する
|
|
1072
|
-
//(typed body を scan して確定 — 過剰 import は clippy unused で落ちるため granular に)。
|
|
1073
|
-
if (forceRunPlanImports.runPlan) {
|
|
1074
|
-
planDrivenNeeded = true; // run_plan + OpSpec + no_exec_arm
|
|
1075
|
-
execOutcomeNeeded = true; // ExecOutcome
|
|
1076
|
-
}
|
|
1077
|
-
if (forceRunPlanImports.relationKind)
|
|
1078
|
-
relationKindNeeded = true;
|
|
1079
|
-
if (forceRunPlanImports.json)
|
|
1080
|
-
jsonMacroEmitted = true;
|
|
1081
|
-
}
|
|
1082
|
-
const usesJson = jsonMacroEmitted;
|
|
1083
|
-
const dispatchArms = plans
|
|
1084
|
-
.map((p) => ` ${rustStrLit(p.name)} => run_${sanitize(p.name)}(&mut self.handlers, input),`)
|
|
1085
|
-
.join("\n");
|
|
1086
|
-
// 依存 import の構造的判定(unused import は clippy/warn になるため使うものだけ列挙)。
|
|
1087
|
-
const runtimeItems = ["primitives", "BehaviorError", "ComponentExec", "SpecVersions", "Value"];
|
|
1088
|
-
if (execOutcomeNeeded)
|
|
1089
|
-
runtimeItems.push("ExecOutcome");
|
|
1090
|
-
if (relationKindNeeded)
|
|
1091
|
-
runtimeItems.push("RelationKind");
|
|
1092
|
-
if (planDrivenNeeded)
|
|
1093
|
-
runtimeItems.push("run_plan", "OpSpec");
|
|
1094
|
-
runtimeItems.sort();
|
|
1095
|
-
const runtimeUse = `use ${runtimeImport}::{\n ${runtimeItems.join(", ")},\n};`;
|
|
1096
|
-
// 逐次経路 native helper(bc#75)。sl_bind/sl_head_or/sl_empty は「local 直読み + input
|
|
1097
|
-
// fall-through + UNKNOWN_BINDING」を再現する(scope snapshot 無し)。concat/ref の field walk は
|
|
1098
|
-
// runtime SSoT(concat_native / ref_native)をそのまま呼ぶ(意味論の再実装をしない)。
|
|
1099
|
-
const seqHelpers = seqHelpersNeeded
|
|
1100
|
-
? `
|
|
1101
|
-
/// sl_empty — the empty scope handed to scope-free primitive exprs (bc#75: literal eval
|
|
1102
|
-
/// never reads scope, so no real snapshot is materialized — just an empty Vec).
|
|
1103
|
-
#[allow(dead_code)]
|
|
1104
|
-
fn sl_empty() -> Vec<(String, Value)> {
|
|
1105
|
-
Vec::new()
|
|
1106
|
-
}
|
|
1107
|
-
|
|
1108
|
-
/// sl_head_or — a skippable node's ref head: its local if produced, else the same-named
|
|
1109
|
-
/// input binding (scope-composition fall-through). UNKNOWN_BINDING comes from the runtime
|
|
1110
|
-
/// SSoT ref_native (expr.rs semantics), never re-implemented here.
|
|
1111
|
-
#[allow(dead_code)]
|
|
1112
|
-
fn sl_head_or(
|
|
1113
|
-
ok: bool,
|
|
1114
|
-
local: &Value,
|
|
1115
|
-
scope: &[(String, Value)],
|
|
1116
|
-
head: &str,
|
|
1117
|
-
) -> Result<Value, behavior_contracts::ExprFailure> {
|
|
1118
|
-
if ok {
|
|
1119
|
-
Ok(local.clone())
|
|
1120
|
-
} else {
|
|
1121
|
-
primitives::ref_native(&[head], scope)
|
|
1122
|
-
}
|
|
1123
|
-
}
|
|
1124
|
-
`
|
|
1125
|
-
: "";
|
|
1126
|
-
const noExecArm = baseNoExecArmNeeded
|
|
1127
|
-
? `
|
|
1128
|
-
/// 生成された exec 分岐に無い op(決定的には起きない — fail-closed)。
|
|
1129
|
-
fn no_exec_arm(id: &str) -> BehaviorError {
|
|
1130
|
-
BehaviorError::new("UNKNOWN_NODE_KIND", format!("op '{id}' has no generated exec arm (fail-closed)"))
|
|
1131
|
-
}
|
|
1132
|
-
`
|
|
1133
|
-
: "";
|
|
1134
|
-
return `// GENERATED by behavior-contracts common generator (bc#39/#75, straight-line) — DO NOT EDIT.
|
|
1135
|
-
// Input: portable component-graph IR only (scp-ir-architecture.md §5/§7.4).
|
|
1136
|
-
// This is the STRAIGHT-LINE codegen endpoint (typed-codegen.md §4.1 / bc#39 A2-rust): each
|
|
1137
|
-
// component is emitted as a NATIVE rust function that drives the plan via the run_plan
|
|
1138
|
-
// primitive and evaluates every port + output. SIMPLE expressions are DE-INTERPRETED to
|
|
1139
|
-
// native rust (Phase B win, largest in rust): concat -> primitives::concat_native (push_str,
|
|
1140
|
-
// no evaluate), ref/refOpt with a static path -> primitives::ref_native / ref_opt_native
|
|
1141
|
-
// (native scope walk, no evaluate/json!). Overflow/short-circuit operators still go through
|
|
1142
|
-
// the A0 evaluate-backed primitives (#36) so the fail-closed semantics stay single-sourced.
|
|
1143
|
-
// It does NOT go through run_behavior's tree-walk (no node_kind dispatch / no eval_ports
|
|
1144
|
-
// loop / no generic exec). Scope: componentRef + cond + simple Expression ports
|
|
1145
|
-
// (map/batched/concurrency -> A3, hydration -> A4). Handlers are ALWAYS injected at the
|
|
1146
|
-
// boundary; they are never generated.
|
|
1147
|
-
// The portable IR is NOT embedded: this module carries only EXPECTED_SPEC_VERSIONS +
|
|
1148
|
-
// COMPONENT_NAMES, so interpreting the IR here is physically impossible. The IR fingerprint is
|
|
1149
|
-
// a BUILD-TIME return on GenerateResult.fingerprint (NOT baked into the module, 0.5.0); the
|
|
1150
|
-
// fail-closed skew gate lives on the consumer/build side (compare it against fingerprint(live IR)).
|
|
1151
|
-
|
|
1152
|
-
// Generated per-component function names deterministically mirror the IR component
|
|
1153
|
-
// identifiers (which may be camelCase), so non_snake_case is expected and intentional.
|
|
1154
|
-
#![allow(non_snake_case)]
|
|
1155
|
-
// Skippable-node result locals are initialized to Value::Null and then overwritten on the
|
|
1156
|
-
// produced path OR by the unproduced writeback (bc#75) — the init is intentionally dead.
|
|
1157
|
-
#![allow(unused_assignments)]
|
|
1158
|
-
|
|
1159
|
-
${runtimeUse}
|
|
1160
|
-
${usesJson ? "use serde_json::json;\n" : ""}use std::sync::LazyLock;
|
|
1161
|
-
|
|
1162
|
-
/// Spec versions baked at generation time (fail-closed comparison on first use).
|
|
1163
|
-
pub const EXPECTED_SPEC_VERSIONS: [(&str, i64); 3] =
|
|
1164
|
-
[("behavior", ${specVersions.behavior}), ("expression", ${specVersions.expression}), ("plan", ${specVersions.plan})];
|
|
1165
|
-
|
|
1166
|
-
/// Component names exposed by bind(), in IR declaration order.
|
|
1167
|
-
${componentNamesConst(componentNames)}
|
|
1168
|
-
|
|
1169
|
-
/// First-use fail-closed module checks (#208 prepared-artifact discipline), forced by bind().
|
|
1170
|
-
static MODULE_CHECK: LazyLock<()> = LazyLock::new(check_generated_module);
|
|
1171
|
-
|
|
1172
|
-
fn runtime_spec_version(key: &str) -> i64 {
|
|
1173
|
-
match key {
|
|
1174
|
-
"behavior" => SpecVersions::BEHAVIOR,
|
|
1175
|
-
"expression" => SpecVersions::EXPRESSION,
|
|
1176
|
-
"plan" => SpecVersions::PLAN,
|
|
1177
|
-
other => {
|
|
1178
|
-
panic!("behavior-contracts generated module: unknown spec key '{other}' (fail-closed)")
|
|
1179
|
-
}
|
|
1180
|
-
}
|
|
1181
|
-
}
|
|
1182
|
-
|
|
1183
|
-
// First-use fail-closed checks (#208 prepared-artifact discipline). IR-independent checks
|
|
1184
|
-
// only (spec-version envelope pin) — the module has no embedded IR to self-check.
|
|
1185
|
-
fn check_generated_module() {
|
|
1186
|
-
for (key, want) in EXPECTED_SPEC_VERSIONS {
|
|
1187
|
-
let got = runtime_spec_version(key);
|
|
1188
|
-
if got != want {
|
|
1189
|
-
panic!("behavior-contracts generated module: spec-version skew for '{key}' (generated={want}, runtime={got}) — regenerate against this runtime (fail-closed)");
|
|
1190
|
-
}
|
|
1191
|
-
}
|
|
1192
|
-
}
|
|
1193
|
-
|
|
1194
|
-
/// UNKNOWN_COMPONENT の fail-closed error(run_behavior と同一コード・文言)。
|
|
1195
|
-
/// cond のみの component だけを含むモジュールでは未使用になり得る(generated helper)。
|
|
1196
|
-
#[allow(dead_code)]
|
|
1197
|
-
fn unknown_component(component: &str) -> BehaviorError {
|
|
1198
|
-
BehaviorError::new("UNKNOWN_COMPONENT", format!("component '{component}' has no handler (fail-closed)"))
|
|
1199
|
-
}
|
|
1200
|
-
${noExecArm}${seqHelpers}
|
|
1201
|
-
// ── straight-line component functions (no run_behavior tree-walk) ──────────────────
|
|
1202
|
-
${fns}
|
|
1203
|
-
|
|
1204
|
-
/// bind — inject handlers (boundary injection; catalog name → implementation) and get an
|
|
1205
|
-
/// executor. Each \`call\` runs the straight-line function for that component (plan via
|
|
1206
|
-
/// run_plan primitive + per-node native/primitive port eval + injected handler) — NOT the
|
|
1207
|
-
/// run_behavior tree-walk. Observationally equivalent to the run_behavior path: same values,
|
|
1208
|
-
/// same emitted op sequence, same Failure code. Forces the first-use fail-closed checks.
|
|
1209
|
-
pub fn bind<H: ComponentExec>(handlers: H) -> Bound<H> {
|
|
1210
|
-
LazyLock::force(&MODULE_CHECK);
|
|
1211
|
-
Bound { handlers }
|
|
1212
|
-
}
|
|
1213
|
-
|
|
1214
|
-
pub struct Bound<H: ComponentExec> {
|
|
1215
|
-
handlers: H,
|
|
1216
|
-
}
|
|
1217
|
-
|
|
1218
|
-
impl<H: ComponentExec> Bound<H> {
|
|
1219
|
-
pub fn call(&mut self, name: &str, input: &[(String, Value)]) -> Result<Value, BehaviorError> {
|
|
1220
|
-
match name {
|
|
1221
|
-
${dispatchArms}
|
|
1222
|
-
other => Err(BehaviorError::new(
|
|
1223
|
-
"UNKNOWN_ENTRY",
|
|
1224
|
-
format!("component '{other}' not found in this module (fail-closed)"),
|
|
1225
|
-
)),
|
|
1226
|
-
}
|
|
1227
|
-
}
|
|
1228
|
-
}
|
|
1229
|
-
`;
|
|
1230
|
-
}
|
|
1231
|
-
const dialect = {
|
|
1232
|
-
emitExpr,
|
|
1233
|
-
mapScopeVar: MAP_SCOPE,
|
|
1234
|
-
emitComponent,
|
|
1235
|
-
emitModule,
|
|
1236
|
-
// 式 emit は plan 構築時に走るので、json! 使用トラッカーの reset は plan 構築より前
|
|
1237
|
-
// (この hook)で行う。emitModule 内 reset では plan 構築中に立った flag を消してしまう。
|
|
1238
|
-
beginModule() {
|
|
1239
|
-
jsonMacroEmitted = false;
|
|
1240
|
-
seqHelpersNeeded = false;
|
|
1241
|
-
planDrivenNeeded = false;
|
|
1242
|
-
baseNoExecArmNeeded = false;
|
|
1243
|
-
relationKindNeeded = false;
|
|
1244
|
-
execOutcomeNeeded = false;
|
|
1245
|
-
},
|
|
1246
|
-
};
|
|
1247
|
-
/**
|
|
1248
|
-
* rust-typed(bc#48)が struct-native exec を綴じるために再利用する内部 emit ヘルパ。straight-line の
|
|
1249
|
-
* plan/handler-dispatch SSoT(run_plan primitive + handlers.exec_ctx + native/primitive port eval)を
|
|
1250
|
-
* そのまま使い、「結果を Value scope でなく struct scope に持つ」差分だけを typed 側で足すための seam。
|
|
1251
|
-
* primitive namespace(P)と ops/plan リテラル・式 emit・sanitize を共有する(意味論の二重実装を避ける)。
|
|
1252
|
-
* go の {@link goStraightlineInternals} と同型(seam が language-neutral であることの担保)。
|
|
1253
|
-
*/
|
|
13
|
+
/** rust の生成側(typed-native / shared typed helpers)が共有する命名ヘルパ。 */
|
|
1254
14
|
export const rustStraightlineInternals = {
|
|
1255
|
-
P,
|
|
1256
|
-
SCOPE,
|
|
1257
|
-
emitExpr,
|
|
1258
|
-
emitOpsLiteral,
|
|
1259
|
-
emitPlanLiteral,
|
|
1260
15
|
rustStrLit,
|
|
1261
16
|
sanitize,
|
|
1262
|
-
dialect,
|
|
1263
17
|
};
|
|
1264
18
|
//# sourceMappingURL=emit-shared-rust.js.map
|