Cache the MA0042 "no async equivalent" results per call-site scope

Merged
ME
2mo ago
+214-24

Problem

DoNotUseBlockingCallInAsyncContextAnalyzer (MA0042 / MA0045) caches the methods that have no async equivalent in a set keyed by the method symbol only, for the whole compilation. The answer depends on the call, so a negative result at one call site suppressed the diagnostics at the others:

Negative resultDepends onEffect of the per-symbol cache
Async equivalent lookup (LookupSymbols at the call site)Extension methods in scope (usings), member accessibilityDiagnostics depend on the order Roslyn analyzes the files (concurrent execution)
Console.Out/Error.Write/WriteLine/FlushThe instanceConsole.Out.Write(' ') hides MA0042 on every other TextWriter.Write(char) call
SemaphoreSlim.Wait(0) / Wait(TimeSpan.Zero)The argumentssemaphore.Wait(0) hides MA0042 on semaphore.Wait(100)

The last two are deterministic, even within a single method body.

Changes

  • The cache is keyed by a LookupScope: the syntax tree and span of the type declaration containing the call, or the whole file when there is none (top-level statements). The using directives, the accessibility and the editorconfig options are the same for every position of a type declaration. The key is a span, not a node, so the cache does not keep syntax nodes alive.
  • HasAsyncEquivalent became FindAsyncEquivalent and returns Found, NotFound (can be cached for the scope) or NotFoundForThisCall (depends on the instance or the arguments: Console, SemaphoreSlim, Sqlite special cases). This also removes the second IsSqliteSpecialCaseMethod evaluation (data-flow analysis) on negative results.

Behavior notes for reviewers

  • No intended change in which calls are reported, except the calls that were wrongly suppressed.
  • An extension method whose namespace is not imported at the call site is still not suggested; the new ExtensionMethod_NotInScope* tests pin that. Reporting it would need the code fix to add the using directive and a compilation-wide extension search (the call-site lookup is also what filters out inaccessible members), so that is left for a separate change.

Tests

  • Console_DoesNotHideTheOtherTextWriters and SemaphoreSlim_Wait_ZeroDoesNotHideNonZero_Diagnostic fail without the fix and pass with it.
  • ExtensionMethod_NotInScopeInAnotherFile and ExtensionMethod_NotInScopeInAnotherNamespaceOfTheSameFile pin the per-call-site behavior. The cross-file race did not reproduce in the test harness, so these pass without the fix as well.
  • MA0042 tests (171) pass on Roslyn 4.8, 4.14, 5.0, 5.6 and 5.9. The full suite passes on 5.9 (4598) and 4.8 (4480). DocumentationGenerator reports no changes.