@onda-lang/binaryen-web 0.8.3 → 0.8.5

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/README.md CHANGED
@@ -37,8 +37,9 @@ the 8-argument `onda_processor_init(params_ptr, state_ptr, mode, buffers_ptr,
37
37
  buffer_frames_ptr, buffer_channels_ptr, buffer_sample_rates_ptr, output_ptr)`, the 12-argument processor
38
38
  `onda_process`, and one `onda_event_N` function per declared event. Init, process, and event entries
39
39
  take an optional call-scoped execution-output pointer carrying independent delegate and print
40
- batches. Each function returns zero on success or a positive generated execution-failure code. These are
41
- the complete wasm32-module profile of the generic
40
+ batches. Each function returns zero on success or a positive execution status: `1` is a generated
41
+ runtime-safety failure, while an event may also return `2` when its input is rejected before
42
+ execution. These are the complete wasm32-module profile of the generic
42
43
  [`Onda processor ABI`](../../docs/processor-abi.md), not a Web Audio-specific interface. The host
43
44
  owns allocation in linear memory. Metadata contains resolved target/integration facts,
44
45
  state/parameter layouts, state-backed control-output offsets, flattened audio-port channels, packed
@@ -47,6 +48,13 @@ the internal [delegate host integration](../../docs/delegates.md) and
47
48
  [print host integration](../../docs/printing.md) references for batch sizing, decoding, formatting,
48
49
  and overflow handling.
49
50
 
51
+ Each `onda_event_N` receives a pointer to the ABI's 16-byte wasm32 `EventInput` descriptor before
52
+ the ordinary processor storage arguments. The backend validates the complete little-endian wire
53
+ payload and aligned workspace before touching handler state or output records. Truncated or trailing
54
+ payloads, invalid slice lengths, out-of-bounds regions, misalignment, and insufficient workspace
55
+ return `PROCESSOR_EXECUTION_INPUT_REJECTED` (`2`) and leave the processor usable; accepted
56
+ structured values are exposed to generated code through aligned leaf tensors.
57
+
50
58
  `createProcessorArtifactFiles()` validates the final module, computes a SHA-256 digest, and returns
51
59
  a reusable `.wasm` plus `.onda.json` descriptor pair. `validateProcessorArtifact`,
52
60
  `parseProcessorMetadata`, and `serializeProcessorMetadata` are also exported for loaders. The
@@ -60,7 +68,7 @@ The executable backend supports:
60
68
  - scalar and fixed scalar-array state/parameter/audio-port addressing
61
69
  - constants, casts, arithmetic, comparisons, structured `if`/loop control, calls, and scalar or multi-value returns
62
70
  - input loads, output stores, and immutable constant-data loads
63
- - scalar/fixed-array event payload loads and event ABI wrappers
71
+ - recursive scalar, tuple, struct, fixed-array, and slice event payload preparation and ABI wrappers
64
72
  - scalar/fixed-array control-output stores in the shared state blob
65
73
  - interleaved mono/static/dynamic external buffers, uniformly clamped source access, fixed
66
74
  constant-time buffer collections, nullable host pointers with neutral zero/discard storage, and
@@ -72,7 +80,13 @@ The executable backend supports:
72
80
  - native WebAssembly numeric intrinsics plus on-demand internal transcendental and strict-FMA helpers
73
81
  - Binaryen validation and optimization before emission
74
82
 
75
- The backend also supports primitive slice locals and reference arguments, event slices, flattened data structs, structure-of-arrays processor state, recursive processor arrays, and canonical top-level/processor oversampling schedules. Oversampling interpolation, substeps, sinc-filter state updates, and output decimation are ordinary MIR operations; Binaryen has no Onda-specific scheduling logic. Recursive call graphs are rejected as unbounded realtime work before fixed-array local storage can become re-entrant. Aggregate shapes that cannot be represented by portable MIR are rejected above the backend boundary.
83
+ The backend also supports primitive and data-struct slice locals and reference arguments, recursive
84
+ event/delegate schemas, flattened data structs, structure-of-arrays processor state, recursive
85
+ processor arrays, and canonical top-level/processor oversampling schedules. Oversampling
86
+ interpolation, substeps, sinc-filter state updates, and output decimation are ordinary MIR
87
+ operations; Binaryen has no Onda-specific scheduling logic. Recursive call graphs are rejected as
88
+ unbounded realtime work before fixed-array local storage can become re-entrant. Aggregate shapes
89
+ that cannot be represented by portable MIR are rejected above the backend boundary.
76
90
 
77
91
  The MIR schema defines three ordered `i32` process parameters:
78
92
  `(start_frame, frames, flags)`. `process_frame(offset)` is the checked source of audio-I/O
package/api.md CHANGED
@@ -139,7 +139,8 @@ real-time execution.
139
139
 
140
140
  `writeDelegateBatch` and `writePrintBatch` initialize reusable batch descriptors.
141
141
  `writeExecutionOutput` connects their addresses. Call `resetExecutionOutput` immediately before
142
- every generated init, process, or event entry. After a successful generated call,
142
+ every generated init or process entry. Generated event entries reset after successful input
143
+ preflight instead, so rejected input preserves existing records. After a successful generated call,
143
144
  `readDelegateBatch` or `readPrintBatch` validates the result counters.
144
145
  `decodeDelegateRecords` converts delegate payloads using `metadata.delegates`.
145
146
  `decodePrintRecords` preserves primitive types and source sites; `formatPrintRecords` and
@@ -296,6 +297,17 @@ validateProcessorModule
296
297
  writeDelegateBatch
297
298
  writeExecutionOutput
298
299
  writePrintBatch
300
+ OndaPayloadType
301
+ OndaPayloadField
302
+ OndaPayloadSchema
303
+ OndaPayloadDefault
304
+ OndaPayloadValue
305
+ OndaPayloadSizes
306
+ PayloadPlan
307
+ canonicalF32Number
308
+ EVENT_INPUT_SIZE_BYTES
309
+ PROCESSOR_EXECUTION_INPUT_REJECTED
310
+ writeEventInput
299
311
  <!-- END WEB API onda_processor_abi -->
300
312
 
301
313
  ### `@onda-lang/binaryen-web`
@@ -410,3 +422,21 @@ paramNormalizedToPlain
410
422
  paramPlainToNormalized
411
423
  registerOndaAudioWorklet
412
424
  <!-- END WEB API onda_webaudio -->
