-
Notifications
You must be signed in to change notification settings - Fork 296
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add new analyzer/fixer for async void [RelayCommand] methods #714
Merged
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
5e8096f
Add AsyncVoidReturningRelayCommandMethodAnalyzer
Sergio0694 8e88f30
Add unit test for new async void analyzer
Sergio0694 328d172
Add AsyncVoidReturningRelayCommandMethodCodeFixer
Sergio0694 ce23265
Add AsyncVoidReturningRelayCommandMethodCodeFixer tests
Sergio0694 c6eedee
Avoid passing properties to async void [RelayCommand] fixer
Sergio0694 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
85 changes: 85 additions & 0 deletions
85
src/CommunityToolkit.Mvvm.CodeFixers/AsyncVoidReturningRelayCommandMethodCodeFixer.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,85 @@ | ||
// Licensed to the .NET Foundation under one or more agreements. | ||
// The .NET Foundation licenses this file to you under the MIT license. | ||
// See the LICENSE file in the project root for more information. | ||
|
||
using System.Collections.Immutable; | ||
using System.Composition; | ||
using System.Threading; | ||
using System.Threading.Tasks; | ||
using Microsoft.CodeAnalysis; | ||
using Microsoft.CodeAnalysis.CodeActions; | ||
using Microsoft.CodeAnalysis.CodeFixes; | ||
using Microsoft.CodeAnalysis.CSharp.Syntax; | ||
using Microsoft.CodeAnalysis.Editing; | ||
using Microsoft.CodeAnalysis.Simplification; | ||
using Microsoft.CodeAnalysis.Text; | ||
using static CommunityToolkit.Mvvm.SourceGenerators.Diagnostics.DiagnosticDescriptors; | ||
|
||
namespace CommunityToolkit.Mvvm.CodeFixers; | ||
|
||
/// <summary> | ||
/// 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. | ||
/// </summary> | ||
[ExportCodeFixProvider(LanguageNames.CSharp)] | ||
[Shared] | ||
public sealed class AsyncVoidReturningRelayCommandMethodCodeFixer : CodeFixProvider | ||
{ | ||
/// <inheritdoc/> | ||
public override ImmutableArray<string> FixableDiagnosticIds { get; } = ImmutableArray.Create(AsyncVoidReturningRelayCommandMethodId); | ||
|
||
/// <inheritdoc/> | ||
public override FixAllProvider? GetFixAllProvider() | ||
{ | ||
return WellKnownFixAllProviders.BatchFixer; | ||
} | ||
|
||
/// <inheritdoc/> | ||
public override async Task RegisterCodeFixesAsync(CodeFixContext context) | ||
{ | ||
Diagnostic diagnostic = context.Diagnostics[0]; | ||
TextSpan diagnosticSpan = context.Span; | ||
|
||
SyntaxNode? root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); | ||
|
||
// Get the method declaration from the target diagnostic | ||
if (root!.FindNode(diagnosticSpan) is MethodDeclarationSyntax methodDeclaration) | ||
{ | ||
// Register the code fix to update the return type to be Task instead | ||
context.RegisterCodeFix( | ||
CodeAction.Create( | ||
title: "Change return type to Task", | ||
createChangedDocument: token => ChangeReturnType(context.Document, root, methodDeclaration, token), | ||
equivalenceKey: "Change return type to Task"), | ||
diagnostic); | ||
} | ||
} | ||
|
||
/// <summary> | ||
/// Applies the code fix to a target method declaration and returns an updated document. | ||
/// </summary> | ||
/// <param name="document">The original document being fixed.</param> | ||
/// <param name="root">The original tree root belonging to the current document.</param> | ||
/// <param name="methodDeclaration">The <see cref="MethodDeclarationSyntax"/> to update.</param> | ||
/// <param name="cancellationToken">The cancellation token for the operation.</param> | ||
/// <returns>An updated document with the applied code fix, and the return type of the method being <see cref="Task"/>.</returns> | ||
private static async Task<Document> ChangeReturnType(Document document, SyntaxNode root, MethodDeclarationSyntax methodDeclaration, CancellationToken cancellationToken) | ||
{ | ||
// Get the semantic model (bail if it's not available) | ||
if (await document.GetSemanticModelAsync(cancellationToken) is not SemanticModel semanticModel) | ||
{ | ||
return document; | ||
} | ||
|
||
// Also bail if we can't resolve the Task symbol (this should really never happen) | ||
if (semanticModel.Compilation.GetTypeByMetadataName("System.Threading.Tasks.Task") is not INamedTypeSymbol taskSymbol) | ||
{ | ||
return document; | ||
} | ||
|
||
// Create the new syntax node for the return, and configure it to automatically add "using System.Threading.Tasks;" if needed | ||
SyntaxNode typeSyntax = SyntaxGenerator.GetGenerator(document).TypeExpression(taskSymbol).WithAdditionalAnnotations(Simplifier.AddImportsAnnotation); | ||
|
||
// Replace the void return type with the newly created Task type expression | ||
return document.WithSyntaxRoot(root.ReplaceNode(methodDeclaration.ReturnType, typeSyntax)); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
59 changes: 59 additions & 0 deletions
59
...vm.SourceGenerators/Diagnostics/Analyzers/AsyncVoidReturningRelayCommandMethodAnalyzer.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,59 @@ | ||
// Licensed to the .NET Foundation under one or more agreements. | ||
// The .NET Foundation licenses this file to you under the MIT license. | ||
// See the LICENSE file in the project root for more information. | ||
|
||
using System.Collections.Immutable; | ||
using System.Linq; | ||
using CommunityToolkit.Mvvm.SourceGenerators.Extensions; | ||
using Microsoft.CodeAnalysis; | ||
using Microsoft.CodeAnalysis.Diagnostics; | ||
using static CommunityToolkit.Mvvm.SourceGenerators.Diagnostics.DiagnosticDescriptors; | ||
|
||
namespace CommunityToolkit.Mvvm.SourceGenerators; | ||
|
||
/// <summary> | ||
/// A diagnostic analyzer that generates a warning when using <c>[RelayCommand]</c> over an <see langword="async"/> <see cref="void"/> method. | ||
/// </summary> | ||
[DiagnosticAnalyzer(LanguageNames.CSharp)] | ||
public sealed class AsyncVoidReturningRelayCommandMethodAnalyzer : DiagnosticAnalyzer | ||
{ | ||
/// <inheritdoc/> | ||
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = ImmutableArray.Create(AsyncVoidReturningRelayCommandMethod); | ||
|
||
/// <inheritdoc/> | ||
public override void Initialize(AnalysisContext context) | ||
{ | ||
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics); | ||
context.EnableConcurrentExecution(); | ||
|
||
context.RegisterCompilationStartAction(static context => | ||
{ | ||
// Get the symbol for [RelayCommand] | ||
if (context.Compilation.GetTypeByMetadataName("CommunityToolkit.Mvvm.Input.RelayCommandAttribute") is not INamedTypeSymbol relayCommandSymbol) | ||
{ | ||
return; | ||
} | ||
|
||
context.RegisterSymbolAction(context => | ||
{ | ||
// We're only looking for async void methods | ||
if (context.Symbol is not IMethodSymbol { IsAsync: true, ReturnsVoid: true } methodSymbol) | ||
{ | ||
return; | ||
} | ||
|
||
// We only care about methods annotated with [RelayCommand] | ||
if (!methodSymbol.HasAttributeWithType(relayCommandSymbol)) | ||
{ | ||
return; | ||
} | ||
|
||
// Warn on async void methods using [RelayCommand] (they should return a Task instead) | ||
context.ReportDiagnostic(Diagnostic.Create( | ||
AsyncVoidReturningRelayCommandMethod, | ||
context.Symbol.Locations.FirstOrDefault(), | ||
context.Symbol)); | ||
}, SymbolKind.Method); | ||
}); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
113 changes: 113 additions & 0 deletions
113
...ourceGenerators.Roslyn401.UnitTests/Test_AsyncVoidReturningRelayCommandMethodCodeFixer.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,113 @@ | ||
// Licensed to the .NET Foundation under one or more agreements. | ||
// The .NET Foundation licenses this file to you under the MIT license. | ||
// See the LICENSE file in the project root for more information. | ||
|
||
using System.Threading.Tasks; | ||
using CommunityToolkit.Mvvm.Input; | ||
using Microsoft.CodeAnalysis.Testing; | ||
using Microsoft.VisualStudio.TestTools.UnitTesting; | ||
using CSharpCodeFixTest = Microsoft.CodeAnalysis.CSharp.Testing.CSharpCodeFixTest< | ||
CommunityToolkit.Mvvm.SourceGenerators.AsyncVoidReturningRelayCommandMethodAnalyzer, | ||
CommunityToolkit.Mvvm.CodeFixers.AsyncVoidReturningRelayCommandMethodCodeFixer, | ||
Microsoft.CodeAnalysis.Testing.Verifiers.MSTestVerifier>; | ||
using CSharpCodeFixVerifier = Microsoft.CodeAnalysis.CSharp.Testing.CSharpCodeFixVerifier< | ||
CommunityToolkit.Mvvm.SourceGenerators.AsyncVoidReturningRelayCommandMethodAnalyzer, | ||
CommunityToolkit.Mvvm.CodeFixers.AsyncVoidReturningRelayCommandMethodCodeFixer, | ||
Microsoft.CodeAnalysis.Testing.Verifiers.MSTestVerifier>; | ||
|
||
namespace CommunityToolkit.Mvvm.SourceGenerators.Roslyn401.UnitTests; | ||
|
||
[TestClass] | ||
public class Test_AsyncVoidReturningRelayCommandMethodCodeFixer | ||
{ | ||
[TestMethod] | ||
public async Task AsyncVoidMethod_FileContainsSystemThreadingTasksUsingDirective() | ||
{ | ||
string original = """ | ||
using System.Threading.Tasks; | ||
using CommunityToolkit.Mvvm.Input; | ||
|
||
partial class C | ||
{ | ||
[RelayCommand] | ||
private async void Foo() | ||
{ | ||
} | ||
} | ||
"""; | ||
|
||
string @fixed = """ | ||
using System.Threading.Tasks; | ||
using CommunityToolkit.Mvvm.Input; | ||
|
||
partial class C | ||
{ | ||
[RelayCommand] | ||
private async Task Foo() | ||
{ | ||
} | ||
} | ||
"""; | ||
|
||
CSharpCodeFixTest test = new() | ||
{ | ||
TestCode = original, | ||
FixedCode = @fixed, | ||
ReferenceAssemblies = ReferenceAssemblies.Net.Net60 | ||
}; | ||
|
||
test.TestState.AdditionalReferences.Add(typeof(RelayCommand).Assembly); | ||
test.ExpectedDiagnostics.AddRange(new[] | ||
{ | ||
// /0/Test0.cs(7,24): error MVVMTK0039: The method C.Foo() annotated with [RelayCommand] is async void (make sure to return a Task type instead) | ||
CSharpCodeFixVerifier.Diagnostic().WithSpan(7, 24, 7, 27).WithArguments("C.Foo()") | ||
Sergio0694 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
}); | ||
|
||
await test.RunAsync(); | ||
} | ||
|
||
[TestMethod] | ||
public async Task AsyncVoidMethod_FileDoesNotContainSystemThreadingTasksUsingDirective() | ||
{ | ||
string original = """ | ||
using CommunityToolkit.Mvvm.Input; | ||
|
||
partial class C | ||
{ | ||
[RelayCommand] | ||
private async void Foo() | ||
{ | ||
} | ||
} | ||
"""; | ||
|
||
string @fixed = """ | ||
using System.Threading.Tasks; | ||
Sergio0694 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
using CommunityToolkit.Mvvm.Input; | ||
|
||
partial class C | ||
{ | ||
[RelayCommand] | ||
private async Task Foo() | ||
{ | ||
} | ||
} | ||
"""; | ||
|
||
CSharpCodeFixTest test = new() | ||
{ | ||
TestCode = original, | ||
FixedCode = @fixed, | ||
ReferenceAssemblies = ReferenceAssemblies.Net.Net60 | ||
}; | ||
|
||
test.TestState.AdditionalReferences.Add(typeof(RelayCommand).Assembly); | ||
test.ExpectedDiagnostics.AddRange(new[] | ||
{ | ||
// /0/Test0.cs(7,24): error MVVMTK0039: The method C.Foo() annotated with [RelayCommand] is async void (make sure to return a Task type instead) | ||
CSharpCodeFixVerifier.Diagnostic().WithSpan(6, 24, 6, 27).WithArguments("C.Foo()") | ||
}); | ||
|
||
await test.RunAsync(); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I see this is already existing for all other descriptors, but I never seen categories to be very long names (
CommunityToolkit.Mvvm.SourceGenerators.RelayCommandGenerator
)There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Mmh good point. We might want to address this in a separate PR for all descriptors 🤔
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Just a note: this will be a breaking change if someone is currently changing severity via
dotnet_analyzer_diagnostic.category-TheLongCategoryName.severity = ...
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Gotcha. I suppose we could do that in 9.0 then 🙂