rust-lang / rust-clippy

A bunch of lints to catch common mistakes and improve your Rust code. Book: https://doc.rust-lang.org/clippy/
https://rust-lang.github.io/rust-clippy/
Other
11.34k stars 1.53k forks source link

Suggest ! return type for functions that never return a value #12290

Open rootCircle opened 8 months ago

rootCircle commented 8 months ago

What it does

Rust's ! type, also known as the never type, signifies that a function never returns normally. Clippy currently doesn't have a lint to suggest using ! when a function never returns a value or will result into diverging computation(eg., an infinite loop or panic), which could lead to potential type safety issues and misleading code patterns.

Advantage

Drawbacks

Example

fn will_error_out() {
  panic!("It returns nothing, but it's not known to compiler")
}

This function always panics, but its return type is implicitly () (unit), suggesting it might return a value. Adding ! as the return type would clarify its behavior:

fn will_error_out() -> ! {
  panic!("It returns nothing, but it's now explicit")
}

Specifying a never return type will make it easier for its usage in where other functions are dependent on this function.

let some_value: bool = will_error_out(); // will not error out for second case
Jarcho commented 7 months ago

This should ignore both unimplemented! and todo! when checking.

rootCircle commented 7 months ago

Yes, I agree. The linter should only warn when a function either:

Checking for infinite loops comprehensively might be difficult, but even basic checks would be helpful.

J-ZhengLi commented 7 months ago

FYI, function contains infinite loop is already linted 😄 infinite_loop

rootCircle commented 7 months ago

FYI, function contains infinite loop is already linted 😄 infinite_loop

Thanks for pointing it out! I think that lint can be used as reference for implementing this one! Also, I think it will be more sane to merge this one in infinite loop one, as both are targeting never return only?(need opinions) 😄