behavior-contracts 0.9.0 → 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.
@@ -2,7 +2,7 @@ import { GeneratorFailure } from "./core.js";
2
2
  import { isControlGate, nodeWirePassthrough } from "../behavior.js";
3
3
  import { rustStraightlineInternals } from "./emit-shared-rust.js";
4
4
  import { rustTypedInternals } from "./emit-shared-rust-typed.js";
5
- import { buildTypePlan, deriveTypeRef, findDecl, inputPortIsOptional, inputPortTypeRef } from "./typed.js";
5
+ import { buildTypePlan, deriveTypeRef, findDecl, guardedMapIntoIsOpt, inputPortIsOptional, inputPortTypeRef } from "./typed.js";
6
6
  import { concurrencyPlan, execPlan, analyzeSequentialOps, classifyExpr, nodeNarrowedPaths } from "./straightline.js";
7
7
  import { NativeExprCompiler } from "./native-expr.js";
8
8
  import { buildAsyncPlans } from "./async-plan.js";
@@ -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) {
@@ -1233,10 +1272,13 @@ function coveredMapNode(n, bodyIds, comp) {
1233
1272
  if (n === null || typeof n !== "object" || !("map" in n))
1234
1273
  return false;
1235
1274
  const m = n.map;
1236
- // #108 (rust twin of the go predicate): a guarded map (`when`) IS covered with NO `into` (guard+into
1237
- // is heterogeneous — fail-closed). over element type must be statically resolvable: prior-node arr
1238
- // field, or an input array port carrying `elemType` (BC does not infer — consumer-interface C3).
1239
- if (m.when !== undefined && m.into !== undefined)
1275
+ // #108 (rust twin of the go predicate): a guarded map (`when`) IS covered with NO `into`. #177: a
1276
+ // guarded map WITH `into` is covered ONLY when the into field is OPT (keep-with-null — kept element →
1277
+ // present into, guard-skipped element → into=None), byte-equal to run_behavior applyInto pass-through +
1278
+ // opt-into null. A REQUIRED into field → run_behavior FAILS MISSING_PROP on a skipped element, so
1279
+ // fail-close is byte-equal. over element type must be statically resolvable: prior-node arr field, or
1280
+ // an input array port carrying `elemType` (BC does not infer — consumer-interface C3).
1281
+ if (m.when !== undefined && m.into !== undefined && !guardedMapIntoIsOpt(n, comp))
1240
1282
  return false;
1241
1283
  if (m.policy !== undefined && m.policy !== "fail")
1242
1284
  return false;
@@ -1254,6 +1296,9 @@ function coveredMapNode(n, bodyIds, comp) {
1254
1296
  return false;
1255
1297
  const head = overE.path[0];
1256
1298
  if (!bodyIds.has(head)) {
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.
1257
1302
  if (overE.path.length !== 1)
1258
1303
  return false;
1259
1304
  const schema = comp.inputPorts?.[head];
@@ -1286,6 +1331,9 @@ function coveredFanoutNode(n, bodyIds, comp) {
1286
1331
  return false;
1287
1332
  const head = overE.path[0];
1288
1333
  if (!bodyIds.has(head)) {
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.
1289
1337
  if (overE.path.length !== 1)
1290
1338
  return false;
1291
1339
  const schema = comp.inputPorts?.[head];
@@ -1318,25 +1366,9 @@ function fanoutItemsElemRef(node, connRef, plan) {
1318
1366
  throw new GeneratorFailure("UNSUPPORTED_NODE_STRAIGHTLINE", `rust fanout (v3): node '${node.id}' connection struct '${connRef.name}' has no 'items' array field.`);
1319
1367
  return itemsField.type.elem;
1320
1368
  }
1321
- /** 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. */
1322
1370
  function fanoutOverElemInfo(comp, node, typedNodes, plan) {
1323
- const f = node.fanout;
1324
- const e = classifyExpr(f.over);
1325
- if (e.kind === "ref" && e.path.length >= 1 && typedNodes.has(e.path[0])) {
1326
- const baseRef = typedNodes.get(e.path[0]);
1327
- const { ref } = typedFieldAccess(`${typedCell(e.path[0])}.borrow()`, baseRef, e.path.slice(1), plan);
1328
- if (ref.kind === "arr") {
1329
- const fieldPath = e.path.slice(1).map((p) => `.${rustFieldName(p)}`).join("");
1330
- return { elemRef: ref.elem, overExpr: `${typedCell(e.path[0])}.borrow()${fieldPath}.clone()` };
1331
- }
1332
- }
1333
- if (e.kind === "ref" && e.path.length === 1) {
1334
- const schema = comp.inputPorts?.[e.path[0]];
1335
- const et = schema?.elemType;
1336
- if (et !== undefined)
1337
- return { elemRef: deriveTypeRef(et, plan), overExpr: `in_.${rustFieldName(e.path[0])}.clone()` };
1338
- }
1339
- 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)");
1340
1372
  }
1341
1373
  /** A covered read SHAPE with static ports + native-lowerable output (+ covered map...into), OR a
1342
1374
  * real-concurrency staged plan (bc#87) whose parallel-stage members are plain componentRef point reads. */
@@ -1980,12 +2012,16 @@ isAsync = false) {
1980
2012
  const batched = m.batched === true;
1981
2013
  const hasInto = m.into !== undefined;
1982
2014
  const hasGuard = m.when !== undefined;
2015
+ // #177 keep-with-null: a guarded map WITH `into` keeps guard-skipped elements with the (opt) into field
2016
+ // set to None (coveredMapNode only admits this when the into field is opt). A guarded NO-into map DROPs
2017
+ // skipped elements instead. Byte-equal to run_behavior's applyInto keep-with-null.
2018
+ const keepWithNull = hasGuard && hasInto;
1983
2019
  const s = sanitize(node.id);
1984
2020
  const structName = portsStructName(comp.name, node.id);
1985
2021
  const batch = `${structName}Batch`;
1986
2022
  const leafSym = resolveLeafSymbol(m.component, leaf);
1987
2023
  // #108: over element type + the OWNED over-Vec expression (prior-node arr OR input array w/ elemType).
1988
- const { elemRef: overElemRef, overExpr } = mapOverElemInfo(comp, node, typedNodes, plan);
2024
+ const { elemRef: overElemRef, overExpr, optArr: overOptArr } = mapOverElemInfo(comp, node, typedNodes, plan);
1989
2025
  const elemMat = mapElemMaterializerName(comp.name, node.id);
1990
2026
  const priorHere = (head) => priorNodeAt(head, atPos);
1991
2027
  const asName = m.as;
@@ -2011,19 +2047,27 @@ isAsync = false) {
2011
2047
  return out;
2012
2048
  };
2013
2049
  // #108 guard: compile `when` to a native bool over an element-scoped resolveHead ($as element value,
2014
- // prior node, input port). On skip: `continue` (element excluded — matches run_behavior's keep-gate).
2015
- const emitGuard = (il) => {
2050
+ // prior node, input port). mkGuard returns the compiled {stmts, expr} (or null when unguarded); the
2051
+ // keep-with-null batched path consumes it directly to branch instead of skipping.
2052
+ const mkGuard = () => {
2016
2053
  if (!hasGuard)
2017
- return [];
2054
+ return null;
2018
2055
  const resolveHead = nativeResolveHead(comp, plan, typedNodes, priorHere, { asBinding: { name: asName, ref: overElemRef, plan }, asBase: `oel_${s}` });
2019
- const g = new NativeExprCompiler(makeRustExprBackend(resolveHead, plan)).compileBool(m.when);
2056
+ return new NativeExprCompiler(makeRustExprBackend(resolveHead, plan)).compileBool(m.when);
2057
+ };
2058
+ // On skip: `continue;` by default (element excluded — matches run_behavior's keep-gate); #177
2059
+ // keep-with-null non-batched passes a skip that first pushes the into=None element.
2060
+ const emitGuard = (il, onSkip = "continue;") => {
2061
+ const g = mkGuard();
2062
+ if (g === null)
2063
+ return [];
2020
2064
  const out = [];
2021
2065
  for (const st of g.stmts)
2022
2066
  out.push(`${il}${st}`);
2023
2067
  // bind the keep flag to a var so clippy's nonminimal_bool doesn't rewrite `!(a > b)` (the `when`
2024
2068
  // expr must stay verbatim = run_behavior's `{cond:[when,true,false]}` strict-bool keep-gate).
2025
2069
  out.push(`${il}let __keep = ${rustStripOuterParens(g.expr)};`);
2026
- out.push(`${il}if !__keep { continue; }`);
2070
+ out.push(`${il}if !__keep { ${onSkip} }`);
2027
2071
  return out;
2028
2072
  };
2029
2073
  const lines = [];
@@ -2035,9 +2079,57 @@ isAsync = false) {
2035
2079
  closers.unshift(`${indent}}`);
2036
2080
  indent += " ";
2037
2081
  }
2038
- lines.push(`${indent}let over_${s} = ${overExpr};`);
2082
+ lines.push(`${indent}let over_${s} = ${rustBindOverExpr(overExpr, overOptArr)};`);
2039
2083
  lines.push(`${indent}let mut built_${s}: Vec<${elemName}> = Vec::with_capacity(over_${s}.len());`);
2040
- if (batched) {
2084
+ if (batched && keepWithNull) {
2085
+ // #177 BATCHED keep-with-null (guarded map...into, opt into): pass 1 records, per over element, whether
2086
+ // it is kept (guard true → build ports) or skipped, preserving ORDER. ONE batched dispatch over the
2087
+ // kept ports, its aligned rows de-boxed into `decs`. Pass 2 re-walks over IN ORDER: a kept element
2088
+ // zips its next deboxed row, a skipped element gets into=None. Byte-equal to run_behavior: batched
2089
+ // keptIdx-aligned collect + applyInto (skipped element unaugmented → opt-into null).
2090
+ const g = mkGuard();
2091
+ lines.push(`${indent}let mut items_${s}: Vec<${structName}> = Vec::with_capacity(over_${s}.len());`);
2092
+ lines.push(`${indent}let mut keep_${s}: Vec<bool> = Vec::with_capacity(over_${s}.len());`);
2093
+ lines.push(`${indent}for oel_${s} in over_${s}.iter() {`);
2094
+ for (const st of g.stmts)
2095
+ lines.push(`${indent} ${st}`);
2096
+ lines.push(`${indent} let __keep = ${rustStripOuterParens(g.expr)};`);
2097
+ lines.push(`${indent} if __keep {`);
2098
+ for (const l of buildPorts(indent + " "))
2099
+ lines.push(l);
2100
+ lines.push(`${indent} items_${s}.push(ep_${s});`);
2101
+ lines.push(`${indent} keep_${s}.push(true);`);
2102
+ lines.push(`${indent} } else {`);
2103
+ lines.push(`${indent} keep_${s}.push(false);`);
2104
+ lines.push(`${indent} }`);
2105
+ lines.push(`${indent}}`);
2106
+ lines.push(`${indent}let mut decs_${s}: Vec<${renderTypeRef(elemDeBoxRef)}> = Vec::with_capacity(items_${s}.len());`);
2107
+ lines.push(`${indent}if !items_${s}.is_empty() {`);
2108
+ lines.push(`${indent} let want_${s} = items_${s}.len();`);
2109
+ lines.push(`${indent} let bp_${s} = ${batch} { items: items_${s} };`);
2110
+ lines.push(`${indent} let row_${s} = match ${leafSym}(&bp_${s})${awaitSfx} {`);
2111
+ lines.push(`${indent} Ok(r) => r,`);
2112
+ lines.push(`${indent} Err(e) => return Err(op_failed(${rustStrLit(node.id)}, "fail", e)),`);
2113
+ lines.push(`${indent} };`);
2114
+ lines.push(`${indent} if row_${s}.len() != want_${s} {`);
2115
+ lines.push(`${indent} return Err(BehaviorError::new("MAP_BATCH_RESULT_MISMATCH", format!("map '{}': batched handler must return a list aligned to items (want {})", ${rustStrLit(node.id)}, want_${s})));`);
2116
+ lines.push(`${indent} }`);
2117
+ lines.push(`${indent} for er_${s} in row_${s}.into_iter() {`);
2118
+ lines.push(`${indent} let dec_${s} = ${renderElemDeBox(`${indent} `)};`);
2119
+ lines.push(`${indent} decs_${s}.push(dec_${s});`);
2120
+ lines.push(`${indent} }`);
2121
+ lines.push(`${indent}}`);
2122
+ lines.push(`${indent}let mut decs_iter_${s} = decs_${s}.into_iter();`);
2123
+ lines.push(`${indent}for (oel_${s}, kept_${s}) in over_${s}.iter().zip(keep_${s}.iter()) {`);
2124
+ lines.push(`${indent} if *kept_${s} {`);
2125
+ lines.push(`${indent} let dec_${s} = decs_iter_${s}.next().expect("aligned kept row");`);
2126
+ lines.push(`${indent} built_${s}.push(${elemMat}(oel_${s}, dec_${s}));`);
2127
+ lines.push(`${indent} } else {`);
2128
+ lines.push(`${indent} built_${s}.push(${elemMat}(oel_${s}, None));`);
2129
+ lines.push(`${indent} }`);
2130
+ lines.push(`${indent}}`);
2131
+ }
2132
+ else if (batched) {
2041
2133
  // build kept-element ports (+ kept over elements for into). Batched into is never guarded (rejected).
2042
2134
  lines.push(`${indent}let mut items_${s}: Vec<${structName}> = Vec::with_capacity(over_${s}.len());`);
2043
2135
  if (hasInto)
@@ -2086,7 +2178,10 @@ isAsync = false) {
2086
2178
  else {
2087
2179
  // #93 shape 2 / #108: NON-batched map — dispatch ONCE PER KEPT ELEMENT.
2088
2180
  lines.push(`${indent}for oel_${s} in over_${s}.iter() {`);
2089
- for (const l of emitGuard(indent + " "))
2181
+ // #177 keep-with-null: a guard-skipped element is KEPT with into=None instead of dropped — byte-equal
2182
+ // to run_behavior's applyInto pass-through + opt-into null.
2183
+ const nonBatchedSkip = keepWithNull ? `built_${s}.push(${elemMat}(oel_${s}, None)); continue;` : "continue;";
2184
+ for (const l of emitGuard(indent + " ", nonBatchedSkip))
2090
2185
  lines.push(l);
2091
2186
  for (const l of buildPorts(indent + " "))
2092
2187
  lines.push(l);
@@ -2137,7 +2232,7 @@ function emitFanoutArm(comp, node, atPos, typedNodes, plan, priorNodeAt, leaf, i
2137
2232
  const connRef = typedNodes.get(node.id);
2138
2233
  const elemRef = fanoutItemsElemRef(node, connRef, plan);
2139
2234
  const elemName = renderTypeRef(elemRef);
2140
- const { elemRef: overElemRef, overExpr } = fanoutOverElemInfo(comp, node, typedNodes, plan);
2235
+ const { elemRef: overElemRef, overExpr, optArr: overOptArr } = fanoutOverElemInfo(comp, node, typedNodes, plan);
2141
2236
  const asName = f.as;
2142
2237
  const priorHere = (head) => priorNodeAt(head, atPos);
2143
2238
  const portNames = Object.keys(f.ports);
@@ -2165,7 +2260,7 @@ function emitFanoutArm(comp, node, atPos, typedNodes, plan, priorNodeAt, leaf, i
2165
2260
  closers.unshift(`${indent}}`);
2166
2261
  indent += " ";
2167
2262
  }
2168
- lines.push(`${indent}let over_${s} = ${overExpr};`);
2263
+ lines.push(`${indent}let over_${s} = ${rustBindOverExpr(overExpr, overOptArr)};`);
2169
2264
  lines.push(`${indent}let mut built_${s}: Vec<${elemName}> = Vec::new();`);
2170
2265
  lines.push(`${indent}let mut pi_${s}: Vec<${structName}> = Vec::with_capacity(over_${s}.len());`);
2171
2266
  lines.push(`${indent}for oel_${s} in over_${s}.iter() {`);
@@ -2955,7 +3050,8 @@ function emitInDecoder(comp, plan) {
2955
3050
  lines.push(` Value::Arr(a) => {`);
2956
3051
  lines.push(` let mut dec: Vec<${elemTy}> = Vec::with_capacity(a.len());`);
2957
3052
  lines.push(` for ev in a.iter() { dec.push(${mat}); }`);
2958
- 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"};`);
2959
3055
  lines.push(` }`);
2960
3056
  lines.push(` other => return Err(marshal_type_error(${rustStrLit(`decode input ${p}: expected array, got `)}, other.type_name())),`);
2961
3057
  lines.push(` }`);