behavior-contracts 0.11.22 → 0.12.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.
Files changed (76) hide show
  1. package/cli-contract.yaml +27 -20
  2. package/dist/behavior.d.ts +5 -0
  3. package/dist/behavior.d.ts.map +1 -1
  4. package/dist/behavior.js +11 -3
  5. package/dist/behavior.js.map +1 -1
  6. package/dist/cli.js +3 -3
  7. package/dist/cli.js.map +1 -1
  8. package/dist/generated/contract.d.ts.map +1 -1
  9. package/dist/generated/contract.js +2 -2
  10. package/dist/generated/contract.js.map +1 -1
  11. package/dist/generated/program.js +4 -4
  12. package/dist/generated/program.js.map +1 -1
  13. package/dist/generator/core.d.ts +13 -10
  14. package/dist/generator/core.d.ts.map +1 -1
  15. package/dist/generator/core.js.map +1 -1
  16. package/dist/generator/emit-native-dynamic.d.ts +203 -0
  17. package/dist/generator/emit-native-dynamic.d.ts.map +1 -0
  18. package/dist/generator/emit-native-dynamic.js +733 -0
  19. package/dist/generator/emit-native-dynamic.js.map +1 -0
  20. package/dist/generator/emit-native-php.d.ts +4 -0
  21. package/dist/generator/emit-native-php.d.ts.map +1 -0
  22. package/dist/generator/emit-native-php.js +668 -0
  23. package/dist/generator/emit-native-php.js.map +1 -0
  24. package/dist/generator/emit-native-python.d.ts +4 -0
  25. package/dist/generator/emit-native-python.d.ts.map +1 -0
  26. package/dist/generator/emit-native-python.js +592 -0
  27. package/dist/generator/emit-native-python.js.map +1 -0
  28. package/dist/generator/emit-php.d.ts +4 -0
  29. package/dist/generator/emit-php.d.ts.map +1 -1
  30. package/dist/generator/emit-php.js +6 -2
  31. package/dist/generator/emit-php.js.map +1 -1
  32. package/dist/generator/emit-python.d.ts +4 -0
  33. package/dist/generator/emit-python.d.ts.map +1 -1
  34. package/dist/generator/emit-python.js +2 -2
  35. package/dist/generator/emit-python.js.map +1 -1
  36. package/dist/generator/emit-shared-go-typed.d.ts +5 -78
  37. package/dist/generator/emit-shared-go-typed.d.ts.map +1 -1
  38. package/dist/generator/emit-shared-go-typed.js +8 -315
  39. package/dist/generator/emit-shared-go-typed.js.map +1 -1
  40. package/dist/generator/emit-shared-go.d.ts +12 -16
  41. package/dist/generator/emit-shared-go.d.ts.map +1 -1
  42. package/dist/generator/emit-shared-go.js +12 -1037
  43. package/dist/generator/emit-shared-go.js.map +1 -1
  44. package/dist/generator/emit-shared-rust-typed.d.ts +0 -93
  45. package/dist/generator/emit-shared-rust-typed.d.ts.map +1 -1
  46. package/dist/generator/emit-shared-rust-typed.js +7 -46
  47. package/dist/generator/emit-shared-rust-typed.js.map +1 -1
  48. package/dist/generator/emit-shared-rust.d.ts +5 -38
  49. package/dist/generator/emit-shared-rust.d.ts.map +1 -1
  50. package/dist/generator/emit-shared-rust.js +3 -1249
  51. package/dist/generator/emit-shared-rust.js.map +1 -1
  52. package/dist/generator/emit-typed-native-go.d.ts.map +1 -1
  53. package/dist/generator/emit-typed-native-go.js +31 -541
  54. package/dist/generator/emit-typed-native-go.js.map +1 -1
  55. package/dist/generator/emit-typed-native-rust.d.ts.map +1 -1
  56. package/dist/generator/emit-typed-native-rust.js +33 -455
  57. package/dist/generator/emit-typed-native-rust.js.map +1 -1
  58. package/dist/generator/index.d.ts +2 -0
  59. package/dist/generator/index.d.ts.map +1 -1
  60. package/dist/generator/index.js +9 -1
  61. package/dist/generator/index.js.map +1 -1
  62. package/dist/generator/native-coverage.d.ts +162 -0
  63. package/dist/generator/native-coverage.d.ts.map +1 -0
  64. package/dist/generator/native-coverage.js +412 -0
  65. package/dist/generator/native-coverage.js.map +1 -0
  66. package/dist/generator/native-expr.d.ts +1 -1
  67. package/dist/generator/native-expr.d.ts.map +1 -1
  68. package/dist/generator/straightline.d.ts +24 -6
  69. package/dist/generator/straightline.d.ts.map +1 -1
  70. package/dist/generator/straightline.js +79 -1
  71. package/dist/generator/straightline.js.map +1 -1
  72. package/dist/generator/typed.d.ts +6 -0
  73. package/dist/generator/typed.d.ts.map +1 -1
  74. package/dist/generator/typed.js +17 -0
  75. package/dist/generator/typed.js.map +1 -1
  76. package/package.json +1 -1
@@ -1,53 +1,17 @@
1
- import { mapTransformExpr } from "../behavior.js";
2
- import { emitDocLiteralCompact } from "./literal.js";
3
- import { sequentialOrder, analyzeSequentialOps, classifyExpr, isScopeFree, componentNeedsScope, } from "./straightline.js";
4
- /** runtime package alias(生成コード内)。emit-go.ts と同じ `dslcontracts`。 */
5
- const PKG = "dslcontracts";
6
- /** scope 式(RunPlan 経路のみ)。逐次経路は進行形 scope ローカル `scope` を使う。 */
7
- const SCOPE = "baseScope()";
8
- /** map 本体の要素 scope 式(RunPlan 経路の map 展開用 — 逐次経路は per-map ローカル)。 */
9
- const MAP_SCOPE = "mscope()";
10
1
  /**
11
- * 生成中 module の helper 要否の構造的トラッカー(emitModule が emit 前に reset)。
12
- * 生成テキストの substring 判定(文字列リテラル内容に誤反応)はしない。
2
+ * emit-shared-go.ts — the go expression dialect the go typed-native emitter (emit-typed-native-go.ts) builds
3
+ * its component plan with (`buildComponentPlan` + `emitExpr`), and the shared `sanitize`. It registers no
4
+ * emitter and binds no module.
13
5
  *
14
- * bc no-json invariant(オーナー指示・0.5.0): 直線生成 Go は encoding/json を import
15
- * しない。runtime import は JSON-free な coderuntime サブパッケージ(defaultRuntimeImport)。
16
- * IR リテラル(JObjOf / json.Number)は直線経路に存在せず、万一 leak しても coderuntime
17
- * には JNode が無いのでコンパイルが LOUD に落ちる(黙って通らない)。
18
- */
19
- const usage = {
20
- runPlan: false,
21
- slBind: false,
22
- slField: false,
23
- slCat: false,
24
- slEmpty: false,
25
- slPart: false, // RunPlan 経路の concat closure part(実並行のみ)
26
- unproduced: false,
27
- };
28
- /**
29
- * typed emitter(bc#47 go-typed)が base straight-line モジュールを同梱し、その上に **RunPlan-style の
30
- * struct-native runner** を積む場合、runner は `sync` と RunPlan-path native helper(slRef/slConcat/slPart/
31
- * slVal)を参照する。bc#75 で base は逐次 component から RunPlan-path helper を落とすため、typed 層は
32
- * この flag で base に「RunPlan-path helper と sync を必ず含めよ」と要求する(typed 経路の後方互換)。
33
- */
34
- let forceRunPlanHelpers = false;
35
- export function setGoForceRunPlanHelpers(on) {
36
- forceRunPlanHelpers = on;
37
- }
38
- function resetUsage() {
39
- for (const k of Object.keys(usage))
40
- usage[k] = false;
41
- }
42
- /**
43
- * bc: codegen は IR を出力してはならない(no-ir invariant)。
44
- * かつては非脱解釈の式(obj/arr/scalar/演算子被演算子)を IR リテラルとして埋め込み、
45
- * A0 primitive(EvalExpr 等)に実行時解釈させていた=インタプリタの松葉杖(=癌)。撤去する。
46
- * ここに来る式はまだネイティブ脱解釈されていない = ネイティブコードで emit すべき(次タスク)。
6
+ * bc no-json invariant(オーナー指示・0.5.0): 生成 Go は encoding/json を import しない。runtime import は
7
+ * JSON-free な coderuntime サブパッケージ(defaultRuntimeImport)。IR リテラル(JObjOf / json.Number)は
8
+ * 生成経路に存在せず、万一 leak しても coderuntime には JNode が無いのでコンパイルが LOUD に落ちる。
47
9
  */
