mostlytech
mostlytech

Reputation: 814

Finding attributes on base type

I'm trying to implement an ICodeIssueProvider to detect if a class (or one of its base types) has a certain attribute or not.

public IEnumerable<CodeIssue> GetIssues(IDocument document,
        CommonSyntaxNode node,
        CancellationToken cancellationToken)
    {
        var methodDeclaration = (MethodDeclarationSyntax)node;
        var semanticModel = document.GetSemanticModel(cancellationToken);

        var methodSymbol = semanticModel.GetDeclaredSymbol(methodDeclaration);
        var typeSymbol = methodSymbol.ContainingType;

        // The following only gets attributes declared on this class, how to
        // also include those declared on a base class ?
        var attributes = typeSymbol.GetAttributes();

Is there a better way than walking up typeSymbol.BaseType all the way to System.Object and calling GetAttributes() on the way?

Also, is there a better way to check if a typeSymbol derives from a specific class than walking up .BaseType and checking manually

(And yes, there is a reason not apparent from the sample below for checking MethodDeclarationSyntax nodes and not ClassDeclarationSyntax nodes)

Upvotes: 4

Views: 718

Answers (1)

Dr Rob Lang
Dr Rob Lang

Reputation: 6883

tldr; No, there is no single method call to do this (as of Sept 2012 CTP Roslyn).

The parent classes you need to search may be (and usually is) a completely separate Syntax Tree to the class you are in. If all your classes were within a single namespace declaration (shudder) then you could search from that SyntaxNode root.

Chances are, your classes are one-per-file, so although they share the same namespace, they're not under the same Syntax Tree root.

Roslyn causes much head-scratching because the Syntax Trees are more akin to the layout of the code files rather than the types the code represents.

There might be a way of creating a new Syntax Tree (existing Syntax Trees are immutable) out of all the classes that exist under that namsepace and then search that tree. To me, that feel like way more complexity than needed, especially as a walking-up-parents method is far more maintainable.

Upvotes: 1

Related Questions