How to change the source code using Roslyn?

How to use Roslyn to change the source code? I can not create SyntaxNode and paste into SyntaxTree. Or use alternatives (Antrl, NRefactory or something else)?

+5
source share
2 answers

You can create SyntaxNode with SyntaxFactory .

And you cannot change the existing syntax tree (because it is immutable), but you can create a new one containing your node. Take a look at the With- and Add- , ReplaceNode and CSharpSyntaxVisitor . It’s hard to say which one is best for your needs.

+3
source

As svick answered you, you cannot modify an existing syntax tree. The Sytnax tree is immutable, but you can create another based on the existing one. To do this, you need to create a node and replace the existing one. Below you can use a simple example (change):

 var name = Syntax.QualifiedName(Syntax.IdentifierName("System"), Syntax.IdentifierName("Collections")); name = Syntax.QualifiedName(name, Syntax.IdentifierName("Generic")); SyntaxTree tree = SyntaxTree.ParseText( @"using System; using System.Collections; using System.Linq; using System.Text; namespace HelloWorld { class Program { static void Main(string[] args) { Console.WriteLine(""Hello, World!""); } } }"); var root = (CompilationUnitSyntax)tree.GetRoot(); var oldUsing = root.Usings[1]; var newUsing = oldUsing.WithName(name); root = root.ReplaceNode(oldUsing, newUsing); Console.WriteLine(root.GetText()); 

In case of invariance, there is a note from the document Getting Started:

The underlying principle of the Roslyn API is immutability. Since immutable data structures cannot be changed after they are created, they can be safely shared and analyzed by several consumers at the same time without the risk that one tool will affect the other in an unpredictable way. No locks or other concurrency measures are required. This applies to syntax trees, compilation, symbols, semantic models, and every other data structure in the Roslyn API. Instead of modification, new objects are created based on the given differences with the old ones. You apply this concept to syntax trees to create tree transformations!

+2
source

Source: https://habr.com/ru/post/1205068/


All Articles