Roslyn在指定节点后插入节点

4
我正在编写一个代码分析器,用于反转if语句以减少嵌套。我已能够生成一个新的if节点并将其替换为文档根。但是,我必须将所有来自该if语句的内容(语句)移动到其下方。让我展示一下我目前已经实现的内容:
var ifNode = @if;
var ifStatement = @if.Statement as BlockSyntax;
var returnNode = (ifNode.Parent as BlockSyntax).Statements.Last() as ReturnStatementSyntax ?? SyntaxFactory.ReturnStatement();
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var invertedIf = ifNode.WithCondition(Negate(ifNode.Condition, semanticModel, cancellationToken))
.WithStatement(returnNode)                
.WithAdditionalAnnotations(Formatter.Annotation);
var root = await document.GetSyntaxRootAsync(cancellationToken);
var newRoot = root.ReplaceNode(ifNode, invertedIf);
newRoot = newRoot.InsertNodesAfter(invertedIf, ifStatement.Statements); //It seems no to be working. There's no code after specified node.

return document.WithSyntaxRoot(newRoot);

之前:

public int Foo()
{
    if (true)
    {
        var a = 3;
        return a;
     }

     return 0;
}

之后:

public int Foo()
{
    if (false)
        return 0;

    var a = 3;
    return a;
}

你想实现什么可能有点难(也许只是对我而言)看清楚。你能提供一下你想要实现的前后效果吗? - JoshVarty
正如@JoshVarty所问,这里有一个关于before/after的例子。 - gandarez
你是如何使用 @If 语法的? - MHGameWork
1个回答

2
Carlos,问题在于你进行ReplaceNode后生成了一个新节点。当你执行InsertNodeAfter并传递原始根节点中的一个节点时,新节点无法找到它。
在分析器中,您需要一次性完成所有更改,或注释或跟踪节点,以便稍后可以返回它们。
但是由于你首先替换了一个节点,所以新节点将恰好处于同一位置。因此,你可以使用快捷方式FindNode,就像这样:
newRoot = newRoot.InsertNodesAfter(newRoot.FindNode(ifNode.Span), ifStatement.Statements);

我还没有测试这段代码,但应该可以正常工作。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接