Fix MA0171 false positives in nameof and conditional access
What
Two MA0171 bugs:
- The rule reported
HasValueinnameof, where it cannot be replaced by a pattern:int? value = null; _ = nameof(value.HasValue); // Expected: no diagnostic, actual: MA0171 - The rule reported
HasValuewhen 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.HasValueis abool?(null whenais null), so it cannot be replaced bya?.B is not null(abool) 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).