How using Roslyn modify source code? I can't create SyntaxNode and insert in SyntaxTree. Or use alternatives (Antrl, NRefactory or something else)?
How svick answered you - you cannot modify existing syntax tree. Sytnax tree is immutable but you can create another one based on existing. For this purpose you have to create node and replace existing one. Below you can simple example (change using):
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 immutable here is a note from Getting started document:
A fundamental tenet of the Roslyn API is immutability. Because immutable data structures cannot be changed after they are created, they can be safely shared and analyzed by multiple consumers simultaneously without the dangers of one tool affecting another in unpredictable ways. No locks or other concurrency measures needed. This applies to syntax trees, compilations, symbols, semantic models, and every other data structure in the Roslyn API. Instead of modification, new objects are created based on specified differences to the old ones. You’ll apply this concept to syntax trees to create tree transformations!
You can create SyntaxNode
s using SyntaxFactory
.
And you can't modify an existing syntax tree (because it's immutable), but you can create a new one containing your node. Look at With-
and Add-
methods, ReplaceNode
and CSharpSyntaxVisitor
. It's hard to say which one of these fits your needs the most.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With