From cd5a93b80428a22a12aa0999d988ca527cc2596b Mon Sep 17 00:00:00 2001 From: Omar Bonnet Date: Mon, 18 Nov 2024 01:21:40 -0500 Subject: [PATCH] Fix switch indentation for list patterns - fixes #72196 --- .../CSharpTest/Formatting/FormattingTests.cs | 28 +++++++++++++++++++ .../Rules/IndentBlockFormattingRule.cs | 10 +++++++ 2 files changed, 38 insertions(+) diff --git a/src/Workspaces/CSharpTest/Formatting/FormattingTests.cs b/src/Workspaces/CSharpTest/Formatting/FormattingTests.cs index a6668e8b9a77c..9cdc7c0c97708 100644 --- a/src/Workspaces/CSharpTest/Formatting/FormattingTests.cs +++ b/src/Workspaces/CSharpTest/Formatting/FormattingTests.cs @@ -5605,6 +5605,34 @@ public object Method(int i) await AssertFormatAsync(expectedCode, code); } + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/72196")] + public async Task FormatSwitchExpression_ListPatternAligned() + { + var code = @"class C +{ + void M() + { + _ = Array.Empty() switch + { + [] => 0, + _ => 1, + }; + } +}"; + var expectedCode = @"class C +{ + void M() + { + _ = Array.Empty() switch + { + [] => 0, + _ => 1, + }; + } +}"; + await AssertFormatAsync(expectedCode, code); + } + [Fact] public async Task FormatSwitchWithPropertyPattern() { diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Rules/IndentBlockFormattingRule.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Rules/IndentBlockFormattingRule.cs index d6331a303a26d..da7ddb4592b41 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Rules/IndentBlockFormattingRule.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Rules/IndentBlockFormattingRule.cs @@ -262,6 +262,11 @@ private static void AddBracketIndentationOperation(List li // Brackets in list patterns are formatted like blocks, so align close bracket with open bracket AddIndentBlockOperation(list, bracketPair.openBracket.GetNextToken(includeZeroWidth: true), bracketPair.closeBracket.GetPreviousToken(includeZeroWidth: true)); + if (IsSwitchExpressionPattern(node)) + { + return; + } + // If we have: // // return Goo([ //<-- determining indentation here. @@ -279,6 +284,11 @@ private static void AddBracketIndentationOperation(List li } } + private static bool IsSwitchExpressionPattern(SyntaxNode node) + { + return node.Parent is SwitchExpressionArmSyntax arm && arm.Pattern == node; + } + private static void AddAlignmentBlockOperationRelativeToFirstTokenOnBaseTokenLine(List list, (SyntaxToken openBrace, SyntaxToken closeBrace) bracePair) { var option = IndentBlockOption.RelativeToFirstTokenOnBaseTokenLine;