Skip to content

[API Proposal]: ForTypesWithDirectBaseTypeOrInterface #68999

@Youssef1313

Description

@Youssef1313

Background and Motivation

It's a common scenario that source generators need to generate code for a type that inherits or implements an interface.

This scenario itself is divided into two scenarios:

  • Direct inheritance
  • Indirect inheritance

There might not be any way for the latter to be implemented efficiently, so this proposal is only about the former case (direct inheritance).

I believe it's possible to implement this API efficiently, though it's a non-trivial for generator authors to do. Besides that, the implementation inside the compiler could be more efficient as it could access some internals :)

Proposed API

namespace Microsoft.CodeAnalysis
{
     public struct SyntaxValueProvider
     {
+        public IncrementalValuesProvider<T> ForTypesWithDirectBaseTypeOrInterface<T>(string fullyQualifiedMetadataName, Func<BaseTypeDeclarationSyntax, CancellationToken, bool> predicate, Func<BaseTypeSyntaxContext, CancellationToken, T> transform);
     }

The BaseTypeSyntaxContext would be like this:

public readonly struct GeneratorAttributeSyntaxContext
{
    /// <summary>
    /// The syntax node for the declaration with the target base type
    /// </summary>
    public BaseTypeDeclarationSyntax TargetNode { get; }
 
    /// <summary>
    /// The symbol that has the requested base type or interface
    /// </summary>
    public ISymbol TargetSymbol { get; }
 
    // intentionally not including SemanticModel. I don't see how it will be important/used here.
}

Usage Examples

context.SyntaxProvider.ForTypesWithDirectBaseTypeOrInterface(
    "FullyQualifiedName",
    (node, ct) => node is ClassDeclarationSyntax,
    (context, ct) => CreateModel(context.TargetSymbol)
);

Open questions

What if there are two matching class declarations for the same symbol? We don't want to transform both nodes.

Alternative Designs

Risks

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions