dtolnay / no-panic

Attribute macro to require that the compiler prove a function can't ever panic
Apache License 2.0
1k stars 13 forks source link

Could we extend no-panic to work on blocks, not just functions? #14

Closed rw closed 4 years ago

rw commented 4 years ago

It would be nice to have this macro work on blocks, not just named functions. One concrete use case is that a function may panic, but inside its body, after making some assertions to set up preconditions, an inner block may be no_panic.

rw commented 4 years ago

I see that this requires the unstable features stmt_expr_attributes and/or proc_macro_hygiene. It still would be useful, though.

dtolnay commented 4 years ago

Sure thing, I would accept a PR to implement this.

rw commented 4 years ago

@dtolnay Cool! Do you think the design needs to change for this use case, or would it use the same reasoning as in your case study? My understanding is that implementing it on blocks might be simpler than implementing it on functions.

dtolnay commented 4 years ago

I don't have an implementation specifically in mind. I suspect implementing blocks would be harder than functions because we don't have a "signature" to work with i.e. what the inputs and outputs of the block might be.

rw commented 4 years ago

The bigger issue I'm trying to solve is that I can't seem to get Vec push to be no_panic, even if I assert preconditions on the length and capacity. Is that something you know about already? Happy to discuss it in a separate issue.

Edit: Solved by 1) asserting that the Vec's capacity is larger than the Vec's length (which can be made true by calling Vec::reserve before the assert), then 2) wrapping the body of the function inside another named function, that has #[no_panic] on it.

dtolnay commented 4 years ago

Closing because I don't plan to dedicate time to this, but if someone submits a PR with a working implementation, I could consider it.