Skip to content

Commit dbae72c

Browse files
xperiandriclaude
andcommitted
Search from the first file that can compile differently, not by file
A file with no conditional directives of its own can still resolve differently between two instances when an earlier file's conditional compilation changes what a shared name means. Skipping such a file because it itself tests no differing define left it unsearched, and Rename could leave the other instance uncompilable. Track the leading run of files both instances compile identically instead of judging each file alone; the search starts at the first file that diverges and covers everything after it. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
1 parent 53ee126 commit dbae72c

2 files changed

Lines changed: 138 additions & 37 deletions

File tree

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

Lines changed: 62 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -690,6 +690,46 @@ let private dependsOnDefines (defines: string Set) (parseTree: ParsedInput) =
690690
| ConditionalDirectiveTrivia.Else _
691691
| ConditionalDirectiveTrivia.EndIf _ -> false)
692692

693+
/// The files two instances of one project compile identically, counting from the first. F# reads a
694+
/// name's meaning from the files ahead of it, so a file that follows one parsing differently can
695+
/// resolve differently however plain it looks itself - the shared run ends at the first such file.
696+
let private identicallyCompiledPrefix
697+
differingDefines
698+
(documentsByPath: Dictionary<string, Document>)
699+
(sourceFiles: string array)
700+
(searchedSourceFiles: string array)
701+
userOpName
702+
=
703+
cancellableTask {
704+
let mutable index = 0
705+
let mutable diverged = false
706+
707+
while not diverged && index < sourceFiles.Length do
708+
let path = sourceFiles[index]
709+
710+
let! compilesTheSame =
711+
if
712+
index >= searchedSourceFiles.Length
713+
|| not (String.Equals(path, searchedSourceFiles[index], StringComparison.OrdinalIgnoreCase))
714+
then
715+
CancellableTask.singleton false
716+
elif Set.isEmpty differingDefines then
717+
CancellableTask.singleton true
718+
else
719+
match documentsByPath.TryGetValue path with
720+
| true, document ->
721+
document.GetFSharpParseResultsAsync userOpName
722+
|> CancellableTask.map (fun parseResults -> not (dependsOnDefines differingDefines parseResults.ParseTree))
723+
| _ -> CancellableTask.singleton false
724+
725+
if compilesTheSame then
726+
index <- index + 1
727+
else
728+
diverged <- true
729+
730+
return HashSet(Seq.truncate index sourceFiles, StringComparer.OrdinalIgnoreCase)
731+
}
732+
693733
/// How many documents of one project a search keeps in flight. The throttle it shares with the other
694734
/// projects decides how many of those actually run.
695735
[<Literal>]
@@ -698,9 +738,9 @@ let private WorkersPerProject = 4
698738
type Project with
699739

700740
/// Find F# references in the given project. When `searchedInstance` is another target-framework
701-
/// instance of the same project file that has already been searched, only the documents whose
702-
/// sources can differ from it are searched: files compiled only here and files whose conditional
703-
/// compilation tests a define the two instances disagree on.
741+
/// instance of the same project file that has already been searched, the leading files both
742+
/// compile identically are left to it; the search starts at the first file that can differ and
743+
/// covers everything after it.
704744
member this.FindFSharpReferencesAsync
705745
(
706746
symbol: FSharpSymbol,
@@ -740,46 +780,38 @@ type Project with
740780
}
741781
| _ -> CancellableTask.singleton Set.empty
742782

743-
let searchedPaths =
744-
searchedInstance
745-
|> ValueOption.map (fun instance -> HashSet(instance.Documents |> Seq.map _.FilePath, StringComparer.OrdinalIgnoreCase))
746-
747783
// Only the defines one instance has and the other lacks can make a shared file parse
748784
// differently; the ones they agree on cannot, however many directives test them.
749-
let definesOf (project: Project) =
785+
let optionsOf (project: Project) =
750786
getFSharpOptionsForProject project
751-
|> CancellableTask.map (fun (_, _, parsingOptions: FSharpParsingOptions, _) -> Set parsingOptions.ConditionalDefines)
787+
|> CancellableTask.map (fun (_, _, parsingOptions: FSharpParsingOptions, options: FSharpProjectOptions) ->
788+
Set parsingOptions.ConditionalDefines, options.SourceFiles)
752789

