我正在编写一个代码分析器,用于反转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;
}