提交 94472bf2 编写于 作者: C CyrusNajmabadi

Preserve trivia

上级 e59176f7
......@@ -431,5 +431,39 @@ void M()
}
}");
}
[WorkItem(15957, "https://github.com/dotnet/roslyn/issues/15957")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)]
public async Task TestTrivia1()
{
await TestAsync(
@"class C
{
void M(object y)
{
if (y != null)
{
}
[|var|] x = o as string;
if (x != null)
{
}
}
}",
@"class C
{
void M(object y)
{
if (y != null)
{
}
if (o is string x)
{
}
}
}", compareTokens: false);
}
}
}
\ No newline at end of file
......@@ -57,26 +57,29 @@ public override Task RegisterCodeFixesAsync(CodeFixContext context)
var localDeclaration = (LocalDeclarationStatementSyntax)localDeclarationLocation.FindNode(cancellationToken);
var ifStatement = (IfStatementSyntax)ifStatementLocation.FindNode(cancellationToken);
var condition = (BinaryExpressionSyntax)conditionLocation.FindNode(cancellationToken);
var conditionPart = (BinaryExpressionSyntax)conditionLocation.FindNode(cancellationToken);
var asExpression = (BinaryExpressionSyntax)asExpressionLocation.FindNode(cancellationToken);
var updatedCondition = SyntaxFactory.IsPatternExpression(
var updatedConditionPart = SyntaxFactory.IsPatternExpression(
asExpression.Left, SyntaxFactory.DeclarationPattern(
((TypeSyntax)asExpression.Right).WithoutTrivia(),
SyntaxFactory.SingleVariableDesignation(
localDeclaration.Declaration.Variables[0].Identifier.WithoutTrivia())));
var trivia = localDeclaration.GetLeadingTrivia().Concat(localDeclaration.GetTrailingTrivia())
.Where(t => t.IsSingleOrMultiLineComment())
.SelectMany(t => ImmutableArray.Create(t, SyntaxFactory.ElasticCarriageReturnLineFeed))
.ToImmutableArray();
var finalCondition = ifStatement.Condition.ReplaceNode(conditionPart, updatedConditionPart);
var updatedIfStatement = ifStatement.ReplaceNode(condition, updatedCondition)
.WithPrependedLeadingTrivia(trivia)
.WithAdditionalAnnotations(Formatter.Annotation);
editor.RemoveNode(localDeclaration);
editor.ReplaceNode(ifStatement, updatedIfStatement);
// Keep the trivia on the node we're removing. But format the next statement so
// they look ok when they move to it.
var removeOptions = localDeclaration.GetTrailingTrivia().Any(t => t.IsRegularOrDocComment())
? SyntaxRemoveOptions.KeepLeadingTrivia | SyntaxRemoveOptions.KeepTrailingTrivia
: SyntaxRemoveOptions.KeepLeadingTrivia;
editor.RemoveNode(localDeclaration, removeOptions);
editor.ReplaceNode(ifStatement, (i, g) =>
{
var currentIf = (IfStatementSyntax)i;
var updatedIf = currentIf.ReplaceNode(currentIf.Condition, finalCondition);
return updatedIf.WithAdditionalAnnotations(Formatter.Annotation);
});
}
private class MyCodeAction : CodeAction.DocumentChangeAction
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册