compiler 0.0.2-preview.1

The Zena self-hosted compiler

Readme Files Dependencies Versions

compiler#

The Zena compiler, written in Zena. It parses, type-checks, and compiles Zena source code to WebAssembly (Wasm GC) and WebAssembly Text (WAT).

Usage#

Parsing a Single File#

Use compiler/parser to parse Zena source text into an AST (Module):

import { parse } from 'compiler/parser';

let ast = parse('export let answer = 42;', 'example.zena');

Loading and Checking a Program#

Use compiler (createCompiler and checkCompilation) with a CompilerHost to resolve imports across a module graph and type-check a program:

import {
  createCompiler, checkCompilation, buildStdlibConfig
} from 'compiler';
import { FsCompilerHost } from 'compiler/fs-host';

let stdlibRoot = '/stdlib';
let host = new FsCompilerHost(stdlibRoot);
let packages = buildStdlibConfig(stdlibRoot, 'host');
let compiler = createCompiler(host, {
  stdlibRoot,
  packages,
});

let result = await compiler.compile({
  entry: '/workspace/main.zena',
  target: 'host',
});
let checked = checkCompilation(result);

Compiling a File to WebAssembly#

Use compiler/compile-file to compile an entry file on disk to a .wasm or .wat output file:

import { compileFile } from 'compiler/compile-file';

let ok = await compileFile({
  entry: 'src/main.zena',
  outPath: 'out/main.wasm',
  stdlibRoot: '/stdlib',
});

Libraries#

  • compiler / compiler/compiler — compiler entry point (Compiler, createCompiler, checkCompilation, ProgramCheckResult)
  • compiler/compile-file — end-to-end file compilation (compileFile, CompileFileOptions)
  • compiler/tokenizer — lexer and token definitions (tokenize, Token, TokenType)
  • compiler/parser — recursive-descent parser (parse, Parser)
  • compiler/ast — AST node definitions (Node, Module, Statement, Expression, TypeAnnotation)
  • compiler/visitor — AST traversal helpers (walk, Visitor)
  • compiler/scope — lexical scope and symbol resolution (ScopeBuilder, ScopeResult, Symbol)
  • compiler/checker — static type checker (checkModule, CheckResult)
  • compiler/semantic-model — semantic queries over a checked module (SemanticModel)
  • compiler/types — compiler type representations (Type, ClassType, FunctionType, typeToString)
  • compiler/diagnostics — compiler diagnostics and source spans (Diagnostic, DiagnosticCode, DiagnosticSeverity, SourceSpan)
  • compiler/package-manifest — zena-package.json manifest and workspace loader (loadWorkspace, loadPackageMap)
  • compiler/module-resolver — package and relative module specifier resolution (ModuleResolver, PackageConfig)
  • compiler/library-loader — module graph loader (LibraryLoader, CompilerHost, SourceFile)
  • compiler/codegen/binary-generator — WebAssembly GC binary emitter (BinaryGenerator)
  • compiler/codegen/wat-generator — WebAssembly Text (WAT) emitter (WatGenerator)

License#

MIT

137.9 KiB Raw
import { Set, HashMap, HashSet } from 'zena:collections';
import {
  Node, Expression, NodeId, ImportSpecifier, FunctionExpression, MethodDefinition, DeclareFunction, VariableDeclaration, FunctionDeclaration, IdentifierPattern,
  ContractClause, ContractKind, ContractMode,
} from '../ast.zena';
import { SemanticModel } from '../semantic-model.zena';
import { SymbolId, noSymbolId } from '../scope/symbol.zena';
import { ByteBuffer, growable, i32ToString } from 'zena:core';
import {
  ValType, ValTypeVoid, ValTypeStructRef, ValTypeRefNull, ValTypeRef, ValTypeEqRef,
  ValTypeAnyRef, ValTypeI8, WasmType, valTypeEquals, ValTypeExternRef, ValTypeRefExtern, ValTypeI32,
  ValTypeNullRef, isNullableAnyRef,
  valTypeToOpcode, nextWasmTypeUid, refTargetOf, sameHeapType
} from './wasm.zena';
import { NodeMap } from '../node-map.zena';
import {
  ClassType, FunctionType, InterfaceType, NullType, TupleType, Type, TypeAliasType, TypeInterner,
  TypeParameterType, UnionType,
  TypeListTable,
} from '../types.zena';
import { Program, CompilationUnit } from '../program.zena';
import { stdlibLibraryOf, stdlibLibraryAnswers } from '../stdlib-manifest.zena';
import { defaultImportedStringConstants, targetUsesJsStrings } from '../targets.zena';

import {
  compareStrings, ClassKey, InterfaceKey, ClassInterfaceKey, CellKey, ClosureKey, ExportKey, ExportGlobalKey, getClassKey, getClassPrivateFieldKey, getTypeKeyForSpecialization, isPresentWordName, presentWordCount, presentWordName, FunctionAdaptationKey, getFunctionAdaptationKey, ClassMethodKey, getClassMethodKey, SpecializedFunctionKey, ClosureSpecializationKey, FunctionValueWrapperKey,
} from './codegen-utils.zena';

@intrinsic('hash')
declare function hash<T>(value: T): i32;


export function sortWasmFields(fields: GrowableArray<WasmField>): void {
  let len = fields.length;
  for (var i = 1; i < len; i += 1) {
    let key = fields[i];
    var j = i - 1;
    while (j >= 0) {
      let a = fields[j].name;
      let b = key.name;
      if (a != null && b != null) {
        if (compareStrings(a, b) > 0) {
          fields[j + 1] = fields[j];
          j -= 1;
        } else {
          break;
        }
      } else {
        break;
      }
    }
    fields[j + 1] = key;
  }
}

export final class WasmExport {
  name: String;
  func: WasmFunction;
  new(this.name, this.func);
}

/**
 * Represents a reference to an entity that has a WebAssembly type index.
 * Before layout runs, the index is -1.
 */
export final class WasmField {
  name: String | null;
  /**
   * `var` for exactly one writer: struct layout can bake a field of a
   * not-yet-registered class as `structref`, and RTA re-resolves such
   * fields in place once discovery has settled (see
   * `Specializer.refreshErasedFieldTypes`). Inherited fields are
   * SHARED WasmField instances between super- and subclass structs, so
   * the in-place write is what keeps them consistent.
   */
  var type: ValType;
  isMutable: boolean;
  new(this.name, this.type, this.isMutable);
}


/**
 * Cache keys for WasmModule's structural type pools (getSignature / getStruct /
 * getArray). Each is a compact string encoding of the requested type's
 * identity, so that a HashMap lookup replaces a linear scan over all types.
 *
 * The shared building block is the ValType unit appended by appendValTypeKey:
 *
 *   <opcode>['#'<target uid> | '?'<target uid>]','
 *
 * i.e. the valtype's wasm opcode, plus the referenced WasmType's uid for
 * concrete ref types ('#' non-null, '?' nullable). Two ValTypes produce the
 * same unit iff valTypeEquals considers them equal.
 *
 * On top of that:
 *   SignatureKey: <param unit>* '|' <result unit>*
 *   StructKey:    [<struct name>] '\n' (<field name>('m'|'c')<field unit>'\n')*
 *   ArrayKey:     ('m'|'c') <element unit>
 *
 * The keys are derived purely from the freshly-built inputs of each request
 * (there is no pre-existing object to cache them on, unlike e.g. ClassKey
 * which is memoized on the ClassType).
 */
function valTypeHashCode(vt: ValType) {
  return match (vt) {
    case ValTypeRef {target}: target.uid * 2
    case ValTypeRefNull {target}: target.uid * 2 + 1
    case _: valTypeToOpcode(vt)
  };
}

/**
 * Identity-based ValType equality for the type-pool cache keys below.
 *
 * This deliberately does NOT use valTypeEquals: that compares ref targets
 * by their type-section INDEX, which is -1 for every type until layout()
 * runs and is reassigned there. Keys whose equality mutates break the
 * caches twice over — distinct keys can spuriously merge before layout
 * (all indices equal -1), and entries cached before layout become
 * unfindable afterwards. Comparing the target OBJECTS is stable across
 * layout, matches valTypeHashCode (uid-based) so hashCode/equals agree,
 * and is equivalent to index equality for laid-out types.
 */
function valTypeKeyEquals(a: ValType, b: ValType): boolean {
  if (valTypeToOpcode(a) != valTypeToOpcode(b)) {
    return false;
  }
  return match (a) {
    case ValTypeRef {target as ta}: if (let ValTypeRef {target as tb} = b) {
      ta == tb
    } else {
      false
    }
    case ValTypeRefNull {target as ta}: if (let ValTypeRefNull {target as tb} = b) {
      ta == tb
    } else {
      false
    }
    case _: true
  };
}

export final class SignatureKey implements Hashable {
  params: GrowableArray<ValType>;
  returns: GrowableArray<ValType>;
  new(this.params, this.returns);

  hashCode(): i32 {
    var h = 17;
    for (let p in this.params) {
      h = h * 31 + valTypeHashCode(p);
    }
    h = h * 31 + 12345;
    for (let r in this.returns) {
      h = h * 31 + valTypeHashCode(r);
    }
    return h;
  }

  operator ==(other: SignatureKey): boolean {
    if (this.params.length != other.params.length || this.returns.length != other.returns.length) {
      return false;
    }
    for (var i = 0; i < this.params.length; i += 1) {
      if (!valTypeKeyEquals(this.params[i], other.params[i])) { return false; }
    }
    for (var j = 0; j < this.returns.length; j += 1) {
      if (!valTypeKeyEquals(this.returns[j], other.returns[j])) { return false; }
    }
    return true;
  }
}

function stringEquals(s1: String | null, s2: String | null): boolean {
  if (s1 == null) {
    return s2 == null;
  }
  if (s2 == null) {
    return false;
  }
  return s1 == s2;
}

export final class StructKey implements Hashable {
  name: String | null;
  fields: GrowableArray<WasmField>;
  new(this.name, this.fields);

  hashCode(): i32 {
    var h = if (this.name == null) 0 else hash(this.name as String);
    for (let f in this.fields) {
      if (f.name != null) {
        h = h * 31 + hash(f.name as String);
      }
      h = h * 31 + valTypeHashCode(f.type);
      if (f.isMutable) {
        h = h * 31 + 777;
      }
    }
    return h;
  }

  operator ==(other: StructKey): boolean {
    if (!stringEquals(this.name, other.name) || this.fields.length != other.fields.length) {
      return false;
    }
    for (var i = 0; i < this.fields.length; i += 1) {
      let f1 = this.fields[i];
      let f2 = other.fields[i];
      if (!stringEquals(f1.name, f2.name) || f1.isMutable != f2.isMutable || !valTypeKeyEquals(f1.type, f2.type)) {
        return false;
      }
    }
    return true;
  }
}

/**
 * The class a field of type `vt` holds, when it holds an instance of one:
 * a reference, nullable or not, to a class's struct. An extension class
 * has no struct of its own, so none of its values is one.
 */
export function classOfField(vt: ValType): ClassType | null {
  let target = refTargetOf(vt);
  if (target is WasmStruct) {
    let ct = target.classType;
    if (ct != null && !ct.isExtension && !target.isTuple) {
      return ct;
    }
  }
  return null;
}

/** The topmost superclass of `ct`. */
function rootClassOf(ct: ClassType) {
  var c = ct;
  while (true) {
    let sup = c.superType;
    if (sup == null) {
      return c;
    }
    c = sup;
  }
  return c;
}

/**
 * What tells tuple groups apart (`WasmModule.getTupleStruct`): which
 * tuples meet (`component`, the root of a union-find class of exact
 * representations, so tuples of one representation always share), the
 * field names,
 * and each field's type, except that a class-typed field is keyed by its
 * class's root, nullable or not. So `(Bird, i32)` and `(Animal | null,
 * i32)` can share a struct when they meet, and `(Bird, i32)` and
 * `(anyref, i32)` never do.
 */
export final class TupleGroupKey implements Hashable {
  component: StructKey;
  names: GrowableArray<String>;
  types: GrowableArray<ValType>;
  roots: GrowableArray<String | null>;
  new(this.component, this.names, this.types, this.roots);

  hashCode(): i32 {
    var h = this.component.hashCode();
    for (var i = 0; i < this.names.length; i += 1) {
      h = h * 31 + hash(this.names[i]);
      let root = this.roots[i];
      h = h * 31 + (if (root != null) hash(root) else valTypeHashCode(this.types[i]));
    }
    return h;
  }

  operator ==(other: TupleGroupKey): boolean {
    if (!(this.component == other.component) || this.names.length != other.names.length) {
      return false;
    }
    for (var i = 0; i < this.names.length; i += 1) {
      if (this.names[i] != other.names[i]) {
        return false;
      }
      let a = this.roots[i];
      let b = other.roots[i];
      if (a != null || b != null) {
        if (a == null || b == null || a != b) {
          return false;
        }
      } else if (!valTypeKeyEquals(this.types[i], other.types[i])) {
        return false;
      }
    }
    return true;
  }
}

/**
 * The class a tuple element of type `t` holds, nullable or not: the
 * semantic counterpart of `classOfField`, for keying tuple types before
 * any struct exists.
 */
function elementClassOf(t: Type): ClassType | null {
  if (t is ClassType) {
    return if (t.isExtension) null else t;
  }
  if (t is TypeAliasType && !t.isDistinct && t.typeParameters == null) {
    return elementClassOf(t.target);
  }
  if (t is UnionType && t.types.length == 2) {
    for (let member in t.types) {
      if (!(member is NullType)) {
        return elementClassOf(member);
      }
    }
  }
  return null;
}

/**
 * The family of a tuple type: its elements, a class-typed one by its
 * class's root. Tuple types of one family can share a struct, so only
 * they are joined (`WasmModule.#joinTuples`).
 */
function tupleFamilyKey(tt: TupleType) {
  var key = 'family';
  for (let el in tt.elementTypes) {
    let ct = elementClassOf(el);
    key = if (ct != null) `${key}|C${getClassKey(rootClassOf(ct)) as String}`
        else `${key}|${getTypeKeyForSpecialization(el)}`;
  }
  return key;
}

/**
 * The boxed tuples whose types meet and whose class-typed fields share a
 * root (`TupleGroupKey`), which are one struct (#1137, records-and-tuples.md
 * §4.1). `classes[i]` lists the classes members put in a class-typed
 * field, and is null for any other field; the field holds the lowest
 * struct all of theirs extend, nullable when any member's is
 * (`WasmModule.settleTupleSlots`).
 */
final class TupleGroup {
  struct: WasmStruct;
  classes: GrowableArray<GrowableArray<ClassType> | null>;
  nullable: GrowableArray<boolean>;
  new(this.struct, this.classes, this.nullable);
}

/** The lowest struct each of `structs` is or extends, or null when none is. */
function commonSuperStruct(structs: GrowableArray<WasmStruct>): WasmStruct | null {
  var candidate: WasmStruct | null = structs[0];
  while (candidate != null) {
    var all = true;
    for (let st in structs) {
      var s: WasmStruct | null = st;
      var found = false;
      while (s != null) {
        if (s === candidate) {
          found = true;
          break;
        }
        s = s.superStruct;
      }
      if (!found) {
        all = false;
        break;
      }
    }
    if (all) {
      return candidate;
    }
    candidate = candidate.superStruct;
  }
  return null;
}

/** How much of one model's tuple notes `WasmModule.noteTupleJoins` has read. */
final class TupleNoteCursor {
  var widenings = 0;
  var erased = 0;
  var tested = 0;
}

export final class ArrayKey implements Hashable {
  elementType: ValType;
  isMutable: boolean;
  new(this.elementType, this.isMutable);

  hashCode(): i32 {
    var h = valTypeHashCode(this.elementType);
    if (this.isMutable) {
      h = h * 31 + 999;
    }
    return h;
  }

  operator ==(other: ArrayKey): boolean {
    return this.isMutable == other.isMutable && valTypeKeyEquals(this.elementType, other.elementType);
  }
}

function getSignatureKey(params: GrowableArray<ValType>, returns: GrowableArray<ValType>) {
  return new SignatureKey(params, returns);
}

function getStructKey(name: String | null, fields: GrowableArray<WasmField>) {
  return new StructKey(name, fields);
}

function getArrayKey(elementType: ValType, isMutable: boolean) {
  return new ArrayKey(elementType, isMutable);
}

export final class WasmStruct extends WasmType {
  var superStruct: WasmStruct | null = null;
  var classType: ClassType | null = null;
  /**
   * A boxed tuple's struct (`WasmModule.getTupleStruct`): immutable
   * fields named by position, and an identity no program can observe,
   * so a copy of one is interchangeable with it.
   */
  var isTuple: boolean = false;
  name: String | null;
  fields: GrowableArray<WasmField>;
  /** Lazy name→index cache; sized-guarded because RTA appends fields. */
  var #fieldIndexCache: HashMap<String, i32> | null = null;
  var #fieldIndexCacheSize = -1;
  new(this.name, this.fields) : super();

