From dbd15ead76dfa5faeb2157f480afac9ce25f80d4 Mon Sep 17 00:00:00 2001 From: Florian Verdonck Date: Mon, 21 Sep 2026 08:57:23 +0200 Subject: [PATCH] Keep the unindent after trailing trivia outside the closed scope A comment at the end of a match that closes a computation expression, or a let body, pushed the closing brace and the next binding one level too far to the right. unindentWithTriviaAwareness spliced its UnIndentBy in front of the comment's newline. That newline is written inside the atCurrentColumn scope of the match, which clamps the indent to its column and restores the old indent on exit, so the unindent was undone before the next line. The WriterModel applied the same unindent to the state after the scope had closed, so the model and the replay disagreed from there on. Move the trivia newline past the scope's restore events instead, with the UnIndentBy right before it. The comment keeps its column; only the line after it changes. Without scope events the event order is the same as before. findTrailingTriviaNewline now skips the NodeStart and NodeEnd markers of debug mode, so the writer events script shows what production does. Mark the changelog as 8.0.1. Fixes #3481 --- CHANGELOG.md | 3 +- .../CodePrinterHelperFunctionsTests.fs | 9 +- .../ComputationExpressionTests.fs | 147 ++++++++++++++++++ src/Fantomas.Core/Context.fs | 29 +++- 4 files changed, 177 insertions(+), 11 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b42fbd9751..9f7f4c492e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,11 +1,12 @@ # Changelog -## [Unreleased] +## [8.0.1] - 2026-09-21 ### Fixed - Remove TailCall shim from Fantomas.FCS. [#3476](https://github.com/fsprojects/fantomas/pull/3476) - Fantomas 8 with use bindings in fsx-file. A `use` at the top level of a script makes the parser warn that it is treated as `let`, and the check Fantomas runs over its own output refused the file on that warning. The warning is about the source as the author wrote it, not about anything the formatter changed, so it is now one of the warnings the check tolerates. [#3478](https://github.com/fsprojects/fantomas/issues/3478) +- Unexpected de-indent after trivia after expression. A comment at the end of a `match` that closes a computation expression, or a `let` body, pushed the closing brace and the next binding one level too far to the right. The unindent before the closing line was placed in front of the comment's newline, where the `match` still held the column it had claimed and restored its own indent on the way out, undoing the unindent. The newline now moves past those restores, so the line after the comment starts at the outer level. [#3481](https://github.com/fsprojects/fantomas/issues/3481) ## [8.0.0] - 2026-09-15 diff --git a/src/Fantomas.Core.Tests/CodePrinterHelperFunctionsTests.fs b/src/Fantomas.Core.Tests/CodePrinterHelperFunctionsTests.fs index dd02ed0c7b..71deb5c388 100644 --- a/src/Fantomas.Core.Tests/CodePrinterHelperFunctionsTests.fs +++ b/src/Fantomas.Core.Tests/CodePrinterHelperFunctionsTests.fs @@ -1025,7 +1025,8 @@ let ``unindentWithTriviaAwareness splices before multiline block comment`` () = [] let ``unindentWithTriviaAwareness finds trivia past trailing restore events`` () = - // Simulates the try-with pattern where restore/unindent events follow the trivia + // Simulates an atCurrentColumn scope closing after the trivia. The newline has to move past the + // restore events, or the RestoreIndent would undo the unindent before the next line is written. let f = indent +> !-"content" @@ -1044,10 +1045,10 @@ let ``unindentWithTriviaAwareness finds trivia past trailing restore events`` () Write "content" WriteLineBecauseOfTrivia WriteTrivia "// trailing comment" - UnIndentBy 4 - WriteLineBecauseOfTrivia RestoreAtColumn 0 - RestoreIndent 0 ] -> Assert.Pass() + RestoreIndent 0 + UnIndentBy 4 + WriteLineBecauseOfTrivia ] -> Assert.Pass() | _ -> Assert.Fail $"Unexpected events: %A{events}" // ============================================================================= diff --git a/src/Fantomas.Core.Tests/ComputationExpressionTests.fs b/src/Fantomas.Core.Tests/ComputationExpressionTests.fs index 11912318cc..e7f62f080f 100644 --- a/src/Fantomas.Core.Tests/ComputationExpressionTests.fs +++ b/src/Fantomas.Core.Tests/ComputationExpressionTests.fs @@ -2626,3 +2626,150 @@ let getBlah _ = } |> Cmd.ofAsyncMsg """ + +[] +let ``comment after match bang as last expression in computation expression, 3481`` () = + formatSourceString + """ +let f () = task { + match! g () with + | Ok _ -> () + | Error _ -> () + + // comment +} + +let x = 1 +""" + config + |> prepend newline + |> should + equal + """ +let f () = + task { + match! g () with + | Ok _ -> () + | Error _ -> () + + // comment + } + +let x = 1 +""" + +[] +let ``comment after match bang in test module, 3481`` () = + formatSourceString + """ +namespace X +module TopologicalBuilderTests = + + [] + let ``Builder works with ANY backend (backend-agnostic principle)`` () = task { + let program = topological simulatorBackend { + return () + } + + match! TopologicalBuilder.execute simulatorBackend program with + | Ok _ -> Assert.True(true) + | Error err -> Assert.Fail($"Program failed: {err.Message}") + + // Programs are COMPLETELY backend-agnostic! + } + + [] + let ``Builder with braiding sequence`` () = + task { + // Increased backend capacity to 20 anyons to support 6 logical qubits + let backend = TopologicalUnifiedBackendFactory.createUnified AnyonSpecies.AnyonType.Ising 20 + + () + } +""" + config + |> prepend newline + |> should + equal + """ +namespace X + +module TopologicalBuilderTests = + + [] + let ``Builder works with ANY backend (backend-agnostic principle)`` () = + task { + let program = topological simulatorBackend { return () } + + match! TopologicalBuilder.execute simulatorBackend program with + | Ok _ -> Assert.True(true) + | Error err -> Assert.Fail($"Program failed: {err.Message}") + + // Programs are COMPLETELY backend-agnostic! + } + + [] + let ``Builder with braiding sequence`` () = + task { + // Increased backend capacity to 20 anyons to support 6 logical qubits + let backend = + TopologicalUnifiedBackendFactory.createUnified AnyonSpecies.AnyonType.Ising 20 + + () + } +""" + +[] +let ``comment after match as last expression in computation expression`` () = + formatSourceString + """ +let f () = task { + match g () with + | Ok _ -> () + | Error _ -> () + // comment +} + +let x = 1 +""" + config + |> prepend newline + |> should + equal + """ +let f () = + task { + match g () with + | Ok _ -> () + | Error _ -> () + // comment + } + +let x = 1 +""" + +[] +let ``comment after match as last expression in let binding`` () = + formatSourceString + """ +let f () = + match g () with + | Ok _ -> () + | Error _ -> () + // comment + +let x = 1 +""" + config + |> prepend newline + |> should + equal + """ +let f () = + match g () with + | Ok _ -> () + | Error _ -> () + // comment + +let x = 1 +""" diff --git a/src/Fantomas.Core/Context.fs b/src/Fantomas.Core/Context.fs index f2a51e30a7..1f42452844 100644 --- a/src/Fantomas.Core/Context.fs +++ b/src/Fantomas.Core/Context.fs @@ -780,7 +780,7 @@ type LongExpressionLayout = | NewlineOnly /// Walk backward from a node, skipping events that don't represent user-visible content -/// (restore/unindent/indent events that unwind surrounding contexts). +/// (restore/unindent/indent events that unwind surrounding contexts, and the node markers of debug mode). /// Returns the node where trailing trivia ends, or null if no trivia is found. let findTrailingTriviaNewline (events: EventList) : EventNode = let mutable current = events.Tail @@ -793,6 +793,8 @@ let findTrailingTriviaNewline (events: EventList) : EventNode = | RestoreAtColumn _ | UnIndentBy _ | IndentBy _ + | NodeStart _ + | NodeEnd _ | WriteLine -> true | _ -> false ) do @@ -856,13 +858,28 @@ let unindentWithTriviaAwareness (ctx: Context) = writerEvent (UnIndentBy unindentAmount) ctx else - // Splice the UnIndentBy into the DLL before the trailing trivia newline, - // and update the WriterModel using the same logic as WriterModel.update. - ctx.WriterEvents.InsertBefore(triviaNewline, UnIndentBy unindentAmount) - |> ignore + // The trivia newline was written inside whatever scopes the content opened, and the events after + // it are those scopes unwinding. An `atCurrentColumn` scope clamps the indent to its column and + // restores the old indent on exit, so an UnIndentBy spliced in front of the newline would be + // undone before the next line is written. See https://github.com/fsprojects/fantomas/issues/3481. + // Move the newline past the unwinding events instead, with the UnIndentBy right before it, so the + // line after the trivia starts at the unindented column. + ctx.WriterEvents.Remove(triviaNewline) + ctx.WriterEvents.Append(UnIndentBy unindentAmount) |> ignore + ctx.WriterEvents.Append(WriteLineBecauseOfTrivia) |> ignore + + // The model already counted the newline at its old position; only the column it lands on changes. + let m: WriterModel = + WriterModel.update ctx.Config.MaxLineLength (UnIndentBy unindentAmount) ctx.WriterModel + + let indentAfterNewline: int = max m.Indent m.AtColumn { ctx with - WriterModel = WriterModel.update ctx.Config.MaxLineLength (UnIndentBy unindentAmount) ctx.WriterModel + WriterModel = + { m with + Indent = indentAfterNewline + Column = indentAfterNewline + } } let indentSepNlnUnindent f =