behavior-contracts 0.11.9 → 0.11.10

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.
@@ -8,7 +8,7 @@ import { NativeExprCompiler } from "./native-expr.js";
8
8
  import { buildAsyncPlans } from "./async-plan.js";
9
9
  import { buildDeBoxPlan, buildWirePlan, notationOfRef } from "./emit-shared-debox.js";
10
10
  const { sanitize, rustStrLit } = rustStraightlineInternals;
11
- const { typeRefIsCopy, rustFieldName, renderTypeRef, typedCell, typedFieldAccess, serializeTyped, emitTypeDecls, emitDefaults, emitSerializers, emitTypedValue, rustCellRead, checkOutputFieldType, emitMarshallers, emitMarshalHelpers, materializeExpr, } = rustTypedInternals;
11
+ const { typeRefIsCopy, rustFieldName, renderTypeRef, typedCell, typedFieldAccess, serializeTyped, emitTypeDecls, emitDefaults, emitTypedValue, rustCellRead, checkOutputFieldType, emitMarshallers, emitMarshalHelpers, } = rustTypedInternals;
12
12
  /** rustErr — build the LOCAL concrete error value for a behavior/plan failure on the covered read
13
13
  * plane (runtime-free). The covered module declares a local `BehaviorError` (see emitBehaviorErrorType);
14
14
  * the runner returns `Result<_, BehaviorError>` over THAT local type. This REPLACES the old
@@ -61,9 +61,8 @@ pub struct ErrorDetail {
61
61
  // covered runner returns \`Result<T, BehaviorError>\` over THIS local type instead of a bc-runtime
62
62
  // failure, so the fully-covered module imports ZERO bc runtime. Codes match run_behavior verbatim
63
63
  // (byte-equal). \`detail\` carries the leaf's structured Error Value across the seam so a caller can
64
- // log / skip / repair / migrate rather than parse a message. The observe companion (test glue, a
65
- // super:: submodule) bridges this local error to the bc-runtime failure at the observe boundary —
66
- // the covered module itself stays runtime-free.
64
+ // log / skip / repair / migrate rather than parse a message. The covered module stays runtime-free:
65
+ // nothing in it converts this local error into a bc-runtime failure.
67
66
  #[derive(Debug, Clone)]
68
67
  pub struct BehaviorError {
69
68
  pub code: String,
@@ -166,7 +165,7 @@ function pascal(s) {
166
165
  * resolveLeafSymbol — the op-agnostic transport symbol a covered leaf (= catalog component) is called
167
166
  * through at its execution point. A consumer-supplied override (`leafTransport.symbols[component]`) wins;
168
167
  * else the in-package DEFAULT convention `leaf_<sanitizedComponent>`. This is the ONE place leaf→symbol
169
- * resolution lives (SSoT) — the runner call sites, the import block, and the test observe transport fns
168
+ * resolution lives (SSoT) — the runner call sites and the import block
170
169
  * all read it. There is no per-node handler indirection: the leaf is one transport, not one method per node.
171
170
  */
