Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How modify source code using Roslyn? [closed]

Tags:

c#

.net

roslyn

How using Roslyn modify source code? I can't create SyntaxNode and insert in SyntaxTree. Or use alternatives (Antrl, NRefactory or something else)?

like image 947
user3382135 Avatar asked Oct 20 '14 04:10

user3382135


2 Answers

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!

like image 157
Krzysztof Madej Avatar answered Sep 28 '22 06:09

Krzysztof Madej


You can create SyntaxNodes 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.

like image 44
svick Avatar answered Sep 28 '22 08:09

svick