Skip to content

Commit d19f2b4

Browse files
committed
Order and intern types by content instead of by type id
CompareTypes orders the constituents of unions, and so printed types, union deduplication, and everything derived from them. Many types it cannot tell apart fell through to the type id, which follows creation order, so these results depended on what had been checked before. Most such ties were copies: checking the same expression again (inference passes, overload resolution, contextual re-checks) created a new type with identical content every time. Types that are the same by content are now interned, so the same inputs yield the same type whenever and however often they are computed: object literal types, spread results and the property symbols they synthesize, widened, regular, and padded copies of object literals, object rest types, types implied by binding patterns, intersections with the same constituents, flags, and alias, and deferred indexed accesses, which are keyed by the flags they record rather than by transient ones. Interned object types are keyed by their members in table order, so spreads such as { ...a, ...b } and { ...b, ...a } stay distinct and each keeps its own property order. Types that remain distinct are ordered by how they were derived: - type parameters sharing a symbol (tuple elements, clones made for signature and mapped type instantiation, distributive and restrictive copies) by the kind of copy, then by their origin and the instantiation they were made for; - fresh and regular literal types, array literal types after the references they were cloned from, and object literal copies by the flags they were created with; - object literal, rest, and binding pattern types by their members, compared by declaration and name rather than by symbol id; - tuple targets by their label declarations. isDeeplyNestedType counts only occurrences of a recursion identity newer than the previous one, using type ids for "newer", so whether a comparison gave up as deeply nested depended on what had been checked before. It now uses a type's generation, one more than that of the types it was built from, which captures the same ordering wherever it follows from how the types are built, and nothing else. The pseudo-type printer reused the declared type of an inferred property assignment when the expression's widened type matched, but that type is widened without the context of its object literal and can differ from the real one. It is now reused only when equivalent.
1 parent 5a79252 commit d19f2b4

36 files changed

Lines changed: 755 additions & 338 deletions

File tree

‎tsc/internal/checker/checker.go‎

Lines changed: 293 additions & 25 deletions
Large diffs are not rendered by default.

‎tsc/internal/checker/pseudotypenodebuilder.go‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -699,6 +699,14 @@ func (b *NodeBuilderImpl) pseudoTypeToType(t *pseudochecker.PseudoType) *Type {
699699
return b.ch.getReturnTypeOfSignature(b.ch.getSignatureFromDeclaration(node))
700700
}
701701
ty := b.ch.getWidenedType(b.ch.getRegularTypeOfExpression(node))
702+
if ast.IsPropertyAssignment(node.Parent) {
703+
// pseudoTypeToNode serializes the type of the property's symbol, which is
704+
// not widened in the context of its containing object literal.
705+
declared := b.ch.getWidenedLiteralType(b.ch.getTypeOfSymbol(b.ch.getSymbolOfDeclaration(node.Parent)))
706+
if declared != ty {
707+
return nil
708+
}
709+
}
702710
return ty
703711
case pseudochecker.PseudoTypeKindNoResult:
704712
return nil // TODO: extract type selection logic from `serializeTypeForDeclaration`, not needed for current usecases but needed if completeness becomes required

‎tsc/internal/checker/relater.go‎

Lines changed: 91 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import (
1010
"github.com/microsoft/TypeScript/tsc/internal/binder"
1111
"github.com/microsoft/TypeScript/tsc/internal/collections"
1212
"github.com/microsoft/TypeScript/tsc/internal/core"
13+
"github.com/microsoft/TypeScript/tsc/internal/debug"
1314
"github.com/microsoft/TypeScript/tsc/internal/diagnostics"
1415
"github.com/microsoft/TypeScript/tsc/internal/jsnum"
1516
"github.com/microsoft/TypeScript/tsc/internal/stringutil"
@@ -776,25 +777,110 @@ func (c *Checker) isDeeplyNestedType(t *Type, stack []*Type, maxDepth int) bool
776777
} else {
777778
identity := getRecursionIdentityFromTarget(target)
778779
count := 0
779-
lastTypeId := TypeId(0)
780+
lastGeneration := 0
780781
for _, t := range stack {
781782
if hasMatchingRecursionIdentity(t, identity) {
782-
// We only count occurrences with a higher type id than the previous occurrence, since higher
783-
// type ids are an indicator of newer instantiations caused by recursion.
784-
if t.id >= lastTypeId {
783+
// We only count occurrences of a generation at least that of the previous occurrence, since
784+
// newer instantiations caused by recursion are built from the previous ones, whereas nested
785+
// type arguments are older than the types they are arguments of.
786+
generation := c.typeGeneration(t)
787+
if generation >= lastGeneration {
785788
count++
786789
if count >= maxDepth {
787790
return true
788791
}
789792
}
790-
lastTypeId = t.id
793+
lastGeneration = generation
791794
}
792795
}
793796
}
794797
}
795798
return false
796799
}
797800

801+
const (
802+
maxTypeGeneration = 1<<16 - 3
803+
typeGenerationInProgress = 1<<16 - 1
804+
)
805+
806+
// typeGeneration returns one more than the highest generation of the types t
807+
// was instantiated from, or zero if it was not instantiated from any. A type is
808+
// created after the types it is instantiated from, so this orders types by
809+
// creation where the order follows from their structure, and unlike type ids
810+
// does not depend on the order in which unrelated types were created.
811+
func (c *Checker) typeGeneration(t *Type) int {
812+
debug.Assert(t.generation != typeGenerationInProgress, "types are only built from existing types")
813+
if t.generation != 0 {
814+
return int(t.generation) - 1
815+
}
816+
t.generation = typeGenerationInProgress
817+
generation := 0
818+
switch {
819+
case t.flags&TypeFlagsObject != 0:
820+
if t.objectFlags&ObjectFlagsReference != 0 && t.AsTypeReference().node == nil {
821+
generation = c.typesGeneration(t.AsTypeReference().resolvedTypeArguments)
822+
} else if m := t.AsObjectType().mapper; m != nil {
823+
generation = c.mapperGeneration(m)
824+
} else if t.symbol != nil && t.symbol.Flags()&ast.SymbolFlagsObjectLiteral != 0 {
825+
// Object literals are built from the types of their properties,
826+
// except for those resolved lazily, such as accessors.
827+
for prop := range t.AsStructuredType().members.Values() {
828+
if prop.Flags()&ast.SymbolFlagsTransient == 0 || prop.CheckFlags()&(ast.CheckFlagsInstantiated|ast.CheckFlagsMapped|ast.CheckFlagsReverseMapped|ast.CheckFlagsDeferredType) != 0 {
829+
continue
830+
}
831+
if propType := c.valueSymbolLinks.Get(prop).resolvedType; propType != nil {
832+
generation = max(generation, c.typeGeneration(propType)+1)
833+
}
834+
}
835+
}
836+
case t.flags&TypeFlagsConditional != 0:
837+
if m := t.AsConditionalType().mapper; m != nil {
838+
generation = c.mapperGeneration(m)
839+
}
840+
case t.flags&TypeFlagsIndexedAccess != 0:
841+
d := t.AsIndexedAccessType()
842+
generation = max(c.typeGeneration(d.objectType), c.typeGeneration(d.indexType)) + 1
843+
case t.flags&TypeFlagsUnionOrIntersection != 0, t.flags&TypeFlagsTemplateLiteral != 0:
844+
generation = c.typesGeneration(t.Types())
845+
case t.flags&TypeFlagsIndex != 0, t.flags&TypeFlagsStringMapping != 0:
846+
generation = c.typeGeneration(t.Target()) + 1
847+
case t.flags&TypeFlagsSubstitution != 0:
848+
d := t.AsSubstitutionType()
849+
generation = max(c.typeGeneration(d.baseType), c.typeGeneration(d.constraint)) + 1
850+
}
851+
generation = min(generation, maxTypeGeneration)
852+
t.generation = uint16(generation + 1)
853+
return generation
854+
}
855+
856+
func (c *Checker) typesGeneration(types []*Type) int {
857+
generation := -1
858+
for _, t := range types {
859+
generation = max(generation, c.typeGeneration(t))
860+
}
861+
return generation + 1
862+
}
863+
864+
// mapperGeneration returns one more than the highest generation of the types
865+
// that m maps to, as far as they are known without computing them.
866+
func (c *Checker) mapperGeneration(m *TypeMapper) int {
867+
switch m.kind {
868+
case TypeMapperKindSimple:
869+
return c.typeGeneration(castTypeMapper[SimpleTypeMapper](m, TypeMapperKindSimple).target) + 1
870+
case TypeMapperKindArray:
871+
return c.typesGeneration(castTypeMapper[ArrayTypeMapper](m, TypeMapperKindArray).targets)
872+
case TypeMapperKindArrayToSingle:
873+
return c.typeGeneration(castTypeMapper[ArrayToSingleTypeMapper](m, TypeMapperKindArrayToSingle).target) + 1
874+
case TypeMapperKindMerged:
875+
d := castTypeMapper[MergedTypeMapper](m, TypeMapperKindMerged)
876+
return max(c.mapperGeneration(d.m1), c.mapperGeneration(d.m2))
877+
case TypeMapperKindComposite:
878+
d := castTypeMapper[CompositeTypeMapper](m, TypeMapperKindComposite)
879+
return max(c.mapperGeneration(d.m1), c.mapperGeneration(d.m2))
880+
}
881+
return 0
882+
}
883+
798884
func hasMatchingRecursionIdentity(t *Type, identity RecursionId) bool {
799885
target := getRecursionIdentityTarget(t)
800886
if target.flags&TypeFlagsIntersection != 0 {

‎tsc/internal/checker/types.go‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -790,6 +790,7 @@ type Type struct {
790790
objectFlags ObjectFlags
791791
id TypeId
792792
kind typeKind `customlint:"protected"`
793+
generation uint16 // see Checker.typeGeneration; zero until computed
793794
symbol *ast.Symbol
794795
alias *TypeAlias
795796
checker *Checker
@@ -1505,6 +1506,7 @@ type TypeParameter struct {
15051506
isDistributed bool
15061507
resolvedDefaultType *Type
15071508
distributedType *Type
1509+
origin *Type // The type parameter a restrictive type parameter was made from, or the tuple target of a tuple element type parameter
15081510
}
15091511

15101512
func (t *TypeParameter) IsThisType() bool { return t.isThisType }

‎tsc/internal/checker/types_test.go‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -177,11 +177,12 @@ func BenchmarkTypeListKey(b *testing.B) {
177177

178178
func newCompositeTestChecker() (*Checker, []*Type) {
179179
c := &Checker{
180-
strictNullChecks: true,
181-
unionTypes: make(map[CacheHashKey]*Type),
182-
unionOfUnionTypes: make(map[UnionOfUnionKey]*Type),
183-
intersectionTypes: make(map[CacheHashKey]*Type),
184-
subtypeReductionCache: make(map[CacheHashKey][]*Type),
180+
strictNullChecks: true,
181+
unionTypes: make(map[CacheHashKey]*Type),
182+
unionOfUnionTypes: make(map[UnionOfUnionKey]*Type),
183+
intersectionTypes: make(map[CacheHashKey]*Type),
184+
intersectionContentTypes: make(map[CacheHashKey]*Type),
185+
subtypeReductionCache: make(map[CacheHashKey][]*Type),
185186
}
186187
c.compareSymbols = c.compareSymbolsWorker
187188
c.neverType = c.newIntrinsicType(TypeFlagsNever, "never")

0 commit comments

Comments
 (0)