Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the semantic model from source in Roslyn

Tags:

c#

.net

roslyn

In all examples when using Roslyn, you have something like this:

SyntaxTree tree = CSharpSyntaxTree.ParseText(
@"using System;
using System.Collections.Generic;
using System.Text;

namespace HelloWorld
{
    // A whole program here...
}");

var root = (CompilationUnitSyntax)tree.GetRoot();

// Getting the semantic model (for MSCORELIB)
var compilation = CSharpCompilation.Create("HelloWorld")
                  .AddReferences(
                     MetadataReference.CreateFromFile(
                       typeof(object).Assembly.Location))
                  .AddSyntaxTrees(tree);
var model = compilation.GetSemanticModel(tree);

How to get the semantic model for my code?

The last piece of code retrieves the semantic model for mscorelib types: MetadataReference.CreateFromFile(typeof(object).Assembly.Location) so that I can inspect usings or other parts of the source and get symbol information.

But if I define types in HelloWorld and wanted to retrieve symbol info from those, I would the semantic model. But since I just loaded mscorelib I would not get this info.

How to load the semantic model for the source I just defined?

like image 509
Andry Avatar asked Nov 24 '16 07:11

Andry


1 Answers

static void Main(string[] args)
{
    SyntaxTree tree = CSharpSyntaxTree.ParseText(
        @"using System;

        namespace HelloWorld
        {
            public class MyType{public void MyMethod(){}}
        }"
    );

    var root = (CompilationUnitSyntax)tree.GetRoot();
    var compilation = CSharpCompilation.Create("HelloWorld")
                      .AddReferences(
                         MetadataReference.CreateFromFile(
                           typeof(object).Assembly.Location))
                      .AddSyntaxTrees(tree);
    var model = compilation.GetSemanticModel(tree);
    var myTypeSyntax = root.DescendantNodes().OfType<TypeDeclarationSyntax>().First();
    var myTypeInfo = model.GetDeclaredSymbol(myTypeSyntax);
    Console.WriteLine(myTypeInfo);
}

Is this what you need? myTypeInfo is a type I defined in HelloWorld and I can get is info.

Just to explain, semantic model is something you can get from compilation. Once you have a compilation, you can get all the info from this compilation. Not just from the added reference (mscorlib in your case).

like image 159
Dudi Keleti Avatar answered Sep 24 '22 18:09

Dudi Keleti