From e4bd97de7193d6ae63c182838df244a3706a22bf Mon Sep 17 00:00:00 2001 From: Andrii Chebukin Date: Thu, 10 Sep 2026 20:14:19 +0200 Subject: [PATCH 1/3] Name a mapped declaration from its root once A build that maps its source paths - as DeterministicSourcePaths does - maps the directory it compiled in along with the file names of its ranges, so the two reach the same root and neither records what that root is. `fileNameOfItem` joined them anyway, on the assumption that the directory is absolute and the file name relative to it, and the declaration of a symbol imported from such an assembly came back naming the directory twice. Nothing matches a path like that, so Go To Definition reported the symbol as external and opened generated metadata instead of its source. Join only when the directory is rooted. When it is not, the file name already reaches the root on its own and is as complete as the metadata can make it. The IDE drops the path map from the options it builds, so this is reached through an assembly on disk - which is where a path map is normally applied, and which no change to those options can rewrite. Co-Authored-By: Claude Opus 5 (1M context) --- .../.FSharp.Compiler.Service/11.0.100.md | 2 + src/Compiler/Symbols/SymbolHelpers.fs | 10 ++- .../FSharpChecker/PathMap.fs | 85 +++++++++++++------ 3 files changed, 67 insertions(+), 30 deletions(-) diff --git a/docs/release-notes/.FSharp.Compiler.Service/11.0.100.md b/docs/release-notes/.FSharp.Compiler.Service/11.0.100.md index d8bf8f9195f..09128f81609 100644 --- a/docs/release-notes/.FSharp.Compiler.Service/11.0.100.md +++ b/docs/release-notes/.FSharp.Compiler.Service/11.0.100.md @@ -6,6 +6,7 @@ * Fix reference-assembly MVID collisions when a public member is renamed in an early file of a large (>~32 file) project under `--optimize-`. The per-file signature hashes were folded with a left-shift-by-one combiner over a 32-bit `Hash`, which truncated the contribution of any file more than ~32 positions from the end of the compile order, so MSBuild's `CopyRefAssembly` saw an unchanged MVID and kept a stale reference assembly (surfacing as `FS0039` downstream). The combiner is now an FNV-1a multiply mix over a 64-bit `Hash`. ([Issue #20389](https://github.com/dotnet/fsharp/issues/20389)) * Fix internal error FS0192 "Iterate2D" when a `[]` parameter auto-quotes an argument that captures a not-yet-generalized use of an inferred generically-recursive function. The auto-quoted (`Expr.WithValue`) copy now keeps a fresh link to the recursive-value use so it receives the same inferred type arguments as the executable expression at the letrec point. ([Issue #20379](https://github.com/dotnet/fsharp/issues/20379)) * Fix `StackOverflowException` when checking a long `seq { ... }` body. ([PR #20480](https://github.com/dotnet/fsharp/pull/20480)) +* `GetDeclarationLocation` no longer names the compile-time directory twice for a declaration in an assembly built with `--pathmap` (as `DeterministicSourcePaths` sets it). Such a build maps the directory it compiled in as well as the file names of its ranges, so both already reach the same root and joining them repeated the directory, leaving a path that matches no file. * Fix `NativePtr.stackalloc` nested in a larger expression (e.g. a call argument or the right of an assignment) producing an assembly that throws `InvalidProgramException` at load. ([Issue #8083](https://github.com/dotnet/fsharp/issues/8083), [PR #20302](https://github.com/dotnet/fsharp/pull/20302)) * Fix internal error "Unexpected generalized type variables when compiling an active pattern" when an active pattern is used in a `let` binding whose right-hand side is a generic value, e.g. `let (T) = id`. Such a binding is now checked like the equivalent `match` and is not generalized. ([Issue #16856](https://github.com/dotnet/fsharp/issues/16856), [PR #20383](https://github.com/dotnet/fsharp/pull/20383)) * Fix Release-only (`--optimize+`) `System.InvalidProgramException` from `Seq.collect` / `yield!` over a value-type (struct) collection implementing `seq<'T>` (e.g. `ImmutableArray<_>`) when materialised with `List.ofSeq` / `Seq.toList` / `Seq.toArray` or a list/array comprehension. The collector lowering now boxes a struct sub-collection to `seq<'T>` before calling `AddMany`/`AddManyAndClose` (matching the coercion the type checker already inserts for `yield!`), and uses `unit` as the try/finally result type instead of the body type (removing a spurious `ldnull` store). ([Issue #20203](https://github.com/dotnet/fsharp/issues/20203)) @@ -168,6 +169,7 @@ * Reject runtime-only Await calls inside ordinary task state-machine methods with FS3918, while preserving normal task composition inside runtime-async methods. ([Issue #20576](https://github.com/dotnet/fsharp/issues/20576), [PR #20584](https://github.com/dotnet/fsharp/pull/20584)) * Fix dependency ordering and stack safety for recursive inline bindings. ([PR #20111](https://github.com/dotnet/fsharp/pull/20111)) * Fix signature generation (`fsc --sig`, `GenerateSignature`, `GetValSignatureText`) dropping the parentheses around a destructured or pattern-annotated tuple parameter when a sibling argument in the same curried group is named, so `(int * float) * z: string` no longer prints as the flat 3-tuple `int * float * z: string`. ([Issue #20397](https://github.com/dotnet/fsharp/issues/20397), [PR #20589](https://github.com/dotnet/fsharp/pull/20589)) +* A project reusing cached framework imports is checked with its own `--pathmap` instead of the map of the project that filled the cache, so the ranges of its in-memory reference data name its real files. ([Issue #20474](https://github.com/dotnet/fsharp/issues/20474), [PR #20476](https://github.com/dotnet/fsharp/pull/20476)) ### Added diff --git a/src/Compiler/Symbols/SymbolHelpers.fs b/src/Compiler/Symbols/SymbolHelpers.fs index 222edab7c13..1ee4c203a68 100644 --- a/src/Compiler/Symbols/SymbolHelpers.fs +++ b/src/Compiler/Symbols/SymbolHelpers.fs @@ -230,14 +230,20 @@ module internal SymbolHelpers = let fileNameOfItem (g: TcGlobals) qualProjectDir (m: range) h = let file = m.FileName if verbose then dprintf "file stored in metadata is '%s'\n" file + + // A build that maps its source paths maps the directory it compiled in as well, so that directory + // and the file name reach the same unrecorded root on their own: joining them repeats the directory. + let underDirectory (dir: string) = + if FileSystem.IsPathRootedShim dir then Path.Combine(dir, file) else file + if not (FileSystem.IsPathRootedShim file) then match ccuOfItem g h with | Some ccu -> - Path.Combine(ccu.SourceCodeDirectory, file) + underDirectory ccu.SourceCodeDirectory | None -> match qualProjectDir with | None -> file - | Some dir -> Path.Combine(dir, file) + | Some dir -> underDirectory dir else file let ParamNameAndTypesOfUnaryCustomOperation g minfo = diff --git a/tests/FSharp.Compiler.ComponentTests/FSharpChecker/PathMap.fs b/tests/FSharp.Compiler.ComponentTests/FSharpChecker/PathMap.fs index 32cae8490e4..8bf70c250d5 100644 --- a/tests/FSharp.Compiler.ComponentTests/FSharpChecker/PathMap.fs +++ b/tests/FSharp.Compiler.ComponentTests/FSharpChecker/PathMap.fs @@ -5,22 +5,31 @@ open System.Threading.Tasks open Xunit open FSharp.Test.ProjectGeneration open FSharp.Compiler.CodeAnalysis +open FSharp.Compiler.EditorServices open FSharp.Compiler.Text let private checkWith (checker: FSharpChecker) (project: SyntheticProject) = ProjectWorkflowBuilder(project, checker = checker).Yield() |> Async.Ignore -/// The file an App names as declaring the function it uses from the library, once another project has filled the -/// cache: the framework imports, and the TcGlobals with them, are cached per framework set. -let private libraryFileSeenAfter (useTransparentCompiler: bool) (cacheFiller: SyntheticProject) (library: SyntheticProject) = +/// The framework imports, and the TcGlobals with them, are cached per framework set; the path map of +/// the project that filled the cache must not reach the ranges a sibling exposes to its consumers. +[] +[] +[] +let ``a sibling's path map does not reach the ranges of a project without one`` (useTransparentCompiler: bool) : Task = task { let checker = FSharpChecker.Create(useTransparentCompiler = useTransparentCompiler) + let library = SyntheticProject.Create("Library", sourceFile "Library" []) + + let mapped = + { SyntheticProject.Create("Mapped", sourceFile "Mapped" []) with + OtherOptions = [ $"--pathmap:{Path.GetDirectoryName library.ProjectDir}=.\\" ] } let app = { SyntheticProject.Create("App", sourceFile "App" [ "Library" ]) with DependsOn = [ library ] } - do! checkWith checker cacheFiller + do! checkWith checker mapped do! checkWith checker app let appFile = app.GetFilePath "App" @@ -45,41 +54,61 @@ let private libraryFileSeenAfter (useTransparentCompiler: bool) (cacheFiller: Sy failwith $"""ModuleLibrary.f not used; symbols: %A{checkResults.GetAllUsesOfAllSymbolsInFile() |> Seq.map _.Symbol.FullName |> Seq.distinct |> List.ofSeq}""") - return libraryFunction.Symbol.DeclarationLocation.Value.FileName + Assert.Equal(library.GetFilePath "Library", libraryFunction.Symbol.DeclarationLocation.Value.FileName) } -/// The path map of the project that filled the cache must not reach the ranges a sibling exposes to its consumers. +/// A build that maps its source paths maps the directory it compiled in as well, so the file name of a +/// range and that directory both reach the same root on their own. Joining them names the directory twice. [] [] [] -let ``a sibling's path map does not reach the ranges of a project without one`` (useTransparentCompiler: bool) : Task = +let ``a declaration in a project with a path map is named from the root once`` (useTransparentCompiler: bool) : Task = task { - let library = SyntheticProject.Create("Library", sourceFile "Library" []) + let checker = FSharpChecker.Create(useTransparentCompiler = useTransparentCompiler) + let library = SyntheticProject.Create("MappedLibrary", sourceFile "Library" []) + let root = Path.GetDirectoryName library.ProjectDir - let mapped = - { SyntheticProject.Create("Mapped", sourceFile "Mapped" []) with - OtherOptions = [ $"--pathmap:{Path.GetDirectoryName library.ProjectDir}=.\\" ] } + let library = + { library with + OtherOptions = [ $"--pathmap:{root}=.\\" ] } - let! declaredIn = libraryFileSeenAfter useTransparentCompiler mapped library + let app = + { SyntheticProject.Create("MappedApp", sourceFile "App" [ "Library" ]) with + DependsOn = [ library ] } - Assert.Equal(library.GetFilePath "Library", declaredIn) - } + do! checkWith checker library + do! checkWith checker app -/// Nor may a project lose its own path map to a sibling without one that filled the cache first. -[] -[] -[] -let ``a project's path map reaches its ranges after a sibling without one filled the cache`` (useTransparentCompiler: bool) : Task = - task { - let unmapped = SyntheticProject.Create("Unmapped", sourceFile "Unmapped" []) - let library = SyntheticProject.Create("Library", sourceFile "Library" []) - let root = Path.GetDirectoryName library.ProjectDir + let appFile = app.GetFilePath "App" + let appLines = File.ReadAllLines appFile - let library = - { library with - OtherOptions = [ $"--pathmap:{root}=." ] } + let! _, answer = + checker.ParseAndCheckFileInProject( + appFile, + 0, + SourceText.ofString (File.ReadAllText appFile), + app.GetProjectOptions checker + ) - let! declaredIn = libraryFileSeenAfter useTransparentCompiler unmapped library + let checkResults = + match answer with + | FSharpCheckFileAnswer.Succeeded checkResults -> checkResults + | FSharpCheckFileAnswer.Aborted -> failwith "the check was aborted" + + let usage = + checkResults.GetAllUsesOfAllSymbolsInFile() + |> Seq.find (fun symbolUse -> symbolUse.Symbol.FullName = $"{library.Name}.ModuleLibrary.f") + + let declaration = + checkResults.GetDeclarationLocation( + usage.Range.EndLine, + usage.Range.EndColumn, + appLines[usage.Range.EndLine - 1], + [ "ModuleLibrary"; "f" ] + ) - Assert.Equal("." + (library.GetFilePath "Library").Substring(root.Length), declaredIn) + match declaration with + | FindDeclResult.DeclFound range -> + Assert.Equal(library.GetFilePath "Library", Path.GetFullPath(Path.Combine(root, range.FileName))) + | result -> failwith $"expected the declaration of ModuleLibrary.f, got %A{result}" } From be7a738a2105e6385cb783246ce9789edd0f0850 Mon Sep 17 00:00:00 2001 From: XperiAndri Date: Sun, 18 Oct 2026 13:34:23 +0200 Subject: [PATCH 2/3] Decide per assembly whether a recorded file name is a compiled file A name recorded under a relative --pathmap already starts with the compile directory, so joining the two repeated it. A relative #line name that a compiler before F# 10 wrote is relative to that directory even when it starts with it. The assembly tells them apart: a name is a compiled file when a module, type or namespace has its range in that file, or a value published through a signature has its implementation there. This replaces the walk from the item to its outermost entity, which missed custom operations, named arguments and members of types declared directly in a namespace. The tests now cover a custom operation, a namespace whose last fragment holds no type, and a value of a signature'd module that sits in a nested module. Co-Authored-By: Claude Sonnet 5.5 --- .../.FSharp.Compiler.Service/11.0.100.md | 2 - .../.FSharp.Compiler.Service/11.0.200.md | 3 + src/Compiler/Symbols/SymbolHelpers.fs | 27 ++- .../FSharpChecker/PathMap.fs | 203 +++++++++++++----- .../FSharpChecker/PathMapFSharp9.dll | Bin 0 -> 4096 bytes tests/FSharp.Test.Utilities/Compiler.fs | 26 +-- 6 files changed, 181 insertions(+), 80 deletions(-) create mode 100644 tests/FSharp.Compiler.ComponentTests/FSharpChecker/PathMapFSharp9.dll diff --git a/docs/release-notes/.FSharp.Compiler.Service/11.0.100.md b/docs/release-notes/.FSharp.Compiler.Service/11.0.100.md index 09128f81609..d8bf8f9195f 100644 --- a/docs/release-notes/.FSharp.Compiler.Service/11.0.100.md +++ b/docs/release-notes/.FSharp.Compiler.Service/11.0.100.md @@ -6,7 +6,6 @@ * Fix reference-assembly MVID collisions when a public member is renamed in an early file of a large (>~32 file) project under `--optimize-`. The per-file signature hashes were folded with a left-shift-by-one combiner over a 32-bit `Hash`, which truncated the contribution of any file more than ~32 positions from the end of the compile order, so MSBuild's `CopyRefAssembly` saw an unchanged MVID and kept a stale reference assembly (surfacing as `FS0039` downstream). The combiner is now an FNV-1a multiply mix over a 64-bit `Hash`. ([Issue #20389](https://github.com/dotnet/fsharp/issues/20389)) * Fix internal error FS0192 "Iterate2D" when a `[]` parameter auto-quotes an argument that captures a not-yet-generalized use of an inferred generically-recursive function. The auto-quoted (`Expr.WithValue`) copy now keeps a fresh link to the recursive-value use so it receives the same inferred type arguments as the executable expression at the letrec point. ([Issue #20379](https://github.com/dotnet/fsharp/issues/20379)) * Fix `StackOverflowException` when checking a long `seq { ... }` body. ([PR #20480](https://github.com/dotnet/fsharp/pull/20480)) -* `GetDeclarationLocation` no longer names the compile-time directory twice for a declaration in an assembly built with `--pathmap` (as `DeterministicSourcePaths` sets it). Such a build maps the directory it compiled in as well as the file names of its ranges, so both already reach the same root and joining them repeated the directory, leaving a path that matches no file. * Fix `NativePtr.stackalloc` nested in a larger expression (e.g. a call argument or the right of an assignment) producing an assembly that throws `InvalidProgramException` at load. ([Issue #8083](https://github.com/dotnet/fsharp/issues/8083), [PR #20302](https://github.com/dotnet/fsharp/pull/20302)) * Fix internal error "Unexpected generalized type variables when compiling an active pattern" when an active pattern is used in a `let` binding whose right-hand side is a generic value, e.g. `let (T) = id`. Such a binding is now checked like the equivalent `match` and is not generalized. ([Issue #16856](https://github.com/dotnet/fsharp/issues/16856), [PR #20383](https://github.com/dotnet/fsharp/pull/20383)) * Fix Release-only (`--optimize+`) `System.InvalidProgramException` from `Seq.collect` / `yield!` over a value-type (struct) collection implementing `seq<'T>` (e.g. `ImmutableArray<_>`) when materialised with `List.ofSeq` / `Seq.toList` / `Seq.toArray` or a list/array comprehension. The collector lowering now boxes a struct sub-collection to `seq<'T>` before calling `AddMany`/`AddManyAndClose` (matching the coercion the type checker already inserts for `yield!`), and uses `unit` as the try/finally result type instead of the body type (removing a spurious `ldnull` store). ([Issue #20203](https://github.com/dotnet/fsharp/issues/20203)) @@ -169,7 +168,6 @@ * Reject runtime-only Await calls inside ordinary task state-machine methods with FS3918, while preserving normal task composition inside runtime-async methods. ([Issue #20576](https://github.com/dotnet/fsharp/issues/20576), [PR #20584](https://github.com/dotnet/fsharp/pull/20584)) * Fix dependency ordering and stack safety for recursive inline bindings. ([PR #20111](https://github.com/dotnet/fsharp/pull/20111)) * Fix signature generation (`fsc --sig`, `GenerateSignature`, `GetValSignatureText`) dropping the parentheses around a destructured or pattern-annotated tuple parameter when a sibling argument in the same curried group is named, so `(int * float) * z: string` no longer prints as the flat 3-tuple `int * float * z: string`. ([Issue #20397](https://github.com/dotnet/fsharp/issues/20397), [PR #20589](https://github.com/dotnet/fsharp/pull/20589)) -* A project reusing cached framework imports is checked with its own `--pathmap` instead of the map of the project that filled the cache, so the ranges of its in-memory reference data name its real files. ([Issue #20474](https://github.com/dotnet/fsharp/issues/20474), [PR #20476](https://github.com/dotnet/fsharp/pull/20476)) ### Added diff --git a/docs/release-notes/.FSharp.Compiler.Service/11.0.200.md b/docs/release-notes/.FSharp.Compiler.Service/11.0.200.md index 49d9c199e26..09236a7afa6 100644 --- a/docs/release-notes/.FSharp.Compiler.Service/11.0.200.md +++ b/docs/release-notes/.FSharp.Compiler.Service/11.0.200.md @@ -14,6 +14,9 @@ * Checker: report Bind resolution failures at the bound expression ([PR #20747](https://github.com/dotnet/fsharp/pull/20747)) * Fix invalid IL (`InvalidProgramException`) when a statically compiled `task { }` or other resumable state machine accesses a `ResumableStateMachine<_>` of a different instantiation than its own, such as a `ResumableStateMachine` field. ([Issue #20958](https://github.com/dotnet/fsharp/issues/20958), [PR #20959](https://github.com/dotnet/fsharp/pull/20959)) * A project reusing cached framework imports is checked with its own `--pathmap` instead of the map of the project that filled the cache, so the ranges of its in-memory reference data name its real files. ([Issue #20474](https://github.com/dotnet/fsharp/issues/20474), [PR #20476](https://github.com/dotnet/fsharp/pull/20476)) +* A project reusing cached framework imports is checked with its own `--pathmap` instead of the map of the project that filled the cache, so the ranges of its in-memory reference data name its real files. ([Issue #20474](https://github.com/dotnet/fsharp/issues/20474), [PR #20476](https://github.com/dotnet/fsharp/pull/20476)) +* `GetDeclarationLocation` no longer names the compile-time directory twice for a declaration in an assembly built with a relative `--pathmap`. Such a build maps the directory it compiled in along with its file names, so a file from under that directory already starts with it, and joining the two left a path that matches no file. Other relative names, such as the `#line` names that compilers before F# 10 wrote, are still resolved against that directory. ([PR #20518](https://github.com/dotnet/fsharp/pull/20518)) +* A project reusing cached framework imports is checked with its own `--pathmap` instead of the map of the project that filled the cache, so the ranges of its in-memory reference data name its real files. ([Issue #20474](https://github.com/dotnet/fsharp/issues/20474), [PR #20476](https://github.com/dotnet/fsharp/pull/20476)) * Split Linux CoreCLR CI into two parallel test batches to reduce test turnaround time. ([PR #20587](https://github.com/dotnet/fsharp/pull/20587)) * Fix wrong results or non-terminating loops in optimized code when an integer `for` loop's start or end expression binds a local. ([Issue #20732](https://github.com/dotnet/fsharp/issues/20732), [PR #20733](https://github.com/dotnet/fsharp/pull/20733)) * Checker: resolve named arguments of failed and unfinished method calls ([PR #20749](https://github.com/dotnet/fsharp/pull/20749)) diff --git a/src/Compiler/Symbols/SymbolHelpers.fs b/src/Compiler/Symbols/SymbolHelpers.fs index 1ee4c203a68..77535715f45 100644 --- a/src/Compiler/Symbols/SymbolHelpers.fs +++ b/src/Compiler/Symbols/SymbolHelpers.fs @@ -226,24 +226,35 @@ module internal SymbolHelpers = // This is not expected: NewDef only occurs within checking | Item.NewDef _ -> None + let startsWithDirectory (dir: string) (file: string) = + file.Length > dir.Length && file.StartsWithOrdinal dir && (file[dir.Length] = '\\' || file[dir.Length] = '/') + + let isCompiledFileOf (ccu: CcuThunk) (fileIndex: int) = + let rec declaresEntityIn (mty: ModuleOrNamespaceType) = + mty.AllEntities + |> Seq.exists (fun entity -> + entity.Range.FileIndex = fileIndex + || (entity.IsNamespace && declaresEntityIn entity.ModuleOrNamespaceType)) + + let implementsSignatureOf (v: Val) = v.DefinitionRange.FileIndex = fileIndex && v.Range.FileIndex <> fileIndex + + let contents = ccu.Contents.ModuleOrNamespaceType + declaresEntityIn contents || (allValsOfModuleOrNamespaceTy contents |> List.exists implementsSignatureOf) + /// Work out the source file for an item and fix it up relative to the CCU if it is relative. let fileNameOfItem (g: TcGlobals) qualProjectDir (m: range) h = let file = m.FileName if verbose then dprintf "file stored in metadata is '%s'\n" file - - // A build that maps its source paths maps the directory it compiled in as well, so that directory - // and the file name reach the same unrecorded root on their own: joining them repeats the directory. - let underDirectory (dir: string) = - if FileSystem.IsPathRootedShim dir then Path.Combine(dir, file) else file - if not (FileSystem.IsPathRootedShim file) then match ccuOfItem g h with + // A relative #line name a compiler before F# 10 wrote is relative to the directory even when it starts with it + | Some ccu when startsWithDirectory ccu.SourceCodeDirectory file && isCompiledFileOf ccu m.FileIndex -> file | Some ccu -> - underDirectory ccu.SourceCodeDirectory + Path.Combine(ccu.SourceCodeDirectory, file) | None -> match qualProjectDir with | None -> file - | Some dir -> underDirectory dir + | Some dir -> Path.Combine(dir, file) else file let ParamNameAndTypesOfUnaryCustomOperation g minfo = diff --git a/tests/FSharp.Compiler.ComponentTests/FSharpChecker/PathMap.fs b/tests/FSharp.Compiler.ComponentTests/FSharpChecker/PathMap.fs index 8bf70c250d5..8d4606cf91a 100644 --- a/tests/FSharp.Compiler.ComponentTests/FSharpChecker/PathMap.fs +++ b/tests/FSharp.Compiler.ComponentTests/FSharpChecker/PathMap.fs @@ -3,33 +3,29 @@ module FSharpChecker.PathMap open System.IO open System.Threading.Tasks open Xunit +open FSharp.Test +open FSharp.Test.Compiler open FSharp.Test.ProjectGeneration +open FSharp.Test.Utilities open FSharp.Compiler.CodeAnalysis open FSharp.Compiler.EditorServices +open FSharp.Compiler.Symbols open FSharp.Compiler.Text let private checkWith (checker: FSharpChecker) (project: SyntheticProject) = ProjectWorkflowBuilder(project, checker = checker).Yield() |> Async.Ignore -/// The framework imports, and the TcGlobals with them, are cached per framework set; the path map of -/// the project that filled the cache must not reach the ranges a sibling exposes to its consumers. -[] -[] -[] -let ``a sibling's path map does not reach the ranges of a project without one`` (useTransparentCompiler: bool) : Task = +/// The file an App names as declaring the function it uses from the library, once another project has filled the +/// cache: the framework imports, and the TcGlobals with them, are cached per framework set. +let private libraryFileSeenAfter (useTransparentCompiler: bool) (cacheFiller: SyntheticProject) (library: SyntheticProject) = task { let checker = FSharpChecker.Create(useTransparentCompiler = useTransparentCompiler) - let library = SyntheticProject.Create("Library", sourceFile "Library" []) - - let mapped = - { SyntheticProject.Create("Mapped", sourceFile "Mapped" []) with - OtherOptions = [ $"--pathmap:{Path.GetDirectoryName library.ProjectDir}=.\\" ] } let app = { SyntheticProject.Create("App", sourceFile "App" [ "Library" ]) with DependsOn = [ library ] } - do! checkWith checker mapped + do! checkWith checker cacheFiller do! checkWith checker app let appFile = app.GetFilePath "App" @@ -54,61 +50,162 @@ let ``a sibling's path map does not reach the ranges of a project without one`` failwith $"""ModuleLibrary.f not used; symbols: %A{checkResults.GetAllUsesOfAllSymbolsInFile() |> Seq.map _.Symbol.FullName |> Seq.distinct |> List.ofSeq}""") - Assert.Equal(library.GetFilePath "Library", libraryFunction.Symbol.DeclarationLocation.Value.FileName) + return libraryFunction.Symbol.DeclarationLocation.Value.FileName } -/// A build that maps its source paths maps the directory it compiled in as well, so the file name of a -/// range and that directory both reach the same root on their own. Joining them names the directory twice. +/// The path map of the project that filled the cache must not reach the ranges a sibling exposes to its consumers. [] [] [] -let ``a declaration in a project with a path map is named from the root once`` (useTransparentCompiler: bool) : Task = +let ``a sibling's path map does not reach the ranges of a project without one`` (useTransparentCompiler: bool) : Task = task { - let checker = FSharpChecker.Create(useTransparentCompiler = useTransparentCompiler) - let library = SyntheticProject.Create("MappedLibrary", sourceFile "Library" []) + let library = SyntheticProject.Create("Library", sourceFile "Library" []) + + let mapped = + { SyntheticProject.Create("Mapped", sourceFile "Mapped" []) with + OtherOptions = [ $"--pathmap:{Path.GetDirectoryName library.ProjectDir}=.\\" ] } + + let! declaredIn = libraryFileSeenAfter useTransparentCompiler mapped library + + Assert.Equal(library.GetFilePath "Library", declaredIn) + } + +/// Nor may a project lose its own path map to a sibling without one that filled the cache first. +[] +[] +[] +let ``a project's path map reaches its ranges after a sibling without one filled the cache`` (useTransparentCompiler: bool) : Task = + task { + let unmapped = SyntheticProject.Create("Unmapped", sourceFile "Unmapped" []) + let library = SyntheticProject.Create("Library", sourceFile "Library" []) let root = Path.GetDirectoryName library.ProjectDir let library = { library with - OtherOptions = [ $"--pathmap:{root}=.\\" ] } + OtherOptions = [ $"--pathmap:{root}=." ] } - let app = - { SyntheticProject.Create("MappedApp", sourceFile "App" [ "Library" ]) with - DependsOn = [ library ] } + let! declaredIn = libraryFileSeenAfter useTransparentCompiler unmapped library - do! checkWith checker library - do! checkWith checker app + Assert.Equal("." + (library.GetFilePath "Library").Substring(root.Length), declaredIn) + } - let appFile = app.GetFilePath "App" - let appLines = File.ReadAllLines appFile +let private builderSource = + """namespace Builders - let! _, answer = - checker.ParseAndCheckFileInProject( - appFile, - 0, - SourceText.ofString (File.ReadAllText appFile), - app.GetProjectOptions checker - ) +type Builder() = + member _.Yield(_: unit) : int list = [] - let checkResults = - match answer with - | FSharpCheckFileAnswer.Succeeded checkResults -> checkResults - | FSharpCheckFileAnswer.Aborted -> failwith "the check was aborted" + [] + member _.Choose(xs: int list, value: int) = value :: xs - let usage = - checkResults.GetAllUsesOfAllSymbolsInFile() - |> Seq.find (fun symbolUse -> symbolUse.Symbol.FullName = $"{library.Name}.ModuleLibrary.f") - - let declaration = - checkResults.GetDeclarationLocation( - usage.Range.EndLine, - usage.Range.EndColumn, - appLines[usage.Range.EndLine - 1], - [ "ModuleLibrary"; "f" ] - ) +module Instance = + let builder = Builder() +""" - match declaration with - | FindDeclResult.DeclFound range -> - Assert.Equal(library.GetFilePath "Library", Path.GetFullPath(Path.Combine(root, range.FileName))) - | result -> failwith $"expected the declaration of ModuleLibrary.f, got %A{result}" - } +let private compileLibrary (root: string) (mappedRoot: string) (withSignature: bool) = + let projectDir = Directory.CreateDirectory(Path.Combine(root, "src", "Domain")).FullName + + let sources = + [ + if withSignature then + "Library.fsi", "module Library\n\nmodule Nested =\n val f: x: int -> int\n" + "Library.fs", "module Library\n\nmodule Nested =\n let f x = x + 1\n" + "Builder.fs", builderSource + "Info.fs", "namespace Builders\n\nopen System.Reflection\n\n[]\ndo ()\n" + ] + + for fileName, text in sources do + File.WriteAllText(Path.Combine(projectDir, fileName), text) + + let result = + runFscProcessIn projectDir [ + "--target:library" + yield! CompilerAssert.DefaultProjectOptions(TargetFramework.Current).OtherOptions + if mappedRoot <> "" then + $"--pathmap:{root}={mappedRoot}" + "-o:Library.dll" + yield! List.map fst sources + ] + + Assert.True((result.ExitCode = 0), $"fsc exited with {result.ExitCode}:\n{result.StdOut}\n{result.StdErr}") + projectDir + +let private checkAgainst (library: string) (source: string) = + FSharp source |> withOptions [ $"-r:{library}" ] |> typecheckResults + +let private locate (source: string) (name: string) = + let lines = source.Split '\n' + let index = lines |> Array.findIndex (fun line -> line.Contains(name, System.StringComparison.Ordinal)) + let line = lines[index] + struct (index + 1, line.IndexOf(name, System.StringComparison.Ordinal) + name.Length, line, List.ofArray (name.Split '.')) + +let private declarationOf (results: FSharpCheckFileResults) (source: string) (name: string) (preferSignature: bool) = + let struct (line, column, text, names) = locate source name + + match results.GetDeclarationLocation(line, column, text, names, preferSignature) with + | FindDeclResult.DeclFound range -> range.FileName + | result -> failwith $"expected the declaration of {name}, got %A{result}" + +let private fileNameResolvedFrom (results: FSharpCheckFileResults) (source: string) (name: string) (recorded: string) = + let struct (line, column, text, names) = locate source name + let symbol = results.GetSymbolUseAtLocation(line, column, text, names).Value.Symbol + SymbolHelpers.fileNameOfItem symbol.SymbolEnv.g None (Range.rangeN recorded line) symbol.Item + +[] +[] +[] +[] +[] +let ``a declaration in a referenced assembly names the file it was compiled from`` (mappedRoot: string) (withSignature: bool) = + let root = TestFramework.createTemporaryDirectory().FullName + let projectDir = compileLibrary root mappedRoot withSignature + let source = "let _ = Library.Nested.f 1\nlet _ = Builders.Instance.builder { choose 1 }" + let results = checkAgainst (Path.Combine(projectDir, "Library.dll")) source + + let compiledFrom (fileName: string) = + let fullIfRooted (path: string) = + if Path.IsPathRooted path then Path.GetFullPath path else path + + let name = fullIfRooted fileName + let mapped = fullIfRooted (if mappedRoot = "" then root else mappedRoot) + Assert.StartsWith(mapped, name) + Path.GetFullPath(Path.Combine(root, name.Substring(mapped.Length).TrimStart('/', '\\'))) + + let assertDeclaredIn name file preferSignature = + Assert.Equal(Path.Combine(projectDir, file), compiledFrom (declarationOf results source name preferSignature)) + + let assertRelativeToCompileDirectory name recorded = + Assert.Equal( + Path.GetFullPath(Path.Combine(projectDir, recorded)), + compiledFrom (fileNameResolvedFrom results source name recorded) + ) + + assertDeclaredIn "Library.Nested.f" "Library.fs" false + assertDeclaredIn "choose" "Builder.fs" false + assertDeclaredIn "Builders" "Info.fs" false + assertRelativeToCompileDirectory "Library.Nested.f" "Original.fs" + assertRelativeToCompileDirectory "choose" (Path.Combine(".", "src", "Domain", "Original.fs")) + + if withSignature then + assertDeclaredIn "Library.Nested.f" "Library.fsi" true + +/// PathMapFSharp9.dll: FSharp.Compiler.Service 43.9.300 compiling, in a root's src\Domain with --pathmap:root=. --deterministic+, +/// module Library +/// let ordinary x = x + 1 +/// #line 1 ".\src\Domain\Original.fs" +/// let fromLine x = x + 2 +/// module Nested = +/// let fromLineNested x = x + 3 +[] +[] +[] +[] +let ``a #line name an older compiler wrote keeps the directory that the name of a compiled file already starts with`` + (name: string) + (recorded: string) + (keepsDirectory: bool) + = + let source = $"let _ = {name} 1" + let results = checkAgainst (Path.Combine(__SOURCE_DIRECTORY__, "PathMapFSharp9.dll")) source + let expected = if keepsDirectory then Path.Combine(@".\src\Domain", recorded) else recorded + Assert.Equal(expected, declarationOf results source name false) diff --git a/tests/FSharp.Compiler.ComponentTests/FSharpChecker/PathMapFSharp9.dll b/tests/FSharp.Compiler.ComponentTests/FSharpChecker/PathMapFSharp9.dll new file mode 100644 index 0000000000000000000000000000000000000000..01fb458cb5774244f93cbe57a36c22d1b9d2a80b GIT binary patch literal 4096 zcmeHKZ%|a%6+drT5Fr{^qDY#Kj{s`QxCLQcF$Na|fy%Ori%95LdAs{uUfq3fef!o* zj1~!v)}~FgozxhUm}EM&PLt7wIt*4n#E~G@#Ke%GlQc-9j-66#F&Il4`nzv;`6DLH zhknZBEa&e%_uPBVyYHQgt^O&BAtEDiWQ3?4oPkxRUrw4aJbiY@bZVP=CcT}jJd$jcf_l%)TS@rcSC0A+~lVS<$?6Y(ZN z1JPZRj93g$6U=Jz*I1a4X zy;&7~3LN#lHeis&nhqQXR-)o@sxCgp>Iz_cGf*rw@u49x#w zP=utjz*t1)XdCpwQLP2qa72rtW@xiH1IIj#t3(2ihV>6~qfO%M%_r~y2IHoz+kOt=R) z3j&jifGh@+72u~4`31-^(Z~)#YqSZ0<<3Sy4HTF?J|Bf;r{t9dEu@Oe6n{V!gF(?# zB4~nn;)E}EF21w3J)lW`=@CJb6#1(}|6>113oNlIo{�Bxh4l6a8d&{ZMpkB#T;5 z6J(E|dZRU$k*w8W_isul_?!&fkKVseF)8FijGKsL#(DnVtPW)2t2yi8HW zNG&R4O;pzjZjqI%R#bz?vPi>g;|gg}pRm8#ttl$OAFotUa@zxw?NC zL@FhDgSk2+s!c0H^0XBqtwoSB7Rs3)hi9I{Xr$0s9DUj)%&MS1C|r6+TmM&fAf{L!>`S+s|o$>v)AheEdTlGGn-c* zJ$Uuxw-(eLK0NLCJKaZndV5tZaOv%5SGzyiT-|eQ`yb@)(&HJO)dT0!j5GJ;p8CP= zA@1?MyKdxV-EWxp?!}bk(?tV2pL|c4S#&CM7eA${d*s43slfPLa^{L!e`5O8VT&M0{XH(CSSD(GF zyIT9%UPtQ1&ZX!Xs7*>=zlk#RGSM4gTYmA7Y{bSi1gUny=_>0-WnLDp}FP}?!;`pP5zyEB*^)3Iry6D9I>^U#w_B5wG zefm&E;hKYcHokcM>gz#e#*qh}?=MV!?)<^?t#eNNWR895!7V$No<95T$&SKHk61cx zu1QR6d9QADTYb^l)NbY0_A754NP6G0KK=W5-}m#L;+oD5^D0kyndzm4i%hN6Z>OK# zY`nGjz>T4!vBQIN-{>0PcgM|I(*Cc#+0E;BeLEGGBmnCpf9>z@H}x4}jIpH5)vY?& z#bka=A1_7Q?RXo}TD;LEKA%mHWby~yc)dma<2ca^+DI1h)=Ad?pMlf+>MWw>i7~^y zFy{_-=Ev?1bylJ-_VJHE7ncvImYlQ}w3JptsvtX6L9YN^4w=C*)Mz$>c>e2{#B4k!4z^_aCF)e{v}L%O@9PqD8o9ap+b-{6zA@>Z2w+ zty*X*Y!YV6@MB$b44Ka6Mc29Ad$NDN?(aZM1^3Gk`mXjr*KnXWbEpf;%ByE4V0Y0q zWfHJo5qon$(x{Pa-~o&~Aq$ulpaSgLgE{OrMN|UhuqqpiMj5LR?v(m%rv{?}at>k^ hiyN%~i*SgQ{~P!^SAY-y&v3}{bx!h|+`gy+{{_*5nlAtV literal 0 HcmV?d00001 diff --git a/tests/FSharp.Test.Utilities/Compiler.fs b/tests/FSharp.Test.Utilities/Compiler.fs index b48ec1dfee5..b6b29acf29b 100644 --- a/tests/FSharp.Test.Utilities/Compiler.fs +++ b/tests/FSharp.Test.Utilities/Compiler.fs @@ -2551,36 +2551,28 @@ $ code --diff {outFile} {expectedFile} /// Result type for CLI subprocess execution (runFsiProcess / runFscProcess). type ProcessResult = { ExitCode: int; StdOut: string; StdErr: string } - /// Quote an argument that contains whitespace so the child process's command line - /// parser sees it as a single token. Arguments routinely embed paths with spaces, - /// e.g. a temp directory under "C:\Users\First Last", or the .NET Framework - /// reference assemblies under "C:\Program Files (x86)". - let private quoteArg (arg: string) = - if arg |> Seq.exists Char.IsWhiteSpace && not (arg.StartsWith("\"", StringComparison.Ordinal)) then - "\"" + arg + "\"" - else - arg - /// Run an F# tool (FSI or FSC) as a subprocess. Shared helper for runFsiProcess / runFscProcess. - let private runToolProcess (toolPath: string) (args: string list) : ProcessResult = - let quotedArgs = args |> List.map quoteArg |> String.concat " " + let private runToolProcess (toolPath: string) (workingDirectory: string) (args: string list) : ProcessResult = #if NETCOREAPP let exe = TestFramework.initialConfig.DotNetExe - let arguments = quoteArg toolPath + " " + quotedArgs + let arguments = toolPath + " " + (args |> String.concat " ") #else let exe = toolPath - let arguments = quotedArgs + let arguments = args |> String.concat " " #endif - let exitCode, stdout, stderr = Commands.executeProcess exe arguments (Directory.GetCurrentDirectory()) + let exitCode, stdout, stderr = Commands.executeProcess exe arguments workingDirectory { ExitCode = exitCode; StdOut = stdout; StdErr = stderr } /// Run FSI as a subprocess with the given arguments. For CLI-level tests only (--help, exit codes, etc.). let runFsiProcess (args: string list) : ProcessResult = - runToolProcess TestFramework.initialConfig.FSI args + runToolProcess TestFramework.initialConfig.FSI (Directory.GetCurrentDirectory()) args + + let runFscProcessIn (workingDirectory: string) (args: string list) : ProcessResult = + runToolProcess TestFramework.initialConfig.FSC workingDirectory args /// Run FSC as a subprocess with the given arguments. For CLI-level tests only (missing files, exit codes, etc.). let runFscProcess (args: string list) : ProcessResult = - runToolProcess TestFramework.initialConfig.FSC args + runFscProcessIn (Directory.GetCurrentDirectory()) args /// Compile-and-run a compilation unit that depends on a FSharp.Core attribute /// which may not yet be shipped in the SDK's NuGet package. From e0fd56f4eaa10d9d5d36d000615fde9477569943 Mon Sep 17 00:00:00 2001 From: XperiAndri Date: Fri, 30 Oct 2026 21:31:37 +0100 Subject: [PATCH 3/3] Find the declaration's line without String.Contains(StringComparison), absent on net472 The Desktop legs could not compile FSharp.Compiler.ComponentTests: the .NET Framework BCL has no `String.Contains(string, StringComparison)`, so the arguments were read as a tuple (FS0001 in PathMap.fs). `IndexOf(name, StringComparison.Ordinal) >= 0` exists on every target. Co-Authored-By: Claude Sonnet 5.5 --- .../.FSharp.Compiler.Service/11.0.200.md | 2 -- .../FSharpChecker/PathMap.fs | 2 +- tests/FSharp.Test.Utilities/Compiler.fs | 15 +++++++++++++-- 3 files changed, 14 insertions(+), 5 deletions(-) diff --git a/docs/release-notes/.FSharp.Compiler.Service/11.0.200.md b/docs/release-notes/.FSharp.Compiler.Service/11.0.200.md index 09236a7afa6..7d7a4fa34d6 100644 --- a/docs/release-notes/.FSharp.Compiler.Service/11.0.200.md +++ b/docs/release-notes/.FSharp.Compiler.Service/11.0.200.md @@ -14,9 +14,7 @@ * Checker: report Bind resolution failures at the bound expression ([PR #20747](https://github.com/dotnet/fsharp/pull/20747)) * Fix invalid IL (`InvalidProgramException`) when a statically compiled `task { }` or other resumable state machine accesses a `ResumableStateMachine<_>` of a different instantiation than its own, such as a `ResumableStateMachine` field. ([Issue #20958](https://github.com/dotnet/fsharp/issues/20958), [PR #20959](https://github.com/dotnet/fsharp/pull/20959)) * A project reusing cached framework imports is checked with its own `--pathmap` instead of the map of the project that filled the cache, so the ranges of its in-memory reference data name its real files. ([Issue #20474](https://github.com/dotnet/fsharp/issues/20474), [PR #20476](https://github.com/dotnet/fsharp/pull/20476)) -* A project reusing cached framework imports is checked with its own `--pathmap` instead of the map of the project that filled the cache, so the ranges of its in-memory reference data name its real files. ([Issue #20474](https://github.com/dotnet/fsharp/issues/20474), [PR #20476](https://github.com/dotnet/fsharp/pull/20476)) * `GetDeclarationLocation` no longer names the compile-time directory twice for a declaration in an assembly built with a relative `--pathmap`. Such a build maps the directory it compiled in along with its file names, so a file from under that directory already starts with it, and joining the two left a path that matches no file. Other relative names, such as the `#line` names that compilers before F# 10 wrote, are still resolved against that directory. ([PR #20518](https://github.com/dotnet/fsharp/pull/20518)) -* A project reusing cached framework imports is checked with its own `--pathmap` instead of the map of the project that filled the cache, so the ranges of its in-memory reference data name its real files. ([Issue #20474](https://github.com/dotnet/fsharp/issues/20474), [PR #20476](https://github.com/dotnet/fsharp/pull/20476)) * Split Linux CoreCLR CI into two parallel test batches to reduce test turnaround time. ([PR #20587](https://github.com/dotnet/fsharp/pull/20587)) * Fix wrong results or non-terminating loops in optimized code when an integer `for` loop's start or end expression binds a local. ([Issue #20732](https://github.com/dotnet/fsharp/issues/20732), [PR #20733](https://github.com/dotnet/fsharp/pull/20733)) * Checker: resolve named arguments of failed and unfinished method calls ([PR #20749](https://github.com/dotnet/fsharp/pull/20749)) diff --git a/tests/FSharp.Compiler.ComponentTests/FSharpChecker/PathMap.fs b/tests/FSharp.Compiler.ComponentTests/FSharpChecker/PathMap.fs index 8d4606cf91a..93bcca107f1 100644 --- a/tests/FSharp.Compiler.ComponentTests/FSharpChecker/PathMap.fs +++ b/tests/FSharp.Compiler.ComponentTests/FSharpChecker/PathMap.fs @@ -135,7 +135,7 @@ let private checkAgainst (library: string) (source: string) = let private locate (source: string) (name: string) = let lines = source.Split '\n' - let index = lines |> Array.findIndex (fun line -> line.Contains(name, System.StringComparison.Ordinal)) + let index = lines |> Array.findIndex (fun line -> line.IndexOf(name, System.StringComparison.Ordinal) >= 0) let line = lines[index] struct (index + 1, line.IndexOf(name, System.StringComparison.Ordinal) + name.Length, line, List.ofArray (name.Split '.')) diff --git a/tests/FSharp.Test.Utilities/Compiler.fs b/tests/FSharp.Test.Utilities/Compiler.fs index b6b29acf29b..e596bb30455 100644 --- a/tests/FSharp.Test.Utilities/Compiler.fs +++ b/tests/FSharp.Test.Utilities/Compiler.fs @@ -2551,14 +2551,25 @@ $ code --diff {outFile} {expectedFile} /// Result type for CLI subprocess execution (runFsiProcess / runFscProcess). type ProcessResult = { ExitCode: int; StdOut: string; StdErr: string } + /// Quote an argument that contains whitespace so the child process's command line + /// parser sees it as a single token. Arguments routinely embed paths with spaces, + /// e.g. a temp directory under "C:\Users\First Last", or the .NET Framework + /// reference assemblies under "C:\Program Files (x86)". + let private quoteArg (arg: string) = + if arg |> Seq.exists Char.IsWhiteSpace && not (arg.StartsWith("\"", StringComparison.Ordinal)) then + "\"" + arg + "\"" + else + arg + /// Run an F# tool (FSI or FSC) as a subprocess. Shared helper for runFsiProcess / runFscProcess. let private runToolProcess (toolPath: string) (workingDirectory: string) (args: string list) : ProcessResult = + let quotedArgs = args |> List.map quoteArg |> String.concat " " #if NETCOREAPP let exe = TestFramework.initialConfig.DotNetExe - let arguments = toolPath + " " + (args |> String.concat " ") + let arguments = quoteArg toolPath + " " + quotedArgs #else let exe = toolPath - let arguments = args |> String.concat " " + let arguments = quotedArgs #endif let exitCode, stdout, stderr = Commands.executeProcess exe arguments workingDirectory { ExitCode = exitCode; StdOut = stdout; StdErr = stderr }