Find all derived classes in a source generator

My source generator needs to find other classes that derive from the inspected class to know whether special code needs to be added. So far, I have only inspected the class to augment itself and followed references from there, like the type of class properties, but not any other classes that also exist in the project that uses the source generator. I can’t seem to find any methods or interfaces or web documentation for this. Is this even possible and how would that work?

I’m looking for something like this:

public static IEnumerable<string> GetDerivedTypes(this ITypeSymbol typeSymbol)
{
    // TODO: Find all available classes,
    // then I can proceed with inheritance checks and further tests
    // Following is made-up code:
    var derivedTypeNames = typeSymbol.ContainingAssembly.AllTypes
        .Where(t => t.IsDerivedFrom(typeSymbol))
        .Select(t => t.Name);
    return derivedTypeNames;
}

2

// Define your base class (e.g., Base)
var baseClassName = "Base";

// Create a SyntaxReceiver
var syntaxReceiver = new MySyntaxReceiver();

// Visit the syntax tree
syntaxReceiver.Visit(syntaxTree.GetRoot());

// Get the derived classes
var derivedClasses = syntaxReceiver.Classes
    .Where(classDeclaration =>
        classDeclaration.BaseList?.Types.Any(baseType =>
            baseType.ToString() == baseClassName) ?? false)
    .ToList();

or

// Create a semantic model
var semanticModel = compilation.GetSemanticModel(syntaxTree);

// Get the base class symbol
var baseClassSymbol = semanticModel.Compilation.GetTypeByMetadataName(baseClassName);

// Find derived types
var derivedTypes = semanticModel.Compilation.GetSymbolsWithName(
    name => name == baseClassName,
    SymbolFilter.Type)
    .SelectMany(symbol => symbol.ContainingAssembly.GlobalNamespace.GetNamespaceMembers())
    .SelectMany(namespaceSymbol => namespaceSymbol.GetTypeMembers())
    .Where(typeSymbol => typeSymbol.BaseType?.Equals(baseClassSymbol) ?? false)
    .ToList();

or
Finding all class declarations than inherit from another with Roslyn

To uncover details:

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

public class ClassSyntaxReceiver : ISyntaxReceiver
{
    public List<ClassDeclarationSyntax> Classes { get; } = new List<ClassDeclarationSyntax>();

    public void OnVisitSyntaxNode(SyntaxNode syntaxNode)
    {
        if (syntaxNode is ClassDeclarationSyntax classDeclaration)
        {
            Classes.Add(classDeclaration);
        }
    }
}

public class MySourceGenerator : ISourceGenerator // to use in the source generator
{
    public void Execute(GeneratorExecutionContext context)
    {
        var syntaxReceiver = (ClassSyntaxReceiver)context.SyntaxReceiver;
        var classes = syntaxReceiver.Classes;

        // Now you can process the list of classes as needed.
        // For example, you can check if each class derives from a specific base class.
    }

    // Other methods and implementation details...
}

In the Execute method, iterate through the collected classes and check if they derive from a specific base class (e.g., Base):

foreach (var classDeclaration in classes)
{
    var semanticModel = context.Compilation.GetSemanticModel(classDeclaration.SyntaxTree);
    var classSymbol = semanticModel.GetDeclaredSymbol(classDeclaration);

    if (classSymbol.BaseType?.Name == "Base")
    {
        // This class derives from the specified base class.
        // Add your custom logic here.
    }
}

Roslyn, how to get all Classes

Roslyn’s SyntaxReceiver – Get Classes Implementing Interface

4

I found out how this works. The answer from rotabor had a hint hidden in it somewhere. I could build the solution to the described problem around that line, after more try and error.

public static string [] GetDerivedTypes(this ITypeSymbol typeSymbol)
{
    var derivedTypes = GetAllTypes(typeSymbol.ContainingAssembly.GlobalNamespace)
        .Where(t => IsDerivedFrom(t, typeSymbol));
    return derivedTypes
        .Select(dt => dt.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat))
        .ToArray();

    static IEnumerable<INamedTypeSymbol> GetAllTypes(INamespaceSymbol nsSymbol) =>
        nsSymbol.GetTypeMembers()
            .Concat(nsSymbol.GetNamespaceMembers().SelectMany(GetAllTypes));

    static bool IsDerivedFrom(ITypeSymbol typeSymbol, ITypeSymbol baseTypeSymbol) =>
        typeSymbol.BaseType != null &&
        (typeSymbol.BaseType.Equals(baseTypeSymbol, SymbolEqualityComparer.Default) ||
            IsDerivedFrom(typeSymbol.BaseType, baseTypeSymbol));
}

The local helper function GetAllTypes recursively finds all types in all namespaces for the assembly. This will not find derived types in other assemblies, I can live with this limitation. Is it efficient? I can’t tell.

The other local helper function IsDerivedFrom then determines whether a type is derived from a base type, possibly transitively. This is also done in a recursive way. It is used to filter the set of all types in the assembly so that only derivations of the specified type remain.

I took some inspiration from functional programming here and I think it fits nicely.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa

Find all derived classes in a source generator

My source generator needs to find other classes that derive from the inspected class to know whether special code needs to be added. So far, I have only inspected the class to augment itself and followed references from there, like the type of class properties, but not any other classes that also exist in the project that uses the source generator. I can’t seem to find any methods or interfaces or web documentation for this. Is this even possible and how would that work?

I’m looking for something like this:

public static IEnumerable<string> GetDerivedTypes(this ITypeSymbol typeSymbol)
{
    // TODO: Find all available classes,
    // then I can proceed with inheritance checks and further tests
    // Following is made-up code:
    var derivedTypeNames = typeSymbol.ContainingAssembly.AllTypes
        .Where(t => t.IsDerivedFrom(typeSymbol))
        .Select(t => t.Name);
    return derivedTypeNames;
}

2

// Define your base class (e.g., Base)
var baseClassName = "Base";

// Create a SyntaxReceiver
var syntaxReceiver = new MySyntaxReceiver();

// Visit the syntax tree
syntaxReceiver.Visit(syntaxTree.GetRoot());

// Get the derived classes
var derivedClasses = syntaxReceiver.Classes
    .Where(classDeclaration =>
        classDeclaration.BaseList?.Types.Any(baseType =>
            baseType.ToString() == baseClassName) ?? false)
    .ToList();

or

// Create a semantic model
var semanticModel = compilation.GetSemanticModel(syntaxTree);

// Get the base class symbol
var baseClassSymbol = semanticModel.Compilation.GetTypeByMetadataName(baseClassName);

// Find derived types
var derivedTypes = semanticModel.Compilation.GetSymbolsWithName(
    name => name == baseClassName,
    SymbolFilter.Type)
    .SelectMany(symbol => symbol.ContainingAssembly.GlobalNamespace.GetNamespaceMembers())
    .SelectMany(namespaceSymbol => namespaceSymbol.GetTypeMembers())
    .Where(typeSymbol => typeSymbol.BaseType?.Equals(baseClassSymbol) ?? false)
    .ToList();

or
Finding all class declarations than inherit from another with Roslyn

To uncover details:

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

public class ClassSyntaxReceiver : ISyntaxReceiver
{
    public List<ClassDeclarationSyntax> Classes { get; } = new List<ClassDeclarationSyntax>();

    public void OnVisitSyntaxNode(SyntaxNode syntaxNode)
    {
        if (syntaxNode is ClassDeclarationSyntax classDeclaration)
        {
            Classes.Add(classDeclaration);
        }
    }
}

public class MySourceGenerator : ISourceGenerator // to use in the source generator
{
    public void Execute(GeneratorExecutionContext context)
    {
        var syntaxReceiver = (ClassSyntaxReceiver)context.SyntaxReceiver;
        var classes = syntaxReceiver.Classes;

        // Now you can process the list of classes as needed.
        // For example, you can check if each class derives from a specific base class.
    }

    // Other methods and implementation details...
}

In the Execute method, iterate through the collected classes and check if they derive from a specific base class (e.g., Base):

foreach (var classDeclaration in classes)
{
    var semanticModel = context.Compilation.GetSemanticModel(classDeclaration.SyntaxTree);
    var classSymbol = semanticModel.GetDeclaredSymbol(classDeclaration);

    if (classSymbol.BaseType?.Name == "Base")
    {
        // This class derives from the specified base class.
        // Add your custom logic here.
    }
}

Roslyn, how to get all Classes

Roslyn’s SyntaxReceiver – Get Classes Implementing Interface

4

I found out how this works. The answer from rotabor had a hint hidden in it somewhere. I could build the solution to the described problem around that line, after more try and error.

public static string [] GetDerivedTypes(this ITypeSymbol typeSymbol)
{
    var derivedTypes = GetAllTypes(typeSymbol.ContainingAssembly.GlobalNamespace)
        .Where(t => IsDerivedFrom(t, typeSymbol));
    return derivedTypes
        .Select(dt => dt.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat))
        .ToArray();

    static IEnumerable<INamedTypeSymbol> GetAllTypes(INamespaceSymbol nsSymbol) =>
        nsSymbol.GetTypeMembers()
            .Concat(nsSymbol.GetNamespaceMembers().SelectMany(GetAllTypes));

    static bool IsDerivedFrom(ITypeSymbol typeSymbol, ITypeSymbol baseTypeSymbol) =>
        typeSymbol.BaseType != null &&
        (typeSymbol.BaseType.Equals(baseTypeSymbol, SymbolEqualityComparer.Default) ||
            IsDerivedFrom(typeSymbol.BaseType, baseTypeSymbol));
}

The local helper function GetAllTypes recursively finds all types in all namespaces for the assembly. This will not find derived types in other assemblies, I can live with this limitation. Is it efficient? I can’t tell.

The other local helper function IsDerivedFrom then determines whether a type is derived from a base type, possibly transitively. This is also done in a recursive way. It is used to filter the set of all types in the assembly so that only derivations of the specified type remain.

I took some inspiration from functional programming here and I think it fits nicely.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật