behavior-contracts 0.11.18 → 0.11.20

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 (44) hide show
  1. package/README.md +14 -6
  2. package/cli-contract.yaml +9 -4
  3. package/dist/behavior.d.ts +16 -7
  4. package/dist/behavior.d.ts.map +1 -1
  5. package/dist/behavior.js +19 -8
  6. package/dist/behavior.js.map +1 -1
  7. package/dist/cli.js +4 -2
  8. package/dist/cli.js.map +1 -1
  9. package/dist/expr-eval.d.ts +8 -1
  10. package/dist/expr-eval.d.ts.map +1 -1
  11. package/dist/expr-eval.js +11 -2
  12. package/dist/expr-eval.js.map +1 -1
  13. package/dist/generated/contract.d.ts.map +1 -1
  14. package/dist/generated/contract.js +2 -2
  15. package/dist/generated/contract.js.map +1 -1
  16. package/dist/generator/core.d.ts +4 -2
  17. package/dist/generator/core.d.ts.map +1 -1
  18. package/dist/generator/core.js.map +1 -1
  19. package/dist/generator/emit-shared-go-typed.d.ts +8 -12
  20. package/dist/generator/emit-shared-go-typed.d.ts.map +1 -1
  21. package/dist/generator/emit-shared-go-typed.js +40 -25
  22. package/dist/generator/emit-shared-go-typed.js.map +1 -1
  23. package/dist/generator/emit-shared-rust-typed.d.ts +12 -16
  24. package/dist/generator/emit-shared-rust-typed.d.ts.map +1 -1
  25. package/dist/generator/emit-shared-rust-typed.js +45 -30
  26. package/dist/generator/emit-shared-rust-typed.js.map +1 -1
  27. package/dist/generator/emit-straightline-typed-typescript.d.ts.map +1 -1
  28. package/dist/generator/emit-straightline-typed-typescript.js +15 -23
  29. package/dist/generator/emit-straightline-typed-typescript.js.map +1 -1
  30. package/dist/generator/emit-typed-native-go.d.ts.map +1 -1
  31. package/dist/generator/emit-typed-native-go.js +188 -160
  32. package/dist/generator/emit-typed-native-go.js.map +1 -1
  33. package/dist/generator/emit-typed-native-rust.d.ts.map +1 -1
  34. package/dist/generator/emit-typed-native-rust.js +550 -285
  35. package/dist/generator/emit-typed-native-rust.js.map +1 -1
  36. package/dist/generator/native-expr.d.ts +49 -6
  37. package/dist/generator/native-expr.d.ts.map +1 -1
  38. package/dist/generator/native-expr.js +87 -21
  39. package/dist/generator/native-expr.js.map +1 -1
  40. package/dist/generator/typed.d.ts +149 -0
  41. package/dist/generator/typed.d.ts.map +1 -1
  42. package/dist/generator/typed.js +106 -1
  43. package/dist/generator/typed.js.map +1 -1
  44. package/package.json +1 -1
@@ -2,7 +2,7 @@ import { entryPortOrder, GeneratorFailure } from "./core.js";
2
2
  import { mapTransformExpr, isControlGate, mapNodeElemIsOpaqueWire, 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, inputPortIsOptional, inputPortTypeRef, lowerProducedAwareRead, unproducedInSlot } from "./typed.js";
6
6
  import { concurrencyPlan, execPlan, analyzeSequentialOps, opsLiteralOf, classifyExpr, nodeNarrowedPaths } from "./straightline.js";
7
7
  import { NativeExprCompiler } from "./native-expr.js";
8
8
  import { buildAsyncPlans } from "./async-plan.js";
