< Summary

Information
Class: MyNet.Observable.Metadata.Generator.ObservablePropertyGenerator
Assembly: MyNet.Observable.Metadata.Generator
File(s): https://raw.githubusercontent.com/sandre58/MyNet/5aaaab311aa14541478b9e402357d98b657a23e4/src/MyNet.Observable.Metadata.Generator/ObservablePropertyGenerator.cs
Tag: 342_31701152804
Line coverage
89%
Covered lines: 98
Uncovered lines: 12
Coverable lines: 110
Total lines: 228
Line coverage: 89%
Branch coverage
63%
Covered branches: 33
Total branches: 52
Branch coverage: 63.4%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.cctor()100%11100%
Initialize(...)100%11100%
GetFieldModels(...)62.5%8888.88%
GetFieldModel(...)54.54%302275%
HasObservablePropertyAttribute(...)100%11100%
InheritsFrom(...)75%4475%
ToPropertyName(...)50%10870%
Emit(...)100%88100%
SanitizeFileName(...)100%11100%
get_TypeKey()50%22100%
WithDiagnostic(...)100%11100%

File(s)

https://raw.githubusercontent.com/sandre58/MyNet/5aaaab311aa14541478b9e402357d98b657a23e4/src/MyNet.Observable.Metadata.Generator/ObservablePropertyGenerator.cs

#LineLine coverage
 1// -----------------------------------------------------------------------
 2// <copyright file="ObservablePropertyGenerator.cs" company="Stéphane ANDRE">
 3// Copyright (c) Stéphane ANDRE. All rights reserved.
 4// </copyright>
 5// -----------------------------------------------------------------------
 6
 7using System;
 8using System.Collections.Immutable;
 9using System.Diagnostics.CodeAnalysis;
 10using System.Linq;
 11using System.Text;
 12using Microsoft.CodeAnalysis;
 13using Microsoft.CodeAnalysis.CSharp;
 14using Microsoft.CodeAnalysis.CSharp.Syntax;
 15using Microsoft.CodeAnalysis.Text;
 16
 17namespace MyNet.Observable.Metadata.Generator;
 18
 19[Generator(LanguageNames.CSharp)]
 20public sealed class ObservablePropertyGenerator : IIncrementalGenerator
 21{
 22    private const string ObservablePropertyAttribute = "MyNet.Observable.Metadata.ObservablePropertyAttribute";
 23    private const string ObservableObjectType = "MyNet.Observable.ObservableObject";
 24
 325    private static readonly DiagnosticDescriptor NotPartialDescriptor = new(
 326        id: "MNETOBS001",
 327        title: "Observable property host type must be partial",
 328        messageFormat: "Type '{0}' must be declared partial to use [ObservableProperty]",
 329        category: "MyNet.Observable.Generator",
 330        defaultSeverity: DiagnosticSeverity.Error,
 331        isEnabledByDefault: true);
 32
 333    private static readonly DiagnosticDescriptor NotObservableObjectDescriptor = new(
 334        id: "MNETOBS002",
 335        title: "Observable property host type must derive from ObservableObject",
 336        messageFormat: "Type '{0}' must derive from ObservableObject to use [ObservableProperty]",
 337        category: "MyNet.Observable.Generator",
 338        defaultSeverity: DiagnosticSeverity.Error,
 339        isEnabledByDefault: true);
 40
 341    private static readonly DiagnosticDescriptor NestedTypeNotSupportedDescriptor = new(
 342        id: "MNETOBS003",
 343        title: "Nested types are not supported for [ObservableProperty]",
 344        messageFormat: "Type '{0}' is nested; move [ObservableProperty] fields to a non-nested partial ObservableObject"
 345        category: "MyNet.Observable.Generator",
 346        defaultSeverity: DiagnosticSeverity.Error,
 347        isEnabledByDefault: true);
 48
 49    public void Initialize(IncrementalGeneratorInitializationContext context)
 50    {
 651        var fields = context.SyntaxProvider.CreateSyntaxProvider(
 652            static (node, _) => node is FieldDeclarationSyntax { AttributeLists.Count: > 0 },
 653            static (ctx, _) => GetFieldModels(ctx))
 654            .SelectMany(static (models, _) => models);
 55
 656        context.RegisterSourceOutput(fields.Collect(), static (spc, models) => Emit(spc, models));
 657    }
 58
 59    private static ImmutableArray<FieldModel?> GetFieldModels(GeneratorSyntaxContext context)
 60    {
 661        if (context.Node is not FieldDeclarationSyntax fieldDeclaration)
 062            return [];
 63
 664        var builder = ImmutableArray.CreateBuilder<FieldModel?>();
 65
 2466        foreach (var variable in fieldDeclaration.Declaration.Variables)
 67        {
 668            if (context.SemanticModel.GetDeclaredSymbol(variable) is not IFieldSymbol fieldSymbol)
 69                continue;
 70
 671            var model = GetFieldModel(context, fieldSymbol);
 672            if (model is not null)
 673                builder.Add(model);
 74        }
 75
 676        return builder.ToImmutable();
 77    }
 78
 79    [SuppressMessage("ReSharper", "ConvertTypeCheckPatternToNullCheck", Justification = "Explicitly checking for nullabi
 80    private static FieldModel? GetFieldModel(GeneratorSyntaxContext context, IFieldSymbol fieldSymbol)
 81    {
 682        if (fieldSymbol.IsStatic || fieldSymbol.IsConst)
 083            return null;
 84
 685        if (!HasObservablePropertyAttribute(fieldSymbol))
 086            return null;
 87
 688        if (fieldSymbol.ContainingType is not INamedTypeSymbol containingType)
 089            return null;
 90
 691        var typeDeclaration = context.Node.Ancestors().OfType<TypeDeclarationSyntax>().FirstOrDefault();
 92
 693        if (typeDeclaration is null)
 094            return null;
 95
 696        var isPartial = typeDeclaration.Modifiers.Any(static m => m.IsKind(SyntaxKind.PartialKeyword));
 697        var typeName = containingType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat);
 698        var location = typeDeclaration.Identifier.GetLocation();
 99
 6100        if (!isPartial)
 3101            return FieldModel.WithDiagnostic(NotPartialDescriptor, location, typeName);
 102
 3103        var observableObject = context.SemanticModel.Compilation.GetTypeByMetadataName(ObservableObjectType);
 3104        if (observableObject is null || !InheritsFrom(containingType, observableObject))
 0105            return FieldModel.WithDiagnostic(NotObservableObjectDescriptor, location, typeName);
 106
 3107        if (containingType.ContainingType is not null)
 0108            return FieldModel.WithDiagnostic(NestedTypeNotSupportedDescriptor, location, typeName);
 109
 3110        var propertyName = ToPropertyName(fieldSymbol.Name);
 3111        if (string.IsNullOrEmpty(propertyName))
 0112            return null;
 113
 3114        var propertyType = fieldSymbol.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat);
 3115        var fieldName = fieldSymbol.Name;
 116
 3117        var namespaceName = containingType.ContainingNamespace.IsGlobalNamespace
 3118            ? string.Empty
 3119            : containingType.ContainingNamespace.ToDisplayString();
 120
 3121        return new FieldModel(namespaceName, containingType.Name, propertyName, propertyType, fieldName, null);
 122    }
 123
 6124    private static bool HasObservablePropertyAttribute(IFieldSymbol fieldSymbol) => Enumerable.Any(fieldSymbol.GetAttrib
 125
 126    private static bool InheritsFrom(INamedTypeSymbol type, INamedTypeSymbol baseType)
 127    {
 12128        for (var current = type; current is not null; current = current.BaseType)
 129        {
 6130            if (SymbolEqualityComparer.Default.Equals(current, baseType))
 3131                return true;
 132        }
 133
 0134        return false;
 135    }
 136
 137    private static string ToPropertyName(string fieldName)
 138    {
 3139        if (fieldName.StartsWith("_", StringComparison.Ordinal))
 3140            fieldName = fieldName.Substring(1);
 141
 3142        if (fieldName.StartsWith("m_", StringComparison.Ordinal))
 0143            fieldName = fieldName.Substring(2);
 144
 3145        return fieldName.Length switch
 3146        {
 0147            0 => string.Empty,
 0148            1 => fieldName.ToUpperInvariant(),
 3149            _ => char.ToUpperInvariant(fieldName[0]) + fieldName.Substring(1)
 3150        };
 151    }
 152
 153    private static void Emit(SourceProductionContext context, ImmutableArray<FieldModel?> models)
 154    {
 6155        var valid = models.Where(static m => m is { Diagnostic: null }).Cast<FieldModel>().ToArray();
 156
 18157        foreach (var diagnostic in models.Where(static m => m?.Diagnostic is not null).Select(static m => m!.Diagnostic!
 3158            context.ReportDiagnostic(diagnostic);
 159
 18160        foreach (var group in valid.GroupBy(static m => m.TypeKey, StringComparer.Ordinal))
 161        {
 3162            var first = group.First();
 3163            var source = new StringBuilder();
 3164            source.AppendLine("// <auto-generated />");
 3165            source.AppendLine("#nullable enable");
 3166            source.AppendLine();
 167
 3168            if (!string.IsNullOrEmpty(first.NamespaceName))
 169            {
 3170                source.Append("namespace ");
 3171                source.Append(first.NamespaceName);
 3172                source.AppendLine(";");
 3173                source.AppendLine();
 174            }
 175
 3176            source.AppendLine($"partial class {first.TypeName}");
 3177            source.AppendLine("{");
 178
 12179            foreach (var field in group.OrderBy(static f => f.PropertyName, StringComparer.Ordinal))
 180            {
 3181                source.AppendLine($"    public {field.PropertyType} {field.PropertyName}");
 3182                source.AppendLine("    {");
 3183                source.AppendLine($"        get => {field.FieldName};");
 3184                source.AppendLine($"        set => SetProperty(ref {field.FieldName}, value);");
 3185                source.AppendLine("    }");
 3186                source.AppendLine();
 187            }
 188
 3189            source.AppendLine("}");
 190
 3191            var fileName = $"{SanitizeFileName(first.TypeName)}.ObservableProperties.g.cs";
 3192            context.AddSource(fileName, SourceText.From(source.ToString(), Encoding.UTF8));
 193        }
 6194    }
 195
 196    private static string SanitizeFileName(string typeName)
 3197        => 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
 3211        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        {
 3223            var diagnostic = Diagnostic.Create(descriptor, location, typeName);
 3224            return new FieldModel(string.Empty, typeName, string.Empty, string.Empty, string.Empty, diagnostic);
 225        }
 226    }
 227}
 228