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

191.0 KiB Raw
import { HashSet, Set } from 'zena:collections';
import { collectValueExports, findDeclaration } from '../lookup.zena';
import {
  isExistentialRecord, isValueHashCodeCall, valueEqFields, valueEqKey, valueEqOperand, valueHashKey,
} from '../value-equality.zena';
import {
  Referrer, ReachabilityContext, TypeLowererInterface, ReachabilityVisitorInterface,
  recordLiteralArgKey, recordLiteralCtorArgKey, recordLiteralMethodArgKey,
  recordLiteralSpecArgKey, RecordResultCall,
  declaringInstantiation, methodTargetKey, specMethodTargetKey,
} from './context.zena';
import { SemanticModel, memberKeyOf, accessKeyOf } from '../../semantic-model.zena';
import {
  Type, ClassType, InterfaceType, FunctionType, TypeParameterType, RecordType, TupleType, InlineTupleType, HoleType, InlineRecordType, UnionType, TypeAliasType, EnumType, ArrayType, NullType, I32Type, U64Type, MethodInfo, FieldInfo, instantiateClassType, instantiateInterfaceType, ThisType, baseType, ErasedType, AnyRefType,
  isBigIntLiteralRaw, isScopedType, scopedInner, soleNonNullMember, internFunctionType, forInLowersToIndexLoop,
  isIterableRangeClass, holdsOwner, typeContainsScoped } from '../../types.zena';
import {
  Node, decoratorStringArg, AsExpression, IsExpression, MatchExpression, RecordLiteral, ClassPattern, MatchCase, LetPatternCondition, AsPattern, BindingPattern, LogicalPattern, TuplePattern, ArrayPattern, RestPattern, RecordPattern, AccessorDeclaration, BinaryExpression, LiteralPattern, NewExpression, MethodDefinition, SymbolPropertyName, RangeExpression, ArrayLiteral, MapLiteral, TupleLiteral, Expression, TemplateElement, TaggedTemplateExpression, ForInStatement, MemberExpression, AwaitExpression, IndexExpression, AssignmentExpression, Identifier, CallExpression, VariableDeclaration, FunctionDeclaration, Pattern, ImportDeclaration, DeclareFunction, ImportSpecifier, IdentifierPattern, FunctionExpression, MixinDeclaration, ClassDeclaration, Module, NumberLiteral, ThrowExpression, TryExpression, ContractClause, contractFailureMessage, ShieldedStatement, StringLiteral, SuperInitializer, TemplateLiteral, UnaryExpression,
} from '../../ast.zena';
import {
  WasmStruct, WasmField, WasmGlobal, WasmFunction, RecordDispatchInfo, TypeTestSite,
} from '../wasm-module.zena';
import {
  ValType, ValTypeVoid, ValTypeRefNull, ValTypeAnyRef, ValTypeEqRef, ValTypeStructRef, ValTypeRef, ValTypeI32, ValTypeI64, ValTypeF32, ValTypeF64, ValTypeExternRef, ValTypeRefExtern, isRefValType,
} from '../wasm.zena';
import { SymbolId, Symbol, noSymbolId } from '../../scope/symbol.zena';
import {
  getClassKey, getClassMethodKey, getInterfaceKey, getClassInterfaceKey, getMixinKeyFromSymbol, getSpecializedFunctionKey, getSpecializedName, getFunctionValueWrapperKey, getOverloadedFunctionKey, getSignatureKey, collectMixinMembers, mixinScopeOfNode, MixinKey, isConcrete, ExportKey, ExportGlobalKey, getTypeUniqueKey, templateConvertHelperName, containsErasedType, pendingSomeClass, pendingNoneClass, parseBigIntLiteralLimbs, bigIntLiteralCacheKey, unwrapAliases,
} from '../codegen-utils.zena';
import {
  typeToValType, typeToStorageValType, mapReturnTypeToWasmResults, mapParamTypeToWasmParams, substituteTypeParamsInCodegen, getClosureStruct, getClassTypeParameters, getInterfaceTypeParameters, substituteTypeParamsInClassContext, eraseTypeParameters, findImplementedWellKnownInterface, findImplementedInterfaceType, findExtendedWellKnownInterface, recordWasmFields, sortedOptionalNames, asyncIteratorPendingFuture, getNonNullableType, boxedRecordWithFields, InlineLayout, inlineLayoutOf,
} from '../type-mapping.zena';

import { dirName, normalizePath } from '../../module-resolver.zena';
import { Program, CompilationUnit } from '../../program.zena';
import { walkEnter } from '../../visitor.zena';
import { resolveImportedSymbolId } from './import-resolver.zena';
import { WellKnown, isWellKnown } from '../../well-known.zena';
import { stdlibLibraryOf, stdlibLibraryAnswers } from '../../stdlib-manifest.zena';
import { growable } from 'zena:core';
import { targetEmitsComponent, targetUsesJsStrings } from '../../targets.zena';

final class DeferredClassDiscovery {
  ct: ClassType;
  model: SemanticModel;
  isGenericInst: boolean;
  didPreRegister: boolean;
  suppressNameEvidence: boolean;

  new(this.ct, this.model, this.isGenericInst, this.didPreRegister,
      this.suppressNameEvidence);
}

final class DeferredInterfaceDiscovery {
  it: InterfaceType;
  model: SemanticModel;
  didPreRegister: boolean;
  suppressNameEvidence: boolean;

  new(this.it, this.model, this.didPreRegister, this.suppressNameEvidence);
}

/**
 * TypeLowerer translates Zena semantic types into their target WebAssembly representation,
 * generating struct and array definitions on-demand as they are discovered.
 */
export final class TypeLowerer implements TypeLowererInterface {
  pass: ReachabilityContext;
  /**
   * Nesting depth of `RecordType`/`TupleType` field layout in `discoverType`.
   * While positive, nominal class and interface specializations register their
   * shell structs immediately (so `recordWasmFields` can name them) and defer
   * member walks until the enclosing record dispatch is registered.
   */
  var #recordFieldDepth = 0;
  var #deferredClasses = new Array<DeferredClassDiscovery>();
  var #deferredInterfaces = new Array<DeferredInterfaceDiscovery>();

  new(this.pass);

  /**
   * Records that in-queue-walked code names `t`, recursing into the
   * component types the discovery arms would visit — the arms are
   * behind the discovery dedup below, so they only ever see a type's
   * FIRST discovery, which may have been a plumbing walk. Depth-bounded
   * against self-referential aliases; the sets dedup re-recording.
   */
  #recordTypeEvidence(t: Type, model: SemanticModel, depth: i32): void {
    if (depth > 12) { return; }
    if (t is ClassType) {
      this.pass.reachablyNamedClasses.add(getClassKey(t) as String);
      let typeArguments = t.typeArguments;
      if (typeArguments != null) {
        for (let ta in typeArguments) {
          this.#recordTypeEvidence(eraseTypeParameters(this.pass.wasm, ta), model, depth + 1);
        }
      }
      // An extension VALUE is its representation type: reached code
      // naming FixedArray<T> allocates and indexes the raw array
      // (array.new_fixed in an index-loop for-in) with no reached
      // signature ever mentioning it, so the representation is
      // evidence in its own right.
      if (t.isExtension && t.onType != null) {
        this.#recordTypeEvidence(eraseTypeParameters(this.pass.wasm,
            substituteTypeParamsInClassContext(this.pass.wasm, t,
                t.onType as Type)), model, depth + 1);
      }
    } else if (t is RecordType) {
      for (let pair in t.properties) {
        this.#recordTypeEvidence(eraseTypeParameters(this.pass.wasm, pair.value), model, depth + 1);
      }
      // Resolving the dispatch needs typeToValType over the field
      // types, which throws for a nested record whose own dispatch is
      // not created yet — and this runs BEFORE discovery on purpose.
      // Save the semantic type; the settle step resolves it.
      this.pass.noteCompositeType(t);
    } else if (t is TupleType) {
      for (var i = 0; i < t.elementTypes.length; i += 1) {
        this.#recordTypeEvidence(eraseTypeParameters(this.pass.wasm, t.elementTypes[i]), model, depth + 1);
      }
      this.pass.noteCompositeType(t);
    } else if (t is InlineTupleType) {
      for (let e in t.elementTypes) {
        this.#recordTypeEvidence(eraseTypeParameters(this.pass.wasm, e), model, depth + 1);
      }
    } else if (t is InlineRecordType) {
      // Its fields are read through its boxed form's dispatch.
      this.#recordTypeEvidence(boxedRecordWithFields(t.record), model, depth + 1);
    } else if (t is UnionType) {
      for (let m in t.types) {
        this.#recordTypeEvidence(eraseTypeParameters(this.pass.wasm, m), model, depth + 1);
      }
    } else if (t is TypeAliasType) {
      this.#recordTypeEvidence(eraseTypeParameters(this.pass.wasm, t.target), model, depth + 1);
    } else if (t is EnumType) {
      this.#recordTypeEvidence(eraseTypeParameters(this.pass.wasm, t.backingType), model, depth + 1);
    } else if (t is ArrayType) {
      this.#recordTypeEvidence(eraseTypeParameters(this.pass.wasm, t.elementType), model, depth + 1);
      // The array TYPE itself is evidence, not only its element: a
      // value of it can exist with no reached signature naming it.
      // Deferred like records — computing the element ValType here
      // could throw for a record element whose dispatch is not
      // created yet; the settle step resolves it.
      this.pass.noteCompositeType(eraseTypeParameters(this.pass.wasm, t));
    } else if (t is FunctionType) {
      // Interning the closure struct here would compute its signature
      // — typeToValType over params/returns — which throws for a
      // record whose dispatch is not created yet. Defer, like records.
      this.pass.noteCompositeType(eraseType(t));
      for (let pt in t.parameters) {
        this.#recordTypeEvidence(eraseTypeParameters(this.pass.wasm, pt), model, depth + 1);
      }
      this.#recordTypeEvidence(eraseTypeParameters(this.pass.wasm, t.returnType), model, depth + 1);
    } else if (t is InterfaceType) {
      this.pass.noteCompositeType(eraseTypeParameters(this.pass.wasm, t));
      let typeArguments = t.typeArguments;
      if (typeArguments != null) {
        for (let ta in typeArguments) {
          this.#recordTypeEvidence(eraseTypeParameters(this.pass.wasm, ta), model, depth + 1);
        }
      }
    }
  }

  discoverType(rawT: Type | null, model: SemanticModel): void {
    if (rawT == null) { return; }
    var t = eraseTypeParameters(this.pass.wasm, rawT);
    while (t is TypeAliasType) {
      t = t.target;
    }
    if (t is EnumType) {
      t = (t as EnumType).backingType;
    }
    let typeStr = getTypeUniqueKey(t);
    // Evidence is recorded BEFORE the dedup below: a type first
    // discovered by a plumbing walk (imports, layout, helper ensures)
    // early-returns on its later in-queue discovery, and recording
    // only inside the arms would then never see it — the wit-parser
    // and fs record structs failed with `index < 0` exactly this way.
    if (this.pass.inQueueWalk && this.pass.currentReachable &&
        !this.pass.suppressNameEvidence) {
      this.#recordTypeEvidence(t, model, 0);
    }
    if (this.pass.currentReachable) {
      if (this.pass.reachedSemanticTypes.has(typeStr)) {
        return;
      }
      this.pass.reachedSemanticTypes.add(typeStr);
    } else {
      if (this.pass.discoveredTypes.has(typeStr)) {
        return;
      }
      this.pass.discoveredTypes.add(typeStr);
    }
    
    if (t is RecordType) {
      this.#recordFieldDepth += 1;
      for (let pair in t.properties) {
        this.discoverType(pair.value, model);
      }
      let fields = recordWasmFields(this.pass.wasm, t, null);
      let st = if (t.isExistential)
          this.pass.wasm.getExistentialDispatch(model, fields, sortedOptionalNames(t))
          else this.pass.wasm.getRecordDispatch(model, fields, sortedOptionalNames(t));
      this.pass.markTypeReached(st.fatPtrType);
      this.pass.markTypeReached(st.vtableType);
      this.pass.markTypeReached(st.concreteType);
      this.#endRecordFieldDiscovery();
    } else if (t is TupleType) {
      this.#recordFieldDepth += 1;
      for (var i = 0; i < t.elementTypes.length; i += 1) {
        this.discoverType(t.elementTypes[i], model);
      }
      let elements = new Array<ValType>();
      for (let el in t.elementTypes) {
        elements.push(typeToValType(this.pass.wasm, el));
      }
      let st = this.pass.wasm.getTupleStruct(t, elements);
      this.pass.markTypeReached(st);
      if (this.pass.inQueueWalk) {
        this.pass.reachablyNamedAnonStructs.add(st);
      }
      this.#endRecordFieldDiscovery();
    } else if (t is InlineTupleType) {
      for (var i = 0; i < t.elementTypes.length; i += 1) {
        this.discoverType(t.elementTypes[i], model);
      }
    } else if (t is InlineRecordType) {
      this.discoverType(boxedRecordWithFields(t.record), model);
    } else if (t is UnionType) {
      for (let member in t.types) {
        this.discoverType(member, model);
      }
    } else if (t is TypeAliasType) {
      this.discoverType(t.target, model);
    } else if (t is EnumType) {
      this.discoverType(t.backingType, model);
    } else if (t is FunctionType) {
      for (let paramType in t.parameters) {
        this.discoverType(paramType, model);
      }
      this.discoverType(t.returnType, model);
      // discoverType is only called for types that can occupy a wasm
      // value position (locals, fields, body-referenced types), so the
      // function type needs its closure struct before layout locks the
      // type section — lowered bodies demand it afterwards. Signatures
      // that are NOT values — every reached method's own signature —
      // must go through discoverSignatureType instead: minting for
      // those put a dead closure struct + impl signature pair in the
      // type section per reached method, about half of it.
      let contextStruct = getClosureStruct(this.pass.wasm, eraseType(t) as FunctionType);
      this.pass.markTypeReached(contextStruct);
      this.pass.noteClosureStruct(contextStruct);

      if (t.functionSymbolId != noSymbolId) {
        let specializer = this.pass.specializer;
        let visitor = this.pass.visitor;
        let targetSymId = t.functionSymbolId;
        let resolvedArgs = new Array<Type>();
        let typeArguments = t.typeArguments;
        if (typeArguments != null) {
          for (let arg in typeArguments) {
            resolvedArgs.push(arg);
          }
        }
        let isSpecialized = resolvedArgs.length > 0 && noOpenTypeParameters(resolvedArgs);
        if (isSpecialized && this.pass.wasm.genericFunctions.has(targetSymId)) {
          specializer.instantiateGenericFunction(targetSymId, resolvedArgs);
        }
        
        var targetWasmFunc: WasmFunction | null = null;
        var keyName = "";
        if (isSpecialized) {
          let specKey = getSpecializedFunctionKey(t.functionSymbolName, resolvedArgs);
          keyName = getSpecializedName(t.functionSymbolName, resolvedArgs);
          if (let (true, f) = this.pass.wasm.specializedFunctions.get(specKey)) {
            targetWasmFunc = f;
          }
        } else {
          keyName = i32ToString(targetSymId as i32);
          let overKey = getOverloadedFunctionKey(targetSymId, t);
          if (let (true, f) = this.pass.wasm.overloadedFunctionMap.get(overKey)) {
            targetWasmFunc = f;
          } else if (let (true, f) = this.pass.wasm.functionMap.get(targetSymId)) {
            targetWasmFunc = f;
          }
        }
        if (targetWasmFunc != null) {
          visitor.registerWrapper(keyName, t, targetWasmFunc, model);
          
          let targs = t.typeArguments;
          if (targs != null && targs.length > 0) {
            let erasedArgs = new Array<Type>();
            for (let arg in (targs as Array<Type>)) {
              erasedArgs.push(eraseType(arg));
            }
            let erasedFt = eraseType(t) as FunctionType;
            let erasedSpecKey = getSpecializedFunctionKey(t.functionSymbolName, erasedArgs);
            
            var erasedTargetWasmFunc: WasmFunction | null = null;
            if (let (true, f) = this.pass.wasm.specializedFunctions.get(erasedSpecKey)) {
              erasedTargetWasmFunc = f;
            } else if (this.pass.wasm.genericFunctions.has(targetSymId)) {
              erasedTargetWasmFunc = specializer.instantiateGenericFunction(targetSymId, erasedArgs);
            }
            
            if (erasedTargetWasmFunc != null) {
              visitor.registerWrapper(getSpecializedName(t.functionSymbolName, erasedArgs), erasedFt, erasedTargetWasmFunc, model);
            }
          }
        }
      }
    } else if (t is ClassType) {
      let targs = t.typeArguments;
      if (t.name == "array" && targs != null && targs.length > 0) {
        let elemType = targs[0];
        this.discoverType(elemType, model);
        // Storage type, matching typeToValType's array arm: narrow and
        // zero-width elements pack, so the array interned here is the
        // one lowering will name.
        let elemValType = typeToStorageValType(this.pass.wasm, elemType);
        let arr = this.pass.wasm.getArray(elemValType, true);
        this.pass.markTypeReached(arr);
        return;
      }
      let cKey = getClassKey(t);
      let lookupId = (t.genericSource ?? t).symbolId;
      // Reached code names this class: its struct can appear in a
      // lowered cast, type test, or nullable field read even if no
      // value is ever constructed, so the type section keeps it.
      // Recorded BEFORE the already-registered early return — being in
      // classInfos says the class is declared, not that it is used.
      if (this.pass.inQueueWalk && this.pass.currentReachable &&
          !this.pass.suppressNameEvidence) {
        this.pass.reachablyNamedClasses.add(cKey as String);
      }
      if (this.pass.wasm.classInfos.has(cKey)) {
        return;
      }
      if (isWellKnown(WellKnown.StringClass, t.name, t.sourcePath)) {
        this.pass.wasm.stringClass = t;
      } else if (isWellKnown(WellKnown.TemplateStringsArrayClass, t.name,
          t.sourcePath)) {
        this.pass.wasm.templateStringsArrayClass = t;
      } else if (isWellKnown(WellKnown.BigIntClass, t.name,
          t.sourcePath)) {
        this.pass.wasm.bigIntClass = t;
      } else if (isWellKnown(WellKnown.ErrorClass, t.name, t.sourcePath)) {
        this.pass.wasm.errorClass = t;
      }
      
      // Register specialized class struct & methods if generic instantiation or mixin intermediate
      let typeArguments = t.typeArguments;
      let isGenericInst = typeArguments != null && typeArguments.length > 0 && isConcrete(t);
      if (!t.isExtension && this.#recordFieldDepth > 0) {
        let didPreRegister = if ((isGenericInst || (t.isMixinIntermediate && !t.isExtension)) &&
            this.pass.classDecls.has(lookupId)) {
          this.pass.specializer.preRegisterClassStruct(t)
        } else {
          false
        };
        this.#deferredClasses.push(new DeferredClassDiscovery(
            t, model, isGenericInst, didPreRegister,
            this.pass.suppressNameEvidence));
        return;
      }
      this.#finishClassDiscovery(t, model, isGenericInst, false, true);
    } else    if (t is InterfaceType) {
      let iKey = getInterfaceKey(t);

      if (this.pass.wasm.interfaceStructs.has(iKey)) {
        let emptyStruct = this.pass.wasm.interfaceStructs[iKey];
        if (this.pass.currentReachable) {

          this.pass.markTypeReached(emptyStruct);
          let emptyVTableStruct = this.pass.wasm.interfaceVTableStructs[iKey];
          this.pass.markTypeReached(emptyVTableStruct);
        }
        return;
      }
      
      // Register specialized interface struct & methods if generic instantiation
      let typeArguments = t.typeArguments;
      var didPreRegister = false;
      if (typeArguments != null && typeArguments.length > 0 && isConcrete(t)) {
        let lookupId = (t.genericSource ?? t).symbolId;
        if (this.pass.interfaceDecls.has(lookupId)) {
          didPreRegister = this.pass.specializer.preRegisterInterfaceStruct(t);
        }
      }

      if (this.pass.wasm.interfaceStructs.has(iKey)) {
        let emptyStruct = this.pass.wasm.interfaceStructs[iKey];
        if (this.pass.currentReachable) {

          this.pass.markTypeReached(emptyStruct);
          let emptyVTableStruct = this.pass.wasm.interfaceVTableStructs[iKey];
          this.pass.markTypeReached(emptyVTableStruct);
        }
      }
      if (this.#recordFieldDepth > 0) {
        this.#deferredInterfaces.push(new DeferredInterfaceDiscovery(
            t, model, didPreRegister, this.pass.suppressNameEvidence));
        return;
      }
      this.#finishInterfaceDiscovery(t, model, didPreRegister);
    } else if (t is ArrayType) {
      this.discoverType(t.elementType, model);
      // Storage type, for the same reason as the `array` class arm.
      let elemValType = typeToStorageValType(this.pass.wasm, t.elementType);
      // Reached, not just created: an array VALUE can exist with no
      // reached signature mentioning the type — a literal iterated by
      // an index loop is array.new_fixed and array.get, both of which
      // reference the type index directly. Under registration
      // (suppressNameEvidence) the mention is a signature's, not a
      // value's, and a reached signature's types are kept structurally.
      if (this.pass.suppressNameEvidence) {
        this.pass.wasm.getArray(elemValType, t.elementsMutable);
      } else {
        this.pass.markTypeReached(this.pass.wasm.getArray(elemValType, t.elementsMutable));
      }

      if (isConcrete(t)) {
        // The wrapper classes must be REGISTERED — member lookup on an
        // array-typed receiver resolves through them — but discovering
        // an array type is not reached code naming them, so their
        // placeholder structs are not name evidence.
        let savedSuppress = this.pass.suppressNameEvidence;
        this.pass.suppressNameEvidence = true;
        let faClass = this.pass.findPreludeClass(WellKnown.FixedArrayClass);
        if (faClass != null) {
          let typeArgs = growable<Type>([t.elementType]);
          this.discoverType(instantiateClassType(faClass, typeArgs), model);
        }
        let iaClass = this.pass.findPreludeClass(WellKnown.ImmutableArrayClass);
        if (iaClass != null) {
          let typeArgs = growable<Type>([t.elementType]);
          this.discoverType(instantiateClassType(iaClass, typeArgs), model);
        }
        this.pass.suppressNameEvidence = savedSuppress;
      }
    }
  }

  #endRecordFieldDiscovery(): void {
    this.#recordFieldDepth -= 1;
    if (this.#recordFieldDepth > 0) {
      return;
    }
    let savedSuppress = this.pass.suppressNameEvidence;
    while (this.#deferredInterfaces.length > 0 || this.#deferredClasses.length > 0) {
      let ifaces = this.#deferredInterfaces;
      this.#deferredInterfaces = new Array<DeferredInterfaceDiscovery>();
      for (let item in ifaces) {
        this.pass.suppressNameEvidence = item.suppressNameEvidence;
        this.#finishInterfaceDiscovery(item.it, item.model, item.didPreRegister);
      }
      let classes = this.#deferredClasses;
      this.#deferredClasses = new Array<DeferredClassDiscovery>();
      for (let item in classes) {
        this.pass.suppressNameEvidence = item.suppressNameEvidence;
        this.#finishClassDiscovery(item.ct, item.model, item.isGenericInst, item.didPreRegister, false);
      }
    }
    this.pass.suppressNameEvidence = savedSuppress;
  }

  #finishClassDiscovery(t: ClassType, model: SemanticModel, isGenericInst: boolean,
      didPreRegister: boolean, registerShell: boolean): void {
    let lookupId = (t.genericSource ?? t).symbolId;
    if (isGenericInst || (t.isMixinIntermediate && !t.isExtension)) {
      // An ERASURE is not a specialization. A mention of one is
      // made by code that does not run: `#linkSuperAndVT` naming a
      // subclass template's supertype, or the walk of a generic
      // class's own template naming its field types. Every value
      // either stands for is some real specialization, discovered on
      // its own.
      //
      // Believing a mention made it a fan-out target for every
      // reached member of the generic class and, once instantiated,
      // gave it a class vtable global — and a vtable global ref.funcs
      // its slots, so an erased body of every method got emitted.
      // Those bodies do not always lower: `hash`/`eq` dispatch on
      // their operand's type and have nothing to dispatch on at
      // anyref, which is what made a generic class whose methods use
      // them impossible to subclass.
      //
      // Nothing is emitted at an erasure, so nothing constructs one
      // either: the erasure of a generic FUNCTION is no longer
      // specialized (noOpenTypeParameters, below), which was the only
      // thing that ran `new Full<T>` as `new Full<erased>`. The STRUCT
      // is still registered — erased signatures and fields name it —
      // and registerSpecializedClass stops there for an erasure.
      let isErasedMention = containsErasedType(t as Type);
      let specializer = this.pass.specializer;
      if (!isErasedMention) {
        // A mention made while laying out a class the module will
        // never emit does not put the specialization on the
        // generic's list. Being on it is what makes a specialization
        // travel: instantiating any sibling instantiates every
        // listed one, and every member reached on the template later
        // fans out over them. If this one turns out to be real,
        // instantiateClassType lists it then.
        if (!this.pass.layingOutUnemittedClass) {
          this.pass.noteSpecialization(t, model);
        }

        // Reaching a generic at one type argument is the evidence
        // that a specialization at another can hold values — the
        // instantiating `new` may live in generic code this mention
        // stands in for. It is not evidence when the mention itself
        // comes from a class the module will never emit: nothing
        // runs there, so nothing constructs anything.
        if (this.pass.isRtaActive && !this.pass.layingOutUnemittedClass &&
            this.pass.instantiatedClasses.has(lookupId)) {
          specializer.instantiateClassType(t, model);
        }
      }

      if (this.pass.classDecls.has(lookupId)) {
        let classDecl = this.pass.classDecls[lookupId];
        let sourceModel = this.pass.classModels[lookupId];
        if (registerShell) {
          specializer.registerSpecializedClass(t, classDecl, sourceModel);
        } else if (didPreRegister) {
          specializer.finishSpecializedClass(t, classDecl, sourceModel);
        }
      }
    }

    if (t.isExtension && t.onType != null) {
      let subOn = substituteTypeParamsInClassContext(this.pass.wasm, t, t.onType as Type);
      this.discoverType(subOn, model);
    }
    for (let pair in t.members) {
      if (pair.value is FieldInfo) {
        let resolvedType = substituteTypeParamsInCodegen(this.pass.wasm, getClassTypeParameters(t), t.typeArguments, pair.value.type);
        this.discoverType(resolvedType, model);
      }
    }
  }

  #finishInterfaceDiscovery(t: InterfaceType, model: SemanticModel, didPreRegister: boolean): void {
    if (didPreRegister) {
      let lookupId = (t.genericSource ?? t).symbolId;
      let ifaceDecl = this.pass.interfaceDecls[lookupId];
      let sourceModel = this.pass.interfaceModels[lookupId];
      this.pass.specializer.finishSpecializedInterface(t, ifaceDecl, sourceModel);
    }
    let itParams = getInterfaceTypeParameters(t);
    for (let ext in t.extendsList) {
      let resolvedExt = substituteTypeParamsInCodegen(this.pass.wasm, itParams, t.typeArguments, ext);
      this.discoverType(resolvedExt, model);
    }
    for (let pair in t.members) {
      if (pair.value is FieldInfo) {
        let resolvedType = substituteTypeParamsInCodegen(this.pass.wasm, itParams, t.typeArguments, pair.value.type);
        this.discoverType(resolvedType, model);
      }
    }
  }

  /**
   * Discover a function signature's component types WITHOUT treating the
   * signature itself as a value-position function type. Reached methods
   * register their own signature through here: routing them through
   * discoverType minted a closure struct + impl signature pair per
   * reached method — nearly half the emitted type section, all dead.
   * The signature deliberately does not claim the discovered-set slot,
   * so a later discoverType of the same erased type (a genuine value
   * position) still processes and mints it.
   */
  discoverSignatureType(rawT: Type | null, model: SemanticModel): void {
    if (rawT == null) { return; }
    let t = eraseTypeParameters(this.pass.wasm, rawT);
    if (t is FunctionType) {
      for (let paramType in t.parameters) {
        // Signature context PROPAGATES: a function-typed parameter of
        // a signature is still a signature component, not a value —
        // its closure struct is pulled transitively by the reached
        // function's own signature marking. Routing it through
        // discoverType recorded a closure struct + impl signature per
        // higher-order method a class-declaration walk visited.
        this.discoverSignatureType(paramType, model);
      }
      this.discoverSignatureType(t.returnType, model);
      return;
    }
    this.discoverType(rawT, model);
  }
}

