c# - Roslyn Get Method Declaration from Invokation -


i'm making roslyn demo generating compiler warnings attributes

i have analyzer analyze method invocations looks so:

public override void initialize(analysiscontext context) {     context.registersyntaxnodeaction(analyzerinvocation, syntaxkind.invocationexpression); }  private static void analyzerinvocation(syntaxnodeanalysiscontext context) {     var invocation = (invocationexpressionsyntax)context.node; } 

i'm trying figure out how method declaration, know can use symbolfinder search method declaration

var model = compilation.getsemanticmodel(tree);  //looking @ first method symbol var methodsyntax = tree.getroot().descendantnodes().oftype<methoddeclarationsyntax>()    .first(/*todo: execute find related symbol */); 

this options expensive , annoying, , leaves open possiblity error because if invoking method coming assembly.

what easiest way method declaration invocationexpressionsyntax? should using symbol finder , if fails use scour imported assemblies or there easier better way?

if need declaration of method calling, can follows.

in first step, find out method is being called:

var methodsymbol = context     .semanticmodel     .getsymbolinfo(invocation, context.cancellationtoken)     .symbol imethodsymbol; 

remember there various reasons why methodsymbol may null (e.g. invoking delegate, not method), test that.

then can find declaring syntax references, , take first one:

var syntaxreference = methodsymbol     .declaringsyntaxreferences     .firstordefault(); 

this can null well, e.g. when calling method assembly, test that.

finally:

var declaration = syntaxreference.getsyntax(context.cancellationtoken); 

that gives syntax. should need semantic model declaration, can using

var semanticmodel = context.compilation.getsemanticmodel(declaration.syntaxtree); 

Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -