How do I get AttributeData from AttributeSyntax in Roslyn?
Asked Answered
A

2

8

Question as in the title.

From an object of type AttributeSyntax how can I get the related AttributeData representation in order to access the metadata?

Axiom answered 9/3, 2015 at 16:48 Comment(0)
J
10

You need to find the ISymbol that the syntax is applied to, call GetAttributes(), and find the returned AttributeData for which ApplicationSyntaxReference matches your AttributeSyntax.

Jochbed answered 9/3, 2015 at 19:8 Comment(2)
How do you get the ISymbol for attribute?Blocker
@Andez: The semantic model should have APIs to get the symbol for the AttributeSyntax. You can use the Syntax Tree Explorer to see which node & which API.Jochbed
T
4

@SLaks answer is correct. Here is some code to retrieve attributes from a AttributeListSyntax:

using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis;
using System.Collections.Generic;

static class Extensions
{
    public static IReadOnlyList<AttributeData> GetAttributes(this AttributeListSyntax attributes, Compilation compilation)
    {
        // Collect pertinent syntax trees from these attributes
        var acceptedTrees = new HashSet<SyntaxTree>();
        foreach (var attribute in attributes.Attributes)
            acceptedTrees.Add(attribute.SyntaxTree);

        var parentSymbol = attributes.Parent!.GetDeclaredSymbol(compilation)!;
        var parentAttributes = parentSymbol.GetAttributes();
        var ret = new List<AttributeData>();
        foreach (var attribute in parentAttributes)
        {
            if (acceptedTrees.Contains(attribute.ApplicationSyntaxReference!.SyntaxTree))
                ret.Add(attribute);
        }

        return ret;
    }

    public static ISymbol? GetDeclaredSymbol(this SyntaxNode node, Compilation compilation)
    {
        var model = compilation.GetSemanticModel(node.SyntaxTree);
        return model.GetDeclaredSymbol(node);
    }
}
Torey answered 27/9, 2022 at 13:0 Comment(1)
This doesn't work for assembly-level symbols. For those, use Compilation.Assembly.GetAttributes().Eyeleteer

© 2022 - 2024 — McMap. All rights reserved.