-
Notifications
You must be signed in to change notification settings - Fork 465
/
AvoidConstArrays.Fixer.cs
176 lines (152 loc) · 8.6 KB
/
AvoidConstArrays.Fixer.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information.
using System;
using System.Linq;
using System.Globalization;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Composition;
using System.Threading;
using System.Threading.Tasks;
using Analyzer.Utilities;
using Analyzer.Utilities.Extensions;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Operations;
namespace Microsoft.NetCore.Analyzers.Runtime
{
/// <summary>
/// CA1861: Avoid constant arrays as arguments. Replace with static readonly arrays.
/// </summary>
[ExportCodeFixProvider(LanguageNames.CSharp, LanguageNames.VisualBasic), Shared]
public sealed class AvoidConstArraysFixer : CodeFixProvider
{
public sealed override ImmutableArray<string> FixableDiagnosticIds { get; } = ImmutableArray.Create(AvoidConstArraysAnalyzer.RuleId);
private static readonly ImmutableArray<string> s_collectionMemberEndings = ImmutableArray.Create("array", "collection", "enumerable", "list");
// See https://github.com/dotnet/roslyn/blob/main/docs/analyzers/FixAllProvider.md for more information on Fix All Providers
public sealed override FixAllProvider GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer;
public override async Task RegisterCodeFixesAsync(CodeFixContext context)
{
Document document = context.Document;
SyntaxNode root = await document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
SyntaxNode node = root.FindNode(context.Span);
SemanticModel model = await document.GetSemanticModelAsync(context.CancellationToken).ConfigureAwait(false);
DocumentEditor editor = await DocumentEditor.CreateAsync(document, context.CancellationToken).ConfigureAwait(false);
string title = MicrosoftNetCoreAnalyzersResources.AvoidConstArraysCodeFixTitle;
context.RegisterCodeFix(CodeAction.Create(
title,
async ct => await ExtractConstArrayAsync(root, node, model, editor, editor.Generator,
context.Diagnostics.First().Properties, ct).ConfigureAwait(false),
equivalenceKey: title),
context.Diagnostics);
}
private static Task<Document> ExtractConstArrayAsync(SyntaxNode root, SyntaxNode node, SemanticModel model, DocumentEditor editor,
SyntaxGenerator generator, ImmutableDictionary<string, string?> properties, CancellationToken cancellationToken)
{
IArrayCreationOperation arrayArgument = GetArrayCreationOperation(node, model, cancellationToken, out bool isInvoked);
INamedTypeSymbol containingType = model.GetEnclosingSymbol(node.SpanStart, cancellationToken).ContainingType;
// Get a valid member name for the extracted constant
string newMemberName = GetExtractedMemberName(containingType.MemberNames, properties["paramName"] ?? GetMemberNameFromType(arrayArgument));
// Get method containing the symbol that is being diagnosed
IOperation? methodContext = arrayArgument.GetAncestor<IMethodBodyOperation>(OperationKind.MethodBody);
methodContext ??= arrayArgument.GetAncestor<IBlockOperation>(OperationKind.Block); // VB methods have a different structure than CS methods
// Create the new member
SyntaxNode newMember = generator.FieldDeclaration(
newMemberName,
generator.TypeExpression(arrayArgument.Type),
GetAccessibility(methodContext is null ? null : model.GetEnclosingSymbol(methodContext.Syntax.SpanStart, cancellationToken)),
DeclarationModifiers.Static | DeclarationModifiers.ReadOnly,
arrayArgument.Syntax.WithoutTrailingTrivia() // don't include extra trivia before the end of the declaration
);
// Add any additional formatting
if (methodContext is not null)
{
newMember = newMember.FormatForExtraction(methodContext.Syntax);
}
ISymbol lastFieldOrPropertSymbol = containingType.GetMembers().LastOrDefault(x => x is IFieldSymbol or IPropertySymbol);
if (lastFieldOrPropertSymbol is not null)
{
// Insert after fields or properties
SyntaxNode lastFieldOrPropertyNode = root.FindNode(lastFieldOrPropertSymbol.Locations.First().SourceSpan);
editor.InsertAfter(generator.GetDeclaration(lastFieldOrPropertyNode), newMember);
}
else
{
// No fields or properties, insert right before the containing method for simplicity
editor.InsertBefore(methodContext?.Syntax, newMember);
}
// Replace argument with a reference to our new member
SyntaxNode identifier = generator.IdentifierName(newMemberName);
if (isInvoked)
{
editor.ReplaceNode(node, generator.WithExpression(identifier, node));
}
else
{
// add any extra trivia that was after the original argument
editor.ReplaceNode(node, generator.Argument(identifier).WithTriviaFrom(arrayArgument.Syntax));
}
// Return changed document
return Task.FromResult(editor.GetChangedDocument());
}
private static IArrayCreationOperation GetArrayCreationOperation(SyntaxNode node, SemanticModel model, CancellationToken cancellationToken, out bool isInvoked)
{
// The analyzer only passes a diagnostic for two scenarios, each having an IArrayCreationOperation:
// 1. The node is an IArgumentOperation that is a direct parent of an IArrayCreationOperation
// 2. The node is an IArrayCreationOperation already, as it was pulled from an
// invocation, like with LINQ extension methods
// If this is a LINQ invocation, the node is already an IArrayCreationOperation
if (model.GetOperation(node, cancellationToken) is IArrayCreationOperation arrayCreation)
{
isInvoked = true;
return arrayCreation;
}
// Otherwise, we'll get the IArrayCreationOperation from the argument node's child
isInvoked = false;
return (IArrayCreationOperation)model.GetOperation(node.ChildNodes().First(), cancellationToken);
}
private static string GetExtractedMemberName(IEnumerable<string> memberNames, string parameterName)
{
bool hasCollectionEnding = s_collectionMemberEndings.Any(x => parameterName.EndsWith(x, true, CultureInfo.InvariantCulture));
if (parameterName == "source" // for LINQ, "sourceArray" is clearer than "source"
|| (memberNames.Contains(parameterName) && !hasCollectionEnding))
{
parameterName += "Array";
}
if (memberNames.Contains(parameterName))
{
int suffix = 0;
while (memberNames.Contains(parameterName + suffix))
{
suffix++;
}
return parameterName + suffix;
}
return parameterName;
}
private static string GetMemberNameFromType(IArrayCreationOperation arrayCreationOperation)
{
#pragma warning disable CA1308 // Normalize strings to uppercase
return ((IArrayTypeSymbol)arrayCreationOperation.Type).ElementType.OriginalDefinition.Name.ToLowerInvariant() + "Array";
#pragma warning restore CA1308 // Normalize strings to uppercase
}
private static Accessibility GetAccessibility(ISymbol? methodSymbol)
{
// If private or public, return private since public accessibility not wanted for fields by default
return methodSymbol?.GetResultantVisibility() switch
{
// Return internal if internal
SymbolVisibility.Internal => Accessibility.Internal,
_ => Accessibility.Private
};
}
}
internal static class SyntaxNodeExtensions
{
internal static SyntaxNode FormatForExtraction(this SyntaxNode node, SyntaxNode previouslyContainingNode)
{
return node.HasTrailingTrivia ? node : node.WithTrailingTrivia(previouslyContainingNode.GetTrailingTrivia());
}
}
}