CultLib/src/GameCult.Caching.MessagePack.Generator/CultDocumentMessagePackGenerator.cs

45 lines
2.1 KiB
C#
Raw Normal View History

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
namespace GameCult.Caching.MessagePack.Generator
{
[Generator]
public class CultDocumentMessagePackGenerator : IIncrementalGenerator
{
public void Initialize(IncrementalGeneratorInitializationContext context)
{
var documentTypes = context.SyntaxProvider
.CreateSyntaxProvider(
static (node, _) => node is ClassDeclarationSyntax cds && cds.AttributeLists.Count > 0,
static (ctx, _) => ctx.SemanticModel.GetDeclaredSymbol(ctx.Node) as INamedTypeSymbol)
.Where(static symbol => symbol is not null)!
.Select((symbol, _) => symbol!)
.Where(static symbol => symbol.GetAttributes().Any(attribute =>
attribute.AttributeClass?.ToDisplayString() == "GameCult.Caching.CultDocumentAttribute"));
context.RegisterSourceOutput(documentTypes.Collect(), (spc, types) =>
{
var builder = new StringBuilder();
builder.AppendLine("// <auto-generated/>");
builder.AppendLine("#nullable enable");
builder.AppendLine("using MessagePack.Formatters;");
builder.AppendLine("namespace GameCult.Caching.MessagePack");
builder.AppendLine("{");
builder.AppendLine(" public static partial class GeneratedCultDocumentResolvers");
builder.AppendLine(" {");
builder.AppendLine(" public static IMessagePackFormatter<T>? GetFormatter<T>()");
builder.AppendLine(" {");
builder.AppendLine(" return null;");
builder.AppendLine(" }");
builder.AppendLine(" }");
builder.AppendLine("}");
spc.AddSource("GeneratedCultDocumentResolvers.g.cs", SourceText.From(builder.ToString(), Encoding.UTF8));
});
}
}
}