|
| 1 | +#nullable enable |
| 2 | + |
| 3 | +using System.Collections.Immutable; |
| 4 | +using System.Linq; |
| 5 | +using System.Text; |
| 6 | +using Microsoft.CodeAnalysis; |
| 7 | +using Microsoft.CodeAnalysis.CSharp.Syntax; |
| 8 | +using Microsoft.CodeAnalysis.Text; |
| 9 | + |
| 10 | +namespace GenerateMembersGenerator; |
| 11 | + |
| 12 | +// <GenerateMembersGenerator> |
| 13 | +/// <summary> |
| 14 | +/// A source generator that adds a <c>Describe()</c> method and a |
| 15 | +/// <c>PropertyNames</c> list to any <see langword="partial"/> class or struct |
| 16 | +/// decorated with <c>[GenerateMembers]</c>. |
| 17 | +/// </summary> |
| 18 | +[Generator] |
| 19 | +public class GenerateMembersIncrementalGenerator : IIncrementalGenerator |
| 20 | +{ |
| 21 | + private const string AttributeFullName = "GenerateMembersGenerator.GenerateMembersAttribute"; |
| 22 | + |
| 23 | + // <Initialize> |
| 24 | + public void Initialize(IncrementalGeneratorInitializationContext context) |
| 25 | + { |
| 26 | + // 1. Emit the marker attribute so users don't need a separate reference. |
| 27 | + context.RegisterPostInitializationOutput(static ctx => |
| 28 | + { |
| 29 | + ctx.AddSource("GenerateMembersAttribute.g.cs", SourceText.From(AttributeSource, Encoding.UTF8)); |
| 30 | + }); |
| 31 | + |
| 32 | + // 2. Filter for type declarations annotated with [GenerateMembers]. |
| 33 | + IncrementalValuesProvider<TypeInfo> typeInfos = context.SyntaxProvider |
| 34 | + .ForAttributeWithMetadataName( |
| 35 | + AttributeFullName, |
| 36 | + predicate: static (node, _) => node is TypeDeclarationSyntax, |
| 37 | + transform: static (ctx, _) => GetTypeInfo(ctx)) |
| 38 | + .Where(static t => t is not null)!; |
| 39 | + |
| 40 | + // 3. Generate source for each qualifying type. |
| 41 | + context.RegisterSourceOutput(typeInfos, static (spc, typeInfo) => |
| 42 | + { |
| 43 | + string source = GenerateSource(typeInfo); |
| 44 | + string hintName = typeInfo.FullyQualifiedName |
| 45 | + .Replace("global::", "") |
| 46 | + .Replace("::", ".") |
| 47 | + .Replace("<", "_") |
| 48 | + .Replace(">", "_"); |
| 49 | + spc.AddSource($"{hintName}.GeneratedMembers.g.cs", SourceText.From(source, Encoding.UTF8)); |
| 50 | + }); |
| 51 | + } |
| 52 | + // </Initialize> |
| 53 | + |
| 54 | + // <GetTypeInfo> |
| 55 | + private static TypeInfo? GetTypeInfo(GeneratorAttributeSyntaxContext context) |
| 56 | + { |
| 57 | + if (context.TargetSymbol is not INamedTypeSymbol typeSymbol) |
| 58 | + return null; |
| 59 | + |
| 60 | + string typeKeyword = context.TargetNode is StructDeclarationSyntax ? "struct" : "class"; |
| 61 | + |
| 62 | + ImmutableArray<IPropertySymbol> properties = typeSymbol.GetMembers() |
| 63 | + .OfType<IPropertySymbol>() |
| 64 | + .Where(p => !p.IsStatic && !p.IsIndexer) |
| 65 | + .ToImmutableArray(); |
| 66 | + |
| 67 | + return new TypeInfo( |
| 68 | + typeSymbol.ContainingNamespace.IsGlobalNamespace |
| 69 | + ? null |
| 70 | + : typeSymbol.ContainingNamespace.ToDisplayString(), |
| 71 | + typeSymbol.Name, |
| 72 | + typeSymbol.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat), |
| 73 | + typeKeyword, |
| 74 | + properties.Select(p => (p.Name, p.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat))) |
| 75 | + .ToImmutableArray()); |
| 76 | + } |
| 77 | + // </GetTypeInfo> |
| 78 | + |
| 79 | + // <GenerateSource> |
| 80 | + private static string GenerateSource(TypeInfo typeInfo) |
| 81 | + { |
| 82 | + var sb = new StringBuilder(); |
| 83 | + |
| 84 | + sb.AppendLine("// <auto-generated />"); |
| 85 | + |
| 86 | + if (typeInfo.Namespace is not null) |
| 87 | + { |
| 88 | + sb.AppendLine($"namespace {typeInfo.Namespace}"); |
| 89 | + sb.AppendLine("{"); |
| 90 | + } |
| 91 | + |
| 92 | + sb.AppendLine($" partial {typeInfo.TypeKeyword} {typeInfo.Name}"); |
| 93 | + sb.AppendLine(" {"); |
| 94 | + |
| 95 | + // PropertyNames |
| 96 | + sb.AppendLine(" /// <summary>Gets the names of all instance properties.</summary>"); |
| 97 | + sb.AppendLine(" public static global::System.Collections.Generic.IReadOnlyList<string> PropertyNames { get; } ="); |
| 98 | + sb.Append(" new string[] { "); |
| 99 | + sb.Append(string.Join(", ", typeInfo.Properties.Select(p => $"\"{p.Name}\""))); |
| 100 | + sb.AppendLine(" };"); |
| 101 | + sb.AppendLine(); |
| 102 | + |
| 103 | + // Describe method |
| 104 | + sb.AppendLine(" /// <summary>Returns a human-readable description of this instance.</summary>"); |
| 105 | + sb.AppendLine(" public string Describe()"); |
| 106 | + sb.AppendLine(" {"); |
| 107 | + sb.AppendLine($" var sb = new global::System.Text.StringBuilder();"); |
| 108 | + sb.AppendLine($" sb.AppendLine(\"{typeInfo.Name}\");"); |
| 109 | + foreach (var (name, _) in typeInfo.Properties) |
| 110 | + { |
| 111 | + sb.AppendLine($" sb.AppendLine($\" {name} = {{{name}}}\");"); |
| 112 | + } |
| 113 | + sb.AppendLine(" return sb.ToString();"); |
| 114 | + sb.AppendLine(" }"); |
| 115 | + |
| 116 | + sb.AppendLine(" }"); |
| 117 | + |
| 118 | + if (typeInfo.Namespace is not null) |
| 119 | + { |
| 120 | + sb.AppendLine("}"); |
| 121 | + } |
| 122 | + |
| 123 | + return sb.ToString(); |
| 124 | + } |
| 125 | + // </GenerateSource> |
| 126 | + |
| 127 | + // <AttributeSource> |
| 128 | + private const string AttributeSource = @"// <auto-generated /> |
| 129 | +namespace GenerateMembersGenerator |
| 130 | +{ |
| 131 | + /// <summary> |
| 132 | + /// Add this attribute to a partial class or struct to automatically generate |
| 133 | + /// a <c>Describe()</c> method and a <c>PropertyNames</c> list. |
| 134 | + /// </summary> |
| 135 | + [global::System.AttributeUsage(global::System.AttributeTargets.Class | global::System.AttributeTargets.Struct)] |
| 136 | + internal sealed class GenerateMembersAttribute : global::System.Attribute |
| 137 | + { |
| 138 | + } |
| 139 | +} |
| 140 | +"; |
| 141 | + // </AttributeSource> |
| 142 | + |
| 143 | + // <TypeInfoClass> |
| 144 | + private sealed class TypeInfo |
| 145 | + { |
| 146 | + public string? Namespace { get; } |
| 147 | + public string Name { get; } |
| 148 | + public string FullyQualifiedName { get; } |
| 149 | + public string TypeKeyword { get; } |
| 150 | + public ImmutableArray<(string Name, string TypeFullName)> Properties { get; } |
| 151 | + |
| 152 | + public TypeInfo( |
| 153 | + string? ns, |
| 154 | + string name, |
| 155 | + string fullyQualifiedName, |
| 156 | + string typeKeyword, |
| 157 | + ImmutableArray<(string Name, string TypeFullName)> properties) |
| 158 | + { |
| 159 | + Namespace = ns; |
| 160 | + Name = name; |
| 161 | + FullyQualifiedName = fullyQualifiedName; |
| 162 | + TypeKeyword = typeKeyword; |
| 163 | + Properties = properties; |
| 164 | + } |
| 165 | + } |
| 166 | + // </TypeInfoClass> |
| 167 | +} |
| 168 | +// </GenerateMembersGenerator> |
0 commit comments