As for a learning experience for defining a Roslyn Analyzer rule, let's say I have interfaces defined like
//These are a marker interfaces.
public interface ISomethingRoot1 {}
public interface ISomethingRoot2 {}
public interface ISomething: ISomethingRoot1
{
int SomeOperation();
}
public interface ISomething2: ISomethingRoot2
{
int SomeOperation2();
}
How could I check function signatures of all the interfaces (maybe even classes that implement these interfaces and classes that inherit from the implementing classes, but that's secondary now) that inherit from the marker interfaces ISomethingRoot1
and ISomethingRoot2
? I see there is at least one question related to this Finding all class declarations than inherit from another with Roslyn, but I haven't got the hang of it. It looks like I should register to SymbolKind.NamedType
actions, but what would the AnalyzeSymbol
part look like to find the function signatures inheriting from ISomethingRoot1
and ISomethingRoot2
?
Here is some code I'm doing currently to make the question more clear:
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public class PublicInterfaceAnalyzer: DiagnosticAnalyzer
{
private static ImmutableArray<DiagnosticDescriptor> SupportedRules { get; } =
new ImmutableArray<DiagnosticsDescriptor>(new DiagnosticDescriptor(id: "CheckId1",
title: "Check1",
messageFormat: "Placeholder text",
category: "Usage",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true));
public override void Initialize(AnalysisContext context)
{
context.RegisterSymbolAction(AnalyzeSymbol, SymbolKind.NamedType);
}
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => SupportedRules;
private void AnalyzeSymbol(SymbolAnalysisContext context)
{
//How to check that the functions have, say, a certain kind of
//of a return value or parameters or naming? I think I know how
//to do that, but I'm not sure how to get a hold of the correct
//interfaces and have a collection or their (public) methods to check.
//This could be one way to go, but then in Initialize
//should be "SymbolKind.Method", would that be the route to take?
//The following omits the code to get the interfaces and do some
//of the checks as this is code in progress and the main problem
//is getting hold of the function signatures of interfaces that
//inherit from the marker interfaces.
var symbol = (IMethodSymbol)context.Symbol;
context.ReportDiagnostic(Diagnostic.Create(SupportedRules[0], symbol.Locations[0], symbol.Name));
}
}