Skip to content

Commit 3713de0

Browse files
Avoid rebuilding later LSP project references (#64936)
Co-authored-by: Andrew Branch <andrewbranch@users.noreply.github.com>
1 parent b9f8778 commit 3713de0

6 files changed

Lines changed: 550 additions & 56 deletions

File tree

‎tsc/internal/collections/ordered_map.go‎

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -107,16 +107,20 @@ func (m *OrderedMap[K, V]) Delete(key K) (V, bool) {
107107
}
108108

109109
delete(m.mp, key)
110+
111+
// Avoid scanning the keys when removing entries from the end.
112+
if last := len(m.keys) - 1; m.keys[last] == key {
113+
var zero K
114+
m.keys[last] = zero
115+
m.keys = m.keys[:last]
116+
return v, true
117+
}
118+
110119
i := slices.Index(m.keys, key)
111-
// If we're just removing the first or last element, avoid shifting everything around.
112120
if i == 0 {
113121
var zero K
114122
m.keys[0] = zero
115123
m.keys = m.keys[1:]
116-
} else if end := len(m.keys) - 1; i == end {
117-
var zero K
118-
m.keys[end] = zero
119-
m.keys = m.keys[:end]
120124
} else {
121125
m.keys = slices.Delete(m.keys, i, i+1)
122126
}

‎tsc/internal/collections/ordered_map_test.go‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package collections_test
33
import (
44
"fmt"
55
"slices"
6+
"strconv"
67
"strings"
78
"testing"
89

@@ -223,3 +224,41 @@ func testOrderedMapUnmarshalJSON(t *testing.T, unmarshal func([]byte, any) error
223224
err = unmarshal([]byte(`{"a": 1, "b": "two"}`), &invalidMap)
224225
assert.ErrorContains(t, err, "unmarshal")
225226
}
227+
228+
func TestOrderedMapDeleteSuffix(t *testing.T) {
229+
t.Parallel()
230+
231+
m := collections.NewOrderedMapFromList([]collections.MapEntry[int, string]{
232+
{Key: 1, Value: "one"},
233+
{Key: 2, Value: "two"},
234+
{Key: 3, Value: "three"},
235+
{Key: 4, Value: "four"},
236+
})
237+
for _, key := range []int{4, 3, 2} {
238+
want, _ := m.Get(key)
239+
value, ok := m.Delete(key)
240+
assert.Assert(t, ok)
241+
assert.Equal(t, value, want)
242+
assert.Assert(t, !m.Has(key))
243+
}
244+
assert.Equal(t, m.Size(), 1)
245+
assert.DeepEqual(t, slices.Collect(m.Keys()), []int{1})
246+
m.Set(2, "new")
247+
assert.DeepEqual(t, slices.Collect(m.Values()), []string{"one", "new"})
248+
}
249+
250+
func BenchmarkOrderedMapDeleteSuffix(b *testing.B) {
251+
for _, size := range []int{1024, 8192, 32768} {
252+
b.Run(strconv.Itoa(size), func(b *testing.B) {
253+
m := collections.NewOrderedMapWithSizeHint[int, int](size)
254+
for b.Loop() {
255+
for key := range size {
256+
m.Set(key, key)
257+
}
258+
for key := size - 1; key > 0; key-- {
259+
m.Delete(key)
260+
}
261+
}
262+
})
263+
}
264+
}

‎tsc/internal/core/bfs.go‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -30,9 +30,9 @@ func (l *BreadthFirstSearchLevel[K, N]) Delete(key K) {
3030
l.jobs.Delete(key)
3131
}
3232

33-
func (l *BreadthFirstSearchLevel[K, N]) Range(f func(node N) bool) {
34-
for job := range l.jobs.Values() {
35-
if !f(job.node) {
33+
func (l *BreadthFirstSearchLevel[K, N]) Range(f func(key K, node N) bool) {
34+
for key, job := range l.jobs.Entries() {
35+
if !f(key, job.node) {
3636
return
3737
}
3838
}

‎tsc/internal/project/projectcollectionbuilder.go‎

Lines changed: 144 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -1086,6 +1086,48 @@ type searchResult struct {
10861086
retain collections.Set[tspath.PathKey]
10871087
}
10881088

1089+
func removeRedundantFindRequests(
1090+
level *core.BreadthFirstSearchLevel[searchNodeKey, searchNode],
1091+
keepFind func(searchNode) bool,
1092+
) {
1093+
var redundantKeys []searchNodeKey
1094+
level.Range(func(key searchNodeKey, node searchNode) bool {
1095+
if key.loadKind != projectLoadKindFind {
1096+
return true
1097+
}
1098+
createKey := searchNodeKey{configFileName: key.configFileName, loadKind: projectLoadKindCreate}
1099+
// Built projects can match at their earlier Find position.
1100+
if level.Has(createKey) && !keepFind(node) {
1101+
redundantKeys = append(redundantKeys, key)
1102+
}
1103+
return true
1104+
})
1105+
for _, key := range redundantKeys {
1106+
level.Delete(key)
1107+
}
1108+
}
1109+
1110+
// Keep earlier candidates in the parallel search so they can still win.
1111+
func pruneAfterCachedMatch(
1112+
level *core.BreadthFirstSearchLevel[searchNodeKey, searchNode],
1113+
isCachedMatch func(searchNodeKey) bool,
1114+
) {
1115+
foundMatch := false
1116+
var trailingKeys []searchNodeKey
1117+
level.Range(func(key searchNodeKey, _ searchNode) bool {
1118+
if foundMatch {
1119+
trailingKeys = append(trailingKeys, key)
1120+
} else {
1121+
foundMatch = isCachedMatch(key)
1122+
}
1123+
return true
1124+
})
1125+
// Collect before deleting to avoid skipping entries. Tail deletion keeps pruning linear.
1126+
for _, key := range slices.Backward(trailingKeys) {
1127+
level.Delete(key)
1128+
}
1129+
}
1130+
10891131
func (b *ProjectCollectionBuilder) findOrCreateDefaultConfiguredProjectWorker(
10901132
fileName tspath.RootedFilePath,
10911133
path tspath.PathKey,
@@ -1100,6 +1142,62 @@ func (b *ProjectCollectionBuilder) findOrCreateDefaultConfiguredProjectWorker(
11001142
visited = &collections.SyncSet[searchNodeKey]{}
11011143
}
11021144

1145+
// A nil LogTree suppresses logging during cached-match checks.
1146+
configMayContainFile := func(config *tsoptions.ParsedCommandLine, logger *logging.LogTree) bool {
1147+
if len(config.FileNames()) == 0 {
1148+
// A solution config can still lead to a match through its references.
1149+
logger.Log("Project does not contain file (no root files)")
1150+
return false
1151+
}
1152+
// !!! what about declaration files in node_modules? wouldn't it be better to
1153+
// check project inclusion if the project is already loaded?
1154+
if config.CompilerOptions().Composite.IsTrue() && !config.FilePaths().Has(path) {
1155+
logger.Log("Project does not contain file (by composite config inclusion)")
1156+
return false
1157+
}
1158+
return true
1159+
}
1160+
1161+
fileInclusion := func(project *Project, logger *logging.LogTree) (included, direct bool) {
1162+
if !project.containsFile(path) {
1163+
logger.Log("Project does not contain file")
1164+
return false, false
1165+
}
1166+
direct = !project.IsSourceFromProjectReference(path)
1167+
if logger != nil {
1168+
logger.Logf("Project contains file %s", core.IfElse(direct, "directly", "as a source of a referenced project"))
1169+
}
1170+
return true, direct
1171+
}
1172+
1173+
visit := func(node searchNode) (included, direct bool) {
1174+
configFilePath := b.toPathKey(node.configFileName)
1175+
config := b.configFileRegistryBuilder.findOrAcquireConfigForFile(node.configFileName, configFilePath, path, node.loadKind, node.logger.Fork("Acquiring config for open file"))
1176+
if config == nil {
1177+
node.logger.Log("Config file for project does not already exist")
1178+
return false, false
1179+
}
1180+
configs.Store(configFilePath, config)
1181+
if !configMayContainFile(config, node.logger) {
1182+
return false, false
1183+
}
1184+
1185+
project := b.findOrCreateProject(node.configFileName, configFilePath, node.loadKind, node.logger)
1186+
if project == nil {
1187+
node.logger.Log("Project does not already exist")
1188+
return false, false
1189+
}
1190+
1191+
if node.loadKind == projectLoadKindCreate {
1192+
// Ensure project is up to date before checking for file inclusion
1193+
b.updateProgram(project, node.logger)
1194+
}
1195+
1196+
return fileInclusion(project.Value(), node.logger)
1197+
}
1198+
1199+
// PreprocessLevel sets up the shared visits before the workers for each level start.
1200+
mixedVisits := make(map[tspath.RootedFilePath]func() (bool, bool))
11031201
search := core.BreadthFirstSearchParallelEx(
11041202
searchNode{configFileName: configFileName, loadKind: loadKind, logger: logger},
11051203
func(node searchNode) []searchNode {
@@ -1120,62 +1218,60 @@ func (b *ProjectCollectionBuilder) findOrCreateDefaultConfiguredProjectWorker(
11201218
}
11211219
return nil
11221220
},
1123-
func(node searchNode) (isResult bool, stop bool) {
1124-
configFilePath := b.toPathKey(node.configFileName)
1125-
config := b.configFileRegistryBuilder.findOrAcquireConfigForFile(node.configFileName, configFilePath, path, node.loadKind, node.logger.Fork("Acquiring config for open file"))
1126-
if config == nil {
1127-
node.logger.Log("Config file for project does not already exist")
1128-
return false, false
1221+
func(node searchNode) (bool, bool) {
1222+
if shared := mixedVisits[node.configFileName]; shared != nil {
1223+
return shared()
11291224
}
1130-
configs.Store(configFilePath, config)
1131-
if len(config.FileNames()) == 0 {
1132-
// Likely a solution tsconfig.json - the search will fan out to its references.
1133-
node.logger.Log("Project does not contain file (no root files)")
1134-
return false, false
1135-
}
1136-
1137-
if config.CompilerOptions().Composite == core.TSTrue {
1138-
// For composite projects, we can get an early negative result.
1139-
// !!! what about declaration files in node_modules? wouldn't it be better to
1140-
// check project inclusion if the project is already loaded?
1141-
if !config.FilePaths().Has(path) {
1142-
node.logger.Log("Project does not contain file (by composite config inclusion)")
1143-
return false, false
1144-
}
1145-
}
1146-
1147-
project := b.findOrCreateProject(node.configFileName, configFilePath, node.loadKind, node.logger)
1148-
if project == nil {
1149-
node.logger.Log("Project does not already exist")
1150-
return false, false
1151-
}
1152-
1153-
if node.loadKind == projectLoadKindCreate {
1154-
// Ensure project is up to date before checking for file inclusion
1155-
b.updateProgram(project, node.logger)
1156-
}
1157-
1158-
if project.Value().containsFile(path) {
1159-
isDirectInclusion := !project.Value().IsSourceFromProjectReference(path)
1160-
if node.logger != nil {
1161-
node.logger.Logf("Project contains file %s", core.IfElse(isDirectInclusion, "directly", "as a source of a referenced project"))
1162-
}
1163-
return true, isDirectInclusion
1164-
}
1165-
1166-
node.logger.Log("Project does not contain file")
1167-
return false, false
1225+
return visit(node)
11681226
},
11691227
core.BreadthFirstSearchOptions[searchNodeKey, searchNode]{
11701228
Visited: visited,
11711229
PreprocessLevel: func(level *core.BreadthFirstSearchLevel[searchNodeKey, searchNode]) {
1172-
level.Range(func(node searchNode) bool {
1173-
if node.loadKind == projectLoadKindFind && level.Has(searchNodeKey{configFileName: node.configFileName, loadKind: projectLoadKindCreate}) {
1174-
// Remove find requests when a create request for the same project is already present.
1175-
level.Delete(searchNodeKey{configFileName: node.configFileName, loadKind: node.loadKind})
1230+
clear(mixedVisits)
1231+
removeRedundantFindRequests(level, func(node searchNode) bool {
1232+
entry, ok := b.configuredProjects.Load(ConfiguredProjectIDFromPathKey(b.toPathKey(node.configFileName)))
1233+
if !ok || entry.Value().Program == nil {
1234+
return false
1235+
}
1236+
createKey := searchNodeKey{configFileName: node.configFileName, loadKind: projectLoadKindCreate}
1237+
if !visited.Has(createKey) {
1238+
// Share the refresh while preserving each job's position and reference load kind.
1239+
node.loadKind = projectLoadKindCreate
1240+
mixedVisits[node.configFileName] = sync.OnceValues(func() (bool, bool) { return visit(node) })
11761241
}
11771242
return true
11781243
})
1244+
pruneAfterCachedMatch(level, func(key searchNodeKey) bool {
1245+
if visited.Has(key) {
1246+
return false
1247+
}
1248+
configPath := b.toPathKey(key.configFileName)
1249+
projectEntry, ok := b.configuredProjects.Load(ConfiguredProjectIDFromPathKey(configPath))
1250+
if !ok {
1251+
return false
1252+
}
1253+
project := projectEntry.Value()
1254+
if project.IsDirty() {
1255+
return false
1256+
}
1257+
configEntry, ok := b.configFileRegistryBuilder.configs.Load(configPath)
1258+
if !ok {
1259+
return false
1260+
}
1261+
cachedConfig := configEntry.Value()
1262+
if cachedConfig.pendingReload != PendingReloadNone {
1263+
return false
1264+
}
1265+
config := cachedConfig.commandLine
1266+
if config == nil || project.CommandLine != config {
1267+
return false
1268+
}
1269+
if !configMayContainFile(config, nil) {
1270+
return false
1271+
}
1272+
_, direct := fileInclusion(project, nil)
1273+
return direct
1274+
})
11791275
},
11801276
},
11811277
func(node searchNode) searchNodeKey {

0 commit comments

Comments
 (0)