behavior-contracts 0.11.17 → 0.11.19
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.
- package/cli-contract.yaml +9 -4
- package/dist/behavior.d.ts +16 -7
- package/dist/behavior.d.ts.map +1 -1
- package/dist/behavior.js +19 -8
- package/dist/behavior.js.map +1 -1
- package/dist/cli.js +4 -2
- package/dist/cli.js.map +1 -1
- package/dist/expr-eval.d.ts +8 -1
- package/dist/expr-eval.d.ts.map +1 -1
- package/dist/expr-eval.js +11 -2
- package/dist/expr-eval.js.map +1 -1
- package/dist/generated/contract.d.ts.map +1 -1
- package/dist/generated/contract.js +2 -2
- package/dist/generated/contract.js.map +1 -1
- package/dist/generator/core.d.ts +4 -2
- package/dist/generator/core.d.ts.map +1 -1
- package/dist/generator/core.js.map +1 -1
- package/dist/generator/emit-shared-go-typed.d.ts +8 -12
- package/dist/generator/emit-shared-go-typed.d.ts.map +1 -1
- package/dist/generator/emit-shared-go-typed.js +40 -25
- package/dist/generator/emit-shared-go-typed.js.map +1 -1
- package/dist/generator/emit-shared-rust-typed.d.ts +12 -16
- package/dist/generator/emit-shared-rust-typed.d.ts.map +1 -1
- package/dist/generator/emit-shared-rust-typed.js +45 -30
- package/dist/generator/emit-shared-rust-typed.js.map +1 -1
- package/dist/generator/emit-shared-typescript-typed.d.ts.map +1 -1
- package/dist/generator/emit-shared-typescript-typed.js +10 -2
- package/dist/generator/emit-shared-typescript-typed.js.map +1 -1
- package/dist/generator/emit-straightline-typed-typescript.d.ts.map +1 -1
- package/dist/generator/emit-straightline-typed-typescript.js +15 -23
- package/dist/generator/emit-straightline-typed-typescript.js.map +1 -1
- package/dist/generator/emit-typed-native-go.d.ts.map +1 -1
- package/dist/generator/emit-typed-native-go.js +185 -141
- package/dist/generator/emit-typed-native-go.js.map +1 -1
- package/dist/generator/emit-typed-native-rust.d.ts.map +1 -1
- package/dist/generator/emit-typed-native-rust.js +556 -283
- package/dist/generator/emit-typed-native-rust.js.map +1 -1
- package/dist/generator/native-expr.d.ts +73 -7
- package/dist/generator/native-expr.d.ts.map +1 -1
- package/dist/generator/native-expr.js +121 -39
- package/dist/generator/native-expr.js.map +1 -1
- package/dist/generator/typed.d.ts +165 -0
- package/dist/generator/typed.d.ts.map +1 -1
- package/dist/generator/typed.js +156 -1
- package/dist/generator/typed.js.map +1 -1
- 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).
|
|
335
|
-
//
|
|
336
|
-
//
|
|
337
|
-
//
|
|
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.
|
|
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 `
|
|
474
|
-
// so nothing has to be copied to be
|
|
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
|
|
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 `
|
|
518
|
-
// by field into the typed struct. `mut` only when there is a field to take (an empty record takes
|
|
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
|
-
|
|
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
|
|
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
|
-
|
|
627
|
-
|
|
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
|
|
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
|
-
|
|
638
|
-
|
|
639
|
-
: `${
|
|
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
|
|
642
|
-
// srcExpr — no probe
|
|
643
|
-
|
|
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
|
|
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
|
-
|
|
650
|
-
//
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
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
|
-
|
|
657
|
-
|
|
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
|
|
669
|
-
// An IDENTITY value box (a map<value> — the entries are ALREADY WireValue) needs no per-entry
|
|
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
|
-
|
|
673
|
-
|
|
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
|
|
683
|
-
//
|
|
684
|
-
//
|
|
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()
|
|
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
|
|
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
|
|
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
|
|
819
|
-
* bakes the helper library). Reset at the
|
|
820
|
-
|
|
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
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
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 —
|
|
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) =>
|
|
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.
|
|
@@ -916,8 +1046,23 @@ function makeRustExprBackend(resolveHead, plan, breakLabel) {
|
|
|
916
1046
|
// Safe by construction: the gated child / guarded element only runs when the ref is non-null (the None
|
|
917
1047
|
// arm is statically unreachable in the proven scope). NOT a default — there is no fallback value.
|
|
918
1048
|
narrowUnwrap: (optExpr, _innerRef) => `${optExpr}.unwrap()`,
|
|
1049
|
+
// #275: wrap a present inner value in SOME — the pure `Some(<inner>)` (Rust opt is Option<T>). The write
|
|
1050
|
+
// twin of optNone; no hoisted stmts (Rust needs no address-of temp, unlike Go's `&_optN`).
|
|
1051
|
+
optSome: (innerExpr, _innerTy) => ({ stmts: [], expr: `Some(${innerExpr})` }),
|
|
1052
|
+
// #275: carry an opt<S> (Option<S>) through into opt<value> (Option<WireValue>) via `.map`, boxing the
|
|
1053
|
+
// PRESENT inner with the ONE box SSoT (renderRustWireBox — the SAME call shape as wireBox) and keeping
|
|
1054
|
+
// absent None (absent stays absent — NOT WireValue::Null, which is the required-`value` collapse). `.map`
|
|
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
|
+
},
|
|
919
1063
|
ternary: (cond, t, e, _ty) => `(if ${rustStripOuterParens(cond)} { ${rustStripOuterParens(t)} } else { ${rustStripOuterParens(e)} })`,
|
|
920
1064
|
shortCircuitBool: (op, temp, left, rStmts, rExpr) => {
|
|
1065
|
+
used.boolAlgebra = true; // #304: the author's and/or, in its fallible-right-operand form.
|
|
921
1066
|
// and: let temp = if left { <rStmts> rExpr } else { false }; or: if left { true } else { <rStmts> rExpr }.
|
|
922
1067
|
// build a block that runs rStmts then yields rExpr (parens stripped — block-tail is not a sub-expr).
|
|
923
1068
|
const rblock = `{ ${rStmts.join(" ")} ${rustStripOuterParens(rExpr)} }`;
|
|
@@ -1195,48 +1340,92 @@ ${inits.join("\n")}
|
|
|
1195
1340
|
}
|
|
1196
1341
|
return parts.join("\n\n");
|
|
1197
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
|
+
}
|
|
1198
1347
|
/**
|
|
1199
|
-
*
|
|
1200
|
-
*
|
|
1201
|
-
*
|
|
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.
|
|
1202
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
|
+
}
|
|
1203
1394
|
/**
|
|
1204
|
-
* rustOverElemInfo — the ONE resolver of a fanout/map `over` to its element TypeRef + the
|
|
1205
|
-
*
|
|
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.
|
|
1206
1399
|
*
|
|
1207
|
-
*
|
|
1208
|
-
*
|
|
1209
|
-
* `Option<Vec<E>>`, which the arm binds via `.unwrap_or_default()` (None → empty Vec), byte-equal to
|
|
1210
|
-
* 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.
|
|
1211
1402
|
*/
|
|
1212
1403
|
function rustOverElemInfo(comp, over, typedNodes, plan, nodeId, label) {
|
|
1404
|
+
const s = sanitize(nodeId);
|
|
1213
1405
|
const e = classifyExpr(over);
|
|
1214
1406
|
if (e.kind === "ref" && e.path.length >= 1 && typedNodes.has(e.path[0])) {
|
|
1215
1407
|
const baseRef = typedNodes.get(e.path[0]);
|
|
1216
1408
|
const { ref } = typedFieldAccess(`${typedCell(e.path[0])}.borrow()`, baseRef, e.path.slice(1), plan);
|
|
1217
1409
|
const fieldPath = e.path.slice(1).map((p) => `.${rustFieldName(p)}`).join("");
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
if (ref.kind === "opt" && ref.inner.kind === "arr")
|
|
1222
|
-
return { elemRef: ref.inner.elem,
|
|
1223
|
-
}
|
|
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) };
|
|
1224
1415
|
}
|
|
1225
1416
|
if (e.kind === "ref" && e.path.length === 1) {
|
|
1226
1417
|
const schema = comp.inputPorts?.[e.path[0]];
|
|
1227
1418
|
const et = schema?.elemType;
|
|
1228
1419
|
// #192: read the input array port by its positional PARAM name (= rustFieldName(port), same name
|
|
1229
|
-
// source as the seam) — box removed, no `in_.` prefix
|
|
1230
|
-
if (et !== undefined)
|
|
1231
|
-
|
|
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
|
+
}
|
|
1232
1426
|
}
|
|
1233
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).`);
|
|
1234
1428
|
}
|
|
1235
|
-
/** rustBindOverExpr — the RHS `let over_<s> = …;` expr. An opt-arr over (#177 (A)) unwraps its
|
|
1236
|
-
* `Option<Vec<E>>` to an empty Vec on None so iteration is 0-length (byte-equal to run_behavior). */
|
|
1237
|
-
function rustBindOverExpr(overExpr, optArr) {
|
|
1238
|
-
return optArr ? `${overExpr}.unwrap_or_default()` : overExpr;
|
|
1239
|
-
}
|
|
1240
1429
|
function mapOverElemInfo(comp, node, typedNodes, plan) {
|
|
1241
1430
|
return rustOverElemInfo(comp, node.map.over, typedNodes, plan, node.id, "combined map (#108)");
|
|
1242
1431
|
}
|
|
@@ -1398,7 +1587,7 @@ function coveredMapNode(n, bodyIds, comp) {
|
|
|
1398
1587
|
if (!bodyIds.has(head)) {
|
|
1399
1588
|
// input-array over: covered only when the port declares elemType (#108 — C3, no inference). #177 (A):
|
|
1400
1589
|
// an OPT input array (`{opt:{arr}}`, required:false) IS covered — its null iterates EMPTY
|
|
1401
|
-
// (
|
|
1590
|
+
// (rustOverAccess collapses None to an empty collection), byte-equal to run_behavior.
|
|
1402
1591
|
if (overE.path.length !== 1)
|
|
1403
1592
|
return false;
|
|
1404
1593
|
const schema = comp.inputPorts?.[head];
|
|
@@ -1433,7 +1622,7 @@ function coveredFanoutNode(n, bodyIds, comp) {
|
|
|
1433
1622
|
if (!bodyIds.has(head)) {
|
|
1434
1623
|
// input-array over: covered only when the port declares elemType (C3 — no inference). #177 (A): an OPT
|
|
1435
1624
|
// input array (`{opt:{arr}}`, required:false) IS covered — its null iterates EMPTY
|
|
1436
|
-
// (
|
|
1625
|
+
// (rustOverAccess collapses None to an empty collection), byte-equal to run_behavior.
|
|
1437
1626
|
if (overE.path.length !== 1)
|
|
1438
1627
|
return false;
|
|
1439
1628
|
const schema = comp.inputPorts?.[head];
|
|
@@ -1609,7 +1798,8 @@ function inputPortRustType(schema, plan, where = "input port") {
|
|
|
1609
1798
|
*/
|
|
1610
1799
|
function emitPortWireField(pn, expr, comp, plan, typedNodes, isPrior, expected, opts) {
|
|
1611
1800
|
const c = compilePortNode(expr, comp, plan, typedNodes, isPrior, `port '${pn}'`, expected, opts);
|
|
1612
|
-
const
|
|
1801
|
+
const [srcExpr, srcKind] = rustBoxSrcOf(c);
|
|
1802
|
+
const boxed = renderRustWireBox(buildWirePlan(c.ref, { from: "top" }, { model: "port", field: pn, plan }, "in"), srcExpr, 0, srcKind);
|
|
1613
1803
|
return { stmts: c.stmts, entry: `(Cow::Borrowed(${rustStrLit(pn)}), ${boxed})` };
|
|
1614
1804
|
}
|
|
1615
1805
|
/** rustPortsLabel — the payload-entry block's label for a node, the ONE name its hoists break to. */
|
|
@@ -1653,27 +1843,41 @@ function rustScalar(s) {
|
|
|
1653
1843
|
return s === "string" ? "String" : s === "int" ? "i64" : s === "float" ? "f64" : "bool";
|
|
1654
1844
|
}
|
|
1655
1845
|
/**
|
|
1656
|
-
* movableRefs — the values (a body node's RESULT, or an input port)
|
|
1657
|
-
*
|
|
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.
|
|
1658
1848
|
*
|
|
1659
1849
|
* Handing a prior node's result to a downstream leaf is where a result set would otherwise be deep-copied:
|
|
1660
1850
|
* a `Vec<WireValue>` clone re-allocates every string in every row, once per node boundary. Counting the
|
|
1661
|
-
* 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).
|
|
1662
1855
|
*
|
|
1663
1856
|
* A read is counted from the ONE place a value can be referenced: a `{ref}` / `{refOpt}` path whose head
|
|
1664
1857
|
* names a body node or an input port (ports, guards, map sources, the output value), plus the parent read
|
|
1665
|
-
* a bindField performs.
|
|
1666
|
-
*
|
|
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.
|
|
1667
1868
|
*/
|
|
1668
|
-
function movableRefs(comp) {
|
|
1669
|
-
const
|
|
1670
|
-
const
|
|
1671
|
-
|
|
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);
|
|
1672
1876
|
};
|
|
1673
|
-
const walk = (n, times) => {
|
|
1877
|
+
const walk = (n, site, times) => {
|
|
1674
1878
|
if (Array.isArray(n)) {
|
|
1675
1879
|
for (const e of n)
|
|
1676
|
-
walk(e, times);
|
|
1880
|
+
walk(e, site, times);
|
|
1677
1881
|
return;
|
|
1678
1882
|
}
|
|
1679
1883
|
if (n === null || typeof n !== "object")
|
|
@@ -1683,45 +1887,64 @@ function movableRefs(comp) {
|
|
|
1683
1887
|
if (keys.length === 1 && (keys[0] === "ref" || keys[0] === "refOpt")) {
|
|
1684
1888
|
const path = rec[keys[0]];
|
|
1685
1889
|
if (Array.isArray(path) && typeof path[0] === "string")
|
|
1686
|
-
bump(path[0], times);
|
|
1890
|
+
bump(path[0], site, times);
|
|
1687
1891
|
return;
|
|
1688
1892
|
}
|
|
1689
1893
|
// an element body repeats: everything under a map / fanout is read once per element.
|
|
1690
1894
|
const repeats = times === 1 && ("map" in rec || "fanout" in rec) ? 2 : times;
|
|
1691
1895
|
for (const k of keys)
|
|
1692
|
-
walk(rec[k], repeats);
|
|
1896
|
+
walk(rec[k], site, repeats);
|
|
1693
1897
|
};
|
|
1694
|
-
|
|
1695
|
-
|
|
1696
|
-
|
|
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);
|
|
1697
1903
|
const cr = nd;
|
|
1698
1904
|
if (cr.parent !== undefined && cr.bindField !== undefined)
|
|
1699
|
-
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);
|
|
1700
1925
|
}
|
|
1701
|
-
return
|
|
1926
|
+
return bySite;
|
|
1702
1927
|
}
|
|
1703
1928
|
function emitNativeRawRunner(comp, plan, ap, leaf, declared) {
|
|
1704
1929
|
const ep = execPlan(comp);
|
|
1705
1930
|
const order = ep.order;
|
|
1706
1931
|
const fn = sanitize(comp.name);
|
|
1707
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;
|
|
1708
1937
|
const typedNodes = new Map();
|
|
1709
1938
|
// #125: control-gate は typeless(typedNodes に載せない)。map ノードは produced-array ref に正規化
|
|
1710
1939
|
// (recorder SoT の element outType を {arr:element} へラップ / legacy {arr} はそのまま)。
|
|
1711
1940
|
for (const n of comp.body)
|
|
1712
1941
|
if (!isControlGate(n))
|
|
1713
1942
|
typedNodes.set(n.id, "map" in n ? mapNodeArrRef(n, plan) : deriveTypeRef(n.outType, plan));
|
|
1714
|
-
//
|
|
1715
|
-
//
|
|
1716
|
-
//
|
|
1717
|
-
const
|
|
1718
|
-
|
|
1719
|
-
for (const pn of Object.keys(comp.body[i].ports ?? {})) {
|
|
1720
|
-
const e = classifyExpr(comp.body[i].ports[pn]);
|
|
1721
|
-
if (e.kind === "ref")
|
|
1722
|
-
moveHeads.delete(e.path[0]);
|
|
1723
|
-
}
|
|
1724
|
-
}
|
|
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();
|
|
1725
1948
|
// the ops literal comes from the SHARED derivation (opsLiteralOf): a local "read cr.policy / cr.parent"
|
|
1726
1949
|
// copy silently drops a MAP's / FANOUT's policy and parent (they live under map./fanout.), which would
|
|
1727
1950
|
// make canSkip — and therefore the produced-aware output — disagree with the go surface on the same IR.
|
|
@@ -1759,8 +1982,10 @@ function emitNativeRawRunner(comp, plan, ap, leaf, declared) {
|
|
|
1759
1982
|
const fnKw = isAsync ? "pub async fn" : "pub fn";
|
|
1760
1983
|
// #192: 1:1 map of the authored method — the entry is the exported fn `<method>` (rustFieldName; no
|
|
1761
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.
|
|
1762
1986
|
lines.push(`${fnKw} ${rustFieldName(comp.name)}(`);
|
|
1763
|
-
|
|
1987
|
+
const entryPorts = entryPortOrder(comp, declared);
|
|
1988
|
+
for (const p of entryPorts) {
|
|
1764
1989
|
lines.push(` ${rustFieldName(p)}: ${inputPortRustType(comp.inputPorts[p], plan, `input port '${p}' of component '${comp.name}'`)},`);
|
|
1765
1990
|
}
|
|
1766
1991
|
lines.push(`) -> Result<${outTy}, BehaviorError> {`);
|
|
@@ -1840,7 +2065,7 @@ function emitNativeRawRunner(comp, plan, ap, leaf, declared) {
|
|
|
1840
2065
|
}
|
|
1841
2066
|
}
|
|
1842
2067
|
const narrowed = nodeNarrowedPaths(comp, node);
|
|
1843
|
-
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) })));
|
|
1844
2069
|
// bc#97: derived per-node await — this point-read's future is awaited HERE (its result-consumption
|
|
1845
2070
|
// point) iff THIS node's terminal handler is async. A sync handler in the same async runner is called
|
|
1846
2071
|
// directly (no `.await`). The runner being `async fn` does not force every call site to await.
|
|
@@ -1891,17 +2116,59 @@ function emitNativeRawRunner(comp, plan, ap, leaf, declared) {
|
|
|
1891
2116
|
skippableKind.set(bodyNode.id, rk);
|
|
1892
2117
|
}
|
|
1893
2118
|
}
|
|
1894
|
-
|
|
1895
|
-
|
|
1896
|
-
|
|
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);
|
|
1897
2125
|
// top-level output that is a bare node-result (not an obj/arr assembly): its honest `ref` must equal the
|
|
1898
2126
|
// declared component output type, or the emitted `let __out = …; Ok(__out)` return does not compile.
|
|
1899
|
-
checkOutputFieldType(comp.name, "<output>", outRef, out.ref
|
|
2127
|
+
checkOutputFieldType(comp.name, "<output>", outRef, out.ref);
|
|
1900
2128
|
lines.push(` let __out = ${out.expr};`);
|
|
1901
2129
|
lines.push(` Ok(__out)`);
|
|
1902
2130
|
lines.push(`}`);
|
|
2131
|
+
const allow = runnerClippyAllow(entryPorts.length, rustExprUsed.boolAlgebra);
|
|
2132
|
+
if (allow !== undefined)
|
|
2133
|
+
lines.splice(attrAt, 0, allow);
|
|
1903
2134
|
return lines.join("\n");
|
|
1904
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
|
+
}
|
|
1905
2172
|
/**
|
|
1906
2173
|
* stageAwaits (#231) — the ONE derivation of a real-concurrency stage's dispatch MECHANISM: a std thread
|
|
1907
2174
|
* cannot host `.await`, so a stage dispatches by joining its members' futures iff ANY member awaits, and
|
|
@@ -2171,14 +2438,17 @@ function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes
|
|
|
2171
2438
|
lines.push(` if let Some(e) = perr_${s} { return Err(e); }`);
|
|
2172
2439
|
const takeSlot = stageIsAsync ? `slot_${s}.take()` : `slot_${s}.lock().unwrap().take()`;
|
|
2173
2440
|
lines.push(` let taken_${s} = ${takeSlot};`);
|
|
2174
|
-
|
|
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} {`);
|
|
2175
2447
|
if (meta.policy === "continue") {
|
|
2176
|
-
//
|
|
2177
|
-
//
|
|
2178
|
-
lines.push(`
|
|
2179
|
-
lines.push(`
|
|
2180
|
-
lines.push(` produced_${s}.set(true);`);
|
|
2181
|
-
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);`);
|
|
2182
2452
|
}
|
|
2183
2453
|
else {
|
|
2184
2454
|
const policyLit = rustStrLit(meta.policy === "retry" ? "retry" : "fail");
|
|
@@ -2211,15 +2481,23 @@ function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes
|
|
|
2211
2481
|
* for continue)。失敗した時点でノードの残りを飛ばすため **labeled block** で囲む(`loop { … break }` は
|
|
2212
2482
|
* clippy の `never_loop` に `-D warnings` で殺される)。この形なら de-box 不一致 / 整列違反の
|
|
2213
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.
|
|
2214
2491
|
*/
|
|
2215
2492
|
function rustPolicyArm(s, indent, continuePolicy, body) {
|
|
2216
2493
|
const produced = `${indent}produced_${s}.set(true);`;
|
|
2494
|
+
const scoped = body.map((l) => ` ${l}`.replace(/\n/g, "\n "));
|
|
2217
2495
|
if (!continuePolicy)
|
|
2218
|
-
return [...
|
|
2496
|
+
return [`${indent}{`, ...scoped, `${indent}}`, produced];
|
|
2219
2497
|
return [
|
|
2220
2498
|
`${indent}let mut skipped_${s} = false;`,
|
|
2221
2499
|
`${indent}'node_${s}: {`,
|
|
2222
|
-
...
|
|
2500
|
+
...scoped,
|
|
2223
2501
|
`${indent}}`,
|
|
2224
2502
|
`${indent}if !skipped_${s} {`,
|
|
2225
2503
|
` ${produced}`,
|
|
@@ -2245,8 +2523,9 @@ isAsync = false, policy = "fail") {
|
|
|
2245
2523
|
const s = sanitize(node.id);
|
|
2246
2524
|
const transform = mapTransformExpr(m);
|
|
2247
2525
|
const leafSym = transform === undefined ? resolveLeafSymbol(m.component, leaf, m.leafSymbol) : "";
|
|
2248
|
-
// #108: over element type +
|
|
2249
|
-
const { elemRef: overElemRef,
|
|
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);
|
|
2250
2529
|
const elemMat = mapElemMaterializerName(comp.name, node.id);
|
|
2251
2530
|
const priorHere = (head) => priorNodeAt(head, atPos);
|
|
2252
2531
|
const asName = m.as;
|
|
@@ -2261,18 +2540,14 @@ isAsync = false, policy = "fail") {
|
|
|
2261
2540
|
// #177/#182 keep-with-skip-value: the into value for a guard-skipped element is driven by relationKind,
|
|
2262
2541
|
// NOT by opt-ness (matching run_behavior applyInto, which fills a connection into with the empty
|
|
2263
2542
|
// connection UNCONDITIONALLY on relationKind==="connection"):
|
|
2264
|
-
// - connection into → the connection-zero in the field's typed rep
|
|
2265
|
-
//
|
|
2266
|
-
//
|
|
2267
|
-
// 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).
|
|
2268
2546
|
// - non-connection into → opt → None = null (#177 keep-with-null; unchanged).
|
|
2269
|
-
|
|
2270
|
-
|
|
2271
|
-
|
|
2272
|
-
|
|
2273
|
-
: elemDeBoxRef.kind === "opt"
|
|
2274
|
-
? "None"
|
|
2275
|
-
: `${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);
|
|
2276
2551
|
// the per-element boxed port entries (#183) — the SAME box SSoT as a point node, over the $as element.
|
|
2277
2552
|
const portEntries = (il) => {
|
|
2278
2553
|
const asBinding = { name: asName, ref: overElemRef, plan };
|
|
@@ -2284,11 +2559,16 @@ isAsync = false, policy = "fail") {
|
|
|
2284
2559
|
// the batch payload. NON-batched element: `ep_<s>` is the per-element transport payload WireRow.
|
|
2285
2560
|
// A FALLIBLE element port (#238) builds its entries in a labeled block inside the loop, so the failure
|
|
2286
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`.
|
|
2287
2564
|
const buildElem = (il, wrap) => {
|
|
2288
2565
|
const pe = portEntries(il);
|
|
2289
|
-
return
|
|
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};`];
|
|
2290
2571
|
};
|
|
2291
|
-
const buildBatchElem = (il) => buildElem(il, (e) => `WireValue::Row(WireRow { entries: ${e} })`);
|
|
2292
2572
|
const buildPayloadElem = (il) => buildElem(il, (e) => rustPayloadRow(e));
|
|
2293
2573
|
// #108 guard: compile `when` to a native bool over an element-scoped resolveHead ($as element value,
|
|
2294
2574
|
// prior node, input port). mkGuard returns the compiled {stmts, expr} (or null when unguarded); the
|
|
@@ -2325,26 +2605,27 @@ isAsync = false, policy = "fail") {
|
|
|
2325
2605
|
}
|
|
2326
2606
|
// the node's own statements start here (rustPolicyArm wraps THIS range when the Kind is `continue`).
|
|
2327
2607
|
const bodyStart = lines.length;
|
|
2328
|
-
lines.push(`${indent}
|
|
2608
|
+
lines.push(`${indent}${ov.open}`);
|
|
2329
2609
|
// `built_<s>` は Component 経路の集積ローカル。純式 map は typed cell へ直接積むので出さない
|
|
2330
2610
|
// (生成物は clippy -D warnings を通るので未使用/不要 mut は出せない)。
|
|
2331
2611
|
if (transform === undefined)
|
|
2332
|
-
lines.push(`${indent}let mut built_${s}: Vec<${elemName}> = Vec::with_capacity(
|
|
2612
|
+
lines.push(`${indent}let mut built_${s}: Vec<${elemName}> = Vec::with_capacity(${ov.count});`);
|
|
2333
2613
|
if (transform !== undefined) {
|
|
2334
2614
|
// 純式 map(#222): transport 呼びもワイヤも de-box も無い。要素式を宣言された要素型へ native に
|
|
2335
2615
|
// materialize して積む(port 境界と同一の宣言型 materializer を通す)。`when` は同一の keep-gate。
|
|
2336
|
-
|
|
2616
|
+
const walk = [`${indent}for oel_${s} in over_${s}.iter() {`];
|
|
2337
2617
|
for (const l of emitGuard(indent + " "))
|
|
2338
|
-
|
|
2618
|
+
walk.push(l);
|
|
2339
2619
|
const tc = compilePortNode(transform, comp, plan, typedNodes, priorHere, `map '${node.id}' transform`, elemArrRef.elem, {
|
|
2340
2620
|
asBinding: { name: asName, ref: overElemRef, plan },
|
|
2341
2621
|
asBase: `oel_${s}`,
|
|
2342
2622
|
narrowed: nodeNarrowedPaths(comp, node),
|
|
2343
2623
|
});
|
|
2344
2624
|
for (const st of tc.stmts)
|
|
2345
|
-
|
|
2346
|
-
|
|
2347
|
-
|
|
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));
|
|
2348
2629
|
lines.push(...rustPolicyArm(sanitize(node.id), indent, false, lines.splice(bodyStart)));
|
|
2349
2630
|
for (const c of closers)
|
|
2350
2631
|
lines.push(c);
|
|
@@ -2357,21 +2638,22 @@ isAsync = false, policy = "fail") {
|
|
|
2357
2638
|
// zips its next deboxed row, a skipped element gets into=None. Byte-equal to run_behavior: batched
|
|
2358
2639
|
// keptIdx-aligned collect + applyInto (skipped element unaugmented → opt-into null).
|
|
2359
2640
|
const g = mkGuard();
|
|
2360
|
-
lines.push(`${indent}let mut items_${s}: Vec<WireValue> = Vec::with_capacity(
|
|
2361
|
-
lines.push(`${indent}let mut keep_${s}: Vec<bool> = Vec::with_capacity(
|
|
2362
|
-
|
|
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() {`];
|
|
2363
2644
|
for (const st of g.stmts)
|
|
2364
|
-
|
|
2365
|
-
|
|
2366
|
-
|
|
2645
|
+
pass1.push(`${indent} ${st}`);
|
|
2646
|
+
pass1.push(`${indent} let __keep = ${rustStripOuterParens(g.expr)};`);
|
|
2647
|
+
pass1.push(`${indent} if __keep {`);
|
|
2367
2648
|
for (const l of buildBatchElem(indent + " "))
|
|
2368
|
-
|
|
2369
|
-
|
|
2370
|
-
|
|
2371
|
-
|
|
2372
|
-
|
|
2373
|
-
|
|
2374
|
-
|
|
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));
|
|
2375
2657
|
lines.push(`${indent}let mut decs_${s}: Vec<${renderTypeRef(elemDeBoxRef)}> = Vec::with_capacity(items_${s}.len());`);
|
|
2376
2658
|
lines.push(`${indent}if !items_${s}.is_empty() {`);
|
|
2377
2659
|
lines.push(`${indent} let want_${s} = items_${s}.len();`);
|
|
@@ -2393,29 +2675,31 @@ isAsync = false, policy = "fail") {
|
|
|
2393
2675
|
lines.push(`${indent} }`);
|
|
2394
2676
|
lines.push(`${indent}}`);
|
|
2395
2677
|
lines.push(`${indent}let mut decs_iter_${s} = decs_${s}.into_iter();`);
|
|
2396
|
-
|
|
2397
|
-
|
|
2398
|
-
|
|
2399
|
-
|
|
2400
|
-
|
|
2401
|
-
|
|
2402
|
-
|
|
2403
|
-
|
|
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));
|
|
2404
2687
|
}
|
|
2405
2688
|
else if (batched) {
|
|
2406
2689
|
// build kept-element ports (+ kept over elements for into). Batched into is never guarded (rejected).
|
|
2407
|
-
lines.push(`${indent}let mut items_${s}: Vec<WireValue> = Vec::with_capacity(
|
|
2690
|
+
lines.push(`${indent}let mut items_${s}: Vec<WireValue> = Vec::with_capacity(${ov.count});`);
|
|
2408
2691
|
if (hasInto)
|
|
2409
|
-
lines.push(`${indent}let mut kept_${s}: Vec<${renderTypeRef(overElemRef)}> = Vec::with_capacity(
|
|
2410
|
-
|
|
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() {`];
|
|
2411
2694
|
for (const l of emitGuard(indent + " "))
|
|
2412
|
-
|
|
2695
|
+
build.push(l);
|
|
2413
2696
|
for (const l of buildBatchElem(indent + " "))
|
|
2414
|
-
|
|
2415
|
-
|
|
2697
|
+
build.push(l);
|
|
2698
|
+
build.push(`${indent} items_${s}.push(ep_${s});`);
|
|
2416
2699
|
if (hasInto)
|
|
2417
|
-
|
|
2418
|
-
|
|
2700
|
+
build.push(`${indent} kept_${s}.push(oel_${s}.clone());`);
|
|
2701
|
+
build.push(`${indent}}`);
|
|
2702
|
+
lines.push(...ov.hold(indent, build));
|
|
2419
2703
|
lines.push(`${indent}if !items_${s}.is_empty() {`);
|
|
2420
2704
|
lines.push(`${indent} let want_${s} = items_${s}.len();`);
|
|
2421
2705
|
// ONE op-agnostic transport call: batch payload WireRow {items:[…]}; result WireList → aligned wires.
|
|
@@ -2449,40 +2733,40 @@ isAsync = false, policy = "fail") {
|
|
|
2449
2733
|
lines.push(`${indent}}`);
|
|
2450
2734
|
}
|
|
2451
2735
|
else {
|
|
2452
|
-
// #93 shape 2 / #108: NON-batched map — dispatch ONCE PER KEPT ELEMENT.
|
|
2453
|
-
|
|
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 = [];
|
|
2454
2742
|
// #177/#182 keep-with-skip-value: a guard-skipped element is KEPT with into=intoSkipDefault (None /
|
|
2455
2743
|
// Conn::default()) instead of dropped — byte-equal to run_behavior's applyInto (opt-into → null /
|
|
2456
2744
|
// connection-into → empty connection).
|
|
2457
2745
|
const nonBatchedSkip = keepWithNull ? `built_${s}.push(${elemMat}(oel_${s}, ${intoSkipDefault})); continue;` : "continue;";
|
|
2458
|
-
|
|
2459
|
-
|
|
2460
|
-
for (const l of buildPayloadElem(indent + " "))
|
|
2461
|
-
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 }));
|
|
2462
2748
|
// Element Error Policy (scp-error.md): `skip` drops the failing element and proceeds (order is
|
|
2463
2749
|
// preserved; the leaf keeps the Error Value it produced). `error` (default) promotes the element
|
|
2464
2750
|
// Failure to the map's Component Failure. ONE op-agnostic transport call per element, ONE WireRow payload.
|
|
2465
|
-
|
|
2466
|
-
|
|
2751
|
+
body.push(`${il}let er_${s} = match ${leafSym}(ep_${s})${awaitSfx} {`);
|
|
2752
|
+
body.push(`${il} Ok(r) => r,`);
|
|
2467
2753
|
if (m.elementPolicy === "skip") {
|
|
2468
|
-
|
|
2754
|
+
body.push(`${il} Err(_) => continue,`);
|
|
2469
2755
|
}
|
|
2470
2756
|
else {
|
|
2471
|
-
|
|
2472
|
-
? `${
|
|
2473
|
-
: `${
|
|
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)),`);
|
|
2474
2760
|
}
|
|
2475
|
-
|
|
2761
|
+
body.push(`${il}};`);
|
|
2476
2762
|
// the element's wire is de-boxed strictly INLINE (fail-closed regardless of elementPolicy).
|
|
2477
|
-
|
|
2478
|
-
|
|
2479
|
-
|
|
2480
|
-
|
|
2481
|
-
else
|
|
2482
|
-
|
|
2483
|
-
|
|
2484
|
-
}
|
|
2485
|
-
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));
|
|
2486
2770
|
}
|
|
2487
2771
|
lines.push(`${indent}*${typedCell(node.id)}.borrow_mut() = built_${s};`);
|
|
2488
2772
|
lines.push(...rustPolicyArm(sanitize(node.id), indent, contPolicy, lines.splice(bodyStart)));
|
|
@@ -2508,7 +2792,8 @@ function emitFanoutArm(comp, node, atPos, typedNodes, plan, priorNodeAt, leaf, i
|
|
|
2508
2792
|
const connRef = typedNodes.get(node.id);
|
|
2509
2793
|
const elemRef = fanoutItemsElemRef(node, connRef, plan);
|
|
2510
2794
|
const elemName = renderTypeRef(elemRef);
|
|
2511
|
-
const { elemRef: overElemRef,
|
|
2795
|
+
const { elemRef: overElemRef, over } = fanoutOverElemInfo(comp, node, typedNodes, plan);
|
|
2796
|
+
const ov = over(isAsync);
|
|
2512
2797
|
const asName = f.as;
|
|
2513
2798
|
const priorHere = (head) => priorNodeAt(head, atPos);
|
|
2514
2799
|
const portNames = Object.keys(f.ports);
|
|
@@ -2538,14 +2823,15 @@ function emitFanoutArm(comp, node, atPos, typedNodes, plan, priorNodeAt, leaf, i
|
|
|
2538
2823
|
}
|
|
2539
2824
|
// the node's own statements start here (rustPolicyArm wraps THIS range when the Kind is `continue`).
|
|
2540
2825
|
const bodyStart = lines.length;
|
|
2541
|
-
lines.push(`${indent}
|
|
2826
|
+
lines.push(`${indent}${ov.open}`);
|
|
2542
2827
|
lines.push(`${indent}let mut built_${s}: Vec<${elemName}> = Vec::new();`);
|
|
2543
|
-
lines.push(`${indent}let mut pi_${s}: Vec<WireValue> = Vec::with_capacity(
|
|
2544
|
-
|
|
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() {`];
|
|
2545
2830
|
for (const l of buildPorts(indent + " "))
|
|
2546
|
-
|
|
2547
|
-
|
|
2548
|
-
|
|
2831
|
+
build.push(l);
|
|
2832
|
+
build.push(`${indent} pi_${s}.push(ep_${s});`);
|
|
2833
|
+
build.push(`${indent}}`);
|
|
2834
|
+
lines.push(...ov.hold(indent, build));
|
|
2549
2835
|
lines.push(`${indent}if !pi_${s}.is_empty() {`);
|
|
2550
2836
|
lines.push(`${indent} let want_${s} = pi_${s}.len();`);
|
|
2551
2837
|
// ONE op-agnostic transport call: batch payload WireRow {items:[…]}; result is a WireList of the aligned
|
|
@@ -2650,65 +2936,45 @@ function emitCondArm(comp, node, atPos, typedNodes, plan, priorNodeAt) {
|
|
|
2650
2936
|
return lines.join("\n");
|
|
2651
2937
|
}
|
|
2652
2938
|
/**
|
|
2653
|
-
*
|
|
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).
|
|
2654
2942
|
*/
|
|
2655
|
-
|
|
2656
|
-
|
|
2657
|
-
|
|
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;
|
|
2658
2958
|
const head = e.path[0];
|
|
2659
|
-
const
|
|
2660
|
-
|
|
2661
|
-
|
|
2662
|
-
|
|
2663
|
-
|
|
2664
|
-
|
|
2665
|
-
|
|
2666
|
-
|
|
2667
|
-
|
|
2668
|
-
|
|
2669
|
-
|
|
2670
|
-
|
|
2671
|
-
|
|
2672
|
-
|
|
2673
|
-
|
|
2674
|
-
|
|
2675
|
-
|
|
2676
|
-
|
|
2677
|
-
|
|
2678
|
-
return {
|
|
2679
|
-
expr: `if produced_${sanitize(head)}.get() { ${producedExpr} } else { ${unproduced} }`,
|
|
2680
|
-
ref: expected ?? ref,
|
|
2681
|
-
};
|
|
2682
|
-
}
|
|
2683
|
-
// Non-skippable node-result: its `ref` is returned honestly (not laundered), so the placing site — the
|
|
2684
|
-
// obj-field assembly below, or the top-level call — runs checkOutputFieldType against the field type.
|
|
2685
|
-
return rustCellPathRead(head, baseRef, e.path.slice(1), plan, moveHeads);
|
|
2686
|
-
}
|
|
2687
|
-
if (node !== null && typeof node === "object" && !Array.isArray(node)) {
|
|
2688
|
-
const keys = Object.keys(node);
|
|
2689
|
-
if (keys.length === 1 && keys[0] === "obj" && expected && expected.kind === "named") {
|
|
2690
|
-
const decl = findDecl(plan, expected.name);
|
|
2691
|
-
const fields = node.obj;
|
|
2692
|
-
const inits = decl.fields.map((f) => {
|
|
2693
|
-
const childPath = fieldPath === "" ? f.name : `${fieldPath}.${f.name}`;
|
|
2694
|
-
const sub = emitProducedAwareValue(fields[f.name], f.type, typedNodes, plan, skippable, skippableKind, compName, childPath, moveHeads);
|
|
2695
|
-
// Non-skippable field: sub.ref is the honest value type → catches a Vec-depth mismatch here. A
|
|
2696
|
-
// skippable field launders sub.ref to expected, but its own produced-arm check (above) already fired.
|
|
2697
|
-
checkOutputFieldType(compName, childPath, f.type, sub.ref, plan);
|
|
2698
|
-
return `${rustFieldName(f.name)}: ${sub.expr}`;
|
|
2699
|
-
});
|
|
2700
|
-
return { expr: `${expected.name} { ${inits.join(", ")} }`, ref: expected };
|
|
2701
|
-
}
|
|
2702
|
-
}
|
|
2703
|
-
return emitTypedValue(node, expected, typedNodes, plan, compName, fieldPath, moveHeads);
|
|
2704
|
-
}
|
|
2705
|
-
function valueLeafProduced(expr, ref, expected) {
|
|
2706
|
-
if (expected && expected.kind === "opt") {
|
|
2707
|
-
if (ref.kind === "opt")
|
|
2708
|
-
return expr;
|
|
2709
|
-
return `Some(${expr})`;
|
|
2710
|
-
}
|
|
2711
|
-
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
|
+
};
|
|
2712
2978
|
}
|
|
2713
2979
|
// bc#90 / runtime-free: the old `valueLeafInner` (which serialized a bindField to a boxed `Value` for the
|
|
2714
2980
|
// binding check) is REMOVED — the bound value is now a typed `Option<K>` built by direct field access
|
|
@@ -2917,12 +3183,19 @@ ${withRustfmtSkip(emitStructSurface([]))}
|
|
|
2917
3183
|
// - Everything fixed at generation time (SQL text, port names, field names) rides as \`&'static str\`
|
|
2918
3184
|
// behind \`Cow::Borrowed\`, so building a payload allocates nothing for it, however often it is called.
|
|
2919
3185
|
// - De-boxing CONSUMES the transport's wire: every string, row and list is MOVED into the typed value,
|
|
2920
|
-
// and a result
|
|
2921
|
-
//
|
|
2922
|
-
//
|
|
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.
|
|
2923
3195
|
// The codegen purity gate fails the build on exactly those spellings (a wire classifier that borrows, a
|
|
2924
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
|
|
2925
|
-
// copy) and the cost is confirmed by benchmark, not by this
|
|
3197
|
+
// copy, an over collection copied out of its place) and the cost is confirmed by benchmark, not by this
|
|
3198
|
+
// comment.
|
|
2926
3199
|
use std::borrow::Cow;
|
|
2927
3200
|
use std::cell::RefCell;`;
|
|
2928
3201
|
const sections = [
|