diff --git a/tsc/internal/checker/exports.go b/tsc/internal/checker/exports.go index 26c6e8180454d..5e073680a3c80 100644 --- a/tsc/internal/checker/exports.go +++ b/tsc/internal/checker/exports.go @@ -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 } diff --git a/tsc/internal/core/context.go b/tsc/internal/core/context.go index 6747a03e2cc55..6779dca36df73 100644 --- a/tsc/internal/core/context.go +++ b/tsc/internal/core/context.go @@ -28,6 +28,7 @@ const ( CheckerLifetimeTemporary CheckerLifetime = iota CheckerLifetimeDiagnostics CheckerLifetimeAPI + CheckerLifetimeCheckedFileQuery ) func WithCheckerLifetime(ctx context.Context, lifetime CheckerLifetime) context.Context { diff --git a/tsc/internal/ls/semantictokens.go b/tsc/internal/ls/semantictokens.go index 8580d0e0f48fc..5f7960dbf5a2b 100644 --- a/tsc/internal/ls/semantictokens.go +++ b/tsc/internal/ls/semantictokens.go @@ -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) program, file := l.getProgramAndFile(documentURI) supplemental := file.SupplementalSourceFiles() @@ -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) diff --git a/tsc/internal/project/checkerpool.go b/tsc/internal/project/checkerpool.go index 3033f1c8bd4ad..2aa3e6538ef8b 100644 --- a/tsc/internal/project/checkerpool.go +++ b/tsc/internal/project/checkerpool.go @@ -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 @@ -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), @@ -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: @@ -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. @@ -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) }) } diff --git a/tsc/internal/project/checkerpool_test.go b/tsc/internal/project/checkerpool_test.go index c66e8cccced4c..6e63fd69becdd 100644 --- a/tsc/internal/project/checkerpool_test.go +++ b/tsc/internal/project/checkerpool_test.go @@ -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" @@ -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: (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) +}