Fix MA0171 false positives in nameof and conditional access

Merged
ME
2mo ago
+144-0

What

Two MA0171 bugs:

  1. The rule reported HasValue in nameof, where it cannot be replaced by a pattern:
    int? value = null;
    _ = nameof(value.HasValue); // Expected: no diagnostic, actual: MA0171
    
  2. The rule reported HasValue when it is part of a conditional access, and the fixer produced broken code:
    _ = a?.B.HasValue;
    // fixed as
    _ = a? ((.B) is not null);
    
    a?.B.HasValue is a bool? (null when a is null), so it cannot be replaced by a?.B is not null (a bool) without changing the behavior, except in some contexts such as == true.

Fix

The analyzer skips HasValue when it is in a nameof operation, and when it is part of a conditional access, i.e. when walking up from HasValue through the receivers (member references, invocations, reduced extension method invocations, implicit conversions) reaches the WhenNotNull operation of a conditional access. As the fixer only runs on the reported diagnostics, it no longer produces broken code.

HasValue is still reported when the conditional access is its parenthesized receiver ((a?.B).HasValue is fixed as (a?.B) is not null), and when it is used in an argument of a conditional access (a?.M(value.HasValue)).

The documentation of MA0171 mentions the conditional access case.

Tests

Added tests for nameof, conditional access (a?.B.HasValue, .ToString(), .GetType(), extension method), parenthesized conditional access, and argument of a conditional access. Ran UsePatternMatchingForEqualityComparisonsAnalyzerHasValueTests on roslyn5.9 (15/15 passed) and roslyn4.8 (15/15 passed).