I have some problems adding an expression to SyntaxTree with Roslyn. I have to achieve the following: Whenever I find a special operator, I want to insert one or more expressions after this operator.
Let's say I want to insert the instruction "myVar = myVar + 1" after each statement that writes the variable "testVar".
So the following snippet:
a = 10; testVar = 50; a = testVar / a; testVar = a;
Should be turned into this piece of code:
a = 10; testVar = 50; myVar = myVar + 1; a = testVar / a; testVar = a; myVar = myVar + 1;
My current approach uses SyntaxVisitor using the "SyntaxNode VisitExpressionStatement (ExpressionStatement node)" method. This method visits all expressions in SyntaxTree and allows you to replace the invited expression with the returned SyntaxNode. However, I do not want to perform replacements , but add new expressions after them, which basically require the return of two expressions. The only solution I found was to use "BlockSyntax", which serves as a container for two expressions (see Code Snippet [0]). Unfortunately, "BlockSyntax" introduces curly braces, which lead to the following result:
a = 10; { testVar = 50; myVar = myVar + 1; } a = testVar / a; { testVar = a; myVar = myVar + 1; }
This approach is unacceptable to me because I do not want to manipulate areas. Is there a way to insert arbitrary expressions into my chosen place with Roslyn?
[0]
public SyntaxNode VisitExpressionStatement(ExpressionStatement node){ if(node has special characteristics){ var newExpression = ... var newStatmentList = new Roslyn.Compilers.CSharp.SyntaxList<StatementSyntax>(); newStatmentList = newStatmentList.Insert(newStatmentList.Count, node); newStatmentList = newStatmentList.Insert(newStatmentList.Count, newExpression); BlockSyntax newBlock = Syntax.Block(newStatmentList); return newBlock; } else { return node; } }
source share