|
| 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.Composition; |
| 7 | +using System.Threading; |
| 8 | +using System.Threading.Tasks; |
| 9 | +using CommunityToolkit.Mvvm.SourceGenerators; |
| 10 | +using Microsoft.CodeAnalysis; |
| 11 | +using Microsoft.CodeAnalysis.CodeActions; |
| 12 | +using Microsoft.CodeAnalysis.CodeFixes; |
| 13 | +using Microsoft.CodeAnalysis.CSharp.Syntax; |
| 14 | +using Microsoft.CodeAnalysis.Editing; |
| 15 | +using Microsoft.CodeAnalysis.Simplification; |
| 16 | +using Microsoft.CodeAnalysis.Text; |
| 17 | +using static CommunityToolkit.Mvvm.SourceGenerators.Diagnostics.DiagnosticDescriptors; |
| 18 | + |
| 19 | +namespace CommunityToolkit.Mvvm.CodeFixers; |
| 20 | + |
| 21 | +/// <summary> |
| 22 | +/// A code fixer that automatically updates the return type of <see langword="async"/> <see cref="void"/> methods using <c>[RelayCommand]</c> to return a <see cref="Task"/> instead. |
| 23 | +/// </summary> |
| 24 | +[ExportCodeFixProvider(LanguageNames.CSharp)] |
| 25 | +[Shared] |
| 26 | +public sealed class AsyncVoidReturningRelayCommandMethodCodeFixer : CodeFixProvider |
| 27 | +{ |
| 28 | + /// <inheritdoc/> |
| 29 | + public override ImmutableArray<string> FixableDiagnosticIds { get; } = ImmutableArray.Create(AsyncVoidReturningRelayCommandMethodId); |
| 30 | + |
| 31 | + /// <inheritdoc/> |
| 32 | + public override FixAllProvider? GetFixAllProvider() |
| 33 | + { |
| 34 | + return WellKnownFixAllProviders.BatchFixer; |
| 35 | + } |
| 36 | + |
| 37 | + /// <inheritdoc/> |
| 38 | + public override async Task RegisterCodeFixesAsync(CodeFixContext context) |
| 39 | + { |
| 40 | + Diagnostic diagnostic = context.Diagnostics[0]; |
| 41 | + TextSpan diagnosticSpan = context.Span; |
| 42 | + |
| 43 | + // Retrieve the property passed by the analyzer |
| 44 | + if (diagnostic.Properties[AsyncVoidReturningRelayCommandMethodAnalyzer.MethodNameKey] is not string methodName) |
| 45 | + { |
| 46 | + return; |
| 47 | + } |
| 48 | + |
| 49 | + SyntaxNode? root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); |
| 50 | + |
| 51 | + // Get the method declaration from the target diagnostic |
| 52 | + if (root!.FindNode(diagnosticSpan) is MethodDeclarationSyntax { Identifier.Text: string identifierName } methodDeclaration && |
| 53 | + identifierName == methodName) |
| 54 | + { |
| 55 | + // Register the code fix to update the return type to be Task instead |
| 56 | + context.RegisterCodeFix( |
| 57 | + CodeAction.Create( |
| 58 | + title: "Change return type to Task", |
| 59 | + createChangedDocument: token => ChangeReturnType(context.Document, root, methodDeclaration, token), |
| 60 | + equivalenceKey: "Change return type to Task"), |
| 61 | + diagnostic); |
| 62 | + } |
| 63 | + } |
| 64 | + |
| 65 | + /// <summary> |
| 66 | + /// Applies the code fix to a target method declaration and returns an updated document. |
| 67 | + /// </summary> |
| 68 | + /// <param name="document">The original document being fixed.</param> |
| 69 | + /// <param name="root">The original tree root belonging to the current document.</param> |
| 70 | + /// <param name="methodDeclaration">The <see cref="MethodDeclarationSyntax"/> to update.</param> |
| 71 | + /// <param name="cancellationToken">The cancellation token for the operation.</param> |
| 72 | + /// <returns>An updated document with the applied code fix, and the return type of the method being <see cref="Task"/>.</returns> |
| 73 | + private static async Task<Document> ChangeReturnType(Document document, SyntaxNode root, MethodDeclarationSyntax methodDeclaration, CancellationToken cancellationToken) |
| 74 | + { |
| 75 | + // Get the semantic model (bail if it's not available) |
| 76 | + if (await document.GetSemanticModelAsync(cancellationToken) is not SemanticModel semanticModel) |
| 77 | + { |
| 78 | + return document; |
| 79 | + } |
| 80 | + |
| 81 | + // Also bail if we can't resolve the Task symbol (this should really never happen) |
| 82 | + if (semanticModel.Compilation.GetTypeByMetadataName("System.Threading.Tasks.Task") is not INamedTypeSymbol taskSymbol) |
| 83 | + { |
| 84 | + return document; |
| 85 | + } |
| 86 | + |
| 87 | + // Create the new syntax node for the return, and configure it to automatically add "using System.Threading.Tasks;" if needed |
| 88 | + SyntaxNode typeSyntax = SyntaxGenerator.GetGenerator(document).TypeExpression(taskSymbol).WithAdditionalAnnotations(Simplifier.AddImportsAnnotation); |
| 89 | + |
| 90 | + // Replace the void return type with the newly created Task type expression |
| 91 | + return document.WithSyntaxRoot(root.ReplaceNode(methodDeclaration.ReturnType, typeSyntax)); |
| 92 | + } |
| 93 | +} |
0 commit comments