Rewrite SyntaxNode to two SyntaxNodes values

I am using Roslyn CSharpSyntaxRewriter to rewrite the following:

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

in

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

My syntactic 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 was able to "trick" this restriction when working with StatementSyntax by building BlockSyntax with missing curly 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 will not work with AssignmentExpressionSyntax , since BlockSyntax cannot be attributed to ExpressionSyntax . ( CSharpSyntaxRewriter is trying to do this. )

How can I rewrite one SyntaxNode to two SyntaxNodes?

Am I facing an API restriction, or are there any tricks like the above that anyone could share?

+1
source share
1 answer

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

You cannot insert a BlockSyntax expression into an expression in an expression.

+1
source

All Articles