|
| 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 CommunityToolkit.GeneratedDependencyProperty.Constants; |
| 7 | +using CommunityToolkit.GeneratedDependencyProperty.Extensions; |
| 8 | +using Microsoft.CodeAnalysis; |
| 9 | +using Microsoft.CodeAnalysis.Diagnostics; |
| 10 | +using static CommunityToolkit.GeneratedDependencyProperty.Diagnostics.DiagnosticDescriptors; |
| 11 | + |
| 12 | +namespace CommunityToolkit.GeneratedDependencyProperty; |
| 13 | + |
| 14 | +/// <summary> |
| 15 | +/// A diagnostic analyzer that generates a diagnostic whenever <c>[GeneratedDependencyProperty]</c> is used on a property with the 'Property' suffix in its name. |
| 16 | +/// </summary> |
| 17 | +[DiagnosticAnalyzer(LanguageNames.CSharp)] |
| 18 | +public sealed class PropertyDeclarationWithPropertyNameSuffixAnalyzer : DiagnosticAnalyzer |
| 19 | +{ |
| 20 | + /// <inheritdoc/> |
| 21 | + public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = [PropertyDeclarationWithPropertySuffix]; |
| 22 | + |
| 23 | + /// <inheritdoc/> |
| 24 | + public override void Initialize(AnalysisContext context) |
| 25 | + { |
| 26 | + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); |
| 27 | + context.EnableConcurrentExecution(); |
| 28 | + |
| 29 | + context.RegisterCompilationStartAction(static context => |
| 30 | + { |
| 31 | + // Get the '[GeneratedDependencyProperty]' symbol (there might be multiples, due to embedded mode) |
| 32 | + ImmutableArray<INamedTypeSymbol> generatedDependencyPropertyAttributeSymbols = context.Compilation.GetTypesByMetadataName(WellKnownTypeNames.GeneratedDependencyPropertyAttribute); |
| 33 | + |
| 34 | + context.RegisterSymbolAction(context => |
| 35 | + { |
| 36 | + IPropertySymbol propertySymbol = (IPropertySymbol)context.Symbol; |
| 37 | + |
| 38 | + // We only want to lookup the attribute if the property name actually ends with the 'Property' suffix |
| 39 | + if (!propertySymbol.Name.EndsWith("Property")) |
| 40 | + { |
| 41 | + return; |
| 42 | + } |
| 43 | + |
| 44 | + // Emit a diagnostic if the property is using '[GeneratedDependencyProperty]' |
| 45 | + if (propertySymbol.TryGetAttributeWithAnyType(generatedDependencyPropertyAttributeSymbols, out AttributeData? attributeData)) |
| 46 | + { |
| 47 | + context.ReportDiagnostic(Diagnostic.Create( |
| 48 | + PropertyDeclarationWithPropertySuffix, |
| 49 | + attributeData.GetLocation(), |
| 50 | + propertySymbol)); |
| 51 | + } |
| 52 | + }, SymbolKind.Property); |
| 53 | + }); |
| 54 | + } |
| 55 | +} |
0 commit comments