import { Set, HashMap } from 'zena:collections'; import { NodeMap, DenseNodeMap } from '../node-map.zena'; import { Node, NodeId, Module, SourceLocation, IdGenerator, makeNodeIdGenerator, // Sealed base types Expression, Statement, Pattern, TypeAnnotation, // Expressions Identifier, NumberLiteral, StringLiteral, BooleanLiteral, NullLiteral, TemplateLiteral, TaggedTemplateExpression, BinaryExpression, UnaryExpression, AssignmentExpression, AsExpression, IsExpression, RangeExpression, PipelineExpression, PipePlaceholder, FunctionExpression, CallExpression, MemberExpression, IndexExpression, ThisExpression, SuperExpression, NewExpression, ArrayLiteral, RecordLiteral, MapLiteral, TupleLiteral, MatchExpression, IfExpression, ThrowExpression, TryExpression, AwaitExpression, ShieldedStatement, // Statements VariableDeclaration, UsingStatement, FunctionDeclaration, ExpressionStatement, BlockStatement, ReturnStatement, YieldStatement, BreakStatement, ContinueStatement, IfStatement, WhileStatement, ForStatement, ForInStatement, ClassDeclaration, InterfaceDeclaration, EnumDeclaration, MixinDeclaration, TypeAliasDeclaration, ImportDeclaration, ExportAllDeclaration, ExportFromDeclaration, DeclareFunction, SymbolDeclaration, ImportSpecifier, Decorator, isBuiltinDecoratorName, ContractClause, ContractKind, isOldCallee, // Patterns BindingPattern, IdentifierPattern, RecordPattern, TuplePattern, ArrayPattern, RestPattern, AsPattern, ClassPattern, LogicalPattern, AssignmentPattern, AbsencePattern, LiteralPattern, // Type annotations NamedTypeAnnotation, UnionTypeAnnotation, NullableTypeAnnotation, FunctionTypeAnnotation, RecordTypeAnnotation, TupleTypeAnnotation, InlineTypeAnnotation, // Helper types TypeParameter, Parameter, MethodDefinition, AccessorDeclaration, FieldDefinition, FieldInitializer, MatchCase, PropertyAssignment, SpreadElement, LetPatternCondition, SetterInfo, SuperInitializer, CaseClassParam, SealedVariant, PropertySignature, MethodSignature, AccessorSignature, CatchClause, SymbolPropertyName } from '../ast.zena'; import { walkChildren } from '../visitor.zena'; import { Symbol, SymbolId, makeSymbolIdGenerator } from './symbol.zena'; import {Scope, ScopeKind} from './scope.zena'; import { isBigIntLiteralRaw } from '../types.zena'; import { WellKnown } from '../well-known.zena'; /** * The export catalog for a module. * * Populated during name resolution by scanning exported declarations. * Used by importing modules to wire up cross-module references. * * Separate maps for value and type exports mirror the scope structure. */ export type ModuleExports = Map; /** * A name that could not be resolved during scope building. * * Since built-in types are pre-seeded and imports are declared from * their specifiers, an unresolved name is a genuine error: a typo, * a missing import, or a reference to a name that doesn't exist. */ export final class UnresolvedName( name: String, node: Node ) /** * Maps nodes to their resolved symbols. Keyed by source offset for efficient * position-based lookup (useful for LSP jump-to-definition). * * To follow through imports: if `getByNode(node).declaration` is an * `ImportSpecifier`, resolve the imported module's exports to find the * original declaration. */ export final class SymbolMap { // One slot per node id of the module, as `SemanticModel.nodeTypes`: // a hash entry per resolved node was 37 bytes each, 150K per large // compile, held for its whole life. #byNode = new DenseNodeMap(0 as NodeId, -1 as NodeId); // The offset index only the language service reads, kept as two // parallel arrays (8 bytes a record) and built into a map on the // first lookup, which a build never makes. #offsets = new GrowableArray(); #offsetSymbols = new GrowableArray(); var #byOffset: HashMap | null = null; byNode: DenseNodeMap { get { return this.#byNode; } } /** Sizes the node table to the module's id range; see `DenseNodeMap`. */ reserve(first: NodeId, last: NodeId): void { this.#byNode.reserve(first, last); } /** * Record a resolved reference or declaration. */ record(node: Node, info: Symbol): void { this.#byNode[node] = info; let loc = node.loc; if (loc != null) { this.#offsets.push(loc.start); this.#offsetSymbols.push(info); let built = this.#byOffset; if (built != null) { built[loc.start] = info; } } } /** * Look up the symbol a node refers to. Returns null if unresolved. */ getByNode(node: Node): Symbol | null { if (let (true, info) = this.#byNode.get(node)) { return info; } return null; } /** * Look up by source offset (0-based). For LSP position-based queries. */ getByOffset(offset: i32): Symbol | null { var built = this.#byOffset; if (built == null) { // Later records win, as they did when every record wrote the map. let map = new Map(this.#offsets.length); for (var i = 0; i < this.#offsets.length; i += 1) { map[this.#offsets[i]] = this.#offsetSymbols[i]; } this.#byOffset = map; built = map; } return if (let (true, info) = built.get(offset)) { info } else { null }; } } /** * A prelude name a module uses, as the import it stands for. * * The prelude is a set of ordinary imports every module gets without * writing them. Each module's scope has an outer prelude scope holding * one import binding per prelude name, so a name the module does not * declare or import itself resolves there, through the same scope chain * as any other name. The bindings the module reads are its implicit * imports; the compiler gives each the import declaration it stands for, * naming the module that declares the name. From there it is an import * like any other: it orders the check, it keeps the declaration's * identity, and it crosses an import cycle by the same rules. */ export final class ImplicitImport( spec: ImportSpecifier, /** The prelude specifier the name is listed under, e.g. `zena:core`. */ preludeSpecifier: String ) /** * The result of scope building for a single module. * * TODO: This could be a record type instead of a class */ export final class ScopeResult( /** * The module's root scope (contains all top-level declarations). */ rootScope: Scope, /** * Exported symbols from this module. */ exports: ModuleExports, /** * Value names that couldn't be resolved. * Each entry is an error: missing import or undeclared name. */ unresolvedNames: GrowableArray, /** * All successfully resolved references and declarations in this module. * Maps nodes to their symbols. */ symbols: SymbolMap, isRead: HashMap, isWritten: HashMap, /** * Names that were declared twice in the same scope. * Each entry is an error: same-scope redeclaration. */ duplicateDeclarations: GrowableArray, unusedVariables: GrowableArray, neverMutatedVariables: GrowableArray, unusedImportDeclarations: GrowableArray, unusedImportedSymbols: GrowableArray, unnecessaryImports: GrowableArray, duplicateImports: GrowableArray, /** * Parent pointer map from node → parent node. */ parents: DenseNodeMap, /** The prelude names this module uses, bound as implicit imports. */ implicitImports: GrowableArray, /** * The import declarations those implicit imports stand for, added by * the compiler once it knows which module declares each name. They are * kept here, out of the module's AST, so the AST stays what the source * says: tools that read it — documentation, formatting, the language * service — see only what was written. */ implicitImportDeclarations: GrowableArray, /** * The standard library declarations the module's syntax depends on * without naming them: `String` for a string literal, `ImmutableArray` * for an array literal, `Future` for an `async` function, and so on * (`#imply`). The module depends on the modules declaring them, and * the compiler adds those edges. */ impliedDeclarations: GrowableArray ) function populateParents(ast: Node, parents: DenseNodeMap): void { walkChildren(ast, (child) => { parents[child] = ast; populateParents(child, parents); return false; // we handle recursion manually to track the parent }, (child) => {}); } /** * Builds the scope tree and export catalog for a single module. * * Pre-seeds built-in primitive types (i32, boolean, etc.), then walks * the AST to declare names and resolve references. This is a file-local * operation: cross-module import wiring happens separately. * * Usage: * let builder = new ScopeBuilder(modulePath); * let result = builder.build(ast); */ export final class ScopeBuilder { #modulePath: String; #exports = new Map(); var #current = new Scope(ScopeKind.Module, null); var #symbolIdGenerator = makeSymbolIdGenerator(); /** * Unresolved identifiers found during the walk. * These may be resolved later when cross-module imports are wired up. */ #unresolvedNames = new Array(); #symbols = new SymbolMap(); #duplicateDeclarations = new Array(); // Sized to the module's node-id range when `build` sees the AST. #parents = new DenseNodeMap(0 as NodeId, -1 as NodeId); #isRead = new Map(); #isWritten = new Map(); #allVariables = new Array(); /** Whether the expression being processed is directly in an `ensures` condition. */ var #inEnsures = false; #allImportDeclarations = new Array(); /** * The prelude: each name every module may use without importing it, * mapped to the specifier it is listed under. Null builds a module * with no prelude at all. */ #preludeNames: HashMap | null; #nodeIds: IdGenerator; /** The prelude scope's bindings, one per prelude name, in prelude order. */ #preludeBindings = new Array(); /** What `ScopeResult.impliedDeclarations` holds, and the same as a set. */ #implied = new Array(); #impliedSet = new Set(); new(modulePath: String, preludeNames: HashMap | null = null, symbolIdGenerator: IdGenerator | null = null, nodeIds: IdGenerator | null = null) : #modulePath = modulePath, #preludeNames = preludeNames, // Without the loader's generator (a module built on its own, as in // tests), draw ids for the prelude's nodes from a range no parse // reaches. #nodeIds = nodeIds ?? makeNodeIdGenerator(1073741824) { if (symbolIdGenerator != null) { this.#symbolIdGenerator = symbolIdGenerator; } this.#current = new Scope(ScopeKind.Module, null, this.#symbolIdGenerator); } #isUnusedButAllowed(sym: Symbol): boolean { if (sym.name == "_") return true; if (this.#exports.has(sym.name)) { if (let (true, exp) = this.#exports.get(sym.name)) { if (exp.declaration === sym.declaration) return true; } } let {declaration} = sym; if (declaration is Parameter) { let param = declaration; if (let (true, parent) = this.#parents.get(param)) { match (parent) { case MethodDefinition {body}: { return body == null; } case DeclareFunction: { return true; } case MethodSignature: { return true; } case _: {} } } } return false; } /** * Build scopes for a module AST. */ build(ast: Node): ScopeResult { if (ast is Module) { this.#parents.reserve(ast.id, (ast as Module).lastNodeId); this.#symbols.reserve(ast.id, (ast as Module).lastNodeId); } populateParents(ast, this.#parents); this.#declareBuiltins(); this.#declarePrelude(ast.loc); if (let Module {body} = ast) { this.#processStatements(body); } let unused = new Array(); let neverMutated = new Array(); for (let sym in this.#allVariables) { if (!this.#isRead.has(sym.id) && !this.#isUnusedButAllowed(sym)) { unused.push(sym); } else if (sym.isMutable && !this.#isWritten.has(sym.id) && sym.name != "_") { neverMutated.push(sym); } } let seenImportedNames = new Set(); let unusedImportDeclarations = new Array(); let unusedImportedSymbols = new Array(); let unnecessaryImports = new Array(); let duplicateImports = new Array(); for (let importDecl in this.#allImportDeclarations) { if (importDecl.imports.length == 0) { continue; } let declUnusedSymbols = new Array(); var hasUsedOrSuppressedOrSpecial = false; for (let spec in importDecl.imports) { let localName = spec.local.name; let sym = this.#symbols.getByNode(spec); if (sym == null) { continue; } // 1. Check for duplicate import: if (seenImportedNames.has(localName)) { duplicateImports.push(new Symbol(localName, spec, this.#modulePath, false, sym.id)); hasUsedOrSuppressedOrSpecial = true; continue; } seenImportedNames.add(localName); // 2. Check for unnecessary prelude import (only when not renamed). // The prelude would import the name anyway, and its implicit // import orders the check just as this one does. let parentScope = this.#current.parent; if (spec.imported.name == spec.local.name && parentScope != null && parentScope.resolve(localName) != null) { unnecessaryImports.push(sym); hasUsedOrSuppressedOrSpecial = true; continue; } // 3. Check if used or suppressed by leading underscore: if (localName.startsWith("_") || this.#isRead.has(sym.id)) { hasUsedOrSuppressedOrSpecial = true; } else { declUnusedSymbols.push(sym); } } if (declUnusedSymbols.length > 0) { if (!hasUsedOrSuppressedOrSpecial) { unusedImportDeclarations.push(importDecl); } else { for (let sym in declUnusedSymbols) { unusedImportedSymbols.push(sym); } } } } return new ScopeResult( this.#current, this.#exports, this.#unresolvedNames, this.#symbols, this.#isRead, this.#isWritten, this.#duplicateDeclarations, unused, neverMutated, unusedImportDeclarations, unusedImportedSymbols, unnecessaryImports, duplicateImports, this.#parents, this.#usedPreludeBindings(), new Array(0), this.#implied ); } /** * Seed the root scope with built-in primitive types. * Creates a parent "builtins" scope so user declarations can shadow them. */ #declareBuiltins(): void { // TODO: This is duplicated with the checker's built-in and intrinsics // seeding. We should unify this into a single shared prelude scope that // both the ScopeBuilder and Checker can use as a parent for all modules. let builtins = new Scope(ScopeKind.Module, this.#current.parent, this.#symbolIdGenerator); builtins.declare("i32", false, null, ""); builtins.declare("u32", false, null, ""); builtins.declare("i64", false, null, ""); builtins.declare("u64", false, null, ""); builtins.declare("f32", false, null, ""); builtins.declare("f64", false, null, ""); builtins.declare("u8", false, null, ""); builtins.declare("u16", false, null, ""); builtins.declare("i8", false, null, ""); builtins.declare("i16", false, null, ""); builtins.declare("v128", false, null, ""); builtins.declare("boolean", false, null, ""); builtins.declare("void", false, null, ""); builtins.declare("never", false, null, ""); builtins.declare("null", false, null, ""); // Re-parent the module scope onto the builtins scope. this.#current = new Scope(ScopeKind.Module, builtins, this.#symbolIdGenerator); } /** * Put the prelude between the builtins and the module's own scope: one * import binding per prelude name, bound like an explicit import and * wired later. The module's declarations and imports shadow them, as * any inner scope does. They are located at the top of the module, * where the imports they stand for would be written. */ #declarePrelude(loc: SourceLocation | null): void { let preludeNames = this.#preludeNames; if (preludeNames == null) { return; } let prelude = new Scope(ScopeKind.Module, this.#current.parent, this.#symbolIdGenerator); let nameIter = preludeNames.keys(); for (let name in nameIter) { let imported = new Identifier(name, loc); imported.id = this.#nodeIds.next(); let local = new Identifier(name, loc); local.id = this.#nodeIds.next(); let spec = new ImportSpecifier(imported, local, loc); spec.id = this.#nodeIds.next(); prelude.declare(name, false, spec, this.#modulePath); this.#symbols.record(spec, prelude.getLocal(name) as Symbol); this.#preludeBindings.push(new ImplicitImport(spec, preludeNames[name])); } this.#current = new Scope(ScopeKind.Module, prelude, this.#symbolIdGenerator); } /** * Note that the module's syntax depends on the standard library's `w` * without naming it: the checker gives the syntax a type, or checks it * against a protocol, that only `w`'s declaration supplies. A string * literal is a `String`, an array literal an `ImmutableArray` or a * `FixedArray`, an `async` function returns a `Future`, a `for`-in asks * for `Iterable`. Without the edge this adds, a library that `w`'s own * module imports is checked before `w` is registered. */ #imply(w: WellKnown): void { if (this.#impliedSet.add(w as i32)) { this.#implied.push(w); } } /** The prelude bindings this module read: its implicit imports. */ #usedPreludeBindings(): GrowableArray { let used = new Array(); for (let binding in this.#preludeBindings) { let sym = this.#symbols.getByNode(binding.spec); if (sym != null && this.#isRead.has(sym.id)) { used.push(binding); } } return used; } /** * Process a list of statements, declaring names into the current scope. * * Two-pass: first pre-declares types and annotated functions (enabling * forward references), then processes all statements fully. */ #processStatements(statements: GrowableArray): void { // First pass: pre-declare classes, interfaces, enums, type aliases, // and annotated functions (enables mutual recursion). for (let statement in statements) { this.#predeclare(statement); } // Second pass: process all statements fully. for (let statement in statements) { this.#processStatement(statement); } } /** * Pre-declare type names and annotated functions. * This allows forward references within the same scope. */ #predeclare(stmt: Statement): void { match (stmt) { case ClassDeclaration {name, exported, sealedVariants}: { this.#current.declare(name.name, false, stmt, this.#modulePath); this.#symbols.record(stmt, this.#current.getLocal(name.name) as Symbol); if (exported) { // Every declaration exports its own symbol, as functions and // values do. A type declaration materializes to one canonical // type keyed by its symbol id // (SharedCheckerState.declaredNominalTypes), and codegen looks // declarations up by that id too. A separate export symbol has // no importTarget back to the declaration, so an importer's // resolveTarget() stops at it, and across an import cycle's // back edge the importer's shell carries an id the declaring // module never registers under: `zena:core` re-exporting // `./error.zena` hands a program on the freestanding target an // `Error` with no constructor, and a mixin applied across a // back edge compiles to a host with no methods. this.#exports[name.name] = this.#current.getLocal(name.name) as Symbol; } // Export sealed variant names so they can be imported individually. if (sealedVariants != null) { for (let variant in sealedVariants) { let variantName = variant.name.name; this.#current.declare(variantName, false, variant, this.#modulePath); this.#symbols.record(variant, this.#current.getLocal(variantName) as Symbol); if (exported) { this.#exports[variantName] = this.#current.getLocal(variantName) as Symbol; } } } } case InterfaceDeclaration {name, exported}: { this.#current.declare(name.name, false, stmt, this.#modulePath); this.#symbols.record(stmt, this.#current.getLocal(name.name) as Symbol); if (exported) { this.#exports[name.name] = this.#current.getLocal(name.name) as Symbol; } } case EnumDeclaration {name, exported}: { this.#current.declare(name.name, false, stmt, this.#modulePath); this.#symbols.record(stmt, this.#current.getLocal(name.name) as Symbol); if (exported) { this.#exports[name.name] = this.#current.getLocal(name.name) as Symbol; } } case MixinDeclaration {name, exported}: { this.#current.declare(name.name, false, stmt, this.#modulePath); this.#symbols.record(stmt, this.#current.getLocal(name.name) as Symbol); if (exported) { this.#exports[name.name] = this.#current.getLocal(name.name) as Symbol; } } case TypeAliasDeclaration {name, exported}: { let ok = this.#current.declare(name.name, false, stmt, this.#modulePath); if (!ok) { this.#duplicateDeclarations.push(new UnresolvedName(name.name, stmt)); } this.#symbols.record(stmt, this.#current.getLocal(name.name) as Symbol); if (exported) { this.#exports[name.name] = this.#current.getLocal(name.name) as Symbol; } } case VariableDeclaration {kind, pattern, typeAnnotation, init, exported}: { // Pre-declare all function bindings for forward references / mutual recursion. match (pattern) { case IdentifierPattern {name} as pat: { match (init) { case FunctionExpression as fe: { this.#current.declare(name, kind == "var", pat, this.#modulePath); let sym = this.#current.getLocal(name) as Symbol; sym.isFunctionBinding = true; var full = typeAnnotation != null; if (!full) { full = fe.returnType != null; for (let p in fe.params) { if (p.typeAnnotation == null && !p.isThisParam && p.defaultValue == null) { full = false; } } } sym.hasFullSignature = full; this.#symbols.record(pat, sym); if (exported) { this.#exports[name] = sym; } } case _: {} } } case _: {} } } case FunctionDeclaration {name as namePat, func, exported}: { // Same predeclaration as an annotated `let f = () => ...`, which is // what makes forward references and mutual recursion work. this.#current.declare(namePat.name, false, namePat, this.#modulePath); let sym = this.#current.getLocal(namePat.name) as Symbol; var full = func.returnType != null; for (let p in func.params) { if (p.typeAnnotation == null && !p.isThisParam && p.defaultValue == null) { full = false; } } if (sym.isFunctionBinding) { sym.hasFullSignature = sym.hasFullSignature && full; } else { sym.isFunctionBinding = true; sym.hasFullSignature = full; } this.#symbols.record(namePat, sym); if (exported) { this.#exports[namePat.name] = sym; } } case DeclareFunction {name, exported}: { this.#current.declare(name.name, false, stmt, this.#modulePath); let sym = this.#current.getLocal(name.name) as Symbol; this.#symbols.record(stmt, sym); if (exported) { this.#exports[name.name] = sym; } } case SymbolDeclaration {name, exported}: { // TODO: declare() then record() is such a common pattern that we // should probably unify it into a helper method like // `declareAndRecord(name, stmt)`. this.#current.declare(name.name, false, stmt, this.#modulePath); let sym = this.#current.getLocal(name.name) as Symbol; this.#symbols.record(stmt, sym); if (exported) { this.#exports[name.name] = sym; } } case _: {} } } /** Process a single statement, creating nested scopes as needed. */ #processStatement(stmt: Statement): void { match (stmt) { case ShieldedStatement {body}: { this.#processNode(body); } case VariableDeclaration {kind, pattern, typeAnnotation, init, exported}: { // Process the initializer first (before declaring the name, // so the name isn't visible in its own initializer). this.#processExpression(init); // Process the type annotation for type reference recording. if (typeAnnotation != null) { this.#processTypeAnnotation(typeAnnotation); } // Declare the variable name(s). match (pattern) { case IdentifierPattern {name} as pat: { // May already be declared by predeclare (annotated functions). if (!this.#current.has(name)) { this.#current.declare(name, kind == "var", pat, this.#modulePath); let sym = this.#current.getLocal(name) as Symbol; this.#symbols.record(pat, sym); this.#allVariables.push(sym); if (exported) { this.#exports[name] = sym; } } else { // Predeclared by this statement, or declared before it, which // the checker reports once this pattern resolves to that // symbol (`bindPattern`): left unresolved, it reached codegen. let sym = this.#current.getLocal(name) as Symbol; this.#symbols.record(pat, sym); if (sym.declaration === pat) { this.#allVariables.push(sym); } } } case _: { this.#declarePattern(pattern, kind, stmt); } } } case UsingStatement {pattern, typeAnnotation, init}: { // Same order as a `let`: the initializer is processed before the // name is declared, so the name is not visible in its own // initializer. The unbound form declares nothing. this.#processExpression(init); if (typeAnnotation != null) { this.#processTypeAnnotation(typeAnnotation); } if (pattern != null) { match (pattern) { case IdentifierPattern {name} as ident: { this.#current.declare(name, false, ident, this.#modulePath); let sym = this.#current.getLocal(name) as Symbol; this.#symbols.record(ident, sym); this.#allVariables.push(sym); } case _: { this.#declarePattern(pattern, "let", stmt); } } } } case FunctionDeclaration {name as namePat, func}: { // The name was already bound by #predeclare, so the body can see // it (recursion) and so can earlier statements (forward refs). this.#processExpression(func as Expression); let sym = this.#current.getLocal(namePat.name) as Symbol; if (sym.declaration === namePat) { this.#allVariables.push(sym); } } case ExpressionStatement {expression}: { this.#processExpression(expression); } case BlockStatement {body}: { this.#enterScope(ScopeKind.Block); this.#processStatements(body); this.#exitScope(); } case IfStatement {test, consequent, alternate}: { if (let LetPatternCondition {pattern, init} = test) { this.#processExpression(init); this.#enterScope(ScopeKind.Block); this.#declarePattern(pattern, "let", test); this.#processStatement(consequent); this.#exitScope(); if (alternate != null) { this.#enterScope(ScopeKind.Block); this.#processStatement(alternate); this.#exitScope(); } } else { this.#processNode(test); this.#processStatement(consequent); if (alternate != null) { this.#processStatement(alternate); } } } // A loop's invariants hold before each test of its condition, so // they see what the condition sees: a `for` loop's own variable, // and nothing the condition or a `for`-in pattern binds. case WhileStatement {test, body, invariants}: { if (let LetPatternCondition {pattern, init} = test) { this.#processExpression(init); this.#processLoopInvariants(invariants); this.#enterScope(ScopeKind.Block); this.#declarePattern(pattern, "let", test); this.#processStatement(body); this.#exitScope(); } else { this.#processNode(test); this.#processLoopInvariants(invariants); this.#processStatement(body); } } case ForStatement {init, test, update, body, invariants}: { this.#enterScope(ScopeKind.Block); if (init != null) { this.#processNode(init); } if (test != null) { this.#processExpression(test); } if (update != null) { this.#processExpression(update); } this.#processLoopInvariants(invariants); this.#processStatement(body); this.#exitScope(); } case ForInStatement {pattern, iterable, body, isAwait, invariants}: { if (isAwait) { // A `for await` steps with futures of options. this.#imply(WellKnown.AsyncIterableInterface); this.#imply(WellKnown.AsyncIteratorInterface); this.#imply(WellKnown.OptionAlias); this.#imply(WellKnown.FutureClass); } this.#imply(WellKnown.IterableInterface); this.#imply(WellKnown.IteratorInterface); this.#processExpression(iterable); this.#processLoopInvariants(invariants); this.#enterScope(ScopeKind.Block); this.#declarePattern(pattern, "let", stmt); this.#processStatement(body); this.#exitScope(); } case ReturnStatement {argument}: { if (argument != null) { this.#processExpression(argument); } } case YieldStatement {argument}: { this.#processExpression(argument); } case ClassDeclaration { name, typeParameters, caseParams, superClass, mixins, implementsList, body, sealedVariants, onType, isResource}: { // A case class, and a sealed class's variants, are hash keys // without an implements clause. if (caseParams != null || sealedVariants != null) { this.#imply(WellKnown.HashableInterface); this.#imply(WellKnown.EquatableInterface); } // A resource class is only ever held through its handles. if (isResource) { this.#imply(WellKnown.OwnAlias); this.#imply(WellKnown.BorrowAlias); } // Class body gets its own scope for `this`, type params, members. this.#enterScope(ScopeKind.Class); if (typeParameters != null) { this.#declareTypeParameters(typeParameters); } if (onType != null) { this.#processTypeAnnotation(onType); } // Process superclass and interface type annotations. if (superClass != null) { this.#processTypeAnnotation(superClass); } if (mixins != null) { for (let mixin in mixins) { this.#processTypeAnnotation(mixin); } } if (implementsList != null) { for (let impl in implementsList) { this.#processTypeAnnotation(impl); } } // Process case class parameter type annotations and default values. if (caseParams != null) { for (let param in caseParams) { this.#processTypeAnnotation(param.typeAnnotation); if (param.defaultValue != null) { this.#processExpression(param.defaultValue as Expression); } } } // Process sealed variant parameter type annotations and default values. if (sealedVariants != null) { for (let variant in sealedVariants) { if (variant.params != null) { for (let param in variant.params as GrowableArray) { this.#processTypeAnnotation(param.typeAnnotation); if (param.defaultValue != null) { this.#processExpression(param.defaultValue as Expression); } } } } } this.#processClassBody(body); this.#exitScope(); } case InterfaceDeclaration {typeParameters, extendsList, body}: { this.#enterScope(ScopeKind.Class); if (typeParameters != null) { this.#declareTypeParameters(typeParameters); } if (extendsList != null) { for (let extnd in extendsList) { this.#processTypeAnnotation(extnd); } } // Process interface body for method/property type annotations. this.#processInterfaceBody(body); this.#exitScope(); } case MixinDeclaration {typeParameters, on, mixins, body, decoratorSubject}: { this.#enterScope(ScopeKind.Class); if (typeParameters != null) { this.#declareTypeParameters(typeParameters); } // A decorator's subject is a placeholder, not a binding: only its // type annotation names anything. The body does get one implicit // binding, `context`, declared on the subject's name node so the // checker can find and type it (the name, getter and setter of // the decorated field). if (decoratorSubject != null) { if (decoratorSubject.typeAnnotation != null) { this.#processTypeAnnotation(decoratorSubject.typeAnnotation as TypeAnnotation); } let subjectName = decoratorSubject.name; if (subjectName is Identifier) { this.#current.declare("context", false, subjectName, this.#modulePath); let contextSym = this.#current.getLocal("context"); if (contextSym != null) { contextSym.isDecoratorContext = true; this.#symbols.record(subjectName, contextSym); } } } // Traverse `with` clause so mixin names are linked in the ReferenceMap. if (on != null) { this.#processTypeAnnotation(on); } if (mixins != null) { for (let mixin in mixins) { this.#processTypeAnnotation(mixin); } } this.#processClassBody(body); this.#exitScope(); } case ImportDeclaration {moduleSpecifier, imports} as idDecl: { this.#allImportDeclarations.push(idDecl); // Declare imported names into the current scope. // The actual bindings come from the imported module's exports. // // An import whose specifier has not been typed yet (the parser // leaves it empty) can never be wired to a module, so its names // stay undeclared and read as ordinary unresolved identifiers. if (moduleSpecifier.value != "") { for (let spec in imports) { let localName = spec.local.name; // Imports go in both namespaces (we don't know yet if it's // a type or value — that's resolved during import wiring). this.#current.declare(localName, false, spec, this.#modulePath); this.#symbols.record(spec, this.#current.getLocal(localName) as Symbol); } } } case BreakStatement: {} case ContinueStatement: {} case EnumDeclaration {members}: { // A string enum is backed by `String`. for (let member in members) { if (member.initializer is StringLiteral) { this.#imply(WellKnown.StringClass); } } } case TypeAliasDeclaration {typeParameters, typeAnnotation}: { this.#enterScope(ScopeKind.Block); if (typeParameters != null) { this.#declareTypeParameters(typeParameters); } if (typeAnnotation != null) { this.#processTypeAnnotation(typeAnnotation); } this.#exitScope(); } case ExportAllDeclaration: {} case ExportFromDeclaration: {} case DeclareFunction {typeParameters, params, returnType}: { this.#enterScope(ScopeKind.Function); if (typeParameters != null) { this.#declareTypeParameters(typeParameters); } for (let param in params) { if (param.typeAnnotation != null) { this.#processTypeAnnotation(param.typeAnnotation); } } this.#processTypeAnnotation(returnType); this.#exitScope(); } case SymbolDeclaration: {} } } /** * Process an expression, recording identifier references. */ #processExpression(expr: Expression): void { match (expr) { case Identifier {name}: { if (name == "") { return; } let info = this.#current.resolve(name); if (info == null) { this.#unresolvedNames.push(new UnresolvedName(name, expr)); } else { this.#symbols.record(expr, info); this.#isRead[info.id] = true; } } case FunctionExpression {typeParameters, params, returnType, body, isAsync, contracts}: { if (isAsync) { this.#imply(WellKnown.FutureClass); } // `old` is the entry-value operator only directly in an // `ensures` condition, not in a function written inside one. let inEnsures = this.#inEnsures; this.#inEnsures = false; this.#enterScope(ScopeKind.Function); if (typeParameters != null) { this.#declareTypeParameters(typeParameters); } for (let param in params) { this.#declareParameter(param); if (param.typeAnnotation != null) { this.#processTypeAnnotation(param.typeAnnotation); } let {defaultValue} = param; if (defaultValue != null) { this.#processExpression(defaultValue); } } if (returnType != null) { this.#processTypeAnnotation(returnType); } this.#processFunctionContracts(contracts); this.#processNode(body); this.#exitScope(); this.#inEnsures = inEnsures; } case BinaryExpression {left, right}: { this.#processExpression(left); this.#processExpression(right); } case UnaryExpression {argument}: { this.#processExpression(argument); } case AssignmentExpression {left, value, operator}: { match (left) { case Identifier as leftIdent: { let info = this.#current.resolve(leftIdent.name); if (info == null) { this.#unresolvedNames.push(new UnresolvedName(leftIdent.name, leftIdent)); } else { this.#symbols.record(leftIdent, info); this.#isWritten[info.id] = true; if (operator != null && operator != "=") { this.#isRead[info.id] = true; } } } case _: { this.#processExpression(left); } } this.#processExpression(value); } case CallExpression {callee, args, typeArguments}: { // `old(e)` in an `ensures` condition is `e`'s value on entry, // whatever else `old` names there, so its callee resolves to // nothing. if (!(this.#inEnsures && isOldCallee(callee))) { this.#processExpression(callee); } if (typeArguments != null) { for (let typeArgument in typeArguments) { this.#processTypeAnnotation(typeArgument); } } for (let arg in args) { this.#processExpression(arg); } } case NewExpression {callee, typeArguments, args, constructorName}: { let info = this.#current.resolve(callee.name); if (info == null) { this.#unresolvedNames.push(new UnresolvedName(callee.name, callee)); } else { this.#symbols.record(callee, info); this.#isRead[info.id] = true; } if (typeArguments != null) { for (let typeArgument in typeArguments) { this.#processTypeAnnotation(typeArgument); } } if (constructorName != null) { if (let SymbolPropertyName {symbolRef} = constructorName) { this.#processExpression(symbolRef); } else {} } for (let arg in args) { this.#processExpression(arg); } } case MemberExpression {object, isSymbolAccess, symbolPath}: { this.#processExpression(object); // property is resolved against the object's type during checking. // A SYMBOL key is different: `x.:sym` names a symbol binding, and // `x.:Iface.sym` names the interface that declares it. Resolving // that path is what makes an unexported symbol unreachable — // without it, `x.:sym` compiled in a module that declares no `sym` // at all, so "don't export the symbol" controlled nothing. if (isSymbolAccess && symbolPath != null) { this.#processExpression(symbolPath); } } case IndexExpression {object, index}: { this.#processExpression(object); this.#processExpression(index); } case ArrayLiteral {elements}: { // Immutable unless the context wants mutable elements. this.#imply(WellKnown.ImmutableArrayClass); this.#imply(WellKnown.FixedArrayClass); for (let element in elements) { this.#processExpression(element); } } case RecordLiteral {properties}: { for (let property in properties) { this.#processRecordProperty(property); } } case TupleLiteral {elements}: { for (let element in elements) { this.#processExpression(element); } } case MapLiteral {entries}: { this.#imply(WellKnown.HashMapClass); for (let entry in entries) { this.#processExpression(entry.key); this.#processExpression(entry.value); } } case TemplateLiteral {expressions}: { this.#imply(WellKnown.StringClass); for (let expression in expressions) { this.#processExpression(expression); } } case TaggedTemplateExpression {tag, quasi}: { // A primitive interpolation may be boxed for the tag. this.#imply(WellKnown.BoxClass); this.#processExpression(tag); this.#processExpression(quasi); } case AsExpression {expression, typeAnnotation}: { this.#processExpression(expression); this.#processTypeAnnotation(typeAnnotation); } case IsExpression {expression, typeAnnotation}: { this.#processExpression(expression); this.#processTypeAnnotation(typeAnnotation); } case MatchExpression {discriminant, cases}: { this.#processExpression(discriminant); for (let matchCase in cases) { this.#processMatchCase(matchCase); } } case IfExpression {test, consequent, alternate}: { if (let LetPatternCondition {pattern, init} = test) { this.#processExpression(init); this.#enterScope(ScopeKind.Block); this.#declarePattern(pattern, "let", test); this.#processNode(consequent); this.#exitScope(); if (alternate != null) { this.#enterScope(ScopeKind.Block); this.#processNode(alternate); this.#exitScope(); } } else { this.#processNode(test); this.#processNode(consequent); if (alternate != null) { this.#processNode(alternate); } } } case ThrowExpression {argument}: { this.#imply(WellKnown.ErrorClass); this.#processExpression(argument); } case AwaitExpression {argument}: { this.#imply(WellKnown.FutureClass); this.#imply(WellKnown.AwaitedAlias); this.#processExpression(argument); } case TryExpression {body, handler, cancelBlock, finalizer}: { this.#processNode(body); if (handler != null) { this.#enterScope(ScopeKind.Block); if (handler.param != null) { // The binding is the standard library's `Error`. this.#imply(WellKnown.ErrorClass); let param = handler.param as Identifier; this.#current.declare(param.name, false, param, this.#modulePath); this.#symbols.record(param, this.#current.getLocal(param.name) as Symbol); } this.#processNode(handler.body); this.#exitScope(); } if (cancelBlock != null) { this.#processNode(cancelBlock); } if (finalizer != null) { this.#processNode(finalizer); } } case PipelineExpression {left, right}: { this.#processExpression(left); this.#processExpression(right); } case RangeExpression {start, end}: { this.#imply(if (start != null && end != null) WellKnown.BoundedRangeClass else if (start != null) WellKnown.FromRangeClass else if (end != null) WellKnown.ToRangeClass else WellKnown.FullRangeClass); // The other type a range's bounds may have. this.#imply(WellKnown.StringIndexAlias); if (start != null) { this.#processExpression(start); } if (end != null) { this.#processExpression(end); } } case ThisExpression: {} case SuperExpression: {} case NumberLiteral {raw}: { if (isBigIntLiteralRaw(raw)) { this.#imply(WellKnown.BigIntClass); } } case StringLiteral: { this.#imply(WellKnown.StringClass); } case BooleanLiteral: {} case NullLiteral: {} case PipePlaceholder: {} } } /** * Process a generic AST node (could be expression, statement, or other). */ #processNode(node: Node): void { match (node) { case Expression: { this.#processExpression(node); } case Statement: { this.#processStatement(node); } case LetPatternCondition {init}: { this.#processExpression(init); // The pattern introduces bindings visible in the then-branch. // This is handled by the parent if/while processing. } case _: {} } } /** * Record the references in a symbol-keyed member's name. * * `[sym]` and `[Owner.sym]` are ordinary expressions, and the checker * checks them as such, so their names need references like any other. * Class, mixin and interface bodies all come through here. */ /** * Records the references a member's decorators make: the name a user * decorator is applied by, and anything its arguments mention. A * builtin decorator (`@intrinsic`, `@external`, `@pure`) is not a name * in any scope, so only its arguments are walked. */ #processDecorators(decorators: GrowableArray): void { for (let dec in decorators) { if (dec.path.length > 0 && !isBuiltinDecoratorName(dec.path[0].name)) { this.#processExpression(dec.path[0] as Expression); } for (let arg in dec.args) { this.#processExpression(arg); } } } #processSymbolKeyedName(member: Node): void { var nameNode: Node | null = null; match (member) { case FieldDefinition as fd: { nameNode = fd.name; this.#processDecorators(fd.decorators); } case MethodDefinition as md: { nameNode = md.name; this.#processDecorators(md.decorators); } case AccessorDeclaration as acc: { nameNode = acc.name; this.#processDecorators(acc.decorators); } case MethodSignature as ms: { nameNode = ms.name; } case _: {} } // `if (let ...)` against a null value traps rather than not matching // (#663), so null is ruled out first. if (nameNode == null) { return; } if (let SymbolPropertyName {symbolRef} = nameNode as Node) { this.#processExpression(symbolRef); } } /** * Process class body members. */ #processClassBody(members: GrowableArray): void { for (let member in members) { this.#processSymbolKeyedName(member); match (member) { case MethodDefinition as md: { if (md.isAsync) { this.#imply(WellKnown.FutureClass); } // Process method parameter and return type annotations. this.#enterScope(ScopeKind.Function); if (md.typeParameters != null) { this.#declareTypeParameters(md.typeParameters); } // A declared receiver gets a symbol of its own, recorded on its // annotation, for the checker's release bookkeeping: a // consuming method owns `this` the way it owns an `Own` // parameter. Nothing resolves `this` to it, so it declares no // name. let {receiver} = md; if (receiver != null) { this.#symbols.record(receiver as Node, new Symbol("this", receiver as Node, this.#modulePath, false, this.#symbolIdGenerator.next())); } for (let param in md.params) { this.#declareParameter(param); if (param.typeAnnotation != null) { this.#processTypeAnnotation(param.typeAnnotation); } let {defaultValue} = param; if (defaultValue != null) { this.#processExpression(defaultValue); } } if (md.returnType != null) { this.#processTypeAnnotation(md.returnType); } this.#processFunctionContracts(md.contracts); let {initializerList} = md; if (initializerList != null) { for (let init in initializerList) { if (let FieldInitializer {value} = init) { this.#processExpression(value); } } } if (md.superInitializer != null) { if (let SuperInitializer {args, constructorName} = md.superInitializer) { if (constructorName != null) { if (let SymbolPropertyName {symbolRef} = constructorName) { this.#processExpression(symbolRef); } else {} } for (let arg in args) { this.#processExpression(arg); } } else {} } if (md.body != null) { this.#processNode(md.body); } this.#exitScope(); } case AccessorDeclaration as acc: { // Process accessor type annotation. this.#processTypeAnnotation(acc.typeAnnotation); if (acc.getter != null) { this.#enterScope(ScopeKind.Function); this.#processNode(acc.getter); this.#exitScope(); } if (acc.setter != null) { let setter = acc.setter as SetterInfo; let {param} = setter; this.#enterScope(ScopeKind.Function); this.#current.declare(param.name, false, param, this.#modulePath); this.#symbols.record(param, this.#current.getLocal(param.name) as Symbol); this.#processNode(setter.body); this.#exitScope(); } } case FieldDefinition {typeAnnotation, value}: { if (typeAnnotation != null) { this.#processTypeAnnotation(typeAnnotation); } if (value != null) { this.#processExpression(value); } } case FieldInitializer {value}: { this.#processExpression(value); } case _: {} } } } /** * Process interface body members for type annotation references. */ #processInterfaceBody(members: GrowableArray): void { for (let member in members) { this.#processSymbolKeyedName(member); match (member) { case MethodSignature as ms: { this.#enterScope(ScopeKind.Function); let {typeParameters} = ms; if (typeParameters != null) { let tps = typeParameters; this.#declareTypeParameters(tps); } for (let param in ms.params) { if (param.typeAnnotation != null) { this.#processTypeAnnotation(param.typeAnnotation); } } if (ms.returnType != null) { this.#processTypeAnnotation(ms.returnType); } this.#exitScope(); } case AccessorSignature as as_: { this.#processTypeAnnotation(as_.typeAnnotation); } case PropertySignature as ps: { this.#processTypeAnnotation(ps.typeAnnotation); } case FieldDefinition {typeAnnotation, value}: { if (typeAnnotation != null) { this.#processTypeAnnotation(typeAnnotation); } if (value != null) { this.#processExpression(value); } } case MethodDefinition as md: { // An interface constructor: a function body with parameters, // scoped like a class method's. The interface's type // parameters are in the enclosing scope; a constructor that // restates them with bounds declares its own. this.#enterScope(ScopeKind.Function); if (md.typeParameters != null) { this.#declareTypeParameters(md.typeParameters); } for (let param in md.params) { this.#declareParameter(param); if (param.typeAnnotation != null) { this.#processTypeAnnotation(param.typeAnnotation); } let {defaultValue} = param; if (defaultValue != null) { this.#processExpression(defaultValue); } } if (md.returnType != null) { this.#processTypeAnnotation(md.returnType); } if (md.body != null) { this.#processNode(md.body); } this.#exitScope(); } case _: {} } } } /** * The names a function's clauses mention. The caller has declared the * parameters, so a `requires` condition sees what the body sees on * entry. An `ensures` condition also sees `result`: each clause gets * a scope holding that one name, declared on the clause, so the * checker finds the symbol through the clause and gives it the * function's return type. See docs/design/contracts.md. */ #processFunctionContracts(contracts: GrowableArray | null): void { if (contracts == null) { return; } for (let clause in contracts) { if (clause.kind != ContractKind.Ensures) { this.#processExpression(clause.condition); continue; } this.#enterScope(ScopeKind.Block); this.#current.declare('result', false, clause, this.#modulePath); this.#symbols.record(clause, this.#current.getLocal('result') as Symbol); this.#inEnsures = true; this.#processExpression(clause.condition); this.#inEnsures = false; this.#exitScope(); } } #processLoopInvariants(invariants: GrowableArray | null): void { if (invariants == null) { return; } for (let clause in invariants) { this.#processExpression(clause.condition); } } /** * Process a match case (pattern + optional guard + body). */ #processMatchCase(mc: MatchCase): void { this.#enterScope(ScopeKind.Block); this.#declarePatternBindings(mc.pattern); if (mc.guard != null) { this.#processExpression(mc.guard); } this.#processNode(mc.body); this.#exitScope(); } /** * Declare bindings introduced by a pattern (destructuring, match, for-in). */ #declarePattern(pat: Pattern, kind: String, declaration: Node): void { match (pat) { case BindingPattern as bp: { this.#declarePattern(bp.pattern, bp.kind, declaration); } case IdentifierPattern {name} as ip: { // `_` is a wildcard, not a binding. The checker skips it too, so // declaring a symbol here would leave it forever untyped. if (name == "_") { return; } // Use the leaf IdentifierPattern as declaration (not the parent // statement). Each binding gets a unique declaration node, which // the checker uses as the key for storing per-binding types. this.#current.declare(name, kind == "var", ip, this.#modulePath); let sym = this.#current.getLocal(name) as Symbol; this.#symbols.record(ip, sym); this.#allVariables.push(sym); } case RecordPattern {properties, rest}: { for (let prop in properties) { this.#declarePatternNode(prop.value, kind, declaration); } if (rest != null) { this.#declarePatternNode(rest, kind, declaration); } } case TuplePattern {elements}: { for (let element in elements) { if (element != null) { this.#declarePatternNode(element, kind, declaration); } } } case ArrayPattern {elements}: { // An array pattern also destructures an iterator. this.#imply(WellKnown.IteratorInterface); for (let element in elements) { if (element != null) { this.#declarePatternNode(element, kind, declaration); } } } case RestPattern {pattern}: { this.#declarePatternNode(pattern, kind, declaration); } case AsPattern {pattern, name}: { // Use the `name` Identifier as the declaration for the alias binding. this.#current.declare(name.name, false, name, this.#modulePath); this.#symbols.record(name, this.#current.getLocal(name.name) as Symbol); this.#declarePatternNode(pattern, kind, declaration); } case ClassPattern {name, typeArguments, properties}: { let info = this.#current.resolve(name.name); if (info != null) { this.#symbols.record(name, info); this.#isRead[info.id] = true; } if (typeArguments != null) { for (let arg in typeArguments) { this.#processTypeAnnotation(arg); } } for (let prop in properties) { this.#declarePatternNode(prop.value, kind, declaration); } } case LogicalPattern {left, right}: { this.#declarePatternNode(left, kind, declaration); this.#declarePatternNode(right, kind, declaration); } case AssignmentPattern {left}: { this.#declarePatternNode(left, kind, declaration); } case LiteralPattern {value}: { // Literal patterns introduce no bindings, but may imply stdlib types (e.g., BigInt). this.#processExpression(value); } case AbsencePattern: { // Absence tests introduce no bindings. } } } #declarePatternBindings(node: Node): void { match (node) { case Pattern: { this.#declarePattern(node, "let", node); } case Identifier as ident: { if (ident.name != "_") { let resolved = this.#current.resolve(ident.name); var isTypePattern = false; if (resolved != null) { if (resolved.isType()) { isTypePattern = true; } } if (isTypePattern) { let s = resolved as Symbol; this.#symbols.record(ident, s); this.#isRead[s.id] = true; } else { this.#current.declare(ident.name, false, ident, this.#modulePath); let sym = this.#current.getLocal(ident.name) as Symbol; this.#symbols.record(ident, sym); this.#allVariables.push(sym); } } } case LiteralPattern {value}: { this.#processExpression(value); } case Expression as expr: { this.#processExpression(expr); } case _: {} } } #declarePatternNode(node: Node, kind: String, declaration: Node): void { match (node) { case Pattern: { this.#declarePattern(node, kind, declaration); } case Identifier as ident: { if (ident.name != "_") { let resolved = this.#current.resolve(ident.name); var isTypePattern = false; if (resolved != null) { if (resolved.isType()) { isTypePattern = true; } } if (isTypePattern) { let s = resolved as Symbol; this.#symbols.record(ident, s); this.#isRead[s.id] = true; } else { this.#current.declare(ident.name, kind == "var", ident, this.#modulePath); let sym = this.#current.getLocal(ident.name) as Symbol; this.#symbols.record(ident, sym); this.#allVariables.push(sym); } } } case LiteralPattern {value}: { this.#processExpression(value); } case Expression as expr: { this.#processExpression(expr); } case _: {} } } #declareParameter(param: Parameter): void { this.#current.declare(param.name.name, false, param, this.#modulePath); let sym = this.#current.getLocal(param.name.name) as Symbol; this.#symbols.record(param, sym); this.#symbols.record(param.name, sym); // Bind Identifier as well for LSP Hover this.#allVariables.push(sym); // For destructured params, also declare the pattern bindings (x, y, etc.). let {pattern} = param; if (pattern != null) { this.#declarePattern(pattern, "let", param); } } #declareTypeParameters(tps: GrowableArray): void { for (let typeParam in tps) { this.#current.declare(typeParam.name, false, typeParam, this.#modulePath); // Record each TypeParameter in the declarations map so the checker can // look up its Symbol via model.resolveDeclaration(typeParam) and store // the TypeParameterType by identity (Symbol.id) rather than by name. let si = this.#current.getLocal(typeParam.name); if (si != null) { this.#symbols.record(typeParam, si); } } // After all params are in scope, resolve constraints/defaults. for (let typeParam in tps) { if (typeParam.constraint != null) { this.#processTypeAnnotation(typeParam.constraint); } if (typeParam.defaultType != null) { this.#processTypeAnnotation(typeParam.defaultType); } } } /** * Walk a type annotation and record type name references. */ #processTypeAnnotation(ann: TypeAnnotation): void { match (ann) { case NamedTypeAnnotation {name, typeArguments}: { if (name != "") { let info = this.#current.resolve(name); if (info != null) { this.#symbols.record(ann, info); this.#isRead[info.id] = true; } else { this.#unresolvedNames.push(new UnresolvedName(name, ann)); } } if (typeArguments != null) { for (let arg in typeArguments) { this.#processTypeAnnotation(arg); } } } case UnionTypeAnnotation {types}: { for (let type in types) { this.#processTypeAnnotation(type); } } case NullableTypeAnnotation {typeAnnotation}: { this.#processTypeAnnotation(typeAnnotation); } case FunctionTypeAnnotation {params, returnType}: { for (let param in params) { this.#processTypeAnnotation(param); } this.#processTypeAnnotation(returnType); } case RecordTypeAnnotation {properties, spreads}: { for (let property in properties) { this.#processTypeAnnotation(property.typeAnnotation); } if (spreads != null) { for (let spread in spreads) { this.#processTypeAnnotation(spread); } } } case TupleTypeAnnotation {elementTypes}: { for (let elementType in elementTypes) { this.#processTypeAnnotation(elementType); } } case InlineTypeAnnotation {typeAnnotation}: { this.#processTypeAnnotation(typeAnnotation); } case _: {} } } #processRecordProperty(node: Node): void { match (node) { case PropertyAssignment {value}: { this.#processExpression(value); } case SpreadElement {argument}: { this.#processExpression(argument); } case _: {} } } #enterScope(kind: ScopeKind): void { this.#current = new Scope(kind, this.#current); } #exitScope(): void { let parent = this.#current.parent; if (parent != null) { this.#current = parent; } } }