Fix MA0215 false positives on await foreach, await using, and top-level statements

Merged
ME
2mo ago
+98-2

What

Two false positives in MA0215 (Return the task instead of awaiting it):

  1. await foreach and await using (statement and declaration) were not counted as awaits. The following code reported on the return, and the code fix removed async, leaving an await foreach in a non-async method (compilation error):

    static async Task<int> A()
    {
        await foreach (var x in E()) { }
        return await Task.FromResult(1);
    }
    

    Expected: no diagnostic. Actual: MA0215 on await Task.FromResult(1).

  2. The rule reported on top-level statements, where the task cannot be returned:

    await System.Threading.Tasks.Task.Delay(1);
    

    Expected: no diagnostic. Actual: MA0215.

Fix

  • The operation walk now flags asynchronous foreach, using statements, and using declarations, and the rule does not report when one is present, as the method must stay async.
  • The synthesized entry point of the top-level statements is skipped (IsTopLevelStatementsEntryPointMethod).
  • docs/Rules/MA0215.md mentions both cases.

Tests

Added AwaitForeach_NoDiagnostic, AwaitUsingStatement_NoDiagnostic, AwaitUsingDeclaration_NoDiagnostic, and TopLevelStatements_NoDiagnostic to ReturnTaskInsteadOfAwaitingItAnalyzerTests (all failed before the fix). The test class passes on roslyn5.9 (44/44) and roslyn4.8 (44/44).