Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/release-notes/.VisualStudio/18.vNext.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
* Peek Definition on an F# symbol whose definition lives in metadata no longer deadlocks Visual Studio. Peek holds the main thread in `JoinableTaskFactory.Run` without pumping messages while it asks the language service for the definition, and generating the metadata document needs that same thread; Peek now stops at definitions that already have a document, and Go To Definition, which owns the wait it makes, still opens the generated one. ([PR #20503](https://github.com/dotnet/fsharp/pull/20503))
* Improve Find All References performance by throttling parallel typechecks. ([PR #20128](https://github.com/dotnet/fsharp/pull/20128), [PR #20695](https://github.com/dotnet/fsharp/pull/20695))
* Fix record-type Rename corrupting copy-and-update expressions, including from abstract signatures, while retaining Find All References results. ([Issue #20791](https://github.com/dotnet/fsharp/issues/20791), [PR #20797](https://github.com/dotnet/fsharp/pull/20797))
* Go To Definition, Find All References, Rename and Quick Info reach the source of a symbol from an assembly built with `--pathmap`, which names its files relative to a root it does not record. ([PR #20519](https://github.com/dotnet/fsharp/pull/20519))
* Fixed Rename incorrectly renaming `get` and `set` keywords for properties with explicit accessors. ([Issue #18270](https://github.com/dotnet/fsharp/issues/18270), [PR #19252](https://github.com/dotnet/fsharp/pull/19252))
* Fixed Find All References crash when F# project contains non-F# files like `.cshtml`. ([Issue #16394](https://github.com/dotnet/fsharp/issues/16394), [PR #19252](https://github.com/dotnet/fsharp/pull/19252))
* Avoid using `cancellableTask` in `DocumentCache`; the editor cache now uses direct `CancellationToken`-aware `task` wrappers, avoiding the background `Task.Run` offload and a larger wrapper closure from the `cancellableTask` builder. ([Issue #20268](https://github.com/dotnet/fsharp/issues/20268))
Expand Down
127 changes: 119 additions & 8 deletions vsintegration/src/FSharp.Editor/Common/CodeAnalysisExtensions.fs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,71 @@ module internal Microsoft.VisualStudio.FSharp.Editor.CodeAnalysisExtensions

open Microsoft.CodeAnalysis
open FSharp.Compiler.Text
open System
open System.Collections.Concurrent
open System.Collections.Generic
open System.IO
open System.Runtime.CompilerServices

/// A compiler range's file name. A build with a path map (DeterministicSourcePaths) leaves it relative to a root the
/// assembly never records, so it only gives the tail of a document's path. .NET Framework throws on a name written for another OS.
let (|RootedFileName|MappedFileName|) (fileName: string) =
try
if Path.IsPathRooted fileName then
RootedFileName
else
MappedFileName
with :? ArgumentException ->
MappedFileName

/// None where the name climbs above its start: what it denotes depends on the root a path map never records.
let private mappedNameTail (fileName: string) =
let segments = ResizeArray<string>()
let mutable climbsAboveItsStart = false

for segment in fileName.Split([| '/'; '\\' |], StringSplitOptions.RemoveEmptyEntries) do
match segment with
| "." -> ()
| ".." when segments.Count > 0 -> segments.RemoveAt(segments.Count - 1)
| ".." -> climbsAboveItsStart <- true
| segment -> segments.Add segment

if climbsAboveItsStart || segments.Count = 0 then
ValueNone
else
let separator = string Path.DirectorySeparatorChar
ValueSome $"{separator}{String.Join(separator, segments)}"

let private endsWithMappedName (path: string) (tail: string) =
path.AsSpan().EndsWith(tail.AsSpan(), StringComparison.OrdinalIgnoreCase)

let isTheFileAt (path: string) (fileName: string) =
match fileName with
| null -> false
| RootedFileName -> String.Equals(Path.GetFullPathSafe fileName, path, StringComparison.OrdinalIgnoreCase)
| MappedFileName -> mappedNameTail fileName |> ValueOption.exists (endsWithMappedName path)

/// One scan of the solution's documents per name: every link of a tooltip and every project searched asks again.
let private documentsByMappedName =
ConditionalWeakTable<Solution, ConcurrentDictionary<string, DocumentId list>>()

let private candidatesForMappedName (solution: Solution) (relative: string) =
let byName =
documentsByMappedName.GetValue(solution, fun _ -> ConcurrentDictionary(StringComparer.OrdinalIgnoreCase))

byName.GetOrAdd(
relative,
fun relative ->
match mappedNameTail relative with
| ValueNone -> []
| ValueSome tail ->
[
for project in solution.Projects do
for document in project.Documents do
if endsWithMappedName document.FilePath tail then
document.Id
]
)

type Project with

Expand Down Expand Up @@ -31,6 +95,41 @@ type Project with
this.GetProjectIdsOfAllProjectsThisProjectDependsOn()
|> Seq.map this.Solution.GetProject

let private assembliesReadBy (reader: Project) =
[
reader.AssemblyName

for referenced in reader.GetAllProjectsThisProjectDependsOn() do
referenced.AssemblyName

for reference in reader.MetadataReferences do
match reference with
| :? PortableExecutableReference as file ->
match file.FilePath with
| null -> ()
| path -> Path.GetFileNameWithoutExtension path
| _ -> ()
]

let private documentsOfMappedName (solution: Solution) (relative: string) (declaringAssemblies: string list) =
let isDeclaredByAny (documentId: DocumentId) =
let assembly = solution.GetProject(documentId.ProjectId).AssemblyName

declaringAssemblies
|> List.exists (fun declarer -> String.Equals(declarer, assembly, StringComparison.OrdinalIgnoreCase))

let candidates =
candidatesForMappedName solution relative |> List.filter isDeclaredByAny

let distinctFiles =
HashSet(
candidates
|> List.map (fun documentId -> solution.GetDocument(documentId).FilePath),
StringComparer.OrdinalIgnoreCase
)

if distinctFiles.Count = 1 then candidates else []

type Solution with

/// Checks if the file path is associated with a document in the solution.
Expand Down Expand Up @@ -80,12 +179,21 @@ type Solution with
member self.GetAllProjectsThisProjectDependsOn(projectId: ProjectId) =
self.GetProjectIdsOfAllProjectReferences projectId |> Seq.map self.GetProject

/// The documents of a range's file; for a mapped name, the one file ending with it in `declaringAssembly` or one `readBy` reads.
member self.GetDocumentIdsWithFSharpFileName(fileName: string, ?declaringAssembly: string, ?readBy: Project) =
match fileName with
| null -> []
| RootedFileName -> self.GetDocumentIdsWithFilePath(Path.GetFullPathSafe fileName) |> List.ofSeq
| MappedFileName ->
match declaringAssembly, readBy with
| Some assembly, _ -> documentsOfMappedName self fileName [ assembly ]
| None, Some reader -> documentsOfMappedName self fileName (assembliesReadBy reader)
| None, None -> []

/// Try to retrieve the corresponding DocumentId for the range's file in the solution
/// and if a projectId is provided, only try to find the document within that project
/// or a project referenced by that project
member self.TryGetDocumentIdFromFSharpRange(range: range, ?projectId: ProjectId) =

let filePath = System.IO.Path.GetFullPathSafe range.FileName
member self.TryGetDocumentIdFromFSharpRange(range: range, ?projectId: ProjectId, ?declaringAssembly: string) =

let checkProjectId (docId: DocumentId) =
if projectId.IsSome then
Expand All @@ -107,13 +215,16 @@ type Solution with
matchingDoc tail
| None -> Some docId

self.GetDocumentIdsWithFilePath filePath |> List.ofSeq |> matchingDoc
self.GetDocumentIdsWithFSharpFileName(
range.FileName,
?declaringAssembly = declaringAssembly,
?readBy = (projectId |> Option.bind self.TryGetProject)
)
|> matchingDoc

/// Try to retrieve the corresponding Document for the range's file in the solution
/// and if a projectId is provided, only try to find the document within that project
/// or a project referenced by that project
member self.TryGetDocumentFromFSharpRange(range: range, ?projectId: ProjectId) =
match projectId with
| Some projectId -> self.TryGetDocumentIdFromFSharpRange(range, projectId)
| None -> self.TryGetDocumentIdFromFSharpRange range
member self.TryGetDocumentFromFSharpRange(range: range, ?projectId: ProjectId, ?declaringAssembly: string) =
self.TryGetDocumentIdFromFSharpRange(range, ?projectId = projectId, ?declaringAssembly = declaringAssembly)
|> Option.map self.GetDocument
20 changes: 10 additions & 10 deletions vsintegration/src/FSharp.Editor/LanguageService/SymbolHelpers.fs
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,11 @@ module internal SymbolHelpers =
do! symbolUses |> Seq.map ((<||) onFound) |> CancellableTask.whenAll

| scope ->
let projectsHoldingTheAssembly () =
match symbolUse.Symbol.Assembly.FileName with
| Some assemblyPath -> ProjectFiltering.getProjectsReferencingAssembly assemblyPath currentDocument.Project.Solution
| None -> []

let projectsToCheck =
match scope with
| Some(SymbolScope.CurrentDocument)
Expand All @@ -152,22 +157,17 @@ module internal SymbolHelpers =
for scopeProject in scopeProjects do
yield scopeProject
yield! scopeProject.GetDependentProjects()

yield! projectsHoldingTheAssembly ()

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖🕵️ [P2] Find All References/Rename cancelled when a C# project references the same DLL

Loaded Library.fs: module ExternalLibrary
                  let value = 42
ExternalLibrary.dll: built with --pathmap:<build>=.
F# App.fs (-r:ExternalLibrary.dll): ExternalLibrary.value
C# App.csproj: <Reference Include="ExternalLibrary.dll" />
Neither consumer has a ProjectReference to the loaded library.
FAR/Rename on value -> OperationCanceledException("Project is not a FSharp project.")

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

At d304595, when an F# library's source is loaded and both F# and C# projects reference its DLL, the expanded search scope includes the C# project and sends it into F# snapshot creation. A fresh probe using a real imported symbol and the pinned selection/filter/guard code passes for the base scoped search but throws OperationCanceledException("Project is not a FSharp project.") for the head; this was not a full editor FAR/Rename run. Perhaps exclude non-F# projects before creating F# snapshots while preserving the newly included F# binary consumers, with a mixed-language regression test.

]
|> List.distinct
| Some(SymbolScope.Projects(scopeProjects, true)) -> scopeProjects
// The symbol is declared in .NET framework, an external assembly or in a C# project within the solution.
// Optimization: Only search projects that reference the specific assembly
| None ->
match symbolUse.Symbol.Assembly.FileName with
| Some assemblyPath ->
let referencingProjects =
ProjectFiltering.getProjectsReferencingAssembly assemblyPath currentDocument.Project.Solution

if List.isEmpty referencingProjects then
Seq.toList currentDocument.Project.Solution.Projects
else
referencingProjects
| None -> Seq.toList currentDocument.Project.Solution.Projects
match projectsHoldingTheAssembly () with
| [] -> Seq.toList currentDocument.Project.Solution.Projects
| referencingProjects -> referencingProjects

do! getSymbolUsesInProjects (symbolUse.Symbol, projectsToCheck, onFound)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ type FSharpSymbolUse with
Some(SymbolScope.Projects([ currentDocument.Project ], isSymbolLocalForProject))
else
let projects =
currentDocument.Project.Solution.GetDocumentIdsWithFilePath(filePath)
currentDocument.Project.Solution.GetDocumentIdsWithFSharpFileName(loc.FileName, this.Symbol.Assembly.SimpleName)
|> Seq.map (fun x -> x.ProjectId)
|> Seq.distinct
|> Seq.map currentDocument.Project.Solution.GetProject
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,12 +59,13 @@ module FSharpFindUsagesService =
}

// File can be included in more than one project, hence single `range` may results with multiple `Document`s.
let rangeToDocumentSpans (solution: Solution, range: range, symbolName: string) =
let rangeToDocumentSpans (solution: Solution, range: range, symbolName: string, declaringAssembly: string) =
if range.Start = range.End then
CancellableTask.singleton [||]
else
cancellableTask {
let documentIds = solution.GetDocumentIdsWithFilePath(range.FileName)
let documentIds =
solution.GetDocumentIdsWithFSharpFileName(range.FileName, declaringAssembly)

let! spans =
seq {
Expand Down Expand Up @@ -117,9 +118,11 @@ module FSharpFindUsagesService =
| FindDeclResult.DeclFound range -> Some range
| _ -> None

let declaringAssembly = symbolUse.Symbol.Assembly.SimpleName

let! declarationSpans =
match declarationRange with
| Some range -> rangeToDocumentSpans (document.Project.Solution, range, symbol.Ident.idText)
| Some range -> rangeToDocumentSpans (document.Project.Solution, range, symbol.Ident.idText, declaringAssembly)
| None -> CancellableTask.singleton [||]

let declarationSpans =
Expand Down
Loading
Loading