Skip to content

Commit 182cede

Browse files
committed
Fixed FixAll issue in SA1516CodeFixProvider
1 parent ad639a8 commit 182cede

1 file changed

Lines changed: 13 additions & 8 deletions

File tree

StyleCop.Analyzers/StyleCop.Analyzers.CodeFixes/LayoutRules/SA1516CodeFixProvider.cs

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -87,16 +87,18 @@ private static Task<Document> GetTransformedDocumentAsync(Document document, Syn
8787
return Task.FromResult(document);
8888
}
8989

90-
SyntaxNode newNode = ProcessNode(node, insertBlankLine);
91-
var newSyntaxRoot = syntaxRoot.ReplaceNode(node, newNode);
90+
// Using the token replacement here to use the same strategy as the FixAll.
91+
var firstToken = node.GetFirstToken();
92+
var newToken = ProcessToken(firstToken, insertBlankLine);
93+
var newSyntaxRoot = syntaxRoot.ReplaceToken(firstToken, newToken);
9294
var newDocument = document.WithSyntaxRoot(newSyntaxRoot);
9395

9496
return Task.FromResult(newDocument);
9597
}
9698

97-
private static SyntaxNode ProcessNode(SyntaxNode node, bool insertBlankLine)
99+
private static SyntaxToken ProcessToken(SyntaxToken token, bool insertBlankLine)
98100
{
99-
var leadingTrivia = node.GetLeadingTrivia();
101+
var leadingTrivia = token.LeadingTrivia;
100102
SyntaxTriviaList newLeadingTrivia;
101103

102104
if (insertBlankLine)
@@ -108,7 +110,7 @@ private static SyntaxNode ProcessNode(SyntaxNode node, bool insertBlankLine)
108110
newLeadingTrivia = leadingTrivia.WithoutBlankLines();
109111
}
110112

111-
return node.WithLeadingTrivia(newLeadingTrivia);
113+
return token.WithLeadingTrivia(newLeadingTrivia);
112114
}
113115

114116
private static SyntaxNode GetRelevantNode(SyntaxNode innerNode)
@@ -164,7 +166,8 @@ protected override async Task<SyntaxNode> FixAllInDocumentAsync(FixAllContext fi
164166

165167
var syntaxRoot = await document.GetSyntaxRootAsync().ConfigureAwait(false);
166168

167-
Dictionary<SyntaxNode, SyntaxNode> replaceMap = new Dictionary<SyntaxNode, SyntaxNode>();
169+
// Using token replacement, because node replacement will do nothing when replacing child nodes from a replaced parent node.
170+
Dictionary<SyntaxToken, SyntaxToken> replaceMap = new Dictionary<SyntaxToken, SyntaxToken>();
168171

169172
foreach (var diagnostic in diagnostics)
170173
{
@@ -179,11 +182,13 @@ protected override async Task<SyntaxNode> FixAllInDocumentAsync(FixAllContext fi
179182

180183
if (node != null)
181184
{
182-
replaceMap[node] = ProcessNode(node, insertBlankLine.Value);
185+
var firstToken = node.GetFirstToken();
186+
187+
replaceMap[firstToken] = ProcessToken(firstToken, insertBlankLine.Value);
183188
}
184189
}
185190

186-
return syntaxRoot.ReplaceNodes(replaceMap.Keys, (original, rewritten) => replaceMap[original]);
191+
return syntaxRoot.ReplaceTokens(replaceMap.Keys, (original, rewritten) => replaceMap[original]);
187192
}
188193
}
189194
}

0 commit comments

Comments
 (0)