behavior-contracts 0.9.1 → 0.9.2

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.
@@ -548,14 +548,23 @@ ${probeArms}
548
548
  ${I}}`;
549
549
  }
550
550
  /**
551
- * renderRustWireBox — the ONE inline BOX renderer (typed→wire), the mirror of renderRustDeBox. Folds a
552
- * language-neutral {@link WirePlan} (the SAME SSoT walk, `dir:"in"`) into a Rust EXPRESSION evaluating to an
553
- * owned `WireValue` built from `srcExpr` (an OWNED native typed value of the plan's type). `value` is
554
- * identity (already the opaque wire); a native scalar wraps in its wire ctor. A `value[]` bound-value list
555
- * carries scalar / opaque elements, so those are the covered element shapes; a nested opt / collection /
556
- * record element is fail-closed here (C1 — the compound box lands with the batched WireRow contract).
551
+ * renderRustWireBox — the ONE inline BOX renderer (typed→wire), the mirror of renderRustDeBox and the twin of
552
+ * renderGoWireBox. Folds a language-neutral {@link WirePlan} (the SAME SSoT walk {@link buildWirePlan},
553
+ * `dir:"in"`) into a Rust EXPRESSION evaluating to an owned `WireValue` built from the OWNED `srcExpr`. The
554
+ * walk is TOTAL over the plan's non-opt kinds (bc#178) and RECURSIVE over the declared element type, so a
555
+ * compound bound value crosses the leaf-param boundary EXACTLY ONCE (box-once; NO decode→re-box round-trip —
556
+ * `srcExpr` is already the native typed value):
557
+ * - `value` identity (already the opaque BC wire);
558
+ * - `scalar` wrap in its wire ctor (WireValue::Str/int/float/Bool);
559
+ * - `record` box each declared field recursively, assemble `WireValue::Row(WireRow{ entries })` — the typed
560
+ * `obj<…>` → wire map ("M") crossing (the real op-agnostic `arr<value>` batch-write param fed a
561
+ * typed `arr<obj>`);
562
+ * - `list` box each element recursively into `WireValue::List(WireList{ items })` ("L").
563
+ * A `map` value or an OPT-wrapped element (optDepth > 0) boxes AMBIGUOUSLY (map key order / opt present-vs-null
564
+ * on the wire are not statically pinned to run_behavior's Value pass-through), so it stays FAIL-CLOSED LOUD —
565
+ * strict-typing, no silent box. `depth` names the per-element closure binding uniquely across nesting.
557
566
  */
558
- function renderRustWireBox(plan, srcExpr) {
567
+ function renderRustWireBox(plan, srcExpr, depth = 0) {
559
568
  if (plan.optDepth === 0) {
560
569
  if (plan.k === "value")
561
570
  return srcExpr; // identity — already the opaque BC wire.
@@ -571,8 +580,19 @@ function renderRustWireBox(plan, srcExpr) {
571
580
  return `WireValue::Bool(${srcExpr})`;
572
581
  }
573
582
  }
583
+ if (plan.k === "record") {
584
+ // typed struct → wire map: box each declared field off its native struct field (moving it out of the owned
585
+ // srcExpr — no probe), assemble a WireRow of (name, WireValue) in declared-field order.
586
+ const entries = plan.fields.map((f) => `(${rustStrLit(f.name)}.to_string(), ${renderRustWireBox(f.plan, `${srcExpr}.${rustFieldName(f.name)}`, depth + 1)})`);
587
+ return `WireValue::Row(WireRow { entries: vec![${entries.join(", ")}] })`;
588
+ }
589
+ if (plan.k === "list") {
590
+ // typed Vec → wire list: consume the owned Vec, box each element recursively (box-once, no round-trip).
591
+ const e = `e${depth}`;
592
+ return `WireValue::List(WireList { items: ${srcExpr}.into_iter().map(|${e}| ${renderRustWireBox(plan.elem, e, depth + 1)}).collect() })`;
593
+ }
574
594
  }
575
- throw new GeneratorFailure("UNSUPPORTED_NODE_STRAIGHTLINE", `rust wire box: a value[] element of type '${plan.expectedType}' is not a scalar / opaque value (a nested opt/collection/record bound-value is not native-covered)`);
595
+ throw new GeneratorFailure("UNSUPPORTED_NODE_STRAIGHTLINE", `rust wire box: a value[] element of type '${plan.expectedType}' is not native-covered by the typed→wire box (an opt-wrapped or map element boxes ambiguously — fail-closed rather than risk a run_behavior divergence)`);
576
596
  }
577
597
  /** returnErrFail — the default de-box mismatch control flow: propagate the structured Error Value out of
578
598
  * the enclosing runner (fail/retry componentRef results + map/fanout element de-box, which fails closed
@@ -1089,24 +1109,43 @@ ${inits.join("\n")}
1089
1109
  * expression that yields the over Vec (#108, rust twin): prior-node arr field (cell clone) or an input
1090
1110
  * array port with elemType (`in_.<field>.clone()`). Fail-closed for an input array without elemType.
1091
1111
  */
1092
- function mapOverElemInfo(comp, node, typedNodes, plan) {
1093
- const m = node.map;
1094
- const e = classifyExpr(m.over);
1112
+ /**
1113
+ * rustOverElemInfo — the ONE resolver of a fanout/map `over` to its element TypeRef + the OWNED Rust
1114
+ * over expression (map/fanout twins both delegate — single definition, no forked copy).
1115
+ *
1116
+ * `optArr` is true when the over's declared type is `{opt:{arr}}` (a prior-node opt-arr field OR an OPT
1117
+ * input array port). #177 (A): a null opt-arr over then iterates EMPTY — the emitted `overExpr` is an
1118
+ * `Option<Vec<E>>`, which the arm binds via `.unwrap_or_default()` (None → empty Vec), byte-equal to
1119
+ * run_behavior. A REQUIRED arr (None) still fails run_behavior FANOUT/MAP_OVER_NOT_ARRAY → optArr:false.
1120
+ */
1121
+ function rustOverElemInfo(comp, over, typedNodes, plan, nodeId, label) {
1122
+ const e = classifyExpr(over);
1095
1123
  if (e.kind === "ref" && e.path.length >= 1 && typedNodes.has(e.path[0])) {
1096
1124
  const baseRef = typedNodes.get(e.path[0]);
1097
1125
  const { ref } = typedFieldAccess(`${typedCell(e.path[0])}.borrow()`, baseRef, e.path.slice(1), plan);
1126
+ const fieldPath = e.path.slice(1).map((p) => `.${rustFieldName(p)}`).join("");
1098
1127
  if (ref.kind === "arr") {
1099
- const fieldPath = e.path.slice(1).map((p) => `.${rustFieldName(p)}`).join("");
1100
- return { elemRef: ref.elem, overExpr: `${typedCell(e.path[0])}.borrow()${fieldPath}.clone()` };
1128
+ return { elemRef: ref.elem, overExpr: `${typedCell(e.path[0])}.borrow()${fieldPath}.clone()`, optArr: false };
1129
+ }
1130
+ if (ref.kind === "opt" && ref.inner.kind === "arr") {
1131
+ return { elemRef: ref.inner.elem, overExpr: `${typedCell(e.path[0])}.borrow()${fieldPath}.clone()`, optArr: true };
1101
1132
  }
1102
1133
  }
1103
1134
  if (e.kind === "ref" && e.path.length === 1) {
1104
1135
  const schema = comp.inputPorts?.[e.path[0]];
1105
1136
  const et = schema?.elemType;
1106
1137
  if (et !== undefined)
1107
- return { elemRef: deriveTypeRef(et, plan), overExpr: `in_.${rustFieldName(e.path[0])}.clone()` };
1138
+ return { elemRef: deriveTypeRef(et, plan), overExpr: `in_.${rustFieldName(e.path[0])}.clone()`, optArr: inputPortIsOptional(schema) };
1108
1139
  }
1109
- throw new GeneratorFailure("UNSUPPORTED_NODE_STRAIGHTLINE", `rust combined map (#108): map '${node.id}' 'over' must be a ref to a prior node's typed arr field OR an input array port with a declared elemType. BC does not infer input-array element types (consumer-interface C3).`);
1140
+ throw new GeneratorFailure("UNSUPPORTED_NODE_STRAIGHTLINE", `rust ${label}: '${nodeId}' 'over' must be a ref to a prior node's typed arr field OR an input array port with a declared elemType. BC does not infer input-array element types (consumer-interface C3).`);
1141
+ }
1142
+ /** rustBindOverExpr — the RHS `let over_<s> = …;` expr. An opt-arr over (#177 (A)) unwraps its
1143
+ * `Option<Vec<E>>` to an empty Vec on None so iteration is 0-length (byte-equal to run_behavior). */
1144
+ function rustBindOverExpr(overExpr, optArr) {
1145
+ return optArr ? `${overExpr}.unwrap_or_default()` : overExpr;
1146
+ }
1147
+ function mapOverElemInfo(comp, node, typedNodes, plan) {
1148
+ return rustOverElemInfo(comp, node.map.over, typedNodes, plan, node.id, "combined map (#108)");
1110
1149
  }
1111
1150
  /** The Rust type of the over-element (back-compat shim). */
1112
1151
  function mapOverElemType(comp, node, typedNodes, plan) {
@@ -1257,17 +1296,14 @@ function coveredMapNode(n, bodyIds, comp) {
1257
1296
  return false;
1258
1297
  const head = overE.path[0];
1259
1298
  if (!bodyIds.has(head)) {
1260
- // input-array over: covered only when the port declares elemType (#108) AND is REQUIRED. #177: an OPT
1261
- // input-array (`{opt:{arr}}`, required:false) resolves to `in_.<field>` of `Option<Vec<E>>` — iterating
1262
- // it does not yield the element type, and run_behavior FAILS MAP_OVER_NOT_ARRAY on a null opt
1263
- // collection — so fail-close here is byte-equal (a faithful nil→empty over is an owner-level decision).
1299
+ // input-array over: covered only when the port declares elemType (#108 — C3, no inference). #177 (A):
1300
+ // an OPT input array (`{opt:{arr}}`, required:false) IS covered — its null iterates EMPTY
1301
+ // (rustOverElemInfo.optArr → `.unwrap_or_default()`, None → empty Vec), byte-equal to run_behavior.
1264
1302
  if (overE.path.length !== 1)
1265
1303
  return false;
1266
1304
  const schema = comp.inputPorts?.[head];
1267
1305
  if (schema === undefined || schema.elemType === undefined)
1268
1306
  return false;
1269
- if (inputPortIsOptional(schema))
1270
- return false;
1271
1307
  }
1272
1308
  const ports = m.ports;
1273
1309
  const plan = planForComp(comp);
@@ -1295,17 +1331,14 @@ function coveredFanoutNode(n, bodyIds, comp) {
1295
1331
  return false;
1296
1332
  const head = overE.path[0];
1297
1333
  if (!bodyIds.has(head)) {
1298
- // input-array over: covered only when the port declares elemType AND is REQUIRED. #177: an OPT
1299
- // input-array (`{opt:{arr}}`, required:false) resolves to `in_.<field>` of `Option<Vec<E>>` —
1300
- // iterating it does not yield the element type, and run_behavior FAILS FANOUT_OVER_NOT_ARRAY on a
1301
- // null opt collection — so fail-close here is byte-equal (a faithful nil→empty over is owner-level).
1334
+ // input-array over: covered only when the port declares elemType (C3 — no inference). #177 (A): an OPT
1335
+ // input array (`{opt:{arr}}`, required:false) IS covered — its null iterates EMPTY
1336
+ // (rustOverElemInfo.optArr → `.unwrap_or_default()`, None → empty Vec), byte-equal to run_behavior.
1302
1337
  if (overE.path.length !== 1)
1303
1338
  return false;
1304
1339
  const schema = comp.inputPorts?.[head];
1305
1340
  if (schema === undefined || schema.elemType === undefined)
1306
1341
  return false;
1307
- if (inputPortIsOptional(schema))
1308
- return false;
1309
1342
  }
1310
1343
  const ports = f.ports;
1311
1344
  const plan = planForComp(comp);
@@ -1333,25 +1366,9 @@ function fanoutItemsElemRef(node, connRef, plan) {
1333
1366
  throw new GeneratorFailure("UNSUPPORTED_NODE_STRAIGHTLINE", `rust fanout (v3): node '${node.id}' connection struct '${connRef.name}' has no 'items' array field.`);
1334
1367
  return itemsField.type.elem;
1335
1368
  }
1336
- /** fanoutOverElemInfo (v3, rust twin) — the over id-list element TypeRef + the OWNED over-Vec expr. */
1369
+ /** fanoutOverElemInfo (v3, rust twin) — delegates to {@link rustOverElemInfo} reading the fanout spec. */
1337
1370
  function fanoutOverElemInfo(comp, node, typedNodes, plan) {
1338
- const f = node.fanout;
1339
- const e = classifyExpr(f.over);
1340
- if (e.kind === "ref" && e.path.length >= 1 && typedNodes.has(e.path[0])) {
1341
- const baseRef = typedNodes.get(e.path[0]);
1342
- const { ref } = typedFieldAccess(`${typedCell(e.path[0])}.borrow()`, baseRef, e.path.slice(1), plan);
1343
- if (ref.kind === "arr") {
1344
- const fieldPath = e.path.slice(1).map((p) => `.${rustFieldName(p)}`).join("");
1345
- return { elemRef: ref.elem, overExpr: `${typedCell(e.path[0])}.borrow()${fieldPath}.clone()` };
1346
- }
1347
- }
1348
- if (e.kind === "ref" && e.path.length === 1) {
1349
- const schema = comp.inputPorts?.[e.path[0]];
1350
- const et = schema?.elemType;
1351
- if (et !== undefined)
1352
- return { elemRef: deriveTypeRef(et, plan), overExpr: `in_.${rustFieldName(e.path[0])}.clone()` };
1353
- }
1354
- throw new GeneratorFailure("UNSUPPORTED_NODE_STRAIGHTLINE", `rust fanout (v3): fanout '${node.id}' 'over' must be a ref to a prior node's typed arr field OR an input array port with a declared elemType.`);
1371
+ return rustOverElemInfo(comp, node.fanout.over, typedNodes, plan, node.id, "fanout (v3)");
1355
1372
  }
1356
1373
  /** A covered read SHAPE with static ports + native-lowerable output (+ covered map...into), OR a
1357
1374
  * real-concurrency staged plan (bc#87) whose parallel-stage members are plain componentRef point reads. */
@@ -2004,7 +2021,7 @@ isAsync = false) {
2004
2021
  const batch = `${structName}Batch`;
2005
2022
  const leafSym = resolveLeafSymbol(m.component, leaf);
2006
2023
  // #108: over element type + the OWNED over-Vec expression (prior-node arr OR input array w/ elemType).
2007
- const { elemRef: overElemRef, overExpr } = mapOverElemInfo(comp, node, typedNodes, plan);
2024
+ const { elemRef: overElemRef, overExpr, optArr: overOptArr } = mapOverElemInfo(comp, node, typedNodes, plan);
2008
2025
  const elemMat = mapElemMaterializerName(comp.name, node.id);
2009
2026
  const priorHere = (head) => priorNodeAt(head, atPos);
2010
2027
  const asName = m.as;
@@ -2062,7 +2079,7 @@ isAsync = false) {
2062
2079
  closers.unshift(`${indent}}`);
2063
2080
  indent += " ";
2064
2081
  }
2065
- lines.push(`${indent}let over_${s} = ${overExpr};`);
2082
+ lines.push(`${indent}let over_${s} = ${rustBindOverExpr(overExpr, overOptArr)};`);
2066
2083
  lines.push(`${indent}let mut built_${s}: Vec<${elemName}> = Vec::with_capacity(over_${s}.len());`);
2067
2084
  if (batched && keepWithNull) {
2068
2085
  // #177 BATCHED keep-with-null (guarded map...into, opt into): pass 1 records, per over element, whether
@@ -2215,7 +2232,7 @@ function emitFanoutArm(comp, node, atPos, typedNodes, plan, priorNodeAt, leaf, i
2215
2232
  const connRef = typedNodes.get(node.id);
2216
2233
  const elemRef = fanoutItemsElemRef(node, connRef, plan);
2217
2234
  const elemName = renderTypeRef(elemRef);
2218
- const { elemRef: overElemRef, overExpr } = fanoutOverElemInfo(comp, node, typedNodes, plan);
2235
+ const { elemRef: overElemRef, overExpr, optArr: overOptArr } = fanoutOverElemInfo(comp, node, typedNodes, plan);
2219
2236
  const asName = f.as;
2220
2237
  const priorHere = (head) => priorNodeAt(head, atPos);
2221
2238
  const portNames = Object.keys(f.ports);
@@ -2243,7 +2260,7 @@ function emitFanoutArm(comp, node, atPos, typedNodes, plan, priorNodeAt, leaf, i
2243
2260
  closers.unshift(`${indent}}`);
2244
2261
  indent += " ";
2245
2262
  }
2246
- lines.push(`${indent}let over_${s} = ${overExpr};`);
2263
+ lines.push(`${indent}let over_${s} = ${rustBindOverExpr(overExpr, overOptArr)};`);
2247
2264
  lines.push(`${indent}let mut built_${s}: Vec<${elemName}> = Vec::new();`);
2248
2265
  lines.push(`${indent}let mut pi_${s}: Vec<${structName}> = Vec::with_capacity(over_${s}.len());`);
2249
2266
  lines.push(`${indent}for oel_${s} in over_${s}.iter() {`);
@@ -3033,7 +3050,8 @@ function emitInDecoder(comp, plan) {
3033
3050
  lines.push(` Value::Arr(a) => {`);
3034
3051
  lines.push(` let mut dec: Vec<${elemTy}> = Vec::with_capacity(a.len());`);
3035
3052
  lines.push(` for ev in a.iter() { dec.push(${mat}); }`);
3036
- lines.push(` in_.${field} = dec;`);
3053
+ // #177 (A): an OPTIONAL array port field is `Option<Vec<E>>` (inputPortTypeRef opt), so wrap in Some.
3054
+ lines.push(` in_.${field} = ${inputPortIsOptional(schema) ? "Some(dec)" : "dec"};`);
3037
3055
  lines.push(` }`);
3038
3056
  lines.push(` other => return Err(marshal_type_error(${rustStrLit(`decode input ${p}: expected array, got `)}, other.type_name())),`);
3039
3057
  lines.push(` }`);