behavior-contracts 0.11.13 → 0.11.15

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 (60) hide show
  1. package/dist/behavior.d.ts +92 -30
  2. package/dist/behavior.d.ts.map +1 -1
  3. package/dist/behavior.js +224 -32
  4. package/dist/behavior.js.map +1 -1
  5. package/dist/builder.d.ts +10 -19
  6. package/dist/builder.d.ts.map +1 -1
  7. package/dist/builder.js +3 -64
  8. package/dist/builder.js.map +1 -1
  9. package/dist/expr-operator-types.d.ts +3 -1
  10. package/dist/expr-operator-types.d.ts.map +1 -1
  11. package/dist/expr-operator-types.js.map +1 -1
  12. package/dist/generator/emit-shared-go.js +1 -1
  13. package/dist/generator/emit-shared-go.js.map +1 -1
  14. package/dist/generator/emit-shared-rust-typed.d.ts +16 -0
  15. package/dist/generator/emit-shared-rust-typed.d.ts.map +1 -1
  16. package/dist/generator/emit-shared-rust-typed.js +27 -6
  17. package/dist/generator/emit-shared-rust-typed.js.map +1 -1
  18. package/dist/generator/emit-shared-rust.js +1 -1
  19. package/dist/generator/emit-shared-rust.js.map +1 -1
  20. package/dist/generator/emit-shared-typescript.js +1 -1
  21. package/dist/generator/emit-shared-typescript.js.map +1 -1
  22. package/dist/generator/emit-typed-native-go.d.ts.map +1 -1
  23. package/dist/generator/emit-typed-native-go.js +24 -18
  24. package/dist/generator/emit-typed-native-go.js.map +1 -1
  25. package/dist/generator/emit-typed-native-rust.d.ts.map +1 -1
  26. package/dist/generator/emit-typed-native-rust.js +36 -36
  27. package/dist/generator/emit-typed-native-rust.js.map +1 -1
  28. package/dist/generator/native-expr.d.ts +0 -4
  29. package/dist/generator/native-expr.d.ts.map +1 -1
  30. package/dist/generator/native-expr.js +2 -6
  31. package/dist/generator/native-expr.js.map +1 -1
  32. package/dist/generator/straightline.d.ts +2 -22
  33. package/dist/generator/straightline.d.ts.map +1 -1
  34. package/dist/generator/straightline.js +14 -72
  35. package/dist/generator/straightline.js.map +1 -1
  36. package/dist/generator/typed.d.ts +10 -7
  37. package/dist/generator/typed.d.ts.map +1 -1
  38. package/dist/generator/typed.js +17 -42
  39. package/dist/generator/typed.js.map +1 -1
  40. package/dist/guard.d.ts +19 -10
  41. package/dist/guard.d.ts.map +1 -1
  42. package/dist/guard.js +38 -27
  43. package/dist/guard.js.map +1 -1
  44. package/dist/lowering.d.ts +1 -1
  45. package/dist/lowering.d.ts.map +1 -1
  46. package/dist/lowering.js +1 -3
  47. package/dist/lowering.js.map +1 -1
  48. package/dist/primitives.d.ts +0 -13
  49. package/dist/primitives.d.ts.map +1 -1
  50. package/dist/primitives.js +0 -30
  51. package/dist/primitives.js.map +1 -1
  52. package/dist/runtime.d.ts +1 -1
  53. package/dist/runtime.d.ts.map +1 -1
  54. package/dist/runtime.js +1 -1
  55. package/dist/runtime.js.map +1 -1
  56. package/dist/type-gate.d.ts +1 -1
  57. package/dist/type-gate.d.ts.map +1 -1
  58. package/dist/type-gate.js +364 -104
  59. package/dist/type-gate.js.map +1 -1
  60. package/package.json +1 -1
package/dist/type-gate.js CHANGED
@@ -36,7 +36,7 @@
36
36
  * **既に compile 済みの artifact** で `compileBehaviors` を通らないため、このゲートは適用しない
