There qutie a fiew ways to get the sematic model.
From a Document
class
Document document = ...;
SemanticModel semanticModel = await document.GetSemanticModelAsync();
From a Compilation
class
CSharpCompilation compilation = ...;
var semanticModel = await compilation.GetSemanticModel(syntaxTree);
From an AnalysisContext
. Fro example inside a DiagnosticAnalyzer
you can do:
public override void Initialize(AnalysisContext context)
{
context.RegisterSemanticModelAction(x =>
{
var semanticModel = x.SemanticModel;
// Do magical magic here.
});
}
var syntaxRoot = await document.GetSyntaxRootAsync();
var semanticModel = await document.GetSemanticModelAsync();
var sampleMethodInvocation = syntaxRoot
.DescendantNodes()
.OfType<InvocationExpressionSyntax>()
.First();
var sampleMethodSymbol = semanticModel.GetSymbolInfo(sampleMethodInvocation).Symbol;
var referencesToSampleMethod = await SymbolFinder.FindReferencesAsync(sampleMethodSymbol, document.Project.Solution);