|
| 1 | +using System.Collections.Immutable; |
| 2 | +using System.Composition; |
| 3 | +using Microsoft.CodeAnalysis; |
| 4 | +using Microsoft.CodeAnalysis.CodeActions; |
| 5 | +using Microsoft.CodeAnalysis.CodeFixes; |
| 6 | +using Microsoft.CodeAnalysis.CSharp; |
| 7 | +using Microsoft.CodeAnalysis.CSharp.Syntax; |
| 8 | +using Microsoft.CodeAnalysis.Editing; |
| 9 | +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; |
| 10 | + |
| 11 | +namespace GraphQL.Analyzers; |
| 12 | + |
| 13 | +[Shared] |
| 14 | +[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(FieldArgumentCodeFixProvider))] |
| 15 | +public class FieldArgumentCodeFixProvider : CodeFixProvider |
| 16 | +{ |
| 17 | + private const string LAMBDA_EXPRESSION_PARAMETER_NAME = "argument"; |
| 18 | + |
| 19 | + public sealed override ImmutableArray<string> FixableDiagnosticIds { get; } = |
| 20 | + ImmutableArray.Create(FieldArgumentAnalyzer.DoNotUseObsoleteArgumentMethod.Id); |
| 21 | + |
| 22 | + public sealed override FixAllProvider GetFixAllProvider() => |
| 23 | + WellKnownFixAllProviders.BatchFixer; |
| 24 | + |
| 25 | + public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) |
| 26 | + { |
| 27 | + var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); |
| 28 | + |
| 29 | + foreach (var diagnostic in context.Diagnostics) |
| 30 | + { |
| 31 | + var diagnosticSpan = diagnostic.Location.SourceSpan; |
| 32 | + |
| 33 | + var argumentInvocation = (InvocationExpressionSyntax)root!.FindNode(diagnosticSpan); |
| 34 | + |
| 35 | + const string codeFixTitle = "Rewrite obsolete 'Argument' method"; |
| 36 | + |
| 37 | + context.RegisterCodeFix( |
| 38 | + CodeAction.Create( |
| 39 | + title: codeFixTitle, |
| 40 | + createChangedDocument: ct => |
| 41 | + RewriteArgumentMethodAsync(context.Document, argumentInvocation, ct), |
| 42 | + equivalenceKey: codeFixTitle), |
| 43 | + diagnostic); |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + private static async Task<Document> RewriteArgumentMethodAsync( |
| 48 | + Document document, |
| 49 | + InvocationExpressionSyntax argumentInvocation, |
| 50 | + CancellationToken cancellationToken) |
| 51 | + { |
| 52 | + var docEditor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false); |
| 53 | + |
| 54 | + var argumentMemberAccess = (MemberAccessExpressionSyntax)argumentInvocation.Expression; |
| 55 | + if (argumentMemberAccess.Name is not GenericNameSyntax genericName) |
| 56 | + { |
| 57 | + return document; |
| 58 | + } |
| 59 | + |
| 60 | + if (genericName.TypeArgumentList.Arguments.Count != 2) |
| 61 | + { |
| 62 | + return document; |
| 63 | + } |
| 64 | + |
| 65 | + var newMethodName = genericName |
| 66 | + .WithTypeArgumentList( |
| 67 | + RewriteTypeArgumentList(genericName)); |
| 68 | + |
| 69 | + docEditor.ReplaceNode(argumentMemberAccess.Name, newMethodName); |
| 70 | + |
| 71 | + var semanticModel = (await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false))!; |
| 72 | + var defaultValueArg = argumentInvocation.GetMethodArgument(Constants.ArgumentNames.DefaultValue, semanticModel); |
| 73 | + |
| 74 | + // .Argument<T>(x, y) or .Argument<T>(x, y, configure: arg => ...) |
| 75 | + if (defaultValueArg == null) |
| 76 | + { |
| 77 | + return docEditor.GetChangedDocument(); |
| 78 | + } |
| 79 | + |
| 80 | + var configureArg = argumentInvocation.GetMethodArgument(Constants.ArgumentNames.Configure, semanticModel); |
| 81 | + |
| 82 | + // .Argument<T>(x, y, defaultValue) |
| 83 | + if (configureArg == null) |
| 84 | + { |
| 85 | + var configureLambdaArg = CreateConfigureLambdaArgument(defaultValueArg); |
| 86 | + docEditor.ReplaceNode(defaultValueArg, configureLambdaArg); |
| 87 | + return docEditor.GetChangedDocument(); |
| 88 | + } |
| 89 | + |
| 90 | + if (configureArg.Expression is not SimpleLambdaExpressionSyntax configureLambda) |
| 91 | + { |
| 92 | + return document; |
| 93 | + } |
| 94 | + |
| 95 | + // .Argument<,>(x, y, defaultValue, arg => ...) |
| 96 | + // .Argument<,>(x, y, arg => ...) |
| 97 | + // .Argument<>(x, y, arg => ...) |
| 98 | + SimpleLambdaExpressionSyntax? newConfigureLambda; |
| 99 | + |
| 100 | + // arg => { arg.Prop = val; } |
| 101 | + if (configureLambda.Block != null) |
| 102 | + { |
| 103 | + newConfigureLambda = AddDefaultValueToConfigureLambdaBlock(configureLambda); |
| 104 | + } |
| 105 | + // arg => arg.Prop = val |
| 106 | + else if (configureLambda.ExpressionBody != null) |
| 107 | + { |
| 108 | + newConfigureLambda = ConvertBodyConfigureLambdaToBlockLambda(configureLambda); |
| 109 | + } |
| 110 | + else |
| 111 | + { |
| 112 | + // theoretically should never happen |
| 113 | + return document; |
| 114 | + } |
| 115 | + |
| 116 | + var newMethodArgumentList = argumentInvocation.ArgumentList |
| 117 | + .Arguments |
| 118 | + .Insert(2, Argument(newConfigureLambda)) |
| 119 | + .RemoveAt(4) |
| 120 | + .RemoveAt(3); |
| 121 | + |
| 122 | + var newArgumentsList = argumentInvocation.ArgumentList.WithArguments(newMethodArgumentList); |
| 123 | + docEditor.ReplaceNode(argumentInvocation.ArgumentList, newArgumentsList); |
| 124 | + |
| 125 | + return docEditor.GetChangedDocument(); |
| 126 | + |
| 127 | + SimpleLambdaExpressionSyntax AddDefaultValueToConfigureLambdaBlock(SimpleLambdaExpressionSyntax lambda) |
| 128 | + { |
| 129 | + var (leadingTrivia, trailingTrivia) = GetBlockStatementTrivia(lambda.Block!); |
| 130 | + var defaultValueStatement = CreateDefaultValueStatement(leadingTrivia, defaultValueArg, trailingTrivia); |
| 131 | + |
| 132 | + return lambda.WithBlock( |
| 133 | + lambda.Block!.AddStatements(defaultValueStatement)); |
| 134 | + } |
| 135 | + |
| 136 | + SimpleLambdaExpressionSyntax ConvertBodyConfigureLambdaToBlockLambda(SimpleLambdaExpressionSyntax lambda) |
| 137 | + { |
| 138 | + var whitespace = Whitespace(" "); |
| 139 | + var block = SyntaxFactory |
| 140 | + .Block( |
| 141 | + ExpressionStatement(lambda.ExpressionBody!.WithoutTrailingTrivia()) |
| 142 | + .WithLeadingTrivia(whitespace), |
| 143 | + ExpressionStatement( |
| 144 | + CreateDefaultValuePropertyAssignment(lambda.Parameter.ToString(), defaultValueArg.Expression)) |
| 145 | + .WithLeadingTrivia(whitespace) |
| 146 | + .WithTrailingTrivia(whitespace)) |
| 147 | + .WithLeadingTrivia(lambda.ExpressionBody!.GetLeadingTrivia()); |
| 148 | + |
| 149 | + return SimpleLambdaExpression(lambda.Parameter, block) |
| 150 | + .WithArrowToken(lambda.ArrowToken); |
| 151 | + } |
| 152 | + } |
| 153 | + |
| 154 | + private static (SyntaxTriviaList leadingTrivia, SyntaxTriviaList trailingTrivia) GetBlockStatementTrivia(BlockSyntax block) |
| 155 | + { |
| 156 | + var lastStatement = block.Statements.LastOrDefault(); |
| 157 | + |
| 158 | + // argument => |
| 159 | + // { |
| 160 | + // statement; |
| 161 | + // } |
| 162 | + // or |
| 163 | + // argument => { statement; } |
| 164 | + if (lastStatement != null) |
| 165 | + { |
| 166 | + return (lastStatement.GetLeadingTrivia(), lastStatement.GetTrailingTrivia()); |
| 167 | + } |
| 168 | + |
| 169 | + // argument => { } |
| 170 | + if (block.OpenBraceToken.GetLocation().GetLineSpan().StartLinePosition.Line == |
| 171 | + block.CloseBraceToken.GetLocation().GetLineSpan().StartLinePosition.Line) |
| 172 | + { |
| 173 | + return (SyntaxTriviaList.Empty, SyntaxTriviaList.Empty); |
| 174 | + } |
| 175 | + |
| 176 | + // argument => |
| 177 | + // { |
| 178 | + // } |
| 179 | + var leadingTrivia = block.GetLeadingTrivia().Add(Whitespace(" ")); |
| 180 | + |
| 181 | + return (leadingTrivia, new SyntaxTriviaList(EndOfLine(Environment.NewLine))); |
| 182 | + } |
| 183 | + |
| 184 | + // {whitespaces}argument.DefaultValue = xxx;\n |
| 185 | + private static ExpressionStatementSyntax CreateDefaultValueStatement( |
| 186 | + SyntaxTriviaList leadingTrivia, |
| 187 | + ArgumentSyntax defaultValueArg, |
| 188 | + SyntaxTriviaList trailingTrivia) => |
| 189 | + ExpressionStatement(CreateDefaultValuePropertyAssignment(defaultValueArg.Expression)) |
| 190 | + .WithLeadingTrivia(leadingTrivia) |
| 191 | + .WithTrailingTrivia(trailingTrivia); |
| 192 | + |
| 193 | + // argument => argument.DefaultValue = expression |
| 194 | + private static ArgumentSyntax CreateConfigureLambdaArgument(ArgumentSyntax defaultValueArg) |
| 195 | + { |
| 196 | + var configureLambda = ParseExpression( |
| 197 | + $"{LAMBDA_EXPRESSION_PARAMETER_NAME} => {CreateDefaultValuePropertyAssignment(defaultValueArg.Expression)}") |
| 198 | + .WithLeadingTrivia(defaultValueArg.GetLeadingTrivia()); |
| 199 | + |
| 200 | + return Argument(configureLambda); |
| 201 | + } |
| 202 | + |
| 203 | + // argument.DefaultValue = expression |
| 204 | + private static ExpressionSyntax CreateDefaultValuePropertyAssignment(ExpressionSyntax expression) => |
| 205 | + CreateDefaultValuePropertyAssignment(LAMBDA_EXPRESSION_PARAMETER_NAME, expression); |
| 206 | + |
| 207 | + // parameterName.DefaultValue = expression |
| 208 | + private static ExpressionSyntax CreateDefaultValuePropertyAssignment(string parameterName, ExpressionSyntax expression) => |
| 209 | + ParseExpression($"{parameterName}.{Constants.ObjectProperties.DefaultValue} = {expression}"); |
| 210 | + |
| 211 | + // from Argument<TArgumentGraphType, TArgumentType> |
| 212 | + // to Argument<TArgumentGraphType> |
| 213 | + private static TypeArgumentListSyntax RewriteTypeArgumentList(GenericNameSyntax genericName) => |
| 214 | + genericName.TypeArgumentList |
| 215 | + .WithArguments( |
| 216 | + SingletonSeparatedList( |
| 217 | + genericName.TypeArgumentList.Arguments.First())); |
| 218 | +} |
0 commit comments