48
- function lit(node) {
49
- throw new Error(`codegen no-ir invariant: refusing to emit IR literal for ${JSON.stringify(node).slice(0, 100)} — de-interpret this expression to native code (next task)`);
50
- }
10
+ import {} from "./straightline.js";
11
+ /** runtime package alias(生成コード内)。 */
12
+ const PKG = "dslcontracts";
13
+ /** map 本体(over/guard/ports)の要素 scope 式名(buildComponentPlan の mapScopeVar)。 */
14
+ const MAP_SCOPE = "mscope()";
51
15
  /** 被演算子 node を native ExprFn thunk(scope→評価済み Value)へ。primitive が短絡/評価順を制御。 */
52
16
  function thunk(node) {
53
17
  return `func(s *${PKG}.Obj) (${PKG}.Value, error) { return ${emitExpr(node, "s")} }`;
@@ -125,11 +89,9 @@ function emitExpr(node, scopeVar) {
125
89
  const arg = node[op];
126
90
  if (op === "ref" || op === "refOpt") {
127
91
  // RunPlan-path: native slRef/slRefOpt(slPart 枝で定義)を使う。逐次 slFieldVE ではない。
128
- usage.slPart = true;
129
92
  return `slRef${op === "refOpt" ? "Opt" : ""}(${emitStringPath(arg)}, ${scopeVar})`;
130
93
  }
131
94
  if (op === "concat") {
132
- usage.slPart = true;
133
95
  return `slConcat([]slPart{${emitConcatParts(arg, scopeVar)}}, ${scopeVar})`;
134
96
  }
135
97
  const prim = OP_PRIM[op];
@@ -158,1004 +120,17 @@ function emitConcatParts(arg, scopeVar) {
158
120
  void scopeVar;
159
121
  return arg.map((p) => `func(s *${PKG}.Obj) (${PKG}.Value, error) { return ${emitExpr(p, "s")} }`).join(", ");
160
122
  }
161
- /** dynamic 式に渡す scope 式(scope-free なら空 scope 定数)。 */
162
- function seqScope(node, ctx) {
163
- if (isScopeFree(node)) {
164
- usage.slEmpty = true;
165
- return "slEmpty()";
166
- }
167
- if (ctx.mapAs)
168
- return ctx.mapAs.mscopeVar;
169
- if (!ctx.scopeVar)
170
- throw new Error("straight-line go: scope-reading expr in a scopeless component (analysis bug)");
171
- return ctx.scopeVar;
172
- }
173
- /**
174
- * 静的 ref の head を配線解決した Go 式(`slVE` を返す)。ローカル直読み / input fallback /
175
- * UNKNOWN_BINDING。Go は多値 spread が「唯一引数」のときしか許さないため、逐次経路の式は
176
- * すべて単一の `slVE` 値({Val, Err})へ落とし、slField/slCat が合成できるようにする。
177
- */
178
- function seqRefHead(head, ctx) {
179
- if (ctx.mapAs && head === ctx.mapAs.as) {
180
- usage.slBind = true;
181
- return `slOkVE(${ctx.mapAs.elVar})`;
182
- }
183
- const idx = ctx.idToIndex.get(head);
184
- if (idx !== undefined) {
185
- const executedBefore = ctx.atOutput || ctx.pos[idx] < ctx.currentPos;
186
- if (executedBefore) {
187
- const meta = ctx.metas[idx];
188
- const local = ctx.local.get(head);
189
- usage.slBind = true;
190
- if (ctx.atOutput || !(meta.canSkip || meta.alwaysSkip))
191
- return `slOkVE(${local})`;
192
- return `slHeadOrVE(${ctx.okFlag.get(head)}, ${local}, input, ${JSON.stringify(head)})`;
193
- }
194
- }
195
- usage.slBind = true;
196
- return `slBindVE(input, ${JSON.stringify(head)})`;
197
- }
198
- /** 分類済み StaticExpr を Go 式へ(`slVE` を返す — 逐次経路のネイティブ inline)。 */
199
- function seqStatic(e, ctx) {
200
- switch (e.kind) {
201
- case "str":
202
- usage.slBind = true;
203
- return `slValVE(${JSON.stringify(e.value)})`;
204
- case "bool":
205
- usage.slBind = true;
206
- return `slValVE(${e.value ? "true" : "false"})`;
207
- case "null":
208
- usage.slBind = true;
209
- return `slValVE(nil)`;
210
- case "ref": {
211
- const head = seqRefHead(e.path[0], ctx);
212
- if (e.path.length === 1)
213
- return head;
214
- usage.slField = true;
215
- const segs = e.path.slice(1).map((p) => JSON.stringify(p)).join(", ");
216
- return `slFieldVE(${JSON.stringify(e.opt ? "refOpt" : "ref")}, ${head}, []string{${segs}})`;
217
- }
218
- case "concat": {
219
- usage.slCat = true;
220
- return `slCatVE(${e.parts.map((p) => seqStatic(p, ctx)).join(", ")})`;
221
- }
222
- case "dynamic":
223
- // primitive 経路は (Value, error) を返す — slVE2 で単一 slVE へ包む(唯一引数 spread)。
224
- usage.slBind = true;
225
- return `slVE2(${emitExpr(e.node, seqScope(e.node, ctx))})`;
226
- }
227
- }
228
- /** Expression IR → Go 式(逐次経路、`slVE` を返す)。 */
229
- function seqExpr(node, ctx) {
230
- return seqStatic(classifyExpr(node), ctx);
231
- }
232
123
  /** component 名を Go 関数名に使える形へ(決定的。名前一意は DUPLICATE_COMPONENT で保証)。 */
233
124
  function sanitize(name) {
234
125
  return name.replace(/[^A-Za-z0-9_]/g, "_");
235
126
  }
236
- /** node id 群 → 衝突しない決定的ローカル名。 */
237
- function allocLocals(prefix, ids) {
238
- const out = new Map();
239
- const taken = new Set();
240
- ids.forEach((id, i) => {
241
- let name = `${prefix}${sanitize(id)}`;
242
- if (taken.has(name))
243
- name = `${name}_${i}`;
244
- taken.add(name);
245
- out.set(id, name);
246
- });
247
- return out;
248
- }
249
- /** 未生成表現の Go 式(single → nil / connection → 空 connection Obj)。 */
250
- function unproducedGo(relationKind) {
251
- usage.unproduced = true;
252
- // 未生成の既定は null(注記の不在がそれ)。connection だけが別表現を持つ。
253
- return `${PKG}.UnproducedValue(${JSON.stringify(relationKind === "connection" ? "connection" : "")})`;
254
- }
255
- /** policy 解釈(fail/retry → OP_FAILED、continue → skip)。plan.go interpretOutcome と code/msg 一致。 */
256
- function seqPolicyThrow(outcomeVar, opId, meta, ind) {
257
- if (meta.policy === "retry") {
258
- return [
259
- `${ind}if ${outcomeVar}.IsError {`,
260
- `${ind}\treturn nil, ${PKG}.NewPlanFailure("OP_FAILED", fmt.Sprintf("operation '%s' failed under 'retry' policy (exhausted): %s", ${JSON.stringify(opId)}, ${outcomeVar}.Err))`,
261
- `${ind}}`,
262
- ];
263
- }
264
- // fail(既定・未知は手前で UNKNOWN_POLICY throw 済みで到達しない)。
265
- return [
266
- `${ind}if ${outcomeVar}.IsError {`,
267
- `${ind}\treturn nil, ${PKG}.NewPlanFailure("OP_FAILED", fmt.Sprintf("operation '%s' failed under 'fail' policy: %s", ${JSON.stringify(opId)}, ${outcomeVar}.Err))`,
268
- `${ind}}`,
269
- ];
270
- }
271
- /**
272
- * emitSeqOp — 逐次直線化された 1 op の文列。policy 検証 → skip 判定(parent 連鎖 / bindField)→
273
- * 実行(componentRef/map/cond)→ policy 解釈 → 結果ローカル格納(+進行形 scope 書き足し)。
274
- */
275
- function emitSeqOp(op, plan, ctx, lines) {
276
- const i = op.index;
277
- const meta = ctx.metas[i];
278
- const o = plan.opsLiteral[i];
279
- const id = o.id;
280
- const local = ctx.local.get(id);
281
- lines.push(`\t// ── op '${id}' (${op.kind === "cond" ? "cond" : op.kind === "map" ? `map ${op.component}` : op.component}${o.policy ? `, policy ${JSON.stringify(o.policy)}` : ""}) ──`);
282
- // policy 検証は skip 判定より先(plan.go preflightOp と同順)。
283
- if (typeof meta.policy === "object") {
284
- lines.push(`\treturn nil, ${PKG}.NewPlanFailure("UNKNOWN_POLICY", ${JSON.stringify(`unknown policy kind: ${meta.policy.invalid}`)})`);
285
- return;
286
- }
287
- const canSkip = meta.canSkip || meta.alwaysSkip;
288
- if (canSkip) {
289
- lines.push(`\tvar ${local} ${PKG}.Value = nil`, `\t${ctx.okFlag.get(id)} := false`);
290
- }
291
- if (meta.alwaysSkip) {
292
- lines.push(`\t// parent '${o.parent}' runs later — preflight sees an unsettled parent: unconditional skip.`);
293
- return;
294
- }
295
- const guards = [];
296
- if (o.parent !== null) {
297
- const pMeta = ctx.metas[o.parent];
298
- if (pMeta.canSkip || pMeta.alwaysSkip)
299
- guards.push(ctx.okFlag.get(plan.opsLiteral[o.parent].id));
300
- }
301
- if (o.bindField !== undefined && o.parent !== null) {
302
- const pLocal = ctx.local.get(plan.opsLiteral[o.parent].id);
303
- const bv = `bv_${sanitize(id)}`;
304
- const inner = [];
305
- const ind = guards.length > 0 ? "\t\t\t" : "\t\t";
306
- // parent result[bindField](parent が Obj のときのみ)。null/欠落なら skip。
307
- inner.push(`${ind}${bv}Obj, ${bv}IsObj := ${pLocal}.(*${PKG}.Obj)`);
308
- inner.push(`${ind}if ${bv}IsObj {`);
309
- inner.push(`${ind}\t${bv}, ${bv}Present := ${bv}Obj.Get(${JSON.stringify(o.bindField)})`);
310
- inner.push(`${ind}\tif ${bv}Present && ${bv} != nil {`);
311
- emitSeqExec(op, plan, ctx, inner, `${ind}\t\t`);
312
- inner.push(`${ind}\t}`);
313
- inner.push(`${ind}}`);
314
- if (guards.length > 0) {
315
- lines.push(`\tif ${guards[0]} {`);
316
- lines.push(...inner);
317
- lines.push(`\t}`);
318
- }
319
- else {
320
- lines.push(...inner);
321
- }
322
- return;
323
- }
324
- if (guards.length > 0) {
325
- lines.push(`\tif ${guards[0]} {`);
326
- emitSeqExec(op, plan, ctx, lines, "\t\t");
327
- lines.push(`\t}`);
328
- return;
329
- }
330
- emitSeqExec(op, plan, ctx, lines, "\t");
331
- }
332
- /** op 本体(handler 呼び + policy 解釈 + 結果格納)を indent 付きで emit。 */
333
- function emitSeqExec(op, plan, ctx, lines, ind) {
334
- const i = op.index;
335
- const meta = ctx.metas[i];
336
- const o = plan.opsLiteral[i];
337
- const id = o.id;
338
- const local = ctx.local.get(id);
339
- const canSkip = meta.canSkip || meta.alwaysSkip;
340
- // 成功時の格納(ローカル + 進行形 scope)。
341
- const store = (valueExpr, target, sind) => {
342
- if (canSkip) {
343
- target.push(`${sind}${local} = ${valueExpr}`, `${sind}${ctx.okFlag.get(id)} = true`);
344
- }
345
- else {
346
- target.push(`${sind}${local} := ${valueExpr}`, `${sind}_ = ${local}`);
347
- }
348
- if (ctx.scopeVar)
349
- target.push(`${sind}${ctx.scopeVar}.Set(${JSON.stringify(id)}, ${local})`);
350
- };
351
- if (op.kind === "cond") {
352
- const c = plan.component.body[i].cond;
353
- const node = { cond: [c.if, c.then, c.else] };
354
- const v = `v_${sanitize(id)}`;
355
- lines.push(`${ind}${v}, ${v}Err := ${emitExpr(node, seqScope(node, ctx))}`);
356
- lines.push(`${ind}if ${v}Err != nil {`, `${ind}\treturn nil, ${v}Err`, `${ind}}`);
357
- store(v, lines, ind);
358
- return;
359
- }
360
- if (op.kind === "map") {
361
- emitSeqMap(op, plan, ctx, lines, ind, store);
362
- return;
363
- }
364
- // componentRef: ports 構築 → handler 呼び → policy 解釈。
365
- const savedPos = ctx.currentPos;
366
- const portsVar = `ports_${sanitize(id)}`;
367
- lines.push(`${ind}${portsVar} := ${PKG}.NewObj()`);
368
- for (const p of op.ports) {
369
- const node = plan.component.body[i].ports[p.name];
370
- const pv = `pv_${sanitize(id)}_${p.name.replace(/[^A-Za-z0-9_]/g, "_")}`;
371
- lines.push(`${ind}${pv} := ${seqExpr(node, ctx)}`);
372
- lines.push(`${ind}if ${pv}.Err != nil {`, `${ind}\treturn nil, ${pv}.Err`, `${ind}}`);
373
- lines.push(`${ind}${portsVar}.Set(${JSON.stringify(p.name)}, ${pv}.Val)`);
374
- }
375
- ctx.currentPos = savedPos;
376
- const oc = `o_${sanitize(id)}`;
377
- lines.push(`${ind}${oc}, ${oc}Resolved := ${PKG}.ExecHandler(handlers, ${JSON.stringify(id)}, ${JSON.stringify(op.component)}, ${portsVar}, nil)`);
378
- lines.push(`${ind}if !${oc}Resolved {`, `${ind}\treturn nil, ${PKG}.NewBehaviorFailure("UNKNOWN_COMPONENT", "component '${op.component}' has no handler (fail-closed)")`, `${ind}}`);
379
- if (meta.policy === "continue") {
380
- lines.push(`${ind}if !${oc}.IsError {`);
381
- store(`${oc}.Ok`, lines, `${ind}\t`);
382
- lines.push(`${ind}}`);
383
- }
384
- else {
385
- lines.push(...seqPolicyThrow(oc, id, meta, ind));
386
- store(`${oc}.Ok`, lines, ind);
387
- }
388
- }
389
- /** emitSeqMap — map ノードの逐次直線展開(RunPlan 経路と観測等価。per-expr scope snapshot 無し)。 */
390
- function emitSeqMap(op, plan, ctx, lines, ind, store) {
391
- const i = op.index;
392
- const meta = ctx.metas[i];
393
- const m = plan.component.body[i].map;
394
- const id = op.id;
395
- const s = sanitize(id);
396
- const comp = JSON.stringify(op.component);
397
- const asKey = JSON.stringify(m.as);
398
- const guardIR = m.when === undefined ? undefined : { cond: [m.when, true, false] };
399
- // 純式 map(Component 呼びなし)の要素式。反復は構造層の責務なので Expression IR に反復演算子は無い。
400
- const transform = mapTransformExpr(m);
401
- const mapNeedsScope = (guardIR !== undefined && !isScopeFree(guardIR)) ||
402
- (transform !== undefined && !isScopeFree(transform)) ||
403
- Object.keys(m.ports ?? {}).some((k) => {
404
- const cls = classifyExpr(m.ports[k]);
405
- const needs = (e) => e.kind === "dynamic" ? !isScopeFree(e.node) : e.kind === "concat" ? e.parts.some(needs) : false;
406
- return needs(cls);
407
- });
408
- const baseScopeExpr = ctx.scopeVar;
409
- const elVar = `el_${s}`;
410
- const mscopeVar = `mscope_${s}`;
411
- const overVar = `over_${s}`;
412
- const keptVar = `kept_${s}`;
413
- const collected = `collected_${s}`;
414
- const contFlag = meta.policy === "continue";
415
- const skipVar = `skip_${s}`;
416
- const mapCtx = { ...ctx, mapAs: { as: m.as, elVar, mscopeVar } };
417
- lines.push(`${ind}${overVar}VE := ${seqExpr(m.over, ctx)}`);
418
- lines.push(`${ind}if ${overVar}VE.Err != nil {`, `${ind}\treturn nil, ${overVar}VE.Err`, `${ind}}`);
419
- lines.push(`${ind}${overVar}, ${overVar}IsArr := ${overVar}VE.Val.([]${PKG}.Value)`);
420
- lines.push(`${ind}if !${overVar}IsArr {`, `${ind}\treturn nil, ${PKG}.NewBehaviorFailure("MAP_OVER_NOT_ARRAY", "map '${id}': 'over' did not evaluate to an array")`, `${ind}}`);
421
- if (transform === undefined) {
422
- lines.push(`${ind}${keptVar} := make([]int, 0, len(${overVar}))`);
423
- if (contFlag)
424
- lines.push(`${ind}${skipVar} := false`);
425
- }
426
- const mscopeLines = (ind2) => {
427
- if (!mapNeedsScope)
428
- return [];
429
- return [
430
- `${ind2}${mscopeVar} := ${PKG}.NewObj()`,
431
- ...(baseScopeExpr
432
- ? [`${ind2}for _, ${mscopeVar}k := range ${baseScopeExpr}.Keys {`, `${ind2}\t${mscopeVar}.Set(${mscopeVar}k, ${baseScopeExpr}.Vals[${mscopeVar}k])`, `${ind2}}`]
433
- : [`${ind2}for _, ${mscopeVar}k := range input.Keys {`, `${ind2}\t${mscopeVar}.Set(${mscopeVar}k, input.Vals[${mscopeVar}k])`, `${ind2}}`]),
434
- `${ind2}${mscopeVar}.Set(${asKey}, ${elVar})`,
435
- ];
436
- };
437
- const guardLines = (ind2) => {
438
- if (guardIR === undefined)
439
- return [];
440
- const g = `g_${s}`;
441
- return [
442
- `${ind2}${g}, ${g}Err := ${emitExpr(guardIR, isScopeFree(guardIR) ? "slEmpty()" : mscopeVar)}`,
443
- `${ind2}if ${g}Err != nil {`,
444
- `${ind2}\treturn nil, ${g}Err`,
445
- `${ind2}}`,
446
- `${ind2}if ${g} != true {`,
447
- `${ind2}\tcontinue`,
448
- `${ind2}}`,
449
- ];
450
- };
451
- const portLines = (ind2, portsVar) => {
452
- const out = [`${ind2}${portsVar} := ${PKG}.NewObj()`];
453
- for (const p of op.ports) {
454
- const pv = `pv_${s}_${p.name.replace(/[^A-Za-z0-9_]/g, "_")}`;
455
- out.push(`${ind2}${pv} := ${seqExpr(m.ports[p.name], mapCtx)}`);
456
- out.push(`${ind2}if ${pv}.Err != nil {`, `${ind2}\treturn nil, ${pv}.Err`, `${ind2}}`);
457
- out.push(`${ind2}${portsVar}.Set(${JSON.stringify(p.name)}, ${pv}.Val)`);
458
- }
459
- return out;
460
- };
461
- if (transform !== undefined) {
462
- const tv = `tv_${s}`;
463
- lines.push(`${ind}${collected} := make([]${PKG}.Value, 0, len(${overVar}))`);
464
- lines.push(`${ind}for _, ${elVar} := range ${overVar} {`);
465
- lines.push(...mscopeLines(`${ind}\t`), ...guardLines(`${ind}\t`));
466
- lines.push(`${ind}\t${tv} := ${seqExpr(transform, mapCtx)}`);
467
- lines.push(`${ind}\tif ${tv}.Err != nil {`, `${ind}\t\treturn nil, ${tv}.Err`, `${ind}\t}`);
468
- lines.push(`${ind}\t${collected} = append(${collected}, ${tv}.Val)`, `${ind}}`);
469
- const finish = [];
470
- store(collected, finish, ind);
471
- lines.push(...finish);
472
- return;
473
- }
474
- if (op.batched) {
475
- const items = `items_${s}`;
476
- lines.push(`${ind}${items} := make([]${PKG}.Value, 0, len(${overVar}))`);
477
- lines.push(`${ind}for ${elVar}Idx, ${elVar} := range ${overVar} {`);
478
- lines.push(...mscopeLines(`${ind}\t`), ...guardLines(`${ind}\t`), ...portLines(`${ind}\t`, `ports_${s}`));
479
- lines.push(`${ind}\t${items} = append(${items}, ports_${s})`, `${ind}\t${keptVar} = append(${keptVar}, ${elVar}Idx)`, `${ind}}`);
480
- lines.push(`${ind}var ${collected} []${PKG}.Value`);
481
- lines.push(`${ind}if len(${items}) == 0 {`, `${ind}\t${collected} = []${PKG}.Value{}`, `${ind}} else {`);
482
- const bp = `bp_${s}`;
483
- lines.push(`${ind}\t${bp} := ${PKG}.NewObj()`, `${ind}\t${bp}.Set("items", ${items})`);
484
- const oc = `mo_${s}`;
485
- lines.push(`${ind}\t${oc}, ${oc}Resolved := ${PKG}.ExecHandler(handlers, ${JSON.stringify(id)}, ${comp}, ${bp}, nil)`);
486
- lines.push(`${ind}\tif !${oc}Resolved {`, `${ind}\t\treturn nil, ${PKG}.NewBehaviorFailure("UNKNOWN_COMPONENT", "component '${op.component}' has no handler (fail-closed)")`, `${ind}\t}`);
487
- if (contFlag) {
488
- lines.push(`${ind}\tif ${oc}.IsError {`, `${ind}\t\t${skipVar} = true`, `${ind}\t} else {`);
489
- lines.push(...batchOk(oc, collected, items, id, s, `${ind}\t\t`));
490
- lines.push(`${ind}\t}`);
491
- }
492
- else {
493
- lines.push(...seqPolicyThrow(oc, id, meta, `${ind}\t`));
494
- lines.push(...batchOk(oc, collected, items, id, s, `${ind}\t`));
495
- }
496
- lines.push(`${ind}}`);
497
- }
498
- else {
499
- lines.push(`${ind}${collected} := make([]${PKG}.Value, 0, len(${overVar}))`);
500
- lines.push(`${ind}for ${elVar}Idx, ${elVar} := range ${overVar} {`);
501
- lines.push(...mscopeLines(`${ind}\t`), ...guardLines(`${ind}\t`), ...portLines(`${ind}\t`, `ports_${s}`));
502
- const oc = `mo_${s}`;
503
- lines.push(`${ind}\t${oc}, ${oc}Resolved := ${PKG}.ExecHandler(handlers, ${JSON.stringify(id)}, ${comp}, ports_${s}, ${elVar})`);
504
- lines.push(`${ind}\tif !${oc}Resolved {`, `${ind}\t\treturn nil, ${PKG}.NewBehaviorFailure("UNKNOWN_COMPONENT", "component '${op.component}' has no handler (fail-closed)")`, `${ind}\t}`);
505
- if (contFlag) {
506
- lines.push(`${ind}\tif ${oc}.IsError {`, `${ind}\t\t${skipVar} = true`, `${ind}\t\tbreak`, `${ind}\t}`);
507
- }
508
- else {
509
- lines.push(...seqPolicyThrow(oc, id, meta, `${ind}\t`));
510
- }
511
- lines.push(`${ind}\t${collected} = append(${collected}, ${oc}.Ok)`, `${ind}\t${keptVar} = append(${keptVar}, ${elVar}Idx)`, `${ind}}`);
512
- }
513
- // finish(into zip-attach or collected)— continue はエラー時 skip して未生成。
514
- const finish = [];
515
- const fInd = contFlag ? `${ind}\t` : ind;
516
- if (m.into === undefined) {
517
- store(collected, finish, fInd);
518
- }
519
- else {
520
- const aug = `aug_${s}`;
521
- // augmented-element build (object-check + shallow copy + into key). Shared by the kept branch and
522
- // the connection guard-skip branch (#182), so the check + copy live in ONE template.
523
- const cpBuild = (intoValExpr) => [
524
- `${fInd}\t\toelObj_${s}, isObj_${s} := oel_${s}.(*${PKG}.Obj)`,
525
- `${fInd}\t\tif !isObj_${s} {`,
526
- `${fInd}\t\t\treturn nil, ${PKG}.NewBehaviorFailure("MAP_INTO_ELEMENT_NOT_OBJECT", fmt.Sprintf("map '${id}': 'into' requires object elements (element %d is not an object)", mj_${s}))`,
527
- `${fInd}\t\t}`,
528
- `${fInd}\t\tcp_${s} := ${PKG}.NewObj()`,
529
- `${fInd}\t\tfor _, fk_${s} := range oelObj_${s}.Keys {`,
530
- `${fInd}\t\t\tcp_${s}.Set(fk_${s}, oelObj_${s}.Vals[fk_${s}])`,
531
- `${fInd}\t\t}`,
532
- `${fInd}\t\tcp_${s}.Set(${JSON.stringify(m.into)}, ${intoValExpr})`,
533
- `${fInd}\t\t${aug} = append(${aug}, cp_${s})`,
534
- ];
535
- finish.push(`${fInd}${aug} := make([]${PKG}.Value, 0, len(${overVar}))`);
536
- finish.push(`${fInd}mk_${s} := 0`);
537
- finish.push(`${fInd}for mj_${s}, oel_${s} := range ${overVar} {`);
538
- finish.push(`${fInd}\tif mk_${s} < len(${keptVar}) && ${keptVar}[mk_${s}] == mj_${s} {`);
539
- finish.push(...cpBuild(`${collected}[mk_${s}]`));
540
- finish.push(`${fInd}\t\tmk_${s}++`);
541
- if (m.relationKind === "connection") {
542
- // guard-skip over a connection-typed into → empty connection (unproducedGo — SSoT).
543
- finish.push(`${fInd}\t} else {`, ...cpBuild(unproducedGo(m.relationKind)), `${fInd}\t}`);
544
- }
545
- else {
546
- finish.push(`${fInd}\t} else {`, `${fInd}\t\t${aug} = append(${aug}, oel_${s})`, `${fInd}\t}`);
547
- }
548
- finish.push(`${fInd}}`);
549
- store(aug, finish, fInd);
550
- }
551
- if (contFlag) {
552
- lines.push(`${ind}if !${skipVar} {`);
553
- lines.push(...finish);
554
- lines.push(`${ind}}`);
555
- }
556
- else {
557
- lines.push(...finish);
558
- }
559
- }
560
- /** batched handler の ok を collected へ(長さ整合検査つき)。 */
561
- function batchOk(oc, collected, items, id, s, ind) {
562
- return [
563
- `${ind}r_batch_${s}, isArr_${s} := ${oc}.Ok.([]${PKG}.Value)`,
564
- `${ind}if !isArr_${s} || len(r_batch_${s}) != len(${items}) {`,
565
- `${ind}\treturn nil, ${PKG}.NewBehaviorFailure("MAP_BATCH_RESULT_MISMATCH", fmt.Sprintf("map '${id}': batched handler must return a list aligned to items (want %d)", len(${items})))`,
566
- `${ind}}`,
567
- `${ind}${collected} = r_batch_${s}`,
568
- ];
569
- }
570
- /**
571
- * emitSequentialGoFn — 逐次 plan の component を素の文列として綴じる(bc#75 の核)。
572
- * RunPlan / OpSpec テーブル / baseScope snapshot / exec closure / per-op ID 探索は無い。
573
- */
574
- function emitSequentialGoFn(plan, order) {
575
- const metas = analyzeSequentialOps(plan.opsLiteral, order, plan.component);
576
- const pos = new Array(plan.opsLiteral.length);
577
- order.forEach((opIdx, k) => (pos[opIdx] = k));
578
- const idToIndex = new Map();
579
- plan.opsLiteral.forEach((o, i) => idToIndex.set(o.id, i));
580
- const needScope = componentNeedsScope(plan);
581
- const ids = plan.opsLiteral.map((o) => o.id);
582
- const local = allocLocals("r_", ids);
583
- const okFlag = allocLocals("ok_", ids);
584
- const ctx = {
585
- pos,
586
- idToIndex,
587
- metas,
588
- local,
589
- okFlag,
590
- scopeVar: needScope ? "scope" : null,
591
- currentPos: 0,
592
- atOutput: false,
593
- };
594
- const lines = [];
595
- lines.push(`func run_${sanitize(plan.name)}(handlers ${PKG}.ComponentExec, input *${PKG}.Obj) (${PKG}.Value, error) {`);
596
- lines.push(`\tif input == nil {`, `\t\tinput = ${PKG}.NewObj()`, `\t}`);
597
- if (needScope) {
598
- // 進行形 scope: input のコピー(bind 側で input は private コピー済み)へノード結果を書き足す。
599
- lines.push(`\tscope := ${PKG}.NewObj()`);
600
- lines.push(`\tfor _, k := range input.Keys {`, `\t\tscope.Set(k, input.Vals[k])`, `\t}`);
601
- }
602
- let unreachable = false;
603
- for (const k of order.keys()) {
604
- const opIdx = order[k];
605
- ctx.currentPos = k;
606
- if (unreachable)
607
- break;
608
- emitSeqOp(plan.ops[opIdx], plan, ctx, lines);
609
- if (typeof metas[opIdx].policy === "object")
610
- unreachable = true;
611
- }
612
- if (!unreachable) {
613
- ctx.atOutput = true;
614
- for (const i of order) {
615
- const meta = metas[i];
616
- if (!(meta.canSkip || meta.alwaysSkip))
617
- continue;
618
- const id = plan.opsLiteral[i].id;
619
- lines.push(`\tif !${okFlag.get(id)} {`);
620
- lines.push(`\t\t${local.get(id)} = ${unproducedGo(plan.opsLiteral[i].relationKind)}`);
621
- if (needScope)
622
- lines.push(`\t\tscope.Set(${JSON.stringify(id)}, ${local.get(id)})`);
623
- lines.push(`\t}`);
624
- }
625
- const outNode = plan.component.output;
626
- lines.push(`\toutVE := ${seqExpr(outNode, ctx)}`);
627
- lines.push(`\tif outVE.Err != nil {`, `\t\treturn nil, outVE.Err`, `\t}`);
628
- lines.push(`\treturn outVE.Val, nil`);
629
- }
630
- lines.push(`}`);
631
- return lines.join("\n");
632
- }
633
- // ══════════════════════════════════════════════════════════════════════════════════
634
- // RunPlan 経路(実並行 plan のみ — bounded 並行の意味論 SSoT を保持)
635
- // ══════════════════════════════════════════════════════════════════════════════════
636
- /** ops リテラル(RunPlan に渡す []OpSpec の Go リテラル)を綴じる。 */
637
- function emitOpsLiteral(plan) {
638
- const rows = plan.opsLiteral.map((o) => {
639
- const parts = [`ID: ${JSON.stringify(o.id)}`, `Parent: ${o.parent === null ? "-1" : String(o.parent)}`];
640
- if (o.bindField !== undefined)
641
- parts.push(`BindField: ${JSON.stringify(o.bindField)}, HasBindField: true`);
642
- if (o.relationKind !== undefined)
643
- parts.push(`RelationKind: ${JSON.stringify(o.relationKind)}`);
644
- if (o.policy !== undefined)
645
- parts.push(`Policy: ${JSON.stringify(o.policy)}, HasPolicy: true`);
646
- return `\t\t{${parts.join(", ")}},`;
647
- });
648
- return `[]${PKG}.OpSpec{\n${rows.join("\n")}\n\t}`;
649
- }
650
- /** 1ノードの exec 分岐本体(index で分岐 — nodeKind ディスパッチではない)。 */
651
- function emitExecArm(op) {
652
- if (op.kind === "map")
653
- return emitMapArm(op);
654
- if (op.kind === "cond") {
655
- return `\t\tif i == ${op.index} {
656
- \t\t\tv, err := ${op.expr}
657
- \t\t\tif err != nil {
658
- \t\t\t\treturn abort(idx, err)
659
- \t\t\t}
660
- \t\t\treturn ${PKG}.OkOutcome(v)
661
- \t\t}`;
662
- }
663
- const portEvals = op.ports
664
- .map((p) => `\t\t\t${goPortVar(p.name)}, err := ${p.expr}
665
- \t\t\tif err != nil {
666
- \t\t\t\treturn abort(idx, err)
667
- \t\t\t}
668
- \t\t\tports.Set(${JSON.stringify(p.name)}, ${goPortVar(p.name)})`)
669
- .join("\n");
670
- const body = op.ports.length === 0 ? "" : `\n${portEvals}`;
671
- return `\t\tif i == ${op.index} {
672
- \t\t\tports := ${PKG}.NewObj()${body}
673
- \t\t\toutcome, resolved := ${PKG}.ExecHandler(handlers, ${JSON.stringify(op.id)}, ${JSON.stringify(op.component)}, ports, nil)
674
- \t\t\tif !resolved {
675
- \t\t\t\treturn abort(idx, ${PKG}.NewBehaviorFailure("UNKNOWN_COMPONENT", "component '${op.component}' has no handler (fail-closed)"))
676
- \t\t\t}
677
- \t\t\treturn outcome
678
- \t\t}`;
679
- }
680
- /** port ローカル変数名(Go 識別子として安全)。 */
681
- function goPortVar(name) {
682
- return `pv_${name.replace(/[^A-Za-z0-9_]/g, "_")}`;
683
- }
684
- /** map arm の要素 ports 構築(RunPlan 経路)。 */
685
- function emitMapPortEvals(op) {
686
- if (op.ports.length === 0)
687
- return `\t\t\t\tports := ${PKG}.NewObj()`;
688
- const lines = op.ports
689
- .map((p) => `\t\t\t\t${goPortVar(p.name)}, err := ${p.expr}
690
- \t\t\t\tif err != nil {
691
- \t\t\t\t\treturn abort(idx, err)
692
- \t\t\t\t}
693
- \t\t\t\tports.Set(${JSON.stringify(p.name)}, ${goPortVar(p.name)})`)
694
- .join("\n");
695
- return `\t\t\t\tports := ${PKG}.NewObj()\n${lines}`;
696
- }
697
- /** emitMapArm — map ノードの直線展開(RunPlan 経路)。 */
698
- function emitMapArm(op) {
699
- const comp = JSON.stringify(op.component);
700
- const nodeId = JSON.stringify(op.id);
701
- const asKey = JSON.stringify(op.as);
702
- const guardBlock = op.guard === undefined
703
- ? ""
704
- : `\n\t\t\t\tgkeep, gerr := ${op.guard}
705
- \t\t\t\tif gerr != nil {
706
- \t\t\t\t\treturn abort(idx, gerr)
707
- \t\t\t\t}
708
- \t\t\t\tif gkeep != true {
709
- \t\t\t\t\tcontinue
710
- \t\t\t\t}`;
711
- const mscopeDef = `\t\t\t\tmel := el
712
- \t\t\t\tmscope := func() *${PKG}.Obj {
713
- \t\t\t\t\ts := ${SCOPE}
714
- \t\t\t\t\ts.Set(${asKey}, mel)
715
- \t\t\t\t\treturn s
716
- \t\t\t\t}
717
- \t\t\t\t_ = mscope`;
718
- // augmented-element build (shallow copy + into key). Shared by the kept branch and the connection
719
- // guard-skip branch (#182), so the object-check + copy live in ONE template.
720
- const cpBuild = (intoValExpr) => `\t\t\t\t\toelObj, isObj := oel.(*${PKG}.Obj)
721
- \t\t\t\t\tif !isObj {
722
- \t\t\t\t\t\treturn abort(idx, ${PKG}.NewBehaviorFailure("MAP_INTO_ELEMENT_NOT_OBJECT", fmt.Sprintf("map '${op.id}': 'into' requires object elements (element %d is not an object)", mj)))
723
- \t\t\t\t\t}
724
- \t\t\t\t\tcp := ${PKG}.NewObj()
725
- \t\t\t\t\tfor _, fk := range oelObj.Keys {
726
- \t\t\t\t\t\tcp.Set(fk, oelObj.Vals[fk])
727
- \t\t\t\t\t}
728
- \t\t\t\t\tcp.Set(${JSON.stringify(op.into)}, ${intoValExpr})
729
- \t\t\t\t\taugmented = append(augmented, cp)`;
730
- // guard-skip: connection-typed into → empty connection (unproducedGo — SSoT); else pass through.
731
- const intoSkip = op.relationKind === "connection"
732
- ? `\t\t\t\t} else {\n${cpBuild(unproducedGo(op.relationKind))}\n\t\t\t\t}`
733
- : `\t\t\t\t} else {\n\t\t\t\t\taugmented = append(augmented, oel)\n\t\t\t\t}`;
734
- const intoTail = op.into === undefined
735
- ? `\t\t\treturn ${PKG}.OkOutcome(collected)`
736
- : `\t\t\taugmented := make([]${PKG}.Value, 0, len(overArr))
737
- \t\t\tmk := 0
738
- \t\t\tfor mj, oel := range overArr {
739
- \t\t\t\tif mk < len(keptIdx) && keptIdx[mk] == mj {
740
- ${cpBuild("collected[mk]")}
741
- \t\t\t\t\tmk++
742
- ${intoSkip}
743
- \t\t\t}
744
- \t\t\treturn ${PKG}.OkOutcome(augmented)`;
745
- // 純式 map(#222/#225): handler も要素ごとの outcome も無い(RunPlan 経路も同じ規律)。
746
- const transformBody = op.transform === undefined
747
- ? undefined
748
- : `\t\t\tcollected := make([]${PKG}.Value, 0, len(overArr))
749
- \t\t\tfor _, el := range overArr {
750
- ${mscopeDef}${guardBlock}
751
- \t\t\t\ttv, tvErr := ${op.transform}
752
- \t\t\t\tif tvErr != nil {
753
- \t\t\t\t\treturn abort(idx, tvErr)
754
- \t\t\t\t}
755
- \t\t\t\tcollected = append(collected, tv)
756
- \t\t\t}
757
- \t\t\treturn ${PKG}.OkOutcome(collected)`;
758
- const body = transformBody !== undefined ? transformBody : op.batched
759
- ? `\t\t\titems := make([]${PKG}.Value, 0, len(overArr))
760
- \t\t\tfor mi, el := range overArr {
761
- ${mscopeDef}${guardBlock}
762
- ${emitMapPortEvals(op)}
763
- \t\t\t\titems = append(items, ports)
764
- \t\t\t\tkeptIdx = append(keptIdx, mi)
765
- \t\t\t}
766
- \t\t\tvar collected []${PKG}.Value
767
- \t\t\tif len(items) == 0 {
768
- \t\t\t\tcollected = []${PKG}.Value{}
769
- \t\t\t} else {
770
- \t\t\t\tbatchPorts := ${PKG}.NewObj()
771
- \t\t\t\tbatchPorts.Set("items", items)
772
- \t\t\t\toutcome, resolved := ${PKG}.ExecHandler(handlers, ${nodeId}, ${comp}, batchPorts, nil)
773
- \t\t\t\tif !resolved {
774
- \t\t\t\t\treturn abort(idx, ${PKG}.NewBehaviorFailure("UNKNOWN_COMPONENT", "component '${op.component}' has no handler (fail-closed)"))
775
- \t\t\t\t}
776
- \t\t\t\tif outcome.IsError {
777
- \t\t\t\t\treturn outcome
778
- \t\t\t\t}
779
- \t\t\t\tr, isArr := outcome.Ok.([]${PKG}.Value)
780
- \t\t\t\tif !isArr || len(r) != len(items) {
781
- \t\t\t\t\treturn abort(idx, ${PKG}.NewBehaviorFailure("MAP_BATCH_RESULT_MISMATCH", fmt.Sprintf("map '${op.id}': batched handler must return a list aligned to items (want %d)", len(items))))
782
- \t\t\t\t}
783
- \t\t\t\tcollected = r
784
- \t\t\t}
785
- ${intoTail}`
786
- : `\t\t\tcollected := make([]${PKG}.Value, 0, len(overArr))
787
- \t\t\tfor mi, el := range overArr {
788
- ${mscopeDef}${guardBlock}
789
- ${emitMapPortEvals(op)}
790
- \t\t\t\toutcome, resolved := ${PKG}.ExecHandler(handlers, ${nodeId}, ${comp}, ports, mel)
791
- \t\t\t\tif !resolved {
792
- \t\t\t\t\treturn abort(idx, ${PKG}.NewBehaviorFailure("UNKNOWN_COMPONENT", "component '${op.component}' has no handler (fail-closed)"))
793
- \t\t\t\t}
794
- \t\t\t\tif outcome.IsError {
795
- \t\t\t\t\treturn outcome
796
- \t\t\t\t}
797
- \t\t\t\tcollected = append(collected, outcome.Ok)
798
- \t\t\t\tkeptIdx = append(keptIdx, mi)
799
- \t\t\t}
800
- ${intoTail}`;
801
- return `\t\tif i == ${op.index} {
802
- \t\t\toverVal, overErr := ${op.over}
803
- \t\t\tif overErr != nil {
804
- \t\t\t\treturn abort(idx, overErr)
805
- \t\t\t}
806
- \t\t\toverArr, isArr := overVal.([]${PKG}.Value)
807
- \t\t\tif !isArr {
808
- \t\t\t\treturn abort(idx, ${PKG}.NewBehaviorFailure("MAP_OVER_NOT_ARRAY", "map '${op.id}': 'over' did not evaluate to an array"))
809
- \t\t\t}
810
- \t\t\tkeptIdx := make([]int, 0, len(overArr))
811
- ${body}
812
- \t\t}`;
813
- }
814
- /**
815
- * emitPlanDrivenGoFn — 実並行 plan(複数 op の stage)の component を RunPlan primitive で綴じる。
816
- * bounded 並行・Skip 伝播・Policy Kind の意味論 SSoT は RunPlan が保持する。per-op exec は index で
817
- * 確定した分岐(`for k := range ops` 線形 ID 探索は idx 解決に一度だけ・switch はハードコード)。
818
- */
819
- function emitPlanDrivenGoFn(plan) {
820
- usage.runPlan = true;
821
- usage.unproduced = true;
822
- const arms = plan.ops.map(emitExecArm).join("\n");
823
- const planLiteral = plan.component.plan
824
- ? emitBehaviorPlanLiteral(plan.component.plan)
825
- : `(*${PKG}.ExecutionPlanSpec)(nil)`;
826
- const output = emitExpr(plan.component.output, SCOPE);
827
- // arms は buildComponentPlan 由来の op.expr(emitModule の reset より前に生成)。slPart/slConcat の
828
- // 使用は実 emit テキストで確定させる。json.Number の追跡は撤去済み(bc no-json invariant: 直線経路は
829
- // IR リテラルを emit しないので encoding/json import は常に不要 — 万一 leak すれば coderuntime に
830
- // JNode/json.Number の受け皿が無くコンパイルが LOUD に落ちる)。
831
- // slRef/slRefOpt/slConcat/slPart は RunPlan-path helper(usage.slPart 枝で定義)。逐次 slFieldVE
832
- // (usage.slField 枝・slVE 型必須)ではないので slPart を立てる。
833
- if (/slRef(Opt)?\(|slConcat\(\[\]slPart\{/.test(arms))
834
- usage.slPart = true;
835
- const relationKinds = plan.opsLiteral.map((o) => (o.relationKind === "connection" ? "connection" : ""));
836
- const rkLiteral = `[]string{${relationKinds.map((r) => JSON.stringify(r)).join(", ")}}`;
837
- return `func run_${sanitize(plan.name)}(handlers ${PKG}.ComponentExec, input *${PKG}.Obj) (${PKG}.Value, error) {
838
- \tops := ${emitOpsLiteral(plan)}
839
- \tif input == nil {
840
- \t\tinput = ${PKG}.NewObj()
841
- \t}
842
- \tresults := ${PKG}.NewObj()
843
- \tvar resultsMu sync.Mutex
844
- \t// baseScope = input params + accumulated ok results (snapshot at call time) — REAL
845
- \t// concurrency needs a deterministic scope snapshot per exec (bc#75: only this path).
846
- \tbaseScope := func() *${PKG}.Obj {
847
- \t\ts := ${PKG}.NewObj()
848
- \t\tfor _, k := range input.Keys {
849
- \t\t\ts.Set(k, input.Vals[k])
850
- \t\t}
851
- \t\tresultsMu.Lock()
852
- \t\tfor _, k := range results.Keys {
853
- \t\t\ts.Set(k, results.Vals[k])
854
- \t\t}
855
- \t\tresultsMu.Unlock()
856
- \t\treturn s
857
- \t}
858
- \trelationKinds := ${rkLiteral}
859
- \texecErrs := make([]error, len(ops))
860
- \tabort := func(idx int, err error) ${PKG}.ExecOutcome {
861
- \t\texecErrs[idx] = err
862
- \t\treturn ${PKG}.ErrOutcome("aborted")
863
- \t}
864
- \t// per-op exec は op の index(RunPlan が渡す OpSpec の位置)で確定する switch。opIndex は
865
- \t// ops リテラルと 1:1 なので線形 ID 探索は不要(RunPlan が visit 順に呼ぶ i を使う)。
866
- \texecByIndex := func(idx int) ${PKG}.ExecOutcome {
867
- \t\ti := idx
868
- ${arms}
869
- \t\treturn abort(idx, ${PKG}.NewBehaviorFailure("UNKNOWN_NODE_KIND", "op has no generated exec arm (fail-closed)"))
870
- \t}
871
- \topIndex := make(map[string]int, len(ops))
872
- \tfor k := range ops {
873
- \t\topIndex[ops[k].ID] = k
874
- \t}
875
- \twrappedExec := func(op ${PKG}.OpSpec, bound ${PKG}.Value) ${PKG}.ExecOutcome {
876
- \t\t_ = bound
877
- \t\toutcome := execByIndex(opIndex[op.ID])
878
- \t\tif !outcome.IsError {
879
- \t\t\tresultsMu.Lock()
880
- \t\t\tresults.Set(op.ID, outcome.Ok)
881
- \t\t\tresultsMu.Unlock()
882
- \t\t}
883
- \t\treturn outcome
884
- \t}
885
- \tplan := ${planLiteral}
886
- \trun, err := ${PKG}.RunPlan(plan, ops, wrappedExec)
887
- \tif firstErr := ${PKG}.FirstExecErrInVisitOrder(execErrs, plan, len(ops), err); firstErr != nil {
888
- \t\treturn nil, firstErr
889
- \t}
890
- \tif err != nil {
891
- \t\treturn nil, err
892
- \t}
893
- \tfor _, id := range run.Skipped {
894
- \t\tif _, present := results.Get(id); present {
895
- \t\t\tcontinue
896
- \t\t}
897
- \t\tresults.Set(id, ${PKG}.UnproducedValue(relationKinds[opIndex[id]]))
898
- \t}
899
- \treturn ${output}
900
- }`;
901
- }
902
- /** behavior plan({groups, concurrency})を *ExecutionPlanSpec Go リテラルへ。 */
903
- function emitBehaviorPlanLiteral(plan) {
904
- const p = plan;
905
- const groups = p.groups ?? [];
906
- const groupsLit = `[][]int{${groups.map((g) => `{${g.join(", ")}}`).join(", ")}}`;
907
- const conc = p.concurrency ?? 1;
908
- return `&${PKG}.ExecutionPlanSpec{Groups: ${groupsLit}, Concurrency: ${conc}}`;
909
- }
910
- function emitComponent(plan, _ctx) {
911
- const order = sequentialOrder(plan.component);
912
- if (order !== null)
913
- return emitSequentialGoFn(plan, order);
914
- return emitPlanDrivenGoFn(plan);
915
- }
916
- function emitModule(plans, ctx) {
917
- const { specVersions, componentNames, runtimeImport } = ctx;
918
- const names = componentNames.map((n) => JSON.stringify(n)).join(", ");
919
- // buildComponentPlan は逐次経路が使わない op.expr を先に emit するため usage を過大に立てる。
920
- // 実 emit 直前で reset し、emitComponent 内の呼び出しだけが import/helper 要否を立てるようにする。
921
- resetUsage();
922
- const fns = plans.map((p) => emitComponent(p, ctx)).join("\n\n");
923
- if (forceRunPlanHelpers) {
924
- // typed 層(go-typed)の struct-native runner は RunPlan-path helper(slRef/slRefOpt/slConcat/slPart/
925
- // slVal)と sync を参照する。それらは usage.slPart 枝(slPart type + slConcat + slRef/slRefOpt/
926
- // slRefWalk)に集約されている。逐次 slVE 系(slField=slFieldVE 等)は typed runner が使わないので
927
- // 立てない(誤って slFieldVE を emit すると slVE 型が要る)。
928
- usage.slPart = true;
929
- usage.runPlan = true; // sync import
930
- }
931
- const dispatchArms = plans
932
- .map((p) => `\tif name == ${JSON.stringify(p.name)} {\n\t\treturn run_${sanitize(p.name)}(handlers, input)\n\t}`)
933
- .join("\n");
934
- // 生成 helper(構造的トラッキングで必要なものだけ emit)。
935
- const helpers = [];
936
- helpers.push(`// slVal wraps a native Go literal as a (Value, error) result (dynamic/RunPlan path).
937
- func slVal(v ${PKG}.Value) (${PKG}.Value, error) { return v, nil }`);
938
- if (usage.slEmpty)
939
- helpers.push(`// slEmpty is the empty scope constant passed to scope-free primitive exprs (bc#75:
940
- // literal eval never reads scope, so no snapshot is materialized).
941
- func slEmpty() *${PKG}.Obj { return ${PKG}.NewObj() }`);
942
- if (usage.slBind)
943
- helpers.push(`// slVE packs a single (Value, error) result so statically-wired inline exprs compose as
944
- // one expression (bc#75: Go only spreads a multi-return call as the sole argument).
945
- type slVE struct {
946
- \tVal ${PKG}.Value
947
- \tErr error
948
- }
949
- // slVE2 folds a primitive (Value, error) return into an slVE (dynamic residual exprs).
950
- func slVE2(v ${PKG}.Value, err error) slVE { return slVE{Val: v, Err: err} }
951
- // slValVE wraps a native literal (string/bool/null) — no evaluate needed.
952
- func slValVE(v ${PKG}.Value) slVE { return slVE{Val: v} }
953
- // slOkVE wraps an already-resolved local (statically-wired ref read: no scope snapshot).
954
- func slOkVE(v ${PKG}.Value) slVE { return slVE{Val: v} }
955
- // slBindVE reads a scope-bound head directly (UNKNOWN_BINDING matches expr.go).
956
- func slBindVE(scope *${PKG}.Obj, head string) slVE {
957
- \tv, ok := scope.Get(head)
958
- \tif !ok {
959
- \t\treturn slVE{Err: ${PKG}.NewExprFailure("UNKNOWN_BINDING", "unknown binding: "+head)}
960
- \t}
961
- \treturn slVE{Val: v}
962
- }
963
- // slHeadOrVE — a skippable node's ref head: its local if produced, else the same-named input
964
- // binding (scope-composition fall-through), else UNKNOWN_BINDING (expr.go semantics).
965
- func slHeadOrVE(ok bool, local ${PKG}.Value, scope *${PKG}.Obj, head string) slVE {
966
- \tif ok {
967
- \t\treturn slVE{Val: local}
968
- \t}
969
- \treturn slBindVE(scope, head)
970
- }`);
971
- if (usage.slField)
972
- helpers.push(`// slFieldVE walks a static field path over an already-resolved head (bc#75: the head is a
973
- // local read, not a scope walk). Reproduces expr.go ref/refOpt field semantics.
974
- func slFieldVE(op string, head slVE, path []string) slVE {
975
- \tif head.Err != nil {
976
- \t\treturn head
977
- \t}
978
- \tcur := head.Val
979
- \tfor _, seg := range path {
980
- \t\tif cur == nil {
981
- \t\t\tif op == "refOpt" {
982
- \t\t\t\treturn slVE{Val: nil}
983
- \t\t\t}
984
- \t\t\treturn slVE{Err: ${PKG}.NewExprFailure("NULL_REF", "null intermediate at ."+seg+" (use ?.)")}
985
- \t\t}
986
- \t\to, ok := cur.(*${PKG}.Obj)
987
- \t\tif !ok {
988
- \t\t\treturn slVE{Err: ${PKG}.NewExprFailure("TYPE_MISMATCH", "cannot access ."+seg+" on "+${PKG}.TypeName(cur))}
989
- \t\t}
990
- \t\tnext, present := o.Get(seg)
991
- \t\tif !present {
992
- \t\t\treturn slVE{Err: ${PKG}.NewExprFailure("MISSING_PROP", "missing property ."+seg)}
993
- \t\t}
994
- \t\tcur = next
995
- \t}
996
- \treturn slVE{Val: cur}
997
- }`);
998
- if (usage.slCat)
999
- helpers.push(`// slCatVE concatenates already-evaluated string parts natively (bc#75: no closures, no
1000
- // slPart func values). Same "all-eval then string check" order + TYPE_MISMATCH as expr.go.
1001
- func slCatVE(parts ...slVE) slVE {
1002
- \tvar b strings.Builder
1003
- \tfor _, p := range parts {
1004
- \t\tif p.Err != nil {
1005
- \t\t\treturn p
1006
- \t\t}
1007
- \t\ts, ok := p.Val.(string)
1008
- \t\tif !ok {
1009
- \t\t\treturn slVE{Err: ${PKG}.NewExprFailure("TYPE_MISMATCH", "concat: strings only (got "+${PKG}.TypeName(p.Val)+"; no implicit toString)")}
1010
- \t\t}
1011
- \t\tb.WriteString(s)
1012
- \t}
1013
- \treturn slVE{Val: b.String()}
1014
- }`);
1015
- if (usage.slPart)
1016
- helpers.push(`// slPart is a self-evaluating concat part (RunPlan path only — real-concurrency plans).
1017
- type slPart = func(scope *${PKG}.Obj) (${PKG}.Value, error)
1018
- // slConcat concatenates n>=2 string parts (RunPlan path); arity<2 is invalid IR.
1019
- func slConcat(parts []slPart, scope *${PKG}.Obj) (${PKG}.Value, error) {
1020
- \tif len(parts) < 2 {
1021
- \t\treturn nil, ${PKG}.NewExprFailure("INVALID_NODE", fmt.Sprintf("concat expects >= 2 args, got %d", len(parts)))
1022
- \t}
1023
- \tvar b strings.Builder
1024
- \tfor _, part := range parts {
1025
- \t\tv, err := part(scope)
1026
- \t\tif err != nil {
1027
- \t\t\treturn nil, err
1028
- \t\t}
1029
- \t\ts, ok := v.(string)
1030
- \t\tif !ok {
1031
- \t\t\treturn nil, ${PKG}.NewExprFailure("TYPE_MISMATCH", "concat: strings only (got "+${PKG}.TypeName(v)+"; no implicit toString)")
1032
- \t\t}
1033
- \t\tb.WriteString(s)
1034
- \t}
1035
- \treturn b.String(), nil
1036
- }
1037
- // slRef/slRefOpt: RunPlan-path native scope/field walk (expr.go ref semantics).
1038
- func slRef(path []string, scope *${PKG}.Obj) (${PKG}.Value, error) { return slRefWalk("ref", path, scope) }
1039
- func slRefOpt(path []string, scope *${PKG}.Obj) (${PKG}.Value, error) { return slRefWalk("refOpt", path, scope) }
1040
- func slRefWalk(op string, path []string, scope *${PKG}.Obj) (${PKG}.Value, error) {
1041
- \tif len(path) == 0 {
1042
- \t\treturn nil, ${PKG}.NewExprFailure("INVALID_NODE", op+" expects a non-empty string path")
1043
- \t}
1044
- \tcur, ok := scope.Get(path[0])
1045
- \tif !ok {
1046
- \t\treturn nil, ${PKG}.NewExprFailure("UNKNOWN_BINDING", "unknown binding: "+path[0])
1047
- \t}
1048
- \tfor _, seg := range path[1:] {
1049
- \t\tif cur == nil {
1050
- \t\t\tif op == "refOpt" {
1051
- \t\t\t\treturn nil, nil
1052
- \t\t\t}
1053
- \t\t\treturn nil, ${PKG}.NewExprFailure("NULL_REF", "null intermediate at ."+seg+" (use ?.)")
1054
- \t\t}
1055
- \t\to, isObj := cur.(*${PKG}.Obj)
1056
- \t\tif !isObj {
1057
- \t\t\treturn nil, ${PKG}.NewExprFailure("TYPE_MISMATCH", "cannot access ."+seg+" on "+${PKG}.TypeName(cur))
1058
- \t\t}
1059
- \t\tnext, present := o.Get(seg)
1060
- \t\tif !present {
1061
- \t\t\treturn nil, ${PKG}.NewExprFailure("MISSING_PROP", "missing property ."+seg)
1062
- \t\t}
1063
- \t\tcur = next
1064
- \t}
1065
- \treturn cur, nil
1066
- }`);
1067
- // 依存 import の構造的判定(bc no-json invariant: encoding/json は決して emit しない)。
1068
- const imports = [];
1069
- imports.push(`\t"fmt"`);
1070
- if (usage.slCat || usage.slPart)
1071
- imports.push(`\t"strings"`);
1072
- if (usage.runPlan)
1073
- imports.push(`\t"sync"`);
1074
- imports.push(``);
1075
- imports.push(`\t${PKG} ${JSON.stringify(runtimeImport)}`);
1076
- return `// GENERATED by behavior-contracts common generator (bc#38/#75, straight-line) — DO NOT EDIT.
1077
- // Input: portable component-graph IR only (scp-ir-architecture.md §5/§7.4).
1078
- // This is the STRAIGHT-LINE codegen endpoint (typed-codegen.md §4.1): each component is
1079
- // emitted as STATIC native Go (bc#75). Strictly-sequential plans compile to plain
1080
- // statements in dependency order — no RunPlan, no []OpSpec table, no per-op ID search, no
1081
- // baseScope() per-expression snapshots. Statically-wired refs read locals directly; static
1082
- // concat is a flat slCat(...) over already-evaluated values. Only plans with REAL bounded
1083
- // concurrency (multi-op stages) drive the RunPlan primitive (semantics SSoT), and there the
1084
- // per-op exec is index-resolved (no linear ID scan). Fail-closed operator semantics
1085
- // (overflow arithmetic, strict-bool short-circuit, obj/arr construction, checked literals)
1086
- // still route through the A0 Prim* primitives (#36) — the semantics SSoT stays single-
1087
- // sourced. Handlers are ALWAYS injected at the boundary; they are never generated.
1088
- // The portable IR is NOT embedded: this module carries only ExpectedSpecVersions +
1089
- // ComponentNames (the IR fingerprint is a BUILD-TIME return on GenerateResult.fingerprint,
1090
- // not baked into the module — the skew gate lives on the consumer/build side, 0.5.0).
1091
-
1092
- package behaviors
1093
-
1094
- import (
1095
- ${imports.join("\n")}
1096
- )
1097
-
1098
- // ExpectedSpecVersions are the spec versions baked at generation time
1099
- // (fail-closed constant comparison at init).
1100
- var ExpectedSpecVersions = map[string]int64{"behavior": ${specVersions.behavior}, "expression": ${specVersions.expression}, "plan": ${specVersions.plan}}
1101
-
1102
- // ComponentNames are the components exposed by Bind(), in IR declaration order.
1103
- var ComponentNames = []string{${names}}
1104
-
1105
- // init — load-time fail-closed checks (#208 prepared-artifact discipline).
1106
- func init() {
1107
- \tfor k, want := range ExpectedSpecVersions {
1108
- \t\tif got := ${PKG}.SpecVersions[k]; got != want {
1109
- \t\t\tpanic(fmt.Sprintf("behavior-contracts generated module: spec-version skew for '%s' (generated=%d, runtime=%d) — regenerate against this runtime (fail-closed)", k, want, got))
1110
- \t\t}
1111
- \t}
1112
- }
1113
-
1114
- // ── native static-wiring helpers (bc#75) — no scope snapshots, no closures ─────
1115
- // These are NATIVE Go — they never call EvaluateExpression / Prim*. They reproduce
1116
- // expr.go's ref/refOpt/concat semantics (same Failure codes) for the statically-wired
1117
- // inline path while removing the expression-tree interpretation.
1118
- ${helpers.join("\n\n")}
1119
-
1120
- // ── straight-line component functions (no RunBehavior tree-walk) ───────────────
1121
- ${fns}
1122
-
1123
- // Bind — inject handlers (boundary injection) and get one executor per component.
1124
- func Bind(handlers ${PKG}.ComponentExec) map[string]func(input *${PKG}.Obj) (${PKG}.Value, error) {
1125
- \tbound := make(map[string]func(input *${PKG}.Obj) (${PKG}.Value, error), len(ComponentNames))
1126
- \tfor _, name := range ComponentNames {
1127
- \t\tn := name
1128
- \t\tbound[n] = func(input *${PKG}.Obj) (${PKG}.Value, error) {
1129
- \t\t\treturn dispatch(n, handlers, input)
1130
- \t\t}
1131
- \t}
1132
- \treturn bound
1133
- }
1134
-
1135
- func dispatch(name string, handlers ${PKG}.ComponentExec, input *${PKG}.Obj) (${PKG}.Value, error) {
1136
- ${dispatchArms}
1137
- \treturn nil, ${PKG}.NewBehaviorFailure("UNKNOWN_ENTRY", "component '"+name+"' not found in this module (fail-closed)")
1138
- }
1139
- `;
1140
- }
1141
127
  const dialect = {
1142
128
  emitExpr,
1143
129
  mapScopeVar: MAP_SCOPE,
1144
- emitComponent,
1145
- emitModule,
1146
- beginModule() {
1147
- resetUsage();
1148
- },
1149
130
  };
1150
- /**
1151
- * go-typed(bc#47)が struct-native exec を綴じるために再利用する内部 emit ヘルパ。
1152
- */
131
+ /** go typed-native が使う式 dialect と命名ヘルパ。 */
1153
132
  export const goStraightlineInternals = {
1154
- PKG,
1155
133
  emitExpr,
1156
- emitOpsLiteral,
1157
- emitBehaviorPlanLiteral,
1158
- goPortVar,
1159
134
  sanitize,
1160
135
  dialect,
1161
136
  };