/** * Semantic Model for the Zena compiler. * * The SemanticModel is a single query surface for all semantic * information about a module. It combines: * * 1. Node types — the inferred type for any AST node (expression, * declaration pattern, parameter, etc.). * 2. Binding types — the type carried by a named binding, keyed by * Symbol.id so each destructured name gets its own entry. * 3. Name resolution — delegates to the ReferenceMap from scope * analysis to find the Symbol for any identifier reference. * 4. Diagnostics collected during type checking. * * Two kinds of "type" live here, both accessible via getNodeType(): * * - **Binding type**: Stored on a declaration node (IdentifierPattern, * Parameter, ClassDeclaration). This is the type the name carries — * either from an explicit annotation or inferred from the initializer. * Query: `getNodeType(symbolInfo.declaration)`. * * - **Expression type**: Stored on an expression node (NumberLiteral, * BinaryExpression, Identifier, etc.). This is the fully resolved * type at that use site, including control-flow narrowing. * Query: `getNodeType(someExpr)`. * * These share the same map keyed by source offset, since declaration * nodes and expression nodes have disjoint offsets. There is no separate * "declared vs inferred" API — the AST's TypeAnnotation tells you * whether the type was explicit; the SemanticModel just gives you the * resolved result. * * A future global analysis pass (e.g., monomorphization) would produce * its own result, not overwrite this model. No third type level is * needed for single-module checking. */ import { Set, HashMap, HashSet } from 'zena:collections'; import { IterableUtils } from 'zena:core'; import { Type, ClassType, InterfaceType, FunctionType, RecordType, TupleType, UnionType, TypeId, } from './types.zena'; import { Diagnostic } from './diagnostics.zena'; import { Node, NodeId, Expression, ClassDeclaration, InterfaceDeclaration, MixinDeclaration, EnumDeclaration, IdGenerator, syntacticMemberName, MemberExpression, getMemberPropertyName, } from './ast.zena'; import { Symbol, SymbolId } from './scope/symbol.zena'; import { SymbolMap } from './scope/scope-builder.zena'; import { NodeMap, DenseNodeMap } from './node-map.zena'; /** * The key a member is registered under: the plain name for a name-keyed * member, and for a symbol-keyed one the key the checker recorded, which * carries the symbol's identity so two same-named symbols key two * different members. * * Every pass that looks a member up goes through here. Falling back to * the spelling keeps a member whose symbol failed to resolve consistent * between passes; that failure is already reported at its declaration. */ export function memberKeyOf(model: SemanticModel, nameNode: Node): String { let recorded = model.memberKey(nameNode); if (recorded != null) { return recorded as String; } return syntacticMemberName(nameNode); } /** * The key a symbol-keyed ACCESS looks its member up by. * * The checker records it on the access node, because `x.[Reader.act]()` * and `x.[Writer.act]()` differ only in the symbol the path resolves to * and nothing downstream can resolve one. A name-keyed access is its * property name, as it has always been. */ export function accessKeyOf(model: SemanticModel, expr: MemberExpression): String { let recorded = model.memberKey(expr as Node); if (recorded != null) { return recorded as String; } return getMemberPropertyName(expr.isSymbolAccess, expr.property.name); } export type SemanticModelProgramUnit = { path: String, model: SemanticModel, }; /** * Which model owns each node and each binding. * * A model answers questions about its own file; a query about a node * from another file — cross-module inlining, a generic instantiated * from elsewhere — needs to find the model that owns it, and this is * that map. * * It belongs to the *check*, not to a compile. Every `Program` built * over the same `CheckResult`s would compute exactly the same index, * so building it per compile made each compile walk every node in the * program (which the execution suite then paid 465 times over), and * left `Program` writing a back-pointer into `SemanticModel`s it * shares with every other compile in the batch. `SharedCheckerState` * holds one of these for exactly as long as the models it indexes * live, and a model is registered once, when its check finishes. */ /** One registered model and the node-id range its module was parsed into. */ final class ModelRange { first: i32; last: i32; model: SemanticModel; /** * Whether `model` still speaks for its file. `register` clears it * when the file gets a newer model with a different range, so a * lookup that lands here need not consult `currentByPath`. */ var current = true; new(this.first, this.last, this.model); } export final class ModelIndex { /** * Which model owns a node, by range. A module's nodes are the * contiguous ids `[Module.id, Module.lastNodeId]`, so the whole * index for a parsed node is one entry per module and a binary * search — where it used to be one map entry per node, 561K of them * at ~37 bytes for a large compile (issue #199). Kept sorted by * `first`; a re-registration of the same module replaces its entry. */ #ranges = new GrowableArray(); /** * Nodes minted after parsing — by the scope builder or the checker — * fall outside every module's range and are recorded one by one, as * before. A few thousand in a large compile. */ #nodeToModel = new Map(); symbolToModel = new Map(); /** How many nodes are indexed individually rather than by range. */ overflowCount: i32 { get { return this.#nodeToModel.size; } } /** How many module ranges are registered. */ rangeCount: i32 { get { return this.#ranges.length; } } /** * The model that currently speaks for each file. * * A cycle-driven re-check (`checkCompilation`'s second pass) replaces * a file's model, and the superseded one must stop answering: its * types were inferred before the back edge resolved, which is the * whole reason for the second pass. Re-registering the replacement * overwrites its claims node by node, but a node the first pass * typed and the second did not would otherwise be left pointing at * the dead model — so ownership is checked against this rather than * assumed from the map. Missing is the right answer there; a * superseded type is not. */ currentByPath = new Map(); /** The live model owning `id`, or null if nothing current owns it. */ ownerOfNode(id: NodeId): SemanticModel | null { let ranges = this.#ranges; let n = id as i32; var lo = 0; var hi = ranges.length - 1; while (lo <= hi) { let mid = lo + (((hi - lo) / 2) as i32); let range = ranges[mid]; if (n < range.first) { hi = mid - 1; } else if (n > range.last) { lo = mid + 1; } else { return if (range.current) range.model else null; } } if (let (true, m) = this.#nodeToModel.get(id)) { return this.#ifCurrent(m); } return null; } /** * Records `model` as the owner of its module's id range, in sorted * position, replacing the entry of an earlier check of the same * module. */ #addRange(model: SemanticModel): void { let first = model.firstNodeId as i32; let last = model.lastNodeId as i32; if (last < first) { return; } let ranges = this.#ranges; var i = 0; while (i < ranges.length && ranges[i].first < first) { i += 1; } if (i < ranges.length && ranges[i].first == first) { ranges[i] = new ModelRange(first, last, model); return; } ranges.push(new ModelRange(first, last, model)); var j = ranges.length - 1; while (j > i) { ranges[j] = ranges[j - 1]; j -= 1; } ranges[i] = new ModelRange(first, last, model); } /** Claims `id` for `model` unless the model's range already does. */ #claim(model: SemanticModel, id: NodeId): void { let n = id as i32; if (n >= (model.firstNodeId as i32) && n <= (model.lastNodeId as i32)) { return; } this.#nodeToModel[id] = model; } /** The live model owning the binding `id`, or null. */ ownerOfBinding(id: SymbolId): SemanticModel | null { if (let (true, m) = this.symbolToModel.get(id)) { return this.#ifCurrent(m); } return null; } #ifCurrent(m: SemanticModel): SemanticModel | null { if (let (true, current) = this.currentByPath.get(m.sourcePath)) { if (current != m) { return null; } } return m; } /** * Claims every node and binding `model` knows about, and makes it the * model for its file. Nodes are keyed by the AST, which the parse * cache keeps stable across checks, so a re-check's claims land on * the same keys and the latest check wins. */ register(model: SemanticModel): void { if (let (true, previous) = this.currentByPath.get(model.sourcePath)) { if (previous != model) { for (let range in this.#ranges) { if (range.model == previous) { range.current = false; } } } } this.currentByPath[model.sourcePath] = model; this.#addRange(model); // The range answers for every parsed node; what is left to record // is the nodes minted later, which each table holds outside its // module's range. for (let k in model.nodeTypes.overflowKeys()) { this.#claim(model, k); } for (let k in model.parents.overflowKeys()) { this.#claim(model, k); } let raKeys = model.recordAdaptations.map.keys(); for (let k in raKeys) { this.#claim(model, k); } let ruKeys = model.recordUnionAdaptations.map.keys(); for (let k in ruKeys) { this.#claim(model, k); } let iaKeys = model.interfaceAdaptations.map.keys(); for (let k in iaKeys) { this.#claim(model, k); } let baKeys = model.boxAdaptations.map.keys(); for (let k in baKeys) { this.#claim(model, k); } let faKeys = model.functionAdaptations.map.keys(); for (let k in faKeys) { this.#claim(model, k); } let ucKeys = model.unionCallCalleeTypes.map.keys(); for (let k in ucKeys) { this.#claim(model, k); } let acKeys = model.originalArgCounts.map.keys(); for (let k in acKeys) { this.#claim(model, k); } let doKeys = model.defaultArgsOwners.map.keys(); for (let k in doKeys) { this.#claim(model, k); } let dpKeys = model.defaultArgParamNames.map.keys(); for (let k in dpKeys) { this.#claim(model, k); } let saKeys = model.staticAccesses.map.keys(); for (let k in saKeys) { this.#claim(model, k); } let mkKeys = model.memberKeys.map.keys(); for (let k in mkKeys) { this.#claim(model, k); } let sdKeys = model.scopeExitDrops.map.keys(); for (let k in sdKeys) { this.#claim(model, k); } let edKeys = model.edgeDrops.map.keys(); for (let k in edKeys) { this.#claim(model, k); } let xdKeys = model.exitDrops.map.keys(); for (let k in xdKeys) { this.#claim(model, k); } let odKeys = model.ownDropIntervals.map.keys(); for (let k in odKeys) { this.#claim(model, k); } let arKeys = model.assignmentReleases.map.keys(); for (let k in arKeys) { this.#claim(model, k); } let mfKeys = model.movedOutFields.map.keys(); for (let k in mfKeys) { this.#claim(model, k); } let ftKeys = model.fieldTakes.map.keys(); for (let k in ftKeys) { this.#claim(model, k); } let sfKeys = model.scopedFieldStores.map.keys(); for (let k in sfKeys) { this.#claim(model, k); } let rsKeys = model.revivingStores.map.keys(); for (let k in rsKeys) { this.#claim(model, k); } let symbols = model.symbols; if (symbols != null) { // Only the nodes outside the module's range need claiming; the // range itself is the model's by construction. for (let k in symbols.byNode.overflowKeys()) { this.#claim(model, k); } } let btKeys = model.bindingTypes.keys(); for (let k in btKeys) { this.symbolToModel[k] = model; } } } /** * One compensating drop at a branch join: release `symbolId` at the end * of one arm, because another arm moved it. On an `if` (armIndex -1) * `onTrueArm` names the side; on a `match`, armIndex is the case index * and `onTrueArm` is unused. */ export final class EdgeDrop { symbolId: SymbolId; onTrueArm: boolean; var armIndex: i32 = -1; new(this.symbolId, this.onTrueArm); } export final class RecordAdaptation { source: RecordType; target: RecordType; new(this.source, this.target); } /** * A use that reads a union of record types by one record shape. The * value is one of `members` at run time, each with its own layout, so * the repack that `RecordAdaptation` does for a known source shape has * to pick the member first — codegen tests the value against each * member's fat pointer type and repacks that member to `target`. */ export final class RecordUnionAdaptation { members: GrowableArray; target: RecordType; /** * The adapted expression can be null (`{a} | {a, b} | null` flowing * into `{a} | null`), so null branches around the member chain * instead of matching no member and trapping. */ sourceNullable: boolean; new(this.members, this.target, this.sourceNullable = false); } export final class InterfaceAdaptation { source: Type; target: InterfaceType; /** * The adapted expression can be null (`C | null` flowing into * `I | null`), so the pack runs under a null guard and null passes * through as a null fat pointer. */ sourceNullable: boolean; new(this.source, this.target, this.sourceNullable = false); } export final class FunctionAdaptation { source: FunctionType; target: FunctionType; new(this.source, this.target); } /** * The bodies of a module that are checked when something reaches * them, rather than when the module is checked. The checker implements * this; reachability calls it from its walk, through the model, so that * neither pass has to import the other. * * Both calls are no-ops for a body that has already been checked, and * for an id that names nothing this module defers. */ export interface DeferredBodies { /** Check the top-level declaration that binds `symId`. */ checkGlobalBody(symId: SymbolId): void; /** * Check the body `nodeId` belongs to: the class member it names, or * the top-level `let` or `function` whose arrow it is. */ checkBodyOfNode(nodeId: i32): void; } /** * An expression that must not change anything a caller can see: the * condition of a `static` clause, or the argument of `old` * (docs/design/pure-functions.md). The checker records one where it * meets the expression, and `checkCompilation` settles them when every * module is checked, since the answer depends on the bodies of what * the expression calls. */ export final class PurityObligation( expression: Expression, /** What the expression is, to begin the error with: "A 'static requires' condition". */ subject: String, /** Whether the expression may name `result`. */ inEnsures: boolean ) export final class SemanticModel { var typeIdGenerator: IdGenerator | null = null; /** The expressions of this module that must be free of effects. */ purityObligations = new Array(); /** Records `obligation`, once however often its expression is checked. */ addPurityObligation(obligation: PurityObligation): void { for (let recorded in this.purityObligations) { if (recorded.expression === obligation.expression) { return; } } this.purityObligations.push(obligation); } /** * Set on a module whose bodies wait for something to reach them: a * dependency, outside the local project. Null on a module checked in * full, which is every module of the local project and every module * at all when the whole compilation is checked eagerly. */ var deferredBodies: DeferredBodies | null = null; /** * The index that can name the owner of a node this model does not * own. Set once, when this model's check finishes; never by a * compile, which is why two compiles over these models cannot fight * over it. */ var index: ModelIndex | null = null; var sourcePath: String = ""; /** * Map from node.id → inferred Type. * Used for both expression types and declaration/binding types. */ /** * Dense over the module's node ids once `setNodeRange` has run (the * checker calls it as soon as it has the AST); anything stored * before that lands in the table's overflow map and is moved. */ #nodeTypes = new DenseNodeMap(0 as NodeId, -1 as NodeId); /** The node-id range of this model's module; see `Module.lastNodeId`. */ var firstNodeId: NodeId = 0 as NodeId; var lastNodeId: NodeId = -1 as NodeId; /** * Tells the model which ids its module's nodes have, so the per-node * tables can be arrays over that range rather than hash maps. */ setNodeRange(first: NodeId, last: NodeId): void { this.firstNodeId = first; this.lastNodeId = last; this.#nodeTypes.reserve(first, last); this.#parents.reserve(first, last); } /** * The record types this module converts to a slot that does not know * the record's shape (`anyref`, a union with other kinds of value), * and the record types in their fields. Only these reach the erased * `==`, so only these need its field-by-field comparison * (ir/equality.zena, `lowerErasedEqDispatch`). */ erasedRecordTypes = new Array(); /** * Where this module uses a tuple of one type as a tuple of another, * element by element (`(Bird, i32)` as `(Animal, i32)`), outermost and * nested. Codegen joins each pair's representation, so the widening * copies nothing (#1137, codegen/wasm-module.zena `getTupleStruct`). */ tupleWidenings = new Array(); /** * The tuple types this module converts to a slot that does not know * the tuple's type (`anyref`, a type parameter's erasure, an interface, * a union with other kinds of value), and those an `is` or `as` tests * or casts to from such a slot. Codegen joins each tested type with the * erased ones of its family, which a value can reach it from (#1181). */ erasedTupleTypes = new Array(); testedTupleTypes = new Array(); /** * Map from node.id → RecordAdaptation for implicit fat pointer adaptation. */ #recordAdaptations = new NodeMap(); setRecordAdaptation(node: Node, source: RecordType, target: RecordType): void { this.#recordAdaptations[node] = new RecordAdaptation(source, target); } getRecordAdaptationDirect(node: Node): RecordAdaptation | null { if (let (true, t) = this.#recordAdaptations.get(node)) { return t; } return null; } getRecordAdaptation(node: Node): RecordAdaptation | null { let t = this.getRecordAdaptationDirect(node); if (t != null) return t; if (this.index != null) { let owner = (this.index as ModelIndex).ownerOfNode(node.id); if (owner != null && owner != this) { return owner.getRecordAdaptationDirect(node); } } return null; } /** * Map from node.id → RecordUnionAdaptation, for a use that reads a * union of record types by one record shape. */ #recordUnionAdaptations = new NodeMap(); setRecordUnionAdaptation(node: Node, members: GrowableArray, target: RecordType, sourceNullable: boolean = false): void { this.#recordUnionAdaptations[node] = new RecordUnionAdaptation(members, target, sourceNullable); } getRecordUnionAdaptationDirect(node: Node): RecordUnionAdaptation | null { if (let (true, t) = this.#recordUnionAdaptations.get(node)) { return t; } return null; } getRecordUnionAdaptation(node: Node): RecordUnionAdaptation | null { let t = this.getRecordUnionAdaptationDirect(node); if (t != null) return t; if (this.index != null) { let owner = (this.index as ModelIndex).ownerOfNode(node.id); if (owner != null && owner != this) { return owner.getRecordUnionAdaptationDirect(node); } } return null; } /** * Map from node.id → InterfaceAdaptation for implicit interface fat pointer adaptation. */ #interfaceAdaptations = new NodeMap(); #resolvedOverloads = new NodeMap(); #resolvedCompoundOperators = new NodeMap(); /** * Map from node.id → the `Box

` a tagged template's primitive * interpolation is wrapped in, recorded when the tag's value type * accepts the box and not the primitive. Codegen constructs the box * around the lowered value; nothing else in the tree names the class. */ #boxAdaptations = new NodeMap(); setBoxAdaptation(node: Node, box: ClassType): void { this.#boxAdaptations[node] = box; } getBoxAdaptationDirect(node: Node): ClassType | null { if (let (true, t) = this.#boxAdaptations.get(node)) { return t; } return null; } getBoxAdaptation(node: Node): ClassType | null { let t = this.getBoxAdaptationDirect(node); if (t != null) return t; if (this.index != null) { let owner = (this.index as ModelIndex).ownerOfNode(node.id); if (owner != null && owner != this) { return owner.getBoxAdaptationDirect(node); } } return null; } setInterfaceAdaptation(node: Node, source: Type, target: InterfaceType, sourceNullable: boolean = false): void { this.#interfaceAdaptations[node] = new InterfaceAdaptation(source, target, sourceNullable); } /** * The overload the checker selected for a call or index expression, * recorded ONLY when the callee had overloads. Codegen must consume * this instead of re-deriving the choice from argument node types: * overload selection is subtype-sensitive and belongs to the checker * alone (registration mangles overloaded members with the DECLARED * signature key, so the recorded FunctionType reproduces the exact * registration name). */ setResolvedOverload(node: Node, ft: FunctionType): void { this.#resolvedOverloads[node] = ft; } getResolvedOverloadDirect(node: Node): FunctionType | null { if (let (true, t) = this.#resolvedOverloads.get(node)) { return t; } return null; } getResolvedOverload(node: Node): FunctionType | null { let t = this.getResolvedOverloadDirect(node); if (t != null) return t; if (this.index != null) { let owner = (this.index as ModelIndex).ownerOfNode(node.id); if (owner != null && owner != this) { return owner.getResolvedOverloadDirect(node); } } return null; } /** * The operator overload selected for the binary step of a compound * assignment (`x += y`, `arr[i] += y`), kept separate from * `#resolvedOverloads` because `arr[i] += y` already records its * `[]=` overload on the same AssignmentExpression node. */ setResolvedCompoundOperator(node: Node, ft: FunctionType): void { this.#resolvedCompoundOperators[node] = ft; } getResolvedCompoundOperatorDirect(node: Node): FunctionType | null { if (let (true, t) = this.#resolvedCompoundOperators.get(node)) { return t; } return null; } getResolvedCompoundOperator(node: Node): FunctionType | null { let t = this.getResolvedCompoundOperatorDirect(node); if (t != null) return t; if (this.index != null) { let owner = (this.index as ModelIndex).ownerOfNode(node.id); if (owner != null && owner != this) { return owner.getResolvedCompoundOperatorDirect(node); } } return null; } getInterfaceAdaptationDirect(node: Node): InterfaceAdaptation | null { if (let (true, t) = this.#interfaceAdaptations.get(node)) { return t; } return null; } getInterfaceAdaptation(node: Node): InterfaceAdaptation | null { let t = this.getInterfaceAdaptationDirect(node); if (t != null) return t; if (this.index != null) { let owner = (this.index as ModelIndex).ownerOfNode(node.id); if (owner != null && owner != this) { return owner.getInterfaceAdaptationDirect(node); } } return null; } /** * Map from node.id → FunctionAdaptation for implicit function argument adaptation. */ #functionAdaptations = new NodeMap(); setFunctionAdaptation(node: Node, source: FunctionType, target: FunctionType): void { this.#functionAdaptations[node] = new FunctionAdaptation(source, target); } getFunctionAdaptationDirect(node: Node): FunctionAdaptation | null { if (let (true, t) = this.#functionAdaptations.get(node)) { return t; } return null; } getFunctionAdaptation(node: Node): FunctionAdaptation | null { let t = this.getFunctionAdaptationDirect(node); if (t != null) return t; if (this.index != null) { let owner = (this.index as ModelIndex).ownerOfNode(node.id); if (owner != null && owner != this) { return owner.getFunctionAdaptationDirect(node); } } return null; } /** * Map from node.id -> UnionType representing the original union type of a callee. */ #unionCallCalleeTypes = new NodeMap(); setUnionCallCalleeType(node: Node, type: UnionType): void { this.#unionCallCalleeTypes[node] = type; } getUnionCallCalleeTypeDirect(node: Node): UnionType | null { if (let (true, t) = this.#unionCallCalleeTypes.get(node)) { return t; } return null; } getUnionCallCalleeType(node: Node): UnionType | null { let t = this.getUnionCallCalleeTypeDirect(node); if (t != null) return t; let {index} = this; if (index != null) { let owner = index.ownerOfNode(node.id); if (owner != null && owner != this) { return owner.getUnionCallCalleeTypeDirect(node); } } return null; } /** * Map from node.id -> original argument count (before checker filled in defaults) */ #originalArgCounts = new NodeMap(); setOriginalArgCount(node: Node, count: i32): void { this.#originalArgCounts[node] = count; } getOriginalArgCountDirect(node: Node): i32 { if (let (true, count) = this.#originalArgCounts.get(node)) { return count; } return -1; } getOriginalArgCount(node: Node): i32 { let c = this.getOriginalArgCountDirect(node); if (c != -1) return c; let {index} = this; if (index != null) { let owner = index.ownerOfNode(node.id); if (owner != null && owner != this) { return owner.getOriginalArgCountDirect(node); } } return -1; } /** * Map from node.id -> ClassType of the class that owns the method defaults */ #defaultArgsOwners = new NodeMap(); setDefaultArgsOwner(node: Node, type: Type): void { this.#defaultArgsOwners[node] = type; } getDefaultArgsOwnerDirect(node: Node): Type | null { if (let (true, t) = this.#defaultArgsOwners.get(node)) { return t; } return null; } getDefaultArgsOwner(node: Node): Type | null { let t = this.getDefaultArgsOwnerDirect(node); if (t != null) return t; let {index} = this; if (index != null) { let owner = index.ownerOfNode(node.id); if (owner != null && owner != this) { return owner.getDefaultArgsOwnerDirect(node); } } return null; } /** * Map from node.id -> Parameter names */ #defaultArgParamNames = new NodeMap>(); setDefaultArgParamNames(node: Node, names: GrowableArray): void { this.#defaultArgParamNames[node] = names; } getDefaultArgParamNamesDirect(node: Node): GrowableArray | null { if (let (true, ns) = this.#defaultArgParamNames.get(node)) { return ns; } return null; } getDefaultArgParamNames(node: Node): GrowableArray | null { let ns = this.getDefaultArgParamNamesDirect(node); if (ns != null) return ns; let {index} = this; if (index != null) { let owner = index.ownerOfNode(node.id); if (owner != null && owner != this) { return owner.getDefaultArgParamNamesDirect(node); } } return null; } /** * The key a symbol-keyed member is registered under, per name node and * per symbol-keyed member access. * * Two symbols may share a name, so the name alone cannot key a member: * a class implementing two interfaces whose symbols are both called * `act` needs two members. The key therefore carries the symbol's * identity, which only the checker knows — every later pass reads it * back from here rather than rebuilding it from the source text. */ #memberKeys = new NodeMap(); setMemberKey(node: Node, key: String): void { this.#memberKeys[node] = key; } /** The recorded key, or null where the checker recorded none. */ memberKeyDirect(node: Node): String | null { if (let (true, k) = this.#memberKeys.get(node)) { return k; } return null; } /** * The recorded key, following the node to the model that owns it — a * member declared in one module is keyed by that module's checker and * read by codegen walking from another. */ memberKey(node: Node): String | null { let direct = this.memberKeyDirect(node); if (direct != null) { return direct; } let {index} = this; if (index != null) { let owner = index.ownerOfNode(node.id); if (owner != null && owner != this) { return owner.memberKeyDirect(node); } } return null; } /** * Map from node.id → boolean to record whether a member/call expression is a static access. */ #staticAccesses = new NodeMap(); setStaticAccess(node: Node, isStatic: boolean): void { this.#staticAccesses[node] = isStatic; } isStaticAccessDirect(node: Node): boolean { if (let (true, s) = this.#staticAccesses.get(node)) { return s; } return false; } isStaticAccess(node: Node): boolean { if (this.isStaticAccessDirect(node)) return true; let {index} = this; if (index != null) { let owner = index.ownerOfNode(node.id); if (owner != null && owner != this) { return owner.isStaticAccessDirect(node); } } return false; } /** * Declarations (keyed by their IdentifierPattern node) whose binding * the compiler releases at scope exit: an `Own` of a resource class * that is never moved, reassigned, captured or otherwise escaped. * The checker decides (ownership.md §Implicit drop); ZIR lowering * materializes the release through the shared finally region. The * verdict is overwritten on a re-check, so stale trues cannot * survive a pass that reached a different conclusion. */ #scopeExitDrops = new NodeMap(); /** * The release regions of a `var` owner binding, keyed by its * declaration's pattern node: pairs of statement indices [start, end) * in the declaring block, end -1 standing for the block's end, over * which the binding holds a value nothing has moved. A region's * finalizer releases whatever the binding holds at its exit. Empty * when the binding is not released at all (ownership.md §Implicit * drop, "`var` owner bindings"). */ #ownDropIntervals = new NodeMap>(); setOwnDropIntervals(node: Node, intervals: GrowableArray): void { this.#ownDropIntervals[node] = intervals; } ownDropIntervalsOfDirect(node: Node): GrowableArray | null { if (let (true, d) = this.#ownDropIntervals.get(node)) { return d; } return null; } ownDropIntervalsOf(node: Node): GrowableArray | null { let direct = this.ownDropIntervalsOfDirect(node); if (direct != null) return direct; let {index} = this; if (index != null) { let owner = index.ownerOfNode(node.id); if (owner != null && owner != this) { return owner.ownDropIntervalsOfDirect(node); } } return null; } ownDropIntervals: NodeMap> { get { return this.#ownDropIntervals; } } /** * Plain stores into a `var` owner binding that release the value the * binding held before them: the checker found the binding live there. * Keyed by the assignment node. */ #assignmentReleases = new NodeMap(); setAssignmentRelease(node: Node): void { this.#assignmentReleases[node] = true; } hasAssignmentReleaseDirect(node: Node): boolean { if (let (true, d) = this.#assignmentReleases.get(node)) { return d; } return false; } hasAssignmentRelease(node: Node): boolean { if (this.hasAssignmentReleaseDirect(node)) return true; let {index} = this; if (index != null) { let owner = index.ownerOfNode(node.id); if (owner != null && owner != this) { return owner.hasAssignmentReleaseDirect(node); } } return false; } assignmentReleases: NodeMap { get { return this.#assignmentReleases; } } /** * Reads of a nullable owner field of `this` that move the owner out * of a consuming method: a take, which stores null into the field * after the read (ownership.md §Affine fields). Keyed by the member * expression. */ #fieldTakes = new NodeMap(); setFieldTake(node: Node): void { this.#fieldTakes[node] = true; } isFieldTakeDirect(node: Node): boolean { if (let (true, d) = this.#fieldTakes.get(node)) { return d; } return false; } isFieldTake(node: Node): boolean { if (this.isFieldTakeDirect(node)) return true; let {index} = this; if (index != null) { let owner = index.ownerOfNode(node.id); if (owner != null && owner != this) { return owner.isFieldTakeDirect(node); } } return false; } fieldTakes: NodeMap { get { return this.#fieldTakes; } } /** * Plain stores into a field whose declared type holds its class's * `scoped T`, at a receiver that may be a restricted instantiation. * What the store does with the value it replaces is decided per * specialization: an owner is released, a `Scoped` refused, and * anything else overwritten. Keyed by the assignment node. */ #scopedFieldStores = new NodeMap(); setScopedFieldStore(node: Node): void { this.#scopedFieldStores[node] = true; } isScopedFieldStoreDirect(node: Node): boolean { if (let (true, d) = this.#scopedFieldStores.get(node)) { return d; } return false; } isScopedFieldStore(node: Node): boolean { if (this.isScopedFieldStoreDirect(node)) return true; let {index} = this; if (index != null) { let owner = index.ownerOfNode(node.id); if (owner != null && owner != this) { return owner.isScopedFieldStoreDirect(node); } } return false; } scopedFieldStores: NodeMap { get { return this.#scopedFieldStores; } } /** * Stores into an owner field of `this` that a dispose moved out on * every path to the store: the field held nothing, so the store * releases nothing and revives it. Keyed by the assignment node. */ #revivingStores = new NodeMap(); setRevivingStore(node: Node): void { this.#revivingStores[node] = true; } isRevivingStoreDirect(node: Node): boolean { if (let (true, d) = this.#revivingStores.get(node)) { return d; } return false; } isRevivingStore(node: Node): boolean { if (this.isRevivingStoreDirect(node)) return true; let {index} = this; if (index != null) { let owner = index.ownerOfNode(node.id); if (owner != null && owner != this) { return owner.isRevivingStoreDirect(node); } } return false; } revivingStores: NodeMap { get { return this.#revivingStores; } } setScopeExitDrop(node: Node, drop: boolean): void { this.#scopeExitDrops[node] = drop; } hasScopeExitDropDirect(node: Node): boolean { if (let (true, d) = this.#scopeExitDrops.get(node)) { return d; } return false; } hasScopeExitDrop(node: Node): boolean { if (this.hasScopeExitDropDirect(node)) return true; if (this.index != null) { let owner = (this.index as ModelIndex).ownerOfNode(node.id); if (owner != null && owner != this) { return owner.hasScopeExitDropDirect(node); } } return false; } /** * Compensating drops, keyed by an IfStatement node: bindings a branch * join must release at the end of one arm because the other arm moved * them (ownership.md §"The branch-join rule"). Lowering emits the * dispose at the flagged arm's end, before the merge. */ #edgeDrops = new NodeMap>(); setEdgeDrops(node: Node, drops: GrowableArray): void { this.#edgeDrops[node] = drops; } edgeDropsOfDirect(node: Node): GrowableArray | null { if (let (true, d) = this.#edgeDrops.get(node)) { return d; } return null; } edgeDropsOf(node: Node): GrowableArray | null { let direct = this.edgeDropsOfDirect(node); if (direct != null) { return direct; } if (this.index != null) { let owner = (this.index as ModelIndex).ownerOfNode(node.id); if (owner != null && owner != this) { return owner.edgeDropsOfDirect(node); } } return null; } /** * Drops owed at an early exit, keyed by its `return`, `break` or * `continue`: bindings still live there that a move elsewhere kept * from being released at their scope's end. Lowering releases them * after the exit's value is computed and before control leaves. */ #exitDrops = new NodeMap>(); setExitDrops(node: Node, drops: GrowableArray): void { this.#exitDrops[node] = drops; } exitDropsOfDirect(node: Node): GrowableArray | null { if (let (true, d) = this.#exitDrops.get(node)) { return d; } return null; } exitDropsOf(node: Node): GrowableArray | null { let direct = this.exitDropsOfDirect(node); if (direct != null) { return direct; } if (this.index != null) { let owner = (this.index as ModelIndex).ownerOfNode(node.id); if (owner != null && owner != this) { return owner.exitDropsOfDirect(node); } } return null; } /** * The affine fields a consuming method's body moved out, keyed by * its MethodDefinition: dispose glue skips them * (ownership.md §Affine fields). */ #movedOutFields = new NodeMap>(); setMovedOutFields(node: Node, names: GrowableArray): void { this.#movedOutFields[node] = names; } movedOutFieldsOfDirect(node: Node): GrowableArray | null { if (let (true, d) = this.#movedOutFields.get(node)) { return d; } return null; } movedOutFieldsOf(node: Node): GrowableArray | null { let direct = this.movedOutFieldsOfDirect(node); if (direct != null) { return direct; } if (this.index != null) { let owner = (this.index as ModelIndex).ownerOfNode(node.id); if (owner != null && owner != this) { return owner.movedOutFieldsOfDirect(node); } } return null; } /** * Map from Symbol.id → Type for named bindings. * Parallel to #nodeTypes but keyed by binding identity, which is * stable across reference sites. The checker populates this when * processing declarations; identifier resolution looks up here. */ #bindingTypes = new Map(); /** * Scope analysis symbol map (nodes → Symbol). * Owned by the SemanticModel so consumers have a single object to query. */ var #symbols: SymbolMap | null = null; /** * Parent pointer map from node → parent node. * Useful for analyses (like DCE) that need to walk up from a node. * Populated during scope analysis. */ var #parents: DenseNodeMap = new DenseNodeMap(0 as NodeId, -1 as NodeId); /** * All diagnostics from type checking. */ #diagnostics = new Array(); /** * Map from exported names to their resolved Type. * Used for cross-module type lookups, especially for built-in * primitives where Symbol ids may differ natively. */ #exportTypes = new Map(); // --- Reference and declaration maps --- symbols: SymbolMap | null { get { return this.#symbols; } } /** * Attach the scope analysis maps. */ setSymbols(symbols: SymbolMap): void { this.#symbols = symbols; } /** * Bulk add parent pointers. */ setParents(parents: DenseNodeMap): void { this.#parents = parents; } /** * Set the parent of a node. */ setParent(child: Node, parent: Node): void { this.#parents[child] = parent; } getParentDirect(child: Node): Node | null { if (let (true, parent) = this.#parents.get(child)) { return parent; } return null; } getParent(child: Node): Node | null { let p = this.getParentDirect(child); if (p != null) return p; let {index} = this; if (index != null) { let owner = index.ownerOfNode(child.id); if (owner != null && owner != this) { return owner.getParentDirect(child); } } return null; } resolveDirect(node: Node): Symbol | null { if (this.#symbols == null) { return null; } return (this.#symbols as SymbolMap).getByNode(node); } resolveByOffset(offset: i32): Symbol | null { if (this.#symbols == null) { return null; } return (this.#symbols as SymbolMap).getByOffset(offset); } resolve(node: Node): Symbol | null { let sym = this.resolveDirect(node); if (sym != null) return sym; let {index} = this; if (index != null) { let owner = index.ownerOfNode(node.id); if (owner != null && owner != this) { return owner.resolveDirect(node); } } return null; } /** * Find the Symbol for a declaration-site node. * Used at declaration-processing time (e.g., when the checker processes * a VariableDeclaration and needs to store the type for its binding). */ resolveDeclaration(node: Node): Symbol | null { return this.resolve(node); } // --- Node types (expressions and declaration nodes) --- /** * Record the inferred type for an AST node. */ setNodeType(node: Node, type: Type): void { this.#nodeTypes[node] = type; } getNodeTypeDirect(node: Node): Type | null { if (let (true, t) = this.#nodeTypes.get(node)) { return t; } return null; } getNodeType(node: Node): Type | null { let t = this.getNodeTypeDirect(node); if (t != null) return t; let {index} = this; if (index != null) { let owner = index.ownerOfNode(node.id); if (owner != null && owner != this) { return owner.getNodeTypeDirect(node); } } return null; } // --- Binding types (keyed by Symbol.id) --- /** * Store the type for a named binding. */ setBindingType(info: Symbol, type: Type): void { this.#bindingTypes[info.id] = type; } getBindingTypeDirect(info: Symbol): Type | null { if (this.#bindingTypes.has(info.id)) { return this.#bindingTypes[info.id]; } return null; } getBindingTypeById(id: SymbolId): Type | null { if (this.#bindingTypes.has(id)) { return this.#bindingTypes[id]; } return null; } getBindingType(info: Symbol): Type | null { let t = this.getBindingTypeDirect(info); if (t != null) return t; let {index} = this; if (index != null) { let owner = index.ownerOfBinding(info.id); if (owner != null && owner != this) { return owner.getBindingTypeDirect(info); } } return null; } // --- Exports --- /** * Register a type as exported under the given name. */ setExportType(name: String, type: Type): void { this.#exportTypes[name] = type; } /** * Get an exported type by name. */ getExportType(name: String): Type | null { if (this.#exportTypes.has(name)) { return this.#exportTypes[name]; } return null; } // --- Diagnostics --- addDiagnostic(diagnostic: Diagnostic): void { this.#diagnostics.push(diagnostic); } diagnostics: GrowableArray { get { return this.#diagnostics; } } nodeTypes: DenseNodeMap { get { return this.#nodeTypes; } } #symbolDependencies = new Map(); #nodeDependencies = new Map(); symbolNames = new Map(); /** * Locals that some closure assigns, or captures before their * declaration runs. Every closure that captures one of these captures * its heap cell, including a closure that only reads it, so that the * reader sees the writer's assignments. Filled by the checker as it * leaves each closure; `capturedInCell` adds the locals the declaring * scope assigns after a capture. */ mutablyCapturedSymbols = new Set(); /** * For each variable assigned after its declaration, the largest node * id among its assignments. Node ids are handed out in source order, * so this is the textually last one. See `capturedInCell`. */ lastAssignment = new Map(); /** * The locals closures capture, each with the closures that capture * it. See `capturedInCell`. */ capturedLocals = new Map(); recordCapture(sym: Symbol, closure: Node): void { if (let (true, local) = this.capturedLocals.get(sym.id)) { local.closures.push(closure); return; } let local = new CapturedLocal(sym); local.closures.push(closure); this.capturedLocals[sym.id] = local; } #declaredClasses = new Array(); #declaredInterfaces = new Array(); #declaredMixins = new Array(); #declaredEnums = new Array(); #declaredGlobals = new Array(); #classDeclarations = new Map(); #interfaceDeclarations = new Map(); #mixinDeclarations = new Map(); #enumDeclarations = new Map(); // Ordered, and in declaration order: reachability roots a module's // exports by iterating this, and the order decides function indices // in the emitted module. Keyed by symbol id in a hash map, the order // followed the ids' hash buckets, which shift whenever a module // loaded ahead of this one gains or loses a symbol — so two targets // whose preludes differ in size emitted the same program with its // functions permuted. #globalDeclarations = new Map.ordered(); #globalDeclarationOverloads = new Map>(); symbolDependencies: HashMap { get { return this.#symbolDependencies; } } nodeDependencies: HashMap { get { return this.#nodeDependencies; } } declaredClasses: GrowableArray { get { return this.#declaredClasses; } } declaredInterfaces: GrowableArray { get { return this.#declaredInterfaces; } } declaredMixins: GrowableArray { get { return this.#declaredMixins; } } declaredEnums: GrowableArray { get { return this.#declaredEnums; } } declaredGlobals: GrowableArray { get { return this.#declaredGlobals; } } classDeclarations: HashMap { get { return this.#classDeclarations; } } interfaceDeclarations: HashMap { get { return this.#interfaceDeclarations; } } mixinDeclarations: HashMap { get { return this.#mixinDeclarations; } } enumDeclarations: HashMap { get { return this.#enumDeclarations; } } globalDeclarations: HashMap { get { return this.#globalDeclarations; } } addDeclaredClass(id: SymbolId, cd: ClassDeclaration): void { this.#classDeclarations[id] = cd; this.#declaredClasses.push(id); } addDeclaredInterface(id: SymbolId, idDec: InterfaceDeclaration): void { this.#interfaceDeclarations[id] = idDec; this.#declaredInterfaces.push(id); } addDeclaredMixin(id: SymbolId, md: MixinDeclaration): void { this.#mixinDeclarations[id] = md; this.#declaredMixins.push(id); } addDeclaredEnum(id: SymbolId, ed: EnumDeclaration): void { this.#enumDeclarations[id] = ed; this.#declaredEnums.push(id); } addDeclaredGlobal(id: SymbolId, node: Node): void { if (!this.#globalDeclarations.has(id)) { this.#globalDeclarations[id] = node; this.#declaredGlobals.push(id); } let list = if (let (true, l) = this.#globalDeclarationOverloads.get(id)) { l } else { let nl = new Array(); this.#globalDeclarationOverloads[id] = nl; nl }; list.push(node); } getGlobalDeclarations(id: SymbolId): GrowableArray | null { if (let (true, l) = this.#globalDeclarationOverloads.get(id)) { return l; } return null; } setSymbolDependencies(id: SymbolId, deps: SymbolDependencies): void { this.#symbolDependencies[id] = deps; } setNodeDependencies(id: i32, deps: SymbolDependencies): void { this.#nodeDependencies[id] = deps; } recordAdaptations: NodeMap { get { return this.#recordAdaptations; } } recordUnionAdaptations: NodeMap { get { return this.#recordUnionAdaptations; } } interfaceAdaptations: NodeMap { get { return this.#interfaceAdaptations; } } boxAdaptations: NodeMap { get { return this.#boxAdaptations; } } functionAdaptations: NodeMap { get { return this.#functionAdaptations; } } unionCallCalleeTypes: NodeMap { get { return this.#unionCallCalleeTypes; } } originalArgCounts: NodeMap { get { return this.#originalArgCounts; } } defaultArgsOwners: NodeMap { get { return this.#defaultArgsOwners; } } defaultArgParamNames: NodeMap> { get { return this.#defaultArgParamNames; } } staticAccesses: NodeMap { get { return this.#staticAccesses; } } memberKeys: NodeMap { get { return this.#memberKeys; } } scopeExitDrops: NodeMap { get { return this.#scopeExitDrops; } } edgeDrops: NodeMap> { get { return this.#edgeDrops; } } exitDrops: NodeMap> { get { return this.#exitDrops; } } movedOutFields: NodeMap> { get { return this.#movedOutFields; } } parents: DenseNodeMap { get { return this.#parents; } } bindingTypes: HashMap { get { return this.#bindingTypes; } } } /** A local some closure captures, and every closure that captures it. */ export final class CapturedLocal { sym: Symbol; closures = new Array(); new(this.sym); } export final class ClosureDependency { id: i32; node: Node; capturesThis: boolean; captures: GrowableArray; dependencies: SymbolDependencies; new(this.id, this.node, this.capturesThis, this.captures, this.dependencies); } /** A tuple of type `source` used as a tuple of type `target` (`tupleWidenings`). */ export final class TupleWidening { source: TupleType; target: TupleType; new(this.source, this.target); } export final class FunctionAdaptationDependency { node: Node; source: FunctionType; target: FunctionType; new(this.node, this.source, this.target); } /** * A set of types that iterates in the order they were added. * * Insertion order, not hash order. `Type.hashCode` is a process-global * uid handed out at construction and never reset — it cannot be, since * a long-lived compiler interns types across compiles, and restarting * the sequence would collide fresh types with cached ones. So a * `HashSet` iterates in an order that depends on how many types * the process had already built, which is to say on how many modules * were compiled before this one. * * That order reaches the emitted bytes: RTA walks this set to intern * wasm types and register function-value wrappers, so compiling one * file twice in a single process emitted two different (equally * correct, equally sized) modules — a permuted type section, and * whichever of two same-signature wrappers was registered first. * The checker adds types during a deterministic AST walk, so insertion * order is stable; hash order was the only thing that was not. */ export final class OrderedTypeSet with IterableUtils implements Iterable { #seen = new Set(); #order = new Array(); /** Adds `t` if it is not already present. Returns whether it was new. */ add(t: Type): boolean { if (!this.#seen.add(t)) { return false; } this.#order.push(t); return true; } [Iterable.iterator](): Iterator { return this.#order.[Iterable.iterator](); } } export final class SymbolDependencies { referencedSymbols = new Set(); referencedClassMethods = new Set(); // Format: ClassSymbolId.methodName usedInterfaceAdaptations = new Set(); // Format: ClassSymbolId::InterfaceSymbolId referencedTypes = new OrderedTypeSet(); closures = new Array(); functionAdaptations = new Array(); var needsExceptionInfra = false; /** * This body can cause a cancellation: it calls `cancel` on a * `TaskGroup`, the one operation that marks a scope cancelled. * Aggregated over reached bodies, this is the whole-program gate * the async cancellation machinery is emitted under. */ var causesCancellation = false; /** * This body has a `for`-in that iterates through the Iterator * protocol (not an array index loop). Half of the generator-disposal * gate: a reached protocol loop in a program that also creates a * generator makes disposal possible, so those loops get a disposal * finalizer and generators get the machinery it drives. */ var hasIteratorForIn = false; /** This body creates a generator (`gen` function). The other half * of the generator-disposal gate. */ var createsGenerator = false; /** This body creates an async generator (`async gen` function). Together * with `hasIteratorForIn`, this also opens the scope-cancellation gate so * `for await` early-exit disposal can cancel pending work. */ var createsAsyncGenerator = false; /** * Enclosing locals assigned inside a `try` body. RTA cells them, so * the handler observes assignments the body completed before it * threw (see `analysis/capture.zena`). */ tryMutatedSymbols = new Set(); }