-
Notifications
You must be signed in to change notification settings - Fork 0
/
InsertDecimalSeparators.cs
77 lines (66 loc) · 2.4 KB
/
InsertDecimalSeparators.cs
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
using System;
using System.Composition;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Rename;
using Microsoft.CodeAnalysis.Text;
using System.Text;
using Microsoft.CodeAnalysis.Formatting;
namespace NumberTooLong
{
[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(InsertDecimalSeparators)), Shared]
public class InsertDecimalSeparators : CodeFixProvider
{
private const string diagnosticId = NumberTooLongAnalyzer.DiagnosticId;
private const string title = "Insert decimal separators";
public sealed override ImmutableArray<string> FixableDiagnosticIds
{
get { return ImmutableArray.Create(diagnosticId); }
}
public sealed override FixAllProvider GetFixAllProvider()
{
return WellKnownFixAllProviders.BatchFixer;
}
public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
{
Diagnostic diagnostic = context.Diagnostics.First();
TextSpan span = diagnostic.Location.SourceSpan;
SyntaxNode root = await context
.Document
.GetSyntaxRootAsync(context.CancellationToken)
.ConfigureAwait(false);
LiteralExpressionSyntax literalSyntax =
root.FindToken(span.Start).Parent as LiteralExpressionSyntax;
context.RegisterCodeFix(
CodeAction.Create(
title,
c => InsertDecimalSeparatorsAsync(context.Document, literalSyntax, c),
equivalenceKey: title),
diagnostic);
}
private async Task<Document> InsertDecimalSeparatorsAsync(
Document document,
LiteralExpressionSyntax literal,
CancellationToken cancellationToken)
{
string text = literal.Token.Text.Replace("_", "");
string newText = text.WithDecimalSeparators();
ExpressionSyntax newSyntax =
SyntaxFactory.ParseExpression(newText)
.WithLeadingTrivia(literal.GetLeadingTrivia())
.WithTrailingTrivia(literal.GetTrailingTrivia())
.WithAdditionalAnnotations(Formatter.Annotation);
SyntaxNode rootNode = await document.GetSyntaxRootAsync();
SyntaxNode newRoot = rootNode.ReplaceNode(literal, newSyntax);
return document.WithSyntaxRoot(newRoot);
}
}
}