  /**
   * Resolves a private member's mangled field name against this
   * struct. Field names carry the key of the class the STRUCT was
   * built for — the specialized class for per-specialization structs,
   * the generic template for structs shared across erased-identical
   * specializations, and the declaring ancestor for inherited fields —
   * so no single caller-side mangle can be correct. The search order
   * preserves lexical privacy: first the accessor's written class
   * chain exactly (a subclass's shadowing private must not win), then
   * this struct's own class chain restricted to classes that are
   * specializations of the lexical class. Both backends share this.
   */
  resolvePrivateFieldName(lexicalCt: ClassType | null, propName: String): String | null {
    if (lexicalCt != null) {
      var l: ClassType | null = lexicalCt;
      while (l != null) {
        var g: ClassType | null = l;
        while (g != null) {
          // A mixin's This class namespaces its private fields with
          // the mixin's scope key (ClassType.privateScopeKey), shared
          // by all applications of the mixin.
          let gc = g;
          let key = if (gc.privateScopeKey != null) {
            getClassPrivateFieldKey(gc.privateScopeKey as String as ClassKey, propName)
          } else {
            getClassPrivateFieldKey(getClassKey(gc), propName)
          };
          if (this.fieldIndexByName(key) >= 0) {
            return key;
          }
          g = gc.genericSource;
        }
        l = l.superType;
      }
    }
    let lexCanonical = if (lexicalCt != null) canonicalClassKey(lexicalCt) else null;
    var c = this.classType;
    while (c != null) {
      let cc = c;
      if (lexCanonical == null ||
          (canonicalClassKey(cc) as String) == (lexCanonical as ClassKey) as String) {
        let key = getClassPrivateFieldKey(getClassKey(cc), propName);
        if (this.fieldIndexByName(key) >= 0) {
          return key;
        }
      }
      c = cc.superType;
    }
    return null;
  }

  /**
   * Index of the named field, or -1. Memoized: field lookups by name
   * happen once per field access during lowering and emission, and a
   * per-access linear scan would multiply out to O(accesses × fields)
   * on wide structs. The cache rebuilds if fields were appended since
   * it was built (interface vtable structs gain fields during RTA).
   */
  fieldIndexByName(fieldName: String): i32 {
    if (this.#fieldIndexCache == null ||
        this.#fieldIndexCacheSize != this.fields.length) {
      let cache = new Map<String, i32>();
      for (var i = 0; i < this.fields.length; i += 1) {
        let n = this.fields[i].name;
        if (n != null) {
          cache[n] = i;
        }
      }
      this.#fieldIndexCache = cache;
      this.#fieldIndexCacheSize = this.fields.length;
    }
    let cache = this.#fieldIndexCache as HashMap<String, i32>;
    return if (let (true, idx) = cache.get(fieldName)) idx else -1;
  }

  /**
   * Keeps the fields whose flag is true, in order, and drops the rest
   * (dead-field elimination, ir/deadfields.zena). Clears the name cache,
   * whose indices the removal shifts.
   */
  retainFields(keep: GrowableArray<boolean>): void {
    let kept = new Array<WasmField>();
    for (var i = 0; i < this.fields.length; i += 1) {
      if (keep[i]) {
        kept.push(this.fields[i]);
      }
    }
    this.fields.clear();
    for (let f in kept) {
      this.fields.push(f);
    }
    this.#fieldIndexCache = null;
    this.#fieldIndexCacheSize = -1;
  }
}

/** The generic-source root's key: specializations compare equal to
 * their template through this. */
export function canonicalClassKey(ct: ClassType): ClassKey {
  var c = ct;
  while (c.genericSource != null) {
    c = c.genericSource as ClassType;
  }
  return getClassKey(c);
}

export final class WasmArray extends WasmType {
  elementType: ValType;
  isMutable: boolean;
  /**
   * The declared supertype of an immutable array of references: the
   * array of its element's supertype, up to `(array anyref)`. That is
   * what makes an immutable array of a subclass a Wasm subtype of the
   * immutable array of its superclass, with no cast and no copy. A
   * mutable array has none — its elements are invariant.
   */
  var superArray: WasmArray | null = null;
  new(this.elementType, this.isMutable) : super();
}

/**
 * A WebAssembly function signature.
 * Deduped by the module so identical signatures share the same type index.
 * Params and returns are represented by WebAssembly ValType enums (e.g. i32, f64).
 */
export final class WasmSignature extends WasmType {
  params: GrowableArray<ValType>;
  returns: GrowableArray<ValType>;
  new(this.params, this.returns) : super();
}

/** The WasmStruct behind a reference ValType, or null. */
export function asWasmStruct(vt: ValType): WasmStruct | null {
  let t = refTargetOf(vt);
  if (t is WasmStruct) {
    return t;
  }
  return null;
}

/** The WasmSignature behind a reference ValType, or null. */
export function asWasmSignature(vt: ValType): WasmSignature | null {
  let t = refTargetOf(vt);
  if (t is WasmSignature) {
    return t;
  }
  return null;
}

/** The WasmArray behind a reference ValType, or null. */
export function asWasmArray(vt: ValType): WasmArray | null {
  let t = refTargetOf(vt);
  if (t is WasmArray) {
    return t;
  }
  return null;
}

/**
 * Wasm-level assignability between value types: may a value of type `a`
 * flow where `b` is expected? Conservative: scalar types must match
 * exactly; reference types allow dropping non-nullability, walking
 * struct supertype chains, and widening struct or array targets to
 * eqref/anyref (all Zena heap values are eq).
 */
/** Nullability-SENSITIVE structural equality. valTypeEquals treats
 * (ref T) and (ref null T) as equal (ref locals are declared nullable
 * and re-cast at uses), but subtyping must not: a nullable value
 * never conforms to a non-null slot. */
export function valTypeIdentical(a: ValType, b: ValType): boolean {
  return match (a) {
    case ValTypeRef as ta: match (b) {
      case ValTypeRef as tb: sameHeapType(ta.target, tb.target)
      case _: false
    }
    case ValTypeRefNull as ta: match (b) {
      case ValTypeRefNull as tb: sameHeapType(ta.target, tb.target)
      case _: false
    }
    case ValTypeRefExtern: b is ValTypeRefExtern
    case ValTypeExternRef: b is ValTypeExternRef
    case _: valTypeEquals(a, b)
  };
}

export function isValSubtype(a: ValType, b: ValType): boolean {
  // valTypeEquals ignores nullability (ref X equals refnull X), so
  // this shortcut answers true for refnull X <: ref X — which is not
  // a subtype. Lowering leans on that laxity in many places (it bails
  // when told a nullable value does not conform), so it stays until
  // those sites are audited; a caller that must not fold a null check
  // (simplify's castIsIdentity) checks nullability itself.
  if (valTypeEquals(a, b)) {
    return true;
  }
  if (a is ValTypeRefExtern && b is ValTypeExternRef) {
    return true;
  }
  if (a is ValTypeStructRef) {
    // structref <: eqref <: anyref.
    return b is ValTypeAnyRef || b is ValTypeEqRef;
  }
  if (a is ValTypeEqRef) {
    return b is ValTypeAnyRef;
  }
  if (a is ValTypeNullRef) {
    return isNullableAnyRef(b);
  }
  let aTarget = refTargetOf(a);
  if (aTarget == null) {
    return false;
  }
  // a is a concrete ref; non-null may widen to nullable, never the reverse.
  let aNullable = a is ValTypeRefNull;
  if (b is ValTypeAnyRef || b is ValTypeEqRef) {
    return true;
  }
  if (b is ValTypeStructRef) {
    return aTarget is WasmStruct;
  }
  let bTarget = refTargetOf(b);
  if (bTarget == null) {
    return false;
  }
  let bNullable = b is ValTypeRefNull;
  if (aNullable && !bNullable) {
    return false;
  }
  return heapSubtype(aTarget, bTarget);
}

/** Declared-subtype check between heap types (struct super chains). */
function heapSubtype(a: WasmType, b: WasmType): boolean {
  if (a == b) {
    return true;
  }
  if (a is WasmStruct) {
    var current = a.superStruct;
    while (current != null) {
      if (current == b) {
        return true;
      }
      current = current.superStruct;
    }
  }
  if (a is WasmArray) {
    var currentArray = a.superArray;
    while (currentArray != null) {
      if (currentArray == b) {
        return true;
      }
      currentArray = currentArray.superArray;
    }
  }
  return false;
}

/**
 * Represents a single compiled WebAssembly function.
 * Tracks its eventual index, signature, and the AST node it was derived from.
 */
/** The shared empty capture lists a function without captures reads. */
export let noCaptures = new Array<SymbolId>();
export let noMutableCaptures = new Set<SymbolId>();

export final class WasmFunction implements Hashable {
  /** The semantic model of the module that declares this function. */
  var model: SemanticModel;
  var index: i32 = -1;
  /** Process-unique id, used for identity-based hashing. */
  uid: i32 = nextWasmTypeUid();
  var name: String | null = null;
  var methodName: String | null = null;
  var structType: WasmStruct | null = null;
  var classType: ClassType | null = null;
  var classDecl: Node | null = null;
  var signature: WasmSignature;
  var node: Node | null = null;
  var isImport: boolean = false;
  var isStatic: boolean = false;
  var importModule: String | null = null;
  var importName: String | null = null;
  /**
   * `@external(..., "async")`: lower the call with the canonical `async`
   * option, so it returns a subtask handle instead of waiting. Only the
   * component target can do anything with it — a core module has no
   * canonical ABI to lower through. See
   * docs/design/component-emission.md 1.6.
   */
  var importIsAsync: boolean = false;
  /**
   * `@external("canon", "stream.write", "stream<u8>")`: the WIT type a
   * typed canonical builtin operates on, spelled as WIT. The stream and
   * future builtins are per-type in the canon section — the immediate
   * is a component type index — so the declaration has to say which
   * type this builtin is an instance of. Empty for everything else.
   */
  var importCanonType: String = "";
  var isCaseClassEq: boolean = false;
  /**
   * For a synthesized structural `==` over two record or tuple types
   * (ir/equality.zena, `lowerValueEqFunction`): the operands' types,
   * without `| null`. Null for every other function.
   */
  var valueEqLeft: Type | null = null;
  var valueEqRight: Type | null = null;
  /**
   * For a synthesized hash of a record or tuple type
   * (ir/equality.zena, `lowerValueHashFunction`): the type, without
   * `| null`. Null for every other function.
   */
  var valueHashType: Type | null = null;

  /** A synthesized resource `:dispose`: no AST body, the class's owner
   * fields release as its whole behavior. */
  var isSyntheticRelease: boolean = false;
  var isCaseClassHash: boolean = false;
  /**
   * Generator split-pass roles (ir/generators.zena): the generator
   * function itself becomes the frame-allocating ramp; its
   * synthesized companion carries the state-machine next() body.
   */
  var isGeneratorRamp: boolean = false;
  var isGeneratorNext: boolean = false;
  /**
   * Async split-pass roles (ir/async.zena), the same shape: the async
   * function itself becomes the frame-allocating ramp, and its
   * synthesized companion carries the state-machine step() body.
   */
  var isAsyncRamp: boolean = false;
  var isAsyncStep: boolean = false;
  /**
   * The synthesized export wrapper for an async `main`: starts the
   * ramp, drains the microtask queue, and unwraps the settled value
   * (async.md §4, Level 0).
   */
  var isAsyncMainWrapper: boolean = false;
  /**
   * A function the component target synthesizes to sit between the
   * canonical ABI and a Zena one: `main$componentRun`, which calls main
   * and then asks the p3 driver for the callback code, and the
   * `$componentExport` wrappers, which convert a signature's strings to
   * and from linear memory. Their bodies live in
   * ir/component-adapters.zena rather than in any source file.
   */
  var isComponentAdapter: boolean = false;
  /**
   * Set on body-less functions that exist only to occupy a vtable
   * slot. A class's vtable struct declares one exactly-typed funcref
   * field per method of the hierarchy, so even a method that
   * reachability never saw a call to must put SOMETHING of the right
   * signature in its slot. Both backends emit a single `unreachable`
   * for these: a virtual dispatch landing on one means the liveness
   * analysis was wrong, and trapping loudly is the correct response.
   */
  var isVtableSlotStub: boolean = false;
  /**
   * Set on functions compiled from a mixin declaration's body: the
   * mixin's private scope key ("<Mixin>_This@<path>"). Private
   * accesses in such functions resolve to "<scope>::#name" — mixin
   * privates are lexical to the mixin declaration and never alias a
   * host class's same-named private. Null for functions written in a
   * class body.
   *
   * Registration paths that know the scope set it directly; lowering
   * derives it from the function's node otherwise
   * (`mixinScopeOfNode`), which is what covers closures and
   * monomorphized generic methods. `privateScopeResolved` marks the
   * derivation as done, so a genuine null is not re-derived per
   * access.
   */
  var privateScopeKey: String | null = null;
  var privateScopeResolved: boolean = false;
  /** For mixin methods, the mixin intermediate ClassType in the super chain. */
  var declaringType: ClassType | null = null;
  /**
   * While a host constructor lowers one of a field decorator's
   * initializers: that application's intermediate, whose type
   * parameters bind before the host's (`substituteTypeParamsInFunctionContext`).
   * One constructor initializes every application in the chain, and the
   * host's flattened context would answer the decorator's parameter with
   * whichever application came first. Lowering sets and restores it per
   * initializer, together with `codegenSubstCache`.
   */
  var substitutionApplication: ClassType | null = null;
  /** The target class struct for a synthesized field getter. */
  var getterStruct: WasmStruct | null = null;
  /** The index of the field in the class struct for the synthesized getter. */
  var getterFieldIndex: i32 = -1;
  /** The target class struct for a synthesized field setter. */
  var setterStruct: WasmStruct | null = null;
  /** The index of the field in the class struct for the synthesized setter. */
  var setterFieldIndex: i32 = -1;
  /**
   * For an adapted record dispatch's `$present` word getter: how each
   * target mask bit (globally indexed across all words) derives from
   * the source — -1 = absent (constant 0), -2 = required in the source
   * (constant 1), else the source's global bit index.
   */
  var getterMaskSpec: GrowableArray<i32> | null = null;
  /** Which 64-bit word of the target mask this getter assembles. */
  var getterMaskWord: i32 = 0;
  /**
   * An adapted getter for an optional target field the source shape
   * lacks: return the slot type's zero value (the mask reports the
   * absence; there is nothing to read).
   */
  var getterReturnsZero: boolean = false;
  /**
   * A slot of an existential record's table, or of a table reading a
   * record through another record's fat pointer: what the synthesized
   * body forwards to (ir/existential.zena).
   */
  var existentialForward: ExistentialForward | null = null;
  /** The concrete target function for an interface trampoline method/property call. */
  var interfaceTrampolineTarget: WasmFunction | null = null;
  /**
   * The class an interface trampoline was built for, and the class
   * vtable slot of its target. A value held as that class may be an
   * instance of a subclass that overrides the target, so the trampoline
   * dispatches through the slot when one does.
   */
  var interfaceTrampolineClass: ClassType | null = null;
  var interfaceTrampolineSlot: String | null = null;
  /** The target imported function for an external reference wrapper. */
  var importWrapperTarget: WasmFunction | null = null;
  var intrinsic: String | null = null;

  var isReached: boolean = false;
  var isAdded: boolean = false;
  var isClosure: boolean = false;
  var isReferenceTaken: boolean = false;
  var contextStruct: WasmStruct | null = null;
  /**
   * The symbols a closure captures, null for the great majority of
   * functions that capture nothing: an array and a set per function
   * were two empty tables on each of 41K functions. Readers go through
   * `noCaptures`/`noMutableCaptures` for the null case.
   */
  var captures: GrowableArray<SymbolId> | null = null;
  var mutableCaptures: HashSet<SymbolId> | null = null;
  var capturesThis: boolean = false;
  var isFunctionAdaptation: boolean = false;
  var functionAdaptationSource: FunctionType | null = null;
  var functionAdaptationTarget: FunctionType | null = null;
  var functionAdaptationResolvedSourceStruct: WasmStruct | null = null;
  var functionAdaptationResolvedTargetStruct: WasmStruct | null = null;
  var isClosureWrapper: boolean = false;
  var closureWrapperTarget: WasmFunction | null = null;
  /**
   * A field decorator's `context.get`/`context.set` function: the
   * closure-ABI wrapper around the decorated field's accessor on one
   * application (docs/design/decorators.md). Synthesized by RTA,
   * lowered by `synthesizeDecoratorAccessorWrapper`.
   */
  var decoratorAccessorTarget: WasmFunction | null = null;
  var typeParameters: Array<TypeParameterType> | null = null;
  var typeArguments: Array<Type> | null = null;
  /**
   * Memoized results of substituteTypeParamsInFunctionContext for this
   * function, keyed by input type identity (codegen/type-mapping.zena).
   */
  var codegenSubstCache: HashMap<Type, Type> | null = null;

  var closureTrampoline: WasmFunction | null = null;
  var isClosureTrampoline: boolean = false;
  var closureTrampolineTarget: WasmFunction | null = null;

  /**
   * Interface-trampoline adaptations for a generic vtable slot, where
   * an implementing class's own signature narrows the interface view:
   * closure parameters to rebuild through a forwarder, and the
   * class-interface pack for a covariant class-typed result. Null on
   * trampolines whose target signature matches the slot.
   */
  var trampolineParamWraps: GrowableArray<TrampolineParamWrap> | null = null;
  var trampolineResultPackPair: ClassInterfaceKey | null = null;
  var trampolineResultPackIface: InterfaceKey | null = null;
  /** Set on a synthesized closure forwarder (see ClosureForwarderSpec). */
  var closureForwarder: ClosureForwarderSpec | null = null;
  /**
   * Set on both halves of a function whose record parameters were
   * exploded (see ExplosionSpec): the original, which became the
   * forwarder, and the core it calls.
   */
  var explosion: ExplosionSpec | null = null;

  new(this.signature, this.node, this.model);
  hashCode(): i32 {
    return this.uid;
  }

  /** Identity equality, paired with the uid hash. */
  operator ==(other: WasmFunction): boolean {
    return this === other;
  }
}

