Skip to content

[v2.0] Add compile-time validation for DependsOn attributes via source generator #1990

@thomhurst

Description

@thomhurst

Summary

The DependsOnAttribute performs type validation at runtime (during attribute instantiation), missing the opportunity for compile-time safety. Developers can use the non-generic version with an incorrect type and only discover the error when running the pipeline.

Current Behavior

File: src/ModularPipelines/Attributes/DependsOnAttribute.cs

public DependsOnAttribute(Type type)
{
    if (!type.IsAssignableTo(typeof(IModule)))
        throw new Exception($"{type.FullName} is not a Module");
    Type = type;
}

This validation happens at reflection time, not compile time.

Problems

  1. No compile-time safety: Errors only surface during pipeline initialization
  2. Non-generic overload risk: Developers might use [DependsOn(typeof(NotAModule))]
  3. Late feedback: CI pipelines fail at runtime instead of build time
  4. Poor IDE experience: No squiggles or warnings for invalid types

Proposed Solution

Source Generator Diagnostics

Add a source generator that emits compile-time diagnostics:

// Generator analyzes [DependsOn(typeof(X))] attributes
// Emits error if X does not implement IModule

[DependsOn(typeof(string))]  // Compile error: MP001 - 'string' does not implement IModule
public class MyModule : Module<None> { }

Diagnostic codes:

  • MP001: Type does not implement IModule
  • MP002: Circular dependency detected
  • MP003: Module depends on itself

API Change (Optional)

Consider marking the non-generic constructor as obsolete:

[Obsolete("Use the generic DependsOn<TModule> attribute for compile-time safety")]
public DependsOnAttribute(Type type) { ... }

Implementation

  1. Extend ModularPipelines.SourceGenerator with attribute analyzer
  2. Register diagnostic descriptors for module validation errors
  3. Emit diagnostics during code generation phase
  4. Add tests for all diagnostic scenarios

Impact

  • Semi-breaking: Adds compile errors for previously runtime errors
  • Improves: Developer experience, build-time safety, IDE integration

Labels

  • v2.0
  • enhancement
  • source-generator
  • developer-experience

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions