Skip to content

Commit ddffeff

Browse files
xperiandriclaude
andcommitted
Answer the Navigate-To search that runs while the solution loads
Navigate To runs a search of its own during load, dispatched through `IAdvancedNavigateToSearchService`. F# did not implement it, so every F# project was reported complete and searched not at all, and no full search follows by design — nothing F# declares could be found until the user searched again. The search is a parse away. What it lacked is the project's compilation options, which do not exist yet during load, so `GetFSharpParseResultsAsync` raises. `GetFSharpQuickParseResultsAsync` parses with whatever parsing options the project system has already produced, or defaults: a dictionary read, no reactor, no I/O, which is what makes it safe to call for every document of every project while the solution loads. Those defines can be the wrong ones, and the document's version does not change when the real options arrive, so the version stamp alone would let an approximate parse answer the accurate search: a declaration behind `#if` could be missed, or reported from a branch that never compiles. The cache entry carries whether it was approximate, and the accurate path refuses those, reparsing instead. The loading path takes either, since its contract allows out-of-date results. `SearchCachedDocumentsAsync` follows the shape of the C# and VB service: priority documents and the projects that hold them are searched first, results are reported per document rather than per project so the first ones appear while the rest are still parsing, and each project is reported complete once it is done. The parses take turns on the throttle every search shares, so a search during load cannot take the cores away from the load itself. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
1 parent 49f4629 commit ddffeff

5 files changed

Lines changed: 262 additions & 26 deletions

File tree

‎docs/release-notes/.VisualStudio/18.vNext.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77

88
### Fixed
99

10+
* Navigate To lists F# declarations while the solution is still loading. Until now the search that runs during load skipped F# entirely, and the full search that follows it is never started, so nothing F# declares could be found until the next search.
1011
* Reuse the in-memory PE reference of a referenced C# project while its dependent semantic version is unchanged, so dependent F# projects no longer re-import every reference and re-check every file each time Roslyn recreates the `Compilation`. ([PR #20460](https://github.com/dotnet/fsharp/pull/20460))
1112
* Fixed `MissingManifestResourceException` when opening F# pages under Tools > Options by giving `FSharpPackage` its own `VSPackage` resource set. ([PR #20408](https://github.com/dotnet/fsharp/pull/20408))
1213
* Go To Definition no longer blocks the UI thread with a bare `Task.Wait`: the synchronous `IFSharpGoToDefinitionService` call now waits through the cancellable threaded-wait dialog, and the editor's `TaskCompletionSource` bridges run their continuations on the thread pool instead of inline on whichever thread finished the check, so repeated F12 on a large solution no longer starves semantic classification and other main-thread work.

‎vsintegration/src/FSharp.Editor/LanguageService/WorkspaceExtensions.fs‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -659,6 +659,12 @@ type Document with
659659
this.TryGetFSharpParseResultsAsync(userOpName)
660660
|> CancellableTask.map (orRaise "FSharp project options not found.")
661661

662+
/// Parses the given F# document with the parsing options its project has already produced, or with defaults when
663+
/// it has none yet: the only parse available while the project system is still loading. The defines can be the
664+
/// wrong ones, so the tree describes a compilation that may never happen.
665+
member this.GetFSharpQuickParseResultsAsync(userOpName) =
666+
this.GetFSharpChecker().ParseDocument(this, this.GetFSharpQuickParsingOptions(), userOpName)
667+
662668
/// Parses and checks the given F# document; ValueNone while its project has no compilation options
663669
/// or the check was aborted.
664670
member this.TryGetFSharpParseAndCheckResultsAsync

‎vsintegration/src/FSharp.Editor/Navigation/NavigateToSearchService.fs‎

Lines changed: 122 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,14 @@ type internal FSharpNavigableItemsCache
2929
(patternMatcherFactory: IPatternMatcherFactory, [<Import(AllowDefault = true)>] workspace: VisualStudioWorkspace) =
3030

3131
let cache =
32-
ConcurrentDictionary<DocumentId, struct (VersionStamp * NavigableItem array)>()
32+
ConcurrentDictionary<
33+
DocumentId,
34+
struct {|
35+
Version: VersionStamp
36+
Approximate: bool
37+
Items: NavigableItem array
38+
|}
39+
>()
3340

3441
/// Whether the file's parse depends on the defines, by file path: known once any instance has parsed it.
3542
let conditionalDirectives =
@@ -49,30 +56,54 @@ type internal FSharpNavigableItemsCache
4956
| ParsedInput.ImplFile file -> not file.Trivia.ConditionalDirectives.IsEmpty
5057
| ParsedInput.SigFile file -> not file.Trivia.ConditionalDirectives.IsEmpty
5158

59+
let store (document: Document) version approximate (parseTree: ParsedInput) =
60+
let items = NavigateTo.GetNavigableItems parseTree
61+
62+
cache[document.Id] <-
63+
struct {|
64+
Version = version
65+
Approximate = approximate
66+
Items = items
67+
|}
68+
69+
match document.FilePath with
70+
| null -> ()
71+
| path -> conditionalDirectives[path] <- hasConditionalDirectives parseTree
72+
73+
items
74+
5275
member _.GetNavigableItems(document: Document) =
5376
cancellableTask {
5477
let! ct = CancellableTask.getCancellationToken ()
5578
let! currentVersion = document.GetTextVersionAsync(ct)
5679

5780
match cache.TryGetValue document.Id with
58-
| true, struct (version, items) when version = currentVersion -> return items
81+
| true, entry when entry.Version = currentVersion && not entry.Approximate -> return entry.Items
5982
| _ ->
6083
let! parseResults = document.GetFSharpParseResultsAsync(nameof (FSharpNavigableItemsCache))
61-
let items = NavigateTo.GetNavigableItems parseResults.ParseTree
62-
cache[document.Id] <- struct (currentVersion, items)
84+
return store document currentVersion false parseResults.ParseTree
85+
}
6386

64-
match document.FilePath with
65-
| null -> ()
66-
| path -> conditionalDirectives[path] <- hasConditionalDirectives parseResults.ParseTree
87+
/// The items of a parse that does not wait for the project's compilation options, for the search that runs while
88+
/// the solution is still loading. A file behind `#if` can be read under the wrong defines, so the entry it leaves
89+
/// behind never answers `GetNavigableItems`.
90+
member _.GetNavigableItemsWhileLoading(document: Document) =
91+
cancellableTask {
92+
let! ct = CancellableTask.getCancellationToken ()
93+
let! currentVersion = document.GetTextVersionAsync(ct)
6794

68-
return items
95+
match cache.TryGetValue document.Id with
96+
| true, entry when entry.Version = currentVersion -> return entry.Items
97+
| _ ->
98+
let! parseResults = document.GetFSharpQuickParseResultsAsync(nameof (FSharpNavigableItemsCache))
99+
return store document currentVersion true parseResults.ParseTree
69100
}
70101

71102
/// The items of the document's last parse, whatever version they came from. Reads no text, so a
72103
/// closed document costs nothing; a caller that needs the items of the current text asks for them.
73104
member _.TryGetCachedNavigableItems(documentId: DocumentId) =
74105
match cache.TryGetValue documentId with
75-
| true, struct (_, items) -> ValueSome items
106+
| true, entry -> ValueSome entry.Items
76107
| _ -> ValueNone
77108

78109
/// Whether the file's parse tree, from whichever instance parsed it first, has `#if` directives.
@@ -113,8 +144,6 @@ type internal FSharpNavigableItemsCache
113144
[<Export(typeof<IFSharpNavigateToSearchService>); Shared>]
114145
type internal FSharpNavigateToSearchService [<ImportingConstructor>] (itemsCache: FSharpNavigableItemsCache) =
115146

116-
let getNavigableItems (document: Document) = itemsCache.GetNavigableItems document
117-
118147
/// A multi-targeted project is one Roslyn project per target framework over the same files. The
119148
/// first instance in the solution searches every file; the others only the files they alone compile
120149
/// and the files whose parse depends on the defines.
@@ -211,9 +240,14 @@ type internal FSharpNavigateToSearchService [<ImportingConstructor>] (itemsCache
211240
let createMatcherFor (searchPattern: string) =
212241
itemsCache.CreateMatcherFor searchPattern
213242

214-
let processDocument (tryMatch: NavigableItem -> PatternMatch voption) (kinds: IImmutableSet<string>) (document: Document) =
243+
let processDocument
244+
(getItems: Document -> CancellableTask<NavigableItem array>)
245+
(tryMatch: NavigableItem -> PatternMatch voption)
246+
(kinds: IImmutableSet<string>)
247+
(document: Document)
248+
=
215249
cancellableTask {
216-
let! items = getNavigableItems document
250+
let! items = getItems document
217251

218252
let matches =
219253
[|
@@ -254,27 +288,89 @@ type internal FSharpNavigateToSearchService [<ImportingConstructor>] (itemsCache
254288
|> ImmutableArray.CreateRange
255289
}
256290

291+
let searchProject (project: Project) searchPattern kinds =
292+
cancellableTask {
293+
let tryMatch = createMatcherFor searchPattern
294+
295+
let! results =
296+
project.Documents
297+
|> Seq.filter (searchedIn project)
298+
|> Seq.map (processDocument itemsCache.GetNavigableItems tryMatch kinds)
299+
// Throttle to avoid launching a parse per document in the project all at once.
300+
|> CancellableTask.whenAllThrottled (max 1 Environment.ProcessorCount)
301+
302+
return results |> Seq.collect _.AsEnumerable() |> Seq.toImmutableArray
303+
}
304+
305+
/// Priority items first, each half in its original order, as NavigateTo's own service orders its work.
306+
let prioritize isPriority items =
307+
let priority, rest = items |> Seq.toArray |> Array.partition isPriority
308+
[| yield! priority; yield! rest |]
309+
310+
/// A parse behind the loading search takes a turn on the budget every search shares.
311+
let throttled (work: CancellableTask<'a>) =
312+
cancellableTask {
313+
let! ct = CancellableTask.getCancellationToken ()
314+
do! SymbolHelpers.searchThrottle.WaitAsync ct
315+
316+
try
317+
return! work
318+
finally
319+
SymbolHelpers.searchThrottle.Release() |> ignore
320+
}
321+
257322
interface IFSharpNavigateToSearchService with
258323
member _.SearchProjectAsync
259324
(project, _priorityDocuments, searchPattern, kinds, cancellationToken)
260325
: Task<ImmutableArray<FSharpNavigateToSearchResult>> =
261-
cancellableTask {
262-
let tryMatch = createMatcherFor searchPattern
263-
264-
let! results =
265-
project.Documents
266-
|> Seq.filter (searchedIn project)
267-
|> Seq.map (processDocument tryMatch kinds)
268-
// Throttle to avoid launching a parse per document in the project all at once.
269-
|> CancellableTask.whenAllThrottled (max 1 Environment.ProcessorCount)
270-
271-
return results |> Seq.collect _.AsEnumerable() |> Seq.toImmutableArray
272-
}
326+
searchProject project searchPattern kinds
273327
|> CancellableTask.start cancellationToken
274328

275329
member _.SearchDocumentAsync(document: Document, searchPattern, kinds, cancellationToken) =
276-
processDocument (createMatcherFor searchPattern) kinds document cancellationToken
330+
processDocument itemsCache.GetNavigableItems (createMatcherFor searchPattern) kinds document cancellationToken
277331

278332
member _.KindsProvided = kindsProvided
279333

280334
member _.CanFilter = true
335+
336+
interface IFSharpAdvancedNavigateToSearchService with
337+
member _.SearchCachedDocumentsAsync
338+
(
339+
_solution,
340+
projects,
341+
priorityDocuments,
342+
searchPattern,
343+
kinds,
344+
_activeDocument,
345+
onResultsFound,
346+
onProjectCompleted,
347+
cancellationToken
348+
) : Task =
349+
let tryMatch = createMatcherFor searchPattern
350+
let priorityIds = ImmutableHashSet.CreateRange(priorityDocuments |> Seq.map _.Id)
351+
let isPriority (document: Document) = priorityIds.Contains document.Id
352+
353+
let searchDocumentWhileLoading document =
354+
cancellableTask {
355+
let! results = throttled (processDocument itemsCache.GetNavigableItemsWhileLoading tryMatch kinds document)
356+
357+
if results.Length > 0 then
358+
do! onResultsFound.Invoke results
359+
}
360+
361+
let searchProjectWhileLoading (project: Project) =
362+
cancellableTask {
363+
do!
364+
project.Documents
365+
|> Seq.filter (searchedIn project)
366+
|> prioritize isPriority
367+
|> CancellableTask.forEachThrottled Environment.ProcessorCount searchDocumentWhileLoading
368+
369+
do! onProjectCompleted.Invoke()
370+
}
371+
372+
projects
373+
|> prioritize (fun project -> project.Documents |> Seq.exists isPriority)
374+
|> Seq.map searchProjectWhileLoading
375+
|> CancellableTask.whenAll
376+
|> CancellableTask.startAsTask cancellationToken

‎vsintegration/tests/FSharp.Editor.Tests/FSharp.Editor.Tests.fsproj‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@
3838
<Compile Include="CrossLanguageSymbolNavigationTests.fs" />
3939
<Compile Include="CopilotContextProviderTests.fs" />
4040
<Compile Include="MultiTargetNavigateToSearchTests.fs" />
41+
<Compile Include="NavigateToSearchWhileLoadingTests.fs" />
4142
<Compile Include="CodeFixes\CodeFixTestFramework.fs" />
4243
<Compile Include="CodeFixes\AddInstanceMemberParameterTests.fs" />
4344
<Compile Include="CodeFixes\ConvertToAnonymousRecordTests.fs" />
Lines changed: 132 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,132 @@
1+
// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information.
2+
3+
/// Navigate To runs a search of its own while the solution is still loading, and nothing it searches
4+
/// then has its compilation options yet.
5+
module FSharp.Editor.Tests.NavigateToSearchWhileLoadingTests
6+
7+
open System
8+
open System.Collections.Immutable
9+
open System.Threading
10+
open System.Threading.Tasks
11+
12+
open Xunit
13+
14+
open Microsoft.CodeAnalysis
15+
open Microsoft.CodeAnalysis.ExternalAccess.FSharp.NavigateTo
16+
17+
open FSharp.Editor.Tests.Helpers
18+
19+
/// A project the project system has not yet handed its command line options: the state every project
20+
/// of the solution is in until it has loaded.
21+
let private loadingProject name source =
22+
let projectId = ProjectId.CreateNewId()
23+
24+
[ RoslynTestHelpers.CreateDocumentInfo projectId $"C:\\{name}.fs" source ]
25+
|> RoslynTestHelpers.CreateProjectInfo projectId $"C:\\{name}.fsproj"
26+
27+
let private loadingSolution source =
28+
let project = loadingProject "test" source
29+
let solution = RoslynTestHelpers.CreateSolution [ project ]
30+
project.Id, solution, solution.Projects |> Seq.exactlyOne
31+
32+
/// One export provider per test: the navigable items are cached in a shared one.
33+
let private searchServices () =
34+
let service: IFSharpNavigateToSearchService =
35+
MefHelpers.createExportProvider().GetExportedValue()
36+
37+
service, service :?> IFSharpAdvancedNavigateToSearchService
38+
39+
let private namesFound (results: ImmutableArray<FSharpNavigateToSearchResult>) = results |> Seq.map _.Name |> Seq.toList
40+
41+
/// The loading search as the searcher drives it: results and project completions arrive through callbacks.
42+
/// Returns the names found and how many times a project was reported complete.
43+
let private searchWhileLoading
44+
(service: IFSharpNavigateToSearchService, advanced: IFSharpAdvancedNavigateToSearchService)
45+
(projects: Project list)
46+
pattern
47+
=
48+
task {
49+
let found = ResizeArray()
50+
let completed = ref 0
51+
52+
do!
53+
advanced.SearchCachedDocumentsAsync(
54+
(List.head projects).Solution,
55+
ImmutableArray.CreateRange projects,
56+
ImmutableArray.Empty,
57+
pattern,
58+
service.KindsProvided,
59+
null,
60+
(fun results ->
61+
lock found (fun () -> found.AddRange results)
62+
Task.CompletedTask),
63+
(fun () ->
64+
Interlocked.Increment &completed.contents |> ignore
65+
Task.CompletedTask),
66+
CancellationToken.None
67+
)
68+
69+
return found |> Seq.map _.Name |> Seq.toList, completed.Value
70+
}
71+
72+
[<Fact>]
73+
let ``the loading search finds what the search that waits for the options cannot`` () : Task =
74+
task {
75+
let _, _, project =
76+
loadingSolution "module Sample =\n let declaredWhileLoading = 1\n"
77+
78+
let (service, _) as services = searchServices ()
79+
80+
let searchAccurately () =
81+
service.SearchProjectAsync(project, ImmutableArray.Empty, "declaredWhileLoading", service.KindsProvided, CancellationToken.None)
82+
:> Task
83+
84+
let! _ = Assert.ThrowsAnyAsync<OperationCanceledException>(fun () -> searchAccurately ())
85+
86+
let! names, completed = searchWhileLoading services [ project ] "declaredWhileLoading"
87+
88+
Assert.Equal<string list>([ "declaredWhileLoading" ], names)
89+
Assert.Equal(1, completed)
90+
91+
// What the loading search left in the cache must not be handed to the accurate search: it was
92+
// read without the project's defines.
93+
let! _ = Assert.ThrowsAnyAsync<OperationCanceledException>(fun () -> searchAccurately ())
94+
()
95+
}
96+
97+
[<Fact>]
98+
let ``the loading search reads a file under the wrong defines and does not keep the answer`` () : Task =
99+
task {
100+
let projectId, solution, project =
101+
loadingSolution "#if FOO\nlet fooOnly = 1\n#endif\n"
102+
103+
let (service, _) as services = searchServices ()
104+
105+
let! namesWhileLoading, _ = searchWhileLoading services [ project ] "fooOnly"
106+
Assert.Equal<string list>([], namesWhileLoading)
107+
108+
{ RoslynTestHelpers.DefaultProjectOptions with
109+
OtherOptions = [| "--define:FOO" |]
110+
}
111+
|> RoslynTestHelpers.SetProjectOptions projectId solution
112+
113+
let! found = service.SearchProjectAsync(project, ImmutableArray.Empty, "fooOnly", service.KindsProvided, CancellationToken.None)
114+
115+
Assert.Equal<string list>([ "fooOnly" ], namesFound found)
116+
}
117+
118+
[<Fact>]
119+
let ``every project is reported complete once, whether or not anything is found in it`` () : Task =
120+
task {
121+
let solution =
122+
RoslynTestHelpers.CreateSolution
123+
[
124+
loadingProject "first" "let found = 1\n"
125+
loadingProject "second" "let other = 2\n"
126+
]
127+
128+
let! names, completed = searchWhileLoading (searchServices ()) (solution.Projects |> Seq.toList) "found"
129+
130+
Assert.Equal<string list>([ "found" ], names)
131+
Assert.Equal(2, completed)
132+
}

0 commit comments

Comments
 (0)