behavior-contracts 0.11.22 → 0.12.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.
Files changed (76) hide show
  1. package/cli-contract.yaml +27 -20
  2. package/dist/behavior.d.ts +5 -0
  3. package/dist/behavior.d.ts.map +1 -1
  4. package/dist/behavior.js +11 -3
  5. package/dist/behavior.js.map +1 -1
  6. package/dist/cli.js +3 -3
  7. package/dist/cli.js.map +1 -1
  8. package/dist/generated/contract.d.ts.map +1 -1
  9. package/dist/generated/contract.js +2 -2
  10. package/dist/generated/contract.js.map +1 -1
  11. package/dist/generated/program.js +4 -4
  12. package/dist/generated/program.js.map +1 -1
  13. package/dist/generator/core.d.ts +13 -10
  14. package/dist/generator/core.d.ts.map +1 -1
  15. package/dist/generator/core.js.map +1 -1
  16. package/dist/generator/emit-native-dynamic.d.ts +203 -0
  17. package/dist/generator/emit-native-dynamic.d.ts.map +1 -0
  18. package/dist/generator/emit-native-dynamic.js +733 -0
  19. package/dist/generator/emit-native-dynamic.js.map +1 -0
  20. package/dist/generator/emit-native-php.d.ts +4 -0
  21. package/dist/generator/emit-native-php.d.ts.map +1 -0
  22. package/dist/generator/emit-native-php.js +668 -0
  23. package/dist/generator/emit-native-php.js.map +1 -0
  24. package/dist/generator/emit-native-python.d.ts +4 -0
  25. package/dist/generator/emit-native-python.d.ts.map +1 -0
  26. package/dist/generator/emit-native-python.js +592 -0
  27. package/dist/generator/emit-native-python.js.map +1 -0
  28. package/dist/generator/emit-php.d.ts +4 -0
  29. package/dist/generator/emit-php.d.ts.map +1 -1
  30. package/dist/generator/emit-php.js +6 -2
  31. package/dist/generator/emit-php.js.map +1 -1
  32. package/dist/generator/emit-python.d.ts +4 -0
  33. package/dist/generator/emit-python.d.ts.map +1 -1
  34. package/dist/generator/emit-python.js +2 -2
  35. package/dist/generator/emit-python.js.map +1 -1
  36. package/dist/generator/emit-shared-go-typed.d.ts +5 -78
  37. package/dist/generator/emit-shared-go-typed.d.ts.map +1 -1
  38. package/dist/generator/emit-shared-go-typed.js +8 -315
  39. package/dist/generator/emit-shared-go-typed.js.map +1 -1
  40. package/dist/generator/emit-shared-go.d.ts +12 -16
  41. package/dist/generator/emit-shared-go.d.ts.map +1 -1
  42. package/dist/generator/emit-shared-go.js +12 -1037
  43. package/dist/generator/emit-shared-go.js.map +1 -1
  44. package/dist/generator/emit-shared-rust-typed.d.ts +0 -93
  45. package/dist/generator/emit-shared-rust-typed.d.ts.map +1 -1
  46. package/dist/generator/emit-shared-rust-typed.js +7 -46
  47. package/dist/generator/emit-shared-rust-typed.js.map +1 -1
  48. package/dist/generator/emit-shared-rust.d.ts +5 -38
  49. package/dist/generator/emit-shared-rust.d.ts.map +1 -1
  50. package/dist/generator/emit-shared-rust.js +3 -1249
  51. package/dist/generator/emit-shared-rust.js.map +1 -1
  52. package/dist/generator/emit-typed-native-go.d.ts.map +1 -1
  53. package/dist/generator/emit-typed-native-go.js +31 -541
  54. package/dist/generator/emit-typed-native-go.js.map +1 -1
  55. package/dist/generator/emit-typed-native-rust.d.ts.map +1 -1
  56. package/dist/generator/emit-typed-native-rust.js +33 -455
  57. package/dist/generator/emit-typed-native-rust.js.map +1 -1
  58. package/dist/generator/index.d.ts +2 -0
  59. package/dist/generator/index.d.ts.map +1 -1
  60. package/dist/generator/index.js +9 -1
  61. package/dist/generator/index.js.map +1 -1
  62. package/dist/generator/native-coverage.d.ts +162 -0
  63. package/dist/generator/native-coverage.d.ts.map +1 -0
  64. package/dist/generator/native-coverage.js +412 -0
  65. package/dist/generator/native-coverage.js.map +1 -0
  66. package/dist/generator/native-expr.d.ts +1 -1
  67. package/dist/generator/native-expr.d.ts.map +1 -1
  68. package/dist/generator/straightline.d.ts +24 -6
  69. package/dist/generator/straightline.d.ts.map +1 -1
  70. package/dist/generator/straightline.js +79 -1
  71. package/dist/generator/straightline.js.map +1 -1
  72. package/dist/generator/typed.d.ts +6 -0
  73. package/dist/generator/typed.d.ts.map +1 -1
  74. package/dist/generator/typed.js +17 -0
  75. package/dist/generator/typed.js.map +1 -1
  76. package/package.json +1 -1
@@ -1,22 +1,15 @@
1
1
  import { entryPortOrder, GeneratorFailure } from "./core.js";
2
- import { mapTransformExpr, isControlGate, mapNodeElemIsOpaqueWire, nodeWirePassthrough } from "../behavior.js";
2
+ import { mapTransformExpr, 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
5
  import { buildTypePlan, deriveTypeRef, findDecl, inputPortIsOptional, inputPortTypeRef, lowerProducedAwareRead, unproducedInSlot } from "./typed.js";
6
- import { concurrencyPlan, execPlan, analyzeSequentialOps, opsLiteralOf, classifyExpr, nodeNarrowedPaths } from "./straightline.js";
6
+ import { execPlan, analyzeSequentialOps, opsLiteralOf, classifyExpr, nodeNarrowedPaths } from "./straightline.js";
7
7
  import { NativeExprCompiler } from "./native-expr.js";
8
+ import { NativeCoverage, buildTypedNodes, fanoutItemsElemRef, mapElemRowRef, resolveOverOrFail } from "./native-coverage.js";
8
9
  import { buildAsyncPlans } from "./async-plan.js";
9
- import { buildDeBoxPlan, buildWirePlan, notationOfRef } from "./emit-shared-debox.js";
10
+ import { buildDeBoxPlan, buildWirePlan } from "./emit-shared-debox.js";
10
11
  const { sanitize, rustStrLit } = rustStraightlineInternals;
11
12
  const { typeRefIsCopy, rustFieldName, renderTypeRef, typedCell, typedFieldAccess, serializeTyped, emitTypeDecls, emitDefaults, emitTypedValue, rustCellRead, rustCellPathRead, checkOutputFieldType, emitMarshallers, emitMarshalHelpers, } = rustTypedInternals;
12
- /** rustErr — build the LOCAL concrete error value for a behavior/plan failure on the covered read
13
- * plane (runtime-free). The covered module declares a local `BehaviorError` (see emitBehaviorErrorType);
14
- * the runner returns `Result<_, BehaviorError>` over THAT local type. This REPLACES the old
15
- * `behavior_contracts::BehaviorError::new(...)` (the last error-plane runtime coupling) — the SAME codes
16
- * are preserved verbatim so the observed failure is byte-equal to run_behavior. */
17
- function rustErr(code, msgExpr) {
18
- return `BehaviorError::new(${JSON.stringify(code)}, ${msgExpr})`;
19
- }
20
13
  /** emitErrorTypeDefs — the LOCAL concrete error TYPE (ErrorKind + ErrorDetail + BehaviorError + impls),
21
14
  * runtime-free. Baked into the covered module (no --shared-types-import) OR into the shared crate (#165,
22
15
  * --shared-types-import) so a cross-crate transport can return `Result<WireValue, BehaviorError>`. Codes
@@ -183,9 +176,6 @@ fn de_missing_field(model: &str, field: &str, expected: &str) -> BehaviorError {
183
176
  function emitBehaviorErrorType() {
184
177
  return `${emitErrorTypeDefs()}\n\n${emitErrorHelpers()}`;
185
178
  }
186
- function pascal(s) {
187
- return s.replace(/[^A-Za-z0-9]+/g, " ").split(" ").filter(Boolean).map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join("") || "X";
188
- }
189
179
  /**
190
180
  * resolveLeafSymbol — the op-agnostic transport symbol a covered leaf (= catalog component) is called
191
181
  * through at its execution point. A consumer-supplied override (`leafTransport.symbols[component]`) wins;
@@ -782,22 +772,7 @@ const returnErrFail = (errValueExpr) => `return Err(${errValueExpr})`;
782
772
  function renderResultDeBox(ref, srcExpr, nodeId, plan, indent, fail = returnErrFail, passthrough = false) {
783
773
  return renderRustDeBox(buildDeBoxPlan(ref, { from: "top" }, { model: nodeId, field: nodeId, plan }, passthrough), srcExpr, { n: 0 }, indent, fail, null);
784
774
  }
785
- /** mapFanoutElemRef — the element ROW TypeRef a map/fanout node decodes (the per-element record). */
786
- function mapFanoutElemRef(node, typedNodes, plan) {
787
- const ref = typedNodes.get(node.id);
788
- if ("fanout" in node)
789
- return fanoutItemsElemRef(node, ref, plan);
790
- return mapElemRowRef(node, ref, plan);
791
- }
792
- function staticArrElems(node) {
793
- if (node === null || typeof node !== "object" || Array.isArray(node))
794
- return null;
795
- const keys = Object.keys(node);
796
- if (keys.length !== 1 || keys[0] !== "arr")
797
- return null;
798
- const arg = node.arr;
799
- return Array.isArray(arg) ? arg : null;
800
- }
775
+ /** #108: a `$as` element-binding resolver for map ports (rust twin). */
801
776
  /**
802
777
  * portFieldRustType — the NATIVE Rust type for a covered port field (bc#90 / runtime-free). The covered
803
778
  * ports struct carries NO `Value` field: every port lowers to a concrete Rust type.
@@ -888,15 +863,13 @@ function compilePortNode(node, comp, plan, typedNodes, isPrior, where, expected,
888
863
  // no separate input-side integrity gate exists.
889
864
  return c;
890
865
  }
891
- /**
892
- * portFieldRustType — the NATIVE Rust type for a covered port field, read off the ONE port lowering
893
- * (compilePortNode / native-expr). Field type = the compiled TypeRef, so it can never disagree with the
894
- * initializer (emitPortInit), which reads the SAME lowering for its value. `where` names the site.
895
- */
896
- function portFieldRustType(node, comp, plan, typedNodes, expected, where = "port", opts) {
897
- const c = compilePortNode(node, comp, plan, typedNodes, (h) => typedNodes.has(h), where, expected, opts);
898
- return renderTypeRef(c.ref);
899
- }
866
+ /** rustCoverage — the ONE native coverage rule (native-coverage.ts) bound to the Rust port lowering: eligibility
867
+ * asks {@link compilePortNode} — the SAME lowering emission uses, with the SAME narrowing and declared port
868
+ * type — so a port is judged covered iff it also emits. */
869
+ const rustCoverage = new NativeCoverage("rust", "rust typed-native", (node, comp, plan, typedNodes, expected, { asBinding, narrowed }) => {
870
+ const opts = asBinding !== undefined ? { asBinding, asBase: asBinding.name, narrowed } : narrowed !== undefined ? { narrowed } : undefined;
871
+ compilePortNode(node, comp, plan, typedNodes, (h) => typedNodes.has(h), "port", expected, opts);
872
+ });
900
873
  // ── native expression compiler backend (#108) — cond `if` / map `when` / cond branches (Rust) ────────
901
874
  //
902
875
  // The runtime-free native expression compiler (native-expr.ts) mirrors run_behavior's cond/guard with
@@ -1269,33 +1242,6 @@ function boundRustType(node, typedNodes, plan) {
1269
1242
  function mapElemMaterializerName(compName, nodeId) {
1270
1243
  return `materialize_map_elem_${sanitize(compName)}_${typedCell(nodeId)}`;
1271
1244
  }
1272
- /** mapNodeArrRef — the map node's PRODUCED-ARRAY TypeRef from its `outType`.
1273
- *
1274
- * A map node's `outType` is its ELEMENT type (scp-error.md "Map element type"), so the produced array
1275
- * is `{arr: element}`. This is the same reading the compiler applies when it resolves what a node
1276
- * result reference has (`type-gate`: `"map" in n ? {arr:ot} : ot`) — the emitter follows that SSoT
1277
- * rather than inspecting the annotation's shape, so an element that is ITSELF an `arr` stays
1278
- * expressible (element `arr(T)` produces `arr(arr(T))`). */
1279
- function mapNodeArrRef(node, plan) {
1280
- const outT = node.outType;
1281
- return deriveTypeRef({ arr: outT }, plan);
1282
- }
1283
- /** mapElemRowRef — the handler's per-element RETURN shape for a covered map node: the `into` field's
1284
- * type (into) or the element outType directly (no-into). This is the type of RawElemNR<Comp><Node>. */
1285
- function mapElemRowRef(node, arrRef, plan) {
1286
- const m = node.map;
1287
- if (m.into === undefined)
1288
- return arrRef.elem;
1289
- if (arrRef.elem.kind !== "named") {
1290
- throw new GeneratorFailure("UNSUPPORTED_NODE_STRAIGHTLINE", `rust combined map (#86 pt2): node '${node.id}' element outType must be a named struct — regenerate as boxed typed/straight-line.`);
1291
- }
1292
- const decl = findDecl(plan, arrRef.elem.name);
1293
- const intoField = decl.fields.find((f) => f.name === m.into);
1294
- if (!intoField) {
1295
- throw new GeneratorFailure("UNSUPPORTED_NODE_STRAIGHTLINE", `rust combined map (#86 pt2): element struct '${arrRef.elem.name}' has no '${m.into}' (into) field.`);
1296
- }
1297
- return intoField.type;
1298
- }
1299
1245
  /**
1300
1246
  * emitMapElemMaterializers — for each covered map...into node, emit the AUGMENTED-element copier: copy
1301
1247
  * the over element's typed fields + place the already-de-boxed `into` value into its field. Pure struct
@@ -1311,9 +1257,8 @@ function emitMapElemMaterializers(comp, typedNodes, plan) {
1311
1257
  if (m.into === undefined)
1312
1258
  continue;
1313
1259
  const arrRef = typedNodes.get(n.id);
1314
- if (arrRef.kind !== "arr" || arrRef.elem.kind !== "named") {
1315
- throw new GeneratorFailure("UNSUPPORTED_NODE_STRAIGHTLINE", `rust combined map (#86 pt2): node '${n.id}' element outType must be a named struct — regenerate as boxed typed/straight-line.`);
1316
- }
1260
+ // the into element is a named struct with an `into` field (mapElemRowRef fails closed otherwise).
1261
+ const intoRowRef = mapElemRowRef("rust", n, arrRef, plan);
1317
1262
  const elemRef = arrRef.elem;
1318
1263
  const decl = findDecl(plan, elemRef.name);
1319
1264
  const intoKey = m.into;
@@ -1321,7 +1266,6 @@ function emitMapElemMaterializers(comp, typedNodes, plan) {
1321
1266
  const overFields = decl.fields.filter((f) => f.name !== intoKey);
1322
1267
  const overElemTy = mapOverElemType(comp, n, typedNodes, plan);
1323
1268
  const fn = mapElemMaterializerName(comp.name, n.id);
1324
- const intoRowRef = mapElemRowRef(n, arrRef, plan);
1325
1269
  const inits = [];
1326
1270
  // Copy scalars (i64/f64/bool) copy directly; String/named/arr/opt clone (clippy clone_on_copy clean).
1327
1271
  for (const f of overFields) {
@@ -1392,39 +1336,23 @@ function rustOverAccess(s, place, optArr, awaits) {
1392
1336
  };
1393
1337
  }
1394
1338
  /**
1395
- * rustOverElemInfo — the ONE resolver of a fanout/map `over` to its element TypeRef + how the arm reads
1396
- * the collection (map/fanout twins both delegate — single definition, no forked copy). It is the only
1397
- * place that knows WHERE the collection lives, so it is the only place that can say how an arm may read
1398
- * it: {@link rustOverAccess} renders that, given whether the arm suspends.
1339
+ * rustOverElemInfo — the Rust read of a fanout/map `over` collection (map/fanout twins both delegate). The
1340
+ * element TypeRef, the optional-array flag and WHERE the collection lives come from the ONE resolver
1341
+ * {@link resolveOverOrFail} (native-coverage.ts); {@link rustOverAccess} renders how an arm may read it,
1342
+ * given whether the arm suspends.
1399
1343
  *
1400
1344
  * An opt-arr over (a prior-node `{opt:{arr}}` field OR an OPT input array port) iterates EMPTY on null
1401
1345
  * (#177 (A)), byte-equal to run_behavior. A REQUIRED arr still fails run_behavior FANOUT/MAP_OVER_NOT_ARRAY.
1402
1346
  */
1403
1347
  function rustOverElemInfo(comp, over, typedNodes, plan, nodeId, label) {
1404
1348
  const s = sanitize(nodeId);
1405
- const e = classifyExpr(over);
1406
- if (e.kind === "ref" && e.path.length >= 1 && typedNodes.has(e.path[0])) {
1407
- const baseRef = typedNodes.get(e.path[0]);
1408
- const { ref } = typedFieldAccess(`${typedCell(e.path[0])}.borrow()`, baseRef, e.path.slice(1), plan);
1409
- const fieldPath = e.path.slice(1).map((p) => `.${rustFieldName(p)}`).join("");
1410
- const cell = { at: "cell", cell: typedCell(e.path[0]), fieldPath };
1411
- if (ref.kind === "arr")
1412
- return { elemRef: ref.elem, over: (awaits) => rustOverAccess(s, cell, false, awaits) };
1413
- if (ref.kind === "opt" && ref.inner.kind === "arr")
1414
- return { elemRef: ref.inner.elem, over: (awaits) => rustOverAccess(s, cell, true, awaits) };
1415
- }
1416
- if (e.kind === "ref" && e.path.length === 1) {
1417
- const schema = comp.inputPorts?.[e.path[0]];
1418
- const et = schema?.elemType;
1419
- // #192: read the input array port by its positional PARAM name (= rustFieldName(port), same name
1420
- // source as the seam) — box removed, no `in_.` prefix.
1421
- if (et !== undefined) {
1422
- const local = { at: "local", expr: rustFieldName(e.path[0]) };
1423
- const optArr = inputPortIsOptional(schema);
1424
- return { elemRef: deriveTypeRef(et, plan), over: (awaits) => rustOverAccess(s, local, optArr, awaits) };
1425
- }
1426
- }
1427
- throw new GeneratorFailure("UNSUPPORTED_NODE_STRAIGHTLINE", `rust ${label}: '${nodeId}' 'over' must be a ref to a prior node's typed arr field OR an input array port with a declared elemType. BC does not infer input-array element types (consumer-interface C3).`);
1349
+ const r = resolveOverOrFail("rust", comp, over, typedNodes, plan, nodeId, label);
1350
+ // #192: an input array port is read by its positional PARAM name (= rustFieldName(port), same name source
1351
+ // as the seam) — box removed, no `in_.` prefix.
1352
+ const place = r.source.kind === "node"
1353
+ ? { at: "cell", cell: typedCell(r.source.head), fieldPath: r.source.path.map((p) => `.${rustFieldName(p)}`).join("") }
1354
+ : { at: "local", expr: rustFieldName(r.source.port) };
1355
+ return { elemRef: r.elemRef, over: (awaits) => rustOverAccess(s, place, r.optArr, awaits) };
1428
1356
  }
1429
1357
  function mapOverElemInfo(comp, node, typedNodes, plan) {
1430
1358
  return rustOverElemInfo(comp, node.map.over, typedNodes, plan, node.id, "combined map (#108)");
@@ -1434,339 +1362,10 @@ function mapOverElemType(comp, node, typedNodes, plan) {
1434
1362
  return renderTypeRef(mapOverElemInfo(comp, node, typedNodes, plan).elemRef);
1435
1363
  }
1436
1364
  // ── eligibility ─────────────────────────────────────────────────────────────────────
1437
- function reconstructR(e) {
1438
- switch (e.kind) {
1439
- case "str":
1440
- return e.value;
1441
- case "bool":
1442
- return e.value;
1443
- case "null":
1444
- return null;
1445
- case "ref":
1446
- return { [e.opt ? "refOpt" : "ref"]: e.path };
1447
- case "concat":
1448
- return { concat: e.parts.map(reconstructR) };
1449
- case "dynamic":
1450
- return e.node;
1451
- }
1452
- }
1453
- /**
1454
- * numLiteralRustExpr — a BARE numeric port literal (JSON number, e.g. the `limit: 20` Query port).
1455
- * `classifyExpr` leaves a bare number `dynamic` (its checked int/float range rules are the evaluate
1456
- * SSoT), so it never reaches the static str/bool/null branch — but a number literal IS statically
1457
- * resolvable to a native `Value`: the SAME range check the runtime applies (integral literal in the
1458
- * safe 2^53-1 window → Value::Int; a fractional/exponent literal → the checked Value::Float) is
1459
- * performed HERE at generation time. Returns the Rust expression for the literal's Value, or null
1460
- * when the node is not a bare number OR an integral literal is out of the safe window (keeping the
1461
- * runtime INVALID_LITERAL semantics — the port is not covered natively, the component falls through).
1462
- * Mirrors behavior_contracts eval of a bare number literal exactly.
1463
- */
1464
- const NUM_SAFE_INT_R = 9007199254740991; // 2^53 - 1 (expr safeInt)
1465
- function numLiteralRustExpr(node) {
1466
- if (typeof node !== "number" || !Number.isFinite(node))
1467
- return null;
1468
- if (Number.isInteger(node)) {
1469
- if (node < -NUM_SAFE_INT_R || node > NUM_SAFE_INT_R)
1470
- return null; // out of safe window → not covered
1471
- return `Value::Int(${node}i64)`;
1472
- }
1473
- // fractional / exponent literal → checked f64 (finite, guaranteed above).
1474
- return `Value::Float(${node}f64)`;
1475
- }
1476
- /** A port node is static (literal / ref / concat of those / static arr / bare number literal) —
1477
- * resolvable to a native Value with no Obj / no evaluate interpreter. */
1478
- /** planForComp — a TypePlan for a single component (its named types are component-scoped). */
1479
- function planForComp(comp) {
1480
- return buildTypePlan({ irVersion: 2, exprVersion: 2, components: [comp] });
1481
- }
1482
- /** buildTypedNodes — the prior-node typed-cell TypeRef map (control-gate nodes typeless; a map node
1483
- * carries its produced-array ref). An untyped node is omitted. */
1484
- function buildTypedNodes(comp, plan) {
1485
- const typedNodes = new Map();
1486
- for (const n of comp.body) {
1487
- if (isControlGate(n))
1488
- continue;
1489
- try {
1490
- typedNodes.set(n.id, "map" in n ? mapNodeArrRef(n, plan) : deriveTypeRef(n.outType, plan));
1491
- }
1492
- catch {
1493
- /* untyped node — omit */
1494
- }
1495
- }
1496
- return typedNodes;
1497
- }
1498
- /** mapAsBinding — the `$as` element binding for a map node's element ports, or undefined (uncovered). */
1499
- function mapAsBinding(comp, node, typedNodes, plan) {
1500
- try {
1501
- return { name: node.map.as, ref: mapOverElemInfo(comp, node, typedNodes, plan).elemRef, plan };
1502
- }
1503
- catch {
1504
- return undefined;
1505
- }
1506
- }
1507
- /** portIsStatic — the ELIGIBILITY gate ASKS the one port lowering (compilePortNode / native-expr) whether
1508
- * it can lower this port. A port that does not lower (or lowers fallibly) fails closed. */
1509
- function portIsStatic(node, comp, plan, typedNodes, expected, asBinding, narrowed) {
1510
- try {
1511
- // #170: eligibility asks the SAME lowering emission uses, with the SAME node narrowing — so a
1512
- // gate/guard-proven opt-in-required port is judged covered iff it also emits (they cannot disagree).
1513
- // #173: with the SAME declared `expected` port type (so covered iff it materializes to that type).
1514
- const opts = asBinding !== undefined ? { asBinding, asBase: asBinding.name, narrowed } : narrowed !== undefined ? { narrowed } : undefined;
1515
- compilePortNode(node, comp, plan, typedNodes, (h) => typedNodes.has(h), "port", expected, opts);
1516
- return true;
1517
- }
1518
- catch {
1519
- return false;
1520
- }
1521
- }
1522
- /** The output must lower to a typed struct/value with no scope read: a ref to a BODY NODE, an
1523
- * obj/arr of such, or a concat. A ref to an input param / non-concat operator is not lowerable. */
1524
- function outputIsNativeLowerable(comp) {
1525
- const bodyIds = new Set(comp.body.map((n) => n.id));
1526
- const walk = (node) => {
1527
- const arr = staticArrElems(node);
1528
- if (arr !== null)
1529
- return arr.every(walk);
1530
- if (node !== null && typeof node === "object" && !Array.isArray(node)) {
1531
- const keys = Object.keys(node);
1532
- if (keys.length === 1 && keys[0] === "obj") {
1533
- const obj = node.obj;
1534
- return Object.keys(obj).every((k) => walk(obj[k]));
1535
- }
1536
- if (keys.length === 1 && keys[0] === "arr")
1537
- return true;
1538
- }
1539
- const e = classifyExpr(node);
1540
- if (e.kind === "str" || e.kind === "bool" || e.kind === "null")
1541
- return true;
1542
- if (e.kind === "ref")
1543
- return bodyIds.has(e.path[0]);
1544
- if (e.kind === "concat")
1545
- return e.parts.every((p) => walk(reconstructR(p)));
1546
- return false;
1547
- };
1548
- return walk(comp.output);
1549
- }
1550
- /**
1551
- * coveredMapNode — the #86 part 2 covered map shape (nestedBatchGet), rust twin of the go predicate.
1552
- */
1553
- function coveredMapNode(n, bodyIds, comp) {
1554
- if (n === null || typeof n !== "object" || !("map" in n))
1555
- return false;
1556
- const m = n.map;
1557
- // #108 (rust twin of the go predicate): a guarded map (`when`) IS covered with NO `into`. #177/#182/#232:
1558
- // a `map...into` ALWAYS has a well-defined unproduced value for the into field — OPT (unproduced → None,
1559
- // #177) OR relationKind:connection (unproduced → the empty connection {items:[],cursor:null}, #182).
1560
- // Byte-equal to run_behavior applyInto. The type gate (`mapIntoHoldsUnproduced`, run for every component
1561
- // at the codegen entry) rejects anything else BEFORE any emitter sees it (#232). over element type must be
1562
- // statically resolvable: prior-node arr field, or an input array port carrying `elemType` (BC does not
1563
- // infer — consumer-interface C3).
1564
- if (m.relationKind !== undefined && m.relationKind !== "connection")
1565
- return false;
1566
- // A map node must carry an outType (its ELEMENT type per the recorder SoT — authoring.ts recordMap
1567
- // holds `node.outType = mapElem`, the PRE-array-wrap element; the emitter synthesizes the produced
1568
- // `[]element`). A map WITHOUT outType is uncovered. (Legacy hand-built IR that already carries the
1569
- // `{arr:element}` produced form is ALSO accepted — mapNodeElemRef normalizes both to the element.)
1570
- // bc#164: an OPAQUE ELEMENT (`outType:"value"` on an output-passthrough map — mapNodeElemIsOpaqueWire,
1571
- // the shared rule) IS covered: each element wire is stored AS-IS in the produced list (no de-box, no
1572
- // per-op re-box), exactly as the componentRef path treats a passthrough result. Any other non-compound
1573
- // element type stays uncovered (loud), as before.
1574
- const outT = n.outType;
1575
- // #225: 純式 map(`transform`)の要素は**式から native に組む**(ワイヤも de-box も無い)ので、要素型が
1576
- // スカラでも被覆される — 宣言型 materializer が組めれば良く、組めなければそこで loud に落ちる。
1577
- // Component map は要素 wire を de-box するので従来どおり compound / opaque wire に限る。
1578
- const isTransformMap = mapTransformExpr(m) !== undefined;
1579
- if (outT === undefined)
1580
- return false;
1581
- if (!isTransformMap && typeof outT !== "object" && !mapNodeElemIsOpaqueWire(n))
1582
- return false;
1583
- const overE = classifyExpr(m.over);
1584
- if (overE.kind !== "ref")
1585
- return false;
1586
- const head = overE.path[0];
1587
- if (!bodyIds.has(head)) {
1588
- // input-array over: covered only when the port declares elemType (#108 — C3, no inference). #177 (A):
1589
- // an OPT input array (`{opt:{arr}}`, required:false) IS covered — its null iterates EMPTY
1590
- // (rustOverAccess collapses None to an empty collection), byte-equal to run_behavior.
1591
- if (overE.path.length !== 1)
1592
- return false;
1593
- const schema = comp.inputPorts?.[head];
1594
- if (schema === undefined || schema.elemType === undefined)
1595
- return false;
1596
- }
1597
- // 純式 map(#222)は port を持たない: 被覆条件は「要素式が宣言された要素型へ native に materialize
1598
- // できること」で、それは compilePortNode(宣言型 materializer)が失敗したときに loud に落ちる。
1599
- const ports = (m.ports ?? {});
1600
- const plan = planForComp(comp);
1601
- const typedNodes = buildTypedNodes(comp, plan);
1602
- const asBinding = mapAsBinding(comp, n, typedNodes, plan);
1603
- const narrowed = nodeNarrowedPaths(comp, n);
1604
- const mSchemas = m.portSchemas;
1605
- for (const p of Object.keys(ports))
1606
- if (!portIsStatic(ports[p], comp, plan, typedNodes, inputPortTypeRef(mSchemas?.[p], plan), asBinding, narrowed))
1607
- return false;
1608
- return true;
1609
- }
1610
- /** coveredFanoutNode (v3, rust twin) — a first-class fanout node is covered when its over is a covered
1611
- * ref (prior-node arr / input array with elemType) and its element ports are static. See the go twin. */
1612
- function coveredFanoutNode(n, bodyIds, comp) {
1613
- if (n === null || typeof n !== "object" || !("fanout" in n))
1614
- return false;
1615
- const f = n.fanout;
1616
- if (f.relationKind !== "connection")
1617
- return false;
1618
- const overE = classifyExpr(f.over);
1619
- if (overE.kind !== "ref")
1620
- return false;
1621
- const head = overE.path[0];
1622
- if (!bodyIds.has(head)) {
1623
- // input-array over: covered only when the port declares elemType (C3 — no inference). #177 (A): an OPT
1624
- // input array (`{opt:{arr}}`, required:false) IS covered — its null iterates EMPTY
1625
- // (rustOverAccess collapses None to an empty collection), byte-equal to run_behavior.
1626
- if (overE.path.length !== 1)
1627
- return false;
1628
- const schema = comp.inputPorts?.[head];
1629
- if (schema === undefined || schema.elemType === undefined)
1630
- return false;
1631
- }
1632
- const ports = f.ports;
1633
- const plan = planForComp(comp);
1634
- const typedNodes = buildTypedNodes(comp, plan);
1635
- let asBinding;
1636
- try {
1637
- asBinding = { name: f.as, ref: fanoutOverElemInfo(comp, n, typedNodes, plan).elemRef, plan };
1638
- }
1639
- catch {
1640
- asBinding = undefined;
1641
- }
1642
- const fSchemas = f.portSchemas;
1643
- for (const p of Object.keys(ports))
1644
- if (!portIsStatic(ports[p], comp, plan, typedNodes, inputPortTypeRef(fSchemas?.[p], plan), asBinding))
1645
- return false;
1646
- return true;
1647
- }
1648
- /** fanoutItemsElemRef (v3, rust twin) — the connection items element TypeRef for a covered fanout node. */
1649
- function fanoutItemsElemRef(node, connRef, plan) {
1650
- if (connRef.kind !== "named")
1651
- throw new GeneratorFailure("UNSUPPORTED_NODE_STRAIGHTLINE", `rust fanout (v3): node '${node.id}' outType must be a connection struct {items,cursor} (got ${JSON.stringify(connRef.kind)}).`);
1652
- const decl = findDecl(plan, connRef.name);
1653
- const itemsField = decl.fields.find((fd) => fd.name === "items");
1654
- if (!itemsField || itemsField.type.kind !== "arr")
1655
- throw new GeneratorFailure("UNSUPPORTED_NODE_STRAIGHTLINE", `rust fanout (v3): node '${node.id}' connection struct '${connRef.name}' has no 'items' array field.`);
1656
- return itemsField.type.elem;
1657
- }
1658
1365
  /** fanoutOverElemInfo (v3, rust twin) — delegates to {@link rustOverElemInfo} reading the fanout spec. */
1659
1366
  function fanoutOverElemInfo(comp, node, typedNodes, plan) {
1660
1367
  return rustOverElemInfo(comp, node.fanout.over, typedNodes, plan, node.id, "fanout (v3)");
1661
1368
  }
1662
- /** A covered read SHAPE with static ports + native-lowerable output (+ covered map...into), OR a
1663
- * real-concurrency staged plan (bc#87) whose parallel-stage members are plain componentRef point reads. */
1664
- function isSequentialComponentRefRead(comp) {
1665
- return coverageRejectReason(comp) === null;
1666
- }
1667
- /**
1668
- * coverageRejectReason — the DIAGNOSTIC twin of isSequentialComponentRefRead (bc#86/#89), rust twin of
1669
- * the go predicate. Returns null when the component IS a covered native read; otherwise a SPECIFIC
1670
- * human-readable reason naming the exact disqualifier and the offending node id. The predicate logic is
1671
- * IDENTICAL to isSequentialComponentRefRead (defined as `coverageRejectReason(c) === null`) so the two
1672
- * can never disagree. This is the message the fail-closed dispatch surfaces per non-native component.
1673
- */
1674
- function coverageRejectReason(comp) {
1675
- const crPlan = planForComp(comp);
1676
- const crTypedNodes = buildTypedNodes(comp, crPlan);
1677
- const ep = execPlan(comp);
1678
- if (ep === null)
1679
- return "component is not a straight-line/staged sequential exec plan (no static exec plan)";
1680
- // #114: a bindField relation child (single|connection) IS covered inside a parallel stage — the
1681
- // sibling hasMany fan-out (parent → members ∥ permissions). Its bound-key skip-gate is preflighted
1682
- // per member (from the settled parent) BEFORE dispatch, so the scoped-thread fan-out keeps
1683
- // run_behavior's per-member skip semantics; the shared relationKind constraint below (single|
1684
- // connection) applies to it too. A map member still falls through (its per-element loop is a further
1685
- // shape). Kept fail-closed: a non-componentRef member is rejected.
1686
- for (const [i] of ep.parallelStageOf) {
1687
- const n = comp.body[i];
1688
- // #125/#108: a cond node IS allowed as a parallel-stage member — it is a pure Expression (no
1689
- // dispatch), settled in ascending preflight order, so its produced flag / typed result cell is
1690
- // settled before any dispatch. No handler, no boxed result — it does not disturb the bounded-
1691
- // concurrency error-precedence protocol. Covers BOTH the when(...) control-gate cond (#136,
1692
- // {ok}/null skip marker) AND the Φ-merge VALUE cond (#108, has outType — the sibling Φ-join). A
1693
- // value cond's outType requirement is enforced by the per-node cond check below, so a parallel
1694
- // value cond without outType still loud-rejects there.
1695
- // #225: 純式 map(`map.transform`)も cond と同じ性質(handler も boxed result も無い変換)なので、
1696
- // 昇順 preflight で確定させれば error-precedence 協定を乱さない。免除根拠は go 側と同一。
1697
- if ("cond" in n)
1698
- continue;
1699
- if ("map" in n && mapTransformExpr(n.map) !== undefined)
1700
- continue;
1701
- if (!("component" in n))
1702
- return `node '${n.id}' is a non-componentRef member of a parallel stage (not native-covered)`;
1703
- }
1704
- const bodyIds = new Set(comp.body.map((b) => b.id));
1705
- for (const n of comp.body) {
1706
- if ("cond" in n) {
1707
- // #125: a when(...) control-gate cond (`{if, then:{obj:{ok:true}}, else:null}`) は制御スキップ
1708
- // マーカーで出力データ型を持たない(A3 の typeless design)— outType を要求しない。gate は `if` を
1709
- // native bool へコンパイルし produced_<gate> に写すだけで、分岐内ノードは既存の
1710
- // `parent=gate, bindField:"ok"` skip-gate(run_behavior の null-binding skip)が実行選択する。
1711
- if (isControlGate(n))
1712
- continue;
1713
- // #108: a DATA-JOIN cond node (Φ 合流) is native-covered (its if/then/else compile via the runtime-
1714
- // free NativeExprCompiler; an uncovered expr fails closed at emit). A data-join cond requires outType
1715
- // (合流値を de-box する対象だから — control gate だけがこの要求を免除される)。
1716
- if (n.outType === undefined)
1717
- return `node '${n.id}' cond has no outType (required to de-box the branch join)`;
1718
- continue;
1719
- }
1720
- if ("fanout" in n) {
1721
- if (!coveredFanoutNode(n, bodyIds, comp))
1722
- return `node '${n.id}' is a non-covered fanout shape (over an input array without elemType, or a dynamic element port)`;
1723
- continue;
1724
- }
1725
- if ("map" in n) {
1726
- if (!coveredMapNode(n, bodyIds, comp))
1727
- return `node '${n.id}' is a non-covered map shape (guard+into heterogeneous, or over an input array without elemType)`;
1728
- continue;
1729
- }
1730
- if (!("component" in n))
1731
- return `node '${n.id}' is not a componentRef, map, or cond node (not native-covered)`;
1732
- const cr = n;
1733
- // Every Error Policy Kind IS covered on a componentRef (see the go emitter's note): `continue` →
1734
- // unproduced (produced-aware output), `retry` → `fail`'s control flow with the Kind in the message.
1735
- // relationKind の閉集合は `connection` の 1 値で、**注記の不在**が「未生成は null」を意味する。ゆえに
1736
- // bindField 由来 skip は 2 形(connection = 空 connection / 不在 = null)とも produced-aware 出力が
1737
- // 表現でき、被覆条件は無い(かつての「明示的に single と書け」は既定値の重複綴りの要求だった)。
1738
- if (cr.relationKind !== undefined && cr.relationKind !== "connection")
1739
- return `relationKind '${cr.relationKind}' not native-covered (node '${n.id}')`;
1740
- // #170: a control-gate child's ports may narrow a gate-proven opt ref to non-null (the (a3) gated read).
1741
- const crNarrowed = nodeNarrowedPaths(comp, cr);
1742
- for (const p of Object.keys(cr.ports))
1743
- if (portIsStatic(cr.ports[p], comp, crPlan, crTypedNodes, inputPortTypeRef(cr.portSchemas?.[p], crPlan), undefined, crNarrowed) === false)
1744
- return `node '${n.id}' port '${p}' is not statically resolvable`;
1745
- }
1746
- if (!outputIsNativeLowerable(comp))
1747
- return "output is not natively lowerable";
1748
- return null;
1749
- }
1750
- function isFullyTyped(comp) {
1751
- if (comp.outputType === undefined)
1752
- return false;
1753
- // #125: a control-gate cond is a typeless skip marker (A3) — it never de-boxes a result, so it is
1754
- // exempt from the "every node carries outType" de-box requirement (matches type-gate's exemption).
1755
- for (const n of comp.body)
1756
- if (!isControlGate(n) && n.outType === undefined)
1757
- return false;
1758
- return true;
1759
- }
1760
- function isNativeRaw(comp) {
1761
- return isSequentialComponentRefRead(comp) && isFullyTyped(comp);
1762
- }
1763
- function assertTypedCoverage(comp) {
1764
- if (!isSequentialComponentRefRead(comp))
1765
- return;
1766
- if (isFullyTyped(comp))
1767
- return;
1768
- throw new GeneratorFailure("UNSUPPORTED_NODE_STRAIGHTLINE", `rust combined read (bc#77): component '${comp.name}' is a sequential componentRef read but lacks outType/outputType on every node — the combined emitter de-boxes the RESULT into the node's outType struct, so a covered read MUST be fully typed (bc#45). Add outType annotations, or regenerate on rust-straightline-native (boxed result).`);
1769
- }
1770
1369
  // ── typed input struct (InNR<Comp>) + NATIVE scalar port lowering ────────────────────────────
1771
1370
  /** Rust type for an input port's declared type (scalar → concrete; array+elemType → Vec<ElemT>; else Value). */
1772
1371
  function inputPortRustType(schema, plan, where = "input port") {
@@ -1934,12 +1533,7 @@ function emitNativeRawRunner(comp, plan, ap, leaf, declared) {
1934
1533
  // it starts clean here and is read once the whole body — cond conditions, map guards, port expressions —
1935
1534
  // has been lowered.
1936
1535
  rustExprUsed.boolAlgebra = false;
1937
- const typedNodes = new Map();
1938
- // #125: control-gate は typeless(typedNodes に載せない)。map ノードは produced-array ref に正規化
1939
- // (recorder SoT の element outType を {arr:element} へラップ / legacy {arr} はそのまま)。
1940
- for (const n of comp.body)
1941
- if (!isControlGate(n))
1942
- typedNodes.set(n.id, "map" in n ? mapNodeArrRef(n, plan) : deriveTypeRef(n.outType, plan));
1536
+ const typedNodes = buildTypedNodes(comp, plan);
1943
1537
  // A result is handed on by MOVE at its LAST read (movableRefs) — every earlier reader copies, because the
1944
1538
  // cell still has to hold the value for the ones after it. The lookup is BY SITE: node k's ports get the
1945
1539
  // heads whose last read is k, the output assembly the heads whose last read is the output.
@@ -2535,7 +2129,7 @@ isAsync = false, policy = "fail") {
2535
2129
  // each element is de-boxed strictly INLINE: the handler returns the per-element WIRE and the arm decodes
2536
2130
  // it against the element ref (the `into` field's type for map...into, else the element type). A de-box
2537
2131
  // mismatch fails closed regardless of elementPolicy (matching the interpreter's whole-node outType throw).
2538
- const elemDeBoxRef = mapElemRowRef(node, elemArrRef, plan);
2132
+ const elemDeBoxRef = mapElemRowRef("rust", node, elemArrRef, plan);
2539
2133
  const renderElemDeBox = (il) => renderResultDeBox(elemDeBoxRef, `er_${s}`, node.id, plan, il, returnErrFail, nodeWirePassthrough(node));
2540
2134
  // #177/#182 keep-with-skip-value: the into value for a guard-skipped element is driven by relationKind,
2541
2135
  // NOT by opt-ness (matching run_behavior applyInto, which fills a connection into with the empty
@@ -2790,7 +2384,7 @@ function emitFanoutArm(comp, node, atPos, typedNodes, plan, priorNodeAt, leaf, i
2790
2384
  const policyLit = rustStrLit(policy === "retry" ? "retry" : "fail");
2791
2385
  const leafSym = resolveLeafSymbol(f.component, leaf, f.leafSymbol);
2792
2386
  const connRef = typedNodes.get(node.id);
2793
- const elemRef = fanoutItemsElemRef(node, connRef, plan);
2387
+ const elemRef = fanoutItemsElemRef("rust", node, connRef, plan);
2794
2388
  const elemName = renderTypeRef(elemRef);
2795
2389
  const { elemRef: overElemRef, over } = fanoutOverElemInfo(comp, node, typedNodes, plan);
2796
2390
  const ov = over(isAsync);
@@ -3061,23 +2655,10 @@ function emit(ctx) {
3061
2655
  // rust CONSUMES this annotation (async fn + .await where derived); go ignores it. per-node granularity
3062
2656
  // is a strict generalization of increment-1's uniform ioModel:'async' (= every terminal async).
3063
2657
  const asyncPlans = buildAsyncPlans(ctx.ir, ctx.ioModel);
3064
- for (const c of ctx.ir.components)
3065
- assertTypedCoverage(c);
3066
- const native = ctx.ir.components.filter(isNativeRaw);
3067
- const nonNative = ctx.ir.components.filter((c) => !isNativeRaw(c));
3068
- // FAIL CLOSED (bc#86/#89): the --typed-native (native codegen) surface is native-only. Previously a
3069
- // non-covered component was SILENTLY DROPPED (emitted only as a comment note), concealing that it
3070
- // never got native codegen. We now throw a LOUD GeneratorFailure naming every uncovered component +
3071
- // its specific reject reason. A fully-covered module is unchanged.
3072
- if (nonNative.length > 0) {
3073
- const rejects = nonNative
3074
- .map((c) => ` - component '${c.name}': ${coverageRejectReason(c) ?? "not a covered native read"}`)
3075
- .join("\n");
3076
- throw new GeneratorFailure("UNSUPPORTED_NODE_STRAIGHTLINE", `rust typed-native (native codegen) surface: ${nonNative.length} component(s) are NOT a covered native read:\n${rejects}\n\n` +
3077
- `The --typed-native (native codegen) surface is native-only and fail-closed: it does not silently ` +
3078
- `box uncovered shapes. Implement native coverage for this shape, fix the spec if the shape is ` +
3079
- `genuinely runtime-dynamic, or generate this component on the --ir dynamic interpreter surface.`);
3080
- }
2658
+ // FAIL CLOSED (bc#86/#89): the native codegen surface is native-only — every component must be a covered,
2659
+ // fully typed native read (the ONE coverage rule, native-coverage.ts), or generation fails LOUDLY naming
2660
+ // each uncovered component and its specific reason (never a silently dropped / boxed component).
2661
+ const native = rustCoverage.assertCovered(ctx.ir.components);
3081
2662
  if (native.length === 0) {
3082
2663
  // an empty native surface (no covered read) carries no runner and no failure — nothing references
3083
2664
  // bc-runtime, so it stays runtime-free (bc#90) with only the component-names const.
@@ -3110,11 +2691,8 @@ ${withRustfmtSkip(emitStructSurface([]))}
3110
2691
  // in-crate (byte-identical to before). resolveRustWire is the SSoT for this decision.
3111
2692
  const crossPackage = ctx.sharedTypesImport !== undefined;
3112
2693
  for (const c of native) {
3113
- const typedNodes = new Map();
3114
2694
  // build the full typed-node map FIRST so a map's over-element resolution can see every node.
3115
- for (const n of c.body)
3116
- if (!isControlGate(n))
3117
- typedNodes.set(n.id, "map" in n ? mapNodeArrRef(n, plan) : deriveTypeRef(n.outType, plan)); // #125: control-gate typeless; map は produced-array ref に正規化
2695
+ const typedNodes = buildTypedNodes(c, plan);
3118
2696
  // #183: a covered node's ports cross the transport boundary as ONE op-agnostic `WireRow` payload built
3119
2697
  // inline at the call site — there are NO per-node ports structs on the covered plane or the shared crate.
3120
2698
  // #192: no `InNR_<comp>` input box — the entry takes positional params.