37
37
  * (conformance vector の再ペイントを避ける — #128/A6 スコープ)。
38
38
  */
39
- import { descend, holdsUnproduced, isControlGate, mapIntoHoldsUnproduced, nodeRelationKind, nodeResultType, portableTypeOfInputPort, unproducedRefType, unproducibleNodeIds } from "./behavior.js";
39
+ import { descend, isControlGate, mapTransformExpr, nodeBindField, nodeNarrowedPaths, nodeParent, overIsDeclaredOptArr, mapIntoHoldsUnproduced, nodeRelationKind, nodeResultType, portableTypeOfInputPort, refPathKey, unproducedRefType, unproducibleNodeIds } from "./behavior.js";
40
40
  import { portableTypeNotation } from "./behavior.js";
41
41
  import { cmpCodePoints } from "./expr-eval.js";
42
42
  // operator I/O 型の唯一の宣言源(SSoT)。resolveExprType は value-operator の結果型をここから**読む**
@@ -108,7 +108,12 @@ function typeLabel(t) {
108
108
  * object 合成を field ごとに組む、等)である。解決できない位置は `undefined` を返し、呼び側が
109
109
  * `UNTYPED_NODE` にする。
110
110
  */
111
- export function resolveExprType(node, nodeTypes, inputPorts) {
111
+ export function resolveExprType(node, nodeTypes, inputPorts,
112
+ // #263: gate/guard/bindField が非 null を証明済みの ref path 集合({@link nodeNarrowedPaths}・SSoT は
113
+ // behavior.ts)。この scope で `ref` が opt を読む位置は inner 型へ narrow する — native emitter
114
+ // (native-expr `NativeExprCompiler.ref`)と**同一の 1 導出・同一鍵**で narrow するので「生成 native ≡
115
+ // run_behavior」が保たれる。空(既定)= narrow 無し(cond の if・map の over/when・output は非 narrow)。
116
+ narrowed = NO_NARROWING) {
112
117
  // リテラル: そのまま確定スカラ。
113
118
  if (node === null)
114
119
  return "null";
@@ -146,15 +151,28 @@ export function resolveExprType(node, nodeTypes, inputPorts) {
146
151
  if (cur === undefined)
147
152
  return undefined;
148
153
  for (const f of rest) {
149
- const next = descend(cur, f);
154
+ // {@link refCore} 準拠: 非 optional な `ref` は**中間が null**なら `NULL_REF` を投げる — その null は
155
+ // 値として consumer に届かない(投げる)ので、中間の opt は結果へ**伝播しない**。降下前に opt を
156
+ // 剥ぐ(`$g.group.permRef` で `group` が opt 中間でも、`ref` が読むのは非 null の `permRef` か、さもなくば
157
+ // throw)。`refOpt` は最初の null 中間で null を返すので opt は**伝播する** — {@link descend} が
158
+ // 「opt を降りたら `{opt:…}` で包む」optional-chain 伝播をそのまま行う。結果の optionality は、
159
+ // `ref` では**最終セグメント自身**の宣言 opt だけ、`refOpt` では経路上のどの opt でも(#241/#244 と
160
+ // 同じ「実態より広くしない」規律 — `ref` の中間 opt は実態が「値 or throw」であって null ではない)。
161
+ const base = op === "ref" && typeof cur === "object" && "opt" in cur ? cur.opt : cur;
162
+ const next = descend(base, f);
150
163
  if (next === undefined)
151
164
  return undefined;
152
165
  cur = next;
153
166
  }
154
- // refOpt は途中 null で null を返し得るため nullable。ただし解決型が既に opt なら二重ラップしない
155
- // (opt 入力の単一セグメント refOpt は opt 値そのもの — #173: これを二重 opt にすると coalesce 等の
156
- // 型解決が壊れ、port 型が誤って value に落ちる)。
157
- return op === "refOpt" ? (typeof cur === "object" && cur !== null && "opt" in cur ? cur : { opt: cur }) : cur;
167
+ // #263: この位置を dominating gate/guard/bindField が非 null と証明済み(`narrowed` に full path が
168
+ // 在る)で、かつ読む型が opt なら inner へ narrow する。証明は「port 評価の前に runtime が既に行う
169
+ // skip/keep」で、native emitter(native-expr `NativeExprCompiler.ref`)も**同一鍵 {@link refPathKey}・
170
+ // 同一集合**で narrow する。narrow は `ref` のみ(`refOpt` は emitter 側で optLeafAccess/fail-closed に
171
+ // 分岐し narrowing 経路に来ない — 面の一致を崩さないため型層も `ref` に限る)。ここで narrow されるのは
172
+ // **最終セグメント opt**(中間 opt は上の walk で既に畳まれている)。
173
+ if (op === "ref" && typeof cur === "object" && "opt" in cur && narrowed.has(refPathKey(path)))
174
+ return cur.opt;
175
+ return cur;
158
176
  }
159
177
  case "obj": {
160
178
  // object 合成: 全フィールドが解決できて初めて確定(1 つでも未確定なら undefined)。
@@ -162,7 +180,7 @@ export function resolveExprType(node, nodeTypes, inputPorts) {
162
180
  return undefined;
163
181
  const obj = {};
164
182
  for (const [k, v] of Object.entries(arg)) {
165
- const ft = resolveExprType(v, nodeTypes, inputPorts);
183
+ const ft = resolveExprType(v, nodeTypes, inputPorts, narrowed);
166
184
  if (ft === undefined)
167
185
  return undefined;
168
186
  obj[k] = ft;
@@ -175,7 +193,7 @@ export function resolveExprType(node, nodeTypes, inputPorts) {
175
193
  return undefined;
176
194
  let elem;
177
195
  for (const e of arg) {
178
- const et = resolveExprType(e, nodeTypes, inputPorts);
196
+ const et = resolveExprType(e, nodeTypes, inputPorts, narrowed);
179
197
  if (et === undefined)
180
198
  return undefined;
181
199
  if (elem === undefined)
@@ -188,12 +206,14 @@ export function resolveExprType(node, nodeTypes, inputPorts) {
188
206
  case "cond": {
189
207
  // {cond:[if, then, else]} — 制御ノード(value-operator ではない)。採用側の型は then/else の join。
190
208
  // join 規則の意味論は SSoT(resolveOperatorResult の "cond-join")に集約する(分岐を散らさない)。
209
+ // narrowed はこの式全体の scope なので nested cond の if/then/else にも伝播する(emitter は 1 つの
210
+ // NativeExprCompiler.narrowed で式全体を compile する — 面の一致)。
191
211
  const triple = arg;
192
212
  if (!Array.isArray(triple) || triple.length !== 3)
193
213
  return undefined;
194
- assertConditionBool(triple[0], nodeTypes, inputPorts, "?:"); // expression-ir.md §3: cond の c は bool
195
- const thenT = resolveExprType(triple[1], nodeTypes, inputPorts);
196
- const elseT = resolveExprType(triple[2], nodeTypes, inputPorts);
214
+ assertConditionBool(triple[0], nodeTypes, inputPorts, "?:", narrowed); // expression-ir.md §3: cond の c は bool
215
+ const thenT = resolveExprType(triple[1], nodeTypes, inputPorts, narrowed);
216
+ const elseT = resolveExprType(triple[2], nodeTypes, inputPorts, narrowed);
197
217
  if (thenT === undefined || elseT === undefined)
198
218
  return undefined;
199
219
  return resolveOperatorResult({ arity: "ternary", operands: "any", result: "cond-join" }, [thenT, elseT]);
@@ -208,18 +228,21 @@ export function resolveExprType(node, nodeTypes, inputPorts) {
208
228
  const operands = Array.isArray(arg) ? arg : [arg]; // 単項は素の値、多項は配列
209
229
  const operandTypes = [];
210
230
  for (const o of operands) {
211
- const ot = resolveExprType(o, nodeTypes, inputPorts);
231
+ const ot = resolveExprType(o, nodeTypes, inputPorts, narrowed);
212
232
  if (ot === undefined)
213
233
  return undefined; // 未確定オペランドがあれば結果も未確定
214
234
  operandTypes.push(ot);
215
235
  }
216
236
  // 宣言 operand 制約の enforcement(expression-ir.md §3・SSoT `sig.operands` を読む)。全被演算子が
217
- // 確定型を持つ場合のみ検査する(未確定は上で undefined 返し済み = UNTYPED 側の責務)。
237
+ // 確定型を持つ場合のみ検査する(未確定は上で undefined 返し済み = UNTYPED 側の責務)。narrowing は
238
+ // 上の resolveExprType で既に反映済み(narrow 済み型で検査する)。
218
239
  assertOperandConstraint(op, sig.operands, operandTypes, `operator '${op}'`);
219
240
  return resolveOperatorResult(sig, operandTypes);
220
241
  }
221
242
  }
222
243
  }
244
+ /** narrowing 無しの scope(cond の if・map の over/when・output 位置など gate/guard に守られない式)の既定。 */
245
+ const NO_NARROWING = /* @__PURE__ */ new Set();
223
246
  /**
224
247
  * canonicalizeType — 導出 PortableType の obj field キーを code-point 順に再構築する
225
248
  * (builder.ts の canonicalizeDeep と同じ規律。golden/fingerprint の決定性のため component の
@@ -278,32 +301,54 @@ export function assertAllNodeTypesDetermined(comp) {
278
301
  `Declare the attach point OPTIONAL (\`${n.map.into}: T | null\`); a required field is a contract that can only throw (run_behavior writes null / no key there).`);
279
302
  nodeTypes.set(n.id, nodeResultType(n));
280
303
  }
281
- // (2) 全式位置の operand 制約 enforcement(条件は bool・len は配列 …)。resolveExprType に埋め込んだ
282
- // 検査を全 port / over / then-else / output で行使し、node レベルの条件(gate の `if`・`map.when`)は
283
- // bool を明示 assert する(両者とも expression-ir.md §3 の要求で、reader 非依存の唯一の検査点)。
304
+ // (1b) `bindField` は「親結果のそのフィールド」を読む参照そのものなので、参照 path と同じ強さで解決できな
305
+ // ければならない。親の宣言型に無いフィールドを名指した bindField は bind が常に欠落し、子は**永久に**
306
+ // 未生成になる(interpreter は毎回 skip して黙って null を返し、typed emitter は failure code を持たない
307
+ // 素の Error で落ちる)。書いた relation が丸ごと死ぬ形なので、実行時ではなく generate 時に落とす。
308
+ const nodeById = new Map(comp.body.map((n) => [n.id, n]));
309
+ for (const n of comp.body) {
310
+ const bf = nodeBindField(n);
311
+ if (bf === undefined)
312
+ continue;
313
+ const parent = nodeParent(n);
314
+ const pt = parent === undefined ? undefined : nodeResultType(nodeById.get(parent));
315
+ if (pt === undefined || descend(pt, bf) !== undefined)
316
+ continue; // 親の型が未確定なら判定しない
317
+ badNodeType(`method '${method}': node '${n.id}': bindField '${bf}' is not a field of its parent '${parent}' ` +
318
+ `('${portableTypeNotation(pt)}'). The bind would be absent on every call, so this node is UNPRODUCED forever — ` +
319
+ `the relation is written but dead. Name a field the parent actually declares.`);
320
+ }
321
+ // (2) 全式位置の operand 制約 enforcement(条件は bool・len は配列・concat は string …)と、**port 宣言
322
+ // との突き合わせ**。resolveExprType に埋め込んだ検査を全 port / over / then-else / output で行使し、node
323
+ // レベルの条件(gate の `if`・`map.when`)は bool を明示 assert する(expression-ir.md §3・reader 非依存の
324
+ // 唯一の検査点)。#263: ノードの port/要素式は「runtime が既に skip/keep で非 null を証明済み」の scope で
325
+ // 評価されるので、その narrowing 集合({@link nodeNarrowedPaths}・SSoT)を resolveExprType に渡す — native
326
+ // emitter が port を lower するのと**同一導出・同一位置**(gate の `if`・`map.when` 自体は proof を立てる側
327
+ // なので narrow しない = NO_NARROWING)。
284
328
  for (const n of comp.body) {
285
329
  if ("fanout" in n) {
286
- resolveExprType(n.fanout.over, nodeTypes, comp.inputPorts);
287
- for (const v of Object.values(n.fanout.ports))
288
- resolveExprType(v, nodeTypes, comp.inputPorts);
330
+ const scope = elementScope(method, n.id, n.fanout, "fanout", nodeTypes, comp);
331
+ assertPortsMatchSchemas(method, n.id, n.fanout, scope, comp.inputPorts, nodeNarrowedPaths(comp, n));
289
332
  }
290
333
  else if ("map" in n) {
291
- resolveExprType(n.map.over, nodeTypes, comp.inputPorts);
292
- // 純式 map(#222)は ports を持たず、要素式そのものが要素値を作る。式位置の operand 制約はここで
293
- // 行使する(要素束縛 `as` は nodeTypes に無いので型は解決しない — 宣言 outType が要素型の根拠)。
294
- for (const v of Object.values(n.map.ports ?? {}))
295
- resolveExprType(v, nodeTypes, comp.inputPorts);
334
+ // 純式 map(#222)は ports を持たず、要素式そのものが要素値を作る。
335
+ const scope = elementScope(method, n.id, n.map, "map", nodeTypes, comp);
336
+ const narrowed = nodeNarrowedPaths(comp, n); // (a2) map `when` guard が kept 要素で証明する非 null。
337
+ assertPortsMatchSchemas(method, n.id, n.map, scope, comp.inputPorts, narrowed);
338
+ // 純式 map(#222)の要素式も「式から組む」位置 — `outType` は要素型なので要素式の型と直接照合する。
339
+ // 要素式も kept 要素の narrowing scope で評価される(emitter は transform に nodeNarrowedPaths を渡す)。
340
+ const transform = mapTransformExpr(n.map);
341
+ if (transform !== undefined)
342
+ assertBuiltOutType(method, n.id, "pure-expression map", resolveExprType(transform, scope, comp.inputPorts, narrowed), n.outType, "its element expression");
296
343
  if (n.map.when !== undefined)
297
- assertConditionBool(n.map.when, nodeTypes, comp.inputPorts, "map.when");
344
+ assertConditionBool(n.map.when, scope, comp.inputPorts, "map.when");
298
345
  }
299
346
  else if ("cond" in n) {
300
347
  assertConditionBool(n.cond.if, nodeTypes, comp.inputPorts, "if");
301
- resolveExprType(n.cond.then, nodeTypes, comp.inputPorts);
302
- resolveExprType(n.cond.else, nodeTypes, comp.inputPorts);
348
+ assertCondOutType(method, n, nodeTypes, comp.inputPorts);
303
349
  }
304
350
  else {
305
- for (const v of Object.values(n.ports))
306
- resolveExprType(v, nodeTypes, comp.inputPorts);
351
+ assertPortsMatchSchemas(method, n.id, n, nodeTypes, comp.inputPorts, nodeNarrowedPaths(comp, n));
307
352
  }
308
353
  }
309
354
  // (3) output(Φ 合成)の全フィールド型が確定型へ resolvable であること。#239: 未生成になり得るノードを
@@ -312,20 +357,134 @@ export function assertAllNodeTypesDetermined(comp) {
312
357
  const outputType = resolveOutputType(comp.output, nodeTypes, comp.inputPorts, method, unproducible, (id) => kindById.get(id), comp.outputType);
313
358
  return outputType;
314
359
  }
360
+ /**
361
+ * elementScope — map/fanout の `over` を検査し、要素束縛 `as` を型スコープへ入れて返す。
362
+ *
363
+ * 1. `over` は**反復対象**なので配列でなければならない(runtime の唯一の関門 {@link resolveOverArray} が
364
+ * `(MAP|FANOUT)_OVER_NOT_ARRAY` で落とす条件そのもの)。宣言型が `{opt:{arr:E}}` の bare ref だけは
365
+ * null が空反復として正当なので通す — その判定は runtime と**同じ述語** {@link overIsDeclaredOptArr}
366
+ * を読む(2 つ目の綴りを作らない)。配列になり得ない `over` は「実行したら必ず落ちる」宣言なので、
367
+ * 実行時ではなく generate 時に落とす(#220/#232 と同じ前倒し)。
368
+ * 2. 要素 port は `as` 束縛を読む。束縛を型スコープに入れないと `resolveExprType` が undefined を返し、
369
+ * 要素 port は operand 制約からも port 契約からも**黙って外れる**(gate は「全式位置」を検査すると
370
+ * 言っているのに、要素位置だけ素通しだった)。要素型は `over` の要素型そのもの。
371
+ */
372
+ function elementScope(method, nodeId, holder, label, nodeTypes, comp) {
373
+ const t = resolveExprType(holder.over, nodeTypes, comp.inputPorts);
374
+ if (t === undefined)
375
+ return nodeTypes; // 型未確定の over は検査対象外(over-reject を作らない)
376
+ const elem = typeof t === "object" && "arr" in t
377
+ ? t.arr
378
+ : overIsDeclaredOptArr(holder.over, comp.body, comp.inputPorts)
379
+ ? t.opt.arr
380
+ : undefined;
381
+ if (elem === undefined)
382
+ badNodeType(`method '${method}': node '${nodeId}': the '.${label}' iterates its 'over' value, so that value must be an array, but it resolves to ` +
383
+ `'${portableTypeNotation(t)}'. run_behavior's resolveOverArray fails ${label.toUpperCase()}_OVER_NOT_ARRAY on anything else — a declaration ` +
384
+ `that can only throw belongs at generate time. (An OPTIONAL array read by a bare reference IS allowed: an absent optional collection iterates zero times.)`);
385
+ return holder.as === undefined ? nodeTypes : new Map(nodeTypes).set(holder.as, elem);
386
+ }
387
+ /**
388
+ * assertPortsMatchSchemas — ノードに配線した各 port 値の型が、その port の**宣言型契約**
389
+ * (`portSchemas[k]` — irVersion 2 で必須。authoring 経路では leaf catalog から `derivePortSchemas` が
390
+ * 機械導出する)に適合することを検査する。
391
+ *
392
+ * ここは output 位置({@link outputPositionType})の対称位置である。以前は port 式を
393
+ * `resolveExprType` に通しては**結果を捨てて**いた(operand 制約の副作用だけを取っていた)ので、宣言
394
+ * port 型と配線値型は一度も突き合わされていなかった — #243 と同じ「宣言はあるが誰も照合しない」形。
395
+ * 静的スカラリテラルだけを見る record 時の検査があったが、`{ref}`/演算式は「実行時型」として素通しで、
396
+ * 型ゲートが解決できる今その制限は残す理由が無い。
397
+ */
398
+ function assertPortsMatchSchemas(method, nodeId, holder, nodeTypes, inputPorts,
399
+ // #263: このノードの port scope で gate/guard/bindField が非 null を証明済みの ref path 集合(default 空)。
400
+ narrowed = NO_NARROWING) {
401
+ // 宣言はしたが配線していない required port(authoring 経路の `checkPortNames` の MISSING_PORT と同じ規則
402
+ // を生 IR 経路にも届かせる)。`derivePortSchemas` は**配線した port だけ**に schema を作るので、
403
+ // authoring 側ではこの形は綴れない — 生 IR だけが「必須と宣言した port を渡さない」呼びを書けた。
404
+ for (const [k, schema] of Object.entries(holder.portSchemas ?? {}))
405
+ if (schema.required === true && !Object.hasOwn(holder.ports ?? {}, k))
406
+ badNodeType(`method '${method}': node '${nodeId}' port '${k}': the port schema declares it REQUIRED, but the node wires no value into it. ` +
407
+ `The Component is called without a port its own contract says it needs — wire it, or declare the port optional (\`required: false\`).`);
408
+ for (const [k, v] of Object.entries(holder.ports ?? {})) {
409
+ const vt = resolveExprType(v, nodeTypes, inputPorts, narrowed); // operand 制約の enforcement もここで起きる
410
+ const schema = holder.portSchemas?.[k];
411
+ // 解決できない配線値 / 可搬型へ写せない宣言(`unknown` 等)は検査対象外 — over-reject を作らない。
412
+ const pt = schema === undefined ? undefined : portableTypeOfInputPort(schema);
413
+ if (vt === undefined || pt === undefined || portValueConforms(vt, pt))
414
+ continue;
415
+ badNodeType(`method '${method}': node '${nodeId}' port '${k}': the port is declared '${portableTypeNotation(pt)}', but the value wired into it has type ` +
416
+ `'${portableTypeNotation(vt)}'. The port schema is the Component's input contract — the handler receives exactly what is wired, with no coercion at the boundary, ` +
417
+ `so a value of another type is a call the Component cannot serve. Wire a value of the declared type, or declare the port the type the body actually has.`);
418
+ }
419
+ }
420
+ /**
421
+ * portValueConforms — 配線値の型 `v` は宣言 port 型 `d` に**適合**するか。
422
+ *
423
+ * 出力位置は厳密一致(宣言は consumer が観測する型そのもの)だが、port は向きが逆で、宣言は「Component が
424
+ * **受け取れる**型」である。だから関係は代入可能性で、equality と食い違うのは次の 3 点だけ(スカラ終端は
425
+ * {@link sameType} に委譲する — 構造的同値の 2 つ目の綴りを作らない):
426
+ * - `value`(不透明ワイヤ port)は任意の値を受ける — de-box されるのは Component の向こう側(#164/#209)。
427
+ * - `{opt:T}` は `T` そのものと静的 null も受ける(省略可 port に「確実に在る値」を渡すのは正当)。
428
+ * - `{map:V}` は「全フィールドが V に適合する object」も受ける(#209 の動的属性 port: 呼び出し位置で
429
+ * 構造的に組んだ obj が map 型 port に入る)。
430
+ */
431
+ function portValueConforms(v, d) {
432
+ if (d === "value")
433
+ return true;
434
+ if (typeof d === "object") {
435
+ if ("opt" in d)
436
+ return v === "null" || portValueConforms(typeof v === "object" && "opt" in v ? v.opt : v, d.opt);
437
+ if ("arr" in d)
438
+ return typeof v === "object" && "arr" in v && portValueConforms(v.arr, d.arr);
439
+ if ("map" in d) {
440
+ if (typeof v !== "object")
441
+ return false;
442
+ if ("map" in v)
443
+ return portValueConforms(v.map, d.map);
444
+ return "obj" in v && Object.values(v.obj).every((f) => portValueConforms(f, d.map));
445
+ }
446
+ if ("obj" in d) {
447
+ if (typeof v !== "object" || !("obj" in v))
448
+ return false;
449
+ const dk = Object.keys(d.obj);
450
+ return (dk.length === Object.keys(v.obj).length && dk.every((k) => k in v.obj && portValueConforms(v.obj[k], d.obj[k])));
451
+ }
452
+ }
453
+ return sameType(v, d);
454
+ }
315
455
  /** 条件式(`?:`/`&&` の cond・gate の `if`・`map.when`)は bool でなければならない(truthiness 禁止・
316
456
  * expression-ir.md §3 L120/L128)。確定型が bool 以外なら loud reject。未解決(undefined)は条件型の
317
457
  * 未確定であって「非 bool を silent に受理」とは別問題なので、ここでは触らない(over-reject を作らない)。 */
318
- function assertConditionBool(cond, nodeTypes, inputPorts, where) {
319
- const t = resolveExprType(cond, nodeTypes, inputPorts);
458
+ function assertConditionBool(cond, nodeTypes, inputPorts, where, narrowed = NO_NARROWING) {
459
+ const t = resolveExprType(cond, nodeTypes, inputPorts, narrowed);
320
460
  if (t !== undefined && t !== "bool")
321
461
  badOperand(`condition at '${where}' must be bool (expression-ir.md §3 forbids truthiness), but resolves to '${typeLabel(t)}' — use a comparison/logical Expression (eq/ne/lt/.../and/or/not) or a bool-typed port`);
322
462
  }
323
- /** 宣言 operand 制約(`OperandConstraint`)の enforcement。確定型を持つ被演算子だけを検査し、`bool`
324
- * (and/or/not — truthiness 禁止)と `arr`(len — 配列限定・expression-ir.md §3 L124)の違反を loud reject
325
- * する。numeric/ordered/string/same は結果ルール側の既存挙動に委ね(null 検査 `x === null` 等の正当な
326
- * 混在を壊さない)— スコープ外。 */
463
+ /**
464
+ * 宣言 operand 制約(`OperandConstraint`・{@link OPERATOR_TYPE_SIGNATURES} が SSoT)の enforcement。確定型を
465
+ * 持つ被演算子だけを検査する(未確定は resolveExprType が先に undefined を返す = UNTYPED 側の責務)。
466
+ * **宣言した制約はすべて読む**(#263: 宣言はあるが読み手がゼロの制約を残さない — 実行時 `TYPE_MISMATCH` に
467
+ * なるだけの穴になる)。各 operand core(expr-eval.ts)の throw 条件と 1:1 に対応させる:
468
+ * - `bool`(and/or/not — truthiness 禁止・`requireBool`): 全 operand が bool。
469
+ * - `arr`(len — 配列限定・`lenCore`): operand が配列。
470
+ * - `ordered`(lt/le/gt/ge — `compareCore` は同一 int/float/string のみ): 全 operand が int/float/string。
471
+ * - `numeric`(add/sub/mul/mod/neg/**div**): 全 operand が int/float。`div` の結果ルール(`div-float`)は
472
+ * 被演算子に依らず常に float を返すので、ここで検査しないと `div` の numeric 制約は**誰も読まず**、
473
+ * 非数値 div が generate を通って実行時 `divCore`→`widenToFloat` の `TYPE_MISMATCH` になっていた(#268)。
474
+ * int/float の混在は numeric を満たす(両方 numeric)ので通し、混在の拒否は結果ルール `arith-join`
475
+ * (undefined→UNTYPED)が担う(責務分離・二重化しない)。
476
+ * - `same`(eq/ne — `valueEquals`): `valueEquals` が throw するのは「**両辺とも非 null** かつ(型が違う or
477
+ * obj/arr)」のときだけ。よって (a) どちらかが**リテラル null**なら常に安全(null 分岐で決まり throw
478
+ * しない — null 比較こそ主用途)、(b) それ以外は opt を剥いだ base どうしが**同一スカラ型**であること
479
+ * (obj/arr 等価は v1 未定義で `valueEquals` が throw する)。narrowing は base 抽出に吸収される。
480
+ * - `string`(concat — `concatCore` は非 string で throw): 全 operand が string。`{opt:string}` の concat は
481
+ * gate/guard/bindField が非 null を証明済みの位置なら resolveExprType が既に `string` へ narrow して
482
+ * いる(#263・narrowing を型層に上げた)ので通り、証明の無い素の optional は reject する。
483
+ */
327
484
  function assertOperandConstraint(op, constraint, operandTypes, where) {
328
485
  const wrong = (want) => badOperand(`${where} requires ${want} operand(s) (expression-ir.md §3), got [${operandTypes.map(typeLabel).join(", ")}]`);
486
+ const isScalar = (t) => t === "int" || t === "float" || t === "string" || t === "bool";
487
+ const base = (t) => (typeof t === "object" && "opt" in t ? t.opt : t);
329
488
  if (constraint === "bool") {
330
489
  if (operandTypes.some((t) => t !== "bool"))
331
490
  wrong("bool");
@@ -334,96 +493,197 @@ function assertOperandConstraint(op, constraint, operandTypes, where) {
334
493
  if (operandTypes.some((t) => typeof t !== "object" || t === null || !("arr" in t)))
335
494
  wrong("array");
336
495
  }
496
+ else if (constraint === "ordered") {
497
+ if (operandTypes.some((t) => t !== "int" && t !== "float" && t !== "string"))
498
+ wrong("int / float / string");
499
+ }
500
+ else if (constraint === "numeric") {
501
+ if (operandTypes.some((t) => t !== "int" && t !== "float"))
502
+ wrong("int / float");
503
+ }
504
+ else if (constraint === "string") {
505
+ if (operandTypes.some((t) => t !== "string"))
506
+ wrong("string");
507
+ }
508
+ else if (constraint === "same") {
509
+ // eq/ne: a literal-null side is always safe (valueEquals takes the null branch); otherwise the non-null
510
+ // shapes (opt stripped) must be the SAME scalar type — differing types / obj/arr equality throw.
511
+ const [a, b] = operandTypes;
512
+ if (operandTypes.length === 2 && a !== "null" && b !== "null" && (!isScalar(base(a)) || !sameType(base(a), base(b))))
513
+ wrong("two same-typed scalars (or a comparison against null)");
514
+ }
337
515
  }
338
516
  /**
339
- * resolveOutputType — `output` 式全体を解決して `outputType` を返す。トップが object 合成のとき、
340
- * 未確定フィールドを個別に名指して `UNTYPED_NODE` を投げる(AC1 の「naming the field」)。
517
+ * assertBuiltOutType — **結果を式から組む**ノードの宣言 `outType` が、実際に組まれる型と一致すること。
518
+ *
519
+ * componentRef / Component map の結果は不透明な handler から来るので突き合わせ相手が無いが、`cond`(分岐の
520
+ * Φ join)と純式 map(`transform` — #222)は結果を**式から組む**ので、産む型が generate 時に分かる。それでも
521
+ * 両者とも式を `resolveExprType` に通して**結果を捨てて**いた(operand 制約の副作用だけを取っていた)ので、
522
+ * 宣言と実態は一度も照合されていなかった — output 位置(#243)・port 位置と同じ「derive して捨てる」形。
523
+ * 食い違うと interpreter はノード結果 conformance で TYPE_MISMATCH を投げ、typed-native は式を lower できず
524
+ * 非被覆になる。どちらも generate 時に分かる食い違いである。
525
+ *
526
+ * 述語は output 位置と同じ {@link sameType}。組まれる型が決まらないとき(join が結合しない int/float 混在、
527
+ * 未確定の被参照など)は検査しない(over-reject を作らない)。control gate cond は `outType` を持たないので
528
+ * 対象外。
341
529
  */
530
+ function assertBuiltOutType(method, nodeId, what, built, declared, detail) {
531
+ if (built === undefined || declared === undefined || sameType(built, declared))
532
+ return;
533
+ badNodeType(`method '${method}': node '${nodeId}' (${what}): the declared outType is '${portableTypeNotation(declared)}', but ${detail} builds ` +
534
+ `'${portableTypeNotation(built)}'. This node BUILDS its result from expressions, so what it produces is known here — the declaration has to be it. ` +
535
+ `Otherwise run_behavior's node-result conformance throws at run time and typed-native cannot lower it, for a disagreement that is visible now.`);
536
+ }
537
+ /** データ結合 cond(Φ join)の宣言 outType 照合 — {@link assertBuiltOutType} の cond 側の入口。 */
538
+ function assertCondOutType(method, n, nodeTypes, inputPorts) {
539
+ const thenT = resolveExprType(n.cond.then, nodeTypes, inputPorts);
540
+ const elseT = resolveExprType(n.cond.else, nodeTypes, inputPorts);
541
+ const join = thenT === undefined || elseT === undefined
542
+ ? undefined
543
+ : resolveOperatorResult({ arity: "ternary", operands: "any", result: "cond-join" }, [thenT, elseT]);
544
+ assertBuiltOutType(method, n.id, "cond", join, n.outType, thenT === undefined || elseT === undefined
545
+ ? "the branch join"
546
+ : `the branch join (then '${portableTypeNotation(thenT)}' / else '${portableTypeNotation(elseT)}')`);
547
+ }
342
548
  /**
343
- * outputRefUnproduced — 出力位置の参照が**未生成になり得るノード**を読むときの #220/#232/#241 規則。
344
- * 3 つを 1 点で決める(判定源は {@link unproducibleNodeIds}=generator の canSkip と同じ 3 源):
549
+ * outputPositionType — 出力位置 1 つ分の「**その位置で実際に materialize される型**」を確定し、宣言型が
550
+ * あればそれと突き合わせる(#220/#232/#239/#241/#243 を 1 点に集約する)。
345
551
  *
346
- * 1. 導出型(#220 の導出・#241 で厳密化): {@link unproducedRefType}(SSoT)。ノード間の参照は skip 連鎖に
347
- * 守られている(親が未生成なら子も実行されない)が、**出力は呼び側が読む**ので守りが無い。未生成値が
348
- * 生成値の型の住人でないなら `{opt:…}`、住人なら(=`relationKind:"connection"` の空 connection)
349
- * **そのまま**。
350
- * 2. 宣言が実態より**狭い**ときの reject(#239): 宣言 `declared` があるなら、それが未生成値を保持できる
351
- * こと({@link holdsUnproduced}=#232 の述語そのもの)。保持できない宣言は「未生成が起きたら必ず落ちる」
352
- * 型なので、実行時ではなく generate 時に落とす。native 面ではこの食い違いが**実行時に観測できない** —
353
- * 非 optional な connection 構造体のゼロ値は空 connection として読めてしまうため、注記の有無で生成物が
354
- * コメント以外バイト同一になる(黙って通り、黙って正しく見える)。
355
- * 3. 宣言が実態より**広い**ときの reject(#241): 導出(1)が非 opt なら、その参照は**決して null に
356
- * ならない**(ランタイムは skip 時に空 connection を書く)。にもかかわらず `T | null` と宣言できると、
357
- * 起こり得ない case を宣言した型が通り、consumer は永久に来ない null の分岐を書かされる。宣言を唯一の
358
- * 真実として扱う以上、ここだけ「正直だが不正確」を許す理由が無い(2 の裏返しを同じ規律で落とす)。
552
+ * 1. materialize される型(#220 の導出・#241 で厳密化): 参照が**未生成になり得る**ノードを読むなら
553
+ * {@link unproducedRefType}(SSoT)。判定源は {@link unproducibleNodeIds}=generator の canSkip と同じ
554
+ * 3 源。ノード間の参照は skip 連鎖に守られている(親が未生成なら子も実行されない)が、**出力は呼び側が
555
+ * 読む**ので守りが無い。未生成値が生成値の型の住人でないなら `{opt:…}`、住人ならそのまま。**path の
556
+ * どこを読むか**まで含めて判定する(丸ごと=空 connection そのもの / `.items`=`[]` / `.cursor`=null)。
557
+ * 2. 宣言との突き合わせ(#243 — #239/#241 はこの 1 検査の 2 方向): 宣言は契約なので、その位置で実際に
558
+ * materialize される型と**厳密に一致**しなければならない。狭すぎ(保持できない値を産む — #239)も
559
+ * 広すぎ(起こり得ない case を宣言する — #241)も同じ 1 つの食い違いで、述語は authoring 経路の出力契約
560
+ * 照合(lowering の `outputContract`)と同じ {@link sameType}。native 面ではこの食い違いが**実行時に
561
+ * 観測できない**ことがある — 非 optional な connection 構造体のゼロ値は空 connection として読めてしまう
562
+ * ため、注記の有無で生成物がコメント以外バイト同一になる(黙って通り、黙って正しく見える)。
359
563
  *
360
- * 宣言が無い経路(authoring: 宣言戻り型との突き合わせは lowering の outputContract が導出型に対して行う)は
361
- * 1 だけを適用する — そこでは導出型そのものが契約の検証に使われる(`Conn | null` を宣言した authoring は
362
- * 導出 `Conn` と食い違って `OUTPUT_TYPE_MISMATCH`)。
564
+ * 宣言が無い経路(authoring: gate の時点では component にまだ `outputType` が無い)は 1 だけを適用する —
565
+ * そこでは導出型そのものが `outputContract` で宣言戻り型の検証に使われる。
363
566
  */
364
- function outputRefUnproduced(where, expr, derived, declared, unproducible, kindOf) {
365
- const path = refPath(expr);
366
- if (path === undefined || !unproducible.has(path[0]))
367
- return derived;
368
- // 空 connection を「読める」のはノードを丸ごと参照する場合だけ。フィールドを 1 段降りた参照が読むのは
369
- // その空 connection の中身なので、保持できるのは opt 宣言(generator の produced-aware 出力と同じ条件)。
370
- const kind = path.length === 1 ? kindOf(path[0]) : undefined;
371
- const read = unproducedRefType(derived, kind);
372
- if (declared === undefined)
567
+ function outputPositionType(where, expr, derived, declared, unproducible, kindOf) {
568
+ const ref = refOf(expr);
569
+ const path = ref?.path;
570
+ const unproduced = path !== undefined && unproducible.has(path[0]);
571
+ // 未生成値の**どこ**を読むかは path が決める(丸ごと=空 connection そのもの / `.items`=`[]` /
572
+ // `.cursor`=null)。その判定は {@link unproducedRefType}(SSoT)に渡し切る — ここで綴らない。
573
+ const kind = unproduced ? kindOf(path[0]) : undefined;
574
+ const read = unproduced ? unproducedRefType(derived, kind, path.slice(1)) : derived;
575
+ // 未生成値が **null** のノードへ 1 段でも降りる参照は、その null を**中間**として踏む。`ref` はそこで
576
+ // NULL_REF で落ち({@link refCore})、produced-aware な native lowering は宣言型のゼロ(nil/None)を返す
577
+ // — 同じ IR・同じデータで interpreter 系と typed-native 系の**観測結果が割れる**(#233 と同じ不変則違反)。
578
+ // null 伝播を書ける operator は `refOpt` だけなので、`ref` はここで落とす(宣言型は既に optional を
579
+ // 強制されているのに、operator の側がその null を作れない — 宣言と operator が食い違っている)。
580
+ if (unproduced && ref.op === "ref" && path.length > 1 && kind !== "connection")
581
+ badNodeType(`${where}: it reads node '${path[0]}' at .${path.slice(1).join(".")} with \`ref\`, but that node can be UNPRODUCED and its unproduced value is null ` +
582
+ `(no \`relationKind\`), so the reference walks INTO a null intermediate. \`ref\` fails NULL_REF there while the produced-aware native lowering ` +
583
+ `returns the declared zero — the same IR would observe different results on the interpreter and on typed-native. ` +
584
+ `Use \`refOpt\` (null propagates, which is what the optional declaration at this position already says), reference the node WHOLE, ` +
585
+ `or annotate it \`relationKind:"connection"\` if its unproduced value really is the empty connection.`);
586
+ // 静的 null(`"null"` に解決する位置)が optional スロットに載るとき、materialize されるのは**宣言型
587
+ // そのもの**(rust `None` / go `*T` の nil — #116)。`"null"` は optional 型の住人であるという意味論は
588
+ // 既に SSoT にある(`resolveOperatorResult` の cond-join: `elseT === "null"` → `{opt:…}`)。宣言型が
589
+ // materialize を駆動するのは de-box が宣言型に対して total なのと同じ規律(#233)。宣言が非 opt なら
590
+ // 下の突き合わせが落とす(required スロットは null を保持できない)。
591
+ if (read === "null" && declared !== undefined && typeof declared === "object" && "opt" in declared)
592
+ return declared;
593
+ if (declared === undefined || sameType(declared, read))
373
594
  return read;
374
- if (!holdsUnproduced(declared, kind))
375
- badNodeType(`${where}: it reads node '${path[0]}', which can be UNPRODUCED (a 'continue' policy, a null bindField bound, or an unproduced parent) — ` +
376
- `so the declared type must be able to hold the unproduced value ${kind === "connection" ? "(the empty connection)" : "(null)"}, but it is declared '${portableTypeNotation(declared)}'. ` +
377
- (kind === "connection"
378
- ? `Declare it OPTIONAL (\`T | null\`); a required non-object is a contract the empty connection cannot satisfy.`
379
- : `Declare it OPTIONAL (\`T | null\`), or annotate the node \`relationKind:"connection"\` if its unproduced value really is the empty connection — the annotation's ABSENCE means null.`));
380
- // #241: 逆向き — 宣言が実態より**広い**。`holdsUnproduced(t, undefined)` は「t は未生成値 null を保持
381
- // できるか」=「t は opt か」そのものなので、同じ述語を向きだけ変えて読む(2 つ目の綴りを作らない)。
382
- if (holdsUnproduced(declared, undefined) && !holdsUnproduced(read, undefined))
383
- badNodeType(`${where}: it reads node '${path[0]}' WHOLE, and that node is \`relationKind:"connection"\` — its unproduced value is the EMPTY connection {items:[],cursor:null}, never null ` +
384
- `(run_behavior's writeUnproduced writes it, and the produced-aware native lowering emits it). ` +
385
- `So the reference can never be null, but it is declared '${portableTypeNotation(declared)}' — a case that cannot occur, which every consumer downstream must branch on for nothing. ` +
386
- `Declare it REQUIRED (\`${portableTypeNotation(read)}\`); drop the node's \`relationKind\` annotation if its unproduced value really is null (the annotation's ABSENCE means null).`);
387
- return read;
595
+ declaredMismatch(where, declared, read, !unproduced
596
+ ? ""
597
+ : kind === "connection"
598
+ ? `It reads node '${path[0]}'${path.length === 1 ? " WHOLE" : ` at .${path.slice(1).join(".")}`}, and that node is \`relationKind:"connection"\` — its unproduced value is ` +
599
+ `the EMPTY connection {items:[],cursor:null}, never null (run_behavior's writeUnproduced writes it, and the produced-aware native lowering emits it), ` +
600
+ `so what arrives here is ${path.length === 1 ? "that empty connection" : `its .${path.slice(1).join(".")}`} and a null case cannot occur. ` +
601
+ `Drop the node's \`relationKind\` annotation if its unproduced value really is null (the annotation's ABSENCE means null).`
602
+ : `It reads node '${path[0]}', which can be UNPRODUCED (a 'continue' policy, a null bindField bound, or an unproduced parent), ` +
603
+ `so what arrives is the produced value OR the unproduced one (null) — the declaration has to hold both. ` +
604
+ `Annotate the node \`relationKind:"connection"\` if its unproduced value really is the empty connection (the annotation's ABSENCE means null).`);
388
605
  }
389
- /** 式が body ノード結果参照(`{ref|refOpt:[head,…]}`)ならその path を返す。 */
390
- function refPath(expr) {
606
+ /**
607
+ * declaredMismatch — 宣言型とその位置で materialize される型の食い違いを報告する**唯一**の点(#243)。
608
+ * 出力位置の全 reject(参照位置・object 合成の形・配列リテラルの形)がここを通る。
609
+ */
610
+ function declaredMismatch(where, declared, materialised, why) {
611
+ badNodeType(`${where}: the declared type is '${portableTypeNotation(declared)}', but the value that materialises there has type ` +
612
+ `'${portableTypeNotation(materialised)}'. The declaration IS the contract, so it must be exactly what the body puts ` +
613
+ `there — neither narrower (a value it cannot hold) nor wider (a case that cannot occur).` +
614
+ (why === "" ? "" : ` ${why}`));
615
+ }
616
+ /** 式が body ノード結果参照(`{ref|refOpt:[head,…]}`)なら operator と path を返す。 */
617
+ function refOf(expr) {
391
618
  if (expr === null || typeof expr !== "object" || Array.isArray(expr))
392
619
  return undefined;
393
620
  const keys = Object.keys(expr);
394
621
  if (keys.length !== 1 || (keys[0] !== "ref" && keys[0] !== "refOpt"))
395
622
  return undefined;
396
623
  const path = expr[keys[0]];
397
- return Array.isArray(path) && typeof path[0] === "string" ? path : undefined;
624
+ return Array.isArray(path) && typeof path[0] === "string" ? { op: keys[0], path: path } : undefined;
398
625
  }
626
+ /** 式が単一 operator キー `op` の構築ノード(`{obj:…}` / `{arr:…}`)ならその引数を返す。 */
627
+ function ctorArg(expr, op) {
628
+ if (expr === null || typeof expr !== "object" || Array.isArray(expr))
629
+ return undefined;
630
+ const keys = Object.keys(expr);
631
+ return keys.length === 1 && keys[0] === op ? expr[op] : undefined;
632
+ }
633
+ /**
634
+ * resolveOutputType — `output` 式を**宣言型と対で**降りながら解決し、`outputType` を返す。
635
+ *
636
+ * Φ 合成の構造(`{obj:…}` / `{arr:…}` の**リテラル構築**)は宣言型と一緒に降りる。そうしないと入れ子の
637
+ * 参照位置が突き合わせから漏れる(トップの 1 段だけ見ていたのが #243 の穴の一部)。降下は {@link descend}
638
+ * (型降下の SSoT)。未確定フィールドは個別に名指して `UNTYPED_NODE`(AC1 の「naming the field」)。
639
+ *
640
+ * リテラル/演算結果の位置(参照でも構築でもない終端)は宣言型が materialize を駆動する側なので
641
+ * {@link outputPositionType} が突き合わせる(例: 合成 connection の `cursor: null` は宣言 `{opt:string}`
642
+ * の住人 — de-box が宣言型に対して total なのと同じ規律 #233)。
643
+ */
399
644
  function resolveOutputType(output, nodeTypes, inputPorts, method, unproducible, kindOf,
400
645
  // 宣言された出力契約(生 IR 経路では IR が運ぶ。authoring 経路ではまだ無い — outputContract が後で導出型と
401
- // 突き合わせる)。フィールドへは {@link descend}(型降下の SSoT)で降りる。
646
+ // 突き合わせる)。
402
647
  declaredOutput) {
403
- // object 合成: フィールドごとに解決し、未確定フィールドを名指す。
404
- if (output !== null && typeof output === "object" && !Array.isArray(output)) {
405
- const rec = output;
406
- const keys = Object.keys(rec);
407
- if (keys.length === 1 && keys[0] === "obj") {
408
- const fields = rec.obj;
648
+ const where = (field) => field === "" ? `method '${method}': the output` : `method '${method}': output composition field '${field}'`;
649
+ // 注記は変数側に置く(control-flow narrowing が `never` 復帰を見るのは注記付き const だけ)。
650
+ const noType = (field) => field === ""
651
+ ? untyped(`method '${method}': the output has no determined type — its value is not resolvable to a portable type (annotate the terminal node with .as<T>(); SA5, fail-closed UNTYPED_NODE)`)
652
+ : untyped(`method '${method}': output composition field '${field}' has no determined type — the value it wires is not resolvable to a portable type (annotate the referenced node with .as<T>() so its type is determined; SA5, fail-closed UNTYPED_NODE)`);
653
+ const walk = (expr, declared, field) => {
654
+ const fields = ctorArg(expr, "obj");
655
+ if (fields !== undefined && fields !== null && typeof fields === "object" && !Array.isArray(fields)) {
409
656
  const obj = {};
410
- for (const [k, v] of Object.entries(fields)) {
411
- const ft = resolveExprType(v, nodeTypes, inputPorts);
412
- if (ft === undefined)
413
- untyped(`method '${method}': output composition field '${k}' has no determined type — the value it wires is not resolvable to a portable type (annotate the referenced node with .as<T>() so its type is determined; SA5, fail-closed UNTYPED_NODE)`);
414
- obj[k] = outputRefUnproduced(`method '${method}': output composition field '${k}'`, v, ft, declaredOutput === undefined ? undefined : descend(declaredOutput, k), unproducible, kindOf);
415
- }
657
+ for (const [k, v] of Object.entries(fields))
658
+ obj[k] = walk(v, declared === undefined ? undefined : descend(declared, k), field === "" ? k : `${field}.${k}`);
659
+ // フィールド集合そのものの一致(宣言に無いキーを組む / 宣言のキーを組まない / そもそも obj でない)。
660
+ // 各フィールドの型は再帰が既に突き合わせているので、ここで見るのは**この段の形**だけ。
661
+ const dObj = declared !== undefined && typeof declared === "object" && "obj" in declared ? declared.obj : undefined;
662
+ if (declared !== undefined &&
663
+ (dObj === undefined ||
664
+ Object.keys(dObj).length !== Object.keys(obj).length ||
665
+ Object.keys(obj).some((k) => !(k in dObj))))
666
+ declaredMismatch(where(field), declared, { obj }, "");
416
667
  return { obj };
417
668
  }
418
- }
419
- // 非 object 合成(単一 ref / 演算式 / スカラ等): 全体を解決。
420
- const t0 = resolveExprType(output, nodeTypes, inputPorts);
421
- const t = t0 === undefined
422
- ? undefined
423
- : outputRefUnproduced(`method '${method}': the output`, output, t0, declaredOutput, unproducible, kindOf);
424
- if (t === undefined)
425
- untyped(`method '${method}': the output has no determined type — its value is not resolvable to a portable type (annotate the terminal node with .as<T>(); SA5, fail-closed UNTYPED_NODE)`);
426
- return t;
669
+ const elems = ctorArg(expr, "arr");
670
+ if (Array.isArray(elems)) {
671
+ const dArr = declared !== undefined && typeof declared === "object" && "arr" in declared ? declared.arr : undefined;
672
+ if (declared !== undefined && dArr === undefined)
673
+ noType(field); // 宣言が配列でない位置に配列リテラル
674
+ if (elems.length === 0)
675
+ noType(field); // 空配列は要素型が定まらない(resolveExprType と同じ)
676
+ const ts = elems.map((e, i) => walk(e, dArr, `${field}[${i}]`));
677
+ if (ts.some((t) => !sameType(t, ts[0])))
678
+ noType(field); // 同種配列でなければ未確定
679
+ return { arr: ts[0] };
680
+ }
681
+ const t = resolveExprType(expr, nodeTypes, inputPorts);
682
+ if (t === undefined)
683
+ noType(field);
684
+ return outputPositionType(where(field), expr, t, declared, unproducible, kindOf);
685
+ };
686
+ return walk(output, declaredOutput, "");
427
687
  }
428
688
  /** body ノード種のラベル(診断メッセージ用)。 */
429
689
  function nodeKindLabel(n) {