Report relational and generic math NaN comparisons in MA0082

Merged
ME
2mo ago
+151-18

Summary

MA0082 ("NaN should not be used in comparisons") had two false negatives:

  1. Relational operators. Only == and != were checked, but <, <=, > and >= against NaN are also always false by IEEE-754 and just as likely to be a bug.
  2. Generic math. T.NaN where T : IFloatingPointIeee754<T> was not detected, since the analyzer only matched double.NaN, float.NaN and Half.NaN.
bool A(double d) => d < double.NaN;   // now reported
bool B<T>(T v) where T : IFloatingPointIeee754<T> => v == T.NaN; // now reported

Changes

Analyzer

  • Adds LessThan, LessThanOrEqual, GreaterThan and GreaterThanOrEqual to the checked operator kinds.
  • Reports a NaN member whose containing type's original definition is System.Numerics.IFloatingPointIeee754<TSelf>. T.NaN always binds to the declaring interface, so derived interfaces such as IBinaryFloatingPointIeee754<T> are covered too. The message uses the type argument (T.NaN should not be used in comparisons).
  • On target frameworks without IFloatingPointIeee754<>, the symbol lookup returns null and nothing is reported.

Code fixer

  • The "Use IsNaN" fix is only registered for == and !=. IsNaN(x) is not an equivalent replacement for x < NaN, which is a constant false. The operator check was previously inside the fix action (making it a no-op after being shown); it now runs before RegisterCodeFix, per the repo's validate-before-registering guideline.
  • value == T.NaN → T.IsNaN(value), T.NaN != value → !T.IsNaN(value). The type used for IsNaN is the interface's type argument; IsNaN comes from INumberBase<TSelf>, which IFloatingPointIeee754<TSelf> inherits.
  • TryGetNaNType now takes the Compilation rather than a pre-resolved System.Half symbol.

Docs — docs/Rules/MA0082.md gains relational and generic math examples, plus a note that the fix only applies to ==/!=.

Reviewer notes

  • MA0082 is an enabled-by-default warning, so projects comparing against NaN with relational operators or T.NaN will get new warnings after upgrading.
  • The generic math fix and "no fix" cases are in separate tests: the testing library drops markup for fixable diagnostic ids from the fixed state's expectations, so a single test can't hold both a fixed line and a remaining MA0082 diagnostic.

Testing

  • dotnet build: 0 warnings, 0 errors, all Roslyn versions.
  • DoNotNaNInComparisonsAnalyzerTests: 8/8 pass on roslyn4.8, 4.14, 5.0, 5.6 and 5.9.
  • Full suite on roslyn5.9: 4597 passed, 0 failed.
  • dotnet run --project src/DocumentationGenerator: no further markdown changes.