|
| 1 | +// Licensed to the .NET Foundation under one or more agreements. |
| 2 | +// The .NET Foundation licenses this file to you under the MIT license. |
| 3 | +// See the LICENSE file in the project root for more information. |
| 4 | + |
| 5 | +using System.Collections.Generic; |
| 6 | +using System.Collections.Immutable; |
| 7 | +using System.Linq; |
| 8 | +using Microsoft.CodeAnalysis; |
| 9 | +using Microsoft.CodeAnalysis.Diagnostics; |
| 10 | +using static CommunityToolkit.Mvvm.SourceGenerators.Diagnostics.DiagnosticDescriptors; |
| 11 | + |
| 12 | +namespace CommunityToolkit.Mvvm.SourceGenerators; |
| 13 | + |
| 14 | +/// <summary> |
| 15 | +/// A diagnostic analyzer that generates a warning when a class is using a code generation attribute when it could inherit instead. |
| 16 | +/// </summary> |
| 17 | +[DiagnosticAnalyzer(LanguageNames.CSharp)] |
| 18 | +public sealed class ClassUsingAttributeInsteadOfInheritanceAnalyzer : DiagnosticAnalyzer |
| 19 | +{ |
| 20 | + /// <summary> |
| 21 | + /// The mapping of target attributes that will trigger the analyzer. |
| 22 | + /// </summary> |
| 23 | + private static readonly ImmutableDictionary<string, string> GeneratorAttributeNamesToFullyQualifiedNamesMap = ImmutableDictionary.CreateRange(new[] |
| 24 | + { |
| 25 | + new KeyValuePair<string, string>("ObservableObjectAttribute", "CommunityToolkit.Mvvm.ComponentModel.ObservableObjectAttribute"), |
| 26 | + new KeyValuePair<string, string>("INotifyPropertyChangedAttribute", "CommunityToolkit.Mvvm.ComponentModel.INotifyPropertyChangedAttribute"), |
| 27 | + }); |
| 28 | + |
| 29 | + /// <summary> |
| 30 | + /// The mapping of diagnostics for each target attribute. |
| 31 | + /// </summary> |
| 32 | + private static readonly ImmutableDictionary<string, DiagnosticDescriptor> GeneratorAttributeNamesToDiagnosticsMap = ImmutableDictionary.CreateRange(new[] |
| 33 | + { |
| 34 | + new KeyValuePair<string, DiagnosticDescriptor>("ObservableObjectAttribute", InheritFromObservableObjectInsteadOfUsingObservableObjectAttributeWarning), |
| 35 | + new KeyValuePair<string, DiagnosticDescriptor>("INotifyPropertyChangedAttribute", InheritFromObservableObjectInsteadOfUsingINotifyPropertyChangedAttributeWarning), |
| 36 | + }); |
| 37 | + |
| 38 | + /// <inheritdoc/> |
| 39 | + public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = ImmutableArray.Create( |
| 40 | + InheritFromObservableObjectInsteadOfUsingObservableObjectAttributeWarning, |
| 41 | + InheritFromObservableObjectInsteadOfUsingINotifyPropertyChangedAttributeWarning); |
| 42 | + |
| 43 | + /// <inheritdoc/> |
| 44 | + public override void Initialize(AnalysisContext context) |
| 45 | + { |
| 46 | + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics); |
| 47 | + context.EnableConcurrentExecution(); |
| 48 | + |
| 49 | + // Defer the callback registration to when the compilation starts, so we can execute more |
| 50 | + // preliminary checks and skip registering any kind of symbol analysis at all if not needed. |
| 51 | + context.RegisterSymbolAction(static context => |
| 52 | + { |
| 53 | + // We're looking for class declarations |
| 54 | + if (context.Symbol is not INamedTypeSymbol { TypeKind: TypeKind.Class, IsRecord: false, IsStatic: false, IsImplicitlyDeclared: false } classSymbol) |
| 55 | + { |
| 56 | + return; |
| 57 | + } |
| 58 | + |
| 59 | + foreach (AttributeData attribute in context.Symbol.GetAttributes()) |
| 60 | + { |
| 61 | + // Same logic as in FieldWithOrphanedDependentObservablePropertyAttributesAnalyzer to find target attributes |
| 62 | + if (attribute.AttributeClass is { Name: string attributeName } attributeClass && |
| 63 | + GeneratorAttributeNamesToFullyQualifiedNamesMap.TryGetValue(attributeName, out string? fullyQualifiedAttributeName) && |
| 64 | + context.Compilation.GetTypeByMetadataName(fullyQualifiedAttributeName) is INamedTypeSymbol attributeSymbol && |
| 65 | + SymbolEqualityComparer.Default.Equals(attributeClass, attributeSymbol)) |
| 66 | + { |
| 67 | + // The type is annotated with either [ObservableObject] or [INotifyPropertyChanged]. |
| 68 | + // Next, we need to check whether it isn't already inheriting from another type. |
| 69 | + if (classSymbol.BaseType is { SpecialType: SpecialType.System_Object }) |
| 70 | + { |
| 71 | + // This type is using the attribute when it could just inherit from ObservableObject, which is preferred |
| 72 | + context.ReportDiagnostic(Diagnostic.Create(GeneratorAttributeNamesToDiagnosticsMap[attributeClass.Name], context.Symbol.Locations.FirstOrDefault(), context.Symbol)); |
| 73 | + } |
| 74 | + } |
| 75 | + } |
| 76 | + }, SymbolKind.NamedType); |
| 77 | + } |
| 78 | +} |
0 commit comments