Rewrite CultCache as attribute-first storage

This commit is contained in:
Meta Vens 2026-05-08 01:13:15 +01:00
commit da94389ee2
29 changed files with 1496 additions and 2488 deletions

View file

@ -0,0 +1,45 @@
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));
});
}
}
}

View file

@ -1,264 +0,0 @@
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
{
/// <summary>
/// Generates MessagePack formatters and resolver mappings for concrete <c>DatabaseEntry</c> types.
/// </summary>
[Generator]
public class DatabaseEntryMessagePackGenerator : IIncrementalGenerator
{
/// <summary>
/// Configures the incremental generator pipeline.
/// </summary>
/// <param name="ctx">The generator initialization context.</param>
public void Initialize(IncrementalGeneratorInitializationContext ctx)
{
// Select DatabaseEntry subclass declarations
var databaseEntryTypes = ctx.SyntaxProvider
.CreateSyntaxProvider(
static (s, _) => s is ClassDeclarationSyntax cds && cds.BaseList != null,
static (ctx, _) => ctx.SemanticModel.GetDeclaredSymbol(ctx.Node) as INamedTypeSymbol)
.Where(static s => s is not null)!
.Select((s, _) => s!)
.Where(symbol =>
{
if (symbol.IsAbstract) return false;
var baseType = symbol.BaseType;
while (baseType != null)
{
if (baseType.ToDisplayString() == "GameCult.Caching.DatabaseEntry")
return true;
baseType = baseType.BaseType;
}
return false;
});
// 2. Distinct types
var collected = databaseEntryTypes.Collect();
// 3. Register output
ctx.RegisterSourceOutput(collected, (spc, types) =>
{
//if (types.Length == 0) return;
var sbResolvers = new StringBuilder();
var sbFormatters = new StringBuilder();
sbResolvers.AppendLine("// <auto-generated/>");
sbResolvers.AppendLine("#nullable enable");
sbResolvers.AppendLine("using System;");
sbResolvers.AppendLine("using MessagePack.Formatters;");
sbResolvers.AppendLine("namespace GameCult.Caching.MessagePack");
sbResolvers.AppendLine("{");
sbResolvers.AppendLine(" static partial class GeneratedDatabaseEntryResolvers");
sbResolvers.AppendLine(" {");
sbResolvers.AppendLine(" public static IMessagePackFormatter<T>? GetFormatter<T>()");
sbResolvers.AppendLine(" {");
sbResolvers.AppendLine(" var t = typeof(T);");
foreach (var type in types)
{
var fullName = type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat);
var formatterName = $"{Sanitize(type)}__MessagePackFormatter";
var fmtSrc = GenerateFormatterFor(type, formatterName);
sbFormatters.AppendLine(fmtSrc);
sbResolvers.AppendLine(
$" if (t == typeof({fullName})) return (IMessagePackFormatter<T>)(object){formatterName}.Instance;");
}
sbResolvers.AppendLine(" return null;");
sbResolvers.AppendLine(" }");
sbResolvers.AppendLine(" }");
sbResolvers.AppendLine("}");
spc.AddSource("GeneratedDatabaseEntryFormatters.g.cs", SourceText.From(sbFormatters.ToString(), Encoding.UTF8));
spc.AddSource("GeneratedDatabaseEntryResolvers.g.cs", SourceText.From(sbResolvers.ToString(), Encoding.UTF8));
});
}
private static string Sanitize(ISymbol symbol)
{
var s = symbol.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat);
return s.Replace(".", "_")
.Replace("global::", string.Empty)
.Replace("<", "_")
.Replace(">", "_")
.Replace(",", "_")
.Replace(" ", "_");
}
// Collect members, order them, generate the formatter
private static string GenerateFormatterFor(INamedTypeSymbol type, string formatterName)
{
var sb = new StringBuilder();
sb.AppendLine("// <auto-generated/>");
sb.AppendLine("#nullable enable");
sb.AppendLine("using System;");
sb.AppendLine("using MessagePack;");
sb.AppendLine("using MessagePack.Formatters;");
sb.AppendLine();
var ns = "GameCult.Caching.MessagePack";
sb.AppendLine($"namespace {ns}");
sb.AppendLine("{");
var typeFull = type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat);
sb.AppendLine($" internal sealed class {formatterName} : IMessagePackFormatter<{typeFull}>");
sb.AppendLine(" {");
sb.AppendLine($" public static readonly {formatterName} Instance = new {formatterName}();");
sb.AppendLine($" private {formatterName}() {{ }}");
sb.AppendLine();
var members = CollectMembers(type);
var slots = AssignSlots(type, members);
var maxSlot = slots.Count == 0 ? -1 : slots.Max(m => m.slot);
// Serialize
sb.AppendLine($" public void Serialize(ref MessagePackWriter writer, {typeFull}? value, MessagePackSerializerOptions options)");
sb.AppendLine(" {");
sb.AppendLine(" if (value == null) { writer.WriteNil(); return; }");
sb.AppendLine($" writer.WriteArrayHeader({maxSlot + 1});");
for (int i = 0; i <= maxSlot; i++)
{
var member = slots.FirstOrDefault(m => m.slot == i);
if (member.name == null)
{
sb.AppendLine(" writer.WriteNil();");
continue;
}
var tname = member.typeSymbol.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat);
var access = $"value.{member.name}";
sb.AppendLine(
tname == "global::System.Guid"
? $" options.Resolver.GetFormatterWithVerify<System.Guid>().Serialize(ref writer, {access}, options);"
: $" options.Resolver.GetFormatterWithVerify<{tname}>().Serialize(ref writer, {access}, options);");
}
sb.AppendLine(" }");
// Deserialize
sb.AppendLine();
sb.AppendLine($" public {typeFull}? Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options)");
sb.AppendLine(" {");
sb.AppendLine(" if (reader.TryReadNil()) return null;");
sb.AppendLine($" var count = reader.ReadArrayHeader();");
sb.AppendLine($" var obj = new {typeFull}();");
sb.AppendLine(" for (var i = 0; i < count; i++)");
sb.AppendLine(" {");
sb.AppendLine(" switch (i)");
sb.AppendLine(" {");
foreach (var (slot, name, tsym) in slots)
{
var tname = tsym.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat);
sb.AppendLine($" case {slot}:");
sb.AppendLine(
tname == "global::System.Guid"
? $" obj.{name} = options.Resolver.GetFormatterWithVerify<System.Guid>().Deserialize(ref reader, options);"
: $" obj.{name} = options.Resolver.GetFormatterWithVerify<{tname}>().Deserialize(ref reader, options);");
sb.AppendLine(" break;");
}
sb.AppendLine(" default:");
sb.AppendLine(" reader.Skip();");
sb.AppendLine(" break;");
sb.AppendLine(" }");
sb.AppendLine(" }");
sb.AppendLine(" return obj;");
sb.AppendLine(" }");
sb.AppendLine(" }");
sb.AppendLine("}");
return sb.ToString();
}
private static List<(string name, ITypeSymbol typeSymbol, int? key, bool ignore)> CollectMembers(INamedTypeSymbol type)
{
var members = new List<(string, ITypeSymbol, int?, bool)>();
foreach (var f in type.GetMembers().OfType<IFieldSymbol>())
{
if (f.IsStatic) continue;
var ignore = f.GetAttributes().Any(a => a.AttributeClass?.ToDisplayString() == "MessagePack.IgnoreMemberAttribute");
var key = GetKeyValue(f);
members.Add((f.Name, f.Type, key, ignore));
}
foreach (var p in type.GetMembers().OfType<IPropertySymbol>())
{
if (p.IsStatic || p.SetMethod == null || p.GetMethod == null) continue;
var ignore = p.GetAttributes().Any(a => a.AttributeClass?.ToDisplayString() == "MessagePack.IgnoreMemberAttribute");
var key = GetKeyValue(p);
members.Add((p.Name, p.Type, key, ignore));
}
return members;
}
private static List<(int slot, string name, ITypeSymbol typeSymbol)> AssignSlots(
INamedTypeSymbol type,
List<(string name, ITypeSymbol typeSymbol, int? key, bool ignore)> members)
{
members = members.Where(m => !m.ignore).ToList();
var slots = new List<(int, string, ITypeSymbol)>();
var id = FindIdMember(type);
if (id != null)
{
slots.Add((0, id.Value.name, id.Value.typeSymbol));
members.RemoveAll(m => m.name == id.Value.name);
}
foreach (var member in members.Where(m => m.key.HasValue).OrderBy(m => m.key!.Value))
{
slots.Add((member.key!.Value, member.name, member.typeSymbol));
}
var nextSlot = slots.Count == 0 ? 0 : slots.Max(s => s.Item1) + 1;
foreach (var member in members.Where(m => !m.key.HasValue))
{
slots.Add((nextSlot, member.name, member.typeSymbol));
nextSlot++;
}
return slots.OrderBy(s => s.Item1).ToList();
}
private static int? GetKeyValue(ISymbol sym)
{
foreach (var attr in sym.GetAttributes())
{
var n = attr.AttributeClass?.ToDisplayString();
if (n == "MessagePack.KeyAttribute" || n == "MessagePack.Key")
{
if (attr.ConstructorArguments.Length >= 1 && attr.ConstructorArguments[0].Value is int i)
return i;
}
}
return null;
}
private static (string name, ITypeSymbol typeSymbol)? FindIdMember(INamedTypeSymbol type)
{
var cur = type;
while (cur != null)
{
foreach (var f in cur.GetMembers().OfType<IFieldSymbol>())
{
if ((f.Name == "ID") && f.Type.ToDisplayString() == "System.Guid")
return (f.Name, f.Type);
}
cur = cur.BaseType;
}
return null;
}
}
}