Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Roslyn to get compile time constant value

I have some example code that simplifies want I am trying to accomplish.

OptionAtrribute.cs

using System;
public class OptionAttribute : Attribute
{
    public OptionAttribute(string option)
    {
        this.PickedOption = option;
    }

    public string PickedOption { get; private set; }
}

Options.cs

using System;
public class Options
{
    public const string Cat = "CT";
    public const string Dog = "DG";
    public const string Monkey = "MNKY";
}

SomeClass.cs

using System;
[Option(Options.Dog)]
public class SomeClass
{

}

How can I get the "OptionAttribute" on the "SomeClass" class and get the "PickedOption" Value?

Update

I am not asking how to use reflection. This is a for generating code when the file that holds the code is saved. I don't have a updated dll at this point so reflection would not work I am trying to use Roslyn to parse the actually file. Below is what I had tries

string solutionPath = @"C:\Project\Project.sln";
var msWorkspace = MSBuildWorkspace.Create();

var solution = await msWorkspace.OpenSolutionAsync(solutionPath);
var project = solution.Projects.FirstOrDefault(p => p.Name == "Project1");
var compilation = await project.GetCompilationAsync();

var document = project.Documents.FirstOrDefault(d => d.Name == "Code.cs");

SyntaxTree syntaxTree = null;
document.TryGetSyntaxTree(out syntaxTree);
var semanticModel = compilation.GetSemanticModel(syntaxTree);

var commandCategoryAttribute = compilation.GetTypeByMetadataName("Project1.OptionAttribute");
var classDeclaration = syntaxTree.GetRoot().DescendantNodes().OfType<ClassDeclarationSyntax>().Skip(2).FirstOrDefault();
var classSymbol = semanticModel.GetDeclaredSymbol(classDeclaration);
var attrSymbol = classSymbol.GetAttributes().FirstOrDefault(a => a.AttributeClass.MetadataName == commandCategoryAttribute.MetadataName);     
var attrSyntax = classDeclaration.AttributeLists.FirstOrDefault().Attributes.FirstOrDefault();

My Solution

I got it working!

public void Test()
{
    string solutionPath = @"C:\Project\Project.sln";
    var msWorkspace = MSBuildWorkspace.Create();
    var solution = msWorkspace.OpenSolutionAsync(solutionPath).Result;
    var project = solution.Projects.FirstOrDefault(p => p.Name == "Project1");
    var compilation = project.GetCompilationAsync().Result;

    var document = project.Documents.FirstOrDefault(d => d.Name == "SomeClass.cs");
    SyntaxTree syntaxTree = null;
    document.TryGetSyntaxTree(out syntaxTree);
    SemanticModel semanticModel = compilation.GetSemanticModel(syntaxTree);


    ClassDeclarationSyntax classDeclaration = syntaxTree.GetRoot().DescendantNodes().OfType<ClassDeclarationSyntax>().FirstOrDefault();
    var attr = classDeclaration.AttributeLists.SelectMany(a => a.Attributes).FirstOrDefault(a => a.Name.ToString() == "Option");


    var exp = attr.ArgumentList.Arguments.First().Expression;
    string value = null;
    var mem = exp as MemberAccessExpressionSyntax;
    if (mem != null)
    {
        value = ResolveMemberAccess(mem, solution, compilation)?.ToString();
    }
    else
    {
        var lit = exp as LiteralExpressionSyntax;
        if (lit != null)
        {
            value = semanticModel.GetConstantValue(lit).Value?.ToString();
        }
    }
}
public object ResolveMemberAccess(MemberAccessExpressionSyntax memberSyntax, Solution solution, Compilation compilation)
{
    var model = compilation.GetSemanticModel(memberSyntax.SyntaxTree);
    var memberSymbol = model.GetSymbolInfo(memberSyntax).Symbol;
    var refs = SymbolFinder.FindReferencesAsync(memberSymbol, solution).Result.FirstOrDefault();

    if (refs != null)
    {
        var defSyntax = refs.Definition.DeclaringSyntaxReferences.First();
        var parent = compilation.GetSemanticModel(defSyntax.SyntaxTree);
        var syn = defSyntax.GetSyntax();

        var literal = syn.DescendantNodes().OfType<LiteralExpressionSyntax>().FirstOrDefault();
        if (literal != null)
        {
            var val = parent.GetConstantValue(literal);
            return val.Value;
        }
        else
        {
            var memberAccess = syn.DescendantNodes().OfType<MemberAccessExpressionSyntax>().FirstOrDefault();
            if (memberAccess != null)
            {
                return ResolveMemberAccess(memberAccess, solution, compilation);
            }
        }
    }
    return null;
}

Thanks!

like image 288
jon antoine Avatar asked Feb 27 '16 13:02

jon antoine


1 Answers

Sounds to me as if you're pretty close actually. Consider adding this to your code:

attrSyntax.ArgumentList.Arguments.First().Expression.ToString()

This will neatly return

Options.Dog

So you know you have that info available. If you change it up a little bit to for example this:

var expression = attrSyntax.ArgumentList.Arguments.First().Expression as MemberAccessExpressionSyntax;
expression.Name.Identifier.ValueText.Dump();

You get as output

Dog

However, if you want the actual value it points to you can do this:

var x = classDeclaration.AttributeLists.First().Attributes.First().ArgumentList.Arguments.First();
semanticModel.GetConstantValue(x.Expression).Value.Dump();

This will output

DG

like image 123
Jeroen Vannevel Avatar answered Oct 12 '22 00:10

Jeroen Vannevel