behavior-contracts 0.9.3 → 0.10.0
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 +116 -24
- package/dist/authoring.d.ts +18 -1
- package/dist/authoring.d.ts.map +1 -1
- package/dist/authoring.js +11 -0
- package/dist/authoring.js.map +1 -1
- package/dist/behavior.d.ts +23 -0
- package/dist/behavior.d.ts.map +1 -1
- package/dist/behavior.js.map +1 -1
- package/dist/bind.d.ts +1 -1
- package/dist/bind.d.ts.map +1 -1
- package/dist/builder.d.ts.map +1 -1
- package/dist/builder.js +21 -6
- package/dist/builder.js.map +1 -1
- package/dist/cli.js +65 -40
- package/dist/cli.js.map +1 -1
- package/dist/commands/codegen.d.ts +18 -12
- package/dist/commands/codegen.d.ts.map +1 -1
- package/dist/commands/codegen.js +111 -27
- package/dist/commands/codegen.js.map +1 -1
- package/dist/commands/ts-extract.d.ts +26 -0
- package/dist/commands/ts-extract.d.ts.map +1 -0
- package/dist/commands/ts-extract.js +265 -0
- package/dist/commands/ts-extract.js.map +1 -0
- package/dist/generated/commands.d.ts.map +1 -1
- package/dist/generated/commands.js +8 -0
- package/dist/generated/commands.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/generated/program.d.ts +4 -0
- package/dist/generated/program.d.ts.map +1 -1
- package/dist/generated/program.js +7 -3
- package/dist/generated/program.js.map +1 -1
- package/dist/generated/types.d.ts +6 -2
- package/dist/generated/types.d.ts.map +1 -1
- package/dist/generator/emit-typed-native-go.d.ts +5 -7
- package/dist/generator/emit-typed-native-go.d.ts.map +1 -1
- package/dist/generator/emit-typed-native-go.js +244 -404
- package/dist/generator/emit-typed-native-go.js.map +1 -1
- package/dist/generator/emit-typed-native-rust.d.ts +6 -8
- package/dist/generator/emit-typed-native-rust.d.ts.map +1 -1
- package/dist/generator/emit-typed-native-rust.js +234 -371
- package/dist/generator/emit-typed-native-rust.js.map +1 -1
- package/dist/guard.d.ts +23 -0
- package/dist/guard.d.ts.map +1 -1
- package/dist/guard.js +52 -0
- package/dist/guard.js.map +1 -1
- package/dist/index.d.ts +3 -32
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +10 -5
- package/dist/index.js.map +1 -1
- package/dist/ir-handle.d.ts +30 -0
- package/dist/ir-handle.d.ts.map +1 -0
- package/dist/ir-handle.js +2 -0
- package/dist/ir-handle.js.map +1 -0
- package/dist/provenance.d.ts +1 -1
- package/dist/provenance.d.ts.map +1 -1
- package/package.json +9 -1
|
@@ -174,16 +174,9 @@ fn de_overflow(model: &str, field: &str, expected: &str, actual_wire: String, ra
|
|
|
174
174
|
function emitBehaviorErrorType() {
|
|
175
175
|
return `${emitErrorTypeDefs()}\n\n${emitErrorHelpers()}`;
|
|
176
176
|
}
|
|
177
|
-
function portFieldName(wire) {
|
|
178
|
-
const safe = wire.replace(/[^A-Za-z0-9_]/g, "_").toLowerCase();
|
|
179
|
-
return `f_${safe}`;
|
|
180
|
-
}
|
|
181
177
|
function pascal(s) {
|
|
182
178
|
return s.replace(/[^A-Za-z0-9]+/g, " ").split(" ").filter(Boolean).map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join("") || "X";
|
|
183
179
|
}
|
|
184
|
-
function portsStructName(compName, nodeId) {
|
|
185
|
-
return `PortsNR${pascal(compName)}${pascal(nodeId)}`;
|
|
186
|
-
}
|
|
187
180
|
/**
|
|
188
181
|
* resolveLeafSymbol — the op-agnostic transport symbol a covered leaf (= catalog component) is called
|
|
189
182
|
* through at its execution point. A consumer-supplied override (`leafTransport.symbols[component]`) wins;
|
|
@@ -191,32 +184,32 @@ function portsStructName(compName, nodeId) {
|
|
|
191
184
|
* resolution lives (SSoT) — the runner call sites, the import block, and the test observe transport fns
|
|
192
185
|
* all read it. There is no per-node handler indirection: the leaf is one transport, not one method per node.
|
|
193
186
|
*/
|
|
194
|
-
function resolveLeafSymbol(component, leaf) {
|
|
195
|
-
|
|
187
|
+
function resolveLeafSymbol(component, leaf, specSymbol) {
|
|
188
|
+
// #176 resolution order: the SPEC-fixed `node.leafSymbol` (defineLeaf meta.transport) FIRST, then the CLI
|
|
189
|
+
// `--leaf-transport` override, then the default `leaf_<comp>`.
|
|
190
|
+
return specSymbol ?? leaf?.symbols[component] ?? `leaf_${sanitize(component)}`;
|
|
196
191
|
}
|
|
197
192
|
/**
|
|
198
|
-
*
|
|
199
|
-
*
|
|
200
|
-
*
|
|
201
|
-
*
|
|
202
|
-
* from the SAME `compilePortNode` lowering `emitPortsStruct` uses, so the spread can never disagree with
|
|
203
|
-
* the field types the ports struct declares.
|
|
193
|
+
* rustPayloadRow — assemble the op-agnostic transport payload `WireRow` from the node's boxed port entries
|
|
194
|
+
* (#183). The ONE place a rust transport payload is wrapped: every call site (point / map-element /
|
|
195
|
+
* fanout-element / batched item) builds its entries via {@link emitPortWireField} and wraps them here.
|
|
196
|
+
* `WireRow.entries` is a public field (the shared crate exports it), so cross-crate construction is direct.
|
|
204
197
|
*/
|
|
205
|
-
function
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
});
|
|
198
|
+
function rustPayloadRow(entries) {
|
|
199
|
+
return `WireRow { entries: vec![${entries.join(", ")}] }`;
|
|
200
|
+
}
|
|
201
|
+
/**
|
|
202
|
+
* rustPayloadBatch — the BATCHED/fanout payload: ONE WireRow `{items:[<per-element ports rows>…]}` over an
|
|
203
|
+
* already-built `Vec<WireValue>` of per-element WireRows (#183). Byte-equal to run_behavior's batched
|
|
204
|
+
* handler contract; the aligned result is a `WireValue::List` the runner reads via its `.items`.
|
|
205
|
+
*/
|
|
206
|
+
function rustPayloadBatch(itemsExpr) {
|
|
207
|
+
return `WireRow { entries: vec![("items".to_string(), WireValue::List(WireList { items: ${itemsExpr} }))] }`;
|
|
216
208
|
}
|
|
217
|
-
/**
|
|
218
|
-
|
|
219
|
-
|
|
209
|
+
/** rustListItems — extract the aligned per-element wires (a `Vec<WireValue>`) from a batched/fanout transport
|
|
210
|
+
* result (a `WireValue::List`); a non-list result yields an empty Vec → caught by the alignment length check. */
|
|
211
|
+
function rustListItems(wvExpr) {
|
|
212
|
+
return `match ${wvExpr} { WireValue::List(l) => l.items, _ => Vec::new() }`;
|
|
220
213
|
}
|
|
221
214
|
/** InNR<Comp> — the concrete per-component input struct name (fields = inputPorts). */
|
|
222
215
|
function inStructName(compName) {
|
|
@@ -559,37 +552,59 @@ ${I}}`;
|
|
|
559
552
|
* - `record` box each declared field recursively, assemble `WireValue::Row(WireRow{ entries })` — the typed
|
|
560
553
|
* `obj<…>` → wire map ("M") crossing (the real op-agnostic `arr<value>` batch-write param fed a
|
|
561
554
|
* typed `arr<obj>`);
|
|
562
|
-
* - `list` box each element recursively into `WireValue::List(WireList{ items })` ("L")
|
|
563
|
-
*
|
|
564
|
-
*
|
|
565
|
-
*
|
|
555
|
+
* - `list` box each element recursively into `WireValue::List(WireList{ items })` ("L");
|
|
556
|
+
* - `map` (bc#181) box each entry's VALUE into a dynamic-keyed WireRow (BTreeMap order — no WireMap type);
|
|
557
|
+
* - `opt` (bc#185) TOTAL: None ⇒ `WireValue::Null`; present ⇒ unwrap all `Some` layers to the owned base
|
|
558
|
+
* and box it through the SAME per-kind walk (`boxBase`) — byte-equal to run_behavior's `Value`
|
|
559
|
+
* pass-through (null stays null), the write-side mirror of the read de-box's opt (`wrapSome`).
|
|
560
|
+
* `depth` names the per-element closure binding uniquely across nesting.
|
|
566
561
|
*/
|
|
562
|
+
/** rustScalarWireCtor — the WireValue constructor for a portable scalar (the ONE mapping; used both as
|
|
563
|
+
* `Ctor(x)` and, point-free, as a `.map(Ctor)` argument in the clippy-clean list box). */
|
|
564
|
+
function rustScalarWireCtor(scalar) {
|
|
565
|
+
switch (scalar) {
|
|
566
|
+
case "string":
|
|
567
|
+
return "WireValue::Str";
|
|
568
|
+
case "int":
|
|
569
|
+
return "WireValue::int";
|
|
570
|
+
case "float":
|
|
571
|
+
return "WireValue::float";
|
|
572
|
+
case "bool":
|
|
573
|
+
return "WireValue::Bool";
|
|
574
|
+
default:
|
|
575
|
+
throw new GeneratorFailure("UNSUPPORTED_NODE_STRAIGHTLINE", `rust wire box: a bare 'null' scalar has no wire constructor`);
|
|
576
|
+
}
|
|
577
|
+
}
|
|
567
578
|
function renderRustWireBox(plan, srcExpr, depth = 0) {
|
|
568
|
-
|
|
579
|
+
// boxBase — box a BASE-typed (non-opt) owned expr per the plan's kind. Both the required (optDepth 0) path
|
|
580
|
+
// and the opt arm (after its None/Some unwrap) fold through this ONE walk, so the opt element reuses the SAME
|
|
581
|
+
// per-kind box (no parallel path). The union is exhausted below; the trailing throw is a bare exhaustiveness
|
|
582
|
+
// guard, never a silent hole.
|
|
583
|
+
const boxBase = (baseSrc) => {
|
|
569
584
|
if (plan.k === "value")
|
|
570
|
-
return
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
case "int":
|
|
576
|
-
return `WireValue::int(${srcExpr})`;
|
|
577
|
-
case "float":
|
|
578
|
-
return `WireValue::float(${srcExpr})`;
|
|
579
|
-
case "bool":
|
|
580
|
-
return `WireValue::Bool(${srcExpr})`;
|
|
581
|
-
}
|
|
582
|
-
}
|
|
585
|
+
return baseSrc; // identity — already the opaque BC wire.
|
|
586
|
+
// strip the source's OWN outer parens before wrapping in the ctor — `WireValue::Str(("a"+x))` is
|
|
587
|
+
// `clippy::double_parens`; `WireValue::Str("a"+x)` is clean (the ctor call already parenthesizes).
|
|
588
|
+
if (plan.k === "scalar")
|
|
589
|
+
return `${rustScalarWireCtor(plan.scalar)}(${rustStripOuterParens(baseSrc)})`;
|
|
583
590
|
if (plan.k === "record") {
|
|
584
591
|
// typed struct → wire map: box each declared field off its native struct field (moving it out of the owned
|
|
585
592
|
// srcExpr — no probe), assemble a WireRow of (name, WireValue) in declared-field order.
|
|
586
|
-
const entries = plan.fields.map((f) => `(${rustStrLit(f.name)}.to_string(), ${renderRustWireBox(f.plan, `${
|
|
593
|
+
const entries = plan.fields.map((f) => `(${rustStrLit(f.name)}.to_string(), ${renderRustWireBox(f.plan, `${baseSrc}.${rustFieldName(f.name)}`, depth + 1)})`);
|
|
587
594
|
return `WireValue::Row(WireRow { entries: vec![${entries.join(", ")}] })`;
|
|
588
595
|
}
|
|
589
596
|
if (plan.k === "list") {
|
|
590
597
|
// typed Vec → wire list: consume the owned Vec, box each element recursively (box-once, no round-trip).
|
|
591
598
|
const e = `e${depth}`;
|
|
592
|
-
|
|
599
|
+
const elemBox = renderRustWireBox(plan.elem, e, depth + 1);
|
|
600
|
+
// clippy-clean: an IDENTITY element box (a `value` list — already a Vec<WireValue>) skips the map
|
|
601
|
+
// (`.map(|e| e)` is `clippy::map_identity`); a bare scalar CONSTRUCTOR box goes point-free
|
|
602
|
+
// (`.map(WireValue::Str)` not `.map(|e| WireValue::Str(e))` — `clippy::redundant_closure`).
|
|
603
|
+
if (elemBox === e)
|
|
604
|
+
return `WireValue::List(WireList { items: ${baseSrc} })`;
|
|
605
|
+
const scalarCtor = plan.elem.optDepth === 0 && plan.elem.k === "scalar" ? rustScalarWireCtor(plan.elem.scalar) : undefined;
|
|
606
|
+
const mapper = scalarCtor !== undefined ? scalarCtor : `|${e}| ${elemBox}`;
|
|
607
|
+
return `WireValue::List(WireList { items: ${baseSrc}.into_iter().map(${mapper}).collect() })`;
|
|
593
608
|
}
|
|
594
609
|
if (plan.k === "map") {
|
|
595
610
|
// bc#181: typed map<V> → wire map, represented as a dynamic-keyed WireRow (there is NO WireMap type; a
|
|
@@ -599,10 +614,22 @@ function renderRustWireBox(plan, srcExpr, depth = 0) {
|
|
|
599
614
|
// deterministic (matching the rust typed map's canonical key order).
|
|
600
615
|
const k = `k${depth}`;
|
|
601
616
|
const v = `v${depth}`;
|
|
602
|
-
return `WireValue::Row(WireRow { entries: ${
|
|
617
|
+
return `WireValue::Row(WireRow { entries: ${baseSrc}.into_iter().map(|(${k}, ${v})| (${k}, ${renderRustWireBox(plan.value, v, depth + 1)})).collect() })`;
|
|
603
618
|
}
|
|
604
|
-
|
|
605
|
-
|
|
619
|
+
throw new GeneratorFailure("UNSUPPORTED_NODE_STRAIGHTLINE", `rust wire box: unexpected plan kind '${plan.k}'`);
|
|
620
|
+
};
|
|
621
|
+
if (plan.optDepth > 0) {
|
|
622
|
+
// bc#185: typed opt<T> → wire, TOTAL. `srcExpr` is an `Option<…Option<Base>>` (optDepth `Some` wraps — the
|
|
623
|
+
// mirror of the read-side de-box `wrapSome`). Presence is SINGLE-BIT on the wire and run_behavior passes the
|
|
624
|
+
// `Value` THROUGH (null stays null), so: None ⇒ WireValue::Null (byte-equal to value_to_wire(Value::Null));
|
|
625
|
+
// present ⇒ unwrap ALL optDepth `Some` layers to the owned base value and box it through the SAME per-kind
|
|
626
|
+
// walk (box-once, no decode→re-box). A present nested opt is a fully-`Some` chain (the read side never builds
|
|
627
|
+
// a partially-None present), so the `_ => Null` arm only ever fires for a genuine absent.
|
|
628
|
+
const ov = `ov${depth}`;
|
|
629
|
+
const pat = "Some(".repeat(plan.optDepth) + ov + ")".repeat(plan.optDepth);
|
|
630
|
+
return `match ${srcExpr} { ${pat} => ${boxBase(ov)}, _ => WireValue::Null }`;
|
|
631
|
+
}
|
|
632
|
+
return boxBase(srcExpr);
|
|
606
633
|
}
|
|
607
634
|
/** returnErrFail — the default de-box mismatch control flow: propagate the structured Error Value out of
|
|
608
635
|
* the enclosing runner (fail/retry componentRef results + map/fanout element de-box, which fails closed
|
|
@@ -709,81 +736,6 @@ function portFieldRustType(node, comp, plan, typedNodes, expected, where = "port
|
|
|
709
736
|
const c = compilePortNode(node, comp, plan, typedNodes, (h) => typedNodes.has(h), where, expected, opts);
|
|
710
737
|
return renderTypeRef(c.ref);
|
|
711
738
|
}
|
|
712
|
-
/**
|
|
713
|
-
* emitPortsStruct — the CONCRETE native ports struct for a componentRef node. Typed fields per the
|
|
714
|
-
* static port type, constructed directly. NO `impl PortReaderT` / by-name `port()` — the covered runner
|
|
715
|
-
* passes `&PortsNR…` to the concrete `node_*` method by direct generic instantiation, and the handler
|
|
716
|
-
* reads `ports.f_<field>` DIRECTLY. The struct derives Clone (a bc#87 parallel stage clones it into the
|
|
717
|
-
* per-worker dispatch). Every field is a NATIVE Rust type (bc#90 / runtime-free) — NO boxed `Value`.
|
|
718
|
-
*/
|
|
719
|
-
function emitPortsStruct(comp, node, asBinding, plan, typedNodes, narrowed) {
|
|
720
|
-
const name = portsStructName(comp.name, node.id);
|
|
721
|
-
const portNames = Object.keys(node.ports);
|
|
722
|
-
if (portNames.length === 0) {
|
|
723
|
-
return `// ${name} — native ports for node '${node.id}' (${node.component}); no ports.\n#[derive(Clone)]\npub struct ${name};`;
|
|
724
|
-
}
|
|
725
|
-
// a node WITH ports always resolves through the one port lowering, which needs the type plan + the
|
|
726
|
-
// prior-node map (both are supplied by every caller — narrow the optional params for the fields below).
|
|
727
|
-
if (plan === undefined || typedNodes === undefined) {
|
|
728
|
-
throw new GeneratorFailure("UNSUPPORTED_NODE_STRAIGHTLINE", `rust typed-native: ports struct for node '${node.id}' needs a type plan + prior-node map`);
|
|
729
|
-
}
|
|
730
|
-
// #170: the field TYPE reads the SAME lowering (incl. gate/guard narrowing) the init does, so a narrowed
|
|
731
|
-
// opt-in-required port is a non-opt field AND a non-opt initializer — they can never disagree.
|
|
732
|
-
// #173: the field TYPE is the DECLARED port type (portSchemas → inputPortTypeRef), materialized by the
|
|
733
|
-
// SAME compilePortTo the init uses — field and init read one lowering, so they cannot diverge.
|
|
734
|
-
const portOpts = asBinding !== undefined ? { asBinding, asBase: asBinding.name, narrowed } : narrowed !== undefined ? { narrowed } : undefined;
|
|
735
|
-
const types = portNames.map((p) => portFieldRustType(node.ports[p], comp, plan, typedNodes, inputPortTypeRef(node.portSchemas?.[p], plan), `port '${p}' of node '${node.id}'`, portOpts));
|
|
736
|
-
const fields = portNames
|
|
737
|
-
.map((p, i) => ` pub ${portFieldName(p)}: ${types[i]}, // ${JSON.stringify(p)}`)
|
|
738
|
-
.join("\n");
|
|
739
|
-
return `// ${name} — CONCRETE native ports for node '${node.id}' (${node.component}). Typed fields per the
|
|
740
|
-
// static port type; constructed directly (no Vec, no heap key strings, no per-port Value boxing). The
|
|
741
|
-
// handler reads the typed fields directly off this concrete struct — no by-name accessor.
|
|
742
|
-
#[derive(Clone)]
|
|
743
|
-
pub struct ${name} {
|
|
744
|
-
${fields}
|
|
745
|
-
}`;
|
|
746
|
-
}
|
|
747
|
-
/**
|
|
748
|
-
* emitMapPortsStructs — element ports struct + batch struct for a covered map node (CONCRETE). The batch
|
|
749
|
-
* struct carries the Vec of per-element CONCRETE ports structs (the handler reads them off the concrete
|
|
750
|
-
* struct — no by-name accessor, no key-value object).
|
|
751
|
-
*/
|
|
752
|
-
function emitMapPortsStructs(comp, node, typedNodes, plan) {
|
|
753
|
-
const m = node.map;
|
|
754
|
-
const name = portsStructName(comp.name, node.id);
|
|
755
|
-
const batch = `${name}Batch`;
|
|
756
|
-
// #108: element ports may read the `$as` binding — resolve the over element type for native typing.
|
|
757
|
-
const { elemRef } = mapOverElemInfo(comp, node, typedNodes, plan);
|
|
758
|
-
const asBinding = { name: m.as, ref: elemRef, plan };
|
|
759
|
-
// #170: a guarded map (`when(ne($e.key,null))`) proves the element key non-null in kept elements — narrow it.
|
|
760
|
-
const elemStruct = emitPortsStruct(comp, { id: node.id, component: m.component, ports: m.ports, portSchemas: m.portSchemas }, asBinding, plan, typedNodes, nodeNarrowedPaths(comp, node));
|
|
761
|
-
return `${elemStruct}
|
|
762
|
-
|
|
763
|
-
// ${batch} — CONCRETE batched ports for map '${node.id}': the Vec of per-element CONCRETE ports structs
|
|
764
|
-
// (a Vec<${name}>, NOT a generic key-value container). The consumer's batched handler reads the typed
|
|
765
|
-
// element ports off the concrete struct directly.
|
|
766
|
-
#[derive(Clone)]
|
|
767
|
-
pub struct ${batch} {
|
|
768
|
-
pub items: Vec<${name}>,
|
|
769
|
-
}`;
|
|
770
|
-
}
|
|
771
|
-
/** emitFanoutPortsStructs (v3, rust twin) — per-id element ports struct + batch struct for a fanout node. */
|
|
772
|
-
function emitFanoutPortsStructs(comp, node, typedNodes, plan) {
|
|
773
|
-
const f = node.fanout;
|
|
774
|
-
const name = portsStructName(comp.name, node.id);
|
|
775
|
-
const batch = `${name}Batch`;
|
|
776
|
-
const { elemRef } = fanoutOverElemInfo(comp, node, typedNodes, plan);
|
|
777
|
-
const asBinding = { name: f.as, ref: elemRef, plan };
|
|
778
|
-
const elemStruct = emitPortsStruct(comp, { id: node.id, component: f.component, ports: f.ports, portSchemas: f.portSchemas }, asBinding, plan, typedNodes);
|
|
779
|
-
return `${elemStruct}
|
|
780
|
-
|
|
781
|
-
// ${batch} — CONCRETE batched ports for fanout '${node.id}': the Vec of per-id CONCRETE ports structs.
|
|
782
|
-
#[derive(Clone)]
|
|
783
|
-
pub struct ${batch} {
|
|
784
|
-
pub items: Vec<${name}>,
|
|
785
|
-
}`;
|
|
786
|
-
}
|
|
787
739
|
// ── native expression compiler backend (#108) — cond `if` / map `when` / cond branches (Rust) ────────
|
|
788
740
|
//
|
|
789
741
|
// The runtime-free native expression compiler (native-expr.ts) mirrors run_behavior's cond/guard with
|
|
@@ -1561,21 +1513,20 @@ function emitInStruct(comp, plan) {
|
|
|
1561
1513
|
// number literal), and a genuinely-dynamic port fails closed. There is no boxed-Value fallback on the
|
|
1562
1514
|
// covered read plane.
|
|
1563
1515
|
/**
|
|
1564
|
-
*
|
|
1565
|
-
*
|
|
1566
|
-
*
|
|
1567
|
-
*
|
|
1568
|
-
*
|
|
1569
|
-
*
|
|
1570
|
-
*
|
|
1571
|
-
* a boxed escape would re-introduce the bc-runtime coupling this module removes). `fieldRustType` is the
|
|
1572
|
-
* ports-struct field type (from portFieldRustType); `resolveRef` resolves a ref head for the scalar path.
|
|
1516
|
+
* emitPortWireField — emit ONE port as a boxed `(name, WireValue)` entry for the op-agnostic transport
|
|
1517
|
+
* payload (#183). The port lowers to its NATIVE value via the ONE port lowering (`compilePortNode`), then
|
|
1518
|
+
* boxes ONCE into the BC-owned `WireValue` through the total box SSoT (`renderRustWireBox` ∘
|
|
1519
|
+
* `buildWirePlan(dir:"in")`) — the SAME renderer every box crossing uses (a `value` / `Vec<WireValue>` port
|
|
1520
|
+
* is already the opaque form, boxed as identity `value` / list-of-`value`, so there is NO double-box). The
|
|
1521
|
+
* entry key is the RAW PORT NAME — the WireRow field-name↔port-name identity is the load-bearing transport
|
|
1522
|
+
* contract (a dynamic-port consumer reads `PK`/`SK`/`GSI1PK` by that name). A FALLIBLE port expr fails closed.
|
|
1573
1523
|
*/
|
|
1574
|
-
function
|
|
1524
|
+
function emitPortWireField(pn, expr, comp, plan, typedNodes, isPrior, expected, opts) {
|
|
1575
1525
|
const c = compilePortNode(expr, comp, plan, typedNodes, isPrior, `port '${pn}'`, expected, opts);
|
|
1576
1526
|
if (c.stmts.length > 0)
|
|
1577
|
-
throw new GeneratorFailure("UNSUPPORTED_NODE_STRAIGHTLINE", `rust typed-native (runtime-free): port '${pn}' ${JSON.stringify(expr)} lowers to a FALLIBLE expression (INT_OVERFLOW / NAN_OR_INF / MOD_ZERO / PRECISION_LOSS) — statements with an early error-return, which a
|
|
1578
|
-
|
|
1527
|
+
throw new GeneratorFailure("UNSUPPORTED_NODE_STRAIGHTLINE", `rust typed-native (runtime-free): port '${pn}' ${JSON.stringify(expr)} lowers to a FALLIBLE expression (INT_OVERFLOW / NAN_OR_INF / MOD_ZERO / PRECISION_LOSS) — statements with an early error-return, which a transport payload literal cannot host. Use a non-fallible port expression.`);
|
|
1528
|
+
const boxed = renderRustWireBox(buildWirePlan(c.ref, { from: "top" }, { model: "port", field: pn, plan }, "in"), c.expr);
|
|
1529
|
+
return `(${rustStrLit(pn)}.to_string(), ${boxed})`;
|
|
1579
1530
|
}
|
|
1580
1531
|
// ── the combined runner (STRUCT-returning; INLINE sequential; native ports in; concrete row out) ──
|
|
1581
1532
|
function rustScalar(s) {
|
|
@@ -1728,7 +1679,6 @@ function emitNativeRawRunner(comp, plan, ap, leaf) {
|
|
|
1728
1679
|
const node = comp.body[i];
|
|
1729
1680
|
const meta = metas[i];
|
|
1730
1681
|
const s = sanitize(node.id);
|
|
1731
|
-
const structName = portsStructName(comp.name, node.id);
|
|
1732
1682
|
const portNames = Object.keys(node.ports);
|
|
1733
1683
|
const ref = typedNodes.get(node.id);
|
|
1734
1684
|
lines.push(` // ── op '${node.id}' (${node.component}${node.relationKind ? ", relationKind:" + node.relationKind : ""}${node.parent ? ", parent:" + node.parent : ""}) ──`);
|
|
@@ -1767,20 +1717,17 @@ function emitNativeRawRunner(comp, plan, ap, leaf) {
|
|
|
1767
1717
|
indent += " ";
|
|
1768
1718
|
}
|
|
1769
1719
|
}
|
|
1770
|
-
const inits = [];
|
|
1771
1720
|
const narrowed = nodeNarrowedPaths(comp, node);
|
|
1772
|
-
|
|
1773
|
-
inits.push(emitPortInit(pn, node.ports[pn], comp, plan, typedNodes, (h) => priorNodeAt(h, k), inputPortTypeRef(node.portSchemas?.[pn], plan), { narrowed }));
|
|
1774
|
-
}
|
|
1721
|
+
const fields = portNames.map((pn) => emitPortWireField(pn, node.ports[pn], comp, plan, typedNodes, (h) => priorNodeAt(h, k), inputPortTypeRef(node.portSchemas?.[pn], plan), { narrowed }));
|
|
1775
1722
|
// bc#97: derived per-node await — this point-read's future is awaited HERE (its result-consumption
|
|
1776
1723
|
// point) iff THIS node's terminal handler is async. A sync handler in the same async runner is called
|
|
1777
1724
|
// directly (no `.await`). The runner being `async fn` does not force every call site to await.
|
|
1778
1725
|
const awaitSfx = ap.nodeIsAsync(node.id) ? ".await" : "";
|
|
1779
|
-
// DIRECT leaf transport call: the resolved op-agnostic symbol, the node's
|
|
1780
|
-
//
|
|
1781
|
-
//
|
|
1782
|
-
const call = `${resolveLeafSymbol(node.component, leaf)}(${
|
|
1783
|
-
lines.push(`${indent}let
|
|
1726
|
+
// DIRECT leaf transport call: the resolved op-agnostic symbol, ONE WireRow payload (the node's boxed
|
|
1727
|
+
// ports). `bound` is NOT passed — it is BC's internal produced/skip gate, already enforced by the
|
|
1728
|
+
// surrounding `if bound_<s>.is_some()` / `if produced_<parent>` guards; the leaf never receives it.
|
|
1729
|
+
const call = `${resolveLeafSymbol(node.component, leaf, node.leafSymbol)}(payload_${s})${awaitSfx}`;
|
|
1730
|
+
lines.push(`${indent}let payload_${s} = ${rustPayloadRow(fields)};`);
|
|
1784
1731
|
// uniform seam: every covered node returns a single result WIRE; the inline de-box (renderResultDeBox)
|
|
1785
1732
|
// classifies it against the STATICALLY declared result type and produces the structured Error Value on a
|
|
1786
1733
|
// mismatch (byte-equal codes to run_behavior's outType check, so ≡ holds). The wire's concrete type is
|
|
@@ -1880,7 +1827,6 @@ function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes
|
|
|
1880
1827
|
for (const i of refMembers) {
|
|
1881
1828
|
const node = comp.body[i];
|
|
1882
1829
|
const s = sanitize(node.id);
|
|
1883
|
-
const structName = portsStructName(comp.name, node.id);
|
|
1884
1830
|
const gated = node.parent !== undefined && priorNodeAt(node.parent, atPos);
|
|
1885
1831
|
// #125: a member gated by a PRIOR-stage control gate (`parent=gate, bindField:"ok"`). Its bindField is
|
|
1886
1832
|
// the gate's skip sentinel, NOT a relation data key — the gate is typeless (no struct field to read).
|
|
@@ -1893,7 +1839,7 @@ function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes
|
|
|
1893
1839
|
// it is a plain local inside the produced block — NOT a stage-scoped mut (nothing captures it) and no
|
|
1894
1840
|
// dead None init. A control-gate parent needs no bound at all (produced_<gate> already carries the skip).
|
|
1895
1841
|
if (gated) {
|
|
1896
|
-
lines.push(` let mut
|
|
1842
|
+
lines.push(` let mut payload_${s}: Option<WireRow> = None;`);
|
|
1897
1843
|
lines.push(`${ind}if produced_${sanitize(node.parent)}.get() {`);
|
|
1898
1844
|
closers.unshift(`${ind}}`);
|
|
1899
1845
|
ind += " ";
|
|
@@ -1912,16 +1858,13 @@ function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes
|
|
|
1912
1858
|
ind += " ";
|
|
1913
1859
|
}
|
|
1914
1860
|
}
|
|
1915
|
-
const inits = [];
|
|
1916
1861
|
const narrowed = nodeNarrowedPaths(comp, node);
|
|
1917
|
-
|
|
1918
|
-
inits.push(emitPortInit(pn, node.ports[pn], comp, plan, typedNodes, (h) => priorNodeAt(h, atPos), inputPortTypeRef(node.portSchemas?.[pn], plan), { narrowed }));
|
|
1919
|
-
}
|
|
1862
|
+
const fields = Object.keys(node.ports).map((pn) => emitPortWireField(pn, node.ports[pn], comp, plan, typedNodes, (h) => priorNodeAt(h, atPos), inputPortTypeRef(node.portSchemas?.[pn], plan), { narrowed }));
|
|
1920
1863
|
if (gated) {
|
|
1921
|
-
lines.push(`${ind}
|
|
1864
|
+
lines.push(`${ind}payload_${s} = Some(${rustPayloadRow(fields)});`);
|
|
1922
1865
|
}
|
|
1923
1866
|
else {
|
|
1924
|
-
lines.push(`${ind}let
|
|
1867
|
+
lines.push(`${ind}let payload_${s}: Option<WireRow> = Some(${rustPayloadRow(fields)});`);
|
|
1925
1868
|
}
|
|
1926
1869
|
for (const c of closers)
|
|
1927
1870
|
lines.push(c);
|
|
@@ -1943,7 +1886,7 @@ function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes
|
|
|
1943
1886
|
lines.push(` let mut ${jobsVar}: Vec<usize> = Vec::new();`);
|
|
1944
1887
|
refMembers.forEach((i, slot) => {
|
|
1945
1888
|
const s = sanitize(comp.body[i].id);
|
|
1946
|
-
lines.push(` if
|
|
1889
|
+
lines.push(` if payload_${s}.is_some() { ${jobsVar}.push(${slot}); }`);
|
|
1947
1890
|
});
|
|
1948
1891
|
lines.push(` let cursor = std::sync::atomic::AtomicUsize::new(0);`);
|
|
1949
1892
|
lines.push(` let workers = ${boundN}usize.min(${jobsVar}.len());`);
|
|
@@ -1957,11 +1900,12 @@ function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes
|
|
|
1957
1900
|
refMembers.forEach((i, slot) => {
|
|
1958
1901
|
const node = comp.body[i];
|
|
1959
1902
|
const s = sanitize(node.id);
|
|
1960
|
-
// DIRECT leaf transport call —
|
|
1961
|
-
// `bound` (BC's internal produced/skip gate is already applied in
|
|
1962
|
-
|
|
1903
|
+
// DIRECT leaf transport call — ONE op-agnostic symbol, ONE WireRow payload (the preflight-built ports,
|
|
1904
|
+
// cloned into the owned-arg call). No `bound` (BC's internal produced/skip gate is already applied in
|
|
1905
|
+
// preflight — the leaf never sees it).
|
|
1906
|
+
const call = `${resolveLeafSymbol(node.component, leaf, node.leafSymbol)}(payload)`;
|
|
1963
1907
|
lines.push(` ${slot} => {`);
|
|
1964
|
-
lines.push(` let
|
|
1908
|
+
lines.push(` let payload = payload_${s}.as_ref().expect("runnable member has ports").clone();`);
|
|
1965
1909
|
lines.push(` let row = ${call};`);
|
|
1966
1910
|
lines.push(` *slot_${s}.lock().unwrap() = Some(row);`);
|
|
1967
1911
|
lines.push(` }`);
|
|
@@ -1977,7 +1921,7 @@ function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes
|
|
|
1977
1921
|
const meta = metas[i];
|
|
1978
1922
|
const s = sanitize(node.id);
|
|
1979
1923
|
const ref = typedNodes.get(node.id);
|
|
1980
|
-
lines.push(` if
|
|
1924
|
+
lines.push(` if payload_${s}.is_some() {`);
|
|
1981
1925
|
lines.push(` let out_${s} = slot_${s}.lock().unwrap().take().expect("runnable member wrote its slot");`);
|
|
1982
1926
|
if (meta.policy === "continue") {
|
|
1983
1927
|
// continue: a failed member (leaf failure OR de-box mismatch) commits no Port (defensive — covered
|
|
@@ -2031,9 +1975,7 @@ isAsync = false) {
|
|
|
2031
1975
|
// skipped elements instead. Byte-equal to run_behavior's applyInto keep-with-null.
|
|
2032
1976
|
const keepWithNull = hasGuard && hasInto;
|
|
2033
1977
|
const s = sanitize(node.id);
|
|
2034
|
-
const
|
|
2035
|
-
const batch = `${structName}Batch`;
|
|
2036
|
-
const leafSym = resolveLeafSymbol(m.component, leaf);
|
|
1978
|
+
const leafSym = resolveLeafSymbol(m.component, leaf, m.leafSymbol);
|
|
2037
1979
|
// #108: over element type + the OWNED over-Vec expression (prior-node arr OR input array w/ elemType).
|
|
2038
1980
|
const { elemRef: overElemRef, overExpr, optArr: overOptArr } = mapOverElemInfo(comp, node, typedNodes, plan);
|
|
2039
1981
|
const elemMat = mapElemMaterializerName(comp.name, node.id);
|
|
@@ -2062,19 +2004,17 @@ isAsync = false) {
|
|
|
2062
2004
|
: elemDeBoxRef.kind === "opt"
|
|
2063
2005
|
? "None"
|
|
2064
2006
|
: `${renderTypeRef(elemDeBoxRef)}::default()`;
|
|
2065
|
-
//
|
|
2066
|
-
const
|
|
2067
|
-
const out = [];
|
|
2068
|
-
const inits = [];
|
|
2007
|
+
// the per-element boxed port entries (#183) — the SAME box SSoT as a point node, over the $as element.
|
|
2008
|
+
const portFields = () => {
|
|
2069
2009
|
const asBinding = { name: asName, ref: overElemRef, plan };
|
|
2070
2010
|
// #170: a guarded map narrows its `when(ne($e.key,null))`-proven element key non-null in kept elements.
|
|
2071
2011
|
const narrowed = nodeNarrowedPaths(comp, node);
|
|
2072
|
-
|
|
2073
|
-
inits.push(emitPortInit(pn, m.ports[pn], comp, plan, typedNodes, priorHere, inputPortTypeRef(m.portSchemas?.[pn], plan), { asBinding, asBase: `oel_${s}`, narrowed }));
|
|
2074
|
-
}
|
|
2075
|
-
out.push(`${il}let ep_${s} = ${structName} { ${inits.join(", ")} };`);
|
|
2076
|
-
return out;
|
|
2012
|
+
return portNames.map((pn) => emitPortWireField(pn, m.ports[pn], comp, plan, typedNodes, priorHere, inputPortTypeRef(m.portSchemas?.[pn], plan), { asBinding, asBase: `oel_${s}`, narrowed }));
|
|
2077
2013
|
};
|
|
2014
|
+
// BATCHED element: `ep_<s>` is a WireRow VALUE (a `WireValue::Row`) collected into the items WireList of
|
|
2015
|
+
// the batch payload. NON-batched element: `ep_<s>` is the per-element transport payload WireRow.
|
|
2016
|
+
const buildBatchElem = (il) => [`${il}let ep_${s} = WireValue::Row(WireRow { entries: vec![${portFields().join(", ")}] });`];
|
|
2017
|
+
const buildPayloadElem = (il) => [`${il}let ep_${s} = ${rustPayloadRow(portFields())};`];
|
|
2078
2018
|
// #108 guard: compile `when` to a native bool over an element-scoped resolveHead ($as element value,
|
|
2079
2019
|
// prior node, input port). mkGuard returns the compiled {stmts, expr} (or null when unguarded); the
|
|
2080
2020
|
// keep-with-null batched path consumes it directly to branch instead of skipping.
|
|
@@ -2117,14 +2057,14 @@ isAsync = false) {
|
|
|
2117
2057
|
// zips its next deboxed row, a skipped element gets into=None. Byte-equal to run_behavior: batched
|
|
2118
2058
|
// keptIdx-aligned collect + applyInto (skipped element unaugmented → opt-into null).
|
|
2119
2059
|
const g = mkGuard();
|
|
2120
|
-
lines.push(`${indent}let mut items_${s}: Vec
|
|
2060
|
+
lines.push(`${indent}let mut items_${s}: Vec<WireValue> = Vec::with_capacity(over_${s}.len());`);
|
|
2121
2061
|
lines.push(`${indent}let mut keep_${s}: Vec<bool> = Vec::with_capacity(over_${s}.len());`);
|
|
2122
2062
|
lines.push(`${indent}for oel_${s} in over_${s}.iter() {`);
|
|
2123
2063
|
for (const st of g.stmts)
|
|
2124
2064
|
lines.push(`${indent} ${st}`);
|
|
2125
2065
|
lines.push(`${indent} let __keep = ${rustStripOuterParens(g.expr)};`);
|
|
2126
2066
|
lines.push(`${indent} if __keep {`);
|
|
2127
|
-
for (const l of
|
|
2067
|
+
for (const l of buildBatchElem(indent + " "))
|
|
2128
2068
|
lines.push(l);
|
|
2129
2069
|
lines.push(`${indent} items_${s}.push(ep_${s});`);
|
|
2130
2070
|
lines.push(`${indent} keep_${s}.push(true);`);
|
|
@@ -2135,15 +2075,17 @@ isAsync = false) {
|
|
|
2135
2075
|
lines.push(`${indent}let mut decs_${s}: Vec<${renderTypeRef(elemDeBoxRef)}> = Vec::with_capacity(items_${s}.len());`);
|
|
2136
2076
|
lines.push(`${indent}if !items_${s}.is_empty() {`);
|
|
2137
2077
|
lines.push(`${indent} let want_${s} = items_${s}.len();`);
|
|
2138
|
-
|
|
2139
|
-
|
|
2078
|
+
// ONE op-agnostic transport call: batch payload WireRow {items:[…]}; result is a WireList unwrapped to
|
|
2079
|
+
// its aligned per-element wires (byte-equal to run_behavior's aligned batch result).
|
|
2080
|
+
lines.push(`${indent} let out_${s} = match ${leafSym}(${rustPayloadBatch(`items_${s}`)})${awaitSfx} {`);
|
|
2140
2081
|
lines.push(`${indent} Ok(r) => r,`);
|
|
2141
2082
|
lines.push(`${indent} Err(e) => return Err(op_failed(${rustStrLit(node.id)}, "fail", e)),`);
|
|
2142
2083
|
lines.push(`${indent} };`);
|
|
2143
|
-
lines.push(`${indent}
|
|
2084
|
+
lines.push(`${indent} let rows_${s}: Vec<WireValue> = ${rustListItems(`out_${s}`)};`);
|
|
2085
|
+
lines.push(`${indent} if rows_${s}.len() != want_${s} {`);
|
|
2144
2086
|
lines.push(`${indent} return Err(BehaviorError::new("MAP_BATCH_RESULT_MISMATCH", format!("map '{}': batched handler must return a list aligned to items (want {})", ${rustStrLit(node.id)}, want_${s})));`);
|
|
2145
2087
|
lines.push(`${indent} }`);
|
|
2146
|
-
lines.push(`${indent} for er_${s} in
|
|
2088
|
+
lines.push(`${indent} for er_${s} in rows_${s}.into_iter() {`);
|
|
2147
2089
|
lines.push(`${indent} let dec_${s} = ${renderElemDeBox(`${indent} `)};`);
|
|
2148
2090
|
lines.push(`${indent} decs_${s}.push(dec_${s});`);
|
|
2149
2091
|
lines.push(`${indent} }`);
|
|
@@ -2160,13 +2102,13 @@ isAsync = false) {
|
|
|
2160
2102
|
}
|
|
2161
2103
|
else if (batched) {
|
|
2162
2104
|
// build kept-element ports (+ kept over elements for into). Batched into is never guarded (rejected).
|
|
2163
|
-
lines.push(`${indent}let mut items_${s}: Vec
|
|
2105
|
+
lines.push(`${indent}let mut items_${s}: Vec<WireValue> = Vec::with_capacity(over_${s}.len());`);
|
|
2164
2106
|
if (hasInto)
|
|
2165
2107
|
lines.push(`${indent}let mut kept_${s}: Vec<${renderTypeRef(overElemRef)}> = Vec::with_capacity(over_${s}.len());`);
|
|
2166
2108
|
lines.push(`${indent}for oel_${s} in over_${s}.iter() {`);
|
|
2167
2109
|
for (const l of emitGuard(indent + " "))
|
|
2168
2110
|
lines.push(l);
|
|
2169
|
-
for (const l of
|
|
2111
|
+
for (const l of buildBatchElem(indent + " "))
|
|
2170
2112
|
lines.push(l);
|
|
2171
2113
|
lines.push(`${indent} items_${s}.push(ep_${s});`);
|
|
2172
2114
|
if (hasInto)
|
|
@@ -2174,21 +2116,19 @@ isAsync = false) {
|
|
|
2174
2116
|
lines.push(`${indent}}`);
|
|
2175
2117
|
lines.push(`${indent}if !items_${s}.is_empty() {`);
|
|
2176
2118
|
lines.push(`${indent} let want_${s} = items_${s}.len();`);
|
|
2177
|
-
|
|
2178
|
-
|
|
2179
|
-
// from the removed trait method; only the call target changes). Returns the aligned per-element wires
|
|
2180
|
-
// (Vec<Wire>). No `bound` (batched maps carry none).
|
|
2181
|
-
lines.push(`${indent} let row_${s} = match ${leafSym}(&bp_${s})${awaitSfx} {`);
|
|
2119
|
+
// ONE op-agnostic transport call: batch payload WireRow {items:[…]}; result WireList → aligned wires.
|
|
2120
|
+
lines.push(`${indent} let out_${s} = match ${leafSym}(${rustPayloadBatch(`items_${s}`)})${awaitSfx} {`);
|
|
2182
2121
|
lines.push(`${indent} Ok(r) => r,`);
|
|
2183
2122
|
lines.push(`${indent} Err(e) => return Err(op_failed(${rustStrLit(node.id)}, "fail", e)),`);
|
|
2184
2123
|
lines.push(`${indent} };`);
|
|
2185
|
-
lines.push(`${indent}
|
|
2124
|
+
lines.push(`${indent} let rows_${s}: Vec<WireValue> = ${rustListItems(`out_${s}`)};`);
|
|
2125
|
+
lines.push(`${indent} if rows_${s}.len() != want_${s} {`);
|
|
2186
2126
|
lines.push(`${indent} return Err(BehaviorError::new("MAP_BATCH_RESULT_MISMATCH", format!("map '{}': batched handler must return a list aligned to items (want {})", ${rustStrLit(node.id)}, want_${s})));`);
|
|
2187
2127
|
lines.push(`${indent} }`);
|
|
2188
2128
|
if (hasInto) {
|
|
2189
2129
|
// zip the aligned per-element WIRES onto each KEPT over element: de-box the element wire strictly
|
|
2190
2130
|
// (into the `into` field's type) then materialize the augmented element.
|
|
2191
|
-
lines.push(`${indent} let mut rows_iter_${s} =
|
|
2131
|
+
lines.push(`${indent} let mut rows_iter_${s} = rows_${s}.into_iter();`);
|
|
2192
2132
|
lines.push(`${indent} for over_el_${s} in kept_${s}.iter() {`);
|
|
2193
2133
|
lines.push(`${indent} let er_${s} = rows_iter_${s}.next().expect("aligned batch row");`);
|
|
2194
2134
|
lines.push(`${indent} let dec_${s} = ${renderElemDeBox(`${indent} `)};`);
|
|
@@ -2197,7 +2137,7 @@ isAsync = false) {
|
|
|
2197
2137
|
}
|
|
2198
2138
|
else {
|
|
2199
2139
|
// no-into: de-box each aligned per-element wire DIRECTLY into the element (result = kept elements).
|
|
2200
|
-
lines.push(`${indent} for er_${s} in
|
|
2140
|
+
lines.push(`${indent} for er_${s} in rows_${s}.into_iter() {`);
|
|
2201
2141
|
lines.push(`${indent} let el_${s} = ${renderElemDeBox(`${indent} `)};`);
|
|
2202
2142
|
lines.push(`${indent} built_${s}.push(el_${s});`);
|
|
2203
2143
|
lines.push(`${indent} }`);
|
|
@@ -2213,13 +2153,12 @@ isAsync = false) {
|
|
|
2213
2153
|
const nonBatchedSkip = keepWithNull ? `built_${s}.push(${elemMat}(oel_${s}, ${intoSkipDefault})); continue;` : "continue;";
|
|
2214
2154
|
for (const l of emitGuard(indent + " ", nonBatchedSkip))
|
|
2215
2155
|
lines.push(l);
|
|
2216
|
-
for (const l of
|
|
2156
|
+
for (const l of buildPayloadElem(indent + " "))
|
|
2217
2157
|
lines.push(l);
|
|
2218
2158
|
// Element Error Policy (scp-error.md): `skip` drops the failing element and proceeds (order is
|
|
2219
2159
|
// preserved; the leaf keeps the Error Value it produced). `error` (default) promotes the element
|
|
2220
|
-
// Failure to the map's Component Failure
|
|
2221
|
-
|
|
2222
|
-
lines.push(`${indent} let er_${s} = match ${leafSym}(${leafCallArgs(`ep_${s}`, portFieldSpread(m.ports, m.portSchemas, comp, plan, typedNodes, { name: asName, ref: overElemRef, plan }, nodeNarrowedPaths(comp, node)))})${awaitSfx} {`);
|
|
2160
|
+
// Failure to the map's Component Failure. ONE op-agnostic transport call per element, ONE WireRow payload.
|
|
2161
|
+
lines.push(`${indent} let er_${s} = match ${leafSym}(ep_${s})${awaitSfx} {`);
|
|
2223
2162
|
lines.push(`${indent} Ok(r) => r,`);
|
|
2224
2163
|
if (m.elementPolicy === "skip") {
|
|
2225
2164
|
lines.push(`${indent} Err(_) => continue,`);
|
|
@@ -2256,9 +2195,7 @@ function emitFanoutArm(comp, node, atPos, typedNodes, plan, priorNodeAt, leaf, i
|
|
|
2256
2195
|
const f = node.fanout;
|
|
2257
2196
|
const awaitSfx = isAsync ? ".await" : "";
|
|
2258
2197
|
const s = sanitize(node.id);
|
|
2259
|
-
const
|
|
2260
|
-
const batch = `${structName}Batch`;
|
|
2261
|
-
const leafSym = resolveLeafSymbol(f.component, leaf);
|
|
2198
|
+
const leafSym = resolveLeafSymbol(f.component, leaf, f.leafSymbol);
|
|
2262
2199
|
const connRef = typedNodes.get(node.id);
|
|
2263
2200
|
const elemRef = fanoutItemsElemRef(node, connRef, plan);
|
|
2264
2201
|
const elemName = renderTypeRef(elemRef);
|
|
@@ -2273,13 +2210,11 @@ function emitFanoutArm(comp, node, atPos, typedNodes, plan, priorNodeAt, leaf, i
|
|
|
2273
2210
|
if (!dkField || dkField.type.kind !== "scalar" || dkField.type.scalar !== "string")
|
|
2274
2211
|
throw new GeneratorFailure("UNSUPPORTED_NODE_STRAIGHTLINE", `rust fanout (v3): node '${node.id}' dedupeKey '${f.dedupeKey}' must be a string field of the connection items element type '${elemRef.name}'.`);
|
|
2275
2212
|
const dkRust = rustFieldName(f.dedupeKey);
|
|
2213
|
+
// per-id boxed port WireFields — `ep_<s>` is a WireRow VALUE collected into the batch payload's items list.
|
|
2276
2214
|
const buildPorts = (il) => {
|
|
2277
|
-
const inits = [];
|
|
2278
2215
|
const asBinding = { name: asName, ref: overElemRef, plan };
|
|
2279
|
-
|
|
2280
|
-
|
|
2281
|
-
}
|
|
2282
|
-
return [`${il}let ep_${s} = ${structName} { ${inits.join(", ")} };`];
|
|
2216
|
+
const fields = portNames.map((pn) => emitPortWireField(pn, f.ports[pn], comp, plan, typedNodes, priorHere, inputPortTypeRef(f.portSchemas?.[pn], plan), { asBinding, asBase: `oel_${s}` }));
|
|
2217
|
+
return [`${il}let ep_${s} = WireValue::Row(WireRow { entries: vec![${fields.join(", ")}] });`];
|
|
2283
2218
|
};
|
|
2284
2219
|
const lines = [];
|
|
2285
2220
|
const closers = [];
|
|
@@ -2292,7 +2227,7 @@ function emitFanoutArm(comp, node, atPos, typedNodes, plan, priorNodeAt, leaf, i
|
|
|
2292
2227
|
}
|
|
2293
2228
|
lines.push(`${indent}let over_${s} = ${rustBindOverExpr(overExpr, overOptArr)};`);
|
|
2294
2229
|
lines.push(`${indent}let mut built_${s}: Vec<${elemName}> = Vec::new();`);
|
|
2295
|
-
lines.push(`${indent}let mut pi_${s}: Vec
|
|
2230
|
+
lines.push(`${indent}let mut pi_${s}: Vec<WireValue> = Vec::with_capacity(over_${s}.len());`);
|
|
2296
2231
|
lines.push(`${indent}for oel_${s} in over_${s}.iter() {`);
|
|
2297
2232
|
for (const l of buildPorts(indent + " "))
|
|
2298
2233
|
lines.push(l);
|
|
@@ -2300,28 +2235,27 @@ function emitFanoutArm(comp, node, atPos, typedNodes, plan, priorNodeAt, leaf, i
|
|
|
2300
2235
|
lines.push(`${indent}}`);
|
|
2301
2236
|
lines.push(`${indent}if !pi_${s}.is_empty() {`);
|
|
2302
2237
|
lines.push(`${indent} let want_${s} = pi_${s}.len();`);
|
|
2303
|
-
|
|
2304
|
-
//
|
|
2305
|
-
|
|
2306
|
-
// (Vec<Option<Wire>> — None = a DANGLING id). No `bound`.
|
|
2307
|
-
lines.push(`${indent} let row_${s} = match ${leafSym}(&bp_${s})${awaitSfx} {`);
|
|
2238
|
+
// ONE op-agnostic transport call: batch payload WireRow {items:[…]}; result is a WireList of the aligned
|
|
2239
|
+
// per-id element wires (a WireValue::Null element → a DANGLING id). No `bound`.
|
|
2240
|
+
lines.push(`${indent} let out_${s} = match ${leafSym}(${rustPayloadBatch(`pi_${s}`)})${awaitSfx} {`);
|
|
2308
2241
|
lines.push(`${indent} Ok(r) => r,`);
|
|
2309
2242
|
lines.push(`${indent} Err(e) => return Err(op_failed(${rustStrLit(node.id)}, "fail", e)),`);
|
|
2310
2243
|
lines.push(`${indent} };`);
|
|
2311
|
-
|
|
2312
|
-
// de-boxed strictly INLINE (a de-box mismatch fails closed). A DANGLING id is
|
|
2313
|
-
// (empty dedupeKey), which the dangling drop excludes.
|
|
2314
|
-
lines.push(`${indent} if
|
|
2244
|
+
lines.push(`${indent} let rows_${s}: Vec<WireValue> = ${rustListItems(`out_${s}`)};`);
|
|
2245
|
+
// each present body is de-boxed strictly INLINE (a de-box mismatch fails closed). A DANGLING id is a
|
|
2246
|
+
// WireValue::Null → the zero element (empty dedupeKey), which the dangling drop excludes.
|
|
2247
|
+
lines.push(`${indent} if rows_${s}.len() != want_${s} {`);
|
|
2315
2248
|
lines.push(`${indent} return Err(BehaviorError::new("FANOUT_BATCH_RESULT_MISMATCH", format!("fanout '{}': batched handler must return a list aligned to the deduped id list (want {})", ${rustStrLit(node.id)}, want_${s})));`);
|
|
2316
2249
|
lines.push(`${indent} }`);
|
|
2317
2250
|
// ── THE ONE dedupe/drop (mirrors fanoutDedupDrop verbatim): first-seen dedupe by dedupeKey field;
|
|
2318
2251
|
// drop dangling (empty dedupeKey ≡ interpreter's null/absent-key body); implicitSource strip is
|
|
2319
2252
|
// structural (the elem type already omits it). cursor is always None (connection wrap).
|
|
2320
2253
|
lines.push(`${indent} let mut seen_${s}: std::collections::HashSet<String> = std::collections::HashSet::new();`);
|
|
2321
|
-
lines.push(`${indent} for
|
|
2322
|
-
lines.push(`${indent} let el_${s}: ${elemName} =
|
|
2323
|
-
lines.push(`${indent}
|
|
2324
|
-
lines.push(`${indent}
|
|
2254
|
+
lines.push(`${indent} for er_${s} in rows_${s}.into_iter() {`);
|
|
2255
|
+
lines.push(`${indent} let el_${s}: ${elemName} = if matches!(er_${s}, WireValue::Null) {`);
|
|
2256
|
+
lines.push(`${indent} Default::default()`);
|
|
2257
|
+
lines.push(`${indent} } else {`);
|
|
2258
|
+
lines.push(`${indent} ${renderResultDeBox(elemRef, `er_${s}`, node.id, plan, `${indent} `, returnErrFail, nodeWirePassthrough(node))}`);
|
|
2325
2259
|
lines.push(`${indent} };`);
|
|
2326
2260
|
lines.push(`${indent} let key_${s} = el_${s}.${dkRust}.clone();`);
|
|
2327
2261
|
if (f.drop === "dangling") {
|
|
@@ -2490,56 +2424,29 @@ fn leaf_failure(message: impl Into<String>) -> BehaviorError {
|
|
|
2490
2424
|
BehaviorError::new("LEAF_FAILURE", message)
|
|
2491
2425
|
}`;
|
|
2492
2426
|
// ── module assembly ──────────────────────────────────────────────────────────────────
|
|
2493
|
-
/** isCrossPackageSharedNode (#165, rust twin of the go predicate) — a node whose ports struct CROSSES the
|
|
2494
|
-
* leaf-transport boundary as a whole value (the batch ports struct passed to the transport), so under
|
|
2495
|
-
* --shared-types-import it must live in the SHARED crate/module (else the transport crate → covered crate
|
|
2496
|
-
* import cycle). Batched maps + fanouts pass a batch struct; every other node passes only primitive port
|
|
2497
|
-
* fields, so its ports struct stays local. The SINGLE predicate emit() (skip-local) and
|
|
2498
|
-
* {@link rustSharedWireTypesModule} (emit-there) both use — they never disagree (SSoT). */
|
|
2499
|
-
function isCrossPackageSharedNode(n) {
|
|
2500
|
-
return "fanout" in n || ("map" in n && n.map.batched === true);
|
|
2501
|
-
}
|
|
2502
2427
|
/**
|
|
2503
2428
|
* rustSharedWireTypesModule (#165, rust twin of goSharedWireTypesPackage) — the BC-GENERATED shared module
|
|
2504
2429
|
* content emitted when the covered module is generated with --shared-types-import. Carries the SAME wire seam
|
|
2505
2430
|
* the covered module emits in-crate when the flag is absent (Probe/NumProbe + WireValue/WireRow/WireList +
|
|
2506
|
-
* the probe classifiers) so a separate leaf-transport crate can
|
|
2507
|
-
* module reference
|
|
2508
|
-
*
|
|
2509
|
-
*
|
|
2510
|
-
*
|
|
2511
|
-
|
|
2512
|
-
* lib.rs (a separate crate) or a module. `pub use` re-exports keep every name reachable unqualified. */
|
|
2513
|
-
export function rustSharedWireTypesModule(ir) {
|
|
2514
|
-
const portsStructs = [];
|
|
2515
|
-
if (ir !== undefined) {
|
|
2516
|
-
const components = ir.components;
|
|
2517
|
-
const plan = buildTypePlan(ir);
|
|
2518
|
-
for (const c of components.filter(isNativeRaw)) {
|
|
2519
|
-
const typedNodes = buildTypedNodes(c, plan);
|
|
2520
|
-
for (const n of c.body) {
|
|
2521
|
-
if (!isCrossPackageSharedNode(n))
|
|
2522
|
-
continue;
|
|
2523
|
-
portsStructs.push("fanout" in n ? emitFanoutPortsStructs(c, n, typedNodes, plan) : emitMapPortsStructs(c, n, typedNodes, plan));
|
|
2524
|
-
}
|
|
2525
|
-
}
|
|
2526
|
-
}
|
|
2527
|
-
const portsSection = portsStructs.length
|
|
2528
|
-
? `\n\n// #165 cross-crate batched/fanout ports structs — the batch ports the covered module's runner passes\n// to the leaf transport as a whole value. Here (not the covered module) so the transport crate can name\n// them without importing the covered crate (cycle-free). Native fields — no boxed Value.\n${portsStructs.filter((s) => s.trim().length > 0).join("\n\n")}`
|
|
2529
|
-
: "";
|
|
2431
|
+
* the probe classifiers) so a separate leaf-transport crate can take a `WireRow` payload + build+return
|
|
2432
|
+
* `WireValue` (and the covered module reference them) without an import cycle. #183: the transport ABI is the
|
|
2433
|
+
* generic `WireRow` payload built inline at the call site — there are NO per-node/per-role batch ports structs
|
|
2434
|
+
* to emit here. The wire types derive Clone (a cross-crate transport + the #164 passthrough store clone them).
|
|
2435
|
+
* Self-contained + runtime-free — drop it in the shared crate's lib.rs (a separate crate) or a module. */
|
|
2436
|
+
export function rustSharedWireTypesModule() {
|
|
2530
2437
|
return `#![allow(dead_code, unused_imports, non_snake_case)]
|
|
2531
2438
|
// GENERATED by behavior-contracts (rust-typed-native) — the BC-OWNED shared wire types (#165). A covered
|
|
2532
2439
|
// module generated with --shared-types-import imports these (\`use <path>::*;\`); a separate leaf-transport
|
|
2533
|
-
// crate builds + returns the SAME \`WireValue\` (and, on failure, the SAME
|
|
2534
|
-
// failure type lives here too so the transport crate returns
|
|
2535
|
-
// importing the covered crate (unlike go's \`error\` interface,
|
|
2536
|
-
// \`.detail\`/\`.message\`, so the type must be shared). Self-contained
|
|
2440
|
+
// crate takes a \`WireRow\` payload + builds + returns the SAME \`WireValue\` (and, on failure, the SAME
|
|
2441
|
+
// \`BehaviorError\`). The concrete failure type lives here too so the transport crate returns
|
|
2442
|
+
// \`Result<WireValue, BehaviorError>\` WITHOUT importing the covered crate (unlike go's \`error\` interface,
|
|
2443
|
+
// rust's runner reads the concrete \`.detail\`/\`.message\`, so the type must be shared). Self-contained.
|
|
2537
2444
|
|
|
2538
2445
|
// Local concrete failure type (runtime-free) — the covered runner + the transport crate share it. Only the
|
|
2539
2446
|
// TYPE lives here; the de-box/op-failure CONSTRUCTORS stay in the covered module (they are called there).
|
|
2540
2447
|
${emitErrorTypeDefs()}
|
|
2541
2448
|
|
|
2542
|
-
${emitRustProbeWireTypes(true)}
|
|
2449
|
+
${emitRustProbeWireTypes(true)}
|
|
2543
2450
|
`;
|
|
2544
2451
|
}
|
|
2545
2452
|
function emit(ctx) {
|
|
@@ -2585,7 +2492,6 @@ ${emitStructSurface([])}
|
|
|
2585
2492
|
// #108: reset the native-expr helper-usage accumulator (set by the cond/guard compiler).
|
|
2586
2493
|
rustExprUsed.helpers = false;
|
|
2587
2494
|
const leaf = ctx.leafTransport;
|
|
2588
|
-
const structs = [];
|
|
2589
2495
|
const inStructs = [];
|
|
2590
2496
|
const elemMaterializers = [];
|
|
2591
2497
|
// every covered node returns a WireValue the inline de-box classifies — the wire seam (probe enums +
|
|
@@ -2604,33 +2510,16 @@ ${emitStructSurface([])}
|
|
|
2604
2510
|
for (const n of c.body)
|
|
2605
2511
|
if (!isControlGate(n))
|
|
2606
2512
|
typedNodes.set(n.id, "map" in n ? mapNodeArrRef(n, plan) : deriveTypeRef(n.outType, plan)); // #125: control-gate typeless; map は produced-array ref に正規化
|
|
2607
|
-
|
|
2608
|
-
|
|
2609
|
-
// instead (rustSharedWireTypesModule), referenced here via the `use <path>::*;` glob — skip local.
|
|
2610
|
-
if (crossPackage && isCrossPackageSharedNode(n))
|
|
2611
|
-
continue;
|
|
2612
|
-
if ("fanout" in n)
|
|
2613
|
-
structs.push(emitFanoutPortsStructs(c, n, typedNodes, plan));
|
|
2614
|
-
else if ("map" in n)
|
|
2615
|
-
structs.push(emitMapPortsStructs(c, n, typedNodes, plan));
|
|
2616
|
-
else if ("cond" in n) {
|
|
2617
|
-
// #108: a cond node has NO ports struct (pure Expression — no handler dispatch).
|
|
2618
|
-
}
|
|
2619
|
-
else
|
|
2620
|
-
structs.push(emitPortsStruct(c, n, undefined, plan, typedNodes, nodeNarrowedPaths(c, n))); // #129: typedNodes for prior-node arr leaf ports. #170: a gated child narrows its gate-proven opt key.
|
|
2621
|
-
}
|
|
2513
|
+
// #183: a covered node's ports cross the transport boundary as ONE op-agnostic `WireRow` payload built
|
|
2514
|
+
// inline at the call site — there are NO per-node ports structs on the covered plane or the shared crate.
|
|
2622
2515
|
inStructs.push(emitInStruct(c, plan));
|
|
2623
2516
|
const mm = emitMapElemMaterializers(c, typedNodes, plan);
|
|
2624
2517
|
if (mm)
|
|
2625
2518
|
elemMaterializers.push(mm);
|
|
2626
2519
|
}
|
|
2627
|
-
//
|
|
2628
|
-
//
|
|
2629
|
-
//
|
|
2630
|
-
// The ports structs are the ONLY Clone-deriving WireValue-bearing structs (input structs derive Default;
|
|
2631
|
-
// outType decls never carry `value` — input-only), so their rendered field types are the total SSoT
|
|
2632
|
-
// signal. A value-free module omits the derive to stay byte-identical to pre-#156.
|
|
2633
|
-
const hasValuePort = structs.some((s) => s.includes("WireValue"));
|
|
2520
|
+
// #183: the wire types derive Clone — the covered plane always builds `WireRow` payloads (the transport
|
|
2521
|
+
// ABI) and the bc#87 parallel stage clones a member's payload into its owned-arg call; the #164 passthrough
|
|
2522
|
+
// store also clones a `WireValue`. Deriving Clone on the (data-only) wire types is unconditional + harmless.
|
|
2634
2523
|
const runners = native.map((c) => emitNativeRawRunner(c, plan, asyncPlans.get(c.name), leaf)).join("\n\n");
|
|
2635
2524
|
const structSurface = emitStructSurface(native);
|
|
2636
2525
|
// Leaf transport import (SSoT resolution via resolveLeafSymbol): if the consumer names an import module,
|
|
@@ -2695,12 +2584,9 @@ use std::cell::RefCell;`;
|
|
|
2695
2584
|
rustExprUsed.helpers
|
|
2696
2585
|
? `// #108 native-expr helper library (runtime-free; byte-equal to expr-eval.ts core) — used by\n// cond / map-guard checked arithmetic. NO bc-runtime reference (failures use the LOCAL BehaviorError).\n${emitExprHelpersRust()}`
|
|
2697
2586
|
: undefined,
|
|
2698
|
-
structs.some((r) => r.trim().length > 0)
|
|
2699
|
-
? `// Native ports structs (one per componentRef node; typed per the static port type — CONCRETE).\n${structs.filter((r) => r.trim().length > 0).join("\n\n")}`
|
|
2700
|
-
: undefined,
|
|
2701
2587
|
`// CONCRETE per-component input structs (fields = inputPorts).\n${inStructs.join("\n\n")}`,
|
|
2702
2588
|
emitsWireTypes
|
|
2703
|
-
? `// strict de-box wire seam — the BC-OWNED, BC-GENERATED concrete WireValue (+ WireRow/WireList): the\n// consumer's single transport builds + returns
|
|
2589
|
+
? `// strict de-box wire seam — the BC-OWNED, BC-GENERATED concrete WireValue (+ WireRow/WireList): the\n// consumer's single transport takes a WireRow payload + builds + returns a WireValue, implements NOTHING over\n// it. The generated INLINE de-box classifies it against the STATICALLY declared type and owns strictness\n// (required/optional, present/absent, error assembly, fail-closed). Self-contained concrete types.\n${emitRustProbeWireTypes(true)}`
|
|
2704
2590
|
: undefined,
|
|
2705
2591
|
elemMaterializers.length
|
|
2706
2592
|
? `// map augmented-element copiers (pure struct field assignment — no dynamic value read).\n${elemMaterializers.join("\n\n")}`
|
|
@@ -2765,10 +2651,14 @@ fn value_to_wire(v: &Value) -> WireValue {
|
|
|
2765
2651
|
// returning the scripted wire in EXACTLY the shape the removed per-node trait method returned. bc#87
|
|
2766
2652
|
// parallel scoped threads share the static (Mutex-guarded); cases run sequentially so a shared static is
|
|
2767
2653
|
// fine. Echo (#129/#141) reads the spread port params directly. ──
|
|
2654
|
+
// ONE free transport per DISTINCT SPEC-fixed SYMBOL (#176/#183), UNIFORM signature
|
|
2655
|
+
// `<sym>(payload: WireRow) -> Result<WireValue, BehaviorError>`: value_to_wire is recursive, so a
|
|
2656
|
+
// batched/fanout `Value::Arr` result becomes a `WireValue::List` (a `Value::Null` element → WireValue::Null,
|
|
2657
|
+
// the dangling marker) and a single result a scalar/row wire — ONE signature serves every cardinality. Echo
|
|
2658
|
+
// (#129/#141) reads the port back FROM THE PAYLOAD BY NAME. A spec-named leaf used in MULTIPLE roles is
|
|
2659
|
+
// emitted ONCE; two nodes → same symbol but DIFFERENT catalog is a LOUD collision (never silent).
|
|
2768
2660
|
const transportFns = [];
|
|
2769
|
-
const
|
|
2770
|
-
const drainStmt = (catalog, echoBind) => `let (is_err, err, ok, ${echoBind}) = next_scripted(${rustStrLit(catalog)}).ok_or_else(|| unknown_component(${rustStrLit(catalog)}))?;\n if is_err {\n return Err(leaf_failure(err));\n }`;
|
|
2771
|
-
const spreadParams = (spread) => spread.map((p) => `${p.field}: ${p.isCopy ? p.renderedType : `&${p.renderedType}`}`).join(", ");
|
|
2661
|
+
const bySym = new Map();
|
|
2772
2662
|
for (const c of native) {
|
|
2773
2663
|
const ap = asyncPlans.get(c.name);
|
|
2774
2664
|
const typedNodes = new Map();
|
|
@@ -2779,98 +2669,71 @@ fn value_to_wire(v: &Value) -> WireValue {
|
|
|
2779
2669
|
if ("cond" in n)
|
|
2780
2670
|
continue; // #108: a cond node has no leaf (pure Expression) — no transport fn.
|
|
2781
2671
|
const catalog = "fanout" in n ? n.fanout.component : "map" in n ? n.map.component : n.component;
|
|
2782
|
-
|
|
2783
|
-
|
|
2784
|
-
|
|
2785
|
-
|
|
2786
|
-
|
|
2787
|
-
|
|
2788
|
-
|
|
2789
|
-
|
|
2790
|
-
|
|
2791
|
-
|
|
2792
|
-
|
|
2793
|
-
|
|
2794
|
-
|
|
2795
|
-
|
|
2796
|
-
|
|
2797
|
-
|
|
2798
|
-
|
|
2799
|
-
|
|
2800
|
-
|
|
2801
|
-
|
|
2802
|
-
|
|
2803
|
-
|
|
2804
|
-
|
|
2805
|
-
|
|
2806
|
-
if (
|
|
2807
|
-
|
|
2808
|
-
|
|
2809
|
-
|
|
2810
|
-
|
|
2811
|
-
|
|
2812
|
-
${drainStmt(catalog, "_echo")}
|
|
2813
|
-
let arr = match ok { Some(Value::Arr(a)) => a, _ => Vec::new() };
|
|
2814
|
-
let wires = arr.iter().map(value_to_wire).collect();
|
|
2815
|
-
Ok(wires)
|
|
2816
|
-
}`);
|
|
2817
|
-
}
|
|
2818
|
-
else {
|
|
2819
|
-
const { elemRef: overElemRef } = mapOverElemInfo(c, n, typedNodes, plan);
|
|
2820
|
-
const params = spreadParams(portFieldSpread(m.ports, m.portSchemas, c, plan, typedNodes, { name: m.as, ref: overElemRef, plan }, nodeNarrowedPaths(c, n)));
|
|
2821
|
-
transportFns.push(`${fnKw} ${sym}(${params}) -> Result<WireValue, BehaviorError> {
|
|
2822
|
-
${drainStmt(catalog, "_echo")}
|
|
2823
|
-
Ok(value_to_wire(&ok.unwrap_or(Value::Null)))
|
|
2824
|
-
}`);
|
|
2825
|
-
}
|
|
2826
|
-
continue;
|
|
2827
|
-
}
|
|
2828
|
-
// componentRef (point read): spread port fields; supports echo (#129/#141) reading the port params.
|
|
2829
|
-
const node = n;
|
|
2830
|
-
// #170: the observe transport fn's param types must match the covered module's leaf call args, which
|
|
2831
|
-
// narrow a gate-proven opt key — so this reads the SAME node narrowing.
|
|
2832
|
-
const crNarrowed = nodeNarrowedPaths(c, node);
|
|
2833
|
-
const ref = typedNodes.get(n.id);
|
|
2834
|
-
const echoBranches = [];
|
|
2835
|
-
if (ref.kind === "named") {
|
|
2836
|
-
const decl = findDecl(plan, ref.name);
|
|
2837
|
-
const field = decl !== undefined && decl.fields.length === 1 ? decl.fields[0] : undefined;
|
|
2838
|
-
const fieldRust = field !== undefined ? renderTypeRef(field.type) : null;
|
|
2839
|
-
const recordRust = renderTypeRef(ref);
|
|
2840
|
-
for (const pn of Object.keys(node.ports)) {
|
|
2841
|
-
let portRust = null;
|
|
2842
|
-
try {
|
|
2843
|
-
portRust = portFieldRustType(node.ports[pn], c, plan, typedNodes, inputPortTypeRef(node.portSchemas?.[pn], plan), `echo port '${pn}'`, { narrowed: crNarrowed });
|
|
2844
|
-
}
|
|
2845
|
-
catch {
|
|
2846
|
-
portRust = null;
|
|
2847
|
-
}
|
|
2848
|
-
if (portRust === recordRust) {
|
|
2849
|
-
// the port IS the whole record → echo it DIRECTLY (matching run_behavior's plain echo:port).
|
|
2850
|
-
const own = typeRefIsCopy(ref) ? `${portFieldName(pn)}` : `${portFieldName(pn)}.clone()`;
|
|
2851
|
-
echoBranches.push(` if echo == ${rustStrLit(pn)} {\n let tv = ${own};\n return Ok(value_to_wire(&${serializeTyped("tv", ref, plan)}));\n }`);
|
|
2852
|
-
}
|
|
2853
|
-
else if (fieldRust !== null && field !== undefined && portRust === fieldRust) {
|
|
2854
|
-
// a scalar port wraps into the record's single field ({v: ports.X}).
|
|
2855
|
-
const own = typeRefIsCopy(field.type) ? `${portFieldName(pn)}` : `${portFieldName(pn)}.clone()`;
|
|
2856
|
-
echoBranches.push(` if echo == ${rustStrLit(pn)} {\n let tv = ${own};\n return Ok(value_to_wire(&Value::Obj(vec![(${rustStrLit(field.name)}.to_string(), ${serializeTyped("tv", field.type, plan)})])));\n }`);
|
|
2672
|
+
const specSym = "fanout" in n ? n.fanout.leafSymbol : "map" in n ? n.map.leafSymbol : n.leafSymbol;
|
|
2673
|
+
const sym = resolveLeafSymbol(catalog, leaf, specSym);
|
|
2674
|
+
const isAsync = ap.nodeIsAsync(n.id);
|
|
2675
|
+
// echo branches (point/componentRef nodes only — a batched/fanout node returns a WireList, not a port).
|
|
2676
|
+
const echo = [];
|
|
2677
|
+
if (!("fanout" in n) && !("map" in n)) {
|
|
2678
|
+
const node = n;
|
|
2679
|
+
const crNarrowed = nodeNarrowedPaths(c, node);
|
|
2680
|
+
const ref = typedNodes.get(n.id);
|
|
2681
|
+
if (ref.kind === "named") {
|
|
2682
|
+
const decl = findDecl(plan, ref.name);
|
|
2683
|
+
const field = decl !== undefined && decl.fields.length === 1 ? decl.fields[0] : undefined;
|
|
2684
|
+
const fieldRust = field !== undefined ? renderTypeRef(field.type) : null;
|
|
2685
|
+
const recordRust = renderTypeRef(ref);
|
|
2686
|
+
for (const pn of Object.keys(node.ports)) {
|
|
2687
|
+
let portRust = null;
|
|
2688
|
+
try {
|
|
2689
|
+
portRust = portFieldRustType(node.ports[pn], c, plan, typedNodes, inputPortTypeRef(node.portSchemas?.[pn], plan), `echo port '${pn}'`, { narrowed: crNarrowed });
|
|
2690
|
+
}
|
|
2691
|
+
catch {
|
|
2692
|
+
portRust = null;
|
|
2693
|
+
}
|
|
2694
|
+
if (portRust === recordRust) {
|
|
2695
|
+
// the port IS the whole record → echo its payload wire DIRECTLY (matching run_behavior's echo:port).
|
|
2696
|
+
echo.push(` if echo == ${rustStrLit(pn)} {\n if let Some((_, v)) = payload.entries.iter().find(|(__k, _)| __k.as_str() == ${rustStrLit(pn)}) {\n return Ok(v.clone());\n }\n }`);
|
|
2697
|
+
}
|
|
2698
|
+
else if (fieldRust !== null && field !== undefined && portRust === fieldRust) {
|
|
2699
|
+
// a scalar port wraps into the record's single field ({v: <port wire>}) — mirrors the scripted `wrap`.
|
|
2700
|
+
echo.push(` if echo == ${rustStrLit(pn)} {\n if let Some((_, v)) = payload.entries.iter().find(|(__k, _)| __k.as_str() == ${rustStrLit(pn)}) {\n return Ok(WireValue::Row(WireRow { entries: vec![(${rustStrLit(field.name)}.to_string(), v.clone())] }));\n }\n }`);
|
|
2701
|
+
}
|
|
2857
2702
|
}
|
|
2858
2703
|
}
|
|
2704
|
+
else if (ref.kind === "arr" && Object.prototype.hasOwnProperty.call(node.ports, "items")) {
|
|
2705
|
+
// #129: an arr node with an `items` port echoes the payload's items wire (a WireList) so the
|
|
2706
|
+
// node→leaf array dataflow test is non-vacuous.
|
|
2707
|
+
echo.push(` if echo == "items" {\n if let Some((_, v)) = payload.entries.iter().find(|(__k, _)| __k.as_str() == "items") {\n return Ok(v.clone());\n }\n }`);
|
|
2708
|
+
}
|
|
2859
2709
|
}
|
|
2860
|
-
|
|
2861
|
-
|
|
2862
|
-
//
|
|
2863
|
-
|
|
2864
|
-
|
|
2710
|
+
const prev = bySym.get(sym);
|
|
2711
|
+
if (prev !== undefined) {
|
|
2712
|
+
// #176/#183: a spec-fixed symbol MUST map to exactly ONE leaf. The same leaf in multiple roles shares
|
|
2713
|
+
// ONE transport — accumulate its echo branches. Two DIFFERENT catalog components → same symbol is a
|
|
2714
|
+
// codegen error (never silent).
|
|
2715
|
+
if (prev.catalog !== catalog)
|
|
2716
|
+
throw new GeneratorFailure("DUPLICATE_COMPONENT", `rust typed-native observe: leaf transport symbol '${sym}' resolves to TWO different catalog components ('${prev.catalog}' and '${catalog}') — a spec-fixed leaf symbol must map to ONE leaf (collision, fail-closed).`);
|
|
2717
|
+
for (const e of echo)
|
|
2718
|
+
if (!prev.echo.includes(e))
|
|
2719
|
+
prev.echo.push(e);
|
|
2720
|
+
continue;
|
|
2865
2721
|
}
|
|
2866
|
-
|
|
2867
|
-
|
|
2868
|
-
|
|
2869
|
-
|
|
2870
|
-
|
|
2722
|
+
bySym.set(sym, { catalog, async: isAsync, echo });
|
|
2723
|
+
}
|
|
2724
|
+
}
|
|
2725
|
+
for (const [sym, le] of bySym) {
|
|
2726
|
+
const fnKw = le.async ? "pub async fn" : "pub fn";
|
|
2727
|
+
const hasEcho = le.echo.length > 0;
|
|
2728
|
+
const echoBind = hasEcho ? "echo" : "_echo";
|
|
2729
|
+
const echoBlock = hasEcho ? `${le.echo.join("\n")}\n` : "";
|
|
2730
|
+
transportFns.push(`${fnKw} ${sym}(${hasEcho ? "payload" : "_payload"}: WireRow) -> Result<WireValue, BehaviorError> {
|
|
2731
|
+
let (is_err, err, ok, ${echoBind}) = next_scripted(${rustStrLit(le.catalog)}).ok_or_else(|| unknown_component(${rustStrLit(le.catalog)}))?;
|
|
2732
|
+
if is_err {
|
|
2733
|
+
return Err(leaf_failure(err));
|
|
2734
|
+
}
|
|
2871
2735
|
${echoBlock} Ok(value_to_wire(&ok.unwrap_or(Value::Null)))
|
|
2872
2736
|
}`);
|
|
2873
|
-
}
|
|
2874
2737
|
}
|
|
2875
2738
|
const arms = native
|
|
2876
2739
|
.map((c) => {
|