Skip to content

Commit ee7491f

Browse files
committed
Count only expanding type references as nested recursion
Comparing types assumes a comparison holds once it is nested in three others of types with the same recursion identity, and inference stops at two. A type reference created while resolving a type node was tracked by itself rather than by its symbol, as it cannot be the source of generative recursion without being instantiated. Type references are interned, so this depended on how a reference was first created. In interface A<T> { slice(): B<T>; every<S extends T>(predicate: (value: T) => value is S): this is A<S>; flatMap<U>(callback: (value: T) => U | readonly U[] | A<U>): U[]; } interface B<T> extends A<T> {} const a: A<0> = []; const b: B<0> = []; B<0> was tracked by itself when the annotation of b was resolved before checking a instantiated slice, and by its symbol otherwise, so the comparison for b was cut short at different depths, changing the error it reported. Cutting a comparison short can also change whether the types are related. Type references are all tracked by their symbol, and a nested occurrence of one counts toward the limit only if it is built from one of the type arguments of the occurrence before it, as each step of an infinitely expanding instantiation is. Otherwise the same generic type can occur nested with unrelated type arguments, as Promise<IteratorResult<T>> does within Promise<AsyncIterable<T>> when inferring from an async iterable (seen in rakazo), which must not stop the inference. Other types keep counting any occurrence no older than the one before it, as they may be built from parts of the types they were instantiated from, extracted by inference. (seen in 54921)
1 parent 1b19647 commit ee7491f

10 files changed

Lines changed: 197 additions & 80 deletions

File tree

