import { Referrer, ReachabilityContext, SpecializerInterface, } from './context.zena'; import { SemanticModel, memberKeyOf } from '../../semantic-model.zena'; import { Type, ClassType, InterfaceType, FunctionType, TypeParameterType, VoidType, BooleanType, I32Type, MethodInfo, FieldInfo, FunctionDeclInfo, AnyRefType, RecordType, releaseMemberOf, synthesizedRelease } from '../../types.zena'; import { Node, ClassDeclaration, FieldDefinition, MethodDefinition, hasEnsuresClause, AccessorDeclaration, SetterInfo, VariableDeclaration, FunctionDeclaration, IdentifierPattern, Decorator, decoratorStringArg, Identifier, SymbolPropertyName, MemberExpression, TypeParameter, SealedVariant, InterfaceDeclaration, Expression, MixinDeclaration, BlockStatement, SuperInitializer, isSymbolFieldDeclaration, } from '../../ast.zena'; import { WasmStruct, WasmField, WasmGlobal, WasmFunction, ClassCodegenInfo } from '../wasm-module.zena'; import { ValType, ValTypeVoid, ValTypeI32, ValTypeRefNull, ValTypeAnyRef, ValTypeRef, ValTypeStructRef, ValTypeFuncRef, } from '../wasm.zena'; import { SymbolId, noSymbolId } from '../../scope/symbol.zena'; import { Set } from 'zena:collections'; import { getClassKey, getInterfaceKey, getInterfaceConstructorBaseName, getClassMethodKey, getClassInterfaceKey, getSignatureKey, matchOverload, collectMixinMembers, getMemberRootClass, getClassPrivateFieldKey, getSpecializedFunctionKey, getSpecializedName, isConcrete, MixinKey, containsErasedType, findMixinDeclaration } from '../codegen-utils.zena'; import { typeToValType, mapReturnTypeToWasmResults, mapParamTypeToWasmParams, substituteTypeParamsInCodegen, substituteTypeParamsInClassContext, getClassTypeParameters, getInterfaceTypeParameters, interfaceMethodOverloads, getClosureStruct } from '../type-mapping.zena'; import { growable } from 'zena:core'; /** * A struct field whose class type was not yet registered when the * struct was laid out, so its valtype was baked as the `structref` * fallback. Discovery can register (and instantiate) the class AFTER * that bake — a body walked late does exactly this — and then the * class's method signatures are precise while the field is erased, * which fails receiver conformance in lowering. Recorded at the bake * site and re-resolved in place once discovery settles. */ final class ErasedFieldBake { field: WasmField; fieldType: Type; new(this.field, this.fieldType); } /** * Records a mixin's private scope on the function that holds `node`'s body. * * A mixin member and a class member can share a name; the class's wins, the * way an override does. Both still register under that one name, and * `registerClassMethod` hands the second caller the function the first one * created. Writing the mixin's scope onto it unconditionally would make the * class's own body resolve its `#` names in the mixin's namespace, where * lowering cannot find them. */ export function applyMixinPrivateScope( fn: WasmFunction, node: Node | null, scope: String | null): void { if (scope == null) { return; } let key = scope as String; if (key == "" || fn.node !== node) { return; } fn.privateScopeKey = key; } /** * Specializer handles the monomorphization of generic classes and functions, * generating runtime specialized structures, vtables, and method wrappers. */ export final class Specializer implements SpecializerInterface { pass: ReachabilityContext; /** Fields baked erased before their class type existed; see ErasedFieldBake. */ #erasedFieldBakes = new Array(); new(this.pass); /** * Re-resolves fields that were baked as `structref` because their * class type had no registration at layout time. Runs once discovery * has fully settled — the same moment the settled layout pass * catches structs that were instantiated late — so a field of a * late-registered class agrees with that class's (now precise) * method signatures. A field whose type still does not resolve stays * erased, which is the pre-existing consistent-erasure behavior. * * Mutates the WasmField in place: inherited fields are shared * instances between super- and subclass structs, and the write must * be visible through both. */ refreshErasedFieldTypes(): void { for (let bake in this.#erasedFieldBakes) { let valType = typeToValType(this.pass.wasm, bake.fieldType); if (valType is ValTypeRef) { bake.field.type = valType; } } } /** * Create the globals backing a class's static fields. One global per * field, named for the class rather than any specialization, because a * static cannot name the class's type parameters and so does not vary * with them. * * Driven by reaching a static, NOT by instantiating the class: a * generic class whose statics are all anyone uses is never * instantiated, and its counter still has to exist. */ discoverStaticFields(classType: ClassType, cd: ClassDeclaration, model: SemanticModel): void { for (let member in cd.body) { if (!(member is FieldDefinition)) { continue; } if (!member.isStatic) { continue; } // `static symbol sym;` parses as a static field annotated `symbol`, // but a symbol is an identity rather than storage: it has no value, // so there is no global to hold it and no type to give one. if (isSymbolFieldDeclaration(member)) { continue; } let fieldName = memberKeyOf(model, member.name as Node); if (fieldName == "") { continue; } let name = `${cd.name.name}_${fieldName}`; // One global per class, not per specialization: two instantiations // of a generic class share the cell, and reaching a static can now // get here without any instantiation at all. var already = false; for (let existing in this.pass.wasm.globals) { if (existing.name == name) { already = true; } } if (already) { continue; } let fType = if (classType.staticMembers.has(fieldName)) { classType.staticMembers[fieldName].type } else { model.getNodeType(member) }; let vType = typeToValType(this.pass.wasm, fType as Type); let initExp: Expression | null = if (member.value != null) { member.value as Expression } else { null }; this.pass.wasm.globals.push( new WasmGlobal(name, fieldName, vType, true, initExp, null, model)); } } /** * The field decorator applications in `classType`'s chain whose body * reads its `context` (docs/design/decorators.md, "The decorated * field's context"). For each: the decorated field's accessors are * registered on the host and reached, whether or not the program * reads the field directly, and one closure-ABI wrapper per accessor * is minted — `context.get`'s `(ctx, host) -> T` and `context.set`'s * `(ctx, host, value)` — keyed by the application's class key in * `decoratorContextWrappers`, where lowering finds them. The field's * name is noted as a string literal, since `context.name` lowers to * one. */ #rootDecoratorContexts(classType: ClassType, model: SemanticModel): void { let decorated = classType.decoratedFields; if (decorated == null) { return; } let hostId = (classType.genericSource ?? classType).symbolId; let cd = if (let (true, decl) = this.pass.classDecls.get(hostId)) decl else null; var chain = classType.superType; while (chain != null && chain.isMixinIntermediate) { let sc = chain; chain = sc.superType; if (sc.decoratorSubjectName == null || sc.decoratorFieldName == null) { continue; } let fieldName = sc.decoratorFieldName as String; if (!decorated.has(fieldName)) { continue; } let df = decorated[fieldName]; let source = df.decorator.genericSource ?? df.decorator; let decl = findMixinDeclaration(this.pass.program, df.decorator); if (decl == null) { continue; } let subjectOpt = decl.decoratorSubject; if (subjectOpt == null) { continue; } let subjectNode = subjectOpt as FieldDefinition; if (!(subjectNode.name is Identifier)) { continue; } // Rooted only for a decorator whose body reads `context`. let decId = source.symbolId; let nodeModel = if (this.pass.classModels.has(decId)) { this.pass.classModels[decId] } else { model }; let contextSym = nodeModel.resolveDeclaration(subjectNode.name); if (contextSym == null || !contextSym.decoratorContextUsed) { continue; } let appKey = getClassKey(sc) as String; if (this.pass.wasm.decoratorContextWrappers.has(`${appKey}::get`)) { continue; } // The subject accessor, registered under the field's name as the // member loop registers it (analysis.zena, the decorator path). let subject = sc.decoratorSubjectName as String; var accNode: AccessorDeclaration | null = null; for (let m in decl.body) { if (m is AccessorDeclaration && memberKeyOf(nodeModel, m.name as Node) == subject) { accNode = m as AccessorDeclaration; } } if (accNode == null) { continue; } let acc = accNode as AccessorDeclaration; let scope = sc.privateScopeKey; let hostType: Type = sc.onType ?? new AnyRefType(); let fieldType = df.fieldType; // The record `context` lowers to, at this application's field // type: discovered here because the body's own walk sees it at // the decorator's type parameter, and the host constructor lowers // an initializer that reads it under this application. let contextProps = new Map(); let stringClass = this.pass.wasm.stringClass; if (stringClass != null) { contextProps["name"] = stringClass as Type; } contextProps["get"] = new FunctionType(growable([hostType]), fieldType); if (acc.setter != null) { contextProps["set"] = new FunctionType(growable([hostType, fieldType]), new VoidType()); } this.pass.typeLowerer.discoverType( new RecordType(contextProps, null, null, false), nodeModel); if (acc.getter != null) { let regG = this.registerClassMethod(classType, cd, `get#${fieldName}`, acc, false, false, null, nodeModel, null); regG.declaringType = sc; applyMixinPrivateScope(regG, acc, scope); this.pass.wasm.addFunction(regG); this.pass.markFunctionReached(regG); let getFt = new FunctionType(growable([hostType]), fieldType); this.#mintDecoratorContextWrapper(`${appKey}::get`, getFt, regG, nodeModel); } let {setter} = acc; if (setter != null) { let regS = this.registerClassMethod(classType, cd, `set#${fieldName}`, setter, false, false, null, nodeModel, null); regS.declaringType = sc; applyMixinPrivateScope(regS, setter, scope); this.pass.wasm.addFunction(regS); this.pass.markFunctionReached(regS); let setFt = new FunctionType(growable([hostType, fieldType]), new VoidType()); this.#mintDecoratorContextWrapper(`${appKey}::set`, setFt, regS, nodeModel); } this.pass.visitor.noteStringLiteral(fieldName); } } /** One `context.get`/`context.set` wrapper: the closure ABI around `target`. */ #mintDecoratorContextWrapper(key: String, ft: FunctionType, target: WasmFunction, model: SemanticModel): void { let wrapperParams = growable([new ValTypeStructRef()]); for (let p in ft.parameters) { mapParamTypeToWasmParams(this.pass.wasm, p, wrapperParams); } let wrapperReturns = new Array(); mapReturnTypeToWasmResults(this.pass.wasm, ft.returnType, wrapperReturns); let sig = this.pass.wasm.getSignature(wrapperParams, wrapperReturns); let wrapper = new WasmFunction(sig, null, model); let targetName = if (target.name != null) target.name as String else "accessor"; wrapper.name = `${targetName}_context_${getSignatureKey(ft)}`; wrapper.decoratorAccessorTarget = target; wrapper.isReferenceTaken = true; this.pass.wasm.decoratorContextWrappers[key] = wrapper; this.pass.wasm.addFunction(wrapper); this.pass.markFunctionReached(wrapper); this.pass.reachablyNamedClosures.add(getClosureStruct(this.pass.wasm, ft)); } instantiateClassType(classType: ClassType, model: SemanticModel): void { if (!this.pass.isRtaActive) { return; } if (!isConcrete(classType) || containsErasedType(classType as Type)) { return; } let cha = this.pass.cha; let typeLowerer = this.pass.typeLowerer; let cKey = getClassKey(classType) as String; if (this.pass.instantiatedSpecializedClasses.has(cKey)) { return; } if (this.pass.instantiationClosed) { throw new Error("class instantiated after layout began: " + cKey); } this.pass.instantiatedSpecializedClasses.add(cKey); cha.registerInstantiatedClass(classType); // Values of this specialization exist, whoever first mentioned it: // list it, so a member reached on the generic later fans out over // it. Discovery passes over mentions made while laying out a class // the module will never emit, and this is where such a // specialization rejoins the register if it turns out to be real. this.pass.noteSpecialization(classType, model); this.#rootDecoratorContexts(classType, model); // Instantiation promotes constructors only for DEMANDED generics — // ones with a `new` site somewhere (queueExplicitCtor records the // demand; concrete sites also pend by key). Unconditional // promotion emitted a constructor nothing calls in every // literal-only String program — string_from_shared builds its // String with struct.new directly. if (this.pass.ctorDemandedGenerics.has((classType.genericSource ?? classType).symbolId)) { if (let (true, funcs) = this.pass.wasm.classMethods.get(cKey)) { for (let func in funcs) { if (func.methodName != null && isConstructorMethodName(func.methodName as String) && !this.pass.reachedFunctionsSet.has(func)) { this.pass.wasm.addFunction(func); this.pass.markFunctionReached(func); // See #reachSuperConstructors: `: super(...)` calls it. this.#reachSuperConstructors(func); } } } } /* if (let (true, funcs) = this.pass.wasm.classMethods.get(cKey)) { for (let func in funcs) { if (!this.pass.reachedFunctionsSet.has(func)) { this.pass.wasm.addFunction(func); this.pass.markFunctionReached(func); } } } */ // A specialization's concrete class type arguments are // instantiated with it: if `FixedArray` exists then String // values exist, and its `contains` lowers to String's `==`. While // String was instantiated unconditionally this held by accident. let typeArguments = classType.typeArguments; if (typeArguments != null) { for (let ta in typeArguments) { if (ta is ClassType && isConcrete(ta)) { if (getClassKey(ta) != getClassKey(classType)) { this.instantiateClassType(ta, this.pass.getClassModel(ta)); } } } } let unspecC = classType.genericSource ?? classType; let classId = unspecC.symbolId; this.pass.instantiatedClasses.add(classId); if (this.pass.specializedClassTypes.has(classId)) { let list = this.pass.specializedClassTypes[classId]; for (let specCt in list) { this.instantiateClassType(specCt, this.pass.getClassModel(specCt)); } } // Keep == and hashCode for any instantiated class if they exist, // as they can be called virtually by generic operations and HashMap/HashSet. let unspecModel = this.pass.getClassModel(classType); // Propagate all reached members of the base class to this new instantiation if (let (true, reachedSet) = this.pass.reachedClassMembers.get(classId)) { let rcKeys = reachedSet.keys(); for (let memberNodeId in rcKeys) { let memberModel = if (this.pass.nodeIdToModel.has(memberNodeId)) { this.pass.nodeIdToModel[memberNodeId] } else { unspecModel }; this.pass.queueReferrer(new Referrer(false, noSymbolId, memberNodeId, memberModel, classType, false)); } } if (let (true, reachedSet) = this.pass.reachedReachableClassMembers.get(classId)) { let rrKeys = reachedSet.keys(); for (let memberNodeId in rrKeys) { let memberModel = if (this.pass.nodeIdToModel.has(memberNodeId)) { this.pass.nodeIdToModel[memberNodeId] } else { unspecModel }; this.pass.queueReferrer(new Referrer(false, noSymbolId, memberNodeId, memberModel, classType, true)); } } // ==/hashCode referrers follow the same evidence as their slots: // without erased equality anywhere, instantiation alone is not a // reason to emit them. Direct `a == b` on concrete receivers // reaches the operator through its own member records. this.pass.reachEqualityBelowComparedBase(classType); if (this.pass.equalityDispatchUsed) { this.pass.reachEqualityOf(classType); let hashMethod = cha.findImplementingMethod(classType, "hashCode"); if (hashMethod != null) { this.pass.queueReferrer(new Referrer(false, noSymbolId, (hashMethod as Node).id as i32, this.pass.getNodeModel(hashMethod as Node, unspecModel), classType, this.pass.currentReachable)); } } if (classType.superType != null) { let superType = classType.superType as ClassType; this.instantiateClassType(superType, this.pass.getClassModel(superType)); } typeLowerer.discoverType(classType, model); let classDecl: Node | null = if (this.pass.classDecls.has(classId)) { this.pass.classDecls[classId] } else { null }; if (classDecl is ClassDeclaration) { this.discoverStaticFields(classType, classDecl, model); // Check if there is an explicit constructor var hasExplicitCtor = false; for (let member in classDecl.body) { if (member is MethodDefinition) { if (member.isConstructor) { hasExplicitCtor = true; } } } if (!hasExplicitCtor && !classType.isExtension && !classType.isMixinIntermediate && !containsErasedType(classType as Type)) { this.registerClassMethod(classType, classDecl, "", null, false, false, null, model); } if (synthesizedRelease(classType)) { // A class whose only release action is its fields: the checker // synthesized its release member (a resource's `:dispose`, a // `scoped T` class's `[release]`), and lowering emits the field // glue as its whole body. let dFunc = this.registerClassMethod(classType, classDecl, releaseMemberOf(classType), null, false, false, null, model); dFunc.isSyntheticRelease = true; } // Discover constructor and field initializers for (let member in classDecl.body) { if (member is MethodDefinition) { if (member.isConstructor) { this.pass.queueReferrer(new Referrer(false, noSymbolId, (member as Node).id as i32, model, classType, this.pass.currentReachable)); } } else if (member is FieldDefinition) { if (member.value != null) { this.pass.queueReferrer(new Referrer(false, noSymbolId, (member as Node).id as i32, model, classType, this.pass.currentReachable)); } } } } else if (classDecl is SealedVariant) { if (!classType.isExtension && !classType.isMixinIntermediate && !containsErasedType(classType as Type)) { this.registerClassMethod(classType, null, "", null, false, false, null, model); } } else if (classDecl != null) { if (!classType.isExtension && !classType.isMixinIntermediate && !containsErasedType(classType as Type)) { this.registerClassMethod(classType, null, "", null, false, false, null, model); } if (classDecl is MixinDeclaration) { for (let composed in classType.mixins) { let compLookupId = (composed.genericSource ?? composed).symbolId; if (this.pass.classDecls.has(compLookupId)) { let cDecl = this.pass.classDecls[compLookupId]; if (cDecl is MixinDeclaration) { let compModel = if (this.pass.classModels.has(compLookupId)) this.pass.classModels[compLookupId] else model; for (let member in cDecl.body) { if (member is FieldDefinition) { if (member.value != null) { this.pass.queueReferrer(new Referrer(false, noSymbolId, (member as Node).id as i32, compModel, classType, this.pass.currentReachable)); } } } } } } for (let member in classDecl.body) { if (member is FieldDefinition) { if (member.value != null) { this.pass.queueReferrer(new Referrer(false, noSymbolId, (member as Node).id as i32, model, classType, this.pass.currentReachable)); } } } } } } registerSpecializedClass(ct: ClassType, classDecl: Node | null, sourceModel: SemanticModel): void { if (!this.preRegisterClassStruct(ct)) { return; } this.finishSpecializedClass(ct, classDecl, sourceModel); } preRegisterClassStruct(ct: ClassType): boolean { let cKey = getClassKey(ct); if (this.pass.wasm.classInfos.has(cKey)) { return false; } // 1. Pre-register empty structs let structName = cKey as String; let emptyStruct = new WasmStruct(structName, new Array()); emptyStruct.classType = ct; if (!ct.isExtension) { this.pass.wasm.types.push(emptyStruct); } let info = new ClassCodegenInfo(emptyStruct); this.pass.wasm.classInfos[cKey] = info; let emptyVTableStruct = new WasmStruct(structName + "_VTable", new Array()); emptyVTableStruct.classType = ct; if (!ct.isExtension) { this.pass.wasm.types.push(emptyVTableStruct); } info.vtableStructType = emptyVTableStruct; return true; } finishSpecializedClass(ct: ClassType, classDecl: Node | null, sourceModel: SemanticModel): void { let cKey = getClassKey(ct); let info = this.pass.wasm.classInfos[cKey]; let emptyStruct = info.structType; let emptyVTableStruct = info.vtableStructType as WasmStruct; let ctVtable = this.pass.wasm.classVtable(cKey); let ctParams = getClassTypeParameters(ct); let isErasedClass = containsErasedType(ct as Type); // 2. Link super types let {superType} = ct; if (superType != null) { let superCt = superType; this.pass.typeLowerer.discoverType(superCt, sourceModel); let superKey = getClassKey(superCt); if (let (true, superInfo) = this.pass.wasm.classInfos.get(superKey)) { if (!superCt.isExtension) { emptyStruct.superStruct = superInfo.structType; var hasSub = false; for (let existingSub in superInfo.subclasses) { if (existingSub === info) { hasSub = true; break; } } if (!hasSub) { superInfo.subclasses.push(info); } let {vtableStructType} = superInfo; if (vtableStructType != null) { emptyVTableStruct.superStruct = vtableStructType; } } } let superVtable = this.pass.wasm.classVtable(superKey); if (superVtable.length > 0 || ctVtable.length > 0) { let newVTable = new Array(); for (let methName in superVtable) { newVTable.push(methName); } for (let methName in ctVtable) { var hasMeth = false; for (let existing in newVTable) { if (existing == methName) { hasMeth = true; break; } } if (!hasMeth) { newVTable.push(methName); } } while (ctVtable.length > 0) { ctVtable.pop(); } for (let m in newVTable) { ctVtable.push(m); } } } if (ct.derivesEquality && !isErasedClass) { var hasEq = false; var hasHash = false; for (let existing in ctVtable) { if (existing == "==") { hasEq = true; } if (existing == "hashCode") { hasHash = true; } } if (!hasEq) { ctVtable.push("=="); } if (!hasHash) { ctVtable.push("hashCode"); } } // 3. Discover referenced types in members (fields) let typeLowerer = this.pass.typeLowerer; let cha = this.pass.cha; for (let pair in ct.members) { if (pair.value is FieldInfo) { let resolvedType = substituteTypeParamsInCodegen(this.pass.wasm, ctParams, ct.typeArguments, pair.value.type); typeLowerer.discoverType(resolvedType, sourceModel); } } let specIfaces = cha.collectAllImplementedInterfaces(ct); for (let iface in specIfaces) { typeLowerer.discoverType(iface, sourceModel); } // An ERASURE gets a struct and nothing else. Erased signatures and // fields name the struct, so it has to exist — but no value is ever if (isErasedClass || ct.isMixinIntermediate) { this.populateClassStructAndMethods(ct, classDecl, sourceModel); return; } // 4. Populate VTable slots and structs let allMembers = new Array(); let allScopes = new Array(); let allModels = new Array(); let allDecls = new Array(); let allDeclaringTypes = new Array(); let classDeclCd = if (classDecl is ClassDeclaration) classDecl else null; let mixinDeclMd = if (classDecl is MixinDeclaration) classDecl else null; if (classDeclCd != null) { var mixinSup = ct.superType; let mixinChain = new Array(); while (mixinSup != null && mixinSup.isMixinIntermediate) { mixinChain.push(mixinSup); mixinSup = mixinSup.superType; } var mci = mixinChain.length - 1; while (mci >= 0) { let mSup = mixinChain[mci]; let mLookupId = (mSup.genericSource ?? mSup).symbolId; if (this.pass.classDecls.has(mLookupId)) { let mDecl = this.pass.classDecls[mLookupId]; if (mDecl is MixinDeclaration) { for (let composed in mSup.mixins) { let compLookupId = (composed.genericSource ?? composed).symbolId; if (this.pass.classDecls.has(compLookupId)) { let cDecl = this.pass.classDecls[compLookupId]; if (cDecl is MixinDeclaration) { let compModel = if (this.pass.classModels.has(compLookupId)) this.pass.classModels[compLookupId] else sourceModel; for (let ms in (cDecl as MixinDeclaration).body) { allMembers.push(ms); allScopes.push(composed.privateScopeKey ?? ""); allModels.push(compModel); allDecls.push(cDecl); allDeclaringTypes.push(mSup); } } } } let mModel = if (this.pass.classModels.has(mLookupId)) this.pass.classModels[mLookupId] else sourceModel; for (let ms in (mDecl as MixinDeclaration).body) { allMembers.push(ms); allScopes.push(mSup.privateScopeKey ?? ""); allModels.push(mModel); allDecls.push(mDecl); allDeclaringTypes.push(mSup); } } } mci -= 1; } for (let ms in classDeclCd.body) { allMembers.push(ms); allScopes.push(""); allModels.push(sourceModel); allDecls.push(classDeclCd); allDeclaringTypes.push(null); } } else if (mixinDeclMd != null) { for (let composed in ct.mixins) { let compLookupId = (composed.genericSource ?? composed).symbolId; if (this.pass.classDecls.has(compLookupId)) { let cDecl = this.pass.classDecls[compLookupId]; if (cDecl is MixinDeclaration) { let compModel = if (this.pass.classModels.has(compLookupId)) this.pass.classModels[compLookupId] else sourceModel; for (let ms in (cDecl as MixinDeclaration).body) { allMembers.push(ms); allScopes.push(composed.privateScopeKey ?? ""); allModels.push(compModel); allDecls.push(cDecl); allDeclaringTypes.push(ct); } } } } for (let ms in mixinDeclMd.body) { allMembers.push(ms); allScopes.push(ct.privateScopeKey ?? ""); allModels.push(sourceModel); allDecls.push(mixinDeclMd); allDeclaringTypes.push(ct); } } var vtMemberIdx = -1; for (let ms in allMembers) { vtMemberIdx += 1; if (ms is MethodDefinition) { if (ms.isStatic) { continue; } if (ms.isConstructor) { continue; } let methName = memberKeyOf(sourceModel, ms.name as Node); if (methName != "") { var vtableMethName = methName; if (ct.members.has(methName)) { let mInfo = ct.members[methName]; if (mInfo.type is FunctionType) { let ft = mInfo.type as FunctionType; let specificType = matchOverload(sourceModel, ft, ms); if (specificType != null) { vtableMethName = methName + getSignatureKey(specificType); } } } var found = false; for (let existing in ctVtable) { if (existing == vtableMethName) { found = true; } } // Private methods are never virtual (member-lookup.md §6): // they get no vtable slot and are always called directly. let isPrivateMeth = methName.length > 0 && methName.sliceBytes(0, 1) == "#"; // Neither is a GENERIC method: a slot holds one `ref.func` // of one signature, and a generic method has no single body // — it exists once per specialization, each with its own. let isGenericMeth = ms.typeParameters != null && (ms.typeParameters as GrowableArray).length > 0; if (!found && !ms.isConstructor && methName != "" && !isPrivateMeth && !isGenericMeth && !ct.isExtension) { ctVtable.push(vtableMethName); } } } else if (ms is AccessorDeclaration) { if (ms.isStatic) { continue; } let accName = this.#registeredAccessorName( memberKeyOf(sourceModel, ms.name as Node), allDeclaringTypes[vtMemberIdx]); // Private-named accessors are lexical, never virtual: no // vtable slots (like private methods). if (accName != "" && !(accName.length > 0 && accName.sliceBytes(0, 1) == "#")) { if (ms.getter != null) { let getterName = "get#" + accName; var found = false; for (let existing in ctVtable) { if (existing == getterName) { found = true; break; } } if (!found && !ct.isExtension) { ctVtable.push(getterName); } } if (ms.setter != null) { let setterName = "set#" + accName; var found = false; for (let existing in ctVtable) { if (existing == setterName) { found = true; break; } } if (!found && !ct.isExtension) { ctVtable.push(setterName); } } } } else if (ms is FieldDefinition) { if (ms.isStatic) { continue; } let fieldName = memberKeyOf(sourceModel, ms.name as Node); if (this.#isDecoratedField(ct, fieldName)) { continue; } if (ms.setterName != null && fieldName != "") { let getterName = "get#" + fieldName; var found = false; for (let existing in ctVtable) { if (existing == getterName) { found = true; break; } } if (!found) { ctVtable.push(getterName); } } if (ms.isAbstract && fieldName != "") { let getterName = "get#" + fieldName; var found = false; for (let existing in ctVtable) { if (existing == getterName) { found = true; break; } } if (!found) { ctVtable.push(getterName); } if (ms.mutability != null && ms.mutability == "var") { let setterName = "set#" + fieldName; var foundS = false; for (let existing in ctVtable) { if (existing == setterName) { foundS = true; break; } } if (!foundS) { ctVtable.push(setterName); } } } if (ms.isDeclare && fieldName != "") { let getterName = "get#" + fieldName; var found = false; for (let existing in ctVtable) { if (existing == getterName) { found = true; break; } } if (!found) { ctVtable.push(getterName); } } } } // 5. Register specialized methods var msIdx = -1; for (let ms in allMembers) { msIdx += 1; // Mixin-declared members get the mixin's private scope key so // their bodies resolve "#" fields to the mixin's namespaced // struct fields (WasmFunction.privateScopeKey). let msScope = allScopes[msIdx]; if (ms is MethodDefinition) { if (ms.isAbstract) { continue; } let {typeParameters} = ms; if (typeParameters != null && typeParameters.length > 0) { continue; } let methName = memberKeyOf(sourceModel, ms.name as Node); // Mixin private methods register under the mixin's scope key // ("::#name") so a host's same-named private is a // different function; bodies from mixins carry the scope for // their own private accesses. let declNode = allDecls[msIdx]; let memberScope = this.#memberScopeOf(ms, msScope, allDeclaringTypes[msIdx]); let regName = if (ms.isConstructor) { if (methName == "") "" else "." + methName } else if (memberScope != "" && methName.length > 0 && methName.sliceBytes(0, 1) == "#") { `${memberScope}::${methName}` } else { methName }; let regFn = this.registerClassMethod(ct, declNode, regName, ms as Node, false, false, null, allModels[msIdx]); regFn.declaringType = allDeclaringTypes[msIdx]; applyMixinPrivateScope(regFn, ms as Node, memberScope); } else if (ms is AccessorDeclaration) { let declNode = allDecls[msIdx]; let accName = this.#registeredAccessorName( memberKeyOf(sourceModel, ms.name as Node), allDeclaringTypes[msIdx]); let isPrivateAcc = accName.length > 0 && accName.sliceBytes(0, 1) == "#"; if (ms.getter != null) { var getterRegName = "get#" + accName; if (isPrivateAcc && msScope != "") { getterRegName = `${msScope}::${getterRegName}`; } let regG = this.registerClassMethod(ct, declNode, getterRegName, ms as Node, false, false, null, allModels[msIdx]); regG.declaringType = allDeclaringTypes[msIdx]; applyMixinPrivateScope(regG, ms as Node, msScope); } let {setter} = ms; if (setter != null) { var setterRegName = "set#" + accName; if (isPrivateAcc && msScope != "") { setterRegName = `${msScope}::${setterRegName}`; } let regS = this.registerClassMethod(ct, declNode, setterRegName, setter, false, false, null, allModels[msIdx]); regS.declaringType = allDeclaringTypes[msIdx]; applyMixinPrivateScope(regS, setter, msScope); } } else if (ms is FieldDefinition) { if (ms.isStatic) { continue; } let declNode = allDecls[msIdx]; let fieldName = memberKeyOf(sourceModel, ms.name as Node); if (fieldName != "" && !this.#isDecoratedField(ct, fieldName)) { if (!fieldName.startsWith("#")) { this.registerClassMethod(ct, declNode, "get#" + fieldName, null, true, false, fieldName, allModels[msIdx]); if (ms.mutability != null && ms.mutability == "var") { this.registerClassMethod(ct, declNode, "set#" + fieldName, null, false, true, fieldName, allModels[msIdx]); } } else { if (ms.setterName != null) { this.registerClassMethod(ct, declNode, "get#" + fieldName, null, true, false, fieldName, allModels[msIdx]); } if (ms.isAbstract) { this.registerClassMethod(ct, declNode, "get#" + fieldName, null, true, false, fieldName, allModels[msIdx]); if (ms.mutability != null && ms.mutability == "var") { this.registerClassMethod(ct, declNode, "set#" + fieldName, null, false, true, fieldName, allModels[msIdx]); } } if (ms.isDeclare) { this.registerClassMethod(ct, declNode, "get#" + fieldName, null, true, false, fieldName, allModels[msIdx]); } } } } } var hasExplicitCtor = false; if (classDecl != null) { let bodyNodes: GrowableArray | null = if (classDecl is ClassDeclaration) { classDecl.body } else if (classDecl is InterfaceDeclaration) { classDecl.body } else if (classDecl is MixinDeclaration) { classDecl.body } else { null }; if (bodyNodes != null) { for (let member in bodyNodes) { if (member is MethodDefinition) { if (member.isConstructor) { hasExplicitCtor = true; } } } } } if (!hasExplicitCtor && !ct.isExtension && !ct.isMixinIntermediate && !containsErasedType(ct as Type)) { this.registerClassMethod(ct, classDecl, "", null, false, false, null, sourceModel); } if (ct.derivesEquality) { let eqFunc = this.registerClassMethod(ct, classDecl, "==", null, false, false, null, sourceModel); eqFunc.isCaseClassEq = true; let hashFunc = this.registerClassMethod(ct, classDecl, "hashCode", null, false, false, null, sourceModel); hashFunc.isCaseClassHash = true; } if (synthesizedRelease(ct)) { // A class whose only release action is its fields: the checker // synthesized its release member (a resource's `:dispose`, a // `scoped T` class's `[release]`), and lowering emits the field // glue as its whole body. let dFunc = this.registerClassMethod(ct, classDecl, releaseMemberOf(ct), null, false, false, null, sourceModel); dFunc.isSyntheticRelease = true; } // Register implicit interface getters/setters for specialized classes let allIfaces = this.pass.cha.collectAllImplementedInterfaces(ct); for (let iface in allIfaces) { getInterfaceKey(iface); if (this.pass.isPackPairUsed(ct, iface)) { let keys = iface.members.keys(); for (let key in keys) { let member = iface.members[key]; if (member is FieldInfo) { let getterName = "get#" + key; getInterfaceKey(iface.genericSource ?? iface); let hasGetter = this.pass.wasm.classMethodMap.has(getClassMethodKey(cKey, getterName)); if (!hasGetter) { this.registerClassMethod(ct, classDecl, getterName, null, true, false, key, sourceModel); } if (member.isMutable) { let setterName = "set#" + key; let hasSetter = this.pass.wasm.classMethodMap.has(getClassMethodKey(cKey, setterName)); if (!hasSetter) { this.registerClassMethod(ct, classDecl, setterName, null, false, true, key, sourceModel); } } } } } } this.populateClassStructAndMethods(ct, classDecl, sourceModel); } registerSpecializedInterface(it: InterfaceType, ifaceDecl: InterfaceDeclaration | null, sourceModel: SemanticModel): void { if (!this.preRegisterInterfaceStruct(it)) { return; } this.finishSpecializedInterface(it, ifaceDecl, sourceModel); } preRegisterInterfaceStruct(it: InterfaceType): boolean { let iKey = getInterfaceKey(it); if (this.pass.wasm.interfaceStructs.has(iKey)) { return false; } // 1. Pre-register empty vtable and fat ptr structs let structName = iKey as String; let emptyVTableStruct = new WasmStruct(structName + "_VTable", new Array()); this.pass.wasm.types.push(emptyVTableStruct); this.pass.wasm.interfaceVTableStructs[iKey] = emptyVTableStruct; let fatPtrFields = growable([ new WasmField("instance", new ValTypeAnyRef(), false), new WasmField("vtable", new ValTypeRef(emptyVTableStruct), false), ]); let emptyStruct = new WasmStruct(structName + "_FatPtr", fatPtrFields); this.pass.wasm.types.push(emptyStruct); this.pass.wasm.interfaceStructs[iKey] = emptyStruct; // The vtable's slots are added for the members reached code calls // (ReachabilityAnalysis.#syncInterfaceSlots). this.pass.specializedInterfaces.push(it); return true; } finishSpecializedInterface(it: InterfaceType, ifaceDecl: InterfaceDeclaration | null, sourceModel: SemanticModel): void { let itParams = getInterfaceTypeParameters(it); // 2. Discover referenced types in members (fields, methods) — as // SIGNATURES: an interface method's function type is not a value, // and value-routing it minted a closure struct + impl signature // per member (22 of them from one Iterable-family interface). // Registration plumbing, so no name evidence (see // registerClassMethod). let savedSuppress = this.pass.suppressNameEvidence; this.pass.suppressNameEvidence = true; for (let pair in it.members) { let resolvedType = substituteTypeParamsInCodegen(this.pass.wasm, itParams, it.typeArguments, pair.value.type); this.pass.typeLowerer.discoverSignatureType(resolvedType, sourceModel); // Substitution leaves an overload list as declared, so each // overload's types are discovered separately. let overloads = interfaceMethodOverloads(this.pass.wasm, it, pair.key); if (overloads != null) { for (let overload in overloads) { this.pass.typeLowerer.discoverSignatureType(overload, sourceModel); } } } this.pass.suppressNameEvidence = savedSuppress; } /** * The class in `ct`'s super chain whose own declaration body * contains `node`, or null when none does (mixin members and * synthesized accessors have no declaring class in the chain). * `instantiateClassType` substitutes `superType` per hop, so the hop * that declares the node IS the declaring class's resolved * instantiation — the substitution context an inherited body is * lowered under. */ declaringClassOf(ct: ClassType, node: Node): ClassType | null { var c: ClassType | null = ct; while (c != null) { let cc = c; if (cc.isMixinIntermediate) { c = cc.superType; continue; } let lookupId = (cc.genericSource ?? cc).symbolId; if (this.pass.classDecls.has(lookupId)) { let decl = this.pass.classDecls[lookupId]; if (decl is ClassDeclaration) { for (let member in (decl as ClassDeclaration).body) { if (member === node) { return cc; } if (member is AccessorDeclaration && (member as AccessorDeclaration).setter != null && ((member as AccessorDeclaration).setter as Node) === node) { return cc; } } } } c = cc.superType; } return null; } registerClassMethod( cType: ClassType, cDecl: Node | null, methName: String, methodNode: Node | null, isSynthesizedGetter: boolean, isSynthesizedSetter: boolean, backingFieldName: String | null, model: SemanticModel, methodTypeArgs: Array | null = null): WasmFunction { // An inherited member registers under its declaring class's // resolved instantiation, not the instantiating class // (binary-size.md §16): the body can only mention type parameters // in scope at its declaration site, so the subclass-keyed copy is // byte-identical to the declaring class's. An override is a // different declaration — its declaring class IS the subclass — // and a subclass binding the base's generics differently resolves // to a different instantiation, so distinct copies survive exactly // where the key genuinely differs. Vtable slots and every lowering // lookup already walk the super chain, so they find the shared // body one hop later. Mixin-scoped names ("Scope::#x") stay // per-host: a mixin body's `this` maps to the host class. // Templates and erasures keep the old keying — nothing is emitted // at either. if (methodNode != null && !methName.contains("::") && isConcrete(cType) && !containsErasedType(cType as Type)) { let declaring = this.declaringClassOf(cType, methodNode); if (declaring != null && declaring != cType) { let declId = ((declaring.genericSource ?? declaring)).symbolId; let dDecl = if (this.pass.classDecls.has(declId)) { this.pass.classDecls[declId] } else { cDecl }; let dModel = if (this.pass.classModels.has(declId)) { this.pass.classModels[declId] } else { model }; return this.registerClassMethod(declaring, dDecl, methName, methodNode, isSynthesizedGetter, isSynthesizedSetter, backingFieldName, dModel, methodTypeArgs); } } var isStatic = false; if (methodNode != null) { if (methodNode is MethodDefinition) { isStatic = methodNode.isStatic; } else if (methodNode is AccessorDeclaration) { isStatic = methodNode.isStatic; } else if (methodNode is FieldDefinition) { isStatic = methodNode.isStatic; } else if (methodNode is SetterInfo) { let parentNode = model.getParent(methodNode); if (parentNode is AccessorDeclaration) { isStatic = parentNode.isStatic; } else if (cDecl is ClassDeclaration) { for (let ms in cDecl.body) { if (ms is AccessorDeclaration && ms.setter === methodNode) { isStatic = ms.isStatic; break; } } } else if (cDecl is MixinDeclaration) { for (let ms in cDecl.body) { if (ms is AccessorDeclaration && ms.setter === methodNode) { isStatic = ms.isStatic; break; } } } } } if (!isStatic && methodNode == null && !isSynthesizedGetter && !isSynthesizedSetter && cType != null && !cType.members.has(methName) && cType.staticMembers.has(methName)) { let mi = cType.staticMembers[methName]; if (mi is MethodInfo) { isStatic = mi.isStatic; } } var realMethName = methName; var methodTypeNode: Type | null = null; var origMethodFt: FunctionType | null = null; if (cType != null) { let cTypeMembers = cType.memberTable(isStatic); if (methName == "") { methodTypeNode = cType.constructorType; // A self-referential generic class instantiates ITSELF while its // own declaration is mid-check — before constructorType is filled // — and that cached instantiation keeps the null forever (the // instantiation caches copy constructorType by value). Derive the // signature from the generic source instead of registering a // bogus receiver-only constructor. if (methodTypeNode == null && cType.genericSource != null) { let gs = cType.genericSource as ClassType; let {constructorType} = gs; if (constructorType != null) { methodTypeNode = substituteTypeParamsInCodegen(this.pass.wasm, gs.typeParameters, cType.typeArguments, constructorType); } } } else if (methName.startsWith(".")) { let ctorName = methName.sliceBytes(14, methName.length); if (cType.constructors.has(ctorName)) { methodTypeNode = cType.constructors[ctorName]; } if (methodTypeNode == null && cType.genericSource != null) { let gs = cType.genericSource as ClassType; if (gs.constructors.has(ctorName)) { let origCtor = gs.constructors[ctorName]; methodTypeNode = substituteTypeParamsInCodegen(this.pass.wasm, gs.typeParameters, cType.typeArguments, origCtor); } } } else { var specificFuncType: FunctionType | null = null; var hasOverloads = false; if (methodNode is MethodDefinition) { if (cTypeMembers.has(methName)) { let mInfo = cTypeMembers[methName]; if (mInfo.type is FunctionType) { let ft = mInfo.type as FunctionType; if (ft.overloads != null) { hasOverloads = true; specificFuncType = matchOverload(model, ft, methodNode); } } } } if (hasOverloads && specificFuncType != null) { methodTypeNode = specificFuncType; realMethName = methName + getSignatureKey(specificFuncType); } else { var baseName = methName; var sigKey = ""; var specIdx = -1; if (methName.length >= 6) { for (var idx = 0; idx <= methName.length - 6; idx += 1) { if (methName.getByteAt(idx) == 95 && // '_' methName.getByteAt(idx + 1) == 115 && // 's' methName.getByteAt(idx + 2) == 112 && // 'p' methName.getByteAt(idx + 3) == 101 && // 'e' methName.getByteAt(idx + 4) == 99 && // 'c' methName.getByteAt(idx + 5) == 95) { // '_' specIdx = idx; break; } } } if (specIdx >= 0) { baseName = methName.sliceBytes(0, specIdx); } else { var dollarIdx = -1; for (var idx = 0; idx < methName.length; idx += 1) { if (methName.getByteAt(idx) == 36) { dollarIdx = idx; break; } } if (dollarIdx > 0 && !methName.contains("get#") && !methName.contains("set#")) { baseName = methName.sliceBytes(0, dollarIdx); sigKey = methName.sliceBytes(dollarIdx, methName.length); } } var currClass: ClassType | null = cType; while (currClass != null && methodTypeNode == null) { let cc = currClass; let ccMembers = cc.memberTable(isStatic); if (baseName != methName) { if (ccMembers.has(baseName)) { let mInfo = ccMembers[baseName]; if (mInfo.type is FunctionType) { let ft = mInfo.type as FunctionType; if (specIdx >= 0) { methodTypeNode = ft; } else if (getSignatureKey(ft) == sigKey) { methodTypeNode = ft; } else if (ft.overloads != null) { let ovs = ft.overloads as GrowableArray; for (let ov in ovs) { if (getSignatureKey(ov) == sigKey) { methodTypeNode = ov; break; } } } } } } else if (ccMembers.has(methName)) { let mInfo = ccMembers[methName]; // A METHOD registration must not take its signature from // a same-named FIELD: a distributed variant's case param // may shadow the sealed base's accessor method (docs() // over a docs field), and the walk must continue up to // the class that declares the method itself. let isMethodReg = methodNode != null && methodNode is MethodDefinition; if (!isMethodReg || mInfo is MethodInfo) { methodTypeNode = mInfo.type; } } else { for (let k in ccMembers.keys()) { if (k.endsWith("::" + methName)) { let mInfo = ccMembers[k]; let isMethodReg = methodNode != null && methodNode is MethodDefinition; if (!isMethodReg || mInfo is MethodInfo) { methodTypeNode = mInfo.type; break; } } } } if (methodTypeNode == null) { currClass = cc.superType; } } } if (methodTypeNode == null) { var strippedMethName = methName; if (strippedMethName.contains("::")) { let parts = strippedMethName.split("::"); strippedMethName = parts[parts.length - 1]; } if (strippedMethName.contains(".")) { let parts = strippedMethName.split("."); strippedMethName = parts[parts.length - 1]; } if (methName == "==" && !isStatic) { let eqParams = growable([cType]); methodTypeNode = new FunctionType(eqParams, new BooleanType()); } else if (methName == "hashCode" && !isStatic) { methodTypeNode = new FunctionType(new Array(), new I32Type()); } else if (strippedMethName.startsWith("get#")) { let fieldName = strippedMethName.sliceBytes(4, strippedMethName.length); var pType: Type | null = null; var curr: ClassType | null = cType; while (curr != null && pType == null) { let cc = curr; let ccMembers = cc.memberTable(isStatic); if (ccMembers.has(methName)) { let m = ccMembers[methName]; if (m is MethodInfo && m.type is FunctionType) { pType = (m.type as FunctionType).returnType; } } if (pType == null && ccMembers.has(strippedMethName)) { let m = ccMembers[strippedMethName]; if (m is MethodInfo && m.type is FunctionType) { pType = (m.type as FunctionType).returnType; } } if (pType == null && ccMembers.has(fieldName)) { let m = ccMembers[fieldName]; if (m is FieldInfo) { pType = m.type; } else if (m is MethodInfo && m.type is FunctionType) { pType = (m.type as FunctionType).returnType; } } if (pType == null && ccMembers.has("#" + fieldName)) { let m = ccMembers["#" + fieldName]; if (m is FieldInfo) { pType = m.type; } } if (pType == null) { for (let k in ccMembers.keys()) { if (k.endsWith("::" + methName) || k.endsWith("::" + strippedMethName) || k.endsWith("::" + fieldName) || k.endsWith("::#" + fieldName)) { let m = ccMembers[k]; if (m is FieldInfo) { pType = m.type; break; } else if (m is MethodInfo && m.type is FunctionType) { pType = (m.type as FunctionType).returnType; break; } } } } curr = cc.superType; } if (pType != null) { methodTypeNode = new FunctionType(new Array(), pType); } } else if (strippedMethName.startsWith("set#")) { let fieldName = strippedMethName.sliceBytes(4, strippedMethName.length); var pType: Type | null = null; var curr: ClassType | null = cType; while (curr != null && pType == null) { let cc = curr; let ccMembers = cc.memberTable(isStatic); if (ccMembers.has(methName)) { let m = ccMembers[methName]; if (m is MethodInfo && m.type is FunctionType) { let ft = m.type as FunctionType; if (ft.parameters.length > 0) { pType = ft.parameters[0]; } else { pType = ft.returnType; } } } if (pType == null && ccMembers.has(strippedMethName)) { let m = ccMembers[strippedMethName]; if (m is MethodInfo && m.type is FunctionType) { let ft = m.type as FunctionType; if (ft.parameters.length > 0) { pType = ft.parameters[0]; } else { pType = ft.returnType; } } } if (pType == null && ccMembers.has(fieldName)) { let m = ccMembers[fieldName]; if (m is FieldInfo) { pType = m.type; } else if (m is MethodInfo && m.type is FunctionType) { let ft = m.type as FunctionType; if (ft.parameters.length > 0) { pType = ft.parameters[0]; } else { pType = ft.returnType; } } } if (pType == null && ccMembers.has("#" + fieldName)) { let m = ccMembers["#" + fieldName]; if (m is FieldInfo) { pType = m.type; } } if (pType == null) { for (let k in ccMembers.keys()) { if (k.endsWith("::" + methName) || k.endsWith("::" + strippedMethName) || k.endsWith("::" + fieldName) || k.endsWith("::#" + fieldName)) { let m = ccMembers[k]; if (m is FieldInfo) { pType = m.type; break; } else if (m is MethodInfo && m.type is FunctionType) { let ft = m.type as FunctionType; if (ft.parameters.length > 0) { pType = ft.parameters[0]; } else { pType = ft.returnType; } break; } } } } curr = cc.superType; } if (pType != null) { let params = growable([pType]); methodTypeNode = new FunctionType(params, new VoidType()); } } } } } if (methodTypeNode is FunctionType) { origMethodFt = methodTypeNode; } if (methodTypeNode != null && cType != null) { // Full class-context substitution, not just cType's own params: // a member found up the super chain (an inherited private // method, a synthesized accessor for an inherited field) has a // type written in terms of the DECLARING class's type // parameters, which are different symbols from cType's. The // body is lowered under the same context, so the signature must // substitute with it too or the two disagree about what T is. methodTypeNode = substituteTypeParamsInClassContext(this.pass.wasm, cType, methodTypeNode); if (methodTypeArgs != null && methodTypeNode is FunctionType) { let fType = methodTypeNode; let {typeParameters} = fType; if (typeParameters != null) { methodTypeNode = substituteTypeParamsInCodegen(this.pass.wasm, typeParameters, methodTypeArgs, methodTypeNode as Type); } } } if (methodTypeNode != null) { // A registration's signature is plumbing, not evidence: the // member may never be reached, and a reached body records its // own evidence when it is walked. Without the suppression, a // registered-but-unreached `slice(range)` kept four Range // structs in a module whose only code is an index loop. let savedSuppress = this.pass.suppressNameEvidence; this.pass.suppressNameEvidence = true; this.pass.typeLowerer.discoverSignatureType(methodTypeNode, model); this.pass.suppressNameEvidence = savedSuppress; } let params = new Array(); let returns = new Array(); let isCtor = isConstructorMethodName(methName); let rootClass = if (isCtor || isStatic) cType else getMemberRootClass(cType, methName); if (!isStatic) { // Constructors take no receiver: a non-extension constructor is a // FACTORY — it computes field values, allocates with one // struct.new, and returns the instance (non-nullable-refs.md, // Construction protocol). Extension constructors already had this // shape, returning the underlying value. if (!isCtor) { if (cType.isExtension && cType.onType != null) { params.push(typeToValType(this.pass.wasm, cType.onType as Type)); } else { // The receiver is the declaring class's struct, non-null: // `this` is never null, and an override shares the slot's // signature by taking the same root receiver, so nullability // plays no part in dispatch. if (let (true, rootInfo) = this.pass.wasm.classInfos.get(getClassKey(rootClass))) { params.push(new ValTypeRef(rootInfo.structType)); } else { params.push(new ValTypeStructRef()); } } } } if (methodTypeNode is FunctionType) { // An `operator ==` below its slot's owner declares its parameter // over its own class, but shares the slot: it takes the owner's // parameter, and its body tests and casts `other` before running // (equality.md, "Overrides compare the same class"). var paramTypes = methodTypeNode.parameters; if (methName == "==" && !isStatic && !isCtor && !cType.isExtension && rootClass !== cType && rootClass.members.has("==")) { let rootMi = rootClass.members["=="]; if (rootMi is MethodInfo && rootMi.type is FunctionType && (rootMi.type as FunctionType).parameters.length == paramTypes.length) { paramTypes = (rootMi.type as FunctionType).parameters; } } for (let p in paramTypes) { mapParamTypeToWasmParams(this.pass.wasm, p, params); } if (!isCtor) { mapReturnTypeToWasmResults(this.pass.wasm, methodTypeNode.returnType, returns); } else if (cType.isExtension && cType.onType != null) { returns.push(typeToValType(this.pass.wasm, cType.onType as Type)); } else { this.#pushCtorReturn(cType, returns); } } else if (!isCtor) { returns.push(new ValTypeI32()); } else if (cType.isExtension && cType.onType != null) { returns.push(typeToValType(this.pass.wasm, cType.onType as Type)); } else { this.#pushCtorReturn(cType, returns); } let sig = this.pass.wasm.getSignature(params, returns); let wasmFunc = new WasmFunction(sig, methodNode, model); if (origMethodFt != null && origMethodFt.typeParameters != null) { wasmFunc.typeParameters = origMethodFt.typeParameters; wasmFunc.typeArguments = methodTypeArgs; } var decs: GrowableArray | null = null; if (methodNode != null) { if (methodNode is MethodDefinition) { decs = methodNode.decorators; } else if (methodNode is AccessorDeclaration) { decs = methodNode.decorators; } else if (methodNode is FieldDefinition) { decs = methodNode.decorators; } } else if (backingFieldName != null && cDecl != null) { if (cDecl is ClassDeclaration) { for (let ms in cDecl.body) { if (ms is FieldDefinition) { let fName = memberKeyOf(model, ms.name as Node); if (fName == backingFieldName) { decs = ms.decorators; } } } } } if (decs != null) { for (let dec in decs) { if (dec.name == "intrinsic" && dec.args.length == 1) { wasmFunc.intrinsic = decoratorStringArg(dec, 0); } } } wasmFunc.isStatic = isStatic; let cName = getClassKey(cType) as String; wasmFunc.name = `${cName}.${realMethName}`; wasmFunc.methodName = realMethName; wasmFunc.classDecl = cDecl; wasmFunc.classType = cType; if (let (true, cInfo) = this.pass.wasm.classInfos.get(getClassKey(cType))) { wasmFunc.structType = cInfo.structType; } if (isSynthesizedGetter && backingFieldName != null) { let st = wasmFunc.structType; if (st != null) { var idx = -1; let lookupBackingName = if (backingFieldName.length > 0 && backingFieldName.sliceBytes(0, 1) == "#") { getClassPrivateFieldKey(getClassKey(cType), backingFieldName) } else { backingFieldName }; for (var fi = 0; fi < st.fields.length; fi += 1) { if (st.fields[fi].name == lookupBackingName) { idx = fi; } } wasmFunc.getterStruct = st; wasmFunc.getterFieldIndex = idx; } } else if (isSynthesizedSetter && backingFieldName != null) { let st = wasmFunc.structType; if (st != null) { var idx = -1; let lookupBackingName = if (backingFieldName.length > 0 && backingFieldName.sliceBytes(0, 1) == "#") { getClassPrivateFieldKey(getClassKey(cType), backingFieldName) } else { backingFieldName }; for (var fi = 0; fi < st.fields.length; fi += 1) { if (st.fields[fi].name == lookupBackingName) { idx = fi; } } wasmFunc.setterStruct = st; wasmFunc.setterFieldIndex = idx; } } let typeParameters = if (cType != null) cType.typeParameters else null; let isGenericTemplate = cType != null && typeParameters != null && typeParameters.length > 0 && (cType.typeArguments == null || !isConcrete(cType)); let registeredKey = getClassMethodKey(getClassKey(cType), realMethName); let methodMap = this.pass.wasm.methodMap(isStatic); if (methodMap.has(registeredKey)) { let func = methodMap[registeredKey]; if (func.node == null && methodNode != null) { func.node = methodNode; } if (func.classDecl == null && cDecl != null) { func.classDecl = cDecl; } // Registration is NOT reaching (binary-size.md §3a). The old // force-reach here — every registered method of an instantiated // class — was what the class vtable's all-methods slot list // required; with slots pruned to dispatchable methods, reaching // comes from the member referrers that name a method, and from // Pass 1.5 for the methods that genuinely hold slots. // CONSTRUCTORS keep it: they are never vtable-dispatched, and an // instantiated class's ctor must exist for its `new` sites // (instantiateClassType promotes ctors registered BEFORE // instantiation; this covers ones registered after). So do // MIXIN-SCOPED private members ("Scope::#name"): a mixin body // names them lexically, and no referrer machinery names them by // key, so nothing else reaches them. Lowering no longer falls // back to a host's same-named member when the registration is // missing — it bails — so dropping this force-reach would be a // loud compile failure rather than a silent wrong answer, but it // would still be a failure. let hasInst = this.pass.instantiatedSpecializedClasses.has(getClassKey(cType) as String); if (!isGenericTemplate && hasInst && isConstructorMethodName(realMethName) && this.pass.ctorDemandedGenerics.has(((cType.genericSource ?? cType)).symbolId)) { if (!this.pass.reachedFunctionsSet.has(func)) { this.#reachRegisteredMethod(func); } } return func; } let hasInstNew = this.pass.instantiatedSpecializedClasses.has(getClassKey(cType) as String); if (!isGenericTemplate && hasInstNew && isConstructorMethodName(realMethName) && this.pass.ctorDemandedGenerics.has(((cType.genericSource ?? cType)).symbolId)) { this.#reachRegisteredMethod(wasmFunc); } methodMap[registeredKey] = wasmFunc; let cKey = getClassKey(cType) as String; if (!this.pass.wasm.classMethods.has(cKey)) { this.pass.wasm.classMethods[cKey] = new Array(); } this.pass.wasm.classMethods[cKey].push(wasmFunc); return wasmFunc; } /** * Force-reach a method a registration decided must exist (the class * is instantiated or an extension, so its vtable references the * function and it WILL be emitted). markFunctionReached is a no-op * when the ambient phase flag says "checkable", but registration * added the function to wasm.functions unconditionally — leaving an * emitted body whose dependencies were never traversed. Whether the * flag happened to be true here depended on which referrer processed * last, so the miss was graph-order dependent (String.split lowering * without its FixedArray extension constructor registered, * in wit-parser's graph but not others). */ #reachRegisteredMethod(func: WasmFunction): void { this.pass.wasm.addFunction(func); this.pass.forceReachFunction(func); if (func.methodName != null && isConstructorMethodName(func.methodName as String) && func.classType != null) { this.#reachSuperConstructors(func); } } /** * A constructor drags its super chain's constructors with it: a * `: super(...)` lowers to a DIRECT call of the superclass's ctor, * resolved through `classMethodMap` — which `layout()` rebuilds from * REACHED functions only, so a super ctor that was merely registered * is gone by lowering (`zir unsupported: super constructor not * found`). * * This used to hold by accident: every class a subclass could name * was instantiated, so every super ctor was promoted on its own. * Instantiating on evidence broke the tie for the one shape where * the two halves disagree — a subclass whose class is instantiated * extending one whose class is not. * * Pending keys rather than direct reaches: the super's ctor may not * be registered yet when the subclass's is, and the settle drain * resolves by key after registration has finished. */ #reachSuperConstructors(func: WasmFunction): void { if (func.classType == null) { return; } let ct = func.classType as ClassType; var curr = ct.superType; var currentFunc: WasmFunction | null = func; while (curr != null) { let superCt = curr; if (superCt.isMixinIntermediate) { curr = superCt.superType; continue; } var superCtorMeth = ""; if (currentFunc != null && currentFunc.node is MethodDefinition) { let md = currentFunc.node as MethodDefinition; if (md.superInitializer != null) { let si = md.superInitializer as SuperInitializer; if (si.constructorName != null) { superCtorMeth = "." + getNodeMemberName(currentFunc.model, si.constructorName as Node); } } } let superKey = getClassMethodKey(getClassKey(superCt), superCtorMeth); this.pass.notePendingMemberReach(superKey); if (let (true, nextFunc) = this.pass.wasm.classMethodMap.get(superKey)) { currentFunc = nextFunc; } else { currentFunc = null; } curr = superCt.superType; } } /** * The name a written accessor registers under on its host. A decorator's * subject accessor is written against the placeholder name and registered * under the decorated field's name (ClassType.decoratorSubjectName on the * application's intermediate class); every other accessor keeps its own. */ #registeredAccessorName(accName: String, declaringType: ClassType | null): String { if (declaringType != null && declaringType.decoratorSubjectName != null && (declaringType.decoratorSubjectName as String) == accName) { return declaringType.decoratorFieldName as String; } return accName; } /** * The scope key a member body's private names register and resolve * under: the declaring intermediate's key, except a decorator's * `shared` method, which lives under the declaration's shared key so * every application in the class calls the one copy. */ #memberScopeOf(ms: MethodDefinition, msScope: String, declaringType: ClassType | null): String { if (ms.isShared && declaringType != null && declaringType.decoratorSharedScopeKey != null) { return declaringType.decoratorSharedScopeKey as String; } return msScope; } /** * Whether `fieldName` is a decorated field of `ct`'s own body. Such a * field has no storage and no synthesized accessors of its own: the * decorator's accessor is registered under its name instead. */ #isDecoratedField(ct: ClassType, fieldName: String): boolean { let decorated = ct.decoratedFields; return decorated != null && decorated.has(fieldName); } populateClassStructAndMethods(ct: ClassType, cd: Node | null, sourceModel: SemanticModel): void { let cKey = getClassKey(ct); if (!this.pass.wasm.classInfos.has(cKey)) { this.registerSpecializedClass(ct, cd, sourceModel); } let ctVtable = this.pass.wasm.classVtable(cKey); var vstOpt: WasmStruct | null = null; var stOpt: WasmStruct | null = null; if (let (true, info) = this.pass.wasm.classInfos.get(cKey)) { stOpt = info.structType; vstOpt = info.vtableStructType; } if (stOpt == null || vstOpt == null) { throw new Error("Class struct or vtable struct not found for class: " + ct.name); } let st = stOpt; let vst = vstOpt; if (st.fields.length > 0) { return; } let vtableSet = new Set(); for (let existing in ctVtable) { vtableSet.add(existing); } let {superType} = ct; if (superType != null) { let superCt = superType; let superLookupId = (superCt.genericSource ?? superCt).symbolId; let superDecl: Node | null = if (this.pass.classDecls.has(superLookupId)) this.pass.classDecls[superLookupId] else null; let superModel = this.pass.getClassModel(superCt); this.populateClassStructAndMethods(superCt, superDecl, superModel); let superVtable = this.pass.wasm.classVtable(getClassKey(superCt)); for (let methName in superVtable) { if (!vtableSet.has(methName)) { ctVtable.push(methName); vtableSet.add(methName); } } } if (ct.derivesEquality) { if (!ct.members.has("==")) { let eqParams = growable([ct]); let eqNames = growable(["other"]); ct.members["=="] = new MethodInfo(new FunctionType(eqParams, new BooleanType(), new FunctionDeclInfo(eqNames)), false, false, false, false); } if (!vtableSet.has("==")) { ctVtable.push("=="); vtableSet.add("=="); } if (!ct.members.has("hashCode")) { ct.members["hashCode"] = new MethodInfo(new FunctionType(new Array(), new I32Type()), false, false, false, false); } if (!vtableSet.has("hashCode")) { ctVtable.push("hashCode"); vtableSet.add("hashCode"); } } // A mixin application's intermediate class gets no methods of its own, // with or without a superclass: each class that applies the mixin // compiles its own copies (the mixin chain walk below), so a mixin // body's `this` is always a class that implements the mixin's `on` // interfaces. let cdDecl = if (cd is ClassDeclaration) cd else null; let isErasedCt = containsErasedType(ct as Type); if (cdDecl != null && !isErasedCt) { let allMembers = new Array(); let allScopes = new Array(); let allModels = new Array(); let allDecls = new Array(); let allDeclaringTypes = new Array(); if (cdDecl != null) { var mixinSup = ct.superType; let mixinChain = new Array(); while (mixinSup != null && mixinSup.isMixinIntermediate) { mixinChain.push(mixinSup); mixinSup = mixinSup.superType; } var mci = mixinChain.length - 1; while (mci >= 0) { let mSup = mixinChain[mci]; let mLookupId = (mSup.genericSource ?? mSup).symbolId; if (this.pass.classDecls.has(mLookupId)) { let mDecl = this.pass.classDecls[mLookupId]; if (mDecl is MixinDeclaration) { for (let composed in mSup.mixins) { let compLookupId = (composed.genericSource ?? composed).symbolId; if (this.pass.classDecls.has(compLookupId)) { let cDecl = this.pass.classDecls[compLookupId]; if (cDecl is MixinDeclaration) { let compModel = if (this.pass.classModels.has(compLookupId)) this.pass.classModels[compLookupId] else sourceModel; for (let ms in (cDecl as MixinDeclaration).body) { allMembers.push(ms); allScopes.push(composed.privateScopeKey ?? ""); allModels.push(compModel); allDecls.push(cDecl); allDeclaringTypes.push(mSup); } } } } let mModel = if (this.pass.classModels.has(mLookupId)) this.pass.classModels[mLookupId] else sourceModel; for (let ms in (mDecl as MixinDeclaration).body) { allMembers.push(ms); allScopes.push(mSup.privateScopeKey ?? ""); allModels.push(mModel); allDecls.push(mDecl); allDeclaringTypes.push(mSup); } } } mci -= 1; } for (let ms in cdDecl.body) { allMembers.push(ms); allScopes.push(""); allModels.push(sourceModel); allDecls.push(cdDecl); allDeclaringTypes.push(null); } } var vtableMethIdx = 0; while (vtableMethIdx < allMembers.length) { let ms = allMembers[vtableMethIdx]; let msScope = allScopes[vtableMethIdx]; let msIdx = vtableMethIdx; vtableMethIdx += 1; if (ms is MethodDefinition) { let {typeParameters} = ms; if (typeParameters != null && typeParameters.length > 0) { continue; } let methName = memberKeyOf(sourceModel, ms.name as Node); if (methName != "") { var vtableMethName = methName; let msMembers = ct.memberTable(ms.isStatic); if (msMembers.has(methName)) { let mInfo = msMembers[methName]; if (mInfo.type is FunctionType) { let ft = mInfo.type as FunctionType; let specificType = matchOverload(allModels[msIdx], ft, ms); if (specificType != null) { vtableMethName = methName + getSignatureKey(specificType); } } } // Privates: no vtable slot (never virtual); mixin // privates register under the mixin's scope key. let isPrivateMeth = methName.length > 0 && methName.sliceBytes(0, 1) == "#"; // See above: a generic method has no single body to hold. let isGenericMeth = ms.typeParameters != null && (ms.typeParameters as GrowableArray).length > 0; if (!ms.isStatic && !vtableSet.has(vtableMethName) && !ms.isConstructor && methName != "" && !isPrivateMeth && !isGenericMeth && !ct.isExtension) { ctVtable.push(vtableMethName); vtableSet.add(vtableMethName); } // An abstract method has a slot, so a call through this // class dispatches to the subclass's override, and no body: // the slot is filled with a stub until a subclass's // implementation replaces it. if (ms.isAbstract) { continue; } let declNode = allDecls[msIdx]; let memberScope = this.#memberScopeOf(ms, msScope, allDeclaringTypes[msIdx]); let regName = if (ms.isConstructor) { if (methName == "") "" else "." + methName } else if (memberScope != "" && methName.length > 0 && methName.sliceBytes(0, 1) == "#") { `${memberScope}::${methName}` } else { methName }; let regFn = this.registerClassMethod(ct, declNode, regName, ms as Node, false, false, null, allModels[msIdx]); regFn.declaringType = allDeclaringTypes[msIdx]; applyMixinPrivateScope(regFn, ms as Node, memberScope); } } else if (ms is AccessorDeclaration) { let declNode = allDecls[msIdx]; let accName = this.#registeredAccessorName( memberKeyOf(sourceModel, ms.name as Node), allDeclaringTypes[msIdx]); let isPrivateAcc = accName.length > 0 && accName.sliceBytes(0, 1) == "#"; if (ms.getter != null) { var getterRegName = "get#" + accName; if (isPrivateAcc && msScope != "") { getterRegName = `${msScope}::${getterRegName}`; } let regG = this.registerClassMethod(ct, declNode, getterRegName, ms as Node, false, false, null, allModels[msIdx]); regG.declaringType = allDeclaringTypes[msIdx]; applyMixinPrivateScope(regG, ms as Node, msScope); } let {setter} = ms; if (setter != null) { var setterRegName = "set#" + accName; if (isPrivateAcc && msScope != "") { setterRegName = `${msScope}::${setterRegName}`; } let regS = this.registerClassMethod(ct, declNode, setterRegName, setter, false, false, null, allModels[msIdx]); regS.declaringType = allDeclaringTypes[msIdx]; applyMixinPrivateScope(regS, setter, msScope); } } else if (ms is FieldDefinition) { if (ms.isStatic) { continue; } let declNode = allDecls[msIdx]; let fieldName = memberKeyOf(sourceModel, ms.name as Node); if (fieldName != "" && !this.#isDecoratedField(ct, fieldName)) { if (!fieldName.startsWith("#")) { let getterName = "get#" + fieldName; if (!vtableSet.has(getterName) && !ct.isExtension) { ctVtable.push(getterName); vtableSet.add(getterName); } this.registerClassMethod(ct, declNode, getterName, null, true, false, fieldName, allModels[msIdx]); if (ms.mutability != null && ms.mutability == "var") { let setterName = "set#" + fieldName; if (!vtableSet.has(setterName) && !ct.isExtension) { ctVtable.push(setterName); vtableSet.add(setterName); } this.registerClassMethod(ct, declNode, setterName, null, false, true, fieldName, allModels[msIdx]); } } else { if (ms.setterName != null) { let getterName = "get#" + fieldName; if (!vtableSet.has(getterName) && !ct.isExtension) { ctVtable.push(getterName); vtableSet.add(getterName); } this.registerClassMethod(ct, declNode, getterName, null, true, false, fieldName, allModels[msIdx]); } if (ms.isAbstract) { let getterName = "get#" + fieldName; if (!vtableSet.has(getterName) && !ct.isExtension) { ctVtable.push(getterName); vtableSet.add(getterName); } this.registerClassMethod(ct, declNode, getterName, null, true, false, fieldName, allModels[msIdx]); if (ms.mutability != null && ms.mutability == "var") { let setterName = "set#" + fieldName; if (!vtableSet.has(setterName) && !ct.isExtension) { ctVtable.push(setterName); vtableSet.add(setterName); } this.registerClassMethod(ct, declNode, setterName, null, false, true, fieldName, allModels[msIdx]); } } if (ms.isDeclare) { let getterName = "get#" + fieldName; if (!vtableSet.has(getterName) && !ct.isExtension) { ctVtable.push(getterName); vtableSet.add(getterName); } this.registerClassMethod(ct, declNode, getterName, null, true, false, fieldName, allModels[msIdx]); } } } } } } if ((cdDecl != null || ct.isCaseClass || (cd is SealedVariant)) && !ct.isExtension && !isErasedCt && !ct.isMixinIntermediate) { if (ct.constructorType != null || ct.constructors.size == 0) { let wasmFunc = this.registerClassMethod(ct, cd, "", null, false, false, null, sourceModel); if (wasmFunc.classDecl == null) { wasmFunc.classDecl = cd; } if (wasmFunc.structType == null) { wasmFunc.structType = st; } // Re-derive the factory's return at the now-registered struct; // the first registration may have preceded it and fallen back to // structref. let returns = growable([new ValTypeRef(st)]); let sig = this.pass.wasm.getSignature( wasmFunc.signature.params, returns); wasmFunc.signature = sig; this.pass.markTypeReached(sig); } for (let entry in ct.constructors) { if (entry.key == "") { continue; } let ctorMethName = "." + entry.key; let cKey = getClassKey(ct); let ctorKey = getClassMethodKey(cKey, ctorMethName); if (let (true, ctorFn) = this.pass.wasm.classMethodMap.get(ctorKey)) { if (ctorFn.classDecl == null) { ctorFn.classDecl = cd; } if (ctorFn.structType == null) { ctorFn.structType = st; } let returns = growable([new ValTypeRef(st)]); let sig = this.pass.wasm.getSignature( ctorFn.signature.params, returns); ctorFn.signature = sig; this.pass.markTypeReached(sig); } } if (ct.derivesEquality) { let eqFunc = this.registerClassMethod(ct, cd, "==", null, false, false, null, sourceModel); eqFunc.isCaseClassEq = true; let hashFunc = this.registerClassMethod(ct, cd, "hashCode", null, false, false, null, sourceModel); hashFunc.isCaseClassHash = true; } if (synthesizedRelease(ct)) { let dFunc = this.registerClassMethod(ct, cd, releaseMemberOf(ct), null, false, false, null, sourceModel); dFunc.isSyntheticRelease = true; } } if (vst.fields.length == 0) { // Every slot name is laid out here, and the ones nothing // dispatches through are dropped from the whole hierarchy once // reachability settles (ReachabilityAnalysis.#pruneUndispatchedSlots). // Deciding per class at this point would be too early: layout runs // partway through the walk, before most call sites are seen. for (let methName in ctVtable) { vst.fields.push(new WasmField(methName, new ValTypeFuncRef(), false)); } } let fields = new Array(); var hasPhysicalSuper = false; if (ct.superType != null) { let superCt = ct.superType as ClassType; if (!superCt.isExtension) { hasPhysicalSuper = true; let superKey = getClassKey(superCt); if (let (true, superInfo) = this.pass.wasm.classInfos.get(superKey)) { let superSt = superInfo.structType; for (let f in superSt.fields) { fields.push(f); } } } } if (!hasPhysicalSuper) { var rootVst = vst; while (rootVst.superStruct != null) { rootVst = rootVst.superStruct as WasmStruct; } // Immutable: the constructor passes it to struct.new and nothing // writes it after, and an immutable field may refine its type in // a subtype, which is what lets a root struct extend `Object` // (ReachabilityAnalysis's #layoutTypeTests). fields.push(new WasmField("", new ValTypeRefNull(rootVst), false)); } let ctParams = getClassTypeParameters(ct); for (let pair in ct.members) { if (pair.value is MethodInfo) { continue; } if (pair.value.isAbstract) { continue; } if (pair.value is FieldInfo && (pair.value as FieldInfo).isStatic) { continue; } var isInherited = false; if (ct.superType != null) { let superKey = getClassKey(ct.superType as ClassType); if (let (true, superInfo) = this.pass.wasm.classInfos.get(superKey)) { let superSt = superInfo.structType; for (let sf in superSt.fields) { if (sf.name == pair.key) { isInherited = true; } } } } if (!isInherited) { let fName = if (pair.key.contains("::#")) { // Mixin private fields arrive pre-scoped from the checker // ("::#name") — the member key IS the field // name, shared by every application of the mixin. pair.key } else if (pair.key.length > 0 && pair.key.sliceBytes(0, 1) == "#") { getClassPrivateFieldKey(cKey, pair.key) } else { pair.key }; let resolvedType = substituteTypeParamsInCodegen(this.pass.wasm, ctParams, ct.typeArguments, pair.value.type); let valType = typeToValType(this.pass.wasm, resolvedType); if (valType is ValTypeVoid) { // A zero-width field (`Box.value`) holds nothing, so it // gets no storage. Reads of it lower to no value and writes // to it lower to just their right-hand side's effects. continue; } // Precise field types (non-nullable-refs.md): `T` stays // `(ref $T)` and only `T | null` is nullable, and `let` fields // are immutable — single-shot construction supplies every // field's value to struct.new, so nothing needs the // defaultable/mutable widening anymore. let fieldIsMutable = if (pair.value is FieldInfo) { (pair.value as FieldInfo).isMutable } else { true }; let wf = new WasmField(fName, valType, fieldIsMutable); // `structref` for a class-typed field means the class had no // registration yet — discovery may still produce one, and then // its method signatures would be precise while this field is // erased. Remember the bake so it can be re-resolved once // discovery settles. if (valType is ValTypeStructRef && resolvedType is ClassType) { this.#erasedFieldBakes.push(new ErasedFieldBake(wf, resolvedType)); } fields.push(wf); } } for (let f in fields) { st.fields.push(f); } } /** * The factory's return type: the instance at its precise struct * type. A registration that precedes the struct falls back to * structref; the constructor patch-up in populateClassStructAndMethods * re-derives the signature once the struct exists — the same * two-step the receiver parameter used. */ #pushCtorReturn(cType: ClassType, returns: GrowableArray): void { if (let (true, cInfo) = this.pass.wasm.classInfos.get(getClassKey(cType))) { returns.push(new ValTypeRef(cInfo.structType)); } else { returns.push(new ValTypeStructRef()); } } /** * The value and body phases of superclass constructors * (non-nullable-refs.md, Construction protocol). A subclass factory * drives its ancestor chain through `` — declared * constructor params in, own field values (struct order, defaults * filled) plus the evaluated super() arguments out — and * ``, the written body run on the allocated instance. * Minted after the discovery fixpoint, when every constructor * signature and struct is final; the ancestors' ASTs were walked * when their factories were reached, so the phases introduce no new * discovery. */ mintConstructorPhases(): void { // Snapshot the reached constructors: minting appends functions. let ctors = new Array(); for (let f in this.pass.wasm.functions) { if (f.methodName != null && isConstructorMethodName(f.methodName as String) && f.classType != null && !(f.classType as ClassType).isExtension) { ctors.push(f); } } for (let f in ctors) { var currFn = f; var anc = (f.classType as ClassType).superType; while (anc != null) { let ancCt = anc; if (ancCt.isMixinIntermediate) { anc = ancCt.superType; continue; } var superCtorMeth = ''; if (currFn.node is MethodDefinition) { let md = currFn.node as MethodDefinition; if (md.superInitializer != null) { let si = md.superInitializer as SuperInitializer; if (si.constructorName != null) { superCtorMeth = '.' + getNodeMemberName(currFn.model, si.constructorName as Node); } } } let factoryKey = getClassMethodKey(getClassKey(ancCt), superCtorMeth); if (let (true, ancFactory) = this.pass.wasm.classMethodMap.get(factoryKey)) { this.#mintPhasesFor(ancCt, ancFactory); currFn = ancFactory; } anc = ancCt.superType; } } } #mintPhasesFor(cType: ClassType, factory: WasmFunction): void { let cKey = getClassKey(cType); let fMeth = factory.methodName as String; let suffix = if (fMeth == '') "" else fMeth.sliceBytes(14, fMeth.length); let initMethName = if (suffix == "") '' else '.' + suffix; let bodyMethName = if (suffix == "") '' else '.' + suffix; let initKey = getClassMethodKey(cKey, initMethName); if (this.pass.wasm.classMethodMap.has(initKey)) { return; } let st = factory.structType; if (st == null) { throw new Error('constructor phases without a struct: ' + (cKey as String)); } let structType = st; // Own fields start after the inherited prefix; a root class's // field 0 is the synthetic . var ownStart = 1; var s = structType.superStruct; while (s != null) { let curr = s; if (curr.classType != null && (curr.classType as ClassType).isMixinIntermediate) { s = curr.superStruct; continue; } ownStart = curr.fields.length; break; } let initReturns = new Array(); var fi = ownStart; while (fi < structType.fields.length) { initReturns.push(structType.fields[fi].type); fi += 1; } var superCt = cType.superType; while (superCt != null && (superCt as ClassType).isMixinIntermediate) { superCt = (superCt as ClassType).superType; } if (superCt != null) { var superCtorMeth = ''; if (factory.node is MethodDefinition) { let md = factory.node as MethodDefinition; if (md.superInitializer != null) { let si = md.superInitializer as SuperInitializer; if (si.constructorName != null) { superCtorMeth = '.' + getNodeMemberName(factory.model, si.constructorName as Node); } } } let superKey = getClassMethodKey( getClassKey(superCt as ClassType), superCtorMeth); if (let (true, superFactory) = this.pass.wasm.classMethodMap.get(superKey)) { for (let p in superFactory.signature.params) { initReturns.push(p); } } } let initSig = this.pass.wasm.getSignature( factory.signature.params, initReturns); let initFn = new WasmFunction(initSig, factory.node, factory.model); initFn.name = `${cKey as String}.${initMethName}`; initFn.methodName = initMethName; initFn.classType = cType; initFn.classDecl = factory.classDecl; initFn.structType = structType; this.pass.wasm.classMethodMap[initKey] = initFn; this.pass.wasm.addFunction(initFn); this.pass.markFunctionReached(initFn); if (ctorHasRunnableBody(factory)) { let bodyParams = growable([new ValTypeRef(structType)]); for (let p in factory.signature.params) { bodyParams.push(p); } let bodySig = this.pass.wasm.getSignature( bodyParams, new Array()); let bodyFn = new WasmFunction(bodySig, factory.node, factory.model); bodyFn.name = `${cKey as String}.${bodyMethName}`; bodyFn.methodName = bodyMethName; bodyFn.classType = cType; bodyFn.classDecl = factory.classDecl; bodyFn.structType = structType; this.pass.wasm.classMethodMap[getClassMethodKey(cKey, bodyMethName)] = bodyFn; this.pass.wasm.addFunction(bodyFn); this.pass.markFunctionReached(bodyFn); } } instantiateInterfaceConstructor(it: InterfaceType, ctorName: String, methodNode: Node, model: SemanticModel): WasmFunction { let source = it.genericSource ?? it; let targsOpt = it.typeArguments; let typeArgs = if (targsOpt != null) targsOpt else new Array(); let baseName = getInterfaceConstructorBaseName(it, ctorName); let specKey = getSpecializedFunctionKey(baseName, typeArgs); if (let (true, existing) = this.pass.wasm.specializedFunctions.get(specKey)) { this.pass.markFunctionReached(existing); return existing; } // The factory returns the interface value: its fat-pointer struct // must exist before the signature is built. this.registerSpecializedInterface(it, this.pass.interfaceDecls[source.symbolId], model); // The constructor's checked type is written at the interface's own // type parameters (registerInterfaceConstructor); substitute the // instantiation's arguments into the signature, as // instantiateGenericFunction does for a generic function. // The constructor's own parameters: the interface's, or a restatement // of them with bounds (checker: registerInterfaceConstructor). let ft = model.getNodeType(methodNode) as FunctionType; let typeParams = ft.typeParameters; let concreteParams = new Array(); let concreteReturns = new Array(); // The substituted types must be discovered before they are mapped: // a class the program has not instantiated yet maps to a bare // structref, and the signature would keep it. A global whose // initializer is the first `new Array()` reaches here from the // queue walk before anything has instantiated GrowableArray. let typeLowerer = this.pass.typeLowerer; for (let p in ft.parameters) { let subType = if (typeParams != null) { substituteTypeParamsInCodegen(this.pass.wasm, typeParams, typeArgs, p) } else { p }; typeLowerer.discoverType(subType, model); mapParamTypeToWasmParams(this.pass.wasm, subType, concreteParams); } let subReturn = if (typeParams != null) { substituteTypeParamsInCodegen(this.pass.wasm, typeParams, typeArgs, ft.returnType) } else { ft.returnType }; typeLowerer.discoverType(subReturn, model); mapReturnTypeToWasmResults(this.pass.wasm, subReturn, concreteReturns); let sig = this.pass.wasm.getSignature(concreteParams, concreteReturns); let wasmFunc = new WasmFunction(sig, methodNode, model); if (typeParams != null) { wasmFunc.typeParameters = typeParams; wasmFunc.typeArguments = typeArgs; } wasmFunc.name = getSpecializedName(baseName, typeArgs); this.pass.wasm.specializedFunctions[specKey] = wasmFunc; this.pass.wasm.addFunction(wasmFunc); // markFunctionReached queues a node referrer for the body with // this specialization's type arguments (see instantiateGenericFunction // for why these entries are needed first). this.pass.nodeIdToNode[methodNode.id as i32] = methodNode; this.pass.nodeIdToModel[methodNode.id as i32] = model; this.pass.markFunctionReached(wasmFunc); return wasmFunc; } instantiateGenericFunction(symId: SymbolId, typeArgs: Array): WasmFunction { let funcExpr = this.pass.wasm.genericFunctions[symId]; let model = this.pass.wasm.genericFunctionModels[symId]; // The signature below is read off the arrow's checked type, which // a module whose bodies waited to be reached has not written yet. let deferred = model.deferredBodies; if (deferred != null) { deferred.checkGlobalBody(symId); } // Determine target name var originalName = ""; let parentNode = model.getParent(funcExpr); if (parentNode is VariableDeclaration) { if (parentNode.pattern is IdentifierPattern) { originalName = (parentNode.pattern as IdentifierPattern).name; } } else if (parentNode is FunctionDeclaration) { originalName = parentNode.name.name; } if (originalName == "") { originalName = "generic_func"; } let specKey = getSpecializedFunctionKey(originalName, typeArgs); let specName = getSpecializedName(originalName, typeArgs); if (this.pass.wasm.specializedFunctions.has(specKey)) { let func = this.pass.wasm.specializedFunctions[specKey]; this.pass.markFunctionReached(func); return func; } // Resolve the original generic FunctionType let funcTypeNode = model.getNodeType(funcExpr) as FunctionType; let typeParams = funcTypeNode.typeParameters; // Substitute typeParams with typeArgs in the function signature let concreteParams = new Array(); let concreteReturns = new Array(); for (let p in funcTypeNode.parameters) { let subType = substituteTypeParamsInCodegen(this.pass.wasm, typeParams, typeArgs, p); mapParamTypeToWasmParams(this.pass.wasm, subType, concreteParams); } let subReturn = substituteTypeParamsInCodegen(this.pass.wasm, typeParams, typeArgs, funcTypeNode.returnType); mapReturnTypeToWasmResults(this.pass.wasm, subReturn, concreteReturns); let sig = this.pass.wasm.getSignature(concreteParams, concreteReturns); let wasmFunc = new WasmFunction(sig, funcExpr, model); // Track type parameters and arguments for codegen context wasmFunc.typeParameters = typeParams; wasmFunc.typeArguments = typeArgs; wasmFunc.name = specName; // Register it this.pass.wasm.specializedFunctions[specKey] = wasmFunc; this.pass.wasm.addFunction(wasmFunc); // markFunctionReached queues a node referrer for the body with // this specialization's type arguments; without these entries the // referrer finds no node and the per-specialization traversal is // silently skipped, so classes the body constructs never // instantiate under the substituted type arguments. this.pass.nodeIdToNode[(funcExpr as Node).id as i32] = funcExpr; this.pass.nodeIdToModel[(funcExpr as Node).id as i32] = model; this.pass.markFunctionReached(wasmFunc); // A module-level function's checker-recorded dependencies live on // its SYMBOL, which the node referrer above never consults. Without // this substituted traversal, generic functions this body calls // only specialize during emission, after type layout is frozen. if (let (true, deps) = model.symbolDependencies.get(symId)) { this.pass.traverseDependencies(deps, model, null, typeArgs, funcExpr); } return wasmFunc; } instantiateGenericMethod(ct: ClassType, cd: Node | null, methName: String, methodNode: Node, typeArgs: Array, model: SemanticModel): WasmFunction { let specKey = getSpecializedName(methName, typeArgs); let registeredKey = getClassMethodKey(getClassKey(ct), specKey); let isStatic = methodNode is MethodDefinition && methodNode.isStatic; let methodMap = this.pass.wasm.methodMap(isStatic); if (methodMap.has(registeredKey)) { return methodMap[registeredKey]; } return this.registerClassMethod(ct, cd, specKey, methodNode, false, false, null, model, typeArgs); } } function getNodeMemberName(model: SemanticModel, node: Node): String { return memberKeyOf(model, node as Node); } function isConstructorMethodName(name: String): boolean { return name == "" || (name.length > 14 && name.startsWith(".")); } function getMethodName(model: SemanticModel, md: MethodDefinition) { return memberKeyOf(model, md.name as Node); } /** * Whether a constructor has body statements to run post-allocation. * Synthesized constructors (node-less) never do; a written `new(...);` * or an empty block has nothing to run either, unless the constructor * has postconditions, which run after the body in that phase. */ function ctorHasRunnableBody(factory: WasmFunction): boolean { if (!(factory.node is MethodDefinition)) { return false; } let md = factory.node as MethodDefinition; if (hasEnsuresClause(md.contracts)) { return true; } let b = md.body; if (b == null) { return false; } if (b is BlockStatement) { return b.body.length > 0; } return true; }