From 74dbb146ffb7f0f86fad91535d4cd06d65df66a5 Mon Sep 17 00:00:00 2001 From: Florian Verdonck Date: Wed, 21 Oct 2026 09:01:09 +0200 Subject: [PATCH 01/16] Indent a parenthesized function type only when its parenthesis needs it Since #3225, every multiline function type in parentheses indented its `->` lines one extra level, to fix #3043. The extra level is only needed in some places. A parenthesis opens an offside context at the first token inside it, and a line starting on that column ends it. After `-> (` or `:> (` at the start of a line, with an indent size of 4, that column is exactly where the `->` lines go. Where the `(` starts its line, as in `type T = (a -> b) list`, one level is enough, which is the 7.0.6 layout. Type.Paren now measures instead. After writing `(` it asks indentPast, the measure-and-step helper from #3446, to start the `->` lines past the column right after it. That gives the 7.0.6 layout where it parses, the #3043 layout after an outer `->`, and the same layout after `:>`. It also clears that column with an indent size of 2, where the blanket extra level put the `->` lines on it. The column is taken before the trivia after the `(`. A block comment there moves the first token right, but a line that starts left of the first token parses, so the `->` lines stay one level in rather than lining up past the comment. Closes #3554 --- ...pcast-to-a-function-type-in-parentheses.fs | 1 + ...-to-a-function-type-in-parentheses.gold.fs | 7 +++++ ...ion-type-with-a-parenthesized-parameter.fs | 1 + ...ype-with-a-parenthesized-parameter.gold.fs | 8 +++++ ...esized-function-type-as-first-parameter.fs | 1 + ...d-function-type-as-first-parameter.gold.fs | 7 +++++ ...ype-at-line-start-gets-one-indent-level.fs | 1 + ...t-line-start-gets-one-indent-level.gold.fs | 6 ++++ ...k-comment-after-the-opening-parenthesis.fs | 1 + ...ment-after-the-opening-parenthesis.gold.fs | 6 ++++ ...on-type-first-in-a-tuple-after-an-arrow.fs | 1 + ...pe-first-in-a-tuple-after-an-arrow.gold.fs | 8 +++++ ...-record-type-discriminant-does-not.gold.fs | 2 +- .../multiline-app-type.gold.fs | 6 +--- src/Fantomas.Core/CodePrinter.fs | 30 ++++++++----------- 15 files changed, 62 insertions(+), 24 deletions(-) create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/Expr/Typed/upcast-to-a-function-type-in-parentheses.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/Expr/Typed/upcast-to-a-function-type-in-parentheses.gold.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/Expr/Typed/upcast-to-a-function-type-with-a-parenthesized-parameter.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/Expr/Typed/upcast-to-a-function-type-with-a-parenthesized-parameter.gold.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/parenthesized-function-type-as-first-parameter.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/parenthesized-function-type-as-first-parameter.gold.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/3554-function-type-at-line-start-gets-one-indent-level.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/3554-function-type-at-line-start-gets-one-indent-level.gold.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/block-comment-after-the-opening-parenthesis.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/block-comment-after-the-opening-parenthesis.gold.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/function-type-first-in-a-tuple-after-an-arrow.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/function-type-first-in-a-tuple-after-an-arrow.gold.fs diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/Expr/Typed/upcast-to-a-function-type-in-parentheses.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/Expr/Typed/upcast-to-a-function-type-in-parentheses.fs new file mode 100644 index 0000000000..a3ef327e1c --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/Expr/Typed/upcast-to-a-function-type-in-parentheses.fs @@ -0,0 +1 @@ +let x = y :> (LongTypeNameNumberOne -> LongTypeNameNumberTwo -> LongTypeNameNumberThree -> LongTypeNameNumberFour -> LongTypeNameNumberFive) diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/Expr/Typed/upcast-to-a-function-type-in-parentheses.gold.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/Expr/Typed/upcast-to-a-function-type-in-parentheses.gold.fs new file mode 100644 index 0000000000..c7b3273d03 --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/Expr/Typed/upcast-to-a-function-type-in-parentheses.gold.fs @@ -0,0 +1,7 @@ +let x = + y + :> (LongTypeNameNumberOne + -> LongTypeNameNumberTwo + -> LongTypeNameNumberThree + -> LongTypeNameNumberFour + -> LongTypeNameNumberFive) diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/Expr/Typed/upcast-to-a-function-type-with-a-parenthesized-parameter.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/Expr/Typed/upcast-to-a-function-type-with-a-parenthesized-parameter.fs new file mode 100644 index 0000000000..bd0e2b90fc --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/Expr/Typed/upcast-to-a-function-type-with-a-parenthesized-parameter.fs @@ -0,0 +1 @@ +let x = y :> (LongTypeNameNumberOne -> LongTypeNameNumberTwo -> LongTypeNameNumberThree -> LongTypeNameNumberFour -> LongTypeNameNumberFive) -> int diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/Expr/Typed/upcast-to-a-function-type-with-a-parenthesized-parameter.gold.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/Expr/Typed/upcast-to-a-function-type-with-a-parenthesized-parameter.gold.fs new file mode 100644 index 0000000000..9663efc7f5 --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/Expr/Typed/upcast-to-a-function-type-with-a-parenthesized-parameter.gold.fs @@ -0,0 +1,8 @@ +let x = + y + :> (LongTypeNameNumberOne + -> LongTypeNameNumberTwo + -> LongTypeNameNumberThree + -> LongTypeNameNumberFour + -> LongTypeNameNumberFive) + -> int diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/parenthesized-function-type-as-first-parameter.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/parenthesized-function-type-as-first-parameter.fs new file mode 100644 index 0000000000..52d3070821 --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/parenthesized-function-type-as-first-parameter.fs @@ -0,0 +1 @@ +type T = (LongTypeNameNumberOne -> LongTypeNameNumberTwo -> LongTypeNameNumberThree -> LongTypeNameNumberFour -> LongTypeNameNumberFive) -> LongTypeNameNumberSix diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/parenthesized-function-type-as-first-parameter.gold.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/parenthesized-function-type-as-first-parameter.gold.fs new file mode 100644 index 0000000000..71024b4cf6 --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/parenthesized-function-type-as-first-parameter.gold.fs @@ -0,0 +1,7 @@ +type T = + (LongTypeNameNumberOne + -> LongTypeNameNumberTwo + -> LongTypeNameNumberThree + -> LongTypeNameNumberFour + -> LongTypeNameNumberFive) + -> LongTypeNameNumberSix diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/3554-function-type-at-line-start-gets-one-indent-level.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/3554-function-type-at-line-start-gets-one-indent-level.fs new file mode 100644 index 0000000000..a772628c56 --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/3554-function-type-at-line-start-gets-one-indent-level.fs @@ -0,0 +1 @@ +type T = (LongTypeNameNumberOne -> LongTypeNameNumberTwo -> LongTypeNameNumberThree -> LongTypeNameNumberFour -> LongTypeNameNumberFive) list diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/3554-function-type-at-line-start-gets-one-indent-level.gold.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/3554-function-type-at-line-start-gets-one-indent-level.gold.fs new file mode 100644 index 0000000000..7db47d9be7 --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/3554-function-type-at-line-start-gets-one-indent-level.gold.fs @@ -0,0 +1,6 @@ +type T = + (LongTypeNameNumberOne + -> LongTypeNameNumberTwo + -> LongTypeNameNumberThree + -> LongTypeNameNumberFour + -> LongTypeNameNumberFive) list diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/block-comment-after-the-opening-parenthesis.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/block-comment-after-the-opening-parenthesis.fs new file mode 100644 index 0000000000..26cdfaf993 --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/block-comment-after-the-opening-parenthesis.fs @@ -0,0 +1 @@ +type T = ((* block *) LongTypeNameNumberOne -> LongTypeNameNumberTwo -> LongTypeNameNumberThree -> LongTypeNameNumberFour -> LongTypeNameNumberFive) list diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/block-comment-after-the-opening-parenthesis.gold.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/block-comment-after-the-opening-parenthesis.gold.fs new file mode 100644 index 0000000000..1abfd7aee0 --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/block-comment-after-the-opening-parenthesis.gold.fs @@ -0,0 +1,6 @@ +type T = + ( (* block *) LongTypeNameNumberOne + -> LongTypeNameNumberTwo + -> LongTypeNameNumberThree + -> LongTypeNameNumberFour + -> LongTypeNameNumberFive) list diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/function-type-first-in-a-tuple-after-an-arrow.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/function-type-first-in-a-tuple-after-an-arrow.fs new file mode 100644 index 0000000000..852e2be832 --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/function-type-first-in-a-tuple-after-an-arrow.fs @@ -0,0 +1 @@ +type T = LongTypeNameNumberOne -> (LongTypeNameNumberOne -> LongTypeNameNumberTwo -> LongTypeNameNumberThree -> LongTypeNameNumberFour -> LongTypeNameNumberFive) * int diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/function-type-first-in-a-tuple-after-an-arrow.gold.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/function-type-first-in-a-tuple-after-an-arrow.gold.fs new file mode 100644 index 0000000000..f704d5f66a --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/function-type-first-in-a-tuple-after-an-arrow.gold.fs @@ -0,0 +1,8 @@ +type T = + LongTypeNameNumberOne + -> (LongTypeNameNumberOne + -> LongTypeNameNumberTwo + -> LongTypeNameNumberThree + -> LongTypeNameNumberFour + -> LongTypeNameNumberFive) * + int diff --git a/src/Fantomas.Core.SnapshotTests/cases/scenarios/PatternMatchingTests/1903-match-on-long-anonymous-record-type-discriminant-does-not.gold.fs b/src/Fantomas.Core.SnapshotTests/cases/scenarios/PatternMatchingTests/1903-match-on-long-anonymous-record-type-discriminant-does-not.gold.fs index c14059fb81..b3cf6795c7 100644 --- a/src/Fantomas.Core.SnapshotTests/cases/scenarios/PatternMatchingTests/1903-match-on-long-anonymous-record-type-discriminant-does-not.gold.fs +++ b/src/Fantomas.Core.SnapshotTests/cases/scenarios/PatternMatchingTests/1903-match-on-long-anonymous-record-type-discriminant-does-not.gold.fs @@ -5,7 +5,7 @@ match {| ChooseAsync: (('T -> Async<_ option>) - -> AsyncSeq<_>) option + -> AsyncSeq<_>) option |} option |} >( diff --git a/src/Fantomas.Core.SnapshotTests/cases/scenarios/TypeAnnotationTests/multiline-app-type.gold.fs b/src/Fantomas.Core.SnapshotTests/cases/scenarios/TypeAnnotationTests/multiline-app-type.gold.fs index 2bda270d98..9634f47538 100644 --- a/src/Fantomas.Core.SnapshotTests/cases/scenarios/TypeAnnotationTests/multiline-app-type.gold.fs +++ b/src/Fantomas.Core.SnapshotTests/cases/scenarios/TypeAnnotationTests/multiline-app-type.gold.fs @@ -16,10 +16,6 @@ type CancellableTaskResultBuilderBase with task: CancellationToken -> ^TaskLike, continuation: ('TResult1 - -> CancellableTaskResultCode< - 'TOverall, - 'Error, - 'TResult2 - >) + -> CancellableTaskResultCode<'TOverall, 'Error, 'TResult2>) ) : bool = true diff --git a/src/Fantomas.Core/CodePrinter.fs b/src/Fantomas.Core/CodePrinter.fs index 375866e1ad..b753a816c1 100644 --- a/src/Fantomas.Core/CodePrinter.fs +++ b/src/Fantomas.Core/CodePrinter.fs @@ -4329,26 +4329,20 @@ let genType (t: Type) = genNode node (isSmallExpression size smallExpression longExpression) ctx | Type.Paren node -> - match node.Type with - | Type.Funs _ -> - let short = - genSingleTextNode node.OpeningParen - +> genType node.Type - +> genSingleTextNode node.ClosingParen + let genOpeningAndInner: Context -> Context = + if not node.Type.IsFuns then + genSingleTextNode node.OpeningParen +> genType node.Type + else - let long = - genSingleTextNode node.OpeningParen - +> indent - +> genType node.Type - +> unindent - +> genSingleTextNode node.ClosingParen + // The parenthesis opens an offside context at the first token inside it, and a line + // starting on that column ends it. The `->` lines of the function type start past the + // column right after the parenthesis, taken before its trivia: a comment there moves + // the first token right, and a line left of that token parses. + enterNode node.OpeningParen + +> genSingleTextNodeText node.OpeningParen + +> fun ctx -> (leaveNode node.OpeningParen +> indentPast ctx.Column (genType node.Type)) ctx - expressionFitsOnRestOfLine short long |> genNode node - | _ -> - genSingleTextNode node.OpeningParen - +> genType node.Type - +> genSingleTextNode node.ClosingParen - |> genNode node + genOpeningAndInner +> genSingleTextNode node.ClosingParen |> genNode node | Type.SignatureParameter node -> genOnelinerAttributes node.Attributes +> optSingle (fun id -> genSingleTextNode id +> sepColon) node.Identifier From 3e1d41b8aa61747c4fc2e236261b6d7ed2a967d1 Mon Sep 17 00:00:00 2001 From: Florian Verdonck Date: Wed, 21 Oct 2026 09:04:53 +0200 Subject: [PATCH 02/16] Keep a return type past its colon without pinning the indent A return type annotation set the indent to the column after `: `. One level from there lands between multiples of the indent size: with an indent size of 4, the `->` lines of `: (a -> b -> ...)`, the `->` of `: unit -> {| ... |}` and the arguments of `: cmap<...>` went to 10. The indent now stays the binding's, so a type that indents its own lines lands on a multiple of it, 8 in all three. A line starting on the column of the `:` ends the return type. A multiline tuple does not indent its own lines: the lines after its first element start at the indent, which is now that column. Where a tuple starts the lines of the type, alone or inside parentheses, a postfix application, an array, a struct tuple, global constraints or the first parameter of a function type, AtColumn keeps them at the column after `: `, where they were before. --- src/Fantomas.Core.SnapshotTests/CaseTests.fs | 55 ++++++++++++++++++- src/Fantomas.Core.SnapshotTests/Formatting.fs | 26 +++++++-- src/Fantomas.Core.SnapshotTests/README.md | 5 +- .../multiline-struct-tuple.fs | 1 + .../multiline-struct-tuple.gold.fs | 9 +++ ...e-as-first-parameter-of-a-function-type.fs | 1 + ...first-parameter-of-a-function-type.gold.fs | 10 ++++ ...ultiline-tuple-in-a-postfix-application.fs | 1 + ...ine-tuple-in-a-postfix-application.gold.fs | 9 +++ .../multiline-tuple-in-an-array.fs | 1 + .../multiline-tuple-in-an-array.gold.fs | 9 +++ .../multiline-tuple-in-parentheses.fs | 1 + .../multiline-tuple-in-parentheses.gold.fs | 7 +++ .../multiline-tuple-on-a-value.fs | 2 + .../multiline-tuple-on-a-value.gold.fs | 5 ++ ...multiline-tuple-with-global-constraints.fs | 1 + ...line-tuple-with-global-constraints.gold.fs | 9 +++ ...function-type-as-return-type-annotation.fs | 1 + ...ion-type-as-return-type-annotation.gold.fs | 10 ++++ ...ing-with-multiline-type-annotation.gold.fs | 12 ++-- ...-type-followed-by-type-declaration.gold.fs | 8 +-- ...n-type-in-parens-gets-extra-indent.gold.fs | 8 +-- src/Fantomas.Core/CodePrinter.fs | 25 ++++++++- 23 files changed, 193 insertions(+), 23 deletions(-) create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/BindingReturnInfo/multiline-struct-tuple.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/BindingReturnInfo/multiline-struct-tuple.gold.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/BindingReturnInfo/multiline-tuple-as-first-parameter-of-a-function-type.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/BindingReturnInfo/multiline-tuple-as-first-parameter-of-a-function-type.gold.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/BindingReturnInfo/multiline-tuple-in-a-postfix-application.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/BindingReturnInfo/multiline-tuple-in-a-postfix-application.gold.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/BindingReturnInfo/multiline-tuple-in-an-array.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/BindingReturnInfo/multiline-tuple-in-an-array.gold.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/BindingReturnInfo/multiline-tuple-in-parentheses.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/BindingReturnInfo/multiline-tuple-in-parentheses.gold.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/BindingReturnInfo/multiline-tuple-on-a-value.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/BindingReturnInfo/multiline-tuple-on-a-value.gold.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/BindingReturnInfo/multiline-tuple-with-global-constraints.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/BindingReturnInfo/multiline-tuple-with-global-constraints.gold.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/function-type-as-return-type-annotation.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/function-type-as-return-type-annotation.gold.fs diff --git a/src/Fantomas.Core.SnapshotTests/CaseTests.fs b/src/Fantomas.Core.SnapshotTests/CaseTests.fs index 893a1db925..07420fde88 100644 --- a/src/Fantomas.Core.SnapshotTests/CaseTests.fs +++ b/src/Fantomas.Core.SnapshotTests/CaseTests.fs @@ -20,6 +20,49 @@ let private failWith (problems: Problem list) : unit = if not problems.IsEmpty then Assert.Fail(problems |> List.map describe |> String.concat "\n\n") +/// The command a gold and its `.actual` are compared with: `FANTOMAS_DIFF_TOOL`, `zed -e --diff` say, +/// or `git diff --no-index` without it. +let private diffTool: string = + let tool: string = Environment.GetEnvironmentVariable "FANTOMAS_DIFF_TOOL" + + if String.IsNullOrEmpty tool then + "git diff --no-index" + else + tool + +/// For a case whose result differs from its golds: a command to compare each gold with what came out, +/// and one to accept them all, unless the update would leave them alone because the result is itself +/// wrong. Absolute paths, so that they work from wherever they are pasted. +let private nextSteps (case: Case.Case) (canAccept: bool) (problems: Problem list) : string list = + let compare: string list = + problems + |> List.choose (fun (problem: Problem) -> + match problem with + | Problem.GoldDiffers(path, _) -> + let gold: string = Path.GetFullPath(Path.Combine(Case.projectDirectory, path)) + Some $"Compare: %s{diffTool} %s{gold} %s{Gold.actualPath gold}" + | _ -> None + ) + + let differs: bool = + problems + |> List.exists (fun (problem: Problem) -> + match problem with + | Problem.NoGold _ + | Problem.GoldDiffers _ -> true + | _ -> false + ) + + let accept: string list = + if canAccept && differs then + [ + $"Accept: FANTOMAS_UPDATE_SNAPSHOTS=1 dotnet test %s{Case.projectDirectory} --filter \"Name~%s{case.RelativePath}\"" + ] + else + [] + + compare @ accept + /// Whether a case is under `negative/`, and so its own gold. let private isNegative (case: Case.Case) : bool = match Placement.claimOf case with @@ -207,7 +250,17 @@ let case (relativePath: string) = Gold.verify path code )) - failWith (resultProblems @ placementProblems @ goldProblems) + let problems: Problem list = resultProblems @ placementProblems @ goldProblems + + if not problems.IsEmpty then + Assert.Fail( + (problems |> List.map describe) + @ [ + String.concat "\n" (nextSteps case (resultProblems.IsEmpty && placementProblems.IsEmpty) goldProblems) + ] + |> List.filter (fun (part: string) -> part <> "") + |> String.concat "\n\n" + ) /// Every file under `cases/` is a case, a gold of one, an `.actual` of one, or a `README.md`. An /// `.actual` of no case is deleted instead. diff --git a/src/Fantomas.Core.SnapshotTests/Formatting.fs b/src/Fantomas.Core.SnapshotTests/Formatting.fs index 66a68d7edf..2c6b345a1c 100644 --- a/src/Fantomas.Core.SnapshotTests/Formatting.fs +++ b/src/Fantomas.Core.SnapshotTests/Formatting.fs @@ -323,12 +323,23 @@ let formatAndCheck (config: FormatConfig) (isSignature: bool) (source: string) : if crlf <> expected then problems.Add(Problem.CrlfDiffers crlf) - let again: string = (formatEach config isSignature formatted.Merged).Merged + // A result that does not parse cannot be formatted again: the parse would throw and take the + // problems found so far with it. + let isValid: bool = + problems + |> Seq.forall (fun (problem: Problem) -> + match problem with + | Problem.Invalid _ -> false + | _ -> true + ) - if again <> formatted.Merged then - problems.Add(Problem.NotIdempotent(Output.Merged, again)) + if isValid then + let again: string = (formatEach config isSignature formatted.Merged).Merged - if hasDefines then + if again <> formatted.Merged then + problems.Add(Problem.NotIdempotent(Output.Merged, again)) + + if isValid && hasDefines then for each in formatted.Combinations do let sourceText: ISourceText = CodeFormatterImpl.getSourceText each.Code let tree, _ = parseFile isSignature sourceText each.Defines @@ -350,7 +361,12 @@ let formatAndCheck (config: FormatConfig) (isSignature: bool) (source: string) : let allDefines: string list list = formatted.Combinations |> List.map (fun (each: ForDefines) -> each.Defines) - for output, code in (Output.Merged, formatted.Merged) :: perDefine do + // Telling text from code needs the result's Oak, which a result that does not parse has none of. + for output, code in + (if isValid then + (Output.Merged, formatted.Merged) :: perDefine + else + []) do let combinations: string list list = match output with | Output.Merged -> allDefines diff --git a/src/Fantomas.Core.SnapshotTests/README.md b/src/Fantomas.Core.SnapshotTests/README.md index 659a3defdb..c016073253 100644 --- a/src/Fantomas.Core.SnapshotTests/README.md +++ b/src/Fantomas.Core.SnapshotTests/README.md @@ -16,7 +16,10 @@ dotnet test src/Fantomas.Core.SnapshotTests --list-tests ``` A failing case prints a line diff against its gold and writes what came out to the `.actual` file -beside it. +beside it. Below the diff it prints a command to compare the gold with that `.actual` in a diff tool, +and one to accept the result for this case alone, which is left out while the result is itself +wrong. The comparison runs `git diff --no-index`, or the command in `FANTOMAS_DIFF_TOOL`, such as +`zed -e --diff` or `code --diff`. To look at an input without making it a case, use the scripts in `scripts/`. They read a case's front matter as its settings, so they take a case file as it is: diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/BindingReturnInfo/multiline-struct-tuple.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/BindingReturnInfo/multiline-struct-tuple.fs new file mode 100644 index 0000000000..40aea61c2a --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/BindingReturnInfo/multiline-struct-tuple.fs @@ -0,0 +1 @@ +let f x : struct (LongTypeNameNumberOne * LongTypeNameNumberTwo * LongTypeNameNumberThree * LongTypeNameNumberFour * LongTypeNameNumberFive) = failwith "" diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/BindingReturnInfo/multiline-struct-tuple.gold.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/BindingReturnInfo/multiline-struct-tuple.gold.fs new file mode 100644 index 0000000000..7262e0ac2d --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/BindingReturnInfo/multiline-struct-tuple.gold.fs @@ -0,0 +1,9 @@ +let f + x + : struct (LongTypeNameNumberOne * + LongTypeNameNumberTwo * + LongTypeNameNumberThree * + LongTypeNameNumberFour * + LongTypeNameNumberFive) + = + failwith "" diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/BindingReturnInfo/multiline-tuple-as-first-parameter-of-a-function-type.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/BindingReturnInfo/multiline-tuple-as-first-parameter-of-a-function-type.fs new file mode 100644 index 0000000000..f46f4339dc --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/BindingReturnInfo/multiline-tuple-as-first-parameter-of-a-function-type.fs @@ -0,0 +1 @@ +let k x : LongTypeNameNumberOne * LongTypeNameNumberTwo * LongTypeNameNumberThree * LongTypeNameNumberFour * LongTypeNameNumberFive -> LongTypeNameNumberSix = failwith "" diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/BindingReturnInfo/multiline-tuple-as-first-parameter-of-a-function-type.gold.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/BindingReturnInfo/multiline-tuple-as-first-parameter-of-a-function-type.gold.fs new file mode 100644 index 0000000000..cae51ef13d --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/BindingReturnInfo/multiline-tuple-as-first-parameter-of-a-function-type.gold.fs @@ -0,0 +1,10 @@ +let k + x + : LongTypeNameNumberOne * + LongTypeNameNumberTwo * + LongTypeNameNumberThree * + LongTypeNameNumberFour * + LongTypeNameNumberFive + -> LongTypeNameNumberSix + = + failwith "" diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/BindingReturnInfo/multiline-tuple-in-a-postfix-application.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/BindingReturnInfo/multiline-tuple-in-a-postfix-application.fs new file mode 100644 index 0000000000..927ff93ee7 --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/BindingReturnInfo/multiline-tuple-in-a-postfix-application.fs @@ -0,0 +1 @@ +let f x : (LongTypeNameNumberOne * LongTypeNameNumberTwo * LongTypeNameNumberThree * LongTypeNameNumberFour * LongTypeNameNumberFive) list = failwith "" diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/BindingReturnInfo/multiline-tuple-in-a-postfix-application.gold.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/BindingReturnInfo/multiline-tuple-in-a-postfix-application.gold.fs new file mode 100644 index 0000000000..b94bcfca78 --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/BindingReturnInfo/multiline-tuple-in-a-postfix-application.gold.fs @@ -0,0 +1,9 @@ +let f + x + : (LongTypeNameNumberOne * + LongTypeNameNumberTwo * + LongTypeNameNumberThree * + LongTypeNameNumberFour * + LongTypeNameNumberFive) list + = + failwith "" diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/BindingReturnInfo/multiline-tuple-in-an-array.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/BindingReturnInfo/multiline-tuple-in-an-array.fs new file mode 100644 index 0000000000..feb373242b --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/BindingReturnInfo/multiline-tuple-in-an-array.fs @@ -0,0 +1 @@ +let f x : (LongTypeNameNumberOne * LongTypeNameNumberTwo * LongTypeNameNumberThree * LongTypeNameNumberFour * LongTypeNameNumberFive)[] = failwith "" diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/BindingReturnInfo/multiline-tuple-in-an-array.gold.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/BindingReturnInfo/multiline-tuple-in-an-array.gold.fs new file mode 100644 index 0000000000..ae30c47d48 --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/BindingReturnInfo/multiline-tuple-in-an-array.gold.fs @@ -0,0 +1,9 @@ +let f + x + : (LongTypeNameNumberOne * + LongTypeNameNumberTwo * + LongTypeNameNumberThree * + LongTypeNameNumberFour * + LongTypeNameNumberFive)[] + = + failwith "" diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/BindingReturnInfo/multiline-tuple-in-parentheses.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/BindingReturnInfo/multiline-tuple-in-parentheses.fs new file mode 100644 index 0000000000..f1531d0fd1 --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/BindingReturnInfo/multiline-tuple-in-parentheses.fs @@ -0,0 +1 @@ +let f x : (('Arg * System.AsyncCallback * obj -> System.IAsyncResult) * (System.IAsyncResult -> 'T) * (System.IAsyncResult -> unit)) = failwith "" diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/BindingReturnInfo/multiline-tuple-in-parentheses.gold.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/BindingReturnInfo/multiline-tuple-in-parentheses.gold.fs new file mode 100644 index 0000000000..e1c79ae4ca --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/BindingReturnInfo/multiline-tuple-in-parentheses.gold.fs @@ -0,0 +1,7 @@ +let f + x + : (('Arg * System.AsyncCallback * obj -> System.IAsyncResult) * + (System.IAsyncResult -> 'T) * + (System.IAsyncResult -> unit)) + = + failwith "" diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/BindingReturnInfo/multiline-tuple-on-a-value.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/BindingReturnInfo/multiline-tuple-on-a-value.fs new file mode 100644 index 0000000000..14373ab9c3 --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/BindingReturnInfo/multiline-tuple-on-a-value.fs @@ -0,0 +1,2 @@ +let actions : ('Arg * System.AsyncCallback * obj -> System.IAsyncResult) * (System.IAsyncResult -> 'T) * (System.IAsyncResult -> unit) = + beginAction, endAction, cancelAction diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/BindingReturnInfo/multiline-tuple-on-a-value.gold.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/BindingReturnInfo/multiline-tuple-on-a-value.gold.fs new file mode 100644 index 0000000000..1e971a94b0 --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/BindingReturnInfo/multiline-tuple-on-a-value.gold.fs @@ -0,0 +1,5 @@ +let actions + : ('Arg * System.AsyncCallback * obj -> System.IAsyncResult) * + (System.IAsyncResult -> 'T) * + (System.IAsyncResult -> unit) = + beginAction, endAction, cancelAction diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/BindingReturnInfo/multiline-tuple-with-global-constraints.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/BindingReturnInfo/multiline-tuple-with-global-constraints.fs new file mode 100644 index 0000000000..b69443b385 --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/BindingReturnInfo/multiline-tuple-with-global-constraints.fs @@ -0,0 +1 @@ +let l x : LongTypeNameNumberOne * LongTypeNameNumberTwo * LongTypeNameNumberThree * LongTypeNameNumberFour * LongTypeNameNumberFive when 'a : comparison = failwith "" diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/BindingReturnInfo/multiline-tuple-with-global-constraints.gold.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/BindingReturnInfo/multiline-tuple-with-global-constraints.gold.fs new file mode 100644 index 0000000000..e39f5a56b9 --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/BindingReturnInfo/multiline-tuple-with-global-constraints.gold.fs @@ -0,0 +1,9 @@ +let l + x + : LongTypeNameNumberOne * + LongTypeNameNumberTwo * + LongTypeNameNumberThree * + LongTypeNameNumberFour * + LongTypeNameNumberFive when 'a: comparison + = + failwith "" diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/function-type-as-return-type-annotation.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/function-type-as-return-type-annotation.fs new file mode 100644 index 0000000000..804d823f5c --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/function-type-as-return-type-annotation.fs @@ -0,0 +1 @@ +let f x : (LongTypeNameNumberOne -> LongTypeNameNumberTwo -> LongTypeNameNumberThree -> LongTypeNameNumberFour -> LongTypeNameNumberFive -> LongTypeNameNumberSix) = failwith "" diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/function-type-as-return-type-annotation.gold.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/function-type-as-return-type-annotation.gold.fs new file mode 100644 index 0000000000..8905595033 --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/function-type-as-return-type-annotation.gold.fs @@ -0,0 +1,10 @@ +let f + x + : (LongTypeNameNumberOne + -> LongTypeNameNumberTwo + -> LongTypeNameNumberThree + -> LongTypeNameNumberFour + -> LongTypeNameNumberFive + -> LongTypeNameNumberSix) + = + failwith "" diff --git a/src/Fantomas.Core.SnapshotTests/cases/scenarios/DallasTests/value-binding-with-multiline-type-annotation.gold.fs b/src/Fantomas.Core.SnapshotTests/cases/scenarios/DallasTests/value-binding-with-multiline-type-annotation.gold.fs index c7567091fa..652358c481 100644 --- a/src/Fantomas.Core.SnapshotTests/cases/scenarios/DallasTests/value-binding-with-multiline-type-annotation.gold.fs +++ b/src/Fantomas.Core.SnapshotTests/cases/scenarios/DallasTests/value-binding-with-multiline-type-annotation.gold.fs @@ -1,10 +1,10 @@ let autoCompleteItems : cmap< - DeclName, - DeclarationListItem * - Position * - string * - (Position -> option) * - FSharp.Compiler.Syntax.ParsedInput + DeclName, + DeclarationListItem * + Position * + string * + (Position -> option) * + FSharp.Compiler.Syntax.ParsedInput > = cmap () diff --git a/src/Fantomas.Core.SnapshotTests/cases/scenarios/LetBindingTests/1624-multiline-return-type-followed-by-type-declaration.gold.fs b/src/Fantomas.Core.SnapshotTests/cases/scenarios/LetBindingTests/1624-multiline-return-type-followed-by-type-declaration.gold.fs index ebc2e1f77f..c9f0b5b03a 100644 --- a/src/Fantomas.Core.SnapshotTests/cases/scenarios/LetBindingTests/1624-multiline-return-type-followed-by-type-declaration.gold.fs +++ b/src/Fantomas.Core.SnapshotTests/cases/scenarios/LetBindingTests/1624-multiline-return-type-followed-by-type-declaration.gold.fs @@ -1,9 +1,9 @@ let useGeolocation : unit - -> {| latitude: float - longitude: float - loading: bool - error: obj option |} = + -> {| latitude: float + longitude: float + loading: bool + error: obj option |} = import "useGeolocation" "react-use" type Viewport = diff --git a/src/Fantomas.Core.SnapshotTests/cases/scenarios/TypeAnnotationTests/3043-multiline-function-type-in-parens-gets-extra-indent.gold.fs b/src/Fantomas.Core.SnapshotTests/cases/scenarios/TypeAnnotationTests/3043-multiline-function-type-in-parens-gets-extra-indent.gold.fs index a1e8f42591..847174bea5 100644 --- a/src/Fantomas.Core.SnapshotTests/cases/scenarios/TypeAnnotationTests/3043-multiline-function-type-in-parens-gets-extra-indent.gold.fs +++ b/src/Fantomas.Core.SnapshotTests/cases/scenarios/TypeAnnotationTests/3043-multiline-function-type-in-parens-gets-extra-indent.gold.fs @@ -2,8 +2,8 @@ type MyCustomTypeWithAPrettyLongDescribingName = MyCustomConstructor1 let private myFunction : string - -> (MyCustomTypeWithAPrettyLongDescribingName - -> MyCustomTypeWithAPrettyLongDescribingName - -> MyCustomTypeWithAPrettyLongDescribingName) - -> unit = + -> (MyCustomTypeWithAPrettyLongDescribingName + -> MyCustomTypeWithAPrettyLongDescribingName + -> MyCustomTypeWithAPrettyLongDescribingName) + -> unit = fun a fn -> () diff --git a/src/Fantomas.Core/CodePrinter.fs b/src/Fantomas.Core/CodePrinter.fs index b753a816c1..870faabf1d 100644 --- a/src/Fantomas.Core/CodePrinter.fs +++ b/src/Fantomas.Core/CodePrinter.fs @@ -3845,6 +3845,27 @@ let genBinding (b: BindingNode) (ctx: Context) : Context = | [ "default" ] -> ctx.Config.SpaceBeforeMember, ctx.Config.AlternativeLongMemberDefinitions | _ -> ctx.Config.SpaceBeforeParameter, ctx.Config.AlignFunctionSignatureToIndentation + // A line of the return type that starts on the column of the `:` ends it. The indent stays the + // binding's, so a type that indents its own lines lands on a multiple of the indent size. A + // multiline tuple starts the lines after its first element at the indent, so where a tuple + // starts the lines of the type, AtColumn keeps them past the `:`. + let genReturnTypeAfterColon (t: Type) : Context -> Context = + let rec isTuple (t: Type) : bool = + match t with + | Type.Paren parenNode -> isTuple parenNode.Type + | Type.WithGlobalConstraints wgcNode -> isTuple wgcNode.Type + | Type.Funs funNode -> + match List.tryHead funNode.Parameters with + | None -> isTuple funNode.ReturnType + | Some(p, _) -> isTuple p + | Type.AppPostfix appPostFixNode -> isTuple appPostFixNode.First + | Type.Array arrayNode -> isTuple arrayNode.Type + | Type.StructTuple _ -> true + | Type.Tuple _ -> true + | _ -> false + + if isTuple t then atCurrentColumn (genType t) else genType t + let isRecursiveLetOrUseFunction = match b.LeadingKeyword.Content with | [ singleText ] -> singleText.Text = "and" || singleText.Text = "and!" @@ -3882,7 +3903,7 @@ let genBinding (b: BindingNode) (ctx: Context) : Context = onlyIfNot isFixed sepSpace +> (genSingleTextNode returnTypeNode.Colon +> sepSpace - +> atCurrentColumnIndent (genType returnTypeNode.Type) + +> genReturnTypeAfterColon returnTypeNode.Type |> genNode returnTypeNode) let genSignature = @@ -4073,7 +4094,7 @@ let genBinding (b: BindingNode) (ctx: Context) : Context = onlyIfCtx (fun ctx -> hasGenerics || ctx.Config.SpaceBeforeColon) sepSpace +> genSingleTextNode rt.Colon +> sepSpace - +> atCurrentColumnIndent (genType rt.Type) + +> genReturnTypeAfterColon rt.Type ) +> sepSpaceUnlessWriteBeforeNewlineNotEmpty +> autoIndentAndNlnWhenWriteBeforeNewlineNotEmpty genEqualsInBinding From 0982228e921c556b1a315f72549489a002fd8093 Mon Sep 17 00:00:00 2001 From: Florian Verdonck Date: Wed, 21 Oct 2026 10:44:13 +0200 Subject: [PATCH 03/16] Indent a multiline tuple after the arrow of a function type When a function type does not fit on its line, its `->` lines go one level in. A tuple after one of them that does not fit either breaks after `*` and starts its next element at the indent, the column of the `->` lines. The element after a line-ending `*` starts a block at its own column, so for a tuple in the middle of the function type, the `->` that follows is read as a new statement and the result does not parse. Inside parentheses, a postfix application or an array it parses, but the tuple's lines still line up with the arrows. A type that a tuple starts after an arrow now goes one level further in, as the last operand too. The check whether a tuple starts the lines of a type is the one a return type already made, now shared by both. A struct tuple type that did not fit on its line started its next element at the indent, left of `struct (` and of the element it continues. It now breaks after `struct (`, puts its elements one level in and its `)` back on the indent of the line it started on. As it places its own lines, the check above no longer counts it as a tuple. A line comment after an arrow was held until the next line break, which came after the type that follows, so the comment moved onto that type and left a blank line behind; before a tuple, it moved after the first element and was not idempotent. It now stays after the arrow, and the type goes on the next line, one level in. Closes #3556 --- CHANGELOG.md | 7 ++ .../multiline-struct-tuple.gold.fs | 12 +-- ...-tuple-in-the-middle-of-a-function-type.fs | 1 + ...e-in-the-middle-of-a-function-type.gold.fs | 5 ++ ...-tuple-in-the-middle-of-a-function-type.fs | 1 + ...e-in-the-middle-of-a-function-type.gold.fs | 6 ++ ...-tuple-in-the-middle-of-a-function-type.fs | 1 + ...e-in-the-middle-of-a-function-type.gold.fs | 7 ++ ...cation-in-the-middle-of-a-function-type.fs | 1 + ...n-in-the-middle-of-a-function-type.gold.fs | 5 ++ ...-array-in-the-middle-of-a-function-type.fs | 1 + ...y-in-the-middle-of-a-function-type.gold.fs | 5 ++ ...theses-in-the-middle-of-a-function-type.fs | 1 + ...s-in-the-middle-of-a-function-type.gold.fs | 5 ++ ...-function-type-in-a-tuple-in-the-middle.fs | 1 + ...tion-type-in-a-tuple-in-the-middle.gold.fs | 9 +++ ...after-an-arrow-before-a-multiline-tuple.fs | 3 + ...-an-arrow-before-a-multiline-tuple.gold.fs | 6 ++ .../trivia/line-comment-after-an-arrow.fs | 3 + .../line-comment-after-an-arrow.gold.fs | 5 ++ ...pe-first-in-a-tuple-after-an-arrow.gold.fs | 2 +- .../StructTuple/multiline-struct-tuple.fs | 1 + .../multiline-struct-tuple.gold.fs | 9 +++ ...ments-on-one-line-after-the-parenthesis.fs | 1 + ...-on-one-line-after-the-parenthesis.gold.fs | 5 ++ src/Fantomas.Core/CodePrinter.fs | 78 ++++++++++++------- 26 files changed, 148 insertions(+), 33 deletions(-) create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/3556-multiline-tuple-in-the-middle-of-a-function-type.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/3556-multiline-tuple-in-the-middle-of-a-function-type.gold.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/function-type-starting-with-a-multiline-tuple-in-the-middle-of-a-function-type.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/function-type-starting-with-a-multiline-tuple-in-the-middle-of-a-function-type.gold.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/multiline-struct-tuple-in-the-middle-of-a-function-type.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/multiline-struct-tuple-in-the-middle-of-a-function-type.gold.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/multiline-tuple-in-a-postfix-application-in-the-middle-of-a-function-type.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/multiline-tuple-in-a-postfix-application-in-the-middle-of-a-function-type.gold.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/multiline-tuple-in-an-array-in-the-middle-of-a-function-type.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/multiline-tuple-in-an-array-in-the-middle-of-a-function-type.gold.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/multiline-tuple-in-parentheses-in-the-middle-of-a-function-type.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/multiline-tuple-in-parentheses-in-the-middle-of-a-function-type.gold.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/parenthesized-function-type-in-a-tuple-in-the-middle.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/parenthesized-function-type-in-a-tuple-in-the-middle.gold.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/trivia/line-comment-after-an-arrow-before-a-multiline-tuple.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/trivia/line-comment-after-an-arrow-before-a-multiline-tuple.gold.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/trivia/line-comment-after-an-arrow.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/trivia/line-comment-after-an-arrow.gold.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/Type/StructTuple/multiline-struct-tuple.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/Type/StructTuple/multiline-struct-tuple.gold.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/Type/StructTuple/struct-tuple-elements-on-one-line-after-the-parenthesis.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/Type/StructTuple/struct-tuple-elements-on-one-line-after-the-parenthesis.gold.fs diff --git a/CHANGELOG.md b/CHANGELOG.md index 26c6ed39cd..3642f7582d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [Unreleased] + +### Fixed + +- Parenthesized function type gets an extra indent level where no outer function type needs it. [#3554](https://github.com/fsprojects/fantomas/issues/3554) +- Multiline tuple in the middle of a function type gives invalid code. [#3556](https://github.com/fsprojects/fantomas/issues/3556) + ## [8.0.10] - 2026-10-14 ### Fixed diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/BindingReturnInfo/multiline-struct-tuple.gold.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/BindingReturnInfo/multiline-struct-tuple.gold.fs index 7262e0ac2d..40d6f38a1b 100644 --- a/src/Fantomas.Core.SnapshotTests/cases/oak/BindingReturnInfo/multiline-struct-tuple.gold.fs +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/BindingReturnInfo/multiline-struct-tuple.gold.fs @@ -1,9 +1,11 @@ let f x - : struct (LongTypeNameNumberOne * - LongTypeNameNumberTwo * - LongTypeNameNumberThree * - LongTypeNameNumberFour * - LongTypeNameNumberFive) + : struct ( + LongTypeNameNumberOne * + LongTypeNameNumberTwo * + LongTypeNameNumberThree * + LongTypeNameNumberFour * + LongTypeNameNumberFive + ) = failwith "" diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/3556-multiline-tuple-in-the-middle-of-a-function-type.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/3556-multiline-tuple-in-the-middle-of-a-function-type.fs new file mode 100644 index 0000000000..31e2a0aa30 --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/3556-multiline-tuple-in-the-middle-of-a-function-type.fs @@ -0,0 +1 @@ +type T = a -> int * LongTypeNameNumberOneLongTypeNameNumberTwoLongTypeNameNumberThreeLongTypeNameNumberFourLongTypeNameNumberFive -> unit diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/3556-multiline-tuple-in-the-middle-of-a-function-type.gold.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/3556-multiline-tuple-in-the-middle-of-a-function-type.gold.fs new file mode 100644 index 0000000000..6888c32089 --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/3556-multiline-tuple-in-the-middle-of-a-function-type.gold.fs @@ -0,0 +1,5 @@ +type T = + a + -> int * + LongTypeNameNumberOneLongTypeNameNumberTwoLongTypeNameNumberThreeLongTypeNameNumberFourLongTypeNameNumberFive + -> unit diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/function-type-starting-with-a-multiline-tuple-in-the-middle-of-a-function-type.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/function-type-starting-with-a-multiline-tuple-in-the-middle-of-a-function-type.fs new file mode 100644 index 0000000000..3f784b83f8 --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/function-type-starting-with-a-multiline-tuple-in-the-middle-of-a-function-type.fs @@ -0,0 +1 @@ +type T = a -> (int * LongTypeNameNumberOneLongTypeNameNumberTwoLongTypeNameNumberThreeLongTypeNameNumberFourLongTypeNameNumberFive -> unit) -> unit diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/function-type-starting-with-a-multiline-tuple-in-the-middle-of-a-function-type.gold.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/function-type-starting-with-a-multiline-tuple-in-the-middle-of-a-function-type.gold.fs new file mode 100644 index 0000000000..87143c214d --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/function-type-starting-with-a-multiline-tuple-in-the-middle-of-a-function-type.gold.fs @@ -0,0 +1,6 @@ +type T = + a + -> (int * + LongTypeNameNumberOneLongTypeNameNumberTwoLongTypeNameNumberThreeLongTypeNameNumberFourLongTypeNameNumberFive + -> unit) + -> unit diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/multiline-struct-tuple-in-the-middle-of-a-function-type.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/multiline-struct-tuple-in-the-middle-of-a-function-type.fs new file mode 100644 index 0000000000..62a95607d5 --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/multiline-struct-tuple-in-the-middle-of-a-function-type.fs @@ -0,0 +1 @@ +type T = a -> struct (int * LongTypeNameNumberOneLongTypeNameNumberTwoLongTypeNameNumberThreeLongTypeNameNumberFourLongTypeNameNumberFive) -> unit diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/multiline-struct-tuple-in-the-middle-of-a-function-type.gold.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/multiline-struct-tuple-in-the-middle-of-a-function-type.gold.fs new file mode 100644 index 0000000000..42112dcf6e --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/multiline-struct-tuple-in-the-middle-of-a-function-type.gold.fs @@ -0,0 +1,7 @@ +type T = + a + -> struct ( + int * + LongTypeNameNumberOneLongTypeNameNumberTwoLongTypeNameNumberThreeLongTypeNameNumberFourLongTypeNameNumberFive + ) + -> unit diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/multiline-tuple-in-a-postfix-application-in-the-middle-of-a-function-type.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/multiline-tuple-in-a-postfix-application-in-the-middle-of-a-function-type.fs new file mode 100644 index 0000000000..9f7387a151 --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/multiline-tuple-in-a-postfix-application-in-the-middle-of-a-function-type.fs @@ -0,0 +1 @@ +type T = a -> (int * LongTypeNameNumberOneLongTypeNameNumberTwoLongTypeNameNumberThreeLongTypeNameNumberFourLongTypeNameNumberFive) list -> unit diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/multiline-tuple-in-a-postfix-application-in-the-middle-of-a-function-type.gold.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/multiline-tuple-in-a-postfix-application-in-the-middle-of-a-function-type.gold.fs new file mode 100644 index 0000000000..7b25cc1470 --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/multiline-tuple-in-a-postfix-application-in-the-middle-of-a-function-type.gold.fs @@ -0,0 +1,5 @@ +type T = + a + -> (int * + LongTypeNameNumberOneLongTypeNameNumberTwoLongTypeNameNumberThreeLongTypeNameNumberFourLongTypeNameNumberFive) list + -> unit diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/multiline-tuple-in-an-array-in-the-middle-of-a-function-type.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/multiline-tuple-in-an-array-in-the-middle-of-a-function-type.fs new file mode 100644 index 0000000000..5ad9c598a1 --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/multiline-tuple-in-an-array-in-the-middle-of-a-function-type.fs @@ -0,0 +1 @@ +type T = a -> (int * LongTypeNameNumberOneLongTypeNameNumberTwoLongTypeNameNumberThreeLongTypeNameNumberFourLongTypeNameNumberFive)[] -> unit diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/multiline-tuple-in-an-array-in-the-middle-of-a-function-type.gold.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/multiline-tuple-in-an-array-in-the-middle-of-a-function-type.gold.fs new file mode 100644 index 0000000000..920036fc91 --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/multiline-tuple-in-an-array-in-the-middle-of-a-function-type.gold.fs @@ -0,0 +1,5 @@ +type T = + a + -> (int * + LongTypeNameNumberOneLongTypeNameNumberTwoLongTypeNameNumberThreeLongTypeNameNumberFourLongTypeNameNumberFive)[] + -> unit diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/multiline-tuple-in-parentheses-in-the-middle-of-a-function-type.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/multiline-tuple-in-parentheses-in-the-middle-of-a-function-type.fs new file mode 100644 index 0000000000..554457cdee --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/multiline-tuple-in-parentheses-in-the-middle-of-a-function-type.fs @@ -0,0 +1 @@ +type T = a -> (int * LongTypeNameNumberOneLongTypeNameNumberTwoLongTypeNameNumberThreeLongTypeNameNumberFourLongTypeNameNumberFive) -> unit diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/multiline-tuple-in-parentheses-in-the-middle-of-a-function-type.gold.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/multiline-tuple-in-parentheses-in-the-middle-of-a-function-type.gold.fs new file mode 100644 index 0000000000..3d58613ddd --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/multiline-tuple-in-parentheses-in-the-middle-of-a-function-type.gold.fs @@ -0,0 +1,5 @@ +type T = + a + -> (int * + LongTypeNameNumberOneLongTypeNameNumberTwoLongTypeNameNumberThreeLongTypeNameNumberFourLongTypeNameNumberFive) + -> unit diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/parenthesized-function-type-in-a-tuple-in-the-middle.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/parenthesized-function-type-in-a-tuple-in-the-middle.fs new file mode 100644 index 0000000000..b712a0f4cc --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/parenthesized-function-type-in-a-tuple-in-the-middle.fs @@ -0,0 +1 @@ +type T = string -> int * (LongTypeNameNumberOne -> LongTypeNameNumberTwo -> LongTypeNameNumberThree -> LongTypeNameNumberFour -> LongTypeNameNumberFive) -> unit diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/parenthesized-function-type-in-a-tuple-in-the-middle.gold.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/parenthesized-function-type-in-a-tuple-in-the-middle.gold.fs new file mode 100644 index 0000000000..c789201af1 --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/parenthesized-function-type-in-a-tuple-in-the-middle.gold.fs @@ -0,0 +1,9 @@ +type T = + string + -> int * + (LongTypeNameNumberOne + -> LongTypeNameNumberTwo + -> LongTypeNameNumberThree + -> LongTypeNameNumberFour + -> LongTypeNameNumberFive) + -> unit diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/trivia/line-comment-after-an-arrow-before-a-multiline-tuple.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/trivia/line-comment-after-an-arrow-before-a-multiline-tuple.fs new file mode 100644 index 0000000000..70c44a2a0c --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/trivia/line-comment-after-an-arrow-before-a-multiline-tuple.fs @@ -0,0 +1,3 @@ +type T = + a -> // after arrow + int * LongTypeNameNumberOneLongTypeNameNumberTwoLongTypeNameNumberThreeLongTypeNameNumberFourLongTypeNameNumberFive -> unit diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/trivia/line-comment-after-an-arrow-before-a-multiline-tuple.gold.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/trivia/line-comment-after-an-arrow-before-a-multiline-tuple.gold.fs new file mode 100644 index 0000000000..7a812394e1 --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/trivia/line-comment-after-an-arrow-before-a-multiline-tuple.gold.fs @@ -0,0 +1,6 @@ +type T = + a + -> // after arrow + int * + LongTypeNameNumberOneLongTypeNameNumberTwoLongTypeNameNumberThreeLongTypeNameNumberFourLongTypeNameNumberFive + -> unit diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/trivia/line-comment-after-an-arrow.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/trivia/line-comment-after-an-arrow.fs new file mode 100644 index 0000000000..802e210c6a --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/trivia/line-comment-after-an-arrow.fs @@ -0,0 +1,3 @@ +type T = + a -> // after arrow + b -> unit diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/trivia/line-comment-after-an-arrow.gold.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/trivia/line-comment-after-an-arrow.gold.fs new file mode 100644 index 0000000000..2829837fc9 --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/trivia/line-comment-after-an-arrow.gold.fs @@ -0,0 +1,5 @@ +type T = + a + -> // after arrow + b + -> unit diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/function-type-first-in-a-tuple-after-an-arrow.gold.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/function-type-first-in-a-tuple-after-an-arrow.gold.fs index f704d5f66a..516d106f15 100644 --- a/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/function-type-first-in-a-tuple-after-an-arrow.gold.fs +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/function-type-first-in-a-tuple-after-an-arrow.gold.fs @@ -5,4 +5,4 @@ type T = -> LongTypeNameNumberThree -> LongTypeNameNumberFour -> LongTypeNameNumberFive) * - int + int diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/Type/StructTuple/multiline-struct-tuple.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/StructTuple/multiline-struct-tuple.fs new file mode 100644 index 0000000000..22d207e158 --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/StructTuple/multiline-struct-tuple.fs @@ -0,0 +1 @@ +let origin: struct (LongTypeNameNumberOne * LongTypeNameNumberTwo * LongTypeNameNumberThree * LongTypeNameNumberFour * LongTypeNameNumberFive) = failwith "" diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/Type/StructTuple/multiline-struct-tuple.gold.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/StructTuple/multiline-struct-tuple.gold.fs new file mode 100644 index 0000000000..29b1d0dc81 --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/StructTuple/multiline-struct-tuple.gold.fs @@ -0,0 +1,9 @@ +let origin + : struct ( + LongTypeNameNumberOne * + LongTypeNameNumberTwo * + LongTypeNameNumberThree * + LongTypeNameNumberFour * + LongTypeNameNumberFive + ) = + failwith "" diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/Type/StructTuple/struct-tuple-elements-on-one-line-after-the-parenthesis.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/StructTuple/struct-tuple-elements-on-one-line-after-the-parenthesis.fs new file mode 100644 index 0000000000..8b4ad64146 --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/StructTuple/struct-tuple-elements-on-one-line-after-the-parenthesis.fs @@ -0,0 +1 @@ +let origin: struct (LongTypeNameNumberOne * LongTypeNameNumberTwo * LongTypeNameNumberThree * LongTypeNameNumberFour * LongTypeName) = failwith "" diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/Type/StructTuple/struct-tuple-elements-on-one-line-after-the-parenthesis.gold.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/StructTuple/struct-tuple-elements-on-one-line-after-the-parenthesis.gold.fs new file mode 100644 index 0000000000..33d05b319b --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/StructTuple/struct-tuple-elements-on-one-line-after-the-parenthesis.gold.fs @@ -0,0 +1,5 @@ +let origin + : struct ( + LongTypeNameNumberOne * LongTypeNameNumberTwo * LongTypeNameNumberThree * LongTypeNameNumberFour * LongTypeName + ) = + failwith "" diff --git a/src/Fantomas.Core/CodePrinter.fs b/src/Fantomas.Core/CodePrinter.fs index 870faabf1d..4c6793f131 100644 --- a/src/Fantomas.Core/CodePrinter.fs +++ b/src/Fantomas.Core/CodePrinter.fs @@ -3832,6 +3832,22 @@ let genReturnTypeBinding (node: BindingReturnInfoNode option) = +> sepSpace +> genType node.Type +/// Whether a tuple starts the lines of a type: the type is one, or begins with one. A multiline tuple +/// starts the lines after its first element at the indent rather than indenting them itself, so the +/// code around the type decides where they go. +let rec startsWithTuple (t: Type) : bool = + match t with + | Type.Tuple _ -> true + | Type.Paren node -> startsWithTuple node.Type + | Type.WithGlobalConstraints node -> startsWithTuple node.Type + | Type.AppPostfix node -> startsWithTuple node.First + | Type.Array node -> startsWithTuple node.Type + | Type.Funs node -> + match List.tryHead node.Parameters with + | None -> startsWithTuple node.ReturnType + | Some(parameter, _) -> startsWithTuple parameter + | _ -> false + let genBinding (b: BindingNode) (ctx: Context) : Context = let spaceBefore, alternativeSyntax = let keywords = @@ -3846,25 +3862,13 @@ let genBinding (b: BindingNode) (ctx: Context) : Context = | _ -> ctx.Config.SpaceBeforeParameter, ctx.Config.AlignFunctionSignatureToIndentation // A line of the return type that starts on the column of the `:` ends it. The indent stays the - // binding's, so a type that indents its own lines lands on a multiple of the indent size. A - // multiline tuple starts the lines after its first element at the indent, so where a tuple - // starts the lines of the type, AtColumn keeps them past the `:`. + // binding's, so a type that indents its own lines lands on a multiple of the indent size. Where + // a tuple starts the lines of the type, AtColumn keeps them past the `:`. let genReturnTypeAfterColon (t: Type) : Context -> Context = - let rec isTuple (t: Type) : bool = - match t with - | Type.Paren parenNode -> isTuple parenNode.Type - | Type.WithGlobalConstraints wgcNode -> isTuple wgcNode.Type - | Type.Funs funNode -> - match List.tryHead funNode.Parameters with - | None -> isTuple funNode.ReturnType - | Some(p, _) -> isTuple p - | Type.AppPostfix appPostFixNode -> isTuple appPostFixNode.First - | Type.Array arrayNode -> isTuple arrayNode.Type - | Type.StructTuple _ -> true - | Type.Tuple _ -> true - | _ -> false - - if isTuple t then atCurrentColumn (genType t) else genType t + if startsWithTuple t then + atCurrentColumn (genType t) + else + genType t let isRecursiveLetOrUseFunction = match b.LeadingKeyword.Content with @@ -4252,12 +4256,23 @@ let genType (t: Type) = | [] -> genType node.ReturnType | (ht, ha) :: rest -> + // A tuple puts its lines at the indent, the column of the `->` lines. The element after a + // line-ending `*` starts a block at its own column, and a `->` on that column is read as + // a new statement. Where a tuple starts the lines of the type, it goes one level in. + let genTypeAfterArrow (t: Type) : Context -> Context = + sepSpaceUnlessWriteBeforeNewlineNotEmpty + +> autoIndentAndNlnWhenWriteBeforeNewlineNotEmpty ( + if startsWithTuple t then + indent +> genType t +> unindent + else + genType t + ) + genType ht +> indentSepNlnUnindent ( genSingleTextNode ha - +> sepSpace - +> col sepNone rest (fun (t, arrow) -> genType t +> sepNln +> genSingleTextNode arrow +> sepSpace) - +> genType node.ReturnType + +> col sepNone rest (fun (t, arrow) -> genTypeAfterArrow t +> sepNln +> genSingleTextNode arrow) + +> genTypeAfterArrow node.ReturnType ) expressionFitsOnRestOfLine short long |> genNode node @@ -4298,12 +4313,21 @@ let genType (t: Type) = node.GreaterThan |> genNode node | Type.StructTuple node -> - genSingleTextNode node.Keyword - +> sepSpace - +> sepOpenT - +> genSynTupleTypeSegments node.Path - +> genSingleTextNode node.ClosingParen - |> genNode node + let genOpening: Context -> Context = + genSingleTextNode node.Keyword +> sepSpace +> sepOpenT + + let short: Context -> Context = + genOpening + +> genSynTupleTypeSegments node.Path + +> genSingleTextNode node.ClosingParen + + let long: Context -> Context = + genOpening + +> indentSepNlnUnindent (genSynTupleTypeSegments node.Path) + +> sepNln + +> genSingleTextNode node.ClosingParen + + expressionFitsOnRestOfLine short long |> genNode node | Type.WithSubTypeConstraint tc -> genTypeConstraint tc | Type.WithGlobalConstraints node -> genType node.Type +> genTypeConstraints node.TypeConstraints |> genNode node | Type.LongIdent idn -> genIdentListNode idn From ea45638b9b8713fa8591e3c007835e485b6759c3 Mon Sep 17 00:00:00 2001 From: Florian Verdonck Date: Wed, 21 Oct 2026 11:05:51 +0200 Subject: [PATCH 04/16] Tell agents how to talk about a formatting change Discussions about formatting stalled on two things. "Comment" meant either trivia in the formatted F# or a comment in Fantomas' own source, and questions came as fragments of code that could not be judged without the code base open, wrapped beyond reading in the chat. AGENTS.md now asks agents to say trivia for comments in the F# that Fantomas reads or writes, and explanatory or doc comment for those in our source, and to keep the latter accurate as part of every change. A finding or question about formatting carries a full example: the input, the result before and after the change, what is wrong, and for a decision every option, checked with the SDK compilers. A question that needs code goes into question.fs in the repo root, which the user reads in the editor; .fantomasignore lists it, so the formatter hook and the editor leave its examples as written. --- .fantomasignore | 3 +++ AGENTS.md | 62 +++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 65 insertions(+) diff --git a/.fantomasignore b/.fantomasignore index 0f22eb5ccc..f2e99e0ef3 100644 --- a/.fantomasignore +++ b/.fantomasignore @@ -5,3 +5,6 @@ scripts/hero-video/fixture # The snapshot cases: inputs and golds are what they are, not code to format src/Fantomas.Core.SnapshotTests/cases/ + +# A question for the user, written by an agent: its examples are the point, not code to format +/question.fs diff --git a/AGENTS.md b/AGENTS.md index e6b2038a6f..5449150aa8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -45,6 +45,68 @@ compatibility overload, and without calling it out as a breaking change. Leave O between tags instead. Code generation on top of the Oak is told to expect this (`docs/docs/end-users/GeneratingCode.fsx`, "Updates"). +## Talking about a formatting change + +### Trivia versus comments in our code + +"Comment" alone is ambiguous here, so always name which kind: + +- **Trivia** is what sits in the F# that Fantomas reads or writes: a trivia line comment, a trivia + block comment, a blank line, a directive. A comment in a formatted result is always trivia. +- In Fantomas' own source, say **explanatory comment** (`//` saying why the code does what it does) + or **doc comment** (`///`). + +Keep the explanatory and doc comments beside the code a change touches accurate as part of every +change, and correct them without asking: re-read them after editing, and say in your report what you +corrected. Comments elsewhere in the file stay as they are. + +An explanatory comment sits beside the code it explains. When it explains one branch of an `if` or a +`match`, it goes at the top of that branch, rather than in a block above the whole expression that +explains every branch at once. + +When it explains a layout, show the layout instead of describing it: a few lines of the F# the code +produces, with a short note on the line that matters. + +### Every example in full + +The user answers from the message alone, without the code base open. Every finding, review point or +question about formatting carries a full example: + +1. The input, as a user would write it: a whole, parseable declaration, never a fragment. +2. What main formats it to, or what the branch did before this change (say which). When the result + is not idempotent, every pass until it settles. +3. What this branch formats it to. +4. What is wrong or what changed, marked with an F# `// <-` comment on the exact lines, and the + compiler error when it does not compile. +5. For a decision: every option as complete code, each saying whether it compiles and is + idempotent, then the question, with an easy answer (A/B, yes/no). + +Say which examples are real output and which are written by hand. Fantomas' parser accepts some +layouts the shipped compilers reject, so check "it compiles" with the SDK compilers: a `.fsx` in its +own folder under `tmp/`, a `global.json` pinning the SDK, then `dotnet fsi`. + +Repeat context rather than refer back to earlier messages, files, section numbers or review point +numbers. When where the printer does it helps, say it in plain words with enough context to follow +without opening `CodePrinter.fs`. After a review, first one line on what it found, then one numbered +question at a time. + +### Asking with question.fs + +When a question needs F# code to show it, because it is about what Fantomas formats code to or +about a formatting bug, write it into `question.fs` in the repo root, left untracked: the chat wraps +long lines, and the user reads code in the editor. Questions about anything else (the docs site, +tooling, staging) stay in the chat. The file: + +- opens with the situation in a few sentences and ends with the question; +- holds the prose as trivia block comments, the `// <-` markers as trivia line comments and every + example as code, so it is the single source of truth; +- parses as a whole: give each block its own name (`Input`, `OptionA`) and say at the top what the + real name is; check it with `scripts/ast.fsx`. + +`.fantomasignore` lists `question.fs`, so the formatter hook and the editor leave its examples as +written. The chat message gives its path and the question in one line. Once the user has answered, +delete the file before doing anything else. + ## Code Style The style rules for this repository are analyzers rather than prose, so the feedback arrives while From b33d874c7f404c9e6b4eec72bc3c8907d337ea1d Mon Sep 17 00:00:00 2001 From: Florian Verdonck Date: Wed, 21 Oct 2026 13:06:33 +0200 Subject: [PATCH 05/16] Keep a tuple after an arrow's trivia comment at the indent When a trivia line comment follows the arrow of a function type, the type after it already starts on a new line one level past the arrows. A multiline tuple there took a second level for its later elements, which only the tuple on the arrow's own line needs: there, the element after a line-ending `*` would otherwise sit on the column of the next `->`, which does not parse. After the comment, the later elements now stay on the indent, under the first one. The explanatory comments for each branch now show the layout they produce, inside the branch they explain. AGENTS.md: a review's findings that come with F# code, nits included, go into an untracked review.fs, written the same way as question.fs. .fantomasignore lists it, so the formatter leaves its examples alone. --- .fantomasignore | 3 ++- AGENTS.md | 15 +++++++---- ...-an-arrow-before-a-multiline-tuple.gold.fs | 2 +- src/Fantomas.Core/CodePrinter.fs | 27 +++++++++++-------- 4 files changed, 29 insertions(+), 18 deletions(-) diff --git a/.fantomasignore b/.fantomasignore index f2e99e0ef3..0fd14eed91 100644 --- a/.fantomasignore +++ b/.fantomasignore @@ -6,5 +6,6 @@ scripts/hero-video/fixture # The snapshot cases: inputs and golds are what they are, not code to format src/Fantomas.Core.SnapshotTests/cases/ -# A question for the user, written by an agent: its examples are the point, not code to format +# A question or review findings for the user, written by an agent: the examples are the point, not code to format /question.fs +/review.fs diff --git a/AGENTS.md b/AGENTS.md index 5449150aa8..f2ac39002c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -90,12 +90,17 @@ numbers. When where the printer does it helps, say it in plain words with enough without opening `CodePrinter.fs`. After a review, first one line on what it found, then one numbered question at a time. -### Asking with question.fs +### question.fs and review.fs When a question needs F# code to show it, because it is about what Fantomas formats code to or about a formatting bug, write it into `question.fs` in the repo root, left untracked: the chat wraps long lines, and the user reads code in the editor. Questions about anything else (the docs site, -tooling, staging) stay in the chat. The file: +tooling, staging) stay in the chat. + +A review's findings that come with F# code, nits included, go into `review.fs` the same way, as +soon as the review is in: every finding with its full example, ending on the first question. + +Either file: - opens with the situation in a few sentences and ends with the question; - holds the prose as trivia block comments, the `// <-` markers as trivia line comments and every @@ -103,9 +108,9 @@ tooling, staging) stay in the chat. The file: - parses as a whole: give each block its own name (`Input`, `OptionA`) and say at the top what the real name is; check it with `scripts/ast.fsx`. -`.fantomasignore` lists `question.fs`, so the formatter hook and the editor leave its examples as -written. The chat message gives its path and the question in one line. Once the user has answered, -delete the file before doing anything else. +`.fantomasignore` lists both, so the formatter hook and the editor leave their examples as written. +The chat message gives the path and the question in one line. Once the user has answered the last +question in it, delete the file before doing anything else. ## Code Style diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/trivia/line-comment-after-an-arrow-before-a-multiline-tuple.gold.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/trivia/line-comment-after-an-arrow-before-a-multiline-tuple.gold.fs index 7a812394e1..e77e1a86f9 100644 --- a/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/trivia/line-comment-after-an-arrow-before-a-multiline-tuple.gold.fs +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Funs/trivia/line-comment-after-an-arrow-before-a-multiline-tuple.gold.fs @@ -2,5 +2,5 @@ type T = a -> // after arrow int * - LongTypeNameNumberOneLongTypeNameNumberTwoLongTypeNameNumberThreeLongTypeNameNumberFourLongTypeNameNumberFive + LongTypeNameNumberOneLongTypeNameNumberTwoLongTypeNameNumberThreeLongTypeNameNumberFourLongTypeNameNumberFive -> unit diff --git a/src/Fantomas.Core/CodePrinter.fs b/src/Fantomas.Core/CodePrinter.fs index 4c6793f131..12bfaf4d86 100644 --- a/src/Fantomas.Core/CodePrinter.fs +++ b/src/Fantomas.Core/CodePrinter.fs @@ -4256,17 +4256,22 @@ let genType (t: Type) = | [] -> genType node.ReturnType | (ht, ha) :: rest -> - // A tuple puts its lines at the indent, the column of the `->` lines. The element after a - // line-ending `*` starts a block at its own column, and a `->` on that column is read as - // a new statement. Where a tuple starts the lines of the type, it goes one level in. - let genTypeAfterArrow (t: Type) : Context -> Context = - sepSpaceUnlessWriteBeforeNewlineNotEmpty - +> autoIndentAndNlnWhenWriteBeforeNewlineNotEmpty ( - if startsWithTuple t then - indent +> genType t +> unindent - else - genType t - ) + let genTypeAfterArrow (t: Type) (ctx: Context) : Context = + if hasWriteBeforeNewlineContent ctx then + // a + // -> // trivia + // int * + // Long under `int`: already past the `->` lines, so no extra level + // -> unit + indentSepNlnUnindent (genType t) ctx + elif startsWithTuple t then + // a + // -> int * + // Long one level in: on the `->` column, the next `->` does not parse + // -> unit + (sepSpace +> indent +> genType t +> unindent) ctx + else + (sepSpace +> genType t) ctx genType ht +> indentSepNlnUnindent ( From eca0b5c4b5802aee3d84b0b5df21d37a2c8215ed Mon Sep 17 00:00:00 2001 From: Florian Verdonck Date: Wed, 21 Oct 2026 13:12:25 +0200 Subject: [PATCH 06/16] Cover a parenthesized function type after an arrow with indent size 2 With indent_size = 2, the blanket extra level from #3225 put the `->` lines of a parenthesized function type after an outer `->` on the column right after the `(`. A line starting there ends the offside context the parenthesis opens, so the result did not parse. Type.Paren now starts those lines past that column whatever the indent size, since the fix for #3554. This adds a case for indent_size = 2, which no case covered, and the changelog entry. Closes #3557 --- CHANGELOG.md | 1 + ...tion-type-after-an-arrow-starts-past-the-parenthesis.fs | 4 ++++ ...type-after-an-arrow-starts-past-the-parenthesis.gold.fs | 7 +++++++ 3 files changed, 12 insertions(+) create mode 100644 src/Fantomas.Core.SnapshotTests/cases/settings/indent_size/Type/Paren/3557-function-type-after-an-arrow-starts-past-the-parenthesis.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/settings/indent_size/Type/Paren/3557-function-type-after-an-arrow-starts-past-the-parenthesis.gold.fs diff --git a/CHANGELOG.md b/CHANGELOG.md index 3642f7582d..fe612774d5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ - Parenthesized function type gets an extra indent level where no outer function type needs it. [#3554](https://github.com/fsprojects/fantomas/issues/3554) - Multiline tuple in the middle of a function type gives invalid code. [#3556](https://github.com/fsprojects/fantomas/issues/3556) +- Parenthesized function type after an arrow gives invalid code with indent_size 2. [#3557](https://github.com/fsprojects/fantomas/issues/3557) ## [8.0.10] - 2026-10-14 diff --git a/src/Fantomas.Core.SnapshotTests/cases/settings/indent_size/Type/Paren/3557-function-type-after-an-arrow-starts-past-the-parenthesis.fs b/src/Fantomas.Core.SnapshotTests/cases/settings/indent_size/Type/Paren/3557-function-type-after-an-arrow-starts-past-the-parenthesis.fs new file mode 100644 index 0000000000..60cd17b2e6 --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/settings/indent_size/Type/Paren/3557-function-type-after-an-arrow-starts-past-the-parenthesis.fs @@ -0,0 +1,4 @@ +(*--- +indent_size = 2 +---*) +type T = a -> (LongTypeNameNumberOne -> LongTypeNameNumberTwo -> LongTypeNameNumberThree -> LongTypeNameNumberFour -> LongTypeNameNumberFive) diff --git a/src/Fantomas.Core.SnapshotTests/cases/settings/indent_size/Type/Paren/3557-function-type-after-an-arrow-starts-past-the-parenthesis.gold.fs b/src/Fantomas.Core.SnapshotTests/cases/settings/indent_size/Type/Paren/3557-function-type-after-an-arrow-starts-past-the-parenthesis.gold.fs new file mode 100644 index 0000000000..2f557e3bd1 --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/settings/indent_size/Type/Paren/3557-function-type-after-an-arrow-starts-past-the-parenthesis.gold.fs @@ -0,0 +1,7 @@ +type T = + a + -> (LongTypeNameNumberOne + -> LongTypeNameNumberTwo + -> LongTypeNameNumberThree + -> LongTypeNameNumberFour + -> LongTypeNameNumberFive) From 2fceb755d52ed712e422ab1697e6d97cc0822c7f Mon Sep 17 00:00:00 2001 From: Florian Verdonck Date: Wed, 21 Oct 2026 13:59:37 +0200 Subject: [PATCH 07/16] Indent a long :? type test, and a tuple after a cast operator A type test that did not fit on one line was broken before its operator, like the other typed expressions, which put `:?` on the column of the expression. `:>`, `:?>` and `:` may start a line there, but for the offside rule `:?` is not an infix token, so the parser read it as the start of a new expression and the result did not compile. The `:?` line now goes one level in, so it breaks the same way as the other operators. A multiline tuple type after any of the four operators put the lines after its first element at the indent, the column of the operator line. That compiled, but read as if the type had ended. Where the type starts with a tuple, it now goes one level in, as it does after the `->` of a function type, which keeps its lines on a multiple of the indent size and, in parentheses after `:>` and `:?`, under the first element. No case covered a type test in an expression, or a tuple after any of these operators; this adds one of each. Closes #3558 --- CHANGELOG.md | 1 + ...ong-type-test-breaks-after-the-operator.fs | 1 + ...ype-test-breaks-after-the-operator.gold.fs | 3 +++ ...tuple-after-an-upcast-goes-one-level-in.fs | 1 + ...-after-an-upcast-goes-one-level-in.gold.fs | 7 +++++++ src/Fantomas.Core/CodePrinter.fs | 20 ++++++++++++++++++- 6 files changed, 32 insertions(+), 1 deletion(-) create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/Expr/Typed/3558-long-type-test-breaks-after-the-operator.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/Expr/Typed/3558-long-type-test-breaks-after-the-operator.gold.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/Expr/Typed/multiline-tuple-after-an-upcast-goes-one-level-in.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/Expr/Typed/multiline-tuple-after-an-upcast-goes-one-level-in.gold.fs diff --git a/CHANGELOG.md b/CHANGELOG.md index fe612774d5..5fdaa671d4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ - Parenthesized function type gets an extra indent level where no outer function type needs it. [#3554](https://github.com/fsprojects/fantomas/issues/3554) - Multiline tuple in the middle of a function type gives invalid code. [#3556](https://github.com/fsprojects/fantomas/issues/3556) - Parenthesized function type after an arrow gives invalid code with indent_size 2. [#3557](https://github.com/fsprojects/fantomas/issues/3557) +- Long type test with :? gives invalid code. [#3558](https://github.com/fsprojects/fantomas/issues/3558) ## [8.0.10] - 2026-10-14 diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/Expr/Typed/3558-long-type-test-breaks-after-the-operator.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/Expr/Typed/3558-long-type-test-breaks-after-the-operator.fs new file mode 100644 index 0000000000..23fdf281b1 --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/Expr/Typed/3558-long-type-test-breaks-after-the-operator.fs @@ -0,0 +1 @@ +let x = someLongValueExpressionThatIsLong :? LongTypeNameNumberOneLongTypeNameNumberTwoLongTypeNameNumberThreeLongTypeNameNumberFourLongTypeNameNumberFive diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/Expr/Typed/3558-long-type-test-breaks-after-the-operator.gold.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/Expr/Typed/3558-long-type-test-breaks-after-the-operator.gold.fs new file mode 100644 index 0000000000..c57ed66ed7 --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/Expr/Typed/3558-long-type-test-breaks-after-the-operator.gold.fs @@ -0,0 +1,3 @@ +let x = + someLongValueExpressionThatIsLong + :? LongTypeNameNumberOneLongTypeNameNumberTwoLongTypeNameNumberThreeLongTypeNameNumberFourLongTypeNameNumberFive diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/Expr/Typed/multiline-tuple-after-an-upcast-goes-one-level-in.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/Expr/Typed/multiline-tuple-after-an-upcast-goes-one-level-in.fs new file mode 100644 index 0000000000..25b817d58a --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/Expr/Typed/multiline-tuple-after-an-upcast-goes-one-level-in.fs @@ -0,0 +1 @@ +let x = someValue :> (LongTypeNameNumberOne * LongTypeNameNumberTwo * LongTypeNameNumberThree * LongTypeNameNumberFour * LongTypeNameNumberFive) diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/Expr/Typed/multiline-tuple-after-an-upcast-goes-one-level-in.gold.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/Expr/Typed/multiline-tuple-after-an-upcast-goes-one-level-in.gold.fs new file mode 100644 index 0000000000..e5dce1c00b --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/Expr/Typed/multiline-tuple-after-an-upcast-goes-one-level-in.gold.fs @@ -0,0 +1,7 @@ +let x = + someValue + :> (LongTypeNameNumberOne * + LongTypeNameNumberTwo * + LongTypeNameNumberThree * + LongTypeNameNumberFour * + LongTypeNameNumberFive) diff --git a/src/Fantomas.Core/CodePrinter.fs b/src/Fantomas.Core/CodePrinter.fs index 12bfaf4d86..7f9cbf2607 100644 --- a/src/Fantomas.Core/CodePrinter.fs +++ b/src/Fantomas.Core/CodePrinter.fs @@ -1307,7 +1307,25 @@ let genExpr (e: Expr) = genExpr node.Expr +> genOperator +> sepSpace +> genType node.Type let long = - genExpr node.Expr +> sepNln +> !-node.Operator +> sepSpace +> genType node.Type + let genOperatorAndType: Context -> Context = + !-node.Operator + +> sepSpace + +> if startsWithTuple node.Type then + // someValue + // :> (int * + // Long) one level in: a tuple puts its lines at the indent, the + // column of `:>` + indent +> genType node.Type +> unindent + else + genType node.Type + + if node.Operator = ":?" then + // someValue + // :? LongTypeName one level in: `:?` is no infix operator, so on the column + // of `someValue` it starts a new expression + genExpr node.Expr +> indentSepNlnUnindent genOperatorAndType + else + genExpr node.Expr +> sepNln +> genOperatorAndType match node.Expr with | Expr.Lambda _ -> long From 8834c512aaab49102198e5e1381180340de9647a Mon Sep 17 00:00:00 2001 From: Florian Verdonck Date: Wed, 21 Oct 2026 14:10:46 +0200 Subject: [PATCH 08/16] Report a match on a constant against a wildcard as an if FANTOMAS-SNOBMATCH-001 only spoke for a two armed match on a boolean. A constant against a wildcard asks the same kind of question, whether the scrutinee equals that constant, and rewrites as mechanically: `if scrutinee = constant then ... else ...`, with the scrutinee still written once. Such a match in the type annotation printer went through review unreported. The rule now reports that shape too, with a message of its own. Unit, two constants without a wildcard, and a constant against a binder stay unreported. Nothing in the analyzed code had the shape, so no existing finding comes with it. --- analyzers/AGENTS.md | 30 +++++++-- .../SnobMatchAnalyzerTests.fs | 63 +++++++++++++++++++ .../Fantomas.Analyzers/SnobMatchAnalyzer.fs | 44 ++++++++++--- .../Fantomas.Analyzers/SnobMatchAnalyzer.fsi | 16 ++--- 4 files changed, 131 insertions(+), 22 deletions(-) diff --git a/analyzers/AGENTS.md b/analyzers/AGENTS.md index 71ed9460de..38d3d548ad 100644 --- a/analyzers/AGENTS.md +++ b/analyzers/AGENTS.md @@ -365,11 +365,31 @@ the reader to expect a destructuring and then does not deliver one, and it spend patterns on a question that has a keyword of its own. That is what the name is about: the match is dressed up for an occasion the code is not having. -It speaks only for the boolean case, which is the one where the rewrite is mechanical. Both arms -are `true` and `false` in either order, or one of them against a wildcard, and either way the -scrutinee becomes the condition and is written once, exactly where it already was. Nothing is -duplicated, nothing new is bound, and there is no judgement to make about whether the scrutinee is -cheap enough to evaluate twice. +It speaks for the two shapes where the rewrite is mechanical. The first is the boolean case: both +arms are `true` and `false` in either order, or one of them against a wildcard, and the scrutinee +becomes the condition. The second is any other constant against a wildcard: + +```fsharp +if node.Operator = ":?" then + genExpr node.Expr +> indentSepNlnUnindent genOperatorAndType +else + genExpr node.Expr +> sepNln +> genOperatorAndType +``` + +rather than + +```fsharp +match node.Operator with +| ":?" -> genExpr node.Expr +> indentSepNlnUnindent genOperatorAndType +| _ -> genExpr node.Expr +> sepNln +> genOperatorAndType +``` + +The constant is not taking anything apart either: the match asks one equality and spends a pattern +on each answer. Either way the scrutinee is written once, exactly where it already was, as the condition or +as the left of the `=`. Nothing is duplicated, nothing new is bound, and there is no judgement to +make about whether the scrutinee is cheap enough to evaluate twice. Unit is left out, having one +value and nothing to ask, and so are two constants without a wildcard, which do not cover the +scrutinee between them. The shape next door is the one this deliberately leaves alone, a constant arm and a binder holding the scrutinee under a second name: diff --git a/analyzers/Fantomas.Analyzers.Tests/SnobMatchAnalyzerTests.fs b/analyzers/Fantomas.Analyzers.Tests/SnobMatchAnalyzerTests.fs index 3b8f84cedf..7194657f9b 100644 --- a/analyzers/Fantomas.Analyzers.Tests/SnobMatchAnalyzerTests.fs +++ b/analyzers/Fantomas.Analyzers.Tests/SnobMatchAnalyzerTests.fs @@ -54,6 +54,69 @@ let f (xs: int list) : int = analyzeSource cliAnalyzer source |> assertLines [ 4 ] +[] +let ``a match on a string constant and a wildcard is reported`` () = + let source: string = + """module M + +let f (operator: string) : int = + match operator with + | ":?" -> 1 + | _ -> 0""" + + analyzeSource cliAnalyzer source |> assertLines [ 4 ] + +[] +let ``a match on an integer constant and a wildcard is reported`` () = + let source: string = + """module M + +let f (x: int) : int = + match x with + | -1 -> 0 + | _ -> x""" + + analyzeSource cliAnalyzer source |> assertLines [ 4 ] + +// A constant arm after the wildcard is never reached; the compiler says so, and an `if` would +// have to invent the opposite test to keep the order. +[] +let ``a match on a wildcard and then a constant is not reported`` () = + let source: string = + """module M + +let f (x: int) : int = + match x with + | _ -> 0 + | 1 -> 1""" + + analyzeSource cliAnalyzer source |> assertLines [] + +// Two constants do not cover the scrutinee between them, so the second arm is not an `else`. +[] +let ``a match on two constants is not reported`` () = + let source: string = + """module M + +let f (x: char) : int = + match x with + | 'a' -> 1 + | 'b' -> 2""" + + analyzeSource cliAnalyzer source |> assertLines [] + +[] +let ``a match on unit and a wildcard is not reported`` () = + let source: string = + """module M + +let f (x: unit) : int = + match x with + | () -> 1 + | _ -> 0""" + + analyzeSource cliAnalyzer source |> assertLines [] + [] let ``a match on a union is not reported`` () = let source: string = diff --git a/analyzers/Fantomas.Analyzers/SnobMatchAnalyzer.fs b/analyzers/Fantomas.Analyzers/SnobMatchAnalyzer.fs index adc061f0a9..78437c5702 100644 --- a/analyzers/Fantomas.Analyzers/SnobMatchAnalyzer.fs +++ b/analyzers/Fantomas.Analyzers/SnobMatchAnalyzer.fs @@ -14,7 +14,7 @@ let Name: string = "SnobMatchAnalyzer" [] let ShortDescription: string = - "Detects a two armed match on a boolean, which is an if expression dressed up as pattern matching." + "Detects a two armed match on a boolean, or on a constant against a wildcard, which is an if expression dressed up as pattern matching." [] let HelpUri: string = @@ -32,6 +32,26 @@ let isBooleanTest (first: SynPat) (second: SynPat) : bool = | SynPat.Const(SynConst.Bool firstValue, _), SynPat.Const(SynConst.Bool secondValue, _) -> firstValue <> secondValue | _ -> false +// Whether a pair of arm patterns is an equality test written out as two arms. +// +// A constant against a wildcard: the first arm is reached when the scrutinee equals the constant +// and the second whenever it does not, which is `if scrutinee = constant then ... else ...` with +// the scrutinee still written once. A boolean constant is the test above, and unit has one value +// and nothing to test. +let isConstantTest (first: SynPat) (second: SynPat) : bool = + match first, second with + | SynPat.Const((SynConst.Bool _ | SynConst.Unit), _), _ -> false + | SynPat.Const _, SynPat.Wild _ -> true + | _ -> false + +[] +let booleanMessage: string = + "Write this as an `if`. A `match` is for taking a value apart, and this one only asks whether a boolean is true, which `if ... then ... else ...` says with no pattern in sight and the scrutinee still written once." + +[] +let constantMessage: string = + "Write this as an `if`. A `match` is for taking a value apart, and this one only asks whether a value equals a constant, which `if ... = ... then ... else ...` says with no pattern in sight and the scrutinee still written once." + // Whether this expression is a match an `if` would say better. // // `SynExpr.Match` alone, where the two rules about arm layout reach through `matchClausesOf` for @@ -43,40 +63,46 @@ let isBooleanTest (first: SynPat) (second: SynPat) : bool = // A `when` guard on either arm means the arms no longer cover the scrutinee between them, so the // match is asking something the patterns do not say. A conditional directive inside means the two // arms this reads are not the arms every build sees. -let shouldBeAnIf (directives: range list) (expr: SynExpr) : range option = +let shouldBeAnIf (directives: range list) (expr: SynExpr) : (range * string) option = match expr with | SynExpr.Match( clauses = [ SynMatchClause(pat = first; whenExpr = None); SynMatchClause(pat = second; whenExpr = None) ] - range = matchRange) when isBooleanTest first second -> + range = matchRange) -> let holdsADirective: bool = directives |> List.exists (fun (directive: range) -> Range.rangeContainsRange matchRange directive) - if holdsADirective then None else Some matchRange + if holdsADirective then + None + elif isBooleanTest first second then + Some(matchRange, booleanMessage) + elif isConstantTest first second then + Some(matchRange, constantMessage) + else + None | _ -> None // Reported on the whole match expression, because the whole of it is what goes. let analyze (parsedInput: ParsedInput) : Message list = let _, directives = triviaOf parsedInput - let findings: ResizeArray = ResizeArray() + let findings: ResizeArray = ResizeArray() let walker: SyntaxCollectorBase = { new SyntaxCollectorBase() with override _.WalkExpr(_path: SyntaxVisitorPath, expr: SynExpr) : unit = match shouldBeAnIf directives expr with | None -> () - | Some matchRange -> findings.Add matchRange + | Some finding -> findings.Add finding } walkAst walker parsedInput findings - |> Seq.map (fun (matchRange: range) -> + |> Seq.map (fun (matchRange: range, message: string) -> { Type = Name - Message = - "Write this as an `if`. A `match` is for taking a value apart, and this one only asks whether a boolean is true, which `if ... then ... else ...` says with no pattern in sight and the scrutinee still written once." + Message = message Code = Code Severity = Severity.Warning Range = matchRange diff --git a/analyzers/Fantomas.Analyzers/SnobMatchAnalyzer.fsi b/analyzers/Fantomas.Analyzers/SnobMatchAnalyzer.fsi index 4027cd6a29..c049f45eb6 100644 --- a/analyzers/Fantomas.Analyzers/SnobMatchAnalyzer.fsi +++ b/analyzers/Fantomas.Analyzers/SnobMatchAnalyzer.fsi @@ -10,19 +10,19 @@ val Name: string = "SnobMatchAnalyzer" [] val ShortDescription: string = - "Detects a two armed match on a boolean, which is an if expression dressed up as pattern matching." + "Detects a two armed match on a boolean, or on a constant against a wildcard, which is an if expression dressed up as pattern matching." [] val HelpUri: string = "https://github.com/fsprojects/fantomas/blob/main/analyzers/AGENTS.md#fantomas-snobmatch-001" -/// Reports a `match` on a boolean, on the whole expression, because the whole of it is what an -/// `if` replaces. +/// Reports a `match` on a boolean, or on a constant against a wildcard, on the whole expression, +/// because the whole of it is what an `if` replaces. /// -/// This is the narrowest shape of the rule and the only one where the rewrite is mechanical: the -/// scrutinee becomes the condition and is written once, exactly where it was. It stays quiet on a -/// guard, on anything other than two arms, on `match!` and `function`, which cannot be rewritten -/// without inventing a `let!` or a parameter, and on a conditional directive inside the match. No -/// fix is offered, as with every rule here. +/// These are the shapes where the rewrite is mechanical: the scrutinee becomes the condition, or +/// one side of an `=` against the constant, and is written once, exactly where it was. It stays +/// quiet on a guard, on anything other than two arms, on a constant against a binder, on `match!` +/// and `function`, which cannot be rewritten without inventing a `let!` or a parameter, and on a +/// conditional directive inside the match. No fix is offered, as with every rule here. [] val cliAnalyzer: ctx: CliContext -> Async From cc175cefe31fd8cee72e6ff5cfc4c54d744173aa Mon Sep 17 00:00:00 2001 From: Florian Verdonck Date: Wed, 21 Oct 2026 14:23:12 +0200 Subject: [PATCH 09/16] Keep a line comment after the opening parenthesis of a type there A line comment after the `(` of a parenthesized type waits for the next newline, and the type inside started on the same line, so the comment landed after the first token of the type and what followed went on the next line at the indent. For `Map` that split the type name from its arguments and did not compile, a tuple was not idempotent, and a function type got a blank line under the comment. When a line comment follows the `(`, the type now starts on the next line, at the first indent level past the `(`, where the context the parenthesis opens allows it. The comment stays where it was written. Closes #3559 --- CHANGELOG.md | 1 + ...e-comment-after-the-opening-parenthesis.fs | 2 ++ ...ment-after-the-opening-parenthesis.gold.fs | 3 ++ ...-opening-parenthesis-of-a-function-type.fs | 3 ++ ...ing-parenthesis-of-a-function-type.gold.fs | 8 +++++ src/Fantomas.Core/CodePrinter.fs | 30 +++++++++++-------- 6 files changed, 35 insertions(+), 12 deletions(-) create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/trivia/3559-line-comment-after-the-opening-parenthesis.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/trivia/3559-line-comment-after-the-opening-parenthesis.gold.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/trivia/line-comment-after-the-opening-parenthesis-of-a-function-type.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/trivia/line-comment-after-the-opening-parenthesis-of-a-function-type.gold.fs diff --git a/CHANGELOG.md b/CHANGELOG.md index 5fdaa671d4..aaad00eeb0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ - Multiline tuple in the middle of a function type gives invalid code. [#3556](https://github.com/fsprojects/fantomas/issues/3556) - Parenthesized function type after an arrow gives invalid code with indent_size 2. [#3557](https://github.com/fsprojects/fantomas/issues/3557) - Long type test with :? gives invalid code. [#3558](https://github.com/fsprojects/fantomas/issues/3558) +- Line comment after the opening parenthesis of a type moves and breaks the type. [#3559](https://github.com/fsprojects/fantomas/issues/3559) ## [8.0.10] - 2026-10-14 diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/trivia/3559-line-comment-after-the-opening-parenthesis.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/trivia/3559-line-comment-after-the-opening-parenthesis.fs new file mode 100644 index 0000000000..1960a32400 --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/trivia/3559-line-comment-after-the-opening-parenthesis.fs @@ -0,0 +1,2 @@ +type T = ( // c + Map) diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/trivia/3559-line-comment-after-the-opening-parenthesis.gold.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/trivia/3559-line-comment-after-the-opening-parenthesis.gold.fs new file mode 100644 index 0000000000..d3a072779b --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/trivia/3559-line-comment-after-the-opening-parenthesis.gold.fs @@ -0,0 +1,3 @@ +type T = + ( // c + Map) diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/trivia/line-comment-after-the-opening-parenthesis-of-a-function-type.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/trivia/line-comment-after-the-opening-parenthesis-of-a-function-type.fs new file mode 100644 index 0000000000..1dff0cdca0 --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/trivia/line-comment-after-the-opening-parenthesis-of-a-function-type.fs @@ -0,0 +1,3 @@ +type T = + a -> ( // c + LongTypeNameNumberOne -> LongTypeNameNumberTwo -> LongTypeNameNumberThree -> LongTypeNameNumberFour -> LongTypeNameNumberFive) diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/trivia/line-comment-after-the-opening-parenthesis-of-a-function-type.gold.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/trivia/line-comment-after-the-opening-parenthesis-of-a-function-type.gold.fs new file mode 100644 index 0000000000..469a3253d0 --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/trivia/line-comment-after-the-opening-parenthesis-of-a-function-type.gold.fs @@ -0,0 +1,8 @@ +type T = + a + -> ( // c + LongTypeNameNumberOne + -> LongTypeNameNumberTwo + -> LongTypeNameNumberThree + -> LongTypeNameNumberFour + -> LongTypeNameNumberFive) diff --git a/src/Fantomas.Core/CodePrinter.fs b/src/Fantomas.Core/CodePrinter.fs index 7f9cbf2607..fca91c357f 100644 --- a/src/Fantomas.Core/CodePrinter.fs +++ b/src/Fantomas.Core/CodePrinter.fs @@ -4397,20 +4397,26 @@ let genType (t: Type) = genNode node (isSmallExpression size smallExpression longExpression) ctx | Type.Paren node -> - let genOpeningAndInner: Context -> Context = - if not node.Type.IsFuns then - genSingleTextNode node.OpeningParen +> genType node.Type + let genInner (columnAfterParen: int) (ctx: Context) : Context = + if hasWriteBeforeNewlineContent ctx then + // ( // trivia + // Map) on a line of its own, past the `(`: the trivia line comment + // ends the line the `(` is on + indentPast (columnAfterParen - 1) (indentSepNlnUnindent (genType node.Type)) ctx + elif node.Type.IsFuns then + // The parenthesis opens an offside context at the first token inside it, and a line + // starting on that column ends it. The `->` lines of the function type start past the + // column right after the parenthesis, taken before its trivia: a block comment there + // moves the first token right, and a line left of that token parses. + indentPast columnAfterParen (genType node.Type) ctx else + genType node.Type ctx - // The parenthesis opens an offside context at the first token inside it, and a line - // starting on that column ends it. The `->` lines of the function type start past the - // column right after the parenthesis, taken before its trivia: a comment there moves - // the first token right, and a line left of that token parses. - enterNode node.OpeningParen - +> genSingleTextNodeText node.OpeningParen - +> fun ctx -> (leaveNode node.OpeningParen +> indentPast ctx.Column (genType node.Type)) ctx - - genOpeningAndInner +> genSingleTextNode node.ClosingParen |> genNode node + enterNode node.OpeningParen + +> genSingleTextNodeText node.OpeningParen + +> (fun ctx -> (leaveNode node.OpeningParen +> genInner ctx.Column) ctx) + +> genSingleTextNode node.ClosingParen + |> genNode node | Type.SignatureParameter node -> genOnelinerAttributes node.Attributes +> optSingle (fun id -> genSingleTextNode id +> sepColon) node.Identifier From 715a1e05af76116918f74736d9b59ab72e39f528 Mon Sep 17 00:00:00 2001 From: Florian Verdonck Date: Wed, 21 Oct 2026 16:32:44 +0200 Subject: [PATCH 10/16] Keep a trivia comment after the last element of a struct tuple type A long struct tuple type puts its elements on lines of their own and its `)` on a line by itself. A comment on its own line after the last element attaches after that element and ends with a newline of its own; the printer added another before the `)`, so every format added a blank line. It now unindents the way the list printer does and adds that newline only when nothing else has. The comment attached to the `)` instead when it lined up with the first element of a struct tuple whose elements share a line. The column search for a line comment follows only the node it directly follows at each depth, so earlier content on the comment's column was never reached. When nothing on that path matches but a later child of the container starts on the column, the comment now follows the container's last node before it. What opens the container does not count: its first child, whatever it is (`[`, `<@`, `begin`, `class`, `task` of `task {`, `foo` of `foo<...>`), and an opening bracket after it (`{|` of `struct {|`). A comment lined up with those stays before the closing token, as on main. The search now reads as two steps: the candidates are the nodes the comment directly follows, found from the end of the children, and one match over those on the comment's column picks the outermost that starts its line, else the innermost, else the first candidate when later content of the container lines up. Whether a node starts its line is read from the source text instead of carrying the end line of the code before it down every depth. The cursor, which never takes this path, is attached without going through it. One existing gold changes: a comment on the column of both the first element of a list and its `]` now goes with the elements, as it already did when the matching element was the last one. --- .../line-comment-on-the-column-of-struct.fs | 5 + ...ne-comment-on-the-column-of-struct.gold.fs | 6 + ...the-column-of-the-opening-array-bracket.fs | 5 + ...olumn-of-the-opening-array-bracket.gold.fs | 6 + ...nt-on-the-column-of-the-opening-bracket.fs | 4 + ...-the-column-of-the-opening-bracket.gold.fs | 6 + ...ne-comment-on-the-column-of-the-builder.fs | 6 + ...-on-the-column-of-the-opening-quotation.fs | 5 + ...he-column-of-the-opening-quotation.gold.fs | 6 + ...-comment-on-the-column-of-the-type-name.fs | 5 + ...ent-on-the-column-of-the-type-name.gold.fs | 4 + ...comment-lined-up-with-the-first-element.fs | 3 + ...nt-lined-up-with-the-first-element.gold.fs | 12 ++ ...her-column-stays-before-the-parenthesis.fs | 12 ++ ...olumn-stays-before-the-parenthesis.gold.fs | 12 ++ .../line-comment-after-the-last-element.fs | 12 ++ ...omment-before-closing-bracket-list.gold.fs | 2 +- src/Fantomas.Core/CodePrinter.fs | 10 +- src/Fantomas.Core/Trivia.fs | 138 +++++++++--------- src/Fantomas.Core/Trivia.fsi | 3 +- 20 files changed, 194 insertions(+), 68 deletions(-) create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/Expr/AnonStructRecord/trivia/line-comment-on-the-column-of-struct.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/Expr/AnonStructRecord/trivia/line-comment-on-the-column-of-struct.gold.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/Expr/ArrayOrList/trivia/line-comment-on-the-column-of-the-opening-array-bracket.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/Expr/ArrayOrList/trivia/line-comment-on-the-column-of-the-opening-array-bracket.gold.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/Expr/ArrayOrList/trivia/line-comment-on-the-column-of-the-opening-bracket.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/Expr/ArrayOrList/trivia/line-comment-on-the-column-of-the-opening-bracket.gold.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/Expr/NamedComputation/trivia/negative/line-comment-on-the-column-of-the-builder.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/Expr/Quote/trivia/line-comment-on-the-column-of-the-opening-quotation.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/Expr/Quote/trivia/line-comment-on-the-column-of-the-opening-quotation.gold.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/Expr/TypeApp/trivia/line-comment-on-the-column-of-the-type-name.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/Expr/TypeApp/trivia/line-comment-on-the-column-of-the-type-name.gold.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/Type/StructTuple/trivia/line-comment-lined-up-with-the-first-element.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/Type/StructTuple/trivia/line-comment-lined-up-with-the-first-element.gold.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/Type/StructTuple/trivia/line-comment-on-another-column-stays-before-the-parenthesis.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/Type/StructTuple/trivia/line-comment-on-another-column-stays-before-the-parenthesis.gold.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/Type/StructTuple/trivia/negative/line-comment-after-the-last-element.fs diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/Expr/AnonStructRecord/trivia/line-comment-on-the-column-of-struct.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/Expr/AnonStructRecord/trivia/line-comment-on-the-column-of-struct.fs new file mode 100644 index 0000000000..8d15bd0f8c --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/Expr/AnonStructRecord/trivia/line-comment-on-the-column-of-struct.fs @@ -0,0 +1,5 @@ +let x = + struct {| A = 1 + B = 2 + // c + |} diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/Expr/AnonStructRecord/trivia/line-comment-on-the-column-of-struct.gold.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/Expr/AnonStructRecord/trivia/line-comment-on-the-column-of-struct.gold.fs new file mode 100644 index 0000000000..c7b97a6fac --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/Expr/AnonStructRecord/trivia/line-comment-on-the-column-of-struct.gold.fs @@ -0,0 +1,6 @@ +let x = + struct {| + A = 1 + B = 2 + // c + |} diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/Expr/ArrayOrList/trivia/line-comment-on-the-column-of-the-opening-array-bracket.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/Expr/ArrayOrList/trivia/line-comment-on-the-column-of-the-opening-array-bracket.fs new file mode 100644 index 0000000000..ccdf9e22cd --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/Expr/ArrayOrList/trivia/line-comment-on-the-column-of-the-opening-array-bracket.fs @@ -0,0 +1,5 @@ +let x = + [| a + b + // c + |] diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/Expr/ArrayOrList/trivia/line-comment-on-the-column-of-the-opening-array-bracket.gold.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/Expr/ArrayOrList/trivia/line-comment-on-the-column-of-the-opening-array-bracket.gold.fs new file mode 100644 index 0000000000..d750e515cb --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/Expr/ArrayOrList/trivia/line-comment-on-the-column-of-the-opening-array-bracket.gold.fs @@ -0,0 +1,6 @@ +let x = + [| + a + b + // c + |] diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/Expr/ArrayOrList/trivia/line-comment-on-the-column-of-the-opening-bracket.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/Expr/ArrayOrList/trivia/line-comment-on-the-column-of-the-opening-bracket.fs new file mode 100644 index 0000000000..116da5bbb7 --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/Expr/ArrayOrList/trivia/line-comment-on-the-column-of-the-opening-bracket.fs @@ -0,0 +1,4 @@ +let x = + [ someLongValueExpressionThatIsLongNumberOne; someLongValueExpressionThatIsLongNumberTwo + // c + ] diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/Expr/ArrayOrList/trivia/line-comment-on-the-column-of-the-opening-bracket.gold.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/Expr/ArrayOrList/trivia/line-comment-on-the-column-of-the-opening-bracket.gold.fs new file mode 100644 index 0000000000..c86f25b886 --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/Expr/ArrayOrList/trivia/line-comment-on-the-column-of-the-opening-bracket.gold.fs @@ -0,0 +1,6 @@ +let x = + [ + someLongValueExpressionThatIsLongNumberOne + someLongValueExpressionThatIsLongNumberTwo + // c + ] diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/Expr/NamedComputation/trivia/negative/line-comment-on-the-column-of-the-builder.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/Expr/NamedComputation/trivia/negative/line-comment-on-the-column-of-the-builder.fs new file mode 100644 index 0000000000..9f992694b3 --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/Expr/NamedComputation/trivia/negative/line-comment-on-the-column-of-the-builder.fs @@ -0,0 +1,6 @@ +let run () = + task { + do! step1 () + do! step2 () + // do! step3 () + } diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/Expr/Quote/trivia/line-comment-on-the-column-of-the-opening-quotation.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/Expr/Quote/trivia/line-comment-on-the-column-of-the-opening-quotation.fs new file mode 100644 index 0000000000..b89e5008a6 --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/Expr/Quote/trivia/line-comment-on-the-column-of-the-opening-quotation.fs @@ -0,0 +1,5 @@ +let x = + <@ a + b + // c + @> diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/Expr/Quote/trivia/line-comment-on-the-column-of-the-opening-quotation.gold.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/Expr/Quote/trivia/line-comment-on-the-column-of-the-opening-quotation.gold.fs new file mode 100644 index 0000000000..6b57b55c54 --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/Expr/Quote/trivia/line-comment-on-the-column-of-the-opening-quotation.gold.fs @@ -0,0 +1,6 @@ +let x = + <@ + a + b + // c + @> diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/Expr/TypeApp/trivia/line-comment-on-the-column-of-the-type-name.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/Expr/TypeApp/trivia/line-comment-on-the-column-of-the-type-name.fs new file mode 100644 index 0000000000..c246771e2a --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/Expr/TypeApp/trivia/line-comment-on-the-column-of-the-type-name.fs @@ -0,0 +1,5 @@ +let x = + foo diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/Expr/TypeApp/trivia/line-comment-on-the-column-of-the-type-name.gold.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/Expr/TypeApp/trivia/line-comment-on-the-column-of-the-type-name.gold.fs new file mode 100644 index 0000000000..5cfd5d59a6 --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/Expr/TypeApp/trivia/line-comment-on-the-column-of-the-type-name.gold.fs @@ -0,0 +1,4 @@ +let x = + foo diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/Type/StructTuple/trivia/line-comment-lined-up-with-the-first-element.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/StructTuple/trivia/line-comment-lined-up-with-the-first-element.fs new file mode 100644 index 0000000000..9c24d06bcd --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/StructTuple/trivia/line-comment-lined-up-with-the-first-element.fs @@ -0,0 +1,3 @@ +let input1 x : struct (LongTypeNameNumberOne * LongTypeNameNumberTwo * LongTypeNameNumberThree * LongTypeNameNumberFour * LongTypeNameNumberFive + // c + ) = failwith "" diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/Type/StructTuple/trivia/line-comment-lined-up-with-the-first-element.gold.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/StructTuple/trivia/line-comment-lined-up-with-the-first-element.gold.fs new file mode 100644 index 0000000000..8b09830493 --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/StructTuple/trivia/line-comment-lined-up-with-the-first-element.gold.fs @@ -0,0 +1,12 @@ +let input1 + x + : struct ( + LongTypeNameNumberOne * + LongTypeNameNumberTwo * + LongTypeNameNumberThree * + LongTypeNameNumberFour * + LongTypeNameNumberFive + // c + ) + = + failwith "" diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/Type/StructTuple/trivia/line-comment-on-another-column-stays-before-the-parenthesis.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/StructTuple/trivia/line-comment-on-another-column-stays-before-the-parenthesis.fs new file mode 100644 index 0000000000..b73920638a --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/StructTuple/trivia/line-comment-on-another-column-stays-before-the-parenthesis.fs @@ -0,0 +1,12 @@ +let f + x + : struct ( + LongTypeNameNumberOne * + LongTypeNameNumberTwo * + LongTypeNameNumberThree * + LongTypeNameNumberFour * + LongTypeNameNumberFive + // c + ) + = + failwith "" diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/Type/StructTuple/trivia/line-comment-on-another-column-stays-before-the-parenthesis.gold.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/StructTuple/trivia/line-comment-on-another-column-stays-before-the-parenthesis.gold.fs new file mode 100644 index 0000000000..c4b30cd195 --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/StructTuple/trivia/line-comment-on-another-column-stays-before-the-parenthesis.gold.fs @@ -0,0 +1,12 @@ +let f + x + : struct ( + LongTypeNameNumberOne * + LongTypeNameNumberTwo * + LongTypeNameNumberThree * + LongTypeNameNumberFour * + LongTypeNameNumberFive + // c + ) + = + failwith "" diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/Type/StructTuple/trivia/negative/line-comment-after-the-last-element.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/StructTuple/trivia/negative/line-comment-after-the-last-element.fs new file mode 100644 index 0000000000..664472bb5d --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/StructTuple/trivia/negative/line-comment-after-the-last-element.fs @@ -0,0 +1,12 @@ +let f + x + : struct ( + LongTypeNameNumberOne * + LongTypeNameNumberTwo * + LongTypeNameNumberThree * + LongTypeNameNumberFour * + LongTypeNameNumberFive + // c + ) + = + failwith "" diff --git a/src/Fantomas.Core.SnapshotTests/cases/scenarios/AlignedMultilineBracketStyleArrayOrListTests/line-comment-before-closing-bracket-list.gold.fs b/src/Fantomas.Core.SnapshotTests/cases/scenarios/AlignedMultilineBracketStyleArrayOrListTests/line-comment-before-closing-bracket-list.gold.fs index 977c983857..f422deb5bc 100644 --- a/src/Fantomas.Core.SnapshotTests/cases/scenarios/AlignedMultilineBracketStyleArrayOrListTests/line-comment-before-closing-bracket-list.gold.fs +++ b/src/Fantomas.Core.SnapshotTests/cases/scenarios/AlignedMultilineBracketStyleArrayOrListTests/line-comment-before-closing-bracket-list.gold.fs @@ -3,5 +3,5 @@ let a = (1, 2, 3) (4, 5, 6) (7, 8, 9) - // some line comment + // some line comment ] diff --git a/src/Fantomas.Core/CodePrinter.fs b/src/Fantomas.Core/CodePrinter.fs index fca91c357f..9633717294 100644 --- a/src/Fantomas.Core/CodePrinter.fs +++ b/src/Fantomas.Core/CodePrinter.fs @@ -4345,9 +4345,17 @@ let genType (t: Type) = +> genSingleTextNode node.ClosingParen let long: Context -> Context = + // struct ( + // int * + // string + // // trivia after the last element: its newline is the one before the `)` + // ) genOpening - +> indentSepNlnUnindent (genSynTupleTypeSegments node.Path) + +> indent +> sepNln + +> genSynTupleTypeSegments node.Path + +> unindentWithTriviaAwareness + +> sepNlnUnlessLastEventIsNewline +> genSingleTextNode node.ClosingParen expressionFitsOnRestOfLine short long |> genNode node diff --git a/src/Fantomas.Core/Trivia.fs b/src/Fantomas.Core/Trivia.fs index 558a2a82a3..ceebe1c255 100644 --- a/src/Fantomas.Core/Trivia.fs +++ b/src/Fantomas.Core/Trivia.fs @@ -6,7 +6,8 @@ open Fantomas.FCS.SyntaxTrivia open Fantomas.FCS.Text open Fantomas.Core.SyntaxOak -let closingDelimiters = Set.ofList [ "]"; "}"; "|}"; ")"; "|)" ] +let openingDelimiters: Set = Set.ofList [ "["; "[|"; "{"; "{|"; "(" ] +let closingDelimiters: Set = Set.ofList [ "]"; "}"; "|}"; ")"; "|)" ] type CommentTrivia with @@ -293,67 +294,73 @@ let lineCommentAfterSourceCodeToTriviaInstruction (containerNode: Node) (trivia: node.AddAfter(trivia) ) -/// Find a node that ended before the trivia and whose start column matches the trivia's column. -/// Searches top-down and returns the outermost match that is the first code on its line, -/// as its column is the indentation the comment lines up with. -/// Without such a node, the deepest node at the comment's column is returned. +/// Find a node to add a line comment to as trivia after. /// -/// Used for indented single-line comments that sit between a parent's children. -/// For example, in: -/// try ... with exn -> () -/// // comment here -/// The comment at column 4 should attach to the try-with (which also starts at column 4), -/// not to the next top-level binding at column 0. -/// -/// When a node and its last child both start at the comment's column, the node wins: +/// The candidates are the nodes the comment directly follows: the child of the container that ends +/// last above the comment, then that child's child that ends last above it, and so on down. In /// c + /// d /// // comment -/// The comment belongs to the infix expression `c + d`, not to `d`. -/// Placing it after `d` would make the expression multiline and move the operator, -/// which then no longer produces the same attachment on the next format. -/// -/// A node that follows other code on its line is only picked when nothing else matches: -/// |> run (fun changes -> -/// printfn "%A" changes -/// // comment -/// The lambda starts at the comment's column, but after `|> run (`. The comment belongs to its body. -let findNodeBeforeWithMatchingColumn (node: Node) (triviaRange: range) : Node option = - let triviaColumn = triviaRange.StartColumn - let triviaLine = triviaRange.StartLine - - // `endLineOfPrevious` is the line where the node before `node` ends. - // A child starts its line when the node before it ends on an earlier line. - // Both are found by range rather than by index, so the order of `Children` does not matter. - let rec visit (endLineOfPrevious: int) (node: Node) : Node option = - let before: Node array = - node.Children |> Array.filter (fun child -> child.Range.EndLine < triviaLine) - - if Array.isEmpty before then - None - else - - let child: Node = - before |> Array.maxBy (fun child -> child.Range.EndLine, child.Range.EndColumn) - - let endLineBeforeChild: int = - node.Children - |> Array.filter (fun sibling -> - not (obj.ReferenceEquals(sibling, child)) - && Position.posGeq child.Range.Start sibling.Range.End - ) - |> Array.fold (fun endLine sibling -> max endLine sibling.Range.EndLine) endLineOfPrevious - - let matchesColumn: bool = child.Range.StartColumn = triviaColumn - - if matchesColumn && endLineBeforeChild < child.Range.StartLine then - Some child - else - visit endLineBeforeChild child - |> Option.orElse (if matchesColumn then Some child else None) +/// they are `c + d` and then `d`. The comment's column picks one of them. +let findNodeBeforeWithMatchingColumn (sourceText: ISourceText) (container: Node) (triviaRange: range) : Node option = + let triviaColumn: int = triviaRange.StartColumn + let triviaLine: int = triviaRange.StartLine + + let endsAboveComment (node: Node) : bool = node.Range.EndLine < triviaLine + let startsOnCommentColumn (node: Node) : bool = node.Range.StartColumn = triviaColumn + + // Only whitespace comes before the node on its line. + let startsItsLine (node: Node) : bool = + let line: string = sourceText.GetLineString(node.Range.StartLine - 1) + MemoryExtensions.IsWhiteSpace(line.AsSpan(0, min node.Range.StartColumn line.Length)) + + // Outermost first. `Children` are in source order, so searching them from the end finds the + // child that ends last above the comment. + let candidates: Node list = + container + |> List.unfold (fun (parent: Node) -> + Array.tryFindBack endsAboveComment parent.Children + |> Option.map (fun (child: Node) -> child, child) + ) - // What precedes the container is unknown, so its first child is taken to start its line. - visit 0 node + let candidatesOnColumn: Node list = List.filter startsOnCommentColumn candidates + + // A comment on the column of what opens the container lines up with the container, not its + // content: its first child (`[`, `<@`, `begin`, `task`, `foo` of `foo<...>`), and an opening + // bracket after it (`{|` of `struct {|`). + let isContentOnCommentColumn (child: Node) : bool = + match child with + | :? SingleTextNode as stn when Set.contains stn.Text openingDelimiters -> false + | _ -> startsOnCommentColumn child + + // From the second child on, while they end above the comment. + let linesUpWithEarlierContent: bool = + let children: Node array = container.Children + + let rec linesUpFrom (index: int) : bool = + index < children.Length + && endsAboveComment children.[index] + && (isContentOnCommentColumn children.[index] || linesUpFrom (index + 1)) + + linesUpFrom 1 + + match List.tryFind startsItsLine candidatesOnColumn, List.tryLast candidatesOnColumn with + | Some outermost, _ -> + // c + + // d + // // comment after `c + d`, not `d`: after `d` the infix turns multiline and + // the comment lands elsewhere on the next format + Some outermost + | None, Some innermost -> + // let a = b + // // comment after `b`, on the column after other code on its line + Some innermost + | None, None when linesUpWithEarlierContent -> + // struct (int * string * bool + // // comment after `bool`, the first candidate: no candidate is on the column, + // ) but `int`, an earlier child of the container, is + List.tryHead candidates + | None, None -> None /// Assigns a trivia node (comment, blank line, directive) to the appropriate child /// of containerNode as either ContentBefore or ContentAfter. @@ -370,7 +377,7 @@ let findNodeBeforeWithMatchingColumn (node: Node) (triviaRange: range) : Node op /// - the successor is at a different column, OR /// - the successor is a leaf node (no children, e.g. closing brackets like `|}`, `]`, `)`) /// Leaf nodes are syntactic delimiters, not content — the comment belongs to the preceding content. -let assignTriviaToTriviaInstruction (containerNode: Node) (trivia: TriviaNode) : unit = +let assignTriviaToTriviaInstruction (sourceText: ISourceText) (containerNode: Node) (trivia: TriviaNode) : unit = let nodeAfter = containerNode.Children |> Array.tryFind (fun node -> node.Range.StartLine > trivia.Range.StartLine) @@ -379,7 +386,7 @@ let assignTriviaToTriviaInstruction (containerNode: Node) (trivia: TriviaNode) : match trivia.Content with | CommentOnSingleLine _ | CommentOnSingleLineWithLeadingNewlines _ when trivia.Range.StartColumn > 0 -> - findNodeBeforeWithMatchingColumn containerNode trivia.Range + findNodeBeforeWithMatchingColumn sourceText containerNode trivia.Range | _ -> None match nodeBefore, nodeAfter with @@ -520,7 +527,7 @@ let promoteNewlinesBeforeComments (trivia: TriviaNode array) : TriviaNode array flushPendingNewlines () result.ToArray() -let addToTree (tree: Oak) (trivia: TriviaNode array) : unit = +let addToTree (sourceText: ISourceText) (tree: Oak) (trivia: TriviaNode array) : unit = for trivia in trivia do let smallestNodeThatContainsTrivia = findNodeWhereRangeFitsIn tree trivia.Range @@ -533,7 +540,7 @@ let addToTree (tree: Oak) (trivia: TriviaNode array) : unit = | CommentOnSingleLine _ | CommentOnSingleLineWithLeadingNewlines _ | Newline - | Directive _ -> assignTriviaToTriviaInstruction parentNode trivia + | Directive _ -> assignTriviaToTriviaInstruction sourceText parentNode trivia | BlockComment _ | Cursor -> blockCommentToTriviaInstruction parentNode trivia @@ -589,15 +596,16 @@ let enrichTree (config: FormatConfig) (sourceText: ISourceText) (ast: ParsedInpu [| yield! comments; yield! newlines; yield! directives |] |> Array.sortBy (fun n -> n.Range.Start.Line, n.Range.Start.Column) - addToTree tree (promoteNewlinesBeforeComments trivia) + addToTree sourceText tree (promoteNewlinesBeforeComments trivia) tree let insertCursor (tree: Oak) (cursor: pos) = let cursorRange = Range.mkRange (tree :> Node).Range.FileName cursor cursor - let nodeWithCursor = findNodeWhereRangeFitsIn tree cursorRange + let cursorTrivia: TriviaNode = TriviaNode(TriviaContent.Cursor, cursorRange) - match nodeWithCursor with + match findNodeWhereRangeFitsIn tree cursorRange with | Some(:? SingleTextNode as node) -> node.AddCursor cursor - | _ -> addToTree tree [| TriviaNode(TriviaContent.Cursor, cursorRange) |] + | Some parentNode -> blockCommentToTriviaInstruction parentNode cursorTrivia + | None -> triviaBeforeOrAfterEntireTree tree cursorTrivia tree diff --git a/src/Fantomas.Core/Trivia.fsi b/src/Fantomas.Core/Trivia.fsi index 9389fdf6f0..446686ae28 100644 --- a/src/Fantomas.Core/Trivia.fsi +++ b/src/Fantomas.Core/Trivia.fsi @@ -22,7 +22,8 @@ val collectCommentTextsFromAST: sourceText: ISourceText -> ast: ParsedInput -> S /// Which side wins depends on the kind of trivia. A comment after code on the same line goes after /// the last node on that line. A comment on its own line goes before the next sibling, unless that /// sibling is a closing bracket, or the comment is indented to the column of the previous sibling -/// while the next one is not. Blank lines before an indented comment travel with the comment. +/// while the next one is not, or to the column of earlier content in the same node. Blank lines +/// before an indented comment travel with the comment. /// Trivia outside every node is attached to the root. /// /// The choices are illustrated in src/Fantomas.Core.Tests/TriviaAssignmentTests.fs. From 53e396a4efcc48aa72efbceed5012fa1665b8c32 Mon Sep 17 00:00:00 2001 From: Florian Verdonck Date: Wed, 21 Oct 2026 17:31:14 +0200 Subject: [PATCH 11/16] Indent a when guard that has a comment before it Since 8.0.8 the `when` of a match clause is a node of its own, so a comment on its own line between the pattern and `when` attaches before that keyword. Writing that comment ends the line, and `when` then started the next one on the column of the `|`, where it ends the clause: the result did not parse. With a comment before `when`, the comment, the guard and the rest of the clause now go one level in. The comment is written before the guard is measured, so its lines do not make the guard count as multiline and the arrow stays on the guard's line when the guard fits. Closes #3560 --- CHANGELOG.md | 1 + ...60-comment-between-the-pattern-and-when.fs | 5 + ...mment-between-the-pattern-and-when.gold.fs | 5 + .../long-guard-after-a-comment-before-when.fs | 5 + ...-guard-after-a-comment-before-when.gold.fs | 10 ++ ...t-indented-between-the-pattern-and-when.fs | 6 + ...when-keeps-the-branch-on-the-bar-column.fs | 12 ++ ...keeps-the-branch-on-the-bar-column.gold.fs | 8 ++ src/Fantomas.Core/CodePrinter.fs | 111 +++++++++++------- 9 files changed, 119 insertions(+), 44 deletions(-) create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/MatchClause/trivia/3560-comment-between-the-pattern-and-when.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/MatchClause/trivia/3560-comment-between-the-pattern-and-when.gold.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/MatchClause/trivia/long-guard-after-a-comment-before-when.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/MatchClause/trivia/long-guard-after-a-comment-before-when.gold.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/MatchClause/trivia/negative/comment-indented-between-the-pattern-and-when.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/settings/fsharp_experimental_keep_indent_in_branch/true/MatchClause/trivia/comment-before-when-keeps-the-branch-on-the-bar-column.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/settings/fsharp_experimental_keep_indent_in_branch/true/MatchClause/trivia/comment-before-when-keeps-the-branch-on-the-bar-column.gold.fs diff --git a/CHANGELOG.md b/CHANGELOG.md index aaad00eeb0..e8f568dfcc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ - Parenthesized function type after an arrow gives invalid code with indent_size 2. [#3557](https://github.com/fsprojects/fantomas/issues/3557) - Long type test with :? gives invalid code. [#3558](https://github.com/fsprojects/fantomas/issues/3558) - Line comment after the opening parenthesis of a type moves and breaks the type. [#3559](https://github.com/fsprojects/fantomas/issues/3559) +- Comment between a match pattern and its when guard gives invalid code. [#3560](https://github.com/fsprojects/fantomas/issues/3560) ## [8.0.10] - 2026-10-14 diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/MatchClause/trivia/3560-comment-between-the-pattern-and-when.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/MatchClause/trivia/3560-comment-between-the-pattern-and-when.fs new file mode 100644 index 0000000000..95529822f3 --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/MatchClause/trivia/3560-comment-between-the-pattern-and-when.fs @@ -0,0 +1,5 @@ +match x with +| a +// c + when a -> 1 +| _ -> 0 diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/MatchClause/trivia/3560-comment-between-the-pattern-and-when.gold.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/MatchClause/trivia/3560-comment-between-the-pattern-and-when.gold.fs new file mode 100644 index 0000000000..56e0f9738f --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/MatchClause/trivia/3560-comment-between-the-pattern-and-when.gold.fs @@ -0,0 +1,5 @@ +match x with +| a + // c + when a -> 1 +| _ -> 0 diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/MatchClause/trivia/long-guard-after-a-comment-before-when.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/MatchClause/trivia/long-guard-after-a-comment-before-when.fs new file mode 100644 index 0000000000..1210a02996 --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/MatchClause/trivia/long-guard-after-a-comment-before-when.fs @@ -0,0 +1,5 @@ +match x with +| a +// c + when someVeryLongConditionNameNumberOne && someVeryLongConditionNameNumberTwo && someVeryLongConditionNameNumberThree -> 1 +| _ -> 0 diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/MatchClause/trivia/long-guard-after-a-comment-before-when.gold.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/MatchClause/trivia/long-guard-after-a-comment-before-when.gold.fs new file mode 100644 index 0000000000..e86b4c8b7f --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/MatchClause/trivia/long-guard-after-a-comment-before-when.gold.fs @@ -0,0 +1,10 @@ +match x with +| a + // c + when + someVeryLongConditionNameNumberOne + && someVeryLongConditionNameNumberTwo + && someVeryLongConditionNameNumberThree + -> + 1 +| _ -> 0 diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/MatchClause/trivia/negative/comment-indented-between-the-pattern-and-when.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/MatchClause/trivia/negative/comment-indented-between-the-pattern-and-when.fs new file mode 100644 index 0000000000..40223a5f6a --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/MatchClause/trivia/negative/comment-indented-between-the-pattern-and-when.fs @@ -0,0 +1,6 @@ +let f x = + match x with + | a + // c + when a > 0 -> 1 + | _ -> 0 diff --git a/src/Fantomas.Core.SnapshotTests/cases/settings/fsharp_experimental_keep_indent_in_branch/true/MatchClause/trivia/comment-before-when-keeps-the-branch-on-the-bar-column.fs b/src/Fantomas.Core.SnapshotTests/cases/settings/fsharp_experimental_keep_indent_in_branch/true/MatchClause/trivia/comment-before-when-keeps-the-branch-on-the-bar-column.fs new file mode 100644 index 0000000000..647405ec1a --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/settings/fsharp_experimental_keep_indent_in_branch/true/MatchClause/trivia/comment-before-when-keeps-the-branch-on-the-bar-column.fs @@ -0,0 +1,12 @@ +(*--- +fsharp_experimental_keep_indent_in_branch = true +---*) +let f rest = + match Stream.peel rest with + | None -> failwith "oh no" + | Some longName + // c + when longName.IsEmpty |> not -> + + longName + |> Map.map (fun _ -> TypedTerm.force) diff --git a/src/Fantomas.Core.SnapshotTests/cases/settings/fsharp_experimental_keep_indent_in_branch/true/MatchClause/trivia/comment-before-when-keeps-the-branch-on-the-bar-column.gold.fs b/src/Fantomas.Core.SnapshotTests/cases/settings/fsharp_experimental_keep_indent_in_branch/true/MatchClause/trivia/comment-before-when-keeps-the-branch-on-the-bar-column.gold.fs new file mode 100644 index 0000000000..202e2ff45a --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/settings/fsharp_experimental_keep_indent_in_branch/true/MatchClause/trivia/comment-before-when-keeps-the-branch-on-the-bar-column.gold.fs @@ -0,0 +1,8 @@ +let f rest = + match Stream.peel rest with + | None -> failwith "oh no" + | Some longName + // c + when longName.IsEmpty |> not -> + + longName |> Map.map (fun _ -> TypedTerm.force) diff --git a/src/Fantomas.Core/CodePrinter.fs b/src/Fantomas.Core/CodePrinter.fs index 9633717294..d0f35b37e5 100644 --- a/src/Fantomas.Core/CodePrinter.fs +++ b/src/Fantomas.Core/CodePrinter.fs @@ -2957,61 +2957,84 @@ let genClause (isLastItem: bool) (node: MatchClauseNode) = | Some barNode -> genSingleTextNodeWithSpaceSuffix sepSpace barNode | None -> sepBar - let genWhenAndBody = - sepSpace - +> leadingExpressionIsMultiline - (optSingle - (fun (whenNode, e) -> - genSingleTextNode whenNode - +> sepSpaceOrIndentAndNlnIfExpressionExceedsPageWidth (genExpr e) - +> sepSpace - ) - node.WhenExpr) - (fun isMultiline ctx -> - if isMultiline then - indentSepNlnUnindent (genSingleTextNode node.Arrow +> sepNln +> genExpr node.BodyExpr) ctx - else - - let genKeepIndentInBranch = - let long = - let startNode = - match node.Bar with - | None -> Pattern.Node node.Pattern - | Some bar -> bar - - genKeepIdentMatchClause startNode node.BodyExpr + // A multiline guard puts `->` and the body on lines of their own. + let genArrowAndBody (isMultilineGuard: bool) (ctx: Context) : Context = + if isMultilineGuard then + indentSepNlnUnindent (genSingleTextNode node.Arrow +> sepNln +> genExpr node.BodyExpr) ctx + else - expressionFitsOnRestOfLine (sepSpace +> genExpr node.BodyExpr) long + let genKeepIndentInBranch: Context -> Context = + let long: Context -> Context = + let startNode: Node = + match node.Bar with + | None -> Pattern.Node node.Pattern + | Some bar -> bar + + let genKeptBranch: Context -> Context = + genKeepIdentMatchClause startNode node.BodyExpr + + match node.WhenExpr with + | Some(whenNode, _) when + whenNode.HasContentBefore + && startNode.Range.StartColumn = (Expr.Node node.BodyExpr).Range.StartColumn + -> + // | Some x + // // trivia + // when x.IsEmpty -> + // + // body on the column of `|`, out of the level genAfterPattern added + unindent +> genKeptBranch +> indent + | _ -> genKeptBranch + + expressionFitsOnRestOfLine (sepSpace +> genExpr node.BodyExpr) long + + let sepArrow: Context -> Context = + if not node.Arrow.HasContentBefore then + genSingleTextNodeWithSpaceSuffix sepSpace node.Arrow + else + // In the weird case where the arrow has content before it and there is no multiline whenExpr, + // we need to ensure a space was written before the arrow to avoid offset errors. + // See https://github.com/fsprojects/fantomas/issues/2888 + !- $" %s{node.Arrow.Text} " |> genNode node.Arrow + + (sepArrow + +> ifElse + (ctx.Config.ExperimentalKeepIndentInBranch + && isLastItem + && not (isStroustrupStyleExpr ctx.Config node.BodyExpr)) + genKeepIndentInBranch + (autoIndentAndNlnIfExpressionExceedsPageWidthUnlessStroustrup genExpr node.BodyExpr)) + ctx - let sepArrow = - if not node.Arrow.HasContentBefore then - genSingleTextNodeWithSpaceSuffix sepSpace node.Arrow - else - // In the weird case where the arrow has content before it and there is no multiline whenExpr, - // we need to ensure a space was written before the arrow to avoid offset errors. - // See https://github.com/fsprojects/fantomas/issues/2888 - !- $" %s{node.Arrow.Text} " |> genNode node.Arrow - - (sepArrow - +> ifElse - (ctx.Config.ExperimentalKeepIndentInBranch - && isLastItem - && not (isStroustrupStyleExpr ctx.Config node.BodyExpr)) - genKeepIndentInBranch - (autoIndentAndNlnIfExpressionExceedsPageWidthUnlessStroustrup genExpr node.BodyExpr)) - ctx - ) + // The trivia before `when` is written by genAfterPattern, before this measures the guard. + let genGuardArrowAndBody (whenNode: SingleTextNode) (guard: Expr) : Context -> Context = + leadingExpressionIsMultiline + (genSingleTextNodeText whenNode + +> leaveNode whenNode + +> sepSpaceOrIndentAndNlnIfExpressionExceedsPageWidth (genExpr guard) + +> sepSpace) + genArrowAndBody + + let genAfterPattern: Context -> Context = + match node.WhenExpr with + | None -> sepSpace +> genArrowAndBody false + | Some(whenNode, guard) when whenNode.HasContentBefore -> + // | a + // // trivia + // when a -> 1 one level in: on the column of `|`, `when` ends the clause + indent +> enterNode whenNode +> genGuardArrowAndBody whenNode guard +> unindent + | Some(whenNode, guard) -> sepSpace +> enterNode whenNode +> genGuardArrowAndBody whenNode guard let genPatAndBody ctx = if not (isStroustrupStyleExpr ctx.Config node.BodyExpr) then - (genPatInClause node.Pattern +> genWhenAndBody) ctx + (genPatInClause node.Pattern +> genAfterPattern) ctx else // The column is taken after the bar, so a stroustrup closing bracket lands strictly right of // it. On the bar's own column the `|` of the next clause no longer parses, and giving only // the last clause the bar's column would leave two columns in one match. See #2990. let startColumn = ctx.Column - (genPatInClause node.Pattern +> atIndentLevel false startColumn genWhenAndBody) ctx + (genPatInClause node.Pattern +> atIndentLevel false startColumn genAfterPattern) ctx genBar +> genPatAndBody |> genNode node From 10d2dde0fdf6968d2804f85091eee649ded2cf00 Mon Sep 17 00:00:00 2001 From: Florian Verdonck Date: Wed, 21 Oct 2026 17:44:49 +0200 Subject: [PATCH 12/16] Add the 8.1.0 changelog Release the fixes of this branch as 8.1.0, a minor release because two of its changes alter how valid code is formatted. Neither has an issue behind it, so their entries link the pull request: a multiline tuple type after `:?`, `:>`, `:?>` or `:` goes one level in, and a line comment lined up with the first element of its container stays with the elements instead of moving before the closing bracket. --- CHANGELOG.md | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e8f568dfcc..0d1550b37e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,11 @@ # Changelog -## [Unreleased] +## [8.1.0] - 2026-10-21 + +### Changed + +- Multiline tuple type after a cast or type annotation operator goes one level in. [#3561](https://github.com/fsprojects/fantomas/pull/3561) +- Line comment lined up with the first element of its container stays with the elements. [#3561](https://github.com/fsprojects/fantomas/pull/3561) ### Fixed From 5fd51cf04dcb06cb2dc60ae3df5de24412dcd3c7 Mon Sep 17 00:00:00 2001 From: Florian Verdonck Date: Wed, 21 Oct 2026 17:59:09 +0200 Subject: [PATCH 13/16] Describe the 8.1 layout changes and the rule of multitudes 8.1 fixes layouts that did not compile or were not idempotent, and fixing them at the cause also moves a few layouts of code that was already valid. The upgrade guide gets a v8.1 section, so someone who sees their code change after upgrading finds out why without reading the pull request: a function type in parentheses goes one level in rather than two, a return type lands on a multiple of the indent size, a long struct tuple type is written like a long list, a tuple type after a cast or annotation operator goes one level in, and a comment lined up with the elements of a list stays with them. Each comes with the output of 8.0 and of 8.1 for the same input. Several of those choices follow one preference that was written down nowhere: when more than one layout parses, every line starts on a multiple of indent_size. The new end-user page, The rule of multitudes, gives the reasons (both style guides, and alignment that does not depend on name length), how it works where the parser needs a line past a column, and the layouts where it does not hold yet. Design decisions lists it, the upgrade guide links to it, and AGENTS.md points agents to Design decisions when they choose or recommend a layout. ReportingBugs moves one place down to make room. --- AGENTS.md | 6 + docs/docs/end-users/DesignDecisions.md | 6 + docs/docs/end-users/ReportingBugs.md | 2 +- docs/docs/end-users/RuleOfMultitudes.md | 101 +++++++++++++++ docs/docs/end-users/UpgradeGuide.md | 158 ++++++++++++++++++++++++ 5 files changed, 272 insertions(+), 1 deletion(-) create mode 100644 docs/docs/end-users/RuleOfMultitudes.md diff --git a/AGENTS.md b/AGENTS.md index f2ac39002c..940d1ac4ee 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -45,6 +45,12 @@ compatibility overload, and without calling it out as a breaking change. Leave O between tags instead. Code generation on top of the Oak is told to expect this (`docs/docs/end-users/GeneratingCode.fsx`, "Updates"). +## Choosing a layout + +When more than one layout parses, the design decisions in +[docs/docs/end-users/DesignDecisions.md](docs/docs/end-users/DesignDecisions.md) choose. Name the +one you apply when you recommend an option. + ## Talking about a formatting change ### Trivia versus comments in our code diff --git a/docs/docs/end-users/DesignDecisions.md b/docs/docs/end-users/DesignDecisions.md index b5d9228345..a7c344ddb1 100644 --- a/docs/docs/end-users/DesignDecisions.md +++ b/docs/docs/end-users/DesignDecisions.md @@ -35,4 +35,10 @@ Fantomas formats code under every combination of `#if` / `#else` / `#endif` defi results, which means every combination has to produce valid F# on its own. See [Conditional Compilation Directives](./ConditionalCompilationDirectives.html). +## The rule of multitudes + +When more than one layout parses, Fantomas prefers the one where every line starts on a multiple of +`indent_size`, rather than on a column taken from a token, which moves when a name changes length. +See [The rule of multitudes](./RuleOfMultitudes.html). + diff --git a/docs/docs/end-users/ReportingBugs.md b/docs/docs/end-users/ReportingBugs.md index 5ae3ad71df..9df5b3e297 100644 --- a/docs/docs/end-users/ReportingBugs.md +++ b/docs/docs/end-users/ReportingBugs.md @@ -1,7 +1,7 @@ --- category: End-users categoryindex: 1 -index: 18 +index: 19 --- # Reporting a bug diff --git a/docs/docs/end-users/RuleOfMultitudes.md b/docs/docs/end-users/RuleOfMultitudes.md new file mode 100644 index 0000000000..8a28a0b5e0 --- /dev/null +++ b/docs/docs/end-users/RuleOfMultitudes.md @@ -0,0 +1,101 @@ +--- +category: End-users +categoryindex: 1 +index: 18 +--- +# The rule of multitudes + +Often more than one layout of the same code parses. When Fantomas has to choose, it prefers the one +where every line it starts sits on a multiple of `indent_size`: a continuation goes in by whole +levels, never to a column in between. Only where a line starts counts; where a token lands further +along a line does not. + +Why: + +- **The style guides ask for it.** Both the + [Microsoft](https://learn.microsoft.com/en-us/dotnet/fsharp/style-guide/formatting#use-consistent-indentation) + and the [G-Research](https://github.com/G-Research/fsharp-formatting-conventions#general-rules-for-indentation) + guide count indentation in spaces "per indentation", and put "consistency of indentation" first. +- **A level reads as structure.** With an indent size of 4, a line at column 10 sits between two + levels and reads as a mistake. +- **It does not depend on names.** A column taken from a token moves when the name in front of it + gets longer or shorter, and every line aligned to it moves along. The Microsoft guide says the + same in + [Avoid formatting that is sensitive to name length](https://learn.microsoft.com/en-us/dotnet/fsharp/style-guide/formatting#avoid-formatting-that-is-sensitive-to-name-length). + +8.1 moved the lines of a return type off the column after `: ` for this reason: + +```fsharp +// v8.0: the `->` lines at column 14, between two levels +let f + x + : (LongTypeNameNumberOne + -> LongTypeNameNumberTwo + -> LongTypeNameNumberThree + -> LongTypeNameNumberFour + -> LongTypeNameNumberFive) + = + failwith "" + +// v8.1: one level past the binding, column 8 +let f + x + : (LongTypeNameNumberOne + -> LongTypeNameNumberTwo + -> LongTypeNameNumberThree + -> LongTypeNameNumberFour + -> LongTypeNameNumberFive) + = + failwith "" +``` + +## When the parser needs a line past a column + +The offside rule sometimes forbids a column. A parenthesis, for one, opens a context at the first +token inside it, and a line that starts on that column ends it. Fantomas does not then align to +the column after it: it steps in whole levels until the line is past it. `indentPast` in +`Context.fs` does that measuring and stepping. + +```fsharp +type T = + a + -> (LongTypeNameNumberOne + -> LongTypeNameNumberTwo // 12, a multiple too, would end the parenthesis; 16 is the next + -> LongTypeNameNumberThree + -> LongTypeNameNumberFour + -> LongTypeNameNumberFive) +``` + +## Applying it + +When two layouts parse, write down the column each line starts on, and prefer the layout where +every one of them is a multiple of `indent_size`. Try `indent_size = 2` and `3` as well: a layout +that lands on the grid only with 4 does not follow the rule, it follows the number 4. This is how a +new layout for Fantomas is judged, so it is the check to make when you propose one. + +## Where it does not hold + +A few layouts align to a token on purpose or for now. A new layout should not add to them without a +reason written down. + +- `fsharp_multiline_bracket_style = cramped` puts the elements of a list under the first one, two + columns past the `[`: + + ```fsharp + let values = + [ someLongValueExpressionThatIsLongNumberOne + someLongValueExpressionThatIsLongNumberTwo + someLongValueExpressionThatIsLongNumberThree ] + ``` + +- The closing `>` of a multiline type application lands one column past the indent: + + ```fsharp + type T = + Dictionary< + LongTypeNameNumberOne, + LongTypeNameNumberTwo * LongTypeNameNumberThree * LongTypeNameNumberFour * LongTypeNameNumberFive + > + ``` + + diff --git a/docs/docs/end-users/UpgradeGuide.md b/docs/docs/end-users/UpgradeGuide.md index f08008122a..61f0485be4 100644 --- a/docs/docs/end-users/UpgradeGuide.md +++ b/docs/docs/end-users/UpgradeGuide.md @@ -600,4 +600,162 @@ has to be rebuilt against `v8`. - `CodeFormatter.FormatASTAsync(ast, config, source)` was added, next to the existing `FormatASTAsync(ast, source)`. - `CodeFormatter.GetWriterEventsAsync` was added for debugging. It returns the writer events produced while formatting. +## v8.1 + +### Formatting + +8.1 fixes a handful of layouts where the formatted code did not compile, or changed again on the +next format; the [changelog](https://github.com/fsprojects/fantomas/blob/main/CHANGELOG.md) lists +them. Fixing them at the cause, rather than with a special case each, also moves a few layouts of +code that was already valid. Two ideas are behind every change below: + +- Indent only as far as the parser needs, and on a multiple of `indent_size`: the + [rule of multitudes](./RuleOfMultitudes.html). 8.0 added extra indentation in places to keep the + compiler happy, and some of it landed on columns like 10 or 14 with an indent size of 4. +- Keep a comment with the code it lines up with. + +The examples use the default settings. + +#### A function type in parentheses goes one level in, not two + +Since 8.0, every multiline function type in parentheses got an extra level, to avoid a compiler +error after an outer `->` ([#3043](https://github.com/fsprojects/fantomas/issues/3043)). There it +stays; everywhere else this is the 7.0.6 layout again. + +```fsharp +// v8.0 +type T = + (LongTypeNameNumberOne + -> LongTypeNameNumberTwo + -> LongTypeNameNumberThree + -> LongTypeNameNumberFour + -> LongTypeNameNumberFive) list + +// v8.1 +type T = + (LongTypeNameNumberOne + -> LongTypeNameNumberTwo + -> LongTypeNameNumberThree + -> LongTypeNameNumberFour + -> LongTypeNameNumberFive) list +``` + +#### A return type lands on a multiple of the indent size + +The lines of a return type no longer hang off the column after `: `. They go one level past the +binding. + +```fsharp +// v8.0 +let f + x + : (LongTypeNameNumberOne + -> LongTypeNameNumberTwo + -> LongTypeNameNumberThree + -> LongTypeNameNumberFour + -> LongTypeNameNumberFive) + = + failwith "" + +// v8.1 +let f + x + : (LongTypeNameNumberOne + -> LongTypeNameNumberTwo + -> LongTypeNameNumberThree + -> LongTypeNameNumberFour + -> LongTypeNameNumberFive) + = + failwith "" +``` + +#### A long struct tuple type is written like a long list + +The elements go on lines of their own, one level in, and the `)` back on the indent of the line it +started on. The elements after the first used to start left of `struct (`, at a column the parser +only accepts in some places: in the middle of a function type, the same shape did not compile. + +```fsharp +// v8.0 +let f + x + : struct (LongTypeNameNumberOne * + LongTypeNameNumberTwo * + LongTypeNameNumberThree * + LongTypeNameNumberFour * + LongTypeNameNumberFive) + = + failwith "" + +// v8.1 +let f + x + : struct ( + LongTypeNameNumberOne * + LongTypeNameNumberTwo * + LongTypeNameNumberThree * + LongTypeNameNumberFour * + LongTypeNameNumberFive + ) + = + failwith "" +``` + +#### A tuple type after `:>`, `:?>`, `:` or `:?` goes one level in + +The lines after the first element used to go back to the column of the operator line, where they +read as if the type had ended. A tuple after the `->` of a function type does the same. + +```fsharp +// v8.0 +let x = + someValue + :> (LongTypeNameNumberOne * + LongTypeNameNumberTwo * + LongTypeNameNumberThree * + LongTypeNameNumberFour * + LongTypeNameNumberFive) + +// v8.1 +let x = + someValue + :> (LongTypeNameNumberOne * + LongTypeNameNumberTwo * + LongTypeNameNumberThree * + LongTypeNameNumberFour * + LongTypeNameNumberFive) +``` + +#### A comment lined up with the elements stays with them + +A line comment written on the column where the elements of a list start now stays with the +elements, also when the closing `]` is on that column too. It used to move before the `]`. A +comment on the column of the opening bracket still stays with the brackets. + +```fsharp +// input +let a = [ + (1,2,3); (4,5,6); (7,8,9) + // some line comment + ] + +// v8.0 +let a = + [ + (1, 2, 3) + (4, 5, 6) + (7, 8, 9) + // some line comment + ] + +// v8.1 +let a = + [ + (1, 2, 3) + (4, 5, 6) + (7, 8, 9) + // some line comment + ] +``` + From 78a0d8cfd7d2fc03d50a144ffd95ecbb3162668c Mon Sep 17 00:00:00 2001 From: Florian Verdonck Date: Wed, 21 Oct 2026 18:33:27 +0200 Subject: [PATCH 14/16] Keep a single anonymous record type argument attached in Stroustrup With Stroustrup, a type application whose only type argument is an anonymous record printed it as an indented list item, with the closing `>` on a line of its own and a space before it. It now stays attached, `convertTo<{|`, fields, `|}>`, for expressions and types alike, as it was before 6.3.0. genPrefixApp makes the choice, since it already holds the padding that keeps a `>` starting a line right of the identifier, where it cannot be read as the comparison operator. It takes the type arguments as a list and uses the same rule as every other place that attaches an anonymous record type: isStroustrupStyleType and canSafelyUseStroustrup, now in Context.fsi, decided once `<` is written so a comment after it counts. With trivia before `>`, the list layout stays, so the `>` always follows `|}` and needs no padding. This is the design @mmabdpr proposed in #3525, after the first version there was reviewed. Closes #3069 Closes #2860 Co-authored-by: Mohammad Mahdi Abdollahpour --- CHANGELOG.md | 2 + ...-space-before-the-closing-angle-bracket.fs | 9 +++++ ...e-before-the-closing-angle-bracket.gold.fs | 6 +++ ...ous-record-type-argument-stays-attached.fs | 11 ++++++ ...ecord-type-argument-stays-attached.gold.fs | 6 +++ ...e-struct-anonymous-record-type-argument.fs | 4 ++ ...uct-anonymous-record-type-argument.gold.fs | 5 +++ src/Fantomas.Core/CodePrinter.fs | 39 ++++++++++++++----- src/Fantomas.Core/Context.fsi | 1 + 9 files changed, 73 insertions(+), 10 deletions(-) create mode 100644 src/Fantomas.Core.SnapshotTests/cases/settings/fsharp_multiline_bracket_style/stroustrup/Expr/TypeApp/2860-no-space-before-the-closing-angle-bracket.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/settings/fsharp_multiline_bracket_style/stroustrup/Expr/TypeApp/2860-no-space-before-the-closing-angle-bracket.gold.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/settings/fsharp_multiline_bracket_style/stroustrup/Expr/TypeApp/3069-single-anonymous-record-type-argument-stays-attached.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/settings/fsharp_multiline_bracket_style/stroustrup/Expr/TypeApp/3069-single-anonymous-record-type-argument-stays-attached.gold.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/settings/fsharp_multiline_bracket_style/stroustrup/Type/AppPrefix/single-struct-anonymous-record-type-argument.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/settings/fsharp_multiline_bracket_style/stroustrup/Type/AppPrefix/single-struct-anonymous-record-type-argument.gold.fs diff --git a/CHANGELOG.md b/CHANGELOG.md index 0d1550b37e..1f5109e25b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,8 @@ - Long type test with :? gives invalid code. [#3558](https://github.com/fsprojects/fantomas/issues/3558) - Line comment after the opening parenthesis of a type moves and breaks the type. [#3559](https://github.com/fsprojects/fantomas/issues/3559) - Comment between a match pattern and its when guard gives invalid code. [#3560](https://github.com/fsprojects/fantomas/issues/3560) +- Regression: Stroustrup bracket style in anonymous record type parameter is not respected. [#3069](https://github.com/fsprojects/fantomas/issues/3069) +- Space inserted before final > in type parameter. [#2860](https://github.com/fsprojects/fantomas/issues/2860) ## [8.0.10] - 2026-10-14 diff --git a/src/Fantomas.Core.SnapshotTests/cases/settings/fsharp_multiline_bracket_style/stroustrup/Expr/TypeApp/2860-no-space-before-the-closing-angle-bracket.fs b/src/Fantomas.Core.SnapshotTests/cases/settings/fsharp_multiline_bracket_style/stroustrup/Expr/TypeApp/2860-no-space-before-the-closing-angle-bracket.fs new file mode 100644 index 0000000000..518930b71f --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/settings/fsharp_multiline_bracket_style/stroustrup/Expr/TypeApp/2860-no-space-before-the-closing-angle-bracket.fs @@ -0,0 +1,9 @@ +(*--- +fsharp_multiline_bracket_style = stroustrup +---*) +{| payload with reason = reason |} +|> Json.serialize<{| + reason: string + old: bool + ``new``: bool +|} > diff --git a/src/Fantomas.Core.SnapshotTests/cases/settings/fsharp_multiline_bracket_style/stroustrup/Expr/TypeApp/2860-no-space-before-the-closing-angle-bracket.gold.fs b/src/Fantomas.Core.SnapshotTests/cases/settings/fsharp_multiline_bracket_style/stroustrup/Expr/TypeApp/2860-no-space-before-the-closing-angle-bracket.gold.fs new file mode 100644 index 0000000000..cb84f337d6 --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/settings/fsharp_multiline_bracket_style/stroustrup/Expr/TypeApp/2860-no-space-before-the-closing-angle-bracket.gold.fs @@ -0,0 +1,6 @@ +{| payload with reason = reason |} +|> Json.serialize<{| + reason: string + old: bool + ``new``: bool +|}> diff --git a/src/Fantomas.Core.SnapshotTests/cases/settings/fsharp_multiline_bracket_style/stroustrup/Expr/TypeApp/3069-single-anonymous-record-type-argument-stays-attached.fs b/src/Fantomas.Core.SnapshotTests/cases/settings/fsharp_multiline_bracket_style/stroustrup/Expr/TypeApp/3069-single-anonymous-record-type-argument-stays-attached.fs new file mode 100644 index 0000000000..9288050edc --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/settings/fsharp_multiline_bracket_style/stroustrup/Expr/TypeApp/3069-single-anonymous-record-type-argument-stays-attached.fs @@ -0,0 +1,11 @@ +(*--- +fsharp_multiline_bracket_style = stroustrup +---*) +let private asJson (arm: IArmResource) = + arm.JsonModel + |> convertTo< + {| + kind: string + properties: {| statisticsEnabled: bool |} + |} + > diff --git a/src/Fantomas.Core.SnapshotTests/cases/settings/fsharp_multiline_bracket_style/stroustrup/Expr/TypeApp/3069-single-anonymous-record-type-argument-stays-attached.gold.fs b/src/Fantomas.Core.SnapshotTests/cases/settings/fsharp_multiline_bracket_style/stroustrup/Expr/TypeApp/3069-single-anonymous-record-type-argument-stays-attached.gold.fs new file mode 100644 index 0000000000..712c80b24b --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/settings/fsharp_multiline_bracket_style/stroustrup/Expr/TypeApp/3069-single-anonymous-record-type-argument-stays-attached.gold.fs @@ -0,0 +1,6 @@ +let private asJson (arm: IArmResource) = + arm.JsonModel + |> convertTo<{| + kind: string + properties: {| statisticsEnabled: bool |} + |}> diff --git a/src/Fantomas.Core.SnapshotTests/cases/settings/fsharp_multiline_bracket_style/stroustrup/Type/AppPrefix/single-struct-anonymous-record-type-argument.fs b/src/Fantomas.Core.SnapshotTests/cases/settings/fsharp_multiline_bracket_style/stroustrup/Type/AppPrefix/single-struct-anonymous-record-type-argument.fs new file mode 100644 index 0000000000..46a9a8eb3c --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/settings/fsharp_multiline_bracket_style/stroustrup/Type/AppPrefix/single-struct-anonymous-record-type-argument.fs @@ -0,0 +1,4 @@ +(*--- +fsharp_multiline_bracket_style = stroustrup +---*) +type Result = Box diff --git a/src/Fantomas.Core.SnapshotTests/cases/settings/fsharp_multiline_bracket_style/stroustrup/Type/AppPrefix/single-struct-anonymous-record-type-argument.gold.fs b/src/Fantomas.Core.SnapshotTests/cases/settings/fsharp_multiline_bracket_style/stroustrup/Type/AppPrefix/single-struct-anonymous-record-type-argument.gold.fs new file mode 100644 index 0000000000..cb48a5703e --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/settings/fsharp_multiline_bracket_style/stroustrup/Type/AppPrefix/single-struct-anonymous-record-type-argument.gold.fs @@ -0,0 +1,5 @@ +type Result = + Box diff --git a/src/Fantomas.Core/CodePrinter.fs b/src/Fantomas.Core/CodePrinter.fs index d0f35b37e5..a3e55850d9 100644 --- a/src/Fantomas.Core/CodePrinter.fs +++ b/src/Fantomas.Core/CodePrinter.fs @@ -2054,11 +2054,7 @@ let genExpr (e: Expr) = |> genNode node | Expr.TypeApp node -> - genPrefixApp - (genExpr node.Identifier) - node.LessThan - (colGenericTypeParameters node.TypeParameters) - node.GreaterThan + genPrefixApp (genExpr node.Identifier) node.LessThan node.TypeParameters sepNone node.GreaterThan |> genNode node | Expr.TryWithSingleClause node -> let genClause = @@ -3318,17 +3314,36 @@ let colGenericTypeParameters typeParameters = let genPrefixApp (identifier: Context -> Context) (lessThan: SingleTextNode) - (typeParameters: Context -> Context) + (typeParameters: Type list) + (spaceInsideBrackets: Context -> Context) (greaterThan: SingleTextNode) (ctx: Context) : Context = - let startColumn = ctx.Column + let startColumn: int = ctx.Column + + // Decided once `<` is written, so a comment after it counts as one waiting for a line break. + let genTypeParameters (ctx: Context) : Context = + match typeParameters with + | [ t ] when + isStroustrupStyleType ctx.Config t + && canSafelyUseStroustrup (Type.Node t) ctx + && not greaterThan.HasContentBefore + -> + // convertTo<{| + // kind: string + // |}> `>` follows `|}` on its line and never starts one, so it needs no padding + genType t ctx + | _ -> + (spaceInsideBrackets + +> colGenericTypeParameters typeParameters + +> spaceInsideBrackets + +> addFixedSpaces (startColumn + 1)) + ctx (identifier +> genSingleTextNode lessThan - +> typeParameters - +> addFixedSpaces (startColumn + 1) + +> genTypeParameters +> genSingleTextNode greaterThan) ctx @@ -4346,6 +4361,9 @@ let genType (t: Type) = | Type.Var node -> genSingleTextNode node | Type.AppPostfix node -> genType node.First +> sepSpace +> genType node.Last |> genNode node | Type.AppPrefix node -> + // Foo< ^T > a space inside both brackets: older compilers read `<^` as an + // operator (#803, #984); SDK 8 and 10 no longer do + // Csv< @"data.csv" > `<@` opens a quotation (#1209) let addExtraSpace = match node.Arguments with | [] -> sepNone @@ -4355,7 +4373,8 @@ let genType (t: Type) = genPrefixApp (genType node.Identifier +> optSingle genIdentListNodeWithDot node.PostIdentifier) node.LessThen - (addExtraSpace +> colGenericTypeParameters node.Arguments +> addExtraSpace) + node.Arguments + addExtraSpace node.GreaterThan |> genNode node | Type.StructTuple node -> diff --git a/src/Fantomas.Core/Context.fsi b/src/Fantomas.Core/Context.fsi index 4bb867352c..0a01db82d7 100644 --- a/src/Fantomas.Core/Context.fsi +++ b/src/Fantomas.Core/Context.fsi @@ -368,6 +368,7 @@ val addParenIfAutoNln: expr: Expr -> f: (Expr -> Context -> Context) -> (Context // ============================================================================= val isStroustrupStyleExpr: config: FormatConfig -> e: Expr -> bool +val isStroustrupStyleType: config: FormatConfig -> t: Type -> bool /// A bracket can only open on the line of what precedes it when nothing else wants that line first, /// which a comment in front of the node does. From 00219e10a3eb1604775c35a636a4834f479ca9aa Mon Sep 17 00:00:00 2001 From: Florian Verdonck Date: Wed, 21 Oct 2026 18:34:53 +0200 Subject: [PATCH 15/16] Describe the Stroustrup type argument layout in the upgrade guide With fsharp_multiline_bracket_style = stroustrup, a type application whose only type argument is an anonymous record now keeps `<{|` and `|}>` together, where 8.0 put the record on lines of its own and the closing `>` on a line by itself. Users of that setting will see their code change, so the v8.1 section shows the layout of 8.0 and of 8.1 for the same input. The section no longer says both ideas in its introduction are behind every change, as this one follows neither. --- docs/docs/end-users/UpgradeGuide.md | 36 ++++++++++++++++++++++++++++- 1 file changed, 35 insertions(+), 1 deletion(-) diff --git a/docs/docs/end-users/UpgradeGuide.md b/docs/docs/end-users/UpgradeGuide.md index 61f0485be4..79b9fc67d8 100644 --- a/docs/docs/end-users/UpgradeGuide.md +++ b/docs/docs/end-users/UpgradeGuide.md @@ -607,7 +607,7 @@ has to be rebuilt against `v8`. 8.1 fixes a handful of layouts where the formatted code did not compile, or changed again on the next format; the [changelog](https://github.com/fsprojects/fantomas/blob/main/CHANGELOG.md) lists them. Fixing them at the cause, rather than with a special case each, also moves a few layouts of -code that was already valid. Two ideas are behind every change below: +code that was already valid. Two ideas are behind most changes below: - Indent only as far as the parser needs, and on a multiple of `indent_size`: the [rule of multitudes](./RuleOfMultitudes.html). 8.0 added extra indentation in places to keep the @@ -758,4 +758,38 @@ let a = ] ``` +#### A single anonymous record type argument stays attached in Stroustrup + +This applies with **`fsharp_multiline_bracket_style = stroustrup`**. `aligned` and `cramped` are +untouched. + +A type application whose only type argument is an anonymous record keeps `<{|` and `|}>` together, +the way Stroustrup puts the bracket of a record at the end of the line before it. Since 6.3.0 the +record went on lines of its own, one level in, with the closing `>` on a line by itself. With more +than one type argument, the arguments still go on lines of their own. + +```fsharp +// v8.0 +let asJson (arm: IArmResource) = + arm.JsonModel + |> convertTo< + {| + kind: string + properties: {| statisticsEnabled: bool |} + location: string + sku: string + |} + > + +// v8.1 +let asJson (arm: IArmResource) = + arm.JsonModel + |> convertTo<{| + kind: string + properties: {| statisticsEnabled: bool |} + location: string + sku: string + |}> +``` + From 574847fb525c76ee379ddc050ca3ed70afdf8537 Mon Sep 17 00:00:00 2001 From: Florian Verdonck Date: Wed, 21 Oct 2026 21:21:54 +0200 Subject: [PATCH 16/16] Keep return type lines and a leading tuple clear of where they start A function type in parentheses steps its `->` lines past the `(`, but when it started with a tuple, the tuple's lines fell back to the column of the `(`. Main put them one level in through the extra level every parenthesized function type used to get. The parenthesized type now applies one rule to a function type and to a type after a trivia line comment: the lines the type indents clear the first token after the `(`, and the lines at the type's own indent, a leading tuple's or the first after the comment, clear the `(` itself. indentPast measures from the current indent, so a tuple an `->` already put a level in gets nothing more. Other parenthesized types keep their layout. A return type on its own line keeps the binding's indent and goes one level in. With an indent size of 2, `: ` is exactly one level wide, so that level is the column the type starts on: the type arguments of `: Dictionary<` and the `->` lines of a function type started under the type name, with the closing `>` right of them. With an indent size of 2, the type now indents from where it starts, as in 8.0; the upgrade guide says so. Layouts checked by hand at an indent size of 2 and in nested parentheses are now cases, and AGENTS.md asks for that from now on. --- AGENTS.md | 3 ++ docs/docs/end-users/UpgradeGuide.md | 6 ++- ...pe-starting-with-a-bare-multiline-tuple.fs | 1 + ...arting-with-a-bare-multiline-tuple.gold.fs | 11 +++++ ...on-type-starting-with-a-multiline-tuple.fs | 1 + ...pe-starting-with-a-multiline-tuple.gold.fs | 11 +++++ ...th-a-parenthesized-tuple-after-an-arrow.fs | 1 + ...parenthesized-tuple-after-an-arrow.gold.fs | 12 +++++ ...e-a-function-type-starting-with-a-tuple.fs | 2 + ...unction-type-starting-with-a-tuple.gold.fs | 13 +++++ ...nction-type-return-type-on-its-own-line.fs | 4 ++ ...n-type-return-type-on-its-own-line.gold.fs | 9 ++++ ...uments-of-a-return-type-on-its-own-line.fs | 4 ++ ...s-of-a-return-type-on-its-own-line.gold.fs | 6 +++ ...g-with-a-multiline-tuple-after-an-arrow.fs | 4 ++ ...h-a-multiline-tuple-after-an-arrow.gold.fs | 12 +++++ ...th-a-parenthesized-tuple-after-an-arrow.fs | 4 ++ ...parenthesized-tuple-after-an-arrow.gold.fs | 12 +++++ ...-the-opening-parenthesis-after-an-arrow.fs | 5 ++ ...opening-parenthesis-after-an-arrow.gold.fs | 4 ++ ...e-comment-after-the-opening-parenthesis.fs | 5 ++ ...ment-after-the-opening-parenthesis.gold.fs | 3 ++ src/Fantomas.Core/CodePrinter.fs | 48 +++++++++++++------ 23 files changed, 164 insertions(+), 17 deletions(-) create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/function-type-starting-with-a-bare-multiline-tuple.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/function-type-starting-with-a-bare-multiline-tuple.gold.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/function-type-starting-with-a-multiline-tuple.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/function-type-starting-with-a-multiline-tuple.gold.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/function-type-starting-with-a-parenthesized-tuple-after-an-arrow.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/function-type-starting-with-a-parenthesized-tuple-after-an-arrow.gold.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/trivia/line-comment-before-a-function-type-starting-with-a-tuple.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/trivia/line-comment-before-a-function-type-starting-with-a-tuple.gold.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/settings/indent_size/BindingReturnInfo/function-type-return-type-on-its-own-line.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/settings/indent_size/BindingReturnInfo/function-type-return-type-on-its-own-line.gold.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/settings/indent_size/BindingReturnInfo/type-arguments-of-a-return-type-on-its-own-line.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/settings/indent_size/BindingReturnInfo/type-arguments-of-a-return-type-on-its-own-line.gold.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/settings/indent_size/Type/Paren/function-type-starting-with-a-multiline-tuple-after-an-arrow.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/settings/indent_size/Type/Paren/function-type-starting-with-a-multiline-tuple-after-an-arrow.gold.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/settings/indent_size/Type/Paren/function-type-starting-with-a-parenthesized-tuple-after-an-arrow.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/settings/indent_size/Type/Paren/function-type-starting-with-a-parenthesized-tuple-after-an-arrow.gold.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/settings/indent_size/Type/Paren/trivia/line-comment-after-the-opening-parenthesis-after-an-arrow.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/settings/indent_size/Type/Paren/trivia/line-comment-after-the-opening-parenthesis-after-an-arrow.gold.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/settings/indent_size/Type/Paren/trivia/line-comment-after-the-opening-parenthesis.fs create mode 100644 src/Fantomas.Core.SnapshotTests/cases/settings/indent_size/Type/Paren/trivia/line-comment-after-the-opening-parenthesis.gold.fs diff --git a/AGENTS.md b/AGENTS.md index 940d1ac4ee..c81fc95077 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -14,6 +14,9 @@ Formatting is tested by snapshot cases, files under `src/Fantomas.Core.SnapshotT beside the result formatting gives for it; that project's README says how to write one. `Fantomas.Core.Tests` holds the unit tests of internals. +A layout you check by hand while working, at another setting or in another position, becomes a case +when no case covers it yet. A check that ran once guards nothing the next time that code changes. + ## Diagnostic Scripts All of these accept a file path or stdin, with optional `--signature` and `--editorconfig ` flags. diff --git a/docs/docs/end-users/UpgradeGuide.md b/docs/docs/end-users/UpgradeGuide.md index 79b9fc67d8..e740877573 100644 --- a/docs/docs/end-users/UpgradeGuide.md +++ b/docs/docs/end-users/UpgradeGuide.md @@ -620,7 +620,8 @@ The examples use the default settings. Since 8.0, every multiline function type in parentheses got an extra level, to avoid a compiler error after an outer `->` ([#3043](https://github.com/fsprojects/fantomas/issues/3043)). There it -stays; everywhere else this is the 7.0.6 layout again. +stays, and so it does when the function type starts with a tuple: the tuple's lines go one level +past the `(`, the `->` lines two. Everywhere else this is the 7.0.6 layout again. ```fsharp // v8.0 @@ -643,7 +644,8 @@ type T = #### A return type lands on a multiple of the indent size The lines of a return type no longer hang off the column after `: `. They go one level past the -binding. +binding. With `indent_size = 2` that level would be the column after `: `, so there the lines are +measured from that column, as in 8.0. ```fsharp // v8.0 diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/function-type-starting-with-a-bare-multiline-tuple.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/function-type-starting-with-a-bare-multiline-tuple.fs new file mode 100644 index 0000000000..1f18b75206 --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/function-type-starting-with-a-bare-multiline-tuple.fs @@ -0,0 +1 @@ +type A = (string option * string option * string option * string option * string option * string option * string option * string option * string -> int) diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/function-type-starting-with-a-bare-multiline-tuple.gold.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/function-type-starting-with-a-bare-multiline-tuple.gold.fs new file mode 100644 index 0000000000..3fcc3ad131 --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/function-type-starting-with-a-bare-multiline-tuple.gold.fs @@ -0,0 +1,11 @@ +type A = + (string option * + string option * + string option * + string option * + string option * + string option * + string option * + string option * + string + -> int) diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/function-type-starting-with-a-multiline-tuple.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/function-type-starting-with-a-multiline-tuple.fs new file mode 100644 index 0000000000..6ea90727ed --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/function-type-starting-with-a-multiline-tuple.fs @@ -0,0 +1 @@ +type A = ((string option * string option * string option * string option * string option * string option * string option * string option * string) -> (int * int)[]) diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/function-type-starting-with-a-multiline-tuple.gold.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/function-type-starting-with-a-multiline-tuple.gold.fs new file mode 100644 index 0000000000..3f945df94c --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/function-type-starting-with-a-multiline-tuple.gold.fs @@ -0,0 +1,11 @@ +type A = + ((string option * + string option * + string option * + string option * + string option * + string option * + string option * + string option * + string) + -> (int * int)[]) diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/function-type-starting-with-a-parenthesized-tuple-after-an-arrow.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/function-type-starting-with-a-parenthesized-tuple-after-an-arrow.fs new file mode 100644 index 0000000000..aed7d439f0 --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/function-type-starting-with-a-parenthesized-tuple-after-an-arrow.fs @@ -0,0 +1 @@ +type C = int -> ((string option * string option * string option * string option * string option * string option * string option * string option * string) -> (int * int)[]) diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/function-type-starting-with-a-parenthesized-tuple-after-an-arrow.gold.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/function-type-starting-with-a-parenthesized-tuple-after-an-arrow.gold.fs new file mode 100644 index 0000000000..162d30c1fe --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/function-type-starting-with-a-parenthesized-tuple-after-an-arrow.gold.fs @@ -0,0 +1,12 @@ +type C = + int + -> ((string option * + string option * + string option * + string option * + string option * + string option * + string option * + string option * + string) + -> (int * int)[]) diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/trivia/line-comment-before-a-function-type-starting-with-a-tuple.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/trivia/line-comment-before-a-function-type-starting-with-a-tuple.fs new file mode 100644 index 0000000000..ed46361a96 --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/trivia/line-comment-before-a-function-type-starting-with-a-tuple.fs @@ -0,0 +1,2 @@ +type B = int -> ( // comment + string option * string option * string option * string option * string option * string option * string option * string option * string -> (int * int)[]) diff --git a/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/trivia/line-comment-before-a-function-type-starting-with-a-tuple.gold.fs b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/trivia/line-comment-before-a-function-type-starting-with-a-tuple.gold.fs new file mode 100644 index 0000000000..3e0dd19c24 --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/oak/Type/Paren/trivia/line-comment-before-a-function-type-starting-with-a-tuple.gold.fs @@ -0,0 +1,13 @@ +type B = + int + -> ( // comment + string option * + string option * + string option * + string option * + string option * + string option * + string option * + string option * + string + -> (int * int)[]) diff --git a/src/Fantomas.Core.SnapshotTests/cases/settings/indent_size/BindingReturnInfo/function-type-return-type-on-its-own-line.fs b/src/Fantomas.Core.SnapshotTests/cases/settings/indent_size/BindingReturnInfo/function-type-return-type-on-its-own-line.fs new file mode 100644 index 0000000000..d1a07afa38 --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/settings/indent_size/BindingReturnInfo/function-type-return-type-on-its-own-line.fs @@ -0,0 +1,4 @@ +(*--- +indent_size = 2 +---*) +let someFunctionName (someArgument: int) : LongTypeNameNumberOne -> LongTypeNameNumberTwo -> LongTypeNameNumberThree -> LongTypeNameNumberFour -> LongTypeNameNumberFive = failwith "" diff --git a/src/Fantomas.Core.SnapshotTests/cases/settings/indent_size/BindingReturnInfo/function-type-return-type-on-its-own-line.gold.fs b/src/Fantomas.Core.SnapshotTests/cases/settings/indent_size/BindingReturnInfo/function-type-return-type-on-its-own-line.gold.fs new file mode 100644 index 0000000000..cde815c7a2 --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/settings/indent_size/BindingReturnInfo/function-type-return-type-on-its-own-line.gold.fs @@ -0,0 +1,9 @@ +let someFunctionName + (someArgument: int) + : LongTypeNameNumberOne + -> LongTypeNameNumberTwo + -> LongTypeNameNumberThree + -> LongTypeNameNumberFour + -> LongTypeNameNumberFive + = + failwith "" diff --git a/src/Fantomas.Core.SnapshotTests/cases/settings/indent_size/BindingReturnInfo/type-arguments-of-a-return-type-on-its-own-line.fs b/src/Fantomas.Core.SnapshotTests/cases/settings/indent_size/BindingReturnInfo/type-arguments-of-a-return-type-on-its-own-line.fs new file mode 100644 index 0000000000..1c1881dc6c --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/settings/indent_size/BindingReturnInfo/type-arguments-of-a-return-type-on-its-own-line.fs @@ -0,0 +1,4 @@ +(*--- +indent_size = 2 +---*) +let x: System.Collections.Generic.Dictionary = failwith "" diff --git a/src/Fantomas.Core.SnapshotTests/cases/settings/indent_size/BindingReturnInfo/type-arguments-of-a-return-type-on-its-own-line.gold.fs b/src/Fantomas.Core.SnapshotTests/cases/settings/indent_size/BindingReturnInfo/type-arguments-of-a-return-type-on-its-own-line.gold.fs new file mode 100644 index 0000000000..43b9276b47 --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/settings/indent_size/BindingReturnInfo/type-arguments-of-a-return-type-on-its-own-line.gold.fs @@ -0,0 +1,6 @@ +let x + : System.Collections.Generic.Dictionary< + string, + System.Text.StringBuilder * System.DateTimeOffset * System.Uri * System.Globalization.CultureInfo + > = + failwith "" diff --git a/src/Fantomas.Core.SnapshotTests/cases/settings/indent_size/Type/Paren/function-type-starting-with-a-multiline-tuple-after-an-arrow.fs b/src/Fantomas.Core.SnapshotTests/cases/settings/indent_size/Type/Paren/function-type-starting-with-a-multiline-tuple-after-an-arrow.fs new file mode 100644 index 0000000000..a8b5b04743 --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/settings/indent_size/Type/Paren/function-type-starting-with-a-multiline-tuple-after-an-arrow.fs @@ -0,0 +1,4 @@ +(*--- +indent_size = 2 +---*) +type E = int -> (string option * string option * string option * string option * string option * string option * string option * string option * string -> (int * int)[]) diff --git a/src/Fantomas.Core.SnapshotTests/cases/settings/indent_size/Type/Paren/function-type-starting-with-a-multiline-tuple-after-an-arrow.gold.fs b/src/Fantomas.Core.SnapshotTests/cases/settings/indent_size/Type/Paren/function-type-starting-with-a-multiline-tuple-after-an-arrow.gold.fs new file mode 100644 index 0000000000..a03a2e0fa7 --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/settings/indent_size/Type/Paren/function-type-starting-with-a-multiline-tuple-after-an-arrow.gold.fs @@ -0,0 +1,12 @@ +type E = + int + -> (string option * + string option * + string option * + string option * + string option * + string option * + string option * + string option * + string + -> (int * int)[]) diff --git a/src/Fantomas.Core.SnapshotTests/cases/settings/indent_size/Type/Paren/function-type-starting-with-a-parenthesized-tuple-after-an-arrow.fs b/src/Fantomas.Core.SnapshotTests/cases/settings/indent_size/Type/Paren/function-type-starting-with-a-parenthesized-tuple-after-an-arrow.fs new file mode 100644 index 0000000000..18ff79251d --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/settings/indent_size/Type/Paren/function-type-starting-with-a-parenthesized-tuple-after-an-arrow.fs @@ -0,0 +1,4 @@ +(*--- +indent_size = 2 +---*) +type C = int -> ((string option * string option * string option * string option * string option * string option * string option * string option * string) -> (int * int)[]) diff --git a/src/Fantomas.Core.SnapshotTests/cases/settings/indent_size/Type/Paren/function-type-starting-with-a-parenthesized-tuple-after-an-arrow.gold.fs b/src/Fantomas.Core.SnapshotTests/cases/settings/indent_size/Type/Paren/function-type-starting-with-a-parenthesized-tuple-after-an-arrow.gold.fs new file mode 100644 index 0000000000..9a41752bd1 --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/settings/indent_size/Type/Paren/function-type-starting-with-a-parenthesized-tuple-after-an-arrow.gold.fs @@ -0,0 +1,12 @@ +type C = + int + -> ((string option * + string option * + string option * + string option * + string option * + string option * + string option * + string option * + string) + -> (int * int)[]) diff --git a/src/Fantomas.Core.SnapshotTests/cases/settings/indent_size/Type/Paren/trivia/line-comment-after-the-opening-parenthesis-after-an-arrow.fs b/src/Fantomas.Core.SnapshotTests/cases/settings/indent_size/Type/Paren/trivia/line-comment-after-the-opening-parenthesis-after-an-arrow.fs new file mode 100644 index 0000000000..786195cecf --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/settings/indent_size/Type/Paren/trivia/line-comment-after-the-opening-parenthesis-after-an-arrow.fs @@ -0,0 +1,5 @@ +(*--- +indent_size = 2 +---*) +type T = a -> ( // c + (int -> int)) diff --git a/src/Fantomas.Core.SnapshotTests/cases/settings/indent_size/Type/Paren/trivia/line-comment-after-the-opening-parenthesis-after-an-arrow.gold.fs b/src/Fantomas.Core.SnapshotTests/cases/settings/indent_size/Type/Paren/trivia/line-comment-after-the-opening-parenthesis-after-an-arrow.gold.fs new file mode 100644 index 0000000000..d67366b081 --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/settings/indent_size/Type/Paren/trivia/line-comment-after-the-opening-parenthesis-after-an-arrow.gold.fs @@ -0,0 +1,4 @@ +type T = + a + -> ( // c + (int -> int)) diff --git a/src/Fantomas.Core.SnapshotTests/cases/settings/indent_size/Type/Paren/trivia/line-comment-after-the-opening-parenthesis.fs b/src/Fantomas.Core.SnapshotTests/cases/settings/indent_size/Type/Paren/trivia/line-comment-after-the-opening-parenthesis.fs new file mode 100644 index 0000000000..2cf052c485 --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/settings/indent_size/Type/Paren/trivia/line-comment-after-the-opening-parenthesis.fs @@ -0,0 +1,5 @@ +(*--- +indent_size = 2 +---*) +type T = ( // c + Map) diff --git a/src/Fantomas.Core.SnapshotTests/cases/settings/indent_size/Type/Paren/trivia/line-comment-after-the-opening-parenthesis.gold.fs b/src/Fantomas.Core.SnapshotTests/cases/settings/indent_size/Type/Paren/trivia/line-comment-after-the-opening-parenthesis.gold.fs new file mode 100644 index 0000000000..0d1c5a3e72 --- /dev/null +++ b/src/Fantomas.Core.SnapshotTests/cases/settings/indent_size/Type/Paren/trivia/line-comment-after-the-opening-parenthesis.gold.fs @@ -0,0 +1,3 @@ +type T = + ( // c + Map) diff --git a/src/Fantomas.Core/CodePrinter.fs b/src/Fantomas.Core/CodePrinter.fs index a3e55850d9..0f52d8b3db 100644 --- a/src/Fantomas.Core/CodePrinter.fs +++ b/src/Fantomas.Core/CodePrinter.fs @@ -3920,11 +3920,18 @@ let genBinding (b: BindingNode) (ctx: Context) : Context = // A line of the return type that starts on the column of the `:` ends it. The indent stays the // binding's, so a type that indents its own lines lands on a multiple of the indent size. Where // a tuple starts the lines of the type, AtColumn keeps them past the `:`. - let genReturnTypeAfterColon (t: Type) : Context -> Context = + let genReturnTypeAfterColon (t: Type) (ctx: Context) : Context = if startsWithTuple t then - atCurrentColumn (genType t) + atCurrentColumn (genType t) ctx + elif ctx.Config.IndentSize = 2 then + // let items + // : Dictionary< + // string, a level past `Dictionary`: `: ` is one level wide, so a level past the + // binding would be its column + // > + atCurrentColumnIndent (genType t) ctx else - genType t + genType t ctx let isRecursiveLetOrUseFunction = match b.LeadingKeyword.Content with @@ -4448,19 +4455,30 @@ let genType (t: Type) = | Type.Paren node -> let genInner (columnAfterParen: int) (ctx: Context) : Context = - if hasWriteBeforeNewlineContent ctx then - // ( // trivia - // Map) on a line of its own, past the `(`: the trivia line comment - // ends the line the `(` is on - indentPast (columnAfterParen - 1) (indentSepNlnUnindent (genType node.Type)) ctx - elif node.Type.IsFuns then - // The parenthesis opens an offside context at the first token inside it, and a line - // starting on that column ends it. The `->` lines of the function type start past the - // column right after the parenthesis, taken before its trivia: a block comment there - // moves the first token right, and a line left of that token parses. - indentPast columnAfterParen (genType node.Type) ctx - else + // ( // trivia + // Map) a trivia line comment after the `(` ends its line + let startsOnFreshLine: bool = hasWriteBeforeNewlineContent ctx + + if not startsOnFreshLine && not node.Type.IsFuns then genType node.Type ctx + else + + // The parenthesis opens an offside context at the first token inside it, and a line + // starting on that column ends it. The lines the type indents clear that column, taken + // before the trivia after the `(`: a block comment there moves the first token right, + // and a line left of that token parses. Lines at the type's own indent, a function type's + // leading tuple or the first after a trivia line comment, come a level before them + // and clear the `(`: + // ((string option * + // string option) + // -> unit) + let columnToClear: int = + if startsOnFreshLine || startsWithTuple node.Type then + columnAfterParen - 1 + ctx.Config.IndentSize + else + columnAfterParen + + indentPast columnToClear (onlyIf startsOnFreshLine sepNln +> genType node.Type) ctx enterNode node.OpeningParen +> genSingleTextNodeText node.OpeningParen