From bc5226f4b31ad7be9fa86b820d76326b5e8862d1 Mon Sep 17 00:00:00 2001 From: nojaf Date: Sat, 22 Aug 2026 17:39:51 +0200 Subject: [PATCH 01/10] Warn on .editorconfig settings Fantomas cannot use A setting carrying the `fsharp_` prefix that is not a Fantomas setting was silently ignored, so a misspelling like `fsharp_multiline_brackets_style` simply never applied. The warning now lists every setting the running version supports, which also catches prefixing one of the four settings editorconfig itself defines: `fsharp_max_line_length` never worked, `max_line_length` is the one that does. A value the spec defines but Fantomas cannot act on, `unset` and `indent_size = tab` among them, is not a mistake and stays silent. Keys are matched without regard to case, and every problem in one file is reported together, once per run. The daemon sends the same information to its client as a `fantomas/configurationWarning` notification after every format request, with an empty list when nothing is wrong so an editor can clear what it showed earlier. Additive to the JSON-RPC contract: a client that does not handle the method ignores it. `Fantomas.Client` surfaces it as the new `FantomasService.ConfigurationWarnings` event. The daemon never writes these to standard error. `Fantomas.Client` redirects that stream, and until now only read it when the process failed to start, so anything written there filled the pipe the two processes share and blocked the daemon inside a request. The client drains it now, and the reports travel over the wire instead. Also fixes two daemon leaks the notification work uncovered: a second folder pinning the same Fantomas started a second daemon and dropped the first from the cache without disposing it, and a daemon whose handshake failed was left running with nothing holding a reference to it. --- CHANGELOG.md | 2 + docs/docs/end-users/Configuration.fsx | 5 +- docs/docs/end-users/FantomasClient.md | 152 ++++++++++ docs/docs/end-users/Recipes.fsx | 5 +- src/Fantomas.Client.Tests/EndToEndTests.fs | 147 ++++++++++ src/Fantomas.Client/CHANGELOG.md | 9 + src/Fantomas.Client/Contracts.fs | 26 ++ src/Fantomas.Client/Contracts.fsi | 72 +++++ src/Fantomas.Client/FantomasToolLocator.fs | 92 +++++- src/Fantomas.Client/LSPFantomasService.fs | 76 +++-- .../LSPFantomasServiceTypes.fs | 3 +- .../LSPFantomasServiceTypes.fsi | 12 +- src/Fantomas.Core/Context.fs | 4 +- src/Fantomas.FCS/Parse.fs | 32 ++- .../EditorConfigurationTests.fs | 204 ++++++++++--- src/Fantomas.Tests/Integration/ConfigTests.fs | 100 +++++++ src/Fantomas.Tests/Integration/DaemonTests.fs | 270 +++++++++++++++++- src/Fantomas.Tests/TestHelpers.fs | 4 +- src/Fantomas/Daemon.fs | 100 ++++++- src/Fantomas/Daemon.fsi | 12 +- src/Fantomas/EditorConfig.fs | 185 ++++++++++-- src/Fantomas/EditorConfig.fsi | 50 +++- src/Fantomas/Program.fs | 4 +- 23 files changed, 1412 insertions(+), 154 deletions(-) create mode 100644 docs/docs/end-users/FantomasClient.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 5425bfd8ce..5857186765 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,8 @@ - Breaking: a single file that `.fantomasignore` matches is reported the same way as an ignored file found while walking a folder. `fantomas A.fs` on an ignored file printed nothing unless `--verbosity d` was given, where `fantomas ./folder` containing only that file printed `A.fs was ignored.` Both now print it. A `--check` run reports the files it ignored at detailed verbosity whether they were named directly or found in a folder, where before only a directly named file was reported. [#3406](https://github.com/fsprojects/fantomas/pull/3406) - At detailed verbosity, a run writing to `--out` now notes a file it found already formatted, as a run formatting in place always did. Both paths decide what formatting came to in the same place, so they say the same things about it. [#3406](https://github.com/fsprojects/fantomas/pull/3406) - Breaking: `Fantomas.Core` is no longer binary compatible with `v7`. Several discriminated unions are structs now, which changes nothing about how they are written or matched, but an assembly compiled against `v7` has to be rebuilt. [#3407](https://github.com/fsprojects/fantomas/pull/3407) +- A setting in `.editorconfig` that carries the `fsharp_` prefix but is not a Fantomas setting now warns instead of being silently ignored, and the warning lists every `.editorconfig` setting the running version supports. This catches a misspelling such as `fsharp_multiline_brackets_style`, and catches prefixing one of the four settings editorconfig itself defines, where `fsharp_max_line_length` never applied and `max_line_length` is the one that works. Settings without the `fsharp_` prefix belong to other tools and are left alone. Every problem in one `.editorconfig` is now reported together and only once per run, rather than once per formatted file. [#3401](https://github.com/fsprojects/fantomas/pull/3401) +- The daemon sends a `fantomas/configurationWarning` notification after every format request, naming the settings in the resolved configuration it could not act on, and sending an empty list when there are none so an editor can clear what it showed earlier. Additive to the JSON-RPC contract: a client that does not handle the method ignores it and keeps working. See the [Fantomas.Client changelog](https://github.com/fsprojects/fantomas/blob/main/src/Fantomas.Client/CHANGELOG.md) for the client-side API. [#3401](https://github.com/fsprojects/fantomas/pull/3401) ### Fixed diff --git a/docs/docs/end-users/Configuration.fsx b/docs/docs/end-users/Configuration.fsx index 98e358cbfd..6f785f3268 100644 --- a/docs/docs/end-users/Configuration.fsx +++ b/docs/docs/end-users/Configuration.fsx @@ -23,6 +23,9 @@ UI might be available depending on the IDE. #r "../../../artifacts/bin/Fantomas.FCS/release/Fantomas.FCS.dll" #r "../../../artifacts/bin/Fantomas.Core/release/Fantomas.Core.dll" #r "../../../artifacts/bin/Fantomas/release/EditorConfig.Core.dll" +#r "../../../artifacts/bin/Fantomas/release/Serilog.dll" +#r "../../../artifacts/bin/Fantomas/release/Serilog.Sinks.Console.dll" +#load "../../../src/Fantomas/Logging.fs" #load "../../../src/Fantomas/EditorConfig.fs" open System @@ -43,7 +46,7 @@ let formatCode input (settings: string) = Some(parts.[0], parts.[1])) |> readOnlyDict - parseOptionsFromEditorConfig FormatConfig.Default editorConfigProperties + parseOptionsFromEditorConfig FormatConfig.Default editorConfigProperties |> fst let! result = CodeFormatter.FormatDocumentAsync(false, input, config) printf $"%s{result.Code}" diff --git a/docs/docs/end-users/FantomasClient.md b/docs/docs/end-users/FantomasClient.md new file mode 100644 index 0000000000..17c2a10e90 --- /dev/null +++ b/docs/docs/end-users/FantomasClient.md @@ -0,0 +1,152 @@ +--- +category: End-users +categoryindex: 1 +index: 14 +--- +# Formatting from an editor with Fantomas.Client + +The [Fantomas.Client](https://www.nuget.org/packages/Fantomas.Client) NuGet package is for tools that +format someone else's code: editor extensions, language servers, custom build tooling. + +It exists because of a versioning problem. If your editor extension referenced +[Fantomas.Core](https://www.nuget.org/packages/Fantomas.Core) directly, everyone using that extension +would be formatting with whatever version you happened to compile against. A repository that pins +Fantomas 6 in its `dotnet-tools.json` would silently be formatted by Fantomas 8, and the diff would +be enormous. + +`Fantomas.Client` avoids this. For each file you ask it to format, it looks for the Fantomas the +*user* installed, starts that version as a background daemon, and talks to it over JSON-RPC. Your +tool stays on one version of `Fantomas.Client`, while the formatting is done by the version the +repository asked for. + +> The code on this page is illustrative rather than runnable. It is meant to show the shape of the +> API, not to be pasted into a script. + +## Formatting a document + +```fsharp +open Fantomas.Client.Contracts +open Fantomas.Client.LSPFantomasService + +// One service for the lifetime of your tool. It caches a daemon per Fantomas version, mapping each +// folder to the version it resolved, so two folders pinning the same version share one process. +// Creating a service per request would start a new one every time. +let service: FantomasService = new LSPFantomasService() + +let request = + { SourceCode = "let a = 1" + // Must be absolute, and must exist on disk. Its folder is what decides which Fantomas + // version gets used, so a path inside the user's repository is what you want here. + FilePath = "/home/me/MyProject/Library.fs" + // None means "use the .editorconfig that applies to FilePath". + Config = None + Cursor = None } + +let response = service.FormatDocumentAsync(request).Result + +if response.Code = int FantomasResponseCode.Formatted then + // Content holds the formatted code. + printfn "%s" (Option.defaultValue "" response.Content) +elif response.Code = int FantomasResponseCode.UnChanged then + // The file was already formatted. Content is None, so do not overwrite anything. + () +else + // Error, Ignored, ToolNotFound, FileNotFound, FilePathIsNotAbsolute, DaemonCreationFailed, ... + // Content carries a message explaining what went wrong. + eprintfn "%s" (Option.defaultValue "" response.Content) +``` + +Every call answers with the same `FantomasResponse`, and `Code` is what you branch on. It is an +`int` rather than a union so the type survives the wire; compare it against `FantomasResponseCode`. +Nothing throws for an unusable path or a missing tool, so there is exactly one place to handle +failure. + +## Reacting to a bad `.editorconfig` + +A `.editorconfig` can name a setting Fantomas does not have, usually a typo such as +`fsharp_multiline_brackets_style`, or give a setting a value it cannot parse. Formatting still +succeeds, using defaults for whatever could not be read, so without being told the user sees the +setting quietly not apply. + +Subscribe to `ConfigurationWarnings` to surface it: + +```fsharp +service.ConfigurationWarnings.Add(fun warning -> + if Array.isEmpty warning.Problems then + // Nothing is wrong any more, so clear whatever you showed for this file earlier. + clearWarnings warning.FilePath + else + warning.Problems + |> Array.map (fun problem -> + if problem.Code = int ConfigurationProblemCode.UnknownSetting then + $"%s{problem.Setting} is not a Fantomas setting" + else + $"%s{problem.Setting} does not accept the value %s{problem.Value}") + |> showWarnings warning.FilePath warning.EditorConfigFiles) +``` + +Worth knowing: + +- The event is raised after **every** format request, with an empty `Problems` array when the + configuration is fine. That is what lets you clear a warning once the user fixes it. +- `EditorConfigFiles` holds the absolute paths of the `.editorconfig` files that contributed. Which + one a given problem came from is not knowable, because editorconfig merges the whole chain into a + single set of properties before Fantomas sees it. There is no line number either, so name the + setting rather than trying to point at it. +- `Source` tells you whether the setting came from a `.editorconfig` on disk or from the `Config` + dictionary your own tool sent along with the request. +- Only Fantomas 8.0.0-alpha-014 and later send these. Against an older daemon the event simply + never fires, so no version check is needed. + +## Formatting a selection + +```fsharp +let selectionRequest = + { SourceCode = sourceCode + FilePath = "/home/me/MyProject/Library.fs" + Config = None + // Same semantics as the F# compiler's range: one-based lines, zero-based columns. + Range = FormatSelectionRange(1, 0, 3, 12) } + +let selectionResponse = service.FormatSelectionAsync(selectionRequest).Result +``` + +The range that actually got formatted comes back in `SelectedRange`, which can differ from what you +asked for when the selection had leading or trailing whitespace. Use the returned range when you +splice the result back into the document, not the one you sent. + +## Keeping the cursor in place + +Pass `Cursor` on a format request and the response tells you where that position ended up after +formatting, so the caret does not jump when you format on save. + +```fsharp +let request = + { SourceCode = sourceCode + FilePath = "/home/me/MyProject/Library.fs" + Config = None + Cursor = Some(FormatCursorPosition(4, 2)) } +``` + +## Discovering settings + +`ConfigurationAsync` returns the settings schema of the Fantomas version resolved for a file: every +setting name, its type, default, and description. Because it comes from the daemon rather than from +whatever you compiled against, it is the authoritative list for that repository, and it is what you +want backing a settings UI or a `.editorconfig` completion list. + +```fsharp +let schema = service.ConfigurationAsync("/home/me/MyProject/Library.fs").Result +// schema.Content holds JSON describing every setting. +``` + +## Lifetime + +```fsharp +// Stop every daemon this service started. Call it when your tool shuts down. +(service :> System.IDisposable).Dispose() +``` + +`ClearCache` throws away the daemons without disposing the service, which is what you want after the +user changes the Fantomas version in their `dotnet-tools.json`. Otherwise the old process keeps +serving requests for the rest of the session. diff --git a/docs/docs/end-users/Recipes.fsx b/docs/docs/end-users/Recipes.fsx index a36e71211e..af757d5ebe 100644 --- a/docs/docs/end-users/Recipes.fsx +++ b/docs/docs/end-users/Recipes.fsx @@ -22,6 +22,9 @@ Sometimes, it makes sense to tweak a few setting for a subset of your codebase. #r "../../../artifacts/bin/Fantomas.FCS/release/Fantomas.FCS.dll" #r "../../../artifacts/bin/Fantomas.Core/release/Fantomas.Core.dll" #r "../../../artifacts/bin/Fantomas/release/EditorConfig.Core.dll" +#r "../../../artifacts/bin/Fantomas/release/Serilog.dll" +#r "../../../artifacts/bin/Fantomas/release/Serilog.Sinks.Console.dll" +#load "../../../src/Fantomas/Logging.fs" #load "../../../src/Fantomas/EditorConfig.fs" open System @@ -42,7 +45,7 @@ let formatCode input (settings: string) = Some(parts.[0], parts.[1])) |> readOnlyDict - parseOptionsFromEditorConfig FormatConfig.Default editorConfigProperties + parseOptionsFromEditorConfig FormatConfig.Default editorConfigProperties |> fst let! result = CodeFormatter.FormatDocumentAsync(false, input, config) printf $"%s{result.Code}" diff --git a/src/Fantomas.Client.Tests/EndToEndTests.fs b/src/Fantomas.Client.Tests/EndToEndTests.fs index f38ea30327..5dd2e76cfd 100644 --- a/src/Fantomas.Client.Tests/EndToEndTests.fs +++ b/src/Fantomas.Client.Tests/EndToEndTests.fs @@ -1,6 +1,7 @@ module Fantomas.Client.Tests open System +open System.Diagnostics open System.IO open System.Text open System.Threading.Tasks @@ -186,6 +187,93 @@ end_of_line = lf Assert.Fail report } + /// The command line of a running process, when the platform lets us read it. + /// `System.Diagnostics` cannot do this, and without it a fantomas daemon is indistinguishable + /// from the many other `dotnet` processes a test run starts. + let commandLineOf (pid: int) : string option = + try + if OperatingSystem.IsLinux() then + let path = $"/proc/%i{pid}/cmdline" + + if File.Exists path then + // The arguments are separated by NUL bytes. + Some(File.ReadAllText(path).Replace('\000', ' ')) + else + None + elif OperatingSystem.IsMacOS() then + let psi = ProcessStartInfo("/bin/ps", $"-p %i{pid} -o command=") + psi.RedirectStandardOutput <- true + psi.RedirectStandardError <- true + use p = Process.Start psi + let out = p.StandardOutput.ReadToEnd() + p.WaitForExit() + if p.ExitCode = 0 then Some out else None + else + None + with _ -> + None + + let canReadCommandLines: bool = + OperatingSystem.IsLinux() || OperatingSystem.IsMacOS() + + /// The processes currently serving as a fantomas daemon. + /// + /// Matching on the command line rather than the process name is what makes this usable: a + /// local tool daemon runs as `dotnet fantomas --daemon`, and so shows up under `dotnet`, the + /// same name as every other `dotnet` process. The test projects run in parallel, and the + /// command line integration tests spawn a `dotnet fantomas ` for nearly every test they + /// have, so counting by name alone counts those too. + let runningDaemons () : Set = + Process.GetProcesses() + |> Array.choose (fun (p: Process) -> + // Every process handed out here holds an operating system handle until it is disposed. + use p = p + + let name = + try + p.ProcessName + with _ -> + "" + + if name <> "dotnet" && name <> "fantomas" then + None + else + match commandLineOf p.Id with + | Some commandLine when commandLine.Contains "fantomas" && commandLine.Contains "--daemon" -> Some p.Id + | _ -> None) + |> Set.ofArray + + /// Everything we can still learn about a process that outlived the service, so that a failure + /// says what it was rather than only which number it had. + let describeProcess (pid: int) : string = + let commandLine = + match commandLineOf pid with + | Some c -> c.Trim() + | None -> "" + + try + use p = Process.GetProcessById pid + $" pid %i{pid}: name=%s{p.ProcessName}, exited=%b{p.HasExited}, cmd=%s{commandLine}" + with e -> + $" pid %i{pid}: gone when inspected (%s{e.GetType().Name}), cmd=%s{commandLine}" + + /// Wait until nothing started during the test is left running, then report what is. + /// Helper processes such as `dotnet tool list` exit on their own, so polling tells them apart + /// from a daemon that leaked, which stays. + let settleDaemons (before: Set) : Task> = + let rec loop (attemptsLeft: int) : Task> = + backgroundTask { + let survivors = Set.difference (runningDaemons ()) before + + if Set.isEmpty survivors || attemptsLeft = 0 then + return survivors + else + do! Task.Delay 200 + return! loop (attemptsLeft - 1) + } + + loop 25 + let withVersion version (callback: string -> Task) = backgroundTask { let file = Path.Combine(folder.FullName, version, "File.fs") @@ -252,3 +340,62 @@ end_of_line = lf let! response = service.FormatDocumentAsync(request) do! expectResponse FantomasResponseCode.Formatted fsharpFile response }) + + /// Daemons are cached per version, not per folder, so a second folder pinning the same version + /// has to reuse the running daemon. Starting another one would drop the first from the cache + /// without disposing it, leaving a process behind for the rest of the session. + /// + /// A nested directory is a second folder as far as the service is concerned, while the tool + /// manifest it resolves upward to is the same one, so no second install is needed here. + /// + /// The check is what survives disposal rather than a count taken while the work is in flight: + /// resolving a folder shells out to `dotnet tool list`, and that process can still be in the + /// table when a sample is taken. A daemon that leaked is not in the cache the service empties, + /// so it is still running afterwards, while every helper process is gone by then. + [] + [] + member _.``a second folder on the same version reuses the daemon``(version: string) = + withVersion version (fun fsharpFile -> + backgroundTask { + let versionFolder: string = Path.GetDirectoryName fsharpFile + + let nested = Directory.CreateDirectory(Path.Combine(versionFolder, "nested-folder")) + + let nestedFile = Path.Combine(nested.FullName, "File.fs") + File.WriteAllText(nestedFile, unformattedCode) + + let request (file: string) : FormatDocumentRequest = + { SourceCode = unformattedCode + FilePath = file + Config = None + Cursor = None } + + if not canReadCommandLines then + Assert.Ignore + "This test tells a fantomas daemon from any other dotnet process by its command line, which it can only read on Linux and macOS." + + let before = runningDaemons () + + // A service of its own, so that it can be disposed here. The fixture shares one for + // every other test and only disposes it once they have all run. + let ownService: FantomasService = new LSPFantomasService() + + let! first = ownService.FormatDocumentAsync(request fsharpFile) + do! expectResponse FantomasResponseCode.Formatted fsharpFile first + + let! second = ownService.FormatDocumentAsync(request nestedFile) + do! expectResponse FantomasResponseCode.Formatted nestedFile second + + ownService.Dispose() + + let! survivors = settleDaemons before + + let described = + survivors |> Seq.map describeProcess |> String.concat Environment.NewLine + + Assert.That( + survivors, + Is.Empty, + $"After formatting in two folders that both pin fantomas %s{version}, %i{survivors.Count} process(es) outlived the service.%s{Environment.NewLine}%s{described}" + ) + }) diff --git a/src/Fantomas.Client/CHANGELOG.md b/src/Fantomas.Client/CHANGELOG.md index a18fa131e2..795d70c3e8 100644 --- a/src/Fantomas.Client/CHANGELOG.md +++ b/src/Fantomas.Client/CHANGELOG.md @@ -4,9 +4,18 @@ This is the changelog for the Fantomas.Client package specifically. It's distinc ## [Unreleased] +### Added +- `FantomasService.ConfigurationWarnings`, an event raised after every format request with the settings in the resolved configuration that Fantomas could not act on: a `fsharp_`-prefixed setting the daemon's version does not have, or a setting carrying a value it cannot parse. Formatting still succeeds using defaults, so without this the setting quietly does not apply. The event is raised with an empty `Problems` array when nothing is wrong, so a subscriber can clear what it reported earlier. Only Fantomas 8.0.0-alpha-014 and later daemons send these; against an older daemon the event never fires, so no version check is needed. See [Formatting from an editor with Fantomas.Client](https://fsprojects.github.io/fantomas/docs/end-users/FantomasClient.html). [#3401](https://github.com/fsprojects/fantomas/pull/3401) +- `ConfigurationWarning`, `ConfigurationProblem`, `ConfigurationProblemCode` and `ConfigurationProblemSource`, the types carried by that event, and `Methods.ConfigurationWarning`, the JSON-RPC method they arrive on. [#3401](https://github.com/fsprojects/fantomas/pull/3401) +- `RunningFantomasTool.ConfigurationWarnings`, for callers driving `FantomasToolLocator.createFor` themselves rather than going through `LSPFantomasService`. The handler has to be registered before the connection starts listening, so `createFor` wires it up; its own signature is unchanged. [#3401](https://github.com/fsprojects/fantomas/pull/3401) + ### Changed - Bump `StreamJsonRpc` to `2.25.29`. [#3393](https://github.com/fsprojects/fantomas/pull/3393) - Breaking: no longer binary compatible with `0.11.0`. Several discriminated unions are structs now, which changes nothing about how they are written or matched, but an assembly compiled against `0.11.0` has to be rebuilt. [#3407](https://github.com/fsprojects/fantomas/pull/3407) +- Breaking: `FantomasService` gained the `ConfigurationWarnings` member, and `RunningFantomasTool` gained a field. Source-breaking only for code that *implements* `FantomasService` or *constructs* `RunningFantomasTool`; calling either is unaffected, at source and at binary level. [#3401](https://github.com/fsprojects/fantomas/pull/3401) + +### Fixed +- Opening a second folder that pins the same Fantomas version started a second daemon and dropped the first one from the cache without disposing it, leaving an orphaned process behind for the rest of the session. Daemons are keyed by version, so a running one for that version is now reused. [#3401](https://github.com/fsprojects/fantomas/pull/3401) ## [0.11.0] - 2026-04-16 diff --git a/src/Fantomas.Client/Contracts.fs b/src/Fantomas.Client/Contracts.fs index 5a0941ce89..2cc356ea8e 100644 --- a/src/Fantomas.Client/Contracts.fs +++ b/src/Fantomas.Client/Contracts.fs @@ -10,6 +10,9 @@ module Methods = [] let Version = "fantomas/version" + [] + let ConfigurationWarning = "fantomas/configurationWarning" + [] let FormatDocument = "fantomas/formatDocument" @@ -73,6 +76,27 @@ type FantomasResponse = SelectedRange: FormatSelectionRange option Cursor: FormatCursorPosition option } +type ConfigurationProblemCode = + | UnknownSetting = 1 + | UnrecognizedValue = 2 + +type ConfigurationProblemSource = + | EditorConfig = 1 + | Request = 2 + +[] +type ConfigurationProblem = + { Code: int + Source: int + Setting: string + Value: string } + +[] +type ConfigurationWarning = + { FilePath: string + EditorConfigFiles: string array + Problems: ConfigurationProblem array } + type FantomasService = interface inherit IDisposable @@ -89,4 +113,6 @@ type FantomasService = filePath: string * ?cancellationToken: CancellationToken -> Task abstract member ClearCache: unit -> unit + + abstract member ConfigurationWarnings: IEvent end diff --git a/src/Fantomas.Client/Contracts.fsi b/src/Fantomas.Client/Contracts.fsi index 2dbc23051a..5c83c9cf18 100644 --- a/src/Fantomas.Client/Contracts.fsi +++ b/src/Fantomas.Client/Contracts.fsi @@ -19,6 +19,12 @@ module Methods = [] val Configuration: string = "fantomas/configuration" + /// Sent by the daemon to the client after every format request, naming the settings in the + /// resolved configuration that Fantomas could not act on. Purely informational: the request + /// still succeeds, using defaults for whatever could not be read. + [] + val ConfigurationWarning: string = "fantomas/configurationWarning" + [] type FormatDocumentRequest = { @@ -88,11 +94,77 @@ type FantomasResponse = Cursor: FormatCursorPosition option } +/// Why a setting in the resolved configuration could not be acted on. +/// Carried as an int rather than a union so it survives the wire. +type ConfigurationProblemCode = + /// A setting carrying the `fsharp_` prefix that this version of Fantomas does not have. + | UnknownSetting = 1 + /// A setting Fantomas has, carrying a value it cannot parse. The default was used instead. + /// Only ever reported for a `fsharp_` setting: the four editorconfig defines itself are + /// shared with other tools, and the spec gives them values Fantomas has no use for. + | UnrecognizedValue = 2 + +/// Where a problematic setting was read from. +type ConfigurationProblemSource = + /// One of the `.editorconfig` files listed in `ConfigurationWarning.EditorConfigFiles`. + | EditorConfig = 1 + /// The `Config` dictionary the client sent with the request. + | Request = 2 + +[] +type ConfigurationProblem = + { + /// One of `ConfigurationProblemCode`. + Code: int + + /// One of `ConfigurationProblemSource`. + Source: int + + /// The editorconfig name of the setting, such as `fsharp_multiline_bracket_style`. + /// A setting name, never a path. + Setting: string + + /// The value that could not be parsed, exactly as it was written in the configuration. + /// Null when `Code` is `UnknownSetting`, because then no value was ever read. + /// + /// A plain string rather than an option: an F# option travels as + /// `{"Case":"Some","Fields":[...]}` and disappears entirely when it is `None`, which is + /// not something a client written in another language should have to know about. + /// Use `Option.ofObj` from F#. + Value: string + } + +[] +type ConfigurationWarning = + { + /// The file that was being formatted, echoed back from the request unchanged. + /// Absolute, because `Fantomas.Client` rejects a relative path before sending the request. + FilePath: string + + /// Absolute paths of the `.editorconfig` files that contributed to the configuration. + /// Empty when no `.editorconfig` applies to `FilePath`. + /// + /// Which of these a given problem came from is not knowable, and deliberately not + /// guessed at: editorconfig merges the whole chain into one set of properties before + /// Fantomas sees it. + EditorConfigFiles: string array + + /// Empty when nothing is wrong, which clears anything reported for this file earlier. + Problems: ConfigurationProblem array + } + type FantomasService = inherit System.IDisposable abstract ClearCache: unit -> unit + /// Raised after every format request, with the settings in the resolved configuration that + /// Fantomas could not act on. Raised with an empty `Problems` list when there is nothing + /// wrong, so a subscriber can clear what it reported earlier. + /// + /// Only daemons from Fantomas 8.0.0-alpha-014 onwards send these; an older one never raises it. + abstract ConfigurationWarnings: IEvent + abstract ConfigurationAsync: filePath: string * ?cancellationToken: CancellationToken -> Task abstract FormatDocumentAsync: diff --git a/src/Fantomas.Client/FantomasToolLocator.fs b/src/Fantomas.Client/FantomasToolLocator.fs index 5b4dfc1cd5..1f2372f2f2 100644 --- a/src/Fantomas.Client/FantomasToolLocator.fs +++ b/src/Fantomas.Client/FantomasToolLocator.fs @@ -1,19 +1,21 @@ module Fantomas.Client.FantomasToolLocator open System +open System.Collections.Generic open System.ComponentModel open System.Diagnostics open System.IO open System.Text.RegularExpressions open System.Runtime.InteropServices open StreamJsonRpc +open Fantomas.Client.Contracts open Fantomas.Client.LSPFantomasServiceTypes // Only 4.6.0-alpha-004 has daemon capabilities -let private supportedRange = SemanticVersioning.Range(">=v4.6.0-alpha-004") +let supportedRange = SemanticVersioning.Range(">=v4.6.0-alpha-004") [] -let private (|CompatibleVersion|_|) (version: string) = +let (|CompatibleVersion|_|) (version: string) : string voption = match SemanticVersioning.Version.TryParse version with | true, parsedVersion -> if supportedRange.IsSatisfied(parsedVersion, includePrerelease = true) then @@ -24,13 +26,13 @@ let private (|CompatibleVersion|_|) (version: string) = // In the past, fantomas was named fantomas-tool. [] -let private (|CompatibleToolName|_|) toolName = +let (|CompatibleToolName|_|) (toolName: string) : string voption = if toolName = "fantomas-tool" || toolName = "fantomas" then ValueSome toolName else ValueNone -let private readOutputStreamAsLines (outputStream: StreamReader) : string list = +let readOutputStreamAsLines (outputStream: StreamReader) : string list = let rec readLines (outputStream: StreamReader) (continuation: string list -> string list) = let nextLine = outputStream.ReadLine() @@ -41,7 +43,7 @@ let private readOutputStreamAsLines (outputStream: StreamReader) : string list = readLines outputStream id -let private startProcess (ps: ProcessStartInfo) : Result = +let startProcess (ps: ProcessStartInfo) : Result = try Ok(Process.Start ps) with @@ -59,7 +61,7 @@ let private startProcess (ps: ProcessStartInfo) : Result Error(ProcessStartError.UnExpectedException(ps.FileName, ps.Arguments, ex.Message)) -let private runToolListCmd (Folder workingDir: Folder) (globalFlag: bool) : Result = +let runToolListCmd (Folder workingDir: Folder) (globalFlag: bool) : Result = let ps = ProcessStartInfo("dotnet") ps.WorkingDirectory <- workingDir @@ -87,10 +89,10 @@ let private runToolListCmd (Folder workingDir: Folder) (globalFlag: bool) : Resu Error(DotNetToolListError.ExitCodeNonZero(ps.FileName, ps.Arguments, exitCode, error)) | Error err -> Error(DotNetToolListError.ProcessStartError err) -let private packageSidVersionRegex = Regex(@"^Package\sId\s+Version.+$") +let packageSidVersionRegex = Regex(@"^Package\sId\s+Version.+$") [] -let private (|CompatibleTool|_|) lines = +let (|CompatibleTool|_|) (lines: string list) : FantomasVersion voption = // These are local bindings, which cannot carry an attribute, so they stay on option. let (|HeaderLine|_|) line = if packageSidVersionRegex.IsMatch line then Some() else None @@ -124,10 +126,10 @@ let private (|CompatibleTool|_|) lines = tool |> ValueOption.ofOption |> ValueOption.map (snd >> FantomasVersion) | _ -> ValueNone -let private isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) +let isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) // Find an executable fantomas file on the PATH -let private fantomasVersionOnPath () : (FantomasExecutableFile * FantomasVersion) option = +let fantomasVersionOnPath () : (FantomasExecutableFile * FantomasVersion) option = let fantomasExecutableOnPathOpt = match Option.ofObj (Environment.GetEnvironmentVariable("PATH")) with | Some s -> s.Split([| if isWindows then ';' else ':' |], StringSplitOptions.RemoveEmptyEntries) @@ -168,7 +170,18 @@ let private fantomasVersionOnPath () : (FantomasExecutableFile * FantomasVersion stdOut |> Option.ofObj |> Option.map (fun s -> - let version = s.ToLowerInvariant().Replace("fantomas", String.Empty).Trim() + // `--version` answers `Fantomas v8.0.0`, `dotnet tool list` answers `8.0.0`. + // Daemons are cached by this string, so the leading v has to go: without it the + // same Fantomas resolved once from the manifest and once from the PATH counts as + // two versions and gets two processes. + let version = + let printed = s.ToLowerInvariant().Replace("fantomas", String.Empty).Trim() + + if printed.StartsWith("v", StringComparison.Ordinal) then + printed.Substring(1) + else + printed + FantomasExecutableFile(fantomasExecutablePath), FantomasVersion(version)) | Error(ProcessStartError.ExecutableFileNotFound _) | Error(ProcessStartError.UnExpectedException _) -> None) @@ -232,9 +245,43 @@ let createFor (startInfo: FantomasToolStartInfo) : Result + // Standard error is redirected, so something has to read it. Left alone it fills the pipe + // the operating system gives the two processes, 4KB by default on Windows, and the daemon + // then blocks inside whatever it was doing when it wrote the line that did not fit. Keep + // the last of it for the failure message below and throw the rest away. + let recentStandardError = Queue() + + daemonProcess.ErrorDataReceived.Add(fun message -> + if not (isNull message.Data) then + lock recentStandardError (fun () -> + recentStandardError.Enqueue message.Data + + while recentStandardError.Count > 50 do + recentStandardError.Dequeue() |> ignore)) + + daemonProcess.BeginErrorReadLine() + let client = new JsonRpc(daemonProcess.StandardInput.BaseStream, daemonProcess.StandardOutput.BaseStream) + let configurationWarnings = Event() + + // Has to happen before StartListening: StreamJsonRpc refuses to add local methods once + // the connection is listening. A daemon that never sends these simply never triggers it. + client.AddLocalRpcMethod( + Methods.ConfigurationWarning, + Action(fun warning -> + try + configurationWarnings.Trigger warning + with _ -> + // A subscriber that throws must not take the connection down with it. An + // exception out of a synchronous local method is not turned into an error + // response: it escapes the dispatcher and disconnects the client, which would + // fault every format request from then on over a message that only carries + // advice. + ()) + ) + do client.StartListening() try @@ -247,14 +294,33 @@ let createFor (startInfo: FantomasToolStartInfo) : Result let error = if daemonProcess.HasExited then - let stdErr = daemonProcess.StandardError.ReadToEnd() + let stdErr = + lock recentStandardError (fun () -> String.Join(Environment.NewLine, recentStandardError)) + $"Daemon std error: %s{stdErr}.\nJsonRpc exception:%s{ex.Message}" else ex.Message + // The handshake failed, so nothing will ever hand this daemon out and nothing will + // ever dispose it. Kill it here rather than leave the process running for the rest of + // the session with no way to reach it. + try + client.Dispose() + with _ -> + () + + try + if not daemonProcess.HasExited then + daemonProcess.Kill() + + daemonProcess.Dispose() + with _ -> + () + Error(ProcessStartError.UnExpectedException(processStart.FileName, processStart.Arguments, error)) | Error err -> Error err diff --git a/src/Fantomas.Client/LSPFantomasService.fs b/src/Fantomas.Client/LSPFantomasService.fs index d585e2a3af..3a88561dd7 100644 --- a/src/Fantomas.Client/LSPFantomasService.fs +++ b/src/Fantomas.Client/LSPFantomasService.fs @@ -31,7 +31,7 @@ type Msg = | GetDaemon of folder: Folder * replyChannel: AsyncReplyChannel> | Reset of AsyncReplyChannel -let private createAgent (ct: CancellationToken) = +let createAgent (ct: CancellationToken) (onConfigurationWarning: ConfigurationWarning -> unit) : MailboxProcessor = MailboxProcessor.Start( (fun inbox -> let rec messageLoop (state: ServiceState) = @@ -61,13 +61,18 @@ let private createAgent (ct: CancellationToken) = match newDaemonResult with | Ok newDaemon -> + newDaemon.ConfigurationWarnings.Add onConfigurationWarning replyChannel.Reply(Ok newDaemon.RpcClient) { FolderToVersion = Map.add folder version state.FolderToVersion Daemons = Map.add version newDaemon state.Daemons } | Error pse -> replyChannel.Reply(Error(GetDaemonError.FantomasProcessStart pse)) - state + // The daemon that was there is disposed and the new one + // never started, so drop the entry rather than leave a + // dead one to be disposed again on the next request. + { state with + Daemons = Map.remove version state.Daemons } else // return running client replyChannel.Reply(Ok daemon.RpcClient) @@ -89,17 +94,47 @@ let private createAgent (ct: CancellationToken) = match fantomasToolResult with | Ok(FantomasToolFound(version, startInfo)) -> - let createDaemonResult = createFor startInfo - - match createDaemonResult with - | Ok daemon -> + // Daemons are keyed by version, not by folder. Two folders that + // pin the same Fantomas share one, so a running daemon for this + // version has to be reused: starting a second would overwrite + // the first in the map and leave its process running with + // nothing left to dispose it. + // + // The reused daemon keeps the StartInfo it was created with, so + // a restart after a crash resolves the tool the way the first + // folder did rather than the way this one just did. + let runningDaemon = + Map.tryFind version state.Daemons + |> Option.filter (fun daemon -> not daemon.Process.HasExited) + + match runningDaemon with + | Some daemon -> replyChannel.Reply(Ok daemon.RpcClient) - { Daemons = Map.add version daemon state.Daemons - FolderToVersion = Map.add folder version state.FolderToVersion } - | Error pse -> - replyChannel.Reply(Error(GetDaemonError.FantomasProcessStart pse)) - state + { state with + FolderToVersion = Map.add folder version state.FolderToVersion } + | None -> + // A daemon that crashed is replaced, but dispose it first so + // the handles it still holds are released. + Map.tryFind version state.Daemons + |> Option.iter (fun daemon -> (daemon :> IDisposable).Dispose()) + + let createDaemonResult = createFor startInfo + + match createDaemonResult with + | Ok daemon -> + daemon.ConfigurationWarnings.Add onConfigurationWarning + replyChannel.Reply(Ok daemon.RpcClient) + + { Daemons = Map.add version daemon state.Daemons + FolderToVersion = Map.add folder version state.FolderToVersion } + | Error pse -> + replyChannel.Reply(Error(GetDaemonError.FantomasProcessStart pse)) + // The daemon that was there is disposed and the new one + // never started, so drop the entry rather than leave a + // dead one to be disposed again on the next request. + { state with + Daemons = Map.remove version state.Daemons } | Error FantomasToolError.NoCompatibleVersionFound -> replyChannel.Reply(Error GetDaemonError.InCompatibleVersionFound) state @@ -143,13 +178,13 @@ let isPathAbsolute (path: string) : bool = else pathRoot.Trim('\\').IndexOf('\\') <> -1 // A UNC server name without a share name (e.g "\\NAME" or "\\NAME\") is invalid -let private isCancellationRequested (requested: bool) : Result = +let isCancellationRequested (requested: bool) : Result = if requested then Error FantomasServiceError.CancellationWasRequested else Ok() -let private getFolderFor (filePath: string) () : Result = +let getFolderFor (filePath: string) () : Result = if not (isPathAbsolute filePath) then Error FantomasServiceError.FilePathIsNotAbsolute elif not (File.Exists filePath) then @@ -157,14 +192,14 @@ let private getFolderFor (filePath: string) () : Result Folder |> Ok -let private getDaemon (agent: MailboxProcessor) (folder: Folder) : Result = +let getDaemon (agent: MailboxProcessor) (folder: Folder) : Result = let daemon = agent.PostAndReply(fun replyChannel -> GetDaemon(folder, replyChannel)) match daemon with | Ok daemon -> Ok daemon | Error gde -> Error(FantomasServiceError.DaemonNotFound gde) -let private fileNotFoundResponse filePath : Task = +let fileNotFoundResponse filePath : Task = { Code = int FantomasResponseCode.FileNotFound FilePath = filePath Content = Some $"File \"%s{filePath}\" does not exist." @@ -172,7 +207,7 @@ let private fileNotFoundResponse filePath : Task = Cursor = None } |> Task.FromResult -let private fileNotAbsoluteResponse filePath : Task = +let fileNotAbsoluteResponse filePath : Task = { Code = int FantomasResponseCode.FilePathIsNotAbsolute FilePath = filePath Content = Some $"\"%s{filePath}\" is not an absolute file path. Relative paths are not supported." @@ -180,7 +215,7 @@ let private fileNotAbsoluteResponse filePath : Task = Cursor = None } |> Task.FromResult -let private daemonNotFoundResponse filePath (error: GetDaemonError) : Task = +let daemonNotFoundResponse filePath (error: GetDaemonError) : Task = let content, code = match error with | GetDaemonError.DotNetToolListError(DotNetToolListError.ProcessStartError(ProcessStartError.ExecutableFileNotFound(executableFile, @@ -221,7 +256,7 @@ let private daemonNotFoundResponse filePath (error: GetDaemonError) : Task Task.FromResult -let private cancellationWasRequestedResponse filePath : Task = +let cancellationWasRequestedResponse filePath : Task = { Code = int FantomasResponseCode.CancellationWasRequested FilePath = filePath Content = Some "FantomasService is being or has been disposed." @@ -335,7 +370,8 @@ let decodeFormatResult (inputFilePath: string) (json: JObject) : FantomasRespons type LSPFantomasService() = let cts = new CancellationTokenSource() - let agent = createAgent cts.Token + let configurationWarnings = Event() + let agent = createAgent cts.Token configurationWarnings.Trigger interface FantomasService with member this.Dispose() = @@ -412,4 +448,6 @@ type LSPFantomasService() = Cursor = None })) |> mapResultToResponse filePath + member _.ConfigurationWarnings = configurationWarnings.Publish + member _.ClearCache() = agent.PostAndReply Reset diff --git a/src/Fantomas.Client/LSPFantomasServiceTypes.fs b/src/Fantomas.Client/LSPFantomasServiceTypes.fs index 5a4933d0d3..eed7669350 100644 --- a/src/Fantomas.Client/LSPFantomasServiceTypes.fs +++ b/src/Fantomas.Client/LSPFantomasServiceTypes.fs @@ -64,7 +64,8 @@ type FantomasToolStartInfo = type RunningFantomasTool = { Process: Process RpcClient: JsonRpc - StartInfo: FantomasToolStartInfo } + StartInfo: FantomasToolStartInfo + ConfigurationWarnings: IEvent } interface IDisposable with member this.Dispose() : unit = diff --git a/src/Fantomas.Client/LSPFantomasServiceTypes.fsi b/src/Fantomas.Client/LSPFantomasServiceTypes.fsi index 71feebed58..663fcec2ba 100644 --- a/src/Fantomas.Client/LSPFantomasServiceTypes.fsi +++ b/src/Fantomas.Client/LSPFantomasServiceTypes.fsi @@ -46,9 +46,15 @@ type FantomasToolStartInfo = [] type RunningFantomasTool = - { Process: System.Diagnostics.Process - RpcClient: StreamJsonRpc.JsonRpc - StartInfo: FantomasToolStartInfo } + { + Process: System.Diagnostics.Process + RpcClient: StreamJsonRpc.JsonRpc + StartInfo: FantomasToolStartInfo + + /// Raised when this daemon reports settings it could not act on. A daemon older than + /// Fantomas 8.0 does not send these, so the event simply never fires. + ConfigurationWarnings: IEvent + } interface System.IDisposable diff --git a/src/Fantomas.Core/Context.fs b/src/Fantomas.Core/Context.fs index aa0dba041f..690becb7ed 100644 --- a/src/Fantomas.Core/Context.fs +++ b/src/Fantomas.Core/Context.fs @@ -6,13 +6,13 @@ open Fantomas.Core open Fantomas.Core.SyntaxOak [] -let (|CommentOrDefineEvent|_|) we = +let (|CommentOrDefineEvent|_|) (we: WriterEvent) : WriterEvent voption = match we with | WriteTrivia _ -> ValueSome we | _ -> ValueNone [] -let (|EmptyWrite|_|) (we: WriterEvent) = +let (|EmptyWrite|_|) (we: WriterEvent) : unit voption = match we with | Write v | WriteTrivia v -> diff --git a/src/Fantomas.FCS/Parse.fs b/src/Fantomas.FCS/Parse.fs index de3b336b5f..9d5c240664 100644 --- a/src/Fantomas.FCS/Parse.fs +++ b/src/Fantomas.FCS/Parse.fs @@ -849,17 +849,19 @@ let getSyntaxErrorMessage ctxt = |> List.exists (fun prods -> match prods - |> List.map Parser.prodIdxToNonTerminal - |> List.map (function - | NONTERM_Category_Type -> Parser.NONTERM_typ - | NONTERM_Category_Expr -> Parser.NONTERM_declExpr - | NONTERM_Category_Pattern -> Parser.NONTERM_atomicPattern - | NONTERM_Category_IfThenElse -> Parser.NONTERM_ifExprThen - | NONTERM_Category_SignatureFile -> Parser.NONTERM_signatureFile - | NONTERM_Category_ImplementationFile -> Parser.NONTERM_implementationFile - | NONTERM_Category_Definition -> Parser.NONTERM_moduleDefn - | NONTERM_Category_Interaction -> Parser.NONTERM_interaction - | nt -> nt) + |> List.map ( + Parser.prodIdxToNonTerminal + >> function + | NONTERM_Category_Type -> Parser.NONTERM_typ + | NONTERM_Category_Expr -> Parser.NONTERM_declExpr + | NONTERM_Category_Pattern -> Parser.NONTERM_atomicPattern + | NONTERM_Category_IfThenElse -> Parser.NONTERM_ifExprThen + | NONTERM_Category_SignatureFile -> Parser.NONTERM_signatureFile + | NONTERM_Category_ImplementationFile -> Parser.NONTERM_implementationFile + | NONTERM_Category_Definition -> Parser.NONTERM_moduleDefn + | NONTERM_Category_Interaction -> Parser.NONTERM_interaction + | nt -> nt + ) |> Set.ofList |> Set.toList with @@ -983,11 +985,11 @@ let getSyntaxErrorMessage ctxt = match (ctxt.ShiftTokens - |> List.map Parser.tokenTagToTokenId - |> List.filter (function + |> List.choose (fun tokenTag -> + match Parser.tokenTagToTokenId tokenTag with | Parser.TOKEN_error - | Parser.TOKEN_EOF -> false - | _ -> true) + | Parser.TOKEN_EOF -> None + | tokenId -> Some tokenId) |> List.map tokenIdToText |> Set.ofList |> Set.toList) diff --git a/src/Fantomas.Tests/EditorConfigurationTests.fs b/src/Fantomas.Tests/EditorConfigurationTests.fs index ecd903f016..3131bd3efb 100644 --- a/src/Fantomas.Tests/EditorConfigurationTests.fs +++ b/src/Fantomas.Tests/EditorConfigurationTests.fs @@ -9,6 +9,8 @@ open System.IO let private (==) (actual: 'T) (expected: 'T) = Assert.That(actual, Is.EqualTo<'T> expected) +let private silentLog: Serilog.ILogger = Serilog.Core.Logger.None + let private defaultConfig = FormatConfig.Default let tempName () = Guid.NewGuid().ToString("N") @@ -102,7 +104,7 @@ let ``single configuration file`` () = use fsharpFile = new FSharpFile(rootFolderName, fsharpFileExtension = ".fs") - let config = EditorConfig.readConfiguration fsharpFile.FSharpFile + let config = EditorConfig.readConfiguration silentLog fsharpFile.FSharpFile config == defaultConfig @@ -119,7 +121,7 @@ let ``pointing to subfolder should return parent config file as well`` () = use fsharpFile = new FSharpFile(rootFolder, subFolder = subFolder) - let config = EditorConfig.readConfiguration fsharpFile.FSharpFile + let config = EditorConfig.readConfiguration silentLog fsharpFile.FSharpFile config.IndentSize == 2 @@ -140,7 +142,7 @@ let ``parent config should not be taking into account when child is root`` () = use fsharpFile = new FSharpFile(rootFolder, subFolder = subFolder) - let config = EditorConfig.readConfiguration fsharpFile.FSharpFile + let config = EditorConfig.readConfiguration silentLog fsharpFile.FSharpFile config.MaxRecordWidth == defaultConfig.MaxRecordWidth config.IndentSize == 2 @@ -156,7 +158,7 @@ let ``configuration file should not affect file extension`` () = ) use fsharpFile = new FSharpFile(rootFolder, fsharpFileExtension = ".fsx") - let config = EditorConfig.readConfiguration fsharpFile.FSharpFile + let config = EditorConfig.readConfiguration silentLog fsharpFile.FSharpFile config.MaxLineLength == defaultConfig.MaxLineLength [] @@ -176,7 +178,7 @@ fsharp_max_function_binding_width=40 use fsharpFile = new FSharpFile(rootDir) - let config = EditorConfig.readConfiguration fsharpFile.FSharpFile + let config = EditorConfig.readConfiguration silentLog fsharpFile.FSharpFile config.MaxIfThenElseShortWidth == 25 config.MaxValueBindingWidth == 40 @@ -189,7 +191,7 @@ let ``non existing file should return defaults for readConfiguration`` () = use configFixture = new ConfigurationFile(defaultConfig, rootDir) let config = - EditorConfig.readConfiguration (Path.Join(Path.GetTempPath(), "bogus.fs")) + EditorConfig.readConfiguration silentLog (Path.Join(Path.GetTempPath(), "bogus.fs")) config == defaultConfig @@ -224,7 +226,7 @@ tab_width=5 new ConfigurationFile(defaultConfig, rootDir, content = editorConfig) use fsharpFile = new FSharpFile(rootDir) - let config = EditorConfig.readConfiguration fsharpFile.FSharpFile + let config = EditorConfig.readConfiguration silentLog fsharpFile.FSharpFile config.IndentSize == 5 [] @@ -246,7 +248,7 @@ fsharp_max_array_or_list_number_of_items = 4 new ConfigurationFile(defaultConfig, rootDir, content = editorConfig) use fsharpFile = new FSharpFile(rootDir) - let config = EditorConfig.readConfiguration fsharpFile.FSharpFile + let config = EditorConfig.readConfiguration silentLog fsharpFile.FSharpFile config.MaxArrayOrListNumberOfItems == 4 config.ArrayOrListMultilineFormatter == NumberOfItems @@ -265,7 +267,7 @@ fsharp_max_array_or_list_width = 123 use fsharpFile = new FSharpFile(rootDir) - let config = EditorConfig.readConfiguration fsharpFile.FSharpFile + let config = EditorConfig.readConfiguration silentLog fsharpFile.FSharpFile config.MaxArrayOrListWidth == 123 @@ -285,7 +287,7 @@ fsharp_max_record_number_of_items = 4 use fsharpFile = new FSharpFile(rootDir) - let config = EditorConfig.readConfiguration fsharpFile.FSharpFile + let config = EditorConfig.readConfiguration silentLog fsharpFile.FSharpFile config.MaxRecordNumberOfItems == 4 @@ -306,7 +308,7 @@ fsharp_max_record_width = 123 use fsharpFile = new FSharpFile(rootDir) - let config = EditorConfig.readConfiguration fsharpFile.FSharpFile + let config = EditorConfig.readConfiguration silentLog fsharpFile.FSharpFile config.MaxRecordWidth == 123 @@ -325,7 +327,7 @@ fsharp_max_infix_operator_expression = 123 use fsharpFile = new FSharpFile(rootDir) - let config = EditorConfig.readConfiguration fsharpFile.FSharpFile + let config = EditorConfig.readConfiguration silentLog fsharpFile.FSharpFile config.MaxInfixOperatorExpression == 123 @@ -347,7 +349,8 @@ end_of_line = cr // A FormatException rather than a bare exception, because that is the type the CLI matches // on to decide what to print. Anything else reports an empty message at normal verbosity. let ex = - Assert.Throws(fun () -> EditorConfig.readConfiguration fsharpFile.FSharpFile |> ignore) + Assert.Throws(fun () -> + EditorConfig.readConfiguration silentLog fsharpFile.FSharpFile |> ignore) ex.Message == "Carriage returns are not valid for F# code, please use one of 'lf' or 'crlf'" @@ -371,7 +374,7 @@ end_of_line = %s use fsharpFile = new FSharpFile(rootDir) - let config = EditorConfig.readConfiguration fsharpFile.FSharpFile + let config = EditorConfig.readConfiguration silentLog fsharpFile.FSharpFile config.EndOfLine == eol @@ -390,7 +393,7 @@ fsharp_multi_line_lambda_closing_newline = true use fsharpFile = new FSharpFile(rootDir) - let config = EditorConfig.readConfiguration fsharpFile.FSharpFile + let config = EditorConfig.readConfiguration silentLog fsharpFile.FSharpFile Assert.That(config.MultiLineLambdaClosingNewline, Is.True) @@ -409,7 +412,7 @@ fsharp_experimental_keep_indent_in_branch = true use fsharpFile = new FSharpFile(rootDir) - let config = EditorConfig.readConfiguration fsharpFile.FSharpFile + let config = EditorConfig.readConfiguration silentLog fsharpFile.FSharpFile Assert.That(config.ExperimentalKeepIndentInBranch, Is.True) @@ -428,7 +431,7 @@ fsharp_bar_before_discriminated_union_declaration = true use fsharpFile = new FSharpFile(rootDir) - let config = EditorConfig.readConfiguration fsharpFile.FSharpFile + let config = EditorConfig.readConfiguration silentLog fsharpFile.FSharpFile Assert.That(config.BarBeforeDiscriminatedUnionDeclaration, Is.True) @@ -447,7 +450,7 @@ insert_final_newline = false use fsharpFile = new FSharpFile(rootDir) - let config = EditorConfig.readConfiguration fsharpFile.FSharpFile + let config = EditorConfig.readConfiguration silentLog fsharpFile.FSharpFile Assert.That(config.InsertFinalNewline, Is.False) @@ -466,7 +469,7 @@ fsharp_multiline_bracket_style = stroustrup use fsharpFile = new FSharpFile(rootDir) - let config = EditorConfig.readConfiguration fsharpFile.FSharpFile + let config = EditorConfig.readConfiguration silentLog fsharpFile.FSharpFile Assert.That(config.MultilineBracketStyle, Is.EqualTo Stroustrup) @@ -485,7 +488,7 @@ fsharp_multiline_bracket_style = aligned use fsharpFile = new FSharpFile(rootDir) - let config = EditorConfig.readConfiguration fsharpFile.FSharpFile + let config = EditorConfig.readConfiguration silentLog fsharpFile.FSharpFile Assert.That(config.MultilineBracketStyle, Is.EqualTo Aligned) @@ -504,7 +507,7 @@ fsharp_multiline_bracket_style = cramped use fsharpFile = new FSharpFile(rootDir) - let config = EditorConfig.readConfiguration fsharpFile.FSharpFile + let config = EditorConfig.readConfiguration silentLog fsharpFile.FSharpFile Assert.That(config.MultilineBracketStyle, Is.EqualTo Cramped) @@ -523,7 +526,7 @@ fsharp_newline_before_multiline_computation_expression = false use fsharpFile = new FSharpFile(rootDir) - let config = EditorConfig.readConfiguration fsharpFile.FSharpFile + let config = EditorConfig.readConfiguration silentLog fsharpFile.FSharpFile Assert.That(config.NewlineBeforeMultilineComputationExpression, Is.False) @@ -542,36 +545,145 @@ fsharp_experimental_elmish = true use fsharpFile = new FSharpFile(rootDir) - let config = EditorConfig.readConfiguration fsharpFile.FSharpFile + let config = EditorConfig.readConfiguration silentLog fsharpFile.FSharpFile Assert.That(config.ExperimentalElmish, Is.True) +let private parse (settings: (string * string) list) = + EditorConfig.parseOptionsFromEditorConfig defaultConfig (readOnlyDict settings) + [] -let ``invalid editorconfig value emits warning to stderr and uses default`` () = - let rootDir = tempName () +let ``an unparsable value is reported and the default is used`` () = + let config, problems = parse [ "fsharp_experimental_elmish", "not_a_bool" ] - let editorConfig = - """ -[*.fs] -fsharp_experimental_elmish = not_a_bool -""" + problems + == [ EditorConfig.EditorConfigProblem.UnrecognizedValue("fsharp_experimental_elmish", "not_a_bool") ] - use configFixture = - new ConfigurationFile(defaultConfig, rootDir, content = editorConfig) + config.ExperimentalElmish == defaultConfig.ExperimentalElmish - use fsharpFile = new FSharpFile(rootDir) +[] +let ``an unknown fsharp setting is reported`` () = + let _, problems = parse [ "fsharp_bogus_option", "true" ] - let capturedErr = new System.IO.StringWriter() - let originalErr = Console.Error - Console.SetError(capturedErr) + problems + == [ EditorConfig.EditorConfigProblem.UnknownSetting "fsharp_bogus_option" ] - let config = - try - EditorConfig.readConfiguration fsharpFile.FSharpFile - finally - Console.SetError(originalErr) - - let output = capturedErr.ToString() - Assert.That(output, Does.Contain("fsharp_experimental_elmish")) - Assert.That(output, Does.Contain("not_a_bool")) - config.ExperimentalElmish == defaultConfig.ExperimentalElmish +[] +let ``a misspelled setting is reported, and the spelling Fantomas expects is one it supports`` () = + let _, problems = parse [ "fsharp_multiline_brackets_style", "stroustrup" ] + + problems + == [ EditorConfig.EditorConfigProblem.UnknownSetting "fsharp_multiline_brackets_style" ] + + Assert.That(EditorConfig.supportedSettings, Does.Contain "fsharp_multiline_bracket_style") + +[] +let ``prefixing a setting editorconfig itself defines is reported`` () = + let config, problems = parse [ "fsharp_max_line_length", "100" ] + + problems + == [ EditorConfig.EditorConfigProblem.UnknownSetting "fsharp_max_line_length" ] + + config.MaxLineLength == defaultConfig.MaxLineLength + +[] +let ``the settings editorconfig itself defines are supported unprefixed`` () = + let config, problems = parse [ "max_line_length", "60" ] + problems == [] + config.MaxLineLength == 60 + +[] +let ``the supported settings list the editorconfig ones first, then the Fantomas ones`` () = + let editorConfigOwn, fantomasOwn = + EditorConfig.supportedSettings + |> List.partition (fun (setting: string) -> not (setting.StartsWith("fsharp_", StringComparison.Ordinal))) + + editorConfigOwn + == [ "end_of_line"; "indent_size"; "insert_final_newline"; "max_line_length" ] + + EditorConfig.supportedSettings == editorConfigOwn @ fantomasOwn + + fantomasOwn + == List.sortWith (fun left right -> String.CompareOrdinal(left, right)) fantomasOwn + +[] +let ``values the editorconfig spec defines are not reported as mistakes`` () = + // `indent_size = tab` is not something an author writes: the library derives it from + // `indent_style = tab`. `unset` and `off` are spec values meaning "no value here". + let _, problems = + parse + [ "indent_size", "tab" + "max_line_length", "off" + "end_of_line", "unset" + "insert_final_newline", "unset" ] + + problems == [] + +[] +let ``keys are matched without regard to case`` () = + // editorconfig keys are case insensitive. The library lowercases what it reads from a file, + // so this is what a request from an editor relies on. + let config, problems = parse [ "FSHARP_MAX_RECORD_WIDTH", "120" ] + + problems == [] + config.MaxRecordWidth == 120 + +[] +let ``a value editorconfig does not define is reported, prefix or not`` () = + // Only the spec vocabulary is excused. A typo in one of editorconfig's own settings is still + // a typo, and warned about the same as any other. + let _, problems = + parse + [ "indent_size", "banana" + "max_line_length", "wide" + "insert_final_newline", "maybe" ] + + problems + == [ EditorConfig.EditorConfigProblem.UnrecognizedValue("indent_size", "banana") + EditorConfig.EditorConfigProblem.UnrecognizedValue("insert_final_newline", "maybe") + EditorConfig.EditorConfigProblem.UnrecognizedValue("max_line_length", "wide") ] + +[] +let ``an unparsable value for a Fantomas setting is still reported`` () = + let _, problems = parse [ "fsharp_max_record_width", "banana" ] + + problems + == [ EditorConfig.EditorConfigProblem.UnrecognizedValue("fsharp_max_record_width", "banana") ] + +[] +let ``settings belonging to other tools are left alone`` () = + let _, problems = + parse + [ "indent_style", "space" + "trim_trailing_whitespace", "true" + "some_other_tool_setting", "42" ] + + problems == [] + +[] +let ``every problem in one set of settings is reported together`` () = + let _, problems = + parse + [ "fsharp_bogus_option", "true" + "fsharp_another_bogus_option", "4" + "fsharp_experimental_elmish", "not_a_bool" ] + + problems + == [ EditorConfig.EditorConfigProblem.UnknownSetting "fsharp_another_bogus_option" + EditorConfig.EditorConfigProblem.UnknownSetting "fsharp_bogus_option" + EditorConfig.EditorConfigProblem.UnrecognizedValue("fsharp_experimental_elmish", "not_a_bool") ] + +[] +let ``problems are reported by kind, and by setting name within a kind`` () = + let _, problems = + parse + [ "fsharp_space_before_colon", "not_a_bool" + "fsharp_zzz_bogus_option", "true" + "fsharp_experimental_elmish", "not_a_bool" + "fsharp_aaa_bogus_option", "true" ] + + problems + == [ EditorConfig.EditorConfigProblem.UnknownSetting "fsharp_aaa_bogus_option" + EditorConfig.EditorConfigProblem.UnknownSetting "fsharp_zzz_bogus_option" + EditorConfig.EditorConfigProblem.UnrecognizedValue("fsharp_experimental_elmish", "not_a_bool") + EditorConfig.EditorConfigProblem.UnrecognizedValue("fsharp_space_before_colon", "not_a_bool") ] diff --git a/src/Fantomas.Tests/Integration/ConfigTests.fs b/src/Fantomas.Tests/Integration/ConfigTests.fs index e1c593119f..5a085ba298 100644 --- a/src/Fantomas.Tests/Integration/ConfigTests.fs +++ b/src/Fantomas.Tests/Integration/ConfigTests.fs @@ -104,3 +104,103 @@ end_of_line = lf let result = System.IO.File.ReadAllText(fileFixture.Filename) result |> should equal "#if FOO\n()\n#else\n()\n#endif\n" + +[] +let private BadEditorConfig = + """ +[*.fs] +fsharp_bogus_option = true +fsharp_experimental_elmish = not_a_bool +some_other_tool_setting = 42 +""" + +let private occurrences (needle: string) (haystack: string) : int = + haystack.Split([| needle |], System.StringSplitOptions.None).Length - 1 + +[] +let ``settings Fantomas cannot use are reported on standard error`` () = + use fileFixture = new TemporaryFileCodeSample("let a = 9\n") + use configFixture = new ConfigurationFile(BadEditorConfig) + + let { ExitCode = exitCode + Output = output + Error = error } = + formatCode [ fileFixture.Filename ] + + exitCode |> should equal 0 + Assert.That(error, Does.Contain "fsharp_bogus_option is not a Fantomas setting") + + Assert.That( + error, + Does.Contain "fsharp_experimental_elmish does not accept the value not_a_bool, using the default instead" + ) + + Assert.That(error, Does.Contain "supports these .editorconfig settings:") + Assert.That(error, Does.Contain "fsharp_multiline_bracket_style") + // A setting without the fsharp_ prefix belongs to some other tool and is none of our business. + Assert.That(error, Does.Not.Contain "some_other_tool_setting") + Assert.That(output, Does.Not.Contain "fsharp_bogus_option") + +[] +let ``settings Fantomas cannot use are reported once, however many files are formatted`` () = + use firstFile = new TemporaryFileCodeSample("let a = 9\n") + use secondFile = new TemporaryFileCodeSample("let b = 9\n") + use thirdFile = new TemporaryFileCodeSample("let c = 9\n") + use configFixture = new ConfigurationFile(BadEditorConfig) + + let { ExitCode = exitCode; Error = error } = + formatCode [ firstFile.Filename; secondFile.Filename; thirdFile.Filename ] + + exitCode |> should equal 0 + + occurrences "fsharp_bogus_option is not a Fantomas setting" error + |> should equal 1 + + occurrences "supports these .editorconfig settings:" error |> should equal 1 + +// Files are formatted in parallel, so the report has to leave one thread as a single message. +// Written as two, the settings list can overtake the problems it belongs to. +[] +let ``the problems come before the settings list, however many files are formatted`` () = + use firstFile = new TemporaryFileCodeSample("let a = 9\n") + use secondFile = new TemporaryFileCodeSample("let b = 9\n") + use thirdFile = new TemporaryFileCodeSample("let c = 9\n") + use fourthFile = new TemporaryFileCodeSample("let d = 9\n") + use configFixture = new ConfigurationFile(BadEditorConfig) + + let { ExitCode = exitCode; Error = error } = + formatCode + [ firstFile.Filename + secondFile.Filename + thirdFile.Filename + fourthFile.Filename ] + + exitCode |> should equal 0 + + let problemsAt = + error.IndexOf("Fantomas cannot use some settings from", System.StringComparison.Ordinal) + + let settingsAt = + error.IndexOf("supports these .editorconfig settings:", System.StringComparison.Ordinal) + + Assert.That(problemsAt, Is.GreaterThanOrEqualTo 0) + Assert.That(settingsAt, Is.GreaterThan problemsAt) + +[] +let ``an editorconfig Fantomas can act on reports nothing`` () = + use fileFixture = new TemporaryFileCodeSample("let a = 9\n") + + use configFixture = + new ConfigurationFile( + """ +[*.fs] +max_line_length = 100 +fsharp_multiline_bracket_style = stroustrup +indent_style = space +""" + ) + + let { ExitCode = exitCode; Error = error } = formatCode [ fileFixture.Filename ] + + exitCode |> should equal 0 + error |> should equal "" diff --git a/src/Fantomas.Tests/Integration/DaemonTests.fs b/src/Fantomas.Tests/Integration/DaemonTests.fs index eade9fe542..f0fbc892fd 100644 --- a/src/Fantomas.Tests/Integration/DaemonTests.fs +++ b/src/Fantomas.Tests/Integration/DaemonTests.fs @@ -15,7 +15,7 @@ let private assertFormatted (actual: string) (expected: string) : unit = String.normalizeNewLine actual |> should equal (String.normalizeNewLine expected) -let private runWithDaemon (fn: JsonRpc -> Async) = +let private runWithDaemon (fn: JsonRpc -> Async) : Async = async { let struct (serverStream, clientStream) = FullDuplexStream.CreatePair() @@ -28,6 +28,51 @@ let private runWithDaemon (fn: JsonRpc -> Async) = (daemon :> IDisposable).Dispose() } +/// As `runWithDaemon`, but listening for the configuration warnings the daemon pushes. +/// The handler has to be attached before the client starts listening. +let private runWithDaemonCollectingWarnings (fn: JsonRpc -> Async) : Async = + async { + let struct (serverStream, clientStream) = FullDuplexStream.CreatePair() + + let daemon = new FantomasDaemon(serverStream, serverStream, realDaemonEnvironment) + + let client = new JsonRpc(clientStream, clientStream) + let warnings = ResizeArray() + + client.AddLocalRpcMethod( + Methods.ConfigurationWarning, + Action(fun warning -> lock warnings (fun () -> warnings.Add warning)) + ) + + client.StartListening() + + // The notification is one-way, so it can still be in flight when the response arrives. + // Poll rather than sleep a fixed amount: a machine under load can take longer than any + // constant we would pick here, and a test that sleeps too little fails intermittently. + let maxAttempts = 50 + + let rec waitForWarning (attempt: int) : Async = + async { + let arrived = lock warnings (fun () -> warnings.Count > 0) + + if arrived || attempt >= maxAttempts then + return () + else + do! Async.Sleep 100 + return! waitForWarning (attempt + 1) + } + + try + do! fn client + do! waitForWarning 0 + finally + // A failing assertion must not leave the connection and the daemon behind. + client.Dispose() + (daemon :> IDisposable).Dispose() + + return List.ofSeq warnings + } + [] let ``version request`` () = runWithDaemon (fun client -> @@ -330,6 +375,229 @@ let add (a : int) (b : int) = // | otherResponse -> Assert.Fail $"Unexpected response %A{otherResponse}" }) +[] +let ``a configuration warning is sent for settings the daemon cannot use`` () = + let sourceCode = "module Foo\n\nlet add a b = a + b" + use codeFile = new TemporaryFileCodeSample(sourceCode) + + let warnings = + runWithDaemonCollectingWarnings (fun client -> + async { + let request = + { SourceCode = sourceCode + FilePath = codeFile.Filename + Config = + Some( + readOnlyDict [ "fsharp_bogus_option", "true"; "fsharp_experimental_elmish", "not_a_bool" ] + ) + Cursor = None } + + let! _response = + client.InvokeAsync(Methods.FormatDocument, request) + |> Async.AwaitTask + + return () + }) + |> Async.RunSynchronously + + match warnings with + | [ warning ] -> + warning.FilePath |> should equal codeFile.Filename + + warning.Problems + |> Array.map (fun problem -> problem.Code, problem.Source, problem.Setting, problem.Value) + |> should + equal + [| int ConfigurationProblemCode.UnknownSetting, + int ConfigurationProblemSource.Request, + "fsharp_bogus_option", + null + int ConfigurationProblemCode.UnrecognizedValue, + int ConfigurationProblemSource.Request, + "fsharp_experimental_elmish", + "not_a_bool" |] + | otherwise -> Assert.Fail $"Expected exactly one configuration warning, got %A{otherwise}" + +[] +let ``a configuration warning with no problems is sent when the configuration is fine`` () = + let sourceCode = "module Foo\n\nlet add a b = a + b" + use codeFile = new TemporaryFileCodeSample(sourceCode) + + let warnings = + runWithDaemonCollectingWarnings (fun client -> + async { + let request = + { SourceCode = sourceCode + FilePath = codeFile.Filename + Config = Some(readOnlyDict [ "fsharp_space_before_colon", "true" ]) + Cursor = None } + + let! _response = + client.InvokeAsync(Methods.FormatDocument, request) + |> Async.AwaitTask + + return () + }) + |> Async.RunSynchronously + + // Sent even when there is nothing wrong, so a client can clear what it reported earlier. + match warnings with + | [ warning ] -> warning.Problems |> should be Empty + | otherwise -> Assert.Fail $"Expected exactly one configuration warning, got %A{otherwise}" + +// The settings an editor sends are checked the same way the ones on disk are. A mistake in them +// must not disturb the response: in daemon mode standard out carries the JSON-RPC protocol, so a +// warning that reached it would fault the connection rather than merely be noisy. +[] +let ``format document with a custom config the daemon cannot use`` () = + runWithDaemon (fun client -> + async { + let sourceCode = "module Foo\n\nlet add a b = a + b" + + use codeFile = new TemporaryFileCodeSample(sourceCode) + + let request = + { SourceCode = sourceCode + FilePath = codeFile.Filename + Config = + Some(readOnlyDict [ "fsharp_bogus_option", "true"; "fsharp_experimental_elmish", "not_a_bool" ]) + Cursor = None } + + let! response = + client.InvokeAsync(Methods.FormatDocument, request) + |> Async.AwaitTask + + match response with + | FormatDocumentResponse.Formatted(formattedContent = formatted) -> + assertFormatted formatted "module Foo\n\nlet add a b = a + b\n" + | otherResponse -> Assert.Fail $"Unexpected response %A{otherResponse}" + }) + +[] +let ``settings from an editorconfig on disk are reported with their source and files`` () = + let sourceCode = "module Foo\n\nlet add a b = a + b" + use codeFile = new TemporaryFileCodeSample(sourceCode) + + use _config = + new ConfigurationFile( + """ +[*.fs] +fsharp_bogus_option = true +fsharp_experimental_elmish = not_a_bool +""" + ) + + let warnings = + runWithDaemonCollectingWarnings (fun client -> + async { + let request = + { SourceCode = sourceCode + FilePath = codeFile.Filename + Config = None + Cursor = None } + + let! _response = + client.InvokeAsync(Methods.FormatDocument, request) + |> Async.AwaitTask + + return () + }) + |> Async.RunSynchronously + + match warnings with + | [ warning ] -> + warning.Problems + |> Array.map (fun problem -> problem.Code, problem.Source, problem.Setting, problem.Value) + |> should + equal + [| int ConfigurationProblemCode.UnknownSetting, + int ConfigurationProblemSource.EditorConfig, + "fsharp_bogus_option", + null + int ConfigurationProblemCode.UnrecognizedValue, + int ConfigurationProblemSource.EditorConfig, + "fsharp_experimental_elmish", + "not_a_bool" |] + + // The paths of the files that contributed, so a client can point the user at them. + Assert.That(warning.EditorConfigFiles, Is.Not.Empty) + + Assert.That( + warning.EditorConfigFiles + |> Array.forall (fun file -> + System.IO.Path.IsPathRooted file + && file.EndsWith(".editorconfig", System.StringComparison.Ordinal)), + Is.True, + $"Expected absolute .editorconfig paths, got %A{warning.EditorConfigFiles}" + ) + + // Not just any .editorconfig: the one this test wrote. + Assert.That(warning.EditorConfigFiles, Does.Contain _config.Filename) + | otherwise -> Assert.Fail $"Expected exactly one configuration warning, got %A{otherwise}" + +[] +let ``format selection reports configuration warnings too`` () = + let sourceCode = "module Foo\n\nlet add a b = a + b" + use codeFile = new TemporaryFileCodeSample(sourceCode) + + let warnings = + runWithDaemonCollectingWarnings (fun client -> + async { + let request = + { SourceCode = sourceCode + FilePath = codeFile.Filename + Config = Some(readOnlyDict [ "fsharp_bogus_option", "true" ]) + Range = FormatSelectionRange(3, 0, 3, 19) } + + let! _response = + client.InvokeAsync(Methods.FormatSelection, request) + |> Async.AwaitTask + + return () + }) + |> Async.RunSynchronously + + match warnings with + | [ warning ] -> + warning.Problems + |> Array.map (fun problem -> problem.Code, problem.Setting) + |> should equal [| int ConfigurationProblemCode.UnknownSetting, "fsharp_bogus_option" |] + | otherwise -> Assert.Fail $"Expected exactly one configuration warning, got %A{otherwise}" + +[] +let ``an ignored file still reports an empty configuration warning`` () = + let sourceCode = "let foo = 4" + + use codeFile = + new TemporaryFileCodeSample(sourceCode, fileName = "Ignored", subFolders = [| "warned" |]) + + use _ignoreFixture = new FantomasIgnoreFile("warned/Ignored.fs") + + let warnings = + runWithDaemonCollectingWarnings (fun client -> + async { + let request = + { SourceCode = sourceCode + FilePath = codeFile.Filename + Config = None + Cursor = None } + + let! _response = + client.InvokeAsync(Methods.FormatDocument, request) + |> Async.AwaitTask + + return () + }) + |> Async.RunSynchronously + + // Reported even though nothing was formatted, so a client can clear a warning it showed for + // this file before the user added it to .fantomasignore. + match warnings with + | [ warning ] -> + warning.FilePath |> should equal codeFile.Filename + warning.Problems |> should be Empty + | otherwise -> Assert.Fail $"Expected exactly one configuration warning, got %A{otherwise}" + [] let ``format nested ignored file`` () = runWithDaemon (fun client -> diff --git a/src/Fantomas.Tests/TestHelpers.fs b/src/Fantomas.Tests/TestHelpers.fs index 918b53e813..14720881b9 100644 --- a/src/Fantomas.Tests/TestHelpers.fs +++ b/src/Fantomas.Tests/TestHelpers.fs @@ -225,7 +225,7 @@ let defaultSettings: CliSettings = /// A `DaemonEnvironment` over the real file system, as the tool itself builds one. let realDaemonEnvironment: DaemonEnvironment = { FileSystem = FileSystem() - ReadConfiguration = EditorConfig.readConfiguration + ReadConfiguration = EditorConfig.tryReadConfiguration Log = Log.Logger } /// A `CliEnvironment` over the real file system, honouring no ignore file. Enough for a test that @@ -233,7 +233,7 @@ let realDaemonEnvironment: DaemonEnvironment = let realEnvironment: CliEnvironment = { FileSystem = FileSystem() IgnoreFile = None - ReadConfiguration = EditorConfig.readConfiguration + ReadConfiguration = EditorConfig.readConfiguration Log.Logger Log = Log.Logger Console = AnsiConsole.Console } diff --git a/src/Fantomas/Daemon.fs b/src/Fantomas/Daemon.fs index 1c110db0ac..91e083917d 100644 --- a/src/Fantomas/Daemon.fs +++ b/src/Fantomas/Daemon.fs @@ -1,6 +1,7 @@ module Fantomas.Daemon open System +open System.Collections.Generic open System.Diagnostics open System.IO open System.IO.Abstractions @@ -18,9 +19,55 @@ open Serilog [] type DaemonEnvironment = { FileSystem: IFileSystem - ReadConfiguration: string -> FormatConfig + ReadConfiguration: string -> EditorConfigResult option Log: ILogger } +let toConfigurationProblem (source: ConfigurationProblemSource) (problem: EditorConfigProblem) : ConfigurationProblem = + match problem with + | EditorConfigProblem.UnknownSetting setting -> + { Code = int ConfigurationProblemCode.UnknownSetting + Source = int source + Setting = setting + Value = null } + | EditorConfigProblem.UnrecognizedValue(setting, value) -> + { Code = int ConfigurationProblemCode.UnrecognizedValue + Source = int source + Setting = setting + Value = value } + +/// Resolve the configuration for a request the way the daemon needs it: the `.editorconfig` on +/// disk, then whatever the editor sent layered on top, keeping the problems from both. +/// +/// Deliberately silent: the problems travel to the client as a notification and are never written +/// to standard error. `Fantomas.Client` drains the daemon's standard error, but an older client +/// does not, and anything written there then accumulates in a pipe nobody reads. A report is +/// around 1.5KB and the default pipe buffer on Windows is 4KB, so a few of them would block the +/// write inside a format request and hang the connection. +let configurationFor + (readConfiguration: string -> EditorConfigResult option) + (filePath: string) + (requestConfig: IReadOnlyDictionary option) + : FormatConfig * ConfigurationWarning = + let config, editorConfigFiles, fileProblems = + match readConfiguration filePath with + | Some result -> result.Config, result.EditorConfigFiles, result.Problems + | None -> FormatConfig.Default, [], [] + + let fromEditorConfig = + List.map (toConfigurationProblem ConfigurationProblemSource.EditorConfig) fileProblems + + let config, fromRequest = + match requestConfig with + | None -> config, [] + | Some properties -> + let config, problems = parseOptionsFromEditorConfig config properties + config, List.map (toConfigurationProblem ConfigurationProblemSource.Request) problems + + config, + { FilePath = filePath + EditorConfigFiles = Array.ofList editorConfigFiles + Problems = List.toArray (fromEditorConfig @ fromRequest) } + type FantomasDaemon(sender: Stream, reader: Stream, environment: DaemonEnvironment) as this = let rpc: JsonRpc = JsonRpc.Attach(sender, reader, this) let traceListener = new DefaultTraceListener() @@ -30,6 +77,19 @@ type FantomasDaemon(sender: Stream, reader: Stream, environment: DaemonEnvironme rpc.TraceSource <- TraceSource(typeof.Name, SourceLevels.Verbose) rpc.TraceSource.Listeners.Add traceListener |> ignore + /// Tell the client which settings in the resolved configuration could not be acted on. Sent + /// after every request, with an empty list when nothing is wrong, so a client can clear what + /// it showed earlier. A client that does not handle the method ignores it. + let notifyConfigurationWarning (warning: ConfigurationWarning) : Task = + task { + try + do! rpc.NotifyAsync(Methods.ConfigurationWarning, [| box warning |]) + with _ -> + // The client went away, or does not speak this method. Never fail a format + // request over a message that only carries advice. + () + } + let disconnectEvent = new ManualResetEvent(false) let exit () = disconnectEvent.Set() |> ignore @@ -57,20 +117,30 @@ type FantomasDaemon(sender: Stream, reader: Stream, environment: DaemonEnvironme (IgnoreFile.find fs (IgnoreFile.loadIgnoreList fs) request.FilePath) request.FilePath then + // Still reported, with nothing in it, so a client can clear what an earlier request + // showed for this file rather than leaving a stale warning behind. + do! + notifyConfigurationWarning + { FilePath = request.FilePath + EditorConfigFiles = Array.empty + Problems = Array.empty } + return FormatDocumentResponse.IgnoredFile request.FilePath else - let config = - match request.Config with - | Some configProperties -> - let config = environment.ReadConfiguration request.FilePath - parseOptionsFromEditorConfig config configProperties - | None -> environment.ReadConfiguration request.FilePath - let cursor = request.Cursor |> Option.map (fun cursor -> CodeFormatter.MakePosition(cursor.Line, cursor.Column)) try + // Reading the configuration belongs inside this: an `.editorconfig` can carry a + // value that raises rather than becoming a problem, `end_of_line = cr` among + // them, and the client should hear about that as an Error response like any + // other failure, not as a remote invocation exception. + let config, warning = + configurationFor environment.ReadConfiguration request.FilePath request.Config + + do! notifyConfigurationWarning warning + let! formatResponse = match cursor with | None -> CodeFormatter.FormatDocumentAsync(request.IsSignatureFile, request.SourceCode, config) @@ -103,13 +173,6 @@ type FantomasDaemon(sender: Stream, reader: Stream, environment: DaemonEnvironme [] member _.FormatSelectionAsync(request: FormatSelectionRequest) : Task = task { - let config = - match request.Config with - | Some configProperties -> - let config = environment.ReadConfiguration request.FilePath - parseOptionsFromEditorConfig config configProperties - | None -> environment.ReadConfiguration request.FilePath - let selection = let r = request.Range @@ -119,6 +182,13 @@ type FantomasDaemon(sender: Stream, reader: Stream, environment: DaemonEnvironme (Position.mkPos r.EndLine r.EndColumn) try + // Inside the try for the same reason as FormatDocumentAsync: a configuration value + // that raises has to reach the client as an Error response. + let config, warning = + configurationFor environment.ReadConfiguration request.FilePath request.Config + + do! notifyConfigurationWarning warning + let! formatted, actualSelection = CodeFormatter.FormatSelectionAsync(request.IsSignatureFile, request.SourceCode, selection, config) diff --git a/src/Fantomas/Daemon.fsi b/src/Fantomas/Daemon.fsi index eac262c9c5..d8099ba26f 100644 --- a/src/Fantomas/Daemon.fsi +++ b/src/Fantomas/Daemon.fsi @@ -7,6 +7,7 @@ open StreamJsonRpc open System.IO.Abstractions open Serilog open Fantomas.Core +open Fantomas.EditorConfig open Fantomas.Client.Contracts /// How the daemon reaches the world outside itself. Narrower than the command line tool's @@ -14,9 +15,14 @@ open Fantomas.Client.Contracts /// run, and it draws nothing, so it needs neither a resolved ignore file nor a console. [] type DaemonEnvironment = - { FileSystem: IFileSystem - ReadConfiguration: string -> FormatConfig - Log: ILogger } + { + FileSystem: IFileSystem + /// The `.editorconfig` result for a file, problems and all. Wider than the command line + /// tool's hook, which only needs the configuration: the daemon sends what it could not use + /// to its client rather than warning about it, so it needs the problems too. + ReadConfiguration: string -> EditorConfigResult option + Log: ILogger + } type FantomasDaemon = interface IDisposable diff --git a/src/Fantomas/EditorConfig.fs b/src/Fantomas/EditorConfig.fs index 5fd646c09a..93200493e6 100644 --- a/src/Fantomas/EditorConfig.fs +++ b/src/Fantomas/EditorConfig.fs @@ -1,9 +1,11 @@ module Fantomas.EditorConfig +open System.Collections.Concurrent open System.Collections.Generic open System.ComponentModel open EditorConfig.Core open Fantomas.Core +open Serilog module Reflection = open System @@ -60,52 +62,161 @@ let getFantomasFields (fallbackConfig: FormatConfig) = (editorConfigName, defaultValue)) [] -let (|Number|_|) (d: string) = +let (|Number|_|) (d: string) : obj voption = match System.Int32.TryParse(d) with | true, d -> ValueSome(box d) | _ -> ValueNone [] -let (|MultilineFormatterType|_|) mft = +let (|MultilineFormatterType|_|) (mft: string) : MultilineFormatterType voption = MultilineFormatterType.OfConfigString mft |> ValueOption.ofOption [] -let (|BracketStyle|_|) bs = +let (|BracketStyle|_|) (bs: string) : MultilineBracketStyle voption = MultilineBracketStyle.OfConfigString bs |> ValueOption.ofOption [] -let (|EndOfLineStyle|_|) eol = +let (|EndOfLineStyle|_|) (eol: string) : EndOfLineStyle voption = EndOfLineStyle.OfConfigString eol |> ValueOption.ofOption [] -let (|Boolean|_|) b = +let (|Boolean|_|) (b: string) : obj voption = if b = "true" then ValueSome(box true) elif b = "false" then ValueSome(box false) else ValueNone +[] +type EditorConfigProblem = + | UnknownSetting of setting: string + | UnrecognizedValue of setting: string * value: string + +[] +type EditorConfigResult = + { Config: FormatConfig + EditorConfigFiles: string list + Problems: EditorConfigProblem list } + +let isFantomasSetting (setting: string) : bool = + setting.StartsWith("fsharp_", System.StringComparison.Ordinal) + +/// Values the editorconfig spec gives a meaning that is not a value. `unset` says a setting from +/// a parent file no longer applies, `indent_size = tab` says to follow `tab_width`, and +/// `max_line_length = off` says there is no limit. Fantomas cannot act on any of them, but they +/// are not mistakes, and the library derives `indent_size = tab` on its own from +/// `indent_style = tab`, so reporting them blames an author for something they never wrote. +/// +/// Only these exact values are excused. Anything else, `indent_size = banana` included, is a +/// mistake and is reported like any other. +let isSpecDefinedNonValue (setting: string) (value: string) : bool = + let value = value.ToLowerInvariant() + + value = "unset" + || (setting = "indent_size" && value = "tab") + || (setting = "max_line_length" && value = "off") + +let supportedSettings: string list = + getFantomasFields FormatConfig.Default + |> Array.map fst + |> List.ofArray + |> List.sortWith (fun left right -> + // The settings editorconfig itself defines come first, then the ones belonging to + // Fantomas, each group ordered the same way everywhere else here: by ordinal. + match compare (isFantomasSetting left) (isFantomasSetting right) with + | 0 -> System.String.CompareOrdinal(left, right) + | difference -> difference) + +let unknownFantomasSettings (editorConfigProperties: IReadOnlyDictionary) : EditorConfigProblem list = + editorConfigProperties.Keys + |> Seq.filter isFantomasSetting + |> Seq.sortWith (fun left right -> System.String.CompareOrdinal(left, right)) + |> Seq.choose (fun setting -> + if List.contains setting supportedSettings then + None + else + Some(EditorConfigProblem.UnknownSetting setting)) + |> Seq.toList + let parseOptionsFromEditorConfig (fallbackConfig: FormatConfig) (editorConfigProperties: IReadOnlyDictionary) - : FormatConfig = - getFantomasFields fallbackConfig - |> Array.map (fun (editorConfigName, defaultValue) -> - match editorConfigProperties.TryGetValue(editorConfigName) with - | true, Number n -> n - | true, Boolean b -> b - | true, MultilineFormatterType mft -> box mft - | true, EndOfLineStyle eol -> box eol - | true, BracketStyle bs -> box bs - | false, _ -> defaultValue - | true, invalidValue -> - eprintfn - $"warning: unrecognized value '%s{invalidValue}' for property '%s{editorConfigName}' in .editorconfig, using default." - - defaultValue) - |> fun newValues -> - - let formatConfigType = FormatConfig.Default.GetType() + : FormatConfig * EditorConfigProblem list = + // editorconfig keys are case insensitive. The library lowercases the ones it reads from a + // file, but nothing lowercases a dictionary handed straight to us, so do it here rather than + // in one caller: a key that differs only in case would otherwise match no setting and raise + // no warning either. Folding keeps the last write, which is what editorconfig does when a + // file sets the same key twice. + let editorConfigProperties = + editorConfigProperties + |> Seq.fold (fun acc setting -> Map.add (setting.Key.ToLowerInvariant()) setting.Value acc) Map.empty + |> Seq.map (fun setting -> setting.Key, setting.Value) + |> readOnlyDict + + let unrecognizedValues = ResizeArray() + + let newValues = + getFantomasFields fallbackConfig + |> Array.map (fun (editorConfigName, defaultValue) -> + match editorConfigProperties.TryGetValue(editorConfigName) with + | true, Number n -> n + | true, Boolean b -> b + | true, MultilineFormatterType mft -> box mft + | true, EndOfLineStyle eol -> box eol + | true, BracketStyle bs -> box bs + | false, _ -> defaultValue + | true, invalidValue -> + if not (isSpecDefinedNonValue editorConfigName invalidValue) then + unrecognizedValues.Add(editorConfigName, invalidValue) + + defaultValue) + + let formatConfigType = FormatConfig.Default.GetType() + + let config = Microsoft.FSharp.Reflection.FSharpValue.MakeRecord(formatConfigType, newValues) :?> FormatConfig + let unrecognized = + unrecognizedValues + |> Seq.sortWith (fun (left, _) (right, _) -> System.String.CompareOrdinal(left, right)) + |> Seq.map EditorConfigProblem.UnrecognizedValue + |> Seq.toList + + config, unknownFantomasSettings editorConfigProperties @ unrecognized + +/// The version without the commit hash `CodeFormatter.GetVersion` appends, so that the +/// settings a user is being pointed at are tied to a version they can act on. +let fantomasVersion: string = + let version = CodeFormatter.GetVersion() + + match version.IndexOf('+') with + | -1 -> version + | index -> version.Substring(0, index) + +/// Every report already written, for the lifetime of the process. Never cleared: the command line +/// reads the same `.editorconfig` again for every file it formats, and this is what keeps one typo +/// from being reported once per file. The daemon does not report through here at all. +let reportedWarnings = ConcurrentDictionary() + +let warnOnce (log: ILogger) (message: string) : unit = + if reportedWarnings.TryAdd(message, ()) then + log.Warning message + +let reportProblems (log: ILogger) (origin: string) (problems: EditorConfigProblem list) : unit = + if not (List.isEmpty problems) then + [ yield "" + yield $"Fantomas cannot use some settings from %s{origin}:" + for problem in problems do + match problem with + | EditorConfigProblem.UnknownSetting setting -> yield $" %s{setting} is not a Fantomas setting" + | EditorConfigProblem.UnrecognizedValue(setting, value) -> + yield $" %s{setting} does not accept the value %s{value}, using the default instead" + yield "" + yield $"Current fantomas version (%s{fantomasVersion}) supports these .editorconfig settings:" + for setting in supportedSettings do + yield $" %s{setting}" + yield "" ] + |> String.concat System.Environment.NewLine + |> warnOnce log + let configToEditorConfig (config: FormatConfig) : string = Reflection.getRecordFields config |> Array.choose (fun (recordField, v) -> @@ -128,14 +239,34 @@ let configToEditorConfig (config: FormatConfig) : string = let editorConfigParser = EditorConfigParser(EditorConfigFileCache.GetOrCreate) -let tryReadConfiguration (fsharpFile: string) : FormatConfig option = +let tryReadConfiguration (fsharpFile: string) : EditorConfigResult option = let editorConfigSettings: FileConfiguration = editorConfigParser.Parse(fileName = fsharpFile) if editorConfigSettings.Properties.Count = 0 then None else - Some(parseOptionsFromEditorConfig FormatConfig.Default editorConfigSettings.Properties) + let config, problems = + parseOptionsFromEditorConfig FormatConfig.Default editorConfigSettings.Properties + + let editorConfigFiles = + editorConfigSettings.EditorConfigFiles + |> Seq.map (fun file -> System.IO.Path.GetFullPath(System.IO.Path.Combine(file.Directory, file.FileName))) + |> Seq.toList + + Some + { Config = config + EditorConfigFiles = editorConfigFiles + Problems = problems } + +let readConfiguration (log: ILogger) (fsharpFile: string) : FormatConfig = + match tryReadConfiguration fsharpFile with + | None -> FormatConfig.Default + | Some result -> + let origin = + match result.EditorConfigFiles with + | [] -> fsharpFile + | files -> String.concat ", " files -let readConfiguration (fsharpFile: string) : FormatConfig = - tryReadConfiguration fsharpFile |> Option.defaultValue FormatConfig.Default + reportProblems log origin result.Problems + result.Config diff --git a/src/Fantomas/EditorConfig.fsi b/src/Fantomas/EditorConfig.fsi index ebd8b8f828..f92e6982c9 100644 --- a/src/Fantomas/EditorConfig.fsi +++ b/src/Fantomas/EditorConfig.fsi @@ -1,5 +1,6 @@ module Fantomas.EditorConfig +open Serilog open Fantomas.Core module Reflection = @@ -14,13 +15,56 @@ module Reflection = val toEditorConfigName: value: char seq -> string +/// A setting in an `.editorconfig` that Fantomas read but could not act on. +[] +type EditorConfigProblem = + /// A setting carrying the `fsharp_` prefix that this version of Fantomas does not have. + | UnknownSetting of setting: string + /// A setting Fantomas has, carrying a value it cannot parse. The default is used instead. + | UnrecognizedValue of setting: string * value: string + +/// What reading the `.editorconfig` chain for one file produced. +[] +type EditorConfigResult = + { + Config: FormatConfig + + /// Absolute paths of the `.editorconfig` files that contributed to `Config`. + /// Which of them a given problem came from is not knowable: editorconfig merges the whole + /// chain into one set of properties before Fantomas sees it. + EditorConfigFiles: string list + + /// The settings that could not be acted on. Not reported anywhere by the time you get + /// them: `readConfiguration` warns about them, the daemon sends them to its client. + Problems: EditorConfigProblem list + } + +/// Every .editorconfig setting this build of Fantomas understands, in the order they are worth +/// reading: the settings editorconfig itself defines first, then the ones belonging to Fantomas, +/// each group in ordinal order. The former keep their upstream names and are not prefixed, the +/// latter all carry the `fsharp_` prefix. +val supportedSettings: string list + +/// Read a `FormatConfig` from editorconfig properties, falling back to `fallbackConfig` for +/// anything the properties do not set. Keys are matched without regard to case, and when two of +/// them fold onto one the last wins, as editorconfig does. Returns the settings it could not act +/// on alongside the configuration, so the caller can decide whether and how to report them. val parseOptionsFromEditorConfig: fallbackConfig: FormatConfig -> editorConfigProperties: System.Collections.Generic.IReadOnlyDictionary -> - FormatConfig + FormatConfig * EditorConfigProblem list val configToEditorConfig: config: FormatConfig -> string -val tryReadConfiguration: fsharpFile: string -> FormatConfig option +/// Read the `.editorconfig` chain that applies to a file. `None` when no `.editorconfig` sets +/// anything for it. +/// +/// Silent: the problems are returned rather than reported. `readConfiguration` warns about them; +/// the daemon sends them to its client instead and must not write them to standard error, which +/// `Fantomas.Client` redirects and never drains. +val tryReadConfiguration: fsharpFile: string -> EditorConfigResult option -val readConfiguration: fsharpFile: string -> FormatConfig +/// Read the `.editorconfig` that applies to a file and warn through `log` about anything in it +/// Fantomas cannot use. The daemon does not go through here: it sends the problems to its client +/// instead, and must not write them to standard error. +val readConfiguration: log: ILogger -> fsharpFile: string -> FormatConfig diff --git a/src/Fantomas/Program.fs b/src/Fantomas/Program.fs index 6c12838553..0e9af0cdee 100644 --- a/src/Fantomas/Program.fs +++ b/src/Fantomas/Program.fs @@ -81,7 +81,7 @@ let main argv = Console.OpenStandardOutput(), Console.OpenStandardInput(), { FileSystem = fileSystem - ReadConfiguration = EditorConfig.readConfiguration + ReadConfiguration = EditorConfig.tryReadConfiguration Log = log } ) @@ -101,7 +101,7 @@ let main argv = fileSystem Environment.CurrentDirectory (IgnoreFile.loadIgnoreList fileSystem) - ReadConfiguration = EditorConfig.readConfiguration + ReadConfiguration = EditorConfig.readConfiguration log Log = log Console = AnsiConsole.Console } From 3cdc9ef503cd91a6ff6e85df5d663c8a4ab7eadb Mon Sep 17 00:00:00 2001 From: nojaf Date: Sat, 22 Aug 2026 18:24:38 +0200 Subject: [PATCH 02/10] Take the Context.fs and Parse.fs tidy-ups back out Both landed in "Warn on .editorconfig settings Fantomas cannot use", which is about `.editorconfig` and says nothing about either file. Reverted here and re-applied in the next commit, so that `git log` on either file points at a commit whose message is about the change. Co-Authored-By: Claude Opus 5 (1M context) --- src/Fantomas.Core/Context.fs | 4 ++-- src/Fantomas.FCS/Parse.fs | 32 +++++++++++++++----------------- 2 files changed, 17 insertions(+), 19 deletions(-) diff --git a/src/Fantomas.Core/Context.fs b/src/Fantomas.Core/Context.fs index 690becb7ed..aa0dba041f 100644 --- a/src/Fantomas.Core/Context.fs +++ b/src/Fantomas.Core/Context.fs @@ -6,13 +6,13 @@ open Fantomas.Core open Fantomas.Core.SyntaxOak [] -let (|CommentOrDefineEvent|_|) (we: WriterEvent) : WriterEvent voption = +let (|CommentOrDefineEvent|_|) we = match we with | WriteTrivia _ -> ValueSome we | _ -> ValueNone [] -let (|EmptyWrite|_|) (we: WriterEvent) : unit voption = +let (|EmptyWrite|_|) (we: WriterEvent) = match we with | Write v | WriteTrivia v -> diff --git a/src/Fantomas.FCS/Parse.fs b/src/Fantomas.FCS/Parse.fs index 9d5c240664..de3b336b5f 100644 --- a/src/Fantomas.FCS/Parse.fs +++ b/src/Fantomas.FCS/Parse.fs @@ -849,19 +849,17 @@ let getSyntaxErrorMessage ctxt = |> List.exists (fun prods -> match prods - |> List.map ( - Parser.prodIdxToNonTerminal - >> function - | NONTERM_Category_Type -> Parser.NONTERM_typ - | NONTERM_Category_Expr -> Parser.NONTERM_declExpr - | NONTERM_Category_Pattern -> Parser.NONTERM_atomicPattern - | NONTERM_Category_IfThenElse -> Parser.NONTERM_ifExprThen - | NONTERM_Category_SignatureFile -> Parser.NONTERM_signatureFile - | NONTERM_Category_ImplementationFile -> Parser.NONTERM_implementationFile - | NONTERM_Category_Definition -> Parser.NONTERM_moduleDefn - | NONTERM_Category_Interaction -> Parser.NONTERM_interaction - | nt -> nt - ) + |> List.map Parser.prodIdxToNonTerminal + |> List.map (function + | NONTERM_Category_Type -> Parser.NONTERM_typ + | NONTERM_Category_Expr -> Parser.NONTERM_declExpr + | NONTERM_Category_Pattern -> Parser.NONTERM_atomicPattern + | NONTERM_Category_IfThenElse -> Parser.NONTERM_ifExprThen + | NONTERM_Category_SignatureFile -> Parser.NONTERM_signatureFile + | NONTERM_Category_ImplementationFile -> Parser.NONTERM_implementationFile + | NONTERM_Category_Definition -> Parser.NONTERM_moduleDefn + | NONTERM_Category_Interaction -> Parser.NONTERM_interaction + | nt -> nt) |> Set.ofList |> Set.toList with @@ -985,11 +983,11 @@ let getSyntaxErrorMessage ctxt = match (ctxt.ShiftTokens - |> List.choose (fun tokenTag -> - match Parser.tokenTagToTokenId tokenTag with + |> List.map Parser.tokenTagToTokenId + |> List.filter (function | Parser.TOKEN_error - | Parser.TOKEN_EOF -> None - | tokenId -> Some tokenId) + | Parser.TOKEN_EOF -> false + | _ -> true) |> List.map tokenIdToText |> Set.ofList |> Set.toList) From ab7da9d453f7208d333f3045dfabea592a847c3a Mon Sep 17 00:00:00 2001 From: nojaf Date: Sat, 22 Aug 2026 18:24:47 +0200 Subject: [PATCH 03/10] Apply IONIDE-010 to Parse.fs, annotate two active patterns `getSyntaxErrorMessage` walked its lists twice where once would do: `List.map |> List.map` is `List.map (f >> g)`, and `List.map |> List.filter` is `List.choose`. That second one is IONIDE-010, which the analyzer run enforces everywhere except here: `Fantomas.FCS` is in the excluded set in `build.fsx`, so nothing would have said so. The two active patterns in Context.fs carry the types they always had. The analyzer does not ask for them; they are here because a partial active pattern reads better with its result type written down. Neither changes behaviour. Co-Authored-By: Claude Opus 5 (1M context) --- src/Fantomas.Core/Context.fs | 4 ++-- src/Fantomas.FCS/Parse.fs | 32 +++++++++++++++++--------------- 2 files changed, 19 insertions(+), 17 deletions(-) diff --git a/src/Fantomas.Core/Context.fs b/src/Fantomas.Core/Context.fs index aa0dba041f..690becb7ed 100644 --- a/src/Fantomas.Core/Context.fs +++ b/src/Fantomas.Core/Context.fs @@ -6,13 +6,13 @@ open Fantomas.Core open Fantomas.Core.SyntaxOak [] -let (|CommentOrDefineEvent|_|) we = +let (|CommentOrDefineEvent|_|) (we: WriterEvent) : WriterEvent voption = match we with | WriteTrivia _ -> ValueSome we | _ -> ValueNone [] -let (|EmptyWrite|_|) (we: WriterEvent) = +let (|EmptyWrite|_|) (we: WriterEvent) : unit voption = match we with | Write v | WriteTrivia v -> diff --git a/src/Fantomas.FCS/Parse.fs b/src/Fantomas.FCS/Parse.fs index de3b336b5f..9d5c240664 100644 --- a/src/Fantomas.FCS/Parse.fs +++ b/src/Fantomas.FCS/Parse.fs @@ -849,17 +849,19 @@ let getSyntaxErrorMessage ctxt = |> List.exists (fun prods -> match prods - |> List.map Parser.prodIdxToNonTerminal - |> List.map (function - | NONTERM_Category_Type -> Parser.NONTERM_typ - | NONTERM_Category_Expr -> Parser.NONTERM_declExpr - | NONTERM_Category_Pattern -> Parser.NONTERM_atomicPattern - | NONTERM_Category_IfThenElse -> Parser.NONTERM_ifExprThen - | NONTERM_Category_SignatureFile -> Parser.NONTERM_signatureFile - | NONTERM_Category_ImplementationFile -> Parser.NONTERM_implementationFile - | NONTERM_Category_Definition -> Parser.NONTERM_moduleDefn - | NONTERM_Category_Interaction -> Parser.NONTERM_interaction - | nt -> nt) + |> List.map ( + Parser.prodIdxToNonTerminal + >> function + | NONTERM_Category_Type -> Parser.NONTERM_typ + | NONTERM_Category_Expr -> Parser.NONTERM_declExpr + | NONTERM_Category_Pattern -> Parser.NONTERM_atomicPattern + | NONTERM_Category_IfThenElse -> Parser.NONTERM_ifExprThen + | NONTERM_Category_SignatureFile -> Parser.NONTERM_signatureFile + | NONTERM_Category_ImplementationFile -> Parser.NONTERM_implementationFile + | NONTERM_Category_Definition -> Parser.NONTERM_moduleDefn + | NONTERM_Category_Interaction -> Parser.NONTERM_interaction + | nt -> nt + ) |> Set.ofList |> Set.toList with @@ -983,11 +985,11 @@ let getSyntaxErrorMessage ctxt = match (ctxt.ShiftTokens - |> List.map Parser.tokenTagToTokenId - |> List.filter (function + |> List.choose (fun tokenTag -> + match Parser.tokenTagToTokenId tokenTag with | Parser.TOKEN_error - | Parser.TOKEN_EOF -> false - | _ -> true) + | Parser.TOKEN_EOF -> None + | tokenId -> Some tokenId) |> List.map tokenIdToText |> Set.ofList |> Set.toList) From bb44aa36592930e2d78672b5d22e0dfe9c387530 Mon Sep 17 00:00:00 2001 From: nojaf Date: Sat, 22 Aug 2026 18:25:51 +0200 Subject: [PATCH 04/10] Read each .editorconfig value as the type its own setting has A value used to be tried against every parser in turn, so a value that meant something to one setting decided the outcome for all of them. `EndOfLineStyle.OfConfigString` raises on `cr` rather than answering, which made `fsharp_max_record_width = cr` fail the whole run with a message about carriage returns. Parsing is now decided by the type of the field the setting writes to, so `cr` is a value only `end_of_line` is offered, and anything else carrying it is reported as a value that setting does not accept. Values are matched without regard to case, as keys already were. Reporting moves out of `EditorConfig` into `EditorConfigReport`, which leaves the configuration module with nothing to say and no Serilog dependency: the two docs scripts that `#load` it no longer have to reference Serilog to do so. The record of what has already been reported belongs to a reporter rather than to the process, so what it does is a question a test can ask. The report itself is shorter and more use. One unknown setting used to print every setting Fantomas has, 43 lines for one typo. It now names the setting, and where the intent is obvious it names the spelling that works: `fsharp_multiline_brackets_style` suggests `fsharp_multiline_bracket_style`, and `fsharp_max_line_length` suggests `max_line_length`. The full list moved to `--verbosity d`, and is not offered at all for a value that could not be read, where the name was right and the list answers nothing. Reading an `.editorconfig` runs once per formatted file, so the reflection it does is worked out once and the name lookup is a set rather than a list scan. Fantomas.Client, three bugs: - Dropping a version from the daemon cache left every folder that resolved to it pinned to a version with no daemon behind it. That is the one state the cache cannot get out of: it answers `CompatibleVersionIsKnownButNoDaemonIsRunning` and changes nothing, so the next request answers the same way, for the rest of the session. A version is now forgotten along with the folders that pointed at it. - `HasExited` says the process is gone, not that its standard error has been read, so the lines explaining a failed handshake were usually missing from the message that reported it. `WaitForExit` with no timeout waits for the readers too. - `fantomas --version` prints `Fantomas v8.0.0+` where `dotnet tool list` prints `8.0.0`. Only the leading `v` was being taken off, so the same Fantomas resolved from a manifest and from the PATH still counted as two versions and still got two daemons. The daemon sends its configuration warning for every format request rather than after every one: the write starts before formatting and is awaited after it, so it is off the way to a formatted document but still on the wire before the response it belongs to. Reading the configuration can raise rather than come back with a problem, and the client now hears about that too instead of being left showing what the previous request gave it. Tests: what a report says is 14 tests over a logger rather than four processes; the daemon tests go through the `ReadConfiguration` and `FileSystem` seams the daemon has rather than the real disk; and the daemon cache is seven deterministic tests over an abstract daemon instead of one test that read the operating system's process table, took five seconds, could be raced by a parallel test project and was skipped outright on Windows. `ConfigurationFile` wrote to `Path.GetTempPath()/.editorconfig`, one path shared by every test that used it. `ConfiguredCodeSample` gives each test a folder of its own. Co-Authored-By: Claude Opus 5 (1M context) --- CHANGELOG.md | 6 +- docs/docs/end-users/Configuration.fsx | 3 - docs/docs/end-users/FantomasClient.md | 26 +- docs/docs/end-users/Recipes.fsx | 3 - src/Fantomas.Client.Tests/DaemonCacheTests.fs | 230 +++++++++++ src/Fantomas.Client.Tests/EndToEndTests.fs | 147 ------- .../Fantomas.Client.Tests.fsproj | 2 + src/Fantomas.Client.Tests/VersionTests.fs | 16 + src/Fantomas.Client/CHANGELOG.md | 5 +- src/Fantomas.Client/Contracts.fsi | 26 +- src/Fantomas.Client/Fantomas.Client.fsproj | 4 + src/Fantomas.Client/FantomasToolLocator.fs | 54 ++- src/Fantomas.Client/FantomasToolLocator.fsi | 6 + src/Fantomas.Client/LSPFantomasService.fs | 206 +++++----- src/Fantomas.Client/LSPFantomasService.fsi | 39 ++ .../LSPFantomasServiceTypes.fsi | 6 +- src/Fantomas.Tests/EditorConfigReportTests.fs | 149 +++++++ .../EditorConfigurationTests.fs | 142 +++++-- src/Fantomas.Tests/Fantomas.Tests.fsproj | 1 + src/Fantomas.Tests/Integration/ConfigTests.fs | 120 ++---- src/Fantomas.Tests/Integration/DaemonTests.fs | 364 ++++++++++-------- src/Fantomas.Tests/TestHelpers.fs | 36 +- src/Fantomas/Daemon.fs | 66 +++- src/Fantomas/Daemon.fsi | 15 + src/Fantomas/EditorConfig.fs | 189 ++++----- src/Fantomas/EditorConfig.fsi | 29 +- src/Fantomas/EditorConfigReport.fs | 145 +++++++ src/Fantomas/EditorConfigReport.fsi | 41 ++ src/Fantomas/Fantomas.fsproj | 2 + src/Fantomas/Program.fs | 2 +- 30 files changed, 1349 insertions(+), 731 deletions(-) create mode 100644 src/Fantomas.Client.Tests/DaemonCacheTests.fs create mode 100644 src/Fantomas.Client.Tests/VersionTests.fs create mode 100644 src/Fantomas.Tests/EditorConfigReportTests.fs create mode 100644 src/Fantomas/EditorConfigReport.fs create mode 100644 src/Fantomas/EditorConfigReport.fsi diff --git a/CHANGELOG.md b/CHANGELOG.md index 5857186765..ca41a45f2e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,11 +18,13 @@ - Breaking: a single file that `.fantomasignore` matches is reported the same way as an ignored file found while walking a folder. `fantomas A.fs` on an ignored file printed nothing unless `--verbosity d` was given, where `fantomas ./folder` containing only that file printed `A.fs was ignored.` Both now print it. A `--check` run reports the files it ignored at detailed verbosity whether they were named directly or found in a folder, where before only a directly named file was reported. [#3406](https://github.com/fsprojects/fantomas/pull/3406) - At detailed verbosity, a run writing to `--out` now notes a file it found already formatted, as a run formatting in place always did. Both paths decide what formatting came to in the same place, so they say the same things about it. [#3406](https://github.com/fsprojects/fantomas/pull/3406) - Breaking: `Fantomas.Core` is no longer binary compatible with `v7`. Several discriminated unions are structs now, which changes nothing about how they are written or matched, but an assembly compiled against `v7` has to be rebuilt. [#3407](https://github.com/fsprojects/fantomas/pull/3407) -- A setting in `.editorconfig` that carries the `fsharp_` prefix but is not a Fantomas setting now warns instead of being silently ignored, and the warning lists every `.editorconfig` setting the running version supports. This catches a misspelling such as `fsharp_multiline_brackets_style`, and catches prefixing one of the four settings editorconfig itself defines, where `fsharp_max_line_length` never applied and `max_line_length` is the one that works. Settings without the `fsharp_` prefix belong to other tools and are left alone. Every problem in one `.editorconfig` is now reported together and only once per run, rather than once per formatted file. [#3401](https://github.com/fsprojects/fantomas/pull/3401) -- The daemon sends a `fantomas/configurationWarning` notification after every format request, naming the settings in the resolved configuration it could not act on, and sending an empty list when there are none so an editor can clear what it showed earlier. Additive to the JSON-RPC contract: a client that does not handle the method ignores it and keeps working. See the [Fantomas.Client changelog](https://github.com/fsprojects/fantomas/blob/main/src/Fantomas.Client/CHANGELOG.md) for the client-side API. [#3401](https://github.com/fsprojects/fantomas/pull/3401) +- A setting in `.editorconfig` that carries the `fsharp_` prefix but is not a Fantomas setting now warns instead of being silently ignored, and where the intent is obvious the warning names the spelling that works. This catches a misspelling such as `fsharp_multiline_brackets_style`, and catches prefixing one of the four settings editorconfig itself defines, where `fsharp_max_line_length` never applied and `max_line_length` is the one that does. Settings without the `fsharp_` prefix belong to other tools and are left alone. Every problem in one `.editorconfig` is reported together and only once per run, rather than once per formatted file, and `--verbosity d` writes out every setting the running version supports. [#3401](https://github.com/fsprojects/fantomas/pull/3401) +- `.editorconfig` keys and values are both matched without regard to case, as the editorconfig specification defines them. `FSHARP_MAX_RECORD_WIDTH` and `fsharp_experimental_elmish = True` used to be ignored. [#3401](https://github.com/fsprojects/fantomas/pull/3401) +- The daemon sends a `fantomas/configurationWarning` notification for every format request, naming the settings in the resolved configuration it could not act on, and sending an empty list when there are none so an editor can clear what it showed earlier. Additive to the JSON-RPC contract: a client that does not handle the method ignores it and keeps working. See the [Fantomas.Client changelog](https://github.com/fsprojects/fantomas/blob/main/src/Fantomas.Client/CHANGELOG.md) for the client-side API. [#3401](https://github.com/fsprojects/fantomas/pull/3401) ### Fixed +- A value that meant something to one setting decided the outcome for every other setting, because each value was tried against every parser in turn. `fsharp_max_record_width = cr` failed the whole run with `Carriage returns are not valid for F# code`; it is now reported as a value that setting does not accept. A value is only read as the type its own setting has. [#3401](https://github.com/fsprojects/fantomas/pull/3401) - `--verbosity` with an unrecognised value exited with code 1 and printed nothing, because the message was logged before the logger was configured. It now reports `Invalid verbosity level` on standard error. [#3399](https://github.com/fsprojects/fantomas/pull/3399) - `--out ` flattened the input tree: every file landed directly in the output folder, so two files with the same name in different subfolders silently overwrote each other. The output folder now mirrors the structure of the input folder, as the documentation already promised. [#3403](https://github.com/fsprojects/fantomas/pull/3403) - `--out ` failed with `Failed to format file` and exit code 1 when the folder of the given path did not exist. Fantomas now creates it, along with the subfolders that mirroring an input folder needs. [#3403](https://github.com/fsprojects/fantomas/pull/3403) diff --git a/docs/docs/end-users/Configuration.fsx b/docs/docs/end-users/Configuration.fsx index 6f785f3268..be9e49c6dd 100644 --- a/docs/docs/end-users/Configuration.fsx +++ b/docs/docs/end-users/Configuration.fsx @@ -23,9 +23,6 @@ UI might be available depending on the IDE. #r "../../../artifacts/bin/Fantomas.FCS/release/Fantomas.FCS.dll" #r "../../../artifacts/bin/Fantomas.Core/release/Fantomas.Core.dll" #r "../../../artifacts/bin/Fantomas/release/EditorConfig.Core.dll" -#r "../../../artifacts/bin/Fantomas/release/Serilog.dll" -#r "../../../artifacts/bin/Fantomas/release/Serilog.Sinks.Console.dll" -#load "../../../src/Fantomas/Logging.fs" #load "../../../src/Fantomas/EditorConfig.fs" open System diff --git a/docs/docs/end-users/FantomasClient.md b/docs/docs/end-users/FantomasClient.md index 17c2a10e90..62cb18d6b4 100644 --- a/docs/docs/end-users/FantomasClient.md +++ b/docs/docs/end-users/FantomasClient.md @@ -95,8 +95,30 @@ Worth knowing: setting rather than trying to point at it. - `Source` tells you whether the setting came from a `.editorconfig` on disk or from the `Config` dictionary your own tool sent along with the request. -- Only Fantomas 8.0.0-alpha-014 and later send these. Against an older daemon the event simply - never fires, so no version check is needed. +- Only Fantomas 8 daemons send these. Against an older one the event simply never fires, so no + version check is needed. +- The event is raised on whichever thread the daemon's message arrived on, never on the thread that + asked for the formatting. Marshal before touching a UI. A handler that throws is swallowed rather + than allowed to fault the connection, so nothing is lost but nothing is reported either. + +If you are talking to the daemon yourself rather than through `Fantomas.Client`, the notification +arrives on `fantomas/configurationWarning` carrying one object: + +```json +{ + "FilePath": "/home/me/MyProject/Library.fs", + "EditorConfigFiles": ["/home/me/MyProject/.editorconfig"], + "Problems": [ + { "Code": 1, "Source": 1, "Setting": "fsharp_multiline_brackets_style", "Value": null }, + { "Code": 2, "Source": 2, "Setting": "fsharp_experimental_elmish", "Value": "not_a_bool" } + ] +} +``` + +`Code` is `1` for a setting Fantomas does not have and `2` for a value it cannot parse; `Source` is +`1` for a `.editorconfig` on disk and `2` for the `Config` dictionary sent with the request. +`Value` is `null` for `Code` `1`, because no value was ever read. `EditorConfigFiles` is empty when +`Problems` is empty. ## Formatting a selection diff --git a/docs/docs/end-users/Recipes.fsx b/docs/docs/end-users/Recipes.fsx index af757d5ebe..e455efc178 100644 --- a/docs/docs/end-users/Recipes.fsx +++ b/docs/docs/end-users/Recipes.fsx @@ -22,9 +22,6 @@ Sometimes, it makes sense to tweak a few setting for a subset of your codebase. #r "../../../artifacts/bin/Fantomas.FCS/release/Fantomas.FCS.dll" #r "../../../artifacts/bin/Fantomas.Core/release/Fantomas.Core.dll" #r "../../../artifacts/bin/Fantomas/release/EditorConfig.Core.dll" -#r "../../../artifacts/bin/Fantomas/release/Serilog.dll" -#r "../../../artifacts/bin/Fantomas/release/Serilog.Sinks.Console.dll" -#load "../../../src/Fantomas/Logging.fs" #load "../../../src/Fantomas/EditorConfig.fs" open System diff --git a/src/Fantomas.Client.Tests/DaemonCacheTests.fs b/src/Fantomas.Client.Tests/DaemonCacheTests.fs new file mode 100644 index 0000000000..3ee2317d43 --- /dev/null +++ b/src/Fantomas.Client.Tests/DaemonCacheTests.fs @@ -0,0 +1,230 @@ +module FantomasClientTests.DaemonCacheTests + +open NUnit.Framework +open Fantomas.Client.LSPFantomasService +open Fantomas.Client.LSPFantomasServiceTypes + +/// A stand-in for a running daemon. `resolveDaemon` is written over an abstract daemon precisely +/// so this can be a number: a real `RunningFantomasTool` needs a process, and the questions here +/// are all about which daemon the cache hands out and what it forgets, not about processes. +type private FakeDaemon = + { Id: int + StartInfo: FantomasToolStartInfo + mutable Running: bool + mutable Disposed: bool } + +type private Recorder() = + let created = ResizeArray() + let disposed = ResizeArray() + + member _.Created: FakeDaemon list = List.ofSeq created + member _.Disposed: FakeDaemon list = List.ofSeq disposed + + member _.Record(daemon: FakeDaemon) = created.Add daemon + member _.RecordDisposed(daemon: FakeDaemon) = disposed.Add daemon + +let private version = FantomasVersion "8.0.0" +let private otherVersion = FantomasVersion "7.0.5" +let private folder = Folder "/repo" +let private nested = Folder "/repo/nested" + +/// Operations that find `version` for every folder and start a daemon that stays up. +let private operationsFor + (recorder: Recorder) + (find: Folder -> Result) + (create: FantomasToolStartInfo -> Result) + : DaemonOperations = + { FindTool = find + Create = + fun startInfo -> + let created = create startInfo + created |> Result.iter recorder.Record + created + StartInfo = fun daemon -> daemon.StartInfo + IsRunning = fun daemon -> daemon.Running + Dispose = + fun daemon -> + daemon.Disposed <- true + daemon.Running <- false + recorder.RecordDisposed daemon } + +let private findsVersion (version: FantomasVersion) (folder: Folder) = + Ok(FantomasToolFound(version, FantomasToolStartInfo.LocalTool folder)) + +let private startsFine (nextId: int ref) (startInfo: FantomasToolStartInfo) = + nextId.Value <- nextId.Value + 1 + + Ok + { Id = nextId.Value + StartInfo = startInfo + Running = true + Disposed = false } + +let private neverStarts (_: FantomasToolStartInfo) = + Error(ProcessStartError.UnExpectedException("dotnet", "fantomas --daemon", "boom")) + +let private expectOk (result: Result<'a, GetDaemonError>) : 'a = + match result with + | Ok value -> value + | Error error -> + Assert.Fail $"Expected a daemon, got %A{error}" + failwith "unreachable" + +[] +let ``two folders on the same version share one daemon`` () = + let recorder = Recorder() + let operations = operationsFor recorder (findsVersion version) (startsFine (ref 0)) + + let first, state = resolveDaemon operations ServiceState.Empty folder + let second, state = resolveDaemon operations state nested + + (expectOk first).Id |> ignore + Assert.That((expectOk second).Id, Is.EqualTo (expectOk first).Id) + Assert.That(List.length recorder.Created, Is.EqualTo 1) + + // Both folders resolved, and the one daemon is the one they resolved to. + Assert.That(Map.count state.FolderToVersion, Is.EqualTo 2) + Assert.That(Map.count state.Daemons, Is.EqualTo 1) + +[] +let ``a folder already resolved is served from the cache without looking for a tool again`` () = + let recorder = Recorder() + let looked = ref 0 + + let find folder = + looked.Value <- looked.Value + 1 + findsVersion version folder + + let operations = operationsFor recorder find (startsFine (ref 0)) + + let _, state = resolveDaemon operations ServiceState.Empty folder + let _, _ = resolveDaemon operations state folder + + Assert.That(looked.Value, Is.EqualTo 1) + +[] +let ``a daemon that crashed is replaced, and the one it replaces is disposed`` () = + let recorder = Recorder() + let operations = operationsFor recorder (findsVersion version) (startsFine (ref 0)) + + let first, state = resolveDaemon operations ServiceState.Empty folder + let first = expectOk first + first.Running <- false + + let second, _ = resolveDaemon operations state folder + let second = expectOk second + + Assert.That(second.Id, Is.Not.EqualTo first.Id) + Assert.That(first.Disposed, Is.True) + // Restarted the way the daemon it replaces was started, not the way this folder resolves now. + Assert.That(second.StartInfo, Is.EqualTo first.StartInfo) + +// The regression this is here for: dropping a version from the cache used to leave every folder +// that resolved to it pointing at a version with no daemon. That is the one state resolveDaemon +// cannot get out of, so the folder answered CompatibleVersionIsKnownButNoDaemonIsRunning for the +// rest of the session instead of trying again. +[] +let ``a folder recovers after the daemon for its version failed to start`` () = + let recorder = Recorder() + let nextId = ref 0 + let working = ref false + + let create startInfo = + if working.Value then + startsFine nextId startInfo + else + neverStarts startInfo + + let operations = operationsFor recorder (findsVersion version) create + + let failed, state = resolveDaemon operations ServiceState.Empty folder + + match failed with + | Error(GetDaemonError.FantomasProcessStart _) -> () + | otherwise -> Assert.Fail $"Expected a start failure, got %A{otherwise}" + + // Nothing left behind pointing at a version with no daemon. + Assert.That(state.FolderToVersion, Is.Empty) + Assert.That(state.Daemons, Is.Empty) + + working.Value <- true + let recovered, _ = resolveDaemon operations state folder + expectOk recovered |> ignore + +[] +let ``a second folder recovers too when the daemon they share failed to start`` () = + let recorder = Recorder() + let nextId = ref 0 + let working = ref true + + let create startInfo = + if working.Value then + startsFine nextId startInfo + else + neverStarts startInfo + + let operations = operationsFor recorder (findsVersion version) create + + // Both folders resolve to the one daemon, then it crashes and will not come back. + let first, state = resolveDaemon operations ServiceState.Empty folder + let _, state = resolveDaemon operations state nested + (expectOk first).Running <- false + working.Value <- false + + let _, state = resolveDaemon operations state folder + + // The other folder shared that version, so it must not be left pinned to it either. + Assert.That(state.FolderToVersion, Is.Empty) + + working.Value <- true + let recovered, _ = resolveDaemon operations state nested + expectOk recovered |> ignore + +[] +let ``forgetting one version leaves the folders on another version alone`` () = + let recorder = Recorder() + let nextId = ref 0 + let working = ref true + + let create startInfo = + if working.Value then + startsFine nextId startInfo + else + neverStarts startInfo + + let find (asked: Folder) = + if asked = nested then + findsVersion otherVersion asked + else + findsVersion version asked + + let operations = operationsFor recorder find create + + let _, state = resolveDaemon operations ServiceState.Empty folder + let survivor, state = resolveDaemon operations state nested + let survivor = expectOk survivor + + // The daemon for `folder`'s version dies and cannot be restarted. + (state.Daemons |> Map.find version).Running <- false + working.Value <- false + let _, state = resolveDaemon operations state folder + + let remaining: (Folder * FantomasVersion) list = Map.toList state.FolderToVersion + Assert.That(remaining, Is.EqualTo<(Folder * FantomasVersion) list> [ nested, otherVersion ]) + Assert.That(state.Daemons |> Map.find otherVersion, Is.SameAs survivor) + +[] +let ``no compatible version is reported without touching the cache`` () = + let recorder = Recorder() + + let operations = + operationsFor recorder (fun _ -> Error FantomasToolError.NoCompatibleVersionFound) (startsFine (ref 0)) + + let result, state = resolveDaemon operations ServiceState.Empty folder + + match result with + | Error GetDaemonError.InCompatibleVersionFound -> () + | otherwise -> Assert.Fail $"Expected no compatible version, got %A{otherwise}" + + Assert.That(state.FolderToVersion, Is.Empty) + Assert.That(recorder.Created, Is.Empty) diff --git a/src/Fantomas.Client.Tests/EndToEndTests.fs b/src/Fantomas.Client.Tests/EndToEndTests.fs index 5dd2e76cfd..f38ea30327 100644 --- a/src/Fantomas.Client.Tests/EndToEndTests.fs +++ b/src/Fantomas.Client.Tests/EndToEndTests.fs @@ -1,7 +1,6 @@ module Fantomas.Client.Tests open System -open System.Diagnostics open System.IO open System.Text open System.Threading.Tasks @@ -187,93 +186,6 @@ end_of_line = lf Assert.Fail report } - /// The command line of a running process, when the platform lets us read it. - /// `System.Diagnostics` cannot do this, and without it a fantomas daemon is indistinguishable - /// from the many other `dotnet` processes a test run starts. - let commandLineOf (pid: int) : string option = - try - if OperatingSystem.IsLinux() then - let path = $"/proc/%i{pid}/cmdline" - - if File.Exists path then - // The arguments are separated by NUL bytes. - Some(File.ReadAllText(path).Replace('\000', ' ')) - else - None - elif OperatingSystem.IsMacOS() then - let psi = ProcessStartInfo("/bin/ps", $"-p %i{pid} -o command=") - psi.RedirectStandardOutput <- true - psi.RedirectStandardError <- true - use p = Process.Start psi - let out = p.StandardOutput.ReadToEnd() - p.WaitForExit() - if p.ExitCode = 0 then Some out else None - else - None - with _ -> - None - - let canReadCommandLines: bool = - OperatingSystem.IsLinux() || OperatingSystem.IsMacOS() - - /// The processes currently serving as a fantomas daemon. - /// - /// Matching on the command line rather than the process name is what makes this usable: a - /// local tool daemon runs as `dotnet fantomas --daemon`, and so shows up under `dotnet`, the - /// same name as every other `dotnet` process. The test projects run in parallel, and the - /// command line integration tests spawn a `dotnet fantomas ` for nearly every test they - /// have, so counting by name alone counts those too. - let runningDaemons () : Set = - Process.GetProcesses() - |> Array.choose (fun (p: Process) -> - // Every process handed out here holds an operating system handle until it is disposed. - use p = p - - let name = - try - p.ProcessName - with _ -> - "" - - if name <> "dotnet" && name <> "fantomas" then - None - else - match commandLineOf p.Id with - | Some commandLine when commandLine.Contains "fantomas" && commandLine.Contains "--daemon" -> Some p.Id - | _ -> None) - |> Set.ofArray - - /// Everything we can still learn about a process that outlived the service, so that a failure - /// says what it was rather than only which number it had. - let describeProcess (pid: int) : string = - let commandLine = - match commandLineOf pid with - | Some c -> c.Trim() - | None -> "" - - try - use p = Process.GetProcessById pid - $" pid %i{pid}: name=%s{p.ProcessName}, exited=%b{p.HasExited}, cmd=%s{commandLine}" - with e -> - $" pid %i{pid}: gone when inspected (%s{e.GetType().Name}), cmd=%s{commandLine}" - - /// Wait until nothing started during the test is left running, then report what is. - /// Helper processes such as `dotnet tool list` exit on their own, so polling tells them apart - /// from a daemon that leaked, which stays. - let settleDaemons (before: Set) : Task> = - let rec loop (attemptsLeft: int) : Task> = - backgroundTask { - let survivors = Set.difference (runningDaemons ()) before - - if Set.isEmpty survivors || attemptsLeft = 0 then - return survivors - else - do! Task.Delay 200 - return! loop (attemptsLeft - 1) - } - - loop 25 - let withVersion version (callback: string -> Task) = backgroundTask { let file = Path.Combine(folder.FullName, version, "File.fs") @@ -340,62 +252,3 @@ end_of_line = lf let! response = service.FormatDocumentAsync(request) do! expectResponse FantomasResponseCode.Formatted fsharpFile response }) - - /// Daemons are cached per version, not per folder, so a second folder pinning the same version - /// has to reuse the running daemon. Starting another one would drop the first from the cache - /// without disposing it, leaving a process behind for the rest of the session. - /// - /// A nested directory is a second folder as far as the service is concerned, while the tool - /// manifest it resolves upward to is the same one, so no second install is needed here. - /// - /// The check is what survives disposal rather than a count taken while the work is in flight: - /// resolving a folder shells out to `dotnet tool list`, and that process can still be in the - /// table when a sample is taken. A daemon that leaked is not in the cache the service empties, - /// so it is still running afterwards, while every helper process is gone by then. - [] - [] - member _.``a second folder on the same version reuses the daemon``(version: string) = - withVersion version (fun fsharpFile -> - backgroundTask { - let versionFolder: string = Path.GetDirectoryName fsharpFile - - let nested = Directory.CreateDirectory(Path.Combine(versionFolder, "nested-folder")) - - let nestedFile = Path.Combine(nested.FullName, "File.fs") - File.WriteAllText(nestedFile, unformattedCode) - - let request (file: string) : FormatDocumentRequest = - { SourceCode = unformattedCode - FilePath = file - Config = None - Cursor = None } - - if not canReadCommandLines then - Assert.Ignore - "This test tells a fantomas daemon from any other dotnet process by its command line, which it can only read on Linux and macOS." - - let before = runningDaemons () - - // A service of its own, so that it can be disposed here. The fixture shares one for - // every other test and only disposes it once they have all run. - let ownService: FantomasService = new LSPFantomasService() - - let! first = ownService.FormatDocumentAsync(request fsharpFile) - do! expectResponse FantomasResponseCode.Formatted fsharpFile first - - let! second = ownService.FormatDocumentAsync(request nestedFile) - do! expectResponse FantomasResponseCode.Formatted nestedFile second - - ownService.Dispose() - - let! survivors = settleDaemons before - - let described = - survivors |> Seq.map describeProcess |> String.concat Environment.NewLine - - Assert.That( - survivors, - Is.Empty, - $"After formatting in two folders that both pin fantomas %s{version}, %i{survivors.Count} process(es) outlived the service.%s{Environment.NewLine}%s{described}" - ) - }) diff --git a/src/Fantomas.Client.Tests/Fantomas.Client.Tests.fsproj b/src/Fantomas.Client.Tests/Fantomas.Client.Tests.fsproj index c3de2d9434..215391bffe 100644 --- a/src/Fantomas.Client.Tests/Fantomas.Client.Tests.fsproj +++ b/src/Fantomas.Client.Tests/Fantomas.Client.Tests.fsproj @@ -9,6 +9,8 @@ + + diff --git a/src/Fantomas.Client.Tests/VersionTests.fs b/src/Fantomas.Client.Tests/VersionTests.fs new file mode 100644 index 0000000000..d735b80874 --- /dev/null +++ b/src/Fantomas.Client.Tests/VersionTests.fs @@ -0,0 +1,16 @@ +module FantomasClientTests.VersionTests + +open NUnit.Framework +open Fantomas.Client.FantomasToolLocator + +// Daemons are cached by version string. `fantomas --version` and `dotnet tool list` say the same +// version two different ways, and while they did, the same Fantomas resolved from a tool manifest +// and from the PATH counted as two versions and got two processes. +[] +[] +[] +[] +[] +[] +let ``a printed version reads as the version a tool manifest names`` (printed: string, expected: string) = + Assert.That(normalizeVersion printed, Is.EqualTo expected) diff --git a/src/Fantomas.Client/CHANGELOG.md b/src/Fantomas.Client/CHANGELOG.md index 795d70c3e8..f8ee77ada2 100644 --- a/src/Fantomas.Client/CHANGELOG.md +++ b/src/Fantomas.Client/CHANGELOG.md @@ -5,7 +5,7 @@ This is the changelog for the Fantomas.Client package specifically. It's distinc ## [Unreleased] ### Added -- `FantomasService.ConfigurationWarnings`, an event raised after every format request with the settings in the resolved configuration that Fantomas could not act on: a `fsharp_`-prefixed setting the daemon's version does not have, or a setting carrying a value it cannot parse. Formatting still succeeds using defaults, so without this the setting quietly does not apply. The event is raised with an empty `Problems` array when nothing is wrong, so a subscriber can clear what it reported earlier. Only Fantomas 8.0.0-alpha-014 and later daemons send these; against an older daemon the event never fires, so no version check is needed. See [Formatting from an editor with Fantomas.Client](https://fsprojects.github.io/fantomas/docs/end-users/FantomasClient.html). [#3401](https://github.com/fsprojects/fantomas/pull/3401) +- `FantomasService.ConfigurationWarnings`, an event raised for every format request with the settings in the resolved configuration that Fantomas could not act on: a `fsharp_`-prefixed setting the daemon's version does not have, or a setting carrying a value it cannot parse. Formatting still succeeds using defaults, so without this the setting quietly does not apply. The event is raised with an empty `Problems` array when nothing is wrong, so a subscriber can clear what it reported earlier, and it is raised on the thread the daemon's message arrived on rather than on the caller's. Only Fantomas 8 daemons send these; against an older daemon the event never fires, so no version check is needed. See [Formatting from an editor with Fantomas.Client](https://fsprojects.github.io/fantomas/docs/end-users/FantomasClient.html). [#3401](https://github.com/fsprojects/fantomas/pull/3401) - `ConfigurationWarning`, `ConfigurationProblem`, `ConfigurationProblemCode` and `ConfigurationProblemSource`, the types carried by that event, and `Methods.ConfigurationWarning`, the JSON-RPC method they arrive on. [#3401](https://github.com/fsprojects/fantomas/pull/3401) - `RunningFantomasTool.ConfigurationWarnings`, for callers driving `FantomasToolLocator.createFor` themselves rather than going through `LSPFantomasService`. The handler has to be registered before the connection starts listening, so `createFor` wires it up; its own signature is unchanged. [#3401](https://github.com/fsprojects/fantomas/pull/3401) @@ -16,6 +16,9 @@ This is the changelog for the Fantomas.Client package specifically. It's distinc ### Fixed - Opening a second folder that pins the same Fantomas version started a second daemon and dropped the first one from the cache without disposing it, leaving an orphaned process behind for the rest of the session. Daemons are keyed by version, so a running one for that version is now reused. [#3401](https://github.com/fsprojects/fantomas/pull/3401) +- A daemon that failed to start left every folder resolved to its version pinned to a version with no daemon behind it, which answered `CompatibleVersionIsKnownButNoDaemonIsRunning` for the rest of the session rather than trying again. Those folders are forgotten along with the version, so the next request resolves the tool from scratch. [#3401](https://github.com/fsprojects/fantomas/pull/3401) +- A Fantomas resolved from the `PATH` counted as a different version from the same Fantomas resolved from a `dotnet-tools.json`, and got a second daemon: `fantomas --version` prints `Fantomas v8.0.0+` where `dotnet tool list` prints `8.0.0`. [#3401](https://github.com/fsprojects/fantomas/pull/3401) +- When a daemon failed its handshake, the standard error quoted in the reported message was whatever had arrived by then rather than all of it, so the lines explaining the failure were usually missing. [#3401](https://github.com/fsprojects/fantomas/pull/3401) ## [0.11.0] - 2026-04-16 diff --git a/src/Fantomas.Client/Contracts.fsi b/src/Fantomas.Client/Contracts.fsi index 5c83c9cf18..3512436551 100644 --- a/src/Fantomas.Client/Contracts.fsi +++ b/src/Fantomas.Client/Contracts.fsi @@ -19,9 +19,13 @@ module Methods = [] val Configuration: string = "fantomas/configuration" - /// Sent by the daemon to the client after every format request, naming the settings in the - /// resolved configuration that Fantomas could not act on. Purely informational: the request - /// still succeeds, using defaults for whatever could not be read. + /// Sent by the daemon to the client for every format request, before the request answers, + /// naming the settings in the resolved configuration that Fantomas could not act on. Purely + /// informational: the request still succeeds, using defaults for whatever could not be read. + /// + /// The notification carries one `ConfigurationWarning`, serialized as it is written here: + /// `{"FilePath": "...", "EditorConfigFiles": ["..."], "Problems": [{"Code": 1, "Source": 1, + /// "Setting": "fsharp_bogus_option", "Value": null}]}`. [] val ConfigurationWarning: string = "fantomas/configurationWarning" @@ -142,7 +146,9 @@ type ConfigurationWarning = FilePath: string /// Absolute paths of the `.editorconfig` files that contributed to the configuration. - /// Empty when no `.editorconfig` applies to `FilePath`. + /// Empty when `Problems` is empty, and when no `.editorconfig` applies to `FilePath`: + /// it is the same list on every request for a file, and there is nothing to do with it + /// while nothing is wrong. /// /// Which of these a given problem came from is not knowable, and deliberately not /// guessed at: editorconfig merges the whole chain into one set of properties before @@ -158,11 +164,17 @@ type FantomasService = abstract ClearCache: unit -> unit - /// Raised after every format request, with the settings in the resolved configuration that + /// Raised for every format request, with the settings in the resolved configuration that /// Fantomas could not act on. Raised with an empty `Problems` list when there is nothing - /// wrong, so a subscriber can clear what it reported earlier. + /// wrong, so a subscriber can clear what it reported earlier, and raised before the request it + /// belongs to answers. + /// + /// Raised on whichever thread the daemon's answer arrived on, never on the caller's. A + /// subscriber that touches a UI has to marshal, and one that throws is swallowed rather than + /// allowed to fault the connection. /// - /// Only daemons from Fantomas 8.0.0-alpha-014 onwards send these; an older one never raises it. + /// Only Fantomas 8 daemons send these; an older one never raises it, so no version check is + /// needed. abstract ConfigurationWarnings: IEvent abstract ConfigurationAsync: filePath: string * ?cancellationToken: CancellationToken -> Task diff --git a/src/Fantomas.Client/Fantomas.Client.fsproj b/src/Fantomas.Client/Fantomas.Client.fsproj index 5fec5fed31..a6a7a1f0a0 100644 --- a/src/Fantomas.Client/Fantomas.Client.fsproj +++ b/src/Fantomas.Client/Fantomas.Client.fsproj @@ -6,6 +6,10 @@ true true + + + + diff --git a/src/Fantomas.Client/FantomasToolLocator.fs b/src/Fantomas.Client/FantomasToolLocator.fs index 1f2372f2f2..0aecd475bb 100644 --- a/src/Fantomas.Client/FantomasToolLocator.fs +++ b/src/Fantomas.Client/FantomasToolLocator.fs @@ -128,6 +128,25 @@ let (|CompatibleTool|_|) (lines: string list) : FantomasVersion voption = let isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) +/// The version `fantomas --version` printed, as `dotnet tool list` would have written it. +/// +/// `--version` answers `Fantomas v8.0.0-alpha-014+e4a1c9d...`, `dotnet tool list` answers +/// `8.0.0-alpha-014`. Daemons are cached by this string, so both the leading `v` and the commit +/// hash have to go: with either of them left on, the same Fantomas resolved once from the manifest +/// and once from the PATH counts as two versions and gets two processes. +let normalizeVersion (printed: string) : string = + let dropPrefix (prefix: string) (text: string) : string = + if text.StartsWith(prefix, StringComparison.OrdinalIgnoreCase) then + text.Substring(prefix.Length).Trim() + else + text + + let printed = printed.Trim() |> dropPrefix "fantomas" |> dropPrefix "v" + + match printed.IndexOf('+') with + | -1 -> printed + | index -> printed.Substring(0, index) + // Find an executable fantomas file on the PATH let fantomasVersionOnPath () : (FantomasExecutableFile * FantomasVersion) option = let fantomasExecutableOnPathOpt = @@ -156,7 +175,6 @@ let fantomasVersionOnPath () : (FantomasExecutableFile * FantomasVersion) option |> Option.bind (fun fantomasExecutablePath -> let processStart = ProcessStartInfo(fantomasExecutablePath) processStart.Arguments <- "--version" - processStart.RedirectStandardOutput <- true processStart.CreateNoWindow <- true processStart.RedirectStandardOutput <- true processStart.RedirectStandardError <- true @@ -164,25 +182,19 @@ let fantomasVersionOnPath () : (FantomasExecutableFile * FantomasVersion) option match startProcess processStart with | Ok p -> - p.WaitForExit() + // Standard error is redirected, so something has to read it, or a version that wrote + // more to it than the pipe holds would block on the write and never exit. Nothing here + // wants what it says. + p.ErrorDataReceived.Add(ignore) + p.BeginErrorReadLine() + let stdOut = p.StandardOutput.ReadToEnd() + p.WaitForExit() stdOut |> Option.ofObj |> Option.map (fun s -> - // `--version` answers `Fantomas v8.0.0`, `dotnet tool list` answers `8.0.0`. - // Daemons are cached by this string, so the leading v has to go: without it the - // same Fantomas resolved once from the manifest and once from the PATH counts as - // two versions and gets two processes. - let version = - let printed = s.ToLowerInvariant().Replace("fantomas", String.Empty).Trim() - - if printed.StartsWith("v", StringComparison.Ordinal) then - printed.Substring(1) - else - printed - - FantomasExecutableFile(fantomasExecutablePath), FantomasVersion(version)) + FantomasExecutableFile(fantomasExecutablePath), FantomasVersion(normalizeVersion s)) | Error(ProcessStartError.ExecutableFileNotFound _) | Error(ProcessStartError.UnExpectedException _) -> None) @@ -266,8 +278,10 @@ let createFor (startInfo: FantomasToolStartInfo) : Result() - // Has to happen before StartListening: StreamJsonRpc refuses to add local methods once - // the connection is listening. A daemon that never sends these simply never triggers it. + // Has to happen before StartListening, for two reasons: StreamJsonRpc refuses to add local + // methods once the connection is listening, and a subscriber added before the daemon can + // send anything is a subscriber that cannot be raced by the first notification. A daemon + // that never sends these simply never triggers it. client.AddLocalRpcMethod( Methods.ConfigurationWarning, Action(fun warning -> @@ -299,6 +313,12 @@ let createFor (startInfo: FantomasToolStartInfo) : Result let error = if daemonProcess.HasExited then + // `HasExited` only says the process is gone; the handler above is fed + // asynchronously and can still be behind. `WaitForExit` with no timeout is the + // one overload that waits for the readers to drain too, so without it the + // message here would be missing the lines that explain the failure. + daemonProcess.WaitForExit() + let stdErr = lock recentStandardError (fun () -> String.Join(Environment.NewLine, recentStandardError)) diff --git a/src/Fantomas.Client/FantomasToolLocator.fsi b/src/Fantomas.Client/FantomasToolLocator.fsi index 95c9c6e5e1..c0bbff2932 100644 --- a/src/Fantomas.Client/FantomasToolLocator.fsi +++ b/src/Fantomas.Client/FantomasToolLocator.fsi @@ -2,6 +2,12 @@ module Fantomas.Client.FantomasToolLocator open Fantomas.Client.LSPFantomasServiceTypes +/// The version `fantomas --version` printed, as `dotnet tool list` would have written it: no +/// `Fantomas` in front, no leading `v`, no `+` on the end. Daemons are cached by this +/// string, so the same Fantomas resolved once from a tool manifest and once from the PATH has to +/// come out of both as the same text, or it gets two processes. +val internal normalizeVersion: printed: string -> string + val findFantomasTool: workingDir: Folder -> Result val createFor: startInfo: FantomasToolStartInfo -> Result diff --git a/src/Fantomas.Client/LSPFantomasService.fs b/src/Fantomas.Client/LSPFantomasService.fs index 3a88561dd7..d369b15bc4 100644 --- a/src/Fantomas.Client/LSPFantomasService.fs +++ b/src/Fantomas.Client/LSPFantomasService.fs @@ -10,12 +10,12 @@ open Fantomas.Client.Contracts open Fantomas.Client.LSPFantomasServiceTypes open Fantomas.Client.FantomasToolLocator -[] -type ServiceState = - { Daemons: Map +[] +type ServiceState<'daemon> = + { Daemons: Map FolderToVersion: Map } - static member Empty: ServiceState = + static member Empty: ServiceState<'daemon> = { Daemons = Map.empty FolderToVersion = Map.empty } @@ -31,119 +31,113 @@ type Msg = | GetDaemon of folder: Folder * replyChannel: AsyncReplyChannel> | Reset of AsyncReplyChannel +[] +type DaemonOperations<'daemon> = + { FindTool: Folder -> Result + Create: FantomasToolStartInfo -> Result<'daemon, ProcessStartError> + StartInfo: 'daemon -> FantomasToolStartInfo + IsRunning: 'daemon -> bool + Dispose: 'daemon -> unit } + +/// Forget a version, and with it every folder that resolved to it. Leaving those folders behind +/// would pin them to a version with no daemon, which is the one state `resolveDaemon` cannot get +/// out of: it answers `CompatibleVersionIsKnownButNoDaemonIsRunning` and changes nothing, so the +/// next request answers the same way, for the rest of the session. Dropping them lets the next +/// request resolve the tool from scratch. +let forgetVersion (version: FantomasVersion) (state: ServiceState<'daemon>) : ServiceState<'daemon> = + { Daemons = Map.remove version state.Daemons + FolderToVersion = state.FolderToVersion |> Map.filter (fun _ known -> known <> version) } + +let startDaemon + (operations: DaemonOperations<'daemon>) + (version: FantomasVersion) + (startInfo: FantomasToolStartInfo) + (folder: Folder) + (state: ServiceState<'daemon>) + : Result<'daemon, GetDaemonError> * ServiceState<'daemon> = + match operations.Create startInfo with + | Ok daemon -> + Ok daemon, + { Daemons = Map.add version daemon state.Daemons + FolderToVersion = Map.add folder version state.FolderToVersion } + | Error error -> Error(GetDaemonError.FantomasProcessStart error), forgetVersion version state + +let resolveDaemon + (operations: DaemonOperations<'daemon>) + (state: ServiceState<'daemon>) + (folder: Folder) + : Result<'daemon, GetDaemonError> * ServiceState<'daemon> = + match Map.tryFind folder state.FolderToVersion with + | Some version -> + match Map.tryFind version state.Daemons with + | Some daemon when operations.IsRunning daemon -> + Ok daemon, + { state with + FolderToVersion = Map.add folder version state.FolderToVersion } + | Some daemon -> + // A weird situation where the process has crashed. Dispose what is left of it so the + // handles it still holds are released, then reboot it the way it was started. + let startInfo = operations.StartInfo daemon + operations.Dispose daemon + startDaemon operations version startInfo folder state + | None -> + // This is a strange situation, we know what version is linked to that folder but there + // is no daemon. The moment a version is added is also the moment a daemon is re-used or + // created. + Error(GetDaemonError.CompatibleVersionIsKnownButNoDaemonIsRunning version), state + | None -> + match operations.FindTool folder with + | Ok(FantomasToolFound(version, startInfo)) -> + // Daemons are keyed by version, not by folder. Two folders that pin the same Fantomas + // share one, so a running daemon for this version has to be reused: starting a second + // would overwrite the first in the map and leave its process running with nothing left + // to dispose it. + // + // The reused daemon keeps the StartInfo it was created with, so a restart after a crash + // resolves the tool the way the first folder did rather than the way this one just did. + match Map.tryFind version state.Daemons with + | Some daemon when operations.IsRunning daemon -> + Ok daemon, + { state with + FolderToVersion = Map.add folder version state.FolderToVersion } + | running -> + // A daemon that crashed is replaced, but dispose it first so the handles it still + // holds are released. + Option.iter operations.Dispose running + startDaemon operations version startInfo folder state + | Error FantomasToolError.NoCompatibleVersionFound -> Error GetDaemonError.InCompatibleVersionFound, state + | Error(FantomasToolError.DotNetListError error) -> Error(GetDaemonError.DotNetToolListError error), state + let createAgent (ct: CancellationToken) (onConfigurationWarning: ConfigurationWarning -> unit) : MailboxProcessor = + let operations: DaemonOperations = + { FindTool = findFantomasTool + Create = + fun startInfo -> + createFor startInfo + |> Result.map (fun daemon -> + // Subscribed here rather than where the daemon is handed out, so that it happens + // once per daemon however many folders end up sharing it. + daemon.ConfigurationWarnings.Add onConfigurationWarning + daemon) + StartInfo = fun daemon -> daemon.StartInfo + IsRunning = fun daemon -> not daemon.Process.HasExited + Dispose = fun daemon -> (daemon :> IDisposable).Dispose() } + MailboxProcessor.Start( (fun inbox -> - let rec messageLoop (state: ServiceState) = + let rec messageLoop (state: ServiceState) = async { let! msg = inbox.Receive() let nextState = match msg with | GetDaemon(folder, replyChannel) -> - // get the version for that folder - // look in the cache first - let versionFromCache = Map.tryFind folder state.FolderToVersion - - match versionFromCache with - | Some version -> - let daemon = Map.tryFind version state.Daemons - - match daemon with - | Some daemon -> - // We have a daemon for the required version in the cache, check if we can still use it. - if daemon.Process.HasExited then - // weird situation where the process has crashed. - // Trying to reboot - (daemon :> IDisposable).Dispose() - - let newDaemonResult = createFor daemon.StartInfo - - match newDaemonResult with - | Ok newDaemon -> - newDaemon.ConfigurationWarnings.Add onConfigurationWarning - replyChannel.Reply(Ok newDaemon.RpcClient) - - { FolderToVersion = Map.add folder version state.FolderToVersion - Daemons = Map.add version newDaemon state.Daemons } - | Error pse -> - replyChannel.Reply(Error(GetDaemonError.FantomasProcessStart pse)) - // The daemon that was there is disposed and the new one - // never started, so drop the entry rather than leave a - // dead one to be disposed again on the next request. - { state with - Daemons = Map.remove version state.Daemons } - else - // return running client - replyChannel.Reply(Ok daemon.RpcClient) - - { state with - FolderToVersion = Map.add folder version state.FolderToVersion } - | None -> - // This is a strange situation, we know what version is linked to that folder but there is no daemon - // The moment a version is added, is also the moment a daemon is re-used or created - replyChannel.Reply( - Error(GetDaemonError.CompatibleVersionIsKnownButNoDaemonIsRunning version) - ) - - state - | None -> - // Try and find a version of fantomas daemon for our current folder - let fantomasToolResult: Result = - findFantomasTool folder - - match fantomasToolResult with - | Ok(FantomasToolFound(version, startInfo)) -> - // Daemons are keyed by version, not by folder. Two folders that - // pin the same Fantomas share one, so a running daemon for this - // version has to be reused: starting a second would overwrite - // the first in the map and leave its process running with - // nothing left to dispose it. - // - // The reused daemon keeps the StartInfo it was created with, so - // a restart after a crash resolves the tool the way the first - // folder did rather than the way this one just did. - let runningDaemon = - Map.tryFind version state.Daemons - |> Option.filter (fun daemon -> not daemon.Process.HasExited) - - match runningDaemon with - | Some daemon -> - replyChannel.Reply(Ok daemon.RpcClient) - - { state with - FolderToVersion = Map.add folder version state.FolderToVersion } - | None -> - // A daemon that crashed is replaced, but dispose it first so - // the handles it still holds are released. - Map.tryFind version state.Daemons - |> Option.iter (fun daemon -> (daemon :> IDisposable).Dispose()) - - let createDaemonResult = createFor startInfo - - match createDaemonResult with - | Ok daemon -> - daemon.ConfigurationWarnings.Add onConfigurationWarning - replyChannel.Reply(Ok daemon.RpcClient) - - { Daemons = Map.add version daemon state.Daemons - FolderToVersion = Map.add folder version state.FolderToVersion } - | Error pse -> - replyChannel.Reply(Error(GetDaemonError.FantomasProcessStart pse)) - // The daemon that was there is disposed and the new one - // never started, so drop the entry rather than leave a - // dead one to be disposed again on the next request. - { state with - Daemons = Map.remove version state.Daemons } - | Error FantomasToolError.NoCompatibleVersionFound -> - replyChannel.Reply(Error GetDaemonError.InCompatibleVersionFound) - state - | Error(FantomasToolError.DotNetListError dotNetToolListError) -> - replyChannel.Reply(Error(GetDaemonError.DotNetToolListError dotNetToolListError)) - state + let daemon, nextState = resolveDaemon operations state folder + replyChannel.Reply(Result.map (fun daemon -> daemon.RpcClient) daemon) + nextState | Reset replyChannel -> Map.toList state.Daemons - |> List.iter (fun (_, daemon) -> (daemon :> IDisposable).Dispose()) + |> List.iter (fun (_, daemon) -> operations.Dispose daemon) replyChannel.Reply() ServiceState.Empty diff --git a/src/Fantomas.Client/LSPFantomasService.fsi b/src/Fantomas.Client/LSPFantomasService.fsi index a01c538441..1f17da73f3 100644 --- a/src/Fantomas.Client/LSPFantomasService.fsi +++ b/src/Fantomas.Client/LSPFantomasService.fsi @@ -1,5 +1,44 @@ module Fantomas.Client.LSPFantomasService +open Fantomas.Client.LSPFantomasServiceTypes + +/// Which daemon serves which folder. Written over an abstract daemon rather than over +/// `RunningFantomasTool` so that the cache can be exercised without starting a process: nothing +/// here does IO, every effect goes through `DaemonOperations`. +[] +type internal ServiceState<'daemon> = + { Daemons: Map + FolderToVersion: Map } + + static member Empty: ServiceState<'daemon> + +[] +type internal GetDaemonError = + | DotNetToolListError of error: DotNetToolListError + | FantomasProcessStart of error: ProcessStartError + | InCompatibleVersionFound + /// A folder resolved to a version with no daemon behind it. `resolveDaemon` never leaves the + /// cache in that state; reaching it means something else emptied `Daemons`. + | CompatibleVersionIsKnownButNoDaemonIsRunning of version: FantomasVersion + +/// Everything the cache does to a daemon and to the world, so that a test can supply all of it. +[] +type internal DaemonOperations<'daemon> = + { FindTool: Folder -> Result + Create: FantomasToolStartInfo -> Result<'daemon, ProcessStartError> + StartInfo: 'daemon -> FantomasToolStartInfo + IsRunning: 'daemon -> bool + Dispose: 'daemon -> unit } + +/// Hand out the daemon serving `folder`, starting one if no running daemon serves its version yet, +/// along with the cache that leaves behind. Daemons are keyed by version rather than by folder, so +/// two folders that pin the same Fantomas share one process. +val internal resolveDaemon: + operations: DaemonOperations<'daemon> -> + state: ServiceState<'daemon> -> + folder: Folder -> + Result<'daemon, GetDaemonError> * ServiceState<'daemon> + type LSPFantomasService = interface Contracts.FantomasService diff --git a/src/Fantomas.Client/LSPFantomasServiceTypes.fsi b/src/Fantomas.Client/LSPFantomasServiceTypes.fsi index 663fcec2ba..c6486101ce 100644 --- a/src/Fantomas.Client/LSPFantomasServiceTypes.fsi +++ b/src/Fantomas.Client/LSPFantomasServiceTypes.fsi @@ -51,8 +51,10 @@ type RunningFantomasTool = RpcClient: StreamJsonRpc.JsonRpc StartInfo: FantomasToolStartInfo - /// Raised when this daemon reports settings it could not act on. A daemon older than - /// Fantomas 8.0 does not send these, so the event simply never fires. + /// Raised when this daemon reports settings it could not act on, on whichever thread its + /// message arrived on. Subscribed to by `createFor` before the connection starts + /// listening, so no notification can outrun a subscriber added there. A daemon older than + /// Fantomas 8 does not send these, so the event simply never fires. ConfigurationWarnings: IEvent } diff --git a/src/Fantomas.Tests/EditorConfigReportTests.fs b/src/Fantomas.Tests/EditorConfigReportTests.fs new file mode 100644 index 0000000000..7cba3622f5 --- /dev/null +++ b/src/Fantomas.Tests/EditorConfigReportTests.fs @@ -0,0 +1,149 @@ +module Fantomas.Tests.EditorConfigReportTests + +open NUnit.Framework +open Fantomas +open Fantomas.EditorConfig +open Fantomas.EditorConfigReport +open Fantomas.Tests.TestHelpers + +let private (==) (actual: 'T) (expected: 'T) = + Assert.That(actual, Is.EqualTo<'T> expected) + +let private unknown = EditorConfigProblem.UnknownSetting +let private unrecognized = EditorConfigProblem.UnrecognizedValue + +/// What a reporter over a collecting logger wrote, one string per message. +let private reportedBy (report: EditorConfigReporter -> unit) : string list = + let logger, collected = collectingLogger () + report (createReporter logger) + (collected ()).Warning + +[] +let ``nothing to say about an editorconfig Fantomas can act on`` () = + describe "/repo/.editorconfig" [] == None + reportedBy (fun report -> report "/repo/.editorconfig" []) == [] + +[] +let ``every problem is named, and the origin with them`` () = + let report = + describe "/repo/.editorconfig" [ unknown "fsharp_wibble"; unrecognized ("fsharp_experimental_elmish", "yes") ] + + match report with + | None -> Assert.Fail "Expected a report" + | Some report -> + Assert.That(report, Does.Contain "/repo/.editorconfig") + Assert.That(report, Does.Contain "fsharp_wibble is not a Fantomas setting") + + Assert.That( + report, + Does.Contain "fsharp_experimental_elmish does not accept the value yes, so the default is used instead" + ) + +[] +let ``a misspelling is answered with the spelling that works`` () = + suggestionFor "fsharp_multiline_brackets_style" + == Some "fsharp_multiline_bracket_style" + + suggestionFor "fsharp_max_recrd_width" == Some "fsharp_max_record_width" + +[] +let ``prefixing a setting editorconfig itself defines is answered with the unprefixed name`` () = + suggestionFor "fsharp_max_line_length" == Some "max_line_length" + suggestionFor "fsharp_indent_size" == Some "indent_size" + +[] +let ``a name nothing like a setting is not guessed at`` () = suggestionFor "fsharp_wibble" == None + +[] +let ``the settings list is not written out for a value that could not be read`` () = + // The name was right. Reading out every name Fantomas knows answers nothing. + match describe "/repo/.editorconfig" [ unrecognized ("fsharp_max_record_width", "banana") ] with + | None -> Assert.Fail "Expected a report" + | Some report -> + Assert.That(report, Does.Not.Contain "--verbosity d") + Assert.That(report, Does.Not.Contain "fsharp_multiline_bracket_style") + +[] +let ``a setting Fantomas does not have points at where the whole list is`` () = + match describe "/repo/.editorconfig" [ unknown "fsharp_wibble" ] with + | None -> Assert.Fail "Expected a report" + | Some report -> Assert.That(report, Does.Contain "--verbosity d") + +[] +let ``the list of supported settings names the running version and every setting it has`` () = + let described = describeSupportedSettings () + + Assert.That(described, Does.Contain fantomasVersion) + + for setting in supportedSettings do + Assert.That(described, Does.Contain setting) + +[] +let ``one report is written once, however many files it is found for`` () = + let written = + reportedBy (fun report -> + for _ in 1..5 do + report "/repo/.editorconfig" [ unknown "fsharp_wibble" ]) + + written |> List.length == 1 + +[] +let ``two editorconfigs with the same problem are both reported`` () = + let written = + reportedBy (fun report -> + report "/repo/one/.editorconfig" [ unknown "fsharp_wibble" ] + report "/repo/two/.editorconfig" [ unknown "fsharp_wibble" ]) + + written |> List.length == 2 + +[] +let ``each reporter starts with a clean record of what it has written`` () = + // The record used to be one dictionary for the lifetime of the process, which meant a test + // could only observe "written once" by starting a new one. + reportedBy (fun report -> report "/repo/.editorconfig" [ unknown "fsharp_wibble" ]) + |> List.length + == 1 + + reportedBy (fun report -> report "/repo/.editorconfig" [ unknown "fsharp_wibble" ]) + |> List.length + == 1 + +// Files are formatted in parallel. Written as several messages, the settings list could arrive +// between another thread's problems and the line they belong to. +[] +let ``a report is one message, problems and all`` () = + let written = + reportedBy (fun report -> + report + "/repo/.editorconfig" + [ unknown "fsharp_wibble"; unrecognized ("fsharp_max_record_width", "banana") ]) + + match written with + | [ single ] -> + Assert.That(single, Does.Contain "fsharp_wibble") + Assert.That(single, Does.Contain "banana") + | otherwise -> Assert.Fail $"Expected one message, got %A{otherwise}" + +[] +let ``the supported settings are written at debug verbosity, once per run`` () = + let logger, collected = collectingLogger () + let report = createReporter logger + + report "/repo/one/.editorconfig" [ unknown "fsharp_wibble" ] + report "/repo/two/.editorconfig" [ unknown "fsharp_wobble" ] + + let debug = (collected ()).Debug + debug |> List.length == 1 + Assert.That(List.head debug, Does.Contain "fsharp_multiline_bracket_style") + +[] +let ``a value carrying braces is not read as a message template`` () = + // Serilog reads `{Foo}` in a message template as a property to fill in. The report is text + // someone wrote in their `.editorconfig`, so it travels as a property rather than as the + // template. + let written = + reportedBy (fun report -> report "/repo/.editorconfig" [ unrecognized ("fsharp_max_record_width", "{Origin}") ]) + + match written with + | [ single ] -> Assert.That(single, Does.Contain "{Origin}") + | otherwise -> Assert.Fail $"Expected one message, got %A{otherwise}" diff --git a/src/Fantomas.Tests/EditorConfigurationTests.fs b/src/Fantomas.Tests/EditorConfigurationTests.fs index 3131bd3efb..dac1fe54e1 100644 --- a/src/Fantomas.Tests/EditorConfigurationTests.fs +++ b/src/Fantomas.Tests/EditorConfigurationTests.fs @@ -9,7 +9,9 @@ open System.IO let private (==) (actual: 'T) (expected: 'T) = Assert.That(actual, Is.EqualTo<'T> expected) -let private silentLog: Serilog.ILogger = Serilog.Core.Logger.None +/// These tests are about what a configuration comes out as, not about what gets said about it. +/// `EditorConfigReportTests` covers the reporting. +let private ignoreProblems: EditorConfigReport.EditorConfigReporter = fun _ _ -> () let private defaultConfig = FormatConfig.Default let tempName () = Guid.NewGuid().ToString("N") @@ -104,7 +106,8 @@ let ``single configuration file`` () = use fsharpFile = new FSharpFile(rootFolderName, fsharpFileExtension = ".fs") - let config = EditorConfig.readConfiguration silentLog fsharpFile.FSharpFile + let config = + EditorConfigReport.readConfiguration ignoreProblems fsharpFile.FSharpFile config == defaultConfig @@ -121,7 +124,8 @@ let ``pointing to subfolder should return parent config file as well`` () = use fsharpFile = new FSharpFile(rootFolder, subFolder = subFolder) - let config = EditorConfig.readConfiguration silentLog fsharpFile.FSharpFile + let config = + EditorConfigReport.readConfiguration ignoreProblems fsharpFile.FSharpFile config.IndentSize == 2 @@ -142,7 +146,9 @@ let ``parent config should not be taking into account when child is root`` () = use fsharpFile = new FSharpFile(rootFolder, subFolder = subFolder) - let config = EditorConfig.readConfiguration silentLog fsharpFile.FSharpFile + let config = + EditorConfigReport.readConfiguration ignoreProblems fsharpFile.FSharpFile + config.MaxRecordWidth == defaultConfig.MaxRecordWidth config.IndentSize == 2 @@ -158,7 +164,10 @@ let ``configuration file should not affect file extension`` () = ) use fsharpFile = new FSharpFile(rootFolder, fsharpFileExtension = ".fsx") - let config = EditorConfig.readConfiguration silentLog fsharpFile.FSharpFile + + let config = + EditorConfigReport.readConfiguration ignoreProblems fsharpFile.FSharpFile + config.MaxLineLength == defaultConfig.MaxLineLength [] @@ -178,7 +187,8 @@ fsharp_max_function_binding_width=40 use fsharpFile = new FSharpFile(rootDir) - let config = EditorConfig.readConfiguration silentLog fsharpFile.FSharpFile + let config = + EditorConfigReport.readConfiguration ignoreProblems fsharpFile.FSharpFile config.MaxIfThenElseShortWidth == 25 config.MaxValueBindingWidth == 40 @@ -191,7 +201,7 @@ let ``non existing file should return defaults for readConfiguration`` () = use configFixture = new ConfigurationFile(defaultConfig, rootDir) let config = - EditorConfig.readConfiguration silentLog (Path.Join(Path.GetTempPath(), "bogus.fs")) + EditorConfigReport.readConfiguration ignoreProblems (Path.Join(Path.GetTempPath(), "bogus.fs")) config == defaultConfig @@ -226,7 +236,10 @@ tab_width=5 new ConfigurationFile(defaultConfig, rootDir, content = editorConfig) use fsharpFile = new FSharpFile(rootDir) - let config = EditorConfig.readConfiguration silentLog fsharpFile.FSharpFile + + let config = + EditorConfigReport.readConfiguration ignoreProblems fsharpFile.FSharpFile + config.IndentSize == 5 [] @@ -248,7 +261,10 @@ fsharp_max_array_or_list_number_of_items = 4 new ConfigurationFile(defaultConfig, rootDir, content = editorConfig) use fsharpFile = new FSharpFile(rootDir) - let config = EditorConfig.readConfiguration silentLog fsharpFile.FSharpFile + + let config = + EditorConfigReport.readConfiguration ignoreProblems fsharpFile.FSharpFile + config.MaxArrayOrListNumberOfItems == 4 config.ArrayOrListMultilineFormatter == NumberOfItems @@ -267,7 +283,8 @@ fsharp_max_array_or_list_width = 123 use fsharpFile = new FSharpFile(rootDir) - let config = EditorConfig.readConfiguration silentLog fsharpFile.FSharpFile + let config = + EditorConfigReport.readConfiguration ignoreProblems fsharpFile.FSharpFile config.MaxArrayOrListWidth == 123 @@ -287,7 +304,8 @@ fsharp_max_record_number_of_items = 4 use fsharpFile = new FSharpFile(rootDir) - let config = EditorConfig.readConfiguration silentLog fsharpFile.FSharpFile + let config = + EditorConfigReport.readConfiguration ignoreProblems fsharpFile.FSharpFile config.MaxRecordNumberOfItems == 4 @@ -308,7 +326,8 @@ fsharp_max_record_width = 123 use fsharpFile = new FSharpFile(rootDir) - let config = EditorConfig.readConfiguration silentLog fsharpFile.FSharpFile + let config = + EditorConfigReport.readConfiguration ignoreProblems fsharpFile.FSharpFile config.MaxRecordWidth == 123 @@ -327,7 +346,8 @@ fsharp_max_infix_operator_expression = 123 use fsharpFile = new FSharpFile(rootDir) - let config = EditorConfig.readConfiguration silentLog fsharpFile.FSharpFile + let config = + EditorConfigReport.readConfiguration ignoreProblems fsharpFile.FSharpFile config.MaxInfixOperatorExpression == 123 @@ -346,11 +366,14 @@ end_of_line = cr use fsharpFile = new FSharpFile(rootDir) - // A FormatException rather than a bare exception, because that is the type the CLI matches - // on to decide what to print. Anything else reports an empty message at normal verbosity. + // `end_of_line` is the one setting `cr` is read as a value for, and refusing it is the whole + // point: a run cannot be asked to write carriage returns. A FormatException rather than a bare + // exception, because that is the type the CLI matches on to decide what to print. Anything else + // reports an empty message at normal verbosity. let ex = Assert.Throws(fun () -> - EditorConfig.readConfiguration silentLog fsharpFile.FSharpFile |> ignore) + EditorConfigReport.readConfiguration ignoreProblems fsharpFile.FSharpFile + |> ignore) ex.Message == "Carriage returns are not valid for F# code, please use one of 'lf' or 'crlf'" @@ -374,7 +397,8 @@ end_of_line = %s use fsharpFile = new FSharpFile(rootDir) - let config = EditorConfig.readConfiguration silentLog fsharpFile.FSharpFile + let config = + EditorConfigReport.readConfiguration ignoreProblems fsharpFile.FSharpFile config.EndOfLine == eol @@ -393,7 +417,8 @@ fsharp_multi_line_lambda_closing_newline = true use fsharpFile = new FSharpFile(rootDir) - let config = EditorConfig.readConfiguration silentLog fsharpFile.FSharpFile + let config = + EditorConfigReport.readConfiguration ignoreProblems fsharpFile.FSharpFile Assert.That(config.MultiLineLambdaClosingNewline, Is.True) @@ -412,7 +437,8 @@ fsharp_experimental_keep_indent_in_branch = true use fsharpFile = new FSharpFile(rootDir) - let config = EditorConfig.readConfiguration silentLog fsharpFile.FSharpFile + let config = + EditorConfigReport.readConfiguration ignoreProblems fsharpFile.FSharpFile Assert.That(config.ExperimentalKeepIndentInBranch, Is.True) @@ -431,7 +457,8 @@ fsharp_bar_before_discriminated_union_declaration = true use fsharpFile = new FSharpFile(rootDir) - let config = EditorConfig.readConfiguration silentLog fsharpFile.FSharpFile + let config = + EditorConfigReport.readConfiguration ignoreProblems fsharpFile.FSharpFile Assert.That(config.BarBeforeDiscriminatedUnionDeclaration, Is.True) @@ -450,7 +477,8 @@ insert_final_newline = false use fsharpFile = new FSharpFile(rootDir) - let config = EditorConfig.readConfiguration silentLog fsharpFile.FSharpFile + let config = + EditorConfigReport.readConfiguration ignoreProblems fsharpFile.FSharpFile Assert.That(config.InsertFinalNewline, Is.False) @@ -469,7 +497,8 @@ fsharp_multiline_bracket_style = stroustrup use fsharpFile = new FSharpFile(rootDir) - let config = EditorConfig.readConfiguration silentLog fsharpFile.FSharpFile + let config = + EditorConfigReport.readConfiguration ignoreProblems fsharpFile.FSharpFile Assert.That(config.MultilineBracketStyle, Is.EqualTo Stroustrup) @@ -488,7 +517,8 @@ fsharp_multiline_bracket_style = aligned use fsharpFile = new FSharpFile(rootDir) - let config = EditorConfig.readConfiguration silentLog fsharpFile.FSharpFile + let config = + EditorConfigReport.readConfiguration ignoreProblems fsharpFile.FSharpFile Assert.That(config.MultilineBracketStyle, Is.EqualTo Aligned) @@ -507,7 +537,8 @@ fsharp_multiline_bracket_style = cramped use fsharpFile = new FSharpFile(rootDir) - let config = EditorConfig.readConfiguration silentLog fsharpFile.FSharpFile + let config = + EditorConfigReport.readConfiguration ignoreProblems fsharpFile.FSharpFile Assert.That(config.MultilineBracketStyle, Is.EqualTo Cramped) @@ -526,7 +557,8 @@ fsharp_newline_before_multiline_computation_expression = false use fsharpFile = new FSharpFile(rootDir) - let config = EditorConfig.readConfiguration silentLog fsharpFile.FSharpFile + let config = + EditorConfigReport.readConfiguration ignoreProblems fsharpFile.FSharpFile Assert.That(config.NewlineBeforeMultilineComputationExpression, Is.False) @@ -545,7 +577,8 @@ fsharp_experimental_elmish = true use fsharpFile = new FSharpFile(rootDir) - let config = EditorConfig.readConfiguration silentLog fsharpFile.FSharpFile + let config = + EditorConfigReport.readConfiguration ignoreProblems fsharpFile.FSharpFile Assert.That(config.ExperimentalElmish, Is.True) @@ -592,19 +625,20 @@ let ``the settings editorconfig itself defines are supported unprefixed`` () = problems == [] config.MaxLineLength == 60 +let private compareSettings (left: string) (right: string) : int = + String.Compare(left, right, StringComparison.OrdinalIgnoreCase) + [] let ``the supported settings list the editorconfig ones first, then the Fantomas ones`` () = let editorConfigOwn, fantomasOwn = EditorConfig.supportedSettings - |> List.partition (fun (setting: string) -> not (setting.StartsWith("fsharp_", StringComparison.Ordinal))) + |> List.partition (EditorConfig.isFantomasSetting >> not) editorConfigOwn == [ "end_of_line"; "indent_size"; "insert_final_newline"; "max_line_length" ] EditorConfig.supportedSettings == editorConfigOwn @ fantomasOwn - - fantomasOwn - == List.sortWith (fun left right -> String.CompareOrdinal(left, right)) fantomasOwn + fantomasOwn == List.sortWith compareSettings fantomasOwn [] let ``values the editorconfig spec defines are not reported as mistakes`` () = @@ -628,6 +662,54 @@ let ``keys are matched without regard to case`` () = problems == [] config.MaxRecordWidth == 120 +[] +let ``values are matched without regard to case as well`` () = + let config, problems = + parse + [ "fsharp_experimental_elmish", "TRUE" + "fsharp_multiline_bracket_style", "Stroustrup" + "end_of_line", "LF" ] + + problems == [] + Assert.That(config.ExperimentalElmish, Is.True) + Assert.That(config.MultilineBracketStyle, Is.EqualTo Stroustrup) + config.EndOfLine == EndOfLineStyle.LF + +[] +let ``a problem names the setting the way it was written`` () = + // The library lowercases what it reads from a file, but an editor sends its own dictionary + // through untouched, and pointing at a spelling nobody wrote helps nobody find the line. + let _, problems = + parse [ "FSHARP_Bogus_Option", "true"; "Fsharp_Max_Record_Width", "banana" ] + + problems + == [ EditorConfig.EditorConfigProblem.UnknownSetting "FSHARP_Bogus_Option" + EditorConfig.EditorConfigProblem.UnrecognizedValue("Fsharp_Max_Record_Width", "banana") ] + +// Every parser used to be tried on every setting, so a value that means something to one of them +// decided the outcome for all the others. `cr` is the one that does damage: `EndOfLineStyle` raises +// on it rather than answering, which failed the whole run with a message about line endings. +[] +let ``a value that means something to another setting is a problem, not a failure`` () = + let config, problems = parse [ "fsharp_max_record_width", "cr" ] + + problems + == [ EditorConfig.EditorConfigProblem.UnrecognizedValue("fsharp_max_record_width", "cr") ] + + config.MaxRecordWidth == defaultConfig.MaxRecordWidth + +[] +let ``a value is only read as the type its own setting has`` () = + // `stroustrup` is a bracket style and nothing else; `4` is a number and nothing else. + let _, problems = + parse + [ "fsharp_experimental_elmish", "stroustrup" + "fsharp_multiline_bracket_style", "4" ] + + problems + == [ EditorConfig.EditorConfigProblem.UnrecognizedValue("fsharp_experimental_elmish", "stroustrup") + EditorConfig.EditorConfigProblem.UnrecognizedValue("fsharp_multiline_bracket_style", "4") ] + [] let ``a value editorconfig does not define is reported, prefix or not`` () = // Only the spec vocabulary is excused. A typo in one of editorconfig's own settings is still diff --git a/src/Fantomas.Tests/Fantomas.Tests.fsproj b/src/Fantomas.Tests/Fantomas.Tests.fsproj index 74177ac991..ead029943b 100644 --- a/src/Fantomas.Tests/Fantomas.Tests.fsproj +++ b/src/Fantomas.Tests/Fantomas.Tests.fsproj @@ -26,6 +26,7 @@ + diff --git a/src/Fantomas.Tests/Integration/ConfigTests.fs b/src/Fantomas.Tests/Integration/ConfigTests.fs index 5a085ba298..2599e46e16 100644 --- a/src/Fantomas.Tests/Integration/ConfigTests.fs +++ b/src/Fantomas.Tests/Integration/ConfigTests.fs @@ -13,18 +13,14 @@ let NormalVerbosity = "--verbosity n" [] let ``config file in working directory should not require relative prefix, 821`` () = use fileFixture = - new TemporaryFileCodeSample( - "let a = // foo - 9" - ) - - use configFixture = - new ConfigurationFile( + new ConfiguredCodeSample( """ [*.fs] indent_size=2 end_of_line=lf -""" +""", + "let a = // foo + 9" ) let args = DetailedVerbosity @ [ fileFixture.Filename ] @@ -37,14 +33,13 @@ end_of_line=lf [] let ``end_of_line=cr should throw an exception`` () = - use fileFixture = new TemporaryFileCodeSample("let a = 9\n") - - use configFixture = - new ConfigurationFile( + use fileFixture = + new ConfiguredCodeSample( """ [*.fs] end_of_line=cr -""" +""", + "let a = 9\n" ) let args = DetailedVerbosity @ [ fileFixture.Filename ] @@ -64,16 +59,15 @@ let ``uses end_of_line setting to write user newlines`` setting = let sampleCode nln = sprintf "let a = 9%s%slet b = 7%s" nln nln nln - use fileFixture = new TemporaryFileCodeSample(sampleCode "\n") - - use configFixture = - new ConfigurationFile( + use fileFixture = + new ConfiguredCodeSample( sprintf """ [*.fs] end_of_line = %s """ - setting + setting, + sampleCode "\n" ) let { ExitCode = exitCode } = runFantomasTool [ fileFixture.Filename ] @@ -88,14 +82,14 @@ end_of_line = %s [] let ``end_of_line should be respected for ifdef`` () = let source = "#if FOO\n()\n#else\n()\n#endif" - use fileFixture = new TemporaryFileCodeSample(source) - use configFixture = - new ConfigurationFile( + use fileFixture = + new ConfiguredCodeSample( """ [*.fs] end_of_line = lf -""" +""", + source ) let { ExitCode = exitCode } = runFantomasTool [ fileFixture.Filename ] @@ -105,99 +99,51 @@ end_of_line = lf result |> should equal "#if FOO\n()\n#else\n()\n#endif\n" -[] -let private BadEditorConfig = - """ +// `EditorConfigReportTests` covers what a report says and when it is written. This is the one +// test that pays for a process: that the report reaches standard error rather than standard out, +// which is `Logging.createLogger`'s doing and not visible from inside the test host. +[] +let ``settings Fantomas cannot use are reported on standard error`` () = + use fileFixture = + new ConfiguredCodeSample( + """ [*.fs] fsharp_bogus_option = true fsharp_experimental_elmish = not_a_bool some_other_tool_setting = 42 -""" - -let private occurrences (needle: string) (haystack: string) : int = - haystack.Split([| needle |], System.StringSplitOptions.None).Length - 1 - -[] -let ``settings Fantomas cannot use are reported on standard error`` () = - use fileFixture = new TemporaryFileCodeSample("let a = 9\n") - use configFixture = new ConfigurationFile(BadEditorConfig) +""", + "let a = 9\n" + ) let { ExitCode = exitCode Output = output Error = error } = formatCode [ fileFixture.Filename ] + // Advice, not a failure: the file is still formatted, with defaults for what could not be read. exitCode |> should equal 0 Assert.That(error, Does.Contain "fsharp_bogus_option is not a Fantomas setting") Assert.That( error, - Does.Contain "fsharp_experimental_elmish does not accept the value not_a_bool, using the default instead" + Does.Contain "fsharp_experimental_elmish does not accept the value not_a_bool, so the default is used instead" ) - Assert.That(error, Does.Contain "supports these .editorconfig settings:") - Assert.That(error, Does.Contain "fsharp_multiline_bracket_style") // A setting without the fsharp_ prefix belongs to some other tool and is none of our business. Assert.That(error, Does.Not.Contain "some_other_tool_setting") Assert.That(output, Does.Not.Contain "fsharp_bogus_option") -[] -let ``settings Fantomas cannot use are reported once, however many files are formatted`` () = - use firstFile = new TemporaryFileCodeSample("let a = 9\n") - use secondFile = new TemporaryFileCodeSample("let b = 9\n") - use thirdFile = new TemporaryFileCodeSample("let c = 9\n") - use configFixture = new ConfigurationFile(BadEditorConfig) - - let { ExitCode = exitCode; Error = error } = - formatCode [ firstFile.Filename; secondFile.Filename; thirdFile.Filename ] - - exitCode |> should equal 0 - - occurrences "fsharp_bogus_option is not a Fantomas setting" error - |> should equal 1 - - occurrences "supports these .editorconfig settings:" error |> should equal 1 - -// Files are formatted in parallel, so the report has to leave one thread as a single message. -// Written as two, the settings list can overtake the problems it belongs to. -[] -let ``the problems come before the settings list, however many files are formatted`` () = - use firstFile = new TemporaryFileCodeSample("let a = 9\n") - use secondFile = new TemporaryFileCodeSample("let b = 9\n") - use thirdFile = new TemporaryFileCodeSample("let c = 9\n") - use fourthFile = new TemporaryFileCodeSample("let d = 9\n") - use configFixture = new ConfigurationFile(BadEditorConfig) - - let { ExitCode = exitCode; Error = error } = - formatCode - [ firstFile.Filename - secondFile.Filename - thirdFile.Filename - fourthFile.Filename ] - - exitCode |> should equal 0 - - let problemsAt = - error.IndexOf("Fantomas cannot use some settings from", System.StringComparison.Ordinal) - - let settingsAt = - error.IndexOf("supports these .editorconfig settings:", System.StringComparison.Ordinal) - - Assert.That(problemsAt, Is.GreaterThanOrEqualTo 0) - Assert.That(settingsAt, Is.GreaterThan problemsAt) - [] let ``an editorconfig Fantomas can act on reports nothing`` () = - use fileFixture = new TemporaryFileCodeSample("let a = 9\n") - - use configFixture = - new ConfigurationFile( + use fileFixture = + new ConfiguredCodeSample( """ [*.fs] max_line_length = 100 fsharp_multiline_bracket_style = stroustrup indent_style = space -""" +""", + "let a = 9\n" ) let { ExitCode = exitCode; Error = error } = formatCode [ fileFixture.Filename ] diff --git a/src/Fantomas.Tests/Integration/DaemonTests.fs b/src/Fantomas.Tests/Integration/DaemonTests.fs index f0fbc892fd..1bb96399eb 100644 --- a/src/Fantomas.Tests/Integration/DaemonTests.fs +++ b/src/Fantomas.Tests/Integration/DaemonTests.fs @@ -1,6 +1,7 @@ module Fantomas.Tests.Integration.DaemonTests open System +open Fantomas open Fantomas.Client.LSPFantomasServiceTypes open Fantomas.Daemon open NUnit.Framework @@ -28,13 +29,16 @@ let private runWithDaemon (fn: JsonRpc -> Async) : Async = (daemon :> IDisposable).Dispose() } -/// As `runWithDaemon`, but listening for the configuration warnings the daemon pushes. -/// The handler has to be attached before the client starts listening. -let private runWithDaemonCollectingWarnings (fn: JsonRpc -> Async) : Async = +/// As `runWithDaemon`, but over the given environment and listening for the configuration warnings +/// the daemon pushes. The handler has to be attached before the client starts listening. +let private runWithDaemonCollectingWarnings + (environment: DaemonEnvironment) + (fn: JsonRpc -> Async) + : Async = async { let struct (serverStream, clientStream) = FullDuplexStream.CreatePair() - let daemon = new FantomasDaemon(serverStream, serverStream, realDaemonEnvironment) + let daemon = new FantomasDaemon(serverStream, serverStream, environment) let client = new JsonRpc(clientStream, clientStream) let warnings = ResizeArray() @@ -49,22 +53,27 @@ let private runWithDaemonCollectingWarnings (fn: JsonRpc -> Async) : Async // The notification is one-way, so it can still be in flight when the response arrives. // Poll rather than sleep a fixed amount: a machine under load can take longer than any // constant we would pick here, and a test that sleeps too little fails intermittently. - let maxAttempts = 50 + // + // Waiting for the count to hold still rather than for the first one to land, so that a test + // asking for exactly one warning can tell that a second one did not follow it. + let count () = + lock warnings (fun () -> warnings.Count) - let rec waitForWarning (attempt: int) : Async = + let rec settle (attemptsLeft: int) (steadyFor: int) : Async = async { - let arrived = lock warnings (fun () -> warnings.Count > 0) + let before = count () - if arrived || attempt >= maxAttempts then + if (before > 0 && steadyFor >= 2) || attemptsLeft = 0 then return () else - do! Async.Sleep 100 - return! waitForWarning (attempt + 1) + do! Async.Sleep 50 + let steadyFor = if count () = before then steadyFor + 1 else 0 + return! settle (attemptsLeft - 1) steadyFor } try do! fn client - do! waitForWarning 0 + do! settle 100 0 finally // A failing assertion must not leave the connection and the daemon behind. client.Dispose() @@ -73,6 +82,23 @@ let private runWithDaemonCollectingWarnings (fn: JsonRpc -> Async) : Async return List.ofSeq warnings } +/// An environment that reads no `.editorconfig` at all, for a test about what the daemon does with +/// a configuration rather than about where the configuration came from. +let private noEditorConfig: DaemonEnvironment = + daemonEnvironment (new System.IO.Abstractions.FileSystem()) (fun _ -> None) + +/// The single warning the daemon sent, or a failure naming what it sent instead. +let private theOnlyWarning (warnings: ConfigurationWarning list) : ConfigurationWarning = + match warnings with + | [ warning ] -> warning + | otherwise -> + Assert.Fail $"Expected exactly one configuration warning, got %A{otherwise}" + failwith "unreachable" + +let private problemsOf (warning: ConfigurationWarning) = + warning.Problems + |> Array.map (fun problem -> problem.Code, problem.Source, problem.Setting, problem.Value) + [] let ``version request`` () = runWithDaemon (fun client -> @@ -222,9 +248,7 @@ let ``format document respecting .editorconfig file`` () = runWithDaemon (fun client -> async { let sourceCode = "module Foo\n\nlet a = //\n 4" - use codeFile = new TemporaryFileCodeSample(sourceCode) - - use _config = new ConfigurationFile("[*.fs]\nindent_size=2") + use codeFile = new ConfiguredCodeSample("[*.fs]\nindent_size=2", sourceCode) let request = { SourceCode = sourceCode @@ -253,9 +277,7 @@ let ``custom configuration has precedence over .editorconfig file`` () = runWithDaemon (fun client -> async { let sourceCode = "module Foo\n\nlet a = //\n 4" - use codeFile = new TemporaryFileCodeSample(sourceCode) - - use _config = new ConfigurationFile("[*.fs]\nindent_size=2") + use codeFile = new ConfiguredCodeSample("[*.fs]\nindent_size=2", sourceCode) let request = { SourceCode = sourceCode @@ -349,9 +371,7 @@ let ``format document with both .editorconfig file and custom config`` () = async { let sourceCode = "module Foo\n\nlet add (a:int) (b:int) = //\n a + b" - use codeFile = new TemporaryFileCodeSample(sourceCode) - - use _config = new ConfigurationFile("[*.fs]\nindent_size=2") + use codeFile = new ConfiguredCodeSample("[*.fs]\nindent_size=2", sourceCode) let request = { SourceCode = sourceCode @@ -375,75 +395,67 @@ let add (a : int) (b : int) = // | otherResponse -> Assert.Fail $"Unexpected response %A{otherResponse}" }) -[] -let ``a configuration warning is sent for settings the daemon cannot use`` () = - let sourceCode = "module Foo\n\nlet add a b = a + b" - use codeFile = new TemporaryFileCodeSample(sourceCode) - - let warnings = - runWithDaemonCollectingWarnings (fun client -> - async { - let request = - { SourceCode = sourceCode - FilePath = codeFile.Filename - Config = - Some( - readOnlyDict [ "fsharp_bogus_option", "true"; "fsharp_experimental_elmish", "not_a_bool" ] - ) - Cursor = None } +let private sourceCode = "module Foo\n\nlet add a b = a + b" - let! _response = - client.InvokeAsync(Methods.FormatDocument, request) - |> Async.AwaitTask +let private documentRequest (filePath: string) (config: (string * string) list option) : FormatDocumentRequest = + { SourceCode = sourceCode + FilePath = filePath + Config = config |> Option.map readOnlyDict + Cursor = None } - return () - }) - |> Async.RunSynchronously +/// Format one document over the given environment and collect what the daemon reported about it. +let private warningsForDocument + (environment: DaemonEnvironment) + (request: FormatDocumentRequest) + : ConfigurationWarning list = + runWithDaemonCollectingWarnings environment (fun client -> + async { + let! _response = + client.InvokeAsync(Methods.FormatDocument, request) + |> Async.AwaitTask - match warnings with - | [ warning ] -> - warning.FilePath |> should equal codeFile.Filename - - warning.Problems - |> Array.map (fun problem -> problem.Code, problem.Source, problem.Setting, problem.Value) - |> should - equal - [| int ConfigurationProblemCode.UnknownSetting, - int ConfigurationProblemSource.Request, - "fsharp_bogus_option", - null - int ConfigurationProblemCode.UnrecognizedValue, - int ConfigurationProblemSource.Request, - "fsharp_experimental_elmish", - "not_a_bool" |] - | otherwise -> Assert.Fail $"Expected exactly one configuration warning, got %A{otherwise}" + return () + }) + |> Async.RunSynchronously [] -let ``a configuration warning with no problems is sent when the configuration is fine`` () = - let sourceCode = "module Foo\n\nlet add a b = a + b" +let ``a configuration warning is sent for settings the daemon cannot use`` () = use codeFile = new TemporaryFileCodeSample(sourceCode) - let warnings = - runWithDaemonCollectingWarnings (fun client -> - async { - let request = - { SourceCode = sourceCode - FilePath = codeFile.Filename - Config = Some(readOnlyDict [ "fsharp_space_before_colon", "true" ]) - Cursor = None } + let warning = + documentRequest + codeFile.Filename + (Some [ "fsharp_bogus_option", "true"; "fsharp_experimental_elmish", "not_a_bool" ]) + |> warningsForDocument noEditorConfig + |> theOnlyWarning + + warning.FilePath |> should equal codeFile.Filename + + problemsOf warning + |> should + equal + [| int ConfigurationProblemCode.UnknownSetting, + int ConfigurationProblemSource.Request, + "fsharp_bogus_option", + null + int ConfigurationProblemCode.UnrecognizedValue, + int ConfigurationProblemSource.Request, + "fsharp_experimental_elmish", + "not_a_bool" |] - let! _response = - client.InvokeAsync(Methods.FormatDocument, request) - |> Async.AwaitTask +[] +let ``a configuration warning with no problems is sent when the configuration is fine`` () = + use codeFile = new TemporaryFileCodeSample(sourceCode) - return () - }) - |> Async.RunSynchronously + let warning = + documentRequest codeFile.Filename (Some [ "fsharp_space_before_colon", "true" ]) + |> warningsForDocument noEditorConfig + |> theOnlyWarning - // Sent even when there is nothing wrong, so a client can clear what it reported earlier. - match warnings with - | [ warning ] -> warning.Problems |> should be Empty - | otherwise -> Assert.Fail $"Expected exactly one configuration warning, got %A{otherwise}" + // Sent even when there is nothing wrong, so a client can clear what it reported earlier, and + // without the file list, which says nothing while nothing is wrong. + warning.Problems |> should be Empty + warning.EditorConfigFiles |> should be Empty // The settings an editor sends are checked the same way the ones on disk are. A mistake in them // must not disturb the response: in daemon mode standard out carries the JSON-RPC protocol, so a @@ -452,16 +464,12 @@ let ``a configuration warning with no problems is sent when the configuration is let ``format document with a custom config the daemon cannot use`` () = runWithDaemon (fun client -> async { - let sourceCode = "module Foo\n\nlet add a b = a + b" - use codeFile = new TemporaryFileCodeSample(sourceCode) let request = - { SourceCode = sourceCode - FilePath = codeFile.Filename - Config = - Some(readOnlyDict [ "fsharp_bogus_option", "true"; "fsharp_experimental_elmish", "not_a_bool" ]) - Cursor = None } + documentRequest + codeFile.Filename + (Some [ "fsharp_bogus_option", "true"; "fsharp_experimental_elmish", "not_a_bool" ]) let! response = client.InvokeAsync(Methods.FormatDocument, request) @@ -474,74 +482,112 @@ let ``format document with a custom config the daemon cannot use`` () = }) [] -let ``settings from an editorconfig on disk are reported with their source and files`` () = - let sourceCode = "module Foo\n\nlet add a b = a + b" +let ``settings read from disk are reported as coming from the editorconfig, with the files`` () = use codeFile = new TemporaryFileCodeSample(sourceCode) - use _config = - new ConfigurationFile( - """ -[*.fs] -fsharp_bogus_option = true -fsharp_experimental_elmish = not_a_bool -""" - ) + // The reading itself is `EditorConfigurationTests`' business. What matters here is that the + // daemon passes on what it was given, tagged as having come from a file rather than a request. + let readConfiguration _ : EditorConfig.EditorConfigResult option = + Some + { Config = FormatConfig.Default + EditorConfigFiles = [ "/repo/.editorconfig"; "/repo/src/.editorconfig" ] + Problems = + [ EditorConfig.EditorConfigProblem.UnknownSetting "fsharp_bogus_option" + EditorConfig.EditorConfigProblem.UnrecognizedValue("fsharp_experimental_elmish", "not_a_bool") ] } + + let environment = + daemonEnvironment (new System.IO.Abstractions.FileSystem()) readConfiguration + + let warning = + documentRequest codeFile.Filename None + |> warningsForDocument environment + |> theOnlyWarning + + problemsOf warning + |> should + equal + [| int ConfigurationProblemCode.UnknownSetting, + int ConfigurationProblemSource.EditorConfig, + "fsharp_bogus_option", + null + int ConfigurationProblemCode.UnrecognizedValue, + int ConfigurationProblemSource.EditorConfig, + "fsharp_experimental_elmish", + "not_a_bool" |] + + // The files that contributed, so a client can point the user at them. + warning.EditorConfigFiles + |> should equal [| "/repo/.editorconfig"; "/repo/src/.editorconfig" |] + +[] +let ``the editorconfig on disk and the request are reported side by side`` () = + use codeFile = new TemporaryFileCodeSample(sourceCode) + + let readConfiguration _ : EditorConfig.EditorConfigResult option = + Some + { Config = FormatConfig.Default + EditorConfigFiles = [ "/repo/.editorconfig" ] + Problems = [ EditorConfig.EditorConfigProblem.UnknownSetting "fsharp_from_the_file" ] } + + let environment = + daemonEnvironment (new System.IO.Abstractions.FileSystem()) readConfiguration + + let warning = + documentRequest codeFile.Filename (Some [ "fsharp_from_the_request", "true" ]) + |> warningsForDocument environment + |> theOnlyWarning + + warning.Problems + |> Array.map (fun problem -> problem.Setting, problem.Source) + |> should + equal + [| "fsharp_from_the_file", int ConfigurationProblemSource.EditorConfig + "fsharp_from_the_request", int ConfigurationProblemSource.Request |] + +[] +let ``a request setting is reported the way the editor spelled it`` () = + use codeFile = new TemporaryFileCodeSample(sourceCode) + + let warning = + documentRequest codeFile.Filename (Some [ "FSHARP_Bogus_Option", "true" ]) + |> warningsForDocument noEditorConfig + |> theOnlyWarning + + warning.Problems + |> Array.map (fun problem -> problem.Setting) + |> should equal [| "FSHARP_Bogus_Option" |] + +// Reading the configuration can raise rather than come back with a problem. The client hears about +// that as an Error response, and still gets a warning, so it does not keep showing what the +// previous request left it with. +[] +let ``a configuration that cannot be read at all is an error, and clears the warning`` () = + use codeFile = new TemporaryFileCodeSample(sourceCode) let warnings = - runWithDaemonCollectingWarnings (fun client -> + runWithDaemonCollectingWarnings noEditorConfig (fun client -> async { - let request = - { SourceCode = sourceCode - FilePath = codeFile.Filename - Config = None - Cursor = None } + let request = documentRequest codeFile.Filename (Some [ "end_of_line", "cr" ]) - let! _response = + let! response = client.InvokeAsync(Methods.FormatDocument, request) |> Async.AwaitTask - return () + match response with + | FormatDocumentResponse.Error(_, message) -> + Assert.That(message, Does.Contain "Carriage returns are not valid") + | otherResponse -> Assert.Fail $"Unexpected response %A{otherResponse}" }) |> Async.RunSynchronously - match warnings with - | [ warning ] -> - warning.Problems - |> Array.map (fun problem -> problem.Code, problem.Source, problem.Setting, problem.Value) - |> should - equal - [| int ConfigurationProblemCode.UnknownSetting, - int ConfigurationProblemSource.EditorConfig, - "fsharp_bogus_option", - null - int ConfigurationProblemCode.UnrecognizedValue, - int ConfigurationProblemSource.EditorConfig, - "fsharp_experimental_elmish", - "not_a_bool" |] - - // The paths of the files that contributed, so a client can point the user at them. - Assert.That(warning.EditorConfigFiles, Is.Not.Empty) - - Assert.That( - warning.EditorConfigFiles - |> Array.forall (fun file -> - System.IO.Path.IsPathRooted file - && file.EndsWith(".editorconfig", System.StringComparison.Ordinal)), - Is.True, - $"Expected absolute .editorconfig paths, got %A{warning.EditorConfigFiles}" - ) - - // Not just any .editorconfig: the one this test wrote. - Assert.That(warning.EditorConfigFiles, Does.Contain _config.Filename) - | otherwise -> Assert.Fail $"Expected exactly one configuration warning, got %A{otherwise}" + (theOnlyWarning warnings).Problems |> should be Empty [] let ``format selection reports configuration warnings too`` () = - let sourceCode = "module Foo\n\nlet add a b = a + b" use codeFile = new TemporaryFileCodeSample(sourceCode) let warnings = - runWithDaemonCollectingWarnings (fun client -> + runWithDaemonCollectingWarnings noEditorConfig (fun client -> async { let request = { SourceCode = sourceCode @@ -557,46 +603,28 @@ let ``format selection reports configuration warnings too`` () = }) |> Async.RunSynchronously - match warnings with - | [ warning ] -> - warning.Problems - |> Array.map (fun problem -> problem.Code, problem.Setting) - |> should equal [| int ConfigurationProblemCode.UnknownSetting, "fsharp_bogus_option" |] - | otherwise -> Assert.Fail $"Expected exactly one configuration warning, got %A{otherwise}" + (theOnlyWarning warnings).Problems + |> Array.map (fun problem -> problem.Code, problem.Setting) + |> should equal [| int ConfigurationProblemCode.UnknownSetting, "fsharp_bogus_option" |] [] let ``an ignored file still reports an empty configuration warning`` () = - let sourceCode = "let foo = 4" + let fs = System.IO.Abstractions.TestingHelpers.MockFileSystem() + let root = mockRoot fs + let ignoredFile = fs.Path.Combine(root, "warned", "Ignored.fs") - use codeFile = - new TemporaryFileCodeSample(sourceCode, fileName = "Ignored", subFolders = [| "warned" |]) + makeFileHierarchy fs [ ignoredFile ] + fs.File.WriteAllText(fs.Path.Combine(root, IgnoreFile.IgnoreFileName), "warned/Ignored.fs") - use _ignoreFixture = new FantomasIgnoreFile("warned/Ignored.fs") - - let warnings = - runWithDaemonCollectingWarnings (fun client -> - async { - let request = - { SourceCode = sourceCode - FilePath = codeFile.Filename - Config = None - Cursor = None } - - let! _response = - client.InvokeAsync(Methods.FormatDocument, request) - |> Async.AwaitTask - - return () - }) - |> Async.RunSynchronously + let warning = + documentRequest ignoredFile None + |> warningsForDocument (daemonEnvironment fs (fun _ -> None)) + |> theOnlyWarning // Reported even though nothing was formatted, so a client can clear a warning it showed for // this file before the user added it to .fantomasignore. - match warnings with - | [ warning ] -> - warning.FilePath |> should equal codeFile.Filename - warning.Problems |> should be Empty - | otherwise -> Assert.Fail $"Expected exactly one configuration warning, got %A{otherwise}" + warning.FilePath |> should equal ignoredFile + warning.Problems |> should be Empty [] let ``format nested ignored file`` () = diff --git a/src/Fantomas.Tests/TestHelpers.fs b/src/Fantomas.Tests/TestHelpers.fs index 14720881b9..5f48814817 100644 --- a/src/Fantomas.Tests/TestHelpers.fs +++ b/src/Fantomas.Tests/TestHelpers.fs @@ -95,16 +95,30 @@ type OutputFolder internal () = if Directory.Exists(foldername) then Directory.Delete(foldername, true) -type ConfigurationFile internal (content: string) = - let filename = Path.Join(Path.GetTempPath(), ".editorconfig") +/// A folder of its own, holding an `.editorconfig` and one F# file it applies to. +/// +/// A test that reads configuration from disk needs the two next to each other, and +/// `ConfigurationFile` writes its `.editorconfig` straight into the temp folder, where every other +/// test doing the same finds it. `root = true` goes in front of the content so the chain stops +/// here rather than picking up whatever sits above the temp folder on this machine. +type ConfiguredCodeSample internal (editorConfig: string, codeSnippet: string, ?extension: string) = + let folder = Path.Join(Path.GetTempPath(), Guid.NewGuid().ToString("N")) + do Directory.CreateDirectory folder |> ignore + + let editorConfigFile = Path.Join(folder, ".editorconfig") + + let filename = + Path.Join(folder, sprintf "File.%s" (Option.defaultValue "fs" extension)) + + do + File.WriteAllText(editorConfigFile, "root = true\n" + editorConfig) + File.WriteAllText(filename, codeSnippet) - do File.WriteAllText(filename, content) member _.Filename: string = filename + member _.EditorConfigFile: string = editorConfigFile interface IDisposable with - member this.Dispose() : unit = - if File.Exists(filename) then - File.Delete(filename) + member this.Dispose() : unit = Directory.Delete(folder, true) type FantomasIgnoreFile internal (content: string) = let filename = Path.Join(Path.GetTempPath(), IgnoreFile.IgnoreFileName) @@ -222,6 +236,14 @@ let defaultSettings: CliSettings = Profile = false Verbosity = VerbosityLevel.Normal } +/// A `DaemonEnvironment` over the given file system, reading whatever configuration is handed in +/// rather than an `.editorconfig` on disk. Enough for a test about what the daemon does with a +/// configuration, as opposed to one about where the configuration came from. +let daemonEnvironment (fs: IFileSystem) (readConfiguration: string -> EditorConfig.EditorConfigResult option) = + { FileSystem = fs + ReadConfiguration = readConfiguration + Log = silentLogger } + /// A `DaemonEnvironment` over the real file system, as the tool itself builds one. let realDaemonEnvironment: DaemonEnvironment = { FileSystem = FileSystem() @@ -233,7 +255,7 @@ let realDaemonEnvironment: DaemonEnvironment = let realEnvironment: CliEnvironment = { FileSystem = FileSystem() IgnoreFile = None - ReadConfiguration = EditorConfig.readConfiguration Log.Logger + ReadConfiguration = EditorConfigReport.readConfiguration (EditorConfigReport.createReporter Log.Logger) Log = Log.Logger Console = AnsiConsole.Console } diff --git a/src/Fantomas/Daemon.fs b/src/Fantomas/Daemon.fs index 5dad7949c9..a1aa23a1c9 100644 --- a/src/Fantomas/Daemon.fs +++ b/src/Fantomas/Daemon.fs @@ -36,14 +36,6 @@ let toConfigurationProblem (source: ConfigurationProblemSource) (problem: Editor Setting = setting Value = value } -/// Resolve the configuration for a request the way the daemon needs it: the `.editorconfig` on -/// disk, then whatever the editor sent layered on top, keeping the problems from both. -/// -/// Deliberately silent: the problems travel to the client as a notification and are never written -/// to standard error. `Fantomas.Client` drains the daemon's standard error, but an older client -/// does not, and anything written there then accumulates in a pipe nobody reads. A report is -/// around 1.5KB and the default pipe buffer on Windows is 4KB, so a few of them would block the -/// write inside a format request and hang the connection. let configurationFor (readConfiguration: string -> EditorConfigResult option) (filePath: string) @@ -64,10 +56,23 @@ let configurationFor let config, problems = parseOptionsFromEditorConfig config properties config, List.map (toConfigurationProblem ConfigurationProblemSource.Request) problems + let problems = List.toArray (fromEditorConfig @ fromRequest) + config, { FilePath = filePath - EditorConfigFiles = Array.ofList editorConfigFiles - Problems = List.toArray (fromEditorConfig @ fromRequest) } + // Only worth sending when there is something to point at. It is the same list on every + // request for a file, and a client has nothing to do with it while nothing is wrong. + EditorConfigFiles = + if Array.isEmpty problems then + Array.empty + else + Array.ofList editorConfigFiles + Problems = problems } + +let noConfigurationProblems (filePath: string) : ConfigurationWarning = + { FilePath = filePath + EditorConfigFiles = Array.empty + Problems = Array.empty } type FantomasDaemon(sender: Stream, reader: Stream, environment: DaemonEnvironment) as this = let rpc: JsonRpc = JsonRpc.Attach(sender, reader, this) @@ -120,11 +125,7 @@ type FantomasDaemon(sender: Stream, reader: Stream, environment: DaemonEnvironme then // Still reported, with nothing in it, so a client can clear what an earlier request // showed for this file rather than leaving a stale warning behind. - do! - notifyConfigurationWarning - { FilePath = request.FilePath - EditorConfigFiles = Array.empty - Problems = Array.empty } + do! notifyConfigurationWarning (noConfigurationProblems request.FilePath) return FormatDocumentResponse.IgnoredFile request.FilePath else @@ -132,15 +133,25 @@ type FantomasDaemon(sender: Stream, reader: Stream, environment: DaemonEnvironme request.Cursor |> Option.map (fun cursor -> CodeFormatter.MakePosition(cursor.Line, cursor.Column)) + // Whether the warning that belongs to this request has gone out yet. Reading the + // configuration can raise rather than come back with a problem, `end_of_line = cr` + // being the one that does, and then nothing has been sent and the client is still + // showing whatever the previous request left it with. + let warningSent = ref false + try - // Reading the configuration belongs inside this: an `.editorconfig` can carry a - // value that raises rather than becoming a problem, `end_of_line = cr` among - // them, and the client should hear about that as an Error response like any - // other failure, not as a remote invocation exception. + // Reading the configuration belongs inside this: the client should hear about a + // value that raises as an Error response like any other failure, not as a + // remote invocation exception. let config, warning = configurationFor environment.ReadConfiguration request.FilePath request.Config - do! notifyConfigurationWarning warning + // Started here rather than awaited here. The write is not on the way to a + // formatted document, but it has to have finished before the response goes out, + // so that a client never sees the answer to a request before the warning that + // belongs to it. + let notified = notifyConfigurationWarning warning + warningSent.Value <- true let! formatResponse = match cursor with @@ -153,6 +164,8 @@ type FantomasDaemon(sender: Stream, reader: Stream, environment: DaemonEnvironme cursor ) + do! notified + if formatResponse.Code = request.SourceCode then return FormatDocumentResponse.Unchanged request.FilePath else @@ -162,6 +175,9 @@ type FantomasDaemon(sender: Stream, reader: Stream, environment: DaemonEnvironme return FormatDocumentResponse.Formatted(request.FilePath, formatResponse.Code, cursor) with ex -> + if not warningSent.Value then + do! notifyConfigurationWarning (noConfigurationProblems request.FilePath) + // A ParseException's own Message is an %A dump of the diagnostic records, and // it is the editor's user who would have been shown it. let message = @@ -182,17 +198,22 @@ type FantomasDaemon(sender: Stream, reader: Stream, environment: DaemonEnvironme (Position.mkPos r.StartLine r.StartColumn) (Position.mkPos r.EndLine r.EndColumn) + let warningSent = ref false + try // Inside the try for the same reason as FormatDocumentAsync: a configuration value // that raises has to reach the client as an Error response. let config, warning = configurationFor environment.ReadConfiguration request.FilePath request.Config - do! notifyConfigurationWarning warning + let notified = notifyConfigurationWarning warning + warningSent.Value <- true let! formatted, actualSelection = CodeFormatter.FormatSelectionAsync(request.IsSignatureFile, request.SourceCode, selection, config) + do! notified + let actualSelection = FormatSelectionRange( actualSelection.StartLine, @@ -203,6 +224,9 @@ type FantomasDaemon(sender: Stream, reader: Stream, environment: DaemonEnvironme return FormatSelectionResponse.Formatted(request.FilePath, formatted, actualSelection) with ex -> + if not warningSent.Value then + do! notifyConfigurationWarning (noConfigurationProblems request.FilePath) + let message = Diagnostics.describeParseFailure request.FilePath (fun () -> request.SourceCode) ex |> Option.defaultValue ex.Message diff --git a/src/Fantomas/Daemon.fsi b/src/Fantomas/Daemon.fsi index d8099ba26f..ec1f3dc4e4 100644 --- a/src/Fantomas/Daemon.fsi +++ b/src/Fantomas/Daemon.fsi @@ -24,6 +24,21 @@ type DaemonEnvironment = Log: ILogger } +/// Resolve the configuration for a request the way the daemon needs it: the `.editorconfig` on +/// disk, then whatever the editor sent layered on top, keeping the problems from both and tagging +/// each with where it came from. +/// +/// Deliberately silent: the warning it returns travels to the client as a notification and is never +/// written to standard error, which `Fantomas.Client` redirects. +val configurationFor: + readConfiguration: (string -> EditorConfigResult option) -> + filePath: string -> + requestConfig: System.Collections.Generic.IReadOnlyDictionary option -> + FormatConfig * ConfigurationWarning + +/// A warning with nothing in it, which tells a client to clear whatever it showed for this file. +val noConfigurationProblems: filePath: string -> ConfigurationWarning + type FantomasDaemon = interface IDisposable diff --git a/src/Fantomas/EditorConfig.fs b/src/Fantomas/EditorConfig.fs index 93200493e6..51b9cab981 100644 --- a/src/Fantomas/EditorConfig.fs +++ b/src/Fantomas/EditorConfig.fs @@ -1,11 +1,9 @@ module Fantomas.EditorConfig -open System.Collections.Concurrent open System.Collections.Generic open System.ComponentModel open EditorConfig.Core open Fantomas.Core -open Serilog module Reflection = open System @@ -54,36 +52,41 @@ let toEditorConfigName value = else $"fsharp_%s{name}" -let getFantomasFields (fallbackConfig: FormatConfig) = - Reflection.getRecordFields fallbackConfig - |> Array.map (fun (recordField, defaultValue) -> - let editorConfigName = toEditorConfigName recordField.PropertyName - - (editorConfigName, defaultValue)) - -[] -let (|Number|_|) (d: string) : obj voption = - match System.Int32.TryParse(d) with - | true, d -> ValueSome(box d) - | _ -> ValueNone - -[] -let (|MultilineFormatterType|_|) (mft: string) : MultilineFormatterType voption = - MultilineFormatterType.OfConfigString mft |> ValueOption.ofOption - -[] -let (|BracketStyle|_|) (bs: string) : MultilineBracketStyle voption = - MultilineBracketStyle.OfConfigString bs |> ValueOption.ofOption - -[] -let (|EndOfLineStyle|_|) (eol: string) : EndOfLineStyle voption = - EndOfLineStyle.OfConfigString eol |> ValueOption.ofOption +/// The editorconfig name of every `FormatConfig` field, in record field order. Worked out once: +/// the names cannot change while the process runs, and `parseOptionsFromEditorConfig` runs for +/// every file that gets formatted. +let settingNames: string array = + Microsoft.FSharp.Reflection.FSharpType.GetRecordFields(typeof) + |> Array.map (fun property -> toEditorConfigName property.Name) + +/// Every field of `fallbackConfig`, paired with the editorconfig name it is written under. +let getFantomasFields (fallbackConfig: FormatConfig) : (string * obj) array = + Microsoft.FSharp.Reflection.FSharpValue.GetRecordFields fallbackConfig + |> Array.zip settingNames + +/// Read one setting's value into the type the matching `FormatConfig` field has. Which parser +/// applies is decided by that type rather than by trying each of them in turn: `cr` means +/// something to `end_of_line` and nothing to any other setting, and trying every parser on every +/// setting made `fsharp_max_record_width = cr` fail the whole run with a message about line +/// endings. +/// +/// Values are matched without regard to case, as editorconfig defines them. +let parseSettingValue (defaultValue: obj) (value: string) : obj option = + let value = value.ToLowerInvariant() -[] -let (|Boolean|_|) (b: string) : obj voption = - if b = "true" then ValueSome(box true) - elif b = "false" then ValueSome(box false) - else ValueNone + match defaultValue with + | :? int -> + match System.Int32.TryParse(value) with + | true, number -> Some(box number) + | _ -> None + | :? bool -> + if value = "true" then Some(box true) + elif value = "false" then Some(box false) + else None + | :? MultilineFormatterType -> MultilineFormatterType.OfConfigString value |> Option.map box + | :? EndOfLineStyle -> EndOfLineStyle.OfConfigString value |> Option.map box + | :? MultilineBracketStyle -> MultilineBracketStyle.OfConfigString value |> Option.map box + | _ -> None [] type EditorConfigProblem = @@ -97,7 +100,7 @@ type EditorConfigResult = Problems: EditorConfigProblem list } let isFantomasSetting (setting: string) : bool = - setting.StartsWith("fsharp_", System.StringComparison.Ordinal) + setting.StartsWith("fsharp_", System.StringComparison.OrdinalIgnoreCase) /// Values the editorconfig spec gives a meaning that is not a value. `unset` says a setting from /// a parent file no longer applies, `indent_size = tab` says to follow `tab_width`, and @@ -114,23 +117,31 @@ let isSpecDefinedNonValue (setting: string) (value: string) : bool = || (setting = "indent_size" && value = "tab") || (setting = "max_line_length" && value = "off") +/// Settings are ordered the same way everywhere here: without regard to case, as they are matched. +let compareSettings (left: string) (right: string) : int = + System.String.Compare(left, right, System.StringComparison.OrdinalIgnoreCase) + let supportedSettings: string list = - getFantomasFields FormatConfig.Default - |> Array.map fst + settingNames |> List.ofArray |> List.sortWith (fun left right -> // The settings editorconfig itself defines come first, then the ones belonging to - // Fantomas, each group ordered the same way everywhere else here: by ordinal. + // Fantomas, each group ordered the same way everywhere else here. match compare (isFantomasSetting left) (isFantomasSetting right) with - | 0 -> System.String.CompareOrdinal(left, right) + | 0 -> compareSettings left right | difference -> difference) -let unknownFantomasSettings (editorConfigProperties: IReadOnlyDictionary) : EditorConfigProblem list = - editorConfigProperties.Keys +/// The same names again, for looking one up rather than reading the list. A `.editorconfig` is +/// read once per formatted file, so a scan of the whole list per setting is worth avoiding. +let supportedSettingLookup: HashSet = + HashSet(settingNames, System.StringComparer.OrdinalIgnoreCase) + +let unknownFantomasSettings (settings: string seq) : EditorConfigProblem list = + settings |> Seq.filter isFantomasSetting - |> Seq.sortWith (fun left right -> System.String.CompareOrdinal(left, right)) + |> Seq.sortWith compareSettings |> Seq.choose (fun setting -> - if List.contains setting supportedSettings then + if supportedSettingLookup.Contains setting then None else Some(EditorConfigProblem.UnknownSetting setting)) @@ -141,81 +152,47 @@ let parseOptionsFromEditorConfig (editorConfigProperties: IReadOnlyDictionary) : FormatConfig * EditorConfigProblem list = // editorconfig keys are case insensitive. The library lowercases the ones it reads from a - // file, but nothing lowercases a dictionary handed straight to us, so do it here rather than - // in one caller: a key that differs only in case would otherwise match no setting and raise - // no warning either. Folding keeps the last write, which is what editorconfig does when a - // file sets the same key twice. - let editorConfigProperties = - editorConfigProperties - |> Seq.fold (fun acc setting -> Map.add (setting.Key.ToLowerInvariant()) setting.Value acc) Map.empty - |> Seq.map (fun setting -> setting.Key, setting.Value) - |> readOnlyDict + // file, but a dictionary an editor hands us is untouched, so match without regard to case + // here rather than in one caller: a key that differs only in case would otherwise match no + // setting and raise no warning either. Each entry carries the spelling it was written with, + // so a problem names what the author typed rather than the folded form. + let properties = + let properties = + Dictionary(System.StringComparer.OrdinalIgnoreCase) + + for setting in editorConfigProperties do + properties[setting.Key] <- struct (setting.Key, setting.Value) + + properties let unrecognizedValues = ResizeArray() let newValues = getFantomasFields fallbackConfig - |> Array.map (fun (editorConfigName, defaultValue) -> - match editorConfigProperties.TryGetValue(editorConfigName) with - | true, Number n -> n - | true, Boolean b -> b - | true, MultilineFormatterType mft -> box mft - | true, EndOfLineStyle eol -> box eol - | true, BracketStyle bs -> box bs + |> Array.map (fun (setting, defaultValue) -> + match properties.TryGetValue setting with | false, _ -> defaultValue - | true, invalidValue -> - if not (isSpecDefinedNonValue editorConfigName invalidValue) then - unrecognizedValues.Add(editorConfigName, invalidValue) + | true, struct (written, value) -> + match parseSettingValue defaultValue value with + | Some parsed -> parsed + | None -> + if not (isSpecDefinedNonValue setting value) then + unrecognizedValues.Add(written, value) - defaultValue) - - let formatConfigType = FormatConfig.Default.GetType() + defaultValue) let config = - Microsoft.FSharp.Reflection.FSharpValue.MakeRecord(formatConfigType, newValues) :?> FormatConfig + Microsoft.FSharp.Reflection.FSharpValue.MakeRecord(typeof, newValues) :?> FormatConfig let unrecognized = unrecognizedValues - |> Seq.sortWith (fun (left, _) (right, _) -> System.String.CompareOrdinal(left, right)) + |> Seq.sortWith (fun (left, _) (right, _) -> compareSettings left right) |> Seq.map EditorConfigProblem.UnrecognizedValue |> Seq.toList - config, unknownFantomasSettings editorConfigProperties @ unrecognized - -/// The version without the commit hash `CodeFormatter.GetVersion` appends, so that the -/// settings a user is being pointed at are tied to a version they can act on. -let fantomasVersion: string = - let version = CodeFormatter.GetVersion() - - match version.IndexOf('+') with - | -1 -> version - | index -> version.Substring(0, index) - -/// Every report already written, for the lifetime of the process. Never cleared: the command line -/// reads the same `.editorconfig` again for every file it formats, and this is what keeps one typo -/// from being reported once per file. The daemon does not report through here at all. -let reportedWarnings = ConcurrentDictionary() - -let warnOnce (log: ILogger) (message: string) : unit = - if reportedWarnings.TryAdd(message, ()) then - log.Warning message - -let reportProblems (log: ILogger) (origin: string) (problems: EditorConfigProblem list) : unit = - if not (List.isEmpty problems) then - [ yield "" - yield $"Fantomas cannot use some settings from %s{origin}:" - for problem in problems do - match problem with - | EditorConfigProblem.UnknownSetting setting -> yield $" %s{setting} is not a Fantomas setting" - | EditorConfigProblem.UnrecognizedValue(setting, value) -> - yield $" %s{setting} does not accept the value %s{value}, using the default instead" - yield "" - yield $"Current fantomas version (%s{fantomasVersion}) supports these .editorconfig settings:" - for setting in supportedSettings do - yield $" %s{setting}" - yield "" ] - |> String.concat System.Environment.NewLine - |> warnOnce log + let written = properties.Values |> Seq.map (fun (struct (written, _)) -> written) + + config, unknownFantomasSettings written @ unrecognized let configToEditorConfig (config: FormatConfig) : string = Reflection.getRecordFields config @@ -258,15 +235,3 @@ let tryReadConfiguration (fsharpFile: string) : EditorConfigResult option = { Config = config EditorConfigFiles = editorConfigFiles Problems = problems } - -let readConfiguration (log: ILogger) (fsharpFile: string) : FormatConfig = - match tryReadConfiguration fsharpFile with - | None -> FormatConfig.Default - | Some result -> - let origin = - match result.EditorConfigFiles with - | [] -> fsharpFile - | files -> String.concat ", " files - - reportProblems log origin result.Problems - result.Config diff --git a/src/Fantomas/EditorConfig.fsi b/src/Fantomas/EditorConfig.fsi index f92e6982c9..abd213cd24 100644 --- a/src/Fantomas/EditorConfig.fsi +++ b/src/Fantomas/EditorConfig.fsi @@ -1,6 +1,5 @@ module Fantomas.EditorConfig -open Serilog open Fantomas.Core module Reflection = @@ -35,20 +34,26 @@ type EditorConfigResult = EditorConfigFiles: string list /// The settings that could not be acted on. Not reported anywhere by the time you get - /// them: `readConfiguration` warns about them, the daemon sends them to its client. + /// them: `EditorConfigReport.readConfiguration` warns about them, the daemon sends them + /// to its client. Problems: EditorConfigProblem list } /// Every .editorconfig setting this build of Fantomas understands, in the order they are worth /// reading: the settings editorconfig itself defines first, then the ones belonging to Fantomas, -/// each group in ordinal order. The former keep their upstream names and are not prefixed, the -/// latter all carry the `fsharp_` prefix. +/// each group ordered without regard to case. The former keep their upstream names and are not +/// prefixed, the latter all carry the `fsharp_` prefix. val supportedSettings: string list +/// Whether a setting belongs to Fantomas rather than to editorconfig itself or to another tool. +/// Matched without regard to case, as editorconfig matches keys. +val isFantomasSetting: setting: string -> bool + /// Read a `FormatConfig` from editorconfig properties, falling back to `fallbackConfig` for -/// anything the properties do not set. Keys are matched without regard to case, and when two of -/// them fold onto one the last wins, as editorconfig does. Returns the settings it could not act -/// on alongside the configuration, so the caller can decide whether and how to report them. +/// anything the properties do not set. Keys and values are both matched without regard to case, +/// as editorconfig defines them, and when two keys fold onto one the last wins. Returns the +/// settings it could not act on alongside the configuration, each named the way it was written, +/// so the caller can decide whether and how to report them. val parseOptionsFromEditorConfig: fallbackConfig: FormatConfig -> editorConfigProperties: System.Collections.Generic.IReadOnlyDictionary -> @@ -59,12 +64,6 @@ val configToEditorConfig: config: FormatConfig -> string /// Read the `.editorconfig` chain that applies to a file. `None` when no `.editorconfig` sets /// anything for it. /// -/// Silent: the problems are returned rather than reported. `readConfiguration` warns about them; -/// the daemon sends them to its client instead and must not write them to standard error, which -/// `Fantomas.Client` redirects and never drains. +/// Silent, and this module writes nothing anywhere: `EditorConfigReport` turns the problems into +/// something a person reads, and the daemon sends them to its client instead. val tryReadConfiguration: fsharpFile: string -> EditorConfigResult option - -/// Read the `.editorconfig` that applies to a file and warn through `log` about anything in it -/// Fantomas cannot use. The daemon does not go through here: it sends the problems to its client -/// instead, and must not write them to standard error. -val readConfiguration: log: ILogger -> fsharpFile: string -> FormatConfig diff --git a/src/Fantomas/EditorConfigReport.fs b/src/Fantomas/EditorConfigReport.fs new file mode 100644 index 0000000000..b4f8e602fc --- /dev/null +++ b/src/Fantomas/EditorConfigReport.fs @@ -0,0 +1,145 @@ +module Fantomas.EditorConfigReport + +open System +open System.Collections.Concurrent +open Serilog +open Serilog.Events +open Fantomas.Core +open Fantomas.EditorConfig + +type EditorConfigReporter = string -> EditorConfigProblem list -> unit + +let fantomasVersion: string = + let version = CodeFormatter.GetVersion() + + match version.IndexOf('+') with + | -1 -> version + | index -> version.Substring(0, index) + +/// How many single character edits turn one setting name into the other, capped at `limit` so a +/// name nothing like any of ours stops being measured early rather than walking every candidate +/// to the end. +let editDistance (limit: int) (left: string) (right: string) : int = + if abs (left.Length - right.Length) > limit then + limit + 1 + else + let mutable previous = Array.init (right.Length + 1) id + let mutable current = Array.zeroCreate (right.Length + 1) + + for row in 1 .. left.Length do + current[0] <- row + + for column in 1 .. right.Length do + let substitution = + previous[column - 1] + (if left[row - 1] = right[column - 1] then 0 else 1) + + current[column] <- min (min (current[column - 1] + 1) (previous[column] + 1)) substitution + + let swap = previous + previous <- current + current <- swap + + min previous[right.Length] (limit + 1) + +/// Close enough that naming the other one is help rather than noise. Three edits is roughly a +/// doubled letter, a dropped one and a swapped pair; beyond that the guess is worse than silence. +[] +let MaximumSuggestionDistance = 3 + +let suggestionFor (setting: string) : string option = + let setting = setting.ToLowerInvariant() + + // The mistake worth answering outright: the four settings editorconfig itself defines are the + // ones a user reaches for the prefix on, and they are exactly the ones where it does not + // belong. `fsharp_max_line_length` never applied, `max_line_length` is the one that does. + let unprefixed = + if isFantomasSetting setting then + Some(setting.Substring "fsharp_".Length) + else + None + + match unprefixed with + | Some unprefixed when List.contains unprefixed supportedSettings -> Some unprefixed + | _ -> + supportedSettings + |> List.choose (fun candidate -> + match editDistance MaximumSuggestionDistance setting candidate with + | distance when distance <= MaximumSuggestionDistance -> Some(candidate, distance) + | _ -> None) + |> List.sortBy snd + |> List.tryHead + |> Option.map fst + +let describeProblem (problem: EditorConfigProblem) : string = + match problem with + | EditorConfigProblem.UnknownSetting setting -> + match suggestionFor setting with + | Some suggestion -> $" %s{setting} is not a Fantomas setting. Did you mean %s{suggestion}?" + | None -> $" %s{setting} is not a Fantomas setting." + | EditorConfigProblem.UnrecognizedValue(setting, value) -> + $" %s{setting} does not accept the value %s{value}, so the default is used instead." + +let describe (origin: string) (problems: EditorConfigProblem list) : string option = + if List.isEmpty problems then + None + else + let namesAnyUnknownSetting = + problems + |> List.exists (fun problem -> + match problem with + | EditorConfigProblem.UnknownSetting _ -> true + | EditorConfigProblem.UnrecognizedValue _ -> false) + + [ yield "" + yield $"Fantomas cannot use some settings from %s{origin}:" + for problem in problems do + yield describeProblem problem + if namesAnyUnknownSetting then + yield + $"Run fantomas with --verbosity d to see every .editorconfig setting fantomas %s{fantomasVersion} supports." + yield "" ] + |> String.concat Environment.NewLine + |> Some + +let describeSupportedSettings () : string = + [ yield "" + yield $"fantomas %s{fantomasVersion} supports these .editorconfig settings:" + for setting in supportedSettings do + yield $" %s{setting}" + yield "" ] + |> String.concat Environment.NewLine + +let createReporter (log: ILogger) : EditorConfigReporter = + // Files are formatted in parallel, so more than one of them can arrive here at once. The whole + // report is one message rather than a line each: written as several, another thread's report + // can land in the middle of this one. + let reported = ConcurrentDictionary() + let supportedSettingsWritten = ref 0 + + fun origin problems -> + match describe origin problems with + | None -> () + | Some report -> + if reported.TryAdd(report, ()) then + // The report carries what someone wrote in their `.editorconfig`, so it travels as + // a property rather than as the message template: a `{` in a value would otherwise + // be read as the start of one. + log.Warning("{EditorConfigReport}", report) + + if + log.IsEnabled LogEventLevel.Debug + && Threading.Interlocked.Exchange(&supportedSettingsWritten.contents, 1) = 0 + then + log.Debug("{SupportedEditorConfigSettings}", describeSupportedSettings ()) + +let readConfiguration (report: EditorConfigReporter) (fsharpFile: string) : FormatConfig = + match tryReadConfiguration fsharpFile with + | None -> FormatConfig.Default + | Some result -> + let origin = + match result.EditorConfigFiles with + | [] -> fsharpFile + | files -> String.concat ", " files + + report origin result.Problems + result.Config diff --git a/src/Fantomas/EditorConfigReport.fsi b/src/Fantomas/EditorConfigReport.fsi new file mode 100644 index 0000000000..0a853d196f --- /dev/null +++ b/src/Fantomas/EditorConfigReport.fsi @@ -0,0 +1,41 @@ +module Fantomas.EditorConfigReport + +open Serilog +open Fantomas.Core +open Fantomas.EditorConfig + +/// Writes what Fantomas could not use out of the `.editorconfig` chain named by the first +/// argument. Each reporter keeps its own record of what it has already written. +type EditorConfigReporter = string -> EditorConfigProblem list -> unit + +/// The running version without the commit hash `CodeFormatter.GetVersion` appends, so that the +/// settings a user is pointed at are tied to a version they can act on. +val fantomasVersion: string + +/// The supported setting closest to one Fantomas does not have, when there is a close one. +/// A prefixed spelling of a setting editorconfig itself defines, `fsharp_max_line_length` for +/// `max_line_length`, is answered outright; anything else has to be within a few characters. +val suggestionFor: setting: string -> string option + +/// What to tell someone about the settings Fantomas could not use out of `origin`, or `None` +/// when there is nothing to tell them. Names every problem, and where a misspelling has an +/// obvious intent, names that too. +/// +/// Deliberately does not list the settings Fantomas does support. That list is long, it is the +/// same list every time, and it answers nothing for a setting whose name was right and whose +/// value was not; `describeSupportedSettings` is there for the run that asks for it. +val describe: origin: string -> problems: EditorConfigProblem list -> string option + +/// Every setting this build understands, as a block to write once per run. +val describeSupportedSettings: unit -> string + +/// A reporter over `log`. Writes each distinct report once, however many files are formatted: +/// the command line reads the same `.editorconfig` again for every one of them, and without +/// this a single typo would be reported once per file. At debug verbosity it also writes the +/// supported settings out, once per run. +val createReporter: log: ILogger -> EditorConfigReporter + +/// Read the `.editorconfig` that applies to a file, reporting anything in it Fantomas cannot use. +/// The daemon does not go through here: it sends the problems to its client instead, and must not +/// write them to standard error, which `Fantomas.Client` redirects. +val readConfiguration: report: EditorConfigReporter -> fsharpFile: string -> FormatConfig diff --git a/src/Fantomas/Fantomas.fsproj b/src/Fantomas/Fantomas.fsproj index 971a15deba..97b13338e3 100644 --- a/src/Fantomas/Fantomas.fsproj +++ b/src/Fantomas/Fantomas.fsproj @@ -29,6 +29,8 @@ + + diff --git a/src/Fantomas/Program.fs b/src/Fantomas/Program.fs index 0e9af0cdee..391a1012eb 100644 --- a/src/Fantomas/Program.fs +++ b/src/Fantomas/Program.fs @@ -101,7 +101,7 @@ let main argv = fileSystem Environment.CurrentDirectory (IgnoreFile.loadIgnoreList fileSystem) - ReadConfiguration = EditorConfig.readConfiguration log + ReadConfiguration = EditorConfigReport.readConfiguration (EditorConfigReport.createReporter log) Log = log Console = AnsiConsole.Console } From 8b908fdfa1b68530cd35e0910e022a6fd48f5179 Mon Sep 17 00:00:00 2001 From: nojaf Date: Sat, 22 Aug 2026 18:33:07 +0200 Subject: [PATCH 05/10] Say what a daemon is, instead of passing five functions about one `DaemonOperations` was two unrelated things in one record: how the cache reaches the world, and what a daemon can tell you about itself. The second group is not an effect and had no business being injected; passing `StartInfo`, `IsRunning` and `Dispose` as functions is what left `'daemon` looking like it stood for nothing. Those three are now `IDaemon`, and `'daemon` is constrained by it, so the expectations are written down in one place rather than implied by a record of lambdas. `DaemonOperations` keeps only the two things the cache genuinely cannot answer for itself. `RunningFantomasTool` does not implement `IDaemon`; `CachedDaemon` wraps it. `RunningFantomasTool` is part of the package and has no business growing a public interface that exists to describe a cache, and the wrapper keeps `IDaemon` internal to this module. The type parameter stays because the cache has to hand a daemon back and the mailbox needs the `JsonRpc` off it. Putting `RpcClient` on `IDaemon` would erase the parameter, but the cache never touches it, and a test would then have to conjure a `JsonRpc` it does not use. Co-Authored-By: Claude Opus 5 (1M context) --- src/Fantomas.Client.Tests/DaemonCacheTests.fs | 46 ++++++++----------- src/Fantomas.Client/LSPFantomasService.fs | 46 +++++++++++-------- src/Fantomas.Client/LSPFantomasService.fsi | 32 +++++++++---- 3 files changed, 69 insertions(+), 55 deletions(-) diff --git a/src/Fantomas.Client.Tests/DaemonCacheTests.fs b/src/Fantomas.Client.Tests/DaemonCacheTests.fs index 3ee2317d43..328abb9b99 100644 --- a/src/Fantomas.Client.Tests/DaemonCacheTests.fs +++ b/src/Fantomas.Client.Tests/DaemonCacheTests.fs @@ -4,31 +4,33 @@ open NUnit.Framework open Fantomas.Client.LSPFantomasService open Fantomas.Client.LSPFantomasServiceTypes -/// A stand-in for a running daemon. `resolveDaemon` is written over an abstract daemon precisely -/// so this can be a number: a real `RunningFantomasTool` needs a process, and the questions here -/// are all about which daemon the cache hands out and what it forgets, not about processes. -type private FakeDaemon = - { Id: int - StartInfo: FantomasToolStartInfo - mutable Running: bool - mutable Disposed: bool } +/// A stand-in for a running daemon: everything `IDaemon` asks for and nothing else. A real +/// `RunningFantomasTool` needs a live process, and the questions here are all about which daemon +/// the cache hands out and what it forgets, not about processes. +type private FakeDaemon(id: int, startInfo: FantomasToolStartInfo) = + member val Running = true with get, set + member val Disposed = false with get, set + member _.Id: int = id + + interface IDaemon with + member _.StartInfo = startInfo + member this.IsRunning = this.Running + + member this.Dispose() = + this.Disposed <- true + this.Running <- false type private Recorder() = let created = ResizeArray() - let disposed = ResizeArray() member _.Created: FakeDaemon list = List.ofSeq created - member _.Disposed: FakeDaemon list = List.ofSeq disposed - member _.Record(daemon: FakeDaemon) = created.Add daemon - member _.RecordDisposed(daemon: FakeDaemon) = disposed.Add daemon let private version = FantomasVersion "8.0.0" let private otherVersion = FantomasVersion "7.0.5" let private folder = Folder "/repo" let private nested = Folder "/repo/nested" -/// Operations that find `version` for every folder and start a daemon that stays up. let private operationsFor (recorder: Recorder) (find: Folder -> Result) @@ -39,26 +41,14 @@ let private operationsFor fun startInfo -> let created = create startInfo created |> Result.iter recorder.Record - created - StartInfo = fun daemon -> daemon.StartInfo - IsRunning = fun daemon -> daemon.Running - Dispose = - fun daemon -> - daemon.Disposed <- true - daemon.Running <- false - recorder.RecordDisposed daemon } + created } let private findsVersion (version: FantomasVersion) (folder: Folder) = Ok(FantomasToolFound(version, FantomasToolStartInfo.LocalTool folder)) let private startsFine (nextId: int ref) (startInfo: FantomasToolStartInfo) = nextId.Value <- nextId.Value + 1 - - Ok - { Id = nextId.Value - StartInfo = startInfo - Running = true - Disposed = false } + Ok(FakeDaemon(nextId.Value, startInfo)) let private neverStarts (_: FantomasToolStartInfo) = Error(ProcessStartError.UnExpectedException("dotnet", "fantomas --daemon", "boom")) @@ -117,7 +107,7 @@ let ``a daemon that crashed is replaced, and the one it replaces is disposed`` ( Assert.That(second.Id, Is.Not.EqualTo first.Id) Assert.That(first.Disposed, Is.True) // Restarted the way the daemon it replaces was started, not the way this folder resolves now. - Assert.That(second.StartInfo, Is.EqualTo first.StartInfo) + Assert.That((second :> IDaemon).StartInfo, Is.EqualTo (first :> IDaemon).StartInfo) // The regression this is here for: dropping a version from the cache used to leave every folder // that resolved to it pointing at a version with no daemon. That is the one state resolveDaemon diff --git a/src/Fantomas.Client/LSPFantomasService.fs b/src/Fantomas.Client/LSPFantomasService.fs index d369b15bc4..e7bf423efa 100644 --- a/src/Fantomas.Client/LSPFantomasService.fs +++ b/src/Fantomas.Client/LSPFantomasService.fs @@ -31,13 +31,15 @@ type Msg = | GetDaemon of folder: Folder * replyChannel: AsyncReplyChannel> | Reset of AsyncReplyChannel +type IDaemon = + inherit IDisposable + abstract StartInfo: FantomasToolStartInfo + abstract IsRunning: bool + [] -type DaemonOperations<'daemon> = +type DaemonOperations<'daemon when 'daemon :> IDaemon> = { FindTool: Folder -> Result - Create: FantomasToolStartInfo -> Result<'daemon, ProcessStartError> - StartInfo: 'daemon -> FantomasToolStartInfo - IsRunning: 'daemon -> bool - Dispose: 'daemon -> unit } + Create: FantomasToolStartInfo -> Result<'daemon, ProcessStartError> } /// Forget a version, and with it every folder that resolved to it. Leaving those folders behind /// would pin them to a version with no daemon, which is the one state `resolveDaemon` cannot get @@ -70,15 +72,15 @@ let resolveDaemon match Map.tryFind folder state.FolderToVersion with | Some version -> match Map.tryFind version state.Daemons with - | Some daemon when operations.IsRunning daemon -> + | Some daemon when (daemon :> IDaemon).IsRunning -> Ok daemon, { state with FolderToVersion = Map.add folder version state.FolderToVersion } | Some daemon -> // A weird situation where the process has crashed. Dispose what is left of it so the // handles it still holds are released, then reboot it the way it was started. - let startInfo = operations.StartInfo daemon - operations.Dispose daemon + let startInfo = (daemon :> IDaemon).StartInfo + (daemon :> IDaemon).Dispose() startDaemon operations version startInfo folder state | None -> // This is a strange situation, we know what version is linked to that folder but there @@ -96,20 +98,31 @@ let resolveDaemon // The reused daemon keeps the StartInfo it was created with, so a restart after a crash // resolves the tool the way the first folder did rather than the way this one just did. match Map.tryFind version state.Daemons with - | Some daemon when operations.IsRunning daemon -> + | Some daemon when (daemon :> IDaemon).IsRunning -> Ok daemon, { state with FolderToVersion = Map.add folder version state.FolderToVersion } | running -> // A daemon that crashed is replaced, but dispose it first so the handles it still // holds are released. - Option.iter operations.Dispose running + running |> Option.iter (fun daemon -> (daemon :> IDaemon).Dispose()) startDaemon operations version startInfo folder state | Error FantomasToolError.NoCompatibleVersionFound -> Error GetDaemonError.InCompatibleVersionFound, state | Error(FantomasToolError.DotNetListError error) -> Error(GetDaemonError.DotNetToolListError error), state +/// A `RunningFantomasTool` as the cache sees it. A wrapper rather than an implementation on the +/// type itself, so that `IDaemon` stays inside this module: `RunningFantomasTool` is part of the +/// package, and it has no business growing an interface that exists to describe a cache. +type CachedDaemon(tool: RunningFantomasTool) = + member _.Tool: RunningFantomasTool = tool + + interface IDaemon with + member _.StartInfo = tool.StartInfo + member _.IsRunning = not tool.Process.HasExited + member _.Dispose() = (tool :> IDisposable).Dispose() + let createAgent (ct: CancellationToken) (onConfigurationWarning: ConfigurationWarning -> unit) : MailboxProcessor = - let operations: DaemonOperations = + let operations: DaemonOperations = { FindTool = findFantomasTool Create = fun startInfo -> @@ -118,14 +131,11 @@ let createAgent (ct: CancellationToken) (onConfigurationWarning: ConfigurationWa // Subscribed here rather than where the daemon is handed out, so that it happens // once per daemon however many folders end up sharing it. daemon.ConfigurationWarnings.Add onConfigurationWarning - daemon) - StartInfo = fun daemon -> daemon.StartInfo - IsRunning = fun daemon -> not daemon.Process.HasExited - Dispose = fun daemon -> (daemon :> IDisposable).Dispose() } + new CachedDaemon(daemon)) } MailboxProcessor.Start( (fun inbox -> - let rec messageLoop (state: ServiceState) = + let rec messageLoop (state: ServiceState) = async { let! msg = inbox.Receive() @@ -133,11 +143,11 @@ let createAgent (ct: CancellationToken) (onConfigurationWarning: ConfigurationWa match msg with | GetDaemon(folder, replyChannel) -> let daemon, nextState = resolveDaemon operations state folder - replyChannel.Reply(Result.map (fun daemon -> daemon.RpcClient) daemon) + replyChannel.Reply(Result.map (fun (daemon: CachedDaemon) -> daemon.Tool.RpcClient) daemon) nextState | Reset replyChannel -> Map.toList state.Daemons - |> List.iter (fun (_, daemon) -> operations.Dispose daemon) + |> List.iter (fun (_, daemon) -> (daemon :> IDaemon).Dispose()) replyChannel.Reply() ServiceState.Empty diff --git a/src/Fantomas.Client/LSPFantomasService.fsi b/src/Fantomas.Client/LSPFantomasService.fsi index 1f17da73f3..7d6af7cc57 100644 --- a/src/Fantomas.Client/LSPFantomasService.fsi +++ b/src/Fantomas.Client/LSPFantomasService.fsi @@ -2,9 +2,8 @@ module Fantomas.Client.LSPFantomasService open Fantomas.Client.LSPFantomasServiceTypes -/// Which daemon serves which folder. Written over an abstract daemon rather than over -/// `RunningFantomasTool` so that the cache can be exercised without starting a process: nothing -/// here does IO, every effect goes through `DaemonOperations`. +/// Which daemon serves which folder. `'daemon` is anything satisfying `IDaemon`; the tool itself +/// uses a `RunningFantomasTool`, and a test uses a record with a flag on it. [] type internal ServiceState<'daemon> = { Daemons: Map @@ -21,14 +20,28 @@ type internal GetDaemonError = /// cache in that state; reaching it means something else emptied `Daemons`. | CompatibleVersionIsKnownButNoDaemonIsRunning of version: FantomasVersion -/// Everything the cache does to a daemon and to the world, so that a test can supply all of it. +/// What the cache needs of a daemon it is holding: enough to tell a live one from a crashed one, +/// to start a replacement the way the original was started, and to let one go. +/// +/// This, rather than `RunningFantomasTool`, is what `'daemon` stands for everywhere in this module. +/// It is an interface so that the cache can be exercised without starting a process: everything +/// here is a question about a daemon, and none of it needs the daemon to be a real one. +type internal IDaemon = + inherit System.IDisposable + + /// How this daemon was started, so a crashed one can be replaced the way it was created rather + /// than the way the folder asking for it resolves now. + abstract StartInfo: FantomasToolStartInfo + + /// Whether the process behind it is still up. + abstract IsRunning: bool + +/// How the cache reaches the world. Only the two things it cannot answer for itself: everything a +/// daemon knows about itself is on `IDaemon`. [] -type internal DaemonOperations<'daemon> = +type internal DaemonOperations<'daemon when 'daemon :> IDaemon> = { FindTool: Folder -> Result - Create: FantomasToolStartInfo -> Result<'daemon, ProcessStartError> - StartInfo: 'daemon -> FantomasToolStartInfo - IsRunning: 'daemon -> bool - Dispose: 'daemon -> unit } + Create: FantomasToolStartInfo -> Result<'daemon, ProcessStartError> } /// Hand out the daemon serving `folder`, starting one if no running daemon serves its version yet, /// along with the cache that leaves behind. Daemons are keyed by version rather than by folder, so @@ -38,6 +51,7 @@ val internal resolveDaemon: state: ServiceState<'daemon> -> folder: Folder -> Result<'daemon, GetDaemonError> * ServiceState<'daemon> + when 'daemon :> IDaemon type LSPFantomasService = interface Contracts.FantomasService From 23e41ec3ae8f37491266cd0433f2519e795f056c Mon Sep 17 00:00:00 2001 From: nojaf Date: Sat, 22 Aug 2026 18:51:44 +0200 Subject: [PATCH 06/10] Use quotes for the "did you mean" --- src/Fantomas.Tests/EditorConfigReportTests.fs | 21 +++++++++++++++++-- src/Fantomas.Tests/Integration/ConfigTests.fs | 5 +++-- src/Fantomas/EditorConfigReport.fs | 9 +++++--- 3 files changed, 28 insertions(+), 7 deletions(-) diff --git a/src/Fantomas.Tests/EditorConfigReportTests.fs b/src/Fantomas.Tests/EditorConfigReportTests.fs index 7cba3622f5..6c16399ad7 100644 --- a/src/Fantomas.Tests/EditorConfigReportTests.fs +++ b/src/Fantomas.Tests/EditorConfigReportTests.fs @@ -32,11 +32,11 @@ let ``every problem is named, and the origin with them`` () = | None -> Assert.Fail "Expected a report" | Some report -> Assert.That(report, Does.Contain "/repo/.editorconfig") - Assert.That(report, Does.Contain "fsharp_wibble is not a Fantomas setting") + Assert.That(report, Does.Contain "'fsharp_wibble' is not a Fantomas setting") Assert.That( report, - Does.Contain "fsharp_experimental_elmish does not accept the value yes, so the default is used instead" + Does.Contain "'fsharp_experimental_elmish' does not accept the value 'yes', so the default is used instead" ) [] @@ -136,6 +136,23 @@ let ``the supported settings are written at debug verbosity, once per run`` () = debug |> List.length == 1 Assert.That(List.head debug, Does.Contain "fsharp_multiline_bracket_style") +// A value is whatever someone typed after the `=`. Unquoted, an empty one vanished and one with +// spaces in it ran into the sentence around it: "does not accept the value not a bool, so there, +// so the default is used instead." +[] +[] +[] +let ``an awkward value is delimited so the sentence still reads`` (value: string, expected: string) = + match describe "/repo/.editorconfig" [ unrecognized ("fsharp_experimental_elmish", value) ] with + | None -> Assert.Fail "Expected a report" + | Some report -> Assert.That(report, Does.Contain $"does not accept the value %s{expected}, so the default") + +[] +let ``a suggestion is delimited too, so the question mark is not read as part of the name`` () = + match describe "/repo/.editorconfig" [ unknown "fsharp_max_line_length" ] with + | None -> Assert.Fail "Expected a report" + | Some report -> Assert.That(report, Does.Contain "Did you mean 'max_line_length'?") + [] let ``a value carrying braces is not read as a message template`` () = // Serilog reads `{Foo}` in a message template as a property to fill in. The report is text diff --git a/src/Fantomas.Tests/Integration/ConfigTests.fs b/src/Fantomas.Tests/Integration/ConfigTests.fs index 2599e46e16..0808ff0a46 100644 --- a/src/Fantomas.Tests/Integration/ConfigTests.fs +++ b/src/Fantomas.Tests/Integration/ConfigTests.fs @@ -122,11 +122,12 @@ some_other_tool_setting = 42 // Advice, not a failure: the file is still formatted, with defaults for what could not be read. exitCode |> should equal 0 - Assert.That(error, Does.Contain "fsharp_bogus_option is not a Fantomas setting") + Assert.That(error, Does.Contain "'fsharp_bogus_option' is not a Fantomas setting") Assert.That( error, - Does.Contain "fsharp_experimental_elmish does not accept the value not_a_bool, so the default is used instead" + Does.Contain + "'fsharp_experimental_elmish' does not accept the value 'not_a_bool', so the default is used instead" ) // A setting without the fsharp_ prefix belongs to some other tool and is none of our business. diff --git a/src/Fantomas/EditorConfigReport.fs b/src/Fantomas/EditorConfigReport.fs index b4f8e602fc..d539e03018 100644 --- a/src/Fantomas/EditorConfigReport.fs +++ b/src/Fantomas/EditorConfigReport.fs @@ -70,14 +70,17 @@ let suggestionFor (setting: string) : string option = |> List.tryHead |> Option.map fst +/// Settings and values are quoted the way the rest of the tool quotes what it was given, and for +/// the same reason: both are text someone else wrote. A value can be empty, or carry spaces, or +/// read like prose, and unquoted it runs into the sentence around it. let describeProblem (problem: EditorConfigProblem) : string = match problem with | EditorConfigProblem.UnknownSetting setting -> match suggestionFor setting with - | Some suggestion -> $" %s{setting} is not a Fantomas setting. Did you mean %s{suggestion}?" - | None -> $" %s{setting} is not a Fantomas setting." + | Some suggestion -> $" '%s{setting}' is not a Fantomas setting. Did you mean '%s{suggestion}'?" + | None -> $" '%s{setting}' is not a Fantomas setting." | EditorConfigProblem.UnrecognizedValue(setting, value) -> - $" %s{setting} does not accept the value %s{value}, so the default is used instead." + $" '%s{setting}' does not accept the value '%s{value}', so the default is used instead." let describe (origin: string) (problems: EditorConfigProblem list) : string option = if List.isEmpty problems then From da1f5a53948ed399e0f2f9c71f280b40a0e11d30 Mon Sep 17 00:00:00 2001 From: nojaf Date: Sat, 22 Aug 2026 19:02:37 +0200 Subject: [PATCH 07/10] Give both daemon format methods one configuration path FormatDocumentAsync and FormatSelectionAsync each carried their own copy of the same forty lines: resolve the configuration, start the notification, await it, and fall back to an empty warning when the read raised. Two copies meant two places to get the ordering right, and one of them did not. When formatting threw, the notification that had already been started was abandoned rather than awaited, so the contract stated in Contracts.fsi held only because StreamJsonRpc happens to serialise its writes. Both methods now go through one helper that owns the whole sequence, error path included. A folder pinned to a version with no daemon behind it used to be a dead end. The cache answered CompatibleVersionIsKnownButNoDaemonIsRunning and changed nothing, so the next request answered the same, for the rest of the session. It now forgets the version and resolves the tool again; nothing produces that state any more, but a cache that has lost track of a daemon should cost a lookup rather than the ability to format. The error case goes with it. The version handshake with a freshly started daemon had no timeout. Daemons are resolved on a single mailbox, so a process that started and then never answered held up every later request with nothing to show for it. It now gets thirty seconds, after which the existing cleanup kills it like any other failed handshake. Smaller things: BeginErrorReadLine drains the pipe with no subscriber attached, so the handler that discarded the lines is gone; a report with no contributing .editorconfig no longer names the F# file as the origin, which sent people looking in the wrong place; and the client documentation now says the warning is raised for every format request and before it answers, matching the signature files. --- docs/docs/end-users/FantomasClient.md | 5 +- src/Fantomas.Client.Tests/DaemonCacheTests.fs | 20 +- src/Fantomas.Client/CHANGELOG.md | 2 + src/Fantomas.Client/FantomasToolLocator.fs | 20 +- src/Fantomas.Client/LSPFantomasService.fs | 17 +- src/Fantomas.Client/LSPFantomasService.fsi | 6 +- src/Fantomas/Daemon.fs | 208 ++++++++++-------- src/Fantomas/EditorConfigReport.fs | 6 +- 8 files changed, 167 insertions(+), 117 deletions(-) diff --git a/docs/docs/end-users/FantomasClient.md b/docs/docs/end-users/FantomasClient.md index 62cb18d6b4..14f0c6c12a 100644 --- a/docs/docs/end-users/FantomasClient.md +++ b/docs/docs/end-users/FantomasClient.md @@ -87,8 +87,9 @@ service.ConfigurationWarnings.Add(fun warning -> Worth knowing: -- The event is raised after **every** format request, with an empty `Problems` array when the - configuration is fine. That is what lets you clear a warning once the user fixes it. +- The event is raised for **every** format request, and before that request answers, with an + empty `Problems` array when the configuration is fine. That is what lets you clear a warning + once the user fixes it. - `EditorConfigFiles` holds the absolute paths of the `.editorconfig` files that contributed. Which one a given problem came from is not knowable, because editorconfig merges the whole chain into a single set of properties before Fantomas sees it. There is no line number either, so name the diff --git a/src/Fantomas.Client.Tests/DaemonCacheTests.fs b/src/Fantomas.Client.Tests/DaemonCacheTests.fs index 328abb9b99..5223021878 100644 --- a/src/Fantomas.Client.Tests/DaemonCacheTests.fs +++ b/src/Fantomas.Client.Tests/DaemonCacheTests.fs @@ -48,7 +48,7 @@ let private findsVersion (version: FantomasVersion) (folder: Folder) = let private startsFine (nextId: int ref) (startInfo: FantomasToolStartInfo) = nextId.Value <- nextId.Value + 1 - Ok(FakeDaemon(nextId.Value, startInfo)) + Ok(new FakeDaemon(nextId.Value, startInfo)) let private neverStarts (_: FantomasToolStartInfo) = Error(ProcessStartError.UnExpectedException("dotnet", "fantomas --daemon", "boom")) @@ -203,6 +203,24 @@ let ``forgetting one version leaves the folders on another version alone`` () = Assert.That(remaining, Is.EqualTo<(Folder * FantomasVersion) list> [ nested, otherVersion ]) Assert.That(state.Daemons |> Map.find otherVersion, Is.SameAs survivor) +// resolveDaemon never produces this state, but it is constructible, and it used to be a dead end: +// the folder was answered "a compatible version is known but no daemon is running", the cache was +// left exactly as it was, and so the next request answered the same, for the rest of the session. +[] +let ``a cache that lost track of a daemon resolves the tool again rather than giving up`` () = + let recorder = Recorder() + let operations = operationsFor recorder (findsVersion version) (startsFine (ref 0)) + + let lostTrack = + { Daemons = Map.empty + FolderToVersion = Map.ofList [ folder, version ] } + + let recovered, state = resolveDaemon operations lostTrack folder + + expectOk recovered |> ignore + Assert.That(Map.count state.Daemons, Is.EqualTo 1) + Assert.That(state.FolderToVersion |> Map.containsKey folder, Is.True) + [] let ``no compatible version is reported without touching the cache`` () = let recorder = Recorder() diff --git a/src/Fantomas.Client/CHANGELOG.md b/src/Fantomas.Client/CHANGELOG.md index f8ee77ada2..930297ac4d 100644 --- a/src/Fantomas.Client/CHANGELOG.md +++ b/src/Fantomas.Client/CHANGELOG.md @@ -13,12 +13,14 @@ This is the changelog for the Fantomas.Client package specifically. It's distinc - Bump `StreamJsonRpc` to `2.25.29`. [#3393](https://github.com/fsprojects/fantomas/pull/3393) - Breaking: no longer binary compatible with `0.11.0`. Several discriminated unions are structs now, which changes nothing about how they are written or matched, but an assembly compiled against `0.11.0` has to be rebuilt. [#3407](https://github.com/fsprojects/fantomas/pull/3407) - Breaking: `FantomasService` gained the `ConfigurationWarnings` member, and `RunningFantomasTool` gained a field. Source-breaking only for code that *implements* `FantomasService` or *constructs* `RunningFantomasTool`; calling either is unaffected, at source and at binary level. [#3401](https://github.com/fsprojects/fantomas/pull/3401) +- The `DaemonCreationFailed` response no longer reports "found a compatible version but no daemon could be launched". The cache state behind that message cannot arise now that a version is forgotten along with the folders pinned to it, and a cache handed that state resolves the tool again rather than reporting it. [#3401](https://github.com/fsprojects/fantomas/pull/3401) ### Fixed - Opening a second folder that pins the same Fantomas version started a second daemon and dropped the first one from the cache without disposing it, leaving an orphaned process behind for the rest of the session. Daemons are keyed by version, so a running one for that version is now reused. [#3401](https://github.com/fsprojects/fantomas/pull/3401) - A daemon that failed to start left every folder resolved to its version pinned to a version with no daemon behind it, which answered `CompatibleVersionIsKnownButNoDaemonIsRunning` for the rest of the session rather than trying again. Those folders are forgotten along with the version, so the next request resolves the tool from scratch. [#3401](https://github.com/fsprojects/fantomas/pull/3401) - A Fantomas resolved from the `PATH` counted as a different version from the same Fantomas resolved from a `dotnet-tools.json`, and got a second daemon: `fantomas --version` prints `Fantomas v8.0.0+` where `dotnet tool list` prints `8.0.0`. [#3401](https://github.com/fsprojects/fantomas/pull/3401) - When a daemon failed its handshake, the standard error quoted in the reported message was whatever had arrived by then rather than all of it, so the lines explaining the failure were usually missing. [#3401](https://github.com/fsprojects/fantomas/pull/3401) +- The version handshake with a freshly started daemon had no timeout. A process that started but never answered held up every later request, because daemons are resolved on a single mailbox. It is now given 30 seconds, after which it is killed like any other failed handshake. [#3401](https://github.com/fsprojects/fantomas/pull/3401) ## [0.11.0] - 2026-04-16 diff --git a/src/Fantomas.Client/FantomasToolLocator.fs b/src/Fantomas.Client/FantomasToolLocator.fs index 0aecd475bb..e6f385df3e 100644 --- a/src/Fantomas.Client/FantomasToolLocator.fs +++ b/src/Fantomas.Client/FantomasToolLocator.fs @@ -147,6 +147,10 @@ let normalizeVersion (printed: string) : string = | -1 -> printed | index -> printed.Substring(0, index) +/// How long a freshly started daemon has to answer the version handshake before it is given up on. +[] +let handshakeTimeoutInMs = 30_000 + // Find an executable fantomas file on the PATH let fantomasVersionOnPath () : (FantomasExecutableFile * FantomasVersion) option = let fantomasExecutableOnPathOpt = @@ -183,9 +187,9 @@ let fantomasVersionOnPath () : (FantomasExecutableFile * FantomasVersion) option match startProcess processStart with | Ok p -> // Standard error is redirected, so something has to read it, or a version that wrote - // more to it than the pipe holds would block on the write and never exit. Nothing here - // wants what it says. - p.ErrorDataReceived.Add(ignore) + // more to it than the pipe holds would block on the write and never exit. This drains + // it with no subscriber attached, which is all that is wanted: nothing here reads what + // it says. p.BeginErrorReadLine() let stdOut = p.StandardOutput.ReadToEnd() @@ -299,11 +303,17 @@ let createFor (startInfo: FantomasToolStartInfo) : Result(Fantomas.Client.Contracts.Methods.Version) |> Async.AwaitTask - |> Async.RunSynchronously + |> fun handshake -> Async.RunSynchronously(handshake, timeout = handshakeTimeoutInMs) Ok { RpcClient = client diff --git a/src/Fantomas.Client/LSPFantomasService.fs b/src/Fantomas.Client/LSPFantomasService.fs index e7bf423efa..24cdc085dc 100644 --- a/src/Fantomas.Client/LSPFantomasService.fs +++ b/src/Fantomas.Client/LSPFantomasService.fs @@ -24,7 +24,6 @@ type GetDaemonError = | DotNetToolListError of error: DotNetToolListError | FantomasProcessStart of error: ProcessStartError | InCompatibleVersionFound - | CompatibleVersionIsKnownButNoDaemonIsRunning of version: FantomasVersion [] type Msg = @@ -64,7 +63,7 @@ let startDaemon FolderToVersion = Map.add folder version state.FolderToVersion } | Error error -> Error(GetDaemonError.FantomasProcessStart error), forgetVersion version state -let resolveDaemon +let rec resolveDaemon (operations: DaemonOperations<'daemon>) (state: ServiceState<'daemon>) (folder: Folder) @@ -83,10 +82,13 @@ let resolveDaemon (daemon :> IDaemon).Dispose() startDaemon operations version startInfo folder state | None -> - // This is a strange situation, we know what version is linked to that folder but there - // is no daemon. The moment a version is added is also the moment a daemon is re-used or - // created. - Error(GetDaemonError.CompatibleVersionIsKnownButNoDaemonIsRunning version), state + // A folder pinned to a version with no daemon behind it. Nothing here produces that + // any more, because every path that drops a version forgets the folders pinned to it, + // but it used to be answered with an error that changed nothing, so the folder gave + // the same answer for the rest of the session. Forget the version and resolve the tool + // from scratch: a cache that has lost track of a daemon should cost a lookup, not the + // ability to format. + resolveDaemon operations (forgetVersion version state) folder | None -> match operations.FindTool folder with | Ok(FantomasToolFound(version, startInfo)) -> @@ -249,9 +251,6 @@ let daemonNotFoundResponse filePath (error: GetDaemonError) : Task "Fantomas.Client did not found a compatible dotnet tool version to launch as daemon process", FantomasResponseCode.ToolNotFound - | GetDaemonError.CompatibleVersionIsKnownButNoDaemonIsRunning(FantomasVersion version) -> - $"Fantomas.Client found a compatible version `%s{version}` but no daemon could be launched.", - FantomasResponseCode.DaemonCreationFailed { Code = int code FilePath = filePath diff --git a/src/Fantomas.Client/LSPFantomasService.fsi b/src/Fantomas.Client/LSPFantomasService.fsi index 7d6af7cc57..7a57e992cc 100644 --- a/src/Fantomas.Client/LSPFantomasService.fsi +++ b/src/Fantomas.Client/LSPFantomasService.fsi @@ -16,9 +16,6 @@ type internal GetDaemonError = | DotNetToolListError of error: DotNetToolListError | FantomasProcessStart of error: ProcessStartError | InCompatibleVersionFound - /// A folder resolved to a version with no daemon behind it. `resolveDaemon` never leaves the - /// cache in that state; reaching it means something else emptied `Daemons`. - | CompatibleVersionIsKnownButNoDaemonIsRunning of version: FantomasVersion /// What the cache needs of a daemon it is holding: enough to tell a live one from a crashed one, /// to start a replacement the way the original was started, and to let one go. @@ -46,6 +43,9 @@ type internal DaemonOperations<'daemon when 'daemon :> IDaemon> = /// Hand out the daemon serving `folder`, starting one if no running daemon serves its version yet, /// along with the cache that leaves behind. Daemons are keyed by version rather than by folder, so /// two folders that pin the same Fantomas share one process. +/// +/// Never leaves a folder pinned to a version with no daemon behind it, and recovers rather than +/// erroring if it is ever handed a cache in that state. val internal resolveDaemon: operations: DaemonOperations<'daemon> -> state: ServiceState<'daemon> -> diff --git a/src/Fantomas/Daemon.fs b/src/Fantomas/Daemon.fs index a1aa23a1c9..d9b0604001 100644 --- a/src/Fantomas/Daemon.fs +++ b/src/Fantomas/Daemon.fs @@ -96,6 +96,50 @@ type FantomasDaemon(sender: Stream, reader: Stream, environment: DaemonEnvironme () } + /// Resolve the configuration for a request, report it to the client, and hand it to `format`. + /// + /// Owns the whole ordering contract in one place, for both format methods: the notification is + /// started before formatting, so the write is not on the way to a formatted document, and it is + /// awaited before returning, so a client never sees the answer to a request before the warning + /// that belongs to it. That has to hold on the way out through the error path too, which is why + /// the started task is awaited in the `with` as well as the happy path. + /// + /// Reading the configuration can raise rather than come back with a problem, `end_of_line = cr` + /// being the one that does. Then nothing has been sent, so an empty warning goes out instead, + /// rather than leaving the client showing what the previous request left it with. + let withConfiguration + (filePath: string) + (sourceCode: string) + (requestConfig: IReadOnlyDictionary option) + (format: FormatConfig -> Task<'response>) + (onError: string -> 'response) + : Task<'response> = + task { + let mutable notified: Task = null + + try + let config, warning = + configurationFor environment.ReadConfiguration filePath requestConfig + + notified <- notifyConfigurationWarning warning + let! response = format config + do! notified + return response + with ex -> + if isNull notified then + do! notifyConfigurationWarning (noConfigurationProblems filePath) + else + do! notified + + // A ParseException's own Message is an %A dump of the diagnostic records, and it is + // the editor's user who would have been shown it. + let message = + Diagnostics.describeParseFailure filePath (fun () -> sourceCode) ex + |> Option.defaultValue ex.Message + + return onError message + } + let disconnectEvent = new ManualResetEvent(false) let exit () = disconnectEvent.Set() |> ignore @@ -133,106 +177,78 @@ type FantomasDaemon(sender: Stream, reader: Stream, environment: DaemonEnvironme request.Cursor |> Option.map (fun cursor -> CodeFormatter.MakePosition(cursor.Line, cursor.Column)) - // Whether the warning that belongs to this request has gone out yet. Reading the - // configuration can raise rather than come back with a problem, `end_of_line = cr` - // being the one that does, and then nothing has been sent and the client is still - // showing whatever the previous request left it with. - let warningSent = ref false - - try - // Reading the configuration belongs inside this: the client should hear about a - // value that raises as an Error response like any other failure, not as a - // remote invocation exception. - let config, warning = - configurationFor environment.ReadConfiguration request.FilePath request.Config - - // Started here rather than awaited here. The write is not on the way to a - // formatted document, but it has to have finished before the response goes out, - // so that a client never sees the answer to a request before the warning that - // belongs to it. - let notified = notifyConfigurationWarning warning - warningSent.Value <- true - - let! formatResponse = - match cursor with - | None -> CodeFormatter.FormatDocumentAsync(request.IsSignatureFile, request.SourceCode, config) - | Some cursor -> - CodeFormatter.FormatDocumentAsync( - request.IsSignatureFile, - request.SourceCode, - config, - cursor - ) - - do! notified - - if formatResponse.Code = request.SourceCode then - return FormatDocumentResponse.Unchanged request.FilePath - else - let cursor = - formatResponse.Cursor - |> Option.map (fun cursorPos -> FormatCursorPosition(cursorPos.Line, cursorPos.Column)) - - return FormatDocumentResponse.Formatted(request.FilePath, formatResponse.Code, cursor) - with ex -> - if not warningSent.Value then - do! notifyConfigurationWarning (noConfigurationProblems request.FilePath) - - // A ParseException's own Message is an %A dump of the diagnostic records, and - // it is the editor's user who would have been shown it. - let message = - Diagnostics.describeParseFailure request.FilePath (fun () -> request.SourceCode) ex - |> Option.defaultValue ex.Message - - return FormatDocumentResponse.Error(request.FilePath, message) + return! + withConfiguration + request.FilePath + request.SourceCode + request.Config + (fun config -> + task { + let! formatResponse = + match cursor with + | None -> + CodeFormatter.FormatDocumentAsync( + request.IsSignatureFile, + request.SourceCode, + config + ) + | Some cursor -> + CodeFormatter.FormatDocumentAsync( + request.IsSignatureFile, + request.SourceCode, + config, + cursor + ) + + if formatResponse.Code = request.SourceCode then + return FormatDocumentResponse.Unchanged request.FilePath + else + let cursor = + formatResponse.Cursor + |> Option.map (fun cursorPos -> + FormatCursorPosition(cursorPos.Line, cursorPos.Column)) + + return + FormatDocumentResponse.Formatted(request.FilePath, formatResponse.Code, cursor) + }) + (fun message -> FormatDocumentResponse.Error(request.FilePath, message)) } [] member _.FormatSelectionAsync(request: FormatSelectionRequest) : Task = - task { - let selection = - let r = request.Range - - Range.mkRange - request.FilePath - (Position.mkPos r.StartLine r.StartColumn) - (Position.mkPos r.EndLine r.EndColumn) - - let warningSent = ref false - - try - // Inside the try for the same reason as FormatDocumentAsync: a configuration value - // that raises has to reach the client as an Error response. - let config, warning = - configurationFor environment.ReadConfiguration request.FilePath request.Config - - let notified = notifyConfigurationWarning warning - warningSent.Value <- true - - let! formatted, actualSelection = - CodeFormatter.FormatSelectionAsync(request.IsSignatureFile, request.SourceCode, selection, config) - - do! notified - - let actualSelection = - FormatSelectionRange( - actualSelection.StartLine, - actualSelection.StartColumn, - actualSelection.EndLine, - actualSelection.EndColumn - ) - - return FormatSelectionResponse.Formatted(request.FilePath, formatted, actualSelection) - with ex -> - if not warningSent.Value then - do! notifyConfigurationWarning (noConfigurationProblems request.FilePath) - - let message = - Diagnostics.describeParseFailure request.FilePath (fun () -> request.SourceCode) ex - |> Option.defaultValue ex.Message - - return FormatSelectionResponse.Error(request.FilePath, message) - } + let selection = + let r = request.Range + + Range.mkRange + request.FilePath + (Position.mkPos r.StartLine r.StartColumn) + (Position.mkPos r.EndLine r.EndColumn) + + withConfiguration + request.FilePath + request.SourceCode + request.Config + (fun config -> + task { + let! formatted, actualSelection = + CodeFormatter.FormatSelectionAsync( + request.IsSignatureFile, + request.SourceCode, + selection, + config + ) + + let actualSelection = + FormatSelectionRange( + actualSelection.StartLine, + actualSelection.StartColumn, + actualSelection.EndLine, + actualSelection.EndColumn + ) + + return FormatSelectionResponse.Formatted(request.FilePath, formatted, actualSelection) + }) + (fun message -> FormatSelectionResponse.Error(request.FilePath, message)) [] member _.Configuration() : string = diff --git a/src/Fantomas/EditorConfigReport.fs b/src/Fantomas/EditorConfigReport.fs index d539e03018..77a1eb2238 100644 --- a/src/Fantomas/EditorConfigReport.fs +++ b/src/Fantomas/EditorConfigReport.fs @@ -141,7 +141,11 @@ let readConfiguration (report: EditorConfigReporter) (fsharpFile: string) : Form | Some result -> let origin = match result.EditorConfigFiles with - | [] -> fsharpFile + // The editorconfig library only reports settings it read from a file, so it should + // always name at least one. Keep a way through anyway, because that is its invariant + // and not ours, but do not name the F# file as the origin: nothing is wrong with it, + // and pointing at it sends someone looking in the wrong place. + | [] -> $"the .editorconfig that applies to %s{fsharpFile}" | files -> String.concat ", " files report origin result.Problems From 0fa6fd9866d4eb0e2a773a20daf9b6071d4deeac Mon Sep 17 00:00:00 2001 From: nojaf Date: Sat, 22 Aug 2026 19:25:29 +0200 Subject: [PATCH 08/10] Serve one daemon request at a time per file A configuration warning carries a file path and nothing that says which request it belongs to. Two format requests in flight for the same file could therefore deliver their warnings in either order, with no way for a client to sort them out, so an empty one could clear problems that were still current. Their results raced each other too, and which one the caller ended up with was down to timing. Requests for the same file now wait on each other. Requests for different files do not, which is what a caller formatting a repository cares about. That ordering had in fact been holding, but for a reason nobody chose. StreamJsonRpc only runs handlers concurrently when they are genuinely asynchronous; one that blocks before its first await holds the message loop and requests serialise instead. Reading an .editorconfig is disk work and it happened ahead of any await, so the loop was held for the length of every configuration read, the next request was not read until it finished, and the notification was issued inside that serialised prefix. The loop is handed back first now, which fixes the responsiveness of it and leaves the ordering resting on the gate rather than on an accident that would have evaporated the moment the configuration read became asynchronous. Contracts.fsi and the client documentation state the guarantee: warnings for one file arrive in the order the requests for it were made, however many are in flight, and warnings for different files interleave freely with FilePath to tell them apart. Both tests were checked against a build with the gate removed. The same-file one fails without it; the different-file one is there so the fix cannot degenerate into discarding concurrency. --- CHANGELOG.md | 1 + docs/docs/end-users/FantomasClient.md | 4 + src/Fantomas.Client/CHANGELOG.md | 1 + src/Fantomas.Client/Contracts.fsi | 8 + src/Fantomas.Tests/Integration/DaemonTests.fs | 65 ++++++ src/Fantomas/Daemon.fs | 209 +++++++++++------- 6 files changed, 205 insertions(+), 83 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ca41a45f2e..3573330fd3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,6 +24,7 @@ ### Fixed +- The daemon held its JSON-RPC message loop while reading an `.editorconfig`, so a request that arrived during it was not read until that finished. It hands the loop back first now, and serves one request at a time per file so that the configuration warnings for a file still arrive in the order the requests did. [#3401](https://github.com/fsprojects/fantomas/pull/3401) - A value that meant something to one setting decided the outcome for every other setting, because each value was tried against every parser in turn. `fsharp_max_record_width = cr` failed the whole run with `Carriage returns are not valid for F# code`; it is now reported as a value that setting does not accept. A value is only read as the type its own setting has. [#3401](https://github.com/fsprojects/fantomas/pull/3401) - `--verbosity` with an unrecognised value exited with code 1 and printed nothing, because the message was logged before the logger was configured. It now reports `Invalid verbosity level` on standard error. [#3399](https://github.com/fsprojects/fantomas/pull/3399) - `--out ` flattened the input tree: every file landed directly in the output folder, so two files with the same name in different subfolders silently overwrote each other. The output folder now mirrors the structure of the input folder, as the documentation already promised. [#3403](https://github.com/fsprojects/fantomas/pull/3403) diff --git a/docs/docs/end-users/FantomasClient.md b/docs/docs/end-users/FantomasClient.md index 14f0c6c12a..a58b9e4d03 100644 --- a/docs/docs/end-users/FantomasClient.md +++ b/docs/docs/end-users/FantomasClient.md @@ -90,6 +90,10 @@ Worth knowing: - The event is raised for **every** format request, and before that request answers, with an empty `Problems` array when the configuration is fine. That is what lets you clear a warning once the user fixes it. +- You can have as many format requests in flight as you like. Warnings for one file arrive in the + order you asked for them, because the daemon serves one request at a time per file, so an empty + one never overtakes problems that are still current. Requests for different files are served + concurrently and their warnings interleave; `FilePath` is what tells them apart. - `EditorConfigFiles` holds the absolute paths of the `.editorconfig` files that contributed. Which one a given problem came from is not knowable, because editorconfig merges the whole chain into a single set of properties before Fantomas sees it. There is no line number either, so name the diff --git a/src/Fantomas.Client/CHANGELOG.md b/src/Fantomas.Client/CHANGELOG.md index 930297ac4d..f917c9eb7a 100644 --- a/src/Fantomas.Client/CHANGELOG.md +++ b/src/Fantomas.Client/CHANGELOG.md @@ -20,6 +20,7 @@ This is the changelog for the Fantomas.Client package specifically. It's distinc - A daemon that failed to start left every folder resolved to its version pinned to a version with no daemon behind it, which answered `CompatibleVersionIsKnownButNoDaemonIsRunning` for the rest of the session rather than trying again. Those folders are forgotten along with the version, so the next request resolves the tool from scratch. [#3401](https://github.com/fsprojects/fantomas/pull/3401) - A Fantomas resolved from the `PATH` counted as a different version from the same Fantomas resolved from a `dotnet-tools.json`, and got a second daemon: `fantomas --version` prints `Fantomas v8.0.0+` where `dotnet tool list` prints `8.0.0`. [#3401](https://github.com/fsprojects/fantomas/pull/3401) - When a daemon failed its handshake, the standard error quoted in the reported message was whatever had arrived by then rather than all of it, so the lines explaining the failure were usually missing. [#3401](https://github.com/fsprojects/fantomas/pull/3401) +- Two format requests in flight for the same file could deliver their configuration warnings in either order, so an empty one could clear problems that were still current. Nothing on the wire says which request a warning belongs to, so a client could not sort them out. The daemon now serves one request at a time per file; different files are unaffected. [#3401](https://github.com/fsprojects/fantomas/pull/3401) - The version handshake with a freshly started daemon had no timeout. A process that started but never answered held up every later request, because daemons are resolved on a single mailbox. It is now given 30 seconds, after which it is killed like any other failed handshake. [#3401](https://github.com/fsprojects/fantomas/pull/3401) ## [0.11.0] - 2026-04-16 diff --git a/src/Fantomas.Client/Contracts.fsi b/src/Fantomas.Client/Contracts.fsi index 3512436551..5f228e0388 100644 --- a/src/Fantomas.Client/Contracts.fsi +++ b/src/Fantomas.Client/Contracts.fsi @@ -173,6 +173,14 @@ type FantomasService = /// subscriber that touches a UI has to marshal, and one that throws is swallowed rather than /// allowed to fault the connection. /// + /// Warnings for one file arrive in the order the requests for it were made, however many of + /// them you have in flight: the daemon serves one request at a time per file. That is what + /// makes the clearing rule sound, so an empty one never overtakes problems that are still + /// current. + /// + /// Requests for different files are served concurrently and their warnings interleave freely. + /// `FilePath` is what tells them apart. + /// /// Only Fantomas 8 daemons send these; an older one never raises it, so no version check is /// needed. abstract ConfigurationWarnings: IEvent diff --git a/src/Fantomas.Tests/Integration/DaemonTests.fs b/src/Fantomas.Tests/Integration/DaemonTests.fs index 1bb96399eb..7844cb5de4 100644 --- a/src/Fantomas.Tests/Integration/DaemonTests.fs +++ b/src/Fantomas.Tests/Integration/DaemonTests.fs @@ -1,6 +1,7 @@ module Fantomas.Tests.Integration.DaemonTests open System +open System.Threading.Tasks open Fantomas open Fantomas.Client.LSPFantomasServiceTypes open Fantomas.Daemon @@ -582,6 +583,70 @@ let ``a configuration that cannot be read at all is an error, and clears the war (theOnlyWarning warnings).Problems |> should be Empty +/// A `ReadConfiguration` that holds each caller inside it long enough to overlap with another, and +/// remembers how many were ever inside at once. +let private countingOverlaps () = + let inFlight = ref 0 + let peak = ref 0 + + let readConfiguration (_: string) : EditorConfig.EditorConfigResult option = + let now = System.Threading.Interlocked.Increment inFlight + + let rec recordPeak () = + let seen = peak.Value + + if now > seen then + if System.Threading.Interlocked.CompareExchange(peak, now, seen) <> seen then + recordPeak () + + recordPeak () + System.Threading.Thread.Sleep 100 + System.Threading.Interlocked.Decrement inFlight |> ignore + None + + readConfiguration, (fun () -> peak.Value) + +/// Send two format requests without waiting for the first, and report how many of them were ever +/// inside `ReadConfiguration` at the same time. +let private overlapOf (firstFile: string) (secondFile: string) : int = + let readConfiguration, peak = countingOverlaps () + + let environment = + daemonEnvironment (new System.IO.Abstractions.FileSystem()) readConfiguration + + let struct (serverStream, clientStream) = FullDuplexStream.CreatePair() + let daemon = new FantomasDaemon(serverStream, serverStream, environment) + let client = new JsonRpc(clientStream, clientStream) + client.StartListening() + + try + let send (file: string) = + client.InvokeAsync(Methods.FormatDocument, documentRequest file None) + + // Started together, awaited afterwards, so both are in flight at once. + let first = send firstFile + let second = send secondFile + Task.WaitAll(first :> Task, second :> Task) + peak () + finally + client.Dispose() + (daemon :> IDisposable).Dispose() + +// A configuration warning carries a file path and nothing that says which request it belongs to, so +// two requests in flight for one file could deliver theirs in either order and a client had no way +// to tell. The daemon serves one request at a time per file instead. +[] +let ``two requests for the same file do not overlap`` () = + use codeFile = new TemporaryFileCodeSample(sourceCode) + overlapOf codeFile.Filename codeFile.Filename |> should equal 1 + +// Only the same file waits. Formatting a repository is the whole point of having several in flight. +[] +let ``two requests for different files still run at the same time`` () = + use firstFile = new TemporaryFileCodeSample(sourceCode) + use secondFile = new TemporaryFileCodeSample(sourceCode) + overlapOf firstFile.Filename secondFile.Filename |> should equal 2 + [] let ``format selection reports configuration warnings too`` () = use codeFile = new TemporaryFileCodeSample(sourceCode) diff --git a/src/Fantomas/Daemon.fs b/src/Fantomas/Daemon.fs index d9b0604001..b4796bab5a 100644 --- a/src/Fantomas/Daemon.fs +++ b/src/Fantomas/Daemon.fs @@ -1,6 +1,7 @@ module Fantomas.Daemon open System +open System.Collections.Concurrent open System.Collections.Generic open System.Diagnostics open System.IO @@ -140,6 +141,39 @@ type FantomasDaemon(sender: Stream, reader: Stream, environment: DaemonEnvironme return onError message } + /// One request at a time per file. + /// + /// Requests are dispatched concurrently, and two in flight for the same file used to interleave: + /// their configuration warnings could arrive in either order, so an empty one could clear + /// problems that were still current, and there is no request identity on the wire for a client + /// to sort them out with. Their results raced each other too, so which one the caller ended up + /// with was down to timing. + /// + /// Only requests for the same file wait on each other. Formatting a repository, which is what a + /// caller with many requests in flight is usually doing, is untouched. + /// + /// A gate per file, kept for the life of the daemon. Bounded by the number of distinct files one + /// session formats, and a `SemaphoreSlim` nobody is waiting on costs very little. + let fileGates = ConcurrentDictionary() + + let oneAtATimePerFile (filePath: string) (work: unit -> Task<'response>) : Task<'response> = + task { + // Hand the message loop back before doing any of the work. Reading an `.editorconfig` + // is disk work and it happens before this request's first await, so without this the + // loop is held for the length of it and the next request is not even read yet. That + // made requests look serialised when they are not, which is a poor thing to leave the + // ordering of these notifications resting on. + do! Task.Yield() + + let gate = fileGates.GetOrAdd(filePath, (fun _ -> new SemaphoreSlim(1, 1))) + do! gate.WaitAsync() + + try + return! work () + finally + gate.Release() |> ignore + } + let disconnectEvent = new ManualResetEvent(false) let exit () = disconnectEvent.Set() |> ignore @@ -153,6 +187,9 @@ type FantomasDaemon(sender: Stream, reader: Stream, environment: DaemonEnvironme traceListener.Dispose() disconnectEvent.Dispose() + for gate in fileGates.Values do + gate.Dispose() + member this.WaitForClose = rpc.Completion [] @@ -160,95 +197,101 @@ type FantomasDaemon(sender: Stream, reader: Stream, environment: DaemonEnvironme [] member _.FormatDocumentAsync(request: FormatDocumentRequest) : Task = - task { - if - IgnoreFile.isIgnoredFile - environment.Log - (IgnoreFile.find fs (IgnoreFile.loadIgnoreList fs) request.FilePath) - request.FilePath - then - // Still reported, with nothing in it, so a client can clear what an earlier request - // showed for this file rather than leaving a stale warning behind. - do! notifyConfigurationWarning (noConfigurationProblems request.FilePath) - - return FormatDocumentResponse.IgnoredFile request.FilePath - else - let cursor = - request.Cursor - |> Option.map (fun cursor -> CodeFormatter.MakePosition(cursor.Line, cursor.Column)) - - return! - withConfiguration + oneAtATimePerFile request.FilePath (fun () -> + task { + if + IgnoreFile.isIgnoredFile + environment.Log + (IgnoreFile.find fs (IgnoreFile.loadIgnoreList fs) request.FilePath) request.FilePath - request.SourceCode - request.Config - (fun config -> - task { - let! formatResponse = - match cursor with - | None -> - CodeFormatter.FormatDocumentAsync( - request.IsSignatureFile, - request.SourceCode, - config - ) - | Some cursor -> - CodeFormatter.FormatDocumentAsync( - request.IsSignatureFile, - request.SourceCode, - config, - cursor - ) - - if formatResponse.Code = request.SourceCode then - return FormatDocumentResponse.Unchanged request.FilePath - else - let cursor = - formatResponse.Cursor - |> Option.map (fun cursorPos -> - FormatCursorPosition(cursorPos.Line, cursorPos.Column)) - - return - FormatDocumentResponse.Formatted(request.FilePath, formatResponse.Code, cursor) - }) - (fun message -> FormatDocumentResponse.Error(request.FilePath, message)) - } + then + // Still reported, with nothing in it, so a client can clear what an earlier request + // showed for this file rather than leaving a stale warning behind. + do! notifyConfigurationWarning (noConfigurationProblems request.FilePath) + + return FormatDocumentResponse.IgnoredFile request.FilePath + else + let cursor = + request.Cursor + |> Option.map (fun cursor -> CodeFormatter.MakePosition(cursor.Line, cursor.Column)) + + return! + withConfiguration + request.FilePath + request.SourceCode + request.Config + (fun config -> + task { + let! formatResponse = + match cursor with + | None -> + CodeFormatter.FormatDocumentAsync( + request.IsSignatureFile, + request.SourceCode, + config + ) + | Some cursor -> + CodeFormatter.FormatDocumentAsync( + request.IsSignatureFile, + request.SourceCode, + config, + cursor + ) + + if formatResponse.Code = request.SourceCode then + return FormatDocumentResponse.Unchanged request.FilePath + else + let cursor = + formatResponse.Cursor + |> Option.map (fun cursorPos -> + FormatCursorPosition(cursorPos.Line, cursorPos.Column)) + + return + FormatDocumentResponse.Formatted( + request.FilePath, + formatResponse.Code, + cursor + ) + }) + (fun message -> FormatDocumentResponse.Error(request.FilePath, message)) + }) [] member _.FormatSelectionAsync(request: FormatSelectionRequest) : Task = - let selection = - let r = request.Range + oneAtATimePerFile request.FilePath (fun () -> + let selection = + let r = request.Range + + Range.mkRange + request.FilePath + (Position.mkPos r.StartLine r.StartColumn) + (Position.mkPos r.EndLine r.EndColumn) - Range.mkRange + withConfiguration request.FilePath - (Position.mkPos r.StartLine r.StartColumn) - (Position.mkPos r.EndLine r.EndColumn) - - withConfiguration - request.FilePath - request.SourceCode - request.Config - (fun config -> - task { - let! formatted, actualSelection = - CodeFormatter.FormatSelectionAsync( - request.IsSignatureFile, - request.SourceCode, - selection, - config - ) - - let actualSelection = - FormatSelectionRange( - actualSelection.StartLine, - actualSelection.StartColumn, - actualSelection.EndLine, - actualSelection.EndColumn - ) - - return FormatSelectionResponse.Formatted(request.FilePath, formatted, actualSelection) - }) - (fun message -> FormatSelectionResponse.Error(request.FilePath, message)) + request.SourceCode + request.Config + (fun config -> + task { + let! formatted, actualSelection = + CodeFormatter.FormatSelectionAsync( + request.IsSignatureFile, + request.SourceCode, + selection, + config + ) + + let actualSelection = + FormatSelectionRange( + actualSelection.StartLine, + actualSelection.StartColumn, + actualSelection.EndLine, + actualSelection.EndColumn + ) + + return FormatSelectionResponse.Formatted(request.FilePath, formatted, actualSelection) + }) + (fun message -> FormatSelectionResponse.Error(request.FilePath, message))) [] member _.Configuration() : string = From 199c9a5792dbcc761d4ea6675dba8b1062eb47fb Mon Sep 17 00:00:00 2001 From: nojaf Date: Sat, 22 Aug 2026 19:33:35 +0200 Subject: [PATCH 09/10] Key the daemon's file gates without regard to case The gates added in the previous commit used the default ordinal comparer, so one file reached through two spellings got two gates and the guarantee they exist to provide silently did not hold between them. Windows and a default macOS volume both make that reachable, and nothing canonicalises the path on the way in: the client checks that it is absolute and no more. On a case sensitive file system two genuinely different files can now share a gate, which costs a little concurrency and nothing else. A handshake that times out now says what it was waiting for and how long it was given, rather than reporting whatever bare timeout message came out of the exception. The next report of one should carry a number someone can argue about. Also documents two things that were decided rather than overlooked. The daemon does not coalesce: several requests queued for one file each run to completion in turn, so a burst grows latency with the length of the queue, though none of them is served stale input because each carries its own source. And disposal does not wait for requests in flight, because awaiting the connection would hang shutdown on a stuck daemon, and the exception a mid-flight request may get is read by nobody once the client is going away. --- docs/docs/end-users/FantomasClient.md | 4 ++++ src/Fantomas.Client/CHANGELOG.md | 2 +- src/Fantomas.Client/FantomasToolLocator.fs | 7 ++++++- src/Fantomas.Tests/Integration/DaemonTests.fs | 14 ++++++++++++++ src/Fantomas/Daemon.fs | 12 +++++++++++- 5 files changed, 36 insertions(+), 3 deletions(-) diff --git a/docs/docs/end-users/FantomasClient.md b/docs/docs/end-users/FantomasClient.md index a58b9e4d03..e882977996 100644 --- a/docs/docs/end-users/FantomasClient.md +++ b/docs/docs/end-users/FantomasClient.md @@ -94,6 +94,10 @@ Worth knowing: order you asked for them, because the daemon serves one request at a time per file, so an empty one never overtakes problems that are still current. Requests for different files are served concurrently and their warnings interleave; `FilePath` is what tells them apart. +- Nothing is coalesced. Several requests queued for one file each run to completion in turn, so a + tool that fires a burst of them will see latency grow with the length of the queue. None of them + is served stale input, because each request carries its own `SourceCode`, but if you format on + every keystroke you want to be dropping your own superseded requests rather than sending them. - `EditorConfigFiles` holds the absolute paths of the `.editorconfig` files that contributed. Which one a given problem came from is not knowable, because editorconfig merges the whole chain into a single set of properties before Fantomas sees it. There is no line number either, so name the diff --git a/src/Fantomas.Client/CHANGELOG.md b/src/Fantomas.Client/CHANGELOG.md index f917c9eb7a..ea37a19383 100644 --- a/src/Fantomas.Client/CHANGELOG.md +++ b/src/Fantomas.Client/CHANGELOG.md @@ -21,7 +21,7 @@ This is the changelog for the Fantomas.Client package specifically. It's distinc - A Fantomas resolved from the `PATH` counted as a different version from the same Fantomas resolved from a `dotnet-tools.json`, and got a second daemon: `fantomas --version` prints `Fantomas v8.0.0+` where `dotnet tool list` prints `8.0.0`. [#3401](https://github.com/fsprojects/fantomas/pull/3401) - When a daemon failed its handshake, the standard error quoted in the reported message was whatever had arrived by then rather than all of it, so the lines explaining the failure were usually missing. [#3401](https://github.com/fsprojects/fantomas/pull/3401) - Two format requests in flight for the same file could deliver their configuration warnings in either order, so an empty one could clear problems that were still current. Nothing on the wire says which request a warning belongs to, so a client could not sort them out. The daemon now serves one request at a time per file; different files are unaffected. [#3401](https://github.com/fsprojects/fantomas/pull/3401) -- The version handshake with a freshly started daemon had no timeout. A process that started but never answered held up every later request, because daemons are resolved on a single mailbox. It is now given 30 seconds, after which it is killed like any other failed handshake. [#3401](https://github.com/fsprojects/fantomas/pull/3401) +- The version handshake with a freshly started daemon had no timeout. A process that started but never answered held up every later request, because daemons are resolved on a single mailbox. It is now given 30 seconds, after which it is killed like any other failed handshake and reported as `Daemon did not answer the version request within 30000 ms.` rather than a bare timeout message. [#3401](https://github.com/fsprojects/fantomas/pull/3401) ## [0.11.0] - 2026-04-16 diff --git a/src/Fantomas.Client/FantomasToolLocator.fs b/src/Fantomas.Client/FantomasToolLocator.fs index e6f385df3e..de3e61d7ef 100644 --- a/src/Fantomas.Client/FantomasToolLocator.fs +++ b/src/Fantomas.Client/FantomasToolLocator.fs @@ -322,7 +322,12 @@ let createFor (startInfo: FantomasToolStartInfo) : Result let error = - if daemonProcess.HasExited then + // A timeout says nothing about what was being waited for, so say it here. The next + // field report should carry a number someone can argue about rather than "it said + // something timed out". + if (ex :? TimeoutException) then + $"Daemon did not answer the version request within %i{handshakeTimeoutInMs} ms." + elif daemonProcess.HasExited then // `HasExited` only says the process is gone; the handler above is fed // asynchronously and can still be behind. `WaitForExit` with no timeout is the // one overload that waits for the readers to drain too, so without it the diff --git a/src/Fantomas.Tests/Integration/DaemonTests.fs b/src/Fantomas.Tests/Integration/DaemonTests.fs index 7844cb5de4..357aedbfb9 100644 --- a/src/Fantomas.Tests/Integration/DaemonTests.fs +++ b/src/Fantomas.Tests/Integration/DaemonTests.fs @@ -640,6 +640,20 @@ let ``two requests for the same file do not overlap`` () = use codeFile = new TemporaryFileCodeSample(sourceCode) overlapOf codeFile.Filename codeFile.Filename |> should equal 1 +// One file reached through two spellings is still one file on Windows and on a default macOS +// volume, and nothing canonicalises the path on the way in, so the gates fold case. +[] +let ``two spellings of one file share a gate`` () = + use codeFile = new TemporaryFileCodeSample(sourceCode) + + let shouted = + System.IO.Path.Combine( + System.IO.Path.GetDirectoryName codeFile.Filename, + (System.IO.Path.GetFileName codeFile.Filename).ToUpperInvariant() + ) + + overlapOf codeFile.Filename shouted |> should equal 1 + // Only the same file waits. Formatting a repository is the whole point of having several in flight. [] let ``two requests for different files still run at the same time`` () = diff --git a/src/Fantomas/Daemon.fs b/src/Fantomas/Daemon.fs index b4796bab5a..cc5a72345e 100644 --- a/src/Fantomas/Daemon.fs +++ b/src/Fantomas/Daemon.fs @@ -154,7 +154,13 @@ type FantomasDaemon(sender: Stream, reader: Stream, environment: DaemonEnvironme /// /// A gate per file, kept for the life of the daemon. Bounded by the number of distinct files one /// session formats, and a `SemaphoreSlim` nobody is waiting on costs very little. - let fileGates = ConcurrentDictionary() + /// Keyed without regard to case, as editorconfig keys are read in this branch, so that one file + /// reached through two spellings does not get two gates and quietly lose the guarantee. Windows + /// and a default macOS volume both make that reachable, and the client checks a path is absolute + /// without canonicalising it. On a case sensitive file system this can make two genuinely + /// different files share a gate, which costs a little concurrency and nothing else. + let fileGates = + ConcurrentDictionary(StringComparer.OrdinalIgnoreCase) let oneAtATimePerFile (filePath: string) (work: unit -> Task<'response>) : Task<'response> = task { @@ -187,6 +193,10 @@ type FantomasDaemon(sender: Stream, reader: Stream, environment: DaemonEnvironme traceListener.Dispose() disconnectEvent.Dispose() + // Not waited on. A request still in flight at this point can find a disposed gate and + // come back as an exception response, which nobody reads: the client is going away, + // which is why we are here. Deliberate, rather than awaiting `rpc.Completion` and + // hanging shutdown on a daemon that is stuck. for gate in fileGates.Values do gate.Dispose() From 8ed10ba3d9e56c3ecf45f5b3cb5254048fb474dc Mon Sep 17 00:00:00 2001 From: nojaf Date: Sat, 22 Aug 2026 20:36:36 +0200 Subject: [PATCH 10/10] Report a misspelling of a setting editorconfig itself defines `max_line_lenght = 100` was ignored without a word, where the same slip in a `fsharp_` setting was reported. It is the same mistake and it costs the author the same silence, so an unprefixed key close enough to a setting Fantomas has is now read as a misspelling of it. Close enough means two edits, not the three a suggestion is offered at, and the difference matters. `indent_style` is three edits from `indent_size` and sits in very nearly every `.editorconfig` ever written, so the wider distance would have put a false report in front of almost every user. Two reaches every realistic typo and reaches nothing anyone meant to write. Settings belonging to other tools stay silent, and there is a test naming the ones that turn up most often. A negative number is no longer accepted for a setting that takes one. No setting means anything below zero, and a run that took one formatted to nonsense widths without saying so. Three things in the client, all of which let the cache keep believing in a daemon that could not serve: - Replacing a crashed daemon started it the way whichever folder noticed the crash resolves now, rather than the way the daemon being replaced was started, so a daemon shared by two folders could come back under a different working directory. The comment above that branch had been claiming the opposite for as long as the code existed. - Liveness was the process being up. A daemon whose connection had ended kept being handed out while its process lingered, and every request against it failed. It now means the process is up and the connection has not ended. - The version a manifest reports and the version `--version` prints are folded to one casing before being compared. Folding only the printed side, which is what the pre-branch code did, manufactures the divergence this is meant to remove; both producers have to agree. Disposal closes the connection before killing the process, so a call still pending faults on a closed connection rather than on a stream that vanished under it. AGENTS.md gains two style rules it did not state: shortest `match` arm first, which is also the order `fsharp_experimental_keep_indent_in_branch` wants, and never `<|`. CLAUDE.md is a symlink to AGENTS.md so there is one file to maintain and it loads for every agent rather than only the ones that know to look. The changelog entries added on this branch move to the end of their section, which AGENTS.md has been asking for all along. --- AGENTS.md | 23 ++++++ CHANGELOG.md | 6 +- CLAUDE.md | 1 + docs/docs/end-users/FantomasClient.md | 9 ++- src/Fantomas.Client.Tests/DaemonCacheTests.fs | 27 ++++++- src/Fantomas.Client.Tests/VersionTests.fs | 4 +- src/Fantomas.Client/CHANGELOG.md | 3 + src/Fantomas.Client/FantomasToolLocator.fs | 27 +++++-- src/Fantomas.Client/FantomasToolLocator.fsi | 7 +- src/Fantomas.Client/LSPFantomasService.fs | 23 +++++- src/Fantomas.Client/LSPFantomasService.fsi | 3 +- .../LSPFantomasServiceTypes.fs | 5 +- .../EditorConfigurationTests.fs | 48 ++++++++++++ src/Fantomas.Tests/Integration/DaemonTests.fs | 2 +- src/Fantomas.Tests/TestHelpers.fs | 13 ++-- src/Fantomas/Daemon.fs | 2 +- src/Fantomas/EditorConfig.fs | 75 ++++++++++++++++++- src/Fantomas/EditorConfig.fsi | 7 ++ src/Fantomas/EditorConfigReport.fs | 55 ++++---------- src/Fantomas/EditorConfigReport.fsi | 9 ++- 20 files changed, 272 insertions(+), 77 deletions(-) create mode 120000 CLAUDE.md diff --git a/AGENTS.md b/AGENTS.md index 6307e5dc5c..9d3a0d5ed4 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -53,6 +53,29 @@ Documentation comments belong in the signature file only, never in both. A `///` alongside one in the `.fsi` is a second copy to keep in step, and the one readers and tooling see is the signature. +In a `match`, put the shortest arm first: + +```fsharp +match tool with +| None -> ValueNone +| Some(_, version) -> ValueSome(FantomasVersion(version.ToLowerInvariant())) +``` + +The short arm is nearly always the one that gets out of the way, and reading it first says what the +rest of the expression is not about. It is also the order `fsharp_experimental_keep_indent_in_branch` +wants: with the long arm last, its body can hold the indentation of the match instead of stepping in +another level. Nothing here is formatted with that setting on, but writing the arms in the order +that suits it costs nothing. + +Never write `<|`. Parenthesise instead: + +```fsharp +oneAtATimePerFile request.FilePath (fun () -> task { ... }) +``` + +It reads against the direction everything around it is written in, and it puts no visible boundary +where the argument starts. + ## Changelog When updating `CHANGELOG.md`, add new entries to the **end** of the relevant section (e.g. `### Fixed`), not the top. One entry per issue. diff --git a/CHANGELOG.md b/CHANGELOG.md index 3573330fd3..9a0c045809 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,8 +24,6 @@ ### Fixed -- The daemon held its JSON-RPC message loop while reading an `.editorconfig`, so a request that arrived during it was not read until that finished. It hands the loop back first now, and serves one request at a time per file so that the configuration warnings for a file still arrive in the order the requests did. [#3401](https://github.com/fsprojects/fantomas/pull/3401) -- A value that meant something to one setting decided the outcome for every other setting, because each value was tried against every parser in turn. `fsharp_max_record_width = cr` failed the whole run with `Carriage returns are not valid for F# code`; it is now reported as a value that setting does not accept. A value is only read as the type its own setting has. [#3401](https://github.com/fsprojects/fantomas/pull/3401) - `--verbosity` with an unrecognised value exited with code 1 and printed nothing, because the message was logged before the logger was configured. It now reports `Invalid verbosity level` on standard error. [#3399](https://github.com/fsprojects/fantomas/pull/3399) - `--out ` flattened the input tree: every file landed directly in the output folder, so two files with the same name in different subfolders silently overwrote each other. The output folder now mirrors the structure of the input folder, as the documentation already promised. [#3403](https://github.com/fsprojects/fantomas/pull/3403) - `--out ` failed with `Failed to format file` and exit code 1 when the folder of the given path did not exist. Fantomas now creates it, along with the subfolders that mirroring an input folder needs. [#3403](https://github.com/fsprojects/fantomas/pull/3403) @@ -36,6 +34,10 @@ - Given several input paths, a folder whose name contains a dot, such as `fantomas my.stuff src`, was taken for a file and reported as `Failed to format file`. A file with no extension was taken for a folder. Which one a path is, is now asked of the file system rather than guessed from the name. A single input path was already classified this way. [#3406](https://github.com/fsprojects/fantomas/pull/3406) - A `.fantomasignore` pattern that cannot be matched against a path reported the raw exception, with its stack trace, through `%A`. It now names the file and the ignore file that could not be told apart, and keeps the exception for detailed verbosity. [#3406](https://github.com/fsprojects/fantomas/pull/3406) - `--profile` reported `Line count: 0` for a file whose line endings are not the ones the platform uses, because it counted occurrences of the platform's newline rather than line breaks. A file saved with line feeds counted nothing on Windows, and one saved with carriage returns counted nothing elsewhere. [#3406](https://github.com/fsprojects/fantomas/pull/3406) +- The daemon held its JSON-RPC message loop while reading an `.editorconfig`, so a request that arrived during it was not read until that finished. It hands the loop back first now, and serves one request at a time per file so that the configuration warnings for a file still arrive in the order the requests did. [#3401](https://github.com/fsprojects/fantomas/pull/3401) +- A value that meant something to one setting decided the outcome for every other setting, because each value was tried against every parser in turn. `fsharp_max_record_width = cr` failed the whole run with `Carriage returns are not valid for F# code`; it is now reported as a value that setting does not accept. A value is only read as the type its own setting has. [#3401](https://github.com/fsprojects/fantomas/pull/3401) +- A misspelling of one of the four settings editorconfig itself defines was silently ignored, where a misspelling of a `fsharp_` setting was reported. `max_line_lenght = 100` now says so. Only names within two edits of a setting Fantomas has are read this way, so settings belonging to other tools, `indent_style` among them, stay silent. [#3401](https://github.com/fsprojects/fantomas/pull/3401) +- A negative number was accepted for any setting that takes one, so `fsharp_max_record_width = -5` formatted to nonsense widths without saying anything. It is now reported like any other value the setting does not accept. [#3401](https://github.com/fsprojects/fantomas/pull/3401) ## [8.0.0-alpha-014] - 2026-08-20 diff --git a/CLAUDE.md b/CLAUDE.md new file mode 120000 index 0000000000..47dc3e3d86 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1 @@ +AGENTS.md \ No newline at end of file diff --git a/docs/docs/end-users/FantomasClient.md b/docs/docs/end-users/FantomasClient.md index e882977996..3b957ff88d 100644 --- a/docs/docs/end-users/FantomasClient.md +++ b/docs/docs/end-users/FantomasClient.md @@ -91,7 +91,7 @@ Worth knowing: empty `Problems` array when the configuration is fine. That is what lets you clear a warning once the user fixes it. - You can have as many format requests in flight as you like. Warnings for one file arrive in the - order you asked for them, because the daemon serves one request at a time per file, so an empty + order the daemon received them, because the daemon serves one request at a time per file, so an empty one never overtakes problems that are still current. Requests for different files are served concurrently and their warnings interleave; `FilePath` is what tells them apart. - Nothing is coalesced. Several requests queued for one file each run to completion in turn, so a @@ -111,7 +111,10 @@ Worth knowing: than allowed to fault the connection, so nothing is lost but nothing is reported either. If you are talking to the daemon yourself rather than through `Fantomas.Client`, the notification -arrives on `fantomas/configurationWarning` carrying one object: +arrives on `fantomas/configurationWarning` carrying one object. The shape of that object is below. +The framing around it is StreamJsonRpc's default, which is JSON-RPC with `Content-Length` headers, +the same as the Language Server Protocol uses, so this is what the payload looks like and not what +goes on the wire byte for byte: ```json { @@ -175,7 +178,7 @@ let schema = service.ConfigurationAsync("/home/me/MyProject/Library.fs").Result ```fsharp // Stop every daemon this service started. Call it when your tool shuts down. -(service :> System.IDisposable).Dispose() +service.Dispose() ``` `ClearCache` throws away the daemons without disposing the service, which is what you want after the diff --git a/src/Fantomas.Client.Tests/DaemonCacheTests.fs b/src/Fantomas.Client.Tests/DaemonCacheTests.fs index 5223021878..d7dc679ddc 100644 --- a/src/Fantomas.Client.Tests/DaemonCacheTests.fs +++ b/src/Fantomas.Client.Tests/DaemonCacheTests.fs @@ -43,14 +43,14 @@ let private operationsFor created |> Result.iter recorder.Record created } -let private findsVersion (version: FantomasVersion) (folder: Folder) = +let private findsVersion (version: FantomasVersion) (folder: Folder) : Result = Ok(FantomasToolFound(version, FantomasToolStartInfo.LocalTool folder)) -let private startsFine (nextId: int ref) (startInfo: FantomasToolStartInfo) = +let private startsFine (nextId: int ref) (startInfo: FantomasToolStartInfo) : Result = nextId.Value <- nextId.Value + 1 Ok(new FakeDaemon(nextId.Value, startInfo)) -let private neverStarts (_: FantomasToolStartInfo) = +let private neverStarts (_: FantomasToolStartInfo) : Result = Error(ProcessStartError.UnExpectedException("dotnet", "fantomas --daemon", "boom")) let private expectOk (result: Result<'a, GetDaemonError>) : 'a = @@ -109,6 +109,27 @@ let ``a daemon that crashed is replaced, and the one it replaces is disposed`` ( // Restarted the way the daemon it replaces was started, not the way this folder resolves now. Assert.That((second :> IDaemon).StartInfo, Is.EqualTo (first :> IDaemon).StartInfo) +// The daemon is shared by every folder on its version, so which folder happens to notice it has +// died must not decide where the replacement runs. The cached-folder path always restarted it as it +// was started; this path used to restart it the way the noticing folder resolves now. +[] +let ``a crashed daemon is restarted as it was started, whichever folder notices`` () = + let recorder = Recorder() + let operations = operationsFor recorder (findsVersion version) (startsFine (ref 0)) + + // `/repo` starts it, `/repo/nested` is the one that finds it dead. + let first, state = resolveDaemon operations ServiceState.Empty folder + (expectOk first).Running <- false + + let replacement, _ = resolveDaemon operations state nested + let replacement = expectOk replacement + + Assert.That( + (replacement :> IDaemon).StartInfo, + Is.EqualTo(FantomasToolStartInfo.LocalTool folder), + "the replacement should run where the daemon it replaces ran, not where the folder that noticed does" + ) + // The regression this is here for: dropping a version from the cache used to leave every folder // that resolved to it pointing at a version with no daemon. That is the one state resolveDaemon // cannot get out of, so the folder answered CompatibleVersionIsKnownButNoDaemonIsRunning for the diff --git a/src/Fantomas.Client.Tests/VersionTests.fs b/src/Fantomas.Client.Tests/VersionTests.fs index d735b80874..8fdee9acc9 100644 --- a/src/Fantomas.Client.Tests/VersionTests.fs +++ b/src/Fantomas.Client.Tests/VersionTests.fs @@ -11,6 +11,8 @@ open Fantomas.Client.FantomasToolLocator [] [] [] -[] +// Folded, because `CompatibleTool` folds the manifest side too. One casing has to win +// and the two producers have to pick the same one. +[] let ``a printed version reads as the version a tool manifest names`` (printed: string, expected: string) = Assert.That(normalizeVersion printed, Is.EqualTo expected) diff --git a/src/Fantomas.Client/CHANGELOG.md b/src/Fantomas.Client/CHANGELOG.md index ea37a19383..7e52a231de 100644 --- a/src/Fantomas.Client/CHANGELOG.md +++ b/src/Fantomas.Client/CHANGELOG.md @@ -21,6 +21,9 @@ This is the changelog for the Fantomas.Client package specifically. It's distinc - A Fantomas resolved from the `PATH` counted as a different version from the same Fantomas resolved from a `dotnet-tools.json`, and got a second daemon: `fantomas --version` prints `Fantomas v8.0.0+` where `dotnet tool list` prints `8.0.0`. [#3401](https://github.com/fsprojects/fantomas/pull/3401) - When a daemon failed its handshake, the standard error quoted in the reported message was whatever had arrived by then rather than all of it, so the lines explaining the failure were usually missing. [#3401](https://github.com/fsprojects/fantomas/pull/3401) - Two format requests in flight for the same file could deliver their configuration warnings in either order, so an empty one could clear problems that were still current. Nothing on the wire says which request a warning belongs to, so a client could not sort them out. The daemon now serves one request at a time per file; different files are unaffected. [#3401](https://github.com/fsprojects/fantomas/pull/3401) +- A daemon whose connection had ended was still handed out while its process lingered, so every request against it failed against a daemon the cache still believed in. Liveness now means the process is up and the connection has not ended. [#3401](https://github.com/fsprojects/fantomas/pull/3401) +- Replacing a crashed daemon started it the way whichever folder noticed the crash resolves now, rather than the way the daemon it replaces was started, so a daemon shared by two folders could come back under a different working directory. [#3401](https://github.com/fsprojects/fantomas/pull/3401) +- The version a tool manifest reports and the version `fantomas --version` prints are now folded to one casing before being compared, so a prerelease label written two ways no longer resolves to two daemons. [#3401](https://github.com/fsprojects/fantomas/pull/3401) - The version handshake with a freshly started daemon had no timeout. A process that started but never answered held up every later request, because daemons are resolved on a single mailbox. It is now given 30 seconds, after which it is killed like any other failed handshake and reported as `Daemon did not answer the version request within 30000 ms.` rather than a bare timeout message. [#3401](https://github.com/fsprojects/fantomas/pull/3401) ## [0.11.0] - 2026-04-16 diff --git a/src/Fantomas.Client/FantomasToolLocator.fs b/src/Fantomas.Client/FantomasToolLocator.fs index de3e61d7ef..7c9a28db88 100644 --- a/src/Fantomas.Client/FantomasToolLocator.fs +++ b/src/Fantomas.Client/FantomasToolLocator.fs @@ -115,7 +115,7 @@ let (|CompatibleTool|_|) (lines: string list) : FantomasVersion voption = match lines with | HeaderLine :: Dashes :: Tools tools -> - let tool = + let tool: (string * string) option = List.tryFind (fun (packageId, version) -> match packageId, version with @@ -123,7 +123,11 @@ let (|CompatibleTool|_|) (lines: string list) : FantomasVersion voption = | _ -> false) tools - tool |> ValueOption.ofOption |> ValueOption.map (snd >> FantomasVersion) + // Folded to match `normalizeVersion`. Daemons are cached under this string and the two + // producers are compared as plain strings, so both sides have to normalise the same way. + match tool with + | None -> ValueNone + | Some(_, version) -> ValueSome(FantomasVersion(version.ToLowerInvariant())) | _ -> ValueNone let isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) @@ -141,11 +145,22 @@ let normalizeVersion (printed: string) : string = else text - let printed = printed.Trim() |> dropPrefix "fantomas" |> dropPrefix "v" + let printed: string = printed.Trim() |> dropPrefix "fantomas" |> dropPrefix "v" - match printed.IndexOf('+') with - | -1 -> printed - | index -> printed.Substring(0, index) + let buildMetadata: int = printed.IndexOf('+') + + let withoutBuildMetadata: string = + if buildMetadata = -1 then + printed + else + printed.Substring(0, buildMetadata) + + // Folded, and folded on the other side too, in `CompatibleTool`. Doing it here alone would be + // worse than not doing it: the two producers have to agree, and they are compared as plain + // strings. Semver reads prerelease identifiers case sensitively, so this is a deliberate + // decision that `8.0.0-Alpha-014` and `8.0.0-alpha-014` name one Fantomas, which is true of + // every package either path can resolve. + withoutBuildMetadata.ToLowerInvariant() /// How long a freshly started daemon has to answer the version handshake before it is given up on. [] diff --git a/src/Fantomas.Client/FantomasToolLocator.fsi b/src/Fantomas.Client/FantomasToolLocator.fsi index c0bbff2932..7e2cf042b2 100644 --- a/src/Fantomas.Client/FantomasToolLocator.fsi +++ b/src/Fantomas.Client/FantomasToolLocator.fsi @@ -3,9 +3,10 @@ module Fantomas.Client.FantomasToolLocator open Fantomas.Client.LSPFantomasServiceTypes /// The version `fantomas --version` printed, as `dotnet tool list` would have written it: no -/// `Fantomas` in front, no leading `v`, no `+` on the end. Daemons are cached by this -/// string, so the same Fantomas resolved once from a tool manifest and once from the PATH has to -/// come out of both as the same text, or it gets two processes. +/// `Fantomas` in front, no leading `v`, no `+` on the end, and folded to lower case as the +/// manifest side is. Daemons are cached by this string, so the same Fantomas resolved once from a +/// tool manifest and once from the PATH has to come out of both as the same text, or it gets two +/// processes. val internal normalizeVersion: printed: string -> string val findFantomasTool: workingDir: Folder -> Result diff --git a/src/Fantomas.Client/LSPFantomasService.fs b/src/Fantomas.Client/LSPFantomasService.fs index 24cdc085dc..6a8f38dfd3 100644 --- a/src/Fantomas.Client/LSPFantomasService.fs +++ b/src/Fantomas.Client/LSPFantomasService.fs @@ -57,11 +57,11 @@ let startDaemon (state: ServiceState<'daemon>) : Result<'daemon, GetDaemonError> * ServiceState<'daemon> = match operations.Create startInfo with + | Error error -> Error(GetDaemonError.FantomasProcessStart error), forgetVersion version state | Ok daemon -> Ok daemon, { Daemons = Map.add version daemon state.Daemons FolderToVersion = Map.add folder version state.FolderToVersion } - | Error error -> Error(GetDaemonError.FantomasProcessStart error), forgetVersion version state let rec resolveDaemon (operations: DaemonOperations<'daemon>) @@ -106,8 +106,17 @@ let rec resolveDaemon FolderToVersion = Map.add folder version state.FolderToVersion } | running -> // A daemon that crashed is replaced, but dispose it first so the handles it still - // holds are released. - running |> Option.iter (fun daemon -> (daemon :> IDaemon).Dispose()) + // holds are released. The replacement is started the way the dead one was, not the + // way this folder resolves now, so that a daemon two folders share does not change + // working directory depending on which of them happened to notice it had died. + let startInfo = + match running with + | None -> startInfo + | Some daemon -> + let asItWasStarted = (daemon :> IDaemon).StartInfo + (daemon :> IDaemon).Dispose() + asItWasStarted + startDaemon operations version startInfo folder state | Error FantomasToolError.NoCompatibleVersionFound -> Error GetDaemonError.InCompatibleVersionFound, state | Error(FantomasToolError.DotNetListError error) -> Error(GetDaemonError.DotNetToolListError error), state @@ -120,7 +129,13 @@ type CachedDaemon(tool: RunningFantomasTool) = interface IDaemon with member _.StartInfo = tool.StartInfo - member _.IsRunning = not tool.Process.HasExited + + member _.IsRunning = + // Both halves matter. A process that is up but whose connection has ended can never + // answer again, and handing its `RpcClient` out means every request from then on fails + // against a daemon the cache still believes in. + not tool.Process.HasExited && not tool.RpcClient.Completion.IsCompleted + member _.Dispose() = (tool :> IDisposable).Dispose() let createAgent (ct: CancellationToken) (onConfigurationWarning: ConfigurationWarning -> unit) : MailboxProcessor = diff --git a/src/Fantomas.Client/LSPFantomasService.fsi b/src/Fantomas.Client/LSPFantomasService.fsi index 7a57e992cc..a3eff607c9 100644 --- a/src/Fantomas.Client/LSPFantomasService.fsi +++ b/src/Fantomas.Client/LSPFantomasService.fsi @@ -30,7 +30,8 @@ type internal IDaemon = /// than the way the folder asking for it resolves now. abstract StartInfo: FantomasToolStartInfo - /// Whether the process behind it is still up. + /// Whether it can still serve a request: the process is up and the connection to it has not + /// ended. A daemon failing either half is disposed and replaced. abstract IsRunning: bool /// How the cache reaches the world. Only the two things it cannot answer for itself: everything a diff --git a/src/Fantomas.Client/LSPFantomasServiceTypes.fs b/src/Fantomas.Client/LSPFantomasServiceTypes.fs index eed7669350..7ecb3c3622 100644 --- a/src/Fantomas.Client/LSPFantomasServiceTypes.fs +++ b/src/Fantomas.Client/LSPFantomasServiceTypes.fs @@ -69,11 +69,14 @@ type RunningFantomasTool = interface IDisposable with member this.Dispose() : unit = + // Connection first: a call still pending faults on a closed connection, which it is + // written to expect, rather than on a stream that vanished under it. + this.RpcClient.Dispose() + if not this.Process.HasExited then this.Process.Kill() this.Process.Dispose() - this.RpcClient.Dispose() [] type ProcessStartError = diff --git a/src/Fantomas.Tests/EditorConfigurationTests.fs b/src/Fantomas.Tests/EditorConfigurationTests.fs index dac1fe54e1..fcb14e177f 100644 --- a/src/Fantomas.Tests/EditorConfigurationTests.fs +++ b/src/Fantomas.Tests/EditorConfigurationTests.fs @@ -194,6 +194,19 @@ fsharp_max_function_binding_width=40 config.MaxValueBindingWidth == 40 config.MaxFunctionBindingWidth == 40 +// A section header with no keys under it sets nothing, so there is no configuration to hand back +// and nothing to complain about. +[] +let ``an editorconfig that sets nothing reads as no configuration at all`` () = + let rootDir = tempName () + + use _configFixture = + new ConfigurationFile(defaultConfig, rootDir, content = "\n[*.fs]\n") + + use fsharpFile = new FSharpFile(rootDir) + + EditorConfig.tryReadConfiguration fsharpFile.FSharpFile == None + [] let ``non existing file should return defaults for readConfiguration`` () = let rootDir = tempName () @@ -732,6 +745,41 @@ let ``an unparsable value for a Fantomas setting is still reported`` () = problems == [ EditorConfig.EditorConfigProblem.UnrecognizedValue("fsharp_max_record_width", "banana") ] +// A mistake in `max_line_length` was silently ignored exactly as a mistake in a `fsharp_` setting +// was, and it is the same mistake. +[] +let ``a misspelling of an unprefixed setting is reported too`` () = + let _, problems = parse [ "max_line_lenght", "100" ] + + problems + == [ EditorConfig.EditorConfigProblem.UnknownSetting "max_line_lenght" ] + +// The reason the distance for unprefixed keys is tighter than the one a suggestion is offered at. +// `indent_style` is three edits from `indent_size` and sits in very nearly every `.editorconfig` +// ever written; warning about it would put a false report in front of almost every user. +[] +let ``settings other tools really use are not read as misspellings of ours`` () = + let _, problems = + parse + [ "indent_style", "space" + "tab_width", "4" + "trim_trailing_whitespace", "true" + "charset", "utf-8" + "root", "true" + "quote_type", "double" + "dotnet_diagnostic_CA1000_severity", "none" ] + + problems == [] + +[] +let ``a negative width is not a width`` () = + let config, problems = parse [ "fsharp_max_record_width", "-5" ] + + problems + == [ EditorConfig.EditorConfigProblem.UnrecognizedValue("fsharp_max_record_width", "-5") ] + + config.MaxRecordWidth == defaultConfig.MaxRecordWidth + [] let ``settings belonging to other tools are left alone`` () = let _, problems = diff --git a/src/Fantomas.Tests/Integration/DaemonTests.fs b/src/Fantomas.Tests/Integration/DaemonTests.fs index 357aedbfb9..2365c4335a 100644 --- a/src/Fantomas.Tests/Integration/DaemonTests.fs +++ b/src/Fantomas.Tests/Integration/DaemonTests.fs @@ -96,7 +96,7 @@ let private theOnlyWarning (warnings: ConfigurationWarning list) : Configuration Assert.Fail $"Expected exactly one configuration warning, got %A{otherwise}" failwith "unreachable" -let private problemsOf (warning: ConfigurationWarning) = +let private problemsOf (warning: ConfigurationWarning) : (int * int * string * string) array = warning.Problems |> Array.map (fun problem -> problem.Code, problem.Source, problem.Setting, problem.Value) diff --git a/src/Fantomas.Tests/TestHelpers.fs b/src/Fantomas.Tests/TestHelpers.fs index 5f48814817..0027fe40db 100644 --- a/src/Fantomas.Tests/TestHelpers.fs +++ b/src/Fantomas.Tests/TestHelpers.fs @@ -97,10 +97,10 @@ type OutputFolder internal () = /// A folder of its own, holding an `.editorconfig` and one F# file it applies to. /// -/// A test that reads configuration from disk needs the two next to each other, and -/// `ConfigurationFile` writes its `.editorconfig` straight into the temp folder, where every other -/// test doing the same finds it. `root = true` goes in front of the content so the chain stops -/// here rather than picking up whatever sits above the temp folder on this machine. +/// A test that reads configuration from disk needs the two next to each other. Writing the +/// `.editorconfig` straight into the temp folder, as this used to, puts it where every other test +/// doing the same finds it. `root = true` goes in front of the content so the chain stops here +/// rather than picking up whatever sits above the temp folder on this machine. type ConfiguredCodeSample internal (editorConfig: string, codeSnippet: string, ?extension: string) = let folder = Path.Join(Path.GetTempPath(), Guid.NewGuid().ToString("N")) do Directory.CreateDirectory folder |> ignore @@ -239,7 +239,10 @@ let defaultSettings: CliSettings = /// A `DaemonEnvironment` over the given file system, reading whatever configuration is handed in /// rather than an `.editorconfig` on disk. Enough for a test about what the daemon does with a /// configuration, as opposed to one about where the configuration came from. -let daemonEnvironment (fs: IFileSystem) (readConfiguration: string -> EditorConfig.EditorConfigResult option) = +let daemonEnvironment + (fs: IFileSystem) + (readConfiguration: string -> EditorConfig.EditorConfigResult option) + : DaemonEnvironment = { FileSystem = fs ReadConfiguration = readConfiguration Log = silentLogger } diff --git a/src/Fantomas/Daemon.fs b/src/Fantomas/Daemon.fs index cc5a72345e..d5684c5648 100644 --- a/src/Fantomas/Daemon.fs +++ b/src/Fantomas/Daemon.fs @@ -44,8 +44,8 @@ let configurationFor : FormatConfig * ConfigurationWarning = let config, editorConfigFiles, fileProblems = match readConfiguration filePath with - | Some result -> result.Config, result.EditorConfigFiles, result.Problems | None -> FormatConfig.Default, [], [] + | Some result -> result.Config, result.EditorConfigFiles, result.Problems let fromEditorConfig = List.map (toConfigurationProblem ConfigurationProblemSource.EditorConfig) fileProblems diff --git a/src/Fantomas/EditorConfig.fs b/src/Fantomas/EditorConfig.fs index 51b9cab981..9f98c58575 100644 --- a/src/Fantomas/EditorConfig.fs +++ b/src/Fantomas/EditorConfig.fs @@ -77,7 +77,9 @@ let parseSettingValue (defaultValue: obj) (value: string) : obj option = match defaultValue with | :? int -> match System.Int32.TryParse(value) with - | true, number -> Some(box number) + // No setting Fantomas has means anything below zero, and a run that took one would format + // to nonsense widths without ever saying so. + | true, number when number >= 0 -> Some(box number) | _ -> None | :? bool -> if value = "true" then Some(box true) @@ -136,9 +138,73 @@ let supportedSettings: string list = let supportedSettingLookup: HashSet = HashSet(settingNames, System.StringComparer.OrdinalIgnoreCase) +/// How many single character edits turn one setting name into the other, capped at `limit`. +/// +/// The cap answers without measuring when the two lengths already differ by more than it. Anything +/// past that is measured in full, so two names of the same length are compared character by +/// character however unalike they are. +let editDistance (limit: int) (left: string) (right: string) : int = + if abs (left.Length - right.Length) > limit then + limit + 1 + else + let mutable previous = Array.init (right.Length + 1) id + let mutable current = Array.zeroCreate (right.Length + 1) + + for row in 1 .. left.Length do + current[0] <- row + + for column in 1 .. right.Length do + let substitution = + previous[column - 1] + (if left[row - 1] = right[column - 1] then 0 else 1) + + current[column] <- min (min (current[column - 1] + 1) (previous[column] + 1)) substitution + + let swap = previous + previous <- current + current <- swap + + min previous[right.Length] (limit + 1) + +/// The supported setting closest to `setting`, when one is within `limit` edits of it. +/// +/// Two candidates the same distance away are separated by the order of `supportedSettings`, since +/// `List.sortBy` is stable. Not a case anyone reaches by mistyping: the two closest settings +/// Fantomas has are three edits apart, so a tie takes a string built on purpose to sit between +/// them. +let nearestSetting (limit: int) (setting: string) : string option = + supportedSettings + |> List.choose (fun candidate -> + match editDistance limit setting candidate with + | distance when distance <= limit -> Some(candidate, distance) + | _ -> None) + |> List.sortBy snd + |> List.tryHead + |> Option.map fst + +/// How far an unprefixed key may be from a setting Fantomas has before it is read as a misspelling +/// of it rather than as something belonging to another tool. +/// +/// Tighter than the distance a suggestion is offered at, and it has to be. `indent_style` is three +/// edits from `indent_size`, and it is in very nearly every `.editorconfig` ever written; warning +/// about it would put a false report in front of almost every user. Two edits reaches every +/// realistic typo, `max_line_lenght` included, and reaches nothing anyone meant to write. +[] +let MaximumUnprefixedTypoDistance = 2 + +/// Whether an unprefixed key looks like a misspelling of a setting Fantomas has, rather than a +/// setting belonging to some other tool. `fsharp_`-prefixed keys are ours by construction, so this +/// only has to judge the ones that carry no prefix. +let looksLikeAMisspelling (setting: string) : bool = + (nearestSetting MaximumUnprefixedTypoDistance setting).IsSome + let unknownFantomasSettings (settings: string seq) : EditorConfigProblem list = settings - |> Seq.filter isFantomasSetting + |> Seq.filter (fun setting -> + // Anything carrying our prefix is ours to complain about. Anything without one belongs to + // another tool unless it is close enough to one of ours to be a typo of it: a mistake in + // `max_line_length` is silently ignored exactly as a mistake in a `fsharp_` setting was, + // and it is the same mistake. + isFantomasSetting setting || looksLikeAMisspelling setting) |> Seq.sortWith compareSettings |> Seq.choose (fun setting -> if supportedSettingLookup.Contains setting then @@ -156,7 +222,7 @@ let parseOptionsFromEditorConfig // here rather than in one caller: a key that differs only in case would otherwise match no // setting and raise no warning either. Each entry carries the spelling it was written with, // so a problem names what the author typed rather than the folded form. - let properties = + let properties: Dictionary = let properties = Dictionary(System.StringComparer.OrdinalIgnoreCase) @@ -165,7 +231,8 @@ let parseOptionsFromEditorConfig properties - let unrecognizedValues = ResizeArray() + let unrecognizedValues: ResizeArray = + ResizeArray() let newValues = getFantomasFields fallbackConfig diff --git a/src/Fantomas/EditorConfig.fsi b/src/Fantomas/EditorConfig.fsi index abd213cd24..34ec7fd1aa 100644 --- a/src/Fantomas/EditorConfig.fsi +++ b/src/Fantomas/EditorConfig.fsi @@ -49,6 +49,13 @@ val supportedSettings: string list /// Matched without regard to case, as editorconfig matches keys. val isFantomasSetting: setting: string -> bool +/// How many single character edits turn one setting name into the other, stopping once the answer +/// is known to be above `limit`. +val editDistance: limit: int -> left: string -> right: string -> int + +/// The supported setting closest to `setting`, when one is within `limit` edits of it. +val nearestSetting: limit: int -> setting: string -> string option + /// Read a `FormatConfig` from editorconfig properties, falling back to `fallbackConfig` for /// anything the properties do not set. Keys and values are both matched without regard to case, /// as editorconfig defines them, and when two keys fold onto one the last wins. Returns the diff --git a/src/Fantomas/EditorConfigReport.fs b/src/Fantomas/EditorConfigReport.fs index 77a1eb2238..7af6daba89 100644 --- a/src/Fantomas/EditorConfigReport.fs +++ b/src/Fantomas/EditorConfigReport.fs @@ -10,39 +10,20 @@ open Fantomas.EditorConfig type EditorConfigReporter = string -> EditorConfigProblem list -> unit let fantomasVersion: string = - let version = CodeFormatter.GetVersion() - - match version.IndexOf('+') with - | -1 -> version - | index -> version.Substring(0, index) - -/// How many single character edits turn one setting name into the other, capped at `limit` so a -/// name nothing like any of ours stops being measured early rather than walking every candidate -/// to the end. -let editDistance (limit: int) (left: string) (right: string) : int = - if abs (left.Length - right.Length) > limit then - limit + 1 - else - let mutable previous = Array.init (right.Length + 1) id - let mutable current = Array.zeroCreate (right.Length + 1) - - for row in 1 .. left.Length do - current[0] <- row - - for column in 1 .. right.Length do - let substitution = - previous[column - 1] + (if left[row - 1] = right[column - 1] then 0 else 1) - - current[column] <- min (min (current[column - 1] + 1) (previous[column] + 1)) substitution + let version: string = CodeFormatter.GetVersion() + let buildMetadata: int = version.IndexOf('+') - let swap = previous - previous <- current - current <- swap - - min previous[right.Length] (limit + 1) + if buildMetadata = -1 then + version + else + version.Substring(0, buildMetadata) /// Close enough that naming the other one is help rather than noise. Three edits is roughly a /// doubled letter, a dropped one and a swapped pair; beyond that the guess is worse than silence. +/// +/// Deliberately looser than `MaximumUnprefixedTypoDistance`, which decides whether to say anything +/// at all. By the time a suggestion is offered we have already decided the setting is a mistake, +/// so a slightly wilder guess costs nothing. [] let MaximumSuggestionDistance = 3 @@ -60,15 +41,7 @@ let suggestionFor (setting: string) : string option = match unprefixed with | Some unprefixed when List.contains unprefixed supportedSettings -> Some unprefixed - | _ -> - supportedSettings - |> List.choose (fun candidate -> - match editDistance MaximumSuggestionDistance setting candidate with - | distance when distance <= MaximumSuggestionDistance -> Some(candidate, distance) - | _ -> None) - |> List.sortBy snd - |> List.tryHead - |> Option.map fst + | _ -> nearestSetting MaximumSuggestionDistance setting /// Settings and values are quoted the way the rest of the tool quotes what it was given, and for /// the same reason: both are text someone else wrote. A value can be empty, or carry spaces, or @@ -116,8 +89,10 @@ let createReporter (log: ILogger) : EditorConfigReporter = // Files are formatted in parallel, so more than one of them can arrive here at once. The whole // report is one message rather than a line each: written as several, another thread's report // can land in the middle of this one. - let reported = ConcurrentDictionary() - let supportedSettingsWritten = ref 0 + let reported: ConcurrentDictionary = + ConcurrentDictionary() + + let supportedSettingsWritten: int ref = ref 0 fun origin problems -> match describe origin problems with diff --git a/src/Fantomas/EditorConfigReport.fsi b/src/Fantomas/EditorConfigReport.fsi index 0a853d196f..af8601ccc1 100644 --- a/src/Fantomas/EditorConfigReport.fsi +++ b/src/Fantomas/EditorConfigReport.fsi @@ -12,6 +12,10 @@ type EditorConfigReporter = string -> EditorConfigProblem list -> unit /// settings a user is pointed at are tied to a version they can act on. val fantomasVersion: string +/// How far a setting may be from a supported one before the guess is worse than silence. +[] +val MaximumSuggestionDistance: int = 3 + /// The supported setting closest to one Fantomas does not have, when there is a close one. /// A prefixed spelling of a setting editorconfig itself defines, `fsharp_max_line_length` for /// `max_line_length`, is answered outright; anything else has to be within a few characters. @@ -31,8 +35,9 @@ val describeSupportedSettings: unit -> string /// A reporter over `log`. Writes each distinct report once, however many files are formatted: /// the command line reads the same `.editorconfig` again for every one of them, and without -/// this a single typo would be reported once per file. At debug verbosity it also writes the -/// supported settings out, once per run. +/// this a single typo would be reported once per file. At debug verbosity the first report it +/// writes is followed by the supported settings, once per run; a run with nothing to report says +/// nothing at all. val createReporter: log: ILogger -> EditorConfigReporter /// Read the `.editorconfig` that applies to a file, reporting anything in it Fantomas cannot use.