425
+
426
+ ### Structured event and delegate values
427
+
428
+ `PayloadPlan` prepares a recursive message schema once. `encode(values)` accepts ordered parameter
429
+ arrays or objects keyed by parameter name; structs are objects containing exactly their declared
430
+ own fields, and arrays/tuples are sequences. Unknown named parameters and excess positional values
431
+ are rejected. Missing event arguments use declared constant defaults.
432
+ Supply `i64` as `bigint`, an exact safe integer, or a decimal string. `decode(bytes)` returns named
433
+ nested values with `bigint` for `i64`. Plans own immutable schema snapshots.
434
+
435
+ `requiredWorkspace(bytes)` preflights packed little-endian input. `sizes(lengths)` reports wire
436
+ and aligned workspace sizes without allocating payload storage. Low-level wasm hosts provision
437
+ both regions and a 16-byte descriptor, then call `writeEventInput` before invoking the event.
438
+ Rejected input returns `PROCESSOR_EXECUTION_INPUT_REJECTED` (2) and leaves processor state usable.
439
+ `OndaAudioProcessor.trigger` performs logical encoding before transferring bytes to the worklet.
440
+ Decoded `f32` leaves use `canonicalF32Number(value)`: the returned JavaScript number has the
441
+ shortest decimal representation that round-trips to the same `f32`, so JSON and controls do not
442
+ expose an irrelevant widened binary tail.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@onda-lang/binaryen-web",
3
- "version": "0.8.3",
3
+ "version": "0.8.5",
4
4
  "type": "module",
5
5
  "description": "Binaryen backend for versioned Onda MIR in browsers and Node.js",
6
6
  "license": "MIT",
@@ -46,7 +46,7 @@
46
46
  "verify-mir": "node ./scripts/verify-mir.mjs"
47
47
  },
48
48
  "dependencies": {
49
- "@onda-lang/processor-abi": "0.8.3",
49
+ "@onda-lang/processor-abi": "0.8.5",
50
50
  "binaryen": "130.0.0"
51
51
  },