/**
 * ReachabilityVisitor traverses reachable AST node subtrees to extract their dependencies,
 * queueing newly discovered methods, functions, and instantiations.
 */
/**
 * An interface-typed `==` operand, possibly nullable: its class is not
 * known statically, so the comparison goes through the erased dispatch.
 */
/**
 * The name a top-level statement binds a function to: the pattern of
 * `let name = (…) => …` or of `function name(…) { … }`, else null. The
 * standard library's functions the compiler roots by name may be
 * written either way.
 */
function declaredPattern(stmt: Node): IdentifierPattern | null {
  match (stmt) {
    case VariableDeclaration {pattern}: {
      if (pattern is IdentifierPattern) {
        return pattern;
      }
    }
    case FunctionDeclaration {name}: { return name; }
    case _: {}
  }
  return null;
}

function isInterfaceOperand(t: Type): boolean {
  if (t is InterfaceType) {
    return true;
  }
  if (t is UnionType) {
    for (let m in t.types) {
      if (m is InterfaceType) {
        return true;
      }
    }
  }
  return false;
}

export final class ReachabilityVisitor implements ReachabilityVisitorInterface {
  pass: ReachabilityContext;
  #discoveringOnDemand = new Set<SymbolId>();
  var #nodes: i32 = 0;
  /**
   * The class types `#rootEqOperator` has rooted, by `uid`, as
   * reachable and as visited only. Every `==` on a class operand in a
   * walked body comes there, and rooting a type a second time queues
   * nothing new: the referrers it queues are keyed by the same type and
   * reachability.
   */
  #eqRootedReachable = new HashSet<i32>();
  #eqRootedVisited = new HashSet<i32>();

  new(this.pass);