‎packages/typescript/enums/objectFlags.d.ts‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,6 @@ export declare enum ObjectFlags {
3636
IsClassInstanceClone = 1 << 26,
3737
IdenticalBaseTypeCalculated = 1 << 27,
3838
IdenticalBaseTypeExists = 1 << 28,
39-
FromTypeNode = 1 << 29,
4039
IsGenericTypeComputed = 1 << 22,
4140
IsGenericObjectType = 1 << 23,
4241
IsGenericIndexType = 1 << 24,

‎packages/typescript/enums/objectFlags.js‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,6 @@ export var ObjectFlags;
3636
ObjectFlags[ObjectFlags["IsClassInstanceClone"] = 67108864] = "IsClassInstanceClone";
3737
ObjectFlags[ObjectFlags["IdenticalBaseTypeCalculated"] = 134217728] = "IdenticalBaseTypeCalculated";
3838
ObjectFlags[ObjectFlags["IdenticalBaseTypeExists"] = 268435456] = "IdenticalBaseTypeExists";
39-
ObjectFlags[ObjectFlags["FromTypeNode"] = 536870912] = "FromTypeNode";
4039
ObjectFlags[ObjectFlags["IsGenericTypeComputed"] = 4194304] = "IsGenericTypeComputed";
4140
ObjectFlags[ObjectFlags["IsGenericObjectType"] = 8388608] = "IsGenericObjectType";
4241
ObjectFlags[ObjectFlags["IsGenericIndexType"] = 16777216] = "IsGenericIndexType";

‎tsc/internal/api/enum_values_generated.go‎

Lines changed: 0 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎tsc/internal/checker/checker.go‎

Lines changed: 9 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -24593,7 +24593,7 @@ func (c *Checker) getTypeFromClassOrInterfaceReference(node *ast.Node, symbol *a
2459324593
// of the class or interface.
2459424594
localTypeArguments := c.fillMissingTypeArguments(c.getTypeArgumentsFromNode(node), typeParameters, minTypeArgumentCount, isJs)
2459524595
typeArguments := append(d.OuterTypeParameters(), localTypeArguments...)
24596-
return c.createTypeReferenceEx(t, typeArguments, ObjectFlagsFromTypeNode)
24596+
return c.createTypeReference(t, typeArguments)
2459724597
}
2459824598
if c.checkNoTypeArguments(node, symbol) {
2459924599
return t
@@ -24688,11 +24688,11 @@ func (c *Checker) createNormalizedTypeReference(target *Type, typeArguments []*T
2468824688
return c.createTypeReference(target, typeArguments)
2468924689
}
2469024690

24691-
func (c *Checker) createNormalizedTupleTypeEx(target *Type, elementTypes []*Type, objectFlags ObjectFlags) *Type {
24691+
func (c *Checker) createNormalizedTupleType(target *Type, elementTypes []*Type) *Type {
2469224692
d := target.AsTupleType()
2469324693
if d.combinedFlags&ElementFlagsNonRequired == 0 {
2469424694
// No need to normalize when we only have regular required elements
24695-
return c.createTypeReferenceEx(target, elementTypes, objectFlags)
24695+
return c.createTypeReference(target, elementTypes)
2469624696
}
2469724697
if d.combinedFlags&ElementFlagsVariadic != 0 {
2469824698
for i, e := range elementTypes {
@@ -24706,7 +24706,7 @@ func (c *Checker) createNormalizedTupleTypeEx(target *Type, elementTypes []*Type
2470624706
})
2470724707
if c.checkCrossProductUnion(checkTypes) {
2470824708
return c.mapType(e, func(t *Type) *Type {
24709-
return c.createNormalizedTupleTypeEx(target, core.ReplaceElement(elementTypes, i, t), objectFlags)
24709+
return c.createNormalizedTupleType(target, core.ReplaceElement(elementTypes, i, t))
2471024710
})
2471124711
}
2471224712
}
@@ -24731,15 +24731,11 @@ func (c *Checker) createNormalizedTupleTypeEx(target *Type, elementTypes []*Type
2473124731
case tupleTarget == c.emptyGenericType:
2473224732
return c.emptyObjectType
2473324733
case len(n.types) != 0:
24734-
return c.createTypeReferenceEx(tupleTarget, n.types, objectFlags)
24734+
return c.createTypeReference(tupleTarget, n.types)
2473524735
}
2473624736
return tupleTarget
2473724737
}
2473824738

24739-
func (c *Checker) createNormalizedTupleType(target *Type, elementTypes []*Type) *Type {
24740-
return c.createNormalizedTupleTypeEx(target, elementTypes, ObjectFlagsNone)
24741-
}
24742-
2474324739
type TupleNormalizer struct {
2474424740
c *Checker
2474524741
types []*Type
@@ -25532,9 +25528,9 @@ func (c *Checker) getTypeFromArrayOrTupleTypeNode(node *ast.Node) *Type {
2553225528
elementTypes = core.Map(node.Elements(), c.getTypeFromTypeNode)
2553325529
}
2553425530
if target.objectFlags&ObjectFlagsTuple != 0 {
25535-
links.resolvedType = c.createNormalizedTupleTypeEx(target, elementTypes, ObjectFlagsFromTypeNode)
25531+
links.resolvedType = c.createNormalizedTupleType(target, elementTypes)
2553625532
} else {
25537-
links.resolvedType = c.createTypeReferenceEx(target, elementTypes, ObjectFlagsFromTypeNode)
25533+
links.resolvedType = c.createTypeReference(target, elementTypes)
2553825534
}
2553925535
}
2554025536
}
@@ -26526,16 +26522,12 @@ func (c *Checker) tryCreateTypeReference(target *Type, typeArguments []*Type) *T
2652626522
}
2652726523

2652826524
func (c *Checker) createTypeReference(target *Type, typeArguments []*Type) *Type {
26529-
return c.createTypeReferenceEx(target, typeArguments, ObjectFlagsNone)
26530-
}
26531-
26532-
func (c *Checker) createTypeReferenceEx(target *Type, typeArguments []*Type, objectFlags ObjectFlags) *Type {
2653326525
id := getTypeListKey(typeArguments)
2653426526
intf := target.AsInterfaceType()
2653526527
if t, ok := intf.instantiations[id]; ok {
2653626528
return t
2653726529
}
26538-
t := c.newObjectType(ObjectFlagsReference|objectFlags|c.getPropagatingFlagsOfTypes(typeArguments, TypeFlagsNone), target.symbol)
26530+
t := c.newObjectType(ObjectFlagsReference|c.getPropagatingFlagsOfTypes(typeArguments, TypeFlagsNone), target.symbol)
2653926531
d := t.AsTypeReference()
2654026532
d.target = target
2654126533
d.resolvedTypeArguments = typeArguments
@@ -29041,7 +29033,7 @@ func (c *Checker) walkBaseConstraint(t *Type, stack []baseConstraintFrame) (*Typ
2904129033
// levels of nesting, we are presumably exploring a repeating pattern with a long cycle that hasn't
2904229034
// yet triggered the deeply nested limiter. We have no test cases that actually get to 50 levels of
2904329035
// nesting, so it is effectively just a safety stop.
29044-
identity := getRecursionIdentity(t)
29036+
identity := c.getRecursionIdentity(t)
2904529037
generation := c.typeGeneration(t)
2904629038
if len(stack) < baseConstraintFreeDepth || len(stack) < baseConstraintMaxDepth && !c.repeatsInBaseConstraintWalk(identity, generation, stack) {
2904729039
constraint = c.computeBaseConstraint(c.getSimplifiedType(t /*writing*/, false), append(stack, baseConstraintFrame{identity, generation}))

‎tsc/internal/checker/relater.go‎

Lines changed: 149 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -778,22 +778,19 @@ func (c *Checker) isDeeplyNestedType(t *Type, stack []*Type, maxDepth int) bool
778778
}
779779
}
780780
} else {
781-
identity := getRecursionIdentityFromTarget(target)
781+
identity := c.getRecursionIdentityFromTarget(target)
782782
count := 0
783-
lastGeneration := 0
783+
var previous *Type
784784
for _, t := range stack {
785-
if hasMatchingRecursionIdentity(t, identity) {
786-
// We only count occurrences of a generation at least that of the previous occurrence, since
787-
// newer instantiations caused by recursion are built from the previous ones, whereas nested
788-
// type arguments are older than the types they are arguments of.
789-
generation := c.typeGeneration(t)
790-
if generation >= lastGeneration {
785+
if c.hasMatchingRecursionIdentity(t, identity) {
786+
// We only count occurrences that may continue an expansion from the previous occurrence.
787+
if previous == nil || c.continuesExpansion(t, previous) {
791788
count++
792789
if count >= maxDepth {
793790
return true
794791
}
795792
}
796-
lastGeneration = generation
793+
previous = t
797794
}
798795
}
799796
}
@@ -884,6 +881,140 @@ func (c *Checker) mapperGeneration(m *TypeMapper) int {
884881
return 0
885882
}
886883

884+
// continuesExpansion reports whether t, an occurrence of a recursion identity
885+
// nested within the occurrence previous, may be the next step of an infinitely
886+
// expanding instantiation. Newer instantiations caused by recursion are built
887+
// from the previous ones, so such a step is no older than the one before it,
888+
// whereas nested type arguments are older than the types they are arguments
889+
// of. A step from a type reference is moreover built from one of its type
890+
// arguments, whereas the same generic type may otherwise occur nested with
891+
// unrelated type arguments, as Promise<IteratorResult<T>> does within
892+
// Promise<AsyncIterable<T>>. Other types may be built from parts of the types
893+
// they were instantiated from, extracted by inference, so any step from them
894+
// that is no older counts, as does one built from types not known.
895+
func (c *Checker) continuesExpansion(t *Type, previous *Type) bool {
896+
if c.typeGeneration(t) < c.typeGeneration(previous) {
897+
return false
898+
}
899+
if t == previous || previous.objectFlags&ObjectFlagsReference == 0 || previous.AsTypeReference().node != nil {
900+
return true
901+
}
902+
typeArguments := previous.AsTypeReference().resolvedTypeArguments
903+
known := true
904+
for _, s := range typeArguments {
905+
found, k := c.isBuiltFrom(t, s)
906+
if found {
907+
return true
908+
}
909+
known = known && k
910+
}
911+
return len(typeArguments) == 0 || !known
912+
}
913+
914+
// isBuiltFrom reports whether t is s, or was instantiated, transitively, from
915+
// s, as typeGeneration counts the types a type was instantiated from, and
916+
// whether the types t was built from were all known.
917+
func (c *Checker) isBuiltFrom(t *Type, s *Type) (found bool, known bool) {
918+
if t == s {
919+
return true, true
920+
}
921+
target := c.typeGeneration(s)
922+
known = true
923+
var visited collections.Set[*Type]
924+
var visit func(t *Type) bool
925+
visit = func(t *Type) bool {
926+
if t == s {
927+
return true
928+
}
929+
if t == nil || c.typeGeneration(t) <= target || visited.Has(t) {
930+
return false
931+
}
932+
visited.Add(t)
933+
builtFrom := false
934+
if !c.visitTypeSources(t, func(u *Type) {
935+
if !builtFrom && visit(u) {
936+
builtFrom = true
937+
}
938+
}) {
939+
known = false
940+
}
941+
return builtFrom
942+
}
943+
found = visit(t)
944+
return found, known
945+
}
946+
947+
// visitTypeSources calls f with each type t was instantiated from, as
948+
// typeGeneration counts them, and reports whether those are all known.
949+
func (c *Checker) visitTypeSources(t *Type, f func(*Type)) bool {
950+
switch {
951+
case t.flags&TypeFlagsObject != 0:
952+
if t.objectFlags&ObjectFlagsReference != 0 {
953+
if t.AsTypeReference().node != nil {
954+
return false
955+
}
956+
for _, a := range t.AsTypeReference().resolvedTypeArguments {
957+
f(a)
958+
}
959+
} else if m := t.AsObjectType().mapper; m != nil {
960+
return c.visitMapperTargets(m, f)
961+
} else if t.symbol != nil && t.symbol.Flags()&ast.SymbolFlagsObjectLiteral != 0 {
962+
for prop := range t.AsStructuredType().members.Values() {
963+
if prop.Flags()&ast.SymbolFlagsTransient == 0 || prop.CheckFlags()&(ast.CheckFlagsInstantiated|ast.CheckFlagsMapped|ast.CheckFlagsReverseMapped|ast.CheckFlagsDeferredType) != 0 {
964+
continue
965+
}
966+
if propType := c.peekTypeOfObjectLiteralMember(prop); propType != nil {
967+
f(propType)
968+
}
969+
}
970+
}
971+
case t.flags&TypeFlagsConditional != 0:
972+
if m := t.AsConditionalType().mapper; m != nil {
973+
return c.visitMapperTargets(m, f)
974+
}
975+
case t.flags&TypeFlagsIndexedAccess != 0:
976+
d := t.AsIndexedAccessType()
977+
f(d.objectType)
978+
f(d.indexType)
979+
case t.flags&TypeFlagsUnionOrIntersection != 0, t.flags&TypeFlagsTemplateLiteral != 0:
980+
for _, u := range t.Types() {
981+
f(u)
982+
}
983+
case t.flags&TypeFlagsIndex != 0, t.flags&TypeFlagsStringMapping != 0:
984+
f(t.Target())
985+
case t.flags&TypeFlagsSubstitution != 0:
986+
d := t.AsSubstitutionType()
987+
f(d.baseType)
988+
f(d.constraint)
989+
}
990+
return true
991+
}
992+
993+
// visitMapperTargets calls f with each type m maps to, as mapperGeneration
994+
// counts them, and reports whether those are all known.
995+
func (c *Checker) visitMapperTargets(m *TypeMapper, f func(*Type)) bool {
996+
switch m.kind {
997+
case TypeMapperKindSimple:
998+
f(castTypeMapper[SimpleTypeMapper](m, TypeMapperKindSimple).target)
999+
return true
1000+
case TypeMapperKindArray:
1001+
for _, t := range castTypeMapper[ArrayTypeMapper](m, TypeMapperKindArray).targets {
1002+
f(t)
1003+
}
1004+
return true
1005+
case TypeMapperKindArrayToSingle:
1006+
f(castTypeMapper[ArrayToSingleTypeMapper](m, TypeMapperKindArrayToSingle).target)
1007+
return true
1008+
case TypeMapperKindMerged:
1009+
d := castTypeMapper[MergedTypeMapper](m, TypeMapperKindMerged)
1010+
return c.visitMapperTargets(d.m1, f) && c.visitMapperTargets(d.m2, f)
1011+
case TypeMapperKindComposite:
1012+
d := castTypeMapper[CompositeTypeMapper](m, TypeMapperKindComposite)
1013+
return c.visitMapperTargets(d.m1, f) && c.visitMapperTargets(d.m2, f)
1014+
}
1015+
return false
1016+
}
1017+
8871018
// deeplyNestedStart returns the highest index in stack from which t is still
8881019
// deeply nested, or -1 if it is not deeply nested. Comparisons starting at or
8891020
// below that index would be truncated the same way.
@@ -899,21 +1030,21 @@ func (c *Checker) deeplyNestedStart(t *Type, stack []*Type, maxDepth int) int {
8991030
return 0
9001031
}
9011032

902-
func hasMatchingRecursionIdentity(t *Type, identity RecursionId) bool {
1033+
func (c *Checker) hasMatchingRecursionIdentity(t *Type, identity RecursionId) bool {
9031034
target := getRecursionIdentityTarget(t)
9041035
if target.flags&TypeFlagsIntersection != 0 {
9051036
for _, t := range target.Types() {
906-
if hasMatchingRecursionIdentity(t, identity) {
1037+
if c.hasMatchingRecursionIdentity(t, identity) {
9071038
return true
9081039
}
9091040
}
9101041
return false
9111042
}
912-
return getRecursionIdentityFromTarget(target) == identity
1043+
return c.getRecursionIdentityFromTarget(target) == identity
9131044
}
9141045

915-
func getRecursionIdentity(t *Type) RecursionId {
916-
return getRecursionIdentityFromTarget(getRecursionIdentityTarget(t))
1046+
func (c *Checker) getRecursionIdentity(t *Type) RecursionId {
1047+
return c.getRecursionIdentityFromTarget(getRecursionIdentityTarget(t))
9171048
}
9181049

9191050
// Get the recursion identity target type from a type. Recursively (a) obtain the target object type of an
@@ -942,7 +1073,7 @@ func getRecursionIdentityTarget(t *Type) *Type {
9421073
// instantiations of that type have the same recursion identity. The default recursion identity is the object
9431074
// identity of the type, meaning that every type is unique. Generally, types with constituents that could circularly
9441075
// reference the type have a recursion identity that differs from the object identity.
945-
func getRecursionIdentityFromTarget(t *Type) RecursionId {
1076+
func (c *Checker) getRecursionIdentityFromTarget(t *Type) RecursionId {
9461077
// Object and array literals are known not to contain recursive references and don't need a recursion identity.
9471078
if t.flags&TypeFlagsObject != 0 && !isObjectOrArrayLiteralType(t) {
9481079
if t.objectFlags&ObjectFlagsReference != 0 && t.AsTypeReference().node != nil {
@@ -951,14 +1082,12 @@ func getRecursionIdentityFromTarget(t *Type) RecursionId {
9511082
// unique AST node.
9521083
return asRecursionId(t.AsTypeReference().node)
9531084
}
954-
if t.symbol != nil && !(t.objectFlags&ObjectFlagsAnonymous != 0 && t.symbol.Flags()&ast.SymbolFlagsClass != 0) && t.objectFlags&ObjectFlagsFromTypeNode == 0 {
1085+
if t.symbol != nil && !(t.objectFlags&ObjectFlagsAnonymous != 0 && t.symbol.Flags()&ast.SymbolFlagsClass != 0) {
9551086
// We track object types that have a symbol by that symbol (representing the origin of the type), but
956-
// exclude the static sides of classes (since they share their symbols with the instance sides) and type
957-
// references that originate in resolution of AST type nodes (since such type nodes cannot be the source
958-
// of generative recursion without first being instantiated).
1087+
// exclude the static sides of classes (since they share their symbols with the instance sides).
9591088
return asRecursionId(t.symbol)
9601089
}
961-
if isTupleType(t) && t.objectFlags&ObjectFlagsFromTypeNode == 0 {
1090+
if isTupleType(t) {
9621091
return asRecursionId(t.Target())
9631092
}
9641093
}

‎tsc/internal/checker/tracer.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -323,7 +323,7 @@ func (a *tracedTypeAdapter) Pattern() *ast.Node {
323323
}
324324

325325
func (a *tracedTypeAdapter) RecursionIdentity() any {
326-
return getRecursionIdentity(a.t).value
326+
return a.checker.getRecursionIdentity(a.t).value
327327
}
328328

329329
func (a *tracedTypeAdapter) Display() string {

‎tsc/internal/checker/types.go‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -734,7 +734,6 @@ const (
734734
// Flags that require TypeFlags.Object and ObjectFlags.Reference
735735
ObjectFlagsIdenticalBaseTypeCalculated = 1 << 27 // has had `getSingleBaseForNonAugmentingSubtype` invoked on it already
736736
ObjectFlagsIdenticalBaseTypeExists = 1 << 28 // has a defined cachedEquivalentBaseType member
737-
ObjectFlagsFromTypeNode = 1 << 29 // Originates in resolution of AST type node
738737
// Flags that require TypeFlags.UnionOrIntersection or TypeFlags.Substitution
739738
ObjectFlagsIsGenericTypeComputed = 1 << 22 // IsGenericObjectType flag has been computed
740739
ObjectFlagsIsGenericObjectType = 1 << 23 // Union or intersection contains generic object type

‎tsc/testdata/baselines/reference/compiler/typeReferenceRecursionIdentityCheckOrder(checkorder=default).errors.txt‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ typeReferenceRecursionIdentityCheckOrder.ts(12,7): error TS2322: Type 'never[]'
1212
Type '{ <S extends never>(predicate: (value: never, index: number, array: never[]) => value is S, thisArg?: any): this is S[]; (predicate: (value: never, index: number, array: never[]) => unknown, thisArg?: any): boolean; }' is not assignable to type '<S extends 0>(predicate: (value: 0) => value is S) => this is A<S>'.
1313
Type predicate 'this is any[]' is not assignable to 'this is A<any>'.
1414
Type 'any[]' is not assignable to type 'A<any>'.
15-
The types returned by 'flatMap(...)' are incompatible between these types.
15+
The types returned by 'slice(...).flatMap(...)' are incompatible between these types.
1616
Type '(U | A<U>)[]' is not assignable to type 'U[]'.
1717
Type 'U | A<U>' is not assignable to type 'U'.
1818
'U' could be instantiated with an arbitrary type which could be unrelated to 'U | A<U>'.
@@ -47,7 +47,7 @@ typeReferenceRecursionIdentityCheckOrder.ts(12,7): error TS2322: Type 'never[]'
4747
!!! error TS2322: Type '{ <S extends never>(predicate: (value: never, index: number, array: never[]) => value is S, thisArg?: any): this is S[]; (predicate: (value: never, index: number, array: never[]) => unknown, thisArg?: any): boolean; }' is not assignable to type '<S extends 0>(predicate: (value: 0) => value is S) => this is A<S>'.
4848
!!! error TS2322: Type predicate 'this is any[]' is not assignable to 'this is A<any>'.
4949
!!! error TS2322: Type 'any[]' is not assignable to type 'A<any>'.
50-
!!! error TS2322: The types returned by 'flatMap(...)' are incompatible between these types.
50+
!!! error TS2322: The types returned by 'slice(...).flatMap(...)' are incompatible between these types.
5151
!!! error TS2322: Type '(U | A<U>)[]' is not assignable to type 'U[]'.
5252
!!! error TS2322: Type 'U | A<U>' is not assignable to type 'U'.
5353
!!! error TS2322: 'U' could be instantiated with an arbitrary type which could be unrelated to 'U | A<U>'.

0 commit comments

Comments
 (0)