|
| 1 | +using System.Text.RegularExpressions; |
| 2 | + |
| 3 | +namespace EffectiveCSharp.Analyzers; |
| 4 | + |
| 5 | +/// <summary> |
| 6 | +/// A <see cref="CodeFixProvider"/> that provides a code fix for the <see cref="ReplaceStringFormatAnalyzer"/>. |
| 7 | +/// </summary> |
| 8 | +/// <seealso cref="Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider" /> |
| 9 | +[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(ReplaceStringFormatCodeFixProvider))] |
| 10 | +[Shared] |
| 11 | +public class ReplaceStringFormatCodeFixProvider : CodeFixProvider |
| 12 | +{ |
| 13 | + private const string Title = "Replace with interpolated string"; |
| 14 | + |
| 15 | + /// <inheritdoc /> |
| 16 | + public override sealed ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(DiagnosticIds.ReplaceStringFormatWithInterpolatedString); |
| 17 | + |
| 18 | + /// <inheritdoc /> |
| 19 | + public override sealed FixAllProvider GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer; |
| 20 | + |
| 21 | + /// <inheritdoc /> |
| 22 | + public override sealed async Task RegisterCodeFixesAsync(CodeFixContext context) |
| 23 | + { |
| 24 | + Diagnostic diagnostic = context.Diagnostics[0]; |
| 25 | + TextSpan diagnosticSpan = diagnostic.Location.SourceSpan; |
| 26 | + |
| 27 | + SyntaxNode? root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); |
| 28 | + InvocationExpressionSyntax? invocationExpr = root?.FindNode(diagnosticSpan).FirstAncestorOrSelf<InvocationExpressionSyntax>(); |
| 29 | + |
| 30 | + context.RegisterCodeFix( |
| 31 | + CodeAction.Create( |
| 32 | + title: Title, |
| 33 | + createChangedSolution: c => ReplaceWithInterpolatedStringAsync(context.Document, invocationExpr, c), |
| 34 | + equivalenceKey: Title), |
| 35 | + diagnostic); |
| 36 | + } |
| 37 | + |
| 38 | + private static bool NeedsParentheses(ExpressionSyntax expression) |
| 39 | + { |
| 40 | + // Check if the expression is complex and needs to be wrapped in parentheses |
| 41 | + return expression is BinaryExpressionSyntax or ConditionalExpressionSyntax or AssignmentExpressionSyntax or CastExpressionSyntax; |
| 42 | + } |
| 43 | + |
| 44 | + private static string CreateInterpolatedString(string formatString, ArgumentSyntax[] arguments) |
| 45 | + { |
| 46 | + string result = formatString; |
| 47 | + |
| 48 | + for (int i = 0; i < arguments.Length; i++) |
| 49 | + { |
| 50 | + string argumentText = arguments[i].ToString(); |
| 51 | + |
| 52 | + // Wrap in parentheses if the argument is a complex expression |
| 53 | + if (NeedsParentheses(arguments[i].Expression)) |
| 54 | + { |
| 55 | + argumentText = $"({argumentText})"; |
| 56 | + } |
| 57 | + |
| 58 | + result = Regex.Replace(result, $@"\{{{i}(.*?)\}}", $"{{{argumentText}$1}}", RegexOptions.Compiled, TimeSpan.FromSeconds(1)); |
| 59 | + } |
| 60 | + |
| 61 | + return $"$\"{result}\""; |
| 62 | + } |
| 63 | + |
| 64 | + private static async Task<Solution> ReplaceWithInterpolatedStringAsync(Document document, InvocationExpressionSyntax? invocationExpr, CancellationToken cancellationToken) |
| 65 | + { |
| 66 | + if (invocationExpr == null) |
| 67 | + { |
| 68 | + return document.Project.Solution; |
| 69 | + } |
| 70 | + |
| 71 | + LiteralExpressionSyntax? formatStringLiteral = invocationExpr.ArgumentList.Arguments.First().Expression as LiteralExpressionSyntax; |
| 72 | + string? formatString = formatStringLiteral?.Token.ValueText; |
| 73 | + |
| 74 | + if (string.IsNullOrEmpty(formatString)) |
| 75 | + { |
| 76 | + return document.Project.Solution; |
| 77 | + } |
| 78 | + |
| 79 | + ArgumentSyntax[] arguments = invocationExpr.ArgumentList.Arguments.Skip(1).ToArray(); |
| 80 | + |
| 81 | + // Replace format placeholders with corresponding arguments in an interpolated string format |
| 82 | + string interpolatedString = CreateInterpolatedString(formatString!, arguments); |
| 83 | + SyntaxNode? root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); |
| 84 | + SyntaxNode? newRoot = root?.ReplaceNode(invocationExpr, SyntaxFactory.ParseExpression(interpolatedString)); |
| 85 | + |
| 86 | + return newRoot != null |
| 87 | + ? document.WithSyntaxRoot(newRoot).Project.Solution |
| 88 | + : document.Project.Solution; |
| 89 | + } |
| 90 | +} |
0 commit comments