@@ -253,7 +253,7 @@ function emitRustProbeWireTypes(clone) {
253
253
  // the copying spellings and failing the build on them: a wire classifier that BORROWS (which forces a
254
254
  // per-cell copy to de-box), a de-box that clones a list out of the wire, and a row cloned out of its cell
255
255
  // before a field is taken from the copy. Owning ONE leaf value that a borrow cannot outlive is not a copy
256
- // of the result set and is not forbidden.
256
+ // of the result set and is not forbidden — that is the whole rule: own what crosses, borrow to reach it.
257
257
  pub enum Probe<T> {
258
258
  Got(T),
259
259
  Wrong {
@@ -331,15 +331,28 @@ impl WireValue {
331
331
  }
332
332
 
333
333
  impl WireRow {
334
- // Move the value at \`field\` OUT of the row (or None when the producer did not send it). The de-box
335
- // reads each declared field exactly once, so taking is always right — and it is what keeps a cell
336
- // from being copied: the String travels from the wire into the typed struct without a heap copy.
337
- // Undeclared extras are simply left behind with the row.
334
+ // Move the value at \`field\` OUT of the row (or None when the producer did not send it). \`at\` is the
335
+ // position the column resolved to in an EARLIER row of the SAME result set: the key is verified to
336
+ // still sit there (one compare) and only a row that does not match is scanned again, so a result set
337
+ // resolves each column name ONCE and every later row reads it by index. Scanning per field instead
338
+ // cost O(columns²) per row — the de-box reads every declared field, and each read walked the row.
339
+ // The reuse needs NO stable-layout assumption from the producer: the verify IS the read's guard, and
340
+ // a differing row just re-resolves.
341
+ //
342
+ // The de-box reads each declared field exactly once, so taking is always right — and it is what keeps
343
+ // a cell from being copied: the String travels from the wire into the typed struct without a heap
344
+ // copy. The emptied slot STAYS in the row (its key is what the next row's O(1) check reads);
345
+ // undeclared extras are simply left behind with the row.
346
+ pub fn take_at(&mut self, field: &str, at: &mut usize) -> Option<WireValue> {
347
+ if !matches!(self.entries.get(*at), Some((k, _)) if k == field) {
348
+ *at = self.entries.iter().position(|(k, _)| k == field)?;
349
+ }
350
+ Some(std::mem::replace(&mut self.entries[*at].1, WireValue::Null))
351
+ }
352
+ // The same move, BY NAME only — the read a consumer's leaf transport does on its payload (each of its
353
+ // ports is read one time, so there is no position to carry) and the read a de-box that runs once does.
338
354
  pub fn take(&mut self, field: &str) -> Option<WireValue> {
339
- self.entries
340
- .iter()
341
- .position(|(k, _)| k == field)
342
- .map(|i| self.entries.swap_remove(i).1)
355
+ self.take_at(field, &mut 0)
343
356
  }
344
357
  }
345
358
 
@@ -443,6 +456,11 @@ pub fn probe_list_at(v: Option<WireValue>) -> Probe<WireList> {
443
456
  }
444
457
  }`;
445
458
  }
459
+ /** hoistLines — the collected `at<id>` column-position declarations, one per line at `indent` (#279).
460
+ * Empty (no trailing newline) when the subtree declared none, so a hoist-free block renders unchanged. */
461
+ function hoistLines(decls, indent) {
462
+ return decls.map((d) => `${indent}${d}\n`).join("");
463
+ }
446
464
  /**
447
465
  * renderRustDeBox — the ONE inline, recursive strict de-box renderer. Folds a language-neutral
448
466
  * {@link DeBoxPlan} (the SSoT walk) into a single Rust EXPRESSION that evaluates to the decoded native
@@ -457,8 +475,15 @@ pub fn probe_list_at(v: Option<WireValue>) -> Probe<WireList> {
457
475
  * position moved out, so the decode copies nothing. Mirrors the interpreter's outType check +
458
476
  * the (now-deleted) per-position decoders, but TOTAL over the grammar (opt(named)/arr(arr)/map(opt)…) and
459
477
  * inlined — the type is baked all the way through by the TS compiler, not the target monomorphizer.
478
+ *
479
+ * #279: a record's field POSITIONS (`at<id>`) live in the nearest enclosing REPETITION — the list / map
480
+ * loop the renderer itself opens — so the whole result set shares one resolved position per column
481
+ * instead of re-scanning every row for every column. `hoist` is how a record hands that declaration up
482
+ * to the loop's block; `null` means there is no enclosing repetition (the record is de-boxed once, so
483
+ * there is nothing to amortise) and each field takes BY NAME. `memoRef` is the position slot the
484
+ * enclosing record gave THIS field ("" = no repetition).
460
485
  */
461
- function renderRustDeBox(plan, srcExpr, ctr, indent, fail) {
486
+ function renderRustDeBox(plan, srcExpr, ctr, indent, fail, hoist, memoRef = "") {
462
487
  const I = indent;
463
488
  const I1 = indent + " ";
464
489
  const id = ctr.n++;
@@ -470,8 +495,9 @@ function renderRustDeBox(plan, srcExpr, ctr, indent, fail) {
470
495
  const missing = fail(`de_missing_field(${ml}, ${fl}, ${nl})`);
471
496
  // the probe expression for this node's access + a value-kind suffix (string/number/bool/row/list).
472
497
  // Every access hands the classifier an OWNED Option<WireValue>: a top / element / map value is already
473
- // moved out by the enclosing position, and a field is MOVED OUT of its row by `take`. Nothing borrows,
474
- // so nothing has to be copied to be kept.
498
+ // moved out by the enclosing position, and a field is MOVED OUT of its row by `take_at` (through the
499
+ // result set's resolved position for that column). Nothing borrows, so nothing has to be copied to be
500
+ // kept.
475
501
  const probe = (suffix) => {
476
502
  switch (plan.access.from) {
477
503
  case "top":
@@ -479,7 +505,9 @@ function renderRustDeBox(plan, srcExpr, ctr, indent, fail) {
479
505
  case "mapval":
480
506
  return `probe_${suffix}_at(Some(${srcExpr}))`;
481
507
  case "field":
482
- return `probe_${suffix}_at(${srcExpr}.take(${rustStrLit(plan.access.key)}))`;
508
+ return memoRef === ""
509
+ ? `probe_${suffix}_at(${srcExpr}.take(${rustStrLit(plan.access.key)}))`
510
+ : `probe_${suffix}_at(${srcExpr}.take_at(${rustStrLit(plan.access.key)}, ${memoRef}))`;
483
511
  }
484
512
  };
485
513
  // wrap the decoded value in optDepth `Some(...)` layers (present ⇒ Some^N(v); absent/null ⇒ None).
@@ -514,11 +542,16 @@ ${probeArms}
514
542
  ${I}}`;
515
543
  }
516
544
  if (plan.k === "record") {
517
- // Each declared field is MOVED OUT of the row by `take` (see the wire seam) — the row is consumed field
518
- // by field into the typed struct. `mut` only when there is a field to take (an empty record takes none).
545
+ // Each declared field is MOVED OUT of the row by `take_at` (see the wire seam) — the row is consumed
546
+ // field by field into the typed struct. `mut` only when there is a field to take (an empty record takes
547
+ // none). #279: under a repetition the record's column POSITIONS live in ONE `at<id>` array declared
548
+ // OUTSIDE the loop, so every row of the result set reuses the resolution the first row paid for.
519
549
  const bind = plan.fields.length > 0 ? `mut sub${id}` : `sub${id}`;
550
+ if (hoist !== null && plan.fields.length > 0)
551
+ hoist.push(`let mut at${id} = [0usize; ${plan.fields.length}];`);
552
+ const slot = (j) => (hoist === null ? "" : `&mut at${id}[${j}]`);
520
553
  const fieldInits = plan.fields
521
- .map((f) => `${I1} ${rustFieldName(f.name)}: ${renderRustDeBox(f.plan, `sub${id}`, ctr, `${I1} `, fail)},`)
554
+ .map((f, j) => `${I1} ${rustFieldName(f.name)}: ${renderRustDeBox(f.plan, `sub${id}`, ctr, `${I1} `, fail, hoist, slot(j))},`)
522
555
  .join("\n");
523
556
  return `match ${probe("row")} {
524
557
  ${I1}Probe::Got(${bind}) => ${wrapSome(`${plan.typeName} {
@@ -546,10 +579,15 @@ ${I}}`;
546
579
  }
547
580
  if (plan.k === "list") {
548
581
  // Consume the list: each element is MOVED into the element de-box, so a row never gets copied to be read.
549
- const elemExpr = renderRustDeBox(plan.elem, `e${id}`, ctr, `${I1} `, fail);
582
+ // #279: the loop IS the result set — the element subtree's column positions are declared before it, so
583
+ // the scan the first row pays for is the only scan the whole list pays for. An OUTER repetition already
584
+ // owns a declaration site, and hoisting all the way out is strictly better, so only the outermost one
585
+ // emits (a nested list's rows then share positions across the whole outer walk too).
586
+ const loopHoist = hoist ?? [];
587
+ const elemExpr = renderRustDeBox(plan.elem, `e${id}`, ctr, `${I1} `, fail, loopHoist);
550
588
  return `match ${probe("list")} {
551
589
  ${I1}Probe::Got(l${id}) => ${wrapSome(`{
552
- ${I1} let mut acc${id} = Vec::with_capacity(l${id}.items.len());
590
+ ${hoist === null ? hoistLines(loopHoist, `${I1} `) : ""}${I1} let mut acc${id} = Vec::with_capacity(l${id}.items.len());
553
591
  ${I1} for e${id} in l${id}.items {
554
592
  ${I1} acc${id}.push(${elemExpr});
555
593
  ${I1} }
@@ -560,10 +598,11 @@ ${I}}`;
560
598
  }
561
599
  // map(V): the wire value is a producer map (a DynamoDB "M"); consume its entries, decode each value as V.
562
600
  // Both halves move: the key becomes the BTreeMap's owned String, the value goes straight into the de-box.
563
- const valExpr = renderRustDeBox(plan.value, `mv${id}`, ctr, `${I1} `, fail);
601
+ const mapHoist = hoist ?? [];
602
+ const valExpr = renderRustDeBox(plan.value, `mv${id}`, ctr, `${I1} `, fail, mapHoist);
564
603
  return `match ${probe("row")} {
565
604
  ${I1}Probe::Got(m${id}) => ${wrapSome(`{
566
- ${I1} let mut acc${id} = std::collections::BTreeMap::new();
605
+ ${hoist === null ? hoistLines(mapHoist, `${I1} `) : ""}${I1} let mut acc${id} = std::collections::BTreeMap::new();
567
606
  ${I1} for (k${id}, mv${id}) in m${id}.entries {
568
607
  ${I1} let v${id} = ${valExpr};
569
608
  ${I1} acc${id}.insert(k${id}.into_owned(), v${id});
@@ -599,6 +638,15 @@ function rustStaticStrLit(expr) {
599
638
  const m = /^(".*")\.to_string\(\)$/.exec(expr);
600
639
  return m ? m[1] : undefined;
601
640
  }
641
+ /** rustStrRead — read a compiled string operand as a PLACE (#307). A comparison only READS its operands,
642
+ * so the owning `.clone()` a head resolver put on one and the owned `String` a rendered literal came as
643
+ * are both waste — the SAME "a read does not own" rule as #278/#281/#294, and the SAME literal unpeel
644
+ * `concat` makes. `String` compares against `&str` directly, so this is also the only spelling clippy
645
+ * accepts: `x == "lit".to_string()` is `clippy::cmp_owned`, an error under a consumer's `-D warnings`
646
+ * that a drift-gated module cannot be edited to silence. */
647
+ function rustStrRead(expr) {
648
+ return rustStaticStrLit(expr) ?? rustStripTrailingClone(expr);
649
+ }
602
650
  /** rustStrWireBox — a string crossing INTO the wire. A value fixed at generation time rides as
603
651
  * `Cow::Borrowed` (the SQL text / a literal port costs NO allocation, however many times the payload is
604
652
  * built); anything else converts with `.into()`, which MOVES an owned String rather than copying it. */
@@ -623,38 +671,71 @@ function rustScalarWireCtor(scalar) {
623
671
  throw new GeneratorFailure("UNSUPPORTED_NODE_STRAIGHTLINE", `rust wire box: a bare 'null' scalar has no wire constructor`);
624
672
  }
625
673
  }
626
- function renderRustWireBox(plan, srcExpr, depth = 0) {
627
- // boxBase — box a BASE-typed (non-opt) owned expr per the plan's kind. Both the required (optDepth 0) path
674
+ /** rustBoxSrcOf — how a BOX should read a resolved value: the ONE place a `borrowed` place is consumed.
675
+ * A value whose resolver only COPIED it rides along with the un-copied PLACE and is read THERE (the copy
676
+ * is dropped — the box owns only what it keeps, #281); anything else is owned and is CONSUMED. Every box
677
+ * seam (`wireBox` / `wireBoxEachElem` / `optMapWireBox` / the port field) goes through here, so the
678
+ * decision cannot drift between them. It is a BOX decision only: a map/fanout `over` never crosses a wire
679
+ * and is never copied at all, so it reads its place unconditionally ({@link rustOverAccess}) rather than
680
+ * choosing between a copy and a place. Takes the pair, not {@link Compiled}, so a resolver that is not
681
+ * native-expr can hand the same decision the same two spellings. */
682
+ function rustBoxSrcOf(c) {
683
+ return c.borrowed !== undefined ? [c.borrowed, "place"] : [c.expr, "owned"];
684
+ }
685
+ /** an IDENTITY box — the value is ALREADY the opaque BC wire, so boxing it is a no-op (only a bare
686
+ * `value`; an opt-wrapped one still needs its None/Some match). The ONE place that fact is spelled: the
687
+ * list / map branches skip their per-element map for it (`.map(|e| e)` is `clippy::map_identity`). */
688
+ function rustWireBoxIsIdentity(plan) {
689
+ return plan.optDepth === 0 && plan.k === "value";
690
+ }
691
+ function renderRustWireBox(plan, srcExpr, depth = 0, src = "owned") {
692
+ const owned = src === "owned";
693
+ // OWN — the wire needs this whole value, and the source only lends it: copy exactly this one value.
694
+ const own = (expr) => (owned ? expr : `${expr}.clone()`);
695
+ // boxBase — box a BASE-typed (non-opt) expr per the plan's kind. Both the required (optDepth 0) path
628
696
  // and the opt arm (after its None/Some unwrap) fold through this ONE walk, so the opt element reuses the SAME
629
697
  // per-kind box (no parallel path). The union is exhausted below; the trailing throw is a bare exhaustiveness
630
- // guard, never a silent hole.
631
- const boxBase = (baseSrc) => {
698
+ // guard, never a silent hole. `baseSrcKind` is the ownership of `baseSrc` (the opt arm rebinds it).
699
+ const boxBase = (baseSrc, baseSrcKind) => {
632
700
  if (plan.k === "value")
633
- return baseSrc; // identity — already the opaque BC wire.
701
+ return baseSrcKind === "owned" ? baseSrc : `${baseSrc}.clone()`; // identity — already the opaque BC wire.
634
702
  // strip the source's OWN outer parens before wrapping in the ctor — `WireValue::Str(("a"+x))` is
635
703
  // `clippy::double_parens`; `WireValue::Str("a"+x)` is clean (the ctor call already parenthesizes).
636
- if (plan.k === "scalar")
637
- return plan.scalar === "string"
638
- ? rustStrWireBox(rustStripOuterParens(baseSrc))
639
- : `${rustScalarWireCtor(plan.scalar)}(${rustStripOuterParens(baseSrc)})`;
704
+ if (plan.k === "scalar") {
705
+ const bare = rustStripOuterParens(baseSrc);
706
+ if (plan.scalar === "string")
707
+ return rustStrWireBox(baseSrcKind === "owned" ? bare : `${bare}.clone()`);
708
+ // a Copy scalar is read BY VALUE: free from a place, one deref from a `&T` binding.
709
+ return `${rustScalarWireCtor(plan.scalar)}(${baseSrcKind === "ref" ? `*${bare}` : bare})`;
710
+ }
711
+ // a field of an owned struct is owned (moved out); a field reached through a borrow is a place.
712
+ const fieldSrc = baseSrcKind === "owned" ? "owned" : "place";
713
+ // an element / entry value an iterator hands out is a `&T` binding when the source is only lent.
714
+ const elemSrc = baseSrcKind === "owned" ? "owned" : "ref";
715
+ const iter = baseSrcKind === "owned" ? "into_iter()" : "iter()";
640
716
  if (plan.k === "record") {
641
- // typed struct → wire map: box each declared field off its native struct field (moving it out of the owned
642
- // srcExpr — no probe), assemble a WireRow of (name, WireValue) in declared-field order.
643
- const entries = plan.fields.map((f) => `(Cow::Borrowed(${rustStrLit(f.name)}), ${renderRustWireBox(f.plan, `${baseSrc}.${rustFieldName(f.name)}`, depth + 1)})`);
717
+ // typed struct → wire map: box each declared field off its native struct field (moving it out of an owned
718
+ // srcExpr — no probe; copying just that field out of a borrowed one), assemble a WireRow of
719
+ // (name, WireValue) in declared-field order.
720
+ const entries = plan.fields.map((f) => `(Cow::Borrowed(${rustStrLit(f.name)}), ${renderRustWireBox(f.plan, `${baseSrc}.${rustFieldName(f.name)}`, depth + 1, fieldSrc)})`);
644
721
  return `WireValue::Row(WireRow { entries: vec![${entries.join(", ")}] })`;
645
722
  }
646
723
  if (plan.k === "list") {
647
- // typed Vec → wire list: consume the owned Vec, box each element recursively (box-once, no round-trip).
724
+ // typed Vec → wire list: consume the owned Vec (or walk the borrowed one), box each element
725
+ // recursively (box-once, no round-trip).
648
726
  const e = `e${depth}`;
649
- const elemBox = renderRustWireBox(plan.elem, e, depth + 1);
650
- // clippy-clean: an IDENTITY element box (a `value` list — already a Vec<WireValue>) skips the map
651
- // (`.map(|e| e)` is `clippy::map_identity`); a bare scalar CONSTRUCTOR box goes point-free
652
- // (`.map(WireValue::Str)` not `.map(|e| WireValue::Str(e))` — `clippy::redundant_closure`).
653
- if (elemBox === e)
654
- return `WireValue::List(WireList { items: ${baseSrc} })`;
727
+ // an IDENTITY element list is already a Vec<WireValue>: hand it over whole (a lent one is copied whole —
728
+ // there is nothing smaller to copy, every element crosses AS-IS).
729
+ if (rustWireBoxIsIdentity(plan.elem))
730
+ return `WireValue::List(WireList { items: ${own(baseSrc)} })`;
731
+ // clippy-clean: a bare scalar CONSTRUCTOR box goes point-free (`.map(WireValue::Str)` not
732
+ // `.map(|e| WireValue::Str(e))` — `clippy::redundant_closure`); a lent Copy element is `.copied()` off
733
+ // the borrowing iterator, which makes it owned by the time the ctor sees it.
655
734
  const scalarCtor = plan.elem.optDepth === 0 && plan.elem.k === "scalar" && plan.elem.scalar !== "string" ? rustScalarWireCtor(plan.elem.scalar) : undefined;
656
- const mapper = scalarCtor !== undefined ? scalarCtor : `|${e}| ${elemBox}`;
657
- return `WireValue::List(WireList { items: ${baseSrc}.into_iter().map(${mapper}).collect() })`;
735
+ if (scalarCtor !== undefined)
736
+ return `WireValue::List(WireList { items: ${baseSrc}.${iter}${owned ? "" : ".copied()"}.map(${scalarCtor}).collect() })`;
737
+ const elemBox = renderRustWireBox(plan.elem, e, depth + 1, elemSrc);
738
+ return `WireValue::List(WireList { items: ${baseSrc}.${iter}.map(|${e}| ${elemBox}).collect() })`;
658
739
  }
659
740
  if (plan.k === "map") {
660
741
  // bc#181: typed map<V> → wire map, represented as a dynamic-keyed WireRow (there is NO WireMap type; a
@@ -665,13 +746,12 @@ function renderRustWireBox(plan, srcExpr, depth = 0) {
665
746
  // data, so they cross as owned wire keys (unlike a generated field name, which stays borrowed).
666
747
  const k = `k${depth}`;
667
748
  const v = `v${depth}`;
668
- const valBox = renderRustWireBox(plan.value, v, depth + 1);
669
- // An IDENTITY value box (a map<value> — the entries are ALREADY WireValue) needs no per-entry map:
749
+ const key = `Cow::Owned(${own(k)})`;
750
+ // An IDENTITY value box (a map<value> — the entries are ALREADY WireValue) needs no per-entry box:
670
751
  // collect the pairs directly (clippy rejects `.map(|(k, v)| (k, v))` as an identity map). Same rule
671
752
  // as the list branch's identity short-circuit above — box-once, no re-wrap.
672
- if (valBox === v)
673
- return `WireValue::Row(WireRow { entries: ${baseSrc}.into_iter().map(|(${k}, ${v})| (Cow::Owned(${k}), ${v})).collect() })`;
674
- return `WireValue::Row(WireRow { entries: ${baseSrc}.into_iter().map(|(${k}, ${v})| (Cow::Owned(${k}), ${valBox})).collect() })`;
753
+ const valBox = rustWireBoxIsIdentity(plan.value) ? own(v) : renderRustWireBox(plan.value, v, depth + 1, elemSrc);
754
+ return `WireValue::Row(WireRow { entries: ${baseSrc}.${iter}.map(|(${k}, ${v})| (${key}, ${valBox})).collect() })`;
675
755
  }
676
756
  throw new GeneratorFailure("UNSUPPORTED_NODE_STRAIGHTLINE", `rust wire box: unexpected plan kind '${plan.k}'`);
677
757
  };
@@ -679,14 +759,16 @@ function renderRustWireBox(plan, srcExpr, depth = 0) {
679
759
  // bc#185: typed opt<T> → wire, TOTAL. `srcExpr` is an `Option<…Option<Base>>` (optDepth `Some` wraps — the
680
760
  // mirror of the read-side de-box `wrapSome`). Presence is SINGLE-BIT on the wire and run_behavior passes the
681
761
  // `Value` THROUGH (null stays null), so: None ⇒ WireValue::Null (byte-equal to value_to_wire(Value::Null));
682
- // present ⇒ unwrap ALL optDepth `Some` layers to the owned base value and box it through the SAME per-kind
683
- // walk (box-once, no decode→re-box). A present nested opt is a fully-`Some` chain (the read side never builds
684
- // a partially-None present), so the `_ => Null` arm only ever fires for a genuine absent.
762
+ // present ⇒ unwrap ALL optDepth `Some` layers to the base value and box it through the SAME per-kind walk
763
+ // (box-once, no decode→re-box). A present nested opt is a fully-`Some` chain (the read side never builds a
764
+ // partially-None present), so the `_ => Null` arm only ever fires for a genuine absent.
765
+ // A LENT option cannot be unwrapped by value (that would move the inner out of the borrow): match its
766
+ // `as_ref()` instead, which binds the inner as a `&T` (match ergonomics carry that through nested Somes).
685
767
  const ov = `ov${depth}`;
686
768
  const pat = "Some(".repeat(plan.optDepth) + ov + ")".repeat(plan.optDepth);
687
- return `match ${srcExpr} { ${pat} => ${boxBase(ov)}, _ => WireValue::Null }`;
769
+ return `match ${owned ? srcExpr : `${srcExpr}.as_ref()`} { ${pat} => ${boxBase(ov, owned ? "owned" : "ref")}, _ => WireValue::Null }`;
688
770
  }
689
- return boxBase(srcExpr);
771
+ return boxBase(srcExpr, src);
690
772
  }
691
773
  /** returnErrFail — the default de-box mismatch control flow: propagate the structured Error Value out of
692
774
  * the enclosing runner (fail/retry componentRef results + map/fanout element de-box, which fails closed
@@ -695,9 +777,10 @@ const returnErrFail = (errValueExpr) => `return Err(${errValueExpr})`;
695
777
  /** renderResultDeBox — inline strict de-box of a whole result WIRE (`srcExpr`, a WireValue) into its
696
778
  * native value, from the TOTAL SSoT plan for `ref` at the top position. `fail` selects the mismatch
697
779
  * control flow. This is the ONE de-box call the runner arms share (componentRef result + map/fanout
698
- * element) — no per-position predicate, no helper decode fn. */
780
+ * element) — no per-position predicate, no helper decode fn. A top result is de-boxed ONCE, so there is
781
+ * no enclosing repetition to share column positions across (`null` hoist — see renderRustDeBox #279). */
699
782
  function renderResultDeBox(ref, srcExpr, nodeId, plan, indent, fail = returnErrFail, passthrough = false) {
700
- return renderRustDeBox(buildDeBoxPlan(ref, { from: "top" }, { model: nodeId, field: nodeId, plan }, passthrough), srcExpr, { n: 0 }, indent, fail);
783
+ return renderRustDeBox(buildDeBoxPlan(ref, { from: "top" }, { model: nodeId, field: nodeId, plan }, passthrough), srcExpr, { n: 0 }, indent, fail, null);
701
784
  }
702
785
  /** mapFanoutElemRef — the element ROW TypeRef a map/fanout node decodes (the per-element record). */
703
786
  function mapFanoutElemRef(node, typedNodes, plan) {
@@ -720,20 +803,27 @@ function staticArrElems(node) {
720
803
  * ports struct carries NO `Value` field: every port lowers to a concrete Rust type.
721
804
  /** rustOwn — the ownership renderer native-expr applies at a resolved ref LEAF: an array field is cloned
722
805
  * (owned) when `ownArrays` (a port) or borrowed (a cond `len`); a Copy scalar behind a guard is deref'd
723
- * (unless a field was already accessed by value); anything else clones. */
806
+ * (unless a field was already accessed by value); anything else clones.
807
+ *
808
+ * Where the owned form is a COPY, the un-copied PLACE rides along as `borrowed` (#281): a consumer that
809
+ * DECOMPOSES the value — the wire box, which builds a new wire out of the parts that cross — reads the
810
+ * place and owns only those parts, so an `arr<obj>` result is never duplicated just to re-box its rows.
811
+ * The deref'd Copy scalar is NOT a place of its own type (`cell.borrow()` is a `Ref<i64>`), so it carries
812
+ * no place; nothing decomposes a scalar anyway. */
724
813
  function rustOwn(guard, ownArrays) {
725
814
  return (expr, ref, fieldAccessed) => {
726
815
  if (ref.kind === "arr")
727
- return ownArrays ? `${expr}.clone()` : expr;
816
+ return ownArrays ? { expr: `${expr}.clone()`, borrowed: expr } : { expr };
728
817
  if (typeRefIsCopy(ref))
729
- return guard && !fieldAccessed ? `*${expr}` : expr;
730
- return `${expr}.clone()`;
818
+ return { expr: guard && !fieldAccessed ? `*${expr}` : expr };
819
+ return { expr: `${expr}.clone()`, borrowed: expr };
731
820
  };
732
821
  }
733
822
  /** rustMoved — the ownership renderer for a head that was MOVED out of its cell: the value is already
734
- * owned, so the leaf adds nothing. (rustOwn's clone/deref exist only because a borrow cannot be kept.) */
823
+ * owned, so the leaf adds nothing — and there is no place to borrow instead (the move IS the cheap read).
824
+ * (rustOwn's clone/deref exist only because a borrow cannot be kept.) */
735
825
  function rustMoved() {
736
- return (expr) => expr;
826
+ return (expr) => ({ expr });
737
827
  }
738
828
  /** nativeResolveHead — the ONE ref-head resolver the runtime-free native-expr compiler reads (cond `if`/
739
829
  * branches, a map/fanout `when` guard, AND a port). A head is a `$as` element binding, a prior body node's
@@ -747,7 +837,7 @@ function nativeResolveHead(comp, plan, typedNodes, isPrior, opts) {
747
837
  }
748
838
  if (isPrior(head)) {
749
839
  const ref = typedNodes.get(head);
750
- // This node's result has exactly one reader (movableCells) — take it out of the cell instead of
840
+ // This read is the LAST of this node's result (movableRefs) — take it out of the cell instead of
751
841
  // copying it. The wire enum has no Default, so a `value` cell swaps in the null wire to move.
752
842
  if (opts?.moveHeads?.has(head) === true)
753
843
  return { expr: rustCellRead(head, ref, false, opts.moveHeads), ref, own: rustMoved() };
@@ -815,9 +905,13 @@ function portFieldRustType(node, comp, plan, typedNodes, expected, where = "port
815
905
  // (bc_expr_* below) returning Result<T, BehaviorError> — the covered module still imports ZERO bc runtime.
816
906
  // The runner is Result<_, BehaviorError>, so a fallible helper propagates with `?`.
817
907
  let rustExprTempSeq = 0;
818
- /** module-level accumulator: set when the native-expr compiler emits a fallible helper call (so emit()
819
- * bakes the helper library). Reset at the start of each emit(). */
820
- const rustExprUsed = { helpers: false };
908
+ /** module-level accumulator for what the native-expr compiler emitted.
909
+ * - `helpers` — a fallible helper call was emitted (so emit() bakes the helper library). Reset at the
910
+ * start of each emit().
911
+ * - `boolAlgebra` (#304) — an author `and`/`or` was lowered, in EITHER form: the pure native `&&`/`||`
912
+ * (binOp) or the short-circuit guard a fallible right operand needs (shortCircuitBool). Read PER ITEM,
913
+ * so it is reset at the start of each {@link emitNativeRawRunner}, not per module. */
914
+ const rustExprUsed = { helpers: false, boolAlgebra: false };
821
915
  /** rustBlockBody — the body of a block-expression that runs `stmts` then yields `expr`. A trailing
822
916
  * `let t = E; t` collapses to `E` (clippy `let_and_return`). */
823
917
  function rustBlockBody(stmts, expr) {
@@ -847,11 +941,23 @@ function makeRustExprBackend(resolveHead, plan, breakLabel) {
847
941
  freshTemp: () => `ex_${rustExprTempSeq++}`,
848
942
  renderType: (ref) => renderTypeRef(ref),
849
943
  wireType: () => renderTypeRef({ kind: "value" }),
850
- // bc#156/#160: box a value[] element into the opaque BC wire via the ONE box SSoT (owned element expr).
851
- wireBox: (item) => renderRustWireBox(buildWirePlan(item.ref, { from: "top" }, { model: "port", field: "port", plan }, "in"), item.expr),
852
- // bc#178: box EACH element of the owned typed Vec into an arr<value> (Vec<WireValue>) — the same
853
- // per-element box renderer as wireBox's list case, applied over the referenced array (box-once/element).
854
- wireBoxEachElem: (srcExpr, elemRef) => `${srcExpr}.into_iter().map(|__be| ${renderRustWireBox(buildWirePlan(elemRef, { from: "elem" }, { model: "port", field: "port", plan }, "in"), "__be")}).collect::<Vec<${renderTypeRef({ kind: "value" })}>>()`,
944
+ // bc#156/#160: box a value[] element into the opaque BC wire via the ONE box SSoT. #281: a value the head
945
+ // resolver only COPIED is boxed out of its place instead (the box owns the parts that cross, not the whole).
946
+ wireBox: (item) => {
947
+ const [srcExpr, srcKind] = rustBoxSrcOf(item);
948
+ return renderRustWireBox(buildWirePlan(item.ref, { from: "top" }, { model: "port", field: "port", plan }, "in"), srcExpr, 0, srcKind);
949
+ },
950
+ // bc#178: box EACH element of the typed Vec into an arr<value> (Vec<WireValue>) — the same per-element box
951
+ // renderer as wireBox's list case, applied over the referenced array (box-once/element).
952
+ wireBoxEachElem: (src, elemRef) => {
953
+ // #281: the re-box builds a NEW Vec<WireValue>, so the source list is never needed as a whole. An owned
954
+ // source is CONSUMED (its strings move into the wire); a source the head resolver copied is walked as a
955
+ // borrow and only its wired fields are owned — copying the list first would duplicate every row,
956
+ // including the fields this port does not carry.
957
+ const [srcExpr, srcKind] = rustBoxSrcOf(src);
958
+ const elemBox = renderRustWireBox(buildWirePlan(elemRef, { from: "elem" }, { model: "port", field: "port", plan }, "in"), "__be", 0, srcKind === "owned" ? "owned" : "ref");
959
+ return `${srcExpr}.${srcKind === "owned" ? "into_iter()" : "iter()"}.map(|__be| ${elemBox}).collect::<Vec<${renderTypeRef({ kind: "value" })}>>()`;
960
+ },
855
961
  scalarType: (s) => rustScalar(s),
856
962
  strLit: (s) => `${rustStrLit(s)}.to_string()`,
857
963
  boolLit: (b) => (b ? "true" : "false"),
@@ -867,14 +973,25 @@ function makeRustExprBackend(resolveHead, plan, breakLabel) {
867
973
  },
868
974
  helperCall: (helper, args) => {
869
975
  used.helpers = true;
870
- // the string code-point compare helpers take &str — borrow the owned String args.
976
+ // the string code-point compare helpers take &str — read each operand as a PLACE (#307) and borrow
977
+ // it; a rendered literal is ALREADY a `&'static str` once unpeeled, so it needs no `&`.
871
978
  const isStrCmp = helper === "strLt" || helper === "strLe" || helper === "strGt" || helper === "strGe";
872
- const passed = isStrCmp ? args.map((a) => `&${a}`) : args;
979
+ const passed = isStrCmp ? args.map((a) => rustStaticStrLit(a) ?? `&${rustStripTrailingClone(a)}`) : args;
873
980
  // lenArr takes &[T] — borrow the owned Vec.
874
981
  const finalArgs = helper === "lenArr" ? args.map((a) => `&${a}`) : passed;
875
982
  return `bc_expr_${rustSnake(helper)}(${finalArgs.join(", ")})`;
876
983
  },
877
- binOp: (op, a, b) => `(${a} ${op} ${b})`,
984
+ binOp: (op, a, b, scalar) => {
985
+ // #304: `&&` / `||` reach here ONLY from an author `and`/`or` (native-expr.ts andOr — the one place
986
+ // a connective is rendered). That is the author's boolean ALGEBRA, which the runner item has to be
987
+ // allowed to keep un-minimized; record it so the item carries the allow and nothing else does.
988
+ if (op === "&&" || op === "||")
989
+ used.boolAlgebra = true;
990
+ // a string ==/!= reads both operands as places (#307): `String` compares against `&str` directly, so
991
+ // neither the literal nor the resolver's owning clone has to be materialized. int/float/bool are Copy.
992
+ // A connective is lowered with scalar "bool", so the two arms are disjoint.
993
+ return scalar === "string" ? `(${rustStrRead(a)} ${op} ${rustStrRead(b)})` : `(${a} ${op} ${b})`;
994
+ },
878
995
  concat: (parts) => {
879
996
  // native String concat via a `[&str; N].concat()` — a string-literal part (`"…".to_string()`) is
880
997
  // used as the bare `"…"` &str; any other owned String is borrowed with `.as_str()`. This shape is
@@ -883,6 +1000,19 @@ function makeRustExprBackend(resolveHead, plan, breakLabel) {
883
1000
  return `[${refs.join(", ")}].concat()`;
884
1001
  },
885
1002
  notOp: (a) => `(!${a})`,
1003
+ // #309: the complement of a FLOAT ordering compare. `!(a > b)` is `clippy::neg_cmp_op_on_partial_ord`
1004
+ // (an ERROR under a consumer's `-D warnings`, on a file `bc check` forbids them to edit), and the fold
1005
+ // to the opposite operator that closes it on a TOTAL order is INVALID here — `!(NaN > 5.0)` is true and
1006
+ // `NaN <= 5.0` is false, and it is the `!` form that matches the interpreter (compareCore collapses an
1007
+ // incomparable pair to c=0). So the complement is spelled against the ORDERING itself: `a <op> b` is
1008
+ // exactly `partial_cmp` yielding the op's Ordering set, and its complement is that match negated —
1009
+ // equal to `!(a <op> b)` for every pair including NaN, and the form the lint asks for.
1010
+ negPartialOrdCmp: (op, a, b) => {
1011
+ const ords = op === "gt" ? ["Greater"] : op === "lt" ? ["Less"] : op === "ge" ? ["Greater", "Equal"] : ["Less", "Equal"];
1012
+ // the receiver + operand are parenthesized: an operand may be a negative float literal (`-5.0f64`),
1013
+ // where `-5.0f64.partial_cmp(…)` would parse as `-(5.0f64.partial_cmp(…))` and not compile.
1014
+ return `(!matches!((${a}).partial_cmp(&(${b})), Some(${ords.map((o) => `std::cmp::Ordering::${o}`).join(" | ")})))`;
1015
+ },
886
1016
  structLit: (name, inits) => `${name} { ${inits.map((i) => `${rustFieldName(i.field)}: ${i.expr}`).join(", ")} }`,
887
1017
  arrLit: (elemTy, items) => `{ let __v: Vec<${elemTy}> = vec![${items.join(", ")}]; __v }`,
888
1018
  // #209: the opaque wire built directly from an inline composite literal at a `value` port.
@@ -922,10 +1052,17 @@ function makeRustExprBackend(resolveHead, plan, breakLabel) {
922
1052
  // #275: carry an opt<S> (Option<S>) through into opt<value> (Option<WireValue>) via `.map`, boxing the
923
1053
  // PRESENT inner with the ONE box SSoT (renderRustWireBox — the SAME call shape as wireBox) and keeping
924
1054
  // absent None (absent stays absent — NOT WireValue::Null, which is the required-`value` collapse). `.map`
925
- // consumes the owned Option (the port access clones/moves it, like narrowUnwrap's `.unwrap()`).
926
- optMapWireBox: (optExpr, innerRef) => `${optExpr}.map(|__ov| ${renderRustWireBox(buildWirePlan(innerRef, { from: "top" }, { model: "port", field: "port", plan }, "in"), "__ov")})`,
1055
+ // CONSUMES an owned Option; a lent one is walked with `.as_ref()` and only its wired parts are owned
1056
+ // (#281 — the box decomposes the inner, so copying the option first is waste).
1057
+ optMapWireBox: (src, innerRef) => {
1058
+ const [optExpr, srcKind] = rustBoxSrcOf(src);
1059
+ const owned = srcKind === "owned";
1060
+ const box = renderRustWireBox(buildWirePlan(innerRef, { from: "top" }, { model: "port", field: "port", plan }, "in"), "__ov", 0, owned ? "owned" : "ref");
1061
+ return `${optExpr}${owned ? "" : ".as_ref()"}.map(|__ov| ${box})`;
1062
+ },
927
1063
  ternary: (cond, t, e, _ty) => `(if ${rustStripOuterParens(cond)} { ${rustStripOuterParens(t)} } else { ${rustStripOuterParens(e)} })`,
928
1064
  shortCircuitBool: (op, temp, left, rStmts, rExpr) => {
1065
+ used.boolAlgebra = true; // #304: the author's and/or, in its fallible-right-operand form.
929
1066
  // and: let temp = if left { <rStmts> rExpr } else { false }; or: if left { true } else { <rStmts> rExpr }.
930
1067
  // build a block that runs rStmts then yields rExpr (parens stripped — block-tail is not a sub-expr).
931
1068
  const rblock = `{ ${rStmts.join(" ")} ${rustStripOuterParens(rExpr)} }`;
@@ -1203,48 +1340,92 @@ ${inits.join("\n")}
1203
1340
  }
1204
1341
  return parts.join("\n\n");
1205
1342
  }
1343
+ /** re-indent a body block by one level, the way {@link rustPolicyArm} does (multi-line entries included). */
1344
+ function rustIndentBody(body) {
1345
+ return body.map((l) => ` ${l}`.replace(/\n/g, "\n "));
1346
+ }
1206
1347
  /**
1207
- * mapOverElemInfo — resolve a covered map's `over` collection element TypeRef + the OWNED Rust
1208
- * expression that yields the over Vec (#108, rust twin): prior-node arr field (cell clone) or an input
1209
- * array port with elemType (`in_.<field>.clone()`). Fail-closed for an input array without elemType.
1348
+ * rustOverAccess — resolve {@link RustOverPlace} × "does this arm suspend?" into the ONE {@link
1349
+ * RustOverAccess} both arm emitters consume. `awaits` is whether the arm `.await`s at all: a map / fanout
1350
+ * arm has exactly one leaf call site, so that is also whether any of its runs could span a suspension.
1210
1351
  */
1352
+ function rustOverAccess(s, place, optArr, awaits) {
1353
+ // lend a place: `&` it, or — opt-arr — `as_deref()` to `Option<&[E]>` and take `&[]` for None.
1354
+ const lend = (base) => (optArr ? `${base}.as_deref().unwrap_or_default()` : `&${base}`);
1355
+ // the ONE spelling of the un-copied place, read by every form below (count, hold, elem).
1356
+ const read = place.at === "local"
1357
+ ? lend(place.expr)
1358
+ : place.fieldPath === "" && !optArr
1359
+ ? `${place.cell}.borrow()` // the cell IS the collection — the guard needs no projection.
1360
+ : `std::cell::Ref::map(${place.cell}.borrow(), |__ov| ${lend(`__ov${place.fieldPath}`)})`;
1361
+ const bind = `let over_${s} = ${read};`;
1362
+ // `iter()` yields `&E` off a `Vec<E>`, a `&Vec<E>`, a `&[E]` and a `Ref<'_, [E]>` alike, so the loop body
1363
+ // is the SAME expression in every form — which is why reading the place costs the arm nothing.
1364
+ const iterate = (indent, body) => [
1365
+ `${indent}for oel_${s} in over_${s}.iter() {`,
1366
+ ...body,
1367
+ `${indent}}`,
1368
+ ];
1369
+ if (!(awaits && place.at === "cell"))
1370
+ return {
1371
+ open: bind,
1372
+ count: `over_${s}.len()`,
1373
+ hold: (_indent, body) => [...body], // the bind is the arm's own first statement; nothing to scope.
1374
+ each: iterate,
1375
+ elem: (indent, body, b) => (b === undefined ? [...body] : [...body, `${indent}let ${b.name} = ${b.value};`]),
1376
+ };
1377
+ const reread = [bind, `let oel_${s} = &over_${s}[i_${s}];`];
1378
+ return {
1379
+ // the count is read ONCE, through the same place, and the guard dies with the statement. The cell is
1380
+ // written by a node that already ran and by nothing inside the arm, so the positions stay in range.
1381
+ open: `let n_${s} = ${read}.len();`,
1382
+ count: `n_${s}`,
1383
+ hold: (indent, body) => [`${indent}{`, `${indent} ${bind}`, ...rustIndentBody(body), `${indent}}`],
1384
+ each: (indent, body) => [`${indent}for i_${s} in 0..n_${s} {`, ...body, `${indent}}`],
1385
+ elem: (indent, body, b) => [
1386
+ `${indent}${b === undefined ? "{" : `let ${b.name} = {`}`,
1387
+ ...reread.map((l) => `${indent} ${l}`),
1388
+ ...rustIndentBody(body),
1389
+ ...(b === undefined ? [] : [`${indent} ${b.value}`]),
1390
+ `${indent}}${b === undefined ? "" : ";"}`,
1391
+ ],
1392
+ };
1393
+ }
1211
1394
  /**
1212
- * rustOverElemInfo — the ONE resolver of a fanout/map `over` to its element TypeRef + the OWNED Rust
1213
- * over expression (map/fanout twins both delegate — single definition, no forked copy).
1395
+ * rustOverElemInfo — the ONE resolver of a fanout/map `over` to its element TypeRef + how the arm reads
1396
+ * the collection (map/fanout twins both delegate — single definition, no forked copy). It is the only
1397
+ * place that knows WHERE the collection lives, so it is the only place that can say how an arm may read
1398
+ * it: {@link rustOverAccess} renders that, given whether the arm suspends.
1214
1399
  *
1215
- * `optArr` is true when the over's declared type is `{opt:{arr}}` (a prior-node opt-arr field OR an OPT
1216
- * input array port). #177 (A): a null opt-arr over then iterates EMPTY — the emitted `overExpr` is an
1217
- * `Option<Vec<E>>`, which the arm binds via `.unwrap_or_default()` (None → empty Vec), byte-equal to
1218
- * run_behavior. A REQUIRED arr (None) still fails run_behavior FANOUT/MAP_OVER_NOT_ARRAY → optArr:false.
1400
+ * An opt-arr over (a prior-node `{opt:{arr}}` field OR an OPT input array port) iterates EMPTY on null
1401
+ * (#177 (A)), byte-equal to run_behavior. A REQUIRED arr still fails run_behavior FANOUT/MAP_OVER_NOT_ARRAY.
1219
1402
  */
1220
1403
  function rustOverElemInfo(comp, over, typedNodes, plan, nodeId, label) {
1404
+ const s = sanitize(nodeId);
1221
1405
  const e = classifyExpr(over);
1222
1406
  if (e.kind === "ref" && e.path.length >= 1 && typedNodes.has(e.path[0])) {
1223
1407
  const baseRef = typedNodes.get(e.path[0]);
1224
1408
  const { ref } = typedFieldAccess(`${typedCell(e.path[0])}.borrow()`, baseRef, e.path.slice(1), plan);
1225
1409
  const fieldPath = e.path.slice(1).map((p) => `.${rustFieldName(p)}`).join("");
1226
- if (ref.kind === "arr") {
1227
- return { elemRef: ref.elem, overExpr: `${typedCell(e.path[0])}.borrow()${fieldPath}.clone()`, optArr: false };
1228
- }
1229
- if (ref.kind === "opt" && ref.inner.kind === "arr") {
1230
- return { elemRef: ref.inner.elem, overExpr: `${typedCell(e.path[0])}.borrow()${fieldPath}.clone()`, optArr: true };
1231
- }
1410
+ const cell = { at: "cell", cell: typedCell(e.path[0]), fieldPath };
1411
+ if (ref.kind === "arr")
1412
+ return { elemRef: ref.elem, over: (awaits) => rustOverAccess(s, cell, false, awaits) };
1413
+ if (ref.kind === "opt" && ref.inner.kind === "arr")
1414
+ return { elemRef: ref.inner.elem, over: (awaits) => rustOverAccess(s, cell, true, awaits) };
1232
1415
  }
1233
1416
  if (e.kind === "ref" && e.path.length === 1) {
1234
1417
  const schema = comp.inputPorts?.[e.path[0]];
1235
1418
  const et = schema?.elemType;
1236
1419
  // #192: read the input array port by its positional PARAM name (= rustFieldName(port), same name
1237
- // source as the seam) — box removed, no `in_.` prefix; `.clone()` owns the iterated Vec.
1238
- if (et !== undefined)
1239
- return { elemRef: deriveTypeRef(et, plan), overExpr: `${rustFieldName(e.path[0])}.clone()`, optArr: inputPortIsOptional(schema) };
1420
+ // source as the seam) — box removed, no `in_.` prefix.
1421
+ if (et !== undefined) {
1422
+ const local = { at: "local", expr: rustFieldName(e.path[0]) };
1423
+ const optArr = inputPortIsOptional(schema);
1424
+ return { elemRef: deriveTypeRef(et, plan), over: (awaits) => rustOverAccess(s, local, optArr, awaits) };
1425
+ }
1240
1426
  }
1241
1427
  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).`);
1242
1428
  }
1243
- /** rustBindOverExpr — the RHS `let over_<s> = …;` expr. An opt-arr over (#177 (A)) unwraps its
1244
- * `Option<Vec<E>>` to an empty Vec on None so iteration is 0-length (byte-equal to run_behavior). */
1245
- function rustBindOverExpr(overExpr, optArr) {
1246
- return optArr ? `${overExpr}.unwrap_or_default()` : overExpr;
1247
- }
1248
1429
  function mapOverElemInfo(comp, node, typedNodes, plan) {
1249
1430
  return rustOverElemInfo(comp, node.map.over, typedNodes, plan, node.id, "combined map (#108)");
1250
1431
  }
@@ -1406,7 +1587,7 @@ function coveredMapNode(n, bodyIds, comp) {
1406
1587
  if (!bodyIds.has(head)) {
1407
1588
  // input-array over: covered only when the port declares elemType (#108 — C3, no inference). #177 (A):
1408
1589
  // an OPT input array (`{opt:{arr}}`, required:false) IS covered — its null iterates EMPTY
1409
- // (rustOverElemInfo.optArr → `.unwrap_or_default()`, None → empty Vec), byte-equal to run_behavior.
1590
+ // (rustOverAccess collapses None to an empty collection), byte-equal to run_behavior.
1410
1591
  if (overE.path.length !== 1)
1411
1592
  return false;
1412
1593
  const schema = comp.inputPorts?.[head];
@@ -1441,7 +1622,7 @@ function coveredFanoutNode(n, bodyIds, comp) {
1441
1622
  if (!bodyIds.has(head)) {
1442
1623
  // input-array over: covered only when the port declares elemType (C3 — no inference). #177 (A): an OPT
1443
1624
  // input array (`{opt:{arr}}`, required:false) IS covered — its null iterates EMPTY
1444
- // (rustOverElemInfo.optArr → `.unwrap_or_default()`, None → empty Vec), byte-equal to run_behavior.
1625
+ // (rustOverAccess collapses None to an empty collection), byte-equal to run_behavior.
1445
1626
  if (overE.path.length !== 1)
1446
1627
  return false;
1447
1628
  const schema = comp.inputPorts?.[head];
@@ -1617,7 +1798,8 @@ function inputPortRustType(schema, plan, where = "input port") {
1617
1798
  */
1618
1799
  function emitPortWireField(pn, expr, comp, plan, typedNodes, isPrior, expected, opts) {
1619
1800
  const c = compilePortNode(expr, comp, plan, typedNodes, isPrior, `port '${pn}'`, expected, opts);
1620
- const boxed = renderRustWireBox(buildWirePlan(c.ref, { from: "top" }, { model: "port", field: pn, plan }, "in"), c.expr);
1801
+ const [srcExpr, srcKind] = rustBoxSrcOf(c);
1802
+ const boxed = renderRustWireBox(buildWirePlan(c.ref, { from: "top" }, { model: "port", field: pn, plan }, "in"), srcExpr, 0, srcKind);
1621
1803
  return { stmts: c.stmts, entry: `(Cow::Borrowed(${rustStrLit(pn)}), ${boxed})` };
1622
1804
  }
1623
1805
  /** rustPortsLabel — the payload-entry block's label for a node, the ONE name its hoists break to. */
@@ -1661,27 +1843,41 @@ function rustScalar(s) {
1661
1843
  return s === "string" ? "String" : s === "int" ? "i64" : s === "float" ? "f64" : "bool";
1662
1844
  }
1663
1845
  /**
1664
- * movableRefs — the values (a body node's RESULT, or an input port) with exactly ONE reader in the whole
1665
- * component, so that reader can take the value by MOVE instead of copying it.
1846
+ * movableRefs — per READ SITE, the values (a body node's RESULT, or an input port) that site may take by
1847
+ * MOVE instead of copying: the heads whose LAST read it is, read there exactly once.
1666
1848
  *
1667
1849
  * Handing a prior node's result to a downstream leaf is where a result set would otherwise be deep-copied:
1668
1850
  * a `Vec<WireValue>` clone re-allocates every string in every row, once per node boundary. Counting the
1669
- * readers statically says when copying is unnecessary — which, in a read chain, is the normal case.
1851
+ * readers statically says when copying is unnecessary — which, in a read chain, is the normal case. A value
1852
+ * with several readers still needs a copy for each reader that is NOT the last, but the last one is handing
1853
+ * on a cell nothing reads again, so it moves (#278: the go surface never owed this copy — a Go slice IS a
1854
+ * reference, so `WireListOf(t_n0)` passes the same backing array on; only Rust has to say who owns).
1670
1855
  *
1671
1856
  * A read is counted from the ONE place a value can be referenced: a `{ref}` / `{refOpt}` path whose head
1672
1857
  * names a body node or an input port (ports, guards, map sources, the output value), plus the parent read
1673
- * a bindField performs. Two reads (or none) ⇒ not movable. A read nested inside a `map` / `fanout` element
1674
- * body runs once PER ELEMENT, so it counts as many — a single textual site is not a single read there.
1858
+ * a bindField performs. Every read a body node makes is attributed to THAT node's execution position; the
1859
+ * output assembly is the site after all of them. A read nested inside a `map` / `fanout` element body runs
1860
+ * once PER ELEMENT, so it counts as many — a single textual site is not a single read there.
1861
+ *
1862
+ * Only a site that emits THROUGH the ownership seam can move: a plain sequential arm's ports, and the
1863
+ * output assembly. A map / fanout / cond arm and a real-concurrency stage member read their heads through
1864
+ * emitters that are not given the seam, so they never move — and, being counted, they hold back every
1865
+ * EARLIER site too (a later read means the cell must still hold its value).
1866
+ *
1867
+ * Site index = position in `ep.order`; `ep.order.length` is the output assembly.
1675
1868
  */
1676
- function movableRefs(comp) {
1677
- const counts = new Map();
1678
- const bump = (head, times) => {
1679
- counts.set(head, (counts.get(head) ?? 0) + times);
1869
+ function movableRefs(comp, ep) {
1870
+ const outputSite = ep.order.length;
1871
+ const reads = new Map();
1872
+ const bump = (head, site, times) => {
1873
+ const perSite = reads.get(head) ?? new Map();
1874
+ perSite.set(site, (perSite.get(site) ?? 0) + times);
1875
+ reads.set(head, perSite);
1680
1876
  };
1681
- const walk = (n, times) => {
1877
+ const walk = (n, site, times) => {
1682
1878
  if (Array.isArray(n)) {
1683
1879
  for (const e of n)
1684
- walk(e, times);
1880
+ walk(e, site, times);
1685
1881
  return;
1686
1882
  }
1687
1883
  if (n === null || typeof n !== "object")
@@ -1691,45 +1887,64 @@ function movableRefs(comp) {
1691
1887
  if (keys.length === 1 && (keys[0] === "ref" || keys[0] === "refOpt")) {
1692
1888
  const path = rec[keys[0]];
1693
1889
  if (Array.isArray(path) && typeof path[0] === "string")
1694
- bump(path[0], times);
1890
+ bump(path[0], site, times);
1695
1891
  return;
1696
1892
  }
1697
1893
  // an element body repeats: everything under a map / fanout is read once per element.
1698
1894
  const repeats = times === 1 && ("map" in rec || "fanout" in rec) ? 2 : times;
1699
1895
  for (const k of keys)
1700
- walk(rec[k], repeats);
1896
+ walk(rec[k], site, repeats);
1701
1897
  };
1702
- walk(comp.body, 1);
1703
- walk(comp.output, 1);
1704
- for (const nd of comp.body) {
1898
+ // ep.order is TOTAL over comp.body (execPlan fail-closes on under-cover), so walking it attributes every
1899
+ // node's reads to a known execution position.
1900
+ ep.order.forEach((bodyIndex, site) => {
1901
+ const nd = comp.body[bodyIndex];
1902
+ walk(nd, site, 1);
1705
1903
  const cr = nd;
1706
1904
  if (cr.parent !== undefined && cr.bindField !== undefined)
1707
- bump(cr.parent, 1);
1905
+ bump(cr.parent, site, 1);
1906
+ });
1907
+ walk(comp.output, outputSite, 1);
1908
+ const siteCanMove = (site) => {
1909
+ if (site === outputSite)
1910
+ return true;
1911
+ const bodyIndex = ep.order[site];
1912
+ if (ep.parallelStageOf.has(bodyIndex))
1913
+ return false;
1914
+ const nd = comp.body[bodyIndex];
1915
+ return !("map" in nd) && !("fanout" in nd) && !("cond" in nd);
1916
+ };
1917
+ const bySite = new Map();
1918
+ for (const [head, perSite] of reads) {
1919
+ const last = Math.max(...perSite.keys());
1920
+ if (perSite.get(last) !== 1 || !siteCanMove(last))
1921
+ continue;
1922
+ const heads = bySite.get(last) ?? new Set();
1923
+ heads.add(head);
1924
+ bySite.set(last, heads);
1708
1925
  }
1709
- return new Set([...counts].filter(([, c]) => c === 1).map(([id]) => id));
1926
+ return bySite;
1710
1927
  }
1711
1928
  function emitNativeRawRunner(comp, plan, ap, leaf, declared) {
1712
1929
  const ep = execPlan(comp);
1713
1930
  const order = ep.order;
1714
1931
  const fn = sanitize(comp.name);
1715
1932
  const isAsync = ap.runnerIsAsync;
1933
+ // #304: the accumulator is read for THIS item (the allow is per item, never per module / per crate), so
1934
+ // it starts clean here and is read once the whole body — cond conditions, map guards, port expressions —
1935
+ // has been lowered.
1936
+ rustExprUsed.boolAlgebra = false;
1716
1937
  const typedNodes = new Map();
1717
1938
  // #125: control-gate は typeless(typedNodes に載せない)。map ノードは produced-array ref に正規化
1718
1939
  // (recorder SoT の element outType を {arr:element} へラップ / legacy {arr} はそのまま)。
1719
1940
  for (const n of comp.body)
1720
1941
  if (!isControlGate(n))
1721
1942
  typedNodes.set(n.id, "map" in n ? mapNodeArrRef(n, plan) : deriveTypeRef(n.outType, plan));
1722
- // Single-reader results are handed on by MOVE (see movableCells). A parallel stage builds its members'
1723
- // payloads inside a scoped-thread closure, so a read there is not the plain sequential read the count
1724
- // assumed — drop every head a stage member reads and let those copy.
1725
- const moveHeads = movableRefs(comp);
1726
- for (const [i] of ep.parallelStageOf) {
1727
- for (const pn of Object.keys(comp.body[i].ports ?? {})) {
1728
- const e = classifyExpr(comp.body[i].ports[pn]);
1729
- if (e.kind === "ref")
1730
- moveHeads.delete(e.path[0]);
1731
- }
1732
- }
1943
+ // A result is handed on by MOVE at its LAST read (movableRefs) — every earlier reader copies, because the
1944
+ // cell still has to hold the value for the ones after it. The lookup is BY SITE: node k's ports get the
1945
+ // heads whose last read is k, the output assembly the heads whose last read is the output.
1946
+ const moveHeadsBySite = movableRefs(comp, ep);
1947
+ const noMoves = new Set();
1733
1948
  // the ops literal comes from the SHARED derivation (opsLiteralOf): a local "read cr.policy / cr.parent"
1734
1949
  // copy silently drops a MAP's / FANOUT's policy and parent (they live under map./fanout.), which would
1735
1950
  // make canSkip — and therefore the produced-aware output — disagree with the go surface on the same IR.
@@ -1767,8 +1982,10 @@ function emitNativeRawRunner(comp, plan, ap, leaf, declared) {
1767
1982
  const fnKw = isAsync ? "pub async fn" : "pub fn";
1768
1983
  // #192: 1:1 map of the authored method — the entry is the exported fn `<method>` (rustFieldName; no
1769
1984
  // `run_native_raw_struct_` prefix) taking POSITIONAL params (one per input port; `In_<comp>` box removed).
1985
+ const attrAt = lines.length; // the allow attribute (if any) is spliced in here once the body is lowered.
1770
1986
  lines.push(`${fnKw} ${rustFieldName(comp.name)}(`);
1771
- for (const p of entryPortOrder(comp, declared)) {
1987
+ const entryPorts = entryPortOrder(comp, declared);
1988
+ for (const p of entryPorts) {
1772
1989
  lines.push(` ${rustFieldName(p)}: ${inputPortRustType(comp.inputPorts[p], plan, `input port '${p}' of component '${comp.name}'`)},`);
1773
1990
  }
1774
1991
  lines.push(`) -> Result<${outTy}, BehaviorError> {`);
@@ -1848,7 +2065,7 @@ function emitNativeRawRunner(comp, plan, ap, leaf, declared) {
1848
2065
  }
1849
2066
  }
1850
2067
  const narrowed = nodeNarrowedPaths(comp, node);
1851
- const pe = rustPortEntries(indent, node.id, `pf_${s}`, portNames.map((pn) => emitPortWireField(pn, node.ports[pn], comp, plan, typedNodes, (h) => priorNodeAt(h, k), inputPortTypeRef(node.portSchemas?.[pn], plan), { narrowed, moveHeads, portsLabel: rustPortsLabel(node.id) })));
2068
+ const pe = rustPortEntries(indent, node.id, `pf_${s}`, portNames.map((pn) => emitPortWireField(pn, node.ports[pn], comp, plan, typedNodes, (h) => priorNodeAt(h, k), inputPortTypeRef(node.portSchemas?.[pn], plan), { narrowed, moveHeads: moveHeadsBySite.get(k) ?? noMoves, portsLabel: rustPortsLabel(node.id) })));
1852
2069
  // bc#97: derived per-node await — this point-read's future is awaited HERE (its result-consumption
1853
2070
  // point) iff THIS node's terminal handler is async. A sync handler in the same async runner is called
1854
2071
  // directly (no `.await`). The runner being `async fn` does not force every call site to await.
@@ -1899,17 +2116,59 @@ function emitNativeRawRunner(comp, plan, ap, leaf, declared) {
1899
2116
  skippableKind.set(bodyNode.id, rk);
1900
2117
  }
1901
2118
  }
1902
- const out = skippable.size > 0
1903
- ? emitProducedAwareValue(comp.output, outRef, typedNodes, plan, skippable, skippableKind, comp.name, "<output>", moveHeads)
1904
- : emitTypedValue(comp.output, outRef, typedNodes, plan, comp.name, "<output>", moveHeads);
2119
+ // ONE output recursion (#295): the produced-aware read is a REF-position lowering handed to it, not a
2120
+ // second recursion — so it reaches EVERY slot the recursion descends into, an array element included.
2121
+ // Both the recursion and the seam it consults read AT the output assembly, which is site `order.length`
2122
+ // (movableRefs) — so both take that site's move set (#278), not a component-wide one.
2123
+ const outMoveHeads = moveHeadsBySite.get(order.length) ?? noMoves;
2124
+ const out = emitTypedValue(comp.output, outRef, typedNodes, plan, comp.name, "<output>", outMoveHeads, skippable.size > 0 ? rustSlotRefLowering(typedNodes, plan, skippable, skippableKind, comp.name, outMoveHeads) : undefined);
1905
2125
  // top-level output that is a bare node-result (not an obj/arr assembly): its honest `ref` must equal the
1906
2126
  // declared component output type, or the emitted `let __out = …; Ok(__out)` return does not compile.
1907
- checkOutputFieldType(comp.name, "<output>", outRef, out.ref, plan);
2127
+ checkOutputFieldType(comp.name, "<output>", outRef, out.ref);
1908
2128
  lines.push(` let __out = ${out.expr};`);
1909
2129
  lines.push(` Ok(__out)`);
1910
2130
  lines.push(`}`);
2131
+ const allow = runnerClippyAllow(entryPorts.length, rustExprUsed.boolAlgebra);
2132
+ if (allow !== undefined)
2133
+ lines.splice(attrAt, 0, allow);
1911
2134
  return lines.join("\n");
1912
2135
  }
2136
+ /**
2137
+ * runnerClippyAllow (#304 / #306) — the generator-owned `#[allow(…)]` an emitted runner carries, or
2138
+ * `undefined` when it needs none.
2139
+ *
2140
+ * A consumer runs `cargo clippy --all-targets -- -D warnings` over this file and CANNOT edit it (`bc check`
2141
+ * drift-gates it byte-identical), so any lint bc trips stops their CI with no way out — the #275 / #73 dead
2142
+ * end. #299 answered that by changing the SPELLINGS bc chooses. These two lints are not spellings: what
2143
+ * they object to is the component's own DECLARATION, which bc must not rewrite.
2144
+ *
2145
+ * - `too_many_arguments` (#306): the arguments ARE the declared input ports (#192's 1:1 positional entry).
2146
+ * Fewer arguments means a different API than the author declared.
2147
+ * - `nonminimal_bool` (#304): the lint minimizes the whole expression's boolean ALGEBRA (Quine–McCluskey),
2148
+ * so a redundant AUTHOR condition fires it on an expression bc lowered FAITHFULLY. bc must not answer by
2149
+ * minimizing it: the `&&`/`||` structure decides which fallible sub-expression is evaluated (andOr's
2150
+ * short-circuit) and therefore which failure the module reports, so minimizing changes what the module
2151
+ * computes and which error the consumer sees.
2152
+ *
2153
+ * The allow is per ITEM and CONDITIONAL — never a module-level `#![allow]` (which would also cover the
2154
+ * static wire seam and the helper library) and never unconditional (which would make the corpus clippy gate,
2155
+ * scripts/clippy-corpus.mjs, stop asserting anything). The condition is the shape that can trip the lint:
2156
+ * an arity over clippy's default threshold of 7, and an author connective actually lowered into this item.
2157
+ * The SPELLINGS #299/#309 own are outside both: a `not` has an exact complement for every operand type
2158
+ * (bool literal, double `not`, eq/ne, a TOTAL-order ordering swap, a float `partial_cmp` match), so a runner
2159
+ * with no author `and`/`or` keeps `nonminimal_bool` fully enforced. Inside a runner that HAS one, the allow
2160
+ * does cover the whole item — the price of the item being the smallest thing rust lets a generator annotate
2161
+ * without a module-wide `#![allow]`.
2162
+ */
2163
+ function runnerClippyAllow(arity, boolAlgebra) {
2164
+ const lints = [
2165
+ // clippy::nonminimal_bool — an author `and`/`or` was lowered into this runner.
2166
+ ...(boolAlgebra ? ["clippy::nonminimal_bool"] : []),
2167
+ // clippy::too_many_arguments — clippy's default threshold is 7 (it reports `(8/7)` at eight).
2168
+ ...(arity > 7 ? ["clippy::too_many_arguments"] : []),
2169
+ ];
2170
+ return lints.length === 0 ? undefined : `#[allow(${lints.join(", ")})]`;
2171
+ }
1913
2172
  /**
1914
2173
  * stageAwaits (#231) — the ONE derivation of a real-concurrency stage's dispatch MECHANISM: a std thread
1915
2174
  * cannot host `.await`, so a stage dispatches by joining its members' futures iff ANY member awaits, and
@@ -2179,14 +2438,17 @@ function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes
2179
2438
  lines.push(` if let Some(e) = perr_${s} { return Err(e); }`);
2180
2439
  const takeSlot = stageIsAsync ? `slot_${s}.take()` : `slot_${s}.lock().unwrap().take()`;
2181
2440
  lines.push(` let taken_${s} = ${takeSlot};`);
2182
- lines.push(` if let Some(out_${s}) = taken_${s} {`);
2441
+ // continue: a member whose COMPONENT failed commits no Port, so the Ok is part of the SAME pattern the
2442
+ // slot is matched by — `Some(Ok(w))`. Nesting a second `if let Ok(…)` inside `if let Some(…)` is
2443
+ // `clippy::collapsible_match`, an ERROR under a consumer's `-D warnings` (#299), and a generated
2444
+ // module cannot be edited to silence it (`bc check` drift-gates it byte-identical). Every other policy
2445
+ // INTERPRETS the Err (op_failed / retry), so its arm binds the Result and matches it.
2446
+ lines.push(` if let Some(${meta.policy === "continue" ? `Ok(wire_${s})` : `out_${s}`}) = taken_${s} {`);
2183
2447
  if (meta.policy === "continue") {
2184
- // continue: a member whose COMPONENT failed commits no Port. A de-box mismatch still propagates —
2185
- // the interpreter's outType check sits outside the policy interpretation (see the sequential arm).
2186
- lines.push(` if let Ok(wire_${s}) = out_${s} {`);
2187
- lines.push(` *${typedCell(node.id)}.borrow_mut() = ${renderResultDeBox(ref, `wire_${s}`, node.id, plan, " ", returnErrFail, nodeWirePassthrough(node))};`);
2188
- lines.push(` produced_${s}.set(true);`);
2189
- lines.push(` }`);
2448
+ // A de-box mismatch still propagates — the interpreter's outType check sits outside the policy
2449
+ // interpretation (see the sequential arm).
2450
+ lines.push(` *${typedCell(node.id)}.borrow_mut() = ${renderResultDeBox(ref, `wire_${s}`, node.id, plan, " ", returnErrFail, nodeWirePassthrough(node))};`);
2451
+ lines.push(` produced_${s}.set(true);`);
2190
2452
  }
2191
2453
  else {
2192
2454
  const policyLit = rustStrLit(meta.policy === "retry" ? "retry" : "fail");
@@ -2219,15 +2481,23 @@ function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes
2219
2481
  * for continue)。失敗した時点でノードの残りを飛ばすため **labeled block** で囲む(`loop { … break }` は
2220
2482
  * clippy の `never_loop` に `-D warnings` で殺される)。この形なら de-box 不一致 / 整列違反の
2221
2483
  * `return Err(...)` はそのまま関数を抜ける — interpreter も outType 検査を policy の外で throw する。
2484
+ *
2485
+ * The body is a BLOCK either way — `continue` only decides whether that block is LABELED. An arm holds
2486
+ * borrows: the `over` binding reads a prior node's cell IN PLACE rather than copying it (#294), and a
2487
+ * `Ref` guard lives to the end of its BLOCK (it has a `Drop` impl — NLL does not end it at its last use),
2488
+ * so an unscoped arm would still hold that cell when the runner's NEXT statement `take()`s it (#278) or
2489
+ * writes it — a `RefCell already borrowed` panic. The arm's own locals (`over_` / `built_` / `items_` …)
2490
+ * are the arm's alone in the first place, so this scope is what the arm always meant.
2222
2491
  */
2223
2492
  function rustPolicyArm(s, indent, continuePolicy, body) {
2224
2493
  const produced = `${indent}produced_${s}.set(true);`;
2494
+ const scoped = body.map((l) => ` ${l}`.replace(/\n/g, "\n "));
2225
2495
  if (!continuePolicy)
2226
- return [...body, produced];
2496
+ return [`${indent}{`, ...scoped, `${indent}}`, produced];
2227
2497
  return [
2228
2498
  `${indent}let mut skipped_${s} = false;`,
2229
2499
  `${indent}'node_${s}: {`,
2230
- ...body.map((l) => ` ${l}`.replace(/\n/g, "\n ")),
2500
+ ...scoped,
2231
2501
  `${indent}}`,
2232
2502
  `${indent}if !skipped_${s} {`,
2233
2503
  ` ${produced}`,
@@ -2253,8 +2523,9 @@ isAsync = false, policy = "fail") {
2253
2523
  const s = sanitize(node.id);
2254
2524
  const transform = mapTransformExpr(m);
2255
2525
  const leafSym = transform === undefined ? resolveLeafSymbol(m.component, leaf, m.leafSymbol) : "";
2256
- // #108: over element type + the OWNED over-Vec expression (prior-node arr OR input array w/ elemType).
2257
- const { elemRef: overElemRef, overExpr, optArr: overOptArr } = mapOverElemInfo(comp, node, typedNodes, plan);
2526
+ // #108: over element type + how this arm reads the collection (prior-node arr OR input array w/ elemType).
2527
+ const { elemRef: overElemRef, over } = mapOverElemInfo(comp, node, typedNodes, plan);
2528
+ const ov = over(isAsync);
2258
2529
  const elemMat = mapElemMaterializerName(comp.name, node.id);
2259
2530
  const priorHere = (head) => priorNodeAt(head, atPos);
2260
2531
  const asName = m.as;
@@ -2269,18 +2540,14 @@ isAsync = false, policy = "fail") {
2269
2540
  // #177/#182 keep-with-skip-value: the into value for a guard-skipped element is driven by relationKind,
2270
2541
  // NOT by opt-ness (matching run_behavior applyInto, which fills a connection into with the empty
2271
2542
  // connection UNCONDITIONALLY on relationKind==="connection"):
2272
- // - connection into → the connection-zero in the field's typed rep (same shape emitProducedAwareValue
2273
- // uses for a skipped connection node): a required `Conn` field → `Conn::default()`, an OPT
2274
- // `Option<Conn>` field → `Some(Conn::default())` (empty connection, NOT None). `Conn::default()`'s
2275
- // derived Default serializes to {items:[],cursor:null} (#182).
2543
+ // - connection into → the connection-zero in the field's typed rep: a required `Conn` field →
2544
+ // `Conn::default()`, an OPT `Option<Conn>` field → `Some(Conn::default())` (empty connection, NOT
2545
+ // None). `Conn::default()`'s derived Default serializes to {items:[],cursor:null} (#182).
2276
2546
  // - non-connection into → opt → None = null (#177 keep-with-null; unchanged).
2277
- const intoSkipDefault = m.relationKind === "connection"
2278
- ? elemDeBoxRef.kind === "opt"
2279
- ? `Some(${renderTypeRef(elemDeBoxRef.inner)}::default())`
2280
- : `${renderTypeRef(elemDeBoxRef)}::default()`
2281
- : elemDeBoxRef.kind === "opt"
2282
- ? "None"
2283
- : `${renderTypeRef(elemDeBoxRef)}::default()`;
2547
+ // That IS the produced-aware output read's unproduced arm at a different position, so it reads the SAME
2548
+ // rule (typed.ts `unproducedInSlot`) with the same rust spellings rather than a second copy. The `into`
2549
+ // attach point always receives the child result WHOLE (there is no path into it), hence `whole: true`.
2550
+ const intoSkipDefault = unproducedInSlot(elemDeBoxRef, m.relationKind, true, RUST_PRODUCED_AWARE);
2284
2551
  // the per-element boxed port entries (#183) — the SAME box SSoT as a point node, over the $as element.
2285
2552
  const portEntries = (il) => {
2286
2553
  const asBinding = { name: asName, ref: overElemRef, plan };
@@ -2292,11 +2559,16 @@ isAsync = false, policy = "fail") {
2292
2559
  // the batch payload. NON-batched element: `ep_<s>` is the per-element transport payload WireRow.
2293
2560
  // A FALLIBLE element port (#238) builds its entries in a labeled block inside the loop, so the failure
2294
2561
  // surfaces at the element the interpreter would have failed on.
2562
+ // The batched shapes bind `ep_<s>` right where they build it — their dispatch is OUTSIDE the element
2563
+ // loop. The non-batched shape hands it ACROSS its per-element dispatch, so it binds through `ov.elem`.
2295
2564
  const buildElem = (il, wrap) => {
2296
2565
  const pe = portEntries(il);
2297
- return [...pe.lines, `${il}let ep_${s} = ${wrap(pe.entries)};`];
2566
+ return { lines: pe.lines, value: wrap(pe.entries) };
2567
+ };
2568
+ const buildBatchElem = (il) => {
2569
+ const b = buildElem(il, (e) => `WireValue::Row(WireRow { entries: ${e} })`);
2570
+ return [...b.lines, `${il}let ep_${s} = ${b.value};`];
2298
2571
  };
2299
- const buildBatchElem = (il) => buildElem(il, (e) => `WireValue::Row(WireRow { entries: ${e} })`);
2300
2572
  const buildPayloadElem = (il) => buildElem(il, (e) => rustPayloadRow(e));
2301
2573
  // #108 guard: compile `when` to a native bool over an element-scoped resolveHead ($as element value,
2302
2574
  // prior node, input port). mkGuard returns the compiled {stmts, expr} (or null when unguarded); the
@@ -2333,26 +2605,27 @@ isAsync = false, policy = "fail") {
2333
2605
  }
2334
2606
  // the node's own statements start here (rustPolicyArm wraps THIS range when the Kind is `continue`).
2335
2607
  const bodyStart = lines.length;
2336
- lines.push(`${indent}let over_${s} = ${rustBindOverExpr(overExpr, overOptArr)};`);
2608
+ lines.push(`${indent}${ov.open}`);
2337
2609
  // `built_<s>` は Component 経路の集積ローカル。純式 map は typed cell へ直接積むので出さない
2338
2610
  // (生成物は clippy -D warnings を通るので未使用/不要 mut は出せない)。
2339
2611
  if (transform === undefined)
2340
- lines.push(`${indent}let mut built_${s}: Vec<${elemName}> = Vec::with_capacity(over_${s}.len());`);
2612
+ lines.push(`${indent}let mut built_${s}: Vec<${elemName}> = Vec::with_capacity(${ov.count});`);
2341
2613
  if (transform !== undefined) {
2342
2614
  // 純式 map(#222): transport 呼びもワイヤも de-box も無い。要素式を宣言された要素型へ native に
2343
2615
  // materialize して積む(port 境界と同一の宣言型 materializer を通す)。`when` は同一の keep-gate。
2344
- lines.push(`${indent}for oel_${s} in over_${s}.iter() {`);
2616
+ const walk = [`${indent}for oel_${s} in over_${s}.iter() {`];
2345
2617
  for (const l of emitGuard(indent + " "))
2346
- lines.push(l);
2618
+ walk.push(l);
2347
2619
  const tc = compilePortNode(transform, comp, plan, typedNodes, priorHere, `map '${node.id}' transform`, elemArrRef.elem, {
2348
2620
  asBinding: { name: asName, ref: overElemRef, plan },
2349
2621
  asBase: `oel_${s}`,
2350
2622
  narrowed: nodeNarrowedPaths(comp, node),
2351
2623
  });
2352
2624
  for (const st of tc.stmts)
2353
- lines.push(`${indent} ${st}`);
2354
- lines.push(`${indent} ${typedCell(node.id)}.borrow_mut().push(${tc.expr});`);
2355
- lines.push(`${indent}}`);
2625
+ walk.push(`${indent} ${st}`);
2626
+ walk.push(`${indent} ${typedCell(node.id)}.borrow_mut().push(${tc.expr});`);
2627
+ walk.push(`${indent}}`);
2628
+ lines.push(...ov.hold(indent, walk));
2356
2629
  lines.push(...rustPolicyArm(sanitize(node.id), indent, false, lines.splice(bodyStart)));
2357
2630
  for (const c of closers)
2358
2631
  lines.push(c);
@@ -2365,21 +2638,22 @@ isAsync = false, policy = "fail") {
2365
2638
  // zips its next deboxed row, a skipped element gets into=None. Byte-equal to run_behavior: batched
2366
2639
  // keptIdx-aligned collect + applyInto (skipped element unaugmented → opt-into null).
2367
2640
  const g = mkGuard();
2368
- lines.push(`${indent}let mut items_${s}: Vec<WireValue> = Vec::with_capacity(over_${s}.len());`);
2369
- lines.push(`${indent}let mut keep_${s}: Vec<bool> = Vec::with_capacity(over_${s}.len());`);
2370
- lines.push(`${indent}for oel_${s} in over_${s}.iter() {`);
2641
+ lines.push(`${indent}let mut items_${s}: Vec<WireValue> = Vec::with_capacity(${ov.count});`);
2642
+ lines.push(`${indent}let mut keep_${s}: Vec<bool> = Vec::with_capacity(${ov.count});`);
2643
+ const pass1 = [`${indent}for oel_${s} in over_${s}.iter() {`];
2371
2644
  for (const st of g.stmts)
2372
- lines.push(`${indent} ${st}`);
2373
- lines.push(`${indent} let __keep = ${rustStripOuterParens(g.expr)};`);
2374
- lines.push(`${indent} if __keep {`);
2645
+ pass1.push(`${indent} ${st}`);
2646
+ pass1.push(`${indent} let __keep = ${rustStripOuterParens(g.expr)};`);
2647
+ pass1.push(`${indent} if __keep {`);
2375
2648
  for (const l of buildBatchElem(indent + " "))
2376
- lines.push(l);
2377
- lines.push(`${indent} items_${s}.push(ep_${s});`);
2378
- lines.push(`${indent} keep_${s}.push(true);`);
2379
- lines.push(`${indent} } else {`);
2380
- lines.push(`${indent} keep_${s}.push(false);`);
2381
- lines.push(`${indent} }`);
2382
- lines.push(`${indent}}`);
2649
+ pass1.push(l);
2650
+ pass1.push(`${indent} items_${s}.push(ep_${s});`);
2651
+ pass1.push(`${indent} keep_${s}.push(true);`);
2652
+ pass1.push(`${indent} } else {`);
2653
+ pass1.push(`${indent} keep_${s}.push(false);`);
2654
+ pass1.push(`${indent} }`);
2655
+ pass1.push(`${indent}}`);
2656
+ lines.push(...ov.hold(indent, pass1));
2383
2657
  lines.push(`${indent}let mut decs_${s}: Vec<${renderTypeRef(elemDeBoxRef)}> = Vec::with_capacity(items_${s}.len());`);
2384
2658
  lines.push(`${indent}if !items_${s}.is_empty() {`);
2385
2659
  lines.push(`${indent} let want_${s} = items_${s}.len();`);
@@ -2401,29 +2675,31 @@ isAsync = false, policy = "fail") {
2401
2675
  lines.push(`${indent} }`);
2402
2676
  lines.push(`${indent}}`);
2403
2677
  lines.push(`${indent}let mut decs_iter_${s} = decs_${s}.into_iter();`);
2404
- lines.push(`${indent}for (oel_${s}, kept_${s}) in over_${s}.iter().zip(keep_${s}.iter()) {`);
2405
- lines.push(`${indent} if *kept_${s} {`);
2406
- lines.push(`${indent} let dec_${s} = decs_iter_${s}.next().expect("aligned kept row");`);
2407
- lines.push(`${indent} built_${s}.push(${elemMat}(oel_${s}, dec_${s}));`);
2408
- lines.push(`${indent} } else {`);
2409
- lines.push(`${indent} built_${s}.push(${elemMat}(oel_${s}, ${intoSkipDefault}));`);
2410
- lines.push(`${indent} }`);
2411
- lines.push(`${indent}}`);
2678
+ const pass2 = [`${indent}for (oel_${s}, kept_${s}) in over_${s}.iter().zip(keep_${s}.iter()) {`];
2679
+ pass2.push(`${indent} if *kept_${s} {`);
2680
+ pass2.push(`${indent} let dec_${s} = decs_iter_${s}.next().expect("aligned kept row");`);
2681
+ pass2.push(`${indent} built_${s}.push(${elemMat}(oel_${s}, dec_${s}));`);
2682
+ pass2.push(`${indent} } else {`);
2683
+ pass2.push(`${indent} built_${s}.push(${elemMat}(oel_${s}, ${intoSkipDefault}));`);
2684
+ pass2.push(`${indent} }`);
2685
+ pass2.push(`${indent}}`);
2686
+ lines.push(...ov.hold(indent, pass2));
2412
2687
  }
2413
2688
  else if (batched) {
2414
2689
  // build kept-element ports (+ kept over elements for into). Batched into is never guarded (rejected).
2415
- lines.push(`${indent}let mut items_${s}: Vec<WireValue> = Vec::with_capacity(over_${s}.len());`);
2690
+ lines.push(`${indent}let mut items_${s}: Vec<WireValue> = Vec::with_capacity(${ov.count});`);
2416
2691
  if (hasInto)
2417
- lines.push(`${indent}let mut kept_${s}: Vec<${renderTypeRef(overElemRef)}> = Vec::with_capacity(over_${s}.len());`);
2418
- lines.push(`${indent}for oel_${s} in over_${s}.iter() {`);
2692
+ lines.push(`${indent}let mut kept_${s}: Vec<${renderTypeRef(overElemRef)}> = Vec::with_capacity(${ov.count});`);
2693
+ const build = [`${indent}for oel_${s} in over_${s}.iter() {`];
2419
2694
  for (const l of emitGuard(indent + " "))
2420
- lines.push(l);
2695
+ build.push(l);
2421
2696
  for (const l of buildBatchElem(indent + " "))
2422
- lines.push(l);
2423
- lines.push(`${indent} items_${s}.push(ep_${s});`);
2697
+ build.push(l);
2698
+ build.push(`${indent} items_${s}.push(ep_${s});`);
2424
2699
  if (hasInto)
2425
- lines.push(`${indent} kept_${s}.push(oel_${s}.clone());`);
2426
- lines.push(`${indent}}`);
2700
+ build.push(`${indent} kept_${s}.push(oel_${s}.clone());`);
2701
+ build.push(`${indent}}`);
2702
+ lines.push(...ov.hold(indent, build));
2427
2703
  lines.push(`${indent}if !items_${s}.is_empty() {`);
2428
2704
  lines.push(`${indent} let want_${s} = items_${s}.len();`);
2429
2705
  // ONE op-agnostic transport call: batch payload WireRow {items:[…]}; result WireList → aligned wires.
@@ -2457,40 +2733,40 @@ isAsync = false, policy = "fail") {
2457
2733
  lines.push(`${indent}}`);
2458
2734
  }
2459
2735
  else {
2460
- // #93 shape 2 / #108: NON-batched map — dispatch ONCE PER KEPT ELEMENT.
2461
- lines.push(`${indent}for oel_${s} in over_${s}.iter() {`);
2736
+ // #93 shape 2 / #108: NON-batched map — dispatch ONCE PER KEPT ELEMENT. This is the ONE shape whose
2737
+ // dispatch sits INSIDE the element loop, so the element is read on BOTH sides of it: the ports before,
2738
+ // the augmenting materializer after. `ov.elem` is what makes each side its own read of the place, so
2739
+ // nothing has to be held (let alone copied) across the dispatch (#300).
2740
+ const il = `${indent} `;
2741
+ const body = [];
2462
2742
  // #177/#182 keep-with-skip-value: a guard-skipped element is KEPT with into=intoSkipDefault (None /
2463
2743
  // Conn::default()) instead of dropped — byte-equal to run_behavior's applyInto (opt-into → null /
2464
2744
  // connection-into → empty connection).
2465
2745
  const nonBatchedSkip = keepWithNull ? `built_${s}.push(${elemMat}(oel_${s}, ${intoSkipDefault})); continue;` : "continue;";
2466
- for (const l of emitGuard(indent + " ", nonBatchedSkip))
2467
- lines.push(l);
2468
- for (const l of buildPayloadElem(indent + " "))
2469
- lines.push(l);
2746
+ const pe = buildPayloadElem(il);
2747
+ body.push(...ov.elem(il, [...emitGuard(il, nonBatchedSkip), ...pe.lines], { name: `ep_${s}`, value: pe.value }));
2470
2748
  // Element Error Policy (scp-error.md): `skip` drops the failing element and proceeds (order is
2471
2749
  // preserved; the leaf keeps the Error Value it produced). `error` (default) promotes the element
2472
2750
  // Failure to the map's Component Failure. ONE op-agnostic transport call per element, ONE WireRow payload.
2473
- lines.push(`${indent} let er_${s} = match ${leafSym}(ep_${s})${awaitSfx} {`);
2474
- lines.push(`${indent} Ok(r) => r,`);
2751
+ body.push(`${il}let er_${s} = match ${leafSym}(ep_${s})${awaitSfx} {`);
2752
+ body.push(`${il} Ok(r) => r,`);
2475
2753
  if (m.elementPolicy === "skip") {
2476
- lines.push(`${indent} Err(_) => continue,`);
2754
+ body.push(`${il} Err(_) => continue,`);
2477
2755
  }
2478
2756
  else {
2479
- lines.push(contPolicy
2480
- ? `${indent} Err(_) => { skipped_${s} = true; break 'node_${s}; }`
2481
- : `${indent} Err(e) => return Err(op_failed(${rustStrLit(node.id)}, ${policyLit}, e)),`);
2757
+ body.push(contPolicy
2758
+ ? `${il} Err(_) => { skipped_${s} = true; break 'node_${s}; }`
2759
+ : `${il} Err(e) => return Err(op_failed(${rustStrLit(node.id)}, ${policyLit}, e)),`);
2482
2760
  }
2483
- lines.push(`${indent} };`);
2761
+ body.push(`${il}};`);
2484
2762
  // the element's wire is de-boxed strictly INLINE (fail-closed regardless of elementPolicy).
2485
- lines.push(`${indent} let dec_${s} = ${renderElemDeBox(`${indent} `)};`);
2486
- if (hasInto) {
2487
- lines.push(`${indent} built_${s}.push(${elemMat}(oel_${s}, dec_${s}));`);
2488
- }
2489
- else {
2490
- lines.push(`${indent} let _ = &oel_${s};`);
2491
- lines.push(`${indent} built_${s}.push(dec_${s});`);
2492
- }
2493
- lines.push(`${indent}}`);
2763
+ body.push(`${il}let dec_${s} = ${renderElemDeBox(il)};`);
2764
+ // …and only an INTO map reads the element again: a no-into map's result IS the de-boxed element.
2765
+ if (hasInto)
2766
+ body.push(...ov.elem(il, [`${il}built_${s}.push(${elemMat}(oel_${s}, dec_${s}));`]));
2767
+ else
2768
+ body.push(`${il}built_${s}.push(dec_${s});`);
2769
+ lines.push(...ov.each(indent, body));
2494
2770
  }
2495
2771
  lines.push(`${indent}*${typedCell(node.id)}.borrow_mut() = built_${s};`);
2496
2772
  lines.push(...rustPolicyArm(sanitize(node.id), indent, contPolicy, lines.splice(bodyStart)));
@@ -2516,7 +2792,8 @@ function emitFanoutArm(comp, node, atPos, typedNodes, plan, priorNodeAt, leaf, i
2516
2792
  const connRef = typedNodes.get(node.id);
2517
2793
  const elemRef = fanoutItemsElemRef(node, connRef, plan);
2518
2794
  const elemName = renderTypeRef(elemRef);
2519
- const { elemRef: overElemRef, overExpr, optArr: overOptArr } = fanoutOverElemInfo(comp, node, typedNodes, plan);
2795
+ const { elemRef: overElemRef, over } = fanoutOverElemInfo(comp, node, typedNodes, plan);
2796
+ const ov = over(isAsync);
2520
2797
  const asName = f.as;
2521
2798
  const priorHere = (head) => priorNodeAt(head, atPos);
2522
2799
  const portNames = Object.keys(f.ports);
@@ -2546,14 +2823,15 @@ function emitFanoutArm(comp, node, atPos, typedNodes, plan, priorNodeAt, leaf, i
2546
2823
  }
2547
2824
  // the node's own statements start here (rustPolicyArm wraps THIS range when the Kind is `continue`).
2548
2825
  const bodyStart = lines.length;
2549
- lines.push(`${indent}let over_${s} = ${rustBindOverExpr(overExpr, overOptArr)};`);
2826
+ lines.push(`${indent}${ov.open}`);
2550
2827
  lines.push(`${indent}let mut built_${s}: Vec<${elemName}> = Vec::new();`);
2551
- lines.push(`${indent}let mut pi_${s}: Vec<WireValue> = Vec::with_capacity(over_${s}.len());`);
2552
- lines.push(`${indent}for oel_${s} in over_${s}.iter() {`);
2828
+ lines.push(`${indent}let mut pi_${s}: Vec<WireValue> = Vec::with_capacity(${ov.count});`);
2829
+ const build = [`${indent}for oel_${s} in over_${s}.iter() {`];
2553
2830
  for (const l of buildPorts(indent + " "))
2554
- lines.push(l);
2555
- lines.push(`${indent} pi_${s}.push(ep_${s});`);
2556
- lines.push(`${indent}}`);
2831
+ build.push(l);
2832
+ build.push(`${indent} pi_${s}.push(ep_${s});`);
2833
+ build.push(`${indent}}`);
2834
+ lines.push(...ov.hold(indent, build));
2557
2835
  lines.push(`${indent}if !pi_${s}.is_empty() {`);
2558
2836
  lines.push(`${indent} let want_${s} = pi_${s}.len();`);
2559
2837
  // ONE op-agnostic transport call: batch payload WireRow {items:[…]}; result is a WireList of the aligned
@@ -2658,65 +2936,45 @@ function emitCondArm(comp, node, atPos, typedNodes, plan, priorNodeAt) {
2658
2936
  return lines.join("\n");
2659
2937
  }
2660
2938
  /**
2661
- * emitProducedAwareValue — the #86 part 1 produced-aware output lowering (rust twin of the go one).
2939
+ * RUST_PRODUCED_AWARE — the rust SPELLINGS of the shared produced-aware output lowering (typed.ts
2940
+ * {@link lowerProducedAwareRead} / {@link unproducedInSlot}). Only the syntax lives here; the rule is
2941
+ * language-neutral and is NOT restated (go's twin is GO_PRODUCED_AWARE).
2662
2942
  */
2663
- function emitProducedAwareValue(node, expected, typedNodes, plan, skippable, skippableKind, compName, fieldPath, moveHeads) {
2664
- const e = classifyExpr(node);
2665
- if (e.kind === "ref" && e.path.length >= 1 && typedNodes.has(e.path[0])) {
2943
+ const RUST_PRODUCED_AWARE = {
2944
+ producedFlag: (head) => `produced_${sanitize(head)}.get()`,
2945
+ optSome: (valueExpr) => `Some(${valueExpr})`,
2946
+ zero: (ref) => (ref.kind === "opt" ? "None" : ref.kind === "named" ? `${ref.name}::default()` : "Default::default()"),
2947
+ conditional: (cond, present, absent) => `if ${cond} { ${present} } else { ${absent} }`,
2948
+ };
2949
+ /**
2950
+ * rustSlotRefLowering — the rust binding of the ONE output recursion's node-result-reference seam
2951
+ * ({@link SlotRefLowering}), used when ANY covered node can SKIP (#86 part 1). Rust twin of goSlotRefLowering.
2952
+ */
2953
+ function rustSlotRefLowering(typedNodes, plan, skippable, skippableKind, compName, moveHeads) {
2954
+ return (node, declared, fieldPath) => {
2955
+ const e = classifyExpr(node);
2956
+ if (e.kind !== "ref" || e.path.length < 1 || !typedNodes.has(e.path[0]))
2957
+ return undefined;
2666
2958
  const head = e.path[0];
2667
- const baseRef = typedNodes.get(head);
2668
- if (skippable.has(head)) {
2669
- const { expr, ref } = rustCellPathRead(head, baseRef, e.path.slice(1), plan, moveHeads);
2670
- // The value actually placed into this output field is `producedExpr` — its type is `ref`, opt-wrapped
2671
- // by valueLeafProduced iff the field is opt and the value is not (matching Some(...)). Compare its
2672
- // RENDERED type against the field's RENDERED type: this is exactly what rustc checks at the produced
2673
- // arm (both if-arms + field must agree), so it fails IFF the emitted module would not compile (E0308).
2674
- const placed = expected && expected.kind === "opt" && ref.kind !== "opt" ? { kind: "opt", inner: ref } : ref;
2675
- checkOutputFieldType(compName, fieldPath, expected, placed, plan);
2676
- const producedExpr = valueLeafProduced(expr, ref, expected);
2677
- const isConn = skippableKind.get(head) === "connection" && e.path.length === 1;
2678
- let unproduced;
2679
- if (isConn) {
2680
- const connTy = expected && expected.kind === "opt" ? renderTypeRef(expected.inner) : renderTypeRef(expected ?? ref);
2681
- unproduced = expected && expected.kind === "opt" ? `Some(${connTy}::default())` : `${connTy}::default()`;
2682
- }
2683
- else {
2684
- unproduced = expected && expected.kind === "opt" ? "None" : "Default::default()";
2685
- }
2686
- return {
2687
- expr: `if produced_${sanitize(head)}.get() { ${producedExpr} } else { ${unproduced} }`,
2688
- ref: expected ?? ref,
2689
- };
2690
- }
2691
- // Non-skippable node-result: its `ref` is returned honestly (not laundered), so the placing site — the
2692
- // obj-field assembly below, or the top-level call — runs checkOutputFieldType against the field type.
2693
- return rustCellPathRead(head, baseRef, e.path.slice(1), plan, moveHeads);
2694
- }
2695
- if (node !== null && typeof node === "object" && !Array.isArray(node)) {
2696
- const keys = Object.keys(node);
2697
- if (keys.length === 1 && keys[0] === "obj" && expected && expected.kind === "named") {
2698
- const decl = findDecl(plan, expected.name);
2699
- const fields = node.obj;
2700
- const inits = decl.fields.map((f) => {
2701
- const childPath = fieldPath === "" ? f.name : `${fieldPath}.${f.name}`;
2702
- const sub = emitProducedAwareValue(fields[f.name], f.type, typedNodes, plan, skippable, skippableKind, compName, childPath, moveHeads);
2703
- // Non-skippable field: sub.ref is the honest value type → catches a Vec-depth mismatch here. A
2704
- // skippable field launders sub.ref to expected, but its own produced-arm check (above) already fired.
2705
- checkOutputFieldType(compName, childPath, f.type, sub.ref, plan);
2706
- return `${rustFieldName(f.name)}: ${sub.expr}`;
2707
- });
2708
- return { expr: `${expected.name} { ${inits.join(", ")} }`, ref: expected };
2709
- }
2710
- }
2711
- return emitTypedValue(node, expected, typedNodes, plan, compName, fieldPath, moveHeads);
2712
- }
2713
- function valueLeafProduced(expr, ref, expected) {
2714
- if (expected && expected.kind === "opt") {
2715
- if (ref.kind === "opt")
2716
- return expr;
2717
- return `Some(${expr})`;
2718
- }
2719
- return expr;
2959
+ const { expr, ref } = rustCellPathRead(head, typedNodes.get(head), e.path.slice(1), plan, moveHeads);
2960
+ // a NON-skippable node's `ref` is returned honestly (not laundered), so the PLACING site runs
2961
+ // checkOutputFieldType against the slot type.
2962
+ if (!skippable.has(head))
2963
+ return { expr, ref };
2964
+ return lowerProducedAwareRead({
2965
+ path: e.path,
2966
+ relationKind: skippableKind.get(head),
2967
+ optional: e.opt,
2968
+ valueExpr: expr,
2969
+ value: ref,
2970
+ declared,
2971
+ compName,
2972
+ fieldPath,
2973
+ check: checkOutputFieldType,
2974
+ spell: RUST_PRODUCED_AWARE,
2975
+ plan,
2976
+ });
2977
+ };
2720
2978
  }
2721
2979
  // bc#90 / runtime-free: the old `valueLeafInner` (which serialized a bindField to a boxed `Value` for the
2722
2980
  // binding check) is REMOVED — the bound value is now a typed `Option<K>` built by direct field access
@@ -2925,12 +3183,19 @@ ${withRustfmtSkip(emitStructSurface([]))}
2925
3183
  // - Everything fixed at generation time (SQL text, port names, field names) rides as \`&'static str\`
2926
3184
  // behind \`Cow::Borrowed\`, so building a payload allocates nothing for it, however often it is called.
2927
3185
  // - De-boxing CONSUMES the transport's wire: every string, row and list is MOVED into the typed value,
2928
- // and a result with a single reader is MOVED out of its cell (\`.take()\`) rather than copied. Reading
2929
- // one field of a result that has several readers borrows to that field and owns only it — the row is
2930
- // never copied to read part of it.
3186
+ // and a result is MOVED out of its cell (\`.take()\`) by its LAST reader rather than copied. A reader
3187
+ // before that one cannot move — the cell still holds the value for the readers after it — but it does
3188
+ // not COPY either: it reads the cell as a borrow and owns exactly what it puts on the wire. So reading
3189
+ // one field owns that field, and re-boxing a result set per row owns each row's crossing fields, with
3190
+ // the result set itself never duplicated to be read. A map / fanout ITERATES its \`over\` collection in
3191
+ // place for the same reason — it reads \`len()\` and \`iter()\` and keeps nothing, so it needs no copy at
3192
+ // all. A node whose leaf call SUSPENDS does not copy it either: a \`Ref\` guard is \`!Send\` and this
3193
+ // runner's future must stay drivable by ANY executor, so such an arm SCOPES its read to the runs that
3194
+ // do not suspend and re-reads the place across the suspension — a borrow flag, not a copy.
2931
3195
  // The codegen purity gate fails the build on exactly those spellings (a wire classifier that borrows, a
2932
3196
  // de-box that clones a list out of the wire, a row cloned out of its cell before a field is taken from the
2933
- // copy) and the cost is confirmed by benchmark, not by this comment.
3197
+ // copy, an over collection copied out of its place) and the cost is confirmed by benchmark, not by this
3198
+ // comment.
2934
3199
  use std::borrow::Cow;
2935
3200
  use std::cell::RefCell;`;
2936
3201
  const sections = [