-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathNamingIdentifierPascal.cs
More file actions
79 lines (70 loc) · 3.23 KB
/
NamingIdentifierPascal.cs
File metadata and controls
79 lines (70 loc) · 3.23 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
71
72
73
74
75
76
77
78
79
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.Rename;
using Microsoft.CodeAnalysis.Text;
namespace IntelliTect.Analyzer.CodeFixes
{
[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(NamingIdentifierPascal))]
[Shared]
public class NamingIdentifierPascal : CodeFixProvider
{
private const string Title = "Fix Naming Violation: Follow PascalCase";
public sealed override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(Analyzers.NamingPropertyPascal.DiagnosticId, Analyzers.NamingMethodPascal.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();
TextSpan diagnosticSpan = diagnostic.Location.SourceSpan;
// Find the type declaration identified by the diagnostic.
SyntaxToken declaration = root.FindToken(diagnosticSpan.Start);
// Register a code action that will invoke the fix.
context.RegisterCodeFix(
CodeAction.Create(
title: Title,
createChangedSolution: c => MakePascal(context.Document, declaration, c),
equivalenceKey: Title),
diagnostic);
}
private static async Task<Solution> MakePascal(Document document, SyntaxToken declaration, CancellationToken cancellationToken)
{
string nameOfField = declaration.ValueText;
string newName = char.ToUpper(nameOfField.First()) + nameOfField.Substring(1);
SemanticModel? semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
if (semanticModel is null || declaration.Parent is null)
{
return document.Project.Solution;
}
ISymbol? symbol = semanticModel.GetDeclaredSymbol(declaration.Parent, cancellationToken);
if (symbol is null)
{
return document.Project.Solution;
}
Solution solution = document.Project.Solution;
SymbolRenameOptions options = new()
{
RenameOverloads = true
};
return await Renamer.RenameSymbolAsync(solution: solution,
symbol: symbol,
options: options,
newName: newName,
cancellationToken: cancellationToken)
.ConfigureAwait(false);
}
}
}