|
| 1 | +namespace EffectiveCSharp.Analyzers; |
| 2 | + |
| 3 | +/// <summary> |
| 4 | +/// A <see cref="CodeFixProvider"/> that provides a code fix for the <see cref="AvoidStringlyTypedApisAnalyzer"/>. |
| 5 | +/// </summary> |
| 6 | +/// <seealso cref="Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider" /> |
| 7 | +[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(AvoidStringlyTypedApisCodeFixProvider))] |
| 8 | +[Shared] |
| 9 | +public class AvoidStringlyTypedApisCodeFixProvider : CodeFixProvider |
| 10 | +{ |
| 11 | + private const string Title = "Use nameof operator"; |
| 12 | + |
| 13 | + /// <inheritdoc/> |
| 14 | + public sealed override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(DiagnosticIds.AvoidStringlyTypedApis); |
| 15 | + |
| 16 | + /// <inheritdoc/> |
| 17 | + public sealed override FixAllProvider GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer; |
| 18 | + |
| 19 | + /// <inheritdoc/> |
| 20 | + public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) |
| 21 | + { |
| 22 | + SyntaxNode? root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); |
| 23 | + Diagnostic diagnostic = context.Diagnostics.First(); |
| 24 | + TextSpan diagnosticSpan = diagnostic.Location.SourceSpan; |
| 25 | + |
| 26 | + SyntaxNode? node = root?.FindNode(diagnosticSpan); |
| 27 | + |
| 28 | + LiteralExpressionSyntax? literalExpression = node switch |
| 29 | + { |
| 30 | + // Check if the node is a LiteralExpressionSyntax directly |
| 31 | + LiteralExpressionSyntax literalNode => literalNode, |
| 32 | + |
| 33 | + // Check if the node is an ArgumentSyntax containing a LiteralExpressionSyntax |
| 34 | + ArgumentSyntax { Expression: LiteralExpressionSyntax argLiteralNode } => argLiteralNode, |
| 35 | + |
| 36 | + _ => null |
| 37 | + }; |
| 38 | + |
| 39 | + if (literalExpression != null) |
| 40 | + { |
| 41 | + context.RegisterCodeFix( |
| 42 | + CodeAction.Create( |
| 43 | + title: Title, |
| 44 | + createChangedSolution: c => UseNameofOperatorAsync(context.Document, literalExpression, c), |
| 45 | + equivalenceKey: Title), |
| 46 | + diagnostic); |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + private static async Task<Solution> UseNameofOperatorAsync(Document document, LiteralExpressionSyntax? literalExpression, CancellationToken cancellationToken) |
| 51 | + { |
| 52 | + string literalValue = literalExpression?.Token.ValueText; |
| 53 | + |
| 54 | + // Walk up the syntax tree to find the containing class or method |
| 55 | + TypeDeclarationSyntax? containingClass = literalExpression?.FirstAncestorOrSelf<TypeDeclarationSyntax>(); |
| 56 | + MethodDeclarationSyntax? containingMethod = literalExpression?.FirstAncestorOrSelf<MethodDeclarationSyntax>(); |
| 57 | + |
| 58 | + string? nameofExpressionText = null; |
| 59 | + |
| 60 | + if (containingClass != null) |
| 61 | + { |
| 62 | + SemanticModel? semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); |
| 63 | + |
| 64 | + if (semanticModel.GetDeclaredSymbol(containingClass, cancellationToken) is { } containingTypeSymbol) |
| 65 | + { |
| 66 | + IEnumerable<string> memberNames = containingTypeSymbol.GetMembers().Select(member => member.Name); |
| 67 | + |
| 68 | + if (memberNames.Contains(literalValue)) |
| 69 | + { |
| 70 | + nameofExpressionText = $"nameof({literalValue})"; |
| 71 | + } |
| 72 | + } |
| 73 | + } |
| 74 | + |
| 75 | + if (nameofExpressionText == null && containingMethod != null) |
| 76 | + { |
| 77 | + SemanticModel? semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); |
| 78 | + |
| 79 | + if (semanticModel.GetDeclaredSymbol(containingMethod, cancellationToken) is { } methodSymbol) |
| 80 | + { |
| 81 | + IEnumerable<string> parameterNames = methodSymbol.Parameters.Select(parameter => parameter.Name); |
| 82 | + |
| 83 | + if (parameterNames.Contains(literalValue)) |
| 84 | + { |
| 85 | + nameofExpressionText = $"nameof({literalValue})"; |
| 86 | + } |
| 87 | + } |
| 88 | + } |
| 89 | + |
| 90 | + if (nameofExpressionText == null) |
| 91 | + { |
| 92 | + return document.Project.Solution; |
| 93 | + } |
| 94 | + |
| 95 | + if (literalExpression != null) |
| 96 | + { |
| 97 | + ExpressionSyntax nameofExpression = SyntaxFactory.ParseExpression(nameofExpressionText) |
| 98 | + .WithTriviaFrom(literalExpression); |
| 99 | + |
| 100 | + SyntaxNode? root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); |
| 101 | + SyntaxNode? newRoot = root?.ReplaceNode(literalExpression, nameofExpression); |
| 102 | + |
| 103 | + if (newRoot != null) |
| 104 | + { |
| 105 | + return document.WithSyntaxRoot(newRoot).Project.Solution; |
| 106 | + } |
| 107 | + } |
| 108 | + |
| 109 | + return document.Project.Solution; |
| 110 | + } |
| 111 | +} |
0 commit comments