52
52
  "publishConfig": {
@@ -1,3 +1,5 @@
1
+ import { PayloadPlan } from "@onda-lang/processor-abi";
2
+ import { prepareEventInput } from "./event-input.js";
1
3
  import binaryen from "binaryen";
2
4
  import {
3
5
  SUPPORTED_MIR_SCHEMA_VERSION,
@@ -17,6 +19,9 @@ import {
17
19
  DELEGATE_BATCH_USED_OFFSET,
18
20
  DELEGATE_BATCH_RECORD_COUNT_OFFSET,
19
21
  DELEGATE_BATCH_OVERFLOW_OFFSET,
22
+ PRINT_BATCH_USED_OFFSET,
23
+ PRINT_BATCH_RECORD_COUNT_OFFSET,
24
+ PRINT_BATCH_OVERFLOW_OFFSET,
20
25
  EXECUTION_OUTPUT_DELEGATE_BATCH_OFFSET,
21
26
  EXECUTION_OUTPUT_PRINT_BATCH_OFFSET,
22
27
  EXECUTION_OUTPUT_SEQUENCE_OFFSET,
@@ -150,6 +155,7 @@ export class MirCompilerCore {
150
155
  for (let index = 0; index < this.module.getNumFunctions(); index += 1) {
151
156
  const func = this.module.getFunctionByIndex(index);
152
157
  const body = binaryen.Function.getBody(func);
158
+ if (!body) continue;
153
159
  // The local-write scan below is part of the safety proof. If Binaryen
154
160
  // adds an expression kind that this backend does not know how to walk,
155
161
  // leave the whole function untouched rather than silently overlooking
@@ -165,7 +171,7 @@ export class MirCompilerCore {
165
171
  this.rewriteExpressionChildren(expression, (child) =>
166
172
  this.rewriteDescriptorLoops(child, func)
167
173
  );
168
- if (binaryen.getExpressionInfo(expression).id !== binaryen.LoopId) {
174
+ if (expressionInfo(expression).id !== binaryen.LoopId) {
169
175
  return expression;
170
176
  }
171
177
 
@@ -174,7 +180,7 @@ export class MirCompilerCore {
174
180
  const definitions = new Map();
175
181
  const writtenLocals = new Set();
176
182
  this.visitExpression(body, (candidate) => {
177
- const info = binaryen.getExpressionInfo(candidate);
183
+ const info = expressionInfo(candidate);
178
184
  if (info.id !== binaryen.LocalSetId) return;
179
185
  writtenLocals.add(info.index);
180
186
  const entries = definitions.get(info.index) ?? [];
@@ -189,7 +195,7 @@ export class MirCompilerCore {
189
195
 
190
196
  const rewriteLoad = (candidate) => {
191
197
  this.rewriteExpressionChildren(candidate, rewriteLoad);
192
- const info = binaryen.getExpressionInfo(candidate);
198
+ const info = expressionInfo(candidate);
193
199
  if (info.id !== binaryen.LoadId || info.isAtomic) return candidate;
194
200
  const candidatePath = controlPaths.get(candidate) ?? [];
195
201
  const localCache = (local) => {
@@ -218,7 +224,7 @@ export class MirCompilerCore {
218
224
  const cache = binaryen._BinaryenFunctionAddVar(func, info.type);
219
225
  this.descriptorLoadsHoisted += 1;
220
226
  const hoistedLoad = this.module.copyExpression(candidate);
221
- const hoistedInfo = binaryen.getExpressionInfo(hoistedLoad);
227
+ const hoistedInfo = expressionInfo(hoistedLoad);
222
228
  binaryen.Load.setPtr(
223
229
  hoistedLoad,
224
230
  this.descriptorPointerForPreheader(
@@ -245,7 +251,7 @@ export class MirCompilerCore {
245
251
  const paths = new Map();
246
252
  const visit = (candidate, path) => {
247
253
  paths.set(candidate, path);
248
- const info = binaryen.getExpressionInfo(candidate);
254
+ const info = expressionInfo(candidate);
249
255
  if (info.id === binaryen.IfId) {
250
256
  visit(info.condition, path);
251
257
  visit(info.ifTrue, [...path, `if:${candidate}:true`]);
@@ -283,7 +289,7 @@ export class MirCompilerCore {
283
289
  controlPaths,
284
290
  candidatePath,
285
291
  ) {
286
- const info = binaryen.getExpressionInfo(expression);
292
+ const info = expressionInfo(expression);
287
293
  if (info.id === binaryen.LocalSetId && info.isTee) {
288
294
  this.cacheDescriptorPointerSideEffects(
289
295
  info.value,
@@ -340,7 +346,7 @@ export class MirCompilerCore {
340
346
  candidatePath,
341
347
  )
342
348
  );
343
- const info = binaryen.getExpressionInfo(expression);
349
+ const info = expressionInfo(expression);
344
350
  if (info.id === binaryen.LocalGetId) {
345
351
  const cache = loopLocalCaches.get(info.index);
346
352
  if (cache && this.descriptorPathDominates(cache.path, candidatePath)) {
@@ -362,7 +368,7 @@ export class MirCompilerCore {
362
368
  return false;
363
369
  }
364
370
  const visit = (candidate) => {
365
- const info = binaryen.getExpressionInfo(candidate);
371
+ const info = expressionInfo(candidate);
366
372
  if (info.id === binaryen.ConstId) return true;
367
373
  if (info.id === binaryen.LocalGetId) return localIsInvariant(info.index);
368
374
  if (info.id === binaryen.GlobalGetId) {
@@ -399,7 +405,7 @@ export class MirCompilerCore {
399
405
  }
400
406
 
401
407
  expressionUsesDescriptorTable(expression, definitions, visitingLocals) {
402
- const info = binaryen.getExpressionInfo(expression);
408
+ const info = expressionInfo(expression);
403
409
  if (info.id === binaryen.GlobalGetId) {
404
410
  return BUFFER_DESCRIPTOR_POINTER_GLOBALS.has(info.name);
405
411
  }
@@ -467,7 +473,7 @@ export class MirCompilerCore {
467
473
  descriptorPointerSideEffects(expression) {
468
474
  const result = [];
469
475
  const visit = (candidate) => {
470
- const info = binaryen.getExpressionInfo(candidate);
476
+ const info = expressionInfo(candidate);
471
477
  if (info.id === binaryen.LocalSetId && info.isTee) {
472
478
  result.push(
473
479
  this.module.local.set(info.index, this.module.copyExpression(info.value)),
@@ -488,7 +494,7 @@ export class MirCompilerCore {
488
494
  }
489
495
 
490
496
  expressionContainsTee(expression) {
491
- const info = binaryen.getExpressionInfo(expression);
497
+ const info = expressionInfo(expression);
492
498
  if (info.id === binaryen.LocalSetId) return info.isTee;
493
499
  if (info.id === binaryen.UnaryId) {
494
500
  return this.expressionContainsTee(info.value);
@@ -516,7 +522,7 @@ export class MirCompilerCore {
516
522
  }
517
523
 
518
524
  rewriteExpressionChildren(expression, rewrite) {
519
- const info = binaryen.getExpressionInfo(expression);
525
+ const info = expressionInfo(expression);
520
526
  const replace = (child, setter) => {
521
527
  if (child) setter(rewrite(child));
522
528
  };
@@ -731,6 +737,14 @@ export class MirCompilerCore {
731
737
  && data.destination.projections.length === 0
732
738
  ) {
733
739
  candidates[functionId][data.destination.base.data] = false;
740
+ } else if (
741
+ kind === "assign"
742
+ && data.value?.kind === "make_slice"
743
+ && data.value.data.source?.kind === "place"
744
+ && data.value.data.source.data.base?.kind === "parameter"
745
+ ) {
746
+ // A view needs the original address even if it is only read through.
747
+ candidates[functionId][data.value.data.source.data.base.data] = false;
734
748
  } else if (kind === "call") {
735
749
  callSites[data.function].push({ caller: functionId, call: data });
736
750
  } else if (kind === "if") {
@@ -1270,8 +1284,10 @@ export class MirCompilerCore {
1270
1284
  );
1271
1285
  } else if (kind === "slice_store") {
1272
1286
  markValueWrite(data?.slice, "slice store");
1273
- } else if (kind === "slice_fill" || kind === "slice_copy") {
1287
+ } else if (kind === "slice_fill") {
1274
1288
  markValueWrite(data?.destination, "slice write");
1289
+ } else if (kind === "slice_copy") {
1290
+ for (const copy of data?.copies ?? []) markValueWrite(copy.destination, "slice write");
1275
1291
  } else if (kind === "call") {
1276
1292
  const callee = summaries[data?.function];
1277
1293
  if (!callee) {
@@ -1396,6 +1412,7 @@ export class MirCompilerCore {
1396
1412
  "slice_load",
1397
1413
  "slice_store",
1398
1414
  "slice_window",
1415
+ "normalize_index",
1399
1416
  ]);
1400
1417
  const scan = (functionId, value) => {
1401
1418
  if (value === null || value === undefined) return;
@@ -1407,15 +1424,16 @@ export class MirCompilerCore {
1407
1424
  if (value.kind === "call" && Number.isInteger(value.data?.function)) {
1408
1425
  callees[functionId].add(value.data.function);
1409
1426
  }
1410
- const fixedDelegatePayloadMayFail = value.kind === "publish_delegate"
1411
- && this.mir.interface.delegates[value.data?.delegate]?.params.some(
1412
- (param) => this.type(param.ty).kind === "array",
1413
- );
1427
+ const delegate = value.kind === "publish_delegate" ? this.mir.interface.delegates[value.data?.delegate] : null;
1428
+ const delegatePayloadMayFail = delegate && (
1429
+ delegate.params.some((param) => this.type(param.ty).kind === "array")
1430
+ || delegate.schema.params.some((param) => param.ty.kind === "slice" && param.ty.element.kind === "struct")
1431
+ );
1414
1432
  const bounds = value.data?.bounds;
1415
1433
  if (
1416
1434
  value.kind === "process_frame"
1417
1435
  || value.kind === "slice_copy"
1418
- || fixedDelegatePayloadMayFail
1436
+ || delegatePayloadMayFail
1419
1437
  || binaryMayFail(functionId, value)
1420
1438
  || (checkedBoundsKinds.has(value.kind) && bounds === "checked")
1421
1439
  || (dynamicBoundsKinds.has(value.kind) && bounds !== "unchecked")
@@ -1449,11 +1467,13 @@ export class MirCompilerCore {
1449
1467
  this.inputLayout = this.layoutPorts(this.mir.interface.inputs);
1450
1468
  this.outputLayout = this.layoutPorts(this.mir.interface.outputs);
1451
1469
  this.controlOutputLayout = this.layoutControlOutputs();
1452
- this.eventLayout = this.mir.interface.events.map((event) =>
1453
- this.layoutEventValues(event.params),
1470
+ this.eventPlans = this.mir.interface.events.map((event) => new PayloadPlan(event.schema));
1471
+ this.delegatePlans = this.mir.interface.delegates.map((event) => new PayloadPlan(event.schema));
1472
+ this.eventLayout = this.mir.interface.events.map((event, index) =>
1473
+ this.layoutEventValues(event.params, this.eventPlans[index]),
1454
1474
  );
1455
- this.delegateLayout = this.mir.interface.delegates.map((delegate) =>
1456
- this.layoutEventValues(delegate.params),
1475
+ this.delegateLayout = this.mir.interface.delegates.map((delegate, index) =>
1476
+ this.layoutEventValues(delegate.params, this.delegatePlans[index]),
1457
1477
  );
1458
1478
  this.requireWasm32Extent(
1459
1479
  this.stateLayout.byteLength,
@@ -1539,6 +1559,7 @@ export class MirCompilerCore {
1539
1559
 
1540
1560
  collectAddressTakenScalarLocals(functionId) {
1541
1561
  const result = new Set();
1562
+ const func = this.mir.functions[functionId];
1542
1563
  const visitBlock = (block) => {
1543
1564
  for (const statement of block.statements) {
1544
1565
  const kind = statement.kind?.kind;
@@ -1558,6 +1579,19 @@ export class MirCompilerCore {
1558
1579
  result.add(argument.data.base.data);
1559
1580
  }
1560
1581
  });
1582
+ } else if (
1583
+ kind === "assign"
1584
+ && data.value?.kind === "make_slice"
1585
+ && data.value.data.source?.kind === "place"
1586
+ && data.value.data.source.data.base?.kind === "local"
1587
+ ) {
1588
+ const source = data.value.data.source.data;
1589
+ if (
1590
+ source.projections.length === 0
1591
+ && this.type(func.locals[source.base.data]?.ty).kind === "scalar"
1592
+ ) {
1593
+ result.add(source.base.data);
1594
+ }
1561
1595
  } else if (kind === "if") {
1562
1596
  visitBlock(data.then_block);
1563
1597
  visitBlock(data.else_block);
@@ -1566,7 +1600,7 @@ export class MirCompilerCore {
1566
1600
  }
1567
1601
  }
1568
1602
  };
1569
- visitBlock(this.mir.functions[functionId].body);
1603
+ visitBlock(func.body);
1570
1604
  return result;
1571
1605
  }
1572
1606
 
@@ -1593,26 +1627,29 @@ export class MirCompilerCore {
1593
1627
  });
1594
1628
  }
1595
1629
 
1596
- layoutEventValues(values) {
1630
+ layoutEventValues(values, plan) {
1631
+ const prefixes = Array(values.length).fill(false);
1632
+ for (const tensor of plan.tensors) prefixes[tensor.parameter] = tensor.lengthPrefix;
1597
1633
  let offset = 0;
1598
1634
  let dynamic = false;
1599
- const result = values.map((value) => {
1635
+ const result = values.map((value, index) => {
1600
1636
  const type = this.type(value.ty);
1601
1637
  if (type.kind === "slice") {
1602
1638
  const entry = {
1603
1639
  offset: dynamic ? null : offset,
1604
1640
  size: null,
1605
1641
  dynamic: true,
1606
- headerSize: 4,
1642
+ headerSize: prefixes[index] ? 4 : 0,
1607
1643
  scalar: type.data.element,
1608
1644
  };
1609
- offset += 4;
1645
+ offset += entry.headerSize;
1610
1646
  dynamic = true;
1611
1647
  return entry;
1612
1648
  }
1613
1649
  const layout = this.typeLayout(value.ty);
1614
1650
  const entry = { ...layout, offset: dynamic ? null : offset, dynamic: false };
1615
1651
  offset += layout.size;
1652
+ if (plan.parameters.some((group) => group.lengthParameter === index)) dynamic = true;
1616
1653
  return entry;
1617
1654
  });
1618
1655
  result.byteLength = dynamic ? null : offset;
@@ -2012,14 +2049,7 @@ export class MirCompilerCore {
2012
2049
  if (kind === "call" && data.results.length > 0) {
2013
2050
  this.requireFunctionId(data.function, "call target");
2014
2051
  const target = this.mir.functions[data.function];
2015
- const aliasesResult = data.args.some((argument, index) =>
2016
- this.parameterPassingMode(data.function, index) !== "value"
2017
- && argument.kind === "place"
2018
- && argument.data.base.kind === "local"
2019
- && argument.data.projections.length === 0
2020
- && this.type(target.params[index].ty).kind === "scalar"
2021
- );
2022
- if (data.results.length === 1 && !aliasesResult) continue;
2052
+ if (data.results.length === 1) continue;
2023
2053
  const scalars = target.results.map((typeId, resultId) =>
2024
2054
  this.requireScalarType(
2025
2055
  typeId,
@@ -2174,13 +2204,16 @@ export class MirCompilerCore {
2174
2204
  }
2175
2205
 
2176
2206
  resetDelegateBatch() {
2177
- const batch = () =>
2178
- this.module.global.get(POINTER_GLOBALS.delegateBatch, binaryen.i32);
2179
- const stores = [
2207
+ return this.resetOutputBatch(POINTER_GLOBALS.delegateBatch, [
2180
2208
  DELEGATE_BATCH_USED_OFFSET,
2181
2209
  DELEGATE_BATCH_RECORD_COUNT_OFFSET,
2182
2210
  DELEGATE_BATCH_OVERFLOW_OFFSET,
2183
- ].map((offset) =>
2211
+ ]);
2212
+ }
2213
+
2214
+ resetOutputBatch(global, offsets) {
2215
+ const batch = () => this.module.global.get(global, binaryen.i32);
2216
+ const stores = offsets.map((offset) =>
2184
2217
  this.module.i32.store(
2185
2218
  offset,
2186
2219
  4,
@@ -2196,6 +2229,23 @@ export class MirCompilerCore {
2196
2229
  ];
2197
2230
  }
2198
2231
 
2232
+ resetExecutionOutput() {
2233
+ const sequence = () =>
2234
+ this.module.global.get(POINTER_GLOBALS.outputSequence, binaryen.i32);
2235
+ return [
2236
+ ...this.resetDelegateBatch(),
2237
+ ...this.resetOutputBatch(POINTER_GLOBALS.printBatch, [
2238
+ PRINT_BATCH_USED_OFFSET,
2239
+ PRINT_BATCH_RECORD_COUNT_OFFSET,
2240
+ PRINT_BATCH_OVERFLOW_OFFSET,
2241
+ ]),
2242
+ this.module.if(
2243
+ this.module.i32.ne(sequence(), this.module.i32.const(0)),
2244
+ this.module.i32.store(0, 4, sequence(), this.module.i32.const(0)),
2245
+ ),
2246
+ ];
2247
+ }
2248
+
2199
2249
  executionOutputBatch(outputLocal, fieldOffset) {
2200
2250
  const output = () => this.module.local.get(outputLocal, binaryen.i32);
2201
2251
  return this.module.if(
@@ -2482,7 +2532,9 @@ export class MirCompilerCore {
2482
2532
  this.fail(`event '${event.name}' has an invalid MIR handler signature`);
2483
2533
  }
2484
2534
  const wrapperName = `$onda.abi.event.${eventId}`;
2535
+ const prepared = prepareEventInput(this, this.eventPlans[eventId]);
2485
2536
  const body = this.module.block(null, [
2537
+ ...prepared.statements,
2486
2538
  this.module.global.set(
2487
2539
  POINTER_GLOBALS.delegateBatch,
2488
2540
  this.executionOutputBatch(7, EXECUTION_OUTPUT_DELEGATE_BATCH_OFFSET),
@@ -2495,10 +2547,11 @@ export class MirCompilerCore {
2495
2547
  POINTER_GLOBALS.outputSequence,
2496
2548
  this.executionOutputSequence(7),
2497
2549
  ),
2550
+ ...this.resetExecutionOutput(),
2498
2551
  ...this.resetRuntimeFailure(event.handler),
2499
2552
  this.module.global.set(
2500
2553
  POINTER_GLOBALS.eventPayload,
2501
- this.module.local.get(0, binaryen.i32),
2554
+ prepared.workspace(),
2502
2555
  ),
2503
2556
  this.module.global.set(
2504
2557
  POINTER_GLOBALS.params,
@@ -2535,10 +2588,17 @@ export class MirCompilerCore {
2535
2588
  wrapperName,
2536
2589
  binaryen.createType(Array.from({ length: 8 }, () => binaryen.i32)),
2537
2590
  binaryen.i32,
2538
- [],
2591
+ prepared.locals,
2539
2592
  body,
2540
2593
  );
2541
2594
  this.module.addFunctionExport(wrapperName, `onda_event_${eventId}`);
2542
2595
  });
2543
2596
  }
2544
2597
  }
2598
+
2599
+ // Operandless control nodes have no accessor table in Binaryen's JS API.
2600
+ function expressionInfo(expression) {
2601
+ const id = binaryen.getExpressionId(expression);
2602
+ if (id === binaryen.NopId || id === binaryen.UnreachableId) return { id };
2603
+ return binaryen.getExpressionInfo(expression);
2604
+ }
@@ -0,0 +1,112 @@
1
+ import binaryen from "binaryen";
2
+ import { PROCESSOR_EXECUTION_INPUT_REJECTED } from "@onda-lang/processor-abi";
3
+
4
+ // Emit preflight separately from transfer so rejection cannot change workspace,
5
+ // state, or existing output records. All generated metadata is per tensor.
6
+ export function prepareEventInput(compiler, plan) {
7
+ const m = compiler.module;
8
+ const locals = [];
9
+ const statements = [];
10
+ const c32 = (value) => m.i32.const(value);
11
+ const c64 = (value) => m.i64.const(BigInt.asIntN(64, BigInt(value)));
12
+ const allocate = (type, value = null) => {
13
+ const index = 8 + locals.length;
14
+ locals.push(type);
15
+ if (value !== null) statements.push(m.local.set(index, value));
16
+ return { get: () => m.local.get(index, type), set: (value) => m.local.set(index, value) };
17
+ };
18
+ const require = (condition) => statements.push(m.if(m.i32.eqz(condition), m.return(c32(PROCESSOR_EXECUTION_INPUT_REJECTED))));
19
+ const wide = (value) => m.i64.extend_u(value);
20
+ const narrow = (value) => m.i32.wrap(value);
21
+ const align = (value, alignment) => m.i64.and(m.i64.add(value, c64(alignment - 1)), c64(-alignment));
22
+ const descriptor = () => m.local.get(0, binaryen.i32);
23
+ const memoryBytes = () => m.i64.shl(wide(m.memory.size()), c64(16));
24
+ require(m.i32.and(m.i32.ne(descriptor(), c32(0)), m.i64.le_u(m.i64.add(wide(descriptor()), c64(16)), memoryBytes())));
25
+ const input = allocate(binaryen.i32, m.i32.load(0, 4, descriptor()));
26
+ const inputBytes = allocate(binaryen.i64, wide(m.i32.load(4, 4, descriptor())));
27
+ const workspace = allocate(binaryen.i32, m.i32.load(8, 4, descriptor()));
28
+ const capacity = allocate(binaryen.i64, wide(m.i32.load(12, 4, descriptor())));
29
+ require(m.i64.le_u(inputBytes.get(), c64(0x7fffffff)));
30
+ require(m.i64.le_u(m.i64.add(wide(input.get()), inputBytes.get()), memoryBytes()));
31
+ require(m.i64.le_u(m.i64.add(wide(workspace.get()), capacity.get()), memoryBytes()));
32
+ require(m.i32.or(m.i64.eqz(inputBytes.get()), m.i32.ne(input.get(), c32(0))));
33
+ const wire = allocate(binaryen.i64, c64(0));
34
+ const prepared = allocate(binaryen.i64, c64(0));
35
+ const transfers = [];
36
+ const retain = (encoding, elements, domain = null) => {
37
+ transfers.push({ encoding, domain,
38
+ source: allocate(binaryen.i32, m.i32.add(input.get(), narrow(wire.get()))),
39
+ target: allocate(binaryen.i32, m.i32.add(workspace.get(), narrow(prepared.get()))),
40
+ elements: allocate(binaryen.i64, elements),
41
+ });
42
+ };
43
+ for (const parameter of plan.parameters) {
44
+ let len;
45
+ if (parameter.dynamic) {
46
+ require(m.i64.le_u(m.i64.add(wire.get(), c64(4)), inputBytes.get()));
47
+ len = allocate(binaryen.i64, wide(m.i32.load(0, 1, m.i32.add(input.get(), narrow(wire.get())))));
48
+ require(m.i64.le_u(len.get(), c64(0x7fffffff)));
49
+ statements.push(prepared.set(align(prepared.get(), 4)));
50
+ retain("i32", c64(1));
51
+ statements.push(wire.set(m.i64.add(wire.get(), c64(4))), prepared.set(m.i64.add(prepared.get(), c64(4))));
52
+ } else {
53
+ len = { get: () => c64(1) };
54
+ }
55
+ for (let index = parameter.start; index < parameter.end; index += 1) {
56
+ const tensor = plan.tensors[index];
57
+ statements.push(prepared.set(align(prepared.get(), tensor.size)));
58
+ retain(tensor.encoding, m.i64.mul(len.get(), c64(tensor.elements)), tensor.domain);
59
+ const transfer = transfers.at(-1);
60
+ require(m.i64.le_u(transfer.elements.get(), c64(Math.floor(0x7fffffff / tensor.size))));
61
+ const bytes = () => m.i64.mul(transfer.elements.get(), c64(tensor.size));
62
+ statements.push(wire.set(m.i64.add(wire.get(), bytes())), prepared.set(m.i64.add(prepared.get(), bytes())));
63
+ require(m.i64.le_u(wire.get(), inputBytes.get()));
64
+ require(m.i64.le_u(wire.get(), c64(0x7fffffff)));
65
+ require(m.i64.le_u(prepared.get(), c64(0x7fffffff)));
66
+ }
67
+ }
68
+ require(m.i64.eq(wire.get(), inputBytes.get()));
69
+ require(m.i64.le_u(prepared.get(), capacity.get()));
70
+ require(m.i32.or(m.i64.eqz(prepared.get()), m.i32.and(m.i32.ne(workspace.get(), c32(0)), m.i32.eqz(m.i32.and(workspace.get(), c32(7))))));
71
+ const index = allocate(binaryen.i32);
72
+ const integer = allocate(binaryen.i64);
73
+ const residue = allocate(binaryen.i64);
74
+ const sizes = { bool: 1, i32: 4, f32: 4, i64: 8, f64: 8 };
75
+ for (let id = 0; id < transfers.length; id += 1) {
76
+ const transfer = transfers[id];
77
+ const { encoding, domain } = transfer;
78
+ const size = sizes[encoding];
79
+ const source = () => m.i32.add(transfer.source.get(), m.i32.mul(index.get(), c32(size)));
80
+ const target = () => m.i32.add(transfer.target.get(), m.i32.mul(index.get(), c32(size)));
81
+ let copy;
82
+ if (domain === null && encoding !== "bool") {
83
+ copy = m.memory.copy(transfer.target.get(), transfer.source.get(), narrow(m.i64.mul(transfer.elements.get(), c64(size))));
84
+ } else {
85
+ const loop = `$input.tensor.${id}`;
86
+ const body = [];
87
+ if (encoding === "bool") {
88
+ body.push(m.i32.store8(0, 1, target(), m.i32.ne(m.i32.load8_u(0, 1, source()), c32(0))));
89
+ } else {
90
+ body.push(integer.set(encoding === "i32" ? m.i64.extend_s(m.i32.load(0, 1, source())) : m.i64.load(0, 1, source())));
91
+ if (!domain.wrap) {
92
+ body.push(integer.set(m.select(m.i64.lt_s(integer.get(), c64(domain.min)), c64(domain.min), integer.get(), binaryen.i64)));
93
+ body.push(integer.set(m.select(m.i64.gt_s(integer.get(), c64(domain.max)), c64(domain.max), integer.get(), binaryen.i64)));
94
+ } else {
95
+ const width = domain.max - domain.min + 1n;
96
+ if (width !== 1n << 64n) {
97
+ const minResidue = (domain.min + (1n << 63n)) % width;
98
+ body.push(residue.set(m.i64.rem_u(m.i64.xor(integer.get(), c64(1n << 63n)), c64(width))));
99
+ body.push(integer.set(m.i64.add(c64(domain.min), m.select(m.i64.ge_u(residue.get(), c64(minResidue)),
100
+ m.i64.sub(residue.get(), c64(minResidue)),
101
+ m.i64.sub(c64(width), m.i64.sub(c64(minResidue), residue.get())), binaryen.i64))));
102
+ }
103
+ }
104
+ body.push(encoding === "i32" ? m.i32.store(0, 4, target(), narrow(integer.get())) : m.i64.store(0, 8, target(), integer.get()));
105
+ }
106
+ body.push(index.set(m.i32.add(index.get(), c32(1))), m.br(loop, m.i64.lt_u(wide(index.get()), transfer.elements.get())));
107
+ copy = m.block(null, [index.set(c32(0)), m.loop(loop, m.block(null, body))]);
108
+ }
109
+ statements.push(m.if(m.i64.ne(transfer.elements.get(), c64(0)), copy));
110
+ }
111
+ return { statements, locals, workspace: workspace.get };
112
+ }
@@ -24,6 +24,14 @@ export class MirCompiler extends MirCompilerLowering {
24
24
  if (type.kind === "slice") {
25
25
  return this.loadSlicePlace(source.data, context);
26
26
  }
27
+ if (type.kind === "scalar") {
28
+ return [
29
+ this.placeAddress(source.data, context),
30
+ this.placeAddress(source.data, context),
31
+ this.module.i32.const(1),
32
+ this.module.i32.const(this.scalarSize(type.data)),
33
+ ];
34
+ }
27
35
  if (type.kind !== "array") {
28
36
  this.fail(`slice place source has unsupported type '${type.kind}'`);
29
37
  }
@@ -536,6 +544,27 @@ export class MirCompiler extends MirCompilerLowering {
536
544
  }
537
545
 
538
546
  compileSliceCopy(statement, data, context) {
547
+ if (!Array.isArray(data.copies)) this.fail("slice copy requires a leaf list");
548
+ if (data.preflight !== "required" && data.preflight !== "proven_unnecessary") {
549
+ this.fail("slice copy requires a valid overlap-preflight mode");
550
+ }
551
+ const groupedPreflight = data.copies.length > 1 && data.preflight === "required";
552
+ const checks = groupedPreflight
553
+ ? data.copies.map((copy) => this.compileSliceCopyLeaf(statement, copy, context, true, false))
554
+ : [];
555
+ return this.module.block(null, [
556
+ ...checks,
557
+ ...data.copies.map((copy) => this.compileSliceCopyLeaf(
558
+ statement,
559
+ copy,
560
+ context,
561
+ false,
562
+ groupedPreflight || data.preflight === "proven_unnecessary",
563
+ )),
564
+ ]);
565
+ }
566
+
567
+ compileSliceCopyLeaf(statement, data, context, checkOnly, overlapSafe) {
539
568
  if (this.sliceAccess(data.destination, context) !== "read_write") {
540
569
  this.fail("slice copy destination is read-only");
541
570
  }
@@ -668,9 +697,10 @@ export class MirCompiler extends MirCompilerLowering {
668
697
  source()[2],
669
698
  ),
670
699
  ),
671
- this.module.if(invalidOverlap(), this.raiseRuntimeFailure(context)),
672
- this.module.local.set(counter, this.module.i32.const(0)),
673
- copy,
700
+ ...(overlapSafe ? [] : [
701
+ this.module.if(invalidOverlap(), this.raiseRuntimeFailure(context)),
702
+ ]),
703
+ ...(checkOnly ? [] : [this.module.local.set(counter, this.module.i32.const(0)), copy]),
674
704
  ]);
675
705
  }
676
706
 
@@ -688,14 +718,7 @@ export class MirCompiler extends MirCompilerLowering {
688
718
  compileValue(value, context) {
689
719
  switch (value.kind) {
690
720
  case "local": {
691
- const scalar = context.localScalars[value.data];
692
- if (!scalar) {
693
- this.fail(`local id ${value.data} is not a scalar or is out of range`);
694
- }
695
- return this.module.local.get(
696
- this.localIndex(value.data, context),
697
- this.wasmType(scalar),
698
- );
721
+ return this.loadLocal(value.data, context);
699
722
  }
700
723
  case "constant":
701
724
  return this.compileConstant(value.data);
@@ -779,11 +802,7 @@ export class MirCompiler extends MirCompilerLowering {
779
802
 
780
803
  loadPlace(place, context) {
781
804
  if (place.base.kind === "local" && place.projections.length === 0) {
782
- const scalar = this.placeScalarType(place, context);
783
- return this.module.local.get(
784
- this.localIndex(place.base.data, context),
785
- this.wasmType(scalar),
786
- );
805
+ return this.loadLocal(place.base.data, context);
787
806
  }
788
807
  if (place.base.kind === "parameter" && place.projections.length === 0) {
789
808
  const scalar = this.placeScalarType(place, context);
@@ -805,7 +824,7 @@ export class MirCompiler extends MirCompilerLowering {
805
824
 
806
825
  storePlace(place, value, scalar, context) {
807
826
  if (place.base.kind === "local" && place.projections.length === 0) {
808
- return this.module.local.set(this.localIndex(place.base.data, context), value);
827
+ return this.storeLocal(place.base.data, value, context);
809
828
  }
810
829
  if (place.base.kind === "parameter" && place.projections.length === 0) {
811
830
  const layout = context.paramLayouts[place.base.data];
@@ -821,6 +840,28 @@ export class MirCompiler extends MirCompilerLowering {
821
840
  return this.storeScalar(scalar, this.placeAddress(place, context), value);
822
841
  }
823
842
 
843
+ loadLocal(localId, context) {
844
+ const scalar = context.localScalars[localId];
845
+ if (!scalar) {
846
+ this.fail(`local id ${localId} is not a scalar or is out of range`);
847
+ }
848
+ const layout = this.localScalarRefLayout[context.functionId]?.[localId];
849
+ return layout
850
+ ? this.loadScalar(scalar, this.module.i32.const(layout.address))
851
+ : this.module.local.get(this.localIndex(localId, context), this.wasmType(scalar));
852
+ }
853
+
854
+ storeLocal(localId, value, context) {
855
+ const scalar = context.localScalars[localId];
856
+ if (!scalar) {
857
+ this.fail(`local id ${localId} is not a scalar or is out of range`);
858
+ }
859
+ const layout = this.localScalarRefLayout[context.functionId]?.[localId];
860
+ return layout
861
+ ? this.storeScalar(scalar, this.module.i32.const(layout.address), value)
862
+ : this.module.local.set(this.localIndex(localId, context), value);
863
+ }
864
+
824
865
  placeAddress(place, context) {
825
866
  let typeId;
826
867
  let address;
@@ -1718,6 +1759,7 @@ export class MirCompiler extends MirCompilerLowering {
1718
1759
  len: array.len,
1719
1760
  })),
1720
1761
  events: this.mir.interface.events.map((event, eventId) => ({
1762
+ schema: event.schema,
1721
1763
  name: event.name,
1722
1764
  export: `onda_event_${eventId}`,
1723
1765
  payload_size_bytes: this.eventLayout[eventId].byteLength,
@@ -1741,6 +1783,7 @@ export class MirCompiler extends MirCompilerLowering {
1741
1783
  }),
1742
1784
  })),
1743
1785
  delegates: this.mir.interface.delegates.map((delegate, delegateId) => ({
1786
+ schema: delegate.schema,
1744
1787
  index: delegateId,
1745
1788
  name: delegate.name,
1746
1789
  payload_size_bytes: this.delegateLayout[delegateId].byteLength,
@@ -167,7 +167,7 @@ export class MirCompilerLowering extends MirCompilerCore {
167
167
  argument.data.index,
168
168
  argument.data.bounds,
169
169
  context,
170
- target.params[index].mode === "read_write_reference",
170
+ ["read_write_reference", "result_reference"].includes(target.params[index].mode),
171
171
  ),
172
172
  ];
173
173
  }
@@ -201,7 +201,7 @@ export class MirCompilerLowering extends MirCompilerCore {
201
201
  argument.data,
202
202
  parameterType,
203
203
  context,
204
- target.params[index].mode === "read_write_reference",
204
+ ["read_write_reference", "result_reference"].includes(target.params[index].mode),
205
205
  ),
206
206
  ];
207
207
  }
@@ -235,80 +235,11 @@ export class MirCompilerLowering extends MirCompilerCore {
235
235
  );
236
236
  const resultType = this.wasmResultType(resultScalars);
237
237
  const call = this.module.call(this.functionNames[data.function], args, resultType);
238
- const localReferenceSync = data.args.flatMap((argument, index) => {
239
- const parameter = target.params[index];
240
- if (
241
- this.parameterPassingMode(data.function, index) === "value"
242
- || argument.kind !== "place"
243
- || argument.data.base.kind !== "local"
244
- || argument.data.projections.length !== 0
245
- ) {
246
- return [];
247
- }
248
- const layout =
249
- this.localScalarRefLayout[context.functionId]?.[argument.data.base.data];
250
- if (!layout) return [];
251
- return [{
252
- localId: argument.data.base.data,
253
- address: layout.address,
254
- scalar: layout.scalar,
255
- writeBack: parameter.mode === "read_write_reference",
256
- }];
257
- });
258
- const beforeCall = localReferenceSync.map((sync) =>
259
- this.storeScalar(
260
- sync.scalar,
261
- this.module.i32.const(sync.address),
262
- this.module.local.get(
263
- this.localIndex(sync.localId, context),
264
- this.wasmType(sync.scalar),
265
- ),
266
- ),
267
- );
268
- const afterCall = localReferenceSync
269
- .filter((sync) => sync.writeBack)
270
- .map((sync) =>
271
- this.module.local.set(
272
- this.localIndex(sync.localId, context),
273
- this.loadScalar(sync.scalar, this.module.i32.const(sync.address)),
274
- ),
275
- );
276
- const resultSpill = context.callResultLocals.get(data);
277
- if (localReferenceSync.length > 0 && data.results.length > 0) {
278
- if (!resultSpill) {
279
- this.fail(`internal result spill is missing for call to '${target.name}'`);
280
- }
281
- const spilledValue = () =>
282
- this.module.local.get(resultSpill.index, resultSpill.type);
283
- const assignResults = data.results.length === 1
284
- ? [
285
- this.module.local.set(
286
- this.localIndex(data.results[0], context),
287
- spilledValue(),
288
- ),
289
- ]
290
- : data.results.map((localId, index) =>
291
- this.module.local.set(
292
- this.localIndex(localId, context),
293
- this.module.tuple.extract(spilledValue(), index),
294
- ),
295
- );
296
- return this.module.block(null, [
297
- ...beforeCall,
298
- this.module.local.set(resultSpill.index, call),
299
- ...afterCall,
300
- ...assignResults,
301
- ...this.propagateRuntimeFailure(data.function, context),
302
- ]);
303
- }
304
238
  let compiledCall;
305
239
  if (data.results.length === 0) {
306
240
  compiledCall = call;
307
241
  } else if (data.results.length === 1) {
308
- compiledCall = this.module.local.set(
309
- this.localIndex(data.results[0], context),
310
- call,
311
- );
242
+ compiledCall = this.storeLocal(data.results[0], call, context);
312
243
  } else {
313
244
  const tupleLocal = context.callResultLocals.get(data);
314
245
  if (!tupleLocal) {
@@ -319,25 +250,18 @@ export class MirCompilerLowering extends MirCompilerCore {
319
250
  compiledCall = this.module.block(null, [
320
251
  this.module.local.set(tupleLocal.index, call),
321
252
  ...data.results.map((localId, index) =>
322
- this.module.local.set(
323
- this.localIndex(localId, context),
253
+ this.storeLocal(
254
+ localId,
324
255
  this.module.tuple.extract(tupleValue(), index),
256
+ context,
325
257
  ),
326
258
  ),
327
259
  ]);
328
260
  }
329
- if (localReferenceSync.length === 0) {
330
- const propagation = this.propagateRuntimeFailure(data.function, context);
331
- return propagation.length === 0
332
- ? compiledCall
333
- : this.module.block(null, [compiledCall, ...propagation]);
334
- }
335
- return this.module.block(null, [
336
- ...beforeCall,
337
- compiledCall,
338
- ...afterCall,
339
- ...this.propagateRuntimeFailure(data.function, context),
340
- ]);
261
+ const propagation = this.propagateRuntimeFailure(data.function, context);
262
+ return propagation.length === 0
263
+ ? compiledCall
264
+ : this.module.block(null, [compiledCall, ...propagation]);
341
265
  }
342
266
 
343
267
  compilePublishDelegate(data, context) {
@@ -379,7 +303,19 @@ export class MirCompilerLowering extends MirCompilerCore {
379
303
  const tooLarge = () => this.module.local.get(oversized, binaryen.i32);
380
304
  const batch = () =>
381
305
  this.module.global.get(POINTER_GLOBALS.delegateBatch, binaryen.i32);
306
+ const plan = this.delegatePlans[data.delegate];
382
307
  const validationStatements = [];
308
+ for (const group of plan.parameters) {
309
+ if (group.lengthParameter === null) continue;
310
+ const length = () => this.compileValue(data.args[group.lengthParameter].data, context);
311
+ validationStatements.push(this.module.if(this.module.i32.lt_s(length(), this.module.i32.const(0)), this.raiseRuntimeFailure(context)));
312
+ for (let index = group.start; index < group.end; index += 1) {
313
+ const tensor = plan.tensors[index];
314
+ const actual = () => this.compileSliceValue(data.args[tensor.parameter].data, context)[2];
315
+ const expected = () => this.module.i64.mul(this.module.i64.extend_u(length()), this.module.i64.const(tensor.elements));
316
+ validationStatements.push(this.module.if(this.module.i64.ne(this.module.i64.extend_u(actual()), expected()), this.raiseRuntimeFailure(context)));
317
+ }
318
+ }
383
319
  const collectionStatements = [
384
320
  this.module.local.set(
385
321
  payloadBytes,
@@ -791,7 +727,7 @@ export class MirCompilerLowering extends MirCompilerCore {
791
727
  const count = type.kind === "array"
792
728
  ? () => this.module.i32.const(type.data.len)
793
729
  : () => slice()[2];
794
- if (type.kind === "slice") {
730
+ if (type.kind === "slice" && this.delegateLayout[delegateId][paramId].headerSize !== 0) {
795
731
  statements.push(
796
732
  this.module.i32.store(0, 1, cursor(), count()),
797
733
  this.module.local.set(
@@ -1035,6 +971,13 @@ export class MirCompilerLowering extends MirCompilerCore {
1035
971
  return this.module.global.get(INIT_ALL_GLOBAL, binaryen.i32);
1036
972
  case "process_frame":
1037
973
  return this.compileProcessFrame(data, context);
974
+ case "normalize_index":
975
+ return this.compileDynamicBoundedIndex(
976
+ () => this.compileValue(data.index, context),
977
+ () => this.compileValue(data.length, context),
978
+ data.bounds,
979
+ context,
980
+ );
1038
981
  case "input_load":
1039
982
  return this.compileInputLoad(data, context);
1040
983
  case "output_load":
@@ -2126,16 +2069,9 @@ export class MirCompilerLowering extends MirCompilerCore {
2126
2069
  if (!type || type.kind !== "slice") {
2127
2070
  this.fail(`event parameter id ${place.base.data} is not a slice`);
2128
2071
  }
2129
- const header = () =>
2130
- this.compileEventParamAddress(context.eventId, place.base.data);
2131
- const address = () =>
2132
- this.module.i32.add(header(), this.module.i32.const(4));
2133
- return [
2134
- address(),
2135
- address(),
2136
- this.module.i32.load(0, 4, header()),
2137
- this.module.i32.const(this.scalarSize(type.data.element)),
2138
- ];
2072
+ const view = this.compileEventParamView(context.eventId, place.base.data);
2073
+ return [view.address(), view.address(), view.length(),
2074
+ this.module.i32.const(this.scalarSize(type.data.element))];
2139
2075
  } else {
2140
2076
  this.fail(`slice place base '${place.base.kind}' is not supported yet`);
2141
2077
  }
@@ -2147,44 +2083,40 @@ export class MirCompilerLowering extends MirCompilerCore {
2147
2083
  );
2148
2084
  }
2149
2085
 
2086
+ alignEventAddress(address, alignment) {
2087
+ return this.module.i32.and(
2088
+ this.module.i32.add(address, this.module.i32.const(alignment - 1)),
2089
+ this.module.i32.const(-alignment));
2090
+ }
2091
+
2150
2092
  compileEventParamAddress(eventId, paramId) {
2151
- const event = this.mir.interface.events[eventId];
2152
- if (!event || !Number.isInteger(paramId) || paramId < 0 || paramId >= event.params.length) {
2093
+ return this.compileEventParamView(eventId, paramId).address();
2094
+ }
2095
+
2096
+ compileEventParamView(eventId, paramId) {
2097
+ const plan = this.eventPlans[eventId];
2098
+ if (!plan || !Number.isInteger(paramId) || paramId < 0 || paramId >= plan.abiParameterCount) {
2153
2099
  this.fail(`event parameter id ${paramId} is invalid for event ${eventId}`);
2154
2100
  }
2155
- let offset = () => this.module.i32.const(0);
2156
- for (let index = 0; index < paramId; index += 1) {
2157
- const previous = offset;
2158
- const type = this.type(event.params[index].ty);
2159
- if (type.kind === "slice") {
2160
- const elementSize = this.scalarSize(type.data.element);
2161
- offset = () =>
2162
- this.module.i32.add(
2163
- previous(),
2164
- this.module.i32.add(
2165
- this.module.i32.const(4),
2166
- this.module.i32.mul(
2167
- this.module.i32.load(
2168
- 0,
2169
- 4,
2170
- this.module.i32.add(
2171
- this.module.global.get(POINTER_GLOBALS.eventPayload, binaryen.i32),
2172
- previous(),
2173
- ),
2174
- ),
2175
- this.module.i32.const(elementSize),
2176
- ),
2177
- ),
2178
- );
2179
- } else {
2180
- const size = this.typeLayout(event.params[index].ty).size;
2181
- offset = () => this.module.i32.add(previous(), this.module.i32.const(size));
2101
+ let address = () => this.module.global.get(POINTER_GLOBALS.eventPayload, binaryen.i32);
2102
+ for (const group of plan.parameters) {
2103
+ let length = () => this.module.i32.const(1);
2104
+ if (group.dynamic) {
2105
+ const previous = address;
2106
+ const header = () => this.alignEventAddress(previous(), 4);
2107
+ if (group.lengthParameter === paramId) return { address: header };
2108
+ length = () => this.module.i32.load(0, 4, header());
2109
+ address = () => this.module.i32.add(header(), this.module.i32.const(4));
2110
+ }
2111
+ for (let index = group.start; index < group.end; index += 1) {
2112
+ const tensor = plan.tensors[index];
2113
+ const previous = address;
2114
+ const start = () => this.alignEventAddress(previous(), tensor.size);
2115
+ const elements = () => this.module.i32.mul(length(), this.module.i32.const(tensor.elements));
2116
+ if (tensor.parameter === paramId) return { address: start, length: elements };
2117
+ address = () => this.module.i32.add(start(), this.module.i32.mul(elements(), this.module.i32.const(tensor.size)));
2182
2118
  }
2183
2119
  }
2184
- return this.module.i32.add(
2185
- this.module.global.get(POINTER_GLOBALS.eventPayload, binaryen.i32),
2186
- offset(),
2187
- );
2188
2120
  }
2189
2121
 
2190
2122
  storeSlicePlace(place, components, context) {
package/src/constants.js CHANGED
@@ -1,2 +1,2 @@
1
1
  // Synchronized from format-versions.json; do not edit this copy directly.
2
- export const SUPPORTED_MIR_SCHEMA_VERSION = 6;
2
+ export const SUPPORTED_MIR_SCHEMA_VERSION = 7;