|
| 1 | +using System.Collections.Generic; |
| 2 | +using System.Linq; |
| 3 | +using System.Text; |
| 4 | +using Microsoft.CodeAnalysis; |
| 5 | +using Microsoft.CodeAnalysis.CSharp; |
| 6 | +using Microsoft.CodeAnalysis.CSharp.Syntax; |
| 7 | + |
| 8 | +namespace Flecs.NET.Sourcegen; |
| 9 | + |
| 10 | +/// <summary> |
| 11 | +/// Emits a <c>[ModuleInitializer]</c> registrar per <c>IFlecsStruct</c> struct. |
| 12 | +/// </summary> |
| 13 | +[Generator] |
| 14 | +public sealed class StructReflectionGenerator : IIncrementalGenerator |
| 15 | +{ |
| 16 | + private const string InterfaceFullyQualifiedName = "Flecs.NET.Core.IFlecsStruct"; |
| 17 | + |
| 18 | + private static readonly DiagnosticDescriptor OpenGenericTypeRule = new( |
| 19 | + id: "FLECSREFL001", |
| 20 | + title: "IFlecsStruct on open generic type", |
| 21 | + messageFormat: "IFlecsStruct is not supported on open generic type '{0}'", |
| 22 | + category: "Flecs.NET.Reflection", |
| 23 | + defaultSeverity: DiagnosticSeverity.Warning, |
| 24 | + isEnabledByDefault: true); |
| 25 | + |
| 26 | + private static readonly DiagnosticDescriptor FileScopedTypeRule = new( |
| 27 | + id: "FLECSREFL002", |
| 28 | + title: "IFlecsStruct on file-scoped type", |
| 29 | + messageFormat: "IFlecsStruct is not supported on file-scoped type '{0}'", |
| 30 | + category: "Flecs.NET.Reflection", |
| 31 | + defaultSeverity: DiagnosticSeverity.Warning, |
| 32 | + isEnabledByDefault: true); |
| 33 | + |
| 34 | + public void Initialize(IncrementalGeneratorInitializationContext context) |
| 35 | + { |
| 36 | + IncrementalValuesProvider<Output> outputs = context.CompilationProvider.SelectMany( |
| 37 | + (compilation, _) => CollectOutputs(compilation)); |
| 38 | + |
| 39 | + context.RegisterSourceOutput(outputs, Produce); |
| 40 | + } |
| 41 | + |
| 42 | + private static List<Output> CollectOutputs(Compilation compilation) |
| 43 | + { |
| 44 | + var results = new List<Output>(); |
| 45 | + |
| 46 | + INamedTypeSymbol? iface = compilation.GetTypeByMetadataName(InterfaceFullyQualifiedName); |
| 47 | + if (iface is null) |
| 48 | + return results; |
| 49 | + |
| 50 | + var seen = new HashSet<INamedTypeSymbol>(SymbolEqualityComparer.Default); |
| 51 | + |
| 52 | + foreach (SyntaxTree tree in compilation.SyntaxTrees) |
| 53 | + { |
| 54 | + SemanticModel semantic = compilation.GetSemanticModel(tree); |
| 55 | + TypeDeclarationSyntax[] typeDecls = tree.GetRoot() |
| 56 | + .DescendantNodes() |
| 57 | + .OfType<TypeDeclarationSyntax>() |
| 58 | + .ToArray(); |
| 59 | + |
| 60 | + foreach (TypeDeclarationSyntax decl in typeDecls) |
| 61 | + { |
| 62 | + if (semantic.GetDeclaredSymbol(decl) is not { } symbol) |
| 63 | + continue; |
| 64 | + |
| 65 | + if (symbol.TypeKind != TypeKind.Struct) |
| 66 | + continue; |
| 67 | + |
| 68 | + if (!ImplementsInterface(symbol, iface)) |
| 69 | + continue; |
| 70 | + |
| 71 | + if (!seen.Add(symbol)) |
| 72 | + continue; |
| 73 | + |
| 74 | + if (decl.Modifiers.Any(SyntaxKind.FileKeyword)) |
| 75 | + { |
| 76 | + results.Add(new Output(null, Diagnostic.Create( |
| 77 | + FileScopedTypeRule, |
| 78 | + symbol.Locations.Length > 0 ? symbol.Locations[0] : null, |
| 79 | + symbol.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)))); |
| 80 | + continue; |
| 81 | + } |
| 82 | + |
| 83 | + if (symbol.IsUnboundGenericType || symbol.TypeParameters.Length > 0) |
| 84 | + { |
| 85 | + results.Add(new Output(null, Diagnostic.Create( |
| 86 | + OpenGenericTypeRule, |
| 87 | + symbol.Locations.Length > 0 ? symbol.Locations[0] : null, |
| 88 | + symbol.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)))); |
| 89 | + continue; |
| 90 | + } |
| 91 | + |
| 92 | + results.Add(new Output(BuildModel(symbol), null)); |
| 93 | + } |
| 94 | + } |
| 95 | + |
| 96 | + return results; |
| 97 | + } |
| 98 | + |
| 99 | + private static bool ImplementsInterface(INamedTypeSymbol type, INamedTypeSymbol iface) |
| 100 | + => type.AllInterfaces.Any(i => SymbolEqualityComparer.Default.Equals(i, iface)); |
| 101 | + |
| 102 | + private static StructModel BuildModel(INamedTypeSymbol structSymbol) |
| 103 | + { |
| 104 | + MemberInfo[] members = CollectMembers(structSymbol); |
| 105 | + |
| 106 | + string fullyQualifiedType = structSymbol.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat); |
| 107 | + string sanitized = SanitizeIdentifier(fullyQualifiedType); |
| 108 | + |
| 109 | + var builder = new StringBuilder(); |
| 110 | + foreach (MemberInfo member in members) |
| 111 | + { |
| 112 | + if (builder.Length > 0) |
| 113 | + builder.Append('\n'); |
| 114 | + |
| 115 | + builder.Append(" component.Member<") |
| 116 | + .Append(member.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)) |
| 117 | + .Append(">(\"") |
| 118 | + .Append(EscapeString(member.Name)) |
| 119 | + .Append("\");"); |
| 120 | + } |
| 121 | + |
| 122 | + return new StructModel( |
| 123 | + fullyQualifiedType, |
| 124 | + $"StructReflection.{sanitized}.g.cs", |
| 125 | + $"__FlecsStructReflection_{sanitized}", |
| 126 | + builder.ToString()); |
| 127 | + } |
| 128 | + |
| 129 | + private static MemberInfo[] CollectMembers(INamedTypeSymbol structSymbol) |
| 130 | + { |
| 131 | + var fields = new List<MemberInfo>(); |
| 132 | + var properties = new List<MemberInfo>(); |
| 133 | + |
| 134 | + foreach (ISymbol member in structSymbol.GetMembers()) |
| 135 | + { |
| 136 | + if (member.DeclaredAccessibility != Accessibility.Public) |
| 137 | + continue; |
| 138 | + |
| 139 | + switch (member) |
| 140 | + { |
| 141 | + case IFieldSymbol field when !field.IsStatic && !field.IsConst: |
| 142 | + fields.Add(new MemberInfo(field.Name, field.Type)); |
| 143 | + break; |
| 144 | + case IPropertySymbol property when !property.IsStatic && property.Parameters.Length == 0: |
| 145 | + properties.Add(new MemberInfo(property.Name, property.Type)); |
| 146 | + break; |
| 147 | + } |
| 148 | + } |
| 149 | + |
| 150 | + return fields.Count > 0 ? fields.ToArray() : properties.ToArray(); |
| 151 | + } |
| 152 | + |
| 153 | + private static void Produce(SourceProductionContext spc, Output output) |
| 154 | + { |
| 155 | + if (output.Diagnostic is { } diagnostic) |
| 156 | + { |
| 157 | + spc.ReportDiagnostic(diagnostic); |
| 158 | + return; |
| 159 | + } |
| 160 | + |
| 161 | + StructModel model = output.Model!.Value; |
| 162 | + |
| 163 | + string source = $$""" |
| 164 | + // <auto-generated/> |
| 165 | + #nullable enable |
| 166 | +
|
| 167 | + using System.Runtime.CompilerServices; |
| 168 | +
|
| 169 | + namespace Flecs.NET.Generated.StructReflection; |
| 170 | +
|
| 171 | + internal static class {{model.GeneratedClassName}} |
| 172 | + { |
| 173 | + [ModuleInitializer] |
| 174 | + internal static void __Register() |
| 175 | + { |
| 176 | + global::Flecs.NET.Core.StructReflection.Register<{{model.FullyQualifiedTypeName}}>( |
| 177 | + static component => |
| 178 | + { |
| 179 | + {{model.MemberStatement}} |
| 180 | + }); |
| 181 | + } |
| 182 | + } |
| 183 | + """; |
| 184 | + |
| 185 | + spc.AddSource(model.GeneratedFileName, source); |
| 186 | + } |
| 187 | + |
| 188 | + private static string SanitizeIdentifier(string fullyQualifiedName) |
| 189 | + { |
| 190 | + var builder = new StringBuilder(fullyQualifiedName.Length); |
| 191 | + foreach (char c in fullyQualifiedName) |
| 192 | + { |
| 193 | + if (c == '_' || char.IsLetterOrDigit(c)) |
| 194 | + builder.Append(c); |
| 195 | + else |
| 196 | + builder.Append('_'); |
| 197 | + } |
| 198 | + |
| 199 | + return builder.ToString(); |
| 200 | + } |
| 201 | + |
| 202 | + private static string EscapeString(string value) |
| 203 | + { |
| 204 | + var builder = new StringBuilder(value.Length); |
| 205 | + foreach (char c in value) |
| 206 | + { |
| 207 | + switch (c) |
| 208 | + { |
| 209 | + case '\\': builder.Append("\\\\"); break; |
| 210 | + case '"': builder.Append("\\\""); break; |
| 211 | + default: builder.Append(c); break; |
| 212 | + } |
| 213 | + } |
| 214 | + |
| 215 | + return builder.ToString(); |
| 216 | + } |
| 217 | + |
| 218 | + private readonly struct Output |
| 219 | + { |
| 220 | + public StructModel? Model { get; } |
| 221 | + public Diagnostic? Diagnostic { get; } |
| 222 | + |
| 223 | + public Output(StructModel? model, Diagnostic? diagnostic) |
| 224 | + { |
| 225 | + Model = model; |
| 226 | + Diagnostic = diagnostic; |
| 227 | + } |
| 228 | + } |
| 229 | + |
| 230 | + private readonly struct StructModel |
| 231 | + { |
| 232 | + public string FullyQualifiedTypeName { get; } |
| 233 | + public string GeneratedFileName { get; } |
| 234 | + public string GeneratedClassName { get; } |
| 235 | + public string MemberStatement { get; } |
| 236 | + |
| 237 | + public StructModel(string fullyQualifiedTypeName, string generatedFileName, string generatedClassName, string memberStatement) |
| 238 | + { |
| 239 | + FullyQualifiedTypeName = fullyQualifiedTypeName; |
| 240 | + GeneratedFileName = generatedFileName; |
| 241 | + GeneratedClassName = generatedClassName; |
| 242 | + MemberStatement = memberStatement; |
| 243 | + } |
| 244 | + } |
| 245 | + |
| 246 | + private readonly struct MemberInfo |
| 247 | + { |
| 248 | + public string Name { get; } |
| 249 | + public ITypeSymbol Type { get; } |
| 250 | + |
| 251 | + public MemberInfo(string name, ITypeSymbol type) |
| 252 | + { |
| 253 | + Name = name; |
| 254 | + Type = type; |
| 255 | + } |
| 256 | + } |
| 257 | +} |
0 commit comments