belav / csharpier

CSharpier is an opinionated code formatter for c#.
https://csharpier.com
MIT License
1.43k stars 99 forks source link

Some remaining little bugs related to C#12 collection expressions #1047

Closed fgimian closed 1 year ago

fgimian commented 1 year ago

Hey there, found a few little issues while migrating a project to .NET 8 today 😄

Here's some sample code:

List<string> items =
[
    // My item
    "Hello",
];

items.AddRange(
    [
        "More really long words",
        "which span multiple lines",
        "are added here",
        "and something bad",
        "happens"
    ]
);

class MyClass
{
    private readonly List<string> _items;

    public MyClass()
    {
        _items = [];
        _items ??= [];
    }
}

And reformatted via the CSharpier CLI as follows:

~\source\ConsoleApp1 via .NET v8.0.100 🎯 net8.0
🕙 [ 06:57:50 PM ] ❯ dotnet csharpier --version
0.26.3+6bcc339686b935c644c660a45dc2722ef3567303

~\source\ConsoleApp1 via .NET v8.0.100 🎯 net8.0
🕙 [ 06:57:54 PM ] ❯ dotnet csharpier .
Error ./Program.cs - Failed syntax tree validation.
  ----------------------------- Original: Around Line 1 -----------------------------
  List<string> items =
  [
      // My item
      "Hello",
  ];

  items.AddRange(
      [
  ----------------------------- Formatted: Around Line 0 -----------------------------
  List<string> items = [// My item
      "Hello",];

  items.AddRange(

      [
          "More really long words",
          "which span multiple lines",
Formatted 1 files in 274ms.

The result is as follows:

List<string> items = [// My item
    "Hello",];

items.AddRange(

    [
        "More really long words",
        "which span multiple lines",
        "are added here",
        "and something bad",
        "happens"
    ]
);

class MyClass
{
    private readonly List<string> _items;

    public MyClass()
    {
        _items =  [];
        _items ??=  [];
    }
}

Here's the same code with comments for each issue:

// CSharpier should have kept the original formatting here.
List<string> items = [// My item
    "Hello",];

// An additional empty line was added below.
items.AddRange(

    [
        "More really long words",
        "which span multiple lines",
        "are added here",
        "and something bad",
        "happens"
    ]
);

class MyClass
{
    private readonly List<string> _items;

    public MyClass()
    {
        // Two spaces were added after the = sign in this scenario.
        _items =  [];
        _items ??=  [];
    }
}

Any help is greatly appreciated Fotis

belav commented 1 year ago

Thanks for catching all of these! I'll have an update out shortly

fgimian commented 1 year ago

Thank you so much for sorting these out so quickly! 🚀