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/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 b6e808a983dfd..60c59b19a4044 100644 --- a/tsc/internal/project/projectcollectionbuilder.go +++ b/tsc/internal/project/projectcollectionbuilder.go @@ -1086,6 +1086,48 @@ type searchResult struct { retain collections.Set[tspath.PathKey] } +func removeRedundantFindRequests( + level *core.BreadthFirstSearchLevel[searchNodeKey, searchNode], + keepFind func(searchNode) bool, +) { + var redundantKeys []searchNodeKey + 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 + }) + for _, key := range redundantKeys { + level.Delete(key) + } +} + +// Keep earlier candidates in the parallel search so they can still win. +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 + }) + // Collect before deleting to avoid skipping entries. Tail deletion keeps pruning linear. + for _, key := range slices.Backward(trailingKeys) { + level.Delete(key) + } +} + func (b *ProjectCollectionBuilder) findOrCreateDefaultConfiguredProjectWorker( fileName tspath.RootedFilePath, path tspath.PathKey, @@ -1100,6 +1142,62 @@ 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. + 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 + } + + 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 { @@ -1120,62 +1218,60 @@ 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 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)") - 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") - return false, false - } - - if node.loadKind == projectLoadKindCreate { - // Ensure project is up to date before checking for file inclusion - 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 visit(node) }, core.BreadthFirstSearchOptions[searchNodeKey, searchNode]{ Visited: visited, PreprocessLevel: func(level *core.BreadthFirstSearchLevel[searchNodeKey, searchNode]) { - level.Range(func(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}) + 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 { + return false + } + project := projectEntry.Value() + if project.IsDirty() { + return false + } + configEntry, ok := b.configFileRegistryBuilder.configs.Load(configPath) + if !ok { + return false + } + cachedConfig := configEntry.Value() + if cachedConfig.pendingReload != PendingReloadNone { + return false + } + config := cachedConfig.commandLine + if config == nil || project.CommandLine != config { + return false + } + if !configMayContainFile(config, nil) { + return false + } + _, direct := fileInclusion(project, nil) + return direct + }) }, }, 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..ec0ce5dcfb276 --- /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, func(searchNode) bool { return false }) + 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 cfa6b1b1114ff..bbfc8abc8b304 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,261 @@ 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 { + 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) + } + }) + }) + + 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("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{ + "/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)