-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathAsyncVoid.cs
More file actions
62 lines (54 loc) · 2.49 KB
/
AsyncVoid.cs
File metadata and controls
62 lines (54 loc) · 2.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
using System.Collections.Immutable;
using System.Composition;
using System.Linq;
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;
namespace IntelliTect.Analyzer.CodeFixes
{
[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(AsyncVoid))]
[Shared]
public class AsyncVoid : CodeFixProvider
{
private const string Title = "Fix Design Violation: Follow AsyncVoid";
public sealed override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(Analyzers.AsyncVoid.DiagnosticId);
public sealed override FixAllProvider GetFixAllProvider()
{
return WellKnownFixAllProviders.BatchFixer;
}
public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
{
SyntaxNode? root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
if (root is null)
{
return;
}
Diagnostic diagnostic = context.Diagnostics.First();
Microsoft.CodeAnalysis.Text.TextSpan diagnosticSpan = diagnostic.Location.SourceSpan;
// Find the type declaration identified by the diagnostic.
var declaration = root.FindToken(diagnosticSpan.Start).Parent as MethodDeclarationSyntax;
if (declaration is null)
{
return;
}
// Register a code action that will invoke the fix.
context.RegisterCodeFix(
CodeAction.Create(
title: Title,
createChangedDocument: c => MakeReturnTask(context.Document, declaration, c),
equivalenceKey: Title),
diagnostic);
}
private static async Task<Document> MakeReturnTask(Document document, MethodDeclarationSyntax declaration, CancellationToken cancellationToken)
{
SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false)
?? throw new System.InvalidOperationException("Could not get syntax root");
SyntaxNode newRoot = root.ReplaceNode(declaration.ReturnType, SyntaxFactory.ParseTypeName(typeof(Task).Name).WithTrailingTrivia(SyntaxFactory.Space));
return document.WithSyntaxRoot(newRoot);
}
}
}