Skip to content

Commit 0cc0c81

Browse files
committed
Cache relation results only once their assumptions are resolved
A relation that succeeds while an outer comparison is still in progress has only been shown to hold under the outer comparison's assumption. Caching it globally made later lookups depend on which comparison happened to run first. The same was true for results cut short by depth limits measured against outer resolutions. Each result now tracks the lowest resolution it depends on and whether it was truncated. Results are cached globally only when the comparison that introduced their assumptions completes, and truncated results only at their own head. Failures remain cached immediately, since assumptions only ever make a relation more likely to succeed. A comparison that only relates by assuming comparisons within it is reported as related once it completes, whether it is computed or read from the cache. Comparisons of types referencing constrained type parameters are considered related while the same comparison with unconstrained type parameters is in progress, since constraints only make more types related. A completed comparison found to succeed now counts the same way. That only went unnoticed because completed comparisons used to stay in progress until the outermost one completed; without it, relating structurally identical generic interfaces creates ten times the types.
1 parent 8ef0ef3 commit 0cc0c81

4 files changed

Lines changed: 192 additions & 51 deletions

File tree

‎tsc/internal/checker/relater.go‎

Lines changed: 165 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -881,6 +881,21 @@ func (c *Checker) mapperGeneration(m *TypeMapper) int {
881881
return 0
882882
}
883883

