Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions tsc/internal/checker/exports.go
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,11 @@ func GetDeclarationModifierFlagsFromSymbol(s *ast.Symbol) ast.ModifierFlags {
return getDeclarationModifierFlagsFromSymbol(s)
}

func (c *Checker) IsSourceFileChecked(sourceFile *ast.SourceFile) bool {
links := c.sourceFileLinks.TryGet(sourceFile)
return links != nil && links.typeChecked && links.unusedChecked && !c.wasCanceled
}

func (c *Checker) WasCanceled() bool {
return c.wasCanceled
}
Expand Down
1 change: 1 addition & 0 deletions tsc/internal/core/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ const (
CheckerLifetimeTemporary CheckerLifetime = iota
CheckerLifetimeDiagnostics
CheckerLifetimeAPI
CheckerLifetimeCheckedFileQuery
)

func WithCheckerLifetime(ctx context.Context, lifetime CheckerLifetime) context.Context {
Expand Down
2 changes: 2 additions & 0 deletions tsc/internal/ls/semantictokens.go
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,7 @@ func SemanticTokensLegend(clientCapabilities lsproto.ResolvedSemanticTokensClien
}

func (l *LanguageService) ProvideSemanticTokens(ctx context.Context, documentURI lsproto.DocumentUri) (lsproto.SemanticTokensResponse, error) {
ctx = core.WithCheckerLifetime(ctx, core.CheckerLifetimeCheckedFileQuery)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added TestSemanticTokensReuseCheckedDiagnosticsChecker in 9afed7b. It runs the #51661 repro through the real session + language service: semantic tokens on a query checker, then diagnostics, then semantic tokens again. It asserts the second request actually took the lending path (hooked on the pool's log, so it can't pass by falling back), that the tokens are identical to the query-checker ones, and that diagnostics are still empty and unchanged afterwards.

Range tokens go through the exact same GetChecker path, so I didn't duplicate the test for them tbh, happy to add it if you prefer.

program, file := l.getProgramAndFile(documentURI)

supplemental := file.SupplementalSourceFiles()
Expand Down Expand Up @@ -158,6 +159,7 @@ func (l *LanguageService) ProvideSemanticTokens(ctx context.Context, documentURI
}

func (l *LanguageService) ProvideSemanticTokensRange(ctx context.Context, documentURI lsproto.DocumentUri, rng lsproto.Range) (lsproto.SemanticTokensRangeResponse, error) {
ctx = core.WithCheckerLifetime(ctx, core.CheckerLifetimeCheckedFileQuery)
program, file := l.getProgramAndFile(documentURI)

mappedRanges := l.converters.FromLSPRangeIntersectingForSourceFile(file, rng, spanmap.FeatureSemanticTokens)
Expand Down
31 changes: 31 additions & 0 deletions tsc/internal/project/checkerpool.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ type checkerPool struct {
heldBy []string // heldBy[i] is the requestID holding checker i, checkerHeldAnonymous, or "" if not held
fileAssociations map[*ast.SourceFile]int // file → query checker index (1+)
requestAssociations map[string]int // requestID → checker index
diagnosticsRequests map[string]struct{}

// lastReleased tracks when each checker was last released.
lastReleased []time.Time
Expand Down Expand Up @@ -98,6 +99,7 @@ func newCheckerPool(opts CheckerPoolOptions, program *compiler.Program, log func
heldBy: make([]string, opts.MaxCheckers),
fileAssociations: make(map[*ast.SourceFile]int),
requestAssociations: make(map[string]int),
diagnosticsRequests: make(map[string]struct{}),
lastReleased: make([]time.Time, opts.MaxCheckers),
diagSem: make(chan struct{}, 1),
querySem: make(chan struct{}, querySlots),
Expand Down Expand Up @@ -135,6 +137,11 @@ func (p *checkerPool) GetChecker(ctx context.Context, file *ast.SourceFile) (*ch
switch lifetime {
case core.CheckerLifetimeDiagnostics:
return p.getDiagnosticsChecker(ctx, requestID)
case core.CheckerLifetimeCheckedFileQuery:
if c, release, ok := p.tryGetCheckedDiagnosticsChecker(requestID, file); ok {
return c, release
}
return p.getQueryChecker(ctx, requestID, file)
case core.CheckerLifetimeAPI:
return p.getPersistentChecker()
default:
Expand Down Expand Up @@ -216,10 +223,33 @@ func (p *checkerPool) getDiagnosticsChecker(ctx context.Context, requestID strin
p.requestAssociations[requestID] = diagIndex
p.registerRequestCleanup(ctx, requestID)
}
p.diagnosticsRequests[requestID] = struct{}{}
}
return c, p.createRelease(requestID, diagIndex, c)
}

func (p *checkerPool) tryGetCheckedDiagnosticsChecker(requestID string, file *ast.SourceFile) (*checker.Checker, func(), bool) {
const diagIndex = 0
if file == nil {
return nil, nil, false
}

p.mu.Lock()
defer p.mu.Unlock()
c := p.checkers[diagIndex]
if c == nil || p.heldBy[diagIndex] != "" || len(p.diagnosticsRequests) > 0 || !c.IsSourceFileChecked(file) {
return nil, nil, false
}
select {
case p.diagSem <- struct{}{}:
p.heldBy[diagIndex] = holdTag(requestID)
p.log("checkerpool: Lending diagnostics checker to query request " + holdTag(requestID))
return c, p.createRelease(requestID, diagIndex, c), true
default:
return nil, nil, false
}
}

// getQueryChecker returns an ephemeral query checker from indices 1+.
// Uses request affinity, then file affinity, then finds/creates.
// Blocks on querySem if all query slots are in use.
Expand Down Expand Up @@ -363,6 +393,7 @@ func (p *checkerPool) registerRequestCleanup(ctx context.Context, requestID stri
p.mu.Lock()
defer p.mu.Unlock()
delete(p.requestAssociations, requestID)
delete(p.diagnosticsRequests, requestID)
})
}

Expand Down
142 changes: 142 additions & 0 deletions tsc/internal/project/checkerpool_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@ package project

import (
"context"
"strings"
"sync/atomic"
"testing"
"testing/synctest"
"time"

"github.com/microsoft/TypeScript/tsc/internal/ast"
"github.com/microsoft/TypeScript/tsc/internal/bundled"
"github.com/microsoft/TypeScript/tsc/internal/checker"
"github.com/microsoft/TypeScript/tsc/internal/compiler"
Expand Down Expand Up @@ -1334,3 +1336,143 @@ func TestCheckerPoolCleanupAfterDiscardIsNoop(t *testing.T) {
pool.mu.Unlock()
})
}

func TestCheckerPoolCheckedFileQuery(t *testing.T) {
t.Parallel()
if !bundled.Embedded {
t.Skip("bundled files are not embedded")
}
files := map[string]any{
"/src/tsconfig.json": `{ "compilerOptions": { "noLib": true } }`,
"/src/index.ts": "export const x: number = 1;",
"/src/other.ts": "export const y: number = 2;",
}
session := NewSession(&SessionInit{
BackgroundCtx: context.Background(),
Options: &SessionOptions{
CurrentDirectory: "/",
DefaultLibraryPath: bundled.LibPath(),
PositionEncoding: lsproto.PositionEncodingKindUTF8,
},
FS: bundled.WrapFS(vfstest.FromMap(files, tspath.CaseInsensitive)),
Logger: logging.NewTestLogger(),
})
session.DidOpenFile(context.Background(), "file:///src/index.ts", 1, files["/src/index.ts"].(string), lsproto.LanguageKindTypeScript)
ls, err := session.GetLanguageService(context.Background(), "file:///src/index.ts")
assert.NilError(t, err)
program := ls.GetProgram()
index := program.GetSourceFile("/src/index.ts")
other := program.GetSourceFile("/src/other.ts")
assert.Assert(t, index != nil && other != nil)

synctest.Test(t, func(t *testing.T) {
pool := newTestCheckerPool(program, CheckerPoolOptions{MaxCheckers: 2, IdleTimeout: 5 * time.Second})
query := func(id string, file *ast.SourceFile) (*checker.Checker, func()) {
ctx := core.WithRequestID(context.Background(), id)
return pool.GetChecker(core.WithCheckerLifetime(ctx, core.CheckerLifetimeCheckedFileQuery), file)
}

c, release := query("query-1", other)
assert.Assert(t, c != pool.checkers[0], "unchecked file should use a query checker")
release()

diagCtx, cancelDiag := context.WithCancel(context.Background())
diagCtx = core.WithCheckerLifetime(core.WithRequestID(diagCtx, "diag"), core.CheckerLifetimeDiagnostics)
var diagChecker *checker.Checker
for _, file := range []*ast.SourceFile{index, other} {
dc, releaseDiag := pool.GetChecker(diagCtx, file)
dc.GetDiagnostics(diagCtx, file)
releaseDiag()
dc, releaseDiag = pool.GetChecker(diagCtx, file)
dc.GetSuggestionDiagnostics(diagCtx, file)
releaseDiag()
diagChecker = dc
}

for _, file := range []*ast.SourceFile{index, other} {
c, release = query("query-2", file)
assert.Assert(t, c != diagChecker, "in-flight diagnostics request should keep the checker for %s", file.FileName())
release()
}

cancelDiag()
synctest.Wait()

c, release = query("query-3", other)
assert.Assert(t, c == diagChecker, "checked file should reuse the diagnostics checker")

c2, release2 := query("query-4", index)
assert.Assert(t, c2 != diagChecker, "lent checker should not be shared")
release2()
release()
synctest.Wait()
})
}

func TestSemanticTokensReuseCheckedDiagnosticsChecker(t *testing.T) {
t.Parallel()
if !bundled.Embedded {
t.Skip("bundled files are not embedded")
}
content := `const assertExists: <T extends number>(actual: T | null | undefined) => asserts actual is T = () => {};

type Value = { n: number | undefined };
const callThisFunc = (f: (this: Value) => void): void => {
f.call({ n: 42 });
};

callThisFunc(function() {
const maybeN = this.n;
assertExists(maybeN);
});
`
files := map[string]any{
"/src/tsconfig.json": `{ "compilerOptions": { "strict": true } }`,
"/src/index.ts": content,
}
session := NewSession(&SessionInit{
BackgroundCtx: context.Background(),
Options: &SessionOptions{
CurrentDirectory: "/",
DefaultLibraryPath: bundled.LibPath(),
PositionEncoding: lsproto.PositionEncodingKindUTF8,
},
FS: bundled.WrapFS(vfstest.FromMap(files, tspath.CaseInsensitive)),
Logger: logging.NewTestLogger(),
})
uri := lsproto.DocumentUri("file:///src/index.ts")
session.DidOpenFile(context.Background(), uri, 1, content, lsproto.LanguageKindTypeScript)
ls, err := session.GetLanguageService(context.Background(), uri)
assert.NilError(t, err)
session.WaitForBackgroundTasks()
pool := session.Snapshot().ProjectCollection.ConfiguredProject("/src/tsconfig.json").checkerPool
var lent atomic.Int32
pool.log = func(msg string) {
if strings.Contains(msg, "Lending diagnostics checker") {
lent.Add(1)
}
}

ctx := core.WithRequestID(context.Background(), "request")
diagnostics := func() []*lsproto.Diagnostic {
report, diagnosticsErr := ls.ProvideDiagnostics(core.WithCheckerLifetime(ctx, core.CheckerLifetimeDiagnostics), uri)
assert.NilError(t, diagnosticsErr)
return report.FullDocumentDiagnosticReport.Items
}
semanticTokens := func() []uint32 {
tokens, tokensErr := ls.ProvideSemanticTokens(ctx, uri)
assert.NilError(t, tokensErr)
assert.Assert(t, tokens.SemanticTokens != nil)
return tokens.SemanticTokens.Data
}

tokensFromQueryChecker := semanticTokens()
assert.Equal(t, lent.Load(), int32(0))
diags := diagnostics()
assert.Equal(t, len(diags), 0)

tokensFromDiagnosticsChecker := semanticTokens()
assert.Equal(t, lent.Load(), int32(1), "semantic tokens should reuse the diagnostics checker")
assert.DeepEqual(t, tokensFromDiagnosticsChecker, tokensFromQueryChecker)
assert.DeepEqual(t, diagnostics(), diags)
}