Skip to content

Commit

Permalink
Check if foreach contains await (RCS1235)
Browse files Browse the repository at this point in the history
  • Loading branch information
josefpihrt committed Mar 29, 2022
1 parent db53df2 commit ab1fd3a
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 6 deletions.
8 changes: 2 additions & 6 deletions src/Analyzers/CSharp/Analysis/OptimizeMethodCallAnalysis.cs
Original file line number Diff line number Diff line change
Expand Up @@ -327,12 +327,8 @@ public static void OptimizeAdd(SyntaxNodeAnalysisContext context, in SimpleMembe
if (invocation.Parent.IsParentKind(SyntaxKind.ForEachStatement))
{
forEachStatement = (ForEachStatementSyntax)invocation.Parent.Parent;

if (forEachStatement.AwaitKeyword.IsKind(SyntaxKind.AwaitKeyword))
return;
}

if (invocation.Parent.IsParentKind(SyntaxKind.Block)
else if (invocation.Parent.IsParentKind(SyntaxKind.Block)
&& invocation.Parent.Parent.IsParentKind(SyntaxKind.ForEachStatement))
{
block = (BlockSyntax)invocation.Parent.Parent;
Expand All @@ -342,7 +338,7 @@ public static void OptimizeAdd(SyntaxNodeAnalysisContext context, in SimpleMembe
}
}

if (forEachStatement != null
if (forEachStatement?.AwaitKeyword.IsKind(SyntaxKind.AwaitKeyword) == false
&& invocation.ArgumentList.Arguments[0].Expression is IdentifierNameSyntax identifierName
&& identifierName.Identifier.ValueText == forEachStatement.Identifier.ValueText)
{
Expand Down
24 changes: 24 additions & 0 deletions src/Tests/Analyzers.Tests/RCS1235OptimizeMethodCallTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -512,6 +512,30 @@ async Task M()
");
}

[Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.OptimizeMethodCall)]
public async Task TestNoDiagnostic_OptimizeAdd_Await2()
{
await VerifyNoDiagnosticAsync(@"
using System.Threading.Tasks;
using System.Collections.Generic;
class C
{
async Task M()
{
var items = new List<string>();
IAsyncEnumerable<string> items2 = null;
await foreach (var item in items2)
{
items.Add(item);
}
}
}
");
}

[Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.OptimizeMethodCall)]
public async Task TestNoDiagnostic_CallCompareOrdinalInsteadOfCompare_NotStringComparisonOrdinal()
{
Expand Down

0 comments on commit ab1fd3a

Please sign in to comment.