|
| 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 System.Linq; |
| 7 | +using CommunityToolkit.Mvvm.SourceGenerators.Extensions; |
| 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 using <c>[RelayCommand]</c> over an <see langword="async"/> <see cref="void"/> method. |
| 16 | +/// </summary> |
| 17 | +[DiagnosticAnalyzer(LanguageNames.CSharp)] |
| 18 | +public sealed class AsyncVoidReturningRelayCommandMethodAnalyzer : DiagnosticAnalyzer |
| 19 | +{ |
| 20 | + /// <inheritdoc/> |
| 21 | + public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = ImmutableArray.Create(AsyncVoidReturningRelayCommandMethod); |
| 22 | + |
| 23 | + /// <inheritdoc/> |
| 24 | + public override void Initialize(AnalysisContext context) |
| 25 | + { |
| 26 | + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics); |
| 27 | + context.EnableConcurrentExecution(); |
| 28 | + |
| 29 | + context.RegisterCompilationStartAction(static context => |
| 30 | + { |
| 31 | + // Get the symbol for [RelayCommand] |
| 32 | + if (context.Compilation.GetTypeByMetadataName("CommunityToolkit.Mvvm.Input.RelayCommandAttribute") is not INamedTypeSymbol relayCommandSymbol) |
| 33 | + { |
| 34 | + return; |
| 35 | + } |
| 36 | + |
| 37 | + context.RegisterSymbolAction(context => |
| 38 | + { |
| 39 | + // We're only looking for async void methods |
| 40 | + if (context.Symbol is not IMethodSymbol { IsAsync: true, ReturnsVoid: true } methodSymbol) |
| 41 | + { |
| 42 | + return; |
| 43 | + } |
| 44 | + |
| 45 | + // We only care about methods annotated with [RelayCommand] |
| 46 | + if (!methodSymbol.HasAttributeWithType(relayCommandSymbol)) |
| 47 | + { |
| 48 | + return; |
| 49 | + } |
| 50 | + |
| 51 | + // Warn on async void methods using [RelayCommand] (they should return a Task instead) |
| 52 | + context.ReportDiagnostic(Diagnostic.Create( |
| 53 | + AsyncVoidReturningRelayCommandMethod, |
| 54 | + context.Symbol.Locations.FirstOrDefault(), |
| 55 | + context.Symbol)); |
| 56 | + }, SymbolKind.Method); |
| 57 | + }); |
| 58 | + } |
| 59 | +} |
0 commit comments