753-
let! differingDefines =
790+
let! alreadyCovered =
754791
match searchedInstance with
755-
| ValueNone -> CancellableTask.singleton Set.empty
792+
| ValueNone -> CancellableTask.singleton (HashSet<string> StringComparer.OrdinalIgnoreCase)
756793
| ValueSome instance ->
757794
cancellableTask {
758-
let! defines = definesOf this
759-
let! searchedDefines = definesOf instance
760-
return (defines - searchedDefines) + (searchedDefines - defines)
761-
}
795+
let! defines, sourceFiles = optionsOf this
796+
let! searchedDefines, searchedSourceFiles = optionsOf instance
762797

763-
let needsSearch (document: Document) =
764-
match searchedPaths with
765-
| ValueSome paths when paths.Contains document.FilePath ->
766-
if differingDefines.IsEmpty then
767-
CancellableTask.singleton false
768-
else
769-
document.GetFSharpParseResultsAsync userOpName
770-
|> CancellableTask.map (fun parseResults -> dependsOnDefines differingDefines parseResults.ParseTree)
771-
| _ -> CancellableTask.singleton true
798+
let differingDefines = (defines - searchedDefines) + (searchedDefines - defines)
799+
800+
let documentsByPath = Dictionary(StringComparer.OrdinalIgnoreCase)
801+
802+
for document in this.Documents do
803+
documentsByPath[document.FilePath] <- document
804+
805+
return! identicallyCompiledPrefix differingDefines documentsByPath sourceFiles searchedSourceFiles userOpName
806+
}
772807

773808
let search (document: Document) =
774809
cancellableTask {
775810
let! ct = CancellableTask.getCancellationToken ()
776811
do! throttle.WaitAsync ct
777812

778813
try
779-
let! needed = needsSearch document
780-
781-
if needed then
782-
do! document.FindFSharpReferencesAsync(symbol, projectSnapshot, onFound document, userOpName)
814+
do! document.FindFSharpReferencesAsync(symbol, projectSnapshot, onFound document, userOpName)
783815
finally
784816
throttle.Release() |> ignore
785817
}
@@ -788,7 +820,8 @@ type Project with
788820
this.Documents
789821
|> Seq.filter (fun document ->
790822
isFSharpSourceFile document.FilePath
791-
&& not (canSkipDocuments.Contains document.FilePath))
823+
&& not (canSkipDocuments.Contains document.FilePath)
824+
&& not (alreadyCovered.Contains document.FilePath))
792825
// Workers take the next document when they free up. Starting one task per document
793826
// instead would leave every document of the solution parked on the throttle at once.
794827
|> CancellableTask.forEachThrottled WorkersPerProject search

‎vsintegration/tests/FSharp.Editor.Tests/MultiTargetFindReferencesTests.fs‎

Lines changed: 76 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information.
22

3-
/// One project loaded as two target-framework instances: `plain` compiles without the fourth file
4-
/// and without FOO, `foo` compiles everything with FOO defined. Both define COMMON.
3+
/// Projects loaded as two target-framework instances each. In the first, `plain` compiles without
4+
/// the fourth file and without FOO, `foo` compiles everything with FOO defined, and both define
5+
/// COMMON; the second pair differs only on FOO.
56
module FSharp.Editor.Tests.MultiTargetFindReferencesTests
67

78
open System
@@ -63,11 +64,13 @@ let private declarationPosition =
6364

6465
let private instanceOf index = if index = 0 then plainId else fooId
6566

66-
let private documentIn (projectId: ProjectId) path =
67+
let private documentOf (solution: Solution) (projectId: ProjectId) path =
6768
solution.GetDocumentIdsWithFilePath path
6869
|> Seq.find (fun id -> id.ProjectId = projectId)
6970
|> solution.GetDocument
7071

72+
let private documentIn projectId path = documentOf solution projectId path
73+
7174
[<Theory>]
7275
[<InlineData(0)>]
7376
[<InlineData(1)>]
@@ -85,17 +88,17 @@ let ``every file is searched once, files under conditional compilation and insta
8588
Assert.Equal(6, foundReferences.Count)
8689

8790
/// What Rename works from: the symbol's uses grouped by Roslyn document.
88-
let private usesByDocument (document: Document) =
91+
let private usesByDocument position (document: Document) =
8992
let sourceText = document.GetTextAsync(CancellationToken.None).Result
90-
let textLine = sourceText.Lines.GetLineFromPosition declarationPosition
93+
let textLine = sourceText.Lines.GetLineFromPosition position
9194

92-
let fcsLine = Line.fromZ (sourceText.Lines.GetLinePosition declarationPosition).Line
95+
let fcsLine = Line.fromZ (sourceText.Lines.GetLinePosition position).Line
9396

9497
let lexerSymbol =
9598
Tokenizer.getSymbolAtPosition (
9699
document.Id,
97100
sourceText,
98-
declarationPosition,
101+
position,
99102
document.FilePath,
100103
[],
101104
SymbolLookupKind.Greedy,
@@ -121,7 +124,8 @@ let private usesByDocument (document: Document) =
121124
[<InlineData(0)>]
122125
[<InlineData(1)>]
123126
let ``rename gets every use once, from an instance that compiles its file`` (instance: int) =
124-
let uses = usesByDocument (documentIn (instanceOf instance) firstPath)
127+
let uses =
128+
usesByDocument declarationPosition (documentIn (instanceOf instance) firstPath)
125129

126130
let located =
127131
[
@@ -142,3 +146,67 @@ let ``rename gets every use once, from an instance that compiles its file`` (ins
142146
solution.GetProject(documentId.ProjectId).Documents |> Seq.map _.FilePath
143147

144148
Assert.Contains(solution.GetDocument(documentId).FilePath, compiledHere)
149+
150+
/// `Consumer` carries no directive of its own, but the record whose field it reads is inferred from
151+
/// `Chooser`, which the two instances compile differently: with FOO the field is `A.Record.value`,
152+
/// without it `B.Record.value`.
153+
let private inferredProject =
154+
SyntheticProject.Create(
155+
"MultiTargetInferredType",
156+
{ sourceFile "Chooser" [] with
157+
ExtraSource =
158+
[
159+
"module A ="
160+
" type Record = { value: int }"
161+
"module B ="
162+
" type Record = { value: int }"
163+
"#if FOO"
164+
"let input: A.Record = { value = 1 }"
165+
"#else"
166+
"let input: B.Record = { value = 1 }"
167+
"#endif"
168+
]
169+
|> String.concat "\n"
170+
},
171+
{ sourceFile "Consumer" [ "Chooser" ] with
172+
ExtraSource = "let output = ModuleChooser.input.value"
173+
}
174+
)
175+
176+
let private inferredSolution, inferredPlainId =
177+
let solution, instances =
178+
RoslynTestHelpers.CreateMultiTargetSolution(
179+
inferredProject,
180+
[
181+
{ Defines = []; ExcludedFileIds = [] }
182+
{
183+
Defines = [ "FOO" ]
184+
ExcludedFileIds = []
185+
}
186+
]
187+
)
188+
189+
match instances with
190+
| [ plainId; _ ] -> solution, plainId
191+
| _ -> failwith "two instances expected"
192+
193+
let private chooserPath = inferredProject.GetFilePath "Chooser"
194+
195+
/// `A.Record.value`, the field only the FOO instance reads outside its own declaration.
196+
let private inferredDeclarationPosition =
197+
(File.ReadAllText chooserPath).IndexOf("value", StringComparison.Ordinal)
198+
199+
// Searching from the instance without FOO, `Consumer` holds no use of this field - it reads
200+
// `B.Record.value` there. Its use in the FOO instance is still a use, and Rename that misses it
201+
// leaves that build calling a field that no longer exists.
202+
[<Fact>]
203+
let ``a file without directives is searched when an earlier file changes what its names mean`` () =
204+
let uses =
205+
usesByDocument inferredDeclarationPosition (documentOf inferredSolution inferredPlainId chooserPath)
206+
207+
let files =
208+
[
209+
for KeyValue(documentId, _) in uses -> inferredSolution.GetDocument(documentId).FilePath
210+
]
211+
212+
Assert.Contains(inferredProject.GetFilePath "Consumer", files)

0 commit comments

Comments
 (0)