-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDependencyCodeFixProvider.cs
More file actions
70 lines (56 loc) · 2.65 KB
/
DependencyCodeFixProvider.cs
File metadata and controls
70 lines (56 loc) · 2.65 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
63
64
65
66
67
68
69
70
using System.Collections.Immutable;
using System.Composition;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Editing;
namespace Hypercube.Utilities.Analyzers.CodeFix;
[Shared, ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(DependencyCodeFixProvider))]
public sealed class DependencyCodeFixProvider : CodeFixProvider
{
private const string Title = "Remove assignment from [Dependency] field";
public override ImmutableArray<string> FixableDiagnosticIds => ["HUA0001"];
public override FixAllProvider GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer;
public override async Task RegisterCodeFixesAsync(CodeFixContext context)
{
var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
if (root is null)
return;
var diagnostic = context.Diagnostics[0];
var diagnosticSpan = diagnostic.Location.SourceSpan;
var node = root.FindNode(diagnosticSpan);
context.RegisterCodeFix(
Microsoft.CodeAnalysis.CodeActions.CodeAction.Create(
title: Title,
createChangedDocument: c => RemoveAssignmentAsync(context.Document, node, c),
equivalenceKey: Title),
diagnostic);
}
private static async Task<Document> RemoveAssignmentAsync(Document document, SyntaxNode node, CancellationToken cancellationToken)
{
var editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false);
switch (node)
{
case AssignmentExpressionSyntax assignment:
editor.ReplaceNode(assignment, assignment.Left.WithoutTrivia());
break;
case VariableDeclaratorSyntax { Initializer: not null } declarator:
editor.RemoveNode(declarator.Initializer, SyntaxRemoveOptions.KeepNoTrivia);
break;
case PrefixUnaryExpressionSyntax prefix:
// ++field/--field => field
editor.ReplaceNode(prefix, prefix.Operand.WithoutTrivia());
break;
case PostfixUnaryExpressionSyntax postfix:
// field++/field-- => field
editor.ReplaceNode(postfix, postfix.Operand.WithoutTrivia());
break;
case ArgumentSyntax argument:
// ref/out/in field => field
var cleanArg = argument.WithRefKindKeyword(default);
editor.ReplaceNode(argument, cleanArg);
break;
}
return editor.GetChangedDocument();
}
}