using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Text;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace OpenWaf.Data.Generator;
///
/// Emits the ORM plumbing for a class marked [Table]: the column map, the
/// row materializer, and the metadata registration — all as ordinary C#, at
/// build time.
///
/// Why generated rather than reflected: the whole NativeAOT wall on this tree is
/// that a compiled binary cannot answer "what are this type's properties" at run
/// time. EF's answer to that question is the sentence the probe counts — 32
/// refusals in the 2026-10-07 window. Here the answer is a switch the compiler
/// wrote, so the question is never asked.
///
/// The column name is the property name unless a [Column] says otherwise,
/// because that is what this schema of record uses: schema.sqlite.sql
/// creates "policy_settings"("Key","Value","UpdatedAt").
///
[Generator]
public sealed class EntityOrmGenerator : IIncrementalGenerator
{
public void Initialize(IncrementalGeneratorInitializationContext context)
{
var entities = context.SyntaxProvider
.ForAttributeWithMetadataName(
"OpenWaf.Data.TableAttribute",
static (node, _) => node is ClassDeclarationSyntax,
static (ctx, _) => Read((INamedTypeSymbol)ctx.TargetSymbol))
.Collect();
context.RegisterSourceOutput(entities, static (spc, entities) =>
{
foreach (var entity in entities)
spc.AddSource("OpenWaf.Data." + entity.ShortName + "Orm.g.cs", Emit(entity));
});
}
private static Entity Read(INamedTypeSymbol type)
{
var table = AttributeArgument(type, "OpenWaf.Data.TableAttribute") ?? type.Name;
var columns = new List();
foreach (var member in type.GetMembers().OfType())
{
if (member.IsStatic || member.IsIndexer) continue;
if (member.GetMethod is null) continue;
if (member.DeclaredAccessibility != Accessibility.Public) continue;
var name = AttributeArgument(member, "OpenWaf.Data.ColumnAttribute") ?? member.Name;
// "global::" is stripped so the switch below can name a type the way a
// reader writes it; the generated code uses the same string.
columns.Add(new ColumnMapping(
member.Name,
name,
member.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat).Replace("global::", string.Empty)));
}
return new Entity(
type.ContainingNamespace.IsGlobalNamespace ? string.Empty : type.ContainingNamespace.ToDisplayString(),
type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat),
type.Name,
table,
columns.ToImmutableArray());
}
private static string? AttributeArgument(ISymbol symbol, string attributeName)
{
var attribute = symbol.GetAttributes()
.FirstOrDefault(a => a.AttributeClass?.ToDisplayString() == attributeName);
return attribute?.ConstructorArguments.Length > 0 ? attribute.ConstructorArguments[0].Value as string : null;
}
private static string Emit(Entity entity)
{
var sb = new StringBuilder();
sb.AppendLine("// ");
sb.AppendLine("// Generated from " + entity.TypeName + " by OpenWaf.Data.Generator. Do not edit.");
sb.AppendLine("#nullable enable");
sb.AppendLine("using System.Collections.Immutable;");
sb.AppendLine("using System.Data.Common;");
sb.AppendLine("using System.Runtime.CompilerServices;");
sb.AppendLine("using OpenWaf.Data;");
sb.AppendLine();
if (entity.Namespace.Length > 0) sb.AppendLine("namespace " + entity.Namespace + ";");
sb.AppendLine();
sb.AppendLine("/// The generated data access for " + entity.ShortName + ": the table's");
sb.AppendLine("/// metadata, its column map and its row materializer. Nothing here is discovered at");
sb.AppendLine("/// run time, which is the point.");
sb.AppendLine("public static class " + entity.ShortName + "Orm");
sb.AppendLine("{");
sb.AppendLine(" [ModuleInitializer]");
sb.AppendLine(" internal static void RegisterOpenWafData() =>");
sb.AppendLine(" OrmMeta.Register<" + entity.TypeName + ">(");
sb.AppendLine(" " + Literal(entity.Table) + ",");
sb.AppendLine(" ColumnOf,");
sb.AppendLine(" ImmutableArray.Create(" + string.Join(", ", entity.Columns.Select(c => Literal(c.Column))) + "));");
sb.AppendLine();
sb.AppendLine(" /// CLR member name to column name. Empty means the member is not a");
sb.AppendLine(" /// column of this table, and the query layer says so rather than guessing.");
sb.AppendLine(" public static string ColumnOf(string member) => member switch");
sb.AppendLine(" {");
foreach (var column in entity.Columns)
sb.AppendLine(" " + Literal(column.Member) + " => " + Literal(column.Column) + ",");
sb.AppendLine(" _ => string.Empty,");
sb.AppendLine(" };");
sb.AppendLine();
sb.AppendLine(" public static Query<" + entity.TypeName + "> Query(OrmContext db) =>");
sb.AppendLine(" new(db, OrmMeta.Get(typeof(" + entity.TypeName + ")), Map);");
sb.AppendLine();
sb.AppendLine(" /// Reads one row of " + Literal(entity.Table) + " into a new object. The");
sb.AppendLine(" /// ordinals are the order " + "RenderSelect" + " emits, which is the order the");
sb.AppendLine(" /// column list was registered in — one list, one order, no name lookups per row.");
sb.AppendLine(" public static " + entity.TypeName + " Map(DbDataReader reader, ISqlDialect dialect) => new " + entity.TypeName);
sb.AppendLine(" {");
for (var i = 0; i < entity.Columns.Length; i++)
sb.AppendLine(" " + entity.Columns[i].Member + " = " + Read(entity.Columns[i], i) + ",");
sb.AppendLine(" };");
sb.AppendLine("}");
return sb.ToString();
}
private static string Read(ColumnMapping column, int ordinal) => column.Type switch
{
"string" => "RowReader.String(reader, " + ordinal + ")",
"bool" => "RowReader.Boolean(reader, " + ordinal + ")",
"int" => "RowReader.Int32(reader, " + ordinal + ")",
"long" => "RowReader.Int64(reader, " + ordinal + ")",
"System.DateTimeOffset" => "RowReader.DateTimeOffset(reader, " + ordinal + ", dialect)",
"System.Guid" => "RowReader.Guid(reader, " + ordinal + ")",
_ => "RowReader.Required<" + column.Type + ">(reader, " + ordinal + ")",
};
private static string Literal(string value) => "\"" + value.Replace("\\", "\\\\").Replace("\"", "\\\"") + "\"";
private sealed record Entity(string Namespace, string TypeName, string ShortName, string Table, ImmutableArray Columns);
private sealed record ColumnMapping(string Member, string Column, string Type);
}