Rewrite SyntaxNode to two SyntaxNodes

主宰稳场 提交于 2019-12-13 02:31:59

问题


I'm using Roslyn's CSharpSyntaxRewriter to rewrite the following:

string myString = "Hello ";
myString += "World!";

to:

string myString = "Hello ";
myString += "World!"; Log("myString", myString);

My syntax rewriter overrides VisitAssignmentExpression as follows.

public override SyntaxNode VisitAssignmentExpression(AssignmentExpressionSyntax node)
{
    //Construct a new node without trailing trivia
    var newNode = node.WithoutTrailingTrivia();
    InvocationExpressionSyntax invocation = //Build proper invocation

    //Now what? I need to bundle up newNode and invocation and return them
    //as an expression syntax
}

I have been able to "cheat" this limitation when dealing with StatementSyntax by constructing a BlockSyntax with missing braces:

var statements = new SyntaxList<StatementSyntax>();
//Tried bundling newNode and invocation together
statements.Add(SyntaxFactory.ExpressionStatement(newNode));
statements.Add(SyntaxFactory.ExpressionStatement(invocation));
var wrapper = SyntaxFactory.Block(statements);

//Now we can remove the { and } braces
wrapper = wrapper.WithOpenBraceToken(SyntaxFactory.MissingToken(SyntaxKind.OpenBraceToken))
    .WithCloseBraceToken(SyntaxFactory.MissingToken(SyntaxKind.CloseBraceToken)

However this approach won't work with AssignmentExpressionSyntax as BlockSyntax cannot be cast to ExpressionSyntax. (The CSharpSyntaxRewriter tries to make this cast.)

How can I rewrite one SyntaxNode into two SyntaxNodes?

Have I run up against a limitation of the API, or are there any tricks similar to the above that someone could share?


回答1:


You need to visit the parent ExpressionStatementSyntax and replace that with a BlockSyntax.

You cannot insert a BlockSyntax as an expression in an expression statement.



来源:https://stackoverflow.com/questions/28802121/rewrite-syntaxnode-to-two-syntaxnodes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!