/**
 * A function whose record parameters are passed as their fields
 * (docs/design/argument-explosion.md). The original `WasmFunction`
 * keeps its signature, so every existing reference to it stays valid;
 * its body becomes a forwarder that reads the exploded records' fields
 * and calls `core`. `core` takes those fields as parameters and holds
 * the declared body. A direct call whose exploded arguments are all
 * record literals calls `core` and allocates no record. `core` may also
 * return the fields of the record `forwarder` returns; the forwarder
 * then builds the record from them.
 */
export final class ExplosionSpec {
  /**
   * Per declared parameter, the dispatch whose fields replace it in
   * `core`'s signature, in `dispatch.fields` order; null for a
   * parameter passed as it is.
   */
  params: GrowableArray<RecordDispatchInfo | null>;
  forwarder: WasmFunction;
  core: WasmFunction;
  /**
   * The dispatch of the record the forwarder returns, when `core`
   * returns its fields instead, in `dispatch.fields` order; else null.
   */
  result: RecordDispatchInfo | null;
  /**
   * For a constructor's value phase (`<ctor-init>`), whose results end
   * with the arguments of its `super(...)`: per such argument, the
   * dispatch whose fields `core` returns in its place, or null for one
   * returned as it is. Null when every result is returned as it is.
   */
  var tail: GrowableArray<RecordDispatchInfo | null> | null = null;
  new(this.params, this.forwarder, this.core, this.result);
}

/**
 * One closure parameter of a generic interface-trampoline whose
 * implementing class narrows the callback's own parameter types (a
 * `this`-typed parameter in the interface declaration). The trampoline
 * rebuilds the argument as a class-view closure pair: `forwarder` as
 * the func, the caller's interface-view pair as the ctx.
 */
export final class TrampolineParamWrap {
  /** Trampoline signature parameter index (0 is the receiver). */
  paramIndex: i32;
  /** The implementing class's view of the callback's closure pair. */
  implClosureStruct: WasmStruct;
  forwarder: WasmFunction;
  new(this.paramIndex, this.implClosureStruct, this.forwarder);
}

/**
 * Body spec for a synthesized closure forwarder: called with the
 * implementing class's argument types, it packs the marked arguments
 * into interface fat pointers and delegates to the caller's
 * interface-view closure pair carried in its ctx slot.
 */
export final class ClosureForwarderSpec {
  /** The caller's interface-view closure pair struct (the ctx cast target). */
  sourceStruct: WasmStruct;
  packs: GrowableArray<ForwarderParamPack>;
  new(this.sourceStruct, this.packs);
}

/**
 * One value a function-adaptation wrapper packs into an interface: an
 * argument on the way in, or the result on the way out. One side of the
 * adaptation holds it as a class instance or as a sub-interface, the
 * other as the interface, so the wrapper makes the pack or the upcast an
 * assignment of the value would make.
 */
export final class AdaptationPack {
  /** Parameter index in the source's impl signature (0 is the ctx), or -1 for the result. */
  index: i32;
  /** Set for a class instance: the class-interface pair whose vtable packs it. */
  pair: ClassInterfaceKey | null;
  /** Set for a fat pointer: the sub-interface it is held as. */
  sourceIface: InterfaceKey | null;
  /** The interface the value becomes. */
  targetIface: InterfaceKey;
  /** The value can be null, and null passes through as a null fat pointer. */
  nullable: boolean;
  new(this.index, this.pair, this.sourceIface, this.targetIface, this.nullable);
}

/** One forwarder argument to pack into an interface fat pointer. */
export final class ForwarderParamPack {
  /** Parameter index in the closure impl signature (0 is the ctx). */
  argIndex: i32;
  /** The class-interface vtable pair that packs the value. */
  pair: ClassInterfaceKey;
  /** The target interface (its fat-pointer struct). */
  ifaceKey: InterfaceKey;
  new(this.argIndex, this.pair, this.ifaceKey);
}

/**
 * One interface type test the discovery walks found: `iface` is the
 * tested interface and `source` the operand's static type. A site whose
 * operand is statically the interface is not recorded; that operand is
 * a fat pointer of it already and the test stays a `ref.test`.
 */
export final class TypeTestSite {
  iface: InterfaceType;
  source: Type;
  new(this.iface, this.source);
}

/**
 * The most candidate pairs an interface may have and still be tested
 * by a chain of class tests. A `ref.test` against a final class struct
 * is an inline type-index compare, about 0.35 ns each on wasmtime;
 * the type-info read costs one `is_subtype` libcall, about 20 ns, for
 * an operand that is not statically a class (docs/design/
 * interface-type-tests.md, "Measured cost"). Sixteen keeps the worst
 * chain well under the libcall.
 */
export let typeTestChainMax = 16;

/** A class a chained interface test tries: its struct, and the pair vtable an `as` packs with. */
export final class TypeTestCandidate {
  structType: WasmStruct;
  vtableGlobal: WasmGlobal;
  new(this.structType, this.vtableGlobal);
}

/** The `TypeInfo` field for the tested interface in slot `slot`. */
export function typeTestSlotName(slot: i32): String {
  return `<impl${i32ToString(slot)}>`;
}

/** The furthest supertype of `st`. */
export function rootStruct(st: WasmStruct): WasmStruct {
  var s = st;
  while (s.superStruct != null) {
    s = s.superStruct as WasmStruct;
  }
  return s;
}

/** Puts `field` first in `st`'s field list. */
export function prependField(st: WasmStruct, field: WasmField): void {
  let rest = new Array<WasmField>();
  for (let f in st.fields) {
    rest.push(f);
  }
  while (st.fields.length > 0) {
    st.fields.pop();
  }
  st.fields.push(field);
  for (let f in rest) {
    st.fields.push(f);
  }
}

export final class VTableInit {
  structType: WasmStruct;
  funcs: GrowableArray<WasmFunction>;
  /**
   * True for a class's method table. Its functions are reached only
   * where a call can dispatch to them (see ReachabilityAnalysis's
   * #fillReachedSlots), rather than all at once when the table is made.
   */
  var isClassVTable = false;
  /**
   * `markReferences` is false for a class's method table, whose slots
   * are pruned after it is built; the analysis marks the functions that
   * survive (#pruneUndispatchedSlots). A function marked here is
   * declared in the module's element section whether or not it stays.
   */
  /**
   * A record table's shape id (`RecordDispatchInfo.shapeId`), stored in
   * the field after the functions; -1 for any other table.
   */
  var shapeTag: i32 = -1;
  /**
   * Globals stored in the fields BEFORE the functions, one per leading
   * field, read with `global.get` in the initializer; a null entry
   * stores the field's null. A class vtable with a `<typeinfo>` field
   * holds its type-info global here, and a type-info table holds the
   * class-interface vtables it answers `is` with (see
   * ReachabilityAnalysis's #layoutTypeTests). Every global named here
   * is declared before this one: the analysis orders the globals so
   * that holds (#orderGlobalInitializers).
   */
  var slotGlobals: GrowableArray<WasmGlobal | null> | null = null;

  new(this.structType, this.funcs, markReferences: boolean = true) {
    if (markReferences) {
      for (let f in this.funcs) {
        f.isReferenceTaken = true;
      }
    }
  }
}

export final class WasmGlobal {
  var index: i32 = -1;
  var symbolId: SymbolId = noSymbolId;
  name: String;
  zenaName: String;
  /**
   * Mutable only so creators that attach an in-place constant initializer
   * AFTER construction (initSingletonStruct, initArraySize) can re-tighten
   * a reference type to non-nullable; the constructor below conservatively
   * nullifies ref types it cannot prove initialized in place.
   */
  var type: ValType;
  isMutable: boolean;
  var isImport: boolean = false;
  var importModule: String | null = null;
  var importName: String | null = null;
  var initExpr: Expression | null = null;
  var initVTable: VTableInit | null = null;
  var initSingletonStruct: ClassType | null = null;
  var initArraySize: i32 = -1;
  var namespaceImport: ImportSpecifier | null = null;
  model: SemanticModel;
  new(
    this.name,
    this.zenaName,
    type: ValType,
    this.isMutable,
    this.initExpr,
    this.initVTable,
    this.model
  ) : type = if (isMutable || (initExpr == null && initVTable == null)) {
        match (type) {
          case ValTypeRef {target}: new ValTypeRefNull(target)
          case ValTypeRefExtern: new ValTypeExternRef()
          case _: type
        }
      } else {
        type
      } {}
}

export final class RecordDispatchInfo {
  fatPtrType: WasmStruct;
  vtableType: WasmStruct;
  concreteType: WasmStruct;
  vtableGlobal: WasmGlobal;
  fields: GrowableArray<WasmField>;
  getterTypes: GrowableArray<WasmSignature>;
  /**
   * Sorted optional field names of the (target) record type; position =
   * presence-bit index. Part of the dispatch key: two record types with
   * identical field lists but different optional sets have different
   * getter semantics.
   */
  optionalNames: GrowableArray<String>;
  /** For an adapted dispatch: the SOURCE shape's sorted optional names
   *  (equals optionalNames on a plain dispatch). */
  inOptionalNames: GrowableArray<String>;
  /**
   * The record shape this dispatch's values have, also stored in the
   * table's trailing `<shape>` field. Record types whose getters have
   * the same signatures share wasm types, so `{a: i32}` and `{b: i32}`
   * have one fat pointer type; the id tells them apart where only the
   * value is known (`lowerErasedEqDispatch`). An adapted dispatch is a
   * projection to its target shape, so it carries the target's id.
   */
  var shapeId: i32 = -1;
  /**
   * An existential record type's dispatch (`getExistentialDispatch`):
   * `fields` are the known ones, its table adds the `<underlying>`,
   * `<shapeOf>` and `<hash>` slots, and it has no table of its own (every
   * value comes from a pack), so `vtableGlobal` is a placeholder that is
   * never emitted.
   */
  var isExistential: boolean = false;
  /**
   * A boxed tuple's stand-in (`getTupleDispatch`), so that argument
   * explosion carries tuples as it does records: `fields` are the tuple
   * struct's, read with `struct_get` and built with `struct_new` alone.
   * The struct is its fat pointer, concrete type and table, and
   * `vtableGlobal` is a placeholder that is never emitted.
   */
  var isTuple: boolean = false;

  new(this.fatPtrType, this.vtableType, this.concreteType, this.vtableGlobal, this.fields, this.getterTypes, this.optionalNames, this.inOptionalNames);

  optionalBitOf(name: String): i32 {
    for (var i = 0; i < this.optionalNames.length; i += 1) {
      if (this.optionalNames[i] == name) { return i; }
    }
    return -1;
  }
}

/** The name of a record table's trailing shape-id field. */
export let recordShapeFieldName = "<shape>";

/** An existential table's slot returning the closed record it holds. */
export let existentialUnderlyingName = "<underlying>";
/** An existential table's slot returning that record's shape id. */
export let existentialShapeName = "<shapeOf>";
/** An existential table's slot returning that record's hash. */
export let existentialHashName = "<hash>";

/** What a forwarding slot computes (`ExistentialForward`). */
export enum ForwardKind {
  /** Read the named field through the source fat pointer. */
  Field,
  /** The closed record held: the source itself, or its own `<underlying>`. */
  Underlying,
  /** That record's shape id. */
  Shape,
  /** That record's hash. */
  Hash,
}

/**
 * A slot body that forwards to the record behind its `structref`
 * parameter, which is a fat pointer of `source`: a closed record's, or
 * an existential's. For a closed `source`, `Hash` calls `hashFunc`, the
 * record type's `$valueHash`.
 */
export final class ExistentialForward {
  source: RecordDispatchInfo;
  kind: ForwardKind;
  field: String | null;
  hashFunc: WasmFunction | null;
  new(this.source, this.kind, this.field, this.hashFunc);
}

/**
 * The table that packs records of `source`'s shape into the existential
 * `target`, or (when `target` is closed) reads a closed record through
 * `source`'s fat pointer.
 */
export final class RecordForwardTable {
  source: RecordDispatchInfo;
  target: RecordDispatchInfo;
  vtableGlobal: WasmGlobal;
  new(this.source, this.target, this.vtableGlobal);
}

/**
 * The closed record shapes packed into some existential that have every
 * field of `target`: the records a run-time `as target` can find in an
 * existential (ir/existential.zena). One dispatch per shape, in the
 * order the packs were made.
 */
export function existentialCastCandidates(packs: GrowableArray<RecordForwardTable>,
    target: RecordDispatchInfo): GrowableArray<RecordDispatchInfo> {
  let out = new Array<RecordDispatchInfo>();
  for (let pack in packs) {
    let s = pack.source;
    if (s.isExistential) {
      continue;
    }
    var seen = false;
    for (let o in out) {
      if (o.shapeId == s.shapeId) {
        seen = true;
      }
    }
    if (!seen && hasFieldsOf(s, target)) {
      out.push(s);
    }
  }
  return out;
}

/** Whether `s` has every field of `t`, at the same wasm type. */
function hasFieldsOf(s: RecordDispatchInfo, t: RecordDispatchInfo): boolean {
  for (let tf in t.fields) {
    var found = false;
    for (let sf in s.fields) {
      if (sf.name == tf.name && valTypeEquals(sf.type, tf.type)) {
        found = true;
      }
    }
    if (!found) {
      return false;
    }
  }
  return true;
}

/** The three slots after an existential table's getters, in order. */
function existentialSlots(wasm: WasmModule): GrowableArray<WasmField> {
  let structRef = new ValTypeStructRef() as ValType;
  let underlyingSig = wasm.getSignature(growable<ValType>([structRef]), growable<ValType>([structRef]));
  let i32Sig = wasm.getSignature(growable<ValType>([structRef]), growable<ValType>([new ValTypeI32()]));
  return growable<WasmField>([
    new WasmField(existentialUnderlyingName, new ValTypeRef(underlyingSig), false),
    new WasmField(existentialShapeName, new ValTypeRef(i32Sig), false),
    new WasmField(existentialHashName, new ValTypeRef(i32Sig), false),
  ]);
}

/** Whether `info` has exactly these fields and optional names. */
function sameRecordFields(info: RecordDispatchInfo, fields: GrowableArray<WasmField>,
    optionalNames: GrowableArray<String>): boolean {
  if (info.fields.length != fields.length || !stringArraysEqual(info.optionalNames, optionalNames)) {
    return false;
  }
  for (var i = 0; i < fields.length; i += 1) {
    if (info.fields[i].name != fields[i].name || !valTypeEquals(info.fields[i].type, fields[i].type)) {
      return false;
    }
  }
  return true;
}

function copyFields(fields: GrowableArray<WasmField>) {
  let out = new Array<WasmField>();
  for (let f in fields) {
    out.push(f);
  }
  return out;
}

function copyStrings(strings: GrowableArray<String>) {
  let out = new Array<String>();
  for (let s in strings) {
    out.push(s);
  }
  return out;
}

function stringArraysEqual(a: GrowableArray<String>, b: GrowableArray<String>): boolean {
  if (a.length != b.length) { return false; }
  for (var i = 0; i < a.length; i += 1) {
    if (a[i] != b[i]) { return false; }
  }
  return true;
}

export final class ClassCodegenInfo {
  structType: WasmStruct;
  var vtableStructType: WasmStruct | null = null;
  var vtableGlobal: WasmGlobal | null = null;
  var singletonGlobal: WasmGlobal | null = null;
  subclasses = new Array<ClassCodegenInfo>();
  new(this.structType);

  getTransitiveSubclasses(result: GrowableArray<ClassCodegenInfo>): void {
    for (let sub in this.subclasses) {
      result.push(sub);
      sub.getTransitiveSubclasses(result);
    }
  }
}

export final class WasmTag {
  var index: i32 = -1;
  signature: WasmSignature;
  new(this.signature);
}

export final class StringLiteralLocation {
  offset: i32;
  length: i32;
  new(this.offset, this.length);
}

/**
 * Codegen's memo tables for one class, owned by the `WasmModule` of the
 * compile that filled them.
 *
 * These were fields on `ClassType`. A checker type outlives the compile
 * that produced it whenever check results are reused — the point of
 * sharing an already-checked stdlib across entry points — so codegen
 * state parked on one is visible to every later compile. The entries are
 * pure functions of checker types, so sharing them is not *wrong*, but
 * they grow without bound in a long-lived process and the instantiations
 * table hands out `ClassType` identities that downstream codegen treats
 * as belonging to the current module.
 *
 * Owning them per compile also survives the compiler going async: a
 * module-global swept between compiles would pull the memo out from
 * under any compile that happened to be interleaved with the sweep, and
 * hand it a different `ClassType` for an instantiation it had already
 * used.
 */
export final class ClassSubstitutions {
  /** Type parameters and arguments in scope for the class, flattened. */
  var params: Array<TypeParameterType> | null = null;
  var args: Array<Type> | null = null;
  /** substituteTypeParamsInClassContext results, by input type identity. */
  substCache = new Map<Type, Type>();
  /** Instantiations of this class, keyed by substituted argument uids. */
  instantiations = new Map<String, ClassType>();


}

/**
 * One of a declared world's async exports on the component target:
 * its kebab-case export name, and the adapter the component lifts.
 */
export final class ComponentAsyncExport {
  exportName: String;
  adapter: WasmFunction;
  new(this.exportName, this.adapter);
}

/**
 * One of a declared world's synchronous exports that goes through a
 * compiler-written wrapper: its kebab-case export name, the core
 * export name the wrapper is lifted under, and the wrapper itself.
 */
