-
-
Notifications
You must be signed in to change notification settings - Fork 21
Remove redundant 'ToCharArray' call rule + fixer #120
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
55 changes: 55 additions & 0 deletions
55
src/Creedengo.Core/Analyzers/GC2333.RemoveRedundantToCharArrayCall.Fixer.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,55 @@ | ||
| namespace Creedengo.Core.Analyzers; | ||
|
|
||
| /// <summary>GC2333: Remove redundant 'ToCharArray' call.</summary> | ||
| [ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(RemoveRedundantToCharArrayCallFixer)), Shared] | ||
| public sealed class RemoveRedundantToCharArrayCallFixer : CodeFixProvider | ||
| { | ||
| /// <inheritdoc/> | ||
| public override ImmutableArray<string> FixableDiagnosticIds => _fixableDiagnosticIds; | ||
| private static readonly ImmutableArray<string> _fixableDiagnosticIds = ImmutableArray.Create(RemoveRedundantToCharArrayCall.Descriptor.Id); | ||
|
|
||
| /// <inheritdoc/> | ||
| [ExcludeFromCodeCoverage] | ||
| public override FixAllProvider GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer; | ||
|
|
||
| /// <inheritdoc/> | ||
| public override async Task RegisterCodeFixesAsync(CodeFixContext context) | ||
| { | ||
| if (context.Diagnostics.Length == 0) | ||
| return; | ||
|
|
||
| var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); | ||
| if (root is null) return; | ||
|
|
||
| var nodeToFix = root.FindNode(context.Span, getInnermostNodeForTie: true); | ||
| context.RegisterCodeFix( | ||
| CodeAction.Create( | ||
| title: "Remove redundant 'ToCharArray' call", | ||
| createChangedDocument: token => RefactorAsync(context.Document, nodeToFix, token), | ||
| equivalenceKey: "Remove redundant 'ToCharArray' call"), | ||
| context.Diagnostics); | ||
| } | ||
|
|
||
| private static async Task<Document> RefactorAsync(Document document, SyntaxNode nodeToFix, CancellationToken token) | ||
| { | ||
| var editor = await DocumentEditor.CreateAsync(document, token).ConfigureAwait(false); | ||
|
|
||
| // nodeToFix is the IdentifierNameSyntax "ToCharArray"; climb up to the InvocationExpressionSyntax | ||
| if (nodeToFix.Parent is not MemberAccessExpressionSyntax memberAccess || | ||
| memberAccess.Parent is not InvocationExpressionSyntax invocationSyntax) | ||
| { | ||
| return document; | ||
| } | ||
|
|
||
| if (editor.SemanticModel.GetOperation(invocationSyntax, token) is not IInvocationOperation invocation || | ||
| invocation.Arguments.Length != 0 || | ||
| invocation.Instance is null || | ||
| invocation.TargetMethod.Name != "ToCharArray") | ||
| { | ||
| return document; | ||
| } | ||
|
|
||
| editor.ReplaceNode(invocationSyntax, invocation.Instance.Syntax); | ||
| return editor.GetChangedDocument(); | ||
| } | ||
| } |
56 changes: 56 additions & 0 deletions
56
src/Creedengo.Core/Analyzers/GC2333.RemoveRedundantToCharArrayCall.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,56 @@ | ||
| namespace Creedengo.Core.Analyzers; | ||
|
|
||
| /// <summary>GC2333: Remove redundant 'ToCharArray' call.</summary> | ||
| [DiagnosticAnalyzer(LanguageNames.CSharp)] | ||
| public sealed class RemoveRedundantToCharArrayCall : DiagnosticAnalyzer | ||
| { | ||
| private static readonly ImmutableArray<SyntaxKind> SyntaxKinds = ImmutableArray.Create( | ||
| SyntaxKind.ForEachStatement); | ||
|
|
||
| /// <summary>The diagnostic descriptor.</summary> | ||
| public static DiagnosticDescriptor Descriptor { get; } = Rule.CreateDescriptor( | ||
| id: Rule.Ids.GCI2333_RemoveRedundantToCharArrayCall, | ||
| title: "Remove redundant 'ToCharArray' call", | ||
| message: "The 'ToCharArray' call is redundant", | ||
| category: Rule.Categories.Performance, | ||
| severity: DiagnosticSeverity.Warning, | ||
| description: "The 'ToCharArray' call is redundant and can be removed."); | ||
|
|
||
| /// <inheritdoc/> | ||
| public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => _supportedDiagnostics; | ||
| private static readonly ImmutableArray<DiagnosticDescriptor> _supportedDiagnostics = ImmutableArray.Create(Descriptor); | ||
|
|
||
| /// <inheritdoc/> | ||
| public override void Initialize(AnalysisContext context) | ||
| { | ||
| context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); | ||
| context.EnableConcurrentExecution(); | ||
| context.RegisterSyntaxNodeAction(static context => AnalyzeLoopNode(context), SyntaxKinds); | ||
| } | ||
|
|
||
| private static void AnalyzeLoopNode(SyntaxNodeAnalysisContext context) | ||
| { | ||
| var forEachStatement = (ForEachStatementSyntax)context.Node; | ||
|
|
||
| if (forEachStatement.Expression is not InvocationExpressionSyntax invocation) | ||
| return; | ||
|
|
||
| if (invocation.Expression is not MemberAccessExpressionSyntax memberAccess) | ||
| return; | ||
|
|
||
| if (memberAccess.Name.Identifier.Text != "ToCharArray") | ||
| return; | ||
|
|
||
| var symbolInfo = context.SemanticModel.GetSymbolInfo(memberAccess); | ||
| if (symbolInfo.Symbol is not IMethodSymbol methodSymbol) | ||
| return; | ||
|
|
||
| if (methodSymbol.ContainingType.SpecialType != SpecialType.System_String) | ||
| return; | ||
|
|
||
| if (methodSymbol.Parameters.Length != 0) | ||
| return; | ||
|
|
||
| context.ReportDiagnostic(Diagnostic.Create(Descriptor, memberAccess.Name.GetLocation())); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
177 changes: 177 additions & 0 deletions
177
src/Creedengo.Tests/Tests/G2333.RemoveRedundantToCharArrayCall.Tests.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,177 @@ | ||
| namespace Creedengo.Tests.Tests; | ||
|
|
||
| [TestClass] | ||
| public sealed class RemoveRedundantToCharArrayCallTests | ||
| { | ||
| private static readonly CodeFixerDlg VerifyAsync = TestRunner.VerifyAsync<RemoveRedundantToCharArrayCall, RemoveRedundantToCharArrayCallFixer>; | ||
|
|
||
| [TestMethod] | ||
| public Task EmptyCodeAsync() => VerifyAsync(""); | ||
|
|
||
| // --- No-diagnostic cases --- | ||
|
|
||
| [TestMethod] // foreach expression is not an invocation (plain variable) — first guard | ||
| public Task ForeachOverPlainStringVariableNoDiagnosticAsync() => VerifyAsync(""" | ||
| public class Test | ||
| { | ||
| public void Run() | ||
| { | ||
| string s = "test"; | ||
|
|
||
| foreach (char c in s) | ||
| System.Console.WriteLine(c); | ||
| } | ||
| } | ||
| """); | ||
|
|
||
| [TestMethod] // foreach expression is not an invocation (plain char array) — first guard | ||
| public Task ForeachOverCharArrayNoDiagnosticAsync() => VerifyAsync(""" | ||
| public class Test | ||
| { | ||
| public void Run() | ||
| { | ||
| char[] chars = new char[] { 'a', 'b' }; | ||
|
|
||
| foreach (char c in chars) | ||
| System.Console.WriteLine(c); | ||
| } | ||
| } | ||
| """); | ||
|
|
||
| [TestMethod] // invocation is not a member access (bare method call) — second guard | ||
| public Task ForeachOverBareMethodCallNoDiagnosticAsync() => VerifyAsync(""" | ||
| public class Test | ||
| { | ||
| private static char[] GetChars() => new char[] { 'a', 'b' }; | ||
|
|
||
| public void Run() | ||
| { | ||
| foreach (char c in GetChars()) | ||
| System.Console.WriteLine(c); | ||
| } | ||
| } | ||
| """); | ||
|
|
||
| [TestMethod] // method name is not "ToCharArray" — third guard | ||
| public Task ForeachOverOtherStringMethodNoDiagnosticAsync() => VerifyAsync(""" | ||
| public class Test | ||
| { | ||
| public void Run() | ||
| { | ||
| string s = "hello world"; | ||
|
|
||
| foreach (string part in s.Split(' ')) | ||
| System.Console.WriteLine(part); | ||
| } | ||
| } | ||
| """); | ||
|
|
||
| [TestMethod] // "ToCharArray" on a non-string type — fifth guard (ContainingType.SpecialType check) | ||
| public Task ForeachOverToCharArrayOnCustomTypeNoDiagnosticAsync() => VerifyAsync(""" | ||
| public class MyBuffer | ||
| { | ||
| public char[] ToCharArray() => new char[] { 'x' }; | ||
| } | ||
|
|
||
| public class Test | ||
| { | ||
| public void Run() | ||
| { | ||
| var buf = new MyBuffer(); | ||
|
|
||
| foreach (char c in buf.ToCharArray()) | ||
| System.Console.WriteLine(c); | ||
| } | ||
| } | ||
| """); | ||
|
|
||
| // --- Positive cases (diagnostic + fix) --- | ||
|
|
||
| [TestMethod] | ||
| public Task ToCharArrayOnVariableShouldBeRemovedAsync() => VerifyAsync(""" | ||
| public class Test | ||
| { | ||
| public void Run() | ||
| { | ||
| string s = "test"; | ||
|
|
||
| foreach (char c in s.[|ToCharArray|]()) | ||
| System.Console.WriteLine(c); | ||
| } | ||
| } | ||
| """, | ||
| """ | ||
| public class Test | ||
| { | ||
| public void Run() | ||
| { | ||
| string s = "test"; | ||
|
|
||
| foreach (char c in s) | ||
| System.Console.WriteLine(c); | ||
| } | ||
| } | ||
| """); | ||
|
PendingChanges marked this conversation as resolved.
|
||
|
|
||
| [TestMethod] | ||
| public Task ToCharArrayOnStringLiteralShouldBeRemovedAsync() => VerifyAsync(""" | ||
| public class Test | ||
| { | ||
| public void Run() | ||
| { | ||
| foreach (char c in "hello".[|ToCharArray|]()) | ||
| System.Console.WriteLine(c); | ||
| } | ||
| } | ||
| """, | ||
| """ | ||
| public class Test | ||
| { | ||
| public void Run() | ||
| { | ||
| foreach (char c in "hello") | ||
| System.Console.WriteLine(c); | ||
| } | ||
| } | ||
| """); | ||
|
|
||
| [TestMethod] | ||
| public Task ToCharArrayOnMethodReturnValueShouldBeRemovedAsync() => VerifyAsync(""" | ||
| public class Test | ||
| { | ||
| private static string GetText() => "test"; | ||
|
|
||
| public void Run() | ||
| { | ||
| foreach (char c in GetText().[|ToCharArray|]()) | ||
| System.Console.WriteLine(c); | ||
| } | ||
| } | ||
| """, | ||
| """ | ||
| public class Test | ||
| { | ||
| private static string GetText() => "test"; | ||
|
|
||
| public void Run() | ||
| { | ||
| foreach (char c in GetText()) | ||
| System.Console.WriteLine(c); | ||
| } | ||
| } | ||
| """); | ||
|
|
||
| [TestMethod] // ToCharArray(int, int) overload is not redundant — sixth guard (Parameters.Length != 0) | ||
| public Task ToCharArrayWithArgumentsNoDiagnosticAsync() => VerifyAsync(""" | ||
| public class Test | ||
| { | ||
| public void Run() | ||
| { | ||
| string s = "test"; | ||
|
|
||
| foreach (char c in s.ToCharArray(0, 2)) | ||
| System.Console.WriteLine(c); | ||
| } | ||
| } | ||
| """); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.