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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .fantomasignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,7 @@ 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 or review findings for the user, written by an agent: the examples are the point, not code to format
/question.fs
/review.fs
76 changes: 76 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <content>` flags.
Expand Down Expand Up @@ -45,6 +48,79 @@ 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

"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.

### 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.

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
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 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

The style rules for this repository are analyzers rather than prose, so the feedback arrives while
Expand Down
18 changes: 18 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,23 @@
# Changelog

## [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

- 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)
- 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

### Fixed
Expand Down
30 changes: 25 additions & 5 deletions analyzers/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
63 changes: 63 additions & 0 deletions analyzers/Fantomas.Analyzers.Tests/SnobMatchAnalyzerTests.fs
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,69 @@ let f (xs: int list) : int =

analyzeSource cliAnalyzer source |> assertLines [ 4 ]

[<Test>]
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 ]

[<Test>]
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.
[<Test>]
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`.
[<Test>]
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 []

[<Test>]
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 []

[<Test>]
let ``a match on a union is not reported`` () =
let source: string =
Expand Down
44 changes: 35 additions & 9 deletions analyzers/Fantomas.Analyzers/SnobMatchAnalyzer.fs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ let Name: string = "SnobMatchAnalyzer"

[<Literal>]
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."

[<Literal>]
let HelpUri: string =
Expand All @@ -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

[<Literal>]
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."

[<Literal>]
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
Expand All @@ -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<range> = ResizeArray<range>()
let findings: ResizeArray<range * string> = ResizeArray<range * string>()

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
Expand Down
16 changes: 8 additions & 8 deletions analyzers/Fantomas.Analyzers/SnobMatchAnalyzer.fsi
Original file line number Diff line number Diff line change
Expand Up @@ -10,19 +10,19 @@ val Name: string = "SnobMatchAnalyzer"

[<Literal>]
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."

[<Literal>]
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.
[<CliAnalyzer(Name, ShortDescription, HelpUri)>]
val cliAnalyzer: ctx: CliContext -> Async<Message list>

Expand Down
6 changes: 6 additions & 0 deletions docs/docs/end-users/DesignDecisions.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).

<fantomas-nav source="{{fsdocs-source-filename}}" previous="{{fsdocs-previous-page-link}}" next="{{fsdocs-next-page-link}}"></fantomas-nav>
2 changes: 1 addition & 1 deletion docs/docs/end-users/ReportingBugs.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
---
category: End-users
categoryindex: 1
index: 18
index: 19
---
# Reporting a bug

Expand Down
Loading
Loading