|
| 1 | +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information. |
| 2 | + |
| 3 | +using System.Collections.Immutable; |
| 4 | +using System.Composition; |
| 5 | +using System.Threading; |
| 6 | +using System.Threading.Tasks; |
| 7 | +using Analyzer.Utilities; |
| 8 | +using Analyzer.Utilities.Extensions; |
| 9 | +using Microsoft.CodeAnalysis; |
| 10 | +using Microsoft.CodeAnalysis.CodeActions; |
| 11 | +using Microsoft.CodeAnalysis.CodeFixes; |
| 12 | +using Microsoft.CodeAnalysis.Editing; |
| 13 | + |
| 14 | +namespace Microsoft.NetCore.Analyzers.Performance |
| 15 | +{ |
| 16 | + /// <summary> |
| 17 | + /// CA1876: Use ReadOnlySpan<T> or ReadOnlyMemory<T> instead of Span<T> or Memory<T> |
| 18 | + /// </summary> |
| 19 | + [ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(PreferReadOnlySpanOverSpanFixer))] |
| 20 | + [Shared] |
| 21 | + public sealed class PreferReadOnlySpanOverSpanFixer : CodeFixProvider |
| 22 | + { |
| 23 | + public sealed override ImmutableArray<string> FixableDiagnosticIds { get; } = |
| 24 | + ImmutableArray.Create(PreferReadOnlySpanOverSpanAnalyzer.RuleId); |
| 25 | + |
| 26 | + public sealed override FixAllProvider GetFixAllProvider() |
| 27 | + { |
| 28 | + return WellKnownFixAllProviders.BatchFixer; |
| 29 | + } |
| 30 | + |
| 31 | + public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) |
| 32 | + { |
| 33 | + var root = await context.Document.GetRequiredSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); |
| 34 | + var node = root.FindNode(context.Span, getInnermostNodeForTie: true); |
| 35 | + var semanticModel = await context.Document.GetRequiredSemanticModelAsync(context.CancellationToken).ConfigureAwait(false); |
| 36 | + |
| 37 | + var diagnostic = context.Diagnostics[0]; |
| 38 | + |
| 39 | + if (semanticModel.GetDeclaredSymbol(node, context.CancellationToken) is not IParameterSymbol parameterSymbol || |
| 40 | + GetReadOnlyTypeName(parameterSymbol.Type) is not { } targetTypeName) |
| 41 | + { |
| 42 | + return; |
| 43 | + } |
| 44 | + |
| 45 | + var title = string.Format(MicrosoftNetCoreAnalyzersResources.PreferReadOnlySpanOverSpanCodeFixTitle, targetTypeName); |
| 46 | + |
| 47 | + context.RegisterCodeFix( |
| 48 | + CodeAction.Create( |
| 49 | + title: title, |
| 50 | + createChangedDocument: c => ChangeParameterTypeAsync(context.Document, node, c), |
| 51 | + equivalenceKey: title), |
| 52 | + diagnostic); |
| 53 | + } |
| 54 | + |
| 55 | + private static string? GetReadOnlyTypeName(ITypeSymbol typeSymbol) |
| 56 | + { |
| 57 | + return typeSymbol is INamedTypeSymbol namedType && namedType.OriginalDefinition.Name is "Span" or "Memory" ? |
| 58 | + $"ReadOnly{typeSymbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)}" : |
| 59 | + null; |
| 60 | + } |
| 61 | + |
| 62 | + private static async Task<Document> ChangeParameterTypeAsync( |
| 63 | + Document document, |
| 64 | + SyntaxNode node, |
| 65 | + CancellationToken cancellationToken) |
| 66 | + { |
| 67 | + var editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false); |
| 68 | + var generator = editor.Generator; |
| 69 | + var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); |
| 70 | + |
| 71 | + // Get the parameter symbol to construct the correct type |
| 72 | + var parameterSymbol = semanticModel.GetDeclaredSymbol(node, cancellationToken) as IParameterSymbol; |
| 73 | + if (parameterSymbol?.Type is not INamedTypeSymbol namedType || namedType.TypeArguments.Length != 1) |
| 74 | + { |
| 75 | + return document; |
| 76 | + } |
| 77 | + |
| 78 | + // Get the compilation to find the readonly types |
| 79 | + var compilation = semanticModel.Compilation; |
| 80 | + var typeName = namedType.OriginalDefinition.Name; |
| 81 | + INamedTypeSymbol? readOnlyType = null; |
| 82 | + |
| 83 | + if (typeName == "Span") |
| 84 | + { |
| 85 | + readOnlyType = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemReadOnlySpan1); |
| 86 | + } |
| 87 | + else if (typeName == "Memory") |
| 88 | + { |
| 89 | + readOnlyType = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemReadOnlyMemory1); |
| 90 | + } |
| 91 | + |
| 92 | + if (readOnlyType == null) |
| 93 | + { |
| 94 | + return document; |
| 95 | + } |
| 96 | + |
| 97 | + // Construct the generic type with the same type argument |
| 98 | + var newType = readOnlyType.Construct(namedType.TypeArguments[0]); |
| 99 | + var newTypeNode = generator.TypeExpression(newType); |
| 100 | + |
| 101 | + // Replace the parameter's type |
| 102 | + editor.ReplaceNode(node, (currentNode, gen) => |
| 103 | + { |
| 104 | + return gen.WithType(currentNode, newTypeNode); |
| 105 | + }); |
| 106 | + |
| 107 | + return editor.GetChangedDocument(); |
| 108 | + } |
| 109 | + } |
| 110 | +} |
0 commit comments