Hamza
Hamza

Reputation: 440

How to get the class identifier from object instantiation using Roslyn

I'm trying to create an analyzer that will find where each method invocation comes from especially the class where the method is defined.

let's assume we have the following code:

 Movie myMovie = new Movie();
 myMovie.Rent();

my analyzer till now can return the expression myMovie.Rent() as ExpressionSyntax

What exactly I want, is where the analyzer found a method invocation using an object in this case myMovie.Rent(), returns the class where the method is defined and the object is instantiated in this case is Movie.

I'm blocked that why I didn't write any code for it if you have any idea or code example, I appreciate it.

Upvotes: 0

Views: 1030

Answers (1)

Amin
Amin

Reputation: 129

First of all, in your analyzer class, inside the Initialize method you should register the syntax node action:

public override void Initialize(AnalysisContext context)
{
    context.RegisterSyntaxNodeAction(SyntaxNodeAnalyze, SyntaxKind.InvocationExpression);
}

In this method, we registered SyntaxNodeAnalyze method to get callbacks from the analyzer. Inside this method, by using the 'SyntaxNodeAnalysisContext' we can query information about the semantic objects. In the following sample, I used SemanticModel to be able to enumerate the custom attributes that I was declared and now, I used them above the method declaration.

private static void SyntaxNodeAnalyze(SyntaxNodeAnalysisContext context)
{
    SemanticModel semanticModel = context.SemanticModel;
    InvocationExpressionSyntax method = (InvocationExpressionSyntax)context.Node;

    var info = semanticModel.GetSymbolInfo(method).Symbol;
    if (info == null)
         return new List<AttributeData>();

    var attribs = info.GetAttributes().Where(f => f.AttributeClass.MetadataName.Equals(typeof(ThrowsExceptionAttribute).Name));

    foreach (var attrib in attribs)
    {
        ...
    }            
}

As you can see in the above code, we can gather useful information by using the GetSymbolInfo method of the 'SemanticModel'. You can use this method to get information about Methods, Properties and other semantic objects.

Upvotes: 1

Related Questions