behavior-contracts 0.9.0 → 0.9.1

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.
@@ -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, inputPortIsOptional, inputPortTypeRef } from "./typed.js";
5
+ import { buildTypePlan, deriveTypeRef, findDecl, guardedMapIntoIsOpt, 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";
@@ -1233,10 +1233,13 @@ function coveredMapNode(n, bodyIds, comp) {
1233
1233
  if (n === null || typeof n !== "object" || !("map" in n))
1234
1234
  return false;
1235
1235
  const m = n.map;
1236
- // #108 (rust twin of the go predicate): a guarded map (`when`) IS covered with NO `into` (guard+into
1237
- // is heterogeneous — fail-closed). over element type must be statically resolvable: prior-node arr
1238
- // field, or an input array port carrying `elemType` (BC does not infer — consumer-interface C3).
1239
- if (m.when !== undefined && m.into !== undefined)
1236
+ // #108 (rust twin of the go predicate): a guarded map (`when`) IS covered with NO `into`. #177: a
1237
+ // guarded map WITH `into` is covered ONLY when the into field is OPT (keep-with-null — kept element →
1238
+ // present into, guard-skipped element → into=None), byte-equal to run_behavior applyInto pass-through +
1239
+ // opt-into null. A REQUIRED into field → run_behavior FAILS MISSING_PROP on a skipped element, so
1240
+ // fail-close is byte-equal. over element type must be statically resolvable: prior-node arr field, or
1241
+ // an input array port carrying `elemType` (BC does not infer — consumer-interface C3).
1242
+ if (m.when !== undefined && m.into !== undefined && !guardedMapIntoIsOpt(n, comp))
1240
1243
  return false;
1241
1244
  if (m.policy !== undefined && m.policy !== "fail")
1242
1245
  return false;
@@ -1254,11 +1257,17 @@ function coveredMapNode(n, bodyIds, comp) {
1254
1257
  return false;
1255
1258
  const head = overE.path[0];
1256
1259
  if (!bodyIds.has(head)) {
1260
+ // input-array over: covered only when the port declares elemType (#108) AND is REQUIRED. #177: an OPT
1261
+ // input-array (`{opt:{arr}}`, required:false) resolves to `in_.<field>` of `Option<Vec<E>>` — iterating
1262
+ // it does not yield the element type, and run_behavior FAILS MAP_OVER_NOT_ARRAY on a null opt
1263
+ // collection — so fail-close here is byte-equal (a faithful nil→empty over is an owner-level decision).
1257
1264
  if (overE.path.length !== 1)
1258
1265
  return false;
1259
1266
  const schema = comp.inputPorts?.[head];
1260
1267
  if (schema === undefined || schema.elemType === undefined)
1261
1268
  return false;
1269
+ if (inputPortIsOptional(schema))
1270
+ return false;
1262
1271
  }
1263
1272
  const ports = m.ports;
1264
1273
  const plan = planForComp(comp);
@@ -1286,11 +1295,17 @@ function coveredFanoutNode(n, bodyIds, comp) {
1286
1295
  return false;
1287
1296
  const head = overE.path[0];
1288
1297
  if (!bodyIds.has(head)) {
1298
+ // input-array over: covered only when the port declares elemType AND is REQUIRED. #177: an OPT
1299
+ // input-array (`{opt:{arr}}`, required:false) resolves to `in_.<field>` of `Option<Vec<E>>` —
1300
+ // iterating it does not yield the element type, and run_behavior FAILS FANOUT_OVER_NOT_ARRAY on a
1301
+ // null opt collection — so fail-close here is byte-equal (a faithful nil→empty over is owner-level).
1289
1302
  if (overE.path.length !== 1)
1290
1303
  return false;
1291
1304
  const schema = comp.inputPorts?.[head];
1292
1305
  if (schema === undefined || schema.elemType === undefined)
1293
1306
  return false;
1307
+ if (inputPortIsOptional(schema))
1308
+ return false;
1294
1309
  }
1295
1310
  const ports = f.ports;
1296
1311
  const plan = planForComp(comp);
@@ -1980,6 +1995,10 @@ isAsync = false) {
1980
1995
  const batched = m.batched === true;
1981
1996
  const hasInto = m.into !== undefined;
1982
1997
  const hasGuard = m.when !== undefined;
1998
+ // #177 keep-with-null: a guarded map WITH `into` keeps guard-skipped elements with the (opt) into field
1999
+ // set to None (coveredMapNode only admits this when the into field is opt). A guarded NO-into map DROPs
2000
+ // skipped elements instead. Byte-equal to run_behavior's applyInto keep-with-null.
2001
+ const keepWithNull = hasGuard && hasInto;
1983
2002
  const s = sanitize(node.id);
1984
2003
  const structName = portsStructName(comp.name, node.id);
1985
2004
  const batch = `${structName}Batch`;
@@ -2011,19 +2030,27 @@ isAsync = false) {
2011
2030
  return out;
2012
2031
  };
2013
2032
  // #108 guard: compile `when` to a native bool over an element-scoped resolveHead ($as element value,
2014
- // prior node, input port). On skip: `continue` (element excluded — matches run_behavior's keep-gate).
2015
- const emitGuard = (il) => {
2033
+ // prior node, input port). mkGuard returns the compiled {stmts, expr} (or null when unguarded); the
2034
+ // keep-with-null batched path consumes it directly to branch instead of skipping.
2035
+ const mkGuard = () => {
2016
2036
  if (!hasGuard)
2017
- return [];
2037
+ return null;
2018
2038
  const resolveHead = nativeResolveHead(comp, plan, typedNodes, priorHere, { asBinding: { name: asName, ref: overElemRef, plan }, asBase: `oel_${s}` });
2019
- const g = new NativeExprCompiler(makeRustExprBackend(resolveHead, plan)).compileBool(m.when);
2039
+ return new NativeExprCompiler(makeRustExprBackend(resolveHead, plan)).compileBool(m.when);
2040
+ };
2041
+ // On skip: `continue;` by default (element excluded — matches run_behavior's keep-gate); #177
2042
+ // keep-with-null non-batched passes a skip that first pushes the into=None element.
2043
+ const emitGuard = (il, onSkip = "continue;") => {
2044
+ const g = mkGuard();
2045
+ if (g === null)
2046
+ return [];
2020
2047
  const out = [];
2021
2048
  for (const st of g.stmts)
2022
2049
  out.push(`${il}${st}`);
2023
2050
  // bind the keep flag to a var so clippy's nonminimal_bool doesn't rewrite `!(a > b)` (the `when`
2024
2051
  // expr must stay verbatim = run_behavior's `{cond:[when,true,false]}` strict-bool keep-gate).
2025
2052
  out.push(`${il}let __keep = ${rustStripOuterParens(g.expr)};`);
2026
- out.push(`${il}if !__keep { continue; }`);
2053
+ out.push(`${il}if !__keep { ${onSkip} }`);
2027
2054
  return out;
2028
2055
  };
2029
2056
  const lines = [];
@@ -2037,7 +2064,55 @@ isAsync = false) {
2037
2064
  }
2038
2065
  lines.push(`${indent}let over_${s} = ${overExpr};`);
2039
2066
  lines.push(`${indent}let mut built_${s}: Vec<${elemName}> = Vec::with_capacity(over_${s}.len());`);
2040
- if (batched) {
2067
+ if (batched && keepWithNull) {
2068
+ // #177 BATCHED keep-with-null (guarded map...into, opt into): pass 1 records, per over element, whether
2069
+ // it is kept (guard true → build ports) or skipped, preserving ORDER. ONE batched dispatch over the
2070
+ // kept ports, its aligned rows de-boxed into `decs`. Pass 2 re-walks over IN ORDER: a kept element
2071
+ // zips its next deboxed row, a skipped element gets into=None. Byte-equal to run_behavior: batched
2072
+ // keptIdx-aligned collect + applyInto (skipped element unaugmented → opt-into null).
2073
+ const g = mkGuard();
2074
+ lines.push(`${indent}let mut items_${s}: Vec<${structName}> = Vec::with_capacity(over_${s}.len());`);
2075
+ lines.push(`${indent}let mut keep_${s}: Vec<bool> = Vec::with_capacity(over_${s}.len());`);
2076
+ lines.push(`${indent}for oel_${s} in over_${s}.iter() {`);
2077
+ for (const st of g.stmts)
2078
+ lines.push(`${indent} ${st}`);
2079
+ lines.push(`${indent} let __keep = ${rustStripOuterParens(g.expr)};`);
2080
+ lines.push(`${indent} if __keep {`);
2081
+ for (const l of buildPorts(indent + " "))
2082
+ lines.push(l);
2083
+ lines.push(`${indent} items_${s}.push(ep_${s});`);
2084
+ lines.push(`${indent} keep_${s}.push(true);`);
2085
+ lines.push(`${indent} } else {`);
2086
+ lines.push(`${indent} keep_${s}.push(false);`);
2087
+ lines.push(`${indent} }`);
2088
+ lines.push(`${indent}}`);
2089
+ lines.push(`${indent}let mut decs_${s}: Vec<${renderTypeRef(elemDeBoxRef)}> = Vec::with_capacity(items_${s}.len());`);
2090
+ lines.push(`${indent}if !items_${s}.is_empty() {`);
2091
+ lines.push(`${indent} let want_${s} = items_${s}.len();`);
2092
+ lines.push(`${indent} let bp_${s} = ${batch} { items: items_${s} };`);
2093
+ lines.push(`${indent} let row_${s} = match ${leafSym}(&bp_${s})${awaitSfx} {`);
2094
+ lines.push(`${indent} Ok(r) => r,`);
2095
+ lines.push(`${indent} Err(e) => return Err(op_failed(${rustStrLit(node.id)}, "fail", e)),`);
2096
+ lines.push(`${indent} };`);
2097
+ lines.push(`${indent} if row_${s}.len() != want_${s} {`);
2098
+ 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})));`);
2099
+ lines.push(`${indent} }`);
2100
+ lines.push(`${indent} for er_${s} in row_${s}.into_iter() {`);
2101
+ lines.push(`${indent} let dec_${s} = ${renderElemDeBox(`${indent} `)};`);
2102
+ lines.push(`${indent} decs_${s}.push(dec_${s});`);
2103
+ lines.push(`${indent} }`);
2104
+ lines.push(`${indent}}`);
2105
+ lines.push(`${indent}let mut decs_iter_${s} = decs_${s}.into_iter();`);
2106
+ lines.push(`${indent}for (oel_${s}, kept_${s}) in over_${s}.iter().zip(keep_${s}.iter()) {`);
2107
+ lines.push(`${indent} if *kept_${s} {`);
2108
+ lines.push(`${indent} let dec_${s} = decs_iter_${s}.next().expect("aligned kept row");`);
2109
+ lines.push(`${indent} built_${s}.push(${elemMat}(oel_${s}, dec_${s}));`);
2110
+ lines.push(`${indent} } else {`);
2111
+ lines.push(`${indent} built_${s}.push(${elemMat}(oel_${s}, None));`);
2112
+ lines.push(`${indent} }`);
2113
+ lines.push(`${indent}}`);
2114
+ }
2115
+ else if (batched) {
2041
2116
  // build kept-element ports (+ kept over elements for into). Batched into is never guarded (rejected).
2042
2117
  lines.push(`${indent}let mut items_${s}: Vec<${structName}> = Vec::with_capacity(over_${s}.len());`);
2043
2118
  if (hasInto)
@@ -2086,7 +2161,10 @@ isAsync = false) {
2086
2161
  else {
2087
2162
  // #93 shape 2 / #108: NON-batched map — dispatch ONCE PER KEPT ELEMENT.
2088
2163
  lines.push(`${indent}for oel_${s} in over_${s}.iter() {`);
2089
- for (const l of emitGuard(indent + " "))
2164
+ // #177 keep-with-null: a guard-skipped element is KEPT with into=None instead of dropped — byte-equal
2165
+ // to run_behavior's applyInto pass-through + opt-into null.
2166
+ const nonBatchedSkip = keepWithNull ? `built_${s}.push(${elemMat}(oel_${s}, None)); continue;` : "continue;";
2167
+ for (const l of emitGuard(indent + " ", nonBatchedSkip))
2090
2168
  lines.push(l);
2091
2169
  for (const l of buildPorts(indent + " "))
2092
2170
  lines.push(l);