fsprojects / fantomas

FSharp source code formatter
https://fsprojects.github.io/fantomas
Other
758 stars 189 forks source link

Misplaced comment in "else if" #3011

Open Smaug123 opened 7 months ago

Smaug123 commented 7 months ago

Issue created from fantomas-online

Code

let foo =
    if bar then
        a <- 1
    else
    // whatnot
    if baz then
        quux <- 3

Result

let foo =
    if bar then
        a <- 1
    else if
        // whatnot
        baz
    then
        quux <- 3

Problem description

The comment has been moved with respect to the if statement. Expected instead was:

let foo =
    if bar then
        a <- 1
    else
        // whatnot
        if baz then
            quux <- 3

(or, in my own codebase with ExperimentalKeepIndentInBranch, I expected no change to the formatting).

Extra information

Options

Fantomas main branch at 2023-12-06T16:47:58Z - 0f8ee237a452f3772afe7989e031b5f65ba389f5

Default Fantomas configuration

Did you know that you can ignore files when formatting by using a .fantomasignore file? PS: It's unlikely that someone else will solve your specific issue, as it's something that you have a personal stake in.

nojaf commented 7 months ago

So, the style guide settled on formatting multiline conditions like:

// ✔️ OK, but better to refactor, see below
if
    complexExpression a b && env.IsDevelopment()
    || someFunctionToCall
        aVeryLongParameterNameOne
        aVeryLongParameterNameTwo
        aVeryLongParameterNameThree 
then
        e1
    else
        e2

// ✔️The same applies to nested `elif` or `else if` expressions
if a then
    b
elif
    someLongFunctionCall
        argumentOne
        argumentTwo
        argumentThree
        argumentFour
then
    c
else if
    someOtherLongFunctionCall
        argumentOne
        argumentTwo
        argumentThree
        argumentFour
then
    d

// whatnot between the else and the if forces this behaviour.

It rings a bell that putting anything between the else if can very easily lead to invalid code, so I believe we deliberately moved the comment.

From a technical point of view, we view your entire if expression as one node, and not the parent if/else node where the else expression is a if/then expression.

majocha commented 7 months ago

I think it would be more logical to assign the comment to the else if node rather than to the condition, i. e. this:

if bar then
    a <- 1
else
    // elif comment
    if
        // baz comment
        baz 
    then
        quux <- 3

should not format to:

if bar then
    a <- 1
else if
    // elif comment
    // baz comment
    baz
then
    quux <- 3

but instead:

if bar then
    a <- 1
// elif comment
else if
    // baz comment
    baz
then
    quux <- 3

fantomas-online repro

nojaf commented 7 months ago

Feel free to investigate how much fun that would be 😉