diff --git a/tsc/internal/ast/utilities.go b/tsc/internal/ast/utilities.go index 668883c00d285..6ebd932056c67 100644 --- a/tsc/internal/ast/utilities.go +++ b/tsc/internal/ast/utilities.go @@ -2452,7 +2452,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) @@ -2461,24 +2461,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: @@ -2532,7 +2531,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/tsc/internal/checker/checker.go b/tsc/internal/checker/checker.go index b03cebf741b22..21bf973518335 100644 --- a/tsc/internal/checker/checker.go +++ b/tsc/internal/checker/checker.go @@ -109,8 +109,8 @@ type EnumLiteralKey struct { // EnumRelationKey type EnumRelationKey struct { - sourceId ast.SymbolId - targetId ast.SymbolId + source *ast.Symbol + target *ast.Symbol } // TypeCacheKind @@ -145,8 +145,8 @@ const ( // CachedTypeKey type CachedTypeKey struct { - kind CachedTypeKind - typeId TypeId + kind CachedTypeKind + t *Type } // NarrowedTypeKey @@ -161,10 +161,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 @@ -192,50 +192,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 } @@ -657,7 +657,7 @@ type Checker struct { moduleSymbols map[*ast.Node]*ast.Symbol globalThisSymbol *ast.Symbol symbolTableAliasCache map[symbolTableID][]*ast.Symbol - classExpressionNameTables map[ast.NodeId]ast.SymbolTable + classExpressionNameTables map[*ast.Node]ast.SymbolTable resolveName func(location *ast.Node, name string, meaning ast.SymbolFlags, nameNotFoundMessage *diagnostics.Message, isUse bool, excludeGlobals bool) *ast.Symbol resolveNameForSymbolSuggestion func(location *ast.Node, name string, meaning ast.SymbolFlags, nameNotFoundMessage *diagnostics.Message, isUse bool, excludeGlobals bool) *ast.Symbol tupleTypes map[CacheHashKey]*Type @@ -6469,7 +6469,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 @@ -8307,7 +8307,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 } @@ -10894,7 +10894,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 } @@ -16027,7 +16027,7 @@ func isESMFormatImportImportingCommonjsFormatFile(usageMode core.ResolutionMode, func (c *Checker) getTypeWithSyntheticDefaultOnly(t *Type, symbol *ast.Symbol, originalSymbol *ast.Symbol, moduleSpecifier *ast.Node, importAttributesType *Type) *Type { hasDefaultOnly := c.isOnlyImportableAsDefault(moduleSpecifier, nil, importAttributesType) 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 } @@ -16040,7 +16040,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 } @@ -17691,7 +17691,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) @@ -18775,7 +18775,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 } } @@ -18806,7 +18806,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) } @@ -22231,7 +22231,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*/) @@ -25019,7 +25019,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 } @@ -25032,7 +25032,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 } @@ -25043,7 +25043,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 } @@ -25051,7 +25051,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 } @@ -26014,7 +26014,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 } @@ -26173,12 +26173,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*/) @@ -27180,10 +27180,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 { @@ -27254,7 +27250,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 } @@ -27391,8 +27387,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 @@ -27955,7 +27951,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 } @@ -28452,7 +28448,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) } @@ -28627,7 +28623,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] } @@ -28699,7 +28695,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 } @@ -29468,7 +29464,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 } @@ -30990,7 +30986,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 } @@ -31307,7 +31303,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 } @@ -31830,7 +31826,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/tsc/internal/checker/emitresolver.go b/tsc/internal/checker/emitresolver.go index f0058eb2b28e3..c4ecf38e963e7 100644 --- a/tsc/internal/checker/emitresolver.go +++ b/tsc/internal/checker/emitresolver.go @@ -177,13 +177,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() { diff --git a/tsc/internal/checker/emitsupport.go b/tsc/internal/checker/emitsupport.go index 3da782c9ab4c4..b2bd842f97963 100644 --- a/tsc/internal/checker/emitsupport.go +++ b/tsc/internal/checker/emitsupport.go @@ -200,16 +200,16 @@ func (c *Checker) isEntityNameVisible(entityName *ast.Node, enclosingDeclaration func noopAddVisibleAlias(declaration *ast.Node, aliasingStatement *ast.Node) {} func (c *Checker) 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) { c.emitResolverLinks.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/tsc/internal/checker/flow.go b/tsc/internal/checker/flow.go index 24d2f4f48b566..0e1e52ffa3587 100644 --- a/tsc/internal/checker/flow.go +++ b/tsc/internal/checker/flow.go @@ -1507,7 +1507,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) @@ -2403,7 +2403,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/tsc/internal/checker/inference.go b/tsc/internal/checker/inference.go index c71e412fef47f..861e9a5d1b127 100644 --- a/tsc/internal/checker/inference.go +++ b/tsc/internal/checker/inference.go @@ -9,8 +9,8 @@ import ( ) type InferenceKey struct { - source TypeId - target TypeId + source *Type + target *Type priority InferencePriority contravariant bool bivariant bool @@ -344,7 +344,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{source: source.id, target: target.id, priority: n.priority, contravariant: n.contravariant, bivariant: n.bivariant} + key := InferenceKey{source: source, target: target, priority: n.priority, contravariant: n.contravariant, bivariant: n.bivariant} if status, ok := n.visited[key]; ok { n.inferencePriority = min(n.inferencePriority, status) return @@ -1013,7 +1013,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 } @@ -1075,7 +1075,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/tsc/internal/checker/jsx.go b/tsc/internal/checker/jsx.go index 4e7dc902d23c6..945a51e2c5521 100644 --- a/tsc/internal/checker/jsx.go +++ b/tsc/internal/checker/jsx.go @@ -264,7 +264,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/tsc/internal/checker/nodebuilder.go b/tsc/internal/checker/nodebuilder.go index a4fb793b334bf..9ca8a7be5af19 100644 --- a/tsc/internal/checker/nodebuilder.go +++ b/tsc/internal/checker/nodebuilder.go @@ -51,8 +51,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/tsc/internal/checker/nodebuilderimpl.go b/tsc/internal/checker/nodebuilderimpl.go index cd4643ac6f273..8a9ca215427a4 100644 --- a/tsc/internal/checker/nodebuilderimpl.go +++ b/tsc/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 inferTypeParameters CacheHashKey @@ -79,20 +79,20 @@ 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 - typeParameterNames collections.CopyOnWriteMap[TypeId, *ast.Identifier] + typeParameterNames collections.CopyOnWriteMap[*Type, *ast.Identifier] typeParameterNamesByText collections.CopyOnWriteSet[string] typeParameterNamesByTextNextNameCount collections.CopyOnWriteMap[string, int] - typeParameterSymbolList collections.CopyOnWriteSet[ast.SymbolId] + typeParameterSymbolList collections.CopyOnWriteSet[*ast.Symbol] } type NodeBuilderImpl struct { @@ -972,7 +972,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 } @@ -1037,11 +1037,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) - if b.ctx.typeParameterSymbolList.Has(symbolId) { + if b.ctx.typeParameterSymbolList.Has(symbol) { return nil } - b.ctx.typeParameterSymbolList.Add(symbolId) + b.ctx.typeParameterSymbolList.Add(symbol) if b.ctx.flags&nodebuilder.FlagsWriteTypeParametersInQualifiedName != 0 && index < (len(chain)-1) { if typeArgumentNodes := b.lookupInstantiatedTypeArgumentNodes(chain, index); typeArgumentNodes != nil { @@ -1476,7 +1475,7 @@ func (b *NodeBuilderImpl) typeParameterShadowsOtherTypeParameterInScope(name str func (b *NodeBuilderImpl) typeParameterToName(typeParameter *Type) *ast.Identifier { if b.ctx.flags&nodebuilder.FlagsGenerateNamesForShadowedTypeParams != 0 { - if cached, ok := b.ctx.typeParameterNames.Get(typeParameter.id); ok { + if cached, ok := b.ctx.typeParameterNames.Get(typeParameter); ok { return cached } } @@ -1495,10 +1494,7 @@ func (b *NodeBuilderImpl) typeParameterToName(typeParameter *Type) *ast.Identifi i, _ := b.ctx.typeParameterNamesByTextNextNameCount.Get(rawText) text := rawText - for true { - if !b.ctx.typeParameterNamesByText.Has(text) && !b.typeParameterShadowsOtherTypeParameterInScope(text, typeParameter) { - break - } + for b.ctx.typeParameterNamesByText.Has(text) || b.typeParameterShadowsOtherTypeParameterInScope(text, typeParameter) { i++ text = fmt.Sprintf("%s_%d", rawText, i) } @@ -1513,7 +1509,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.Set(rawText, i) - b.ctx.typeParameterNames.Set(typeParameter.id, result.AsIdentifier()) + b.ctx.typeParameterNames.Set(typeParameter, result.AsIdentifier()) b.ctx.typeParameterNamesByText.Add(text) } @@ -2105,7 +2101,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) } @@ -2271,7 +2267,7 @@ func (b *NodeBuilderImpl) serializeTypeForDeclaration(declaration *ast.Declarati t = b.ch.errorType } } else { - 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) @@ -2856,7 +2852,7 @@ func getTypeAliasForTypeLiteral(c *Checker, t *Type) *ast.Symbol { return nil } -func (b *NodeBuilderImpl) shouldWriteTypeOfFunctionSymbol(symbol *ast.Symbol, typeId TypeId) (bool, *ast.Symbol) { +func (b *NodeBuilderImpl) shouldWriteTypeOfFunctionSymbol(symbol *ast.Symbol, t *Type) (bool, *ast.Symbol) { // `typeof C.name` can only be written when the member name is a valid identifier isStaticMethodSymbol := symbol.Flags()&ast.SymbolFlagsMethod != 0 && scanner.IsIdentifierText(symbol.Name(), core.LanguageVariantStandard) && core.Some(symbol.Declarations(), func(declaration *ast.Node) bool { return ast.IsStatic(declaration) && !b.ch.isLateBindableIndexSignature(ast.GetNameOfDeclaration(declaration)) @@ -2888,7 +2884,7 @@ func (b *NodeBuilderImpl) shouldWriteTypeOfFunctionSymbol(symbol *ast.Symbol, ty symbol = b.ch.getMergedSymbol(symbol.ValueDeclaration().Parent.Symbol()) } // 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)), symbol // And the build is going to succeed without visibility error or there is no structural fallback allowed } return false, symbol @@ -2898,7 +2894,7 @@ func (b *NodeBuilderImpl) createAnonymousTypeNode(t *Type) *ast.TypeNode { return b.createAnonymousTypeNodeEx(t, false, false) } -func (b *NodeBuilderImpl) shouldEmitTypeOfSymbol(forceExpansion bool, forceClassExpansion bool, isInstanceType ast.SymbolFlags, symbol *ast.Symbol, typeId TypeId) (bool, *ast.Symbol) { +func (b *NodeBuilderImpl) shouldEmitTypeOfSymbol(forceExpansion bool, forceClassExpansion bool, isInstanceType ast.SymbolFlags, symbol *ast.Symbol, t *Type) (bool, *ast.Symbol) { if forceExpansion { return false, symbol } @@ -2906,11 +2902,10 @@ func (b *NodeBuilderImpl) shouldEmitTypeOfSymbol(forceExpansion bool, forceClass if nonFunctionResult { return true, symbol } - return b.shouldWriteTypeOfFunctionSymbol(symbol, typeId) + return b.shouldWriteTypeOfFunctionSymbol(symbol, t) } func (b *NodeBuilderImpl) createAnonymousTypeNodeEx(t *Type, forceClassExpansion bool, forceExpansion bool) *ast.TypeNode { - typeId := t.id symbol := t.symbol if symbol != nil { isInstantiationExpressionType := t.objectFlags&ObjectFlagsInstantiationExpressionType != 0 @@ -2930,17 +2925,17 @@ func (b *NodeBuilderImpl) createAnonymousTypeNodeEx(t *Type, forceClassExpansion // fallback re-enters typeToTypeNode with the very same instantiation type, which would // in turn try to reuse the same node again. Mark the type as visited around the reuse // attempt so the inner recursion bottoms out via the visitedTypes guard below. - if b.ctx.visitedTypes.Has(typeId) { + if b.ctx.visitedTypes.Has(t) { return b.createCyclicStructurePlaceholder() } - b.ctx.visitedTypes.Add(typeId) + b.ctx.visitedTypes.Add(t) typeNode := b.tryReuseExistingNonParameterTypeNode(existing, t, nil, nil) - b.ctx.visitedTypes.Delete(typeId) + b.ctx.visitedTypes.Delete(t) if typeNode != nil { return typeNode } } - if b.ctx.visitedTypes.Has(typeId) { + if b.ctx.visitedTypes.Has(t) { return b.createCyclicStructurePlaceholder() } return b.visitAndTransformType(t, (*NodeBuilderImpl).createTypeNodeFromObjectType) @@ -2957,14 +2952,14 @@ func (b *NodeBuilderImpl) createAnonymousTypeNodeEx(t *Type, forceClassExpansion // // Instance and static types share the same symbol; only add 'typeof' for the static side. // return b.symbolToTypeNode(symbol, isInstanceType, nil) // } else - if ok, symbol := b.shouldEmitTypeOfSymbol(forceExpansion, forceClassExpansion, isInstanceType, symbol, typeId); ok { + if ok, symbol := b.shouldEmitTypeOfSymbol(forceExpansion, forceClassExpansion, isInstanceType, symbol, t); ok { if b.shouldExpandType(t, false /*isAlias*/) { b.ctx.depth++ } else { return b.symbolToTypeNode(symbol, isInstanceType, nil) } } - if b.ctx.visitedTypes.Has(typeId) { + 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 { @@ -2977,7 +2972,7 @@ func (b *NodeBuilderImpl) createAnonymousTypeNodeEx(t *Type, forceClassExpansion return b.visitAndTransformType(t, (*NodeBuilderImpl).createTypeNodeFromObjectType) } } else if t.objectFlags&ObjectFlagsReverseMapped != 0 && b.ctx.flags&nodebuilder.FlagsAllowAnonymousIdentifier == 0 { - if b.ctx.visitedTypes.Has(typeId) { + if b.ctx.visitedTypes.Has(t) { return b.createCyclicStructurePlaceholder() } return b.visitAndTransformType(t, (*NodeBuilderImpl).createTypeNodeFromObjectType) @@ -3006,7 +3001,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) { return b.createCyclicStructurePlaceholder() } return b.visitAndTransformType(t, (*NodeBuilderImpl).typeToTypeNode) @@ -3236,13 +3231,13 @@ func (b *NodeBuilderImpl) visitAndTransformType(t *Type, transform func(b *NodeB return b.createElidedInformationPlaceholder() } - typeId := t.id + cycleType := t isArrayOrTuple := b.ch.isArrayOrTupleType(t) if isArrayOrTuple { // Deferred and regular references share a cycle identity. - typeId = b.ch.createTypeReference(t.Target(), b.ch.getTypeArguments(t)).id + cycleType = b.ch.createTypeReference(t.Target(), b.ch.getTypeArguments(t)) } - if b.ctx.visitedTypes.Has(typeId) { + if b.ctx.visitedTypes.Has(cycleType) { return b.createCyclicStructurePlaceholder() } @@ -3253,11 +3248,11 @@ func (b *NodeBuilderImpl) visitAndTransformType(t *Type, transform func(b *NodeB // Do not bound finite container nesting by the shared Array symbol or tuple origin. id = nil 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 } @@ -3265,7 +3260,7 @@ func (b *NodeBuilderImpl) visitAndTransformType(t *Type, transform func(b *NodeB // of types allows us to catch circular references to instantiations of the same anonymous type key := CompositeTypeCacheIdentity{ - typeId: typeId, + t: cycleType, flags: b.ctx.flags, internalFlags: b.ctx.internalFlags, } @@ -3293,7 +3288,7 @@ func (b *NodeBuilderImpl) visitAndTransformType(t *Type, transform func(b *NodeB if t.objectFlags&ObjectFlagsReverseMapped != 0 { // Growing type arguments can prevent a reverse mapped type from repeating. // Bound expansion by its mapped declaration as well as its type identity. - origin := CompositeSymbolIdentity{nodeId: ast.GetNodeId(t.AsReverseMappedType().mappedType.AsMappedType().declaration.AsNode())} + origin := CompositeSymbolIdentity{node: t.AsReverseMappedType().mappedType.AsMappedType().declaration.AsNode()} depth := b.ctx.symbolDepth[origin] if depth >= 100 { b.ctx.truncating = true @@ -3312,7 +3307,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(cycleType) prevTrackedSymbols := b.ctx.trackedSymbols b.ctx.trackedSymbols = nil startLength := b.ctx.approximateLength @@ -3330,7 +3325,7 @@ func (b *NodeBuilderImpl) visitAndTransformType(t *Type, transform func(b *NodeB trackedSymbols: b.ctx.trackedSymbols, } } - b.ctx.visitedTypes.Delete(typeId) + b.ctx.visitedTypes.Delete(cycleType) if id != nil { b.ctx.symbolDepth[*id] = depth } @@ -3753,12 +3748,11 @@ func (b *NodeBuilderImpl) lookupInstantiatedTypeArgumentNodes(chain []*ast.Symbo func (b *NodeBuilderImpl) lookupExpressionChainTypeArgumentNodes(chain []*ast.Symbol, index int) *ast.TypeParameterList { if b.shouldWriteTypeParametersInQualifiedName(chain, index) { symbol := chain[index] - symbolId := ast.GetSymbolId(symbol) - if b.ctx.typeParameterSymbolList.Has(symbolId) { + if b.ctx.typeParameterSymbolList.Has(symbol) { return nil } - b.ctx.typeParameterSymbolList.Add(symbolId) + b.ctx.typeParameterSymbolList.Add(symbol) if typeArgumentNodes := b.lookupInstantiatedTypeArgumentNodes(chain, index); typeArgumentNodes != nil { return typeArgumentNodes } diff --git a/tsc/internal/checker/nodebuilderscopes.go b/tsc/internal/checker/nodebuilderscopes.go index 244d598682c59..6bbefb1099d3e 100644 --- a/tsc/internal/checker/nodebuilderscopes.go +++ b/tsc/internal/checker/nodebuilderscopes.go @@ -38,14 +38,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/tsc/internal/checker/relater.go b/tsc/internal/checker/relater.go index a9bc484fef1d2..fe7b756a91495 100644 --- a/tsc/internal/checker/relater.go +++ b/tsc/internal/checker/relater.go @@ -287,7 +287,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/tsc/internal/checker/symbolaccessibility.go b/tsc/internal/checker/symbolaccessibility.go index ec8b9b754cac0..ca5a0590ec8dd 100644 --- a/tsc/internal/checker/symbolaccessibility.go +++ b/tsc/internal/checker/symbolaccessibility.go @@ -171,10 +171,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 { @@ -438,7 +438,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( @@ -455,7 +455,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. @@ -541,11 +541,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] @@ -881,9 +880,8 @@ func (c *Checker) someSymbolTableInScope( // bindAnonymousDeclaration and aren't stored in any container's locals, so this // synthesized table lets someSymbolTableInScope expose them during accessibility checks. func (c *Checker) getClassExpressionNameTable(location *ast.Node) ast.SymbolTable { - nodeId := ast.GetNodeId(location) if c.classExpressionNameTables != nil { - if table, ok := c.classExpressionNameTables[nodeId]; ok { + if table, ok := c.classExpressionNameTables[location]; ok { return table } } @@ -894,9 +892,9 @@ func (c *Checker) getClassExpressionNameTable(location *ast.Node) ast.SymbolTabl } table := ast.SymbolTable{nameText: classSymbol} if c.classExpressionNameTables == nil { - c.classExpressionNameTables = make(map[ast.NodeId]ast.SymbolTable) + c.classExpressionNameTables = make(map[*ast.Node]ast.SymbolTable) } - c.classExpressionNameTables[nodeId] = table + c.classExpressionNameTables[location] = table return table } diff --git a/tsc/internal/checker/types.go b/tsc/internal/checker/types.go index 7e4748930262c..99ef2f1affffc 100644 --- a/tsc/internal/checker/types.go +++ b/tsc/internal/checker/types.go @@ -333,8 +333,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/tsc/internal/ls/callhierarchy.go b/tsc/internal/ls/callhierarchy.go index 4796bcb3b7630..d0ebf8b0764a5 100644 --- a/tsc/internal/ls/callhierarchy.go +++ b/tsc/internal/ls/callhierarchy.go @@ -567,8 +567,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 { @@ -695,7 +695,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) @@ -977,7 +977,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/tsc/internal/ls/completions.go b/tsc/internal/ls/completions.go index 62564fbbd2f7e..0ba8c3c956b5b 100644 --- a/tsc/internal/ls/completions.go +++ b/tsc/internal/ls/completions.go @@ -176,7 +176,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 @@ -784,8 +784,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) && @@ -794,8 +794,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} @@ -803,9 +802,8 @@ func (l *LanguageService) getCompletionData( } addSymbolSortInfo := func(symbol *ast.Symbol) { - symbolId := ast.GetSymbolId(symbol) if isStaticProperty(symbol) { - symbolToSortTextMap[symbolId] = SortTextLocalDeclarationPriority + symbolToSortTextMap[symbol] = SortTextLocalDeclarationPriority } } @@ -832,13 +830,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) || @@ -847,7 +841,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) @@ -945,7 +939,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 { @@ -1169,21 +1163,20 @@ func (l *LanguageService) getCompletionData( // Set sort texts. 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 objectLikeContainer.Kind == ast.KindObjectLiteralExpression && preferences.IncludeCompletionsWithObjectLiteralMethodSnippets.IsTrue() { displayName, _ := getCompletionEntryDisplayNameForSymbol(file, preferences, member, nil /*origin*/, CompletionKindObjectPropertyDeclaration, false /*isJsxIdentifierExpected*/) if displayName != "" { - originalSortText := core.OrElse(symbolToSortTextMap[symbolId], SortTextLocationPriority) - symbolToSortTextMap[symbolId] = ObjectLiteralPropertySortText(originalSortText, displayName) + originalSortText := core.OrElse(symbolToSortTextMap[member], SortTextLocationPriority) + symbolToSortTextMap[member] = ObjectLiteralPropertySortText(originalSortText, displayName) } } } @@ -1411,8 +1404,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 } } @@ -1548,14 +1540,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 } } } @@ -1626,12 +1617,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) @@ -1654,10 +1644,9 @@ func (l *LanguageService) getCompletionData( ) 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 } } } @@ -1994,7 +1983,7 @@ func (l *LanguageService) getCompletionEntriesFromSymbols( continue } - originalSortText := data.symbolToSortTextMap[ast.GetSymbolId(symbol)] + originalSortText := data.symbolToSortTextMap[symbol] if originalSortText == "" { originalSortText = SortTextLocationPriority } @@ -3131,7 +3120,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 } @@ -3148,7 +3137,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) @@ -3373,7 +3362,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) || @@ -3384,9 +3373,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/tsc/internal/printer/namegenerator.go b/tsc/internal/printer/namegenerator.go index 81078f087a3bd..3e715e24a7beb 100644 --- a/tsc/internal/printer/namegenerator.go +++ b/tsc/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/tsc/internal/transformers/declarations/transform.go b/tsc/internal/transformers/declarations/transform.go index f2bb66a6803cb..fcf372a035836 100644 --- a/tsc/internal/transformers/declarations/transform.go +++ b/tsc/internal/transformers/declarations/transform.go @@ -73,10 +73,10 @@ type DeclarationTransformer struct { resultHasExternalModuleIndicator bool suppressNewDiagnosticContexts bool witnessedCjsExports collections.Set[string] - lateStatementReplacementMap map[ast.NodeId]*ast.Node - expandoHosts map[ast.NodeId]*ast.Node // store the result of transforming expando hosts so they can be inserted later if the host is actually referenced - expandoMembers map[ast.NodeId][]*ast.Node // store any found expando _members_ after transforming them so *if* the host is referenced, they can be emitted alongside it - deferredExpandoAssignments map[ast.NodeId][]*ast.BinaryExpression // expando assignments whose host wasn't visible when collected, processed if the host is late-marked visible + lateStatementReplacementMap map[*ast.Node]*ast.Node + expandoHosts map[*ast.Node]*ast.Node // store the result of transforming expando hosts so they can be inserted later if the host is actually referenced + expandoMembers map[*ast.Node][]*ast.Node // store any found expando _members_ after transforming them so *if* the host is referenced, they can be emitted alongside it + deferredExpandoAssignments map[*ast.Node][]*ast.BinaryExpression // expando assignments whose host wasn't visible when collected, processed if the host is late-marked visible seenProperties collections.Set[thisPropertyAssignmentKey] thisPropertyAssignmentsCollected []*ast.Node rawReferencedFiles []ReferencedFilePair @@ -289,10 +289,10 @@ 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 = make(map[ast.NodeId]*ast.Node) - tx.expandoMembers = make(map[ast.NodeId][]*ast.Node) - tx.deferredExpandoAssignments = make(map[ast.NodeId][]*ast.BinaryExpression) + tx.lateStatementReplacementMap = make(map[*ast.Node]*ast.Node) + tx.expandoHosts = make(map[*ast.Node]*ast.Node) + tx.expandoMembers = make(map[*ast.Node][]*ast.Node) + tx.deferredExpandoAssignments = make(map[*ast.Node][]*ast.BinaryExpression) tx.rawReferencedFiles = make([]ReferencedFilePair, 0) tx.rawTypeReferenceDirectives = make([]*ast.FileReference, 0) tx.rawLibReferenceDirectives = make([]*ast.FileReference, 0) @@ -410,8 +410,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 @@ -423,8 +422,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 @@ -1174,7 +1172,7 @@ func (tx *DeclarationTransformer) visitDeclarationStatements(input *ast.Node) *a case ast.KindExportAssignment: return tx.transformExportAssignment(input, input, input.Expression(), input.AsExportAssignment().IsExportEquals) 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) @@ -1741,11 +1739,10 @@ func (tx *DeclarationTransformer) transformTopLevelDeclaration(input *ast.Node) return nil } original := tx.EmitContext().MostOriginal(input) - id := ast.GetNodeId(original) - _, isExpandoHost := tx.expandoHosts[id] - _, hasDeferredExpandoAssignments := tx.deferredExpandoAssignments[id] + _, isExpandoHost := tx.expandoHosts[original] + _, hasDeferredExpandoAssignments := tx.deferredExpandoAssignments[original] if isExpandoHost || hasDeferredExpandoAssignments { - return tx.createFullExpandoBlock(id) + return tx.createFullExpandoBlock(original) } previousEnclosingDeclaration := tx.enclosingDeclaration @@ -1883,9 +1880,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, @@ -2773,13 +2769,13 @@ func (tx *DeclarationTransformer) transformExpandoAssignment(node *ast.BinaryExp return } - hostId := tx.getExpandoHostId(declaration) + hostKey := tx.getExpandoHost(declaration) if ast.IsDeclaration(declaration) && isDeclarationAndNotVisible(tx.EmitContext(), tx.resolver, declaration) { // The host isn't visible (yet) - printing the type of a visible declaration may still // late-mark it as visible (e.g. an exported variable whose type prints as `typeof host`), // so defer the assignment to be processed if and when that happens. - tx.deferredExpandoAssignments[hostId] = append(tx.deferredExpandoAssignments[hostId], node) + tx.deferredExpandoAssignments[hostKey] = append(tx.deferredExpandoAssignments[hostKey], node) return } @@ -2803,15 +2799,15 @@ func (tx *DeclarationTransformer) transformExpandoAssignment(node *ast.BinaryExp _, cleanupDiagnosticContext := tx.setupDiagnosticContext(node.AsNode()) defer cleanupDiagnosticContext() - preexistingExpandoHasExport := core.Some(tx.expandoMembers[hostId], ast.IsExportDeclaration) + preexistingExpandoHasExport := core.Some(tx.expandoMembers[hostKey], ast.IsExportDeclaration) if ast.IsIdentifier(node.Right) { if !preexistingExpandoHasExport { - tx.addExportModifierToExpandoMembers(hostId) + tx.addExportModifierToExpandoMembers(hostKey) } // alias-like, emit an `export {name}` or `export {name as alias}` result := tx.transformBinaryExpressionToExportDeclaration(node.AsNode(), exportName) - tx.expandoMembers[hostId] = append(tx.expandoMembers[hostId], result) + tx.expandoMembers[hostKey] = append(tx.expandoMembers[hostKey], result) return } @@ -2856,33 +2852,32 @@ func (tx *DeclarationTransformer) transformExpandoAssignment(node *ast.BinaryExp statements = append(statements, tx.Factory().NewExportDeclaration(nil /*modifiers*/, false /*isTypeOnly*/, namedExports, nil /*moduleSpecifier*/, nil /*attributes*/)) if !preexistingExpandoHasExport { // Done before adding statements to expando members to keep the initial variable statement, before we rename anything, private - tx.addExportModifierToExpandoMembers(hostId) + tx.addExportModifierToExpandoMembers(hostKey) } } - tx.expandoMembers[hostId] = append(tx.expandoMembers[hostId], statements...) + tx.expandoMembers[hostKey] = append(tx.expandoMembers[hostKey], statements...) } -func (tx *DeclarationTransformer) addExportModifierToExpandoMembers(hostId ast.NodeId) { +func (tx *DeclarationTransformer) addExportModifierToExpandoMembers(host *ast.Node) { // Add an `export` modifier to all existing expando members so they remain exported after the `export {}` is added - for _, decl := range tx.expandoMembers[hostId] { + for _, decl := range tx.expandoMembers[host] { // only invoked when `tx.expandoMembers` does not *yet* contain an `export` declaration, so no need to skip one here to prevent `export export {}` modifierFlags := ast.ModifierFlagsExport | ast.GetCombinedModifierFlags(decl) decl.AsMutable().SetModifiers(tx.Factory().NewModifierList(ast.CreateModifiersFromModifierFlags(modifierFlags, tx.Factory().NewModifier))) } } -func (tx *DeclarationTransformer) getExpandoHostId(declaration *ast.Declaration) ast.NodeId { +func (tx *DeclarationTransformer) getExpandoHost(declaration *ast.Declaration) *ast.Node { root := core.IfElse(ast.IsVariableDeclaration(declaration), declaration.Parent.Parent, declaration) - id := ast.GetNodeId(tx.EmitContext().MostOriginal(root)) - return id + return tx.EmitContext().MostOriginal(root) } func (tx *DeclarationTransformer) transformExpandoHost(name *ast.Node, declaration *ast.Declaration) { root := core.IfElse(ast.IsVariableDeclaration(declaration), declaration.Parent.Parent, declaration) - id := tx.getExpandoHostId(declaration) + host := tx.getExpandoHost(declaration) - if _, ok := tx.expandoHosts[id]; ok { + if _, ok := tx.expandoHosts[host]; ok { return } @@ -2914,7 +2909,7 @@ func (tx *DeclarationTransformer) transformExpandoHost(name *ast.Node, declarati typeParameters, parameters, asteriskToken := extractExpandoHostParams(fn) replacement = append(replacement, tx.Factory().NewFunctionDeclaration(modifiers, asteriskToken, tx.Factory().NewIdentifier(name.Text()), tx.ensureTypeParams(fn, typeParameters), tx.updateParamList(fn, parameters), tx.ensureType(fn, false), nil /*fullSignature*/, nil /*body*/)) } else { - tx.expandoHosts[id] = tx.transformTopLevelDeclaration(declaration) + tx.expandoHosts[host] = tx.transformTopLevelDeclaration(declaration) return } @@ -2929,24 +2924,24 @@ func (tx *DeclarationTransformer) transformExpandoHost(name *ast.Node, declarati } // store host result to be added to the output when it's actually visited - tx.expandoHosts[id] = tx.Factory().NewSyntaxList(replacement) - if _, ok := tx.lateStatementReplacementMap[id]; ok { - tx.lateStatementReplacementMap[id] = tx.createFullExpandoBlock(id) + tx.expandoHosts[host] = tx.Factory().NewSyntaxList(replacement) + if _, ok := tx.lateStatementReplacementMap[host]; ok { + tx.lateStatementReplacementMap[host] = tx.createFullExpandoBlock(host) } } -func (tx *DeclarationTransformer) createFullExpandoBlock(id ast.NodeId) *ast.Node { +func (tx *DeclarationTransformer) createFullExpandoBlock(hostKey *ast.Node) *ast.Node { // Process any expando assignments on this host that were skipped because it wasn't // visible when they were collected - if it's still not visible, they simply get // re-deferred, and are dropped if the host is never late-marked visible. - if deferred, ok := tx.deferredExpandoAssignments[id]; ok { - delete(tx.deferredExpandoAssignments, id) + if deferred, ok := tx.deferredExpandoAssignments[hostKey]; ok { + delete(tx.deferredExpandoAssignments, hostKey) for _, assignment := range deferred { tx.transformExpandoAssignment(assignment) } } - n := tx.expandoHosts[id] - if addOns, ok := tx.expandoMembers[id]; ok { + n := tx.expandoHosts[hostKey] + if addOns, ok := tx.expandoMembers[hostKey]; ok { var modifiers *ast.ModifierList var name *ast.Node var host []*ast.Node