Skip to content
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

Add Rust rule for dangerous use of eagerly evaluated patterns #65

Open
iFrostizz opened this issue Jul 16, 2024 · 1 comment
Open

Add Rust rule for dangerous use of eagerly evaluated patterns #65

iFrostizz opened this issue Jul 16, 2024 · 1 comment

Comments

@iFrostizz
Copy link

Some functions in the standard lib are eagerly evaluated. This is the case of unwrap_or, map_or, ok_or, and, or, and more on other types ...
One could assume that it it safe to write:

let definitely_errors: Result<(), ()> = Err(());
let potential_data: Option<()> = Some(());
let _ = potential_data.unwrap_or(definitely_errors.unwrap());

while this will result in a panic. The reason is that definitely_errors.unwrap() is lazily evaluated. To write something that means "if there some data, then unwrap the value inside of definitely_errors since it may be safe to do so, sometimes assumptions are made on these kind of invariants (ex: If some value is None then another one is Some/Ok for sure).
In order to translate this, one should instead use unwrap_or_else which is lazily evaluated.

In the playground:
https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=6a018576a896d586c2e7a44d72f6803e

A rule could be written that detects if the usage of such an eagerly evaluated block may be unsafe (for instance unwrapping inside of it).

@GrosQuildu
Copy link
Collaborator

Seems like clippy and dylint do not check for that issue; there is an opposite lint only: https://rust-lang.github.io/rust-clippy/stable/index.html#/unwrap_or_else

Thanks for the idea! We should implement it someday, but feel free to send a PR.

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

No branches or pull requests

2 participants