884+
// deeplyNestedStart returns the highest index in stack from which t is still
885+
// deeply nested, or -1 if it is not deeply nested. Comparisons starting at or
886+
// below that index would be truncated the same way.
887+
func (c *Checker) deeplyNestedStart(t *Type, stack []*Type, maxDepth int) int {
888+
if !c.isDeeplyNestedType(t, stack, maxDepth) {
889+
return -1
890+
}
891+
for k := len(stack) - maxDepth; k > 0; k-- {
892+
if c.isDeeplyNestedType(t, stack[k:], maxDepth) {
893+
return k
894+
}
895+
}
896+
return 0
897+
}
898+
884899
func hasMatchingRecursionIdentity(t *Type, identity RecursionId) bool {
885900
target := getRecursionIdentityTarget(t)
886901
if target.flags&TypeFlagsIntersection != 0 {
@@ -2668,22 +2683,48 @@ type ErrorChain struct {
26682683
}
26692684

26702685
type Relater struct {
2671-
c *Checker
2672-
relation *Relation
2673-
errorNode *ast.Node
2674-
errorChain *ErrorChain
2675-
relatedInfo []*ast.Diagnostic
2676-
maybeKeys []CacheHashKey
2677-
maybeKeysSet collections.Set[CacheHashKey]
2678-
sourceStack []*Type
2679-
targetStack []*Type
2680-
maybeCount int
2681-
sourceDepth int
2682-
targetDepth int
2686+
c *Checker
2687+
relation *Relation
2688+
errorNode *ast.Node
2689+
errorChain *ErrorChain
2690+
relatedInfo []*ast.Diagnostic
2691+
// maybeKeys are the comparisons in progress, followed by completed ones
2692+
// that hold assuming comparisons still in progress. maybeKeysSet indexes
2693+
// them by key.
2694+
maybeKeys []maybeKey
2695+
maybeKeysSet map[CacheHashKey]int
2696+
sourceStack []*Type
2697+
targetStack []*Type
2698+
// sourceDepths and targetDepths are the depths of the comparisons that
2699+
// pushed each entry of sourceStack and targetStack.
2700+
sourceDepths []int
2701+
targetDepths []int
2702+
// depth is the number of comparisons in progress.
2703+
depth int
2704+
// low is the lowest depth that the result of the innermost comparison in
2705+
// progress depends on, through assumptions or truncation. Results that
2706+
// depend on no comparison below their own are the same from scratch.
2707+
low int
2708+
// truncated is set if that result depends on a truncation that would not
2709+
// happen from scratch.
2710+
truncated bool
26832711
expandingFlags ExpandingFlags
2684-
overflow bool
2685-
relationCount int
2686-
next *Relater
2712+
// expandingSourceDepth and expandingTargetDepth are the highest depths
2713+
// from which the expanding flags would still be set.
2714+
expandingSourceDepth int
2715+
expandingTargetDepth int
2716+
overflow bool
2717+
relationCount int
2718+
next *Relater
2719+
}
2720+
2721+
type maybeKey struct {
2722+
key CacheHashKey
2723+
// low is the lowest depth that the comparison depends on, which is its
2724+
// own while it is in progress.
2725+
low int
2726+
result Ternary
2727+
truncated bool
26872728
}
26882729

26892730
func (c *Checker) getRelater() *Relater {
@@ -2696,13 +2737,15 @@ func (c *Checker) getRelater() *Relater {
26962737
}
26972738

26982739
func (c *Checker) putRelater(r *Relater) {
2699-
r.maybeKeysSet.Clear()
2740+
clear(r.maybeKeysSet)
27002741
*r = Relater{
27012742
c: c,
27022743
maybeKeys: r.maybeKeys[:0],
27032744
maybeKeysSet: r.maybeKeysSet,
27042745
sourceStack: r.sourceStack[:0],
27052746
targetStack: r.targetStack[:0],
2747+
sourceDepths: r.sourceDepths[:0],
2748+
targetDepths: r.targetDepths[:0],
27062749
next: c.freeRelater,
27072750
}
27082751
c.freeRelater = r
@@ -3227,38 +3270,67 @@ func (r *Relater) recursiveTypeRelatedTo(source *Type, target *Type, reportError
32273270
return TernaryFalse
32283271
}
32293272
// If source and target are already being compared, consider them related with assumptions
3230-
if r.maybeKeysSet.Has(id) {
3231-
return TernaryMaybe
3273+
if i, ok := r.maybeKeysSet[id]; ok {
3274+
return r.assume(i)
32323275
}
32333276
// A constrained key indicates that we have type references that reference constrained
32343277
// type parameters. For such keys we also check against the key we would have gotten if all type parameters
32353278
// were unconstrained.
32363279
if constrained {
32373280
broadestEquivalentId, _ := getRelationKey(source, target, intersectionState, r.relation == r.c.identityRelation, true /*ignoreConstraints*/)
3238-
if r.maybeKeysSet.Has(broadestEquivalentId) {
3239-
return TernaryMaybe
3281+
if i, ok := r.maybeKeysSet[broadestEquivalentId]; ok {
3282+
return r.assume(i)
3283+
}
3284+
// What relates with unconstrained type parameters also relates with
3285+
// constrained ones.
3286+
if entry := r.relation.get(broadestEquivalentId); entry&RelationComparisonResultSucceeded != 0 {
3287+
r.c.reliabilityFlags |= entry & (RelationComparisonResultReportsUnmeasurable | RelationComparisonResultReportsUnreliable)
3288+
return TernaryTrue
32403289
}
32413290
}
32423291
if len(r.sourceStack) == 100 || len(r.targetStack) == 100 {
32433292
// We stop relating if we reach 100 levels of nesting. This is a backstop to catch infinite recursion
32443293
// that wasn't caught by isDeeplyNestedType. It will also stop relating types that truly are over 100
32453294
// levels deep, but those are exceedingly rare.
3295+
depth := r.depth
3296+
if len(r.sourceStack) == 100 {
3297+
depth = min(depth, r.sourceDepths[0])
3298+
}
3299+
if len(r.targetStack) == 100 {
3300+
depth = min(depth, r.targetDepths[0])
3301+
}
3302+
r.truncate(depth)
32463303
return TernaryMaybe
32473304
}
3305+
depth := r.depth
3306+
r.depth++
32483307
maybeStart := len(r.maybeKeys)
3249-
r.maybeKeys = append(r.maybeKeys, id)
3250-
r.maybeKeysSet.Add(id)
3251-
saveExpandingFlags := r.expandingFlags
3308+
r.maybeKeys = append(r.maybeKeys, maybeKey{key: id, low: depth, result: TernaryMaybe})
3309+
if r.maybeKeysSet == nil {
3310+
r.maybeKeysSet = make(map[CacheHashKey]int)
3311+
}
3312+
r.maybeKeysSet[id] = maybeStart
3313+
saveLow, saveTruncated := r.low, r.truncated
3314+
r.low, r.truncated = depth, false
3315+
saveExpandingFlags, saveExpandingSourceDepth, saveExpandingTargetDepth := r.expandingFlags, r.expandingSourceDepth, r.expandingTargetDepth
32523316
if recursionFlags&RecursionFlagsSource != 0 {
32533317
r.sourceStack = append(r.sourceStack, source)
3254-
if r.expandingFlags&ExpandingFlagsSource == 0 && r.c.isDeeplyNestedType(source, r.sourceStack, 3) {
3255-
r.expandingFlags |= ExpandingFlagsSource
3318+
r.sourceDepths = append(r.sourceDepths, depth)
3319+
if r.expandingFlags&ExpandingFlagsSource == 0 {
3320+
if k := r.c.deeplyNestedStart(source, r.sourceStack, 3); k >= 0 {
3321+
r.expandingFlags |= ExpandingFlagsSource
3322+
r.expandingSourceDepth = r.sourceDepths[k]
3323+
}
32563324
}
32573325
}
32583326
if recursionFlags&RecursionFlagsTarget != 0 {
32593327
r.targetStack = append(r.targetStack, target)
3260-
if r.expandingFlags&ExpandingFlagsTarget == 0 && r.c.isDeeplyNestedType(target, r.targetStack, 3) {
3261-
r.expandingFlags |= ExpandingFlagsTarget
3328+
r.targetDepths = append(r.targetDepths, depth)
3329+
if r.expandingFlags&ExpandingFlagsTarget == 0 {
3330+
if k := r.c.deeplyNestedStart(target, r.targetStack, 3); k >= 0 {
3331+
r.expandingFlags |= ExpandingFlagsTarget
3332+
r.expandingTargetDepth = r.targetDepths[k]
3333+
}
32623334
}
32633335
}
32643336
saveReliabilityFlags := r.c.reliabilityFlags
@@ -3268,6 +3340,7 @@ func (r *Relater) recursiveTypeRelatedTo(source *Type, target *Type, reportError
32683340
if tr := r.c.tracer; tr != nil {
32693341
tr.Instant(tracing.PhaseCheckTypes, "recursiveTypeRelatedTo_DepthLimit", map[string]any{"sourceId": source.id, "targetId": target.id, "depth": len(r.sourceStack), "targetDepth": len(r.targetStack)})
32703342
}
3343+
r.truncate(min(r.expandingSourceDepth, r.expandingTargetDepth))
32713344
result = TernaryMaybe
32723345
} else {
32733346
if tr := r.c.tracer; tr != nil {
@@ -3279,39 +3352,83 @@ func (r *Relater) recursiveTypeRelatedTo(source *Type, target *Type, reportError
32793352
r.c.reliabilityFlags |= saveReliabilityFlags
32803353
if recursionFlags&RecursionFlagsSource != 0 {
32813354
r.sourceStack = r.sourceStack[:len(r.sourceStack)-1]
3355+
r.sourceDepths = r.sourceDepths[:len(r.sourceDepths)-1]
32823356
}
32833357
if recursionFlags&RecursionFlagsTarget != 0 {
32843358
r.targetStack = r.targetStack[:len(r.targetStack)-1]
3359+
r.targetDepths = r.targetDepths[:len(r.targetDepths)-1]
32853360
}
3286-
r.expandingFlags = saveExpandingFlags
3287-
if result != TernaryFalse {
3288-
if result == TernaryTrue || (len(r.sourceStack) == 0 && len(r.targetStack) == 0) {
3289-
if result == TernaryTrue || result == TernaryMaybe {
3290-
// If result is definitely true, record all maybe keys as having succeeded. Also, record Ternary.Maybe
3291-
// results as having succeeded once we reach depth 0, but never record Ternary.Unknown results.
3292-
r.resetMaybeStack(maybeStart, propagatingVarianceFlags, true)
3293-
} else {
3294-
r.resetMaybeStack(maybeStart, propagatingVarianceFlags, false)
3295-
}
3296-
}
3297-
// Note: it's intentional that we don't reset in the else case;
3298-
// we leave them on the stack such that when we hit depth zero
3299-
// above, we can report all of them as successful.
3300-
} else {
3361+
r.expandingFlags, r.expandingSourceDepth, r.expandingTargetDepth = saveExpandingFlags, saveExpandingSourceDepth, saveExpandingTargetDepth
3362+
r.depth--
3363+
low, truncated := r.low, r.truncated
3364+
r.low, r.truncated = saveLow, saveTruncated
3365+
switch {
3366+
case result == TernaryFalse:
33013367
// A false result goes straight into global cache (when something is false under
33023368
// assumptions it will also be false without assumptions)
33033369
r.relation.set(id, RelationComparisonResultFailed|propagatingVarianceFlags)
33043370
r.relationCount--
33053371
r.resetMaybeStack(maybeStart, propagatingVarianceFlags, false)
3372+
case low >= depth:
3373+
// The result depends on no comparison outside of this one, so it is the
3374+
// same from scratch. Comparisons that completed assuming this one hold
3375+
// as well, unless they relied on truncation, which may not happen from
3376+
// scratch. Ternary.Unknown results are never recorded.
3377+
switch {
3378+
case result == TernaryUnknown:
3379+
r.resetMaybeStack(maybeStart, propagatingVarianceFlags, false)
3380+
case truncated:
3381+
r.resetMaybeStack(maybeStart, propagatingVarianceFlags, false)
3382+
r.relation.set(id, RelationComparisonResultSucceeded|propagatingVarianceFlags)
3383+
r.relationCount--
3384+
default:
3385+
r.resetMaybeStack(maybeStart, propagatingVarianceFlags, true)
3386+
}
3387+
// The result no longer depends on any comparison in progress, so it
3388+
// is reported as related, the same as when it is read from the cache.
3389+
if result == TernaryMaybe {
3390+
result = TernaryTrue
3391+
}
3392+
default:
3393+
// The result holds while the comparisons it depends on are in progress,
3394+
// so it is kept until the outermost of them completes. Until then, the
3395+
// same comparison elsewhere in this one relates the same way.
3396+
for i := maybeStart; i < len(r.maybeKeys); i++ {
3397+
m := &r.maybeKeys[i]
3398+
m.low = min(m.low, low)
3399+
m.truncated = m.truncated || truncated
3400+
if result == TernaryTrue {
3401+
m.result = TernaryTrue
3402+
}
3403+
}
3404+
r.low = min(r.low, low)
3405+
r.truncated = r.truncated || truncated
33063406
}
33073407
return result
33083408
}
33093409

3410+
// assume relates a comparison in progress, or one that completed assuming one
3411+
// in progress, as it was related so far.
3412+
func (r *Relater) assume(i int) Ternary {
3413+
m := &r.maybeKeys[i]
3414+
r.low = min(r.low, m.low)
3415+
r.truncated = r.truncated || m.truncated
3416+
return m.result
3417+
}
3418+
3419+
// truncate records that the comparison in progress was cut short in a way
3420+
// that depends on depth and the depths above it.
3421+
func (r *Relater) truncate(depth int) {
3422+
r.low = min(r.low, depth)
3423+
r.truncated = true
3424+
}
3425+
33103426
func (r *Relater) resetMaybeStack(maybeStart int, propagatingVarianceFlags RelationComparisonResult, markAllAsSucceeded bool) {
33113427
for i := maybeStart; i < len(r.maybeKeys); i++ {
3312-
r.maybeKeysSet.Delete(r.maybeKeys[i])
3428+
key := r.maybeKeys[i].key
3429+
delete(r.maybeKeysSet, key)
33133430
if markAllAsSucceeded {
3314-
r.relation.set(r.maybeKeys[i], RelationComparisonResultSucceeded|propagatingVarianceFlags)
3431+
r.relation.set(key, RelationComparisonResultSucceeded|propagatingVarianceFlags)
33153432
r.relationCount--
33163433
}
33173434
}
@@ -3681,7 +3798,8 @@ func (r *Relater) structuredTypeRelatedToWorker(source *Type, target *Type, repo
36813798
case target.flags&TypeFlagsConditional != 0:
36823799
// If we reach 10 levels of nesting for the same conditional type, assume it is an infinitely expanding recursive
36833800
// conditional type and bail out with a Ternary.Maybe result.
3684-
if r.c.isDeeplyNestedType(target, r.targetStack, 10) {
3801+
if k := r.c.deeplyNestedStart(target, r.targetStack, 10); k >= 0 {
3802+
r.truncate(r.targetDepths[k])
36853803
return TernaryMaybe
36863804
}
36873805
c := target.AsConditionalType()
@@ -3862,7 +3980,8 @@ func (r *Relater) structuredTypeRelatedToWorker(source *Type, target *Type, repo
38623980
case source.flags&TypeFlagsConditional != 0:
38633981
// If we reach 10 levels of nesting for the same conditional type, assume it is an infinitely expanding recursive
38643982
// conditional type and bail out with a Ternary.Maybe result.
3865-
if r.c.isDeeplyNestedType(source, r.sourceStack, 10) {
3983+
if k := r.c.deeplyNestedStart(source, r.sourceStack, 10); k >= 0 {
3984+
r.truncate(r.sourceDepths[k])
38663985
return TernaryMaybe
38673986
}
38683987
if target.flags&TypeFlagsConditional != 0 {

‎tsc/testdata/baselines/reference/compiler/relationMaybeCheckOrder.errors.txt‎

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,7 @@
11
relationMaybeCheckOrder.ts(8,32): error TS2322: Type 'B' is not assignable to type 'string | number | symbol'.
2-
relationMaybeCheckOrder.ts(18,11): error TS2322: Type '2' is not assignable to type '1'.
32

43

5-
==== relationMaybeCheckOrder.ts (2 errors) ====
4+
==== relationMaybeCheckOrder.ts (1 errors) ====
65
// Relating to 'keyof M<T>' rejects keys that relate only by assuming a
76
// comparison still in progress. Relating 'A' to 'B' assumes only itself
87
// along 'next', so it completes on its own and must be accepted whether
@@ -23,8 +22,6 @@ relationMaybeCheckOrder.ts(18,11): error TS2322: Type '2' is not assignable to t
2322
function g(x: unknown): 2;
2423
function g(x: unknown) { return 1 as any; }
2524
const r: 1 = g(a);
26-
~
27-
!!! error TS2322: Type '2' is not assignable to type '1'.
2825
}
2926

3027
const w: 1 = h(a);

‎tsc/testdata/baselines/reference/compiler/relationMaybeCheckOrder.types‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ function f<T>() {
4747

4848
const r: 1 = g(a);
4949
>r : 1
50-
>g(a) : 2
50+
>g(a) : 1
5151
>g : { (x: keyof M<T>): 1; (x: unknown): 2; }
5252
>a : A
5353
}
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
relationTruncatedCacheCheckOrder.ts(14,1): error TS2322: Type 'S<[string]>' is not assignable to type 'R<[string]>'.
2+
The types of 'next.leaf' are incompatible between these types.
3+
Type 'number' is not assignable to type '[[string]]'.
4+
5+
6+
==== relationTruncatedCacheCheckOrder.ts (1 errors) ====
7+
// Relating 'S<[string]>' to 'R<[string]>' from scratch reaches 'next.leaf'
8+
// before giving up on deeply nested types, and fails there. Inside the
9+
// relation of 'S<string>' to 'R<string>' it is one level deeper and is cut
10+
// short instead. That truncated result must not be cached, so the error for
11+
// 'q = p' must be reported whether or not 'y = x' was checked first.
12+
13+
type S<T> = { next: S<[T]>; leaf: T extends [[unknown]] ? number : T };
14+
type R<T> = { next: R<[T]>; leaf: T };
15+
16+
declare let x: S<string>, y: R<string>;
17+
declare let p: S<[string]>, q: R<[string]>;
18+
19+
y = x;
20+
q = p;
21+
~
22+
!!! error TS2322: Type 'S<[string]>' is not assignable to type 'R<[string]>'.
23+
!!! error TS2322: The types of 'next.leaf' are incompatible between these types.
24+
!!! error TS2322: Type 'number' is not assignable to type '[[string]]'.
25+

0 commit comments

Comments
 (0)