172
171
  function resolveLeafSymbol(component, leaf, specSymbol) {
@@ -1456,23 +1455,6 @@ function inputPortRustType(schema, plan, where = "input port") {
1456
1455
  throw new GeneratorFailure("UNSUPPORTED_NODE_STRAIGHTLINE", `rust typed-native (runtime-free): ${where} is OPTIONAL (declared {opt:…}) but its inner type ${JSON.stringify(schema?.type)} has no native Rust lowering, so "absent" has no native representation. Declare an elemType for an array/map, or use a natively-lowerable scalar.`);
1457
1456
  return "Value";
1458
1457
  }
1459
- /** The scalar kind an input port declares, or undefined if it is not a native scalar. */
1460
- function inputScalarKind(schema) {
1461
- switch (schema?.type) {
1462
- case "string":
1463
- case "literal": // a `"literal"` union is a constrained String (see inputPortRustType).
1464
- return "String";
1465
- case "int":
1466
- return "i64";
1467
- case "float":
1468
- case "number": // a `"number"` port is the FLOAT channel (run_behavior: number → float / f64).
1469
- return "f64";
1470
- case "bool":
1471
- return "bool";
1472
- default:
1473
- return undefined;
1474
- }
1475
- }
1476
1458
  /** A ref resolver for native lowering: given a ref head + remaining field path, return a native scalar
1477
1459
  * Rust expression (typed input field / prior-node typed struct scalar / element binding field), or null
1478
1460
  * when the ref does not resolve to a REQUIRED (non-opt) native scalar (then the caller falls back to the
@@ -2743,413 +2725,6 @@ use std::cell::RefCell;`;
2743
2725
  ];
2744
2726
  return `${sections.filter((x) => !!x).join("\n\n")}\n`;
2745
2727
  }
2746
- /**
2747
- * rustTypedNativeObserve — the TEST-ONLY observe companion (a submodule string the test harness writes
2748
- * alongside the covered module). It carries the typed->Value serializers (ser_*) + the SCRIPTED analog of
2749
- * the consumer's leaf transport symbols: free \`leaf_<comp>\` fns that drain a shared scripted static and
2750
- * return the scripted wire (so the covered module's transport calls resolve to real fns), + an
2751
- * observe_native_raw dispatch that fills the static from the per-case spec, decodes the generic input into
2752
- * the concrete InNR_<comp>, drives the module-private struct runner, and serializes its result to a
2753
- * canonical Value for the equivalence pin. Lives OUTSIDE the covered module so the module stays literal
2754
- * whole-file zero (the ser_* / decode helpers are test glue, never on the consumer's read hot path).
2755
- */
2756
- export function rustTypedNativeObserve(ir, ioModel = "sync", leaf, declared) {
2757
- const components = ir.components;
2758
- const native = components.filter(isNativeRaw);
2759
- const plan = buildTypePlan(ir);
2760
- const needSync = native.some((c) => concurrencyPlan(c) !== null);
2761
- const serializers = emitSerializers(plan);
2762
- const marshallers = emitMarshallers(plan);
2763
- // bc#97: the observe glue must MATCH the covered module's per-node async-ness — the scripted handler's
2764
- // node_* methods are `async fn` exactly where the trait's are, and observe_native_raw awaits an async
2765
- // runner. Built from the SAME SSoT propagation pass the covered emitter used, so glue never drifts.
2766
- const asyncPlans = buildAsyncPlans(ir, ioModel);
2767
- const anyAsyncRunner = native.some((c) => asyncPlans.get(c.name).runnerIsAsync);
2768
- // ── per-component input decoders: generic &[(String,Value)] -> concrete InNR_<comp> (test glue). ──
2769
- const inDecoders = native.map((c) => emitInDecoder(c, plan, declared)).join("\n\n");
2770
- // every covered node returns a WireValue the inline de-box classifies — so the scripted wire adapter is
2771
- // needed whenever any component has a handler node.
2772
- const anyDeBox = native.some((c) => c.body.some((n) => !("cond" in n)));
2773
- // value_to_wire (TEST glue): builds the covered module's BC-OWNED concrete `WireValue` from a scripted bc
2774
- // `Value` — the test-harness analog of the consumer's real transport (which builds `WireValue` as it reads
2775
- // the producer). Numbers ride in their declared type (WireValue::Int / WireValue::Float) — nothing parses;
2776
- // the wire tags + classification live ONCE in the covered module's WireValue (probe_*_at), so this only
2777
- // CONSTRUCTS — a scripted wrong-variant value maps to the corresponding WireValue variant and the covered
2778
- // de-box classifies it (TYPE_MISMATCH ≡ run_behavior), no separate scripted classifier.
2779
- const wireAdapter = anyDeBox
2780
- ? `// ── value_to_wire (TEST glue): scripted bc Value -> the covered module's BC-owned WireValue ──
2781
- fn value_to_wire(v: &Value) -> WireValue {
2782
- match v {
2783
- Value::Null => WireValue::Null,
2784
- Value::Bool(b) => WireValue::Bool(*b),
2785
- Value::Int(n) => WireValue::Int(*n),
2786
- Value::Float(f) => WireValue::Float(*f),
2787
- Value::Str(s) => WireValue::Str(Cow::Owned(s.clone())),
2788
- Value::Arr(items) => WireValue::List(WireList { items: items.iter().map(value_to_wire).collect() }),
2789
- Value::Obj(pairs) => WireValue::Row(WireRow {
2790
- entries: pairs.iter().map(|(k, vv)| (Cow::Owned(k.clone()), value_to_wire(vv))).collect(),
2791
- }),
2792
- }
2793
- }`
2794
- : "";
2795
- // ── op-agnostic leaf TRANSPORT fns (TEST glue) — the scripted analog of the consumer's transport
2796
- // symbols. ONE free `leaf_<component>` per DISTINCT covered leaf (catalog component) in the IR (a
2797
- // per-module leaf has one consistent shape — verified), draining the shared scripted-outcome static and
2798
- // returning the scripted wire in EXACTLY the shape the removed per-node trait method returned. bc#87
2799
- // parallel scoped threads share the static (Mutex-guarded); cases run sequentially so a shared static is
2800
- // fine. Echo (#129/#141) reads the spread port params directly. ──
2801
- // ONE free transport per DISTINCT SPEC-fixed SYMBOL (#176/#183), UNIFORM signature
2802
- // `<sym>(payload: WireRow) -> Result<WireValue, BehaviorError>`: value_to_wire is recursive, so a
2803
- // batched/fanout `Value::Arr` result becomes a `WireValue::List` (a `Value::Null` element → WireValue::Null,
2804
- // the dangling marker) and a single result a scalar/row wire — ONE signature serves every cardinality. Echo
2805
- // (#129/#141) reads the port back FROM THE PAYLOAD BY NAME. A spec-named leaf used in MULTIPLE roles is
2806
- // emitted ONCE; two nodes → same symbol but DIFFERENT catalog is a LOUD collision (never silent).
2807
- const transportFns = [];
2808
- const bySym = new Map();
2809
- for (const c of native) {
2810
- const ap = asyncPlans.get(c.name);
2811
- const typedNodes = new Map();
2812
- for (const n of c.body)
2813
- if (!isControlGate(n))
2814
- typedNodes.set(n.id, "map" in n ? mapNodeArrRef(n, plan) : deriveTypeRef(n.outType, plan)); // #125: control-gate typeless; map は produced-array ref に正規化
2815
- for (const n of c.body) {
2816
- if ("cond" in n)
2817
- continue; // #108: a cond node has no leaf (pure Expression) — no transport fn.
2818
- // #225: 純式 map も Component を呼ばないので transport fn を持たない(cond と同じ)。
2819
- if ("map" in n && mapTransformExpr(n.map) !== undefined)
2820
- continue;
2821
- const catalog = ("fanout" in n ? n.fanout.component : "map" in n ? n.map.component : n.component);
2822
- const specSym = "fanout" in n ? n.fanout.leafSymbol : "map" in n ? n.map.leafSymbol : n.leafSymbol;
2823
- const sym = resolveLeafSymbol(catalog, leaf, specSym);
2824
- const isAsync = ap.nodeIsAsync(n.id);
2825
- // echo branches (point/componentRef nodes only — a batched/fanout node returns a WireList, not a port).
2826
- const echo = [];
2827
- if (!("fanout" in n) && !("map" in n)) {
2828
- const node = n;
2829
- const crNarrowed = nodeNarrowedPaths(c, node);
2830
- const ref = typedNodes.get(n.id);
2831
- if (ref.kind === "named") {
2832
- const decl = findDecl(plan, ref.name);
2833
- const field = decl !== undefined && decl.fields.length === 1 ? decl.fields[0] : undefined;
2834
- const fieldRust = field !== undefined ? renderTypeRef(field.type) : null;
2835
- const recordRust = renderTypeRef(ref);
2836
- for (const pn of Object.keys(node.ports)) {
2837
- let portRust = null;
2838
- try {
2839
- portRust = portFieldRustType(node.ports[pn], c, plan, typedNodes, inputPortTypeRef(node.portSchemas?.[pn], plan), `echo port '${pn}'`, { narrowed: crNarrowed });
2840
- }
2841
- catch {
2842
- portRust = null;
2843
- }
2844
- if (portRust === recordRust) {
2845
- // the port IS the whole record → echo its payload wire DIRECTLY (matching run_behavior's echo:port).
2846
- echo.push(` if echo == ${rustStrLit(pn)} {\n if let Some(v) = payload.take(${rustStrLit(pn)}) {\n return Ok(v);\n }\n }`);
2847
- }
2848
- else if (fieldRust !== null && field !== undefined && portRust === fieldRust) {
2849
- // a scalar port wraps into the record's single field ({v: <port wire>}) — mirrors the scripted `wrap`.
2850
- echo.push(` if echo == ${rustStrLit(pn)} {\n if let Some(v) = payload.take(${rustStrLit(pn)}) {\n return Ok(WireValue::Row(WireRow { entries: vec![(Cow::Borrowed(${rustStrLit(field.name)}), v)] }));\n }\n }`);
2851
- }
2852
- }
2853
- }
2854
- else if (ref.kind === "arr" && Object.prototype.hasOwnProperty.call(node.ports, "items")) {
2855
- // #129: an arr node with an `items` port echoes the payload's items wire (a WireList) so the
2856
- // node→leaf array dataflow test is non-vacuous.
2857
- echo.push(` if echo == "items" {\n if let Some(v) = payload.take("items") {\n return Ok(v);\n }\n }`);
2858
- }
2859
- }
2860
- const prev = bySym.get(sym);
2861
- if (prev !== undefined) {
2862
- // #176/#183: a spec-fixed symbol MUST map to exactly ONE leaf. The same leaf in multiple roles shares
2863
- // ONE transport — accumulate its echo branches. Two DIFFERENT catalog components → same symbol is a
2864
- // codegen error (never silent).
2865
- if (prev.catalog !== catalog)
2866
- 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).`);
2867
- for (const e of echo)
2868
- if (!prev.echo.includes(e))
2869
- prev.echo.push(e);
2870
- continue;
2871
- }
2872
- bySym.set(sym, { catalog, async: isAsync, echo });
2873
- }
2874
- }
2875
- for (const [sym, le] of bySym) {
2876
- const fnKw = le.async ? "pub async fn" : "pub fn";
2877
- const hasEcho = le.echo.length > 0;
2878
- const echoBind = hasEcho ? "echo" : "_echo";
2879
- const echoBlock = hasEcho ? `${le.echo.join("\n")}\n` : "";
2880
- transportFns.push(`${fnKw} ${sym}(${hasEcho ? "mut payload" : "_payload"}: WireRow) -> Result<WireValue, BehaviorError> {
2881
- let (is_err, err, ok, ${echoBind}) = next_scripted(${rustStrLit(le.catalog)}).ok_or_else(|| unknown_component(${rustStrLit(le.catalog)}))?;
2882
- if is_err {
2883
- return Err(leaf_failure(err));
2884
- }
2885
- ${echoBlock} Ok(value_to_wire(&ok.unwrap_or(Value::Null)))
2886
- }`);
2887
- }
2888
- const arms = native
2889
- .map((c) => {
2890
- const outRef = c.outputType !== undefined ? deriveTypeRef(c.outputType, plan) : undefined;
2891
- const ser = outRef ? serializeTyped("tv", outRef, plan) : "tv";
2892
- // bc#90 / runtime-free: the covered runner returns the module-LOCAL `BehaviorError` (via super::*);
2893
- // bridge it to the bc-runtime `behavior_contracts::BehaviorError` at the observe boundary (same
2894
- // code/message) so the conformance harness (main.rs) reads the stable code without the covered
2895
- // module ever touching bc runtime. decode_* is test glue and returns the local error too.
2896
- // bc#97: an async runner returns a Future — drive it to completion with the std-only block-on
2897
- // (bc_block_on) so observe_native_raw keeps its SYNC external signature (the harness is unchanged).
2898
- // The scripted async node_* return ready values, so the future needs no real executor / no runtime.
2899
- // #192: decode the generic test input into the entry's POSITIONAL args (test glue), then call the
2900
- // 1:1 entry positionally (box removed). A no-input entry is called with no args (no decoder).
2901
- const args = entryPortOrder(c, declared).map((p) => rustFieldName(p));
2902
- const runnerCall = `super::${rustFieldName(c.name)}(${args.join(", ")})`;
2903
- const driven = asyncPlans.get(c.name).runnerIsAsync ? `bc_block_on(${runnerCall})` : runnerCall;
2904
- const decode = args.length === 0 ? "" : ` let (${args.join(", ")},) = decode_${sanitize(c.name)}(input).map_err(to_rt_err)?;\n`;
2905
- const unusedInput = args.length === 0 ? " let _ = input;\n" : "";
2906
- return ` ${rustStrLit(c.name)} => {\n${decode}${unusedInput} let tv = ${driven}.map_err(to_rt_err)?;\n Ok(${ser})\n }`;
2907
- })
2908
- .join("\n");
2909
- // the scripted-outcome source is a MODULE-LEVEL static (Mutex<Option<HashMap>> + AtomicUsize), NOT a
2910
- // per-call handler object: the free transport fns drain it, and observe_native_raw resets+fills it from
2911
- // the per-case handlers spec before driving the runner. A static (not thread_local) so the bc#87 parallel
2912
- // scoped threads — which call the transport fns concurrently — share it (Mutex-guarded). Cases run
2913
- // sequentially in the harness, so one shared static per case is fine.
2914
- const adapter = `// SCRIPTED_QUEUES — the shared scripted-outcome source the free leaf transport fns drain (TEST glue).
2915
- // { "<component>": (queue, single) }. reset+filled per case by observe_native_raw. \`Mutex::new(None)\` is
2916
- // a const initializer (no LazyLock/OnceLock needed). SCRIPTED_SEEN mirrors the old probe counter.
2917
- static SCRIPTED_QUEUES: std::sync::Mutex<Option<std::collections::HashMap<String, (Vec<serde_json::Value>, bool)>>> =
2918
- std::sync::Mutex::new(None);
2919
- #[allow(dead_code)]
2920
- static SCRIPTED_SEEN: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
2921
-
2922
- // fill_scripted — reset + load the shared static from the JSON handlers spec: { "<component>": {ok|error}
2923
- // | [ {ok|error}, … ] }.
2924
- fn fill_scripted(spec: &serde_json::Map<String, serde_json::Value>) {
2925
- let mut map = std::collections::HashMap::new();
2926
- for (name, raw) in spec {
2927
- let (items, single) = match raw {
2928
- serde_json::Value::Array(a) => (a.clone(), false),
2929
- other => (vec![other.clone()], true),
2930
- };
2931
- map.insert(name.clone(), (items, single));
2932
- }
2933
- *SCRIPTED_QUEUES.lock().unwrap() = Some(map);
2934
- SCRIPTED_SEEN.store(0, std::sync::atomic::Ordering::SeqCst);
2935
- }
2936
-
2937
- // next_scripted — drain one scripted outcome for a component (last entry repeats — mirrors the reference
2938
- // scripted handlers); None when the component has no scripted queue. Returns (is_error, err, ok_value,
2939
- // echo). The bc#87 parallel-stage runner calls the transport fns from multiple threads, so the drain is
2940
- // Mutex-guarded. #129: \`echo\` carries the reference scriptedHandlers' \`echo\` directive (e.g. "items")
2941
- // so a scripted node can ECHO a named input PORT back — used to make the node→leaf array dataflow test
2942
- // non-vacuous (the leaf returns its \`items\` port; a dropped/boxed array diverges).
2943
- fn next_scripted(component: &str) -> Option<(bool, String, Option<Value>, String)> {
2944
- SCRIPTED_SEEN.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
2945
- let mut guard = SCRIPTED_QUEUES.lock().unwrap();
2946
- let map = guard.as_mut()?;
2947
- let (queue, single) = map.get_mut(component)?;
2948
- let raw = if *single || queue.len() <= 1 { queue[0].clone() } else { queue.remove(0) };
2949
- // normalize echo:port to the port NAME X so a de-box handler's echo comparison fires;
2950
- // echo:items already names the port directly.
2951
- let echo = {
2952
- let e = raw.get("echo").and_then(|e| e.as_str()).unwrap_or("");
2953
- if e == "port" { raw.get("port").and_then(|p| p.as_str()).unwrap_or("").to_string() } else { e.to_string() }
2954
- };
2955
- if let Some(okv) = raw.get("ok") {
2956
- let v = behavior_contracts::decode_value(okv).expect("decode ok");
2957
- Some((false, String::new(), Some(v), echo))
2958
- } else {
2959
- let e = raw.get("error").and_then(|e| e.as_str()).unwrap_or("").to_string();
2960
- Some((true, e, None, echo))
2961
- }
2962
- }`;
2963
- void needSync;
2964
- return `// GENERATED test-only observe companion (bc#77/#94) — NOT part of the covered module. Serializes the
2965
- // struct-native runner's result to a canonical Value for the equivalence pin, and carries the SCRIPTED
2966
- // analog of the consumer's leaf transport symbols: free \`leaf_<comp>\` fns that drain a shared scripted
2967
- // static and return the scripted wire (exactly the shape the removed per-node trait method returned). The
2968
- // consumer never uses this (it keeps the model native + supplies its own transport fns over its own wire
2969
- // payload); it exists only so the test harness can byte-compare the STRUCT-only covered read against
2970
- // run_behavior. A submodule of the covered module (reads its pub entry fns + the CONCRETE
2971
- // structs — incl. the LOCAL BehaviorError — via super::*, and its \`leaf_<comp>\` fns resolve the covered
2972
- // module's transport calls). bc#90 / runtime-free: the covered module's BehaviorError is LOCAL, so this
2973
- // test-glue companion refers to it via super::* (as \`BehaviorError\`) and refers to the bc-runtime failure
2974
- // type FULLY-QUALIFIED (\`behavior_contracts::BehaviorError\`) only where it bridges at the observe boundary.
2975
- // The transport-fn signatures spread the port fields, so they carry \`&String\`/\`&Vec\` params and (for
2976
- // point reads) many args — clippy::ptr_arg / too_many_arguments are TEST-glue-only allows here.
2977
- #![allow(dead_code, unused_imports, unused_variables, non_snake_case, clippy::ptr_arg, clippy::too_many_arguments, clippy::needless_lifetimes, clippy::type_complexity)]
2978
- use behavior_contracts::Value;
2979
- use super::*;
2980
-
2981
- // bridge the covered module's LOCAL BehaviorError (super::BehaviorError) to the bc-runtime failure type
2982
- // the conformance harness reads (same code + message + structured detail) — the ONLY place the two meet
2983
- // (test glue). The de-box's structured Error Value is carried over so the harness can assert it.
2984
- fn to_rt_err(e: BehaviorError) -> behavior_contracts::BehaviorError {
2985
- let mut rt = behavior_contracts::BehaviorError::new(e.code, e.message);
2986
- if let Some(d) = e.detail {
2987
- let d = *d;
2988
- rt.detail = Some(Box::new(behavior_contracts::ErrorDetail {
2989
- kind: d.kind.map(|k| match k {
2990
- ErrorKind::TypeMismatch => behavior_contracts::ErrorKind::TypeMismatch,
2991
- ErrorKind::MissingField => behavior_contracts::ErrorKind::MissingField,
2992
- ErrorKind::Overflow => behavior_contracts::ErrorKind::Overflow,
2993
- }),
2994
- model: d.model,
2995
- field: d.field,
2996
- expected_type: d.expected_type,
2997
- actual_wire_type: d.actual_wire_type,
2998
- raw_value: d.raw_value,
2999
- context: d.context,
3000
- }));
3001
- }
3002
- rt
3003
- }
3004
- ${anyAsyncRunner
3005
- ? `// bc#97 (TEST glue) — a minimal std-only block-on that drives an async runner Future to completion so
3006
- // observe_native_raw stays sync-callable (the harness never changes). The covered async fn's futures are
3007
- // ready (the scripted handler does no real I/O), so a no-op waker + spin poll resolves in one step. This
3008
- // lives ONLY in the observe companion — the covered module itself imports zero runtime.
3009
- fn bc_block_on<F: std::future::Future>(mut fut: F) -> F::Output {
3010
- use std::task::{Context, Poll, RawWaker, RawWakerVTable, Waker};
3011
- fn noop(_: *const ()) {}
3012
- fn clone(_: *const ()) -> RawWaker {
3013
- RawWaker::new(std::ptr::null(), &VTABLE)
3014
- }
3015
- static VTABLE: RawWakerVTable = RawWakerVTable::new(clone, noop, noop, noop);
3016
- let waker = unsafe { Waker::from_raw(RawWaker::new(std::ptr::null(), &VTABLE)) };
3017
- let mut cx = Context::from_waker(&waker);
3018
- // SAFETY: fut is owned on the stack and never moved after pinning (it is dropped at scope end).
3019
- let mut fut = unsafe { std::pin::Pin::new_unchecked(&mut fut) };
3020
- loop {
3021
- match fut.as_mut().poll(&mut cx) {
3022
- Poll::Ready(v) => return v,
3023
- Poll::Pending => std::thread::yield_now(),
3024
- }
3025
- }
3026
- }`
3027
- : ""}
3028
-
3029
- ${serializers}
3030
-
3031
- // Value -> typed struct marshallers for the concrete-row decode (TEST glue only).
3032
- ${marshallers}
3033
-
3034
- ${emitMarshalHelpers()}
3035
-
3036
- // input decoders (generic &[(String,Value)] -> concrete InNR_<comp>; TEST glue, one decode at the boundary).
3037
- ${inDecoders}
3038
-
3039
- // scripted wire adapter (TEST glue) — wraps a scripted Value as a WireValue the generated inline de-box probes.
3040
- ${wireAdapter}
3041
-
3042
- ${adapter}
3043
-
3044
- // scripted leaf transport fns (one per covered leaf — the free op-agnostic transport the covered runner
3045
- // calls directly; test glue draining the shared scripted static).
3046
- ${transportFns.join("\n\n")}
3047
-
3048
- // observe_native_raw resets+fills the shared scripted static from the per-case handlers spec, then drives
3049
- // the covered struct-native runner and serializes to a canonical Value (test only). No handler object is
3050
- // passed — the runner calls the free \`leaf_<comp>\` transport fns above directly.
3051
- pub fn observe_native_raw(
3052
- name: &str,
3053
- spec: &serde_json::Map<String, serde_json::Value>,
3054
- input: &[(String, Value)],
3055
- ) -> Result<Value, behavior_contracts::BehaviorError> {
3056
- fill_scripted(spec);
3057
- match name {
3058
- ${arms}
3059
- other => Err(behavior_contracts::BehaviorError::new("UNKNOWN_ENTRY", format!("component '{other}' is not a covered read (fail-closed)"))),
3060
- }
3061
- }
3062
- `;
3063
- }
3064
- /** emitInDecoder — a TEST-glue decoder `decode_<comp>(input) -> Result<(<positional args...>,), BehaviorError>`.
3065
- * Reads each declared input port from the generic &[(String,Value)] into a local (= the entry's positional
3066
- * param; scalar → typed read; value-typed → the raw wire clone), returned as a tuple the observe companion
3067
- * destructures and passes positionally to the 1:1 entry (#192, box removed). A missing key leaves Default
3068
- * (every covered input is required + supplied by the corpus). Lives ONLY in the observe companion. */
3069
- function emitInDecoder(comp, plan, declared) {
3070
- const ports = entryPortOrder(comp, declared);
3071
- if (ports.length === 0 || comp.inputPorts === undefined)
3072
- return ""; // no input → observe calls the entry with no args.
3073
- const args = ports.map((p) => rustFieldName(p));
3074
- const types = ports.map((p) => inputPortRustType(comp.inputPorts[p], plan, `input port '${p}' of component '${comp.name}'`));
3075
- const lines = [];
3076
- // trailing comma → always a tuple (never a parenthesized single value).
3077
- lines.push(`fn decode_${sanitize(comp.name)}(input: &[(String, Value)]) -> Result<(${types.join(", ")},), BehaviorError> {`);
3078
- // neutral init per port: a SCALAR `value` port renders as bare `WireValue` (no Default) — init it
3079
- // with `WireValue::Null`, the SAME value-kind neutral the covered emitter uses for value cells (the
3080
- // cellInit SSoT above). Every other port type (scalar, Vec<WireValue>, Option<…>) has a Default.
3081
- ports.forEach((p, i) => lines.push(` let mut ${args[i]}: ${types[i]} = ${comp.inputPorts[p]?.type === "value" ? "WireValue::Null" : "Default::default()"};`));
3082
- // an if/else-if chain (clippy-clean regardless of port count — a single-arm `match` trips single_match).
3083
- lines.push(` for (k, v) in input {`);
3084
- ports.forEach((p, i) => {
3085
- const field = args[i];
3086
- const schema = comp.inputPorts[p];
3087
- const scalar = inputScalarKind(schema);
3088
- const et = schema.elemType;
3089
- const head = i === 0 ? " if" : " } else if";
3090
- lines.push(`${head} k == ${rustStrLit(p)} {`);
3091
- if ((schema?.type === "array" || schema?.type === "arr") && et !== undefined) {
3092
- // #108: decode the boxed Value::Arr into the native Vec<ElemT> (test glue — materialize each elem).
3093
- // bc#156: a `value[]` element is BC's opaque wire — decode it with the BC-owned value_to_wire
3094
- // constructor (the SAME wire the output de-box uses), NOT the typed materializer (WireValue is not a
3095
- // de-box target). This is the generic bound-value list built from a heterogeneous / empty input array.
3096
- const elemRef = deriveTypeRef(et, plan);
3097
- const elemTy = renderTypeRef(elemRef);
3098
- const mat = elemRef.kind === "value" ? "value_to_wire(ev)" : materializeExpr("ev", elemRef, plan);
3099
- lines.push(` match v {`);
3100
- lines.push(` Value::Arr(a) => {`);
3101
- lines.push(` let mut dec: Vec<${elemTy}> = Vec::with_capacity(a.len());`);
3102
- lines.push(` for ev in a.iter() { dec.push(${mat}); }`);
3103
- // #177 (A): an OPTIONAL array port field is `Option<Vec<E>>` (inputPortTypeRef opt), so wrap in Some.
3104
- lines.push(` ${field} = ${inputPortIsOptional(schema) ? "Some(dec)" : "dec"};`);
3105
- lines.push(` }`);
3106
- lines.push(` other => return Err(marshal_type_error(${rustStrLit(`decode input ${p}: expected array, got `)}, other.type_name())),`);
3107
- lines.push(` }`);
3108
- }
3109
- else if (schema?.type === "value") {
3110
- // bc#156: a scalar `value` port — the raw bound value as BC's opaque wire (value_to_wire).
3111
- lines.push(` ${field} = value_to_wire(v);`);
3112
- }
3113
- else if (schema?.type === "map" && et !== undefined) {
3114
- // #108-map: decode the boxed Value::Obj into the native BTreeMap<String, V> (test glue — the input
3115
- // map port carries a declared elemType). materializeExpr covers the map de-box (obj → BTreeMap).
3116
- // #209: a map whose VALUE type is the opaque `value` decodes with the BC-owned value_to_wire — the
3117
- // SAME rule the `value[]` array branch above and the scalar `value` branch apply (`value` is
3118
- // input-only, so the typed materializer stays fail-closed for it).
3119
- const valRef = deriveTypeRef(et, plan);
3120
- if (valRef.kind === "value") {
3121
- lines.push(` let mut mv: std::collections::BTreeMap<String, WireValue> = std::collections::BTreeMap::new();`);
3122
- lines.push(` if let Value::Obj(mo) = v { for (mk, mvv) in mo.iter() { mv.insert(mk.clone(), value_to_wire(mvv)); } }`);
3123
- lines.push(` ${field} = mv;`);
3124
- }
3125
- else {
3126
- const mapRef = { kind: "map", value: valRef };
3127
- lines.push(` ${field} = ${materializeExpr("v", mapRef, plan)};`);
3128
- }
3129
- }
3130
- else if (inputPortIsOptional(schema)) {
3131
- // #139: an OPTIONAL scalar port decodes into Option<T> via the inputPortTypeRef SSoT (a present key
3132
- // materializes Some(v); an absent key never enters this block, leaving the Default None).
3133
- lines.push(` ${field} = ${materializeExpr("v", inputPortTypeRef(schema, plan), plan)};`);
3134
- }
3135
- else if (scalar === undefined) {
3136
- lines.push(` ${field} = v.clone();`);
3137
- }
3138
- else {
3139
- const pat = scalar === "String" ? "Value::Str(sv)" : scalar === "i64" ? "Value::Int(sv)" : scalar === "f64" ? "Value::Float(sv)" : "Value::Bool(sv)";
3140
- const label = scalar === "String" ? "string" : scalar === "i64" ? "int" : scalar === "f64" ? "float" : "bool";
3141
- const bind = scalar === "String" ? "sv.clone()" : "*sv";
3142
- // bc#90 / runtime-free: build the module-LOCAL BehaviorError (TYPE_MISMATCH) via the local
3143
- // marshal_type_error helper — decode_* returns the local error, bridged at the observe boundary.
3144
- lines.push(` match v { ${pat} => ${field} = ${bind}, other => return Err(marshal_type_error(${rustStrLit(`decode input ${p}: expected ${label}, got `)}, other.type_name())) }`);
3145
- }
3146
- });
3147
- lines.push(` }`);
3148
- lines.push(` }`);
3149
- lines.push(` Ok((${args.join(", ")},))`);
3150
- lines.push(`}`);
3151
- return lines.join("\n");
3152
- }
3153
2728
  export const rustTypedNativeEmitter = {
3154
2729
  language: "rust-typed-native",
3155
2730
  classification: "codegen", // native: 型付きフラットコード生成・IR/dict 非在(#128/A6)