  /** AST nodes the discovery walk has entered. */
  discoveredNodes: i32 { get { return this.#nodes; } }

  /**
   * Registers every string-literal payload under `root` into the
   * shared literal registry: plain literals and template elements.
   * discoverNodeTypes does this as part of its full walk; node-referrer
   * processing calls THIS when checker-recorded dependencies let it
   * skip that walk. The dependency records carry no literals, so
   * skipping the walk used to silently drop any literal whose only
   * occurrences were in dependency-carrying METHOD bodies, forcing
   * per-occurrence inline construction in both backends.
   */
  /**
   * An unboxing cast — `(erased as f64)` — lowers to a ref.cast to
   * `Box<target>`'s struct plus a field read (ir/operators.zena), but
   * the AST names only the SCALAR target, so nothing else roots the
   * Box specialization. Same for the erased-== diamond in
   * ir/equality.zena. Mirror the lowering's decision here: a
   * scalar-target cast whose operand is reference-typed roots
   * Box<target>.
   */
  #typeTestSiteKeys = new Set<String>();

  /**
   * Records an interface type test — `x is I`, `x as I`, or a `case I`
   * arm — with its operand's static type, for the analysis's
   * #markTypeTestPairs: a test answers true for the reached classes
   * that implement `I` and fit the operand's type. An operand that is
   * statically `I` is not recorded, since it holds a fat pointer of
   * `I` already and the lowering tests that struct.
   */
  noteTypeTestSites(n: Node, model: SemanticModel,
      resolveType: (t: Type) => Type): void {
    if (n is IsExpression) {
      this.#noteTypeTest(model.getNodeType(n.typeAnnotation),
          model.getNodeType(n.expression), resolveType);
    } else if (n is AsExpression) {
      // The cast's own type is its target; the checker records no type
      // on the annotation node of an `as`.
      this.#noteTypeTest(model.getNodeType(n),
          model.getNodeType(n.expression), resolveType);
    } else if (n is MatchExpression) {
      let source = model.getNodeType(n.discriminant);
      for (let c in n.cases) {
        this.#noteTypeTestPattern(c.pattern, source, model, resolveType);
      }
    } else if (n is LetPatternCondition) {
      this.#noteTypeTestPattern(n.pattern as Node, model.getNodeType(n.init),
          model, resolveType);
    }
  }

  /**
   * The interface tests inside a pattern. A nested pattern (a tuple
   * element, a record or class field) tests a value whose type this
   * walk does not recover, so its tests are recorded against `anyref`,
   * the widest operand.
   */
  #noteTypeTestPattern(p: Node, source: Type | null, model: SemanticModel,
      resolveType: (t: Type) => Type): void {
    if (p is Identifier) {
      if (p.name != "_") {
        this.#noteTypeTest(model.getNodeType(p), source, resolveType);
      }
    } else if (p is AsPattern) {
      this.#noteTypeTestPattern(p.pattern, source, model, resolveType);
    } else if (p is BindingPattern) {
      this.#noteTypeTestPattern(p.pattern, source, model, resolveType);
    } else if (p is LogicalPattern) {
      this.#noteTypeTestPattern(p.left, source, model, resolveType);
      this.#noteTypeTestPattern(p.right, source, model, resolveType);
    } else if (p is ClassPattern) {
      // `case Iterable<i32>:` tests an interface.
      this.#noteTypeTest(model.getNodeType(p.name), source, resolveType);
      for (let prop in p.properties) {
        this.#noteTypeTestPattern(prop.value, null, model, resolveType);
      }
    } else if (p is RecordPattern) {
      for (let prop in p.properties) {
        this.#noteTypeTestPattern(prop.value, null, model, resolveType);
      }
    } else if (p is TuplePattern) {
      for (let el in p.elements) {
        if (el != null) {
          this.#noteTypeTestPattern(el, null, model, resolveType);
        }
      }
    } else if (p is ArrayPattern) {
      for (let el in p.elements) {
        if (el != null) {
          this.#noteTypeTestPattern(el, null, model, resolveType);
        }
      }
    }
  }

  #noteTypeTest(targetOpt: Type | null, sourceOpt: Type | null,
      resolveType: (t: Type) => Type): void {
    if (targetOpt == null) {
      return;
    }
    let target = getNonNullableType(baseType(resolveType(targetOpt)));
    if (!(target is InterfaceType)) {
      return;
    }
    let source: Type = if (sourceOpt == null) new AnyRefType() as Type
        else resolveType(sourceOpt);
    let sourceBase = getNonNullableType(baseType(source));
    if (sourceBase is InterfaceType &&
        getInterfaceKey(sourceBase) == getInterfaceKey(target)) {
      return;
    }
    let key = `${getInterfaceKey(target) as String}|${getTypeUniqueKey(source)}`;
    if (this.#typeTestSiteKeys.has(key)) {
      return;
    }
    this.#typeTestSiteKeys.add(key);
    this.pass.wasm.typeTestSites.push(new TypeTestSite(target, source));
  }

  /**
   * Discovers the class types a PATTERN tests — `case Foo {..}:`
   * (ClassPattern, type on the name node) and the bare `case Foo:`
   * (a plain Identifier resolving to a type symbol), recursing through
   * the combining pattern kinds. Mirrors ir/patterns.zena's
   * lowerPatternTest, which emits a ref.test/ref.cast per tested
   * class; a class only ever named this way surfaced as
   * `ref.test references unemitted struct` once the type section
   * stopped carrying every declared class.
   */
  discoverPatternTypes(p: Node, model: SemanticModel,
      resolveType: (t: Type) => Type): void {
    if (p is StringLiteral) {
      // `case "lit":` can be a BARE literal-expression pattern.
      let {stringClass} = this.pass.wasm;
      if (stringClass != null) {
        let bsc = stringClass;
        this.pass.notePendingMemberReach(
            getClassMethodKey(getClassKey(bsc), "=="));
      }
    }
    if (p is NumberLiteral) {
      this.#reachBigIntPatternLiteral(p, model, resolveType);
    }
    if (p is LiteralPattern) {
      // `case "lit":` lowers to a DIRECT call to String.== resolved by
      // name (ir/patterns.zena stringPatternEq) — no call node for RTA.
      if (p.value is StringLiteral &&
          this.pass.wasm.stringClass != null) {
        let sc = this.pass.wasm.stringClass as ClassType;
        let scModel = this.pass.getClassModel(sc);
        for (let md in this.pass.cha.findImplementingMethods(sc, "==")) {
          this.pass.queueReferrer(new Referrer(false, noSymbolId,
              (md as Node).id as i32,
              this.pass.getNodeModel(md as Node, scModel), sc, true));
        }
        // And by key, deferred: the node referrer depends on find/arm
        // plumbing; the key lookup is what the lowering itself uses.
        this.pass.notePendingMemberReach(
            getClassMethodKey(getClassKey(sc), "=="));
      } else if (p.value is NumberLiteral) {
        this.#reachBigIntPatternLiteral(
            p.value as NumberLiteral, model, resolveType);
      }
    }
    if (p is ClassPattern) {
      let t = model.getNodeType(p.name);
      if (t != null) {
        this.pass.typeLowerer.discoverType(resolveType(t), model);
      }
      for (let prop in p.properties) {
        this.discoverPatternTypes(prop.value, model, resolveType);
      }
    } else if (p is Identifier) {
      let symOpt = model.resolveDeclaration(p);
      if (symOpt != null && symOpt.isType()) {
        let t = model.getNodeType(p);
        if (t != null) {
          this.pass.typeLowerer.discoverType(resolveType(t), model);
        }
      }
    } else if (p is AsPattern) {
      this.discoverPatternTypes(p.pattern, model, resolveType);
    } else if (p is BindingPattern) {
      this.discoverPatternTypes(p.pattern, model, resolveType);
    } else if (p is LogicalPattern) {
      this.discoverPatternTypes(p.left, model, resolveType);
      this.discoverPatternTypes(p.right, model, resolveType);
    } else if (p is TuplePattern) {
      for (let el in p.elements) {
        if (el != null) {
          this.discoverPatternTypes(el, model, resolveType);
        }
      }
    } else if (p is ArrayPattern) {
      for (let el in p.elements) {
        if (el != null) {
          this.discoverPatternTypes(el, model, resolveType);
        }
      }
    } else if (p is RestPattern) {
      this.discoverPatternTypes(p.pattern, model, resolveType);
    } else if (p is RecordPattern) {
      for (let prop in p.properties) {
        this.discoverPatternTypes(prop.value, model, resolveType);
      }
    }
  }

  /**
   * `==`/`!=` on ERASED operands lowers through the equality diamond
   * (ir/equality.zena), which dispatches `==`/`hashCode` through the
   * class vtable — the reason those two slots are kept even on
   * hierarchy-less classes. A program with no erased equality (and no
   * `hash` intrinsic use) needs neither slot; for `return
   * "Hello World"` they carried String.==, #regionEquals, hashCode
   * and both hash helpers — 633 bytes.
   */
  noteEqualityUse(bin: BinaryExpression, model: SemanticModel,
      resolveType: (t: Type) => Type): void {
    if (bin.operator != "==" && bin.operator != "!=") { return; }
    let lt = model.getNodeType(bin.left);
    let rt = model.getNodeType(bin.right);
    // An inline operand compares slot by slot (#812): what each slot's
    // type needs to compare is noted, the inline type itself never is.
    let inlineType = if (lt != null && inlineLayoutOf(this.pass.wasm, resolveType(lt)) != null) {
      resolveType(lt)
    } else if (rt != null && inlineLayoutOf(this.pass.wasm, resolveType(rt)) != null) {
      resolveType(rt)
    } else {
      null
    };
    if (inlineType != null) {
      let layout = inlineLayoutOf(this.pass.wasm, inlineType) as InlineLayout;
      for (let member in layout.members) {
        for (let el in member.elementTypes) {
          if (el is HoleType) {
            continue;
          }
          let leaf = baseType(el);
          this.#noteEqualityOperand(leaf, model);
          this.noteValueEquality(leaf, leaf, model);
        }
      }
      return;
    }
    if (lt != null) {
      this.#noteEqualityOperand(resolveType(lt), model);
    }
    if (rt != null) {
      this.#noteEqualityOperand(resolveType(rt), model);
    }
    if (lt != null && rt != null) {
      this.noteValueEquality(resolveType(lt), resolveType(rt), model);
    }
  }

  /**
   * What comparing one operand of type `t` needs: the erased comparison's
   * dispatch for an erased or interface operand, and a concrete class's
   * `==` operator, which ir/operators.zena calls by name with no call
   * node or dependency record (the template body says `T == T`), so it is
   * rooted from the use.
   */
  #noteEqualityOperand(t: Type, model: SemanticModel): void {
    // An operand's type may appear nowhere else, such as a call's record
    // result compared directly (`f() == g()`), and mapping it needs it
    // discovered.
    this.pass.typeLowerer.discoverType(t, model);
    let vt = typeToValType(this.pass.wasm, t);
    if (vt is ValTypeAnyRef || vt is ValTypeEqRef || vt is ValTypeStructRef ||
        isInterfaceOperand(t)) {
      this.pass.useEqualityDispatch();
    }
    this.#rootEqOperator(t, model);
  }

  /**
   * `==` on two record or tuple operands compares them field by field,
   * through one synthesized function per pair of operand types
   * (value-equality.zena). Registers that function and discovers both
   * types, then whatever comparing each pair of fields needs: a nested
   * pair's function, or what a scalar operand needs.
   */
  noteValueEquality(lt: Type, rt: Type, model: SemanticModel): void {
    let l = valueEqOperand(lt);
    let r = valueEqOperand(rt);
    if (l == null || r == null || !this.pass.currentReachable) {
      return;
    }
    // An existential compares the records it holds, through the erased
    // comparison (ir/existential.zena).
    if (isExistentialRecord(l as Type) || isExistentialRecord(r as Type)) {
      this.pass.equalityDispatchUsed = true;
      return;
    }
    let left = l as Type;
    let right = r as Type;
    let fields = valueEqFields(left, right);
    if (fields == null) {
      return;
    }
    let wasm = this.pass.wasm;
    let key = valueEqKey(left, right);
    if (let (true, existing) = wasm.valueEqFuncs.get(key)) {
      this.pass.markFunctionReached(existing);
      return;
    }
    this.pass.typeLowerer.discoverType(left, model);
    this.pass.typeLowerer.discoverType(right, model);
    let params = growable<ValType>([
      typeToValType(wasm, left),
      typeToValType(wasm, right),
    ]);
    let returns = growable<ValType>([new ValTypeI32()]);
    let fn = new WasmFunction(wasm.getSignature(params, returns), null, model);
    fn.name = '$valueEq';
    fn.valueEqLeft = left;
    fn.valueEqRight = right;
    wasm.valueEqFuncs[key] = fn;
    wasm.addFunction(fn);
    this.pass.markFunctionReached(fn);
    for (let f in fields) {
      if (valueEqOperand(f.left) != null && valueEqOperand(f.right) != null) {
        this.noteValueEquality(f.left, f.right, model);
      } else {
        this.#noteEqualityOperand(f.left, model);
        this.#noteEqualityOperand(f.right, model);
      }
    }
  }

  /**
   * `hash<T>` on a record or tuple type hashes its fields, through one
   * synthesized function per type (ir/equality.zena,
   * `lowerValueHashFunction`). Registers that function and discovers the
   * type, then what hashing each field needs: a nested record's or
   * tuple's function, or a class's `hashCode`.
   */
  /**
   * Registers the adapted record dispatches and existential conversions
   * recorded on `n`. Both `discoverNodeTypes` and `registerInstantiations`
   * run this: checker dependency records carry symbols only, and record
   * adaptations attach to expressions as well as `RecordPattern` and
   * `RestPattern` nodes.
   */
  #registerRecordAdaptations(n: Node, model: SemanticModel,
      resolveType: (t: Type) => Type): void {
    let typeLowerer = this.pass.typeLowerer;
    let unionAdaptation = model.getRecordUnionAdaptation(n);
    if (unionAdaptation != null) {
      // Every member needs both its own dispatch, to test the value
      // against, and a dispatch adapted to the target shape.
      let tgtRec = unwrapAliases(resolveType(unionAdaptation.target)) as RecordType;
      typeLowerer.discoverType(tgtRec, model);
      for (let member in unionAdaptation.members) {
        let srcRec = unwrapAliases(resolveType(member)) as RecordType;
        typeLowerer.discoverType(srcRec, model);
        let inFields = recordWasmFields(this.pass.wasm, srcRec, null);
        let outFields = recordWasmFields(this.pass.wasm, tgtRec, null);
        this.pass.wasm.getAdaptedRecordDispatch(model,
            inFields, sortedOptionalNames(srcRec),
            outFields, sortedOptionalNames(tgtRec));
      }
    }
    let adaptation = model.getRecordAdaptation(n);
    if (adaptation != null) {
      let srcRec = unwrapAliases(resolveType(adaptation.source)) as RecordType;
      let tgtRec = unwrapAliases(resolveType(adaptation.target)) as RecordType;
      typeLowerer.discoverType(tgtRec, model);
      typeLowerer.discoverType(srcRec, model);
      if (srcRec.isExistential || tgtRec.isExistential) {
        this.#registerExistentialConversion(srcRec, tgtRec, model);
      } else {
        let inFields = recordWasmFields(this.pass.wasm, srcRec, null);
        let outFields = recordWasmFields(this.pass.wasm, tgtRec, null);
        this.pass.wasm.getAdaptedRecordDispatch(model,
            inFields, sortedOptionalNames(srcRec),
            outFields, sortedOptionalNames(tgtRec));
      }
    }
  }

  /**
   * The tables a conversion involving an existential record type needs
   * (ir/existential.zena): a pack into an existential, from a closed
   * record (whose hash its `<hash>` slot calls) or from another
   * existential; a projection of an existential to a closed type naming
   * only fields it knows; or, for one naming others, an `as` decided at
   * run time, whose tables the analysis makes once every pack is known.
   */
  #registerExistentialConversion(srcRec: RecordType, tgtRec: RecordType, model: SemanticModel): void {
    let wasm = this.pass.wasm;
    let srcD = this.#dispatchOf(srcRec, model);
    let tgtD = this.#dispatchOf(tgtRec, model);
    if (tgtRec.isExistential) {
      var hashFunc: WasmFunction | null = null;
      if (!srcRec.isExistential) {
        this.noteValueHash(srcRec, model);
        if (let (true, f) = wasm.valueHashFuncs.get(valueHashKey(srcRec))) {
          hashFunc = f;
        }
      }
      wasm.getExistentialPack(model, srcD, tgtD, hashFunc);
      return;
    }
    var knows = true;
    for (let key in tgtRec.properties.keys()) {
      if (!srcRec.properties.has(key)) {
        knows = false;
      }
    }
    if (knows) {
      wasm.getForwardDispatch(model, srcD, tgtD);
    } else {
      this.pass.noteExistentialCastTarget(tgtD);
    }
  }

  #dispatchOf(rec: RecordType, model: SemanticModel): RecordDispatchInfo {
    let fields = recordWasmFields(this.pass.wasm, rec, null);
    return if (rec.isExistential)
        this.pass.wasm.getExistentialDispatch(model, fields, sortedOptionalNames(rec))
        else this.pass.wasm.getRecordDispatch(model, fields, sortedOptionalNames(rec));
  }

  noteValueHash(t: Type, model: SemanticModel): void {
    let v = valueEqOperand(t);
    if (v == null || !this.pass.currentReachable) {
      return;
    }
    // An existential hashes the record it holds, through its table.
    if (isExistentialRecord(v as Type)) {
      return;
    }
    let type = v as Type;
    let wasm = this.pass.wasm;
    let key = valueHashKey(type);
    if (let (true, existing) = wasm.valueHashFuncs.get(key)) {
      this.pass.markFunctionReached(existing);
      return;
    }
    this.pass.typeLowerer.discoverType(type, model);
    let params = growable<ValType>([typeToValType(wasm, type)]);
    let returns = growable<ValType>([new ValTypeI32()]);
    let fn = new WasmFunction(wasm.getSignature(params, returns), null, model);
    fn.name = '$valueHash';
    fn.valueHashType = type;
    wasm.valueHashFuncs[key] = fn;
    wasm.addFunction(fn);
    this.pass.markFunctionReached(fn);
    let fields = valueEqFields(type, type);
    if (fields == null) {
      return;
    }
    for (let f in fields) {
      if (valueEqOperand(f.left) != null) {
        this.noteValueHash(f.left, model);
      } else {
        this.#noteEqualityOperand(f.left, model);
      }
    }
  }

  /** Roots `==` (and hashCode, its pair) on a concrete class operand. */
  #rootEqOperator(rawT: Type, model: SemanticModel): void {
    // Literal types (`"a" == x`) carry their base class.
    let t = baseType(rawT);
    var ct: ClassType | null = null;
    if (t is ClassType && isConcrete(t)) {
      ct = t;
    } else if (t is UnionType) {
      // `T | null` unions still compare through the member's ==.
      for (let m in t.types) {
        if (m is ClassType && isConcrete(m)) { ct = m; }
      }
    }
    if (ct == null) { return; }
    let rooted = if (this.pass.currentReachable) this.#eqRootedReachable else this.#eqRootedVisited;
    if (!rooted.add(ct.uid)) { return; }
    if (this.pass.currentReachable) {
      this.#eqRootedVisited.add(ct.uid);
    }
    if (!ct.members.has("==") && !ct.isFinal) {
      this.pass.noteEqualityBase(ct);
    }
    // A case class's synthesized == dispatches its case-class FIELDS'
    // == through their class-vtable slots — and those slot decisions
    // bake at layout, before the reach-time flag flip would land.
    // Seeing case-class equality IS the evidence; set it now, during
    // the walk.
    if (ct.derivesEquality) {
      this.pass.useEqualityDispatch();
    }
    let ccModel = this.pass.getClassModel(ct);
    for (let md in this.pass.cha.findImplementingMethods(ct, "==")) {
      this.pass.queueReferrer(new Referrer(false, noSymbolId,
          (md as Node).id as i32,
          this.pass.getNodeModel(md as Node, ccModel), ct,
          this.pass.currentReachable));
    }
    // A case class's synthesized ==/hashCode have no AST node for the
    // find above; they are registered functions. Reach them by key —
    // deferred, since registration can postdate this walk.
    this.pass.notePendingMemberReach(getClassMethodKey(getClassKey(ct), "=="));
    this.pass.notePendingMemberReach(getClassMethodKey(getClassKey(ct), "hashCode"));
  }

  /**
   * What a contract clause's check needs when its condition is false
   * (`lowerContractClause`): the message, and the standard library
   * function the check calls with it. Both body walks come here, since
   * the checker's dependency records hold neither.
   */
  noteContractClause(clause: ContractClause): void {
    if (!this.pass.wasm.runsContractClause(clause)) { return; }
    this.noteStringLiteral(contractFailureMessage(clause));
    this.queueStdlibFunction('core', '$contractFailed');
  }

  /**
   * What a store into a `scoped T` field calls at this specialization
   * (emitScopedFieldReplace): the release of an owner it replaces, or
   * the function a store over a `Scoped<T>` calls. Both body walks come
   * here, since the checker's dependency records cannot name `T`'s
   * classes.
   */
  noteScopedFieldStore(assign: AssignmentExpression, model: SemanticModel,
      resolveType: (t: Type) => Type): void {
    if (assign.operator != null || !model.isScopedFieldStore(assign as Node)) { return; }
    let stored = model.getNodeType(assign.left);
    if (stored == null) { return; }
    let t = resolveType(stored);
    if (holdsOwner(t)) {
      this.pass.noteReleaseTargets(t, model);
    } else if (typeContainsScoped(t)) {
      this.queueStdlibFunction('core', '$scopedValueDropped');
    }
  }

  registerLiterals(root: Node): void {
    walkEnter(root, (n) => {
      if (n is StringLiteral) {
        this.noteStringLiteral(n.value);
      }
      if (n is TemplateElement) {
        this.noteStringLiteral(n.cooked);
      }
    });
  }

  /**
   * Registers a string-literal payload AND instantiates `String`. A
   * literal is the evidence that a String value exists in this program
   * — the class is no longer instantiated unconditionally at init, so
   * the evidence has to act here, where every literal passes through.
   * `instantiateClassType` early-returns once it has happened.
   */
  noteStringLiteral(value: String): void {
    if (targetUsesJsStrings(this.pass.wasm.target)) {
      this.pass.wasm.getImportedStringGlobal(value, this.pass.program.units[0].model);
      let sc = this.pass.wasm.stringClass;
      if (sc != null) {
        this.pass.specializer.instantiateClassType(
            sc, this.pass.getClassModel(sc));
        this.queueExplicitCtor(sc, "<constructor>.#fromHandle");
      }
      return;
    }
    this.pass.wasm.registerStringLiteral(value);
    let sc = this.pass.wasm.stringClass;
    if (sc != null) {
      this.pass.specializer.instantiateClassType(
          sc, this.pass.getClassModel(sc));
    }
  }

  /**
   * Discovers the generic INSTANTIATIONS under `root` — new
   * expressions (plus their explicit constructors), array literals,
   * and range expressions — without the full node-type walk. The
   * checker's dependency records let node-referrer processing skip
   * discoverNodeTypes, but those records are symbol-level: they carry
   * no monomorphic instantiations, exactly as they carry no string
   * literals (see registerLiterals above). Skipping the walk used to
   * silently lose `new Box<boolean>(...)` inside dependency-carrying
   * method bodies: the specialization surfaced only through type
   * annotations (constructor queued as merely checkable) and its
   * constructor was never registered.
   */
  registerInstantiations(root: Node, model: SemanticModel, resolveType: (t: Type) => Type,
      classType: ClassType | null): void {
    let specializer = this.pass.specializer;
    // The body's own mixin scope, if it was written in a mixin: it
    // decides which member a private name in this body refers to.
    let bodyScope = mixinScopeOfNode(model, root);
    walkEnter(root, (n) => {
      // Private-method calls are lexically bound and never virtual, so
      // the dependency records are their ONLY discovery edge when the
      // body walk is skipped — and the records miss them for
      // specialized generics (the third organ of this disease, after
      // string literals and generic instantiations). Queue the
      // declaration node against the walking specialization, exactly
      // like the explicit-constructor promotion.
      if (n is TaggedTemplateExpression) {
        this.registerTaggedTemplate(n, model);
      }
      if (n is TemplateLiteral) {
        this.registerTemplateLiteral(n, model, resolveType);
      }
      this.maybeRegisterBigIntNode(n, model, resolveType);
      if (n is ContractClause) {
        this.noteContractClause(n);
      }
      if (n is AssignmentExpression) {
        this.noteScopedFieldStore(n, model, resolveType);
      }
      // A `for await`'s Pending arm is a node-level fact too: the
      // records say a body iterates, and nothing about what future
      // the loop suspends on.
      if (n is ForInStatement) {
        this.registerForInPendingArm(n, model, resolveType);
      }
      // So are the interface members the body dispatches through.
      this.noteInterfaceDispatch(n, model, resolveType);
      // Interface adaptations (a class value packed at an interface
      // slot) are node-level facts the dependency records never carry
      // — the fourth organ. Without this, a generic class packed into
      // an interface from a specialized body has a struct and no
      // class-interface vtable, and lowering's iface_pack fails.
      if (n is Expression) {
        let ifaceAdaptation = model.getInterfaceAdaptation(n);
        if (ifaceAdaptation != null) {
          let srcT = resolveType(ifaceAdaptation.source);
          let tgtT = resolveType(ifaceAdaptation.target);
          if (srcT is ClassType && tgtT is InterfaceType) {
            this.pass.demandPackPair(srcT, tgtT);
          } else if (srcT is InterfaceType && tgtT is InterfaceType) {
            this.pass.typeLowerer.discoverType(srcT, model);
            this.pass.typeLowerer.discoverType(tgtT, model);
          }
        }
      }
      this.#registerRecordAdaptations(n, model, resolveType);
      // Cast/test targets and local binding types are the types a
      // BODY names without any signature or dependency record naming
      // them — a lowered `as` is a ref.cast to the target's struct,
      // and a local is declared with its binding's valtype. The
      // records are symbol-level (organ seven, after literals and
      // instantiations); while every classInfos struct was emitted
      // wholesale this was invisible, and pruning to evidence surfaced
      // it as `Invalid WasmType index < 0` at emit.
      if (n is AsExpression) {
        let t = model.getNodeType(n);
        if (t != null) {
          this.pass.typeLowerer.discoverType(resolveType(t), model);
        }
      }
      if (n is BinaryExpression) {
        this.noteEqualityUse(n, model, resolveType);
      }
      if (n is IsExpression) {
        let t = model.getNodeType(n.typeAnnotation);
        if (t != null) {
          this.pass.typeLowerer.discoverType(resolveType(t), model);
        }
      }
      this.noteTypeTestSites(n, model, resolveType);
      if (n is VariableDeclaration) {
        let t = model.getNodeType(n.pattern);
        if (t != null) {
          this.pass.typeLowerer.discoverType(resolveType(t), model);
        }
      }
      // A boxed tuple or record literal in expression position names
      // its struct the same way a local does — organ seven, continued.
      if (n is TupleLiteral || n is RecordLiteral) {
        let t = model.getNodeType(n);
        if (t != null) {
          this.pass.typeLowerer.discoverType(resolveType(t), model);
        }
      }
      // Patterns test classes: `case Foo {..}:` and the bare
      // `case Foo:` both lower to a ref.test/cast against Foo's
      // struct (ir/patterns.zena) — body-named types with no record
      // naming them.
      if (n is MatchCase) {
        this.discoverPatternTypes(n.pattern, model, resolveType);
      }
      if (n is LetPatternCondition) {
        this.discoverPatternTypes(n.pattern, model, resolveType);
      }
      if (n is CallExpression) {
        this.#noteIntrinsicEqTargets(n, model, resolveType);
        this.#noteMethodCall(n, model, resolveType);
        // Plain identifier calls (module-level `let` functions,
        // including non-exported ones) are also absent from the
        // dependency records when the callee is private to its
        // module — organ five. Symbol referrers dedup, so
        // re-queueing exported ones is free.
        let calleeExpr = n.callee;
        if (calleeExpr is Identifier) {
          let calleeSym = model.resolve(calleeExpr);
          if (calleeSym != null) {
            let calleeTarget = calleeSym.resolveTarget();
            let calleeDecl = calleeTarget.declaration;
            var isToString = false;
            if (calleeDecl != null) {
              if (this.pass.wasm.intrinsics.has(calleeDecl.id)) {
                if (this.pass.wasm.intrinsics[calleeDecl.id] == "to_string") {
                  isToString = true;
                }
              }
              if (!isToString && calleeDecl is DeclareFunction) {
                for (let dec in calleeDecl.decorators) {
                  if (dec.name == "intrinsic" && dec.args.length == 1 && (decoratorStringArg(dec, 0) ?? "") == "to_string") {
                    isToString = true;
                    break;
                  }
                }
              }
            }
            if (isToString && n.args.length == 1) {
              this.registerToStringOperand(n.args[0], model, resolveType);
            }
            if (model.globalDeclarations.has(calleeTarget.id)) {
              this.pass.queueReferrer(new Referrer(true,
                  calleeTarget.id, -1, model, null, true));
              this.#noteRecordLiteralArgs(n, calleeTarget.id);
              this.#noteRecordResultCall(n, model, calleeTarget.id);
            }
          }
        }
      }
      if (classType != null && n is CallExpression) {
        let callee = n.callee;
        if (callee is MemberExpression) {
          let pName = callee.property.name;
          if (pName.length > 0 && pName.sliceBytes(0, 1) == "#") {
            // Generic private methods monomorphize per solved
            // type-argument list; thread the checker-solved arguments
            // (substituted into the walking specialization's context)
            // so the declaration registers its specialized copy under
            // the mangled slot name the call site will look up — not
            // just the shared template.
            var targs: Array<Type> | null = null;
            let calleeType = model.getNodeType(callee);
            if (calleeType is FunctionType) {
              let cTargs = calleeType.typeArguments;
              if (cTargs != null && cTargs.length > 0) {
                let resolved = new Array<Type>();
                for (let a in (cTargs as Array<Type>)) {
                  resolved.push(resolveType(a));
                }
                targs = resolved;
              }
            }
            if (bodyScope != null) {
              this.queueMixinPrivateMember(classType,
                  bodyScope, pName);
            } else {
              this.queuePrivateMethod(classType, pName, targs);
            }
          }
        }
      }
      // A private name READ in a mixin body reaches that mixin's
      // private ACCESSOR — the arm above only covers call position,
      // and on this walk (dependency records present) nothing else
      // looks at member expressions at all.
      if (classType != null && bodyScope != null && n is MemberExpression) {
        let pName = n.property.name;
        if (pName.length > 0 && pName.sliceBytes(0, 1) == "#") {
          this.queueMixinPrivateMember(classType,
              bodyScope, pName);
        }
      }
      // PUBLIC generic methods monomorphize per solved type-argument
      // list, exactly like the private ones handled above — and the
      // dependency records name the method without its arguments, so
      // on this walk the specialized slot the call site will look up
      // (`map_spec_i32`) is never registered. Organ six. It went
      // unnoticed for as long as an instantiated class registered
      // every method it had.
      if (n is MemberExpression) {
        this.registerGenericMethodUse(n, model, resolveType);
        this.#noteMemberStaticTarget(n, model, resolveType);
      }
      // A primitive interpolation the checker boxed for its tag
      // (`setBoxAdaptation`): the box class appears on no expression
      // node, so the adaptation is its one mention here.
      if (n is TaggedTemplateExpression) {
        for (let sub in n.quasi.expressions) {
          let box = model.getBoxAdaptation(sub);
          if (box != null) {
            let resolvedBox = resolveType(box) as ClassType;
            if (isConcrete(resolvedBox) && !containsErasedType(resolvedBox as Type)) {
              specializer.instantiateClassType(resolvedBox, model);
            }
            this.queueExplicitCtor(resolvedBox, "<constructor>");
          }
        }
      }
      if (n is SuperInitializer) {
        this.#noteSplicedDefaultGlobals(n, n.args, model, resolveType);
      }
      if (n is NewExpression) {
        this.#noteSplicedDefaultGlobals(n, n.args, model, resolveType);
        let neType = model.getNodeType(n);
        let ctorName = if (n.constructorName != null) {
          getNodeMemberName(model, n.constructorName as Node)
        } else {
          "<constructor>"
        };
        let ctorMethodKey = if (ctorName == "<constructor>") "<constructor>" else "<constructor>." + ctorName;
        // A `new` on an interface (callee typed as the interface, below)
        // may be typed as the class its constructor declares; it
        // constructs nothing itself — the factory's body does — so the
        // class arm must not run for it.
        let calleeNodeT = model.getNodeType(n.callee);
        if (neType is ClassType && !(calleeNodeT is InterfaceType)) {
          let resolved = resolveType(neType) as ClassType;
          if (isConcrete(resolved) && !containsErasedType(resolved as Type)) {
            specializer.instantiateClassType(resolved, model);
          }
          this.queueExplicitCtor(resolved, ctorMethodKey);
          this.#noteRecordLiteralCtorArgs(n, resolved, ctorMethodKey);
        }
        // `new I<args>.name(...)` on an interface: the constructor is a
        // factory function specialized per type-argument list. The
        // checker types the CALLEE as the instantiated interface (the
        // expression itself may be typed as the class the constructor
        // declares); resolve it under the walk's arguments first, as the
        // class arm does. A mention with open parameters is a
        // template's — the specialization walk names the real
        // arguments — and nothing is emitted at an erasure, so neither
        // mints a copy.
        if (calleeNodeT is InterfaceType) {
          let resolvedI = resolveType(calleeNodeT);
          if (resolvedI is InterfaceType) {
            if (isConcrete(resolvedI) && !containsErasedType(resolvedI)) {
              this.registerInterfaceConstructorUse(resolvedI, ctorMethodKey);
            }
          }
        }
        // A resource `new` TYPES as its wrapper — `Own<C>` is an
        // OPAQUE type, so the arm above skips entirely — but it
        // CONSTRUCTS the resource class the CALLEE names. The callee
        // is the honest "constructed class" for every `new`. An
        // imported class is bound in its own module's model, which
        // `getBindingType` reaches through the binding index; a lookup
        // by id in this model alone missed it, and the constructor of
        // an imported resource class was never rooted.
        let calleeSym = model.resolve(n.callee);
        if (calleeSym != null) {
          let calleeT = model.getBindingType(calleeSym.resolveTarget());
          if (calleeT is ClassType) {
            this.queueExplicitCtor(resolveType(calleeT) as ClassType, ctorMethodKey);
          }
        }
      }
      if (n is MapLiteral) {
        this.registerMapLiteral(n, model, resolveType);
      }
      this.registerAsyncNode(n, model, resolveType);
      if (n is CallExpression) {
        this.#noteSplicedDefaultGlobals(n, n.args, model, resolveType);
        this.#noteIntrinsicEqTargets(n, model, resolveType);
        this.#noteMethodCall(n, model, resolveType);
        // Plain identifier calls: the dependency records omit
        // module-private symbols, so the call edge here is the only
        // discovery for non-exported top-level functions. Symbol
        // referrers dedup, so re-queueing exported callees is free.
        let calleeExpr = n.callee;
        if (calleeExpr is Identifier) {
          let calleeSym = model.resolve(calleeExpr);
          if (calleeSym != null) {
            let calleeTarget = calleeSym.resolveTarget();
            // Module-level declarations only: queueing LOCAL closure
            // variables preempts their proper function-expression
            // discovery (the reached-key blocks the real referrer).
            if (model.globalDeclarations.has(calleeTarget.id)) {
              this.pass.queueReferrer(new Referrer(true,
                  calleeTarget.id, -1, model, null,
                  this.pass.currentReachable));
              this.#noteRecordLiteralArgs(n, calleeTarget.id);
              this.#noteRecordResultCall(n, model, calleeTarget.id);
            }
          }
        }
      }
      if (n is ArrayLiteral) {
        let alType = model.getNodeType(n);
        if (alType != null) {
          let resolved = resolveType(alType);
          // Discover the array type structurally too: dependency records
          // are symbol-level, so on this walk (bodies with records skip
          // discoverNodeTypes) a structural ELEMENT type — an array of
          // tuple literals — would otherwise first materialize during
          // lowering, after layout locked the type section.
          this.pass.typeLowerer.discoverType(resolved, model);
          // No unconditional ImmutableArray<elem> instantiation here:
          // a literal LOWERS to array.new_fixed of the raw array —
          // there is no constructor call — and a program that names
          // ImmutableArray (an `as` cast, a `from` call) discovers it
          // through that mention like any other class.
        }
      }
      if (n is TupleLiteral) {
        // Boxed tuple literals need their struct before layout, for the
        // same records-are-symbol-level reason as the ArrayLiteral arm.
        let tlType = model.getNodeType(n);
        if (tlType != null) {
          this.pass.typeLowerer.discoverType(resolveType(tlType), model);
        }
      }
      if (n is RangeExpression && !isForInRangeLiteral(model, n)) {
        let reType = model.getNodeType(n);
        if (reType is ClassType) {
          let rangeCt = resolveType(reType) as ClassType;
          specializer.instantiateClassType(rangeCt, model);
          // A range literal CONSTRUCTS its range class — same tail as
          // `new` (lowering's #constructInstance) with no NewExpression.
          this.queueExplicitCtor(rangeCt);
        }
      }
    });
  }

  /**
   * Default argument expressions are spliced from the callee's AST into
   * the caller's argument list without re-checking them in the caller, so
   * globals they name are absent from the caller's dependency records and
   * may belong to another module's `globalDeclarations`.
   */
  #noteSplicedDefaultGlobals(
      node: Node,
      args: GrowableArray<Expression>,
      model: SemanticModel,
      resolveType: (t: Type) => Type): void {
    let orig = model.getOriginalArgCount(node);
    if (orig < 0 || orig >= args.length) {
      return;
    }
    var i = orig;
    while (i < args.length) {
      walkEnter(args[i], (n) => {
        if (n is Identifier) {
          let sym = model.resolve(n);
          if (sym != null) {
            let target = sym.resolveTarget();
            if (let (true, targetModel) = this.pass.symbolIdToModel.get(target.id)) {
              this.pass.queueReferrer(new Referrer(true, target.id, -1,
                  targetModel, null, this.pass.currentReachable));
              let parentNode = targetModel.getParent(n);
              if (parentNode is CallExpression && parentNode.callee === n) {
                this.#noteRecordLiteralArgs(parentNode, target.id);
                this.#noteRecordResultCall(parentNode, targetModel, target.id);
                let rawCalleeType = targetModel.getNodeType(n);
                if (rawCalleeType != null) {
                  let calleeType = resolveType(rawCalleeType);
                  if (calleeType is FunctionType) {
                    let {typeArguments} = calleeType;
                    if (typeArguments != null && typeArguments.length > 0) {
                      let resolvedArgs = new Array<Type>();
                      for (let arg in typeArguments) {
                        resolvedArgs.push(arg);
                      }
                      if (noOpenTypeParameters(resolvedArgs) &&
                          this.pass.wasm.genericFunctions.has(target.id)) {
                        let spec = this.pass.specializer.instantiateGenericFunction(
                            target.id, resolvedArgs);
                        this.#noteSpecializedCall(parentNode, targetModel, spec);
                      }
                    }
                  }
                }
              } else {
                let rawNodeType = targetModel.getNodeType(n);
                if (rawNodeType != null) {
                  this.discoverIdentifierReferenceAsValue(
                      n, targetModel, resolveType(rawNodeType));
                }
              }
            }
          }
        }
      });
      i += 1;
    }
  }

  /**
   * `eq(a, b)` and `hash(v)` lower inline to their operand class's `==`
   * or `hashCode` (ir/equality.zena), so the call reaches that method the
   * way a written `a == b` would. The intrinsic is recognized by its
   * decorator, since the call may be visited before the declaration is.
   */
  /** Records a direct call whose result is a record or a tuple. */
  #noteRecordResultCall(n: CallExpression, model: SemanticModel,
      callee: SymbolId): void {
    let t = model.getNodeType(n);
    if (t == null) {
      return;
    }
    let rt = unwrapAliases(t);
    if (!(rt is RecordType || rt is TupleType)) {
      return;
    }
    let id = (n as Node).id as i32;
    if (!this.pass.recordResultCallIds.has(id)) {
      this.pass.recordResultCallIds.add(id);
      this.pass.recordResultCalls.push(new RecordResultCall(n, model, callee));
    }
  }

  /**
   * Records a call of a method of a class, keyed by the method's
   * declaration: its record and tuple literal arguments, and the call
   * itself when its result is a record or a tuple (argument explosion,
   * ir/explode.zena). Only the lowering knows whether a call is direct;
   * these are the evidence that some call could pass or take the fields.
   */
  #noteMethodCall(n: CallExpression, model: SemanticModel,
      resolveType: (t: Type) => Type): void {
    let callee = n.callee;
    if (!(callee is MemberExpression) || callee.optional || callee.isSymbolAccess) {
      return;
    }
    let objType = model.getNodeType(callee.object);
    if (objType == null) {
      return;
    }
    // `hashCode()` on a record or tuple hashes it through its type's
    // function (ir/equality.zena).
    if (isValueHashCodeCall(n, callee, resolveType(objType), model)) {
      this.noteValueHash(resolveType(objType), model);
      return;
    }
    let resolved = baseType(resolveType(objType));
    if (!(resolved is ClassType)) {
      return;
    }
    let name = memberKeyOf(model, callee.property as Node);
    if (name == "") {
      return;
    }
    if (!isConcrete(resolved)) {
      return;
    }
    let md = this.pass.cha.findImplementingMethod(resolved, name, model.isStaticAccess(callee));
    if (md == null) {
      return;
    }
    let declaring = declaringInstantiation(this.pass.classDecls, resolved,
        md as Node);
    if (declaring == null) {
      return;
    }
    var target = methodTargetKey((md as Node).id as i32, declaring);
    // A generic method's call names the specialization for its solved
    // type arguments, as this walk sees them.
    if (md.typeParameters != null) {
      let ft = model.getNodeType(callee);
      if (!(ft is FunctionType)) {
        return;
      }
      let typeArgs = ft.typeArguments;
      if (typeArgs == null) {
        return;
      }
      let args = new Array<Type>();
      for (let a in typeArgs) {
        args.push(resolveType(a));
      }
      if (!noOpenTypeParameters(args)) {
        return;
      }
      target = specMethodTargetKey(target, getSpecializedName(name, args));
    }
    for (var i = 0; i < n.args.length; i += 1) {
      if (n.args[i] is RecordLiteral || n.args[i] is TupleLiteral) {
        this.pass.recordLiteralMethodArgs.add(recordLiteralMethodArgKey(target, i));
      }
    }
    let t = model.getNodeType(n);
    if (t == null) {
      return;
    }
    let rt = unwrapAliases(t);
    if (!(rt is RecordType || rt is TupleType)) {
      return;
    }
    // A call in a generic body resolves per instantiation, so it is
    // recorded once per target.
    let callKey = `${(n as Node).id as i32}|${target}`;
    if (!this.pass.recordResultMethodCalls.has(callKey)) {
      this.pass.recordResultMethodCalls.add(callKey);
      let rc = new RecordResultCall(n, model, noSymbolId);
      rc.methodTarget = target;
      this.pass.recordResultCalls.push(rc);
    }
  }

  /** Records the arguments of a `new` that are record or tuple literals. */
  #noteRecordLiteralCtorArgs(n: NewExpression, ct: ClassType,
      ctorMethodKey: String): void {
    let classKey = getClassKey(ct) as String;
    for (var i = 0; i < n.args.length; i += 1) {
      if (n.args[i] is RecordLiteral || n.args[i] is TupleLiteral) {
        this.pass.recordLiteralCtorArgs.add(
            recordLiteralCtorArgKey(classKey, ctorMethodKey, i));
      }
    }
  }

  /**
   * Records a call of the specialization `spec` of a generic function:
   * its record and tuple literal arguments, and the call itself when its
   * result is a record or a tuple (argument explosion, ir/explode.zena).
   * A call in a
   * generic body names a specialization per walk, so each is recorded
   * once per target.
   */
  #noteSpecializedCall(n: CallExpression, model: SemanticModel,
      spec: WasmFunction): void {
    let name = spec.name;
    if (name == null) {
      return;
    }
    let specName = name as String;
    for (var i = 0; i < n.args.length; i += 1) {
      if (n.args[i] is RecordLiteral || n.args[i] is TupleLiteral) {
        this.pass.recordLiteralSpecArgs.add(recordLiteralSpecArgKey(specName, i));
      }
    }
    let t = model.getNodeType(n);
    if (t == null) {
      return;
    }
    let rt = unwrapAliases(t);
    if (!(rt is RecordType || rt is TupleType)) {
      return;
    }
    let callKey = `${(n as Node).id as i32}|${specName}`;
    if (!this.pass.recordResultMethodCalls.has(callKey)) {
      this.pass.recordResultMethodCalls.add(callKey);
      let rc = new RecordResultCall(n, model, noSymbolId);
      rc.specTarget = specName;
      this.pass.recordResultCalls.push(rc);
    }
  }

  /** Records the arguments of a direct call that are record or tuple literals. */
  #noteRecordLiteralArgs(n: CallExpression, callee: SymbolId): void {
    for (var i = 0; i < n.args.length; i += 1) {
      if (n.args[i] is RecordLiteral || n.args[i] is TupleLiteral) {
        this.pass.recordLiteralArgs.add(recordLiteralArgKey(callee, i));
      }
    }
  }

  #noteIntrinsicEqTargets(n: CallExpression, model: SemanticModel,
      resolveType: (t: Type) => Type): void {
    if (!this.pass.currentReachable) {
      return;
    }
    let callee = n.callee;
    if (!(callee is Identifier)) {
      return;
    }
    let sym = model.resolve(callee);
    if (sym == null) {
      return;
    }
    let calleeType = model.getNodeType(callee);
    let calleeFt = if (calleeType is FunctionType) calleeType else null;
    let decl = findDeclaration(this.pass.wasm, sym.resolveTarget(), calleeFt);
    if (decl == null) {
      return;
    }
    var opName = "";
    var releases = false;
    for (let dec in decl.decorators) {
      if (dec.name == "intrinsic" && dec.args.length == 1) {
        let intrinsicName = decoratorStringArg(dec, 0) ?? "";
        if (intrinsicName == "eq") {
          opName = "==";
        } else if (intrinsicName == "hash") {
          opName = "hashCode";
        } else if (intrinsicName == "release_owned") {
          releases = true;
        }
      }
    }
    // `releaseOwned<T>` calls a resource's `:dispose`, or a future's
    // `[release]`, on what its type argument owns.
    if (releases && calleeFt != null) {
      let releaseArgs = calleeFt.typeArguments;
      if (releaseArgs != null) {
        for (let ta in releaseArgs) {
          this.pass.noteReleaseTargets(resolveType(ta), model);
        }
      }
      return;
    }
    if (opName == "") {
      return;
    }
    let argTypes = new Array<Type>();
    for (let arg in n.args) {
      let argType = model.getNodeType(arg);
      if (argType != null) {
        let resolved = resolveType(argType);
        argTypes.push(resolved);
        this.pass.notePendingStaticTargets(resolved, opName);
      }
    }
    // A record or tuple compares and hashes through a function per type
    // (ir/equality.zena), which the intrinsic lowers to a call of.
    if (opName == "==" && argTypes.length == 2) {
      this.noteValueEquality(argTypes[0], argTypes[1], model);
    } else if (opName == "hashCode" && argTypes.length == 1) {
      this.noteValueHash(argTypes[0], model);
    }
  }

  /**
   * A reached member access on a class-typed value reaches the function
   * lowering resolves for it, walking up from the value's class: the
   * method, the getter, and for an assignment target the setter. When
   * a subclass overrides it the call dispatches, and the analysis then
   * reaches the overrides (ReachabilityAnalysis.#fillReachedSlots).
   * Names that are not method table slots are dropped there.
   */
  #noteMemberStaticTarget(n: MemberExpression, model: SemanticModel,
      resolveType: (t: Type) => Type): void {
    if (!this.pass.currentReachable) {
      return;
    }
    let objType = model.getNodeType(n.object);
    if (objType == null) {
      return;
    }
    let rawResolved = resolveType(objType);
    let resolved = if (n.optional) getNonNullableType(rawResolved) else rawResolved;
    let propName = memberKeyOf(model, n.property as Node);
    if (propName == "") {
      return;
    }
    this.pass.notePendingStaticTargets(resolved, propName);
    this.pass.notePendingStaticTargets(resolved, "get#" + propName);
    let parent = model.getParent(n);
    if (parent is AssignmentExpression &&
        (parent.left as Node).id == (n as Node).id) {
      this.pass.notePendingStaticTargets(resolved, "set#" + propName);
    }
  }

  /**
   * Queues a specialization's explicit constructor as REACHABLE. The
   * instantiation may be cached from a type-only context (a union
   * annotation), where the constructor was queued as merely checkable
   * and instantiateClassType's dedup then skips re-queueing forever;
   * a `new` expression proves it reachable (queueReferrer dedupes by
   * node+class key, and its reachable branch promotes prior
   * checkable state).
   */
  queueExplicitCtor(resolved: ClassType, ctorMethodKey: String = "<constructor>"): void {
    // A `new` site is the constructor's evidence. Declared ctors are
    // walked as member referrers; SYNTHESIZED ctors (no `new(...)` in
    // the class body, or registered after this walk) have no node —
    // reach those by key at the settle drain. Blanket promotion at
    // instantiation used to cover both, at the cost of emitting a
    // constructor nothing calls (string literals build their String
    // with struct.new directly).
    // Record DEMAND against the generic (and its super chain, for the
    // `: super(...)` calls): a `new` site whose type arguments resolve
    // only at a later specialization still proves the generic's
    // constructors are called. Instantiation promotes registered
    // ctors for demanded generics; concrete sites also pend by key.
    var demandCt: ClassType | null = resolved;
    while (demandCt != null) {
      let dc = demandCt;
      if (dc.isMixinIntermediate) {
        demandCt = dc.superType;
        continue;
      }
      this.pass.ctorDemandedGenerics.add((dc.genericSource ?? dc).symbolId);
      demandCt = dc.superType;
    }
    if (isConcrete(resolved) && !containsErasedType(resolved as Type)) {
      this.pass.notePendingMemberReach(
          getClassMethodKey(getClassKey(resolved), ctorMethodKey));
    }
    let ctorDeclId = ((resolved.genericSource ?? resolved)).symbolId;
    if (!this.pass.classDecls.has(ctorDeclId)) {
      return;
    }
    let cdNode = this.pass.classDecls[ctorDeclId];
    if (!(cdNode is ClassDeclaration)) {
      return;
    }
    let cdModel = this.pass.classModels[ctorDeclId];
    let targetName = if (ctorMethodKey == "<constructor>") "<constructor>" else if (ctorMethodKey.startsWith("<constructor>.")) ctorMethodKey.sliceBytes(14, ctorMethodKey.length) else ctorMethodKey;
    for (let member in cdNode.body) {
      if (member is MethodDefinition) {
        if (member.isConstructor && ctorMethodName(cdModel, member) == targetName) {
          this.pass.queueReferrer(new Referrer(false, noSymbolId,
              (member as Node).id as i32, cdModel, resolved, true));
        }
      }
    }
  }

  /**
   * Mint the factory behind a `new` on an interface: the constructor's
   * body, specialized at the instantiation's type arguments. Every
   * interface declaration is indexed up front (analysis.zena), so a
   * miss here is a compiler bug.
   */
  registerInterfaceConstructorUse(it: InterfaceType, ctorMethodKey: String): void {
    let source = it.genericSource ?? it;
    let declId = source.symbolId;
    if (!this.pass.interfaceDecls.has(declId)) {
      throw new Error(`interface constructor: declaration of '${it.name}' is not indexed`);
    }
    let decl = this.pass.interfaceDecls[declId];
    let declModel = this.pass.interfaceModels[declId];
    let targetName = if (ctorMethodKey == "<constructor>") {
      "<constructor>"
    } else {
      ctorMethodKey.sliceBytes(14, ctorMethodKey.length)
    };
    for (let member in decl.body) {
      if (member is MethodDefinition) {
        if (member.isConstructor && ctorMethodName(declModel, member) == targetName) {
          this.pass.specializer.instantiateInterfaceConstructor(it, targetName, member, declModel);
          return;
        }
      }
    }
    throw new Error(`interface constructor '${targetName}' not found on '${it.name}'`);
  }

  /**
   * A map literal instantiates its checked HashMap class and calls its
   * constructor and `[]=` (lowerMapLiteral's shape), but carries no
   * NewExpression to prove the instantiation. Without this, a program
   * whose only HashMap construction is a literal — the tokenizer's
   * KEYWORDS global, reached from an external entry point — fails with
   * 'map constructor missing' in __start.
   */
  registerMapLiteral(ml: MapLiteral, model: SemanticModel,
      resolveType: (t: Type) => Type): void {
    let mlType = model.getNodeType(ml);
    if (mlType is ClassType) {
      let resolved = resolveType(mlType) as ClassType;
      this.pass.specializer.instantiateClassType(resolved, model);
      this.queueExplicitCtor(resolved);
      this.queuePrivateMethod(resolved, '[]=');
    }
  }

  /**
   * The `zena:async` runtime the A1 transform will call (async.md §3).
   *
   * RTA cannot see these calls: the split pass synthesizes them after
   * this analysis has finished. So an async function declares what its
   * frame needs, and an await site declares what its resume segment
   * needs — the same shape as for-in declaring `Iterator.next`.
   *
   * `isFrameFuture` distinguishes the two roles. An async function's
   * OWN `Future<T>` is constructed by the ramp and settled by step();
   * an AWAITED `Future<A>` is parked on and read back.
   */
  registerAsyncFuture(futureType: ClassType, model: SemanticModel,
      isFrameFuture: boolean): void {
    // A generic async function's TEMPLATE walk names its frame future
    // at the erasure. Nothing is emitted at an erasure: recording it
    // would queue cancellation machinery (private methods, a ctor) on
    // the erased class, which has no methods to register — each
    // specialization records its own concrete Future.
    if (containsErasedType(futureType as Type)) {
      return;
    }
    this.pass.specializer.instantiateClassType(futureType, model);
    this.pass.typeLowerer.discoverType(futureType as Type, model);
    if (isFrameFuture) {
      this.queueExplicitCtor(futureType);
      this.queuePrivateMethod(futureType, ':complete');
      this.queuePrivateMethod(futureType, ':fail');
      // `tail return` adoption (async.md §8): like valueOrThrow and
      // drainMicrotasks below, the split pass reaches this by name
      // with no call node to find, and whether THIS function adopts
      // is not worth an AST scan — one small method per frame future.
      this.queuePrivateMethod(futureType, ':adoptFrom');
      // The cancellation machinery is queued only when a reached body
      // can cause a cancellation (the whole-program gate). The frame
      // future is recorded either way, so a cause discovered in a
      // later round still equips every frame; with the machinery
      // already active, a newly discovered async function queues its
      // share immediately.
      this.pass.asyncFrameFutures.push(futureType as Type);
      this.pass.asyncFrameFutureModels.push(model);
      if (this.pass.cancellationMachineryActive) {
        this.queueCancellationMachinery(futureType, model);
      }
      // On core-module targets, an async `main` is driven by a
      // synthesized export wrapper that drains the queue and unwraps
      // the result (async.md §4, Level 0). Whether THIS function is
      // that main is not knowable here, so reach both pieces for any
      // async function on those targets.
      if (!targetEmitsComponent(this.pass.wasm.target)) {
        this.queuePrivateMethod(futureType, ':valueOrThrow');
        this.queueStdlibFunction('async', 'drainMicrotasks');
      }
    } else {
      this.queuePrivateMethod(futureType, ':valueOrThrow');
      this.queuePrivateMethod(futureType, ':subscribe');
    }
    this.registerTaskInterface(futureType, model);
  }

  /**
   * The frame implements `Task`, so its vtable struct must carry
   * a `resume` slot. Nothing in user code references the interface, so
   * mark it used HERE — by the time the split pass runs, the vtable
   * struct's fields are already fixed.
   *
   * The interface is read off `subscribe`'s parameter rather
   * than looked up by name: every async function resolves its own
   * `Future<T>` anyway, so this needs no well-known-type registry.
   */
  registerTaskInterface(futureType: ClassType,
      model: SemanticModel): void {
    if (!futureType.members.has(':subscribe')) {
      return;
    }
    let mi = futureType.members[':subscribe'];
    if (!(mi is MethodInfo)) {
      return;
    }
    let ft = mi.type;
    if (!(ft is FunctionType)) {
      return;
    }
    let params = ft.parameters;
    if (params.length != 1 || !(params[0] is InterfaceType)) {
      return;
    }
    let iface = params[0] as InterfaceType;
    this.pass.typeLowerer.discoverType(iface as Type, model);
    this.pass.demandInterfaceMember(iface, 'run');
  }

  /**
   * Queues everything an async function's frame needs once the
   * program is known to cause cancellations: the frame future's
   * cancelled-completion, the scope accessor, and CancelScope's
   * symbol-keyed methods (docs/design/cancellation.md). The
   * reachability pass calls this for every recorded frame when a
   * cause is first reached; later-discovered frames queue their own.
   */
  queueCancellationMachinery(futureType: ClassType, model: SemanticModel): void {
    this.queuePrivateMethod(futureType, ':cancelComplete');
    this.queueStdlibFunction('async', 'currentScope');
    // The checkpoint an async `tail return` emits before its callee's
    // eager ramp (async.md §8) — by name, like currentScope.
    this.queueStdlibFunction('async', 'checkCancellation');
    // The scope's constructors are symbol-keyed and reached by the
    // walks of currentScope (the root scope) and TaskGroup's
    // constructors (every other scope); nothing queues them by key.
    let scopeCt = this.cancelScopeType();
    if (scopeCt != null) {
      let sct = scopeCt as ClassType;
      this.pass.specializer.instantiateClassType(sct, model);
      this.queuePrivateMethod(sct, ':install');
      this.queuePrivateMethod(sct, ':checkpoint');
      this.queuePrivateMethod(sct, ':registerTask');
      this.queuePrivateMethod(sct, ':shieldScope');
      this.queueExplicitCtor(sct, '<constructor>.:childScope');
      this.queuePrivateMethod(sct, ':cancelScope');
    }
  }

  /**
   * The `CancelScope` class type, read off `currentScope`'s checked
   * return type — the same no-registry approach as the Task interface,
   * which is read off `subscribe`'s parameter. Null when `zena:async`
   * is not part of the program.
   */
  cancelScopeType(): ClassType | null {
    let prog = this.pass.program;
    if (!prog.unitsByPath.has('zena:async')) {
      return null;
    }
    let unit = prog.unitsByPath['zena:async'];
    for (let stmt in unit.ast.body) {
      let pattern = declaredPattern(stmt);
      if (pattern != null && pattern.name == 'currentScope') {
        let sym = unit.model.resolveDeclaration(pattern);
        let t = if (sym != null) unit.model.getBindingType(sym) else null;
        if (t != null && t is FunctionType) {
          let ret = t.returnType;
          if (ret is ClassType) {
            return ret;
          }
        }
      }
    }
    return null;
  }

  /**
   * An async function or an await expression, from either RTA walk.
   * Both reduce to "which Future instantiation does this need?".
   */
  registerAsyncNode(n: Node, model: SemanticModel,
      resolveType: (t: Type) => Type): void {
    if (n is AwaitExpression) {
      var awaited = model.getNodeType(n.argument);
      // A scoped future suspends on the future behind the wrapper.
      if (awaited != null && isScopedType(awaited)) {
        awaited = scopedInner(awaited) ?? awaited;
      }
      if (awaited != null) {
        let resolved = resolveType(awaited);
        if (resolved is ClassType) {
          this.registerAsyncFuture(resolved, model, false);
        } else if (resolved is UnionType) {
          // A union await suspends on whichever future arm arrived, so
          // every future arm's instantiation must exist
          // (registerAsyncFuture quietly skips bare arms — they have
          // no `subscribe`). The bare arms forward through the queue
          // hop, which needs scheduleTask.
          for (let arm in resolved.types) {
            let armResolved = resolveType(arm);
            if (armResolved is ClassType) {
              this.registerAsyncFuture(armResolved, model, false);
            }
          }
          this.queueStdlibFunction('async', 'scheduleTask');
        }
      }
      return;
    }
    var isAsyncFn = false;
    var isGenFn = false;
    match (n) {
      case FunctionExpression {isAsync, isGenerator}: {
        isAsyncFn = isAsync;
        isGenFn = isGenerator;
      }
      case MethodDefinition {isAsync, isGenerator}: {
        isAsyncFn = isAsync;
        isGenFn = isGenerator;
      }
      case _: {}
    }
    if (!isAsyncFn) {
      return;
    }
    let ft = model.getNodeType(n);
    if (ft == null || !(ft is FunctionType)) {
      return;
    }
    var retT = ft.returnType;
    // A Scoped-returning async function's frame future is the Future
    // behind the wrapper.
    if (isScopedType(retT)) {
      retT = scopedInner(retT) ?? retT;
    }
    let ret = resolveType(retT);
    if (isGenFn && ret is InterfaceType) {
      let iterIface = ret as InterfaceType;
      if (!containsErasedType(iterIface as Type)) {
        this.pass.typeLowerer.discoverType(iterIface as Type, model);
        this.pass.demandInterfaceMember(iterIface, 'next');
        let stepFuture = asyncIteratorPendingFuture(this.pass.wasm, iterIface);
        if (stepFuture != null) {
          let sf = stepFuture as ClassType;
          this.registerAsyncFuture(sf, model, true);
          let some = pendingSomeClass(sf);
          if (some != null) {
            let someCt = some as ClassType;
            this.pass.specializer.instantiateClassType(someCt, model);
            this.pass.typeLowerer.discoverType(someCt as Type, model);
            this.queueExplicitCtor(someCt);
          }
          let none = pendingNoneClass(sf);
          if (none != null) {
            let noneCt = none as ClassType;
            this.pass.specializer.instantiateClassType(noneCt, model);
            this.pass.typeLowerer.discoverType(noneCt as Type, model);
            this.queueExplicitCtor(noneCt);
          }
        }
      }
    } else if (ret is ClassType) {
      this.registerAsyncFuture(ret, model, true);
    }
    // On core-module targets, the async-main wrapper reaches
    // `zena:async.drainMicrotasks` through `getStdlibFunc`, so there is
    // no call node for RTA to find it by — async.zena throws outright
    // if it was not reached. Root it from the async function that
    // implies it, rather than from every program.
    if (!targetEmitsComponent(this.pass.wasm.target)) {
      this.queueStdlibFunction('async', 'drainMicrotasks');
    }
  }

  /**
   * Queues a module-level stdlib function by module path and export
   * name, for code the compiler synthesizes rather than reads out of
   * an AST — nothing in the program need reference it.
   */
  /**
   * Roots a standard library function that no source names — the
   * executor entries an await needs, a template's converter.
   *
   * Keyed on the owning LIBRARY, not a module id, and every file of that
   * library is searched. A library's declarations move between its files
   * as it is reorganized, and a re-export shim left at an old path is an
   * empty module to this walk — searching the library instead of one
   * module means neither breaks the rooting. It is the same rule the
   * well-known declaration registry uses for types.
   *
   * A miss throws. Returning quietly would leave an emitted call
   * pointing at a function nothing reached, and every caller here has
   * already decided the construct is present. Two files of one library
   * declaring the same name is equally an error: there would be no
   * answer to which one the emitted call meant.
   *
   * Where lowering has a documented fallback for a helper that may not
   * exist, the caller uses `queueOptionalStdlibFunction` and takes the
   * same branch lowering will.
   */
  /**
   * Records the members `n` calls through an interface vtable, so that
   * they get slots (ReachabilityContext.demandInterfaceMember): a member
   * read, call or write, an index read or write, a for-in's iteration
   * protocol, and an array pattern's length and element reads. Both body
   * walks run this: most bodies get registerInstantiations, with the
   * checker's dependency records standing in for the rest of the walk,
   * and those records hold no interface members.
   */
  noteInterfaceDispatch(n: Node, model: SemanticModel,
      resolveType: (t: Type) => Type): void {
    if (n is ArrayPattern) {
      this.pass.noteArrayPattern();
    } else if (n is MemberExpression) {
      let recv = interfaceReceiver(n.object, model, resolveType);
      if (recv != null) {
        let name = accessKeyOf(model, n);
        let isMethod = recv.members.has(name) && recv.members[name] is MethodInfo;
        this.pass.demandInterfaceMember(recv, if (isMethod) name else "get#" + name);
      }
    } else if (n is IndexExpression) {
      let recv = interfaceReceiver(n.object, model, resolveType);
      if (recv != null) {
        this.pass.demandInterfaceMember(recv, "[]");
      }
    } else if (n is AssignmentExpression) {
      let left = n.left;
      if (left is MemberExpression) {
        let recv = interfaceReceiver(left.object, model, resolveType);
        if (recv != null) {
          let name = accessKeyOf(model, left);
          this.pass.demandInterfaceMember(recv, "set#" + name);
        }
      } else if (left is IndexExpression) {
        let recv = interfaceReceiver(left.object, model, resolveType);
        if (recv != null) {
          this.pass.demandInterfaceMember(recv, "[]=");
        }
      }
    } else if (n is ForInStatement) {
      let t = model.getNodeType(n.iterable);
      if (t == null) {
        return;
      }
      let iterable = resolveType(t);
      if (iterable is ArrayType ||
          (iterable is ClassType && forInLowersToIndexLoop(iterable))) {
        return;
      }
      // Demanding a member of Iterable demands it of every interface
      // that extends Iterable too, so this covers an interface-typed
      // iterable as well as the iterator a class's `:iterator` returns.
      this.#demandPreludeMember(WellKnown.IterableInterface, ":iterator");
      this.#demandPreludeMember(WellKnown.IteratorInterface, "next");
      if (n.isAwait) {
        this.#demandPreludeMember(WellKnown.AsyncIterableInterface, ":asyncIterator");
        this.#demandPreludeMember(WellKnown.AsyncIteratorInterface, "next");
      }
    }
  }

  #demandPreludeMember(w: WellKnown, memberName: String): void {
    let iface = this.pass.findPreludeInterface(w);
    if (iface != null) {
      this.pass.demandInterfaceMember(iface, memberName);
    }
  }

  /**
   * Roots one iteration protocol a for-in drives over classes: for each
   * class the loop is known to iterate, its adaptation to the iterable
   * interface and its implementation of the symbol member. The slots
   * the loop dispatches through are noteInterfaceDispatch's.
   */
  rootIterationProtocol(iterable: WellKnown, symbolKey: String,
      protocolClasses: GrowableArray<ClassType>, model: SemanticModel): void {
    let iterableIface = this.pass.findPreludeInterface(iterable);
    if (iterableIface != null) {
      let cha = this.pass.cha;
      let typeLowerer = this.pass.typeLowerer;
      for (let resolvedClass in protocolClasses) {
        // The prelude's iterable is the generic declaration; the pair
        // the loop packs is the class's own specialization of it.
        let specializedIterable = findImplementedInterfaceType(this.pass.wasm, resolvedClass, iterableIface);
        this.pass.demandPackPair(resolvedClass, specializedIterable ?? iterableIface);

        let targetModel = this.pass.getClassModel(resolvedClass);
        let mds = cha.findImplementingMethods(resolvedClass, symbolKey);
        for (let md in mds) {
          this.pass.queueReferrer(new Referrer(false, noSymbolId, (md as Node).id as i32, this.pass.getNodeModel(md as Node, targetModel), resolvedClass, this.pass.currentReachable));
        }

        if (specializedIterable != null) {
          typeLowerer.discoverType(specializedIterable, model);
        }
      }
    }
  }

  /**
   * Roots what a `for await`'s Pending arm lowers to (async-iteration.md,
   * "Consuming"): the loop suspends on the step's future, whose type the
   * checker recorded on the statement, and reads `Some<V>`'s value out of
   * what it settles with. The checker records that type only for a loop
   * over an asynchronous iterator; a plain `for`, and a `for await` over
   * a synchronous one, has no Pending arm and roots nothing here.
   *
   * Called from both walks, since a body with dependency records skips the
   * full one.
   */
  registerForInPendingArm(n: ForInStatement, model: SemanticModel,
      resolveType: (t: Type) => Type): void {
    if (!n.isAwait) {
      return;
    }
    let pendingT = model.getNodeType(n);
    if (pendingT == null) {
      return;
    }
    let pendingFuture = resolveType(pendingT);
    if (pendingFuture is ClassType) {
      this.registerAsyncFuture(pendingFuture, model, false);
      let some = pendingSomeClass(pendingFuture);
      if (some != null) {
        this.pass.typeLowerer.discoverType(some, model);
      }
    }
  }

  queueStdlibFunction(library: String, exportName: String): void {
    if (!this.#tryQueueStdlibFunction(library, exportName)) {
      throw new Error("No file of standard library '" + library +
          "' declares '" + exportName + "'");
    }
  }

  /**
   * Roots `exportName` if the library declares it, and reports whether it
   * did. For helpers whose absence lowering handles by emitting
   * something else; the caller must then root that something else.
   */
  queueOptionalStdlibFunction(library: String, exportName: String): boolean {
    return this.#tryQueueStdlibFunction(library, exportName);
  }

  #tryQueueStdlibFunction(library: String, exportName: String): boolean {
    let prog = this.pass.program;
    var found: Symbol | null = null;
    var foundModel: SemanticModel | null = null;
    for (let unit in prog.units) {
      let owner = stdlibLibraryOf(unit.ast.path);
      if (owner == null || !stdlibLibraryAnswers(owner as String, library)) {
        continue;
      }
      for (let stmt in unit.ast.body) {
        // Declared either way: `export let name = (…) => …` or
        // `export function name(…) { … }`.
        let pattern = declaredPattern(stmt);
        if (pattern != null) {
          if (pattern.name == exportName) {
            let sym = unit.model.resolveDeclaration(pattern);
            if (sym == null) {
              throw new Error("Standard library '" + library + "' declares '" +
                  exportName + "' in " + unit.ast.path +
                  " but it did not resolve to a symbol");
            }
            if (found != null && (found as Symbol).id != sym.id) {
              throw new Error("Standard library '" + library +
                  "' declares '" + exportName + "' in more than one file");
            }
            found = sym;
            foundModel = unit.model;
          }
        }
      }
    }
    if (found == null) {
      return false;
    }
    this.pass.queueReferrer(new Referrer(true, (found as Symbol).id,
        -1, foundModel as SemanticModel, null, true));
    return true;
  }

  /**
   * Registers the monomorphized copy of a PUBLIC generic method named
   * by a member expression, under the mangled slot name the call site
   * will look up. Mirrors the generic-method branch of
   * discoverNodeTypes' MemberExpression arm, for the walk that skips
   * it. A non-generic member needs nothing here: the checker's
   * dependency records already name it.
   */
  registerGenericMethodUse(mem: MemberExpression, model: SemanticModel,
      resolveType: (t: Type) => Type): void {
    let objType = model.getNodeType(mem.object);
    if (objType == null) { return; }
    let rawResolvedObj = resolveType(objType);
    let resolvedObj = if (mem.optional) getNonNullableType(rawResolvedObj) else rawResolvedObj;
    if (resolvedObj is InterfaceType) {
      this.registerGenericInterfaceMethodUse(mem, model, resolveType, resolvedObj);
      return;
    }
    if (!(resolvedObj is ClassType)) { return; }
    let propName = if (mem.isSymbolAccess) ":" + mem.property.name else mem.property.name;
    let isStatic = model.isStaticAccess(mem);
    let members = resolvedObj.memberTable(isStatic);
    if (!members.has(propName)) { return; }
    let mi = members[propName];
    if (!(mi is MethodInfo)) { return; }
    // A static's receiver is the class NAME, so `resolvedObj` is the
    // unspecialized template — and that is the right registration
    // target: a static is outside its class's generic scope and
    // monomorphizes on its own solved arguments alone
    // (docs/design/generics.md, statics). Anything else reached
    // through a non-concrete receiver is an erasure mention and
    // registers nothing.
    if (!isConcrete(resolvedObj) && !mi.isStatic) { return; }
    var targetClass = resolvedObj;
    if (!isConcrete(targetClass)) {
      // Register the static's specialization under the ERASED class
      // key — the receiver key lowering's static lookup computes
      // (#lowerStaticCall erases the receiver before walking
      // classMethodMap). Registering under the raw template key parks
      // the copy where nothing ever looks.
      let erased = eraseTypeParameters(this.pass.wasm, targetClass as Type);
      if (!(erased is ClassType)) { return; }
      targetClass = erased;
    }
    let miType = mi.type;
    if (!(miType is FunctionType)) { return; }
    let {typeParameters} = miType;
    if (typeParameters == null || typeParameters.length == 0) {
      return;
    }
    // The checker solved the arguments onto the member's node type;
    // substitute them into the walking specialization's context, as
    // the private-method arm does.
    let useType = model.getNodeType(mem);
    if (useType == null || !(useType is FunctionType)) { return; }
    let rawArgs = useType.typeArguments;
    if (rawArgs == null || rawArgs.length == 0) { return; }
    let typeArgs = new Array<Type>();
    for (let a in rawArgs) {
      typeArgs.push(resolveType(a));
    }
    // A solved argument that is still a bare type parameter means this
    // walk is a generic body's TEMPLATE — a call in a generic function
    // whose own parameter feeds the method's. The mention is the
    // template of a call, not a call: every value it stands for
    // belongs to a specialization some real walk registers with its
    // own solved arguments. Minting at the erasure instead fails
    // loudly at lowering ("method not found @..._spec_erased").
    if (!noOpenTypeParameters(typeArgs)) { return; }
    let isPrivate = propName.length > 0 && propName.sliceBytes(0, 1) == "#";
    if (!mi.isStatic && !targetClass.isExtension && !isPrivate &&
        !containsErasedType(targetClass) &&
        !typeArgs.some((typeArg) => containsErasedType(typeArg))) {
      this.pass.demandGenericClassMethod(targetClass, propName, typeArgs, model);
      if (this.pass.currentReachable) {
        this.pass.notePendingStaticTargets(
            targetClass, getSpecializedName(propName, typeArgs));
      }
    }
    let unspecId = (targetClass.genericSource ?? targetClass).symbolId;
    let cd = if (let (true, decl) = this.pass.classDecls.get(unspecId)) decl else null;
    let targetModel = this.pass.getClassModel(targetClass);
            for (let md in this.pass.cha.findImplementingMethods(targetClass, propName)) {
      if (md.isStatic != isStatic) { continue; }
      let fn = this.pass.specializer.instantiateGenericMethod(targetClass, cd, propName, md as Node,
          typeArgs, this.pass.getNodeModel(md as Node, targetModel));
      // Registering is not enough. `WasmModule.layout()` REBUILDS
      // classMethodMap from `wasm.functions`, which RTA has already
      // pruned to reached functions — so a registered-but-unreached
      // specialization is erased from the map before lowering looks it
      // up, and lowering bails with "method not found". Reaching it is
      // what makes the registration survive. (This was invisible while
      // instantiation reached every method a class had.)
      this.pass.markFunctionReached(fn);
      this.pass.queueReferrer(new Referrer(false, noSymbolId, (md as Node).id as i32,
          this.pass.getNodeModel(md as Node, targetModel), targetClass,
          this.pass.currentReachable, typeArgs));
    }
  }

  /**
   * A generic method named through an INTERFACE-typed receiver: the
   * call dispatches virtually, so the solved type-argument list
   * becomes a vtable-slot demand on the interface specialization
   * (`demandGenericInterfaceMethod`). The class-interface vtable pass
   * instantiates each implementing class's monomorphized copy when it
   * fills the slot — classes can join the interface in later rounds,
   * so the fan-out cannot happen here. The template/erasure guards
   * mirror the class-receiver path above.
   */
  registerGenericInterfaceMethodUse(mem: MemberExpression, model: SemanticModel,
      resolveType: (t: Type) => Type, resolvedObj: InterfaceType): void {
    if (!isConcrete(resolvedObj) || containsErasedType(resolvedObj as Type)) { return; }
    let propName = if (mem.isSymbolAccess) ":" + mem.property.name else mem.property.name;
    if (!resolvedObj.members.has(propName)) { return; }
    let mi = resolvedObj.members[propName];
    if (!(mi is MethodInfo)) { return; }
    let miType = mi.type;
    if (!(miType is FunctionType)) { return; }
    let {typeParameters} = miType;
    if (typeParameters == null || typeParameters.length == 0) {
      return;
    }
    let useType = model.getNodeType(mem);
    if (useType == null || !(useType is FunctionType)) { return; }
    let rawArgs = useType.typeArguments;
    if (rawArgs == null || rawArgs.length == 0) { return; }
    let typeArgs = new Array<Type>();
    for (let a in rawArgs) {
      typeArgs.push(resolveType(a));
    }
    if (!noOpenTypeParameters(typeArgs)) { return; }
    for (let a in typeArgs) {
      if (containsErasedType(a)) { return; }
    }
    this.pass.demandGenericInterfaceMethod(resolvedObj, propName, typeArgs, model);
  }


  /**
   * Roots the helpers a template literal's lowering resolves BY NAME
   * (`getStdlibFunc`) instead of through a call node: the per-operand
   * `zena:string-convert` converter, and the `__concatN` /
   * `String.fromRawParts` join. RTA cannot see those calls, so nothing
   * else roots them — the pass used to compensate by reaching every
   * numeric converter in every program, which is most of what a
   * hello-world carried.
   *
   * `ir/templates.zena` decides the same two things from the same AST;
   * the part count is `2 * expressions + 1` there and here, and the
   * converter name comes from the shared `templateConvertHelperName`.
   * A disagreement surfaces as `Invalid function call: function index
   * < 0`, not as bad code.
   */
  registerToStringOperand(expr: Expression, model: SemanticModel,
      resolveType: (t: Type) => Type): void {
    let t = model.getNodeType(expr);
    if (t == null) { return; }
    let resolvedT = resolveType(t);
    if (containsErasedType(resolvedT)) {
      return;
    }
    if (resolvedT is NullType) {
      this.noteStringLiteral("null");
      return;
    }
    if (resolvedT is UnionType) {
      for (let m in resolvedT.types) {
        if (m is NullType) {
          this.noteStringLiteral("null");
          break;
        }
      }
    }
    let nonNullT = getNonNullableType(resolvedT);
    let name = templateConvertHelperName(nonNullT);
    if (name != "") {
      this.queueStdlibFunction('core', name);
      return;
    }
    let bt = baseType(nonNullT);
    if (bt is ClassType) {
      if (isWellKnown(WellKnown.StringClass, bt.name, bt.sourcePath)) {
        return;
      }
      let stringableIface = findImplementedWellKnownInterface(this.pass.wasm, bt, WellKnown.StringableInterface);
      if (stringableIface != null) {
        let ccModel = this.pass.getClassModel(bt);
        let mds = this.pass.cha.findImplementingMethods(bt, ":toString");
        for (let md in mds) {
          this.pass.queueReferrer(new Referrer(false, noSymbolId,
              (md as Node).id as i32,
              this.pass.getNodeModel(md as Node, ccModel), bt,
              this.pass.currentReachable));
        }
        this.pass.notePendingMemberReach(getClassMethodKey(getClassKey(bt), ":toString"));
        if (this.pass.currentReachable) {
          this.pass.notePendingStaticTargets(bt, ":toString");
        }
      } else {
        this.noteStringLiteral(`<${bt.name}>`);
      }
    } else if (bt is InterfaceType) {
      let stringableIface = findExtendedWellKnownInterface(this.pass.wasm, bt, WellKnown.StringableInterface);
      if (stringableIface != null) {
        this.pass.demandInterfaceMember(bt, ":toString");
        this.pass.demandInterfaceMember(stringableIface, ":toString");
      } else {
        this.noteStringLiteral(`<${bt.name}>`);
      }
    } else if (bt is RecordType) {
      this.noteStringLiteral("<record>");
    } else if (bt is TupleType || bt is InlineTupleType) {
      this.noteStringLiteral("<tuple>");
    } else {
      this.noteStringLiteral("<object>");
    }
  }

  registerTemplateLiteral(tpl: TemplateLiteral, model: SemanticModel,
      resolveType: (t: Type) => Type): void {
    if (tpl.expressions.length == 0) {
      // Lowers to a plain string literal; no helper involved.
      return;
    }
    for (let e in tpl.expressions) {
      this.registerToStringOperand(e, model, resolveType);
    }
    let partCount = tpl.expressions.length * 2 + 1;
    // `__concatN` is an optimization the standard library does not
    // currently provide, and lowering falls through to String.fromParts
    // when it is absent. Root whichever one lowering will emit, by
    // asking the same question it asks.
    if (partCount >= 2 && partCount <= 5 &&
        this.queueOptionalStdlibFunction('core',
            '__concat' + i32ToString(partCount))) {
      return;
    }
    // Otherwise the join goes through String.fromParts over a
    // FixedArray<String>, so both have to exist.
    let {stringClass} = this.pass.wasm;
    if (stringClass != null) {
      let sc = stringClass;
      let scModel = this.pass.getClassModel(sc);
      for (let md in this.pass.cha.findImplementingMethods(sc, 'fromRawParts')) {
        this.pass.queueReferrer(new Referrer(false, noSymbolId,
            (md as Node).id as i32,
            this.pass.getNodeModel(md as Node, scModel), sc,
            this.pass.currentReachable));
      }
      this.pass.typeLowerer.discoverType(new ArrayType(sc, true), model);
    }
  }

  /**
   * Queues a specialization's private method (by name) as reachable.
   *
   * The walk covers the SUPER CHAIN, not just `classType`'s own body:
   * the accessing body may be an inherited method walked under a
   * subclass's context, and the private it names is declared on the
   * ancestor. Every chain hop declaring the name is queued (privates
   * are lexical, so under shadowing only the accessor's own class's
   * copy is called — the extra hop is an over-reach, never a wrong
   * binding). Each hop is already the declaring class's resolved
   * instantiation, which is also the key registration uses
   * (binary-size.md §16).
   */
  queuePrivateMethod(classType: ClassType, methName: String,
      typeArguments: Array<Type> | null = null): void {
    var c: ClassType | null = classType;
    while (c != null) {
      let cc = c;
      let declId = ((cc.genericSource ?? cc)).symbolId;
      if (this.pass.classDecls.has(declId)) {
        let cdNode = this.pass.classDecls[declId];
        if (cdNode is ClassDeclaration) {
          let cdModel = this.pass.classModels[declId];
          for (let member in cdNode.body) {
            if (member is MethodDefinition && !member.isConstructor) {
              if (ctorMethodName(cdModel, member) == methName) {
                if (typeArguments != null &&
                    typeArguments.length > 0) {
                  // Generic private method: register the monomorphized
                  // copy under its specialized slot name, exactly like
                  // public generic member references do — queuing the
                  // bare declaration would only register the shared
                  // template.
                  this.pass.specializer.instantiateGenericMethod(cc,
                      cdNode, methName, member as Node,
                      typeArguments, cdModel);
                  this.pass.queueReferrer(new Referrer(false, noSymbolId,
                      (member as Node).id as i32, cdModel, cc, true, typeArguments));
                } else {
                  this.pass.queueReferrer(new Referrer(false, noSymbolId,
                      (member as Node).id as i32, cdModel, cc, true));
                }
              }
            }
          }
        }
      }
      c = cc.superType;
    }
  }

  /**
   * Queues the mixin-scoped private member a mixin body names, as used
   * by the host class the body is being compiled for.
   *
   * This is the referrer that mixin privates used to lack, and whose
   * absence was covered by force-reaching every "::"-named member of
   * every instantiated class. `scope` is the accessing body's own
   * mixin scope key, and it decides WHICH member is meant: a private
   * name in a mixin body is that mixin's, whatever same-named private
   * the host or another mixin declares. Searching by name and taking
   * the first hit (what the CHA member searches do) would find the
   * host's, which is a different member entirely.
   *
   * The node referrer registers under the scoped name on its own —
   * both the method and accessor arms of the referrer loop re-derive
   * the scope from the member's declaration — so this only has to name
   * the right declaration.
   */
  queueMixinPrivateMember(classType: ClassType, scope: String,
      propName: String): void {
    let declId = ((classType.genericSource ?? classType)).symbolId;
    if (!this.pass.classDecls.has(declId)) {
      return;
    }
    let cdNode = this.pass.classDecls[declId];
    if (!(cdNode is ClassDeclaration)) {
      return;
    }
    let cdModel = this.pass.classModels[declId];
    let members = new Array<Node>();
    let scopes = new Array<String>();
    let seen = new Map<MixinKey, boolean>();
    collectMixinMembers(this.pass.program, cdModel,
        cdNode.mixins, members, seen, scopes);
    for (var i = 0; i < members.length; i += 1) {
      if (scopes[i] != scope) { continue; }
      let member = members[i];
      var name = "";
      if (member is MethodDefinition && !member.isConstructor) {
        name = ctorMethodName(cdModel, member);
      } else if (member is AccessorDeclaration) {
        name = accessorMemberName(cdModel, member);
      } else {
        continue;
      }
      if (name != propName) { continue; }
      this.pass.queueReferrer(new Referrer(false, noSymbolId,
          member.id as i32, this.pass.getNodeModel(member, cdModel),
          classType, true));
    }
  }

  /**
   * TSA-cache global + tag reachability for one tagged template.
   * Shared by the full walk and the dependency-record skip path (the
   * records carry neither the cache global nor the tag reference —
   * organ four of the skipped-walk blindness).
   */
  registerTaggedTemplate(expr: TaggedTemplateExpression, model: SemanticModel): void {
        // The tag receives the raw text of each segment as well as the
        // cooked (`strings.raw`), and the lowering reads both out of the
        // string registry. The walk above notes every segment's cooked
        // text; a raw text that differs — a segment with an escape in
        // it — is a literal of its own.
        for (let quasi in expr.quasi.quasis) {
          if (quasi.raw != quasi.cooked) {
            this.noteStringLiteral(quasi.raw);
          }
        }

        if (!this.pass.wasm.templateLiteralGlobals.has(expr)) {
          var tsaStruct: WasmStruct | null = null;
          let tsaClass = this.pass.wasm.templateStringsArrayClass;
          if (tsaClass != null) {
            // A tagged template is the only thing that builds one, so
            // this is where the class becomes real. Instantiating it
            // because it was merely discovered would put its struct, its
            // two String arrays and its vtable global into every module
            // that imports a library re-exporting it — the same reason
            // `String` is not instantiated at discovery either.
            this.pass.specializer.instantiateClassType(
                tsaClass, this.pass.getClassModel(tsaClass));
            let key = getClassKey(tsaClass);
            if (let (true, tsaInfo) = this.pass.wasm.classInfos.get(key)) {
              tsaStruct = tsaInfo.structType;
            }
          }
          if (tsaStruct == null) {
            throw new Error("TemplateStringsArray class struct not found during tagged template literal discovery!");
          }
          
          let globalName = "tsa_cache_" + i32ToString(expr.id as i32);
          let globalType = new ValTypeRefNull(tsaStruct);
          let g = new WasmGlobal(
            globalName,
            globalName,
            globalType,
            true, // isMutable
            null, // initExpr
            null, // initVTable
            model
          );
          this.pass.wasm.globals.push(g);
          this.pass.wasm.templateLiteralGlobals[expr] = g;
        }
    if (expr.tag is Identifier) {
      let tagSym = model.resolve(expr.tag as Identifier);
      if (tagSym != null) {
        this.pass.queueReferrer(new Referrer(true, tagSym.id,
            -1, model, null, true));
      }
    }
  }

  #isBigIntType(t: Type): boolean {
    let core = baseType(soleNonNullMember(t) ?? t);
    return core is ClassType &&
        isWellKnown(WellKnown.BigIntClass, core.name, core.sourcePath);
  }

  #reachBigIntPatternLiteral(num: NumberLiteral, model: SemanticModel,
      resolveType: (t: Type) => Type): void {
    if (this.pass.wasm.bigIntClass == null) {
      return;
    }
    let t = model.getNodeType(num);
    if (!isBigIntLiteralRaw(num.raw) &&
        (t == null || !this.#isBigIntType(resolveType(t)))) {
      return;
    }
    this.registerBigIntLiteral(num.raw, false, model);
    let bc = this.pass.wasm.bigIntClass as ClassType;
    let bcModel = this.pass.getClassModel(bc);
    for (let md in this.pass.cha.findImplementingMethods(bc, "==")) {
      this.pass.queueReferrer(new Referrer(false, noSymbolId,
          (md as Node).id as i32,
          this.pass.getNodeModel(md as Node, bcModel), bc, true));
    }
    this.pass.notePendingMemberReach(
        getClassMethodKey(getClassKey(bc), "=="));
  }

  maybeRegisterBigIntNode(n: Node, model: SemanticModel,
      resolveType: (t: Type) => Type): void {
    if (n is UnaryExpression && n.operator == "-" && n.argument is NumberLiteral) {
      let t = model.getNodeType(n);
      if (t != null && this.#isBigIntType(resolveType(t))) {
        this.registerBigIntLiteral((n.argument as NumberLiteral).raw, true, model);
      }
      return;
    }
    if (n is NumberLiteral) {
      let parent = model.getParent(n);
      if (parent != null && parent is UnaryExpression &&
          parent.operator == "-") {
        let pt = model.getNodeType(parent);
        if (pt != null && this.#isBigIntType(resolveType(pt))) {
          return;
        }
      }
      let t = model.getNodeType(n);
      if (isBigIntLiteralRaw(n.raw) ||
          (t != null && this.#isBigIntType(resolveType(t)))) {
        this.registerBigIntLiteral(n.raw, false, model);
      }
    }
  }

  registerBigIntLiteral(raw: String, negative: boolean, model: SemanticModel): void {
    let bc = this.pass.wasm.bigIntClass;
    if (bc == null) {
      return;
    }
    this.pass.specializer.instantiateClassType(bc, this.pass.getClassModel(bc));
    this.pass.typeLowerer.discoverType(bc, model);
    this.pass.typeLowerer.discoverType(new ArrayType(new U64Type(), true), model);
    this.queuePrivateMethod(bc, '#fromMag');

    let (sign, limbs) = parseBigIntLiteralLimbs(raw, negative);
    let cacheKey = bigIntLiteralCacheKey(sign, limbs);
    if (!this.pass.wasm.bigIntLiteralGlobals.has(cacheKey)) {
      var bigIntStruct: WasmStruct | null = null;
      if (let (true, info) = this.pass.wasm.classInfos.get(getClassKey(bc))) {
        bigIntStruct = info.structType;
      }
      if (bigIntStruct == null) {
        throw new Error("BigInt class struct not found during literal discovery!");
      }
      let globalName = "bigint_lit_" + i32ToString(this.pass.wasm.bigIntLiteralGlobals.size);
      let g = new WasmGlobal(
        globalName,
        globalName,
        new ValTypeRefNull(bigIntStruct),
        true,
        null,
        null,
        model
      );
      this.pass.wasm.globals.push(g);
      this.pass.wasm.bigIntLiteralGlobals[cacheKey] = g;
    }
  }

  discoverNodeTypes(root: Node, model: SemanticModel, resolveType: (t: Type) => Type): void {
    // The body's own mixin scope, if it was written in a mixin: it
    // decides which member a private name in this body refers to.
    let bodyScope = mixinScopeOfNode(model, root);
    walkEnter(root, (n) => {
      // One field increment per node walked, on this class rather than
      // through `pass`: a compound write to a field reached through an
      // interface-typed reference does not lower ("zir unsupported:
      // interface compound write").
      this.#nodes += 1;
      if (n is ThrowExpression || n is TryExpression) {
        this.pass.noteExceptionInfra(model);
      }
      if (n is ContractClause) {
        this.noteContractClause(n);
      }
      if (n is AssignmentExpression) {
        this.noteScopedFieldStore(n, model, resolveType);
      }
      if (n is BinaryExpression) {
        this.noteEqualityUse(n, model, resolveType);
      }
      if (n is MatchCase) {
        this.discoverPatternTypes(n.pattern, model, resolveType);
      }
      if (n is LetPatternCondition) {
        this.discoverPatternTypes(n.pattern, model, resolveType);
      }
      this.noteInterfaceDispatch(n, model, resolveType);
      // `x is T`: the test's own type is boolean, so the target class
      // appears on no expression node — the annotation is the only
      // mention, exactly as in registerInstantiations. Without this, a
      // case class named only by an `is` (never constructed, never
      // cast to) has no struct when the body arrives through a symbol
      // referrer, and lowering bails with 'is target kind'.
      if (n is IsExpression) {
        let annotated = model.getNodeType(n.typeAnnotation);
        if (annotated != null) {
          this.pass.typeLowerer.discoverType(resolveType(annotated), model);
        }
      }
      this.noteTypeTestSites(n, model, resolveType);
      if (n is StringLiteral) {
        this.noteStringLiteral(n.value);
      }
      let typeLowerer = this.pass.typeLowerer;
      let specializer = this.pass.specializer;
      let t = model.getNodeType(n);
      if (t != null) {
        let resolved = resolveType(t);
        // A `function` declaration's own nodes — its name identifier
        // and its FunctionExpression — carry the function's type, but
        // they are not VALUE positions: a top-level `function` is
        // never a closure, and a genuine value use (the identifier in
        // an expression elsewhere, an arrow in value position) still
        // discovers the closure struct at that site. Discovering the
        // declaration's own type as a value minted a closure struct +
        // erased impl signature per declared function, used as a
        // value or not.
        var isDeclarationSignature = false;
        if (resolved is FunctionType) {
          // Method and accessor DEFINITIONS are signatures too: a
          // class-declaration walk visits every member, and treating
          // each member's function type as a value minted a closure
          // struct per method — 22 of them for a walk of String.
          if (n is MethodDefinition || n is AccessorDeclaration ||
              n is FunctionDeclaration) {
            isDeclarationSignature = true;
          } else {
            let parent = model.getParent(n);
            if (parent != null && (parent is FunctionDeclaration ||
                parent is MethodDefinition || parent is AccessorDeclaration)) {
              isDeclarationSignature = true;
            }
          }
        }
        if (isDeclarationSignature) {
          typeLowerer.discoverSignatureType(resolved, model);
        } else {
          typeLowerer.discoverType(resolved, model);
        }
      }
      // A primitive interpolation the checker boxed for its tag
      // (`setBoxAdaptation`): the box class appears on no expression
      // node, so the adaptation is its one mention here.
      if (n is TaggedTemplateExpression) {
        for (let sub in n.quasi.expressions) {
          let box = model.getBoxAdaptation(sub);
          if (box != null) {
            let resolvedBox = resolveType(box) as ClassType;
            if (isConcrete(resolvedBox) && !containsErasedType(resolvedBox as Type)) {
              specializer.instantiateClassType(resolvedBox, model);
            }
            this.queueExplicitCtor(resolvedBox, "<constructor>");
          }
        }
      }
      if (n is SuperInitializer) {
        this.#noteSplicedDefaultGlobals(n, n.args, model, resolveType);
      }
      if (n is NewExpression) {
        this.#noteSplicedDefaultGlobals(n, n.args, model, resolveType);
        let neType = model.getNodeType(n);
        let ctorName = if (n.constructorName != null) {
          getNodeMemberName(model, n.constructorName as Node)
        } else {
          "<constructor>"
        };
        let ctorMethodKey = if (ctorName == "<constructor>") "<constructor>" else "<constructor>." + ctorName;
        // A `new` on an interface (callee typed as the interface, below)
        // may be typed as the class its constructor declares; it
        // constructs nothing itself — the factory's body does — so the
        // class arm must not run for it.
        let calleeNodeT = model.getNodeType(n.callee);
        if (neType is ClassType && !(calleeNodeT is InterfaceType)) {
          let resolved = resolveType(neType) as ClassType;
          if (isConcrete(resolved) && !containsErasedType(resolved as Type)) {
            specializer.instantiateClassType(resolved, model);
          }
          this.queueExplicitCtor(resolved, ctorMethodKey);
          this.#noteRecordLiteralCtorArgs(n, resolved, ctorMethodKey);
        }
        // `new I<args>.name(...)` on an interface: the constructor is a
        // factory function specialized per type-argument list. The
        // checker types the CALLEE as the instantiated interface (the
        // expression itself may be typed as the class the constructor
        // declares); resolve it under the walk's arguments first, as the
        // class arm does. A mention with open parameters is a
        // template's — the specialization walk names the real
        // arguments — and nothing is emitted at an erasure, so neither
        // mints a copy.
        if (calleeNodeT is InterfaceType) {
          let resolvedI = resolveType(calleeNodeT);
          if (resolvedI is InterfaceType) {
            if (isConcrete(resolvedI) && !containsErasedType(resolvedI)) {
              this.registerInterfaceConstructorUse(resolvedI, ctorMethodKey);
            }
          }
        }
        // A resource `new` TYPES as its wrapper — `Own<C>` is an
        // OPAQUE type, so the arm above skips entirely — but it
        // CONSTRUCTS the resource class the CALLEE names. The callee
        // is the honest "constructed class" for every `new`. An
        // imported class is bound in its own module's model, which
        // `getBindingType` reaches through the binding index; a lookup
        // by id in this model alone missed it, and the constructor of
        // an imported resource class was never rooted.
        let calleeSym = model.resolve(n.callee);
        if (calleeSym != null) {
          let calleeT = model.getBindingType(calleeSym.resolveTarget());
          if (calleeT is ClassType) {
            this.queueExplicitCtor(resolveType(calleeT) as ClassType, ctorMethodKey);
          }
        }
      }
      if (n is MapLiteral) {
        this.registerMapLiteral(n, model, resolveType);
      }
      this.registerAsyncNode(n, model, resolveType);
      if (n is CallExpression) {
        this.#noteSplicedDefaultGlobals(n, n.args, model, resolveType);
        this.#noteIntrinsicEqTargets(n, model, resolveType);
        this.#noteMethodCall(n, model, resolveType);
        // Plain identifier calls: the dependency records omit
        // module-private symbols, so the call edge here is the only
        // discovery for non-exported top-level functions. Symbol
        // referrers dedup, so re-queueing exported callees is free.
        let calleeExpr = n.callee;
        if (calleeExpr is Identifier) {
          let calleeSym = model.resolve(calleeExpr);
          if (calleeSym != null) {
            let calleeTarget = calleeSym.resolveTarget();
            let calleeDecl = calleeTarget.declaration;
            var isToString = false;
            if (calleeDecl != null) {
              if (this.pass.wasm.intrinsics.has(calleeDecl.id)) {
                if (this.pass.wasm.intrinsics[calleeDecl.id] == "to_string") {
                  isToString = true;
                }
              }
              if (!isToString && calleeDecl is DeclareFunction) {
                for (let dec in calleeDecl.decorators) {
                  if (dec.name == "intrinsic" && dec.args.length == 1 && (decoratorStringArg(dec, 0) ?? "") == "to_string") {
                    isToString = true;
                    break;
                  }
                }
              }
            }
            if (isToString && n.args.length == 1) {
              this.registerToStringOperand(n.args[0], model, resolveType);
            }
            // Module-level declarations only: queueing LOCAL closure
            // variables preempts their proper function-expression
            // discovery (the reached-key blocks the real referrer).
            if (model.globalDeclarations.has(calleeTarget.id)) {
              this.pass.queueReferrer(new Referrer(true,
                  calleeTarget.id, -1, model, null,
                  this.pass.currentReachable));
              this.#noteRecordLiteralArgs(n, calleeTarget.id);
              this.#noteRecordResultCall(n, model, calleeTarget.id);
            }
          }
        }
      }
      if (n is ArrayLiteral) {
        let alType = model.getNodeType(n);

        if (alType != null) {
          // Discover the literal's type (the raw array roots itself as
          // a composite; a class type roots normally). The
          // unconditional ImmutableArray<elem> instantiation that used
          // to live here is gone — see the record-path arm.
          this.pass.typeLowerer.discoverType(resolveType(alType), model);
        }
      }
      if (n is RangeExpression && !isForInRangeLiteral(model, n)) {
        let reType = model.getNodeType(n);
        if (reType is ClassType) {
          let rangeCt = resolveType(reType) as ClassType;
          specializer.instantiateClassType(rangeCt, model);
          // A range literal CONSTRUCTS its range class — same tail as
          // `new` (lowering's #constructInstance) with no NewExpression.
          this.queueExplicitCtor(rangeCt);
        }
      }
      this.#registerRecordAdaptations(n, model, resolveType);
      if (n is Expression) {
        let ifaceAdaptation = model.getInterfaceAdaptation(n);
        if (ifaceAdaptation != null) {
          let srcT = resolveType(ifaceAdaptation.source);
          let tgtT = resolveType(ifaceAdaptation.target) as InterfaceType;
          if (srcT is ClassType) {
            this.pass.demandPackPair(srcT, tgtT);
          } else if (srcT is InterfaceType) {
            this.pass.typeLowerer.discoverType(srcT, model);
            this.pass.typeLowerer.discoverType(tgtT, model);
          }
        }
      }
      if (n is TemplateElement) {
        this.noteStringLiteral(n.cooked);
      }
      if (n is TaggedTemplateExpression) {
        this.registerTaggedTemplate(n, model);
      }
      if (n is TemplateLiteral) {
        this.registerTemplateLiteral(n, model, resolveType);
      }
      this.maybeRegisterBigIntNode(n, model, resolveType);
      if (n is ForInStatement) {
        this.registerForInPendingArm(n, model, resolveType);
        let iterableType = model.getNodeType(n.iterable);
        if (iterableType != null) {
          let resolvedIterable = resolveType(iterableType);

          let resolvedIterableTypes = new Array<ClassType>();
          if (resolvedIterable is ClassType) {
            if (resolvedIterable.name.length >= 5 && resolvedIterable.name.sliceBytes(resolvedIterable.name.length - 5, resolvedIterable.name.length) == "_This") {
              // Find enclosing mixin declaration
              var enclosingMixinDecl: MixinDeclaration | null = null;
              var curr = n as Node;
              while (true) {
                let parent = model.getParent(curr);
                if (parent == null) { break; }
                if (parent is MixinDeclaration) {
                  enclosingMixinDecl = parent;
                  break;
                }
                curr = parent;
              }
              if (enclosingMixinDecl != null) {
                var mixinSym = model.resolve(enclosingMixinDecl.name);
                if (mixinSym == null) {
                  mixinSym = model.resolve(enclosingMixinDecl);
                }
                if (mixinSym != null) {
                  let mixKey = getMixinKeyFromSymbol(model, mixinSym);
                  if (this.pass.mixinToClasses.has(mixKey)) {
                    let classes = this.pass.mixinToClasses[mixKey];
                    for (let cType in classes) {
                      resolvedIterableTypes.push(cType);
                    }
                  }
                }
              }
            } else {
              resolvedIterableTypes.push(resolvedIterable);
            }
          } else if (resolvedIterable is ThisType) {
            // Find enclosing ClassDeclaration or MixinDeclaration
            var enclosingClassDecl: ClassDeclaration | null = null;
            var enclosingMixinDecl: MixinDeclaration | null = null;
            var curr = n as Node;
            while (true) {
              let parent = model.getParent(curr);
              if (parent == null) { break; }
              if (parent is ClassDeclaration) {
                enclosingClassDecl = parent;
                break;
              }
              if (parent is MixinDeclaration) {
                enclosingMixinDecl = parent;
                break;
              }
              curr = parent;
            }
            if (enclosingClassDecl != null) {
              let ct = this.pass.getClassDeclType(enclosingClassDecl, model);
              if (ct != null) {
                resolvedIterableTypes.push(ct);
              }
            } else if (enclosingMixinDecl != null) {
              var mixinSym = model.resolve(enclosingMixinDecl.name);
              if (mixinSym == null) {
                mixinSym = model.resolve(enclosingMixinDecl);
              }
              if (mixinSym != null) {
                let mixKey = getMixinKeyFromSymbol(model, mixinSym);
                if (this.pass.mixinToClasses.has(mixKey)) {
                  let classes = this.pass.mixinToClasses[mixKey];
                  for (let cType in classes) {
                    resolvedIterableTypes.push(cType);
                  }
                }
              }
            }
          } else if (resolvedIterable is ArrayType) {
            // A bare array iterable lowers to array.len/array.get
            // directly, but the wasm array TYPE those instructions
            // reference still has to exist. Instantiating
            // FixedArray<elem> here — as this arm used to — was what
            // put three FixedArray specializations (the element type
            // plus siblings) in a program whose only loop is over an
            // array literal.
            this.pass.typeLowerer.discoverType(resolvedIterable, model);
          }

          // lowerForIn (ir/control-flow.zena) compiles a for-in over
          // FixedArray, ImmutableArray or Array to a direct index loop
          // — no :iterator call, no ArrayIterator, no Iterable
          // dispatch — so those iterables must root none of the
          // protocol machinery. The filter mirrors lowerForIn's
          // dispatch; a class skipped here that lowering DOES
          // iterator-path fails loudly there, never silently.
          let protocolClasses = new Array<ClassType>();
          for (let rc in resolvedIterableTypes) {
            if (!forInLowersToIndexLoop(rc)) {
              protocolClasses.push(rc);
            } else if (!(n.iterable is RangeExpression &&
                isForInRangeLiteral(model, n.iterable))) {
              // The index loop still consumes the VALUE: the class —
              // and through it an extension's raw representation type,
              // which array.len/array.get reference — must exist even
              // though no method on it is ever called. A range literal
              // is the exception: the loop reads its bounds directly
              // and no range value exists.
              this.pass.typeLowerer.discoverType(rc, model);
            }
          }
          let usesIteratorProtocol = if (resolvedIterable is ArrayType) {
            false
          } else if (resolvedIterable is ClassType ||
              resolvedIterable is ThisType) {
            protocolClasses.length > 0
          } else {
            // Interfaces, type parameters, unions: lowering takes the
            // iterator path for all of them.
            true
          };

          if (usesIteratorProtocol) {
            // The synchronous protocol first, then the asynchronous
            // one, in lowerForInIterator's order: a class that is an
            // Iterator or Iterable iterates synchronously in either
            // loop, and only a `for await` reaches AsyncIterator or
            // AsyncIterable (the checker rejects a plain `for` over
            // them). An interface receiver roots whichever protocol it
            // extends.
            let syncClasses = new Array<ClassType>();
            let asyncClasses = new Array<ClassType>();
            for (let rc in protocolClasses) {
              if (findImplementedWellKnownInterface(this.pass.wasm, rc, WellKnown.IteratorInterface) != null ||
                  findImplementedWellKnownInterface(this.pass.wasm, rc, WellKnown.IterableInterface) != null) {
                syncClasses.push(rc);
              } else {
                asyncClasses.push(rc);
              }
            }
            var rootSync = protocolClasses.length == 0 || syncClasses.length > 0;
            var rootAsync = n.isAwait && (protocolClasses.length == 0 || asyncClasses.length > 0);
            if (resolvedIterable is InterfaceType) {
              rootSync = findExtendedWellKnownInterface(this.pass.wasm, resolvedIterable, WellKnown.IterableInterface) != null ||
                  findExtendedWellKnownInterface(this.pass.wasm, resolvedIterable, WellKnown.IteratorInterface) != null;
              rootAsync = !rootSync;
            }
            if (rootSync) {
              this.rootIterationProtocol(WellKnown.IterableInterface, ":iterator", syncClasses, model);
            }
            if (rootAsync) {
              this.rootIterationProtocol(WellKnown.AsyncIterableInterface, ":asyncIterator", asyncClasses, model);
            }
          }
        }
      }
      if (n is MemberExpression) {
        this.#noteMemberStaticTarget(n, model, resolveType);
        let objType = model.getNodeType(n.object);
        if (objType != null) {
          let rawResolvedObj = resolveType(objType);
          let resolvedObj = if (n.optional) getNonNullableType(rawResolvedObj) else rawResolvedObj;
          let propName = if (n.isSymbolAccess) ":" + n.property.name else n.property.name;
          
          if (resolvedObj is InterfaceType) {
            this.registerGenericInterfaceMethodUse(n, model, resolveType, resolvedObj);
          } else if (resolvedObj is ClassType) {
            let targetModel = this.pass.getClassModel(resolvedObj);

            // A private name read in a mixin body is that mixin's
            // member — method or accessor — and the CHA searches below
            // would find the host's same-named one instead (they scan
            // the class's own body first and match on name alone).
            if (bodyScope != null && propName.length > 0 &&
                propName.sliceBytes(0, 1) == "#") {
              this.queueMixinPrivateMember(resolvedObj, bodyScope, propName);
            }

            let isStaticAccess = model.isStaticAccess(n);
            var isMethod = false;
            var isStaticMethod = false;
            var isGenericMethod = false;
            var methodTypeArgs: Array<Type> | null = null;
            var currClassWalk: ClassType | null = resolvedObj;
            while (currClassWalk != null && !isMethod) {
              let cc = currClassWalk;
              let ccMembers = cc.memberTable(isStaticAccess);
              if (ccMembers.has(propName)) {
                let mi = ccMembers[propName];
                if (mi is MethodInfo) {
                  isMethod = true;
                  isStaticMethod = mi.isStatic;
                  if (mi.type is FunctionType) {
                    let ft = mi.type as FunctionType;
                    let {typeParameters} = ft;
                    if (typeParameters != null && typeParameters.length > 0) {
                      isGenericMethod = true;
                      let nodeTypeRaw = model.getNodeType(n);
                      if (nodeTypeRaw is FunctionType) {
                        let {typeArguments} = nodeTypeRaw;
                        if (typeArguments != null) {
                          // Through the walk's resolver: on a
                          // specialization's walk the solved arguments
                          // may still spell the enclosing function's
                          // own parameters (`race<T>` from inside a
                          // generic body), and instantiating at a bare
                          // parameter mints the erasure — see
                          // registerGenericMethodUse, which this
                          // mirrors.
                          let resolvedArgs = new Array<Type>();
                          for (let a in typeArguments) {
                            resolvedArgs.push(resolveType(a));
                          }
                          methodTypeArgs = resolvedArgs;
                        }
                      }
                    }
                  }
                }
              }
              currClassWalk = cc.superType;
            }
            
            let cha = this.pass.cha;
            let specializer = this.pass.specializer;
            let resolvedName = if (isMethod) propName else "get#" + propName;
            if (isGenericMethod && methodTypeArgs != null &&
                noOpenTypeParameters(methodTypeArgs)) {
              let isPrivate = propName.length > 0 && propName.sliceBytes(0, 1) == "#";
              if (!isStaticMethod && !resolvedObj.isExtension && !isPrivate &&
                  !containsErasedType(resolvedObj) &&
                  !methodTypeArgs.some((typeArg) => containsErasedType(typeArg))) {
                this.pass.demandGenericClassMethod(resolvedObj, propName, methodTypeArgs, model);
                if (this.pass.currentReachable) {
                  this.pass.notePendingStaticTargets(
                      resolvedObj, getSpecializedName(propName, methodTypeArgs));
                }
              }
            }
            let mds = cha.findImplementingMethods(resolvedObj, resolvedName);
            for (let md in mds) {
              if (md.isStatic != isStaticAccess) { continue; }
              if (isGenericMethod && methodTypeArgs != null) {
                // Arguments still open after resolution mean this walk
                // is a template's: the mention is the template of a
                // call, and every value it stands for belongs to a
                // specialization some real walk registers.
                if (!noOpenTypeParameters(methodTypeArgs)) {
                  continue;
                }
                let unspecCdId = (resolvedObj.genericSource ?? resolvedObj).symbolId;
                let cd = if (let (true, decl) = this.pass.classDecls.get(unspecCdId)) decl else null;
                // Reach it, not merely register it — layout() rebuilds
                // classMethodMap from the pruned function list. See
                // registerGenericMethodUse.
                this.pass.markFunctionReached(
                  specializer.instantiateGenericMethod(resolvedObj, cd, propName, md as Node, methodTypeArgs, this.pass.getNodeModel(md as Node, targetModel)));
                this.pass.queueReferrer(new Referrer(false, noSymbolId, (md as Node).id as i32,
                    this.pass.getNodeModel(md as Node, targetModel), resolvedObj,
                    this.pass.currentReachable, methodTypeArgs));
              } else {
                this.pass.queueReferrer(new Referrer(false, noSymbolId, (md as Node).id as i32, this.pass.getNodeModel(md as Node, targetModel), resolvedObj, this.pass.currentReachable));
              }
            }
            if (!isMethod) {
              for (let fd in cha.findImplementingFields(resolvedObj, propName)) {
                if (fd.isStatic == isStaticAccess) {
                  this.pass.queueReferrer(new Referrer(false, noSymbolId, (fd as Node).id as i32, this.pass.getNodeModel(fd as Node, targetModel), resolvedObj, this.pass.currentReachable));
                }
              }
              for (let acc in cha.findImplementingAccessors(resolvedObj, resolvedName)) {
                if (acc.isStatic == isStaticAccess) {
                  this.pass.queueReferrer(new Referrer(false, noSymbolId, (acc as Node).id as i32, this.pass.getNodeModel(acc as Node, targetModel), resolvedObj, this.pass.currentReachable));
                }
              }
            }
          }
        }
      }
      if (n is AssignmentExpression) {
        if (n.left is MemberExpression) {
          let mem = n.left as MemberExpression;
          let objType = model.getNodeType(mem.object);
          if (objType != null) {
            let rawResolvedObj = resolveType(objType);
            let resolvedObj = if (mem.optional) getNonNullableType(rawResolvedObj) else rawResolvedObj;
            if (resolvedObj is ClassType) {
              let propName = if (mem.isSymbolAccess) ":" + mem.property.name else mem.property.name;
              let setterName = "set#" + propName;
              let isStaticAssign = model.isStaticAccess(mem);
              for (let acc in this.pass.cha.findImplementingAccessors(resolvedObj, setterName)) {
                if (acc.isStatic == isStaticAssign) {
                  let targetModel = this.pass.getClassModel(resolvedObj);
                  this.pass.queueReferrer(new Referrer(false, noSymbolId, (acc as Node).id as i32, this.pass.getNodeModel(acc as Node, targetModel), resolvedObj, this.pass.currentReachable));
                }
              }
            }
          }
        }
      }
      if (n is Identifier) {
        let parentNode = model.getParent(n);
        var isCallee = false;
        if (parentNode is CallExpression) {
          if (parentNode.callee === n) {
            isCallee = true;
          }
        }
        
        if (isCallee) {
          let sym = model.resolve(n);
          if (sym != null) {
            var targetSymId = sym.id;
            let {declaration} = sym;
            if (declaration is ImportSpecifier) {
              targetSymId = resolveImportedSymbolId(this.pass.program, model, declaration, null);
            }
            let resolvedArgs = new Array<Type>();
            let rawNodeType = model.getNodeType(n);
            if (rawNodeType != null) {
              let nodeType = resolveType(rawNodeType);
              if (nodeType is FunctionType) {
                let {typeArguments} = nodeType;
                if (typeArguments != null) {
                  for (let arg in typeArguments) {
                    resolvedArgs.push(arg);
                  }
                }
              }
            }
            let isSpecialized = resolvedArgs.length > 0 && noOpenTypeParameters(resolvedArgs);
            if (isSpecialized && targetSymId != noSymbolId && this.pass.wasm.genericFunctions.has(targetSymId)) {
              let spec = this.pass.specializer.instantiateGenericFunction(targetSymId, resolvedArgs);
              this.#noteSpecializedCall(parentNode as CallExpression, model, spec);
            } else if (targetSymId != noSymbolId) {
              let resolvedOv = model.getResolvedOverload(parentNode as CallExpression);
              var targetFunc: WasmFunction | null = null;
              if (resolvedOv != null) {
                let overKey = getOverloadedFunctionKey(targetSymId, resolvedOv);
                if (let (true, f) = this.pass.wasm.overloadedFunctionMap.get(overKey)) {
                  targetFunc = f;
                }
              }
              if (targetFunc == null) {
                if (let (true, f) = this.pass.wasm.functionMap.get(targetSymId)) {
                  targetFunc = f;
                }
              }
              if (targetFunc != null) {
                this.pass.markFunctionReached(targetFunc);
              }
            }
          }
        } else {
          let rawNodeType = model.getNodeType(n);
          if (rawNodeType != null) {
            let nodeType = resolveType(rawNodeType);
            this.discoverIdentifierReferenceAsValue(n, model, nodeType);
          }
        }
      }
    });
  }

  discoverIdentifierReferenceAsValue(ident: Identifier, model: SemanticModel, nodeType: Type): void {
    if (!(nodeType is FunctionType)) {
      return;
    }
    let sym = model.resolve(ident);
    if (sym == null) {
      return;
    }
    var targetSymId = sym.id;
    let {declaration} = sym;
    if (declaration is ImportSpecifier) {
      targetSymId = resolveImportedSymbolId(this.pass.program, model, declaration, null);
      if (targetSymId == noSymbolId) {
        // `resolveImportedSymbolId` answers from the specifier text and
        // the map of declarations each unit makes, so it has no answer
        // for a package specifier ("zena-lang:wit-parser/document" is no unit's
        // path) or for a name a module re-exports rather than declares.
        // The checker already linked the specifier to the declaration it
        // names, so follow that link instead of leaving the function
        // value without a wrapper.
        targetSymId = sym.resolveTarget().id;
      }
    }
    let resolvedArgs = new Array<Type>();
    let {typeArguments} = nodeType;
    if (typeArguments != null) {
      for (let arg in typeArguments) {
        resolvedArgs.push(arg);
      }
    }
    let isSpecialized = resolvedArgs.length > 0 && noOpenTypeParameters(resolvedArgs);
    if (isSpecialized && targetSymId != noSymbolId && this.pass.wasm.genericFunctions.has(targetSymId)) {
      this.pass.specializer.instantiateGenericFunction(targetSymId, resolvedArgs);
    }
    
    var targetWasmFunc: WasmFunction | null = null;
    var keyName = "";
    if (isSpecialized) {
      let specKey = getSpecializedFunctionKey(ident.name, resolvedArgs);
      keyName = getSpecializedName(ident.name, resolvedArgs);
      if (let (true, f) = this.pass.wasm.specializedFunctions.get(specKey)) {
        targetWasmFunc = f;
      }
    } else {
      // Keyed by the symbol the import points at, as lowering looks it
      // up: an imported `function` used as a value has its own
      // specifier symbol, and a wrapper keyed by that is never found.
      keyName = i32ToString(sym.resolveTarget().id as i32);
      let overKey = getOverloadedFunctionKey(targetSymId, nodeType);
      if (let (true, f) = this.pass.wasm.overloadedFunctionMap.get(overKey)) {
        targetWasmFunc = f;
      } else if (let (true, f) = this.pass.wasm.functionMap.get(targetSymId)) {
        targetWasmFunc = f;
      } else if (!this.#discoveringOnDemand.has(targetSymId)) {
        this.#discoveringOnDemand.add(targetSymId);
        if (let (true, targetModel) = this.pass.symbolIdToModel.get(targetSymId)) {
          let decls = targetModel.getGlobalDeclarations(targetSymId);
          if (decls != null) {
            let resolver = (t: Type) => t;
            let declList = decls as GrowableArray<Node>;
            for (let decl in declList) {
              if (decl is VariableDeclaration) {
                this.discoverVariableDeclaration(targetSymId, decl, targetModel);
              } else if (decl is FunctionDeclaration) {
                this.discoverFunctionDeclaration(targetSymId, decl, targetModel);
              }
            }
            for (let decl in declList) {
              this.discoverNodeTypes(decl, targetModel, resolver);
            }
            if (let (true, f) = this.pass.wasm.overloadedFunctionMap.get(overKey)) {
              targetWasmFunc = f;
            } else if (let (true, f) = this.pass.wasm.functionMap.get(targetSymId)) {
              targetWasmFunc = f;
            }
          }
        }
        this.#discoveringOnDemand.delete(targetSymId);
      }
    }
    if (targetWasmFunc != null) {
      this.registerWrapper(keyName, nodeType, targetWasmFunc, model);
      
      let ntArgs = nodeType.typeArguments;
      if (ntArgs != null && ntArgs.length > 0) {
        let erasedArgs = new Array<Type>();
        for (let arg in (ntArgs as Array<Type>)) {
          erasedArgs.push(eraseType(arg));
        }
        let erasedFt = eraseType(nodeType) as FunctionType;
        let erasedSpecKey = getSpecializedFunctionKey(ident.name, erasedArgs);
        
        var erasedTargetWasmFunc: WasmFunction | null = null;
        if (let (true, f) = this.pass.wasm.specializedFunctions.get(erasedSpecKey)) {
          erasedTargetWasmFunc = f;
        } else if (targetSymId != noSymbolId && this.pass.wasm.genericFunctions.has(targetSymId)) {
          erasedTargetWasmFunc = this.pass.specializer.instantiateGenericFunction(targetSymId, erasedArgs);
        }
        
        if (erasedTargetWasmFunc != null) {
          this.registerWrapper(getSpecializedName(ident.name, erasedArgs), erasedFt, erasedTargetWasmFunc, model);
        }
      }
    }
  }

  registerWrapper(keyName: String, ft: FunctionType, targetWasmFunc: WasmFunction, model: SemanticModel): void {
    let wrapperParams = growable<ValType>([new ValTypeStructRef()]);
    for (let p in ft.parameters) {
      mapParamTypeToWasmParams(this.pass.wasm, p, wrapperParams);
    }
    let wrapperReturns = new Array<ValType>();
    mapReturnTypeToWasmResults(this.pass.wasm, ft.returnType, wrapperReturns);
    let sig = this.pass.wasm.getSignature(wrapperParams, wrapperReturns);
    
    let wrapperKey = getFunctionValueWrapperKey(keyName, ft);
    this.pass.markFunctionReached(targetWasmFunc);
    if (!this.pass.wasm.functionValueWrappers.has(wrapperKey)) {
      let wrapperFunc = new WasmFunction(sig, null, model);
      let targetName = if (targetWasmFunc.name != null) targetWasmFunc.name as String else "func";
      wrapperFunc.name = `${targetName}_valwrapper_${getSignatureKey(ft)}`;
      wrapperFunc.isClosureWrapper = true;
      wrapperFunc.closureWrapperTarget = targetWasmFunc;
      wrapperFunc.isReferenceTaken = true;
      
      this.pass.wasm.functionValueWrappers[wrapperKey] = wrapperFunc;
      this.pass.wasm.addFunction(wrapperFunc);
      this.pass.markFunctionReached(wrapperFunc);
      
      // The wrapper is force-reached above and its synthesized body
      // references this struct, so the struct is needed regardless of
      // which walk registered it.
      this.pass.reachablyNamedClosures.add(
          getClosureStruct(this.pass.wasm, ft));
    }
  }

  discoverFunctionValueWrapper(ft: FunctionType, model: SemanticModel): void {
    let targetSymId = ft.functionSymbolId;
    if (targetSymId == noSymbolId) {
      return;
    }
    
    let resolvedArgs = new Array<Type>();
    let {typeArguments} = ft;
    if (typeArguments != null) {
      for (let arg in typeArguments) {
        resolvedArgs.push(arg);
      }
    }
    let isSpecialized = resolvedArgs.length > 0 && noOpenTypeParameters(resolvedArgs);
    if (isSpecialized && targetSymId != noSymbolId && this.pass.wasm.genericFunctions.has(targetSymId)) {
      this.pass.specializer.instantiateGenericFunction(targetSymId, resolvedArgs);
    }
    
    var targetWasmFunc: WasmFunction | null = null;
    var keyName = "";
    if (isSpecialized) {
      let specKey = getSpecializedFunctionKey(ft.functionSymbolName, resolvedArgs);
      keyName = getSpecializedName(ft.functionSymbolName, resolvedArgs);
      if (let (true, f) = this.pass.wasm.specializedFunctions.get(specKey)) {
        targetWasmFunc = f;
      }
    } else {
      keyName = i32ToString(targetSymId as i32);
      let overKey = getOverloadedFunctionKey(targetSymId, ft);
      if (let (true, f) = this.pass.wasm.overloadedFunctionMap.get(overKey)) {
        targetWasmFunc = f;
      } else if (let (true, f) = this.pass.wasm.functionMap.get(targetSymId)) {
        targetWasmFunc = f;
      } else if (!this.#discoveringOnDemand.has(targetSymId)) {
        this.#discoveringOnDemand.add(targetSymId);
        if (let (true, targetModel) = this.pass.symbolIdToModel.get(targetSymId)) {
          let decls = targetModel.getGlobalDeclarations(targetSymId);
          if (decls != null) {
            let resolver = (t: Type) => t;
            let declList = decls as GrowableArray<Node>;
            for (let decl in declList) {
              if (decl is VariableDeclaration) {
                this.discoverVariableDeclaration(targetSymId, decl, targetModel);
              } else if (decl is FunctionDeclaration) {
                this.discoverFunctionDeclaration(targetSymId, decl, targetModel);
              }
            }
            for (let decl in declList) {
              this.discoverNodeTypes(decl, targetModel, resolver);
            }
            if (let (true, f) = this.pass.wasm.overloadedFunctionMap.get(overKey)) {
              targetWasmFunc = f;
            } else if (let (true, f) = this.pass.wasm.functionMap.get(targetSymId)) {
              targetWasmFunc = f;
            }
          }
        }
        this.#discoveringOnDemand.delete(targetSymId);
      }
    }
    if (targetWasmFunc != null) {
      this.registerWrapper(keyName, ft, targetWasmFunc, model);
      
      let ftArgs = ft.typeArguments;
      if (ftArgs != null && ftArgs.length > 0) {
        let erasedArgs = new Array<Type>();
        for (let arg in (ftArgs as Array<Type>)) {
          erasedArgs.push(eraseType(arg));
        }
        let erasedFt = eraseType(ft) as FunctionType;
        let erasedSpecKey = getSpecializedFunctionKey(ft.functionSymbolName, erasedArgs);
        
        var erasedTargetWasmFunc: WasmFunction | null = null;
        if (let (true, f) = this.pass.wasm.specializedFunctions.get(erasedSpecKey)) {
          erasedTargetWasmFunc = f;
        } else if (targetSymId != noSymbolId && this.pass.wasm.genericFunctions.has(targetSymId)) {
          erasedTargetWasmFunc = this.pass.specializer.instantiateGenericFunction(targetSymId, erasedArgs);
        }
        
        if (erasedTargetWasmFunc != null) {
          this.registerWrapper(getSpecializedName(ft.functionSymbolName, erasedArgs), erasedFt, erasedTargetWasmFunc, model);
        }
      }
    }
  }

  /**
   * A top-level `function` declaration reaches codegen through exactly the
   * same path as `let f = () => ...`: it is a named binding of a
   * FunctionExpression, so it becomes one WasmFunction with no context
   * struct.
   */
  discoverFunctionDeclaration(symId: SymbolId, funcDecl: FunctionDeclaration, moduleModel: SemanticModel): void {
    // Everything below reads node types the body check writes, and
    // this is reached on demand from a use site as well as from the
    // queue walk — so the module whose bodies waited is asked here too.
    let deferredDecl = moduleModel.deferredBodies;
    if (deferredDecl != null) {
      deferredDecl.checkGlobalBody(symId);
    }
    let funcType = moduleModel.getNodeType(funcDecl.func);
    if (funcType != null) {
      // The declaration's own type is a SIGNATURE, not a value: a
      // top-level `function` is never a closure, and a use of it as a
      // value discovers the closure struct at the use site. Routing
      // it through discoverType minted a closure struct + erased impl
      // signature pair for every declared function, used-as-value or
      // not — the last two types in `return 42`'s module.
      this.pass.typeLowerer.discoverSignatureType(funcType, moduleModel);
    }
    this.#discoverFunctionBinding(
        funcDecl.name as Pattern, funcDecl.func, funcDecl.exported, moduleModel);
  }

  discoverVariableDeclaration(symId: SymbolId, varDecl: VariableDeclaration, moduleModel: SemanticModel): void {
    // See discoverFunctionDeclaration: the node types below exist only
    // once the declaration's body has been checked.
    let deferredDecl = moduleModel.deferredBodies;
    if (deferredDecl != null) {
      deferredDecl.checkGlobalBody(symId);
    }
    let typeLowerer = this.pass.typeLowerer;
    let varType = moduleModel.getNodeType(varDecl);
    if (varType != null) {
      typeLowerer.discoverType(varType, moduleModel);
    }
    let patType = moduleModel.getNodeType(varDecl.pattern);
    if (patType != null) {
      typeLowerer.discoverType(patType, moduleModel);
    }
    if (varDecl.init != null) {
      let initType = moduleModel.getNodeType(varDecl.init);
      if (initType != null) {
        typeLowerer.discoverType(initType, moduleModel);
      }
    }

    if (varDecl.init is FunctionExpression) {
      this.#discoverFunctionBinding(
          varDecl.pattern, varDecl.init as FunctionExpression, varDecl.exported,
          moduleModel);
    } else {
      // Global Variable
      if (varDecl.pattern is IdentifierPattern && varDecl.init != null) {
        let ident = varDecl.pattern as IdentifierPattern;
        let expr = varDecl.init;
        let nodeType = moduleModel.getNodeType(ident);
        let isMutable = true;

        let vType = typeToValType(this.pass.wasm, nodeType as Type);

        let sym = moduleModel.resolveDeclaration(ident);
        if (sym != null) {
          let name = `${ident.name}_${i32ToString(sym.id as i32)}`;
          let wasmGlobal = new WasmGlobal(name, ident.name, vType, isMutable, expr, null, moduleModel);
          wasmGlobal.symbolId = sym.id;
          this.pass.wasm.globals.push(wasmGlobal);
          this.pass.wasm.globalMap[sym.id] = wasmGlobal;

          let isEntry = this.pass.program.entryPoint != null && moduleModel.sourcePath == (this.pass.program.entryPoint as CompilationUnit).ast.path;
          if (varDecl.exported && isEntry) {
            this.pass.wasm.exportGlobalMap[ident.name as ExportGlobalKey] = wasmGlobal;
          }
        }
      }
    }
  }

  /** Shared by `let f = () => ...` and `function f() { ... }`. */
  #discoverFunctionBinding(pattern: Pattern, funcExpr: FunctionExpression, exported: boolean, moduleModel: SemanticModel): void {
    let funcTypeNode = moduleModel.getNodeType(funcExpr);
    var isGeneric = false;
    if (funcTypeNode is FunctionType) {
      let {typeParameters} = funcTypeNode;
      if (typeParameters != null && typeParameters.length > 0) {
        isGeneric = true;
      }
    }
    
    if (isGeneric) {
      if (pattern is IdentifierPattern) {
        let sym = moduleModel.resolveDeclaration(pattern);
        if (sym != null) {
          this.pass.wasm.genericFunctions[sym.id] = funcExpr;
          this.pass.wasm.genericFunctionModels[sym.id] = moduleModel;
        }
      }
    } else {
      let overKey = if (pattern is IdentifierPattern && funcTypeNode is FunctionType) {
        let sym = moduleModel.resolveDeclaration(pattern);
        if (sym != null) getOverloadedFunctionKey(sym.id, funcTypeNode) else ""
      } else {
        ""
      };
      if (overKey != "") {
        if (let (true, existingFunc) = this.pass.wasm.overloadedFunctionMap.get(overKey)) {
          if (this.pass.currentReachable) {
            this.pass.markFunctionReached(existingFunc);
          }
          return;
        }
      } else if (pattern is IdentifierPattern) {
        let sym = moduleModel.resolveDeclaration(pattern);
        if (sym != null) {
          if (let (true, existingFunc) = this.pass.wasm.functionMap.get(sym.id)) {
            if (this.pass.currentReachable) {
              this.pass.markFunctionReached(existingFunc);
            }
            return;
          }
        }
      }

      let params = new Array<ValType>();
      let returns = new Array<ValType>();
      
      if (funcTypeNode is FunctionType) {
        for (let p in funcTypeNode.parameters) {
          mapParamTypeToWasmParams(this.pass.wasm, p, params);
        }
        mapReturnTypeToWasmResults(this.pass.wasm, funcTypeNode.returnType, returns);
      } else {
        returns.push(new ValTypeI32());
      }
      
      let sig = this.pass.wasm.getSignature(params, returns);
      let wasmFunc = new WasmFunction(sig, funcExpr, moduleModel);
      this.pass.wasm.addFunction(wasmFunc);
      
      if (pattern is IdentifierPattern) {
        let sym = moduleModel.resolveDeclaration(pattern);
        let decls = if (sym != null) moduleModel.getGlobalDeclarations((sym as Symbol).id) else null;
        let isOverloaded = decls != null && (decls as GrowableArray<Node>).length > 1;
        wasmFunc.name = if (isOverloaded && funcTypeNode is FunctionType) {
          pattern.name + getSignatureKey(funcTypeNode)
        } else {
          pattern.name
        };
        if (sym != null) {
          if (overKey != "") {
            this.pass.wasm.overloadedFunctionMap[overKey] = wasmFunc;
          }
          if (!this.pass.wasm.functionMap.has(sym.id)) {
            this.pass.wasm.functionMap[sym.id] = wasmFunc;
          }
          let isEntry = this.pass.program.entryPoint != null && moduleModel.sourcePath == (this.pass.program.entryPoint as CompilationUnit).ast.path;
          if ((exported || pattern.name == "main") && isEntry) {
            let exportName = if (isOverloaded && wasmFunc.name != null) (wasmFunc.name as String) else pattern.name;
            this.pass.wasm.exportMap[exportName as ExportKey] = wasmFunc;
          }
          if (this.pass.currentReachable) {
            this.pass.markFunctionReached(wasmFunc);
          }
        }
      }
    }
  }

  discoverImportDeclaration(importDecl: ImportDeclaration, moduleModel: SemanticModel): void {
    for (let spec in importDecl.imports) {
      let sym = moduleModel.resolveDeclaration(spec as Node);
      if (sym != null) {
        let targetSym = sym.resolveTarget();
        this.pass.symbolIdToTargetId[sym.id] = targetSym.id;
      }
      if (spec.imported.name == "*") {
        let localIdent = spec.local;
        let sym = moduleModel.resolveDeclaration(spec as Node);
        if (sym != null) {
          let nodeType = moduleModel.getBindingType(sym);
          if (nodeType != null) {
            this.pass.typeLowerer.discoverType(nodeType, moduleModel);
            let vType = typeToValType(this.pass.wasm, nodeType);
            let name = `${localIdent.name}_${i32ToString(sym.id as i32)}`;
            
            let wasmGlobal = new WasmGlobal(name, localIdent.name, vType, true, null, null, moduleModel);
            wasmGlobal.namespaceImport = spec;
            this.pass.wasm.globals.push(wasmGlobal);
            this.pass.wasm.globalMap[sym.id] = wasmGlobal;

            // Mark exported functions in target module as reference taken so they are emitted in Wasm element section
            let parentNode = moduleModel.getParent(spec);
            if (parentNode is ImportDeclaration) {
              let specifier = parentNode.moduleSpecifier.value;
              var canonicalPath = specifier;
              if (specifier.startsWith("./") || specifier.startsWith("../")) {
                let referrer = moduleModel.getParent(parentNode);
                if (referrer is Module) {
                  let dir = dirName(referrer.path);
                  canonicalPath = normalizePath(`${dir}/${specifier}`);
                }
              }
              
              let prog = this.pass.wasm.program as Program;

              if (prog.unitsByPath.has(canonicalPath)) {
                let targetUnit = prog.unitsByPath[canonicalPath];
                let exports = new Map<String, Symbol>();
                collectValueExports(prog, targetUnit, exports);
                
                for (let key in exports.keys()) {
                  if (let (true, exportSym) = exports.get(key)) {
                    // `import * as ns` takes a reference to every
                    // export, so each one is a root. This used to lean
                    // on the target module's globals already having
                    // been walked as checkable roots; once a library
                    // unit is only visited when something reaches it,
                    // the namespace object was built with nothing in
                    // it and calling through it trapped on a null
                    // reference.
                    let exportTarget = exportSym.resolveTarget();
                    this.pass.queueReferrer(new Referrer(true, exportTarget.id,
                        -1, targetUnit.model, null, true));
                    if (this.pass.wasm.functionMap.has(exportSym.id)) {
                      let f = this.pass.wasm.functionMap[exportSym.id];
                      f.isReferenceTaken = true;
                      this.pass.markFunctionReached(f);
                      if (f.closureTrampoline == null) {
                        let tParams = growable<ValType>([
                          new ValTypeStructRef(),
                        ]);
                        for (let p in f.signature.params) {
                          tParams.push(p);
                        }
                        let tSig = this.pass.wasm.getSignature(tParams, f.signature.returns);
                        let trampoline = new WasmFunction(tSig, null, f.model);
                        let fName = if (f.name != null) (f.name as String) else "anonymous";
                        trampoline.name = fName + "$trampoline";
                        trampoline.isClosureTrampoline = true;
                        trampoline.closureTrampolineTarget = f;
                        trampoline.isReferenceTaken = true;
                        f.closureTrampoline = trampoline;
                        this.pass.wasm.addFunction(trampoline);
                        this.pass.markFunctionReached(trampoline);
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }

  discoverDeclareFunction(decl: DeclareFunction, moduleModel: SemanticModel): void {
    let sym = moduleModel.resolveDeclaration(decl);
    if (sym == null) {
      return;
    }

    if (let (true, existingFunc) = this.pass.wasm.functionMap.get(sym.id)) {
      if (this.pass.currentReachable) {
        this.pass.markFunctionReached(existingFunc);
      }
      return;
    }

    var isIntrinsic = false;
    var intrinsicName = "";
    var isExternal = false;
    var externalModule = "";
    var externalName = "";
    var externalAsync = false;
    var externalCanonType = "";
    for (let dec in decl.decorators) {
      if (dec.name == "intrinsic") {
        if (dec.args.length == 1) {
          intrinsicName = decoratorStringArg(dec, 0) ?? "";
          isIntrinsic = true;
        } else {
          throw new Error("Intrinsic decorator must have exactly one argument");
        }
      } else if (dec.name == "external") {
        if (dec.args.length == 2 || dec.args.length == 3) {
          externalModule = decoratorStringArg(dec, 0) ?? "";
          externalName = decoratorStringArg(dec, 1) ?? "";
          isExternal = true;
          // A third argument is the import's canonical options, comma
          // separated. `async` is one; a WIT type spelling (`stream<u8>`,
          // `future:<interface>#<payload>`) names the type a typed
          // canonical builtin operates on. The rest of the canonical
          // option space (memory, realloc, string-encoding) is the
          // compiler's business rather than the program's, because only
          // the compiler knows where the memory lives. The split is
          // depth-aware: a future payload like `result<a, b>` carries
          // commas of its own, so only depth-zero commas separate.
          if (dec.args.length == 3) {
            let raw = decoratorStringArg(dec, 2) ?? "";
            let optionList = new Array<String>();
            var depth = 0;
            var from = 0;
            for (var oi = 0; oi <= raw.length; oi += 1) {
              if (oi < raw.length) {
                let c = raw.getByteAt(oi);
                if (c == 60) { depth += 1; continue; } // '<'
                if (c == 62) { depth -= 1; continue; } // '>'
                if (c != 44 || depth > 0) { continue; } // ','
              }
              var piece = raw.sliceBytes(from, oi);
              while (piece.startsWith(" ")) {
                piece = piece.sliceBytes(1, piece.length);
              }
              optionList.push(piece);
              from = oi + 1;
            }
            for (let option in optionList) {
              if (option == "async") {
                externalAsync = true;
              } else if (option.startsWith("stream") ||
                  option.startsWith("future") ||
                  option.startsWith("resource:") ||
                  option.startsWith("return:")) {
                externalCanonType = option;
              } else if (option != "") {
                throw new Error(
                  "Unknown @external option '" + option + "' on '" +
                  decl.name.name + "' (expected 'async', a stream/" +
                  "future type like 'stream<u8>', a " +
                  "'resource:<interface>#<name>' reference, or a " +
                  "'return:<interface>#<type>' result type)");
              }
            }
          }
        } else {
          throw new Error("External decorator must have two or three arguments");
        }
      }
    }

    if (isIntrinsic) {
      let key = `${moduleModel.sourcePath}::${decl.name.name}`;
      if (let (true, list) = this.pass.program.exportedFunctions.get(key)) {
        for (let df in list) {
          var dfIntrinsicName = "";
          for (let dec in df.decorators) {
            if (dec.name == "intrinsic" && dec.args.length == 1) {
              dfIntrinsicName = decoratorStringArg(dec, 0) ?? "";
            }
          }
          if (dfIntrinsicName != "") {
            this.pass.wasm.intrinsics[df.id] = dfIntrinsicName;
            if (dfIntrinsicName == "cancel.raise") {
              // The cancellation tag exists exactly when the program
              // can cancel; finalizer-region lowering consults it.
              // The stdlib's own raise sites (a cancelled future's
              // reads) are reached by every async program, so the
              // whole-program gate decides, not reachability alone —
              // under a closed gate those sites lower to unreachable.
              if (this.pass.cancellationPossible) {
                this.pass.wasm.ensureCancellationInfra();
              }
            } else if (dfIntrinsicName == "eq") {
              // The eq intrinsic lowers through the equality diamond,
              // whose string tier resolves String.== by name.
              this.pass.useEqualityDispatch();
              let {stringClass} = this.pass.wasm;
              if (stringClass != null) {
                let eqSc = stringClass;
                this.pass.notePendingMemberReach(
                    getClassMethodKey(getClassKey(eqSc), "=="));
                this.pass.notePendingMemberReach(
                    getClassMethodKey(getClassKey(eqSc), "hashCode"));
              }
            } else if (dfIntrinsicName == "hash") {
              // hash<T> dispatches hashCode through class vtables on
              // erased receivers — the other equality-dispatch signal.
              this.pass.useEqualityDispatch();
              if (this.pass.wasm.stringClass != null) {
                let hSc = this.pass.wasm.stringClass as ClassType;
                this.pass.notePendingMemberReach(
                    getClassMethodKey(getClassKey(hSc), "hashCode"));
              }
              if (!targetUsesJsStrings(this.pass.wasm.target)) {
                this.registerStringHashHelper(moduleModel);
                this.pass.wasm.ensureHashInfra(moduleModel);
                this.pass.markFunctionReached(this.pass.wasm.stringHashFunc as WasmFunction);
              }
            }
          }
        }
      }
    } else if (isExternal) {
      let funcType = moduleModel.getNodeType(decl) as FunctionType;
      // A host import moves strings across the boundary too: the host
      // READS String parameters it receives (console's log_string) and
      // WRITES String returns it produces.
      this.pass.noteHostImportSignature(funcType);
      let params = new Array<ValType>();
      for (let pt in funcType.parameters) {
        mapParamTypeToWasmParams(this.pass.wasm, pt, params);
      }
      let returns = new Array<ValType>();
      mapReturnTypeToWasmResults(this.pass.wasm, funcType.returnType, returns);

      if (externalModule == "wasm:js-string") {
        for (var i = 0; i < returns.length; i += 1) {
          if (returns[i] is ValTypeExternRef) {
            returns[i] = new ValTypeRefExtern();
          }
        }
      }

      var isGcRef = false;
      if (returns.length == 1) {
        match (returns[0]) {
          case ValTypeAnyRef: { isGcRef = true; }
          case ValTypeEqRef: { isGcRef = true; }
          case ValTypeStructRef: { isGcRef = true; }
          case ValTypeRef: { isGcRef = true; }
          case ValTypeRefNull: { isGcRef = true; }
          case _: {}
        }
      }

      if (isGcRef) {
        let importReturns = growable<ValType>([new ValTypeExternRef()]);
        let importSig = this.pass.wasm.getSignature(params, importReturns);
        let importFunc = new WasmFunction(importSig, decl, moduleModel);
        importFunc.isImport = true;
        importFunc.importModule = externalModule;
        importFunc.importName = externalName;
        importFunc.importIsAsync = externalAsync;
        importFunc.importCanonType = externalCanonType;
        importFunc.name = decl.name.name + "_raw_import";
        this.pass.wasm.functionImports.push(importFunc);

        let wrapperSig = this.pass.wasm.getSignature(params, returns);
        let wrapperFunc = new WasmFunction(wrapperSig, decl, moduleModel);
        wrapperFunc.name = decl.name.name;
        wrapperFunc.importWrapperTarget = importFunc;
        this.pass.wasm.addFunction(wrapperFunc);

        this.pass.wasm.functionMap[sym.id] = wrapperFunc;
      } else {
        let sig = this.pass.wasm.getSignature(params, returns);
        let wasmFunc = new WasmFunction(sig, decl, moduleModel);
        wasmFunc.isImport = true;
        wasmFunc.importModule = externalModule;
        wasmFunc.importName = externalName;
        wasmFunc.importIsAsync = externalAsync;
        wasmFunc.importCanonType = externalCanonType;
        this.pass.wasm.functionImports.push(wasmFunc);
        this.pass.wasm.functionMap[sym.id] = wasmFunc;
      }
      
      let finalFunc = this.pass.wasm.functionMap[sym.id];
      if (this.pass.currentReachable) {
        this.pass.markFunctionReached(finalFunc);
      }
    }
  }

  registerStringHashHelper(model: SemanticModel): void {
    if (this.pass.wasm.stringHashHelper != null || targetUsesJsStrings(this.pass.wasm.target)) {
      return;
    }

    var stringStruct: WasmStruct | null = null;
    let {stringClass} = this.pass.wasm;
    if (stringClass != null) {
      let key = getClassKey(stringClass);
      if (let (true, stringInfo) = this.pass.wasm.classInfos.get(key)) {
        stringStruct = stringInfo.structType;
      }
    }
    if (stringStruct == null) {
      throw new Error("string_hash_helper discovery: String class struct not found!");
    }
    
    let helperParams = growable<ValType>([new ValTypeRefNull(stringStruct)]);
    let helperReturns = growable<ValType>([new ValTypeI32()]);
    let helperSig = this.pass.wasm.getSignature(helperParams, helperReturns);
    
    let helperFunc = new WasmFunction(helperSig, null, model);
    helperFunc.name = "string_hash_helper";
    this.pass.wasm.addFunction(helperFunc);
    this.pass.wasm.stringHashHelper = helperFunc;
    this.pass.markFunctionReached(helperFunc);
  }

}

/**
 * Whether a specialization's type arguments are all closed.
 *
 * A generic function named from inside another generic's body carries
 * its type parameters verbatim — `fill<T>(v)` inside `outer<T>`. That
 * is not a call site, it is the template of one: every value it stands
 * for belongs to some `fill<i32>` a real call site names. Specializing
 * it anyway emits a body per generic function per module, at arguments
 * nothing supplies — dead code, and the arguments key as "erased"
 * (getTypeKeyForSpecialization), so the body is one that cannot lower
 * `hash`/`eq`, which dispatch on their operand's type.
 */
function noOpenTypeParameters(args: Array<Type>): boolean {
  for (let a in args) {
    if (a is TypeParameterType) { return false; }
  }
  return true;
}

function eraseType(t: Type): Type {
  return match (t) {
    case TypeParameterType: new ErasedType()
    case FunctionType as ft: {
      let params = new Array<Type>();
      for (let p in ft.parameters) {
        params.push(eraseType(p));
      }
      let ret = internFunctionType(params, eraseType(ft.returnType), ft.info,
          ft.typeParameters);
      ret.functionSymbolId = ft.functionSymbolId;
      ret.functionSymbolName = ft.functionSymbolName;
      ret
    }
    case ClassType as ct: {
      let {typeArguments} = ct;
      if (typeArguments != null) {
        let args = new Array<Type>();
        for (let arg in typeArguments) {
          args.push(eraseType(arg));
        }
        instantiateClassType(ct.genericSource ?? ct, args)
      } else {
        ct
      }
    }
    case InterfaceType as it: {
      let {typeArguments} = it;
      if (typeArguments != null) {
        let args = new Array<Type>();
        for (let arg in typeArguments) {
          args.push(eraseType(arg));
        }
        instantiateInterfaceType(it.genericSource ?? it, args)
      } else {
        it
      }
    }
    case ArrayType as at: {
      new ArrayType(eraseType(at.elementType), at.elementsMutable)
    }
    case TupleType as tt: {
      let types = new Array<Type>();
      for (let type in tt.elementTypes) {
        types.push(eraseType(type));
      }
      new TupleType(types, null, 0)
    }
    case _: t
  };
}



function matchTypesForImport(t1: Type, t2: Type): boolean {
  if (t1 is TypeParameterType) {
    return true;
  }
  match (t1) {
    case ArrayType {elementType, elementsMutable}: {
      if (t2 is ArrayType) {
        if (elementsMutable != t2.elementsMutable) { return false; }
        return matchTypesForImport(elementType, t2.elementType);
      }
      return false;
    }
    case ClassType as ct1: {
      if (t2 is ClassType) {
        if (ct1.name != t2.name) { return false; }
        let {typeArguments} = ct1;
        if (typeArguments != null && t2.typeArguments != null) {
          let args1 = typeArguments;
          let args2 = t2.typeArguments as Array<Type>;
          if (args1.length != args2.length) { return false; }
          var i = 0;
          while (i < args1.length) {
            if (!matchTypesForImport(args1[i], args2[i])) { return false; }
            i += 1;
          }
        }
        return true;
      }
      return false;
    }
    case InterfaceType as it1: {
      if (t2 is InterfaceType) {
        if (it1.name != t2.name) { return false; }
        let {typeArguments} = it1;
        if (typeArguments != null && t2.typeArguments != null) {
          let args1 = typeArguments;
          let args2 = t2.typeArguments as Array<Type>;
          if (args1.length != args2.length) { return false; }
          var i = 0;
          while (i < args1.length) {
            if (!matchTypesForImport(args1[i], args2[i])) { return false; }
            i += 1;
          }
        }
        return true;
      }
      return false;
    }
    case _: {
      return getTypeUniqueKey(t1) == getTypeUniqueKey(t2);
    }
  }
}

function matchOverloadForImport(t1: Type, t2: Type): boolean {
  if (t1 is FunctionType && t2 is FunctionType) {
    if (t1.parameters.length != t2.parameters.length) {
      return false;
    }
    var i = 0;
    while (i < t1.parameters.length) {
      if (!matchTypesForImport(t1.parameters[i], t2.parameters[i])) {
        return false;
      }
      i += 1;
    }
    return true;
  }
  return false;
}


function accessorMemberName(model: SemanticModel, acc: AccessorDeclaration): String {
  return memberKeyOf(model, acc.name as Node);
}

function getNodeMemberName(model: SemanticModel, node: Node): String {
  return memberKeyOf(model, node);
}

function ctorMethodName(model: SemanticModel, md: MethodDefinition): String {
  return memberKeyOf(model, md.name as Node);
}

/**
 * True when lowerForIn (ir/control-flow.zena) takes the direct
 * index-loop path for a for-in whose iterable has this class type:
 * FixedArray, ImmutableArray and Array compile to array.len/array.get,
 * and BoundedRange and FromRange to a loop counting from the range's
 * start. None of them touch the Iterable/Iterator protocol. Mirrors
 * lowerForIn's dispatch, including the type-argument requirement for
 * the arrays — a bare mention with no arguments has no element type
 * there and falls back to the iterator path.
 */
/**
 * The interface a member access or index on `object` dispatches
 * through, or null when `object` is not interface-typed. A nullable
 * receiver (`x?.m()`) dispatches through its non-null member.
 */
function interfaceReceiver(object: Expression, model: SemanticModel,
    resolveType: (t: Type) => Type): InterfaceType | null {
  let t = model.getNodeType(object);
  if (t == null) {
    return null;
  }
  let resolved = getNonNullableType(resolveType(t));
  return if (resolved is InterfaceType) resolved else null;
}

/**
 * True when `range` is a literal written directly as a for-in's
 * iterable, as in `for (let i in 0..n)`. lowerForIn compiles that loop
 * from the literal's bounds and never constructs the range, so the
 * range class needs no instance, constructor or struct type.
 */
function isForInRangeLiteral(model: SemanticModel,
    range: RangeExpression): boolean {
  let parent = model.getParent(range);
  if (!(parent is ForInStatement)) {
    return false;
  }
  if ((parent.iterable as Node).id != (range as Node).id) {
    return false;
  }
  let t = model.getNodeType(range);
  return t is ClassType && isIterableRangeClass(t);
}
VersionPublishedDependenciesApproved by
0.0.2-preview.1 2026-11-19