-
Notifications
You must be signed in to change notification settings - Fork 147
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #596 from Evangelink/task-return-null
VSTHRD114: Do not return null from non-async Task method
- Loading branch information
Showing
27 changed files
with
961 additions
and
52 deletions.
There are no files selected for viewing
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,31 @@ | ||
# VSTHRD114 Avoid returning a null Task | ||
|
||
Returning `null` from a non-async `Task`/`Task<T>` method will cause a `NullReferenceException` at runtime. This problem can be avoided by returning `Task.CompletedTask`, `Task.FromResult<T>(null)` or `Task.FromResult(default(T))` instead. | ||
|
||
## Examples of patterns that are flagged by this analyzer | ||
|
||
Any non-async `Task` returning method with an explicit `return null;` will be flagged. | ||
|
||
```csharp | ||
Task DoAsync() { | ||
return null; | ||
} | ||
|
||
Task<object> GetSomethingAsync() { | ||
return null; | ||
} | ||
``` | ||
|
||
## Solution | ||
|
||
Return a task like `Task.CompletedTask` or `Task.FromResult`. | ||
|
||
```csharp | ||
Task DoAsync() { | ||
return Task.CompletedTask; | ||
} | ||
|
||
Task<object> GetSomethingAsync() { | ||
return Task.FromResult<object>(null); | ||
} | ||
``` |
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
83 changes: 83 additions & 0 deletions
83
...soft.VisualStudio.Threading.Analyzers.CodeFixes/VSTHRD114AvoidReturningNullTaskCodeFix.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,83 @@ | ||
namespace Microsoft.VisualStudio.Threading.Analyzers | ||
{ | ||
using System.Collections.Immutable; | ||
using System.Threading; | ||
using System.Threading.Tasks; | ||
using Microsoft.CodeAnalysis; | ||
using Microsoft.CodeAnalysis.CodeActions; | ||
using Microsoft.CodeAnalysis.CodeFixes; | ||
using Microsoft.CodeAnalysis.CSharp; | ||
using Microsoft.CodeAnalysis.CSharp.Syntax; | ||
using Microsoft.CodeAnalysis.Simplification; | ||
|
||
[ExportCodeFixProvider(LanguageNames.CSharp)] | ||
public class VSTHRD114AvoidReturningNullTaskCodeFix : CodeFixProvider | ||
{ | ||
private static readonly ImmutableArray<string> ReusableFixableDiagnosticIds = ImmutableArray.Create( | ||
VSTHRD114AvoidReturningNullTaskAnalyzer.Id); | ||
|
||
/// <inheritdoc /> | ||
public override ImmutableArray<string> FixableDiagnosticIds => ReusableFixableDiagnosticIds; | ||
|
||
/// <inheritdoc /> | ||
public override FixAllProvider GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer; | ||
|
||
public override async Task RegisterCodeFixesAsync(CodeFixContext context) | ||
{ | ||
foreach (var diagnostic in context.Diagnostics) | ||
{ | ||
var semanticModel = await context.Document.GetSemanticModelAsync(context.CancellationToken).ConfigureAwait(false); | ||
var syntaxRoot = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); | ||
|
||
if (!(syntaxRoot.FindNode(diagnostic.Location.SourceSpan) is LiteralExpressionSyntax nullLiteral)) | ||
{ | ||
continue; | ||
} | ||
|
||
var methodDeclaration = nullLiteral.FirstAncestorOrSelf<MethodDeclarationSyntax>(); | ||
if (methodDeclaration == null) | ||
{ | ||
continue; | ||
} | ||
|
||
if (!(methodDeclaration.ReturnType is GenericNameSyntax genericReturnType)) | ||
{ | ||
context.RegisterCodeFix(CodeAction.Create(Strings.VSTHRD114_CodeFix_CompletedTask, ct => ApplyTaskCompletedTaskFix(ct), "CompletedTask"), diagnostic); | ||
} | ||
else | ||
{ | ||
if (genericReturnType.TypeArgumentList.Arguments.Count != 1) | ||
{ | ||
continue; | ||
} | ||
|
||
context.RegisterCodeFix(CodeAction.Create(Strings.VSTHRD114_CodeFix_FromResult, ct => ApplyTaskFromResultFix(genericReturnType.TypeArgumentList.Arguments[0], ct), "FromResult"), diagnostic); | ||
} | ||
|
||
Task<Document> ApplyTaskCompletedTaskFix(CancellationToken cancellationToken) | ||
{ | ||
ExpressionSyntax completedTaskExpression = SyntaxFactory.MemberAccessExpression( | ||
SyntaxKind.SimpleMemberAccessExpression, | ||
SyntaxFactory.IdentifierName("Task"), | ||
SyntaxFactory.IdentifierName("CompletedTask")) | ||
.WithAdditionalAnnotations(Simplifier.Annotation); | ||
|
||
return Task.FromResult(context.Document.WithSyntaxRoot(syntaxRoot.ReplaceNode(nullLiteral, completedTaskExpression))); | ||
} | ||
|
||
Task<Document> ApplyTaskFromResultFix(TypeSyntax returnTypeArgument, CancellationToken cancellationToken) | ||
{ | ||
ExpressionSyntax completedTaskExpression = SyntaxFactory.InvocationExpression( | ||
SyntaxFactory.MemberAccessExpression( | ||
SyntaxKind.SimpleMemberAccessExpression, | ||
SyntaxFactory.IdentifierName("Task"), | ||
SyntaxFactory.GenericName("FromResult").AddTypeArgumentListArguments(returnTypeArgument))) | ||
.AddArgumentListArguments(SyntaxFactory.Argument(nullLiteral)) | ||
.WithAdditionalAnnotations(Simplifier.Annotation); | ||
|
||
return Task.FromResult(context.Document.WithSyntaxRoot(syntaxRoot.ReplaceNode(nullLiteral, completedTaskExpression))); | ||
} | ||
} | ||
} | ||
} | ||
} |
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
File renamed without changes.
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
Oops, something went wrong.