Review a generated route source generator

from Source generators
C# 14 / .NET 10 advanced 6 min 4 issues to find

Review this generated implementation before it is packaged as an analyzer.

Generate one deterministic route class per marked controller, preserve valid C# identities, avoid build-time side effects, and retain per-controller incrementality.

csharp
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;

[Generator]
public sealed class RouteGenerator : IIncrementalGenerator
{
    public void Initialize(IncrementalGeneratorInitializationContext context)
    {
        var classes = context.SyntaxProvider.CreateSyntaxProvider(
            static (node, _) => node is ClassDeclarationSyntax,
            static (match, _) => (ClassDeclarationSyntax)match.Node)
            .Collect();
        context.RegisterSourceOutput(context.CompilationProvider.Combine(classes),
            static (output, pair) =>
            {
                foreach (var declaration in pair.Right)
                {
                    var symbol = pair.Left.GetSemanticModel(declaration.SyntaxTree).GetDeclaredSymbol(declaration)!;
                    string route = symbol.Name.Replace("Controller", "");
                    string source = $"public static class {symbol.Name}Routes {{ public const string Path = \"/{route}\"; }}";
                    System.IO.File.AppendAllText("generator.log", source);
                    output.AddSource("Routes.g.cs", source);
                }
            });
    } }

generated code is illustrative, not from any one model

Open in playground
Report an error