From dcc389cb76e11dad4767577a19847eacc0a9e6fd Mon Sep 17 00:00:00 2001 From: Cheng Date: Fri, 23 Oct 2026 23:02:26 +0800 Subject: [PATCH 1/4] Avoid rebuilding later LSP project references --- tsc/internal/collections/ordered_map.go | 14 +- tsc/internal/collections/ordered_map_test.go | 39 +++++ .../project/projectcollectionbuilder.go | 38 +++++ .../project/projectcollectionbuilder_test.go | 135 ++++++++++++++++++ 4 files changed, 221 insertions(+), 5 deletions(-) diff --git a/tsc/internal/collections/ordered_map.go b/tsc/internal/collections/ordered_map.go index d933ffa0e7557..8c58f679f7c33 100644 --- a/tsc/internal/collections/ordered_map.go +++ b/tsc/internal/collections/ordered_map.go @@ -107,16 +107,20 @@ func (m *OrderedMap[K, V]) Delete(key K) (V, bool) { } delete(m.mp, key) + + // Avoid scanning the keys when removing entries from the end. + if last := len(m.keys) - 1; m.keys[last] == key { + var zero K + m.keys[last] = zero + m.keys = m.keys[:last] + return v, true + } + i := slices.Index(m.keys, key) - // If we're just removing the first or last element, avoid shifting everything around. if i == 0 { var zero K m.keys[0] = zero m.keys = m.keys[1:] - } else if end := len(m.keys) - 1; i == end { - var zero K - m.keys[end] = zero - m.keys = m.keys[:end] } else { m.keys = slices.Delete(m.keys, i, i+1) } diff --git a/tsc/internal/collections/ordered_map_test.go b/tsc/internal/collections/ordered_map_test.go index 25a911e7a5f7d..63422f57d930c 100644 --- a/tsc/internal/collections/ordered_map_test.go +++ b/tsc/internal/collections/ordered_map_test.go @@ -3,6 +3,7 @@ package collections_test import ( "fmt" "slices" + "strconv" "strings" "testing" @@ -223,3 +224,41 @@ func testOrderedMapUnmarshalJSON(t *testing.T, unmarshal func([]byte, any) error err = unmarshal([]byte(`{"a": 1, "b": "two"}`), &invalidMap) assert.ErrorContains(t, err, "unmarshal") } + +func TestOrderedMapDeleteSuffix(t *testing.T) { + t.Parallel() + + m := collections.NewOrderedMapFromList([]collections.MapEntry[int, string]{ + {Key: 1, Value: "one"}, + {Key: 2, Value: "two"}, + {Key: 3, Value: "three"}, + {Key: 4, Value: "four"}, + }) + for _, key := range []int{4, 3, 2} { + want, _ := m.Get(key) + value, ok := m.Delete(key) + assert.Assert(t, ok) + assert.Equal(t, value, want) + assert.Assert(t, !m.Has(key)) + } + assert.Equal(t, m.Size(), 1) + assert.DeepEqual(t, slices.Collect(m.Keys()), []int{1}) + m.Set(2, "new") + assert.DeepEqual(t, slices.Collect(m.Values()), []string{"one", "new"}) +} + +func BenchmarkOrderedMapDeleteSuffix(b *testing.B) { + for _, size := range []int{1024, 8192, 32768} { + b.Run(strconv.Itoa(size), func(b *testing.B) { + m := collections.NewOrderedMapWithSizeHint[int, int](size) + for b.Loop() { + for key := range size { + m.Set(key, key) + } + for key := size - 1; key > 0; key-- { + m.Delete(key) + } + } + }) + } +} diff --git a/tsc/internal/project/projectcollectionbuilder.go b/tsc/internal/project/projectcollectionbuilder.go index 99872b4cb6eee..30ac2b3b13d4e 100644 --- a/tsc/internal/project/projectcollectionbuilder.go +++ b/tsc/internal/project/projectcollectionbuilder.go @@ -1159,6 +1159,44 @@ func (b *ProjectCollectionBuilder) findOrCreateDefaultConfiguredProjectWorker( } return true }) + // Skip later candidates once a clean loaded project contains the file. + // Keep earlier candidates in parallel to preserve reference order. + foundMatch := false + var trailingKeys []searchNodeKey + level.Range(func(node searchNode) bool { + key := searchNodeKey{configFileName: node.configFileName, loadKind: node.loadKind} + if foundMatch { + trailingKeys = append(trailingKeys, key) + return true + } + if visited.Has(key) { + return true + } + configPath := b.toPathKey(node.configFileName) + projectEntry, ok := b.configuredProjects.Load(ConfiguredProjectIDFromPathKey(configPath)) + if !ok || projectEntry.Value().IsDirty() { + return true + } + configEntry, ok := b.configFileRegistryBuilder.configs.Load(configPath) + if !ok || configEntry.Value().pendingReload != PendingReloadNone { + return true + } + config := configEntry.Value().commandLine + project := projectEntry.Value() + if config == nil || project.CommandLine != config || len(config.FileNames()) == 0 { + return true + } + if config.CompilerOptions().Composite.IsTrue() && !config.FilePaths().Has(path) { + return true + } + foundMatch = project.containsFile(path) && !project.IsSourceFromProjectReference(path) + return true + }) + // Delete after traversal so entries are not skipped. + // Removing from the end keeps pruning linear. + for _, key := range slices.Backward(trailingKeys) { + level.Delete(key) + } }, }, func(node searchNode) searchNodeKey { diff --git a/tsc/internal/project/projectcollectionbuilder_test.go b/tsc/internal/project/projectcollectionbuilder_test.go index cfa6b1b1114ff..2a1f3bc23be78 100644 --- a/tsc/internal/project/projectcollectionbuilder_test.go +++ b/tsc/internal/project/projectcollectionbuilder_test.go @@ -6,9 +6,11 @@ import ( "maps" "strings" "testing" + "testing/synctest" "github.com/microsoft/TypeScript/tsc/internal/bundled" "github.com/microsoft/TypeScript/tsc/internal/core" + "github.com/microsoft/TypeScript/tsc/internal/ls/lsconv" "github.com/microsoft/TypeScript/tsc/internal/lsp/lsproto" "github.com/microsoft/TypeScript/tsc/internal/project" "github.com/microsoft/TypeScript/tsc/internal/testutil/projecttestutil" @@ -23,6 +25,139 @@ func TestProjectCollectionBuilder(t *testing.T) { t.Skip("bundled files are not embedded") } + t.Run("does not rebuild later references after loading the default project", func(t *testing.T) { + t.Parallel() + synctest.Test(t, func(t *testing.T) { + files := map[string]any{ + "/project/tsconfig.json": `{"files": [], "references": [{"path": "./tsconfig.app.json"}, {"path": "./tsconfig.node.json"}, {"path": "./tsconfig.tools.json"}]}`, + "/project/tsconfig.app.json": `{"include": ["src"]}`, + "/project/tsconfig.node.json": `{"files": ["vite.config.ts"]}`, + "/project/vite.config.ts": `export default {};`, + "/project/tsconfig.tools.json": `{"files": ["tools.ts"]}`, + "/project/tools.ts": `export {};`, + "/project/src/a.ts": `export const a = 1;`, + "/project/src/b.ts": `export const b = 2;`, + "/project/src/c.ts": `export const c = 3;`, + } + session, utils := projecttestutil.Setup(files) + defer session.Close() + for i, name := range []string{"a", "b", "c"} { + synctest.Wait() + logStart := len(utils.Logs()) + fileName := "/project/src/" + name + ".ts" + uri := lsproto.DocumentUri("file://" + fileName) + session.DidOpenFile(context.Background(), uri, 1, files[fileName].(string), lsproto.LanguageKindTypeScript) + _, err := session.GetLanguageService(context.Background(), uri) + assert.NilError(t, err) + defaultProject := session.Snapshot().GetDefaultProject(uri) + assert.Assert(t, defaultProject != nil) + assert.Equal(t, defaultProject.ConfigFileName(), tspath.RootedFilePath("/project/tsconfig.app.json")) + synctest.Wait() + if i > 0 { + assert.Equal(t, strings.Count(utils.Logs()[logStart:], "Program update for /project/tsconfig.node.json completed"), 0) + assert.Equal(t, strings.Count(utils.Logs()[logStart:], "Program update for /project/tsconfig.tools.json completed"), 0) + } + session.DidCloseFile(context.Background(), uri) + } + }) + }) + + t.Run("preserves reference order and breadth-first project selection", func(t *testing.T) { + t.Parallel() + for _, test := range []struct { + name string + firstConfig string + want tspath.RootedFilePath + }{ + {"first direct match", `{"files": ["src/main.ts"]}`, "/project/first.json"}, + {"first match through import", `{"files": ["entry.ts"]}`, "/project/first.json"}, + {"later direct match before deeper reference", `{"files": [], "references": [{"path": "./deep.json"}]}`, "/project/second.json"}, + } { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + files := map[string]any{ + "/project/tsconfig.json": `{"files": [], "references": [{"path": "./first.json"}, {"path": "./second.json"}]}`, + "/project/first.json": test.firstConfig, + "/project/second.json": `{"files": ["src/main.ts"]}`, + "/project/deep.json": `{"files": ["src/main.ts"]}`, + "/project/entry.ts": `import "./src/main";`, + "/project/src/main.ts": `export const value = 1;`, + } + session, _ := projecttestutil.Setup(files) + defer session.Close() + uri := lsproto.DocumentUri("file:///project/src/main.ts") + session.DidOpenFile(context.Background(), uri, 1, files["/project/src/main.ts"].(string), lsproto.LanguageKindTypeScript) + defaultProject := session.Snapshot().GetDefaultProject(uri) + assert.Assert(t, defaultProject != nil) + assert.Equal(t, defaultProject.ConfigFileName(), test.want) + }) + } + }) + + t.Run("cached matches do not change project selection", func(t *testing.T) { + t.Parallel() + for _, test := range []struct { + name string + firstConfig string + warmFile string + changedFile tspath.RootedFilePath + newContent string + want tspath.RootedFilePath + }{ + { + name: "earlier candidate wins over cached later match", + firstConfig: `{"files": ["main.ts"]}`, + warmFile: "anchor.ts", + want: "/project/first.json", + }, + { + name: "config change invalidates cached match", + firstConfig: `{"files": ["entry.ts", "main.ts"]}`, + warmFile: "entry.ts", + changedFile: "/project/first.json", + newContent: `{"files": ["other.ts"]}`, + want: "/project/second.json", + }, + { + name: "source change invalidates cached match", + firstConfig: `{"files": ["entry.ts"]}`, + warmFile: "entry.ts", + changedFile: "/project/entry.ts", + newContent: `export {};`, + want: "/project/second.json", + }, + } { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + files := map[string]any{ + "/project/tsconfig.json": `{"files": [], "references": [{"path": "./first.json"}, {"path": "./second.json"}]}`, + "/project/first.json": test.firstConfig, + "/project/second.json": `{"files": ["main.ts", "anchor.ts"]}`, + "/project/main.ts": `export const value = 1;`, + "/project/entry.ts": `import "./main";`, + "/project/anchor.ts": `export {};`, + "/project/other.ts": `export {};`, + } + session, utils := projecttestutil.Setup(files) + defer session.Close() + warmURI := lsproto.DocumentUri("file:///project/" + test.warmFile) + session.DidOpenFile(context.Background(), warmURI, 1, files["/project/"+test.warmFile].(string), lsproto.LanguageKindTypeScript) + session.DidCloseFile(context.Background(), warmURI) + if test.changedFile != "" { + assert.NilError(t, utils.FS().WriteFile(test.changedFile, test.newContent)) + session.DidChangeWatchedFiles(context.Background(), []*lsproto.FileEvent{ + {Type: lsproto.FileChangeTypeChanged, Uri: lsconv.FileNameToDocumentURI(test.changedFile)}, + }) + } + uri := lsproto.DocumentUri("file:///project/main.ts") + session.DidOpenFile(context.Background(), uri, 1, files["/project/main.ts"].(string), lsproto.LanguageKindTypeScript) + defaultProject := session.Snapshot().GetDefaultProject(uri) + assert.Assert(t, defaultProject != nil) + assert.Equal(t, defaultProject.ConfigFileName(), test.want) + }) + } + }) + t.Run("when project found is solution referencing default project directly", func(t *testing.T) { t.Parallel() files := filesForSolutionConfigFile([]string{"./tsconfig-src.json"}, "", nil) From fc6eb21815be430e642ed3bf800c9bc1225e6a3b Mon Sep 17 00:00:00 2001 From: Cheng Date: Tue, 24 Nov 2026 11:36:19 +0800 Subject: [PATCH 2/4] Share file inclusion checks during project selection Pass the stored key to Range callbacks so callers can reuse it directly. Co-authored-by: Andrew Branch --- tsc/internal/core/bfs.go | 6 +- .../project/projectcollectionbuilder.go | 69 ++++++++++--------- .../project/projectcollectionbuilder_test.go | 5 +- 3 files changed, 43 insertions(+), 37 deletions(-) diff --git a/tsc/internal/core/bfs.go b/tsc/internal/core/bfs.go index 0ffb2541f2978..cb6ce70d8efdd 100644 --- a/tsc/internal/core/bfs.go +++ b/tsc/internal/core/bfs.go @@ -30,9 +30,9 @@ func (l *BreadthFirstSearchLevel[K, N]) Delete(key K) { l.jobs.Delete(key) } -func (l *BreadthFirstSearchLevel[K, N]) Range(f func(node N) bool) { - for job := range l.jobs.Values() { - if !f(job.node) { +func (l *BreadthFirstSearchLevel[K, N]) Range(f func(key K, node N) bool) { + for key, job := range l.jobs.Entries() { + if !f(key, job.node) { return } } diff --git a/tsc/internal/project/projectcollectionbuilder.go b/tsc/internal/project/projectcollectionbuilder.go index 7dc18f8e4215d..b53bed0628e24 100644 --- a/tsc/internal/project/projectcollectionbuilder.go +++ b/tsc/internal/project/projectcollectionbuilder.go @@ -1100,6 +1100,33 @@ func (b *ProjectCollectionBuilder) findOrCreateDefaultConfiguredProjectWorker( visited = &collections.SyncSet[searchNodeKey]{} } + configMayContainFile := func(config *tsoptions.ParsedCommandLine, logger *logging.LogTree) bool { + if len(config.FileNames()) == 0 { + // A solution config can still lead to a match through its references. + logger.Log("Project does not contain file (no root files)") + return false + } + // !!! what about declaration files in node_modules? wouldn't it be better to + // check project inclusion if the project is already loaded? + if config.CompilerOptions().Composite.IsTrue() && !config.FilePaths().Has(path) { + logger.Log("Project does not contain file (by composite config inclusion)") + return false + } + return true + } + + fileInclusion := func(project *Project, logger *logging.LogTree) (included, direct bool) { + if !project.containsFile(path) { + logger.Log("Project does not contain file") + return false, false + } + direct = !project.IsSourceFromProjectReference(path) + if logger != nil { + logger.Logf("Project contains file %s", core.IfElse(direct, "directly", "as a source of a referenced project")) + } + return true, direct + } + search := core.BreadthFirstSearchParallelEx( searchNode{configFileName: configFileName, loadKind: loadKind, logger: logger}, func(node searchNode) []searchNode { @@ -1128,22 +1155,10 @@ func (b *ProjectCollectionBuilder) findOrCreateDefaultConfiguredProjectWorker( return false, false } configs.Store(configFilePath, config) - if len(config.FileNames()) == 0 { - // Likely a solution tsconfig.json - the search will fan out to its references. - node.logger.Log("Project does not contain file (no root files)") + if !configMayContainFile(config, node.logger) { return false, false } - if config.CompilerOptions().Composite == core.TSTrue { - // For composite projects, we can get an early negative result. - // !!! what about declaration files in node_modules? wouldn't it be better to - // check project inclusion if the project is already loaded? - if !config.FilePaths().Has(path) { - node.logger.Log("Project does not contain file (by composite config inclusion)") - return false, false - } - } - project := b.findOrCreateProject(node.configFileName, configFilePath, node.loadKind, node.logger) if project == nil { node.logger.Log("Project does not already exist") @@ -1155,33 +1170,23 @@ func (b *ProjectCollectionBuilder) findOrCreateDefaultConfiguredProjectWorker( b.updateProgram(project, node.logger) } - if project.Value().containsFile(path) { - isDirectInclusion := !project.Value().IsSourceFromProjectReference(path) - if node.logger != nil { - node.logger.Logf("Project contains file %s", core.IfElse(isDirectInclusion, "directly", "as a source of a referenced project")) - } - return true, isDirectInclusion - } - - node.logger.Log("Project does not contain file") - return false, false + return fileInclusion(project.Value(), node.logger) }, core.BreadthFirstSearchOptions[searchNodeKey, searchNode]{ Visited: visited, PreprocessLevel: func(level *core.BreadthFirstSearchLevel[searchNodeKey, searchNode]) { - level.Range(func(node searchNode) bool { + level.Range(func(key searchNodeKey, node searchNode) bool { if node.loadKind == projectLoadKindFind && level.Has(searchNodeKey{configFileName: node.configFileName, loadKind: projectLoadKindCreate}) { // Remove find requests when a create request for the same project is already present. - level.Delete(searchNodeKey{configFileName: node.configFileName, loadKind: node.loadKind}) + level.Delete(key) } return true }) - // Skip later candidates once a clean loaded project contains the file. - // Keep earlier candidates in parallel to preserve reference order. + // A clean project that directly contains the file can rule out later candidates. + // Earlier candidates still take precedence and can be checked in parallel. foundMatch := false var trailingKeys []searchNodeKey - level.Range(func(node searchNode) bool { - key := searchNodeKey{configFileName: node.configFileName, loadKind: node.loadKind} + level.Range(func(key searchNodeKey, node searchNode) bool { if foundMatch { trailingKeys = append(trailingKeys, key) return true @@ -1200,13 +1205,13 @@ func (b *ProjectCollectionBuilder) findOrCreateDefaultConfiguredProjectWorker( } config := configEntry.Value().commandLine project := projectEntry.Value() - if config == nil || project.CommandLine != config || len(config.FileNames()) == 0 { + if config == nil || project.CommandLine != config { return true } - if config.CompilerOptions().Composite.IsTrue() && !config.FilePaths().Has(path) { + if !configMayContainFile(config, nil) { return true } - foundMatch = project.containsFile(path) && !project.IsSourceFromProjectReference(path) + _, foundMatch = fileInclusion(project, nil) return true }) // Delete after traversal so entries are not skipped. diff --git a/tsc/internal/project/projectcollectionbuilder_test.go b/tsc/internal/project/projectcollectionbuilder_test.go index 2a1f3bc23be78..b361a35be5c42 100644 --- a/tsc/internal/project/projectcollectionbuilder_test.go +++ b/tsc/internal/project/projectcollectionbuilder_test.go @@ -54,8 +54,9 @@ func TestProjectCollectionBuilder(t *testing.T) { assert.Equal(t, defaultProject.ConfigFileName(), tspath.RootedFilePath("/project/tsconfig.app.json")) synctest.Wait() if i > 0 { - assert.Equal(t, strings.Count(utils.Logs()[logStart:], "Program update for /project/tsconfig.node.json completed"), 0) - assert.Equal(t, strings.Count(utils.Logs()[logStart:], "Program update for /project/tsconfig.tools.json completed"), 0) + openLogs := utils.Logs()[logStart:] + assert.Equal(t, strings.Count(openLogs, "Program update for /project/tsconfig.node.json completed"), 0) + assert.Equal(t, strings.Count(openLogs, "Program update for /project/tsconfig.tools.json completed"), 0) } session.DidCloseFile(context.Background(), uri) } From 62d339c1ffd8989e18ade1b1900a7bdc20dec60e Mon Sep 17 00:00:00 2001 From: Cheng Date: Tue, 24 Nov 2026 13:38:54 +0800 Subject: [PATCH 3/4] Cover cached project selection and fix find request deduplication --- .../project/projectcollectionbuilder.go | 74 ++++++++------ .../projectcollectionbuilder_internal_test.go | 98 +++++++++++++++++++ .../project/projectcollectionbuilder_test.go | 30 ++++++ 3 files changed, 173 insertions(+), 29 deletions(-) create mode 100644 tsc/internal/project/projectcollectionbuilder_internal_test.go diff --git a/tsc/internal/project/projectcollectionbuilder.go b/tsc/internal/project/projectcollectionbuilder.go index b53bed0628e24..437a9dd5acdc4 100644 --- a/tsc/internal/project/projectcollectionbuilder.go +++ b/tsc/internal/project/projectcollectionbuilder.go @@ -1086,6 +1086,41 @@ type searchResult struct { retain collections.Set[tspath.PathKey] } +func removeRedundantFindRequests(level *core.BreadthFirstSearchLevel[searchNodeKey, searchNode]) { + var redundantKeys []searchNodeKey + level.Range(func(key searchNodeKey, _ searchNode) bool { + if key.loadKind == projectLoadKindFind && level.Has(searchNodeKey{configFileName: key.configFileName, loadKind: projectLoadKindCreate}) { + redundantKeys = append(redundantKeys, key) + } + return true + }) + for _, key := range redundantKeys { + level.Delete(key) + } +} + +// Earlier candidates can still win, so keep them in the parallel search. +func pruneAfterCachedMatch( + level *core.BreadthFirstSearchLevel[searchNodeKey, searchNode], + isCachedMatch func(searchNodeKey) bool, +) { + foundMatch := false + var trailingKeys []searchNodeKey + level.Range(func(key searchNodeKey, _ searchNode) bool { + if foundMatch { + trailingKeys = append(trailingKeys, key) + } else { + foundMatch = isCachedMatch(key) + } + return true + }) + // Delete after traversal so entries are not skipped. + // Removing from the end keeps pruning linear. + for _, key := range slices.Backward(trailingKeys) { + level.Delete(key) + } +} + func (b *ProjectCollectionBuilder) findOrCreateDefaultConfiguredProjectWorker( fileName tspath.RootedFilePath, path tspath.PathKey, @@ -1175,50 +1210,31 @@ func (b *ProjectCollectionBuilder) findOrCreateDefaultConfiguredProjectWorker( core.BreadthFirstSearchOptions[searchNodeKey, searchNode]{ Visited: visited, PreprocessLevel: func(level *core.BreadthFirstSearchLevel[searchNodeKey, searchNode]) { - level.Range(func(key searchNodeKey, node searchNode) bool { - if node.loadKind == projectLoadKindFind && level.Has(searchNodeKey{configFileName: node.configFileName, loadKind: projectLoadKindCreate}) { - // Remove find requests when a create request for the same project is already present. - level.Delete(key) - } - return true - }) - // A clean project that directly contains the file can rule out later candidates. - // Earlier candidates still take precedence and can be checked in parallel. - foundMatch := false - var trailingKeys []searchNodeKey - level.Range(func(key searchNodeKey, node searchNode) bool { - if foundMatch { - trailingKeys = append(trailingKeys, key) - return true - } + removeRedundantFindRequests(level) + pruneAfterCachedMatch(level, func(key searchNodeKey) bool { if visited.Has(key) { - return true + return false } - configPath := b.toPathKey(node.configFileName) + configPath := b.toPathKey(key.configFileName) projectEntry, ok := b.configuredProjects.Load(ConfiguredProjectIDFromPathKey(configPath)) if !ok || projectEntry.Value().IsDirty() { - return true + return false } configEntry, ok := b.configFileRegistryBuilder.configs.Load(configPath) if !ok || configEntry.Value().pendingReload != PendingReloadNone { - return true + return false } config := configEntry.Value().commandLine project := projectEntry.Value() if config == nil || project.CommandLine != config { - return true + return false } if !configMayContainFile(config, nil) { - return true + return false } - _, foundMatch = fileInclusion(project, nil) - return true + _, direct := fileInclusion(project, nil) + return direct }) - // Delete after traversal so entries are not skipped. - // Removing from the end keeps pruning linear. - for _, key := range slices.Backward(trailingKeys) { - level.Delete(key) - } }, }, func(node searchNode) searchNodeKey { diff --git a/tsc/internal/project/projectcollectionbuilder_internal_test.go b/tsc/internal/project/projectcollectionbuilder_internal_test.go new file mode 100644 index 0000000000000..4722167bb469c --- /dev/null +++ b/tsc/internal/project/projectcollectionbuilder_internal_test.go @@ -0,0 +1,98 @@ +package project + +import ( + "slices" + "testing" + + "github.com/microsoft/TypeScript/tsc/internal/core" + "github.com/microsoft/TypeScript/tsc/internal/tspath" + "gotest.tools/v3/assert" +) + +func TestPruneAfterCachedMatch(t *testing.T) { + t.Parallel() + + root := searchNode{configFileName: "/solution.json", loadKind: projectLoadKindCreate} + candidates := []searchNode{ + {configFileName: "/earlier.json", loadKind: projectLoadKindCreate}, + {configFileName: "/cached.json", loadKind: projectLoadKindCreate}, + {configFileName: "/later.json", loadKind: projectLoadKindCreate}, + {configFileName: "/last.json", loadKind: projectLoadKindCreate}, + } + keyFor := func(node searchNode) searchNodeKey { + return searchNodeKey{configFileName: node.configFileName, loadKind: node.loadKind} + } + + var remaining []tspath.RootedFilePath + core.BreadthFirstSearchParallelEx( + root, + func(node searchNode) []searchNode { + if node == root { + return candidates + } + return nil + }, + func(searchNode) (bool, bool) { return false, false }, + core.BreadthFirstSearchOptions[searchNodeKey, searchNode]{ + PreprocessLevel: func(level *core.BreadthFirstSearchLevel[searchNodeKey, searchNode]) { + if level.Has(keyFor(root)) { + return + } + pruneAfterCachedMatch(level, func(key searchNodeKey) bool { + return key.configFileName == "/cached.json" + }) + level.Range(func(key searchNodeKey, _ searchNode) bool { + remaining = append(remaining, key.configFileName) + return true + }) + }, + }, + keyFor, + ) + assert.DeepEqual(t, remaining, []tspath.RootedFilePath{"/earlier.json", "/cached.json"}) +} + +func TestRemoveRedundantFindRequests(t *testing.T) { + t.Parallel() + + root := searchNode{configFileName: "/solution.json", loadKind: projectLoadKindCreate} + first := searchNodeKey{configFileName: "/first.json", loadKind: projectLoadKindCreate} + second := searchNodeKey{configFileName: "/second.json", loadKind: projectLoadKindCreate} + findOnly := searchNodeKey{configFileName: "/find-only.json", loadKind: projectLoadKindFind} + candidates := []searchNode{ + {configFileName: first.configFileName, loadKind: projectLoadKindFind}, + {configFileName: second.configFileName, loadKind: projectLoadKindFind}, + {configFileName: findOnly.configFileName, loadKind: findOnly.loadKind}, + {configFileName: first.configFileName, loadKind: first.loadKind}, + {configFileName: second.configFileName, loadKind: second.loadKind}, + } + keyFor := func(node searchNode) searchNodeKey { + return searchNodeKey{configFileName: node.configFileName, loadKind: node.loadKind} + } + + var remaining []searchNodeKey + core.BreadthFirstSearchParallelEx( + root, + func(node searchNode) []searchNode { + if node == root { + return candidates + } + return nil + }, + func(searchNode) (bool, bool) { return false, false }, + core.BreadthFirstSearchOptions[searchNodeKey, searchNode]{ + PreprocessLevel: func(level *core.BreadthFirstSearchLevel[searchNodeKey, searchNode]) { + if level.Has(keyFor(root)) { + return + } + removeRedundantFindRequests(level) + level.Range(func(key searchNodeKey, _ searchNode) bool { + remaining = append(remaining, key) + return true + }) + }, + }, + keyFor, + ) + assert.Assert(t, slices.Equal(remaining, []searchNodeKey{findOnly, first, second}), "remaining candidates: %v", remaining) +} diff --git a/tsc/internal/project/projectcollectionbuilder_test.go b/tsc/internal/project/projectcollectionbuilder_test.go index b361a35be5c42..20447d90c1d1e 100644 --- a/tsc/internal/project/projectcollectionbuilder_test.go +++ b/tsc/internal/project/projectcollectionbuilder_test.go @@ -159,6 +159,36 @@ func TestProjectCollectionBuilder(t *testing.T) { } }) + t.Run("cached source redirect does not prune a later direct match", func(t *testing.T) { + t.Parallel() + files := map[string]any{ + "/project/tsconfig.json": `{"files": [], "references": [{"path": "./first.json"}, {"path": "./second.json"}]}`, + "/project/first.json": `{"files": ["entry.ts"], "references": [{"path": "./redirect.json"}]}`, + "/project/second.json": `{"files": ["main.ts"]}`, + "/project/redirect.json": `{"compilerOptions": {"composite": true}, "files": ["main.ts"]}`, + "/project/entry.ts": `import "./main";`, + "/project/main.ts": `export const value = 1;`, + } + session, utils := projecttestutil.Setup(files) + defer session.Close() + ctx := context.Background() + + entryURI := lsproto.DocumentUri("file:///project/entry.ts") + session.DidOpenFile(ctx, entryURI, 1, files["/project/entry.ts"].(string), lsproto.LanguageKindTypeScript) + first := session.Snapshot().GetDefaultProject(entryURI) + assert.Assert(t, first != nil) + assert.Equal(t, first.ConfigFileName(), tspath.RootedFilePath("/project/first.json")) + assert.Assert(t, !first.IsDirty()) + assert.Assert(t, first.Program.GetSourceFile("/project/main.ts") != nil) + assert.Assert(t, first.IsSourceFromProjectReference(utils.PathKey("/project/main.ts"))) + + uri := lsproto.DocumentUri("file:///project/main.ts") + session.DidOpenFile(ctx, uri, 1, files["/project/main.ts"].(string), lsproto.LanguageKindTypeScript) + defaultProject := session.Snapshot().GetDefaultProject(uri) + assert.Assert(t, defaultProject != nil) + assert.Equal(t, defaultProject.ConfigFileName(), tspath.RootedFilePath("/project/second.json")) + }) + t.Run("when project found is solution referencing default project directly", func(t *testing.T) { t.Parallel() files := filesForSolutionConfigFile([]string{"./tsconfig-src.json"}, "", nil) From 18b225a377cc3f4ef9b83370fcb889b04f587482 Mon Sep 17 00:00:00 2001 From: Cheng Date: Wed, 25 Nov 2026 11:38:37 +0800 Subject: [PATCH 4/4] Preserve project selection order for mixed Find and Create requests --- .../project/projectcollectionbuilder.go | 105 ++++++++++++------ .../projectcollectionbuilder_internal_test.go | 2 +- .../project/projectcollectionbuilder_test.go | 91 +++++++++++++++ 3 files changed, 163 insertions(+), 35 deletions(-) diff --git a/tsc/internal/project/projectcollectionbuilder.go b/tsc/internal/project/projectcollectionbuilder.go index 437a9dd5acdc4..60c59b19a4044 100644 --- a/tsc/internal/project/projectcollectionbuilder.go +++ b/tsc/internal/project/projectcollectionbuilder.go @@ -1086,10 +1086,18 @@ type searchResult struct { retain collections.Set[tspath.PathKey] } -func removeRedundantFindRequests(level *core.BreadthFirstSearchLevel[searchNodeKey, searchNode]) { +func removeRedundantFindRequests( + level *core.BreadthFirstSearchLevel[searchNodeKey, searchNode], + keepFind func(searchNode) bool, +) { var redundantKeys []searchNodeKey - level.Range(func(key searchNodeKey, _ searchNode) bool { - if key.loadKind == projectLoadKindFind && level.Has(searchNodeKey{configFileName: key.configFileName, loadKind: projectLoadKindCreate}) { + level.Range(func(key searchNodeKey, node searchNode) bool { + if key.loadKind != projectLoadKindFind { + return true + } + createKey := searchNodeKey{configFileName: key.configFileName, loadKind: projectLoadKindCreate} + // Built projects can match at their earlier Find position. + if level.Has(createKey) && !keepFind(node) { redundantKeys = append(redundantKeys, key) } return true @@ -1099,7 +1107,7 @@ func removeRedundantFindRequests(level *core.BreadthFirstSearchLevel[searchNodeK } } -// Earlier candidates can still win, so keep them in the parallel search. +// Keep earlier candidates in the parallel search so they can still win. func pruneAfterCachedMatch( level *core.BreadthFirstSearchLevel[searchNodeKey, searchNode], isCachedMatch func(searchNodeKey) bool, @@ -1114,8 +1122,7 @@ func pruneAfterCachedMatch( } return true }) - // Delete after traversal so entries are not skipped. - // Removing from the end keeps pruning linear. + // Collect before deleting to avoid skipping entries. Tail deletion keeps pruning linear. for _, key := range slices.Backward(trailingKeys) { level.Delete(key) } @@ -1135,6 +1142,7 @@ func (b *ProjectCollectionBuilder) findOrCreateDefaultConfiguredProjectWorker( visited = &collections.SyncSet[searchNodeKey]{} } + // A nil LogTree suppresses logging during cached-match checks. configMayContainFile := func(config *tsoptions.ParsedCommandLine, logger *logging.LogTree) bool { if len(config.FileNames()) == 0 { // A solution config can still lead to a match through its references. @@ -1162,6 +1170,34 @@ func (b *ProjectCollectionBuilder) findOrCreateDefaultConfiguredProjectWorker( return true, direct } + visit := func(node searchNode) (included, direct bool) { + configFilePath := b.toPathKey(node.configFileName) + config := b.configFileRegistryBuilder.findOrAcquireConfigForFile(node.configFileName, configFilePath, path, node.loadKind, node.logger.Fork("Acquiring config for open file")) + if config == nil { + node.logger.Log("Config file for project does not already exist") + return false, false + } + configs.Store(configFilePath, config) + if !configMayContainFile(config, node.logger) { + return false, false + } + + project := b.findOrCreateProject(node.configFileName, configFilePath, node.loadKind, node.logger) + if project == nil { + node.logger.Log("Project does not already exist") + return false, false + } + + if node.loadKind == projectLoadKindCreate { + // Ensure project is up to date before checking for file inclusion + b.updateProgram(project, node.logger) + } + + return fileInclusion(project.Value(), node.logger) + } + + // PreprocessLevel sets up the shared visits before the workers for each level start. + mixedVisits := make(map[tspath.RootedFilePath]func() (bool, bool)) search := core.BreadthFirstSearchParallelEx( searchNode{configFileName: configFileName, loadKind: loadKind, logger: logger}, func(node searchNode) []searchNode { @@ -1182,50 +1218,51 @@ func (b *ProjectCollectionBuilder) findOrCreateDefaultConfiguredProjectWorker( } return nil }, - func(node searchNode) (isResult bool, stop bool) { - configFilePath := b.toPathKey(node.configFileName) - config := b.configFileRegistryBuilder.findOrAcquireConfigForFile(node.configFileName, configFilePath, path, node.loadKind, node.logger.Fork("Acquiring config for open file")) - if config == nil { - node.logger.Log("Config file for project does not already exist") - return false, false + func(node searchNode) (bool, bool) { + if shared := mixedVisits[node.configFileName]; shared != nil { + return shared() } - configs.Store(configFilePath, config) - if !configMayContainFile(config, node.logger) { - return false, false - } - - project := b.findOrCreateProject(node.configFileName, configFilePath, node.loadKind, node.logger) - if project == nil { - node.logger.Log("Project does not already exist") - return false, false - } - - if node.loadKind == projectLoadKindCreate { - // Ensure project is up to date before checking for file inclusion - b.updateProgram(project, node.logger) - } - - return fileInclusion(project.Value(), node.logger) + return visit(node) }, core.BreadthFirstSearchOptions[searchNodeKey, searchNode]{ Visited: visited, PreprocessLevel: func(level *core.BreadthFirstSearchLevel[searchNodeKey, searchNode]) { - removeRedundantFindRequests(level) + clear(mixedVisits) + removeRedundantFindRequests(level, func(node searchNode) bool { + entry, ok := b.configuredProjects.Load(ConfiguredProjectIDFromPathKey(b.toPathKey(node.configFileName))) + if !ok || entry.Value().Program == nil { + return false + } + createKey := searchNodeKey{configFileName: node.configFileName, loadKind: projectLoadKindCreate} + if !visited.Has(createKey) { + // Share the refresh while preserving each job's position and reference load kind. + node.loadKind = projectLoadKindCreate + mixedVisits[node.configFileName] = sync.OnceValues(func() (bool, bool) { return visit(node) }) + } + return true + }) pruneAfterCachedMatch(level, func(key searchNodeKey) bool { if visited.Has(key) { return false } configPath := b.toPathKey(key.configFileName) projectEntry, ok := b.configuredProjects.Load(ConfiguredProjectIDFromPathKey(configPath)) - if !ok || projectEntry.Value().IsDirty() { + if !ok { + return false + } + project := projectEntry.Value() + if project.IsDirty() { return false } configEntry, ok := b.configFileRegistryBuilder.configs.Load(configPath) - if !ok || configEntry.Value().pendingReload != PendingReloadNone { + if !ok { return false } - config := configEntry.Value().commandLine - project := projectEntry.Value() + cachedConfig := configEntry.Value() + if cachedConfig.pendingReload != PendingReloadNone { + return false + } + config := cachedConfig.commandLine if config == nil || project.CommandLine != config { return false } diff --git a/tsc/internal/project/projectcollectionbuilder_internal_test.go b/tsc/internal/project/projectcollectionbuilder_internal_test.go index 4722167bb469c..ec0ce5dcfb276 100644 --- a/tsc/internal/project/projectcollectionbuilder_internal_test.go +++ b/tsc/internal/project/projectcollectionbuilder_internal_test.go @@ -85,7 +85,7 @@ func TestRemoveRedundantFindRequests(t *testing.T) { if level.Has(keyFor(root)) { return } - removeRedundantFindRequests(level) + removeRedundantFindRequests(level, func(searchNode) bool { return false }) level.Range(func(key searchNodeKey, _ searchNode) bool { remaining = append(remaining, key) return true diff --git a/tsc/internal/project/projectcollectionbuilder_test.go b/tsc/internal/project/projectcollectionbuilder_test.go index 20447d90c1d1e..bbfc8abc8b304 100644 --- a/tsc/internal/project/projectcollectionbuilder_test.go +++ b/tsc/internal/project/projectcollectionbuilder_test.go @@ -159,6 +159,97 @@ func TestProjectCollectionBuilder(t *testing.T) { } }) + t.Run("mixed find and create requests preserve project selection", func(t *testing.T) { + t.Parallel() + for _, test := range []struct { + name string + loaded bool + updatedBConfig string + want tspath.RootedFilePath + }{ + {"loaded project keeps its earlier find position", true, "", "/project/b.json"}, + {"unloaded project can still be created", false, "", "/project/b.json"}, + {"dirty project keeps its earlier position after refresh", true, `{"files": ["b.ts", "main.ts", "a.ts"]}`, "/project/b.json"}, + {"dirty project loses stale match", true, `{"files": ["b.ts"]}`, "/project/c.json"}, + } { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + files := map[string]any{ + "/project/tsconfig.json": `{"files": [], "references": [{"path": "./find.json"}, {"path": "./create.json"}]}`, + "/project/find.json": `{"compilerOptions": {"disableReferencedProjectLoad": true}, "files": [], "references": [{"path": "./a.json"}, {"path": "./b.json"}]}`, + "/project/create.json": `{"files": [], "references": [{"path": "./c.json"}, {"path": "./a.json"}, {"path": "./b.json"}]}`, + "/project/a.json": `{"files": ["a.ts"]}`, + "/project/b.json": `{"files": ["main.ts", "b.ts"]}`, + "/project/c.json": `{"files": ["c.ts"]}`, + "/project/a.ts": `export {};`, + "/project/b.ts": `export {};`, + "/project/c.ts": `export {};`, + "/project/main.ts": `export {};`, + } + if test.loaded { + files["/project/c.json"] = `{"files": ["main.ts", "c.ts"]}` + } + + session, utils := projecttestutil.Setup(files) + defer session.Close() + ctx := context.Background() + if test.loaded { + for _, fileName := range []string{"/project/b.ts", "/project/c.ts"} { + session.DidOpenFile(ctx, lsproto.DocumentUri("file://"+fileName), 1, files[fileName].(string), lsproto.LanguageKindTypeScript) + } + projects := session.Snapshot().ProjectCollection + for _, configPath := range []string{"/project/b.json", "/project/c.json"} { + project := projects.ConfiguredProject(utils.PathKey(configPath)) + assert.Assert(t, project != nil) + assert.Assert(t, !project.IsDirty()) + assert.Assert(t, project.HasFile("/project/main.ts")) + } + } else { + assert.Assert(t, session.Snapshot().ProjectCollection.ConfiguredProject(utils.PathKey("/project/b.json")) == nil) + } + + if test.updatedBConfig != "" { + assert.NilError(t, utils.FS().WriteFile("/project/b.json", test.updatedBConfig)) + session.DidChangeWatchedFiles(ctx, []*lsproto.FileEvent{ + {Type: lsproto.FileChangeTypeChanged, Uri: "file:///project/b.json"}, + }) + } + uri := lsproto.DocumentUri("file:///project/main.ts") + session.DidOpenFile(ctx, uri, 1, files["/project/main.ts"].(string), lsproto.LanguageKindTypeScript) + defaultProject := session.Snapshot().GetDefaultProject(uri) + assert.Assert(t, defaultProject != nil) + assert.Equal(t, defaultProject.ConfigFileName(), test.want) + }) + } + }) + + t.Run("registered but unbuilt project waits for its create position", func(t *testing.T) { + t.Parallel() + files := map[string]any{ + "/project/tsconfig.json": `{"files": [], "references": [{"path": "./find.json"}, {"path": "./create.json"}]}`, + "/project/find.json": `{"compilerOptions": {"disableReferencedProjectLoad": true}, "files": [], "references": [{"path": "./b"}]}`, + "/project/create.json": `{"files": [], "references": [{"path": "./c.json"}, {"path": "./b"}]}`, + "/project/c.json": `{"files": ["main.ts"]}`, + "/project/b/tsconfig.json": `{"files": ["../main.ts"], "references": [{"path": "./child"}]}`, + "/project/b/child/tsconfig.json": `{"compilerOptions": {"composite": true}, "files": ["child.ts"]}`, + "/project/b/child/child.ts": `export {};`, + "/project/main.ts": `export {};`, + } + session, utils := projecttestutil.Setup(files) + defer session.Close() + ctx := context.Background() + session.DidOpenFile(ctx, "file:///project/b/child/child.ts", 1, files["/project/b/child/child.ts"].(string), lsproto.LanguageKindTypeScript) + registeredProject := session.Snapshot().ProjectCollection.ConfiguredProject(utils.PathKey("/project/b/tsconfig.json")) + assert.Assert(t, registeredProject != nil) + assert.Assert(t, registeredProject.Program == nil) + + uri := lsproto.DocumentUri("file:///project/main.ts") + session.DidOpenFile(ctx, uri, 1, files["/project/main.ts"].(string), lsproto.LanguageKindTypeScript) + defaultProject := session.Snapshot().GetDefaultProject(uri) + assert.Assert(t, defaultProject != nil) + assert.Equal(t, defaultProject.ConfigFileName(), tspath.RootedFilePath("/project/c.json")) + }) + t.Run("cached source redirect does not prune a later direct match", func(t *testing.T) { t.Parallel() files := map[string]any{