dotnet / roslyn

The Roslyn .NET compiler provides C# and Visual Basic languages with rich code analysis APIs.
https://docs.microsoft.com/dotnet/csharp/roslyn-sdk/
MIT License
19.1k stars 4.04k forks source link

Formatter formats collection expression with trailing comma incorrectly #75920

Open just-ero opened 1 week ago

just-ero commented 1 week ago

Environment data

VS Code version: 1.95.2, e8653663e8840adaf45af01eab5c627a5af81807, x64
C# Extension version: v2.56.31

Steps to reproduce

  1. Create or open a C# project.
  2. Add the following code wherever syntactically applicable:
    void M()
    {
           int[] arr =
           [
               0,
           ];
    }
  3. Ensure the file uses 4 spaces for indentations and editor.formatOnSave is enabled.
  4. Save the file.

Expected behavior

void M()
{
    int[] arr =
    [
        0,
    ];
}

Actual behavior

void M()
{
    int[] arr =
    [
        0,
        ];
}
JoeRobich commented 1 week ago

@just-ero Something seems off about your C# extension version. The closest I can find to 1.14.2 is 1.14.0 published back in 2018. The Roslyn Formatter that ships with that version of the extension predates collection expressions.

just-ero commented 1 week ago

Thanks for the heads up. That was the version of the C# DevKit extension. I've fixed my mistake.

JoeRobich commented 1 week ago

@just-ero Thanks for updating! I can reproduce your issue and will move it to the Roslyn repo.

The body of the method is indented 8 spaces and when the formatter deindents those lines to 4 spaces, it fails to deindent the line with the closing square bracket. The same code without the trailing comma formats as expected.

JoeRobich commented 1 week ago

CC: @CyrusNajmabadi

CyrusNajmabadi commented 1 week ago

I don't repro this in VS @JoeRobich . Do you? Is there a full repro for this?

JoeRobich commented 1 week ago

@CyrusNajmabadi These are the step I used to reproduce it.

For VS Code I followed these steps:

  1. dotnet new console -o TestConsole
  2. cd TestConsole
  3. code .
  4. Replace contents of Program.cs the following (Note that indent size is 4 spaces and the body of the M method is doubly indented)
    void M()
    {
        int[] arr =
        [
            0,
        ];
    }
  5. Format the document

VS Code: https://github.com/user-attachments/assets/abf3d9f2-5062-4211-b94d-adb858cdbcb5

Doing similar in VS also reproduces the problem:

  1. Launch VS
  2. Create new Console project
  3. Replace contents of Program.cs as above
  4. Format the document

VS: https://github.com/user-attachments/assets/ca727ce1-5a43-400f-bd62-05e0bdc7c5e7

JoeRobich commented 1 week ago

Retitled the issue as formatOnSave is not necessary to reproduce the issue. Also, I have no idea why my videos are links instead of being embedded.