|
| 1 | +using System.Collections.Immutable; |
| 2 | +using System.Composition; |
| 3 | +using System.Linq; |
| 4 | +using System.Threading; |
| 5 | +using System.Threading.Tasks; |
| 6 | +using Microsoft.CodeAnalysis; |
| 7 | +using Microsoft.CodeAnalysis.CodeFixes; |
| 8 | +using Microsoft.CodeAnalysis.CSharp; |
| 9 | +using Microsoft.CodeAnalysis.CSharp.Syntax; |
| 10 | +using Microsoft.CodeAnalysis.Editing; |
| 11 | +using Microsoft.CodeAnalysis.FindSymbols; |
| 12 | +using Sharpen.Analyzer.FixProvider.Common; |
| 13 | +using Sharpen.Analyzer.Rules; |
| 14 | +using Sharpen.Analyzer.Safety.FixProviderSafety; |
| 15 | + |
| 16 | +namespace Sharpen.Analyzer; |
| 17 | + |
| 18 | +[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(PreferParamsCollectionsCodeFixProvider))] |
| 19 | +[Shared] |
| 20 | +public sealed class PreferParamsCollectionsCodeFixProvider : CSharp13OrAboveSharpenCodeFixProvider |
| 21 | +{ |
| 22 | + public override ImmutableArray<string> FixableDiagnosticIds => |
| 23 | + ImmutableArray.Create(CSharp13Rules.PreferParamsCollectionsRule.Id); |
| 24 | + |
| 25 | + protected override async Task RegisterCodeFixesAsync(CodeFixContext context, SyntaxNode root, Diagnostic diagnostic) |
| 26 | + { |
| 27 | + var parameter = root.FindNode(diagnostic.Location.SourceSpan, getInnermostNodeForTie: true) |
| 28 | + .FirstAncestorOrSelf<ParameterSyntax>(); |
| 29 | + if (parameter is null) |
| 30 | + return; |
| 31 | + |
| 32 | + var semanticModel = await context.Document.GetSemanticModelAsync(context.CancellationToken).ConfigureAwait(false); |
| 33 | + if (semanticModel is null) |
| 34 | + return; |
| 35 | + |
| 36 | + // Fix-provider-side safety gate: only offer code actions when the mapped safety checker says it's safe. |
| 37 | + var safetyEvaluation = FixProviderSafetyRunner.EvaluateOrMatchFailed( |
| 38 | + checker: new PreferParamsCollectionsSafetyChecker(), |
| 39 | + syntaxTree: root.SyntaxTree, |
| 40 | + semanticModel: semanticModel, |
| 41 | + diagnostic: diagnostic, |
| 42 | + matchSucceeded: true, |
| 43 | + cancellationToken: context.CancellationToken); |
| 44 | + |
| 45 | + if (safetyEvaluation.Outcome != FixProviderSafetyOutcome.Safe) |
| 46 | + return; |
| 47 | + |
| 48 | + RegisterCodeFix( |
| 49 | + context: context, |
| 50 | + diagnostic: diagnostic, |
| 51 | + title: "Prefer collection-based params", |
| 52 | + equivalenceKey: nameof(PreferParamsCollectionsCodeFixProvider), |
| 53 | + createChangedDocument: ct => ApplyAsync(context.Document, parameter, ct)); |
| 54 | + } |
| 55 | + |
| 56 | + private static async Task<Document> ApplyAsync(Document document, ParameterSyntax parameter, CancellationToken ct) |
| 57 | + { |
| 58 | + var semanticModel = await document.GetSemanticModelAsync(ct).ConfigureAwait(false); |
| 59 | + if (semanticModel is null) |
| 60 | + return document; |
| 61 | + |
| 62 | + var method = parameter.FirstAncestorOrSelf<BaseMethodDeclarationSyntax>(); |
| 63 | + if (method is null) |
| 64 | + return document; |
| 65 | + |
| 66 | + var methodSymbol = semanticModel.GetDeclaredSymbol(method, ct) as IMethodSymbol; |
| 67 | + if (methodSymbol is null) |
| 68 | + return document; |
| 69 | + |
| 70 | + var parameterSymbol = semanticModel.GetDeclaredSymbol(parameter, ct) as IParameterSymbol; |
| 71 | + if (parameterSymbol is null) |
| 72 | + return document; |
| 73 | + |
| 74 | + // Target type: ReadOnlySpan<T> |
| 75 | + var elementType = (parameterSymbol.Type as IArrayTypeSymbol)?.ElementType; |
| 76 | + if (elementType is null) |
| 77 | + return document; |
| 78 | + |
| 79 | + var readOnlySpanType = semanticModel.Compilation.GetTypeByMetadataName("System.ReadOnlySpan`1"); |
| 80 | + if (readOnlySpanType is null) |
| 81 | + return document; |
| 82 | + |
| 83 | + var newParamType = readOnlySpanType.Construct(elementType); |
| 84 | + |
| 85 | + // 1) Update declaration |
| 86 | + var editor = await DocumentEditor.CreateAsync(document, ct).ConfigureAwait(false); |
| 87 | + var newTypeSyntax = SyntaxFactory.ParseTypeName(newParamType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)) |
| 88 | + .WithTriviaFrom(parameter.Type!); |
| 89 | + |
| 90 | + editor.ReplaceNode(parameter.Type!, newTypeSyntax); |
| 91 | + |
| 92 | + var updatedDocument = editor.GetChangedDocument(); |
| 93 | + var updatedSolution = updatedDocument.Project.Solution; |
| 94 | + |
| 95 | + // 2) Update in-solution call sites |
| 96 | + var updatedCompilation = await updatedDocument.Project.GetCompilationAsync(ct).ConfigureAwait(false); |
| 97 | + if (updatedCompilation is null) |
| 98 | + return updatedDocument; |
| 99 | + |
| 100 | + // We keep using the original symbol for reference search; SymbolFinder works across the solution. |
| 101 | + var references = await SymbolFinder.FindReferencesAsync(methodSymbol, updatedSolution, ct).ConfigureAwait(false); |
| 102 | + |
| 103 | + foreach (var reference in references) |
| 104 | + { |
| 105 | + foreach (var location in reference.Locations) |
| 106 | + { |
| 107 | + var refDocument = updatedSolution.GetDocument(location.Document.Id); |
| 108 | + if (refDocument is null) |
| 109 | + continue; |
| 110 | + |
| 111 | + var refRoot = await refDocument.GetSyntaxRootAsync(ct).ConfigureAwait(false); |
| 112 | + if (refRoot is null) |
| 113 | + continue; |
| 114 | + |
| 115 | + var node = refRoot.FindNode(location.Location.SourceSpan, getInnermostNodeForTie: true); |
| 116 | + var invocation = node.FirstAncestorOrSelf<InvocationExpressionSyntax>(); |
| 117 | + if (invocation is null) |
| 118 | + continue; |
| 119 | + |
| 120 | + var refSemanticModel = await refDocument.GetSemanticModelAsync(ct).ConfigureAwait(false); |
| 121 | + if (refSemanticModel is null) |
| 122 | + continue; |
| 123 | + |
| 124 | + var invokedSymbol = refSemanticModel.GetSymbolInfo(invocation, ct).Symbol as IMethodSymbol; |
| 125 | + if (invokedSymbol is null) |
| 126 | + continue; |
| 127 | + |
| 128 | + // Only update invocations that bind to the same method. |
| 129 | + if (!SymbolEqualityComparer.Default.Equals(invokedSymbol.OriginalDefinition, methodSymbol.OriginalDefinition)) |
| 130 | + continue; |
| 131 | + |
| 132 | + // If the call already passes an array explicitly, leave it (ReadOnlySpan<T> can be created from array implicitly). |
| 133 | + // If the call uses expanded params arguments, wrap them into an array creation. |
| 134 | + var args = invocation.ArgumentList.Arguments; |
| 135 | + var paramIndex = parameterSymbol.Ordinal; |
| 136 | + if (args.Count <= paramIndex) |
| 137 | + continue; |
| 138 | + |
| 139 | + // Determine if this is an expanded params call: more args than parameters. |
| 140 | + // (If the call passes a single argument at the params position, we assume it's already an array-like value.) |
| 141 | + var isExpanded = args.Count > methodSymbol.Parameters.Length; |
| 142 | + if (!isExpanded) |
| 143 | + continue; |
| 144 | + |
| 145 | + var expandedArgs = args.Skip(paramIndex).ToImmutableArray(); |
| 146 | + var arrayCreation = SyntaxFactory.ArrayCreationExpression( |
| 147 | + SyntaxFactory.ArrayType( |
| 148 | + SyntaxFactory.ParseTypeName(elementType.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)), |
| 149 | + SyntaxFactory.SingletonList(SyntaxFactory.ArrayRankSpecifier( |
| 150 | + SyntaxFactory.SingletonSeparatedList<ExpressionSyntax>(SyntaxFactory.OmittedArraySizeExpression()))))) |
| 151 | + .WithInitializer(SyntaxFactory.InitializerExpression( |
| 152 | + SyntaxKind.ArrayInitializerExpression, |
| 153 | + SyntaxFactory.SeparatedList(expandedArgs.Select(a => a.Expression)))); |
| 154 | + |
| 155 | + var newArgs = args.Take(paramIndex) |
| 156 | + .Concat(new[] { SyntaxFactory.Argument(arrayCreation).WithTriviaFrom(args[paramIndex]) }) |
| 157 | + .ToImmutableArray(); |
| 158 | + |
| 159 | + var newInvocation = invocation.WithArgumentList(SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList(newArgs))); |
| 160 | + |
| 161 | + var refEditor = await DocumentEditor.CreateAsync(refDocument, ct).ConfigureAwait(false); |
| 162 | + refEditor.ReplaceNode(invocation, newInvocation); |
| 163 | + updatedSolution = refEditor.GetChangedDocument().Project.Solution; |
| 164 | + } |
| 165 | + } |
| 166 | + |
| 167 | + return updatedSolution.GetDocument(document.Id) ?? updatedDocument; |
| 168 | + } |
| 169 | +} |
0 commit comments