Skip to content

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

@iFrostizz

Description

@iFrostizz

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).

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions