|
| 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.Immutable; |
| 6 | +using Microsoft.CodeAnalysis; |
| 7 | +using Microsoft.CodeAnalysis.Diagnostics; |
| 8 | +using Microsoft.CodeAnalysis.Operations; |
| 9 | +using static CommunityToolkit.Mvvm.SourceGenerators.Diagnostics.DiagnosticDescriptors; |
| 10 | + |
| 11 | +namespace CommunityToolkit.Mvvm.SourceGenerators; |
| 12 | + |
| 13 | +/// <summary> |
| 14 | +/// A diagnostic analyzer that generates a warning when accessing a field instead of a generated observable property. |
| 15 | +/// </summary> |
| 16 | +[DiagnosticAnalyzer(LanguageNames.CSharp)] |
| 17 | +public sealed class FieldReferenceForObservablePropertyFieldAnalyzer : DiagnosticAnalyzer |
| 18 | +{ |
| 19 | + /// <inheritdoc/> |
| 20 | + public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = ImmutableArray.Create(FieldReferenceForObservablePropertyFieldWarning); |
| 21 | + |
| 22 | + /// <inheritdoc/> |
| 23 | + public override void Initialize(AnalysisContext context) |
| 24 | + { |
| 25 | + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics); |
| 26 | + context.EnableConcurrentExecution(); |
| 27 | + |
| 28 | + context.RegisterOperationAction(static context => |
| 29 | + { |
| 30 | + // We're only looking for references to fields that could potentially be observable properties |
| 31 | + if (context.Operation is not IFieldReferenceOperation { Field: IFieldSymbol { IsStatic: false, IsConst: false, IsImplicitlyDeclared: false, ContainingType: INamedTypeSymbol } fieldSymbol }) |
| 32 | + { |
| 33 | + return; |
| 34 | + } |
| 35 | + |
| 36 | + foreach (AttributeData attribute in fieldSymbol.GetAttributes()) |
| 37 | + { |
| 38 | + // Look for the [ObservableProperty] attribute (there can only ever be one per field) |
| 39 | + if (attribute.AttributeClass is { Name: "ObservablePropertyAttribute" } attributeClass && |
| 40 | + context.Compilation.GetTypeByMetadataName("CommunityToolkit.Mvvm.ComponentModel.ObservablePropertyAttribute") is INamedTypeSymbol attributeSymbol && |
| 41 | + SymbolEqualityComparer.Default.Equals(attributeClass, attributeSymbol)) |
| 42 | + { |
| 43 | + // Emit a warning to redirect users to access the generated property instead |
| 44 | + context.ReportDiagnostic(Diagnostic.Create(FieldReferenceForObservablePropertyFieldWarning, context.Operation.Syntax.GetLocation(), fieldSymbol.ContainingType, fieldSymbol)); |
| 45 | + |
| 46 | + return; |
| 47 | + } |
| 48 | + } |
| 49 | + }, OperationKind.FieldReference); |
| 50 | + } |
| 51 | +} |
0 commit comments