export final class ComponentSyncExport {
  exportName: String;
  coreName: String;
  func: WasmFunction;
  new(this.exportName, this.coreName, this.func);
}

/**
 * The destructor of a resource the program provides: the resource's
 * WIT name, the core export name the wrapper's `<resource>__dtor` is
 * exported under (the component's destructor shim is filled from it),
 * and the function.
 */
export final class ComponentResourceDtor {
  resourceName: String;
  coreName: String;
  func: WasmFunction;
  new(this.resourceName, this.coreName, this.func);
}

export final class WasmModule {
  /**
   * Per-class substitution memos for this compile. Keyed by
   * `ClassType.uid`, not by the type: `Type`'s cases are case classes, so
   * `==` is structural while `hashCode` is the uid — an inconsistent pair
   * to hash on. The uid is the identity these tables want ("type identity
   * is equality", types.zena).
   */
  classSubstitutions = new Map<i32, ClassSubstitutions>();

  /** The memo tables for `ct`, created on first use. */
  substitutionsFor(ct: ClassType): ClassSubstitutions {
    if (let (true, existing) = this.classSubstitutions.get(ct.uid)) {
      return existing;
    }
    let fresh = new ClassSubstitutions();
    this.classSubstitutions[ct.uid] = fresh;
    return fresh;
  }

  /**
   * Instantiations of each interface by substituted argument uids, the
   * interface counterpart of `ClassSubstitutions.instantiations`, so a
   * generic interface mentioned in many signatures is instantiated once
   * per argument list here too.
   */
  interfaceInstantiations = new Map<i32, HashMap<String, InterfaceType>>();

  /** The instantiation table for `it`, created on first use. */
  interfaceInstantiationsFor(it: InterfaceType): HashMap<String, InterfaceType> {
    if (let (true, existing) = this.interfaceInstantiations.get(it.uid)) {
      return existing;
    }
    let fresh = new Map<String, InterfaceType>();
    this.interfaceInstantiations[it.uid] = fresh;
    return fresh;
  }

  /**
   * `eraseTypeParameters` results for class, interface, alias and record
   * types, by the input's uid. Erasure is a function of the input alone,
   * and the entry is made before a recursive type's parts are erased so a
   * self-reference erases to one object rather than recursing without end.
   */
  erasures = new Map<i32, Type>();

  /** `eraseTypeArgument` results, by the input's uid. */
  argumentErasures = new Map<i32, Type>();

  /**
   * The interned types this module's codegen builds unions through.
   * The generator sets it to the checker's, so the compile's unions
   * share identity across checking and codegen; a module generated
   * without one (the tests build generators directly) interns on its
   * own, which only loses the sharing.
   */
  var interner = new TypeInterner();

  /**
   * `substituteTypeParamsInCodegen` results, by the input's uid and
   * then by the parameter and argument uids; see the memo there.
   */
  substitutionResults = new Map<i32, TypeListTable>();

  /**
   * The result table for input `t`, created on first use: a table
   * keyed by the parameters' uids, then the arguments'.
   */
  substitutionResultsFor(t: Type): TypeListTable {
    if (let (true, existing) = this.substitutionResults.get(t.uid)) {
      return existing;
    }
    let fresh = new TypeListTable();
    this.substitutionResults[t.uid] = fresh;
    return fresh;
  }

  /**
   * Whether to emit the wide-arithmetic proposal's instructions
   * natively (`i64.mul_wide_u` and friends, 0xFC 19..22) instead of
   * the equivalent 32-bit-halves sequences.
   *
   * Off by default: wasmtime, wasmi, JavaScriptCore and SpiderMonkey
   * implement the proposal, V8 does not, and the stdlib has to run
   * under `node`. `lowerWideArith` builds both lowerings from the same
   * operands and they agree on every input, so the flag changes the
   * emitted bytes and the speed, not the values.
   */
  var wideArithmetic: boolean = false;

  /**
   * Whether `debug` contract clauses are compiled
   * (docs/design/contracts.md). On for a test build and a debug build;
   * otherwise a `debug requires (c)` is type-checked and emits nothing.
   * Reachability and lowering both ask `runsContractClause`, since one
   * registers what the other emits a call to.
   */
  var debugContracts: boolean = false;

  /**
   * Whether `clause` is checked at run time in this build. A `static`
   * clause never is: it is a specification for a verifier, type-checked
   * and emitted nowhere.
   */
  runsContractClause(clause: ContractClause): boolean {
    return match (clause.mode) {
      case ContractMode.Checked: true
      case ContractMode.Debug: this.debugContracts
      case ContractMode.Static: false
    };
  }

  /** Whether `contracts` holds an `ensures` clause this build checks. */
  runsEnsuresClause(contracts: GrowableArray<ContractClause> | null): boolean {
    if (contracts == null) { return false; }
    for (let clause in contracts) {
      if (clause.kind == ContractKind.Ensures && this.runsContractClause(clause)) {
        return true;
      }
    }
    return false;
  }

  var types = new Array<WasmType>();
  tags = new Array<WasmTag>();
  exportTagMap = new Map<String, WasmTag>();
  var exceptionTag: WasmTag | null = null;
  var exceptionPayload: WasmGlobal | null = null;
  var cancellationTag: WasmTag | null = null;
  /**
   * The async half of the cancellation gate: the program can cause a
   * scope cancellation, so async frames carry scopes, checkpoints,
   * and wake registration. Distinct from the tag's existence, because
   * generator disposal mints the tag without any of that — the scope
   * methods the async split pass resolves exist only when RTA queued
   * them under this flag.
   */
  var scopeCancellationActive: boolean = false;
  /**
   * The generator half: a reached protocol `for`-in plus a reached
   * generator make disposal possible, so generator frames carry the
   * `$disposing` machinery and protocol loops the disposal finalizer.
   */
  var generatorDisposalActive: boolean = false;
  /**
   * The common supertype of every generator frame struct, minted when
   * disposal is active: the for-in disposal finalizer tests and casts
   * against it, so `$state` and `$disposing` sit at a shape every
   * generator shares whatever its own spill fields are.
   */
  var generatorFrameSuper: WasmStruct | null = null;
  var isLayoutLocked: boolean = false;
  var startFunction: WasmFunction | null = null;
  
  /** 
   * A complete list of all imported functions.
   */
  functionImports = new Array<WasmFunction>();

  /**
   * Replaces the import lists with the same imports in another order,
   * and rebinds indices to match.
   */
  reorderImports(functionImports: GrowableArray<WasmFunction>,
      globalImports: GrowableArray<WasmGlobal>): void {
    this.functionImports.clear();
    for (let f in functionImports) {
      this.functionImports.push(f);
    }
    this.globalImports.clear();
    for (let g in globalImports) {
      this.globalImports.push(g);
    }
    this.bindIndices();
  }

  /** 
   * A complete list of all functions in the module, including anonymous
   * functions that do not have a corresponding symbol. Array order dictates
   * the final WebAssembly function index.
   */
  var functions = new Array<WasmFunction>();
  
  globals = new Array<WasmGlobal>();
  globalImports = new Array<WasmGlobal>();
  importedStringGlobals = new HashMap<String, WasmGlobal>();
  /**
   * The `context.get`/`context.set` wrappers of each field decorator
   * application that reads its `context`, keyed by the application's
   * intermediate class key plus `::get` or `::set`.
   */
  decoratorContextWrappers = new HashMap<String, WasmFunction>();
  importedStringWrappers = new HashMap<String, WasmGlobal>();
  /** The import module of every string literal's global. */
  var importedStringConstants = defaultImportedStringConstants;

  getImportedStringGlobal(value: String, model: SemanticModel): WasmGlobal {
    if (let (true, g) = this.importedStringGlobals.get(value)) {
      return g;
    }
    let name = "_str_" + i32ToString(this.globalImports.length);
    let g = new WasmGlobal(name, name, new ValTypeRefExtern(), false, null, null, model);
    g.isImport = true;
    g.type = new ValTypeRefExtern();
    g.importModule = this.importedStringConstants;
    g.importName = value;
    this.globalImports.push(g);
    this.importedStringGlobals[value] = g;
    return g;
  }

  getImportedStringWrapperGlobal(value: String, model: SemanticModel): WasmGlobal {
    if (let (true, gw) = this.importedStringWrappers.get(value)) {
      return gw;
    }
    this.getImportedStringGlobal(value, model);
    let sKey = getClassKey(this.stringClass as ClassType);
    let info = this.classInfos[sKey];
    let stringStruct = info.structType;
    let name = "_str_wrap_" + i32ToString(this.importedStringWrappers.size);
    let gw = new WasmGlobal(name, name, new ValTypeRefNull(stringStruct), true, null, null, model);
    this.globals.push(gw);
    this.importedStringWrappers[value] = gw;
    return gw;
  }



  /**
   * Maps a Zena symbol ID to its compiled WebAssembly function.
   * Used to resolve call targets. Anonymous functions will not be in this map.
   */
  functionMap = new Map<SymbolId, WasmFunction>();
  /**
   * Maps `<symId>$<paramTypeKeys>` to the compiled WebAssembly function for
   * each overload of a top-level `function` declaration.
   */
  overloadedFunctionMap = new Map<String, WasmFunction>();
  /**
   * The node ids of calls whose record result is only read for its
   * fields (ir/explode.zena): lowering calls the callee's core there and
   * holds the result as fields.
   */
  fieldsOnlyResultCalls = new Set<i32>();
  /**
   * The `var` locals held as their fields (ir/explode.zena), with their
   * record's dispatch: lowering carries them through joins as one value
   * per field.
   */
  fieldHeldVars = new Map<SymbolId, RecordDispatchInfo>();
  
  /**
   * Maps a Zena AST Node ID to its compiler intrinsic name (e.g. `memory.size`).
   */
  intrinsics = new Map<NodeId, String>();

  globalMap = new Map<SymbolId, WasmGlobal>();

  var program: Program | null = null;
  var target: String = "";
  var stringClass: ClassType | null = null;
  var templateStringsArrayClass: ClassType | null = null;
  var bigIntClass: ClassType | null = null;
  var errorClass: ClassType | null = null;
  exportMap = new Map<ExportKey, WasmFunction>();
  exportGlobalMap = new Map<ExportGlobalKey, WasmGlobal>();
  classInfos = new Map<ClassKey, ClassCodegenInfo>();
  /**
   * Vtable method-name lists for specialized classes, keyed by class key.
   * The vtable belongs to the specialized class itself, not to whichever
   * ClassType instance mentions it: many instances share one class key, and
   * keeping this state per key (instead of mutating ClassType.vtable on
   * instances) lets substitution share instantiation objects safely.
   */
  vtables = new Map<ClassKey, GrowableArray<String>>();
  interfaceStructs = new Map<InterfaceKey, WasmStruct>();
  interfaceVTableStructs = new Map<InterfaceKey, WasmStruct>();
  /** One entry per emitted rec group, in emission order; a size of 1
   * emits the bare (header-free) form. Set by layout(). */
  var typeRecGroupSizes = new Array<i32>();
  classInterfaceVTables = new Map<ClassInterfaceKey, WasmGlobal>();
  #signatureCache = new Map<SignatureKey, WasmSignature>();
  #structCache = new Map<StructKey, WasmStruct>();
  /**
   * Interned structs with no name — boxed tuples and records. Lowered
   * bodies reference them directly and run after layout, so nothing in
   * a signature roots them; RTA roots this list wholesale, like
   * closure structs.
   */
  anonymousStructs = new Array<WasmStruct>();
  #arrayCache = new Map<ArrayKey, WasmArray>();
  /**
   * The class-interface pairs whose vtable reachable code reads, by
   * specialization: packing a `Box<i32>` into `Shape<i32>` marks that
   * pair and no other specialization of `Box`, and so does a type test
   * a `Box<i32>` answers. The vtable phase builds a pair's vtable, and a
   * trampoline per slot, only for a pair marked here (#815).
   */
  usedInterfaceAdaptations = new HashSet<ClassInterfaceKey>();
  /**
   * Interface type tests (`x is I`, `x as I`, `case I`) whose operand
   * is not statically `I`, as the discovery walks record them. The
   * analysis turns them into `typeTestPairs` once it knows which
   * classes exist (#markTypeTestPairs), and lays out the type-info
   * tables that answer them (#layoutTypeTests). See
   * docs/design/interface-type-tests.md.
   */
  typeTestSites = new Array<TypeTestSite>();
  /**
   * The slot of each tested interface in the `TypeInfo` struct: the
   * interfaces with more than `typeTestChainMax` candidate pairs. The
   * rest are in `typeTestChained`, tested by a chain of class tests.
   */
  typeTestSlots = new Map<InterfaceKey, i32>();
  /** The tested interfaces with a slot, in slot order. */
  typeTestSlotInterfaces = new Array<InterfaceType>();
  /** The tested interfaces answered by a chain of class tests (#layoutTypeTests). */
  typeTestChained = new Map<InterfaceKey, InterfaceType>();
  /** The (class, interface) pairs some test can answer true for. */
  typeTestPairs = new Map<ClassInterfaceKey, boolean>();
  /** The classes in `typeTestPairs`, in classInfos order. */
  typeTestClasses = new Map<ClassKey, ClassType>();
  /** The classes some test reaches through a non-class operand. */
  typeTestOpenClasses = new Map<ClassKey, boolean>();
  /** Whether some test's operand can hold a fat pointer of any interface. */
  var typeTestOpenSite = false;
  /**
   * The struct with one slot per tested interface, holding the
   * class-interface vtable for a class that implements it and null
   * for one that does not; null until a test exists.
   */
  var typeInfoStruct: WasmStruct | null = null;
  /** The supertype of every candidate hierarchy's root vtable struct: one `<typeinfo>` field. */
  var vtableBaseStruct: WasmStruct | null = null;
  /** The supertype of every candidate hierarchy's root class struct: one `<vtable>` field typed by `vtableBaseStruct`. */
  var objectStruct: WasmStruct | null = null;
  /** The supertype of every interface fat pointer struct: the `instance` field. */
  var fatPointerBaseStruct: WasmStruct | null = null;
  /** Each candidate class's `TypeInfo` global. */
  typeInfoGlobals = new Map<ClassKey, WasmGlobal>();
  classMethodMap = new Map<ClassMethodKey, WasmFunction>();
  staticMethodMap = new Map<ClassMethodKey, WasmFunction>();
  classMethods = new Map<String, GrowableArray<WasmFunction>>();

  methodMap(isStatic: boolean): HashMap<ClassMethodKey, WasmFunction> {
    return if (isStatic) this.staticMethodMap else this.classMethodMap;
  }
  var stringHashHelper: WasmFunction | null = null;
  functionAdaptations = new Map<FunctionAdaptationKey, WasmFunction>();
  /**
   * The values each function-adaptation wrapper that needs any packs
   * into an interface (see AdaptationPack). Kept off WasmFunction: few
   * wrappers pack anything, and one more field there would make every
   * function's object 16 bytes larger (docs/design/compiler-memory.md).
   */
  functionAdaptationPacks = new Map<WasmFunction, GrowableArray<AdaptationPack>>();
  var arrayMethods = new Array<WasmFunction>();
  
  /**
   * The vtable global registered for exactly this (class, interface) pair,
   * or null. There is deliberately no fuzzy fallback here: a miss means the
   * key derivation at the call site disagrees with the key derivation at
   * registration, which is a bug to surface, not to paper over. (A previous
   * fallback matched entries by `_`-suffix prefix, which is not unique
   * across specializations — Foo would match both Foo_i32 and Foo_string —
   * and it had trapped unconditionally since the compound-key migration,
   * proving no passing path ever needed it.)
   */
  getClassInterfaceVTable(key: ClassInterfaceKey): WasmGlobal | null {
    if (this.classInterfaceVTables.has(key)) {
      return this.classInterfaceVTables[key];
    }
    return null;
  }

  #stdlibFuncCache = new Map<String, WasmFunction>();

  /**
   * The emitted function a standard library export lowers to, or null.
   *
   * Keyed on the owning LIBRARY rather than a module id, and every file
   * of that library is searched — the same rule the rooting walk in
   * `reachability/visitor.zena` uses, and for the same reason: a
   * library's declarations move between its files, and a re-export shim
   * at an old path declares nothing this search can see. The two must
   * agree, because one roots what the other emits a call to.
   */
  getStdlibFunc(library: String, exportName: String): WasmFunction | null {
    let key = `${library}::${exportName}`;
    if (this.#stdlibFuncCache.has(key)) {
      return this.#stdlibFuncCache[key];
    }
    let prog = this.program;
    if (prog == null) { return null; }
    for (let unit in prog.units) {
      let owner = stdlibLibraryOf(unit.ast.path);
      if (owner == null || !stdlibLibraryAnswers(owner as String, library)) {
        continue;
      }
      let found = this.#findStdlibFuncIn(unit, key, exportName);
      if (found != null) {
        return found;
      }
    }
    return null;
  }

  /**
   * A top-level function of the unit at `path`, by name, or null. For
   * modules the compiler wrote itself (the component entry wrapper),
   * which are not stdlib libraries and not the entry, so neither
   * lookup above reaches them.
   */
  getUnitFunc(path: String, name: String): WasmFunction | null {
    let key = `${path}::${name}`;
    if (this.#stdlibFuncCache.has(key)) {
      return this.#stdlibFuncCache[key];
    }
    let prog = this.program;
    if (prog == null) { return null; }
    for (let unit in prog.units) {
      if (unit.ast.path != path) { continue; }
      return this.#findStdlibFuncIn(unit, key, name);
    }
    return null;
  }

