@yabgu_gm/tensionscript 0.12.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3084,6 +3084,31 @@ declare module "types:tensionscript/src/resolver" {
3084
3084
  * collection wants `Array<T>`, and letting `T[N]` hold references would make
3085
3085
  * `@unmanaged` records carry GC edges they cannot describe. Refused by name.
3086
3086
  */
3087
+ /**
3088
+ * Turns on `Feature.MultiValue` the first time a value-form `[T * N]` return
3089
+ * type is resolved.
3090
+ *
3091
+ * **At resolution, not at emission.** The module's feature flags are computed
3092
+ * once, in `Compiler`'s constructor (`module.setFeatures`), and a return is
3093
+ * emitted long after that — so this sets the option *and* re-sets the module's
3094
+ * flags, which `setFeatures` supports (`module.ts`). Measuring that
3095
+ * re-settability is what this hook rests on: with a write-once flags word this
3096
+ * would have needed a deferred second pass.
3097
+ *
3098
+ * Policy is **auto-enable** rather than a required flag: a consumer who writes
3099
+ * `function make(): [T * N]` should not have to know that the emitter lowers it
3100
+ * to multivalue results. The trade is that the module's declared feature set
3101
+ * depends on its source, which is exactly the contract `--exportRuntime`
3102
+ * already sets. A module that never returns one never gets the flag.
3103
+ *
3104
+ * Idempotent: `features` is a bitmask, and re-setting the same flags is a
3105
+ * no-op for binaryen.
3106
+ */
3107
+ private enableMultiValueForArrayReturn;
3108
+ /** Whether `type` is a fixed array in its **value** form — N inline elements
3109
+ * with no address of their own — as opposed to the `@unmanaged` view (a
3110
+ * pointer) or the `@managed` heap form (Landing 5c). */
3111
+ private isValueFormFixedArray;
3087
3112
  private resolveFixedArrayType;
3088
3113
  /**
3089
3114
  * Resolves an {@link UnmanagedArrayTypeNode} to a
@@ -3730,7 +3755,7 @@ declare module "types:tensionscript/src/program" {
3730
3755
  import { Type, Signature } from "types:tensionscript/src/types";
3731
3756
  import { Token } from "types:tensionscript/src/tokenizer";
3732
3757
  import { Node, Source, DecoratorNode, DecoratorKind, TypeParameterNode, TypeNode, NamedTypeNode, FunctionTypeNode, ArrowKind, Expression, IdentifierExpression, Statement, ClassDeclaration, DeclarationStatement, EnumDeclaration, EnumValueDeclaration, FieldDeclaration, FunctionDeclaration, InterfaceDeclaration, NamespaceDeclaration, TypeDeclaration, VariableDeclaration, VariableLikeDeclarationStatement } from "types:tensionscript/src/ast";
3733
- import { Module, ExpressionRef, FunctionRef, MemorySegment } from "types:tensionscript/src/module";
3758
+ import { Module, ExpressionRef, FunctionRef, MemorySegment, TypeRef } from "types:tensionscript/src/module";
3734
3759
  import { Resolver } from "types:tensionscript/src/resolver";
3735
3760
  import { Flow } from "types:tensionscript/src/flow";
3736
3761
  import { Parser } from "types:tensionscript/src/parser";
@@ -4514,6 +4539,29 @@ declare module "types:tensionscript/src/program" {
4514
4539
  * therefore cannot alias.
4515
4540
  */
4516
4541
  fieldLocals: Map<string, Local> | null;
4542
+ /**
4543
+ * The WASM slot type for this local, when it is **not** what {@link type}
4544
+ * says it is.
4545
+ *
4546
+ * `type` answers "what does the source see" — a record, so `p.field` resolves;
4547
+ * an array, so `arr[i]` resolves. The slot is a different question, and for
4548
+ * most locals the two agree. Three cases where they do not:
4549
+ *
4550
+ * - **view local** (`isViewLocal`) — the slot is the pointer; handled below by
4551
+ * substituting `usizeType`, because a pointer *is* a type.
4552
+ * - **multivalue tuple** — the slot is the `TypeRef` binaryen makes for a
4553
+ * multi-result signature. That has **no `Type` at all**: `createType(refs)`
4554
+ * answers a `TypeRef` the type system cannot describe. Hence an override
4555
+ * rather than a substitution — this is the one local whose slot cannot be
4556
+ * named by a `Type`.
4557
+ *
4558
+ * {@link TypeRef.None} for every other local, so the ordinary case costs
4559
+ * nothing — the same reasoning as {@link fieldLocals}. A sentinel rather than
4560
+ * `| null` because `TypeRef` is an integer type and cannot be nullable here
4561
+ * (measured: `AS204: Type 'TypeRef' cannot be nullable` when the self-hosted
4562
+ * compiler parsed this declaration).
4563
+ */
4564
+ typeRefOverride: TypeRef;
4517
4565
  /**
4518
4566
  * Whether this local is a **view parameter**: `a: @unmanaged T` where `T` is
4519
4567
  * an inline type.
@@ -4669,6 +4717,23 @@ declare module "types:tensionscript/src/program" {
4669
4717
  * one structure regardless of where the leaves' storage came from.
4670
4718
  */
4671
4719
  bindSroaParameterLeaves(type: Type, path: string, into: Map<string, Local>, localIndex: number, flow: Flow): BindResult;
4720
+ /**
4721
+ * Binds a value-form `[T * N]` parameter's **leaves** to the WASM parameters
4722
+ * that carry them.
4723
+ *
4724
+ * The array sibling of {@link bindSroaParameterLeaves}, and the same tree
4725
+ * shape `fillSroaArrayLocals` builds for a local: the map is keyed `"0"`,
4726
+ * `"1"`, ... and a record element is a placeholder carrying its field leaves.
4727
+ * What differs is where the leaves' storage comes from — incoming parameters
4728
+ * here, fresh locals there.
4729
+ *
4730
+ * Element-major, matching `Signature.leafTypesOf` and the caller's operand
4731
+ * order. A parameter is a **value** for the callee's whole body: nothing is
4732
+ * written back, so a store to `arr[0].x` is invisible to the caller. That is
4733
+ * the copy semantics the representation is for, and it costs nothing extra —
4734
+ * the leaves are separate slots precisely because the value has no address.
4735
+ */
4736
+ bindSroaArrayParameterLeaves(type: Type, path: string, into: Map<string, Local>, localIndex: number, flow: Flow): BindResult;
4672
4737
  /** Constructs a new concrete function. */
4673
4738
  constructor(
4674
4739
  /** Name incl. type parameters, i.e. `foo<i32>`. */
@@ -4681,8 +4746,23 @@ declare module "types:tensionscript/src/program" {
4681
4746
  signature: Signature, // pre-resolved
4682
4747
  /** Contextual type arguments inherited from its parent class, if any. */
4683
4748
  contextualTypeArguments?: Map<string, Type> | null);
4684
- /** Gets the types of additional locals that are not parameters. */
4685
- getNonParameterLocalTypes(): Type[];
4749
+ /**
4750
+ * The **WASM slot types** of the additional locals that are not parameters.
4751
+ *
4752
+ * Named for the refs rather than the types because that is what it now
4753
+ * answers: most slots are `local.type.toRef()`, but a multivalue tuple's slot
4754
+ * is a `TypeRef` with no `Type` behind it ({@link Local.typeRefOverride}), and
4755
+ * a view local's slot is the pointer rather than the record it names. Callers
4756
+ * feed this straight to `Module#addFunction`'s `varTypes`, which is a
4757
+ * `TypeRef[]` — so the conversion belongs here, where the slot is decided,
4758
+ * rather than at each of them.
4759
+ *
4760
+ * Renamed from `getNonParameterLocalTypes` when the tuple override landed:
4761
+ * four call sites all wrapped the old answer in `typesToRefs`, and renaming
4762
+ * means a caller that was missed fails to compile instead of silently
4763
+ * declaring a slot of the wrong type.
4764
+ */
4765
+ getNonParameterLocalTypeRefs(): TypeRef[];
4686
4766
  /** Gets the name of the parameter at the specified index. */
4687
4767
  getParameterName(index: number): string;
4688
4768
  /** Creates a stub for use with this function, i.e. for varargs or override calls. */
@@ -5080,6 +5160,23 @@ declare module "types:tensionscript/src/types" {
5080
5160
  fixedElementType: Type | null;
5081
5161
  /** Element count of a {@link TypeKind.FixedArray}, else `0`. */
5082
5162
  fixedLength: number;
5163
+ /**
5164
+ * Who owns a {@link TypeKind.FixedArray}'s storage — the second axis of the
5165
+ * kind, alongside the element and the length.
5166
+ *
5167
+ * The memory model was already on the AST (`TypeNode.memoryModel`) and was
5168
+ * simply dropped before Landing 5a.5: `Type.fixedArray` interned one object
5169
+ * per `(element, length)`, so `[u32 * 4]`, `@unmanaged [u32 * 4]`,
5170
+ * `@managed [u32 * 4]` and `@inline [u32 * 4]` were **the same Type**, and
5171
+ * the prefix was decorative — measured, all four emitted identical code.
5172
+ *
5173
+ * The two forms are not the same thing. `[u32 * 4]` is 16 bytes of inline
5174
+ * elements with no address of its own; `@unmanaged [u32 * 4]` is a pointer to
5175
+ * four elements, i.e. 4 bytes. Part of {@link equals} for the same reason
5176
+ * {@link dynamicMemoryModel} is: interning them together would make the two
5177
+ * spellings the same object, and no downstream test could tell them apart.
5178
+ */
5179
+ fixedMemoryModel: MemoryModelCode;
5083
5180
  /**
5084
5181
  * Element type of a {@link TypeKind.UnmanagedArray}, else `null`.
5085
5182
  *
@@ -5103,12 +5200,16 @@ declare module "types:tensionscript/src/types" {
5103
5200
  */
5104
5201
  dynamicMemoryModel: MemoryModelCode;
5105
5202
  /**
5106
- * Alignment (log2) of a {@link TypeKind.FixedArray}: its element's.
5203
+ * Alignment (log2) of a {@link TypeKind.FixedArray}.
5204
+ *
5205
+ * For the **value** form this is the element's. `alignLog2` cannot derive
5206
+ * that from `byteSize` -- a 24-byte `f32[6]` would report 16-byte alignment
5207
+ * (`31 - clz(24)` = 4), and a 96-byte `f32[24]` would report 64. An array is
5208
+ * aligned as its element is, no matter how long it is, so the value is carried
5209
+ * rather than computed.
5107
5210
  *
5108
- * `alignLog2` cannot derive this from `byteSize` -- a 24-byte `f32[6]` would
5109
- * report 16-byte alignment (`31 - clz(24)` = 4), and a 96-byte `f32[24]` would
5110
- * report 64. An array is aligned as its element is, no matter how long it is,
5111
- * so the value is carried rather than computed.
5211
+ * For the **view** form it is the *pointer's*, because that is what the value
5212
+ * is: the extent says nothing about how the address is aligned.
5112
5213
  */
5113
5214
  private fixedAlignLog2;
5114
5215
  /** Respective non-nullable type, if nullable. */
@@ -5184,6 +5285,34 @@ declare module "types:tensionscript/src/types" {
5184
5285
  get isManaged(): boolean;
5185
5286
  /** Tests if this is a class type explicitly annotated as unmanaged. */
5186
5287
  get isUnmanaged(): boolean;
5288
+ /**
5289
+ * This type's extent in bytes when it is stored **inline**, rather than by
5290
+ * reference.
5291
+ *
5292
+ * For a scalar the two are the same number, and for an ordinary class neither
5293
+ * is what an inline array wants -- a class element is stored as its 4-byte
5294
+ * reference, so `byteSize` is right there. The one case where `byteSize` is
5295
+ * **wrong** is a C-layout record (`@unmanaged` / `@managed struct`, and
5296
+ * `@inline struct`, which the parser also flags `@unmanaged`): there
5297
+ * `byteSize` is the reference width (4) while the bytes an inline element
5298
+ * actually occupies are the record's layout size, `Class#nextMemoryOffset`.
5299
+ *
5300
+ * That is the same pair `builtin_sizeof` distinguishes
5301
+ * (`builtins.ts`, the `Unmanaged | ManagedStruct` branch), and it is why
5302
+ * `sizeof<Props>()` answered 16 while `sizeof<[Props * 4]>()` answered 16
5303
+ * instead of 64: the array's size was built from the reference width.
5304
+ */
5305
+ get inlineExtentBytes(): number;
5306
+ /**
5307
+ * This type's alignment as a log2 when it is stored inline.
5308
+ *
5309
+ * A record's alignment is the strongest of its fields', accumulated while the
5310
+ * resolver lays it out (`Class#alignLog2`), and **not** `Type#alignLog2` —
5311
+ * which reads the class's 4-byte reference size and would report 2 for every
5312
+ * record, including one aligned to 8. The same distinction `builtin_alignof`
5313
+ * makes, for the same reason.
5314
+ */
5315
+ get inlineAlignLog2(): number;
5187
5316
  get isMemory(): boolean;
5188
5317
  /** Gets the corresponding non-nullable type. */
5189
5318
  get nonNullableType(): Type;
@@ -5258,19 +5387,39 @@ declare module "types:tensionscript/src/types" {
5258
5387
  /** A 32-bit float. */
5259
5388
  static readonly f32: Type;
5260
5389
  /** A 64-bit float. */
5261
- /** Interned fixed-array types, keyed by element type and length. */
5390
+ /** Interned fixed-array types, keyed by model, element type and length. */
5262
5391
  private static _fixedArrays;
5263
5392
  /**
5264
- * Gets the {@link TypeKind.FixedArray} of `elementType` repeated `length` times.
5393
+ * Gets the {@link TypeKind.FixedArray} of `elementType` repeated `length`
5394
+ * times, in the storage named by `memoryModel`.
5265
5395
  *
5266
- * Interned: the same element and length always yield the same `Type`, so
5267
- * `offsetof`, `alignof`, `sizeof` and field lookup can compare by identity the
5268
- * way they do for every other type. Size is the element's byte size times the
5269
- * length, and the alignment is the element's -- carried in
5270
- * {@link fixedAlignLog2} rather than derived from the total, because a total
5271
- * is not a power of two for the lengths records actually have (`f32[6]`).
5396
+ * Interned: the same `(model, element, length)` always yields the same `Type`,
5397
+ * so `offsetof`, `alignof`, `sizeof` and field lookup can compare by identity
5398
+ * the way they do for every other type.
5399
+ *
5400
+ * **The model is part of the identity**, and that is the point of Landing
5401
+ * 5a.5. Before it, this function had one axis (element, length) and the memory
5402
+ * model was dropped, so `[u32 * 4]` and `@unmanaged [u32 * 4]` were the same
5403
+ * Type object — measured: both compiled, both `sizeof` 16, and all four
5404
+ * spellings (`[T * N]`, `@unmanaged [T * N]`, `@managed [T * N]`,
5405
+ * `@inline [T * N]`) emitted byte-identical code. A prefix that changes
5406
+ * nothing is worse than one that is refused, because it reads as if it means
5407
+ * something.
5408
+ *
5409
+ * The two honourable forms differ in both size and alignment:
5410
+ *
5411
+ * value (`Any` / `Inline`) — inline elements: `elementSize * length` bytes,
5412
+ * aligned as the element is
5413
+ * view (`Unmanaged`) — one address: `pointerSize` bits, aligned as a
5414
+ * pointer is
5415
+ * heap (`Managed`) — one GC reference, same shape as the view; the
5416
+ * form itself is refused until Landing 5c, but
5417
+ * the Type can be built so that `sizeof` answers
5418
+ * the truth before the refusal fires
5419
+ *
5420
+ * `pointerSize` is in **bits**, matching `Type.size`.
5272
5421
  */
5273
- static fixedArray(elementType: Type, length: number): Type;
5422
+ static fixedArray(elementType: Type, length: number, memoryModel: MemoryModelCode, pointerSize: number): Type;
5274
5423
  /** Gets the element type of a {@link TypeKind.FixedArray}. */
5275
5424
  get fixedArrayElementType(): Type;
5276
5425
  /** Interned unmanaged-array types, keyed by element type and pointer width. */
@@ -11073,6 +11222,42 @@ declare module "types:tensionscript/src/compiler" {
11073
11222
  addDebugLocation(expr: ExpressionRef, range: Range): void;
11074
11223
  /** Checks whether a particular function signature is supported. */
11075
11224
  checkSignatureSupported(signature: Signature, reportNode: FunctionTypeNode): boolean;
11225
+ /**
11226
+ * The `[T * N]` half of signature support, kept separate so that a refusal
11227
+ * can **stop** the function rather than merely be reported.
11228
+ *
11229
+ * `checkSignatureSupported` reports and compilation carries on — the right
11230
+ * shape for a feature gate, whose codegen path can still produce a module.
11231
+ * Not for this one: a value-form `[T * N]` parameter or return has no slot, so
11232
+ * continuing reaches `Signature#paramRefs` / `#resultRefs`, which call
11233
+ * `toRef`, which asserts for the value form by design. Measured before this
11234
+ * split: `export function f(a: [u32 * 4]): u32` and
11235
+ * `export function f(p: usize): [u32 * 4]` both crashed the compiler inside
11236
+ * `toRef` instead of reporting.
11237
+ */
11238
+ private checkFixedArrayStorageInSignature;
11239
+ /**
11240
+ * Refuses a `[T * N]` that has no storage in the position it was written in.
11241
+ *
11242
+ * Landing 5a.5 made the memory model part of the Type, which splits the kind
11243
+ * into three: the **view** (`@unmanaged [T * N]`, one address — works
11244
+ * everywhere `@unmanaged T` works), the **heap** form (`@managed [T * N]`,
11245
+ * Landing 5c) and the **value** form (`[T * N]`, `u32[N]`, `@inline [T * N]`
11246
+ * — N inline elements, no address of its own).
11247
+ *
11248
+ * The value form exists and is laid out correctly: it is a record field's
11249
+ * type, `sizeof` counts N × sizeof(T), and Landing 1's fixtures assert all of
11250
+ * that. What it does not have is a **slot**. `toRef` asserts for it by design,
11251
+ * so every position that needs a WASM local, parameter or result must be
11252
+ * refused *before* that assert is reached — otherwise the compiler crashes
11253
+ * where the answer is a diagnostic. Landing 5b gives the form inline storage
11254
+ * (stack slot, copy at the ABI, sret) and these refusals come out.
11255
+ *
11256
+ * This mirrors `Program.checkInlineStructValue`, which refuses the same class
11257
+ * of position for the same reason (a value with no address where one is
11258
+ * needed). `position` names the site so the message says which case was hit.
11259
+ */
11260
+ private checkFixedArrayStoragePosition;
11076
11261
  /** Is `type` an `@inline struct`: a value carried as its fields, never as a
11077
11262
  * pointer? */
11078
11263
  /**
@@ -11127,6 +11312,23 @@ declare module "types:tensionscript/src/compiler" {
11127
11312
  * there is no address to pass. Anything else refuses by name rather than
11128
11313
  * compiling a pointer.
11129
11314
  */
11315
+ /**
11316
+ * Expands a value-form `[T * N]` argument into one operand per element leaf.
11317
+ *
11318
+ * Two shapes reach here, and they differ in where the leaves come from:
11319
+ *
11320
+ * - **A value-form local** — push its SROA leaves. `pushSroaLeafOperands`
11321
+ * walks the map depth first through placeholders, which is exactly the
11322
+ * element-major order `paramRefs` declares.
11323
+ * - **An array literal** — compile each element into its own operand. A record
11324
+ * element is several leaves and no literal names them (`{x, y}` goes through
11325
+ * the class path and *allocates*), so it is refused by name, matching
11326
+ * `fillSroaArrayFromLiteral`.
11327
+ *
11328
+ * Anything else — a call returning an array, a conditional — would need the
11329
+ * value materialised somewhere, which is the return path, not this one.
11330
+ */
11331
+ private expandSroaArrayArgument;
11130
11332
  private expandSroaArgument;
11131
11333
  /**
11132
11334
  * The SROA local an expression names, or `null`.
@@ -11413,6 +11615,165 @@ declare module "types:tensionscript/src/compiler" {
11413
11615
  * has already reported why), and the caller has been told.
11414
11616
  */
11415
11617
  emitSroaStores(type: Type, fieldLocals: Map<string, Local>, dest: ExpressionRef, baseOffset: number, stmts: ExpressionRef[]): void;
11618
+ /**
11619
+ * Whether `type` is a fixed array in its **value** form — N inline elements,
11620
+ * no address of its own — as opposed to the `@unmanaged` view (a pointer,
11621
+ * Landing 5a.5) or the `@managed` heap form (Landing 5c).
11622
+ */
11623
+ isValueFormFixedArray(type: Type): boolean;
11624
+ /**
11625
+ * The largest `N` whose value-form array can be indexed with a **runtime**
11626
+ * index.
11627
+ *
11628
+ * A runtime index on SROA leaves has no address to scale, so the element is
11629
+ * selected with a `br_table` over one block per element. Past a handful of
11630
+ * blocks that dispatch costs more than the thing it replaces: the caller who
11631
+ * wants an arbitrary index over many elements wants a pointer, and
11632
+ * `@unmanaged [T * N]` gives them one with no block at all. Eight is the
11633
+ * boundary between the two. Landing 5d's spill strategy is what would lift it.
11634
+ */
11635
+ private static readonly VALUE_ARRAY_MAX_RUNTIME_INDEX;
11636
+ /** Per-emission counter for the runtime-index block labels, so two accesses in
11637
+ * one function cannot collide (Binaryen requires unique block names). */
11638
+ private sroaSelectId;
11639
+ /**
11640
+ * Fills `into` with one entry per **element** of a value-form `[T * N]`.
11641
+ *
11642
+ * The same shape `fillSroaFieldLocals` gives a record, with the index where
11643
+ * the field name would be: the map is string-keyed and `"0"`, `"1"` are
11644
+ * ordinary keys, so no new container is needed — only a new way to enumerate
11645
+ * the entries.
11646
+ *
11647
+ * - A **scalar** element gets one WASM local, named `<path>$<index>`.
11648
+ * - A **record** element is several leaves, so it gets the placeholder local
11649
+ * (`index -1`) carrying a nested map — exactly what a nested `@inline`
11650
+ * field gets, and for the same reason: `arr[i]` on a record names a whole
11651
+ * sub-value that no single local can hold, while `arr[i].x` descends one
11652
+ * hop to a leaf.
11653
+ *
11654
+ * Returns `false` when an element was refused, having reported why.
11655
+ */
11656
+ private fillSroaArrayLocals;
11657
+ /**
11658
+ * Compiles a value-form `[T * N]` local as SROA: one WASM local per element
11659
+ * leaf, no local for the array itself, no store for the zero case.
11660
+ *
11661
+ * Returns `true` when the declaration was handled here (the caller must not
11662
+ * fall through to the ordinary local path).
11663
+ */
11664
+ private compileSroaValueArrayLocal;
11665
+ /**
11666
+ * Stores an array literal's elements into a value-form array's leaves.
11667
+ *
11668
+ * A scalar element is compiled straight into its leaf. A **record** element is
11669
+ * several leaves and a literal cannot name them one at a time, so it is
11670
+ * refused by name here rather than compiled: the object-literal spelling
11671
+ * (`{ x: 1.5, y: 2.5 }`) goes through the class path and *allocates* — measured,
11672
+ * `const p: P = { x: 1.5 }` emitted `P#constructor` plus setters and needed
11673
+ * `env.abort`, i.e. a heap record behind a pointer, which is not a value.
11674
+ * Initialising the elements field by field (`arr[0].x = 10.5`) is the working
11675
+ * route, and it is what the diagnostic says.
11676
+ */
11677
+ private fillSroaArrayFromLiteral;
11678
+ /**
11679
+ * The local behind `name`, when that local is a value-form `[T * N]` — i.e. a
11680
+ * value stored as one WASM local per element leaf, with no slot of its own.
11681
+ *
11682
+ * Returns `null` for everything else, including the view form (which *is* an
11683
+ * address and goes through the ordinary path).
11684
+ */
11685
+ private resolveSroaValueArray;
11686
+ /**
11687
+ * The compile-time value of an index expression, or `-1` when it is not a
11688
+ * non-negative integer literal.
11689
+ *
11690
+ * `-1` is the "not constant" answer rather than an error: a runtime index is a
11691
+ * legitimate access, it just takes the `br_table` path.
11692
+ */
11693
+ private constantIndexValue;
11694
+ /**
11695
+ * Indexes a value-form `[T * N]` local, whose elements are separate WASM
11696
+ * locals.
11697
+ *
11698
+ * A **constant** index needs no dispatch at all: it names one leaf, and the
11699
+ * access is `local.get` / `local.set` on it. A **runtime** index has no address
11700
+ * to scale, so it is selected with a `br_table` over one block per element —
11701
+ * bounded by {@link VALUE_ARRAY_MAX_RUNTIME_INDEX}, past which the caller wants
11702
+ * a pointer view instead.
11703
+ */
11704
+ private compileSroaValueArrayElementAccess;
11705
+ /**
11706
+ * Selects one element leaf of a value-form array by a runtime index.
11707
+ *
11708
+ * The shape is one `br_table` with a block per element, each block yielding
11709
+ * that element's leaf — the only way to choose between WASM locals at runtime,
11710
+ * since they are not addressable. An index outside `[0, N)` is the caller's
11711
+ * error, exactly as it is for `[T *]`: the extent is compile-time and there is
11712
+ * no length on the value stack to check against.
11713
+ */
11714
+ private compileSroaValueArrayRuntimeIndex;
11715
+ /**
11716
+ * Reads `arr[i].field` where `arr` is a value-form array **of records** and `i`
11717
+ * is a runtime index. Returns `0` when the shape does not apply.
11718
+ *
11719
+ * A record element is several leaves per candidate, so a single-value
11720
+ * `br_table` cannot select one — but a *field* is one leaf per candidate, so
11721
+ * the selection is per leaf: one block per element, each yielding that
11722
+ * element's `<field>` leaf. Same block nesting as the scalar runtime index
11723
+ * (`compileSroaValueArrayRuntimeIndex`), one hop lower.
11724
+ *
11725
+ * This is the shape the collision solver writes by hand today —
11726
+ * `arr[i].x` with a runtime `i` over a run of records — which is why it is
11727
+ * worth the dispatch rather than only supporting a constant index.
11728
+ */
11729
+ private compileSroaArrayLeafByRuntimeIndex;
11730
+ /**
11731
+ * Writes `arr[i].field = value` where `arr` is a value-form array of records
11732
+ * and `i` is a runtime index. Returns `0` when the shape does not apply.
11733
+ *
11734
+ * The mirror of {@link compileSroaArrayLeafByRuntimeIndex}: one block per
11735
+ * element, each storing into that element's `<field>` leaf. The value is
11736
+ * materialised into a temp first — one WASM node cannot be the parent of N
11737
+ * stores — which is the same reason the scalar runtime-index write does it.
11738
+ */
11739
+ private compileSroaArrayLeafStoreByRuntimeIndex;
11740
+ /**
11741
+ * Emits the `br_table` that selects one of `leafIndices` by a runtime index.
11742
+ *
11743
+ * The only way to choose between WASM locals at runtime, since locals are not
11744
+ * addressable: one block per candidate, the body sitting **after** its block's
11745
+ * `end` (where a branch target lands), element 0 as the fall-through.
11746
+ *
11747
+ * One helper rather than four. After Landing 5b.1 four call sites emitted this
11748
+ * same nesting — scalar read, scalar write, record-field read, record-field
11749
+ * write — differing only in which leaf each block touched. Params and returns
11750
+ * would have added more, and a structural bug in one of them would have been
11751
+ * invisible in the other three.
11752
+ *
11753
+ * **A method, not a closure.** The self-hosted compiler refuses an arrow
11754
+ * function that captures a local without a declared type — `AS100: a captured
11755
+ * local without a declared type (closures lowering)` — so the four sites
11756
+ * cannot share a callback.
11757
+ *
11758
+ * `storeValueLocal` is `-1` for a read; for a store it names the temp holding
11759
+ * the value. A store's body cannot reuse the caller's expression tree: a WASM
11760
+ * node has one parent, so N stores cannot share one subtree. `resultType` is
11761
+ * `TypeRef.None` for a store, in which case the dispatch yields nothing.
11762
+ */
11763
+ private compileLeafIndexSelect;
11764
+ /**
11765
+ * Returns a value-form `[T * N]` value as WASM multivalue results.
11766
+ *
11767
+ * One result per element leaf, element-major — the order `resultRefs` declares
11768
+ * and the caller's unpack indexes into. The leaves are read out of the value's
11769
+ * SROA locals; a fresh array literal goes through the same path, because the
11770
+ * literal binds to leaves before the return is compiled.
11771
+ *
11772
+ * Requires `Feature.MultiValue`, which `Resolver` turns on when it resolves
11773
+ * this return type (`enableMultiValueOnce`), so a module that returns one of
11774
+ * these always has the feature and a module that does not never does.
11775
+ */
11776
+ private compileMultivalueReturnStatement;
11416
11777
  private compileSroaLocal;
11417
11778
  /**
11418
11779
  * The instance fields of an `@inline struct`, in declaration order, or `null`
package/dist/asc.js CHANGED
@@ -5,7 +5,7 @@
5
5
  * SPDX-License-Identifier: Apache-2.0
6
6
  */
7
7
  var le=Object.defineProperty;var Me=Object.getOwnPropertyDescriptor;var Pe=Object.getOwnPropertyNames;var Ve=Object.prototype.hasOwnProperty;var cn=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var nn=(e,t)=>{for(var n in t)le(e,n,{get:t[n],enumerable:!0})},se=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Pe(t))!Ve.call(e,s)&&s!==n&&le(e,s,{get:()=>t[s],enumerable:!(r=Me(t,s))||r.enumerable});return e},Dn=(e,t,n)=>(se(e,t,"default"),n&&se(n,t,"default"));var ue={};nn(ue,{promises:()=>je});var je,fe=cn(()=>{"use strict";je={}});var ce={};nn(ce,{createRequire:()=>Ge});function Ge(){return function(t){throw new Error(`Cannot find module: '${t}'`)}}var de=cn(()=>{"use strict"});var kn={};nn(kn,{argv:()=>Ke,cwd:()=>In,exit:()=>qe,hrtime:()=>Ye,platform:()=>Xe,umask:()=>He});function In(){return"."}function He(){return 0}function qe(e=0){throw Error(`exit ${e}`)}function Ye(e){var t=We.call(xe),n=Math.floor(t*.001),r=Math.floor(t*1e6-n*1e9);return e&&(n-=e[0],r-=e[1],r<0&&(n--,r+=1e9)),[n,r]}var Xe,Ke,xe,We,On=cn(()=>{"use strict";Xe="linux";Ke=[];xe=globalThis.performance||{},We=xe.now||function(){return new Date().getTime()}});var Rn={};nn(Rn,{basename:()=>et,delimiter:()=>at,dirname:()=>nt,extname:()=>tt,format:()=>it,isAbsolute:()=>Ze,join:()=>Je,normalize:()=>he,parse:()=>rt,relative:()=>Qe,resolve:()=>dn,sep:()=>Ln,win32:()=>ot});function j(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}function pe(e,t){for(var n="",r=0,s=-1,o=0,f,c=0;c<=e.length;++c){if(c<e.length)f=e.charCodeAt(c);else{if(f===47)break;f=47}if(f===47){if(!(s===c-1||o===1))if(s!==c-1&&o===2){if(n.length<2||r!==2||n.charCodeAt(n.length-1)!==46||n.charCodeAt(n.length-2)!==46){if(n.length>2){var p=n.lastIndexOf("/");if(p!==n.length-1){p===-1?(n="",r=0):(n=n.slice(0,p),r=n.length-1-n.lastIndexOf("/")),s=c,o=0;continue}}else if(n.length===2||n.length===1){n="",r=0,s=c,o=0;continue}}t&&(n.length>0?n+="/..":n="..",r=2)}else n.length>0?n+="/"+e.slice(s+1,c):n=e.slice(s+1,c),r=c-s-1;s=c,o=0}else f===46&&o!==-1?++o:o=-1}return n}function $e(e,t){var n=t.dir||t.root,r=t.base||(t.name||"")+(t.ext||"");return n?n===t.root?n+r:n+e+r:r}function dn(){for(var e="",t=!1,n,r=arguments.length-1;r>=-1&&!t;r--){var s;r>=0?s=arguments[r]:(n===void 0&&(n=In()),s=n),j(s),s.length!==0&&(e=s+"/"+e,t=s.charCodeAt(0)===47)}return e=pe(e,!t),t?e.length>0?"/"+e:"/":e.length>0?e:"."}function he(e){if(j(e),e.length===0)return".";var t=e.charCodeAt(0)===47,n=e.charCodeAt(e.length-1)===47;return e=pe(e,!t),e.length===0&&!t&&(e="."),e.length>0&&n&&(e+="/"),t?"/"+e:e}function Ze(e){return j(e),e.length>0&&e.charCodeAt(0)===47}function Je(){if(arguments.length===0)return".";for(var e,t=0;t<arguments.length;++t){var n=arguments[t];j(n),n.length>0&&(e===void 0?e=n:e+="/"+n)}return e===void 0?".":he(e)}function Qe(e,t){if(j(e),j(t),e===t||(e=dn(e),t=dn(t),e===t))return"";if(e===".")return t;for(var n=1;n<e.length&&e.charCodeAt(n)===47;++n);for(var r=e.length,s=r-n,o=1;o<t.length&&t.charCodeAt(o)===47;++o);for(var f=t.length,c=f-o,p=s<c?s:c,b=-1,d=0;d<=p;++d){if(d===p){if(c>p){if(t.charCodeAt(o+d)===47)return t.slice(o+d+1);if(d===0)return t.slice(o+d)}else s>p&&(e.charCodeAt(n+d)===47?b=d:d===0&&(b=0));break}var g=e.charCodeAt(n+d),y=t.charCodeAt(o+d);if(g!==y)break;g===47&&(b=d)}var m="";for(d=n+b+1;d<=r;++d)(d===r||e.charCodeAt(d)===47)&&(m.length===0?m+="..":m+="/..");return m.length>0?m+t.slice(o+b):(o+=b,t.charCodeAt(o)===47&&++o,t.slice(o))}function nt(e){if(j(e),e.length===0)return".";for(var t=e.charCodeAt(0),n=t===47,r=-1,s=!0,o=e.length-1;o>=1;--o)if(t=e.charCodeAt(o),t===47){if(!s){r=o;break}}else s=!1;return r===-1?n?"/":".":n&&r===1?"//":e.slice(0,r)}function et(e,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');j(e);var n=0,r=-1,s=!0,o;if(t!==void 0&&t.length>0&&t.length<=e.length){if(t.length===e.length&&t===e)return"";var f=t.length-1,c=-1;for(o=e.length-1;o>=0;--o){var p=e.charCodeAt(o);if(p===47){if(!s){n=o+1;break}}else c===-1&&(s=!1,c=o+1),f>=0&&(p===t.charCodeAt(f)?--f===-1&&(r=o):(f=-1,r=c))}return n===r?r=c:r===-1&&(r=e.length),e.slice(n,r)}else{for(o=e.length-1;o>=0;--o)if(e.charCodeAt(o)===47){if(!s){n=o+1;break}}else r===-1&&(s=!1,r=o+1);return r===-1?"":e.slice(n,r)}}function tt(e){j(e);for(var t=-1,n=0,r=-1,s=!0,o=0,f=e.length-1;f>=0;--f){var c=e.charCodeAt(f);if(c===47){if(!s){n=f+1;break}continue}r===-1&&(s=!1,r=f+1),c===46?t===-1?t=f:o!==1&&(o=1):t!==-1&&(o=-1)}return t===-1||r===-1||o===0||o===1&&t===r-1&&t===n+1?"":e.slice(t,r)}function it(e){if(e===null||typeof e!="object")throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof e);return $e("/",e)}function rt(e){j(e);var t={root:"",dir:"",base:"",ext:"",name:""};if(e.length===0)return t;var n=e.charCodeAt(0),r=n===47,s;r?(t.root="/",s=1):s=0;for(var o=-1,f=0,c=-1,p=!0,b=e.length-1,d=0;b>=s;--b){if(n=e.charCodeAt(b),n===47){if(!p){f=b+1;break}continue}c===-1&&(p=!1,c=b+1),n===46?o===-1?o=b:d!==1&&(d=1):o!==-1&&(d=-1)}return o===-1||c===-1||d===0||d===1&&o===c-1&&o===f+1?c!==-1&&(f===0&&r?t.base=t.name=e.slice(1,c):t.base=t.name=e.slice(f,c)):(f===0&&r?(t.name=e.slice(1,o),t.base=e.slice(1,c)):(t.name=e.slice(f,o),t.base=e.slice(f,c)),t.ext=e.slice(o,c)),f>0?t.dir=e.slice(0,f-1):r&&(t.dir="/"),t}var Ln,at,ot,Nn=cn(()=>{"use strict";On();Ln="/",at=":",ot=null});var ge={};nn(ge,{pathToFileURL:()=>lt});function st(e){return e.replace(/%/g,"%25").replace(/\\/g,"%5C").replace(/\n/g,"%0A").replace(/\r/g,"%0D").replace(/\t/g,"%09")}function lt(e){let t=dn(e);e.charCodeAt(e.length-1)===47&&t[t.length-1]!==Ln&&(t+="/");let n=new URL("file://");return n.pathname=st(t),n}var me=cn(()=>{"use strict";Nn()});var Wn={};nn(Wn,{Stats:()=>Cn,checkDiagnostics:()=>Tn,compileString:()=>Dt,configToArguments:()=>qn,createMemoryStream:()=>Hn,default:()=>Wn,defaultOptimizeLevel:()=>we,defaultShrinkLevel:()=>Se,definitionFiles:()=>St,libraryFiles:()=>G,libraryPrefix:()=>L,main:()=>De,options:()=>wt,tscOptions:()=>It,version:()=>Xn});var ut=Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]",X,sn,v,P,xn;ut?(X=await import("fs"),sn=await import("module"),v=await import("path"),P=globalThis.process,xn=await import("url")):(X=await Promise.resolve().then(()=>(fe(),ue)),sn=await Promise.resolve().then(()=>(de(),ce)),v=await Promise.resolve().then(()=>(Nn(),Rn)),P=await Promise.resolve().then(()=>(On(),kn)),xn=await Promise.resolve().then(()=>(me(),ge)));var En=typeof process<"u"&&process||{},ft=En.env&&"CI"in En.env,ct="\x1B[90m",dt="\x1B[91m",xt="\x1B[92m",pt="\x1B[93m",ht="\x1B[94m",gt="\x1B[95m",mt="\x1B[96m",bt="\x1B[97m",W="\x1B[0m",en=class{constructor(t){this.stream=t,this.enabled=!!(this.stream&&this.stream.isTTY||ft)}gray(t){return this.enabled?ct+t+W:t}red(t){return this.enabled?dt+t+W:t}green(t){return this.enabled?xt+t+W:t}yellow(t){return this.enabled?pt+t+W:t}blue(t){return this.enabled?ht+t+W:t}magenta(t){return this.enabled?gt+t+W:t}cyan(t){return this.enabled?mt+t+W:t}white(t){return this.enabled?bt+t+W:t}},An=new en(En.stdout),Lt=new en(En.stderr);function yt(e){for(var t=0,n=0,r=e.length;n<r;++n){let s=e.charCodeAt(n);s<128?t+=1:s<2048?t+=2:(s&64512)===55296&&n+1<r&&(e.charCodeAt(n+1)&64512)===56320?(++n,t+=4):t+=3}return t}function Ft(e,t,n){var r=n-t;if(r<1)return"";for(var s=null,o=[],f=0,c;t<n;)c=e[t++],c<128?o[f++]=c:c>191&&c<224?o[f++]=(c&31)<<6|e[t++]&63:c>239&&c<365?(c=((c&7)<<18|(e[t++]&63)<<12|(e[t++]&63)<<6|e[t++]&63)-65536,o[f++]=55296+(c>>10),o[f++]=56320+(c&1023)):o[f++]=(c&15)<<12|(e[t++]&63)<<6|e[t++]&63,f>=8192&&((s||(s=[])).push(String.fromCharCode(...o)),f=0);return s?(f&&s.push(String.fromCharCode(...o.slice(0,f))),s.join("")):String.fromCharCode(...o.slice(0,f))}function vt(e,t,n){for(var r=n,s=0,o=e.length;s<o;++s){let f=e.charCodeAt(s),c;f<128?t[n++]=f:f<2048?(t[n++]=f>>6|192,t[n++]=f&63|128):(f&64512)===55296&&s+1<o&&((c=e.charCodeAt(s+1))&64512)===56320?(f=65536+((f&1023)<<10)+(c&1023),++s,t[n++]=f>>18|240,t[n++]=f>>12&63|128,t[n++]=f>>6&63|128,t[n++]=f&63|128):(t[n++]=f>>12|224,t[n++]=f>>6&63|128,t[n++]=f&63|128)}return n-r}var _n={length:yt,read:Ft,write:vt};var be=sn.createRequire(import.meta.url);function Fe(e,t,n=!0){var r={},s=[],o=[],f=[],c={};Object.keys(t).forEach(d=>{if(!d.startsWith(" ")){var g=t[d];g.alias!=null&&(typeof g.alias=="string"?c[g.alias]=d:Array.isArray(g.alias)&&g.alias.forEach(y=>c[y]=d)),n&&g.default!=null&&(r[d]=g.default)}});for(var p=0,b=(e=e.slice()).length;p<b;++p){let d=e[p];if(d=="--"){++p;break}let g=/^(?:(-\w)(?:=(.*))?|(--\w{2,})(?:=(.*))?)$/.exec(d),y,m;if(g)t[d]?y=t[m=d]:g[1]!=null?(y=t[m=c[g[1].substring(1)]],y&&g[2]!=null&&(e[p--]=g[2])):g[3]!=null&&(y=t[m=g[3].substring(2)],y&&g[4]!=null&&(e[p--]=g[4]));else if(d.charCodeAt(0)==45)y=t[m=d];else{o.push(d);continue}if(y)if(y.value)Object.keys(y.value).forEach(a=>r[a]=y.value[a]);else if(y.type==null||y.type==="b")r[m]=!0;else if(p+1<e.length&&e[p+1].charCodeAt(0)!=45)switch(y.type){case"i":r[m]=parseInt(e[++p],10);break;case"I":r[m]=(r[m]||[]).concat(parseInt(e[++p],10));break;case"f":r[m]=parseFloat(e[++p]);break;case"F":r[m]=(r[m]||[]).concat(parseFloat(e[++p]));break;case"s":r[m]=String(e[++p]);break;case"S":r[m]=(r[m]||[]).concat(e[++p].split(","));break;default:s.push(d),--p}else switch(y.type){case"i":case"f":r[m]=y.default||0;break;case"s":r[m]=y.default||"";break;case"I":case"F":case"S":r[m]=y.default||[];break;default:s.push(d)}else s.push(d)}for(;p<b;)f.push(e[p++]);return n&&Mn(t,r),{options:r,unknown:s,arguments:o,trailing:f}}function ve(e,t){t||(t={});var n=t.indent||2,r=t.padding||24,s=t.eol||`
8
- `,o={},f=[];Object.keys(e).forEach(b=>{var d=e[b];if(d.description!=null){for(var g="";g.length<n;)g+=" ";for(g+="--"+b,d.alias&&(g+=", -"+d.alias);g.length<r;)g+=" ";var y;!t.noCategories&&d.category?(y=o[d.category])||(o[d.category]=y=[]):y=f,Array.isArray(d.description)?y.push(g+d.description[0]+d.description.slice(1).map(m=>{for(let a=0;a<r;++a)m=" "+m;return s+m}).join("")):y.push(g+d.description)}});var c=[],p=!1;return Object.keys(o).forEach(b=>{p=!0,c.push(s+" "+An.gray(b)+s),c.push(o[b].join(s))}),p&&f.length&&c.push(s+" "+An.gray("Other")+s),c.push(f.join(s)),c.join(s)}function ye(e,t){if(e!=null)switch(t){case void 0:case"b":return!!e;case"i":return Math.trunc(e)||0;case"f":return Number(e)||0;case"s":return e===!0?"":e===!1?null:String(e);case"I":return Array.isArray(e)||(e=[e]),e.map(n=>Math.trunc(n)||0);case"F":return Array.isArray(e)||(e=[e]),e.map(n=>Number(n)||0);case"S":return Array.isArray(e)||(e=[e]),e.map(String)}}function Un(e,t,n,r){let s={};for(let[o,{type:f,mutuallyExclusive:c,isPath:p,useNodeResolution:b,cliOnly:d}]of Object.entries(e)){let g=ye(t[o],f),y=ye(n[o],f);if(g==null){if(y!=null){if(d)continue;if(Array.isArray(y)){let m;p&&(y=y.map(a=>tn(a,r,b))),c!=null&&(m=t[c])?s[o]=y.filter(a=>!m.includes(a)):s[o]=y.slice()}else p&&(y=tn(y,r,b)),s[o]=y}}else if(y==null)Array.isArray(g)?s[o]=g.slice():s[o]=g;else if(Array.isArray(g)){if(d){s[o]=g.slice();continue}let m;p&&(y=y.map(a=>tn(a,r,b))),c!=null&&(m=t[c])?s[o]=[...g,...y.filter(a=>!g.includes(a)&&!m.includes(a))]:s[o]=[...g,...y.filter(a=>!g.includes(a))]}else s[o]=g}return s}function Et(e){let t=v.parse(e);return t.root||(t.root="./"),v.format(t)}function tn(e,t,n=!1){return v.isAbsolute(e)?e:n&&!e.startsWith(".")&&be.resolve?be.resolve(e,{paths:[t]}):Et(v.join(t,e))}function Mn(e,t){for(let[n,{default:r}]of Object.entries(e))t[n]==null&&r!=null&&(t[n]=r)}var Ee="0.12.0",Y={version:{category:"General",description:"Prints just the compiler's version and exits.",type:"b",alias:"v"},help:{category:"General",description:"Prints this message and exits.",type:"b",alias:"h"},config:{category:"General",description:"Configuration file to apply. CLI arguments take precedence.",type:"s",cliOnly:!0},target:{category:"General",description:"Configuration file target to use. Defaults to 'release'.",type:"s",cliOnly:!0},optimize:{category:"Optimization",description:["Optimizes the module. Typical shorthands are:",""," Default optimizations -O"," Make a release build -O --noAssert"," Make a debug build --debug"," Optimize for speed -Ospeed"," Optimize for size -Osize",""],type:"b",alias:"O"},optimizeLevel:{category:"Optimization",description:"How much to focus on optimizing code. [0-3]",type:"i"},shrinkLevel:{category:"Optimization",description:"How much to focus on shrinking code size. [0-2, s=1, z=2]",type:"i"},converge:{category:"Optimization",description:"Re-optimizes until no further improvements can be made.",type:"b",default:!1},noAssert:{category:"Optimization",description:"Replaces assertions with just their value without trapping.",type:"b",default:!1},outFile:{category:"Output",description:"Specifies the WebAssembly output file (.wasm).",type:"s",alias:"o",isPath:!0},textFile:{category:"Output",description:"Specifies the WebAssembly text output file (.wat).",type:"s",alias:"t",isPath:!0},bindings:{category:"Output",description:["Specifies the bindings to generate (.js + .d.ts).",""," esm JavaScript bindings & typings for ESM integration."," raw Like esm, but exports just the instantiate function."," Useful where modules are meant to be instantiated"," multiple times or non-ESM imports must be provided."],type:"S",alias:"b"},sourceMap:{category:"Debugging",description:["Enables source map generation. Optionally takes the URL","used to reference the source map from the binary file."],type:"s"},uncheckedBehavior:{category:"Debugging",description:["Changes the behavior of unchecked() expressions.","Using this option can potentially cause breakage.",""," default The default behavior: unchecked operations are"," only used inside of unchecked()."," never Unchecked operations are never used, even when"," inside of unchecked()."," always Unchecked operations are always used if possible,"," whether or not unchecked() is used."],type:"s",default:"default"},debug:{category:"Debugging",description:"Enables debug information in emitted binaries.",type:"b",default:!1},importMemory:{category:"Features",description:"Imports the memory from 'env.memory'.",type:"b",default:!1},noExportMemory:{category:"Features",description:"Does not export the memory as 'memory'.",type:"b",default:!1},initialMemory:{category:"Features",description:"Sets the initial memory size in pages.",type:"i",default:0},maximumMemory:{category:"Features",description:"Sets the maximum memory size in pages.",type:"i",default:0},sharedMemory:{category:"Features",description:"Declare memory as shared. Requires maximumMemory.",type:"b",default:!1},zeroFilledMemory:{category:"Features",description:"Assume imported memory is zeroed. Requires importMemory.",type:"b",default:!1},importTable:{category:"Features",description:"Imports the function table from 'env.table'.",type:"b",default:!1},exportTable:{category:"Features",description:"Exports the function table as 'table'.",type:"b",default:!1},exportStart:{category:"Features",description:["Exports the start function using the specified name instead","of calling it implicitly. Useful to obtain the exported memory","before executing any code accessing it."],type:"s"},runtime:{category:"Features",description:["Specifies the runtime variant to include in the program.",""," incremental TLSF + incremental GC (default)"," minimal TLSF + lightweight GC invoked externally"," stub Minimal runtime stub (never frees)"," ... Path to a custom runtime implementation",""],type:"s",default:"incremental"},exportRuntime:{category:"Features",description:["Always exports the runtime helpers (__new, __collect, __pin etc.).","Automatically determined when generation of --bindings is enabled."],type:"b",default:!1},stackSize:{category:"Features",description:["Overrides the stack size. Only relevant for incremental GC","or when using a custom runtime that requires stack space.","Defaults to 0 without and to 32768 with incremental GC."],default:0,type:"i"},enable:{category:"Features",description:["Enables WebAssembly features being disabled by default.",""," threads Threading and atomic operations."," simd SIMD types and operations."," reference-types Reference types and operations."," gc Garbage collection (WIP)."," stringref String reference types."," relaxed-simd Relaxed SIMD operations.",""],TODO_doesNothingYet:[" exception-handling Exception handling."," tail-calls Tail call operations."," multi-value Multi value types."," memory64 Memory64 operations."," extended-const Extended const expressions."],type:"S",mutuallyExclusive:"disable"},disable:{category:"Features",description:["Disables WebAssembly features being enabled by default.",""," mutable-globals Mutable global imports and exports."," sign-extension Sign-extension operations"," nontrapping-f2i Non-trapping float to integer ops."," bulk-memory Bulk memory operations.",""],type:"S",mutuallyExclusive:"enable"},use:{category:"Features",description:["Aliases a global object under another name, e.g., to switch","the default 'Math' implementation used: --use Math=JSMath","Can also be used to introduce an integer constant."],type:"S",alias:"u"},lowMemoryLimit:{category:"Features",description:"Enforces very low (<64k) memory constraints.",default:0,type:"i"},memoryBase:{category:"Linking",description:"Sets the start offset of emitted memory segments.",type:"i",default:0},tableBase:{category:"Linking",description:"Sets the start offset of emitted table elements.",type:"i",default:0},transform:{category:"API",description:"Specifies the path to a custom transform to load.",type:"S",isPath:!0,useNodeResolution:!0},trapMode:{category:"Binaryen",description:["Sets the trap mode to use.",""," allow Allow trapping operations. This is the default."," clamp Replace trapping operations with clamping semantics."," js Replace trapping operations with JS semantics.",""],type:"s",default:"allow"},runPasses:{category:"Binaryen",description:["Specifies additional Binaryen passes to run after other","optimizations, if any. See: Binaryen/src/passes/pass.cpp"],type:"s"},noValidate:{category:"Binaryen",description:"Skips validating the module using Binaryen.",type:"b",default:!1},baseDir:{description:"Specifies the base directory of input and output files.",type:"s",default:"."},noColors:{description:"Disables terminal colors.",type:"b",default:!1},noUnsafe:{description:["Disallows the use of unsafe features in user code.","Does not affect library files and external modules."],type:"b",default:!1},disableWarning:{description:["Disables warnings matching the given diagnostic code.","If no diagnostic code is given, all warnings are disabled."],type:"I"},noEmit:{description:"Performs compilation as usual but does not emit code.",type:"b",default:!1},showConfig:{description:"Print computed compiler options and exit.",type:"b",default:!1},stats:{description:"Prints statistics on I/O and compile times.",type:"b",default:!1},pedantic:{description:"Make yourself sad for no good reason.",type:"b",default:!1},lib:{description:["Adds one or multiple paths to custom library components and","uses exports of all top-level files at this path as globals."],type:"S",isPath:!0},path:{description:["Adds one or multiple paths to package resolution, similar","to node_modules. Prefers an 'ascMain' entry in a package's","package.json and falls back to an inner 'assembly/' folder."],type:"S",isPath:!0},wasm:{description:"Uses the specified Wasm binary of the compiler.",type:"s"}," ...":{description:"Specifies node.js options (CLI only). See: node --help"},"-Os":{value:{optimizeLevel:0,shrinkLevel:1}},"-Oz":{value:{optimizeLevel:0,shrinkLevel:2}},"-O0":{value:{optimizeLevel:0,shrinkLevel:0}},"-O1":{value:{optimizeLevel:1,shrinkLevel:0}},"-O2":{value:{optimizeLevel:2,shrinkLevel:0}},"-O3":{value:{optimizeLevel:3,shrinkLevel:0}},"-O0s":{value:{optimizeLevel:0,shrinkLevel:1}},"-O1s":{value:{optimizeLevel:1,shrinkLevel:1}},"-O2s":{value:{optimizeLevel:2,shrinkLevel:1}},"-O3s":{value:{optimizeLevel:3,shrinkLevel:1}},"-O0z":{value:{optimizeLevel:0,shrinkLevel:2}},"-O1z":{value:{optimizeLevel:1,shrinkLevel:2}},"-O2z":{value:{optimizeLevel:2,shrinkLevel:2}},"-O3z":{value:{optimizeLevel:3,shrinkLevel:2}},"-Ospeed":{value:{optimizeLevel:3,shrinkLevel:0}},"-Osize":{value:{optimizeLevel:0,shrinkLevel:2,converge:!0}},"--measure":{value:{stats:!0}}},Ae="~lib/",_e={array:`/// <reference path="./rt/index.d.ts" />
8
+ `,o={},f=[];Object.keys(e).forEach(b=>{var d=e[b];if(d.description!=null){for(var g="";g.length<n;)g+=" ";for(g+="--"+b,d.alias&&(g+=", -"+d.alias);g.length<r;)g+=" ";var y;!t.noCategories&&d.category?(y=o[d.category])||(o[d.category]=y=[]):y=f,Array.isArray(d.description)?y.push(g+d.description[0]+d.description.slice(1).map(m=>{for(let a=0;a<r;++a)m=" "+m;return s+m}).join("")):y.push(g+d.description)}});var c=[],p=!1;return Object.keys(o).forEach(b=>{p=!0,c.push(s+" "+An.gray(b)+s),c.push(o[b].join(s))}),p&&f.length&&c.push(s+" "+An.gray("Other")+s),c.push(f.join(s)),c.join(s)}function ye(e,t){if(e!=null)switch(t){case void 0:case"b":return!!e;case"i":return Math.trunc(e)||0;case"f":return Number(e)||0;case"s":return e===!0?"":e===!1?null:String(e);case"I":return Array.isArray(e)||(e=[e]),e.map(n=>Math.trunc(n)||0);case"F":return Array.isArray(e)||(e=[e]),e.map(n=>Number(n)||0);case"S":return Array.isArray(e)||(e=[e]),e.map(String)}}function Un(e,t,n,r){let s={};for(let[o,{type:f,mutuallyExclusive:c,isPath:p,useNodeResolution:b,cliOnly:d}]of Object.entries(e)){let g=ye(t[o],f),y=ye(n[o],f);if(g==null){if(y!=null){if(d)continue;if(Array.isArray(y)){let m;p&&(y=y.map(a=>tn(a,r,b))),c!=null&&(m=t[c])?s[o]=y.filter(a=>!m.includes(a)):s[o]=y.slice()}else p&&(y=tn(y,r,b)),s[o]=y}}else if(y==null)Array.isArray(g)?s[o]=g.slice():s[o]=g;else if(Array.isArray(g)){if(d){s[o]=g.slice();continue}let m;p&&(y=y.map(a=>tn(a,r,b))),c!=null&&(m=t[c])?s[o]=[...g,...y.filter(a=>!g.includes(a)&&!m.includes(a))]:s[o]=[...g,...y.filter(a=>!g.includes(a))]}else s[o]=g}return s}function Et(e){let t=v.parse(e);return t.root||(t.root="./"),v.format(t)}function tn(e,t,n=!1){return v.isAbsolute(e)?e:n&&!e.startsWith(".")&&be.resolve?be.resolve(e,{paths:[t]}):Et(v.join(t,e))}function Mn(e,t){for(let[n,{default:r}]of Object.entries(e))t[n]==null&&r!=null&&(t[n]=r)}var Ee="0.13.0",Y={version:{category:"General",description:"Prints just the compiler's version and exits.",type:"b",alias:"v"},help:{category:"General",description:"Prints this message and exits.",type:"b",alias:"h"},config:{category:"General",description:"Configuration file to apply. CLI arguments take precedence.",type:"s",cliOnly:!0},target:{category:"General",description:"Configuration file target to use. Defaults to 'release'.",type:"s",cliOnly:!0},optimize:{category:"Optimization",description:["Optimizes the module. Typical shorthands are:",""," Default optimizations -O"," Make a release build -O --noAssert"," Make a debug build --debug"," Optimize for speed -Ospeed"," Optimize for size -Osize",""],type:"b",alias:"O"},optimizeLevel:{category:"Optimization",description:"How much to focus on optimizing code. [0-3]",type:"i"},shrinkLevel:{category:"Optimization",description:"How much to focus on shrinking code size. [0-2, s=1, z=2]",type:"i"},converge:{category:"Optimization",description:"Re-optimizes until no further improvements can be made.",type:"b",default:!1},noAssert:{category:"Optimization",description:"Replaces assertions with just their value without trapping.",type:"b",default:!1},outFile:{category:"Output",description:"Specifies the WebAssembly output file (.wasm).",type:"s",alias:"o",isPath:!0},textFile:{category:"Output",description:"Specifies the WebAssembly text output file (.wat).",type:"s",alias:"t",isPath:!0},bindings:{category:"Output",description:["Specifies the bindings to generate (.js + .d.ts).",""," esm JavaScript bindings & typings for ESM integration."," raw Like esm, but exports just the instantiate function."," Useful where modules are meant to be instantiated"," multiple times or non-ESM imports must be provided."],type:"S",alias:"b"},sourceMap:{category:"Debugging",description:["Enables source map generation. Optionally takes the URL","used to reference the source map from the binary file."],type:"s"},uncheckedBehavior:{category:"Debugging",description:["Changes the behavior of unchecked() expressions.","Using this option can potentially cause breakage.",""," default The default behavior: unchecked operations are"," only used inside of unchecked()."," never Unchecked operations are never used, even when"," inside of unchecked()."," always Unchecked operations are always used if possible,"," whether or not unchecked() is used."],type:"s",default:"default"},debug:{category:"Debugging",description:"Enables debug information in emitted binaries.",type:"b",default:!1},importMemory:{category:"Features",description:"Imports the memory from 'env.memory'.",type:"b",default:!1},noExportMemory:{category:"Features",description:"Does not export the memory as 'memory'.",type:"b",default:!1},initialMemory:{category:"Features",description:"Sets the initial memory size in pages.",type:"i",default:0},maximumMemory:{category:"Features",description:"Sets the maximum memory size in pages.",type:"i",default:0},sharedMemory:{category:"Features",description:"Declare memory as shared. Requires maximumMemory.",type:"b",default:!1},zeroFilledMemory:{category:"Features",description:"Assume imported memory is zeroed. Requires importMemory.",type:"b",default:!1},importTable:{category:"Features",description:"Imports the function table from 'env.table'.",type:"b",default:!1},exportTable:{category:"Features",description:"Exports the function table as 'table'.",type:"b",default:!1},exportStart:{category:"Features",description:["Exports the start function using the specified name instead","of calling it implicitly. Useful to obtain the exported memory","before executing any code accessing it."],type:"s"},runtime:{category:"Features",description:["Specifies the runtime variant to include in the program.",""," incremental TLSF + incremental GC (default)"," minimal TLSF + lightweight GC invoked externally"," stub Minimal runtime stub (never frees)"," ... Path to a custom runtime implementation",""],type:"s",default:"incremental"},exportRuntime:{category:"Features",description:["Always exports the runtime helpers (__new, __collect, __pin etc.).","Automatically determined when generation of --bindings is enabled."],type:"b",default:!1},stackSize:{category:"Features",description:["Overrides the stack size. Only relevant for incremental GC","or when using a custom runtime that requires stack space.","Defaults to 0 without and to 32768 with incremental GC."],default:0,type:"i"},enable:{category:"Features",description:["Enables WebAssembly features being disabled by default.",""," threads Threading and atomic operations."," simd SIMD types and operations."," reference-types Reference types and operations."," gc Garbage collection (WIP)."," stringref String reference types."," relaxed-simd Relaxed SIMD operations.",""],TODO_doesNothingYet:[" exception-handling Exception handling."," tail-calls Tail call operations."," multi-value Multi value types."," memory64 Memory64 operations."," extended-const Extended const expressions."],type:"S",mutuallyExclusive:"disable"},disable:{category:"Features",description:["Disables WebAssembly features being enabled by default.",""," mutable-globals Mutable global imports and exports."," sign-extension Sign-extension operations"," nontrapping-f2i Non-trapping float to integer ops."," bulk-memory Bulk memory operations.",""],type:"S",mutuallyExclusive:"enable"},use:{category:"Features",description:["Aliases a global object under another name, e.g., to switch","the default 'Math' implementation used: --use Math=JSMath","Can also be used to introduce an integer constant."],type:"S",alias:"u"},lowMemoryLimit:{category:"Features",description:"Enforces very low (<64k) memory constraints.",default:0,type:"i"},memoryBase:{category:"Linking",description:"Sets the start offset of emitted memory segments.",type:"i",default:0},tableBase:{category:"Linking",description:"Sets the start offset of emitted table elements.",type:"i",default:0},transform:{category:"API",description:"Specifies the path to a custom transform to load.",type:"S",isPath:!0,useNodeResolution:!0},trapMode:{category:"Binaryen",description:["Sets the trap mode to use.",""," allow Allow trapping operations. This is the default."," clamp Replace trapping operations with clamping semantics."," js Replace trapping operations with JS semantics.",""],type:"s",default:"allow"},runPasses:{category:"Binaryen",description:["Specifies additional Binaryen passes to run after other","optimizations, if any. See: Binaryen/src/passes/pass.cpp"],type:"s"},noValidate:{category:"Binaryen",description:"Skips validating the module using Binaryen.",type:"b",default:!1},baseDir:{description:"Specifies the base directory of input and output files.",type:"s",default:"."},noColors:{description:"Disables terminal colors.",type:"b",default:!1},noUnsafe:{description:["Disallows the use of unsafe features in user code.","Does not affect library files and external modules."],type:"b",default:!1},disableWarning:{description:["Disables warnings matching the given diagnostic code.","If no diagnostic code is given, all warnings are disabled."],type:"I"},noEmit:{description:"Performs compilation as usual but does not emit code.",type:"b",default:!1},showConfig:{description:"Print computed compiler options and exit.",type:"b",default:!1},stats:{description:"Prints statistics on I/O and compile times.",type:"b",default:!1},pedantic:{description:"Make yourself sad for no good reason.",type:"b",default:!1},lib:{description:["Adds one or multiple paths to custom library components and","uses exports of all top-level files at this path as globals."],type:"S",isPath:!0},path:{description:["Adds one or multiple paths to package resolution, similar","to node_modules. Prefers an 'ascMain' entry in a package's","package.json and falls back to an inner 'assembly/' folder."],type:"S",isPath:!0},wasm:{description:"Uses the specified Wasm binary of the compiler.",type:"s"}," ...":{description:"Specifies node.js options (CLI only). See: node --help"},"-Os":{value:{optimizeLevel:0,shrinkLevel:1}},"-Oz":{value:{optimizeLevel:0,shrinkLevel:2}},"-O0":{value:{optimizeLevel:0,shrinkLevel:0}},"-O1":{value:{optimizeLevel:1,shrinkLevel:0}},"-O2":{value:{optimizeLevel:2,shrinkLevel:0}},"-O3":{value:{optimizeLevel:3,shrinkLevel:0}},"-O0s":{value:{optimizeLevel:0,shrinkLevel:1}},"-O1s":{value:{optimizeLevel:1,shrinkLevel:1}},"-O2s":{value:{optimizeLevel:2,shrinkLevel:1}},"-O3s":{value:{optimizeLevel:3,shrinkLevel:1}},"-O0z":{value:{optimizeLevel:0,shrinkLevel:2}},"-O1z":{value:{optimizeLevel:1,shrinkLevel:2}},"-O2z":{value:{optimizeLevel:2,shrinkLevel:2}},"-O3z":{value:{optimizeLevel:3,shrinkLevel:2}},"-Ospeed":{value:{optimizeLevel:3,shrinkLevel:0}},"-Osize":{value:{optimizeLevel:0,shrinkLevel:2,converge:!0}},"--measure":{value:{stats:!0}}},Ae="~lib/",_e={array:`/// <reference path="./rt/index.d.ts" />
9
9
 
10
10
  import { BLOCK_MAXSIZE } from "./rt/common";
11
11
  import { Runtime } from "shared/runtime";