Report relational and generic math NaN comparisons in MA0082
Merged
ME
2mo ago+151+151+012345678901234567890123456789-18-18-01234567890123456789
Summary
MA0082 ("NaN should not be used in comparisons") had two false negatives:
- Relational operators. Only
==and!=were checked, but<,<=,>and>=againstNaNare also alwaysfalseby IEEE-754 and just as likely to be a bug. - Generic math.
T.NaNwhereT : IFloatingPointIeee754<T>was not detected, since the analyzer only matcheddouble.NaN,float.NaNandHalf.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,GreaterThanandGreaterThanOrEqualto the checked operator kinds. - Reports a
NaNmember whose containing type's original definition isSystem.Numerics.IFloatingPointIeee754<TSelf>.T.NaNalways binds to the declaring interface, so derived interfaces such asIBinaryFloatingPointIeee754<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 forx < NaN, which is a constantfalse. The operator check was previously inside the fix action (making it a no-op after being shown); it now runs beforeRegisterCodeFix, per the repo's validate-before-registering guideline. value == T.NaN→T.IsNaN(value),T.NaN != value→!T.IsNaN(value). The type used forIsNaNis the interface's type argument;IsNaNcomes fromINumberBase<TSelf>, whichIFloatingPointIeee754<TSelf>inherits.TryGetNaNTypenow takes theCompilationrather than a pre-resolvedSystem.Halfsymbol.
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
NaNwith relational operators orT.NaNwill 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.