| | | 1 | | // ----------------------------------------------------------------------- |
| | | 2 | | // <copyright file="ObservablePropertyGenerator.cs" company="Stéphane ANDRE"> |
| | | 3 | | // Copyright (c) Stéphane ANDRE. All rights reserved. |
| | | 4 | | // </copyright> |
| | | 5 | | // ----------------------------------------------------------------------- |
| | | 6 | | |
| | | 7 | | using System; |
| | | 8 | | using System.Collections.Immutable; |
| | | 9 | | using System.Diagnostics.CodeAnalysis; |
| | | 10 | | using System.Linq; |
| | | 11 | | using System.Text; |
| | | 12 | | using Microsoft.CodeAnalysis; |
| | | 13 | | using Microsoft.CodeAnalysis.CSharp; |
| | | 14 | | using Microsoft.CodeAnalysis.CSharp.Syntax; |
| | | 15 | | using Microsoft.CodeAnalysis.Text; |
| | | 16 | | |
| | | 17 | | namespace MyNet.Observable.Metadata.Generator; |
| | | 18 | | |
| | | 19 | | [Generator(LanguageNames.CSharp)] |
| | | 20 | | public sealed class ObservablePropertyGenerator : IIncrementalGenerator |
| | | 21 | | { |
| | | 22 | | private const string ObservablePropertyAttribute = "MyNet.Observable.Metadata.ObservablePropertyAttribute"; |
| | | 23 | | private const string ObservableObjectType = "MyNet.Observable.ObservableObject"; |
| | | 24 | | |
| | 3 | 25 | | private static readonly DiagnosticDescriptor NotPartialDescriptor = new( |
| | 3 | 26 | | id: "MNETOBS001", |
| | 3 | 27 | | title: "Observable property host type must be partial", |
| | 3 | 28 | | messageFormat: "Type '{0}' must be declared partial to use [ObservableProperty]", |
| | 3 | 29 | | category: "MyNet.Observable.Generator", |
| | 3 | 30 | | defaultSeverity: DiagnosticSeverity.Error, |
| | 3 | 31 | | isEnabledByDefault: true); |
| | | 32 | | |
| | 3 | 33 | | private static readonly DiagnosticDescriptor NotObservableObjectDescriptor = new( |
| | 3 | 34 | | id: "MNETOBS002", |
| | 3 | 35 | | title: "Observable property host type must derive from ObservableObject", |
| | 3 | 36 | | messageFormat: "Type '{0}' must derive from ObservableObject to use [ObservableProperty]", |
| | 3 | 37 | | category: "MyNet.Observable.Generator", |
| | 3 | 38 | | defaultSeverity: DiagnosticSeverity.Error, |
| | 3 | 39 | | isEnabledByDefault: true); |
| | | 40 | | |
| | 3 | 41 | | private static readonly DiagnosticDescriptor NestedTypeNotSupportedDescriptor = new( |
| | 3 | 42 | | id: "MNETOBS003", |
| | 3 | 43 | | title: "Nested types are not supported for [ObservableProperty]", |
| | 3 | 44 | | messageFormat: "Type '{0}' is nested; move [ObservableProperty] fields to a non-nested partial ObservableObject" |
| | 3 | 45 | | category: "MyNet.Observable.Generator", |
| | 3 | 46 | | defaultSeverity: DiagnosticSeverity.Error, |
| | 3 | 47 | | isEnabledByDefault: true); |
| | | 48 | | |
| | | 49 | | public void Initialize(IncrementalGeneratorInitializationContext context) |
| | | 50 | | { |
| | 6 | 51 | | var fields = context.SyntaxProvider.CreateSyntaxProvider( |
| | 6 | 52 | | static (node, _) => node is FieldDeclarationSyntax { AttributeLists.Count: > 0 }, |
| | 6 | 53 | | static (ctx, _) => GetFieldModels(ctx)) |
| | 6 | 54 | | .SelectMany(static (models, _) => models); |
| | | 55 | | |
| | 6 | 56 | | context.RegisterSourceOutput(fields.Collect(), static (spc, models) => Emit(spc, models)); |
| | 6 | 57 | | } |
| | | 58 | | |
| | | 59 | | private static ImmutableArray<FieldModel?> GetFieldModels(GeneratorSyntaxContext context) |
| | | 60 | | { |
| | 6 | 61 | | if (context.Node is not FieldDeclarationSyntax fieldDeclaration) |
| | 0 | 62 | | return []; |
| | | 63 | | |
| | 6 | 64 | | var builder = ImmutableArray.CreateBuilder<FieldModel?>(); |
| | | 65 | | |
| | 24 | 66 | | foreach (var variable in fieldDeclaration.Declaration.Variables) |
| | | 67 | | { |
| | 6 | 68 | | if (context.SemanticModel.GetDeclaredSymbol(variable) is not IFieldSymbol fieldSymbol) |
| | | 69 | | continue; |
| | | 70 | | |
| | 6 | 71 | | var model = GetFieldModel(context, fieldSymbol); |
| | 6 | 72 | | if (model is not null) |
| | 6 | 73 | | builder.Add(model); |
| | | 74 | | } |
| | | 75 | | |
| | 6 | 76 | | return builder.ToImmutable(); |
| | | 77 | | } |
| | | 78 | | |
| | | 79 | | [SuppressMessage("ReSharper", "ConvertTypeCheckPatternToNullCheck", Justification = "Explicitly checking for nullabi |
| | | 80 | | private static FieldModel? GetFieldModel(GeneratorSyntaxContext context, IFieldSymbol fieldSymbol) |
| | | 81 | | { |
| | 6 | 82 | | if (fieldSymbol.IsStatic || fieldSymbol.IsConst) |
| | 0 | 83 | | return null; |
| | | 84 | | |
| | 6 | 85 | | if (!HasObservablePropertyAttribute(fieldSymbol)) |
| | 0 | 86 | | return null; |
| | | 87 | | |
| | 6 | 88 | | if (fieldSymbol.ContainingType is not INamedTypeSymbol containingType) |
| | 0 | 89 | | return null; |
| | | 90 | | |
| | 6 | 91 | | var typeDeclaration = context.Node.Ancestors().OfType<TypeDeclarationSyntax>().FirstOrDefault(); |
| | | 92 | | |
| | 6 | 93 | | if (typeDeclaration is null) |
| | 0 | 94 | | return null; |
| | | 95 | | |
| | 6 | 96 | | var isPartial = typeDeclaration.Modifiers.Any(static m => m.IsKind(SyntaxKind.PartialKeyword)); |
| | 6 | 97 | | var typeName = containingType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat); |
| | 6 | 98 | | var location = typeDeclaration.Identifier.GetLocation(); |
| | | 99 | | |
| | 6 | 100 | | if (!isPartial) |
| | 3 | 101 | | return FieldModel.WithDiagnostic(NotPartialDescriptor, location, typeName); |
| | | 102 | | |
| | 3 | 103 | | var observableObject = context.SemanticModel.Compilation.GetTypeByMetadataName(ObservableObjectType); |
| | 3 | 104 | | if (observableObject is null || !InheritsFrom(containingType, observableObject)) |
| | 0 | 105 | | return FieldModel.WithDiagnostic(NotObservableObjectDescriptor, location, typeName); |
| | | 106 | | |
| | 3 | 107 | | if (containingType.ContainingType is not null) |
| | 0 | 108 | | return FieldModel.WithDiagnostic(NestedTypeNotSupportedDescriptor, location, typeName); |
| | | 109 | | |
| | 3 | 110 | | var propertyName = ToPropertyName(fieldSymbol.Name); |
| | 3 | 111 | | if (string.IsNullOrEmpty(propertyName)) |
| | 0 | 112 | | return null; |
| | | 113 | | |
| | 3 | 114 | | var propertyType = fieldSymbol.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat); |
| | 3 | 115 | | var fieldName = fieldSymbol.Name; |
| | | 116 | | |
| | 3 | 117 | | var namespaceName = containingType.ContainingNamespace.IsGlobalNamespace |
| | 3 | 118 | | ? string.Empty |
| | 3 | 119 | | : containingType.ContainingNamespace.ToDisplayString(); |
| | | 120 | | |
| | 3 | 121 | | return new FieldModel(namespaceName, containingType.Name, propertyName, propertyType, fieldName, null); |
| | | 122 | | } |
| | | 123 | | |
| | 6 | 124 | | private static bool HasObservablePropertyAttribute(IFieldSymbol fieldSymbol) => Enumerable.Any(fieldSymbol.GetAttrib |
| | | 125 | | |
| | | 126 | | private static bool InheritsFrom(INamedTypeSymbol type, INamedTypeSymbol baseType) |
| | | 127 | | { |
| | 12 | 128 | | for (var current = type; current is not null; current = current.BaseType) |
| | | 129 | | { |
| | 6 | 130 | | if (SymbolEqualityComparer.Default.Equals(current, baseType)) |
| | 3 | 131 | | return true; |
| | | 132 | | } |
| | | 133 | | |
| | 0 | 134 | | return false; |
| | | 135 | | } |
| | | 136 | | |
| | | 137 | | private static string ToPropertyName(string fieldName) |
| | | 138 | | { |
| | 3 | 139 | | if (fieldName.StartsWith("_", StringComparison.Ordinal)) |
| | 3 | 140 | | fieldName = fieldName.Substring(1); |
| | | 141 | | |
| | 3 | 142 | | if (fieldName.StartsWith("m_", StringComparison.Ordinal)) |
| | 0 | 143 | | fieldName = fieldName.Substring(2); |
| | | 144 | | |
| | 3 | 145 | | return fieldName.Length switch |
| | 3 | 146 | | { |
| | 0 | 147 | | 0 => string.Empty, |
| | 0 | 148 | | 1 => fieldName.ToUpperInvariant(), |
| | 3 | 149 | | _ => char.ToUpperInvariant(fieldName[0]) + fieldName.Substring(1) |
| | 3 | 150 | | }; |
| | | 151 | | } |
| | | 152 | | |
| | | 153 | | private static void Emit(SourceProductionContext context, ImmutableArray<FieldModel?> models) |
| | | 154 | | { |
| | 6 | 155 | | var valid = models.Where(static m => m is { Diagnostic: null }).Cast<FieldModel>().ToArray(); |
| | | 156 | | |
| | 18 | 157 | | foreach (var diagnostic in models.Where(static m => m?.Diagnostic is not null).Select(static m => m!.Diagnostic! |
| | 3 | 158 | | context.ReportDiagnostic(diagnostic); |
| | | 159 | | |
| | 18 | 160 | | foreach (var group in valid.GroupBy(static m => m.TypeKey, StringComparer.Ordinal)) |
| | | 161 | | { |
| | 3 | 162 | | var first = group.First(); |
| | 3 | 163 | | var source = new StringBuilder(); |
| | 3 | 164 | | source.AppendLine("// <auto-generated />"); |
| | 3 | 165 | | source.AppendLine("#nullable enable"); |
| | 3 | 166 | | source.AppendLine(); |
| | | 167 | | |
| | 3 | 168 | | if (!string.IsNullOrEmpty(first.NamespaceName)) |
| | | 169 | | { |
| | 3 | 170 | | source.Append("namespace "); |
| | 3 | 171 | | source.Append(first.NamespaceName); |
| | 3 | 172 | | source.AppendLine(";"); |
| | 3 | 173 | | source.AppendLine(); |
| | | 174 | | } |
| | | 175 | | |
| | 3 | 176 | | source.AppendLine($"partial class {first.TypeName}"); |
| | 3 | 177 | | source.AppendLine("{"); |
| | | 178 | | |
| | 12 | 179 | | foreach (var field in group.OrderBy(static f => f.PropertyName, StringComparer.Ordinal)) |
| | | 180 | | { |
| | 3 | 181 | | source.AppendLine($" public {field.PropertyType} {field.PropertyName}"); |
| | 3 | 182 | | source.AppendLine(" {"); |
| | 3 | 183 | | source.AppendLine($" get => {field.FieldName};"); |
| | 3 | 184 | | source.AppendLine($" set => SetProperty(ref {field.FieldName}, value);"); |
| | 3 | 185 | | source.AppendLine(" }"); |
| | 3 | 186 | | source.AppendLine(); |
| | | 187 | | } |
| | | 188 | | |
| | 3 | 189 | | source.AppendLine("}"); |
| | | 190 | | |
| | 3 | 191 | | var fileName = $"{SanitizeFileName(first.TypeName)}.ObservableProperties.g.cs"; |
| | 3 | 192 | | context.AddSource(fileName, SourceText.From(source.ToString(), Encoding.UTF8)); |
| | | 193 | | } |
| | 6 | 194 | | } |
| | | 195 | | |
| | | 196 | | private static string SanitizeFileName(string typeName) |
| | 3 | 197 | | => typeName.Replace('<', '_').Replace('>', '_'); |
| | | 198 | | |
| | | 199 | | private sealed class FieldModel( |
| | | 200 | | string namespaceName, |
| | | 201 | | string typeName, |
| | | 202 | | string propertyName, |
| | | 203 | | string propertyType, |
| | | 204 | | string fieldName, |
| | | 205 | | Diagnostic? diagnostic) |
| | | 206 | | { |
| | | 207 | | public string NamespaceName { get; } = namespaceName; |
| | | 208 | | |
| | | 209 | | public string TypeName { get; } = typeName; |
| | | 210 | | |
| | 3 | 211 | | public string TypeKey => string.IsNullOrEmpty(NamespaceName) ? TypeName : NamespaceName + "." + TypeName; |
| | | 212 | | |
| | | 213 | | public string PropertyName { get; } = propertyName; |
| | | 214 | | |
| | | 215 | | public string PropertyType { get; } = propertyType; |
| | | 216 | | |
| | | 217 | | public string FieldName { get; } = fieldName; |
| | | 218 | | |
| | | 219 | | public Diagnostic? Diagnostic { get; } = diagnostic; |
| | | 220 | | |
| | | 221 | | public static FieldModel WithDiagnostic(DiagnosticDescriptor descriptor, Location location, string typeName) |
| | | 222 | | { |
| | 3 | 223 | | var diagnostic = Diagnostic.Create(descriptor, location, typeName); |
| | 3 | 224 | | return new FieldModel(string.Empty, typeName, string.Empty, string.Empty, string.Empty, diagnostic); |
| | | 225 | | } |
| | | 226 | | } |
| | | 227 | | } |
| | | 228 | | |