behavior-contracts 0.11.6 → 0.11.8
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/dist/behavior.d.ts +25 -5
- package/dist/behavior.d.ts.map +1 -1
- package/dist/behavior.js +59 -16
- package/dist/behavior.js.map +1 -1
- package/dist/builder.d.ts.map +1 -1
- package/dist/builder.js +2 -2
- package/dist/builder.js.map +1 -1
- package/dist/generator/emit-shared-go.d.ts.map +1 -1
- package/dist/generator/emit-shared-go.js +17 -3
- package/dist/generator/emit-shared-go.js.map +1 -1
- package/dist/generator/emit-shared-rust-typed.d.ts +13 -1
- package/dist/generator/emit-shared-rust-typed.d.ts.map +1 -1
- package/dist/generator/emit-shared-rust-typed.js +21 -7
- package/dist/generator/emit-shared-rust-typed.js.map +1 -1
- package/dist/generator/emit-shared-rust.d.ts.map +1 -1
- package/dist/generator/emit-shared-rust.js +22 -6
- package/dist/generator/emit-shared-rust.js.map +1 -1
- package/dist/generator/emit-shared-typescript-typed.d.ts.map +1 -1
- package/dist/generator/emit-shared-typescript-typed.js +11 -1
- package/dist/generator/emit-shared-typescript-typed.js.map +1 -1
- package/dist/generator/emit-shared-typescript.d.ts.map +1 -1
- package/dist/generator/emit-shared-typescript.js +20 -5
- package/dist/generator/emit-shared-typescript.js.map +1 -1
- package/dist/generator/emit-straightline-typed-typescript.d.ts.map +1 -1
- package/dist/generator/emit-straightline-typed-typescript.js +3 -43
- package/dist/generator/emit-straightline-typed-typescript.js.map +1 -1
- package/dist/generator/emit-typed-native-go.d.ts +4 -4
- package/dist/generator/emit-typed-native-go.d.ts.map +1 -1
- package/dist/generator/emit-typed-native-go.js +149 -101
- package/dist/generator/emit-typed-native-go.js.map +1 -1
- package/dist/generator/emit-typed-native-rust.d.ts +2 -2
- package/dist/generator/emit-typed-native-rust.d.ts.map +1 -1
- package/dist/generator/emit-typed-native-rust.js +304 -233
- package/dist/generator/emit-typed-native-rust.js.map +1 -1
- package/dist/generator/straightline.d.ts +4 -2
- package/dist/generator/straightline.d.ts.map +1 -1
- package/dist/generator/straightline.js +4 -0
- package/dist/generator/straightline.js.map +1 -1
- package/dist/guard.js +7 -11
- package/dist/guard.js.map +1 -1
- package/dist/lowering.d.ts.map +1 -1
- package/dist/lowering.js +11 -19
- package/dist/lowering.js.map +1 -1
- package/dist/plan.d.ts +9 -2
- package/dist/plan.d.ts.map +1 -1
- package/dist/plan.js +9 -2
- package/dist/plan.js.map +1 -1
- package/dist/primitives.d.ts +0 -2
- package/dist/primitives.d.ts.map +1 -1
- package/dist/primitives.js +0 -4
- package/dist/primitives.js.map +1 -1
- package/dist/runtime.d.ts +1 -1
- package/dist/runtime.d.ts.map +1 -1
- package/dist/runtime.js +1 -1
- package/dist/runtime.js.map +1 -1
- package/dist/type-gate.d.ts.map +1 -1
- package/dist/type-gate.js +32 -5
- package/dist/type-gate.js.map +1 -1
- package/package.json +1 -1
|
@@ -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, checkOutputFieldType, emitMarshallers, emitMarshalHelpers, materializeExpr, } = rustTypedInternals;
|
|
11
|
+
const { typeRefIsCopy, rustFieldName, renderTypeRef, typedCell, typedFieldAccess, serializeTyped, emitTypeDecls, emitDefaults, emitSerializers, emitTypedValue, rustCellRead, checkOutputFieldType, emitMarshallers, emitMarshalHelpers, materializeExpr, } = 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
|
|
@@ -115,12 +115,12 @@ fn op_failed(node: &str, policy: &str, e: BehaviorError) -> BehaviorError {
|
|
|
115
115
|
}
|
|
116
116
|
}
|
|
117
117
|
|
|
118
|
-
// de_type_mismatch / de_missing_field
|
|
118
|
+
// de_type_mismatch / de_missing_field — the de-box mismatch failures the generated decode
|
|
119
119
|
// produces (scp-error.md "The Error Value"). Codes are byte-equal to the runtime outType check
|
|
120
120
|
// (TYPE_MISMATCH / MISSING_PROP) so the covered read stays equivalent to run_behavior; detail.kind
|
|
121
|
-
// distinguishes typeMismatch / missingField
|
|
121
|
+
// distinguishes typeMismatch / missingField.
|
|
122
122
|
#[allow(dead_code)]
|
|
123
|
-
fn de_type_mismatch(model: &str, field: &str, expected: &str, actual_wire:
|
|
123
|
+
fn de_type_mismatch(model: &str, field: &str, expected: &str, actual_wire: &str, raw: Cow<'static, str>) -> BehaviorError {
|
|
124
124
|
BehaviorError::with_detail(
|
|
125
125
|
"TYPE_MISMATCH",
|
|
126
126
|
format!("node '{model}': {field}: expected {expected}, got {actual_wire}"),
|
|
@@ -129,8 +129,8 @@ fn de_type_mismatch(model: &str, field: &str, expected: &str, actual_wire: Strin
|
|
|
129
129
|
model: Some(model.to_string()),
|
|
130
130
|
field: Some(field.to_string()),
|
|
131
131
|
expected_type: Some(expected.to_string()),
|
|
132
|
-
actual_wire_type: Some(actual_wire),
|
|
133
|
-
raw_value: Some(raw),
|
|
132
|
+
actual_wire_type: Some(actual_wire.to_string()),
|
|
133
|
+
raw_value: Some(raw.into_owned()),
|
|
134
134
|
context: std::collections::BTreeMap::new(),
|
|
135
135
|
},
|
|
136
136
|
)
|
|
@@ -151,24 +151,6 @@ fn de_missing_field(model: &str, field: &str, expected: &str) -> BehaviorError {
|
|
|
151
151
|
context: std::collections::BTreeMap::new(),
|
|
152
152
|
},
|
|
153
153
|
)
|
|
154
|
-
}
|
|
155
|
-
|
|
156
|
-
#[allow(dead_code)]
|
|
157
|
-
fn de_overflow(model: &str, field: &str, expected: &str, actual_wire: String, raw: String) -> BehaviorError {
|
|
158
|
-
let message = format!("node '{model}': {field}: {raw} is outside the range of {expected}");
|
|
159
|
-
BehaviorError::with_detail(
|
|
160
|
-
"TYPE_MISMATCH",
|
|
161
|
-
message,
|
|
162
|
-
ErrorDetail {
|
|
163
|
-
kind: Some(ErrorKind::Overflow),
|
|
164
|
-
model: Some(model.to_string()),
|
|
165
|
-
field: Some(field.to_string()),
|
|
166
|
-
expected_type: Some(expected.to_string()),
|
|
167
|
-
actual_wire_type: Some(actual_wire),
|
|
168
|
-
raw_value: Some(raw),
|
|
169
|
-
context: std::collections::BTreeMap::new(),
|
|
170
|
-
},
|
|
171
|
-
)
|
|
172
154
|
}`;
|
|
173
155
|
}
|
|
174
156
|
/** emitBehaviorErrorType — the FULL local error layer (type defs THEN constructors) baked into the covered
|
|
@@ -207,7 +189,7 @@ function rustPayloadRow(entries) {
|
|
|
207
189
|
* handler contract; the aligned result is a `WireValue::List` the runner reads via its `.items`.
|
|
208
190
|
*/
|
|
209
191
|
function rustPayloadBatch(itemsExpr) {
|
|
210
|
-
return `WireRow { entries: vec![("items"
|
|
192
|
+
return `WireRow { entries: vec![(Cow::Borrowed("items"), WireValue::List(WireList { items: ${itemsExpr} }))] }`;
|
|
211
193
|
}
|
|
212
194
|
/** rustListItems — extract the aligned per-element wires (a `Vec<WireValue>`) from a batched/fanout transport
|
|
213
195
|
* result (a `WireValue::List`); a non-list result yields an empty Vec → caught by the alignment length check. */
|
|
@@ -219,7 +201,7 @@ function rustListItems(wvExpr) {
|
|
|
219
201
|
// A covered record read returns the consumer's WIRE (a value implementing WireRow), and the generated
|
|
220
202
|
// decode probes it per field from the declared type. The consumer supplies variant classification (a
|
|
221
203
|
// probe reports the producer's own wire tag as a free string); the generated code owns strictness —
|
|
222
|
-
// required/optional, present/absent, error assembly, fail-closed. The seam stays native: Probe
|
|
204
|
+
// required/optional, present/absent, error assembly, fail-closed. The seam stays native: Probe
|
|
223
205
|
// are concrete enums and WireRow/WireList are monomorphized via mutual associated types (Row/List), so no
|
|
224
206
|
// boxed Value / dyn / Box crosses the boundary.
|
|
225
207
|
/** emitRustProbeWireTypes — the once-per-module probe enums + the BC-OWNED concrete wire types + their
|
|
@@ -227,39 +209,40 @@ function rustListItems(wvExpr) {
|
|
|
227
209
|
* result the consumer's SINGLE op-agnostic transport builds and returns; the consumer implements NOTHING
|
|
228
210
|
* over it (no trait, no probe protocol). The generated inline de-box reads it via these inherent methods —
|
|
229
211
|
* static typed extraction lowers the generic result to the covered plane's typed values immediately, so no
|
|
230
|
-
* dynamic value crosses the covered/hot plane (bc#87). Numbers ride
|
|
212
|
+
* dynamic value crosses the covered/hot plane (bc#87). Numbers ride NATIVE (i64 / f64) — nothing to parse. */
|
|
231
213
|
function emitRustProbeWireTypes(clone) {
|
|
232
214
|
// bc#156: WireValue is a port field (Vec<WireValue>) when a `value` input port exists — the ports struct
|
|
233
215
|
// derives Clone (bc#87 parallel dispatch) and the port init clones the input, so WireValue/WireRow/WireList
|
|
234
216
|
// must be Clone THEN. A value-free module never clones the wire (return-only), so the derive is omitted to
|
|
235
217
|
// keep those generated modules byte-identical to pre-#156.
|
|
236
218
|
const cloneDerive = clone ? "#[derive(Clone)]\n" : "";
|
|
237
|
-
return `// Probe<T>
|
|
238
|
-
// the matched value
|
|
239
|
-
//
|
|
240
|
-
//
|
|
219
|
+
return `// Probe<T> — the outcome of classifying one wire attribute against a declared type. Got carries
|
|
220
|
+
// the matched value MOVED OUT of the wire (a number arrives already native, so there is nothing to parse
|
|
221
|
+
// and no range check to fail); actual_wire_type is the producer's own wire tag
|
|
222
|
+
// (S/N/BOOL/M/L/NULL), a \`&'static str\` so classifying costs NO allocation; raw_value is the offending
|
|
223
|
+
// value, borrowed when it is a fixed word. Concrete enums — no boxed runtime value.
|
|
224
|
+
//
|
|
225
|
+
// NO CLONE. Classification CONSUMES the wire: the transport's result is an owned local that is dead the
|
|
226
|
+
// moment it is de-boxed, so every string / row / list is MOVED into the typed value. A \`.clone()\` here
|
|
227
|
+
// would deep-copy the whole result set once per node boundary — that is a heap copy of every cell, it
|
|
228
|
+
// scales with node count, and it is what made a generated native read lose to an interpreter. The purity
|
|
229
|
+
// gate rejects \`.clone()\` and per-call \`.to_string()\` in this module; keep it that way.
|
|
241
230
|
pub enum Probe<T> {
|
|
242
231
|
Got(T),
|
|
243
|
-
Wrong { actual_wire_type:
|
|
244
|
-
Null { actual_wire_type:
|
|
245
|
-
Absent,
|
|
246
|
-
}
|
|
247
|
-
|
|
248
|
-
pub enum NumProbe {
|
|
249
|
-
Got { raw: String, actual_wire_type: String },
|
|
250
|
-
Wrong { actual_wire_type: String, raw_value: String },
|
|
251
|
-
Null { actual_wire_type: String, raw_value: String },
|
|
232
|
+
Wrong { actual_wire_type: &'static str, raw_value: Cow<'static, str> },
|
|
233
|
+
Null { actual_wire_type: &'static str, raw_value: Cow<'static, str> },
|
|
252
234
|
Absent,
|
|
253
235
|
}
|
|
254
236
|
|
|
255
237
|
// WireValue — the BC-OWNED, BC-GENERATED, self-contained (runtime-free) generic result the consumer's
|
|
256
238
|
// single op-agnostic transport returns. The consumer BUILDS it as it reads the producer (the raw I/O act)
|
|
257
|
-
// — WireValue::Str/
|
|
258
|
-
// it. Numbers
|
|
259
|
-
// nested WireRow / WireList. NO trait, NO consumer classification protocol.
|
|
239
|
+
// — WireValue::Str/Int/Float/Bool/Null/Row/List, or the int()/float() constructors — and implements NOTHING
|
|
240
|
+
// over it. Numbers are NATIVE (i64 / f64): the producer's own integer reaches the de-box unparsed. A
|
|
241
|
+
// composite is a nested WireRow / WireList. NO trait, NO consumer classification protocol.
|
|
260
242
|
${cloneDerive}pub enum WireValue {
|
|
261
|
-
Str(
|
|
262
|
-
|
|
243
|
+
Str(Cow<'static, str>),
|
|
244
|
+
Int(i64),
|
|
245
|
+
Float(f64),
|
|
263
246
|
Bool(bool),
|
|
264
247
|
Null,
|
|
265
248
|
Row(WireRow),
|
|
@@ -267,11 +250,15 @@ ${cloneDerive}pub enum WireValue {
|
|
|
267
250
|
}
|
|
268
251
|
|
|
269
252
|
// WireRow / WireList — a wire map (a DynamoDB "M") / wire array (an "L"). Native Vec-backed; the generated
|
|
270
|
-
// de-box
|
|
271
|
-
// error assembly).
|
|
272
|
-
//
|
|
253
|
+
// de-box drains them by declared field / element and owns strictness (required/optional, present/absent,
|
|
254
|
+
// error assembly).
|
|
255
|
+
//
|
|
256
|
+
// A key is \`Cow<'static, str>\`: the field names BC generates are compile-time constants and ride as
|
|
257
|
+
// \`Cow::Borrowed\` (zero allocation, however many times a payload is built), while a producer-supplied key
|
|
258
|
+
// read at run time rides as \`Cow::Owned\`. The same holds for Str — a generated SQL literal costs
|
|
259
|
+
// nothing per call, a value read off the wire owns its text.
|
|
273
260
|
${cloneDerive}pub struct WireRow {
|
|
274
|
-
pub entries: Vec<(
|
|
261
|
+
pub entries: Vec<(Cow<'static, str>, WireValue)>,
|
|
275
262
|
}
|
|
276
263
|
|
|
277
264
|
${cloneDerive}pub struct WireList {
|
|
@@ -279,138 +266,99 @@ ${cloneDerive}pub struct WireList {
|
|
|
279
266
|
}
|
|
280
267
|
|
|
281
268
|
impl WireValue {
|
|
282
|
-
// constructors the consumer's transport uses to build numeric results (
|
|
269
|
+
// constructors the consumer's transport uses to build numeric results (i64 / f64, carried natively).
|
|
283
270
|
pub fn int(n: i64) -> Self {
|
|
284
|
-
WireValue::
|
|
271
|
+
WireValue::Int(n)
|
|
285
272
|
}
|
|
286
273
|
pub fn float(n: f64) -> Self {
|
|
287
|
-
WireValue::
|
|
288
|
-
}
|
|
289
|
-
// the top result is always present (Some(self)); the field/elem probes share the same classifiers.
|
|
290
|
-
pub fn as_string(&self) -> Probe<String> {
|
|
291
|
-
probe_string_at(Some(self))
|
|
292
|
-
}
|
|
293
|
-
pub fn as_number(&self) -> NumProbe {
|
|
294
|
-
probe_number_at(Some(self))
|
|
295
|
-
}
|
|
296
|
-
pub fn as_bool(&self) -> Probe<bool> {
|
|
297
|
-
probe_bool_at(Some(self))
|
|
298
|
-
}
|
|
299
|
-
pub fn as_row(&self) -> Probe<&WireRow> {
|
|
300
|
-
probe_row_at(Some(self))
|
|
301
|
-
}
|
|
302
|
-
pub fn as_list(&self) -> Probe<&WireList> {
|
|
303
|
-
probe_list_at(Some(self))
|
|
274
|
+
WireValue::Float(n)
|
|
304
275
|
}
|
|
305
276
|
fn tag(&self) -> &'static str {
|
|
306
277
|
match self {
|
|
307
278
|
WireValue::Str(_) => "S",
|
|
308
|
-
WireValue::
|
|
279
|
+
WireValue::Int(_) | WireValue::Float(_) => "N",
|
|
309
280
|
WireValue::Bool(_) => "BOOL",
|
|
310
281
|
WireValue::Null => "NULL",
|
|
311
282
|
WireValue::Row(_) => "M",
|
|
312
283
|
WireValue::List(_) => "L",
|
|
313
284
|
}
|
|
314
285
|
}
|
|
315
|
-
|
|
286
|
+
// the offending value as text, for a failure detail. CONSUMES the value (the cold path owns it by
|
|
287
|
+
// then), so reporting a wrong string moves it out instead of copying it.
|
|
288
|
+
fn into_raw(self) -> Cow<'static, str> {
|
|
316
289
|
match self {
|
|
317
|
-
WireValue::Str(s) => s
|
|
318
|
-
WireValue::
|
|
319
|
-
WireValue::
|
|
320
|
-
WireValue::
|
|
321
|
-
WireValue::
|
|
290
|
+
WireValue::Str(s) => s,
|
|
291
|
+
WireValue::Int(n) => Cow::Owned(n.to_string()),
|
|
292
|
+
WireValue::Float(f) => Cow::Owned(f.to_string()),
|
|
293
|
+
WireValue::Bool(b) => Cow::Owned(b.to_string()),
|
|
294
|
+
WireValue::Null => Cow::Borrowed("null"),
|
|
295
|
+
WireValue::Row(_) | WireValue::List(_) => Cow::Borrowed("[composite]"),
|
|
322
296
|
}
|
|
323
297
|
}
|
|
324
298
|
}
|
|
325
299
|
|
|
326
300
|
impl WireRow {
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
pub fn probe_string(&self, field: &str) -> Probe<String> {
|
|
334
|
-
probe_string_at(self.get(field))
|
|
335
|
-
}
|
|
336
|
-
pub fn probe_number(&self, field: &str) -> NumProbe {
|
|
337
|
-
probe_number_at(self.get(field))
|
|
338
|
-
}
|
|
339
|
-
pub fn probe_bool(&self, field: &str) -> Probe<bool> {
|
|
340
|
-
probe_bool_at(self.get(field))
|
|
341
|
-
}
|
|
342
|
-
pub fn probe_row(&self, field: &str) -> Probe<&WireRow> {
|
|
343
|
-
probe_row_at(self.get(field))
|
|
344
|
-
}
|
|
345
|
-
pub fn probe_list(&self, field: &str) -> Probe<&WireList> {
|
|
346
|
-
probe_list_at(self.get(field))
|
|
301
|
+
// Move the value at \`field\` OUT of the row (or None when the producer did not send it). The de-box
|
|
302
|
+
// reads each declared field exactly once, so taking is always right — and it is what keeps a cell
|
|
303
|
+
// from being copied: the String travels from the wire into the typed struct without a heap copy.
|
|
304
|
+
// Undeclared extras are simply left behind with the row.
|
|
305
|
+
pub fn take(&mut self, field: &str) -> Option<WireValue> {
|
|
306
|
+
self.entries.iter().position(|(k, _)| k == field).map(|i| self.entries.swap_remove(i).1)
|
|
347
307
|
}
|
|
348
308
|
}
|
|
349
309
|
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
}
|
|
360
|
-
pub fn elem_number(&self, i: usize) -> NumProbe {
|
|
361
|
-
probe_number_at(self.items.get(i))
|
|
362
|
-
}
|
|
363
|
-
pub fn elem_bool(&self, i: usize) -> Probe<bool> {
|
|
364
|
-
probe_bool_at(self.items.get(i))
|
|
365
|
-
}
|
|
366
|
-
pub fn elem_row(&self, i: usize) -> Probe<&WireRow> {
|
|
367
|
-
probe_row_at(self.items.get(i))
|
|
368
|
-
}
|
|
369
|
-
pub fn elem_list(&self, i: usize) -> Probe<&WireList> {
|
|
370
|
-
probe_list_at(self.items.get(i))
|
|
310
|
+
// the ONE classifier per kind, over an OWNED Option<WireValue> (None = absent attribute/element). The
|
|
311
|
+
// BC-owned WireValue variant IS the wire tag — no consumer classification. Each takes the value BY VALUE
|
|
312
|
+
// and hands the match MOVED OUT: de-boxing a result never copies a cell, a row, or a list.
|
|
313
|
+
pub fn probe_string_at(v: Option<WireValue>) -> Probe<Cow<'static, str>> {
|
|
314
|
+
match v {
|
|
315
|
+
None => Probe::Absent,
|
|
316
|
+
Some(WireValue::Str(s)) => Probe::Got(s),
|
|
317
|
+
Some(WireValue::Null) => Probe::Null { actual_wire_type: "NULL", raw_value: Cow::Borrowed("null") },
|
|
318
|
+
Some(o) => Probe::Wrong { actual_wire_type: o.tag(), raw_value: o.into_raw() },
|
|
371
319
|
}
|
|
372
320
|
}
|
|
373
|
-
|
|
374
|
-
// the ONE classifier per kind, over an Option<&WireValue> (None = absent attribute/element). The BC-owned
|
|
375
|
-
// WireValue variant IS the wire tag — no consumer classification.
|
|
376
|
-
fn probe_string_at(v: Option<&WireValue>) -> Probe<String> {
|
|
321
|
+
pub fn probe_int_at(v: Option<WireValue>) -> Probe<i64> {
|
|
377
322
|
match v {
|
|
378
323
|
None => Probe::Absent,
|
|
379
|
-
Some(WireValue::
|
|
380
|
-
Some(WireValue::Null) => Probe::Null { actual_wire_type: "NULL"
|
|
381
|
-
Some(o) => Probe::Wrong { actual_wire_type: o.tag()
|
|
324
|
+
Some(WireValue::Int(n)) => Probe::Got(n),
|
|
325
|
+
Some(WireValue::Null) => Probe::Null { actual_wire_type: "NULL", raw_value: Cow::Borrowed("null") },
|
|
326
|
+
Some(o) => Probe::Wrong { actual_wire_type: o.tag(), raw_value: o.into_raw() },
|
|
382
327
|
}
|
|
383
328
|
}
|
|
384
|
-
|
|
329
|
+
// a float position accepts an int and widens it — the same widening the interpreter's outType check does,
|
|
330
|
+
// so the generated read and run_behavior agree on an integral value in a float field.
|
|
331
|
+
pub fn probe_float_at(v: Option<WireValue>) -> Probe<f64> {
|
|
385
332
|
match v {
|
|
386
|
-
None =>
|
|
387
|
-
Some(WireValue::
|
|
388
|
-
Some(WireValue::
|
|
389
|
-
Some(
|
|
333
|
+
None => Probe::Absent,
|
|
334
|
+
Some(WireValue::Float(f)) => Probe::Got(f),
|
|
335
|
+
Some(WireValue::Int(n)) => Probe::Got(n as f64),
|
|
336
|
+
Some(WireValue::Null) => Probe::Null { actual_wire_type: "NULL", raw_value: Cow::Borrowed("null") },
|
|
337
|
+
Some(o) => Probe::Wrong { actual_wire_type: o.tag(), raw_value: o.into_raw() },
|
|
390
338
|
}
|
|
391
339
|
}
|
|
392
|
-
fn probe_bool_at(v: Option
|
|
340
|
+
pub fn probe_bool_at(v: Option<WireValue>) -> Probe<bool> {
|
|
393
341
|
match v {
|
|
394
342
|
None => Probe::Absent,
|
|
395
|
-
Some(WireValue::Bool(b)) => Probe::Got(
|
|
396
|
-
Some(WireValue::Null) => Probe::Null { actual_wire_type: "NULL"
|
|
397
|
-
Some(o) => Probe::Wrong { actual_wire_type: o.tag()
|
|
343
|
+
Some(WireValue::Bool(b)) => Probe::Got(b),
|
|
344
|
+
Some(WireValue::Null) => Probe::Null { actual_wire_type: "NULL", raw_value: Cow::Borrowed("null") },
|
|
345
|
+
Some(o) => Probe::Wrong { actual_wire_type: o.tag(), raw_value: o.into_raw() },
|
|
398
346
|
}
|
|
399
347
|
}
|
|
400
|
-
fn probe_row_at(v: Option
|
|
348
|
+
pub fn probe_row_at(v: Option<WireValue>) -> Probe<WireRow> {
|
|
401
349
|
match v {
|
|
402
350
|
None => Probe::Absent,
|
|
403
351
|
Some(WireValue::Row(r)) => Probe::Got(r),
|
|
404
|
-
Some(WireValue::Null) => Probe::Null { actual_wire_type: "NULL"
|
|
405
|
-
Some(o) => Probe::Wrong { actual_wire_type: o.tag()
|
|
352
|
+
Some(WireValue::Null) => Probe::Null { actual_wire_type: "NULL", raw_value: Cow::Borrowed("null") },
|
|
353
|
+
Some(o) => Probe::Wrong { actual_wire_type: o.tag(), raw_value: o.into_raw() },
|
|
406
354
|
}
|
|
407
355
|
}
|
|
408
|
-
fn probe_list_at(v: Option
|
|
356
|
+
pub fn probe_list_at(v: Option<WireValue>) -> Probe<WireList> {
|
|
409
357
|
match v {
|
|
410
358
|
None => Probe::Absent,
|
|
411
359
|
Some(WireValue::List(l)) => Probe::Got(l),
|
|
412
|
-
Some(WireValue::Null) => Probe::Null { actual_wire_type: "NULL"
|
|
413
|
-
Some(o) => Probe::Wrong { actual_wire_type: o.tag()
|
|
360
|
+
Some(WireValue::Null) => Probe::Null { actual_wire_type: "NULL", raw_value: Cow::Borrowed("null") },
|
|
361
|
+
Some(o) => Probe::Wrong { actual_wire_type: o.tag(), raw_value: o.into_raw() },
|
|
414
362
|
}
|
|
415
363
|
}`;
|
|
416
364
|
}
|
|
@@ -424,12 +372,12 @@ fn probe_list_at(v: Option<&WireValue>) -> Probe<&WireList> {
|
|
|
424
372
|
* nested collection to a nested loop. A required-position mismatch does `return Err(de_*(...))` (fail
|
|
425
373
|
* closed, propagating the structured Error Value from the enclosing runner); an optional position
|
|
426
374
|
* (optDepth>0) maps absent/null to the all-None value. `ctr` hands out unique temp names (`sub2`, `l3`,
|
|
427
|
-
* `m4`, `
|
|
428
|
-
*
|
|
375
|
+
* `m4`, `e3`, `k4`) so nested blocks never collide. Every position consumes an OWNED value the enclosing
|
|
376
|
+
* position moved out, so the decode copies nothing. Mirrors the interpreter's outType check +
|
|
429
377
|
* the (now-deleted) per-position decoders, but TOTAL over the grammar (opt(named)/arr(arr)/map(opt)…) and
|
|
430
378
|
* inlined — the type is baked all the way through by the TS compiler, not the target monomorphizer.
|
|
431
379
|
*/
|
|
432
|
-
function renderRustDeBox(plan, srcExpr, ctr, indent, fail
|
|
380
|
+
function renderRustDeBox(plan, srcExpr, ctr, indent, fail) {
|
|
433
381
|
const I = indent;
|
|
434
382
|
const I1 = indent + " ";
|
|
435
383
|
const id = ctr.n++;
|
|
@@ -440,16 +388,17 @@ function renderRustDeBox(plan, srcExpr, ctr, indent, fail, idxExpr = "") {
|
|
|
440
388
|
const mismatch = fail(`de_type_mismatch(${ml}, ${fl}, ${nl}, actual_wire_type, raw_value)`);
|
|
441
389
|
const missing = fail(`de_missing_field(${ml}, ${fl}, ${nl})`);
|
|
442
390
|
// the probe expression for this node's access + a value-kind suffix (string/number/bool/row/list).
|
|
391
|
+
// Every access hands the classifier an OWNED Option<WireValue>: a top / element / map value is already
|
|
392
|
+
// moved out by the enclosing position, and a field is MOVED OUT of its row by `take`. Nothing borrows,
|
|
393
|
+
// so nothing has to be copied to be kept.
|
|
443
394
|
const probe = (suffix) => {
|
|
444
395
|
switch (plan.access.from) {
|
|
445
396
|
case "top":
|
|
446
|
-
return `${srcExpr}.as_${suffix}()`;
|
|
447
|
-
case "field":
|
|
448
|
-
return `${srcExpr}.probe_${suffix}(${rustStrLit(plan.access.key)})`;
|
|
449
397
|
case "elem":
|
|
450
|
-
return `${srcExpr}.elem_${suffix}(${idxExpr})`;
|
|
451
398
|
case "mapval":
|
|
452
|
-
return
|
|
399
|
+
return `probe_${suffix}_at(Some(${srcExpr}))`;
|
|
400
|
+
case "field":
|
|
401
|
+
return `probe_${suffix}_at(${srcExpr}.take(${rustStrLit(plan.access.key)}))`;
|
|
453
402
|
}
|
|
454
403
|
};
|
|
455
404
|
// wrap the decoded value in optDepth `Some(...)` layers (present ⇒ Some^N(v); absent/null ⇒ None).
|
|
@@ -466,30 +415,32 @@ function renderRustDeBox(plan, srcExpr, ctr, indent, fail, idxExpr = "") {
|
|
|
466
415
|
: `${I1}Probe::Wrong { actual_wire_type, raw_value }\n${I1}| Probe::Null { actual_wire_type, raw_value } => ${mismatch},\n${I1}Probe::Absent => ${missing},`;
|
|
467
416
|
if (plan.k === "scalar") {
|
|
468
417
|
if (plan.scalar === "int" || plan.scalar === "float") {
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
: `${I1}NumProbe::Wrong { actual_wire_type, raw_value }\n${I1}| NumProbe::Null { actual_wire_type, raw_value } => ${mismatch},\n${I1}NumProbe::Absent => ${missing},`;
|
|
473
|
-
return `match ${probe("number")} {
|
|
474
|
-
${I1}NumProbe::Got { raw, actual_wire_type } => match raw.parse::<${rustT}>() {
|
|
475
|
-
${I1} Ok(n) => ${wrapSome("n")},
|
|
476
|
-
${I1} Err(_) => ${fail(`de_overflow(${ml}, ${fl}, ${nl}, actual_wire_type, raw)`)},
|
|
477
|
-
${I1}},
|
|
478
|
-
${numArms}
|
|
418
|
+
return `match ${probe(plan.scalar)} {
|
|
419
|
+
${I1}Probe::Got(v) => ${wrapSome("v")},
|
|
420
|
+
${probeArms}
|
|
479
421
|
${I}}`;
|
|
480
422
|
}
|
|
481
|
-
|
|
482
|
-
|
|
423
|
+
if (plan.scalar === "string") {
|
|
424
|
+
// Cow → the struct's owned String: `into_owned()` on the producer's own text is a MOVE, not a copy.
|
|
425
|
+
return `match ${probe("string")} {
|
|
426
|
+
${I1}Probe::Got(v) => ${wrapSome("v.into_owned()")},
|
|
427
|
+
${probeArms}
|
|
428
|
+
${I}}`;
|
|
429
|
+
}
|
|
430
|
+
return `match ${probe("bool")} {
|
|
483
431
|
${I1}Probe::Got(v) => ${wrapSome("v")},
|
|
484
432
|
${probeArms}
|
|
485
433
|
${I}}`;
|
|
486
434
|
}
|
|
487
435
|
if (plan.k === "record") {
|
|
436
|
+
// Each declared field is MOVED OUT of the row by `take` (see the wire seam) — the row is consumed field
|
|
437
|
+
// by field into the typed struct. `mut` only when there is a field to take (an empty record takes none).
|
|
438
|
+
const bind = plan.fields.length > 0 ? `mut sub${id}` : `sub${id}`;
|
|
488
439
|
const fieldInits = plan.fields
|
|
489
440
|
.map((f) => `${I1} ${rustFieldName(f.name)}: ${renderRustDeBox(f.plan, `sub${id}`, ctr, `${I1} `, fail)},`)
|
|
490
441
|
.join("\n");
|
|
491
442
|
return `match ${probe("row")} {
|
|
492
|
-
${I1}Probe::Got(
|
|
443
|
+
${I1}Probe::Got(${bind}) => ${wrapSome(`${plan.typeName} {
|
|
493
444
|
${fieldInits}
|
|
494
445
|
${I1}}`)},
|
|
495
446
|
${probeArms}
|
|
@@ -497,27 +448,28 @@ ${I}}`;
|
|
|
497
448
|
}
|
|
498
449
|
if (plan.k === "list" && plan.elem.k === "value") {
|
|
499
450
|
// bc#164: `{arr:"value"}` output-passthrough — the result wire is a list of OPAQUE values; validate the
|
|
500
|
-
// container is a list, then
|
|
451
|
+
// container is a list, then MOVE its items across as-is (no per-element de-box / no re-box). The elements
|
|
501
452
|
// stay `WireValue` so a downstream op-agnostic leaf consumes them with no per-op `typed→Value` re-box.
|
|
502
453
|
return `match ${probe("list")} {
|
|
503
|
-
${I1}Probe::Got(l${id}) => ${wrapSome(`l${id}.items
|
|
454
|
+
${I1}Probe::Got(l${id}) => ${wrapSome(`l${id}.items`)},
|
|
504
455
|
${probeArms}
|
|
505
456
|
${I}}`;
|
|
506
457
|
}
|
|
507
458
|
if (plan.k === "value") {
|
|
508
459
|
// bc#164: a bare `value` output-passthrough (top position) — the whole result wire crosses UNCHANGED
|
|
509
|
-
// (
|
|
460
|
+
// (moved), no probe, no de-box. (elem-position `value` is handled by the list branch above; field/mapval
|
|
510
461
|
// never carry `value` — buildWirePlan does not relax those positions.)
|
|
511
462
|
if (plan.access.from !== "top")
|
|
512
463
|
throw new GeneratorFailure("UNSUPPORTED_NODE_STRAIGHTLINE", `rust de-box: a 'value' node at a non-top position (${plan.access.from}) is not a legal passthrough shape`);
|
|
513
|
-
return
|
|
464
|
+
return srcExpr;
|
|
514
465
|
}
|
|
515
466
|
if (plan.k === "list") {
|
|
516
|
-
|
|
467
|
+
// Consume the list: each element is MOVED into the element de-box, so a row never gets copied to be read.
|
|
468
|
+
const elemExpr = renderRustDeBox(plan.elem, `e${id}`, ctr, `${I1} `, fail);
|
|
517
469
|
return `match ${probe("list")} {
|
|
518
470
|
${I1}Probe::Got(l${id}) => ${wrapSome(`{
|
|
519
|
-
${I1} let mut acc${id} = Vec::with_capacity(l${id}.len());
|
|
520
|
-
${I1} for
|
|
471
|
+
${I1} let mut acc${id} = Vec::with_capacity(l${id}.items.len());
|
|
472
|
+
${I1} for e${id} in l${id}.items {
|
|
521
473
|
${I1} acc${id}.push(${elemExpr});
|
|
522
474
|
${I1} }
|
|
523
475
|
${I1} acc${id}
|
|
@@ -525,14 +477,15 @@ ${I1}}`)},
|
|
|
525
477
|
${probeArms}
|
|
526
478
|
${I}}`;
|
|
527
479
|
}
|
|
528
|
-
// map(V): the wire value is a producer map (a DynamoDB "M");
|
|
529
|
-
|
|
480
|
+
// map(V): the wire value is a producer map (a DynamoDB "M"); consume its entries, decode each value as V.
|
|
481
|
+
// Both halves move: the key becomes the BTreeMap's owned String, the value goes straight into the de-box.
|
|
482
|
+
const valExpr = renderRustDeBox(plan.value, `mv${id}`, ctr, `${I1} `, fail);
|
|
530
483
|
return `match ${probe("row")} {
|
|
531
484
|
${I1}Probe::Got(m${id}) => ${wrapSome(`{
|
|
532
485
|
${I1} let mut acc${id} = std::collections::BTreeMap::new();
|
|
533
|
-
${I1} for k${id} in m${id}.
|
|
486
|
+
${I1} for (k${id}, mv${id}) in m${id}.entries {
|
|
534
487
|
${I1} let v${id} = ${valExpr};
|
|
535
|
-
${I1} acc${id}.insert(k${id}, v${id});
|
|
488
|
+
${I1} acc${id}.insert(k${id}.into_owned(), v${id});
|
|
536
489
|
${I1} }
|
|
537
490
|
${I1} acc${id}
|
|
538
491
|
${I1}}`)},
|
|
@@ -558,16 +511,31 @@ ${I}}`;
|
|
|
558
511
|
* pass-through (null stays null), the write-side mirror of the read de-box's opt (`wrapSome`).
|
|
559
512
|
* `depth` names the per-element closure binding uniquely across nesting.
|
|
560
513
|
*/
|
|
514
|
+
/** rustStaticStrLit — the bare `&'static str` behind a RENDERED string literal (`"…".to_string()`), or
|
|
515
|
+
* undefined when the expression is a computed String. The ONE unpeel: a literal that is about to become
|
|
516
|
+
* a wire value or a concat part never needs the owned String the expression renderer produced. */
|
|
517
|
+
function rustStaticStrLit(expr) {
|
|
518
|
+
const m = /^(".*")\.to_string\(\)$/.exec(expr);
|
|
519
|
+
return m ? m[1] : undefined;
|
|
520
|
+
}
|
|
521
|
+
/** rustStrWireBox — a string crossing INTO the wire. A value fixed at generation time rides as
|
|
522
|
+
* `Cow::Borrowed` (the SQL text / a literal port costs NO allocation, however many times the payload is
|
|
523
|
+
* built); anything else converts with `.into()`, which MOVES an owned String rather than copying it. */
|
|
524
|
+
function rustStrWireBox(src) {
|
|
525
|
+
const lit = rustStaticStrLit(src);
|
|
526
|
+
return lit !== undefined ? `WireValue::Str(Cow::Borrowed(${lit}))` : `WireValue::Str(${src}.into())`;
|
|
527
|
+
}
|
|
561
528
|
/** rustScalarWireCtor — the WireValue constructor for a portable scalar (the ONE mapping; used both as
|
|
562
|
-
* `Ctor(x)` and, point-free, as a `.map(Ctor)` argument in the clippy-clean list box).
|
|
529
|
+
* `Ctor(x)` and, point-free, as a `.map(Ctor)` argument in the clippy-clean list box). A string does NOT
|
|
530
|
+
* come through here — it goes through {@link rustStrWireBox}, which keeps a literal borrowed. */
|
|
563
531
|
function rustScalarWireCtor(scalar) {
|
|
564
532
|
switch (scalar) {
|
|
565
533
|
case "string":
|
|
566
534
|
return "WireValue::Str";
|
|
567
535
|
case "int":
|
|
568
|
-
return "WireValue::
|
|
536
|
+
return "WireValue::Int";
|
|
569
537
|
case "float":
|
|
570
|
-
return "WireValue::
|
|
538
|
+
return "WireValue::Float";
|
|
571
539
|
case "bool":
|
|
572
540
|
return "WireValue::Bool";
|
|
573
541
|
default:
|
|
@@ -585,11 +553,13 @@ function renderRustWireBox(plan, srcExpr, depth = 0) {
|
|
|
585
553
|
// strip the source's OWN outer parens before wrapping in the ctor — `WireValue::Str(("a"+x))` is
|
|
586
554
|
// `clippy::double_parens`; `WireValue::Str("a"+x)` is clean (the ctor call already parenthesizes).
|
|
587
555
|
if (plan.k === "scalar")
|
|
588
|
-
return
|
|
556
|
+
return plan.scalar === "string"
|
|
557
|
+
? rustStrWireBox(rustStripOuterParens(baseSrc))
|
|
558
|
+
: `${rustScalarWireCtor(plan.scalar)}(${rustStripOuterParens(baseSrc)})`;
|
|
589
559
|
if (plan.k === "record") {
|
|
590
560
|
// typed struct → wire map: box each declared field off its native struct field (moving it out of the owned
|
|
591
561
|
// srcExpr — no probe), assemble a WireRow of (name, WireValue) in declared-field order.
|
|
592
|
-
const entries = plan.fields.map((f) => `(${rustStrLit(f.name)}
|
|
562
|
+
const entries = plan.fields.map((f) => `(Cow::Borrowed(${rustStrLit(f.name)}), ${renderRustWireBox(f.plan, `${baseSrc}.${rustFieldName(f.name)}`, depth + 1)})`);
|
|
593
563
|
return `WireValue::Row(WireRow { entries: vec![${entries.join(", ")}] })`;
|
|
594
564
|
}
|
|
595
565
|
if (plan.k === "list") {
|
|
@@ -601,7 +571,7 @@ function renderRustWireBox(plan, srcExpr, depth = 0) {
|
|
|
601
571
|
// (`.map(WireValue::Str)` not `.map(|e| WireValue::Str(e))` — `clippy::redundant_closure`).
|
|
602
572
|
if (elemBox === e)
|
|
603
573
|
return `WireValue::List(WireList { items: ${baseSrc} })`;
|
|
604
|
-
const scalarCtor = plan.elem.optDepth === 0 && plan.elem.k === "scalar" ? rustScalarWireCtor(plan.elem.scalar) : undefined;
|
|
574
|
+
const scalarCtor = plan.elem.optDepth === 0 && plan.elem.k === "scalar" && plan.elem.scalar !== "string" ? rustScalarWireCtor(plan.elem.scalar) : undefined;
|
|
605
575
|
const mapper = scalarCtor !== undefined ? scalarCtor : `|${e}| ${elemBox}`;
|
|
606
576
|
return `WireValue::List(WireList { items: ${baseSrc}.into_iter().map(${mapper}).collect() })`;
|
|
607
577
|
}
|
|
@@ -610,7 +580,8 @@ function renderRustWireBox(plan, srcExpr, depth = 0) {
|
|
|
610
580
|
// declared map<V> is the dynamic-keyed twin of a record — the READ side de-boxes a WireRow INTO map<V>
|
|
611
581
|
// the SAME way, emit-shared-debox `mapval`). Box EACH entry's VALUE recursively (box-once, no round-trip);
|
|
612
582
|
// keys carried as dynamic strings. BTreeMap<String,_> iterates in ascending key order, so the WireRow is
|
|
613
|
-
// deterministic (matching the rust typed map's canonical key order).
|
|
583
|
+
// deterministic (matching the rust typed map's canonical key order). A declared map's keys are runtime
|
|
584
|
+
// data, so they cross as owned wire keys (unlike a generated field name, which stays borrowed).
|
|
614
585
|
const k = `k${depth}`;
|
|
615
586
|
const v = `v${depth}`;
|
|
616
587
|
const valBox = renderRustWireBox(plan.value, v, depth + 1);
|
|
@@ -618,8 +589,8 @@ function renderRustWireBox(plan, srcExpr, depth = 0) {
|
|
|
618
589
|
// collect the pairs directly (clippy rejects `.map(|(k, v)| (k, v))` as an identity map). Same rule
|
|
619
590
|
// as the list branch's identity short-circuit above — box-once, no re-wrap.
|
|
620
591
|
if (valBox === v)
|
|
621
|
-
return `WireValue::Row(WireRow { entries: ${baseSrc}.into_iter().collect() })`;
|
|
622
|
-
return `WireValue::Row(WireRow { entries: ${baseSrc}.into_iter().map(|(${k}, ${v})| (${k}, ${valBox})).collect() })`;
|
|
592
|
+
return `WireValue::Row(WireRow { entries: ${baseSrc}.into_iter().map(|(${k}, ${v})| (Cow::Owned(${k}), ${v})).collect() })`;
|
|
593
|
+
return `WireValue::Row(WireRow { entries: ${baseSrc}.into_iter().map(|(${k}, ${v})| (Cow::Owned(${k}), ${valBox})).collect() })`;
|
|
623
594
|
}
|
|
624
595
|
throw new GeneratorFailure("UNSUPPORTED_NODE_STRAIGHTLINE", `rust wire box: unexpected plan kind '${plan.k}'`);
|
|
625
596
|
};
|
|
@@ -678,6 +649,11 @@ function rustOwn(guard, ownArrays) {
|
|
|
678
649
|
return `${expr}.clone()`;
|
|
679
650
|
};
|
|
680
651
|
}
|
|
652
|
+
/** rustMoved — the ownership renderer for a head that was MOVED out of its cell: the value is already
|
|
653
|
+
* owned, so the leaf adds nothing. (rustOwn's clone/deref exist only because a borrow cannot be kept.) */
|
|
654
|
+
function rustMoved() {
|
|
655
|
+
return (expr) => expr;
|
|
656
|
+
}
|
|
681
657
|
/** nativeResolveHead — the ONE ref-head resolver the runtime-free native-expr compiler reads (cond `if`/
|
|
682
658
|
* branches, a map/fanout `when` guard, AND a port). A head is a `$as` element binding, a prior body node's
|
|
683
659
|
* typed cell (behind a RefCell borrow guard), or an input port (a by-value struct field). #139: the input
|
|
@@ -690,11 +666,17 @@ function nativeResolveHead(comp, plan, typedNodes, isPrior, opts) {
|
|
|
690
666
|
}
|
|
691
667
|
if (isPrior(head)) {
|
|
692
668
|
const ref = typedNodes.get(head);
|
|
669
|
+
// This node's result has exactly one reader (movableCells) — take it out of the cell instead of
|
|
670
|
+
// copying it. The wire enum has no Default, so a `value` cell swaps in the null wire to move.
|
|
671
|
+
if (opts?.moveHeads?.has(head) === true)
|
|
672
|
+
return { expr: rustCellRead(head, ref, false, opts.moveHeads), ref, own: rustMoved() };
|
|
693
673
|
return { expr: `${typedCell(head)}.borrow()`, ref, own: rustOwn(true, ownArrays) };
|
|
694
674
|
}
|
|
695
675
|
const ref = inputPortTypeRef(comp.inputPorts?.[head], plan);
|
|
696
676
|
if (ref === undefined)
|
|
697
677
|
return null;
|
|
678
|
+
if (opts?.moveHeads?.has(head) === true)
|
|
679
|
+
return { expr: rustFieldName(head), ref, own: rustMoved() };
|
|
698
680
|
// #192: the input port is a positional PARAMETER of the entry (box removed) — read it by param name
|
|
699
681
|
// (= rustFieldName(port), the single input-ref name source; same owned-value semantics as `in_.field`).
|
|
700
682
|
return { expr: rustFieldName(head), ref, own: rustOwn(false, ownArrays) };
|
|
@@ -808,17 +790,14 @@ function makeRustExprBackend(resolveHead, plan) {
|
|
|
808
790
|
// native String concat via a `[&str; N].concat()` — a string-literal part (`"…".to_string()`) is
|
|
809
791
|
// used as the bare `"…"` &str; any other owned String is borrowed with `.as_str()`. This shape is
|
|
810
792
|
// clippy-clean (no to_string_in_format_args / single_char_push_str / unnecessary_to_string).
|
|
811
|
-
const refs = parts.map((p) => {
|
|
812
|
-
const m = /^(".*")\.to_string\(\)$/.exec(p);
|
|
813
|
-
return m ? m[1] : `(${p}).as_str()`;
|
|
814
|
-
});
|
|
793
|
+
const refs = parts.map((p) => rustStaticStrLit(p) ?? `(${p}).as_str()`);
|
|
815
794
|
return `[${refs.join(", ")}].concat()`;
|
|
816
795
|
},
|
|
817
796
|
notOp: (a) => `(!${a})`,
|
|
818
797
|
structLit: (name, inits) => `${name} { ${inits.map((i) => `${rustFieldName(i.field)}: ${i.expr}`).join(", ")} }`,
|
|
819
798
|
arrLit: (elemTy, items) => `{ let __v: Vec<${elemTy}> = vec![${items.join(", ")}]; __v }`,
|
|
820
799
|
// #209: the opaque wire built directly from an inline composite literal at a `value` port.
|
|
821
|
-
wireRowLit: (entries) => `WireValue::Row(WireRow { entries: vec![${entries.map((e) => `(${rustStrLit(e.key)}
|
|
800
|
+
wireRowLit: (entries) => `WireValue::Row(WireRow { entries: vec![${entries.map((e) => `(Cow::Borrowed(${rustStrLit(e.key)}), ${e.expr})`).join(", ")}] })`,
|
|
822
801
|
wireListLit: (items) => `WireValue::List(WireList { items: vec![${items.join(", ")}] })`,
|
|
823
802
|
// #209: a string-keyed map literal — a BTreeMap built from statically known entries (key order is the
|
|
824
803
|
// BTreeMap's own code-point order, matching the canonical serialization).
|
|
@@ -1263,7 +1242,7 @@ function coveredMapNode(n, bodyIds, comp) {
|
|
|
1263
1242
|
// arr field, or an input array port carrying `elemType` (BC does not infer — consumer-interface C3).
|
|
1264
1243
|
if (m.when !== undefined && m.into !== undefined && !guardedMapIntoIsCoverable(n, comp))
|
|
1265
1244
|
return false;
|
|
1266
|
-
if (m.relationKind !== undefined && m.relationKind !== "
|
|
1245
|
+
if (m.relationKind !== undefined && m.relationKind !== "connection")
|
|
1267
1246
|
return false;
|
|
1268
1247
|
// A map node must carry an outType (its ELEMENT type per the recorder SoT — authoring.ts recordMap
|
|
1269
1248
|
// holds `node.outType = mapElem`, the PRE-array-wrap element; the emitter synthesizes the produced
|
|
@@ -1274,7 +1253,13 @@ function coveredMapNode(n, bodyIds, comp) {
|
|
|
1274
1253
|
// per-op re-box), exactly as the componentRef path treats a passthrough result. Any other non-compound
|
|
1275
1254
|
// element type stays uncovered (loud), as before.
|
|
1276
1255
|
const outT = n.outType;
|
|
1277
|
-
|
|
1256
|
+
// #225: 純式 map(`transform`)の要素は**式から native に組む**(ワイヤも de-box も無い)ので、要素型が
|
|
1257
|
+
// スカラでも被覆される — 宣言型 materializer が組めれば良く、組めなければそこで loud に落ちる。
|
|
1258
|
+
// Component map は要素 wire を de-box するので従来どおり compound / opaque wire に限る。
|
|
1259
|
+
const isTransformMap = mapTransformExpr(m) !== undefined;
|
|
1260
|
+
if (outT === undefined)
|
|
1261
|
+
return false;
|
|
1262
|
+
if (!isTransformMap && typeof outT !== "object" && !mapNodeElemIsOpaqueWire(n))
|
|
1278
1263
|
return false;
|
|
1279
1264
|
const overE = classifyExpr(m.over);
|
|
1280
1265
|
if (overE.kind !== "ref")
|
|
@@ -1388,8 +1373,12 @@ function coverageRejectReason(comp) {
|
|
|
1388
1373
|
// {ok}/null skip marker) AND the Φ-merge VALUE cond (#108, has outType — the sibling Φ-join). A
|
|
1389
1374
|
// value cond's outType requirement is enforced by the per-node cond check below, so a parallel
|
|
1390
1375
|
// value cond without outType still loud-rejects there.
|
|
1376
|
+
// #225: 純式 map(`map.transform`)も cond と同じ性質(handler も boxed result も無い変換)なので、
|
|
1377
|
+
// 昇順 preflight で確定させれば error-precedence 協定を乱さない。免除根拠は go 側と同一。
|
|
1391
1378
|
if ("cond" in n)
|
|
1392
1379
|
continue;
|
|
1380
|
+
if ("map" in n && mapTransformExpr(n.map) !== undefined)
|
|
1381
|
+
continue;
|
|
1393
1382
|
if (!("component" in n))
|
|
1394
1383
|
return `node '${n.id}' is a non-componentRef member of a parallel stage (not native-covered)`;
|
|
1395
1384
|
}
|
|
@@ -1424,14 +1413,10 @@ function coverageRejectReason(comp) {
|
|
|
1424
1413
|
const cr = n;
|
|
1425
1414
|
// Every Error Policy Kind IS covered on a componentRef (see the go emitter's note): `continue` →
|
|
1426
1415
|
// unproduced (produced-aware output), `retry` → `fail`'s control flow with the Kind in the message.
|
|
1427
|
-
//
|
|
1428
|
-
//
|
|
1429
|
-
//
|
|
1430
|
-
|
|
1431
|
-
const childOfGate = cr.parent !== undefined && isControlGate(comp.body.find((b) => b.id === cr.parent));
|
|
1432
|
-
if (!childOfGate && cr.bindField !== undefined && cr.relationKind !== "single" && cr.relationKind !== "connection")
|
|
1433
|
-
return `node '${n.id}' relationKind '${cr.relationKind ?? "point"}' not native-covered (bindField only supports single|connection)`;
|
|
1434
|
-
if (cr.relationKind !== undefined && cr.relationKind !== "single" && cr.relationKind !== "connection")
|
|
1416
|
+
// relationKind の閉集合は `connection` の 1 値で、**注記の不在**が「未生成は null」を意味する。ゆえに
|
|
1417
|
+
// bindField 由来 skip は 2 形(connection = 空 connection / 不在 = null)とも produced-aware 出力が
|
|
1418
|
+
// 表現でき、被覆条件は無い(かつての「明示的に single と書け」は既定値の重複綴りの要求だった)。
|
|
1419
|
+
if (cr.relationKind !== undefined && cr.relationKind !== "connection")
|
|
1435
1420
|
return `relationKind '${cr.relationKind}' not native-covered (node '${n.id}')`;
|
|
1436
1421
|
// #170: a control-gate child's ports may narrow a gate-proven opt ref to non-null (the (a3) gated read).
|
|
1437
1422
|
const crNarrowed = nodeNarrowedPaths(comp, cr);
|
|
@@ -1513,12 +1498,60 @@ function emitPortWireField(pn, expr, comp, plan, typedNodes, isPrior, expected,
|
|
|
1513
1498
|
if (c.stmts.length > 0)
|
|
1514
1499
|
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.`);
|
|
1515
1500
|
const boxed = renderRustWireBox(buildWirePlan(c.ref, { from: "top" }, { model: "port", field: pn, plan }, "in"), c.expr);
|
|
1516
|
-
return `(${rustStrLit(pn)}
|
|
1501
|
+
return `(Cow::Borrowed(${rustStrLit(pn)}), ${boxed})`;
|
|
1517
1502
|
}
|
|
1518
1503
|
// ── the combined runner (STRUCT-returning; INLINE sequential; native ports in; concrete row out) ──
|
|
1519
1504
|
function rustScalar(s) {
|
|
1520
1505
|
return s === "string" ? "String" : s === "int" ? "i64" : s === "float" ? "f64" : "bool";
|
|
1521
1506
|
}
|
|
1507
|
+
/**
|
|
1508
|
+
* movableRefs — the values (a body node's RESULT, or an input port) with exactly ONE reader in the whole
|
|
1509
|
+
* component, so that reader can take the value by MOVE instead of copying it.
|
|
1510
|
+
*
|
|
1511
|
+
* Handing a prior node's result to a downstream leaf is where a result set would otherwise be deep-copied:
|
|
1512
|
+
* a `Vec<WireValue>` clone re-allocates every string in every row, once per node boundary. Counting the
|
|
1513
|
+
* readers statically says when copying is unnecessary — which, in a read chain, is the normal case.
|
|
1514
|
+
*
|
|
1515
|
+
* A read is counted from the ONE place a value can be referenced: a `{ref}` / `{refOpt}` path whose head
|
|
1516
|
+
* names a body node or an input port (ports, guards, map sources, the output value), plus the parent read
|
|
1517
|
+
* a bindField performs. Two reads (or none) ⇒ not movable. A read nested inside a `map` / `fanout` element
|
|
1518
|
+
* body runs once PER ELEMENT, so it counts as many — a single textual site is not a single read there.
|
|
1519
|
+
*/
|
|
1520
|
+
function movableRefs(comp) {
|
|
1521
|
+
const counts = new Map();
|
|
1522
|
+
const bump = (head, times) => {
|
|
1523
|
+
counts.set(head, (counts.get(head) ?? 0) + times);
|
|
1524
|
+
};
|
|
1525
|
+
const walk = (n, times) => {
|
|
1526
|
+
if (Array.isArray(n)) {
|
|
1527
|
+
for (const e of n)
|
|
1528
|
+
walk(e, times);
|
|
1529
|
+
return;
|
|
1530
|
+
}
|
|
1531
|
+
if (n === null || typeof n !== "object")
|
|
1532
|
+
return;
|
|
1533
|
+
const rec = n;
|
|
1534
|
+
const keys = Object.keys(rec);
|
|
1535
|
+
if (keys.length === 1 && (keys[0] === "ref" || keys[0] === "refOpt")) {
|
|
1536
|
+
const path = rec[keys[0]];
|
|
1537
|
+
if (Array.isArray(path) && typeof path[0] === "string")
|
|
1538
|
+
bump(path[0], times);
|
|
1539
|
+
return;
|
|
1540
|
+
}
|
|
1541
|
+
// an element body repeats: everything under a map / fanout is read once per element.
|
|
1542
|
+
const repeats = times === 1 && ("map" in rec || "fanout" in rec) ? 2 : times;
|
|
1543
|
+
for (const k of keys)
|
|
1544
|
+
walk(rec[k], repeats);
|
|
1545
|
+
};
|
|
1546
|
+
walk(comp.body, 1);
|
|
1547
|
+
walk(comp.output, 1);
|
|
1548
|
+
for (const nd of comp.body) {
|
|
1549
|
+
const cr = nd;
|
|
1550
|
+
if (cr.parent !== undefined && cr.bindField !== undefined)
|
|
1551
|
+
bump(cr.parent, 1);
|
|
1552
|
+
}
|
|
1553
|
+
return new Set([...counts].filter(([, c]) => c === 1).map(([id]) => id));
|
|
1554
|
+
}
|
|
1522
1555
|
function emitNativeRawRunner(comp, plan, ap, leaf, declared) {
|
|
1523
1556
|
const ep = execPlan(comp);
|
|
1524
1557
|
const order = ep.order;
|
|
@@ -1541,6 +1574,17 @@ function emitNativeRawRunner(comp, plan, ap, leaf, declared) {
|
|
|
1541
1574
|
for (const n of comp.body)
|
|
1542
1575
|
if (!isControlGate(n))
|
|
1543
1576
|
typedNodes.set(n.id, "map" in n ? mapNodeArrRef(n, plan) : deriveTypeRef(n.outType, plan));
|
|
1577
|
+
// Single-reader results are handed on by MOVE (see movableCells). A parallel stage builds its members'
|
|
1578
|
+
// payloads inside a scoped-thread closure, so a read there is not the plain sequential read the count
|
|
1579
|
+
// assumed — drop every head a stage member reads and let those copy.
|
|
1580
|
+
const moveHeads = movableRefs(comp);
|
|
1581
|
+
for (const [i] of ep.parallelStageOf) {
|
|
1582
|
+
for (const pn of Object.keys(comp.body[i].ports ?? {})) {
|
|
1583
|
+
const e = classifyExpr(comp.body[i].ports[pn]);
|
|
1584
|
+
if (e.kind === "ref")
|
|
1585
|
+
moveHeads.delete(e.path[0]);
|
|
1586
|
+
}
|
|
1587
|
+
}
|
|
1544
1588
|
// the ops literal comes from the SHARED derivation (opsLiteralOf): a local "read cr.policy / cr.parent"
|
|
1545
1589
|
// copy silently drops a MAP's / FANOUT's policy and parent (they live under map./fanout.), which would
|
|
1546
1590
|
// make canSkip — and therefore the produced-aware output — disagree with the go surface on the same IR.
|
|
@@ -1562,7 +1606,7 @@ function emitNativeRawRunner(comp, plan, ap, leaf, declared) {
|
|
|
1562
1606
|
lines.push(`// de-boxes the returned wire INLINE (match wire.as_*() { … } fully unrolled — no decode helper) into`);
|
|
1563
1607
|
lines.push(`// the node's outType struct cell — no boxed handler result, no generic enum crossing, no dispatch on a dynamic value on the covered plane. Node`);
|
|
1564
1608
|
lines.push(`// results are typed struct cells; a relation child reads the parent's REAL struct result via`);
|
|
1565
|
-
lines.push(`// direct field access (child-present decision from the real parent value —
|
|
1609
|
+
lines.push(`// direct field access (child-present decision from the real parent value — relation /`);
|
|
1566
1610
|
lines.push(`// connection converge). A real-concurrency stage (bc#87) is static parallel orchestration —`);
|
|
1567
1611
|
lines.push(`// scoped worker threads (bounded by the static plan.concurrency) call the transport; preflight +`);
|
|
1568
1612
|
lines.push(`// interpret are committed in ascending index order so the value / op multiset / failure`);
|
|
@@ -1658,7 +1702,7 @@ function emitNativeRawRunner(comp, plan, ap, leaf, declared) {
|
|
|
1658
1702
|
}
|
|
1659
1703
|
}
|
|
1660
1704
|
const narrowed = nodeNarrowedPaths(comp, node);
|
|
1661
|
-
const fields = portNames.map((pn) => emitPortWireField(pn, node.ports[pn], comp, plan, typedNodes, (h) => priorNodeAt(h, k), inputPortTypeRef(node.portSchemas?.[pn], plan), { narrowed }));
|
|
1705
|
+
const fields = portNames.map((pn) => emitPortWireField(pn, node.ports[pn], comp, plan, typedNodes, (h) => priorNodeAt(h, k), inputPortTypeRef(node.portSchemas?.[pn], plan), { narrowed, moveHeads }));
|
|
1662
1706
|
// bc#97: derived per-node await — this point-read's future is awaited HERE (its result-consumption
|
|
1663
1707
|
// point) iff THIS node's terminal handler is async. A sync handler in the same async runner is called
|
|
1664
1708
|
// directly (no `.await`). The runner being `async fn` does not force every call site to await.
|
|
@@ -1707,8 +1751,8 @@ function emitNativeRawRunner(comp, plan, ap, leaf, declared) {
|
|
|
1707
1751
|
}
|
|
1708
1752
|
}
|
|
1709
1753
|
const out = skippable.size > 0
|
|
1710
|
-
? emitProducedAwareValue(comp.output, outRef, typedNodes, plan, skippable, skippableKind, comp.name, "<output>")
|
|
1711
|
-
: emitTypedValue(comp.output, outRef, typedNodes, plan, comp.name, "<output>");
|
|
1754
|
+
? emitProducedAwareValue(comp.output, outRef, typedNodes, plan, skippable, skippableKind, comp.name, "<output>", moveHeads)
|
|
1755
|
+
: emitTypedValue(comp.output, outRef, typedNodes, plan, comp.name, "<output>", moveHeads);
|
|
1712
1756
|
// top-level output that is a bare node-result (not an obj/arr assembly): its honest `ref` must equal the
|
|
1713
1757
|
// declared component output type, or the emitted `let __out = …; Ok(__out)` return does not compile.
|
|
1714
1758
|
checkOutputFieldType(comp.name, "<output>", outRef, out.ref, plan);
|
|
@@ -1742,10 +1786,16 @@ function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes
|
|
|
1742
1786
|
// when-gated connection relations each folding to `ref | emptyConn`). Both are mutually independent
|
|
1743
1787
|
// (§1), so ascending-at-head is byte-equal to run_behavior. A cond never shares a stage with a node
|
|
1744
1788
|
// that depends on it (an intra-stage parent/child dep is rejected by concurrencyPlan).
|
|
1745
|
-
|
|
1746
|
-
const
|
|
1789
|
+
// #225: dispatch を持たないメンバ = cond + 純式 map。昇順に、**逐次パスと同じ arm** で emit する。
|
|
1790
|
+
const noDispatch = (i) => "cond" in comp.body[i] || ("map" in comp.body[i] && mapTransformExpr(comp.body[i].map) !== undefined);
|
|
1791
|
+
const condMembers = stage.filter(noDispatch);
|
|
1792
|
+
const refMembers = stage.filter((i) => !noDispatch(i));
|
|
1747
1793
|
for (const i of condMembers) {
|
|
1748
|
-
|
|
1794
|
+
const n = comp.body[i];
|
|
1795
|
+
lines.push("cond" in n
|
|
1796
|
+
? emitCondArm(comp, n, atPos + stage.indexOf(i), typedNodes, plan, priorNodeAt)
|
|
1797
|
+
: // 純式 map は leaf を呼ばないので async 性を持たない(sync 既定)。
|
|
1798
|
+
emitMapArm(comp, n, atPos + stage.indexOf(i), typedNodes, plan, priorNodeAt, leaf, false, metas[i].policy));
|
|
1749
1799
|
}
|
|
1750
1800
|
// A cond-ONLY stage carries no handler fan-out — the conds above ARE the whole stage. Skip the scoped-
|
|
1751
1801
|
// thread orchestration block entirely (an empty one is dead scaffolding clippy rejects: never_loop /
|
|
@@ -1773,7 +1823,7 @@ function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes
|
|
|
1773
1823
|
// it is a plain local inside the produced block — NOT a stage-scoped mut (nothing captures it) and no
|
|
1774
1824
|
// dead None init. A control-gate parent needs no bound at all (produced_<gate> already carries the skip).
|
|
1775
1825
|
if (gated) {
|
|
1776
|
-
lines.push(` let
|
|
1826
|
+
lines.push(` let payload_${s}: std::sync::Mutex<Option<WireRow>> = std::sync::Mutex::new(None);`);
|
|
1777
1827
|
lines.push(`${ind}if produced_${sanitize(node.parent)}.get() {`);
|
|
1778
1828
|
closers.unshift(`${ind}}`);
|
|
1779
1829
|
ind += " ";
|
|
@@ -1795,10 +1845,10 @@ function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes
|
|
|
1795
1845
|
const narrowed = nodeNarrowedPaths(comp, node);
|
|
1796
1846
|
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 }));
|
|
1797
1847
|
if (gated) {
|
|
1798
|
-
lines.push(`${ind}payload_${s} = Some(${rustPayloadRow(fields)});`);
|
|
1848
|
+
lines.push(`${ind}*payload_${s}.lock().unwrap() = Some(${rustPayloadRow(fields)});`);
|
|
1799
1849
|
}
|
|
1800
1850
|
else {
|
|
1801
|
-
lines.push(`${ind}let payload_${s}: Option<WireRow
|
|
1851
|
+
lines.push(`${ind}let payload_${s}: std::sync::Mutex<Option<WireRow>> = std::sync::Mutex::new(Some(${rustPayloadRow(fields)}));`);
|
|
1802
1852
|
}
|
|
1803
1853
|
for (const c of closers)
|
|
1804
1854
|
lines.push(c);
|
|
@@ -1820,7 +1870,7 @@ function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes
|
|
|
1820
1870
|
lines.push(` let mut ${jobsVar}: Vec<usize> = Vec::new();`);
|
|
1821
1871
|
refMembers.forEach((i, slot) => {
|
|
1822
1872
|
const s = sanitize(comp.body[i].id);
|
|
1823
|
-
lines.push(` if payload_${s}.is_some() { ${jobsVar}.push(${slot}); }`);
|
|
1873
|
+
lines.push(` if payload_${s}.lock().unwrap().is_some() { ${jobsVar}.push(${slot}); }`);
|
|
1824
1874
|
});
|
|
1825
1875
|
lines.push(` let cursor = std::sync::atomic::AtomicUsize::new(0);`);
|
|
1826
1876
|
lines.push(` let workers = ${boundN}usize.min(${jobsVar}.len());`);
|
|
@@ -1835,11 +1885,11 @@ function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes
|
|
|
1835
1885
|
const node = comp.body[i];
|
|
1836
1886
|
const s = sanitize(node.id);
|
|
1837
1887
|
// DIRECT leaf transport call — ONE op-agnostic symbol, ONE WireRow payload (the preflight-built ports,
|
|
1838
|
-
//
|
|
1839
|
-
// preflight — the leaf never sees it).
|
|
1888
|
+
// MOVED into the owned-arg call — the worker that wins the slot takes it). No `bound` (BC's internal
|
|
1889
|
+
// produced/skip gate is already applied in preflight — the leaf never sees it).
|
|
1840
1890
|
const call = `${resolveLeafSymbol(node.component, leaf, node.leafSymbol)}(payload)`;
|
|
1841
1891
|
lines.push(` ${slot} => {`);
|
|
1842
|
-
lines.push(` let payload = payload_${s}.
|
|
1892
|
+
lines.push(` let payload = payload_${s}.lock().unwrap().take().expect("runnable member has ports");`);
|
|
1843
1893
|
lines.push(` let row = ${call};`);
|
|
1844
1894
|
lines.push(` *slot_${s}.lock().unwrap() = Some(row);`);
|
|
1845
1895
|
lines.push(` }`);
|
|
@@ -1855,8 +1905,12 @@ function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes
|
|
|
1855
1905
|
const meta = metas[i];
|
|
1856
1906
|
const s = sanitize(node.id);
|
|
1857
1907
|
const ref = typedNodes.get(node.id);
|
|
1858
|
-
|
|
1859
|
-
|
|
1908
|
+
// A member that ran wrote its slot; taking it is both the "did it run" test and the move of the wire
|
|
1909
|
+
// out of the stage (the payload was already taken by the worker, so it can no longer answer that).
|
|
1910
|
+
// bind first: an `if let` scrutinee keeps its temporaries — including the MutexGuard — alive for the
|
|
1911
|
+
// whole body, which outlives the borrow the body needs.
|
|
1912
|
+
lines.push(` let taken_${s} = slot_${s}.lock().unwrap().take();`);
|
|
1913
|
+
lines.push(` if let Some(out_${s}) = taken_${s} {`);
|
|
1860
1914
|
if (meta.policy === "continue") {
|
|
1861
1915
|
// continue: a member whose COMPONENT failed commits no Port. A de-box mismatch still propagates —
|
|
1862
1916
|
// the interpreter's outType check sits outside the policy interpretation (see the sequential arm).
|
|
@@ -2005,7 +2059,10 @@ isAsync = false, policy = "fail") {
|
|
|
2005
2059
|
// the node's own statements start here (rustPolicyArm wraps THIS range when the Kind is `continue`).
|
|
2006
2060
|
const bodyStart = lines.length;
|
|
2007
2061
|
lines.push(`${indent}let over_${s} = ${rustBindOverExpr(overExpr, overOptArr)};`);
|
|
2008
|
-
|
|
2062
|
+
// `built_<s>` は Component 経路の集積ローカル。純式 map は typed cell へ直接積むので出さない
|
|
2063
|
+
// (生成物は clippy -D warnings を通るので未使用/不要 mut は出せない)。
|
|
2064
|
+
if (transform === undefined)
|
|
2065
|
+
lines.push(`${indent}let mut built_${s}: Vec<${elemName}> = Vec::with_capacity(over_${s}.len());`);
|
|
2009
2066
|
if (transform !== undefined) {
|
|
2010
2067
|
// 純式 map(#222): transport 呼びもワイヤも de-box も無い。要素式を宣言された要素型へ native に
|
|
2011
2068
|
// materialize して積む(port 境界と同一の宣言型 materializer を通す)。`when` は同一の keep-gate。
|
|
@@ -2326,13 +2383,13 @@ function emitCondArm(comp, node, atPos, typedNodes, plan, priorNodeAt) {
|
|
|
2326
2383
|
/**
|
|
2327
2384
|
* emitProducedAwareValue — the #86 part 1 produced-aware output lowering (rust twin of the go one).
|
|
2328
2385
|
*/
|
|
2329
|
-
function emitProducedAwareValue(node, expected, typedNodes, plan, skippable, skippableKind, compName, fieldPath) {
|
|
2386
|
+
function emitProducedAwareValue(node, expected, typedNodes, plan, skippable, skippableKind, compName, fieldPath, moveHeads) {
|
|
2330
2387
|
const e = classifyExpr(node);
|
|
2331
2388
|
if (e.kind === "ref" && e.path.length >= 1 && typedNodes.has(e.path[0])) {
|
|
2332
2389
|
const head = e.path[0];
|
|
2333
2390
|
const baseRef = typedNodes.get(head);
|
|
2334
2391
|
if (skippable.has(head)) {
|
|
2335
|
-
const base =
|
|
2392
|
+
const base = rustCellRead(head, baseRef, false, moveHeads);
|
|
2336
2393
|
const { expr, ref } = typedFieldAccess(base, baseRef, e.path.slice(1), plan);
|
|
2337
2394
|
// The value actually placed into this output field is `producedExpr` — its type is `ref`, opt-wrapped
|
|
2338
2395
|
// by valueLeafProduced iff the field is opt and the value is not (matching Some(...)). Compare its
|
|
@@ -2356,7 +2413,7 @@ function emitProducedAwareValue(node, expected, typedNodes, plan, skippable, ski
|
|
|
2356
2413
|
};
|
|
2357
2414
|
}
|
|
2358
2415
|
const isBareCopyScalar = e.path.length === 1 && baseRef.kind === "scalar" && (baseRef.scalar === "int" || baseRef.scalar === "float" || baseRef.scalar === "bool");
|
|
2359
|
-
const base =
|
|
2416
|
+
const base = rustCellRead(head, baseRef, isBareCopyScalar, moveHeads);
|
|
2360
2417
|
const { expr, ref } = typedFieldAccess(base, baseRef, e.path.slice(1), plan);
|
|
2361
2418
|
// Non-skippable node-result: its `ref` is returned honestly (not laundered), so the placing site — the
|
|
2362
2419
|
// obj-field assembly below, or the top-level call — runs checkOutputFieldType against the field type.
|
|
@@ -2369,7 +2426,7 @@ function emitProducedAwareValue(node, expected, typedNodes, plan, skippable, ski
|
|
|
2369
2426
|
const fields = node.obj;
|
|
2370
2427
|
const inits = decl.fields.map((f) => {
|
|
2371
2428
|
const childPath = fieldPath === "" ? f.name : `${fieldPath}.${f.name}`;
|
|
2372
|
-
const sub = emitProducedAwareValue(fields[f.name], f.type, typedNodes, plan, skippable, skippableKind, compName, childPath);
|
|
2429
|
+
const sub = emitProducedAwareValue(fields[f.name], f.type, typedNodes, plan, skippable, skippableKind, compName, childPath, moveHeads);
|
|
2373
2430
|
// Non-skippable field: sub.ref is the honest value type → catches a Vec-depth mismatch here. A
|
|
2374
2431
|
// skippable field launders sub.ref to expected, but its own produced-arm check (above) already fired.
|
|
2375
2432
|
checkOutputFieldType(compName, childPath, f.type, sub.ref, plan);
|
|
@@ -2378,7 +2435,7 @@ function emitProducedAwareValue(node, expected, typedNodes, plan, skippable, ski
|
|
|
2378
2435
|
return { expr: `${expected.name} { ${inits.join(", ")} }`, ref: expected };
|
|
2379
2436
|
}
|
|
2380
2437
|
}
|
|
2381
|
-
return emitTypedValue(node, expected, typedNodes, plan, compName, fieldPath);
|
|
2438
|
+
return emitTypedValue(node, expected, typedNodes, plan, compName, fieldPath, moveHeads);
|
|
2382
2439
|
}
|
|
2383
2440
|
function valueLeafProduced(expr, ref, expected) {
|
|
2384
2441
|
if (expected && expected.kind === "opt") {
|
|
@@ -2416,7 +2473,7 @@ fn leaf_failure(message: impl Into<String>) -> BehaviorError {
|
|
|
2416
2473
|
/**
|
|
2417
2474
|
* rustSharedWireTypesModule (#165, rust twin of goSharedWireTypesPackage) — the BC-GENERATED shared module
|
|
2418
2475
|
* content emitted when the covered module is generated with --shared-types-import. Carries the SAME wire seam
|
|
2419
|
-
* the covered module emits in-crate when the flag is absent (Probe
|
|
2476
|
+
* the covered module emits in-crate when the flag is absent (Probe + WireValue/WireRow/WireList +
|
|
2420
2477
|
* the probe classifiers) so a separate leaf-transport crate can take a `WireRow` payload + build+return
|
|
2421
2478
|
* `WireValue` (and the covered module reference them) without an import cycle. #183: the transport ABI is the
|
|
2422
2479
|
* generic `WireRow` payload built inline at the call site — there are NO per-node/per-role batch ports structs
|
|
@@ -2433,6 +2490,8 @@ export function rustSharedWireTypesModule() {
|
|
|
2433
2490
|
|
|
2434
2491
|
// Local concrete failure type (runtime-free) — the covered runner + the transport crate share it. Only the
|
|
2435
2492
|
// TYPE lives here; the de-box/op-failure CONSTRUCTORS stay in the covered module (they are called there).
|
|
2493
|
+
use std::borrow::Cow;
|
|
2494
|
+
|
|
2436
2495
|
${emitErrorTypeDefs()}
|
|
2437
2496
|
|
|
2438
2497
|
${emitRustProbeWireTypes(true)}
|
|
@@ -2486,7 +2545,7 @@ ${emitStructSurface([])}
|
|
|
2486
2545
|
// WireValue/WireRow/WireList traits) is emitted once whenever any handler node exists.
|
|
2487
2546
|
const anyWire = native.some((c) => c.body.some((n) => !("cond" in n)));
|
|
2488
2547
|
// #165: --shared-types-import parity with go. When set, the BC-OWNED wire types (WireValue/WireRow/
|
|
2489
|
-
// WireList + Probe
|
|
2548
|
+
// WireList + Probe) AND the batched-map/fanout batch ports structs (the ONLY structs that cross
|
|
2490
2549
|
// the leaf-transport boundary as a whole value) live in the SHARED crate/module at that path; the covered
|
|
2491
2550
|
// module IMPORTS them (`use <path>::*;`) instead of defining them locally — so a separate transport crate
|
|
2492
2551
|
// can return the shared WireValue with NO import cycle (covered → tx → shared, no back-edge). Absent →
|
|
@@ -2534,7 +2593,7 @@ ${emitStructSurface([])}
|
|
|
2534
2593
|
return undefined;
|
|
2535
2594
|
return `// op-agnostic leaf transport symbols (consumer-supplied) — called directly at each covered node.\nuse ${leaf.import}::{${[...syms].sort().join(", ")}};`;
|
|
2536
2595
|
})();
|
|
2537
|
-
// #165: --shared-types-import — bring the BC-OWNED wire types (WireValue/WireRow/WireList + Probe
|
|
2596
|
+
// #165: --shared-types-import — bring the BC-OWNED wire types (WireValue/WireRow/WireList + Probe)
|
|
2538
2597
|
// and the batched/fanout batch ports structs into scope from the shared crate/module (a glob `use`, so no
|
|
2539
2598
|
// reference site is qualified). The covered module defines NONE of them locally; a separate transport crate
|
|
2540
2599
|
// returns the SAME shared WireValue with no import cycle. Absent → in-crate (byte-identical to before).
|
|
@@ -2547,7 +2606,7 @@ ${emitStructSurface([])}
|
|
|
2547
2606
|
const banner = `#![allow(dead_code, unused_imports, unused_variables, non_snake_case)]
|
|
2548
2607
|
// GENERATED by behavior-contracts (bc#90, rust-typed-native — the RUNTIME-FREE read de-box; STRUCT-ONLY,
|
|
2549
2608
|
// FULLY-NATIVE). A covered read is a strictly-sequential typed componentRef chain (point reads +
|
|
2550
|
-
//
|
|
2609
|
+
// relation children), emitted ONLY as a STRUCT-returning runner that calls the op-agnostic leaf
|
|
2551
2610
|
// TRANSPORT symbol DIRECTLY at each covered node's execution point: native ports struct IN (direct
|
|
2552
2611
|
// construction — every port is a CONCRETE Rust value: String / bool / Vec<&str> projection / i64 limit —
|
|
2553
2612
|
// NO boxed Value, NO by-name accessor); the transport is called with the node's port fields spread and
|
|
@@ -2557,11 +2616,20 @@ ${emitStructSurface([])}
|
|
|
2557
2616
|
// The covered plane carries NO bc-runtime reference at all — failures use the LOCAL BehaviorError (same
|
|
2558
2617
|
// codes, byte-equal to run_behavior). INLINE sequential (no plan driver) so a relation child reads the
|
|
2559
2618
|
// parent's REAL struct result via direct field access and the child-present decision is made from the real
|
|
2560
|
-
// parent value —
|
|
2619
|
+
// parent value — relation / connection converge with run_behavior (fixes #323/#74). The exposed API
|
|
2561
2620
|
// is the 1:1 entry <method>(<positional params>) -> Result<T, BehaviorError> (the InNR_<comp> box removed);
|
|
2562
2621
|
// the consumer supplies the leaf transport symbols (default in-scope names leaf_<comp>, or a leafTransport
|
|
2563
|
-
// import).
|
|
2564
|
-
//
|
|
2622
|
+
// import).
|
|
2623
|
+
//
|
|
2624
|
+
// NO CLONE, NO PER-CALL ALLOCATION — the two rules this module is generated under:
|
|
2625
|
+
// - Everything fixed at generation time (SQL text, port names, field names) rides as \`&'static str\`
|
|
2626
|
+
// behind \`Cow::Borrowed\`, so building a payload allocates nothing for it, however often it is called.
|
|
2627
|
+
// - De-boxing CONSUMES the transport's wire: every string, row and list is MOVED into the typed value.
|
|
2628
|
+
// A \`.clone()\` on this path deep-copies the result set once per node boundary and scales with node
|
|
2629
|
+
// count — it is the difference between beating a hand-written driver and losing to an interpreter.
|
|
2630
|
+
// The codegen purity gate rejects \`.clone()\` and per-call \`.to_string()\` here, and the cost is confirmed
|
|
2631
|
+
// by benchmark, not by asserting it in this comment.
|
|
2632
|
+
use std::borrow::Cow;
|
|
2565
2633
|
use std::cell::RefCell;`;
|
|
2566
2634
|
const sections = [
|
|
2567
2635
|
banner,
|
|
@@ -2621,7 +2689,7 @@ export function rustTypedNativeObserve(ir, ioModel = "sync", leaf, declared) {
|
|
|
2621
2689
|
const anyDeBox = native.some((c) => c.body.some((n) => !("cond" in n)));
|
|
2622
2690
|
// value_to_wire (TEST glue): builds the covered module's BC-OWNED concrete `WireValue` from a scripted bc
|
|
2623
2691
|
// `Value` — the test-harness analog of the consumer's real transport (which builds `WireValue` as it reads
|
|
2624
|
-
// the producer). Numbers ride
|
|
2692
|
+
// the producer). Numbers ride in their declared type (WireValue::Int / WireValue::Float) — nothing parses;
|
|
2625
2693
|
// the wire tags + classification live ONCE in the covered module's WireValue (probe_*_at), so this only
|
|
2626
2694
|
// CONSTRUCTS — a scripted wrong-variant value maps to the corresponding WireValue variant and the covered
|
|
2627
2695
|
// de-box classifies it (TYPE_MISMATCH ≡ run_behavior), no separate scripted classifier.
|
|
@@ -2631,12 +2699,12 @@ fn value_to_wire(v: &Value) -> WireValue {
|
|
|
2631
2699
|
match v {
|
|
2632
2700
|
Value::Null => WireValue::Null,
|
|
2633
2701
|
Value::Bool(b) => WireValue::Bool(*b),
|
|
2634
|
-
Value::Int(n) => WireValue::
|
|
2635
|
-
Value::Float(f) => WireValue::
|
|
2636
|
-
Value::Str(s) => WireValue::Str(s.clone()),
|
|
2702
|
+
Value::Int(n) => WireValue::Int(*n),
|
|
2703
|
+
Value::Float(f) => WireValue::Float(*f),
|
|
2704
|
+
Value::Str(s) => WireValue::Str(Cow::Owned(s.clone())),
|
|
2637
2705
|
Value::Arr(items) => WireValue::List(WireList { items: items.iter().map(value_to_wire).collect() }),
|
|
2638
2706
|
Value::Obj(pairs) => WireValue::Row(WireRow {
|
|
2639
|
-
entries: pairs.iter().map(|(k, vv)| (k.clone(), value_to_wire(vv))).collect(),
|
|
2707
|
+
entries: pairs.iter().map(|(k, vv)| (Cow::Owned(k.clone()), value_to_wire(vv))).collect(),
|
|
2640
2708
|
}),
|
|
2641
2709
|
}
|
|
2642
2710
|
}`
|
|
@@ -2664,6 +2732,9 @@ fn value_to_wire(v: &Value) -> WireValue {
|
|
|
2664
2732
|
for (const n of c.body) {
|
|
2665
2733
|
if ("cond" in n)
|
|
2666
2734
|
continue; // #108: a cond node has no leaf (pure Expression) — no transport fn.
|
|
2735
|
+
// #225: 純式 map も Component を呼ばないので transport fn を持たない(cond と同じ)。
|
|
2736
|
+
if ("map" in n && mapTransformExpr(n.map) !== undefined)
|
|
2737
|
+
continue;
|
|
2667
2738
|
const catalog = ("fanout" in n ? n.fanout.component : "map" in n ? n.map.component : n.component);
|
|
2668
2739
|
const specSym = "fanout" in n ? n.fanout.leafSymbol : "map" in n ? n.map.leafSymbol : n.leafSymbol;
|
|
2669
2740
|
const sym = resolveLeafSymbol(catalog, leaf, specSym);
|
|
@@ -2689,18 +2760,18 @@ fn value_to_wire(v: &Value) -> WireValue {
|
|
|
2689
2760
|
}
|
|
2690
2761
|
if (portRust === recordRust) {
|
|
2691
2762
|
// the port IS the whole record → echo its payload wire DIRECTLY (matching run_behavior's echo:port).
|
|
2692
|
-
echo.push(` if echo == ${rustStrLit(pn)} {\n if let Some(
|
|
2763
|
+
echo.push(` if echo == ${rustStrLit(pn)} {\n if let Some(v) = payload.take(${rustStrLit(pn)}) {\n return Ok(v);\n }\n }`);
|
|
2693
2764
|
}
|
|
2694
2765
|
else if (fieldRust !== null && field !== undefined && portRust === fieldRust) {
|
|
2695
2766
|
// a scalar port wraps into the record's single field ({v: <port wire>}) — mirrors the scripted `wrap`.
|
|
2696
|
-
echo.push(` if echo == ${rustStrLit(pn)} {\n if let Some(
|
|
2767
|
+
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 }`);
|
|
2697
2768
|
}
|
|
2698
2769
|
}
|
|
2699
2770
|
}
|
|
2700
2771
|
else if (ref.kind === "arr" && Object.prototype.hasOwnProperty.call(node.ports, "items")) {
|
|
2701
2772
|
// #129: an arr node with an `items` port echoes the payload's items wire (a WireList) so the
|
|
2702
2773
|
// node→leaf array dataflow test is non-vacuous.
|
|
2703
|
-
echo.push(` if echo == "items" {\n if let Some(
|
|
2774
|
+
echo.push(` if echo == "items" {\n if let Some(v) = payload.take("items") {\n return Ok(v);\n }\n }`);
|
|
2704
2775
|
}
|
|
2705
2776
|
}
|
|
2706
2777
|
const prev = bySym.get(sym);
|
|
@@ -2723,7 +2794,7 @@ fn value_to_wire(v: &Value) -> WireValue {
|
|
|
2723
2794
|
const hasEcho = le.echo.length > 0;
|
|
2724
2795
|
const echoBind = hasEcho ? "echo" : "_echo";
|
|
2725
2796
|
const echoBlock = hasEcho ? `${le.echo.join("\n")}\n` : "";
|
|
2726
|
-
transportFns.push(`${fnKw} ${sym}(${hasEcho ? "payload" : "_payload"}: WireRow) -> Result<WireValue, BehaviorError> {
|
|
2797
|
+
transportFns.push(`${fnKw} ${sym}(${hasEcho ? "mut payload" : "_payload"}: WireRow) -> Result<WireValue, BehaviorError> {
|
|
2727
2798
|
let (is_err, err, ok, ${echoBind}) = next_scripted(${rustStrLit(le.catalog)}).ok_or_else(|| unknown_component(${rustStrLit(le.catalog)}))?;
|
|
2728
2799
|
if is_err {
|
|
2729
2800
|
return Err(leaf_failure(err));
|