Andry Andry - 13 days ago 5
C# Question

How to get the semantic model from source in 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
using
s 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?

Answer
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).