Skip to content

[Diagnostics] Diagnose comparisons with '.nan' and suggest using '.isNan' instead #33860

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 11 commits into from
Sep 9, 2020
Merged

Conversation

theblixguy
Copy link
Collaborator

@theblixguy theblixguy commented Sep 8, 2020

This is based on a suggestion from @stephentyrone on Twitter: https://twitter.com/stephentyrone/status/1302702935831384071


It is a pretty common mistake to compare values to the .nan static property, instead of using the .isNaN instance property when checking for the presence or absence of NaN.

According to isNaN documentation:

Because NaN is not equal to any value, including NaN, use this property instead of the equal-to operator (==) or not-equal-to operator (!=) to test whether a value is or is not NaN.

So, diagnose comparisons using ==, >= and etc when either of the arguments is .nan from FloatingPoint protocol. For example:

2.0 >= .nan // warning

let value = 0.1
value == .nan // warning

and suggest using isNaN when applicable.

@stephentyrone
Copy link
Contributor

I'm fine with the diagnostics generated. Pavel or Holly may have feedback on the implementation details, so please let one of them review as well.

@theblixguy
Copy link
Collaborator Author

Thank you! While I wait for them to take a look as well, let me run some tests:

@swift-ci please smoke test

Copy link
Collaborator

@xwu xwu left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a good warning to have! Thanks for tackling it.

@theblixguy
Copy link
Collaborator Author

Heh, I didn't notice I wrote isNan instead of isNaN (quite subtle!). Thanks @xwu!

@theblixguy
Copy link
Collaborator Author

@swift-ci please smoke test

@xwu
Copy link
Collaborator

xwu commented Sep 9, 2020

@swift-ci please smoke test macOS platform

Copy link
Contributor

@xedin xedin left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM! I have left a couple of improvement suggestions inline.

@theblixguy
Copy link
Collaborator Author

@swift-ci please smoke test

@theblixguy
Copy link
Collaborator Author

:shipit:

@theblixguy theblixguy merged commit 49e7c61 into swiftlang:master Sep 9, 2020
@theblixguy theblixguy deleted the chore/nan branch September 9, 2020 21:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants