behavior-contracts 0.9.2 → 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 +18 -10
- 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-shared-go.d.ts.map +1 -1
- package/dist/generator/emit-shared-go.js +40 -19
- package/dist/generator/emit-shared-go.js.map +1 -1
- package/dist/generator/emit-shared-rust.d.ts.map +1 -1
- package/dist/generator/emit-shared-rust.js +50 -30
- package/dist/generator/emit-shared-rust.js.map +1 -1
- package/dist/generator/emit-shared-typescript.d.ts.map +1 -1
- package/dist/generator/emit-shared-typescript.js +26 -4
- package/dist/generator/emit-shared-typescript.js.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 +292 -420
- 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 +275 -382
- package/dist/generator/emit-typed-native-rust.js.map +1 -1
- package/dist/generator/native-expr.d.ts +7 -0
- package/dist/generator/native-expr.d.ts.map +1 -1
- package/dist/generator/native-expr.js +11 -0
- package/dist/generator/native-expr.js.map +1 -1
- package/dist/generator/straightline.d.ts +5 -0
- package/dist/generator/straightline.d.ts.map +1 -1
- package/dist/generator/straightline.js +1 -0
- package/dist/generator/straightline.js.map +1 -1
- package/dist/generator/typed.d.ts +17 -11
- package/dist/generator/typed.d.ts.map +1 -1
- package/dist/generator/typed.js +19 -12
- package/dist/generator/typed.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/plan.d.ts +7 -0
- package/dist/plan.d.ts.map +1 -1
- package/dist/plan.js +7 -2
- package/dist/plan.js.map +1 -1
- package/dist/primitives.d.ts +4 -3
- package/dist/primitives.d.ts.map +1 -1
- package/dist/primitives.js +8 -7
- package/dist/primitives.js.map +1 -1
- package/dist/provenance.d.ts +1 -1
- package/dist/provenance.d.ts.map +1 -1
- package/package.json +9 -1
|
@@ -2,7 +2,7 @@ import { GeneratorFailure } from "./core.js";
|
|
|
2
2
|
import { isControlGate, nodeWirePassthrough } from "../behavior.js";
|
|
3
3
|
import { rustStraightlineInternals } from "./emit-shared-rust.js";
|
|
4
4
|
import { rustTypedInternals } from "./emit-shared-rust-typed.js";
|
|
5
|
-
import { buildTypePlan, deriveTypeRef, findDecl,
|
|
5
|
+
import { buildTypePlan, deriveTypeRef, findDecl, guardedMapIntoIsCoverable, inputPortIsOptional, inputPortTypeRef } from "./typed.js";
|
|
6
6
|
import { concurrencyPlan, execPlan, analyzeSequentialOps, classifyExpr, nodeNarrowedPaths } from "./straightline.js";
|
|
7
7
|
import { NativeExprCompiler } from "./native-expr.js";
|
|
8
8
|
import { buildAsyncPlans } from "./async-plan.js";
|
|
@@ -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,40 +552,84 @@ ${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
|
-
|
|
595
|
-
|
|
609
|
+
if (plan.k === "map") {
|
|
610
|
+
// bc#181: typed map<V> → wire map, represented as a dynamic-keyed WireRow (there is NO WireMap type; a
|
|
611
|
+
// declared map<V> is the dynamic-keyed twin of a record — the READ side de-boxes a WireRow INTO map<V>
|
|
612
|
+
// the SAME way, emit-shared-debox `mapval`). Box EACH entry's VALUE recursively (box-once, no round-trip);
|
|
613
|
+
// keys carried as dynamic strings. BTreeMap<String,_> iterates in ascending key order, so the WireRow is
|
|
614
|
+
// deterministic (matching the rust typed map's canonical key order).
|
|
615
|
+
const k = `k${depth}`;
|
|
616
|
+
const v = `v${depth}`;
|
|
617
|
+
return `WireValue::Row(WireRow { entries: ${baseSrc}.into_iter().map(|(${k}, ${v})| (${k}, ${renderRustWireBox(plan.value, v, depth + 1)})).collect() })`;
|
|
618
|
+
}
|
|
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);
|
|
596
633
|
}
|
|
597
634
|
/** returnErrFail — the default de-box mismatch control flow: propagate the structured Error Value out of
|
|
598
635
|
* the enclosing runner (fail/retry componentRef results + map/fanout element de-box, which fails closed
|
|
@@ -699,81 +736,6 @@ function portFieldRustType(node, comp, plan, typedNodes, expected, where = "port
|
|
|
699
736
|
const c = compilePortNode(node, comp, plan, typedNodes, (h) => typedNodes.has(h), where, expected, opts);
|
|
700
737
|
return renderTypeRef(c.ref);
|
|
701
738
|
}
|
|
702
|
-
/**
|
|
703
|
-
* emitPortsStruct — the CONCRETE native ports struct for a componentRef node. Typed fields per the
|
|
704
|
-
* static port type, constructed directly. NO `impl PortReaderT` / by-name `port()` — the covered runner
|
|
705
|
-
* passes `&PortsNR…` to the concrete `node_*` method by direct generic instantiation, and the handler
|
|
706
|
-
* reads `ports.f_<field>` DIRECTLY. The struct derives Clone (a bc#87 parallel stage clones it into the
|
|
707
|
-
* per-worker dispatch). Every field is a NATIVE Rust type (bc#90 / runtime-free) — NO boxed `Value`.
|
|
708
|
-
*/
|
|
709
|
-
function emitPortsStruct(comp, node, asBinding, plan, typedNodes, narrowed) {
|
|
710
|
-
const name = portsStructName(comp.name, node.id);
|
|
711
|
-
const portNames = Object.keys(node.ports);
|
|
712
|
-
if (portNames.length === 0) {
|
|
713
|
-
return `// ${name} — native ports for node '${node.id}' (${node.component}); no ports.\n#[derive(Clone)]\npub struct ${name};`;
|
|
714
|
-
}
|
|
715
|
-
// a node WITH ports always resolves through the one port lowering, which needs the type plan + the
|
|
716
|
-
// prior-node map (both are supplied by every caller — narrow the optional params for the fields below).
|
|
717
|
-
if (plan === undefined || typedNodes === undefined) {
|
|
718
|
-
throw new GeneratorFailure("UNSUPPORTED_NODE_STRAIGHTLINE", `rust typed-native: ports struct for node '${node.id}' needs a type plan + prior-node map`);
|
|
719
|
-
}
|
|
720
|
-
// #170: the field TYPE reads the SAME lowering (incl. gate/guard narrowing) the init does, so a narrowed
|
|
721
|
-
// opt-in-required port is a non-opt field AND a non-opt initializer — they can never disagree.
|
|
722
|
-
// #173: the field TYPE is the DECLARED port type (portSchemas → inputPortTypeRef), materialized by the
|
|
723
|
-
// SAME compilePortTo the init uses — field and init read one lowering, so they cannot diverge.
|
|
724
|
-
const portOpts = asBinding !== undefined ? { asBinding, asBase: asBinding.name, narrowed } : narrowed !== undefined ? { narrowed } : undefined;
|
|
725
|
-
const types = portNames.map((p) => portFieldRustType(node.ports[p], comp, plan, typedNodes, inputPortTypeRef(node.portSchemas?.[p], plan), `port '${p}' of node '${node.id}'`, portOpts));
|
|
726
|
-
const fields = portNames
|
|
727
|
-
.map((p, i) => ` pub ${portFieldName(p)}: ${types[i]}, // ${JSON.stringify(p)}`)
|
|
728
|
-
.join("\n");
|
|
729
|
-
return `// ${name} — CONCRETE native ports for node '${node.id}' (${node.component}). Typed fields per the
|
|
730
|
-
// static port type; constructed directly (no Vec, no heap key strings, no per-port Value boxing). The
|
|
731
|
-
// handler reads the typed fields directly off this concrete struct — no by-name accessor.
|
|
732
|
-
#[derive(Clone)]
|
|
733
|
-
pub struct ${name} {
|
|
734
|
-
${fields}
|
|
735
|
-
}`;
|
|
736
|
-
}
|
|
737
|
-
/**
|
|
738
|
-
* emitMapPortsStructs — element ports struct + batch struct for a covered map node (CONCRETE). The batch
|
|
739
|
-
* struct carries the Vec of per-element CONCRETE ports structs (the handler reads them off the concrete
|
|
740
|
-
* struct — no by-name accessor, no key-value object).
|
|
741
|
-
*/
|
|
742
|
-
function emitMapPortsStructs(comp, node, typedNodes, plan) {
|
|
743
|
-
const m = node.map;
|
|
744
|
-
const name = portsStructName(comp.name, node.id);
|
|
745
|
-
const batch = `${name}Batch`;
|
|
746
|
-
// #108: element ports may read the `$as` binding — resolve the over element type for native typing.
|
|
747
|
-
const { elemRef } = mapOverElemInfo(comp, node, typedNodes, plan);
|
|
748
|
-
const asBinding = { name: m.as, ref: elemRef, plan };
|
|
749
|
-
// #170: a guarded map (`when(ne($e.key,null))`) proves the element key non-null in kept elements — narrow it.
|
|
750
|
-
const elemStruct = emitPortsStruct(comp, { id: node.id, component: m.component, ports: m.ports, portSchemas: m.portSchemas }, asBinding, plan, typedNodes, nodeNarrowedPaths(comp, node));
|
|
751
|
-
return `${elemStruct}
|
|
752
|
-
|
|
753
|
-
// ${batch} — CONCRETE batched ports for map '${node.id}': the Vec of per-element CONCRETE ports structs
|
|
754
|
-
// (a Vec<${name}>, NOT a generic key-value container). The consumer's batched handler reads the typed
|
|
755
|
-
// element ports off the concrete struct directly.
|
|
756
|
-
#[derive(Clone)]
|
|
757
|
-
pub struct ${batch} {
|
|
758
|
-
pub items: Vec<${name}>,
|
|
759
|
-
}`;
|
|
760
|
-
}
|
|
761
|
-
/** emitFanoutPortsStructs (v3, rust twin) — per-id element ports struct + batch struct for a fanout node. */
|
|
762
|
-
function emitFanoutPortsStructs(comp, node, typedNodes, plan) {
|
|
763
|
-
const f = node.fanout;
|
|
764
|
-
const name = portsStructName(comp.name, node.id);
|
|
765
|
-
const batch = `${name}Batch`;
|
|
766
|
-
const { elemRef } = fanoutOverElemInfo(comp, node, typedNodes, plan);
|
|
767
|
-
const asBinding = { name: f.as, ref: elemRef, plan };
|
|
768
|
-
const elemStruct = emitPortsStruct(comp, { id: node.id, component: f.component, ports: f.ports, portSchemas: f.portSchemas }, asBinding, plan, typedNodes);
|
|
769
|
-
return `${elemStruct}
|
|
770
|
-
|
|
771
|
-
// ${batch} — CONCRETE batched ports for fanout '${node.id}': the Vec of per-id CONCRETE ports structs.
|
|
772
|
-
#[derive(Clone)]
|
|
773
|
-
pub struct ${batch} {
|
|
774
|
-
pub items: Vec<${name}>,
|
|
775
|
-
}`;
|
|
776
|
-
}
|
|
777
739
|
// ── native expression compiler backend (#108) — cond `if` / map `when` / cond branches (Rust) ────────
|
|
778
740
|
//
|
|
779
741
|
// The runtime-free native expression compiler (native-expr.ts) mirrors run_behavior's cond/guard with
|
|
@@ -811,6 +773,9 @@ function makeRustExprBackend(resolveHead, plan) {
|
|
|
811
773
|
wireType: () => renderTypeRef({ kind: "value" }),
|
|
812
774
|
// bc#156/#160: box a value[] element into the opaque BC wire via the ONE box SSoT (owned element expr).
|
|
813
775
|
wireBox: (item) => renderRustWireBox(buildWirePlan(item.ref, { from: "top" }, { model: "port", field: "port", plan }, "in"), item.expr),
|
|
776
|
+
// bc#178: box EACH element of the owned typed Vec into an arr<value> (Vec<WireValue>) — the same
|
|
777
|
+
// per-element box renderer as wireBox's list case, applied over the referenced array (box-once/element).
|
|
778
|
+
wireBoxEachElem: (srcExpr, elemRef) => `${srcExpr}.into_iter().map(|__be| ${renderRustWireBox(buildWirePlan(elemRef, { from: "elem" }, { model: "port", field: "port", plan }, "in"), "__be")}).collect::<Vec<${renderTypeRef({ kind: "value" })}>>()`,
|
|
814
779
|
scalarType: (s) => rustScalar(s),
|
|
815
780
|
strLit: (s) => `${rustStrLit(s)}.to_string()`,
|
|
816
781
|
boolLit: (b) => (b ? "true" : "false"),
|
|
@@ -1272,13 +1237,14 @@ function coveredMapNode(n, bodyIds, comp) {
|
|
|
1272
1237
|
if (n === null || typeof n !== "object" || !("map" in n))
|
|
1273
1238
|
return false;
|
|
1274
1239
|
const m = n.map;
|
|
1275
|
-
// #108 (rust twin of the go predicate): a guarded map (`when`) IS covered with NO `into`. #177: a
|
|
1276
|
-
// guarded map WITH `into` is covered
|
|
1277
|
-
//
|
|
1278
|
-
//
|
|
1279
|
-
//
|
|
1280
|
-
//
|
|
1281
|
-
|
|
1240
|
+
// #108 (rust twin of the go predicate): a guarded map (`when`) IS covered with NO `into`. #177/#182: a
|
|
1241
|
+
// guarded map WITH `into` is covered when the guard-skipped element has a well-defined skip value — the
|
|
1242
|
+
// into field is OPT (skip → None, #177) OR relationKind:connection (skip → the empty connection
|
|
1243
|
+
// {items:[],cursor:null}, #182). Byte-equal to run_behavior applyInto (opt-into → null / connection-into
|
|
1244
|
+
// → unproducedValue("connection")). A REQUIRED non-connection into → run_behavior FAILS MISSING_PROP on a
|
|
1245
|
+
// skipped element, so fail-close is byte-equal. over element type must be statically resolvable: prior-node
|
|
1246
|
+
// arr field, or an input array port carrying `elemType` (BC does not infer — consumer-interface C3).
|
|
1247
|
+
if (m.when !== undefined && m.into !== undefined && !guardedMapIntoIsCoverable(n, comp))
|
|
1282
1248
|
return false;
|
|
1283
1249
|
if (m.policy !== undefined && m.policy !== "fail")
|
|
1284
1250
|
return false;
|
|
@@ -1547,21 +1513,20 @@ function emitInStruct(comp, plan) {
|
|
|
1547
1513
|
// number literal), and a genuinely-dynamic port fails closed. There is no boxed-Value fallback on the
|
|
1548
1514
|
// covered read plane.
|
|
1549
1515
|
/**
|
|
1550
|
-
*
|
|
1551
|
-
*
|
|
1552
|
-
*
|
|
1553
|
-
*
|
|
1554
|
-
*
|
|
1555
|
-
*
|
|
1556
|
-
*
|
|
1557
|
-
* a boxed escape would re-introduce the bc-runtime coupling this module removes). `fieldRustType` is the
|
|
1558
|
-
* 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.
|
|
1559
1523
|
*/
|
|
1560
|
-
function
|
|
1524
|
+
function emitPortWireField(pn, expr, comp, plan, typedNodes, isPrior, expected, opts) {
|
|
1561
1525
|
const c = compilePortNode(expr, comp, plan, typedNodes, isPrior, `port '${pn}'`, expected, opts);
|
|
1562
1526
|
if (c.stmts.length > 0)
|
|
1563
|
-
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
|
|
1564
|
-
|
|
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})`;
|
|
1565
1530
|
}
|
|
1566
1531
|
// ── the combined runner (STRUCT-returning; INLINE sequential; native ports in; concrete row out) ──
|
|
1567
1532
|
function rustScalar(s) {
|
|
@@ -1714,7 +1679,6 @@ function emitNativeRawRunner(comp, plan, ap, leaf) {
|
|
|
1714
1679
|
const node = comp.body[i];
|
|
1715
1680
|
const meta = metas[i];
|
|
1716
1681
|
const s = sanitize(node.id);
|
|
1717
|
-
const structName = portsStructName(comp.name, node.id);
|
|
1718
1682
|
const portNames = Object.keys(node.ports);
|
|
1719
1683
|
const ref = typedNodes.get(node.id);
|
|
1720
1684
|
lines.push(` // ── op '${node.id}' (${node.component}${node.relationKind ? ", relationKind:" + node.relationKind : ""}${node.parent ? ", parent:" + node.parent : ""}) ──`);
|
|
@@ -1753,20 +1717,17 @@ function emitNativeRawRunner(comp, plan, ap, leaf) {
|
|
|
1753
1717
|
indent += " ";
|
|
1754
1718
|
}
|
|
1755
1719
|
}
|
|
1756
|
-
const inits = [];
|
|
1757
1720
|
const narrowed = nodeNarrowedPaths(comp, node);
|
|
1758
|
-
|
|
1759
|
-
inits.push(emitPortInit(pn, node.ports[pn], comp, plan, typedNodes, (h) => priorNodeAt(h, k), inputPortTypeRef(node.portSchemas?.[pn], plan), { narrowed }));
|
|
1760
|
-
}
|
|
1721
|
+
const fields = portNames.map((pn) => emitPortWireField(pn, node.ports[pn], comp, plan, typedNodes, (h) => priorNodeAt(h, k), inputPortTypeRef(node.portSchemas?.[pn], plan), { narrowed }));
|
|
1761
1722
|
// bc#97: derived per-node await — this point-read's future is awaited HERE (its result-consumption
|
|
1762
1723
|
// point) iff THIS node's terminal handler is async. A sync handler in the same async runner is called
|
|
1763
1724
|
// directly (no `.await`). The runner being `async fn` does not force every call site to await.
|
|
1764
1725
|
const awaitSfx = ap.nodeIsAsync(node.id) ? ".await" : "";
|
|
1765
|
-
// DIRECT leaf transport call: the resolved op-agnostic symbol, the node's
|
|
1766
|
-
//
|
|
1767
|
-
//
|
|
1768
|
-
const call = `${resolveLeafSymbol(node.component, leaf)}(${
|
|
1769
|
-
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)};`);
|
|
1770
1731
|
// uniform seam: every covered node returns a single result WIRE; the inline de-box (renderResultDeBox)
|
|
1771
1732
|
// classifies it against the STATICALLY declared result type and produces the structured Error Value on a
|
|
1772
1733
|
// mismatch (byte-equal codes to run_behavior's outType check, so ≡ holds). The wire's concrete type is
|
|
@@ -1866,7 +1827,6 @@ function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes
|
|
|
1866
1827
|
for (const i of refMembers) {
|
|
1867
1828
|
const node = comp.body[i];
|
|
1868
1829
|
const s = sanitize(node.id);
|
|
1869
|
-
const structName = portsStructName(comp.name, node.id);
|
|
1870
1830
|
const gated = node.parent !== undefined && priorNodeAt(node.parent, atPos);
|
|
1871
1831
|
// #125: a member gated by a PRIOR-stage control gate (`parent=gate, bindField:"ok"`). Its bindField is
|
|
1872
1832
|
// the gate's skip sentinel, NOT a relation data key — the gate is typeless (no struct field to read).
|
|
@@ -1879,7 +1839,7 @@ function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes
|
|
|
1879
1839
|
// it is a plain local inside the produced block — NOT a stage-scoped mut (nothing captures it) and no
|
|
1880
1840
|
// dead None init. A control-gate parent needs no bound at all (produced_<gate> already carries the skip).
|
|
1881
1841
|
if (gated) {
|
|
1882
|
-
lines.push(` let mut
|
|
1842
|
+
lines.push(` let mut payload_${s}: Option<WireRow> = None;`);
|
|
1883
1843
|
lines.push(`${ind}if produced_${sanitize(node.parent)}.get() {`);
|
|
1884
1844
|
closers.unshift(`${ind}}`);
|
|
1885
1845
|
ind += " ";
|
|
@@ -1898,16 +1858,13 @@ function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes
|
|
|
1898
1858
|
ind += " ";
|
|
1899
1859
|
}
|
|
1900
1860
|
}
|
|
1901
|
-
const inits = [];
|
|
1902
1861
|
const narrowed = nodeNarrowedPaths(comp, node);
|
|
1903
|
-
|
|
1904
|
-
inits.push(emitPortInit(pn, node.ports[pn], comp, plan, typedNodes, (h) => priorNodeAt(h, atPos), inputPortTypeRef(node.portSchemas?.[pn], plan), { narrowed }));
|
|
1905
|
-
}
|
|
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 }));
|
|
1906
1863
|
if (gated) {
|
|
1907
|
-
lines.push(`${ind}
|
|
1864
|
+
lines.push(`${ind}payload_${s} = Some(${rustPayloadRow(fields)});`);
|
|
1908
1865
|
}
|
|
1909
1866
|
else {
|
|
1910
|
-
lines.push(`${ind}let
|
|
1867
|
+
lines.push(`${ind}let payload_${s}: Option<WireRow> = Some(${rustPayloadRow(fields)});`);
|
|
1911
1868
|
}
|
|
1912
1869
|
for (const c of closers)
|
|
1913
1870
|
lines.push(c);
|
|
@@ -1929,7 +1886,7 @@ function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes
|
|
|
1929
1886
|
lines.push(` let mut ${jobsVar}: Vec<usize> = Vec::new();`);
|
|
1930
1887
|
refMembers.forEach((i, slot) => {
|
|
1931
1888
|
const s = sanitize(comp.body[i].id);
|
|
1932
|
-
lines.push(` if
|
|
1889
|
+
lines.push(` if payload_${s}.is_some() { ${jobsVar}.push(${slot}); }`);
|
|
1933
1890
|
});
|
|
1934
1891
|
lines.push(` let cursor = std::sync::atomic::AtomicUsize::new(0);`);
|
|
1935
1892
|
lines.push(` let workers = ${boundN}usize.min(${jobsVar}.len());`);
|
|
@@ -1943,11 +1900,12 @@ function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes
|
|
|
1943
1900
|
refMembers.forEach((i, slot) => {
|
|
1944
1901
|
const node = comp.body[i];
|
|
1945
1902
|
const s = sanitize(node.id);
|
|
1946
|
-
// DIRECT leaf transport call —
|
|
1947
|
-
// `bound` (BC's internal produced/skip gate is already applied in
|
|
1948
|
-
|
|
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)`;
|
|
1949
1907
|
lines.push(` ${slot} => {`);
|
|
1950
|
-
lines.push(` let
|
|
1908
|
+
lines.push(` let payload = payload_${s}.as_ref().expect("runnable member has ports").clone();`);
|
|
1951
1909
|
lines.push(` let row = ${call};`);
|
|
1952
1910
|
lines.push(` *slot_${s}.lock().unwrap() = Some(row);`);
|
|
1953
1911
|
lines.push(` }`);
|
|
@@ -1963,7 +1921,7 @@ function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes
|
|
|
1963
1921
|
const meta = metas[i];
|
|
1964
1922
|
const s = sanitize(node.id);
|
|
1965
1923
|
const ref = typedNodes.get(node.id);
|
|
1966
|
-
lines.push(` if
|
|
1924
|
+
lines.push(` if payload_${s}.is_some() {`);
|
|
1967
1925
|
lines.push(` let out_${s} = slot_${s}.lock().unwrap().take().expect("runnable member wrote its slot");`);
|
|
1968
1926
|
if (meta.policy === "continue") {
|
|
1969
1927
|
// continue: a failed member (leaf failure OR de-box mismatch) commits no Port (defensive — covered
|
|
@@ -2017,9 +1975,7 @@ isAsync = false) {
|
|
|
2017
1975
|
// skipped elements instead. Byte-equal to run_behavior's applyInto keep-with-null.
|
|
2018
1976
|
const keepWithNull = hasGuard && hasInto;
|
|
2019
1977
|
const s = sanitize(node.id);
|
|
2020
|
-
const
|
|
2021
|
-
const batch = `${structName}Batch`;
|
|
2022
|
-
const leafSym = resolveLeafSymbol(m.component, leaf);
|
|
1978
|
+
const leafSym = resolveLeafSymbol(m.component, leaf, m.leafSymbol);
|
|
2023
1979
|
// #108: over element type + the OWNED over-Vec expression (prior-node arr OR input array w/ elemType).
|
|
2024
1980
|
const { elemRef: overElemRef, overExpr, optArr: overOptArr } = mapOverElemInfo(comp, node, typedNodes, plan);
|
|
2025
1981
|
const elemMat = mapElemMaterializerName(comp.name, node.id);
|
|
@@ -2033,19 +1989,32 @@ isAsync = false) {
|
|
|
2033
1989
|
// mismatch fails closed regardless of elementPolicy (matching the interpreter's whole-node outType throw).
|
|
2034
1990
|
const elemDeBoxRef = mapElemRowRef(node, elemArrRef, plan);
|
|
2035
1991
|
const renderElemDeBox = (il) => renderResultDeBox(elemDeBoxRef, `er_${s}`, node.id, plan, il, returnErrFail, nodeWirePassthrough(node));
|
|
2036
|
-
//
|
|
2037
|
-
|
|
2038
|
-
|
|
2039
|
-
|
|
1992
|
+
// #177/#182 keep-with-skip-value: the into value for a guard-skipped element is driven by relationKind,
|
|
1993
|
+
// NOT by opt-ness (matching run_behavior applyInto, which fills a connection into with the empty
|
|
1994
|
+
// connection UNCONDITIONALLY on relationKind==="connection"):
|
|
1995
|
+
// - connection into → the connection-zero in the field's typed rep (same shape emitProducedAwareValue
|
|
1996
|
+
// uses for a skipped connection node): a required `Conn` field → `Conn::default()`, an OPT
|
|
1997
|
+
// `Option<Conn>` field → `Some(Conn::default())` (empty connection, NOT None). `Conn::default()`'s
|
|
1998
|
+
// derived Default serializes to {items:[],cursor:null} (#182).
|
|
1999
|
+
// - non-connection into → opt → None = null (#177 keep-with-null; unchanged).
|
|
2000
|
+
const intoSkipDefault = m.relationKind === "connection"
|
|
2001
|
+
? elemDeBoxRef.kind === "opt"
|
|
2002
|
+
? `Some(${renderTypeRef(elemDeBoxRef.inner)}::default())`
|
|
2003
|
+
: `${renderTypeRef(elemDeBoxRef)}::default()`
|
|
2004
|
+
: elemDeBoxRef.kind === "opt"
|
|
2005
|
+
? "None"
|
|
2006
|
+
: `${renderTypeRef(elemDeBoxRef)}::default()`;
|
|
2007
|
+
// the per-element boxed port entries (#183) — the SAME box SSoT as a point node, over the $as element.
|
|
2008
|
+
const portFields = () => {
|
|
2040
2009
|
const asBinding = { name: asName, ref: overElemRef, plan };
|
|
2041
2010
|
// #170: a guarded map narrows its `when(ne($e.key,null))`-proven element key non-null in kept elements.
|
|
2042
2011
|
const narrowed = nodeNarrowedPaths(comp, node);
|
|
2043
|
-
|
|
2044
|
-
inits.push(emitPortInit(pn, m.ports[pn], comp, plan, typedNodes, priorHere, inputPortTypeRef(m.portSchemas?.[pn], plan), { asBinding, asBase: `oel_${s}`, narrowed }));
|
|
2045
|
-
}
|
|
2046
|
-
out.push(`${il}let ep_${s} = ${structName} { ${inits.join(", ")} };`);
|
|
2047
|
-
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 }));
|
|
2048
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())};`];
|
|
2049
2018
|
// #108 guard: compile `when` to a native bool over an element-scoped resolveHead ($as element value,
|
|
2050
2019
|
// prior node, input port). mkGuard returns the compiled {stmts, expr} (or null when unguarded); the
|
|
2051
2020
|
// keep-with-null batched path consumes it directly to branch instead of skipping.
|
|
@@ -2088,14 +2057,14 @@ isAsync = false) {
|
|
|
2088
2057
|
// zips its next deboxed row, a skipped element gets into=None. Byte-equal to run_behavior: batched
|
|
2089
2058
|
// keptIdx-aligned collect + applyInto (skipped element unaugmented → opt-into null).
|
|
2090
2059
|
const g = mkGuard();
|
|
2091
|
-
lines.push(`${indent}let mut items_${s}: Vec
|
|
2060
|
+
lines.push(`${indent}let mut items_${s}: Vec<WireValue> = Vec::with_capacity(over_${s}.len());`);
|
|
2092
2061
|
lines.push(`${indent}let mut keep_${s}: Vec<bool> = Vec::with_capacity(over_${s}.len());`);
|
|
2093
2062
|
lines.push(`${indent}for oel_${s} in over_${s}.iter() {`);
|
|
2094
2063
|
for (const st of g.stmts)
|
|
2095
2064
|
lines.push(`${indent} ${st}`);
|
|
2096
2065
|
lines.push(`${indent} let __keep = ${rustStripOuterParens(g.expr)};`);
|
|
2097
2066
|
lines.push(`${indent} if __keep {`);
|
|
2098
|
-
for (const l of
|
|
2067
|
+
for (const l of buildBatchElem(indent + " "))
|
|
2099
2068
|
lines.push(l);
|
|
2100
2069
|
lines.push(`${indent} items_${s}.push(ep_${s});`);
|
|
2101
2070
|
lines.push(`${indent} keep_${s}.push(true);`);
|
|
@@ -2106,15 +2075,17 @@ isAsync = false) {
|
|
|
2106
2075
|
lines.push(`${indent}let mut decs_${s}: Vec<${renderTypeRef(elemDeBoxRef)}> = Vec::with_capacity(items_${s}.len());`);
|
|
2107
2076
|
lines.push(`${indent}if !items_${s}.is_empty() {`);
|
|
2108
2077
|
lines.push(`${indent} let want_${s} = items_${s}.len();`);
|
|
2109
|
-
|
|
2110
|
-
|
|
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} {`);
|
|
2111
2081
|
lines.push(`${indent} Ok(r) => r,`);
|
|
2112
2082
|
lines.push(`${indent} Err(e) => return Err(op_failed(${rustStrLit(node.id)}, "fail", e)),`);
|
|
2113
2083
|
lines.push(`${indent} };`);
|
|
2114
|
-
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} {`);
|
|
2115
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})));`);
|
|
2116
2087
|
lines.push(`${indent} }`);
|
|
2117
|
-
lines.push(`${indent} for er_${s} in
|
|
2088
|
+
lines.push(`${indent} for er_${s} in rows_${s}.into_iter() {`);
|
|
2118
2089
|
lines.push(`${indent} let dec_${s} = ${renderElemDeBox(`${indent} `)};`);
|
|
2119
2090
|
lines.push(`${indent} decs_${s}.push(dec_${s});`);
|
|
2120
2091
|
lines.push(`${indent} }`);
|
|
@@ -2125,19 +2096,19 @@ isAsync = false) {
|
|
|
2125
2096
|
lines.push(`${indent} let dec_${s} = decs_iter_${s}.next().expect("aligned kept row");`);
|
|
2126
2097
|
lines.push(`${indent} built_${s}.push(${elemMat}(oel_${s}, dec_${s}));`);
|
|
2127
2098
|
lines.push(`${indent} } else {`);
|
|
2128
|
-
lines.push(`${indent} built_${s}.push(${elemMat}(oel_${s},
|
|
2099
|
+
lines.push(`${indent} built_${s}.push(${elemMat}(oel_${s}, ${intoSkipDefault}));`);
|
|
2129
2100
|
lines.push(`${indent} }`);
|
|
2130
2101
|
lines.push(`${indent}}`);
|
|
2131
2102
|
}
|
|
2132
2103
|
else if (batched) {
|
|
2133
2104
|
// build kept-element ports (+ kept over elements for into). Batched into is never guarded (rejected).
|
|
2134
|
-
lines.push(`${indent}let mut items_${s}: Vec
|
|
2105
|
+
lines.push(`${indent}let mut items_${s}: Vec<WireValue> = Vec::with_capacity(over_${s}.len());`);
|
|
2135
2106
|
if (hasInto)
|
|
2136
2107
|
lines.push(`${indent}let mut kept_${s}: Vec<${renderTypeRef(overElemRef)}> = Vec::with_capacity(over_${s}.len());`);
|
|
2137
2108
|
lines.push(`${indent}for oel_${s} in over_${s}.iter() {`);
|
|
2138
2109
|
for (const l of emitGuard(indent + " "))
|
|
2139
2110
|
lines.push(l);
|
|
2140
|
-
for (const l of
|
|
2111
|
+
for (const l of buildBatchElem(indent + " "))
|
|
2141
2112
|
lines.push(l);
|
|
2142
2113
|
lines.push(`${indent} items_${s}.push(ep_${s});`);
|
|
2143
2114
|
if (hasInto)
|
|
@@ -2145,21 +2116,19 @@ isAsync = false) {
|
|
|
2145
2116
|
lines.push(`${indent}}`);
|
|
2146
2117
|
lines.push(`${indent}if !items_${s}.is_empty() {`);
|
|
2147
2118
|
lines.push(`${indent} let want_${s} = items_${s}.len();`);
|
|
2148
|
-
|
|
2149
|
-
|
|
2150
|
-
// from the removed trait method; only the call target changes). Returns the aligned per-element wires
|
|
2151
|
-
// (Vec<Wire>). No `bound` (batched maps carry none).
|
|
2152
|
-
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} {`);
|
|
2153
2121
|
lines.push(`${indent} Ok(r) => r,`);
|
|
2154
2122
|
lines.push(`${indent} Err(e) => return Err(op_failed(${rustStrLit(node.id)}, "fail", e)),`);
|
|
2155
2123
|
lines.push(`${indent} };`);
|
|
2156
|
-
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} {`);
|
|
2157
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})));`);
|
|
2158
2127
|
lines.push(`${indent} }`);
|
|
2159
2128
|
if (hasInto) {
|
|
2160
2129
|
// zip the aligned per-element WIRES onto each KEPT over element: de-box the element wire strictly
|
|
2161
2130
|
// (into the `into` field's type) then materialize the augmented element.
|
|
2162
|
-
lines.push(`${indent} let mut rows_iter_${s} =
|
|
2131
|
+
lines.push(`${indent} let mut rows_iter_${s} = rows_${s}.into_iter();`);
|
|
2163
2132
|
lines.push(`${indent} for over_el_${s} in kept_${s}.iter() {`);
|
|
2164
2133
|
lines.push(`${indent} let er_${s} = rows_iter_${s}.next().expect("aligned batch row");`);
|
|
2165
2134
|
lines.push(`${indent} let dec_${s} = ${renderElemDeBox(`${indent} `)};`);
|
|
@@ -2168,7 +2137,7 @@ isAsync = false) {
|
|
|
2168
2137
|
}
|
|
2169
2138
|
else {
|
|
2170
2139
|
// no-into: de-box each aligned per-element wire DIRECTLY into the element (result = kept elements).
|
|
2171
|
-
lines.push(`${indent} for er_${s} in
|
|
2140
|
+
lines.push(`${indent} for er_${s} in rows_${s}.into_iter() {`);
|
|
2172
2141
|
lines.push(`${indent} let el_${s} = ${renderElemDeBox(`${indent} `)};`);
|
|
2173
2142
|
lines.push(`${indent} built_${s}.push(el_${s});`);
|
|
2174
2143
|
lines.push(`${indent} }`);
|
|
@@ -2178,18 +2147,18 @@ isAsync = false) {
|
|
|
2178
2147
|
else {
|
|
2179
2148
|
// #93 shape 2 / #108: NON-batched map — dispatch ONCE PER KEPT ELEMENT.
|
|
2180
2149
|
lines.push(`${indent}for oel_${s} in over_${s}.iter() {`);
|
|
2181
|
-
// #177 keep-with-
|
|
2182
|
-
// to run_behavior's applyInto
|
|
2183
|
-
|
|
2150
|
+
// #177/#182 keep-with-skip-value: a guard-skipped element is KEPT with into=intoSkipDefault (None /
|
|
2151
|
+
// Conn::default()) instead of dropped — byte-equal to run_behavior's applyInto (opt-into → null /
|
|
2152
|
+
// connection-into → empty connection).
|
|
2153
|
+
const nonBatchedSkip = keepWithNull ? `built_${s}.push(${elemMat}(oel_${s}, ${intoSkipDefault})); continue;` : "continue;";
|
|
2184
2154
|
for (const l of emitGuard(indent + " ", nonBatchedSkip))
|
|
2185
2155
|
lines.push(l);
|
|
2186
|
-
for (const l of
|
|
2156
|
+
for (const l of buildPayloadElem(indent + " "))
|
|
2187
2157
|
lines.push(l);
|
|
2188
2158
|
// Element Error Policy (scp-error.md): `skip` drops the failing element and proceeds (order is
|
|
2189
2159
|
// preserved; the leaf keeps the Error Value it produced). `error` (default) promotes the element
|
|
2190
|
-
// Failure to the map's Component Failure
|
|
2191
|
-
|
|
2192
|
-
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} {`);
|
|
2193
2162
|
lines.push(`${indent} Ok(r) => r,`);
|
|
2194
2163
|
if (m.elementPolicy === "skip") {
|
|
2195
2164
|
lines.push(`${indent} Err(_) => continue,`);
|
|
@@ -2226,9 +2195,7 @@ function emitFanoutArm(comp, node, atPos, typedNodes, plan, priorNodeAt, leaf, i
|
|
|
2226
2195
|
const f = node.fanout;
|
|
2227
2196
|
const awaitSfx = isAsync ? ".await" : "";
|
|
2228
2197
|
const s = sanitize(node.id);
|
|
2229
|
-
const
|
|
2230
|
-
const batch = `${structName}Batch`;
|
|
2231
|
-
const leafSym = resolveLeafSymbol(f.component, leaf);
|
|
2198
|
+
const leafSym = resolveLeafSymbol(f.component, leaf, f.leafSymbol);
|
|
2232
2199
|
const connRef = typedNodes.get(node.id);
|
|
2233
2200
|
const elemRef = fanoutItemsElemRef(node, connRef, plan);
|
|
2234
2201
|
const elemName = renderTypeRef(elemRef);
|
|
@@ -2243,13 +2210,11 @@ function emitFanoutArm(comp, node, atPos, typedNodes, plan, priorNodeAt, leaf, i
|
|
|
2243
2210
|
if (!dkField || dkField.type.kind !== "scalar" || dkField.type.scalar !== "string")
|
|
2244
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}'.`);
|
|
2245
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.
|
|
2246
2214
|
const buildPorts = (il) => {
|
|
2247
|
-
const inits = [];
|
|
2248
2215
|
const asBinding = { name: asName, ref: overElemRef, plan };
|
|
2249
|
-
|
|
2250
|
-
|
|
2251
|
-
}
|
|
2252
|
-
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(", ")}] });`];
|
|
2253
2218
|
};
|
|
2254
2219
|
const lines = [];
|
|
2255
2220
|
const closers = [];
|
|
@@ -2262,7 +2227,7 @@ function emitFanoutArm(comp, node, atPos, typedNodes, plan, priorNodeAt, leaf, i
|
|
|
2262
2227
|
}
|
|
2263
2228
|
lines.push(`${indent}let over_${s} = ${rustBindOverExpr(overExpr, overOptArr)};`);
|
|
2264
2229
|
lines.push(`${indent}let mut built_${s}: Vec<${elemName}> = Vec::new();`);
|
|
2265
|
-
lines.push(`${indent}let mut pi_${s}: Vec
|
|
2230
|
+
lines.push(`${indent}let mut pi_${s}: Vec<WireValue> = Vec::with_capacity(over_${s}.len());`);
|
|
2266
2231
|
lines.push(`${indent}for oel_${s} in over_${s}.iter() {`);
|
|
2267
2232
|
for (const l of buildPorts(indent + " "))
|
|
2268
2233
|
lines.push(l);
|
|
@@ -2270,28 +2235,27 @@ function emitFanoutArm(comp, node, atPos, typedNodes, plan, priorNodeAt, leaf, i
|
|
|
2270
2235
|
lines.push(`${indent}}`);
|
|
2271
2236
|
lines.push(`${indent}if !pi_${s}.is_empty() {`);
|
|
2272
2237
|
lines.push(`${indent} let want_${s} = pi_${s}.len();`);
|
|
2273
|
-
|
|
2274
|
-
//
|
|
2275
|
-
|
|
2276
|
-
// (Vec<Option<Wire>> — None = a DANGLING id). No `bound`.
|
|
2277
|
-
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} {`);
|
|
2278
2241
|
lines.push(`${indent} Ok(r) => r,`);
|
|
2279
2242
|
lines.push(`${indent} Err(e) => return Err(op_failed(${rustStrLit(node.id)}, "fail", e)),`);
|
|
2280
2243
|
lines.push(`${indent} };`);
|
|
2281
|
-
|
|
2282
|
-
// de-boxed strictly INLINE (a de-box mismatch fails closed). A DANGLING id is
|
|
2283
|
-
// (empty dedupeKey), which the dangling drop excludes.
|
|
2284
|
-
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} {`);
|
|
2285
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})));`);
|
|
2286
2249
|
lines.push(`${indent} }`);
|
|
2287
2250
|
// ── THE ONE dedupe/drop (mirrors fanoutDedupDrop verbatim): first-seen dedupe by dedupeKey field;
|
|
2288
2251
|
// drop dangling (empty dedupeKey ≡ interpreter's null/absent-key body); implicitSource strip is
|
|
2289
2252
|
// structural (the elem type already omits it). cursor is always None (connection wrap).
|
|
2290
2253
|
lines.push(`${indent} let mut seen_${s}: std::collections::HashSet<String> = std::collections::HashSet::new();`);
|
|
2291
|
-
lines.push(`${indent} for
|
|
2292
|
-
lines.push(`${indent} let el_${s}: ${elemName} =
|
|
2293
|
-
lines.push(`${indent}
|
|
2294
|
-
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))}`);
|
|
2295
2259
|
lines.push(`${indent} };`);
|
|
2296
2260
|
lines.push(`${indent} let key_${s} = el_${s}.${dkRust}.clone();`);
|
|
2297
2261
|
if (f.drop === "dangling") {
|
|
@@ -2460,56 +2424,29 @@ fn leaf_failure(message: impl Into<String>) -> BehaviorError {
|
|
|
2460
2424
|
BehaviorError::new("LEAF_FAILURE", message)
|
|
2461
2425
|
}`;
|
|
2462
2426
|
// ── module assembly ──────────────────────────────────────────────────────────────────
|
|
2463
|
-
/** isCrossPackageSharedNode (#165, rust twin of the go predicate) — a node whose ports struct CROSSES the
|
|
2464
|
-
* leaf-transport boundary as a whole value (the batch ports struct passed to the transport), so under
|
|
2465
|
-
* --shared-types-import it must live in the SHARED crate/module (else the transport crate → covered crate
|
|
2466
|
-
* import cycle). Batched maps + fanouts pass a batch struct; every other node passes only primitive port
|
|
2467
|
-
* fields, so its ports struct stays local. The SINGLE predicate emit() (skip-local) and
|
|
2468
|
-
* {@link rustSharedWireTypesModule} (emit-there) both use — they never disagree (SSoT). */
|
|
2469
|
-
function isCrossPackageSharedNode(n) {
|
|
2470
|
-
return "fanout" in n || ("map" in n && n.map.batched === true);
|
|
2471
|
-
}
|
|
2472
2427
|
/**
|
|
2473
2428
|
* rustSharedWireTypesModule (#165, rust twin of goSharedWireTypesPackage) — the BC-GENERATED shared module
|
|
2474
2429
|
* content emitted when the covered module is generated with --shared-types-import. Carries the SAME wire seam
|
|
2475
2430
|
* the covered module emits in-crate when the flag is absent (Probe/NumProbe + WireValue/WireRow/WireList +
|
|
2476
|
-
* the probe classifiers) so a separate leaf-transport crate can
|
|
2477
|
-
* module reference
|
|
2478
|
-
*
|
|
2479
|
-
*
|
|
2480
|
-
*
|
|
2481
|
-
|
|
2482
|
-
* lib.rs (a separate crate) or a module. `pub use` re-exports keep every name reachable unqualified. */
|
|
2483
|
-
export function rustSharedWireTypesModule(ir) {
|
|
2484
|
-
const portsStructs = [];
|
|
2485
|
-
if (ir !== undefined) {
|
|
2486
|
-
const components = ir.components;
|
|
2487
|
-
const plan = buildTypePlan(ir);
|
|
2488
|
-
for (const c of components.filter(isNativeRaw)) {
|
|
2489
|
-
const typedNodes = buildTypedNodes(c, plan);
|
|
2490
|
-
for (const n of c.body) {
|
|
2491
|
-
if (!isCrossPackageSharedNode(n))
|
|
2492
|
-
continue;
|
|
2493
|
-
portsStructs.push("fanout" in n ? emitFanoutPortsStructs(c, n, typedNodes, plan) : emitMapPortsStructs(c, n, typedNodes, plan));
|
|
2494
|
-
}
|
|
2495
|
-
}
|
|
2496
|
-
}
|
|
2497
|
-
const portsSection = portsStructs.length
|
|
2498
|
-
? `\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")}`
|
|
2499
|
-
: "";
|
|
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() {
|
|
2500
2437
|
return `#![allow(dead_code, unused_imports, non_snake_case)]
|
|
2501
2438
|
// GENERATED by behavior-contracts (rust-typed-native) — the BC-OWNED shared wire types (#165). A covered
|
|
2502
2439
|
// module generated with --shared-types-import imports these (\`use <path>::*;\`); a separate leaf-transport
|
|
2503
|
-
// crate builds + returns the SAME \`WireValue\` (and, on failure, the SAME
|
|
2504
|
-
// failure type lives here too so the transport crate returns
|
|
2505
|
-
// importing the covered crate (unlike go's \`error\` interface,
|
|
2506
|
-
// \`.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.
|
|
2507
2444
|
|
|
2508
2445
|
// Local concrete failure type (runtime-free) — the covered runner + the transport crate share it. Only the
|
|
2509
2446
|
// TYPE lives here; the de-box/op-failure CONSTRUCTORS stay in the covered module (they are called there).
|
|
2510
2447
|
${emitErrorTypeDefs()}
|
|
2511
2448
|
|
|
2512
|
-
${emitRustProbeWireTypes(true)}
|
|
2449
|
+
${emitRustProbeWireTypes(true)}
|
|
2513
2450
|
`;
|
|
2514
2451
|
}
|
|
2515
2452
|
function emit(ctx) {
|
|
@@ -2555,7 +2492,6 @@ ${emitStructSurface([])}
|
|
|
2555
2492
|
// #108: reset the native-expr helper-usage accumulator (set by the cond/guard compiler).
|
|
2556
2493
|
rustExprUsed.helpers = false;
|
|
2557
2494
|
const leaf = ctx.leafTransport;
|
|
2558
|
-
const structs = [];
|
|
2559
2495
|
const inStructs = [];
|
|
2560
2496
|
const elemMaterializers = [];
|
|
2561
2497
|
// every covered node returns a WireValue the inline de-box classifies — the wire seam (probe enums +
|
|
@@ -2574,33 +2510,16 @@ ${emitStructSurface([])}
|
|
|
2574
2510
|
for (const n of c.body)
|
|
2575
2511
|
if (!isControlGate(n))
|
|
2576
2512
|
typedNodes.set(n.id, "map" in n ? mapNodeArrRef(n, plan) : deriveTypeRef(n.outType, plan)); // #125: control-gate typeless; map は produced-array ref に正規化
|
|
2577
|
-
|
|
2578
|
-
|
|
2579
|
-
// instead (rustSharedWireTypesModule), referenced here via the `use <path>::*;` glob — skip local.
|
|
2580
|
-
if (crossPackage && isCrossPackageSharedNode(n))
|
|
2581
|
-
continue;
|
|
2582
|
-
if ("fanout" in n)
|
|
2583
|
-
structs.push(emitFanoutPortsStructs(c, n, typedNodes, plan));
|
|
2584
|
-
else if ("map" in n)
|
|
2585
|
-
structs.push(emitMapPortsStructs(c, n, typedNodes, plan));
|
|
2586
|
-
else if ("cond" in n) {
|
|
2587
|
-
// #108: a cond node has NO ports struct (pure Expression — no handler dispatch).
|
|
2588
|
-
}
|
|
2589
|
-
else
|
|
2590
|
-
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.
|
|
2591
|
-
}
|
|
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.
|
|
2592
2515
|
inStructs.push(emitInStruct(c, plan));
|
|
2593
2516
|
const mm = emitMapElemMaterializers(c, typedNodes, plan);
|
|
2594
2517
|
if (mm)
|
|
2595
2518
|
elemMaterializers.push(mm);
|
|
2596
2519
|
}
|
|
2597
|
-
//
|
|
2598
|
-
//
|
|
2599
|
-
//
|
|
2600
|
-
// The ports structs are the ONLY Clone-deriving WireValue-bearing structs (input structs derive Default;
|
|
2601
|
-
// outType decls never carry `value` — input-only), so their rendered field types are the total SSoT
|
|
2602
|
-
// signal. A value-free module omits the derive to stay byte-identical to pre-#156.
|
|
2603
|
-
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.
|
|
2604
2523
|
const runners = native.map((c) => emitNativeRawRunner(c, plan, asyncPlans.get(c.name), leaf)).join("\n\n");
|
|
2605
2524
|
const structSurface = emitStructSurface(native);
|
|
2606
2525
|
// Leaf transport import (SSoT resolution via resolveLeafSymbol): if the consumer names an import module,
|
|
@@ -2665,12 +2584,9 @@ use std::cell::RefCell;`;
|
|
|
2665
2584
|
rustExprUsed.helpers
|
|
2666
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()}`
|
|
2667
2586
|
: undefined,
|
|
2668
|
-
structs.some((r) => r.trim().length > 0)
|
|
2669
|
-
? `// 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")}`
|
|
2670
|
-
: undefined,
|
|
2671
2587
|
`// CONCRETE per-component input structs (fields = inputPorts).\n${inStructs.join("\n\n")}`,
|
|
2672
2588
|
emitsWireTypes
|
|
2673
|
-
? `// 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)}`
|
|
2674
2590
|
: undefined,
|
|
2675
2591
|
elemMaterializers.length
|
|
2676
2592
|
? `// map augmented-element copiers (pure struct field assignment — no dynamic value read).\n${elemMaterializers.join("\n\n")}`
|
|
@@ -2735,10 +2651,14 @@ fn value_to_wire(v: &Value) -> WireValue {
|
|
|
2735
2651
|
// returning the scripted wire in EXACTLY the shape the removed per-node trait method returned. bc#87
|
|
2736
2652
|
// parallel scoped threads share the static (Mutex-guarded); cases run sequentially so a shared static is
|
|
2737
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).
|
|
2738
2660
|
const transportFns = [];
|
|
2739
|
-
const
|
|
2740
|
-
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 }`;
|
|
2741
|
-
const spreadParams = (spread) => spread.map((p) => `${p.field}: ${p.isCopy ? p.renderedType : `&${p.renderedType}`}`).join(", ");
|
|
2661
|
+
const bySym = new Map();
|
|
2742
2662
|
for (const c of native) {
|
|
2743
2663
|
const ap = asyncPlans.get(c.name);
|
|
2744
2664
|
const typedNodes = new Map();
|
|
@@ -2749,98 +2669,71 @@ fn value_to_wire(v: &Value) -> WireValue {
|
|
|
2749
2669
|
if ("cond" in n)
|
|
2750
2670
|
continue; // #108: a cond node has no leaf (pure Expression) — no transport fn.
|
|
2751
2671
|
const catalog = "fanout" in n ? n.fanout.component : "map" in n ? n.map.component : n.component;
|
|
2752
|
-
|
|
2753
|
-
|
|
2754
|
-
|
|
2755
|
-
|
|
2756
|
-
|
|
2757
|
-
|
|
2758
|
-
|
|
2759
|
-
|
|
2760
|
-
|
|
2761
|
-
|
|
2762
|
-
|
|
2763
|
-
|
|
2764
|
-
|
|
2765
|
-
|
|
2766
|
-
|
|
2767
|
-
|
|
2768
|
-
|
|
2769
|
-
|
|
2770
|
-
|
|
2771
|
-
|
|
2772
|
-
|
|
2773
|
-
|
|
2774
|
-
|
|
2775
|
-
|
|
2776
|
-
if (
|
|
2777
|
-
|
|
2778
|
-
|
|
2779
|
-
|
|
2780
|
-
|
|
2781
|
-
|
|
2782
|
-
${drainStmt(catalog, "_echo")}
|
|
2783
|
-
let arr = match ok { Some(Value::Arr(a)) => a, _ => Vec::new() };
|
|
2784
|
-
let wires = arr.iter().map(value_to_wire).collect();
|
|
2785
|
-
Ok(wires)
|
|
2786
|
-
}`);
|
|
2787
|
-
}
|
|
2788
|
-
else {
|
|
2789
|
-
const { elemRef: overElemRef } = mapOverElemInfo(c, n, typedNodes, plan);
|
|
2790
|
-
const params = spreadParams(portFieldSpread(m.ports, m.portSchemas, c, plan, typedNodes, { name: m.as, ref: overElemRef, plan }, nodeNarrowedPaths(c, n)));
|
|
2791
|
-
transportFns.push(`${fnKw} ${sym}(${params}) -> Result<WireValue, BehaviorError> {
|
|
2792
|
-
${drainStmt(catalog, "_echo")}
|
|
2793
|
-
Ok(value_to_wire(&ok.unwrap_or(Value::Null)))
|
|
2794
|
-
}`);
|
|
2795
|
-
}
|
|
2796
|
-
continue;
|
|
2797
|
-
}
|
|
2798
|
-
// componentRef (point read): spread port fields; supports echo (#129/#141) reading the port params.
|
|
2799
|
-
const node = n;
|
|
2800
|
-
// #170: the observe transport fn's param types must match the covered module's leaf call args, which
|
|
2801
|
-
// narrow a gate-proven opt key — so this reads the SAME node narrowing.
|
|
2802
|
-
const crNarrowed = nodeNarrowedPaths(c, node);
|
|
2803
|
-
const ref = typedNodes.get(n.id);
|
|
2804
|
-
const echoBranches = [];
|
|
2805
|
-
if (ref.kind === "named") {
|
|
2806
|
-
const decl = findDecl(plan, ref.name);
|
|
2807
|
-
const field = decl !== undefined && decl.fields.length === 1 ? decl.fields[0] : undefined;
|
|
2808
|
-
const fieldRust = field !== undefined ? renderTypeRef(field.type) : null;
|
|
2809
|
-
const recordRust = renderTypeRef(ref);
|
|
2810
|
-
for (const pn of Object.keys(node.ports)) {
|
|
2811
|
-
let portRust = null;
|
|
2812
|
-
try {
|
|
2813
|
-
portRust = portFieldRustType(node.ports[pn], c, plan, typedNodes, inputPortTypeRef(node.portSchemas?.[pn], plan), `echo port '${pn}'`, { narrowed: crNarrowed });
|
|
2814
|
-
}
|
|
2815
|
-
catch {
|
|
2816
|
-
portRust = null;
|
|
2817
|
-
}
|
|
2818
|
-
if (portRust === recordRust) {
|
|
2819
|
-
// the port IS the whole record → echo it DIRECTLY (matching run_behavior's plain echo:port).
|
|
2820
|
-
const own = typeRefIsCopy(ref) ? `${portFieldName(pn)}` : `${portFieldName(pn)}.clone()`;
|
|
2821
|
-
echoBranches.push(` if echo == ${rustStrLit(pn)} {\n let tv = ${own};\n return Ok(value_to_wire(&${serializeTyped("tv", ref, plan)}));\n }`);
|
|
2822
|
-
}
|
|
2823
|
-
else if (fieldRust !== null && field !== undefined && portRust === fieldRust) {
|
|
2824
|
-
// a scalar port wraps into the record's single field ({v: ports.X}).
|
|
2825
|
-
const own = typeRefIsCopy(field.type) ? `${portFieldName(pn)}` : `${portFieldName(pn)}.clone()`;
|
|
2826
|
-
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
|
+
}
|
|
2827
2702
|
}
|
|
2828
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
|
+
}
|
|
2829
2709
|
}
|
|
2830
|
-
|
|
2831
|
-
|
|
2832
|
-
//
|
|
2833
|
-
|
|
2834
|
-
|
|
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;
|
|
2835
2721
|
}
|
|
2836
|
-
|
|
2837
|
-
|
|
2838
|
-
|
|
2839
|
-
|
|
2840
|
-
|
|
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
|
+
}
|
|
2841
2735
|
${echoBlock} Ok(value_to_wire(&ok.unwrap_or(Value::Null)))
|
|
2842
2736
|
}`);
|
|
2843
|
-
}
|
|
2844
2737
|
}
|
|
2845
2738
|
const arms = native
|
|
2846
2739
|
.map((c) => {
|