rust-lang / project-error-handling

Error handling project group
Apache License 2.0
268 stars 18 forks source link

no-panic as a language feature #49

Open yaahc opened 2 years ago

yaahc commented 2 years ago

A common request I see is for the ability to require that the compiler prove a function can't ever panic. There are already libraries / tools that provide functionality like this.

As I see it we need to answer the following questions:

As well as resolve the following issues:

And here are some previous discussions related to this topic:

yaahc commented 2 years ago

Related: https://github.com/rust-embedded/wg/issues/551

adsick commented 1 year ago

What are the use cases of no-panic

I guess the main reason of not having panic is avoiding crashes and ensuring every possible case is checked&handled correctly. Crashes are not funny especially in context like kernel or some critical infrastructure, e.g. embedded. Take for example emergency alert systems. And generally I would prefer software that never crashes. Sorry if that sounds too obvious but I found it missing from your list of use cases.

Or it was more like use cases of crate https://github.com/dtolnay/no-panic ?

StyMaar commented 1 year ago

A reason why I'd like to have a way to mark functions (or blocks) as “cannot possibly panic” is that it would allow to relax some rules that are annoying (especially for beginners, contributing to the learning curve) but needed to ensure safe rust is panic-safe.

Consider the following:


struct MyStruct{
    foo: Foo,
    // other fields go there
}

// I want to temporarily take ownership of the `foo` field, 
// this isn't currently allowed because it's not panic safe
fn my_function(my_obj: &mut MyStruct){

    let f: Foo = my_obj.foo; // now my_obj is in an invalid state.
    let new_f : Foo = do_something_with_a_foo(f);

   my_obj.foo = new_f; // my_obj is valid again \o/

}

There are work-around this issues (from refactoring everything, to just using Option<Foo>, but if we could enforce that my_function cannot panic then this pattern could be legalized inside no-panic functions (and the error message could be clearer also than a “cannot move out of borrowed content”, because this error message is a lie: you can definitely move out of borrowed content with mem::replace…).

As a conclusion, I should mention that the meaning of “no panic” is a bit different depending on the use-case you're targeting:

safinaskar commented 1 year ago

@StyMaar , this is very similar to https://crates.io/crates/replace_with . replace_with will certainly benefit from some kind of compile time assert of no-panic

Fi3 commented 1 year ago

Hi, below a POC for checking if blocks are panic free using the rustc_* libraries.

https://users.rust-lang.org/t/poc-statically-check-if-paths-are-panic-free/95948