From 20a38ce92e3138395f0e0fc1f2a393c38ce62e91 Mon Sep 17 00:00:00 2001 From: Andreas Weizel Date: Wed, 4 May 2016 00:12:32 +0200 Subject: [PATCH] Fixed #220: Codefix for RECS0113 C# Redundant comma in array initializer does not format correctly --- ...tCommaInArrayInitializerCodeFixProvider.cs | 8 ++++-- .../RedundantCommaInArrayInitializerTests.cs | 26 +++++++++++++++++++ 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/RefactoringEssentials/CSharp/Diagnostics/Synced/RedundanciesInCode/RedundantCommaInArrayInitializerCodeFixProvider.cs b/RefactoringEssentials/CSharp/Diagnostics/Synced/RedundanciesInCode/RedundantCommaInArrayInitializerCodeFixProvider.cs index b5c35994..aa05f32b 100644 --- a/RefactoringEssentials/CSharp/Diagnostics/Synced/RedundanciesInCode/RedundantCommaInArrayInitializerCodeFixProvider.cs +++ b/RefactoringEssentials/CSharp/Diagnostics/Synced/RedundanciesInCode/RedundantCommaInArrayInitializerCodeFixProvider.cs @@ -46,11 +46,15 @@ public async override Task RegisterCodeFixesAsync(CodeFixContext context) return; var redundantComma = node.Expressions.GetSeparator(elementCount - 1); + var newSeparatedExpList = new List(node.Expressions.GetWithSeparators().Where(t => t != redundantComma)); + var lastExp = newSeparatedExpList.Last(); + newSeparatedExpList.RemoveAt(newSeparatedExpList.Count - 1); + newSeparatedExpList.Add(lastExp.WithTrailingTrivia(redundantComma.TrailingTrivia)); + var newRoot = root.ReplaceNode( node, node - .WithExpressions(SyntaxFactory.SeparatedList(node.Expressions.ToArray())) - .WithAdditionalAnnotations(Formatter.Annotation)); + .WithExpressions(SyntaxFactory.SeparatedList(SyntaxFactory.NodeOrTokenList(newSeparatedExpList)))); context.RegisterCodeFix(CodeActionFactory.Create(node.Span, diagnostic.Severity, "Remove ','", document.WithSyntaxRoot(newRoot)), diagnostic); } diff --git a/Tests/CSharp/Diagnostics/RedundantCommaInArrayInitializerTests.cs b/Tests/CSharp/Diagnostics/RedundantCommaInArrayInitializerTests.cs index 0e4049f9..76e4d417 100644 --- a/Tests/CSharp/Diagnostics/RedundantCommaInArrayInitializerTests.cs +++ b/Tests/CSharp/Diagnostics/RedundantCommaInArrayInitializerTests.cs @@ -95,5 +95,31 @@ void TestMethod () }"; Analyze(input); } + + [Test] + public void TestPreserveTrivia() + { + Analyze(@" +class TestClass +{ + void TestMethod() + { + var a = new int[] { + 1, + 2$,$ + }; + } +}", @" +class TestClass +{ + void TestMethod() + { + var a = new int[] { + 1, + 2 + }; + } +}"); + } } }