Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Roslyn API, Reading a .cs file, updating a class, writing back to .cs file

Tags:

c#

roslyn

I have this working code that will load a .cs file into the Roslyn SyntaxTree class, create a new PropertyDeclarationSyntax, insert it into the class, and re-write the .cs file. I'm doing this as a learning experience as well as some potential future ideas. I found that there doesn't really seem to be a full Roslyn API documentation anywhere and I'm unsure if I am doing this efficiently. My main concern is where I call 'root.ToFullString()' - whilst it works, is this the right way to do it?

using System.IO;
using System.Linq;
using Roslyn.Compilers;
using Roslyn.Compilers.CSharp;

class RoslynWrite
{
    public RoslynWrite()
    {
        const string csFile = "MyClass.cs";

        // Parse .cs file using Roslyn SyntaxTree
        var syntaxTree = SyntaxTree.ParseFile(csFile);
        var root = syntaxTree.GetRoot();
        // Get the first class from the syntax tree
        var myClass = root.DescendantNodes().OfType<ClassDeclarationSyntax>().First();

        // Create a new property : 'public bool MyProperty { get; set; }'
        var myProperty = Syntax.PropertyDeclaration(Syntax.ParseTypeName("bool"), "MyProperty")
                            .WithModifiers(Syntax.Token(SyntaxKind.PublicKeyword))
                            .WithAccessorList(
                            Syntax.AccessorList(Syntax.List(
                                Syntax.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration)
                                    .WithSemicolonToken(Syntax.Token(SyntaxKind.SemicolonToken)),
                                Syntax.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration)
                                    .WithSemicolonToken(Syntax.Token(SyntaxKind.SemicolonToken)))));

        // Add the new property to the class
        var updatedClass = myClass.AddMembers(myProperty);
        // Update the SyntaxTree and normalize whitespace 
        var updatedRoot = root.ReplaceNode(myClass, updatedClass).NormalizeWhitespace();

        // Is this the way to write the syntax tree? ToFullString?
        File.WriteAllText(csFile, updatedRoot.ToFullString());
    }
}
like image 813
ShaunO Avatar asked Aug 18 '13 04:08

ShaunO


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr. Stroustroupe.

Is C language easy?

C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.

What is C language?

C is an imperative procedural language supporting structured programming, lexical variable scope, and recursion, with a static type system. It was designed to be compiled to provide low-level access to memory and language constructs that map efficiently to machine instructions, all with minimal runtime support.


1 Answers

Answered on the Roslyn CTP forum in this post:

That approach is generally fine, though if you are worried about allocating a string for the text of the entire file, you should probably use IText.Write(TextWriter) instead of ToFullString().

Keep in mind that it's possible to generate trees that will not round-trip through the parser. For example, if you generated something that violates precedence rules, the SyntaxTree construction APIs won't catch that.

like image 198
Kevin Pilch Avatar answered Oct 25 '22 00:10

Kevin Pilch