Skip to content
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

RCS1246 - update, added Last #1436

Merged
merged 6 commits into from
Apr 15, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions ChangeLog.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

- Fix analyzer [RCS1077](https://josefpihrt.github.io/docs/roslynator/analyzers/RCS1077) ([PR](https://github.com/dotnet/roslynator/pull/1428))

### Changed

- Update - add Last [RCS1246](https://josefpihrt.github.io/docs/roslynator/analyzers/RCS1246) ([PR](https://github.com/dotnet/roslynator/pull/1431))
jakubreznak marked this conversation as resolved.
Show resolved Hide resolved

## [4.12.0] - 2024-03-19

### Added
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -257,6 +257,16 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context)
ct => UseElementAccessInsteadOfEnumerableMethodRefactoring.UseElementAccessInsteadOfElementAtAsync(document, invocation, ct),
GetEquivalenceKey(diagnostic, "UseElementAccessInsteadOfElementAt"));

context.RegisterCodeFix(codeAction, diagnostic);
return;
}
case "Last":
{
CodeAction codeAction = CodeAction.Create(
"Use [] instead of calling 'Last'",
ct => UseElementAccessInsteadOfEnumerableMethodRefactoring.UseElementAccessInsteadOfLastAsync(document, invocation, ct),
GetEquivalenceKey(diagnostic, "UseElementAccessInsteadOfLast"));

context.RegisterCodeFix(codeAction, diagnostic);
return;
}
Expand Down
4 changes: 4 additions & 0 deletions src/Analyzers.xml
Original file line number Diff line number Diff line change
Expand Up @@ -7286,6 +7286,10 @@ public class C
<Before><![CDATA[list.ElementAt(1)]]></Before>
<After><![CDATA[list[1]]]></After>
</Sample>
<Sample>
<Before><![CDATA[list.Last()]]></Before>
<After><![CDATA[list[^1]]]></After>
</Sample>
</Samples>
<Options>
<Option Identifier="DoNotUseElementAccessWhenExpressionIsInvocation">
Expand Down
17 changes: 17 additions & 0 deletions src/Analyzers/CSharp/Analysis/InvocationExpressionAnalyzer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,23 @@ private static void AnalyzeInvocationExpression(SyntaxNodeAnalysisContext contex
break;
}
case "Last":
{
if (DiagnosticRules.OptimizeLinqMethodCall.IsEffective(context))
{
if (!invocationInfo.Expression.IsKind(SyntaxKind.ElementAccessExpression, SyntaxKind.InvocationExpression)
&& UseElementAccessAnalysis.IsFixableLast(invocationInfo, context.SemanticModel, context.CancellationToken))
jakubreznak marked this conversation as resolved.
Show resolved Hide resolved
{
DiagnosticHelpers.ReportDiagnostic(
context,
DiagnosticRules.UseElementAccess,
Location.Create(invocation.SyntaxTree, TextSpan.FromBounds(invocationInfo.Name.SpanStart, invocationInfo.ArgumentList.Span.End)));
}

OptimizeLinqMethodCallAnalysis.AnalyzeWhere(context, invocationInfo);
}

break;
}
case "LastOrDefault":
case "LongCount":
case "Single":
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,14 +50,9 @@ public static async Task ComputeRefactoringsAsync(RefactoringContext context, In
if (!UseElementAccessAnalysis.IsFixableLast(invocationInfo, semanticModel, context.CancellationToken))
break;

string propertyName = CSharpUtility.GetCountOrLengthPropertyName(invocationInfo.Expression, semanticModel, context.CancellationToken);

if (propertyName is null)
break;

context.RegisterRefactoring(
"Use [] instead of calling 'Last'",
ct => UseElementAccessInsteadOfEnumerableMethodRefactoring.UseElementAccessInsteadOfLastAsync(context.Document, invocation, propertyName, ct),
ct => UseElementAccessInsteadOfEnumerableMethodRefactoring.UseElementAccessInsteadOfLastAsync(context.Document, invocation, ct),
RefactoringDescriptors.UseElementAccessInsteadOfLinqMethod);

break;
Expand Down
54 changes: 54 additions & 0 deletions src/Tests/Analyzers.Tests/RCS1246UseElementAccessTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,60 @@ void M()
");
}

[Theory, Trait(Traits.Analyzer, DiagnosticIdentifiers.UseElementAccess)]
[InlineData("((List<object>)x).[|Last()|]", "((List<object>)x)[^1]")]
[InlineData("((IList<object>)x).[|Last()|]", "((IList<object>)x)[^1]")]
[InlineData("((IReadOnlyList<object>)x).[|Last()|]", "((IReadOnlyList<object>)x)[^1]")]
[InlineData("((Collection<object>)x).[|Last()|]", "((Collection<object>)x)[^1]")]
[InlineData("((ImmutableArray<object>)x).[|Last()|]", "((ImmutableArray<object>)x)[^1]")]
[InlineData("((object[])x).[|Last()|]", "((object[])x)[^1]")]
[InlineData("((string)x).[|Last()|]", "((string)x)[^1]")]
public async Task Test_UseElementAccessInsteadOfLast(string source, string expected)
{
await VerifyDiagnosticAndFixAsync(@"
using System;
using System.Linq;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.ObjectModel;

class C
{
void M()
{
object x = null;
var y = [||];
}
}
", source, expected);
}

[Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.UseElementAccess)]
public async Task TestNoDiagnostic_UseElementAccessInsteadOfLast()
{
await VerifyNoDiagnosticAsync(@"
using System;
using System.Linq;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.ObjectModel;

class C
{
void M()
{
object x = null;

x = ((ICollection<object>)x).Last();
x = ((IReadOnlyCollection<object>)x).Last();
x = ((IEnumerable<object>)x).Last();

x = ((Dictionary<object, object>)x).Last();
}
}
");
}

[Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.UseElementAccess)]
public async Task TestNoDiagnostic_UseElementAccessInsteadOfFirst()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,6 @@ public static Task<Document> UseElementAccessInsteadOfFirstAsync(
public static Task<Document> UseElementAccessInsteadOfLastAsync(
Document document,
InvocationExpressionSyntax invocation,
string propertyName,
CancellationToken cancellationToken = default)
{
ArgumentListSyntax argumentList = invocation.ArgumentList;
Expand All @@ -105,11 +104,7 @@ public static Task<Document> UseElementAccessInsteadOfLastAsync(
expression = expression.WithTrailingTrivia(trivia);
}

ExpressionSyntax argumentExpression = SubtractExpression(
SimpleMemberAccessExpression(
expression,
IdentifierName(propertyName)),
NumericLiteralExpression(1));
ExpressionSyntax argumentExpression = ParseExpression("^1");

ElementAccessExpressionSyntax elementAccess = ElementAccessExpression(
expression,
Expand Down