From 78178117d0c405d7871a4061a473068229254ddc Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Wed, 8 Apr 2026 10:46:00 -0700 Subject: [PATCH] Replace most ID usage with pointers --- internal/ast/utilities.go | 17 ++- internal/checker/checker.go | 108 +++++++++--------- internal/checker/emitresolver.go | 12 +- internal/checker/flow.go | 4 +- internal/checker/inference.go | 10 +- internal/checker/jsx.go | 2 +- internal/checker/nodebuilder.go | 4 +- internal/checker/nodebuilderimpl.go | 58 +++++----- internal/checker/nodebuilderscopes.go | 9 +- internal/checker/relater.go | 2 +- internal/checker/symbolaccessibility.go | 13 +-- internal/checker/types.go | 4 +- internal/ls/callhierarchy.go | 8 +- internal/ls/completions.go | 59 ++++------ internal/printer/namegenerator.go | 11 +- .../transformers/declarations/transform.go | 23 ++-- 16 files changed, 160 insertions(+), 184 deletions(-) diff --git a/internal/ast/utilities.go b/internal/ast/utilities.go index 686d0932109..831aef8f2bf 100644 --- a/internal/ast/utilities.go +++ b/internal/ast/utilities.go @@ -2337,7 +2337,7 @@ func GetModuleInstanceState(node *Node) ModuleInstanceState { return getModuleInstanceState(node, nil, nil) } -func getModuleInstanceState(node *Node, ancestors []*Node, visited map[NodeId]ModuleInstanceState) ModuleInstanceState { +func getModuleInstanceState(node *Node, ancestors []*Node, visited map[*Node]ModuleInstanceState) ModuleInstanceState { module := node.AsModuleDeclaration() if module.Body != nil { return getModuleInstanceStateCached(module.Body, pushAncestor(ancestors, node), visited) @@ -2346,24 +2346,23 @@ func getModuleInstanceState(node *Node, ancestors []*Node, visited map[NodeId]Mo } } -func getModuleInstanceStateCached(node *Node, ancestors []*Node, visited map[NodeId]ModuleInstanceState) ModuleInstanceState { +func getModuleInstanceStateCached(node *Node, ancestors []*Node, visited map[*Node]ModuleInstanceState) ModuleInstanceState { if visited == nil { - visited = make(map[NodeId]ModuleInstanceState) + visited = make(map[*Node]ModuleInstanceState) } - nodeId := GetNodeId(node) - if cached, ok := visited[nodeId]; ok { + if cached, ok := visited[node]; ok { if cached != ModuleInstanceStateUnknown { return cached } return ModuleInstanceStateNonInstantiated } - visited[nodeId] = ModuleInstanceStateUnknown + visited[node] = ModuleInstanceStateUnknown result := getModuleInstanceStateWorker(node, ancestors, visited) - visited[nodeId] = result + visited[node] = result return result } -func getModuleInstanceStateWorker(node *Node, ancestors []*Node, visited map[NodeId]ModuleInstanceState) ModuleInstanceState { +func getModuleInstanceStateWorker(node *Node, ancestors []*Node, visited map[*Node]ModuleInstanceState) ModuleInstanceState { // A module is uninstantiated if it contains only switch node.Kind { case KindInterfaceDeclaration, KindTypeAliasDeclaration, KindJSTypeAliasDeclaration: @@ -2417,7 +2416,7 @@ func getModuleInstanceStateWorker(node *Node, ancestors []*Node, visited map[Nod return ModuleInstanceStateInstantiated } -func getModuleInstanceStateForAliasTarget(node *Node, ancestors []*Node, visited map[NodeId]ModuleInstanceState) ModuleInstanceState { +func getModuleInstanceStateForAliasTarget(node *Node, ancestors []*Node, visited map[*Node]ModuleInstanceState) ModuleInstanceState { name := node.PropertyNameOrName() if name.Kind != KindIdentifier { // Skip for invalid syntax like this: export { "x" } diff --git a/internal/checker/checker.go b/internal/checker/checker.go index 744e6dcbe2f..9b23b5fc69b 100644 --- a/internal/checker/checker.go +++ b/internal/checker/checker.go @@ -107,8 +107,8 @@ type EnumLiteralKey struct { // EnumRelationKey type EnumRelationKey struct { - sourceId ast.SymbolId - targetId ast.SymbolId + source *ast.Symbol + target *ast.Symbol } // TypeCacheKind @@ -143,8 +143,8 @@ const ( // CachedTypeKey type CachedTypeKey struct { - kind CachedTypeKind - typeId TypeId + kind CachedTypeKind + t *Type } // NarrowedTypeKey @@ -159,10 +159,10 @@ type NarrowedTypeKey struct { // UnionOfUnionKey type UnionOfUnionKey struct { - id1 TypeId - id2 TypeId - r UnionReduction - a CacheHashKey + t1 *Type + t2 *Type + r UnionReduction + a CacheHashKey } // CachedSignatureKey @@ -190,50 +190,50 @@ type StringMappingKey struct { // AssignmentReducedKey type AssignmentReducedKey struct { - id1 TypeId - id2 TypeId + t1 *Type + t2 *Type } // DiscriminatedContextualTypeKey type DiscriminatedContextualTypeKey struct { - nodeId ast.NodeId - typeId TypeId + node *ast.Node + t *Type } // InstantiationExpressionKey type InstantiationExpressionKey struct { - nodeId ast.NodeId - typeId TypeId + node *ast.Node + t *Type } // SubstitutionTypeKey type SubstitutionTypeKey struct { - baseId TypeId - constraintId TypeId + base *Type + constraint *Type } // ReverseMappedTypeKey type ReverseMappedTypeKey struct { - sourceId TypeId - targetId TypeId - constraintId TypeId + source *Type + target *Type + constraint *Type } // IterationTypesKey type IterationTypesKey struct { - typeId TypeId - use IterationUse + t *Type + use IterationUse } // PropertiesTypesKey type PropertiesTypesKey struct { - typeId TypeId + t *Type include TypeFlags includeOrigin bool } @@ -6096,7 +6096,7 @@ func (c *Checker) getIterationTypesOfIterable(t *Type, use IterationUse, errorNo if IsTypeAny(t) { return IterationTypes{c.anyType, c.anyType, c.anyType} } - key := IterationTypesKey{typeId: t.id, use: use & IterationUseCacheFlags} + key := IterationTypesKey{t: t, use: use & IterationUseCacheFlags} // If we are reporting errors and encounter a cached `noIterationTypes`, we should ignore the cached value and continue as if nothing was cached. // In addition, we should not cache any new results for this call. noCache := false @@ -7911,7 +7911,7 @@ func (c *Checker) createArrayLiteralType(t *Type) *Type { if t.objectFlags&ObjectFlagsReference == 0 { return t } - key := CachedTypeKey{kind: CachedTypeKindArrayLiteralType, typeId: t.id} + key := CachedTypeKey{kind: CachedTypeKindArrayLiteralType, t: t} if cached, ok := c.cachedTypes[key]; ok { return cached } @@ -10284,7 +10284,7 @@ func (c *Checker) getInstantiationExpressionType(exprType *Type, node *ast.Node) if exprType == c.silentNeverType || c.isErrorType(exprType) || typeArguments == nil { return exprType } - key := InstantiationExpressionKey{nodeId: ast.GetNodeId(node), typeId: exprType.id} + key := InstantiationExpressionKey{node: node, t: exprType} if cached := c.instantiationExpressionTypes[key]; cached != nil { return cached } @@ -15148,7 +15148,7 @@ func isESMFormatImportImportingCommonjsFormatFile(usageMode core.ResolutionMode, func (c *Checker) getTypeWithSyntheticDefaultOnly(t *Type, symbol *ast.Symbol, originalSymbol *ast.Symbol, moduleSpecifier *ast.Node) *Type { hasDefaultOnly := c.isOnlyImportableAsDefault(moduleSpecifier, nil) if hasDefaultOnly && t != nil && !c.isErrorType(t) { - key := CachedTypeKey{kind: CachedTypeKindDefaultOnlyType, typeId: t.id} + key := CachedTypeKey{kind: CachedTypeKindDefaultOnlyType, t: t} if cached := c.cachedTypes[key]; cached != nil { return cached } @@ -15161,7 +15161,7 @@ func (c *Checker) getTypeWithSyntheticDefaultOnly(t *Type, symbol *ast.Symbol, o func (c *Checker) getTypeWithSyntheticDefaultImportType(t *Type, symbol *ast.Symbol, originalSymbol *ast.Symbol, moduleSpecifier *ast.Node) *Type { if t != nil && !c.isErrorType(t) { - key := CachedTypeKey{kind: CachedTypeKindSyntheticType, typeId: t.id} + key := CachedTypeKey{kind: CachedTypeKindSyntheticType, t: t} if cached := c.cachedTypes[key]; cached != nil { return cached } @@ -16782,7 +16782,7 @@ func (c *Checker) getConstraintOfDistributiveConditionalType(t *Type) *Type { // Please note: the distributive constraint is a kludge for emulating what a negated type could to do filter // a union - once negated types exist and are applied to the conditional false branch, this "constraint" // likely doesn't need to exist. - if d.root.isDistributive && c.cachedTypes[CachedTypeKey{kind: CachedTypeKindRestrictiveInstantiation, typeId: t.id}] != t { + if d.root.isDistributive && c.cachedTypes[CachedTypeKey{kind: CachedTypeKindRestrictiveInstantiation, t: t}] != t { constraint := c.getSimplifiedType(d.checkType, false /*writing*/) if constraint == d.checkType { constraint = c.getConstraintOfType(constraint) @@ -17803,7 +17803,7 @@ func (c *Checker) getWidenedType(t *Type) *Type { func (c *Checker) getWidenedTypeWithContext(t *Type, context *WideningContext) *Type { if t.objectFlags&ObjectFlagsRequiresWidening != 0 { if context == nil { - if cached := c.cachedTypes[CachedTypeKey{kind: CachedTypeKindWidened, typeId: t.id}]; cached != nil { + if cached := c.cachedTypes[CachedTypeKey{kind: CachedTypeKindWidened, t: t}]; cached != nil { return cached } } @@ -17834,7 +17834,7 @@ func (c *Checker) getWidenedTypeWithContext(t *Type, context *WideningContext) * result = c.createTypeReference(t.Target(), core.SameMap(c.getTypeArguments(t), c.getWidenedType)) } if result != nil && context == nil { - c.cachedTypes[CachedTypeKey{kind: CachedTypeKindWidened, typeId: t.id}] = result + c.cachedTypes[CachedTypeKey{kind: CachedTypeKindWidened, t: t}] = result } return core.OrElse(result, t) } @@ -21251,7 +21251,7 @@ func (c *Checker) getApparentTypeOfIntersectionType(t *Type, thisArgument *Type) } return d.resolvedApparentType } - key := CachedTypeKey{kind: CachedTypeKindApparentType, typeId: thisArgument.id} + key := CachedTypeKey{kind: CachedTypeKindApparentType, t: thisArgument} result := c.cachedTypes[key] if result == nil { result = c.getTypeWithThisArgument(t, thisArgument, true /*needApparentType*/) @@ -23857,7 +23857,7 @@ func (c *Checker) getPermissiveInstantiation(t *Type) *Type { if t.flags&(TypeFlagsPrimitive|TypeFlagsAnyOrUnknown|TypeFlagsNever) != 0 { return t } - key := CachedTypeKey{kind: CachedTypeKindPermissiveInstantiation, typeId: t.id} + key := CachedTypeKey{kind: CachedTypeKindPermissiveInstantiation, t: t} if cached := c.cachedTypes[key]; cached != nil { return cached } @@ -23870,7 +23870,7 @@ func (c *Checker) getRestrictiveInstantiation(t *Type) *Type { if t.flags&(TypeFlagsPrimitive|TypeFlagsAnyOrUnknown|TypeFlagsNever) != 0 { return t } - key := CachedTypeKey{kind: CachedTypeKindRestrictiveInstantiation, typeId: t.id} + key := CachedTypeKey{kind: CachedTypeKindRestrictiveInstantiation, t: t} if cached := c.cachedTypes[key]; cached != nil { return cached } @@ -23881,7 +23881,7 @@ func (c *Checker) getRestrictiveInstantiation(t *Type) *Type { // This also gives us a way to detect restrictive instances upon comparisons and _disable_ the "distributeive constraint" // assignability check for them, which is distinctly unsafe, as once you have a restrctive instance, all the type parameters // are constrained to `unknown` and produce tons of false positives/negatives! - c.cachedTypes[CachedTypeKey{kind: CachedTypeKindRestrictiveInstantiation, typeId: result.id}] = result + c.cachedTypes[CachedTypeKey{kind: CachedTypeKindRestrictiveInstantiation, t: result}] = result return result } @@ -23889,7 +23889,7 @@ func (c *Checker) getRestrictiveTypeParameter(t *Type) *Type { if t.AsTypeParameter().constraint == nil && c.getConstraintDeclaration(t) == nil || t.AsTypeParameter().constraint == c.noConstraintType { return t } - key := CachedTypeKey{kind: CachedTypeKindRestrictiveTypeParameter, typeId: t.id} + key := CachedTypeKey{kind: CachedTypeKindRestrictiveTypeParameter, t: t} if cached := c.cachedTypes[key]; cached != nil { return cached } @@ -24822,7 +24822,7 @@ func (c *Checker) getBaseTypeOfEnumLikeType(t *Type) *Type { } func (c *Checker) getBaseTypeOfLiteralTypeUnion(t *Type) *Type { - key := CachedTypeKey{kind: CachedTypeKindLiteralUnionBaseType, typeId: t.id} + key := CachedTypeKey{kind: CachedTypeKindLiteralUnionBaseType, t: t} if cached, ok := c.cachedTypes[key]; ok { return cached } @@ -24981,12 +24981,12 @@ func (c *Checker) getUnionTypeEx(types []*Type, unionReduction UnionReduction, a } // We optimize for the common case of unioning a union type with some other type (such as `undefined`). if len(types) == 2 && origin == nil && (types[0].flags&TypeFlagsUnion != 0 || types[1].flags&TypeFlagsUnion != 0) { - id1 := types[0].id - id2 := types[1].id - if id1 > id2 { - id1, id2 = id2, id1 + t1 := types[0] + t2 := types[1] + if t1.id > t2.id { + t1, t2 = t2, t1 } - key := UnionOfUnionKey{id1: id1, id2: id2, r: unionReduction, a: getAliasKey(alias)} + key := UnionOfUnionKey{t1: t1, t2: t2, r: unionReduction, a: getAliasKey(alias)} t := c.unionOfUnionTypes[key] if t == nil { t = c.getUnionTypeWorker(types, unionReduction, alias, nil /*origin*/) @@ -25949,10 +25949,6 @@ func (c *Checker) isErrorType(t *Type) bool { return t == c.errorType || t.flags&TypeFlagsAny != 0 && t.alias != nil } -func compareTypeIds(t1, t2 *Type) int { - return int(t1.id) - int(t2.id) -} - func (c *Checker) checkCrossProductUnion(types []*Type) bool { size := c.getCrossProductUnionSize(types) if size >= 100_000 { @@ -26013,7 +26009,7 @@ func (c *Checker) getExtractStringType(t *Type) *Type { } func (c *Checker) getLiteralTypeFromProperties(t *Type, include TypeFlags, includeOrigin bool) *Type { - key := PropertiesTypesKey{typeId: t.id, include: include, includeOrigin: includeOrigin} + key := PropertiesTypesKey{t: t, include: include, includeOrigin: includeOrigin} if cached, ok := c.propertiesTypes[key]; ok { return cached } @@ -26145,8 +26141,8 @@ func (c *Checker) getMappedTypeNameTypeKind(t *Type) MappedTypeNameTypeKind { func (c *Checker) getIndexTypeForGenericType(t *Type, indexFlags IndexFlags) *Type { key := CachedTypeKey{ - kind: core.IfElse(indexFlags&IndexFlagsStringsOnly != 0, CachedTypeKindStringIndexType, CachedTypeKindIndexType), - typeId: t.id, + kind: core.IfElse(indexFlags&IndexFlagsStringsOnly != 0, CachedTypeKindStringIndexType, CachedTypeKindIndexType), + t: t, } if indexType := c.cachedTypes[key]; indexType != nil { return indexType @@ -26709,7 +26705,7 @@ func (c *Checker) getSubstitutionType(baseType *Type, constraint *Type) *Type { } func (c *Checker) getOrCreateSubstitutionType(baseType *Type, constraint *Type) *Type { - key := SubstitutionTypeKey{baseId: baseType.id, constraintId: constraint.id} + key := SubstitutionTypeKey{base: baseType, constraint: constraint} if cached := c.substitutionTypes[key]; cached != nil { return cached } @@ -27163,7 +27159,7 @@ func (c *Checker) getSimplifiedType(t *Type, writing bool) *Type { // the type itself if no transformation is possible. The writing flag indicates that the type is // the target of an assignment. func (c *Checker) getSimplifiedIndexedAccessType(t *Type, writing bool) *Type { - key := CachedTypeKey{kind: core.IfElse(writing, CachedTypeKindIndexedAccessForWriting, CachedTypeKindIndexedAccessForReading), typeId: t.id} + key := CachedTypeKey{kind: core.IfElse(writing, CachedTypeKindIndexedAccessForWriting, CachedTypeKindIndexedAccessForReading), t: t} if cached := c.cachedTypes[key]; cached != nil { return core.IfElse(cached == c.circularConstraintType, t, cached) } @@ -27333,7 +27329,7 @@ func (c *Checker) getSingleBaseForNonAugmentingSubtype(t *Type) *Type { if t.objectFlags&ObjectFlagsReference == 0 || t.Target().objectFlags&ObjectFlagsClassOrInterface == 0 { return nil } - key := CachedTypeKey{kind: CachedTypeKindEquivalentBaseType, typeId: t.id} + key := CachedTypeKey{kind: CachedTypeKindEquivalentBaseType, t: t} if t.objectFlags&ObjectFlagsIdenticalBaseTypeCalculated != 0 { return c.cachedTypes[key] } @@ -27405,7 +27401,7 @@ func (c *Checker) getRegularTypeOfObjectLiteral(t *Type) *Type { if !(isObjectLiteralType(t) && t.objectFlags&ObjectFlagsFreshLiteral != 0) { return t } - key := CachedTypeKey{kind: CachedTypeKindRegularObjectLiteral, typeId: t.id} + key := CachedTypeKey{kind: CachedTypeKindRegularObjectLiteral, t: t} if cached := c.cachedTypes[key]; cached != nil { return cached } @@ -27975,7 +27971,7 @@ func (c *Checker) getPromisedTypeOfPromiseEx(t *Type, errorNode *ast.Node, thisT if IsTypeAny(t) { return nil } - key := CachedTypeKey{kind: CachedTypeKindPromisedTypeOfPromise, typeId: t.id} + key := CachedTypeKey{kind: CachedTypeKindPromisedTypeOfPromise, t: t} if cached := c.cachedTypes[key]; cached != nil { return cached } @@ -29471,7 +29467,7 @@ func (c *Checker) getClassMemberDecoratorContextOverrideType(nameType *Type, isP core.IfElse(isStatic, CachedTypeKindDecoratorContextPrivateStatic, CachedTypeKindDecoratorContextPrivate), core.IfElse(isStatic, CachedTypeKindDecoratorContextStatic, CachedTypeKindDecoratorContext), ) - key := CachedTypeKey{kind: kind, typeId: nameType.id} + key := CachedTypeKey{kind: kind, t: nameType} if overrideType := c.cachedTypes[key]; overrideType != nil { return overrideType } @@ -29788,7 +29784,7 @@ func (d *ObjectLiteralDiscriminator) matches(index int, t *Type) bool { } func (c *Checker) discriminateContextualTypeByObjectMembers(node *ast.Node, contextualType *Type) *Type { - key := DiscriminatedContextualTypeKey{nodeId: ast.GetNodeId(node), typeId: contextualType.id} + key := DiscriminatedContextualTypeKey{node: node, t: contextualType} if discriminated := c.discriminatedContextualTypes[key]; discriminated != nil { return discriminated } @@ -30311,7 +30307,7 @@ func (c *Checker) getAwaitedTypeNoAliasEx(t *Type, errorNode *ast.Node, diagnost return t } // If we've already cached an awaited type, return a possible `Awaited` for it. - key := CachedTypeKey{kind: CachedTypeKindAwaitedType, typeId: t.id} + key := CachedTypeKey{kind: CachedTypeKindAwaitedType, t: t} if awaitedType := c.cachedTypes[key]; awaitedType != nil { return awaitedType } diff --git a/internal/checker/emitresolver.go b/internal/checker/emitresolver.go index b9194021738..7d0ace02a69 100644 --- a/internal/checker/emitresolver.go +++ b/internal/checker/emitresolver.go @@ -259,13 +259,13 @@ func (r *EmitResolver) markLinkedAliases(node *ast.Node) { exportSymbol = r.checker.getTargetOfExportSpecifier(node.Parent, ast.SymbolFlagsValue|ast.SymbolFlagsType|ast.SymbolFlagsNamespace|ast.SymbolFlagsAlias, false) } - visited := make(map[ast.SymbolId]struct{}, 2) // guard against circular imports + visited := make(map[*ast.Symbol]struct{}, 2) // guard against circular imports for exportSymbol != nil { - _, seen := visited[ast.GetSymbolId(exportSymbol)] + _, seen := visited[exportSymbol] if seen { break } - visited[ast.GetSymbolId(exportSymbol)] = struct{}{} + visited[exportSymbol] = struct{}{} var nextSymbol *ast.Symbol for _, declaration := range exportSymbol.Declarations { @@ -357,16 +357,16 @@ func (r *EmitResolver) isEntityNameVisible(entityName *ast.Node, enclosingDeclar func noopAddVisibleAlias(declaration *ast.Node, aliasingStatement *ast.Node) {} func (r *EmitResolver) hasVisibleDeclarations(symbol *ast.Symbol, shouldComputeAliasToMakeVisible bool) *printer.SymbolAccessibilityResult { - var aliasesToMakeVisibleSet map[ast.NodeId]*ast.Node + var aliasesToMakeVisibleSet map[*ast.Node]*ast.Node var addVisibleAlias func(declaration *ast.Node, aliasingStatement *ast.Node) if shouldComputeAliasToMakeVisible { addVisibleAlias = func(declaration *ast.Node, aliasingStatement *ast.Node) { r.declarationLinks.Get(declaration).isVisible = core.TSTrue if aliasesToMakeVisibleSet == nil { - aliasesToMakeVisibleSet = make(map[ast.NodeId]*ast.Node) + aliasesToMakeVisibleSet = make(map[*ast.Node]*ast.Node) } - aliasesToMakeVisibleSet[ast.GetNodeId(declaration)] = aliasingStatement + aliasesToMakeVisibleSet[declaration] = aliasingStatement } } else { addVisibleAlias = noopAddVisibleAlias diff --git a/internal/checker/flow.go b/internal/checker/flow.go index 89787a418d7..ab542514a60 100644 --- a/internal/checker/flow.go +++ b/internal/checker/flow.go @@ -1475,7 +1475,7 @@ func getCandidateVariableDeclarationInitializer(node *ast.Node) *ast.Node { // array types are ultimately converted into manifest array types (using getFinalArrayType) // and never escape the getFlowTypeOfReference function. func (c *Checker) getEvolvingArrayType(elementType *Type) *Type { - key := CachedTypeKey{kind: CachedTypeKindEvolvingArrayType, typeId: elementType.id} + key := CachedTypeKey{kind: CachedTypeKindEvolvingArrayType, t: elementType} result := c.cachedTypes[key] if result == nil { result = c.newObjectType(ObjectFlagsEvolvingArray, nil) @@ -2373,7 +2373,7 @@ func (c *Checker) getAssignmentReducedType(declaredType *Type, assignedType *Typ if assignedType.flags&TypeFlagsNever != 0 { return assignedType } - key := AssignmentReducedKey{id1: declaredType.id, id2: assignedType.id} + key := AssignmentReducedKey{t1: declaredType, t2: assignedType} result := c.assignmentReducedTypes[key] if result == nil { result = c.getAssignmentReducedTypeWorker(declaredType, assignedType) diff --git a/internal/checker/inference.go b/internal/checker/inference.go index 64ea6d8ce70..3f10de74f26 100644 --- a/internal/checker/inference.go +++ b/internal/checker/inference.go @@ -9,8 +9,8 @@ import ( ) type InferenceKey struct { - s TypeId - t TypeId + s *Type + t *Type } type InferenceState struct { @@ -327,7 +327,7 @@ func (c *Checker) inferFromContravariantTypesIfStrictFunctionTypes(n *InferenceS // such that we would go on inferring forever, even though we would never infer // between the same pair of types. func (c *Checker) invokeOnce(n *InferenceState, source *Type, target *Type, action func(c *Checker, n *InferenceState, source *Type, target *Type)) { - key := InferenceKey{s: source.id, t: target.id} + key := InferenceKey{s: source, t: target} if status, ok := n.visited[key]; ok { n.inferencePriority = min(n.inferencePriority, status) return @@ -928,7 +928,7 @@ func (c *Checker) inferToMappedType(n *InferenceState, source *Type, target *Typ // property is computed by inferring from the source property type to X for the type // variable T[P] (i.e. we treat the type T[P] as the type variable we're inferring for). func (c *Checker) inferTypeForHomomorphicMappedType(source *Type, target *Type, constraint *Type) *Type { - key := ReverseMappedTypeKey{sourceId: source.id, targetId: target.id, constraintId: constraint.id} + key := ReverseMappedTypeKey{source: source, target: target, constraint: constraint} if cached := c.reverseHomomorphicMappedCache[key]; cached != nil { return cached } @@ -990,7 +990,7 @@ func (c *Checker) isPartiallyInferableType(t *Type) bool { } func (c *Checker) inferReverseMappedType(source *Type, target *Type, constraint *Type) *Type { - key := ReverseMappedTypeKey{sourceId: source.id, targetId: target.id, constraintId: constraint.id} + key := ReverseMappedTypeKey{source: source, target: target, constraint: constraint} if cached, ok := c.reverseMappedCache[key]; ok { return core.OrElse(cached, c.unknownType) } diff --git a/internal/checker/jsx.go b/internal/checker/jsx.go index d5cad0b4524..bad31b07554 100644 --- a/internal/checker/jsx.go +++ b/internal/checker/jsx.go @@ -262,7 +262,7 @@ func (c *Checker) getContextualTypeForChildJsxExpression(node *ast.Node, child * } func (c *Checker) discriminateContextualTypeByJSXAttributes(node *ast.Node, contextualType *Type) *Type { - key := DiscriminatedContextualTypeKey{nodeId: ast.GetNodeId(node), typeId: contextualType.id} + key := DiscriminatedContextualTypeKey{node: node, t: contextualType} if discriminated := c.discriminatedContextualTypes[key]; discriminated != nil { return discriminated } diff --git a/internal/checker/nodebuilder.go b/internal/checker/nodebuilder.go index a47e8601976..235b3c0c093 100644 --- a/internal/checker/nodebuilder.go +++ b/internal/checker/nodebuilder.go @@ -30,8 +30,8 @@ func (b *NodeBuilder) enterContext(enclosingDeclaration *ast.Node, flags nodebui symbolDepth: make(map[CompositeSymbolIdentity]int), trackedSymbols: make([]*TrackedSymbolArgs, 0), reverseMappedStack: make([]*ast.Symbol, 0), - enclosingSymbolTypes: make(map[ast.SymbolId]*Type), - remappedSymbolReferences: make(map[ast.SymbolId]*ast.Symbol), + enclosingSymbolTypes: make(map[*ast.Symbol]*Type), + remappedSymbolReferences: make(map[*ast.Symbol]*ast.Symbol), } tracker = NewSymbolTrackerImpl(b.impl.ctx, tracker) b.impl.ctx.tracker = tracker diff --git a/internal/checker/nodebuilderimpl.go b/internal/checker/nodebuilderimpl.go index 4e7336deea2..79c11229695 100644 --- a/internal/checker/nodebuilderimpl.go +++ b/internal/checker/nodebuilderimpl.go @@ -23,8 +23,8 @@ import ( type CompositeSymbolIdentity struct { isConstructorNode bool - symbolId ast.SymbolId - nodeId ast.NodeId + symbol *ast.Symbol + node *ast.Node } type TrackedSymbolArgs struct { @@ -41,7 +41,7 @@ type SerializedTypeEntry struct { } type CompositeTypeCacheIdentity struct { - typeId TypeId + t *Type flags nodebuilder.Flags internalFlags nodebuilder.InternalFlags } @@ -67,22 +67,22 @@ type NodeBuilderContext struct { enclosingDeclaration *ast.Node enclosingFile *ast.SourceFile inferTypeParameters []*Type - visitedTypes collections.Set[TypeId] + visitedTypes collections.Set[*Type] symbolDepth map[CompositeSymbolIdentity]int trackedSymbols []*TrackedSymbolArgs mapper *TypeMapper reverseMappedStack []*ast.Symbol - enclosingSymbolTypes map[ast.SymbolId]*Type + enclosingSymbolTypes map[*ast.Symbol]*Type suppressReportInferenceFallback bool - remappedSymbolReferences map[ast.SymbolId]*ast.Symbol + remappedSymbolReferences map[*ast.Symbol]*ast.Symbol // per signature scope state hasCreatedTypeParameterSymbolList bool hasCreatedTypeParametersNamesLookups bool - typeParameterNames map[TypeId]*ast.Identifier + typeParameterNames map[*Type]*ast.Identifier typeParameterNamesByText map[string]struct{} typeParameterNamesByTextNextNameCount map[string]int - typeParameterSymbolList map[ast.SymbolId]struct{} + typeParameterSymbolList map[*ast.Symbol]struct{} } type NodeBuilderImpl struct { @@ -864,7 +864,7 @@ func (b *NodeBuilderImpl) getNameOfSymbolFromNameType(symbol *ast.Symbol) string * It will also use a representation of a number as written instead of a decimal form, e.g. `0o11` instead of `9`. */ func (b *NodeBuilderImpl) getNameOfSymbolAsWritten(symbol *ast.Symbol) string { - result, ok := b.ctx.remappedSymbolReferences[ast.GetSymbolId(symbol)] + result, ok := b.ctx.remappedSymbolReferences[symbol] if ok { symbol = result } @@ -932,10 +932,10 @@ func (b *NodeBuilderImpl) getTypeParametersOfClassOrInterface(symbol *ast.Symbol func (b *NodeBuilderImpl) lookupTypeParameterNodes(chain []*ast.Symbol, index int) *ast.TypeParameterList { debug.Assert(chain != nil && 0 <= index && index < len(chain)) symbol := chain[index] - symbolId := ast.GetSymbolId(symbol) + symbolId := symbol if !b.ctx.hasCreatedTypeParameterSymbolList { b.ctx.hasCreatedTypeParameterSymbolList = true - b.ctx.typeParameterSymbolList = make(map[ast.SymbolId]struct{}) + b.ctx.typeParameterSymbolList = make(map[*ast.Symbol]struct{}) } _, ok := b.ctx.typeParameterSymbolList[symbolId] if ok { @@ -1319,7 +1319,7 @@ func (b *NodeBuilderImpl) typeParameterShadowsOtherTypeParameterInScope(name str func (b *NodeBuilderImpl) typeParameterToName(typeParameter *Type) *ast.Identifier { if b.ctx.flags&nodebuilder.FlagsGenerateNamesForShadowedTypeParams != 0 && b.ctx.typeParameterNames != nil { - cached, ok := b.ctx.typeParameterNames[typeParameter.id] + cached, ok := b.ctx.typeParameterNames[typeParameter] if ok { return cached } @@ -1337,7 +1337,7 @@ func (b *NodeBuilderImpl) typeParameterToName(typeParameter *Type) *ast.Identifi if b.ctx.flags&nodebuilder.FlagsGenerateNamesForShadowedTypeParams != 0 { if !b.ctx.hasCreatedTypeParametersNamesLookups { b.ctx.hasCreatedTypeParametersNamesLookups = true - b.ctx.typeParameterNames = make(map[TypeId]*ast.Identifier) + b.ctx.typeParameterNames = make(map[*Type]*ast.Identifier) b.ctx.typeParameterNamesByText = make(map[string]struct{}) b.ctx.typeParameterNamesByTextNextNameCount = make(map[string]int) } @@ -1369,7 +1369,7 @@ func (b *NodeBuilderImpl) typeParameterToName(typeParameter *Type) *ast.Identifi // avoiding iterations of the above loop turns out to be worth it when `i` starts to get large, so we cache the max // `i` we've used thus far, to save work later b.ctx.typeParameterNamesByTextNextNameCount[rawText] = i - b.ctx.typeParameterNames[typeParameter.id] = result.AsIdentifier() + b.ctx.typeParameterNames[typeParameter] = result.AsIdentifier() b.ctx.typeParameterNamesByText[text] = struct{}{} } @@ -1965,7 +1965,7 @@ func (b *NodeBuilderImpl) serializeReturnTypeForSignature(signature *Signature, if signature.declaration != nil && !ast.NodeIsSynthesized(signature.declaration) { symbol := b.ch.getSymbolOfDeclaration(signature.declaration) var ok bool - returnType, ok = b.ctx.enclosingSymbolTypes[ast.GetSymbolId(symbol)] + returnType, ok = b.ctx.enclosingSymbolTypes[symbol] if !ok || returnType == nil { returnType = b.ch.instantiateType(b.ch.getReturnTypeOfSignature(signature), b.ctx.mapper) } @@ -2053,7 +2053,7 @@ func (b *NodeBuilderImpl) serializeTypeForDeclaration(declaration *ast.Declarati symbol = b.ch.getSymbolOfDeclaration(declaration) } if t == nil { - t = b.ctx.enclosingSymbolTypes[ast.GetSymbolId(symbol)] + t = b.ctx.enclosingSymbolTypes[symbol] if t == nil { if symbol.Flags&ast.SymbolFlagsAccessor != 0 && declaration.Kind == ast.KindSetAccessor { t = b.ch.instantiateType(b.ch.getWriteTypeOfSymbol(symbol), b.ctx.mapper) @@ -2547,7 +2547,7 @@ func getTypeAliasForTypeLiteral(c *Checker, t *Type) *ast.Symbol { return nil } -func (b *NodeBuilderImpl) shouldWriteTypeOfFunctionSymbol(symbol *ast.Symbol, typeId TypeId) bool { +func (b *NodeBuilderImpl) shouldWriteTypeOfFunctionSymbol(symbol *ast.Symbol, t *Type) bool { isStaticMethodSymbol := symbol.Flags&ast.SymbolFlagsMethod != 0 && core.Some(symbol.Declarations, func(declaration *ast.Node) bool { return ast.IsStatic(declaration) && !b.ch.isLateBindableIndexSignature(ast.GetNameOfDeclaration(declaration)) }) @@ -2566,14 +2566,13 @@ func (b *NodeBuilderImpl) shouldWriteTypeOfFunctionSymbol(symbol *ast.Symbol, ty } if isStaticMethodSymbol || isNonLocalFunctionSymbol { // typeof is allowed only for static/non local functions - return (b.ctx.flags&nodebuilder.FlagsUseTypeOfFunction != 0 || b.ctx.visitedTypes.Has(typeId)) && // it is type of the symbol uses itself recursively + return (b.ctx.flags&nodebuilder.FlagsUseTypeOfFunction != 0 || b.ctx.visitedTypes.Has(t)) && // it is type of the symbol uses itself recursively (b.ctx.flags&nodebuilder.FlagsUseStructuralFallback == 0 || b.ch.IsValueSymbolAccessible(symbol, b.ctx.enclosingDeclaration)) // And the build is going to succeed without visibility error or there is no structural fallback allowed } return false } func (b *NodeBuilderImpl) createAnonymousTypeNode(t *Type) *ast.TypeNode { - typeId := t.id symbol := t.symbol if symbol != nil { isInstantiationExpressionType := t.objectFlags&ObjectFlagsInstantiationExpressionType != 0 @@ -2593,7 +2592,7 @@ func (b *NodeBuilderImpl) createAnonymousTypeNode(t *Type) *ast.TypeNode { return typeNode } } - if b.ctx.visitedTypes.Has(typeId) { + if b.ctx.visitedTypes.Has(t) { return b.createElidedInformationPlaceholder() } return b.visitAndTransformType(t, (*NodeBuilderImpl).createTypeNodeFromObjectType) @@ -2610,9 +2609,9 @@ func (b *NodeBuilderImpl) createAnonymousTypeNode(t *Type) *ast.TypeNode { // // Instance and static types share the same symbol; only add 'typeof' for the static side. // return b.symbolToTypeNode(symbol, isInstanceType, nil) // } else - if symbol.Flags&ast.SymbolFlagsClass != 0 && b.ch.getBaseTypeVariableOfClass(symbol) == nil && !(symbol.ValueDeclaration != nil && ast.IsClassLike(symbol.ValueDeclaration) && b.ctx.flags&nodebuilder.FlagsWriteClassExpressionAsTypeLiteral != 0 && (!ast.IsClassDeclaration(symbol.ValueDeclaration) || b.ch.IsSymbolAccessible(symbol, b.ctx.enclosingDeclaration, isInstanceType, false /*shouldComputeAliasesToMakeVisible*/).Accessibility != printer.SymbolAccessibilityAccessible)) || symbol.Flags&(ast.SymbolFlagsEnum|ast.SymbolFlagsValueModule) != 0 || b.shouldWriteTypeOfFunctionSymbol(symbol, typeId) { + if symbol.Flags&ast.SymbolFlagsClass != 0 && b.ch.getBaseTypeVariableOfClass(symbol) == nil && !(symbol.ValueDeclaration != nil && ast.IsClassLike(symbol.ValueDeclaration) && b.ctx.flags&nodebuilder.FlagsWriteClassExpressionAsTypeLiteral != 0 && (!ast.IsClassDeclaration(symbol.ValueDeclaration) || b.ch.IsSymbolAccessible(symbol, b.ctx.enclosingDeclaration, isInstanceType, false /*shouldComputeAliasesToMakeVisible*/).Accessibility != printer.SymbolAccessibilityAccessible)) || symbol.Flags&(ast.SymbolFlagsEnum|ast.SymbolFlagsValueModule) != 0 || b.shouldWriteTypeOfFunctionSymbol(symbol, t) { return b.symbolToTypeNode(symbol, isInstanceType, nil) - } else if b.ctx.visitedTypes.Has(typeId) { + } else if b.ctx.visitedTypes.Has(t) { // If type is an anonymous type literal in a type alias declaration, use type alias name typeAlias := getTypeAliasForTypeLiteral(b.ch, t) if typeAlias != nil { @@ -2646,7 +2645,7 @@ func (b *NodeBuilderImpl) getTypeFromTypeNode(node *ast.TypeNode, noMappedTypes func (b *NodeBuilderImpl) typeToTypeNodeOrCircularityElision(t *Type) *ast.TypeNode { if t.flags&TypeFlagsUnion != 0 { - if b.ctx.visitedTypes.Has(t.id) { + if b.ctx.visitedTypes.Has(t) { if b.ctx.flags&nodebuilder.FlagsAllowAnonymousIdentifier == 0 { b.ctx.encounteredError = true b.ctx.tracker.ReportCyclicStructureError() @@ -2862,23 +2861,22 @@ func (b *NodeBuilderImpl) typeReferenceToTypeNode(t *Type) *ast.TypeNode { } func (b *NodeBuilderImpl) visitAndTransformType(t *Type, transform func(b *NodeBuilderImpl, t *Type) *ast.TypeNode) *ast.TypeNode { - typeId := t.id isConstructorObject := t.objectFlags&ObjectFlagsAnonymous != 0 && t.symbol != nil && t.symbol.Flags&ast.SymbolFlagsClass != 0 var id *CompositeSymbolIdentity switch { case t.objectFlags&ObjectFlagsReference != 0 && t.AsTypeReference().node != nil: - id = &CompositeSymbolIdentity{false, 0, ast.GetNodeId(t.AsTypeReference().node)} + id = &CompositeSymbolIdentity{false, nil, t.AsTypeReference().node} case t.flags&TypeFlagsConditional != 0: - id = &CompositeSymbolIdentity{false, 0, ast.GetNodeId(t.AsConditionalType().root.node.AsNode())} + id = &CompositeSymbolIdentity{false, nil, t.AsConditionalType().root.node.AsNode()} case t.symbol != nil: - id = &CompositeSymbolIdentity{isConstructorObject, ast.GetSymbolId(t.symbol), 0} + id = &CompositeSymbolIdentity{isConstructorObject, t.symbol, nil} default: id = nil } // Since instantiations of the same anonymous type have the same symbol, tracking symbols instead // of types allows us to catch circular references to instantiations of the same anonymous type - key := CompositeTypeCacheIdentity{typeId, b.ctx.flags, b.ctx.internalFlags} + key := CompositeTypeCacheIdentity{t, b.ctx.flags, b.ctx.internalFlags} if b.ctx.enclosingDeclaration != nil && b.links.Has(b.ctx.enclosingDeclaration) { links := b.links.Get(b.ctx.enclosingDeclaration) cachedResult, ok := links.serializedTypes[key] @@ -2903,7 +2901,7 @@ func (b *NodeBuilderImpl) visitAndTransformType(t *Type, transform func(b *NodeB } b.ctx.symbolDepth[*id] = depth + 1 } - b.ctx.visitedTypes.Add(typeId) + b.ctx.visitedTypes.Add(t) prevTrackedSymbols := b.ctx.trackedSymbols b.ctx.trackedSymbols = nil startLength := b.ctx.approximateLength @@ -2921,7 +2919,7 @@ func (b *NodeBuilderImpl) visitAndTransformType(t *Type, transform func(b *NodeB trackedSymbols: b.ctx.trackedSymbols, } } - b.ctx.visitedTypes.Delete(typeId) + b.ctx.visitedTypes.Delete(t) if id != nil { b.ctx.symbolDepth[*id] = depth } diff --git a/internal/checker/nodebuilderscopes.go b/internal/checker/nodebuilderscopes.go index 6b0371bb527..2934b01ca70 100644 --- a/internal/checker/nodebuilderscopes.go +++ b/internal/checker/nodebuilderscopes.go @@ -50,14 +50,13 @@ type localsRecord struct { } func (b *NodeBuilderImpl) addSymbolTypeToContext(symbol *ast.Symbol, t *Type) func() { - id := ast.GetSymbolId(symbol) - oldType, oldTypeExists := b.ctx.enclosingSymbolTypes[id] - b.ctx.enclosingSymbolTypes[id] = t + oldType, oldTypeExists := b.ctx.enclosingSymbolTypes[symbol] + b.ctx.enclosingSymbolTypes[symbol] = t return func() { if oldTypeExists { - b.ctx.enclosingSymbolTypes[id] = oldType + b.ctx.enclosingSymbolTypes[symbol] = oldType } else { - delete(b.ctx.enclosingSymbolTypes, id) + delete(b.ctx.enclosingSymbolTypes, symbol) } } } diff --git a/internal/checker/relater.go b/internal/checker/relater.go index 691bb1d24a0..3718d958c6c 100644 --- a/internal/checker/relater.go +++ b/internal/checker/relater.go @@ -289,7 +289,7 @@ func (c *Checker) isEnumTypeRelatedTo(source *ast.Symbol, target *ast.Symbol, er if sourceSymbol.Name != targetSymbol.Name || sourceSymbol.Flags&ast.SymbolFlagsRegularEnum == 0 || targetSymbol.Flags&ast.SymbolFlagsRegularEnum == 0 { return false } - key := EnumRelationKey{sourceId: ast.GetSymbolId(sourceSymbol), targetId: ast.GetSymbolId(targetSymbol)} + key := EnumRelationKey{source: sourceSymbol, target: targetSymbol} if entry := c.enumRelation[key]; entry != RelationComparisonResultNone && !(entry&RelationComparisonResultFailed != 0 && errorReporter != nil) { return entry&RelationComparisonResultSucceeded != 0 } diff --git a/internal/checker/symbolaccessibility.go b/internal/checker/symbolaccessibility.go index 8c749b55ea1..b9886be7a0e 100644 --- a/internal/checker/symbolaccessibility.go +++ b/internal/checker/symbolaccessibility.go @@ -170,10 +170,10 @@ func (c *Checker) getAlternativeContainingModules(symbol *ast.Symbol, enclosingD return nil } containingFile := ast.GetSourceFileOfNode(enclosingDeclaration) - id := ast.GetNodeId(containingFile.AsNode()) + id := containingFile.AsNode() links := c.symbolContainerLinks.Get(symbol) if links.extendedContainersByFile == nil { - links.extendedContainersByFile = make(map[ast.NodeId][]*ast.Symbol) + links.extendedContainersByFile = make(map[*ast.Node][]*ast.Symbol) } existing, ok := links.extendedContainersByFile[id] if ok && existing != nil { @@ -376,7 +376,7 @@ func (c *Checker) getAccessibleSymbolChain( meaning ast.SymbolFlags, useOnlyExternalAliasing bool, ) []*ast.Symbol { - return c.getAccessibleSymbolChainEx(accessibleSymbolChainContext{symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing, make(map[ast.SymbolId]map[symbolTableID]struct{})}) + return c.getAccessibleSymbolChainEx(accessibleSymbolChainContext{symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing, make(map[*ast.Symbol]map[symbolTableID]struct{})}) } func (c *Checker) GetAccessibleSymbolChain( @@ -393,7 +393,7 @@ type accessibleSymbolChainContext struct { enclosingDeclaration *ast.Node meaning ast.SymbolFlags useOnlyExternalAliasing bool - visitedSymbolTablesMap map[ast.SymbolId]map[symbolTableID]struct{} + visitedSymbolTablesMap map[*ast.Symbol]map[symbolTableID]struct{} } // symbolTableID uniquely identifies a symbol table by encoding its source. @@ -465,11 +465,10 @@ func (c *Checker) getAccessibleSymbolChainEx(ctx accessibleSymbolChainContext) [ * @param {ignoreQualification} boolean Set when a symbol is being looked for through the exports of another symbol (meaning we have a route to qualify it already) */ func (c *Checker) getAccessibleSymbolChainFromSymbolTable(ctx accessibleSymbolChainContext, t ast.SymbolTable, tableId symbolTableID, ignoreQualification bool, isLocalNameLookup bool) []*ast.Symbol { - symId := ast.GetSymbolId(ctx.symbol) - visitedSymbolTables, ok := ctx.visitedSymbolTablesMap[symId] + visitedSymbolTables, ok := ctx.visitedSymbolTablesMap[ctx.symbol] if !ok { visitedSymbolTables = make(map[symbolTableID]struct{}) - ctx.visitedSymbolTablesMap[symId] = visitedSymbolTables + ctx.visitedSymbolTablesMap[ctx.symbol] = visitedSymbolTables } _, present := visitedSymbolTables[tableId] diff --git a/internal/checker/types.go b/internal/checker/types.go index 84e2e3fb093..403bb471407 100644 --- a/internal/checker/types.go +++ b/internal/checker/types.go @@ -274,8 +274,8 @@ type accessibleChainCacheKey struct { } type ContainingSymbolLinks struct { - extendedContainersByFile map[ast.NodeId][]*ast.Symbol // Symbols of nodes which which logically contain this one, cached by file the request is made within - extendedContainers *[]*ast.Symbol // Containers (other than the parent) which this symbol is aliased in + extendedContainersByFile map[*ast.Node][]*ast.Symbol // Symbols of nodes which which logically contain this one, cached by file the request is made within + extendedContainers *[]*ast.Symbol // Containers (other than the parent) which this symbol is aliased in accessibleChainCache map[accessibleChainCacheKey][]*ast.Symbol } diff --git a/internal/ls/callhierarchy.go b/internal/ls/callhierarchy.go index 461ede931da..1190d535eb3 100644 --- a/internal/ls/callhierarchy.go +++ b/internal/ls/callhierarchy.go @@ -557,8 +557,8 @@ func convertEntryToCallSite(entry *ReferenceEntry) *callSite { } } -func getCallSiteGroupKey(site *callSite) ast.NodeId { - return ast.GetNodeId(site.declaration) +func getCallSiteGroupKey(site *callSite) *ast.Node { + return site.declaration } func (l *LanguageService) convertCallSiteGroupToIncomingCall(program *compiler.Program, entries []*callSite) *lsproto.CallHierarchyIncomingCall { @@ -674,7 +674,7 @@ func (l *LanguageService) symbolAndEntriesToIncomingCalls(ctx context.Context, p return lsproto.CallHierarchyIncomingCallsOrNull{}, nil } - grouped := make(map[ast.NodeId][]*callSite) + grouped := make(map[*ast.Node][]*callSite) for _, site := range callSites { key := getCallSiteGroupKey(site) grouped[key] = append(grouped[key], site) @@ -948,7 +948,7 @@ func (l *LanguageService) getOutgoingCalls(program *compiler.Program, declaratio return nil } - grouped := make(map[ast.NodeId][]*callSite) + grouped := make(map[*ast.Node][]*callSite) for _, site := range callSites { key := getCallSiteGroupKey(site) grouped[key] = append(grouped[key], site) diff --git a/internal/ls/completions.go b/internal/ls/completions.go index 71f04e0419f..81da867d445 100644 --- a/internal/ls/completions.go +++ b/internal/ls/completions.go @@ -88,7 +88,7 @@ type completionDataData struct { keywordFilters KeywordCompletionFilters literals []literalValue symbolToOriginInfoMap map[int]*symbolOriginInfo - symbolToSortTextMap map[ast.SymbolId]SortText + symbolToSortTextMap map[*ast.Symbol]SortText recommendedCompletion *ast.Symbol previousToken *ast.Node contextToken *ast.Node @@ -668,8 +668,8 @@ func (l *LanguageService) getCompletionData( var autoImports []*autoimport.FixAndExport // Keys are indexes of `symbols`. symbolToOriginInfoMap := map[int]*symbolOriginInfo{} - symbolToSortTextMap := map[ast.SymbolId]SortText{} - var seenPropertySymbols collections.Set[ast.SymbolId] + symbolToSortTextMap := map[*ast.Symbol]SortText{} + var seenPropertySymbols collections.Set[*ast.Symbol] isTypeOnlyLocation := insideJSDocTagTypeExpression || insideJsDocImportTag || importStatementCompletion != nil && location.Parent != nil && ast.IsTypeOnlyImportOrExportDeclaration(location.Parent) || !isContextTokenValueLocation(contextToken) && @@ -678,8 +678,7 @@ func (l *LanguageService) getCompletionData( isContextTokenTypeLocation(contextToken)) addSymbolOriginInfo := func(symbol *ast.Symbol, insertQuestionDot bool, insertAwait bool) { - symbolId := ast.GetSymbolId(symbol) - if insertAwait && seenPropertySymbols.AddIfAbsent(symbolId) { + if insertAwait && seenPropertySymbols.AddIfAbsent(symbol) { symbolToOriginInfoMap[len(symbols)-1] = &symbolOriginInfo{kind: getNullableSymbolOriginInfoKind(symbolOriginInfoKindPromise, insertQuestionDot)} } else if insertQuestionDot { symbolToOriginInfoMap[len(symbols)-1] = &symbolOriginInfo{kind: symbolOriginInfoKindNullable} @@ -687,9 +686,8 @@ func (l *LanguageService) getCompletionData( } addSymbolSortInfo := func(symbol *ast.Symbol) { - symbolId := ast.GetSymbolId(symbol) if isStaticProperty(symbol) { - symbolToSortTextMap[symbolId] = SortTextLocalDeclarationPriority + symbolToSortTextMap[symbol] = SortTextLocalDeclarationPriority } } @@ -716,13 +714,9 @@ func (l *LanguageService) getCompletionData( if nameSymbol != nil { firstAccessibleSymbol = getFirstSymbolInChain(nameSymbol, contextToken, typeChecker) } - var firstAccessibleSymbolId ast.SymbolId - if firstAccessibleSymbol != nil { - firstAccessibleSymbolId = ast.GetSymbolId(firstAccessibleSymbol) - } - if firstAccessibleSymbolId != 0 && seenPropertySymbols.AddIfAbsent(firstAccessibleSymbolId) { + if firstAccessibleSymbol != nil && seenPropertySymbols.AddIfAbsent(firstAccessibleSymbol) { symbols = append(symbols, firstAccessibleSymbol) - symbolToSortTextMap[firstAccessibleSymbolId] = SortTextGlobalsOrKeywords + symbolToSortTextMap[firstAccessibleSymbol] = SortTextGlobalsOrKeywords moduleSymbol := firstAccessibleSymbol.Parent if moduleSymbol == nil || !checker.IsExternalModuleSymbol(moduleSymbol) || @@ -731,7 +725,7 @@ func (l *LanguageService) getCompletionData( } else { // !!! auto-import symbol } - } else if firstAccessibleSymbolId == 0 || !seenPropertySymbols.Has(firstAccessibleSymbolId) { + } else if firstAccessibleSymbol == nil || !seenPropertySymbols.Has(firstAccessibleSymbol) { symbols = append(symbols, symbol) addSymbolOriginInfo(symbol, insertQuestionDot, insertAwait) addSymbolSortInfo(symbol) @@ -829,7 +823,7 @@ func (l *LanguageService) getCompletionData( return typeChecker.IsValidPropertyAccess(valueAccessNode, s.Name) } isValidTypeAccess := func(s *ast.Symbol) bool { - return symbolCanBeReferencedAtTypeLocation(s, typeChecker, collections.Set[ast.SymbolId]{}) + return symbolCanBeReferencedAtTypeLocation(s, typeChecker, collections.Set[*ast.Symbol]{}) } var isValidAccess bool if isNamespaceName { @@ -1051,14 +1045,13 @@ func (l *LanguageService) getCompletionData( transformObjectLiteralMembers := preferences.IncludeCompletionsWithObjectLiteralMethodSnippets.IsTrue() && objectLikeContainer.Kind == ast.KindObjectLiteralExpression for _, member := range filteredMembers { - symbolId := ast.GetSymbolId(member) if spreadMemberNames.Has(member.Name) { - symbolToSortTextMap[symbolId] = SortTextMemberDeclaredBySpreadAssignment + symbolToSortTextMap[member] = SortTextMemberDeclaredBySpreadAssignment } if member.Flags&ast.SymbolFlagsOptional != 0 { - _, ok := symbolToSortTextMap[symbolId] + _, ok := symbolToSortTextMap[member] if !ok { - symbolToSortTextMap[symbolId] = SortTextOptionalMember + symbolToSortTextMap[member] = SortTextOptionalMember } } if transformObjectLiteralMembers { @@ -1274,8 +1267,7 @@ func (l *LanguageService) getCompletionData( for name, symbol := range localsContainer.Locals() { symbols = append(symbols, symbol) if _, ok := localExports[name]; ok { - symbolId := ast.GetSymbolId(symbol) - symbolToSortTextMap[symbolId] = SortTextOptionalMember + symbolToSortTextMap[symbol] = SortTextOptionalMember } } @@ -1410,14 +1402,13 @@ func (l *LanguageService) getCompletionData( symbols = append(symbols, filteredSymbols...) // Set sort texts. for _, symbol := range filteredSymbols { - symbolId := ast.GetSymbolId(symbol) if spreadMemberNames.Has(ast.SymbolName(symbol)) { - symbolToSortTextMap[symbolId] = SortTextMemberDeclaredBySpreadAssignment + symbolToSortTextMap[symbol] = SortTextMemberDeclaredBySpreadAssignment } if symbol.Flags&ast.SymbolFlagsOptional != 0 { - _, ok := symbolToSortTextMap[symbolId] + _, ok := symbolToSortTextMap[symbol] if !ok { - symbolToSortTextMap[symbolId] = SortTextOptionalMember + symbolToSortTextMap[symbol] = SortTextOptionalMember } } } @@ -1488,12 +1479,11 @@ func (l *LanguageService) getCompletionData( symbols = append(symbols, typeChecker.GetSymbolsInScope(scopeNode, symbolMeanings)...) core.CheckEachDefined(symbols, "getSymbolsInScope() should all be defined") for index, symbol := range symbols { - symbolId := ast.GetSymbolId(symbol) if !typeChecker.IsArgumentsSymbol(symbol) && !core.Some(symbol.Declarations, func(decl *ast.Declaration) bool { return ast.GetSourceFileOfNode(decl) == file }) { - symbolToSortTextMap[symbolId] = SortTextGlobalsOrKeywords + symbolToSortTextMap[symbol] = SortTextGlobalsOrKeywords } if typeOnlyAliasNeedsPromotion && symbol.Flags&ast.SymbolFlagsValue == 0 { typeOnlyAliasDeclaration := core.Find(symbol.Declarations, ast.IsTypeOnlyImportDeclaration) @@ -1515,10 +1505,9 @@ func (l *LanguageService) getCompletionData( core.IfElse(ast.IsClassLike(scopeNode.Parent), scopeNode, nil)) if thisType != nil && !isProbablyGlobalType(thisType, file, typeChecker) { for _, symbol := range getPropertiesForCompletion(thisType, typeChecker) { - symbolId := ast.GetSymbolId(symbol) symbols = append(symbols, symbol) symbolToOriginInfoMap[len(symbols)-1] = &symbolOriginInfo{kind: symbolOriginInfoKindThisType} - symbolToSortTextMap[symbolId] = SortTextSuggestedClassMembers + symbolToSortTextMap[symbol] = SortTextSuggestedClassMembers } } } @@ -1846,7 +1835,7 @@ func (l *LanguageService) getCompletionEntriesFromSymbols( continue } - originalSortText := data.symbolToSortTextMap[ast.GetSymbolId(symbol)] + originalSortText := data.symbolToSortTextMap[symbol] if originalSortText == "" { originalSortText = SortTextLocationPriority } @@ -2488,7 +2477,7 @@ func shouldIncludeSymbol( if file.AsSourceFile().ExternalModuleIndicator != nil && compilerOptions.AllowUmdGlobalAccess != core.TSTrue && symbol != symbolOrigin && - data.symbolToSortTextMap[ast.GetSymbolId(symbol)] == SortTextGlobalsOrKeywords && + data.symbolToSortTextMap[symbol] == SortTextGlobalsOrKeywords && symbol.Parent != nil && checker.IsExternalModuleSymbol(symbol.Parent) { return false } @@ -2505,7 +2494,7 @@ func shouldIncludeSymbol( if data.isTypeOnlyLocation { // It's a type, but you can reach it by namespace.type as well. - return symbolCanBeReferencedAtTypeLocation(symbol, typeChecker, collections.Set[ast.SymbolId]{}) + return symbolCanBeReferencedAtTypeLocation(symbol, typeChecker, collections.Set[*ast.Symbol]{}) } // expressions are value space (which includes the value namespaces) @@ -2726,7 +2715,7 @@ func isContextTokenTypeLocation(contextToken *ast.Node) bool { } // True if symbol is a type or a module containing at least one type. -func symbolCanBeReferencedAtTypeLocation(symbol *ast.Symbol, typeChecker *checker.Checker, seenModules collections.Set[ast.SymbolId]) bool { +func symbolCanBeReferencedAtTypeLocation(symbol *ast.Symbol, typeChecker *checker.Checker, seenModules collections.Set[*ast.Symbol]) bool { // Since an alias can be merged with a local declaration, we need to test both the alias and its target. // This code used to just test the result of `skipAlias`, but that would ignore any locally introduced meanings. return nonAliasCanBeReferencedAtTypeLocation(symbol, typeChecker, seenModules) || @@ -2737,9 +2726,9 @@ func symbolCanBeReferencedAtTypeLocation(symbol *ast.Symbol, typeChecker *checke ) } -func nonAliasCanBeReferencedAtTypeLocation(symbol *ast.Symbol, typeChecker *checker.Checker, seenModules collections.Set[ast.SymbolId]) bool { +func nonAliasCanBeReferencedAtTypeLocation(symbol *ast.Symbol, typeChecker *checker.Checker, seenModules collections.Set[*ast.Symbol]) bool { return symbol.Flags&ast.SymbolFlagsType != 0 || typeChecker.IsUnknownSymbol(symbol) || - symbol.Flags&ast.SymbolFlagsModule != 0 && seenModules.AddIfAbsent(ast.GetSymbolId(symbol)) && + symbol.Flags&ast.SymbolFlagsModule != 0 && seenModules.AddIfAbsent(symbol) && core.Some( typeChecker.GetExportsOfModule(symbol), func(e *ast.Symbol) bool { return symbolCanBeReferencedAtTypeLocation(e, typeChecker, seenModules) }) diff --git a/internal/printer/namegenerator.go b/internal/printer/namegenerator.go index 2fd38affb4a..93c0093db71 100644 --- a/internal/printer/namegenerator.go +++ b/internal/printer/namegenerator.go @@ -22,8 +22,8 @@ type NameGenerator struct { Context *EmitContext IsFileLevelUniqueNameInCurrentFile func(string, bool) bool // callback for Printer.isFileLevelUniqueNameInCurrentFile GetTextOfNode func(*ast.Node) string // callback for Printer.getTextOfNode - nodeIdToGeneratedName map[ast.NodeId]string // Map of generated names for specific nodes - nodeIdToGeneratedPrivateName map[ast.NodeId]string // Map of generated private names for specific nodes + nodeIdToGeneratedName map[*ast.Node]string // Map of generated names for specific nodes + nodeIdToGeneratedPrivateName map[*ast.Node]string // Map of generated private names for specific nodes autoGeneratedIdToGeneratedName map[AutoGenerateId]string // Map of generated names for temp and loop variables nameGenerationScope *nameGenerationScope privateNameGenerationScope *nameGenerationScope @@ -136,18 +136,17 @@ func (g *NameGenerator) GenerateName(name *ast.MemberName) string { } func (g *NameGenerator) generateNameForNodeCached(node *ast.Node, privateName bool, flags GeneratedIdentifierFlags, prefix string, suffix string) string { - nodeId := ast.GetNodeId(node) cache := core.IfElse(privateName, &g.nodeIdToGeneratedPrivateName, &g.nodeIdToGeneratedName) if *cache == nil { - *cache = make(map[ast.NodeId]string) + *cache = make(map[*ast.Node]string) } - if name, ok := (*cache)[nodeId]; ok { + if name, ok := (*cache)[node]; ok { return name } name := g.generateNameForNode(node, privateName, flags, prefix, suffix) - (*cache)[nodeId] = name + (*cache)[node] = name return name } diff --git a/internal/transformers/declarations/transform.go b/internal/transformers/declarations/transform.go index 0b5d0aebed6..43faf69d69f 100644 --- a/internal/transformers/declarations/transform.go +++ b/internal/transformers/declarations/transform.go @@ -59,8 +59,8 @@ type DeclarationTransformer struct { enclosingDeclaration *ast.Node resultHasExternalModuleIndicator bool suppressNewDiagnosticContexts bool - lateStatementReplacementMap map[ast.NodeId]*ast.Node - expandoHosts collections.Set[ast.NodeId] + lateStatementReplacementMap map[*ast.Node]*ast.Node + expandoHosts collections.Set[*ast.Node] rawReferencedFiles []ReferencedFilePair rawTypeReferenceDirectives []*ast.FileReference rawLibReferenceDirectives []*ast.FileReference @@ -251,8 +251,8 @@ func (tx *DeclarationTransformer) visitSourceFile(node *ast.SourceFile) *ast.Nod tx.resultHasExternalModuleIndicator = false tx.suppressNewDiagnosticContexts = false tx.state.lateMarkedStatements = make([]*ast.Node, 0) - tx.lateStatementReplacementMap = make(map[ast.NodeId]*ast.Node) - tx.expandoHosts = collections.Set[ast.NodeId]{} + tx.lateStatementReplacementMap = make(map[*ast.Node]*ast.Node) + tx.expandoHosts = collections.Set[*ast.Node]{} tx.rawReferencedFiles = make([]ReferencedFilePair, 0) tx.rawTypeReferenceDirectives = make([]*ast.FileReference, 0) tx.rawLibReferenceDirectives = make([]*ast.FileReference, 0) @@ -337,8 +337,7 @@ func (tx *DeclarationTransformer) transformAndReplaceLatePaintedStatements(state tx.needsDeclare = saveNeedsDeclare original := tx.EmitContext().MostOriginal(next) - id := ast.GetNodeId(original) - tx.lateStatementReplacementMap[id] = result + tx.lateStatementReplacementMap[original] = result } // And lastly, we need to get the final form of all those indetermine import declarations from before and add them to the output list @@ -350,8 +349,7 @@ func (tx *DeclarationTransformer) transformAndReplaceLatePaintedStatements(state continue } original := tx.EmitContext().MostOriginal(statement) - id := ast.GetNodeId(original) - replacement, ok := tx.lateStatementReplacementMap[id] + replacement, ok := tx.lateStatementReplacementMap[original] if !ok { results = append(results, statement) continue // not replaced @@ -1056,7 +1054,7 @@ func (tx *DeclarationTransformer) visitDeclarationStatements(input *ast.Node) *a tx.removeAllComments(assignment) return tx.Factory().NewSyntaxList([]*ast.Node{statement, assignment}) default: - id := ast.GetNodeId(tx.EmitContext().MostOriginal(input)) + id := tx.EmitContext().MostOriginal(input) if tx.lateStatementReplacementMap[id] == nil { // Don't actually transform yet; just leave as original node - will be elided/swapped by late pass tx.lateStatementReplacementMap[id] = tx.transformTopLevelDeclaration(input) @@ -1389,9 +1387,8 @@ func (tx *DeclarationTransformer) transformModuleDeclaration(input *ast.ModuleDe tx.Visitor().Visit(inner) // eagerly transform nested namespaces (the nesting doesn't need any elision or painting done) original := tx.EmitContext().MostOriginal(inner) - id := ast.GetNodeId(original) - body, _ := tx.lateStatementReplacementMap[id] - delete(tx.lateStatementReplacementMap, id) + body, _ := tx.lateStatementReplacementMap[original] + delete(tx.lateStatementReplacementMap, original) return tx.Factory().UpdateModuleDeclaration( input, mods, @@ -2106,7 +2103,7 @@ func (tx *DeclarationTransformer) transformExpandoAssignment(node *ast.BinaryExp func (tx *DeclarationTransformer) transformExpandoHost(name *ast.Node, declaration *ast.Declaration) { root := core.IfElse(ast.IsVariableDeclaration(declaration), declaration.Parent.Parent, declaration) - id := ast.GetNodeId(tx.EmitContext().MostOriginal(root)) + id := tx.EmitContext().MostOriginal(root) if tx.expandoHosts.Has(id) { return