Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the open source released "roslyn" to read code file and generate new code files

Tags:

c#

roslyn

Where do I start?

in my current solution I have models like this:

public class MyAwesomeModel
{
 ....
}

I want to take the roslyn code project to parse the source files and go over the syntax trees to generate new code files. Take those source files and add them to a c# project file to import in my solution again in visual studio.

Where do I start. Cloning roslyn and just write a console app that reference all of roslyn and start digging into roslyn to find out how, or is there any blogs,documentatino that shows something like this.

like image 447
Poul K. Sørensen Avatar asked Apr 05 '14 10:04

Poul K. Sørensen


1 Answers

It was somewhat easy to do.

Create a console app and add reference to Microsoft.CodeAnalysis.CSharp in your project.

Here is the program that visited all properties in a source text:

using System;
using System.Collections.Generic;
using System.Text.Json;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;

class ModelCollector : CSharpSyntaxWalker
{
    public Dictionary<string, List<string>> Models { get; } = new Dictionary<string, List<string>>();
    public override void VisitPropertyDeclaration(PropertyDeclarationSyntax node)
    {
        var classnode = node.Parent as ClassDeclarationSyntax;
        if (!Models.ContainsKey(classnode.Identifier.ValueText))
        {
            Models.Add(classnode.Identifier.ValueText, new List<string>());
        }

        Models[classnode.Identifier.ValueText].Add(node.Identifier.ValueText);
    }
}

class Program
{
    static void Main()
    {
        var code = @"
                using System;
                using System.Collections.Generic;
                using System.Linq;
                using System.Text;

                namespace HelloWorld
                {
                    public class MyAwesomeModel
                    {
                        public string MyProperty {get;set;}
                        public int MyProperty1 {get;set;}
                    }

                }";

        var tree = CSharpSyntaxTree.ParseText(code);

        var root = (CompilationUnitSyntax)tree.GetRoot();
        var modelCollector = new ModelCollector();
        modelCollector.Visit(root);

        Console.WriteLine(JsonSerializer.Serialize(modelCollector.Models));
    }
}
like image 78
Poul K. Sørensen Avatar answered Sep 26 '22 03:09

Poul K. Sørensen