  #findStdlibFuncIn(unit: CompilationUnit, key: String,
      exportName: String): WasmFunction | null {
    for (let stmt in unit.ast.body) {
      match (stmt) {
        case DeclareFunction as df: {
          if (df.name.name == exportName) {
            let sym = unit.model.resolveDeclaration(df);
            if (sym != null && this.functionMap.has(sym.id)) {
              let f = this.functionMap[sym.id];
              this.#stdlibFuncCache[key] = f;
              return f;
            }
          }
        }
        case VariableDeclaration as vd: {
          if (vd.pattern is IdentifierPattern) {
            let pat = vd.pattern as IdentifierPattern;
            if (pat.name == exportName) {
              let sym = unit.model.resolve(pat);
              if (sym != null && this.functionMap.has(sym.id)) {
                let f = this.functionMap[sym.id];
                this.#stdlibFuncCache[key] = f;
                return f;
              }
            }
          }
        }
        case FunctionDeclaration as fd: {
          if (fd.name.name == exportName) {
            let sym = unit.model.resolve(fd.name);
            if (sym != null && this.functionMap.has(sym.id)) {
              let f = this.functionMap[sym.id];
              this.#stdlibFuncCache[key] = f;
              return f;
            }
          }
        }
        case _: {}
      }
    }
    return null;
  }

  mutableCapturedSymbols = new Set<SymbolId>();
  
  datas = new Array<ByteBuffer>();
  rawDatas = new Array<ByteBuffer>();
  stringLiterals = new Map<String, i32>();
  stringLiteralIds = new Map<String, i32>();
  bigIntLiteralGlobals = new Map<String, WasmGlobal>();
  stringLiteralLocations = new Map<String, StringLiteralLocation>();
  var sharedStringsGlobal: WasmGlobal | null = null;
  var stringFromSharedFunc: WasmFunction | null = null;
  var stringLiteralsArrayGlobal: WasmGlobal | null = null;
  var getStringLiteralFunc: WasmFunction | null = null;
  var stringArrayType: WasmArray | null = null;
  var sharedStringsDataIdx: i32 = -1;
  var sharedStringsLength: i32 = 0;
  var hasMemory: boolean = false;
  var stringHashFunc: WasmFunction | null = null;
  /**
   * `$erasedEq(a, b)`: equality of two references whose class is not known
   * statically, dispatched to the runtime class's `operator ==`
   * (ir/equality.zena, lowerErasedEqDispatch).
   */
  var erasedEqFunc: WasmFunction | null = null;
  /**
   * The structural `==` functions over pairs of record or tuple types,
   * by `valueEqKey` (value-equality.zena). Reachability adds one per
   * pair a reached `==` compares, and per pair of nested fields.
   */
  valueEqFuncs = new Map<String, WasmFunction>();
  /**
   * The hash functions of record and tuple types, by `valueHashKey`.
   * Reachability adds one per type a reached `hash<T>` intrinsic hashes,
   * and per nested record or tuple field.
   */
  valueHashFuncs = new Map<String, WasmFunction>();
  /**
   * Set by RTA when String is genuinely instantiated. The `$string*`
   * host-interop helpers are synthesized against String's struct
   * layout and exist to hand String values across the host boundary,
   * so they follow instantiation — declaration is not evidence, since
   * every program declares String through the prelude.
   */
  var stringClassIsInstantiated = false;
  /**
   * Which DIRECTIONS the host boundary moves strings in. Writes = the
   * host builds a guest String ($stringCreate/$stringSetByte): an
   * entry-unit export takes a String(-containing) parameter, a
   * reached host import returns one, or the exception infrastructure
   * exists (the host builds trace messages). Reads = the host
   * consumes one ($stringGetByte/$stringGetLength): an export returns
   * a String, or a reached host import takes one. A program whose
   * boundary only RETURNS a string ships only the read half.
   */
  var hostWritesStrings = false;
  var hostReadsStrings = false;
  /**
   * The same evidence for the component target: a String crosses one of
   * this module's exports, so `zena:wasi` is rooted and the
   * lifts carry the memory options.
   *
   * Separate from the two above because the boundaries are different.
   * The `$string*` helpers hand a String to an embedder holding the core
   * module; a component's host never sees the core module, and its
   * strings cross as bytes in linear memory. Setting both would emit
   * four exports a component cannot call.
   */
  var componentMovesStrings = false;
  var stringCreateFunc: WasmFunction | null = null;
  var stringSetByteFunc: WasmFunction | null = null;
  var stringGetByteFunc: WasmFunction | null = null;
  /**
   * The split async-main entry for hosts that cannot wait (async.md §4):
   * start the body and park its future, then unwrap it once pings have
   * driven it to completion. Null unless the program has an async main.
   */
  var asyncMainStartFunc: WasmFunction | null = null;
  var asyncMainResultFunc: WasmFunction | null = null;
  /**
   * The component target's async entry point and the callback the host
   * re-enters it through, present exactly when the program links a
   * driver that needs one (today: `zena:time`'s p3 clock). Null
   * otherwise, and then the entry is lifted synchronously.
   */
  var componentEntryFunc: WasmFunction | null = null;
  var componentCallbackFunc: WasmFunction | null = null;
  /**
   * The component type of the value the async entry returns through
   * `task.return`, or -1 when it returns nothing. Set with the entry
   * (component-adapters.zena) from what the program's `main` resolves
   * to; the shape puts it on the entry's lifted type.
   */
  var componentEntryResult = -1;
  /**
   * The declared world's async exports, each the adapter the
   * component lifts with the callback (component-adapters.zena), in
   * the order the entry wrapper declares them.
   */
  componentAsyncExports = new Array<ComponentAsyncExport>();
  /** The declared world's wrapped synchronous exports, on the
   * component target. */
  componentSyncExports = new Array<ComponentSyncExport>();
  /** The destructors of the resources the program provides. */
  componentResourceDtors = new Array<ComponentResourceDtor>();
  /**
   * The `$componentExport` wrapper for each export whose signature
   * carries a `string`, keyed by the export's own name. An export with
   * only flat scalars has none and is lifted directly; the map is empty
   * for every other target.
   */
  var componentExportWrappers = new Map<ExportKey, WasmFunction>();
  /**
   * `zena:wasi`'s allocator and its `post-return`, exported
   * from the core module under the names the canonical options use.
   * Present exactly when something in the component moves a `string`.
   */
  var componentReallocFunc: WasmFunction | null = null;
  var componentPostReturnFunc: WasmFunction | null = null;
  var stringGetLengthFunc: WasmFunction | null = null;
  
  recordDispatchInfos = new Array<RecordDispatchInfo>();
  adaptedDispatchInfos = new Array<RecordDispatchInfo>();
  /** Existential record types' dispatches (`getExistentialDispatch`). */
  existentialDispatchInfos = new Array<RecordDispatchInfo>();
  /** Boxed tuples' structs, one per group (`getTupleStruct`). */
  #tupleGroups = new HashMap<TupleGroupKey, TupleGroup>();
  /** The same groups, in the order they were made, for `settleTupleSlots`. */
  #tupleGroupList = new Array<TupleGroup>();
  var #tupleSlotsSettled = false;
  /** Union-find parents over tuple representations (exact element types). */
  #tupleParents = new HashMap<StructKey, StructKey>();
  /** The union-find classes some group's struct was made for. */
  #tupleComponentsWithStructs = new HashSet<StructKey>();
  /** Each mapped tuple type's representation, by `getTypeKeyForSpecialization`. */
  #tuplePreciseOf = new HashMap<String, StructKey>();
  /** Joins waiting for a tuple type to be mapped, both ways, by type key. */
  #tuplePending = new HashMap<String, GrowableArray<String>>();
  /** Per compilation unit, how much of its tuple notes `noteTupleJoins` read. */
  #tupleCursors = new Array<TupleNoteCursor>();
  #erasedTuples = new Array<TupleType>();
  #testedTuples = new Array<TupleType>();
  /** Boxed tuples' stand-in dispatches, by tuple struct (`getTupleDispatch`). */
  tupleDispatchInfos = new HashMap<WasmStruct, RecordDispatchInfo>();
  /** Tables that pack a record into an existential (`getExistentialPack`). */
  existentialPacks = new Array<RecordForwardTable>();
  /** Tables reading a closed record through another fat pointer (`getForwardDispatch`). */
  forwardTables = new Array<RecordForwardTable>();
  /** The next record shape id (`RecordDispatchInfo.shapeId`). */
  var recordShapeCount = 0;
  
  cellStructs = new Map<CellKey, WasmStruct>();
  closureStructs = new Map<ClosureKey, WasmStruct>();
  closureFunctions = new NodeMap<WasmFunction>();
  specializedClosures = new Map<ClosureSpecializationKey, WasmFunction>();
  functionValueWrappers = new Map<FunctionValueWrapperKey, WasmFunction>();
  templateLiteralGlobals = new NodeMap<WasmGlobal>();
  genericFunctions = new Map<SymbolId, FunctionExpression>();
  genericFunctionModels = new Map<SymbolId, SemanticModel>();
  genericMethods = new Map<ClassMethodKey, MethodDefinition>();
  genericMethodModels = new Map<ClassMethodKey, SemanticModel>();
  specializedFunctions = new Map<SpecializedFunctionKey, WasmFunction>();
  
  functionAdaptationWrappers = new NodeMap<WasmFunction>();
  symbolNames = new Map<SymbolId, String>();
  
  /** A record dispatch whose fat pointer is `st`, or null when `st` is not one. */
  recordDispatchOfFatPointer(st: WasmStruct): RecordDispatchInfo | null {
    for (let info in this.recordDispatchInfos) {
      if (info.fatPtrType === st) {
        return info;
      }
    }
    return null;
  }

  findRecordDispatch(fields: GrowableArray<WasmField>, optionalNames: GrowableArray<String>): RecordDispatchInfo | null {
    for (let info in this.recordDispatchInfos) {
      if (info.fields.length == fields.length &&
          stringArraysEqual(info.optionalNames, optionalNames)) {
        var match = true;
        for (var i = 0; i < fields.length; i += 1) {
          if (info.fields[i].name != fields[i].name || !valTypeEquals(info.fields[i].type, fields[i].type)) {
            match = false;
            break;
          }
        }
        if (match) return info;
      }
    }
    return null;
  }
  
  findAdaptedDispatch(inFields: GrowableArray<WasmField>, inOptionalNames: GrowableArray<String>, outFields: GrowableArray<WasmField>, outOptionalNames: GrowableArray<String>): RecordDispatchInfo | null {
    for (let info in this.adaptedDispatchInfos) {
      if (!stringArraysEqual(info.optionalNames, outOptionalNames) ||
          !stringArraysEqual(info.inOptionalNames, inOptionalNames)) {
        continue;
      }
      let s = info.concreteType;
      var inMatch = false;
      if (s.fields.length == inFields.length) {
        inMatch = true;
        for (var i = 0; i < inFields.length; i += 1) {
          if (s.fields[i].name != inFields[i].name || !valTypeEquals(s.fields[i].type, inFields[i].type)) {
            inMatch = false;
            break;
          }
        }
      }
      if (inMatch && info.fields.length == outFields.length) {
        var outMatch = true;
        for (var i = 0; i < outFields.length; i += 1) {
          if (info.fields[i].name != outFields[i].name || !valTypeEquals(info.fields[i].type, outFields[i].type)) {
            outMatch = false;
            break;
          }
        }
        if (outMatch) {
          return info;
        }
      }
    }
    return null;
  }
  
  /**
   * Gets an existing WasmSignature if one matches the given parameters and
   * returns, or creates a new one and adds it to the type pool.
   *
   * Deduplicates by SignatureKey so identical signatures share the same
   * WebAssembly type index.
   */
  getSignature(params: GrowableArray<ValType>, returns: GrowableArray<ValType>): WasmSignature {
    let key = getSignatureKey(params, returns);
    if (let (true, cached) = this.#signatureCache.get(key)) {
      return cached;
    }
    if (this.isLayoutLocked) {
      var pStr = "";
      for (let p in params) {
        pStr = pStr + match (p) {
          case ValTypeRef as r: {
            if (r.target is WasmStruct) {
              let s = r.target as WasmStruct;
              `ref_${if (s.name == null) "anon" else s.name as String}(uid=${i32ToString(s.uid)},idx=${i32ToString(s.index)})`
            } else {
              `ref_non_struct(uid=${i32ToString(r.target.uid)},idx=${i32ToString(r.target.index)})`
            }
          }
          case ValTypeRefNull as rn: {
            if (rn.target is WasmStruct) {
              let s = rn.target as WasmStruct;
              `refnull_${if (s.name == null) "anon" else s.name as String}(uid=${i32ToString(s.uid)},idx=${i32ToString(s.index)})`
            } else {
              `refnull_non_struct(uid=${i32ToString(rn.target.uid)},idx=${i32ToString(rn.target.index)})`
            }
          }
          case _: i32ToString(valTypeToOpcode(p))
        } + ",";
      }
      var rStr = "";
      for (let r in returns) {
        rStr = rStr + match (r) {
          case ValTypeRef as r: {
            if (r.target is WasmStruct) {
              let s = r.target as WasmStruct;
              `ref_${if (s.name == null) "anon" else s.name as String}(uid=${i32ToString(s.uid)},idx=${i32ToString(s.index)})`
            } else {
              `ref_non_struct(uid=${i32ToString(r.target.uid)},idx=${i32ToString(r.target.index)})`
            }
          }
          case ValTypeRefNull as rn: {
            if (rn.target is WasmStruct) {
              let s = rn.target as WasmStruct;
              `refnull_${if (s.name == null) "anon" else s.name as String}(uid=${i32ToString(s.uid)},idx=${i32ToString(s.index)})`
            } else {
              `refnull_non_struct(uid=${i32ToString(rn.target.uid)},idx=${i32ToString(rn.target.index)})`
            }
          }
          case _: i32ToString(valTypeToOpcode(r))
        } + ",";
      }
      throw new Error(`Signature allocated after layout! Params: ${pStr} Returns: ${rStr}`);
    }
    let sig = new WasmSignature(params, returns);
    this.types.push(sig);
    this.#signatureCache[key] = sig;
    return sig;
  }

  /**
   * A signature needed after layout: the type section is appended a
   * singleton rec group at the next index. Every type the signature
   * names is already laid out, so the new entry refers only to smaller
   * indices, which a later group may do. For the specialization pass,
   * which clones a function with a narrower parameter once the
   * module's types are fixed.
   */
  getSignatureLate(params: GrowableArray<ValType>, returns: GrowableArray<ValType>): WasmSignature {
    let key = getSignatureKey(params, returns);
    if (let (true, cached) = this.#signatureCache.get(key)) {
      return cached;
    }
    let sig = new WasmSignature(params, returns);
    sig.index = this.types.length;
    this.types.push(sig);
    this.typeRecGroupSizes.push(1);
    this.#signatureCache[key] = sig;
    return sig;
  }

  /** The interned signature with these params and results, or null. Never creates one. */
  findSignature(params: GrowableArray<ValType>, returns: GrowableArray<ValType>): WasmSignature | null {
    if (let (true, cached) = this.#signatureCache.get(getSignatureKey(params, returns))) {
      return cached;
    }
    return null;
  }

  /** The interned struct with this name and these fields, or null. Never creates one. */
  findStruct(name: String | null, fields: GrowableArray<WasmField>): WasmStruct | null {
    if (let (true, cached) = this.#structCache.get(getStructKey(name, fields))) {
      return cached;
    }
    return null;
  }

  /**
   * The interned array of this element type, or null. Never creates
   * one. `elementType` is the stored element type, nullable for a
   * reference (`getArray` stores it that way).
   */
  findArray(elementType: ValType, isMutable: boolean): WasmArray | null {
    if (let (true, cached) = this.#arrayCache.get(getArrayKey(elementType, isMutable))) {
      return cached;
    }
    return null;
  }

  getStruct(name: String | null, fields: GrowableArray<WasmField>): WasmStruct {
    let key = getStructKey(name, fields);
    if (let (true, cached) = this.#structCache.get(key)) {
      return cached;
    }
    if (this.isLayoutLocked) {
      var fieldNames = "";
      for (let f in fields) {
        if (f.name != null) {
          fieldNames = `${fieldNames} ${f.name as String}`;
        }
      }
      throw new Error("Struct allocated after layout:" + fieldNames);
    }
    let st = new WasmStruct(name, fields);
    this.types.push(st);
    this.#structCache[key] = st;
    if (name == null) {
      this.anonymousStructs.push(st);
    }
    return st;
  }

  /**
   * The struct a boxed tuple with elements of types `elements` lowers
   * to: one immutable field per element, named by its position, except a
   * zero-width (`void`) element, which has none.
   */
  getTupleStruct(tt: TupleType, elements: GrowableArray<ValType>): WasmStruct {
    // The tuple's exact representation, and the joins waiting for it.
    let exact = new Array<WasmField>(elements.length);
    for (var i = 0; i < elements.length; i += 1) {
      if (!(elements[i] is ValTypeVoid)) {
        exact.push(new WasmField(i32ToString(i), elements[i], false));
      }
    }
    let precise = new StructKey(null, exact);
    let semantic = getTypeKeyForSpecialization(tt);
    if (!this.#tuplePreciseOf.has(semantic)) {
      this.#tuplePreciseOf[semantic] = precise;
      if (let (true, partners) = this.#tuplePending.get(semantic)) {
        for (let partner in partners) {
          if (let (true, other) = this.#tuplePreciseOf.get(partner)) {
            this.#joinRepresentations(precise, other);
          }
        }
      }
    }
    let component = this.#findTuple(precise);
    let names = new Array<String>(elements.length);
    let types = new Array<ValType>(elements.length);
    let roots = new Array<String | null>(elements.length);
    let classes = new Array<ClassType | null>(elements.length);
    let nullable = new Array<boolean>(elements.length);
    for (var i = 0; i < elements.length; i += 1) {
      let vt = elements[i];
      if (vt is ValTypeVoid) {
        continue;
      }
      let ct = classOfField(vt);
      names.push(i32ToString(i));
      types.push(vt);
      roots.push(if (ct != null) getClassKey(rootClassOf(ct)) as String else null);
      classes.push(ct);
      nullable.push(vt is ValTypeRefNull);
    }
    let key = new TupleGroupKey(component, names, types, roots);
    if (let (true, group) = this.#tupleGroups.get(key)) {
      this.#widenTupleGroup(group, classes, nullable);
      return group.struct;
    }
    if (this.isLayoutLocked) {
      throw new Error("Tuple struct allocated after layout");
    }
    let fields = new Array<WasmField>(names.length);
    for (var i = 0; i < names.length; i += 1) {
      fields.push(new WasmField(names[i], types[i], false));
    }
    let st = new WasmStruct(null, fields);
    st.isTuple = true;
    this.types.push(st);
    this.anonymousStructs.push(st);
    let members = new Array<GrowableArray<ClassType> | null>(classes.length);
    for (let ct in classes) {
      members.push(if (ct != null) growable<ClassType>([ct]) else null);
    }
    let group = new TupleGroup(st, members, nullable);
    this.#tupleGroups[key] = group;
    this.#tupleGroupList.push(group);
    this.#tupleComponentsWithStructs.add(component);
    return st;
  }

  /**
   * The union-find class of the tuple representation `key`: tuples whose
   * elements have exactly these wasm types, by the class's root.
   */
  #findTuple(key: StructKey): StructKey {
    var k = key;
    while (true) {
      if (let (true, parent) = this.#tupleParents.get(k)) {
        k = parent;
      } else {
        break;
      }
    }
    // Path compression.
    var c = key;
    while (!(c == k)) {
      let next = this.#tupleParents[c];
      this.#tupleParents[c] = k;
      c = next;
    }
    return k;
  }

  /**
   * Joins the tuple types `a` and `b`, of one family, so that they share a
   * struct (`TupleGroupKey`). The join is between their representations,
   * known once each type has been mapped (`getTupleStruct`); until then it
   * waits (`#tuplePending`).
   */
  #joinTuples(a: TupleType, b: TupleType): void {
    if (tupleFamilyKey(a) != tupleFamilyKey(b)) {
      return;
    }
    let ka = getTypeKeyForSpecialization(a);
    let kb = getTypeKeyForSpecialization(b);
    if (ka == kb) {
      return;
    }
    let pa = this.#tuplePreciseOf.get(ka);
    let pb = this.#tuplePreciseOf.get(kb);
    if (let (true, ra) = pa) {
      if (let (true, rb) = pb) {
        this.#joinRepresentations(ra, rb);
        return;
      }
    }
    this.#addPendingTupleJoin(ka, kb);
    this.#addPendingTupleJoin(kb, ka);
  }

  #addPendingTupleJoin(from: String, to: String): void {
    if (let (true, list) = this.#tuplePending.get(from)) {
      list.push(to);
    } else {
      this.#tuplePending[from] = growable<String>([to]);
    }
  }

  /**
   * Joins the classes of two tuple representations. A join between two
   * classes that both already have a struct is refused: the structs were
   * handed out, so a widening between them copies instead
   * (`LoweringContext.copyTuple`).
   */
  #joinRepresentations(a: StructKey, b: StructKey): void {
    let ra = this.#findTuple(a);
    let rb = this.#findTuple(b);
    if (ra == rb) {
      return;
    }
    let aHas = this.#tupleComponentsWithStructs.has(ra);
    let bHas = this.#tupleComponentsWithStructs.has(rb);
    if (aHas && bHas) {
      return;
    }
    // A class with a struct stays the root, so its groups keep their keys.
    if (bHas) {
      this.#tupleParents[ra] = rb;
    } else {
      this.#tupleParents[rb] = ra;
    }
  }

  /**
   * Joins the tuple types the checker found meeting in `units` since the
   * last call (`SemanticModel.tupleWidenings`), and each type an `is` or
   * `as` tests from an erased slot with the erased types of its family
   * (`erasedTupleTypes`, `testedTupleTypes`; #1181). Called before
   * discovery, when no struct exists yet, and again when it ends, for
   * what the bodies it checked on demand added.
   */
  noteTupleJoins(units: GrowableArray<CompilationUnit>): void {
    for (var u = 0; u < units.length; u += 1) {
      let model = units[u].model;
      while (this.#tupleCursors.length <= u) {
        this.#tupleCursors.push(new TupleNoteCursor());
      }
      let cursor = this.#tupleCursors[u];
      while (cursor.widenings < model.tupleWidenings.length) {
        let w = model.tupleWidenings[cursor.widenings];
        this.#joinTuples(w.source, w.target);
        cursor.widenings += 1;
      }
      while (cursor.erased < model.erasedTupleTypes.length) {
        let erased = model.erasedTupleTypes[cursor.erased];
        for (let tested in this.#testedTuples) {
          this.#joinTuples(erased, tested);
        }
        this.#erasedTuples.push(erased);
        cursor.erased += 1;
      }
      while (cursor.tested < model.testedTupleTypes.length) {
        let tested = model.testedTupleTypes[cursor.tested];
        for (let erased in this.#erasedTuples) {
          this.#joinTuples(erased, tested);
        }
        this.#testedTuples.push(tested);
        cursor.tested += 1;
      }
    }
  }

  /**
   * Records a member of `group` whose class-typed fields hold `classes`,
   * nullable where `nullable` says. The fields' types are settled once
   * discovery ends (`settleTupleSlots`); a member that would widen one
   * after that is a compiler error, since lowering has read them.
   */
  #widenTupleGroup(group: TupleGroup, classes: GrowableArray<ClassType | null>,
      nullable: GrowableArray<boolean>): void {
    for (var i = 0; i < classes.length; i += 1) {
      let have = group.classes[i];
      let add = classes[i];
      if (have == null || add == null) {
        continue;
      }
      var known = false;
      for (let ct in have) {
        if (getClassKey(ct) == getClassKey(add)) {
          known = true;
        }
      }
      if (known && (group.nullable[i] || !nullable[i])) {
        continue;
      }
      if (this.#tupleSlotsSettled && !this.#tupleSlotHolds(group, i, add, nullable[i])) {
        throw new Error(`Tuple field ${i} widened after discovery, by ${getClassKey(add) as String}`);
      }
      if (!known) {
        have.push(add);
      }
      group.nullable[i] = group.nullable[i] || nullable[i];
    }
  }

  /** The struct of class `ct`. */
  #classStruct(ct: ClassType): WasmStruct {
    if (let (true, info) = this.classInfos.get(getClassKey(ct))) {
      return info.structType;
    }
    throw new Error(`A tuple field holds a class with no struct: ${getClassKey(ct) as String}`);
  }

  /** Whether field `i` of the settled `group` holds a `ct`, nullable when `isNull`. */
  #tupleSlotHolds(group: TupleGroup, i: i32, ct: ClassType, isNull: boolean): boolean {
    let vt = group.struct.fields[i].type;
    let target = refTargetOf(vt);
    if (isNull && !(vt is ValTypeRefNull) && !(vt is ValTypeStructRef)) {
      return false;
    }
    if (vt is ValTypeStructRef) {
      return true;
    }
    var s: WasmStruct | null = this.#classStruct(ct);
    while (s != null) {
      if (s === target) {
        return true;
      }
      s = s.superStruct;
    }
    return false;
  }

  /**
   * Gives every tuple group's class-typed fields their final types, once
   * discovery has registered every tuple type the module uses and every
   * class's struct: the lowest struct the members' classes' structs all
   * extend, nullable when a member's field is, or `structref` when they
   * share none. A struct chain need not follow the classes' own: a
   * resource class extends `Resource`, and its struct does not. Lowering
   * then reads the fields, casting an element to its own type where that
   * is narrower.
   */
  settleTupleSlots(): void {
    for (let group in this.#tupleGroupList) {
      for (var i = 0; i < group.classes.length; i += 1) {
        let members = group.classes[i];
        if (members == null) {
          continue;
        }
        let structs = new Array<WasmStruct>();
        for (let ct in members) {
          structs.push(this.#classStruct(ct));
        }
        let common = commonSuperStruct(structs);
        group.struct.fields[i].type = if (common == null) new ValTypeStructRef() as ValType
            else if (group.nullable[i]) new ValTypeRefNull(common) as ValType
            else new ValTypeRef(common) as ValType;
      }
    }
    this.#tupleSlotsSettled = true;
  }

  getClosureStruct(params: GrowableArray<ValType>, returns: GrowableArray<ValType>): WasmStruct {
    let implParams = growable<ValType>([new ValTypeStructRef()]);
    for (let p in params) {
      implParams.push(p);
    }
    let implSig = this.getSignature(implParams, returns);
    
    let fields = growable<WasmField>([
      new WasmField("func", new ValTypeRef(implSig), false),
      new WasmField("ctx", new ValTypeStructRef(), false),
    ]);
    
    return this.getStruct(null, fields);
  }
  
  getRecordDispatch(model: SemanticModel, fields: GrowableArray<WasmField>, optionalNames: GrowableArray<String>): RecordDispatchInfo {
    sortWasmFields(fields);

    let existing = this.findRecordDispatch(fields, optionalNames);
    if (existing != null) {
      return existing;
    }
    if (this.isLayoutLocked) {
      throw new Error("Struct allocated after layout");
    }
    
    let concreteType = this.getStruct(null, fields);
    let vtableFields = new Array<WasmField>();
    let getterTypes = new Array<WasmSignature>();
    let getters = new Array<WasmFunction>();
    
    for (var i = 0; i < fields.length; i += 1) {
      let getterValType = fields[i].type;
      
      let params = growable<ValType>([new ValTypeStructRef()]);
      
      let returns = new Array<ValType>();
      if (!(getterValType is ValTypeVoid)) {
        returns.push(getterValType);
      }
      
      let getterType = this.getSignature(params, returns);
      getterTypes.push(getterType);
      
      let getterFunc = new WasmFunction(getterType, null, model);
      getterFunc.getterStruct = concreteType;
      getterFunc.getterFieldIndex = i;
      this.addFunction(getterFunc);
      getters.push(getterFunc);
      
      vtableFields.push(new WasmField(
        fields[i].name,
        new ValTypeRef(getterType),
        false
      ));
    }
    vtableFields.push(new WasmField(recordShapeFieldName, new ValTypeI32(), false));

    let vtableType = this.getStruct(null, vtableFields);

    let fatPtrFields = growable<WasmField>([
      new WasmField(null, new ValTypeStructRef(), false),
      new WasmField(null, new ValTypeRef(vtableType), false),
    ]);

    let fatPtrType = this.getStruct(null, fatPtrFields);

    let shapeId = this.recordShapeCount;
    this.recordShapeCount += 1;
    let vtableInit = new VTableInit(vtableType, getters);
    vtableInit.shapeTag = shapeId;
    let vtableGlobal = new WasmGlobal("vtable_record", "vtable_record", new ValTypeRef(vtableType), false, null, vtableInit, model);
    this.globals.push(vtableGlobal);

    let info = new RecordDispatchInfo(fatPtrType, vtableType, concreteType, vtableGlobal, fields, getterTypes, optionalNames, optionalNames);
    info.shapeId = shapeId;
    this.recordDispatchInfos.push(info);

    return info;
  }
  
  /** The registered dispatch of the existential type with these known fields. */
  findExistentialDispatch(fields: GrowableArray<WasmField>, optionalNames: GrowableArray<String>): RecordDispatchInfo | null {
    for (let info in this.existentialDispatchInfos) {
      if (sameRecordFields(info, fields, optionalNames)) {
        return info;
      }
    }
    return null;
  }

  /**
   * The dispatch of the existential record type `{...fields, ...}`: a fat
   * pointer whose table reads the known fields and also returns the
   * closed record held (`<underlying>`), its shape id (`<shapeOf>`) and
   * its hash (`<hash>`) — what `is`, `as`, `==` and `hash` need of a
   * record whose shape only the run time knows. The slots make the table
   * type, and so the fat pointer type, differ from every closed record's.
   */
  getExistentialDispatch(model: SemanticModel, fields: GrowableArray<WasmField>, optionalNames: GrowableArray<String>): RecordDispatchInfo {
    sortWasmFields(fields);
    let existing = this.findExistentialDispatch(fields, optionalNames);
    if (existing != null) {
      return existing;
    }
    if (this.isLayoutLocked) {
      throw new Error("Struct allocated after layout");
    }
    let getterTypes = new Array<WasmSignature>();
    let vtableFields = new Array<WasmField>();
    for (let field in fields) {
      let returns = new Array<ValType>();
      if (!(field.type is ValTypeVoid)) {
        returns.push(field.type);
      }
      let getterType = this.getSignature(growable<ValType>([new ValTypeStructRef()]), returns);
      getterTypes.push(getterType);
      vtableFields.push(new WasmField(field.name, new ValTypeRef(getterType), false));
    }
    for (let slot in existentialSlots(this)) {
      vtableFields.push(slot);
    }
    let vtableType = this.getStruct(null, vtableFields);
    let fatPtrType = this.getStruct(null, growable<WasmField>([
      new WasmField(null, new ValTypeStructRef(), false),
      new WasmField(null, new ValTypeRef(vtableType), false),
    ]));
    let placeholder = new WasmGlobal("vtable_existential", "vtable_existential",
        new ValTypeRef(vtableType), false, null, null, model);
    let info = new RecordDispatchInfo(fatPtrType, vtableType, fatPtrType, placeholder, fields,
        getterTypes, optionalNames, optionalNames);
    info.isExistential = true;
    this.existentialDispatchInfos.push(info);
    return info;
  }

  /**
   * The table packing records of `source` (a closed record's dispatch, or
   * an existential's) into the existential `target`. A packed value's
   * instance is the source value itself, and each slot forwards to it.
   */
  /**
   * The stand-in dispatch through which argument explosion reads and
   * builds the boxed tuples of struct `st` (`RecordDispatchInfo.isTuple`):
   * one per struct, so dispatches compare by identity as records' do.
   */
  getTupleDispatch(model: SemanticModel, st: WasmStruct): RecordDispatchInfo {
    if (let (true, existing) = this.tupleDispatchInfos.get(st)) {
      return existing;
    }
    let placeholder = new WasmGlobal("tuple", "tuple", new ValTypeRef(st),
        false, null, null, model);
    let none = new Array<String>();
    let info = new RecordDispatchInfo(st, st, st, placeholder, st.fields,
        new Array<WasmSignature>(), none, none);
    info.isTuple = true;
    this.tupleDispatchInfos[st] = info;
    return info;
  }

  getExistentialPack(model: SemanticModel, source: RecordDispatchInfo, target: RecordDispatchInfo,
      hashFunc: WasmFunction | null): RecordForwardTable {
    for (let pack in this.existentialPacks) {
      if (pack.source === source && pack.target === target) {
        return pack;
      }
    }
    if (this.isLayoutLocked) {
      throw new Error("Struct allocated after layout");
    }
    let funcs = new Array<WasmFunction>();
    for (var i = 0; i < target.fields.length; i += 1) {
      funcs.push(this.#forwarder(model, target.getterTypes[i],
          new ExistentialForward(source, ForwardKind.Field, target.fields[i].name, null)));
    }
    let structRef = new ValTypeStructRef() as ValType;
    funcs.push(this.#forwarder(model, this.getSignature(growable<ValType>([structRef]), growable<ValType>([structRef])),
        new ExistentialForward(source, ForwardKind.Underlying, null, null)));
    let i32Sig = this.getSignature(growable<ValType>([structRef]), growable<ValType>([new ValTypeI32()]));
    funcs.push(this.#forwarder(model, i32Sig, new ExistentialForward(source, ForwardKind.Shape, null, null)));
    funcs.push(this.#forwarder(model, i32Sig, new ExistentialForward(source, ForwardKind.Hash, null, hashFunc)));
    let vtableGlobal = new WasmGlobal("vtable_pack", "vtable_pack", new ValTypeRef(target.vtableType),
        false, null, new VTableInit(target.vtableType, funcs), model);
    this.globals.push(vtableGlobal);
    let pack = new RecordForwardTable(source, target, vtableGlobal);
    this.existentialPacks.push(pack);
    return pack;
  }

  /**
   * The table reading values of the closed record type `target` through
   * `source`'s fat pointer: a projection of an existential (or, for a
   * run-time `as`, of the closed record it holds) to `target`. Its shape
   * id is `target`'s, since the projection is a value of `target`.
   */
  getForwardDispatch(model: SemanticModel, source: RecordDispatchInfo, target: RecordDispatchInfo): RecordForwardTable {
    for (let table in this.forwardTables) {
      if (table.source === source && table.target === target) {
        return table;
      }
    }
    if (this.isLayoutLocked) {
      throw new Error("Struct allocated after layout");
    }
    let funcs = new Array<WasmFunction>();
    for (var i = 0; i < target.fields.length; i += 1) {
      funcs.push(this.#forwarder(model, target.getterTypes[i],
          new ExistentialForward(source, ForwardKind.Field, target.fields[i].name, null)));
    }
    let init = new VTableInit(target.vtableType, funcs);
    init.shapeTag = target.shapeId;
    let vtableGlobal = new WasmGlobal("vtable_forward", "vtable_forward", new ValTypeRef(target.vtableType),
        false, null, init, model);
    this.globals.push(vtableGlobal);
    let table = new RecordForwardTable(source, target, vtableGlobal);
    this.forwardTables.push(table);
    return table;
  }

  #forwarder(model: SemanticModel, sig: WasmSignature, forward: ExistentialForward): WasmFunction {
    let func = new WasmFunction(sig, null, model);
    func.existentialForward = forward;
    this.addFunction(func);
    return func;
  }

  getAdaptedRecordDispatch(model: SemanticModel, inFields: GrowableArray<WasmField>, inOptionalNames: GrowableArray<String>, outFields: GrowableArray<WasmField>, outOptionalNames: GrowableArray<String>): RecordDispatchInfo {
    sortWasmFields(inFields);
    sortWasmFields(outFields);

    let existing = this.findAdaptedDispatch(inFields, inOptionalNames, outFields, outOptionalNames);
    if (existing != null) {
      return existing;
    }
    if (this.isLayoutLocked) {
      throw new Error("Struct allocated after layout");
    }
      
    let inStructType = this.getStruct(null, inFields);
    let vtableFields = new Array<WasmField>();
    let getterTypes = new Array<WasmSignature>();
    let getters = new Array<WasmFunction>();
    
    for (var i = 0; i < outFields.length; i += 1) {
      let fieldValType = outFields[i].type;
      
      let params = growable<ValType>([new ValTypeStructRef()]);
      
      let returns = new Array<ValType>();
      if (!(fieldValType is ValTypeVoid)) {
        returns.push(fieldValType);
      }
      
      let getterType = this.getSignature(params, returns);
      getterTypes.push(getterType);
      
      let getterFunc = new WasmFunction(getterType, null, model);
      getterFunc.getterStruct = inStructType;

      // Find the corresponding field in the inFields by name
      var inIndex = -1;
      for (var j = 0; j < inFields.length; j += 1) {
        if (inFields[j].name == outFields[i].name) {
          inIndex = j;
          break;
        }
      }

      let outName = outFields[i].name;
      if (outName != null && isPresentWordName(outName as String)) {
        // The target's mask derives per bit from the source shape:
        // constant 1 for fields the source holds unconditionally,
        // constant 0 for fields it lacks, the source's own bit where
        // the source also tracks it. The spec covers every word; the
        // getter's word index selects its 64-bit slice.
        let spec = new Array<i32>();
        for (let optName in outOptionalNames) {
          var srcBit = -1;
          for (var j = 0; j < inOptionalNames.length; j += 1) {
            if (inOptionalNames[j] == optName) { srcBit = j; }
          }
          if (srcBit >= 0) {
            spec.push(srcBit);
          } else {
            var inHas = false;
            for (var j = 0; j < inFields.length; j += 1) {
              if (inFields[j].name != null &&
                  (inFields[j].name as String) == optName) {
                inHas = true;
              }
            }
            spec.push(if (inHas) -2 else -1);
          }
        }
        var word = 0;
        let wordCount = presentWordCount(outOptionalNames.length);
        for (var w = 0; w < wordCount; w += 1) {
          if (presentWordName(w) == (outName as String)) { word = w; }
        }
        getterFunc.getterMaskSpec = spec;
        getterFunc.getterMaskWord = word;
        getterFunc.getterFieldIndex = -1;
      } else if (inIndex < 0) {
        var outOptional = false;
        if (outName != null) {
          for (let optName in outOptionalNames) {
            if (optName == (outName as String)) { outOptional = true; }
          }
        }
        if (outOptional) {
          // Absent in the source; the mask reports it, the getter just
          // needs a well-typed placeholder.
          getterFunc.getterReturnsZero = true;
        }
        getterFunc.getterFieldIndex = -1;
      } else {
        getterFunc.getterFieldIndex = inIndex;
      }
      this.addFunction(getterFunc);
      getters.push(getterFunc);
      
      vtableFields.push(new WasmField(
        outFields[i].name,
        new ValTypeRef(getterType),
        false
      ));
    }
    vtableFields.push(new WasmField(recordShapeFieldName, new ValTypeI32(), false));

    let vtableType = this.getStruct(null, vtableFields);

    let fatPtrFields = growable<WasmField>([
      new WasmField(null, new ValTypeStructRef(), false),
      new WasmField(null, new ValTypeRef(vtableType), false),
    ]);

    let fatPtrType = this.getStruct(null, fatPtrFields);

    // A projection: the value is the target shape, whose plain dispatch
    // owns the id.
    let target = this.getRecordDispatch(model, copyFields(outFields), copyStrings(outOptionalNames));
    let vtableInit = new VTableInit(vtableType, getters);
    vtableInit.shapeTag = target.shapeId;
    // TODO: better naming since keyStr is gone
    let vtableGlobal = new WasmGlobal("vtable_adapt", "vtable_adapt", new ValTypeRef(vtableType), false, null, vtableInit, model);
    this.globals.push(vtableGlobal);
    
    // We return information about the TARGET shape (outFields), but with a vtable matching our adapted getters
    let info = new RecordDispatchInfo(fatPtrType, vtableType, inStructType, vtableGlobal, outFields, getterTypes, outOptionalNames, inOptionalNames);
    info.shapeId = target.shapeId;
    this.adaptedDispatchInfos.push(info);
    
    return info;
  }

  /** The shared vtable method-name list for a specialized class key. */
  classVtable(key: ClassKey): GrowableArray<String> {
    if (let (true, existing) = this.vtables.get(key)) {
      return existing;
    }
    let fresh = new Array<String>();
    this.vtables[key] = fresh;
    return fresh;
  }

  /**
   * Each function's index in `functions`, built on first use and
   * dropped whenever the list changes: the ZIR passes that look bodies
   * up by function each rebuilt it per sweep, 4M entries in an -O2
   * compile.
   */
  var #functionIndex: HashMap<WasmFunction, i32> | null = null;

  functionIndex(): HashMap<WasmFunction, i32> {
    let existing = this.#functionIndex;
    if (existing != null) {
      return existing;
    }
    let index = new HashMap<WasmFunction, i32>();
    for (var i = 0; i < this.functions.length; i += 1) {
      index[this.functions[i]] = i;
    }
    this.#functionIndex = index;
    return index;
  }

  /** To call after replacing or reordering `functions` in place. */
  invalidateFunctionIndex(): void {
    this.#functionIndex = null;
  }

  addFunction(func: WasmFunction): void {
    if (func.isAdded) {
      return;
    }
    func.isAdded = true;
    this.functions.push(func);
    this.#functionIndex = null;
    let {classType} = func;
    if (classType != null && func.methodName != null) {
      let key = getClassMethodKey(getClassKey(classType), func.methodName as String);
      this.methodMap(func.isStatic)[key] = func;
      let cKey = getClassKey(classType) as String;
      if (!this.classMethods.has(cKey)) {
        this.classMethods[cKey] = new Array<WasmFunction>();
      }
      this.classMethods[cKey].push(func);
    }
    if (func.isFunctionAdaptation && func.functionAdaptationSource != null && func.functionAdaptationTarget != null) {
      let key = getFunctionAdaptationKey(func.functionAdaptationSource as Type, func.functionAdaptationTarget as Type);
      this.functionAdaptations[key] = func;
    }
    if (func.isClosure) {
      let coalesced1 = func.mutableCaptures ?? noMutableCaptures;
      for (let symId in coalesced1) {
        this.mutableCapturedSymbols.add(symId);
      }
    }
  }

  getArray(elementType: ValType, isMutable: boolean): WasmArray {
    let finalElemType = if (let ValTypeRef {target} = elementType) {
      new ValTypeRefNull(target)
    } else {
      elementType
    };
    let key = getArrayKey(finalElemType, isMutable);
    if (let (true, cached) = this.#arrayCache.get(key)) {
      return cached;
    }
    let arr = new WasmArray(finalElemType, isMutable);
    this.types.push(arr);
    this.#arrayCache[key] = arr;
    // Before reachability has linked class structs to their supertypes
    // the chain cannot be read yet; linkArraySupertypes fills it in
    // for every array interned until then.
    if (!isMutable && this.#arraySupertypesLinked) {
      arr.superArray = this.#immutableArraySuper(finalElemType);
    }
    return arr;
  }

  var #arraySupertypesLinked = false;

  /**
   * Gives every immutable array interned so far its declared supertype
   * (WasmArray.superArray), and every one interned from now on its
   * supertype at creation. Called once reachability analysis has linked
   * class structs to their supertypes, which the chain reads; arrays
   * are interned throughout that analysis, before the links exist.
   */
  linkArraySupertypes(): void {
    this.#arraySupertypesLinked = true;
    // The chain interns supertype arrays as it goes, growing `types`;
    // an index loop visits those too.
    for (let t in this.types) {
      if (t is WasmArray) {
        let arr = t as WasmArray;
        if (!arr.isMutable && arr.superArray == null) {
          arr.superArray = this.#immutableArraySuper(arr.elementType);
        }
      }
    }
  }

  /**
   * The supertype an immutable array declares (see WasmArray.superArray):
   * for an element that is a struct reference, the immutable array of
   * the struct's supertype, or of `anyref` at the top of a hierarchy;
   * for an element that is itself an array, `(array anyref)`. Function
   * references live outside the `anyref` hierarchy and value elements
   * have no subtypes, so those arrays declare none.
   */
  #immutableArraySuper(elementType: ValType): WasmArray | null {
    if (let ValTypeRefNull {target} = elementType) {
      if (target is WasmStruct) {
        let sup = (target as WasmStruct).superStruct;
        if (sup != null) {
          return this.getArray(new ValTypeRefNull(sup), false);
        }
        return this.getArray(new ValTypeAnyRef(), false);
      }
      if (target is WasmArray) {
        return this.getArray(new ValTypeAnyRef(), false);
      }
      return null;
    } else {
      return null;
    }
  }

  getByteArrayType(): WasmArray {
    return this.getArray(new ValTypeI8(), true);
  }

  addData(bytes: ByteBuffer): i32 {
    let segment = new ByteBuffer();
    segment.writeByte(1); // passive flag
    segment.writeULEB128(bytes.length);
    segment.writeBuffer(bytes);
    this.datas.push(segment);
    this.rawDatas.push(bytes);
    return this.datas.length - 1;
  }

  /**
   * Records a string literal for the shared registry. The packed
   * shared segment built at layout is the ONE store for literal
   * bytes: registration creates no per-literal data segment, and
   * every materialization is a zero-copy view into the shared
   * backing array. A literal missing from the registry at codegen
   * time is a discovery bug and fails the compile loudly.
   */
  registerStringLiteral(value: String): void {
    if (!this.stringLiterals.has(value)) {
      this.stringLiterals[value] = -1;
    }
  }

  ensureMemory(): void {
    this.hasMemory = true;
  }
  
  ensureExceptionInfra(model: SemanticModel): void {
    if (this.exceptionTag != null) {
      return;
    }
    
    // The payload type is the stdlib `Error`, found through the class RTA
    // recognized rather than by struct name — a program may declare its own
    // class called `Error`.
    let errorClassOpt = this.errorClass;
    let errorStruct = if (errorClassOpt != null) {
      if (let (true, info) = this.classInfos.get(getClassKey(errorClassOpt))) {
        info.structType
      } else {
        null
      }
    } else {
      null
    };

    let payloadType = if (errorStruct != null) new ValTypeRefNull(errorStruct) else new ValTypeEqRef();
    
    let params = new Array<ValType>();
    let sig = this.getSignature(params, new Array<ValType>());
    
    let tag = new WasmTag(sig);
    this.tags.push(tag);
    this.exceptionTag = tag;
    this.exportTagMap["__zena_exception"] = tag;
    
    let payloadGlobal = new WasmGlobal(
      "__zena_exception_payload",
      "__zena_exception_payload",
      payloadType,
      true,
      null,
      null,
      model
    );
    this.globals.push(payloadGlobal);
    this.exceptionPayload = payloadGlobal;

    if (!targetUsesJsStrings(this.target)) {
      this.hostWritesStrings = true;
      this.ensureStringCreate(model);
      this.ensureStringSetByte(model);
    }
  }

  /**
   * The cancellation channel's tag (docs/design/cancellation.md). No
   * payload and no payload global: `catch (e)` cannot observe a
   * cancellation, so there is nothing to carry. Created by RTA when
   * `cancel.raise` is reached; a program that never raises
   * cancellation gets no second tag, and finalizer regions keep their
   * one-tag shape.
   */
  ensureCancellationInfra(): void {
    if (this.cancellationTag != null) {
      return;
    }
    let sig = this.getSignature(new Array<ValType>(), new Array<ValType>());
    let tag = new WasmTag(sig);
    this.tags.push(tag);
    this.cancellationTag = tag;
    this.exportTagMap["__zena_cancellation"] = tag;
  }

  // The four `$string*` helpers below carry the String as nullable
  // `externref` and cast internally (scaffold.zena's `externToString`
  // does the `any.convert_extern` + `ref.cast`). The type is load-bearing,
  // not incidental: V8's Wasm-into-JS inlining is what makes the host's
  // per-byte loop fast, and Jakob Kummerow (V8) states it triggers only
  // for nullable `externref` — `anyref` is unsupported, and an implicit
  // type check at the boundary is slower than an explicit `ref.cast`
  // inside. Widening these to `anyref` would keep every test passing and
  // silently lose the optimization.
  // https://github.com/WebAssembly/gc/issues/568#issuecomment-2470464481
  // See docs/design/host-interop.md, "Strings".
  ensureStringCreate(model: SemanticModel): void {
    if (this.stringCreateFunc != null) return;
    let createParams = growable<ValType>([new ValTypeI32()]);
    let createReturns = growable<ValType>([new ValTypeExternRef()]);
    let createSig = this.getSignature(createParams, createReturns);
    let createFunc = new WasmFunction(createSig, null, model);
    createFunc.name = "$stringCreate";
    this.addFunction(createFunc);
    this.stringCreateFunc = createFunc;
  }

  ensureStringSetByte(model: SemanticModel): void {
    if (this.stringSetByteFunc != null) return;
    let setByteParams = growable<ValType>([
      new ValTypeExternRef(),
      new ValTypeI32(),
      new ValTypeI32(),
    ]);
    let setByteReturns = new Array<ValType>();
    let setByteSig = this.getSignature(setByteParams, setByteReturns);
    let setByteFunc = new WasmFunction(setByteSig, null, model);
    setByteFunc.name = "$stringSetByte";
    this.addFunction(setByteFunc);
    this.stringSetByteFunc = setByteFunc;
  }

  ensureStringGetByte(model: SemanticModel): void {
    if (this.stringGetByteFunc != null) return;
    let getByteParams = growable<ValType>([
      new ValTypeExternRef(),
      new ValTypeI32(),
    ]);
    let getByteReturns = growable<ValType>([new ValTypeI32()]);
    let getByteSig = this.getSignature(getByteParams, getByteReturns);
    let getByteFunc = new WasmFunction(getByteSig, null, model);
    getByteFunc.name = "$stringGetByte";
    this.addFunction(getByteFunc);
    this.stringGetByteFunc = getByteFunc;
  }

  ensureStringGetLength(model: SemanticModel): void {
    if (this.stringGetLengthFunc != null) return;
    let getLengthParams = growable<ValType>([new ValTypeExternRef()]);
    let getLengthReturns = growable<ValType>([new ValTypeI32()]);
    let getLengthSig = this.getSignature(getLengthParams, getLengthReturns);
    let getLengthFunc = new WasmFunction(getLengthSig, null, model);
    getLengthFunc.name = "$stringGetLength";
    this.addFunction(getLengthFunc);
    this.stringGetLengthFunc = getLengthFunc;
  }

  ensureStringHelpers(model: SemanticModel): void {
    if (targetUsesJsStrings(this.target)) {
      return;
    }
    if (this.hostWritesStrings) {
      this.ensureStringCreate(model);
      this.ensureStringSetByte(model);
    }
    if (this.hostReadsStrings) {
      this.ensureStringGetByte(model);
      this.ensureStringGetLength(model);
    }
  }

  ensureStringLiteralHelpers(model: SemanticModel): void {
    if (this.stringFromSharedFunc != null && this.getStringLiteralFunc != null) {
      return;
    }
    let stringClassOpt = this.stringClass;
    if (stringClassOpt == null) {
      throw new Error("ensureStringLiteralHelpers: String class not recognized!");
    }
    let stringInfoOpt =
        if (let (true, info) = this.classInfos.get(getClassKey(stringClassOpt))) {
          info
        } else {
          null
        };
    if (stringInfoOpt == null) {
      throw new Error("ensureStringLiteralHelpers: String class struct not found!");
    }
    let stringStruct = stringInfoOpt.structType;
    let stringType = new ValTypeRefNull(stringStruct);
    let stringArrayType = this.getArray(stringType, true);
    this.stringArrayType = stringArrayType;

    let arrayValType = new ValTypeRef(stringArrayType);
    let literalsArrayGlobal = new WasmGlobal("string_literals_array", "string_literals_array", arrayValType, false, null, null, model);
    literalsArrayGlobal.initArraySize = this.stringLiterals.size;
    this.globals.push(literalsArrayGlobal);
    this.stringLiteralsArrayGlobal = literalsArrayGlobal;

    let byteArrayStruct = this.getByteArrayType();
    let byteArrayType = new ValTypeRefNull(byteArrayStruct);

    let sharedGlobalName = "shared_strings_data";
    let sharedGlobal = new WasmGlobal(sharedGlobalName, sharedGlobalName, byteArrayType, true, null, null, model);
    this.globals.push(sharedGlobal);
    this.sharedStringsGlobal = sharedGlobal;

    let sigParams = new Array<ValType>();
    sigParams.push(new ValTypeI32()); // offset
    sigParams.push(new ValTypeI32()); // length
    let sigReturns = growable<ValType>([stringType]);

    let sig = this.getSignature(sigParams, sigReturns);
    let helperFunc = new WasmFunction(sig, null, model);
    helperFunc.name = "string_from_shared";
    this.addFunction(helperFunc);
    this.stringFromSharedFunc = helperFunc;

    let getSigParams = growable<ValType>([new ValTypeI32()]); // id
    let getSigReturns = new Array<ValType>();
    let nonNullableStringType = new ValTypeRef(stringStruct);
    getSigReturns.push(nonNullableStringType);

    let getSig = this.getSignature(getSigParams, getSigReturns);
    let getHelperFunc = new WasmFunction(getSig, null, model);
    getHelperFunc.name = "get_string_literal";
    this.addFunction(getHelperFunc);
    this.getStringLiteralFunc = getHelperFunc;
  }

  ensureHashInfra(model: SemanticModel): void {
    if (this.stringHashFunc != null) {
      return;
    }
    // Found through the class RTA recognized, not by struct name: a program
    // may declare its own class called `String`.
    let stringClassOpt = this.stringClass;
    if (stringClassOpt == null) {
      throw new Error("$stringHash discovery: String class not recognized!");
    }
    let stringInfoOpt =
        if (let (true, info) = this.classInfos.get(getClassKey(stringClassOpt))) {
          info
        } else {
          null
        };
    if (stringInfoOpt == null) {
      throw new Error("$stringHash discovery: String class struct not found!");
    }
    let stringStruct = stringInfoOpt.structType;
    let params = growable<ValType>([new ValTypeRefNull(stringStruct)]);
    let returns = growable<ValType>([new ValTypeI32()]);
    let sig = this.getSignature(params, returns);
    let hashFunc = new WasmFunction(sig, null, model);
    hashFunc.name = "$stringHash";
    this.addFunction(hashFunc);
    this.stringHashFunc = hashFunc;
  }

  ensureErasedEqInfra(model: SemanticModel): void {
    if (this.erasedEqFunc != null) {
      return;
    }
    let params = growable<ValType>([new ValTypeEqRef(), new ValTypeEqRef()]);
    let returns = growable<ValType>([new ValTypeI32()]);
    let func = new WasmFunction(this.getSignature(params, returns), null, model);
    func.name = "$erasedEq";
    this.addFunction(func);
    this.erasedEqFunc = func;
  }

  

  /**
   * Locks in the module layout, assigning final WebAssembly indices (i32)
   * to all types, functions, and globals. Must be called after all
   * discoveries are made, but before the emission passes begin.
   */
  layout(): void {
    // console.log("wasm.layout() called! types count = " + i32ToString(this.types.length));
    this.isLayoutLocked = true;
    
    this.classMethodMap.clear();
    this.staticMethodMap.clear();
    this.classMethods.clear();
    this.functionAdaptations.clear();
    this.arrayMethods = new Array<WasmFunction>();
    for (let func in this.functions) {
      let {classType} = func;
      if (classType != null && func.methodName != null) {
        let key = getClassMethodKey(getClassKey(classType), func.methodName as String);
        this.methodMap(func.isStatic)[key] = func;
        let cKey = getClassKey(classType) as String;
        if (!this.classMethods.has(cKey)) {
          this.classMethods[cKey] = new Array<WasmFunction>();
        }
        this.classMethods[cKey].push(func);
      }
      if (func.isFunctionAdaptation && func.functionAdaptationSource != null && func.functionAdaptationTarget != null) {
        let key = getFunctionAdaptationKey(func.functionAdaptationSource as Type, func.functionAdaptationTarget as Type);
        this.functionAdaptations[key] = func;
      }
      if (func.classType != null) {
        let className = (func.classType as ClassType).name;
        if (className == "FixedArray" || className == "ImmutableArray") {
          this.arrayMethods.push(func);
        }
      }
    }
    
    this.layoutTypes();
    for (let rd in this.recordDispatchInfos) {
    }
    for (var i = 0; i < this.tags.length; i += 1) {
      let t = this.tags[i];
      t.index = i;
    }
    this.bindIndices();
  }

  /**
   * Numbers functions and globals by position, imports first, as wasm
   * does. Layout calls it, and so does anything that removes or reorders
   * functions or globals afterwards.
   */
  bindIndices(): void {
    var functionIndex = 0;
    for (let f in this.functionImports) {
      f.index = functionIndex;
      functionIndex += 1;
    }
    for (let f in this.functions) {
      f.index = functionIndex;
      functionIndex += 1;
    }
    var globalIndex = 0;
    for (let g in this.globalImports) {
      g.index = globalIndex;
      globalIndex += 1;
    }
    for (let g in this.globals) {
      g.index = globalIndex;
      globalIndex += 1;
    }
  }

  /**
   * Orders the type section into recursion groups and assigns type
   * indices: the type half of `layout()`. It runs again after dead-field
   * elimination and type pruning (module-generator.zena), because
   * removing fields can break a cycle a group was formed for, and can
   * make two groups' types structurally identical, which wasm would then
   * treat as one type.
   */
  layoutTypes(): void {
    // Minimal recursion groups: one rec group per strongly-connected
    // component of the type-reference graph (fields, array elements,
    // signature params/results, supertypes), in dependency order —
    // Tarjan pops a component only after every component it references,
    // so cross-group references always point to an earlier group, and
    // only intra-group references point forward. Wasm-gc canonicalizes
    // structural identity per GROUP, so the one-big-group layout this
    // replaces made every type's cross-module identity depend on every
    // other type in the module. In practice almost every component is
    // a singleton (99% in the compiler's own module; the largest
    // genuine cycle is 8 types), and a singleton emits with no group
    // header — a self-reference included, since the bare form IS a
    // one-member rec group.
    let uniqueTypes = new Array<WasmType>();
    let seenTypes = new Set<WasmType>();
    // `types` can contain duplicate entries (the generator/async split
    // passes push types the reachability pass already emitted).
    for (let t in this.types) {
      if (!seenTypes.has(t)) {
        seenTypes.add(t);
        uniqueTypes.push(t);
      }
    }
    let typeCount = uniqueTypes.length;
    let posOf = new Map<WasmType, i32>();
    for (var i = 0; i < typeCount; i += 1) {
      posOf[uniqueTypes[i]] = i;
    }
    let adjacency = new Array<GrowableArray<i32>>();
    let pushRef = (list: GrowableArray<i32>, vt: ValType) => {
      match (vt) {
        case ValTypeRef {target}: {
          if (let (true, p) = posOf.get(target)) { list.push(p); }
        }
        case ValTypeRefNull {target}: {
          if (let (true, p) = posOf.get(target)) { list.push(p); }
        }
        case _: {}
      }
    };
    for (var i = 0; i < typeCount; i += 1) {
      let t = uniqueTypes[i];
      let list = new Array<i32>();
      if (t is WasmStruct) {
        if (t.superStruct != null) {
          if (let (true, p) = posOf.get(t.superStruct as WasmStruct)) {
            list.push(p);
          }
        }
        for (let f in t.fields) { pushRef(list, f.type); }
      } else if (t is WasmArray) {
        if (t.superArray != null) {
          if (let (true, p) = posOf.get(t.superArray as WasmArray)) {
            list.push(p);
          }
        }
        pushRef(list, t.elementType);
      } else if (t is WasmSignature) {
        for (let pv in t.params) { pushRef(list, pv); }
        for (let rv in t.returns) { pushRef(list, rv); }
      }
      adjacency.push(list);
    }

    // Iterative Tarjan. Deterministic: roots in first-seen order,
    // edges in declaration order — the fixpoint gate depends on it.
    let sccOf = new Array<i32>();
    let lowLink = new Array<i32>();
    let onStack = new Array<boolean>();
    for (var i = 0; i < typeCount; i += 1) {
      sccOf.push(-1);
      lowLink.push(0);
      onStack.push(false);
    }
    let componentStack = new Array<i32>();
    let componentMembers = new Array<GrowableArray<i32>>();
    var nextDiscovery = 0;
    let workNode = new Array<i32>();
    let workEdge = new Array<i32>();
    for (var root = 0; root < typeCount; root += 1) {
      if (sccOf[root] != -1) { continue; }
      workNode.push(root);
      workEdge.push(0);
      while (workNode.length > 0) {
        let v = workNode[workNode.length - 1];
        let ei = workEdge[workEdge.length - 1];
        if (ei == 0) {
          sccOf[v] = nextDiscovery;
          lowLink[v] = nextDiscovery;
          nextDiscovery += 1;
          componentStack.push(v);
          onStack[v] = true;
        }
        let edges = adjacency[v];
        var descended = false;
        var e = ei;
        while (e < edges.length) {
          let w = edges[e];
          if (sccOf[w] == -1) {
            workEdge[workEdge.length - 1] = e + 1;
            workNode.push(w);
            workEdge.push(0);
            descended = true;
            break;
          }
          if (onStack[w] && sccOf[w] < lowLink[v]) {
            lowLink[v] = sccOf[w];
          }
          e += 1;
        }
        if (descended) { continue; }
        if (lowLink[v] == sccOf[v]) {
          let members = new Array<i32>();
          while (true) {
            let w = componentStack.pop();
            onStack[w] = false;
            members.push(w);
            if (w == v) { break; }
          }
          componentMembers.push(members);
        }
        let ignoredNode = workNode.pop();
        let ignoredEdge = workEdge.pop();
        if (workNode.length > 0) {
          let parent = workNode[workNode.length - 1];
          if (lowLink[v] < lowLink[parent]) {
            lowLink[parent] = lowLink[v];
          }
        }
      }
    }

    // Canonically-identical groups MERGE into one rec group. Wasm-gc
    // type identity is structural per group: two singleton groups of
    // the same shape are THE SAME type, so structurally-identical
    // nominal classes (same fields, same super — sealed variants with
    // one payload; every slot-pruned empty vtable struct) would
    // collapse, and `is`/`as`/match would stop telling them apart —
    // position IN a shared group is the only brand the format offers.
    // A group's key encodes its emitted shape with external references
    // by (merged-group id, member index); groups arrive in dependency
    // order, so by induction two same-keyed groups have the SAME
    // merged dependencies, all of which precede the first twin — which
    // makes appending later twins to the first one's group always
    // order-valid.
    let groupOfType = new Array<i32>();
    let memberIndexOfType = new Array<i32>();
    for (var i = 0; i < typeCount; i += 1) {
      groupOfType.push(-1);
      memberIndexOfType.push(-1);
    }
    let mergedMembers = new Array<GrowableArray<i32>>();
    let groupByKey = new Map<String, i32>();
    for (let members in componentMembers) {
      // Ascending first-seen order inside a group: deterministic, and
      // independent of DFS pop order.
      var mi = 1;
      while (mi < members.length) {
        let mkey = members[mi];
        var mj = mi - 1;
        while (mj >= 0 && members[mj] > mkey) {
          members[mj + 1] = members[mj];
          mj -= 1;
        }
        members[mj + 1] = mkey;
        mi += 1;
      }

      // WebAssembly GC requires that supertypes be defined before subtypes
      // even within a recursive type group. If any member has a supertype
      // that is also in this group, topologically sort members so that
      // all supertypes precede their subtypes, breaking ties by first-seen order.
      if (members.length > 1) {
        let memberSet = new Map<i32, boolean>();
        for (let m in members) {
          memberSet[m] = true;
        }
        // A subtype must follow its supertype within a group, and an
        // array has one as a struct does (WasmArray.superArray).
        let superOf = (t: WasmType): WasmType | null => {
          if (t is WasmStruct) { return (t as WasmStruct).superStruct; }
          if (t is WasmArray) { return (t as WasmArray).superArray; }
          return null;
        };
        var hasIntraGroupSubtype = false;
        for (let m in members) {
          let t = uniqueTypes[m];
          if (superOf(t) != null) {
            let s = superOf(t) as WasmType;
            if (s != null) {
              if (let (true, sp) = posOf.get(s)) {
                if (let (true, _present) = memberSet.get(sp)) {
                  hasIntraGroupSubtype = true;
                  break;
                }
              }
            }
          }
        }
        if (hasIntraGroupSubtype) {
          let childrenOf = new Map<i32, GrowableArray<i32>>();
          let inDegree = new Map<i32, i32>();
          for (let m in members) {
            inDegree[m] = 0;
          }
          for (let m in members) {
            let t = uniqueTypes[m];
            if (superOf(t) != null) {
              let s = superOf(t) as WasmType;
              if (s != null) {
                if (let (true, sp) = posOf.get(s)) {
                  if (let (true, _present) = memberSet.get(sp)) {
                    inDegree[m] = 1;
                    var ch: GrowableArray<i32> | null = null;
                    if (let (true, existing) = childrenOf.get(sp)) {
                      ch = existing;
                    } else {
                      let arr = new Array<i32>();
                      childrenOf[sp] = arr;
                      ch = arr;
                    }
                    (ch as GrowableArray<i32>).push(m);
                  }
                }
              }
            }
          }
          let ready = new Array<i32>();
          for (let m in members) {
            if (inDegree[m] == 0) {
              ready.push(m);
            }
          }
          let sortedMembers = new Array<i32>();
          while (ready.length > 0) {
            let curr = ready[0];
            var ri = 0;
            while (ri < ready.length - 1) {
              ready[ri] = ready[ri + 1];
              ri += 1;
            }
            ready.pop();
            sortedMembers.push(curr);

            if (let (true, ch) = childrenOf.get(curr)) {
              for (let child in ch) {
                let d = inDegree[child] - 1;
                inDegree[child] = d;
                if (d == 0) {
                  var insertAt = ready.length;
                  var ci = 0;
                  while (ci < ready.length) {
                    if (ready[ci] > child) {
                      insertAt = ci;
                      break;
                    }
                    ci += 1;
                  }
                  ready.push(child);
                  var cj = ready.length - 1;
                  while (cj > insertAt) {
                    ready[cj] = ready[cj - 1];
                    cj -= 1;
                  }
                  ready[insertAt] = child;
                }
              }
            }
          }
          var si = 0;
          while (si < members.length) {
            members[si] = sortedMembers[si];
            si += 1;
          }
        }
      }

      let intraIndex = new Map<i32, i32>();
      for (var i = 0; i < members.length; i += 1) {
        intraIndex[members[i]] = i;
      }
      let parts = new Array<String>();
      let encodeTarget = (target: WasmType) => {
        if (let (true, tp) = posOf.get(target)) {
          if (let (true, ii) = intraIndex.get(tp)) {
            parts.push("#");
            parts.push(i32ToString(ii));
            return;
          }
          parts.push("@");
          parts.push(i32ToString(groupOfType[tp]));
          parts.push(".");
          parts.push(i32ToString(memberIndexOfType[tp]));
          return;
        }
        // A reference to a type outside the layout would already be a
        // broken module; keep the key honest anyway.
        parts.push("?");
      };
      let encodeVal = (vt: ValType) => {
        match (vt) {
          case ValTypeRef {target}: {
            parts.push("r");
            encodeTarget(target);
          }
          case ValTypeRefNull {target}: {
            parts.push("n");
            encodeTarget(target);
          }
          case _: {
            parts.push(i32ToString(valTypeToOpcode(vt)));
          }
        }
        parts.push(",");
      };
      for (let m in members) {
        let t = uniqueTypes[m];
        if (t is WasmStruct) {
          parts.push("S");
          if (t.superStruct != null) {
            encodeTarget(t.superStruct as WasmStruct);
          }
          parts.push("[");
          for (let f in t.fields) {
            encodeVal(f.type);
            parts.push(if (f.isMutable) "m" else "c");
          }
          parts.push("]");
        } else if (t is WasmArray) {
          parts.push("A");
          if (t.superArray != null) {
            encodeTarget(t.superArray as WasmArray);
          }
          encodeVal(t.elementType);
          parts.push(if (t.isMutable) "m" else "c");
        } else if (t is WasmSignature) {
          parts.push("F");
          for (let pv in t.params) {
            encodeVal(pv);
          }
          parts.push(">");
          for (let rv in t.returns) {
            encodeVal(rv);
          }
        }
        parts.push(";");
      }
      let keyParts = new Array<String>.fixed(parts.length, "");
      for (var pi = 0; pi < parts.length; pi += 1) {
        keyParts[pi] = parts[pi];
      }
      let key = String.fromParts(keyParts);
      var g = -1;
      if (let (true, existing) = groupByKey.get(key)) {
        g = existing;
      } else {
        g = mergedMembers.length;
        mergedMembers.push(new Array<i32>());
        groupByKey[key] = g;
      }
      let bucket = mergedMembers[g];
      for (let m in members) {
        groupOfType[m] = g;
        memberIndexOfType[m] = bucket.length;
        bucket.push(m);
      }
    }

    let orderedTypes = new Array<WasmType>();
    let groupSizes = new Array<i32>();
    for (let bucket in mergedMembers) {
      for (let m in bucket) {
        orderedTypes.push(uniqueTypes[m]);
      }
      groupSizes.push(bucket.length);
    }
    this.types = orderedTypes;
    this.typeRecGroupSizes = groupSizes;

    for (var i = 0; i < this.types.length; i += 1) {
      this.types[i].index = i;
    }

  }
}
VersionPublishedDependenciesApproved by
0.0.2-preview.1 2026-11-19