Skip to content

Commit dca6039

Browse files
committed
Discard results cached by signature help
Signature help resolves a call from the arguments typed so far, without reporting errors, and string literal completions resolve it with inference from the argument being typed blocked. The results those requests cache depend on that state, which is not part of their keys, so checking that reuses them could infer other types or miss errors. Nothing such a request caches is kept: it runs in a cycle headed below every computation, which ends with the request. The state of such a request, the number of arguments typed so far and the nodes inference is blocked from, is held in a request that exists only while it runs, rather than in fields of the checker that any computation could read.
1 parent 59ac12c commit dca6039

5 files changed

Lines changed: 78 additions & 37 deletions

File tree

‎tsc/internal/checker/checker.go‎

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -653,7 +653,6 @@ type Checker struct {
653653
// members of one parent are often looked up together.
654654
lastLateBindableParent *ast.Symbol
655655
lastLateBindableKinds uint8
656-
isInferencePartiallyBlocked bool
657656
wasCanceled bool
658657
evaluate evaluator.Evaluator
659658
resolveName func(location *ast.Node, name string, meaning ast.SymbolFlags, nameNotFoundMessage *diagnostics.Message, isUse bool, excludeGlobals bool) *ast.Symbol
@@ -716,7 +715,7 @@ type Checker struct {
716715
resumeBuf []int
717716
deferredAttach []deferredAttachment // See attachState
718717
recordingFromCheck bool // A query begun in a check is in progress; see recordFromCheck
719-
apparentArgumentCount *int
718+
request *editorRequest // The editor request being answered, if any; see runEditorRequest
720719
lastGetCombinedNodeFlagsNode *ast.Node
721720
lastGetCombinedNodeFlagsResult ast.NodeFlags
722721
lastGetCombinedModifierFlagsNode *ast.Node
@@ -801,7 +800,6 @@ type Checker struct {
801800
isStringIndexSignatureOnlyType func(*Type) bool
802801
markNodeAssignments func(*ast.Node) bool
803802
compareTypesAssignable TypeComparer
804-
skipDirectInferenceNodes collections.Set[*ast.Node]
805803
ctx context.Context
806804
activeMappers []*TypeMapper
807805
activeTypeMappersCaches []clearableMap[activeMapperCacheEntry]
@@ -9504,7 +9502,7 @@ func (c *Checker) resolveCall(node *ast.Node, signatures []*Signature, candidate
95049502
isDecorator := node.Kind == ast.KindDecorator
95059503
isJsxOpeningOrSelfClosingElement := ast.IsJsxOpeningLikeElement(node)
95069504
isInstanceof := node.Kind == ast.KindBinaryExpression
9507-
reportErrors := !c.isInferencePartiallyBlocked && candidatesOutArray == nil
9505+
reportErrors := (c.request == nil || !c.request.inferencePartiallyBlocked) && candidatesOutArray == nil
95089506
var s CallState
95099507
s.node = node
95109508
if !isDecorator && !isInstanceof && !isSuperCall(node) && !ast.IsJsxOpeningFragment(node) {
@@ -10187,8 +10185,8 @@ func (c *Checker) pickLongestCandidateSignature(node *ast.Node, candidates []*Si
1018710185
// declare function f<T>(k: keyof T);
1018810186
// f<Foo>("
1018910187
argCount := len(args)
10190-
if c.apparentArgumentCount != nil {
10191-
argCount = *c.apparentArgumentCount
10188+
if c.request != nil && c.request.argumentCount != nil {
10189+
argCount = *c.request.argumentCount
1019210190
}
1019310191
bestIndex := c.getLongestCandidateIndex(candidates, argCount)
1019410192
candidate := candidates[bestIndex]

‎tsc/internal/checker/inference.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1648,7 +1648,7 @@ func (c *Checker) isFromInferenceBlockedSource(t *Type) bool {
16481648
}
16491649

16501650
func (c *Checker) isSkipDirectInferenceNode(node *ast.Node) bool {
1651-
return c.skipDirectInferenceNodes.Has(node)
1651+
return c.request != nil && c.request.skipDirectInferenceNodes.Has(node)
16521652
}
16531653

16541654
func newInferenceInfo(typeParameter *Type) *InferenceInfo {

‎tsc/internal/checker/services.go‎

Lines changed: 55 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -324,45 +324,55 @@ func (c *Checker) shouldTreatPropertiesOfExternalModuleAsExports(resolvedExterna
324324

325325
func (c *Checker) GetContextualType(node *ast.Expression, contextFlags ContextFlags) *Type {
326326
if contextFlags&ContextFlagsIgnoreNodeInferences != 0 {
327-
return c.runWithInferenceBlockedFromSourceNode(node, func() *Type { return c.getContextualType(node, contextFlags) })
327+
return runEditorRequest(c, node, c.inferenceBlockedFrom(node), func() *Type { return c.getContextualType(node, contextFlags) })
328328
}
329329
return c.getContextualType(node, contextFlags)
330330
}
331331

332-
func (c *Checker) runWithInferenceBlockedFromSourceNode[T any](node *ast.Node, fn func() T) T {
333-
containingCall := ast.FindAncestor(node, ast.IsCallLikeExpression)
334-
if containingCall != nil {
335-
toMarkSkip := node
336-
for {
337-
c.skipDirectInferenceNodes.Add(toMarkSkip)
338-
toMarkSkip = toMarkSkip.Parent
339-
if toMarkSkip == nil || toMarkSkip == containingCall {
332+
// An editorRequest is state of an editor request that what the checker
333+
// computes for it depends on, but is not cached under, such as the number of
334+
// arguments typed so far. It exists only while runEditorRequest runs the
335+
// request, discarding whatever the request caches.
336+
type editorRequest struct {
337+
argumentCount *int // The number of arguments to resolve a call with, if not those it has
338+
// Inference from these nodes, the one being edited and its ancestors up
339+
// to the call, is skipped, and call resolution reports no errors.
340+
skipDirectInferenceNodes collections.Set[*ast.Node]
341+
inferencePartiallyBlocked bool
342+
}
343+
344+
// inferenceBlockedFrom returns a request that blocks inference from node, an
345+
// argument being edited, and its ancestors up to the call.
346+
func (c *Checker) inferenceBlockedFrom(node *ast.Node) *editorRequest {
347+
request := &editorRequest{inferencePartiallyBlocked: true}
348+
if containingCall := ast.FindAncestor(node, ast.IsCallLikeExpression); containingCall != nil {
349+
for n := node; ; {
350+
request.skipDirectInferenceNodes.Add(n)
351+
n = n.Parent
352+
if n == nil || n == containingCall {
340353
break
341354
}
342355
}
343356
}
344-
345-
c.isInferencePartiallyBlocked = true
346-
result := c.runWithoutResolvedSignatureCaching(node, fn)
347-
c.isInferencePartiallyBlocked = false
348-
349-
c.skipDirectInferenceNodes.Clear()
350-
return result
357+
return request
351358
}
352359

353360
func GetResolvedSignatureForSignatureHelp(node *ast.Node, argumentCount int, c *Checker) (*Signature, []*Signature) {
354361
type result struct {
355362
signature *Signature
356363
candidates []*Signature
357364
}
358-
res := c.runWithoutResolvedSignatureCaching(node, func() result {
359-
signature, candidates := c.getResolvedSignatureWorker(node, CheckModeIsForSignatureHelp, argumentCount)
365+
res := runEditorRequest(c, node, &editorRequest{argumentCount: &argumentCount}, func() result {
366+
signature, candidates := c.getResolvedSignatureWithCandidates(node, CheckModeIsForSignatureHelp)
360367
return result{signature, candidates}
361368
})
362369
return res.signature, res.candidates
363370
}
364371

365-
func (c *Checker) runWithoutResolvedSignatureCaching[T any](node *ast.Node, fn func() T) T {
372+
// runEditorRequest runs fn, which answers an editor request at node in the
373+
// state of request. The calls and functions enclosing node are resolved
374+
// again in that state, and whatever fn caches is discarded once it returns.
375+
func runEditorRequest[T any](c *Checker, node *ast.Node, request *editorRequest, fn func() T) T {
366376
ancestorNode := ast.FindAncestor(node, ast.IsCallLikeOrFunctionLikeExpression)
367377
if ancestorNode != nil {
368378
cachedResolvedSignatures := make(map[*SignatureLinks]*Signature)
@@ -376,7 +386,7 @@ func (c *Checker) runWithoutResolvedSignatureCaching[T any](node *ast.Node, fn f
376386
}
377387
ancestorNode = ast.FindAncestor(ancestorNode.Parent, ast.IsCallLikeOrFunctionLikeExpression)
378388
}
379-
result := fn()
389+
result := runDiscardingCaches(c, request, fn)
380390
for signatureLinks, resolvedSignature := range cachedResolvedSignatures {
381391
signatureLinks.resolvedSignature.swap(resolvedSignature)
382392
}
@@ -385,7 +395,23 @@ func (c *Checker) runWithoutResolvedSignatureCaching[T any](node *ast.Node, fn f
385395
}
386396
return result
387397
}
388-
return fn()
398+
return runDiscardingCaches(c, request, fn)
399+
}
400+
401+
// runDiscardingCaches runs fn in the state of request, and discards whatever
402+
// it caches: it all happens in a cycle headed below every computation, which
403+
// ends with the request.
404+
func runDiscardingCaches[T any](c *Checker, request *editorRequest, fn func() T) T {
405+
debug.Assert(len(c.resolutions) == 1 && c.circularityStart == 0 && c.request == nil, "editor request inside a computation")
406+
c.markCircular(0)
407+
c.request = request
408+
result := fn()
409+
c.request = nil
410+
// Not even the results of the participants of cycles inside the request
411+
// are kept.
412+
c.cycleParticipants = nil
413+
c.endCyclesAt(0)
414+
return result
389415
}
390416

391417
func (c *Checker) SkipAlias(symbol *ast.Symbol) *ast.Symbol {
@@ -888,28 +914,29 @@ func (c *Checker) GetConstantValue(node *ast.Node) any {
888914
return nil
889915
}
890916

891-
func (c *Checker) getResolvedSignatureWorker(node *ast.Node, checkMode CheckMode, argumentCount int) (*Signature, []*Signature) {
892-
c.apparentArgumentCount = &argumentCount
917+
func (c *Checker) getResolvedSignatureWithCandidates(node *ast.Node, checkMode CheckMode) (*Signature, []*Signature) {
893918
candidatesOutArray := &[]*Signature{}
894919
var res *Signature
895920
if node != nil && ast.IsParseTreeNode(node) {
896921
res = c.getResolvedSignature(node, candidatesOutArray, checkMode)
897922
}
898-
c.apparentArgumentCount = nil
899923
return res, *candidatesOutArray
900924
}
901925

902926
func (c *Checker) GetCandidateSignaturesForStringLiteralCompletions(call *ast.CallLikeExpression, editingArgument *ast.Node) []*Signature {
903927
// first, get candidates when inference is blocked from the source node.
904-
candidates := c.runWithInferenceBlockedFromSourceNode(editingArgument, func() []*Signature {
905-
_, blockedInferenceCandidates := c.getResolvedSignatureWorker(call, CheckModeNormal, 0)
928+
noArguments := 0
929+
blocked := c.inferenceBlockedFrom(editingArgument)
930+
blocked.argumentCount = &noArguments
931+
candidates := runEditorRequest(c, editingArgument, blocked, func() []*Signature {
932+
_, blockedInferenceCandidates := c.getResolvedSignatureWithCandidates(call, CheckModeNormal)
906933
return blockedInferenceCandidates
907934
})
908935
candidatesSet := collections.NewSetFromItems(candidates...)
909936

910937
// next, get candidates where the source node is considered for inference.
911-
otherCandidates := c.runWithoutResolvedSignatureCaching(editingArgument, func() []*Signature {
912-
_, inferenceCandidates := c.getResolvedSignatureWorker(call, CheckModeNormal, 0)
938+
otherCandidates := runEditorRequest(c, editingArgument, &editorRequest{argumentCount: &noArguments}, func() []*Signature {
939+
_, inferenceCandidates := c.getResolvedSignatureWithCandidates(call, CheckModeNormal)
913940
return inferenceCandidates
914941
})
915942

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
signatureHelpInferenceQueryOrder.ts(7,30): error TS2741: Property 'b' is missing in type 'A' but required in type 'B'.
2+
3+
4+
==== signatureHelpInferenceQueryOrder.ts (1 errors) ====
5+
function f<T, U>(y: T, y1: U, p: (z: U) => T, p1: (x: T) => U): [T, U] { return [y, p1(y)]; }
6+
interface A { a: A; }
7+
interface B extends A { b; }
8+
9+
declare var a: A, b: B;
10+
11+
var d = f(a, b, x => x, x => x);
12+
~
13+
!!! error TS2741: Property 'b' is missing in type 'A' but required in type 'B'.
14+
!!! related TS2728 signatureHelpInferenceQueryOrder.ts:3:25: 'b' is declared here.
15+
!!! related TS6502 signatureHelpInferenceQueryOrder.ts:1:51: The expected type comes from the return type of this signature.
16+

‎tsc/testdata/baselines/reference/compiler/signatureHelpInferenceQueryOrder(checkorder=editorfirst).types‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,8 @@ declare var a: A, b: B;
2626
>b : B
2727

2828
var d = f(a, b, x => x, x => x);
29-
>d : [A, A]
30-
>f(a, b, x => x, x => x) : [A, A]
29+
>d : [A, B]
30+
>f(a, b, x => x, x => x) : [A, B]
3131
>f : <T, U>(y: T, y1: U, p: (z: U) => T, p1: (x: T) => U) => [T, U]
3232
>a : A
3333
>b : B

0 commit comments

Comments
 (0)