rust: error: Extend the Result documentation
PATCH v2 1/1 rust: error: Extend the Result documentation
Extend the Result documentation by some guidelines and examples how to handle Result error cases gracefully. And how to not handle them.
While at it fix one missing Result link in the existing documentation.
---
Changes in v2:
* Improve the linkage (Daniel & Alice)
* Reformat the examples, add if let, drop "automatically", call the example(), improve the formatting, etc (Miguel)
@Miguel: I'm somehow unclear what you like to have linked with
"By the way, it may make sense to link to the relevant chapter of
the online book or similar somewhere in the explanation (on top of the Rust reference)."
?
rust/kernel/error.rs | 118 ++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 117 insertions(+), 1 deletion(-)
rust/kernel/error.rs +117 -1
@@ -254,8 +254,124 @@ fn from(e: core::convert::Infallible) -> Error {/// [`Error`] as its error type. /// /// Note that even if a function does not return anything when it succeeds, -/// it should still be modeled as returning a `Result` rather than +/// it should still be modeled as returning a [`Result`] rather than /// just an [`Error`]. +/// +/// Calling a function that returns [`Result`] needs the caller to handle +/// the returned [`Result`]. +/// +/// This can be done "manually" by using [`match`]. Using [`match`] to decode +/// the [`Result`] is similar to C where all the return value decoding and the +/// error handling is done explicitly by writing handling code for each +/// error to cover. Using [`match`] the error and success handling can be +/// implemented in all detail as required. For example (inspired by +/// [samples/rust/rust_minimal.rs]): +/// +/// ``` +/// fn example() -> Result { +/// let mut numbers = KVec::new(); +/// +/// match numbers.push(72, GFP_KERNEL) { +/// Err(e) => { +/// pr_err!("Error pushing 72: {e:?}"); +/// return Err(e.into()); +/// } +/// // Do nothing, continue. +/// Ok(()) => (), +/// } +/// +/// match numbers.push(108, GFP_KERNEL) { +/// Err(e) => { +/// pr_err!("Error pushing 108: {e:?}"); +/// return Err(e.into()); +/// } +/// // Do nothing, continue. +/// Ok(()) => (), +/// } +/// +/// match numbers.push(200, GFP_KERNEL) { +/// Err(e) => { +/// pr_err!("Error pushing 200: {e:?}"); +/// return Err(e.into()); +/// } +/// // Do nothing, continue. +/// Ok(()) => (), +/// } +/// +/// Ok(()) +/// } +/// # example(); +/// ``` +/// +/// An alternative to be more concise is the [`if let`] syntax: +/// +/// ``` +/// fn example() -> Result { +/// let mut numbers = KVec::new(); +/// +/// if let Err(e) = numbers.push(72, GFP_KERNEL) { +/// pr_err!("Error pushing 72: {e:?}"); +/// return Err(e.into()); +/// } +/// +/// if let Err(e) = numbers.push(108, GFP_KERNEL) { +/// pr_err!("Error pushing 108: {e:?}"); +/// return Err(e.into()); +/// } +/// +/// if let Err(e) = numbers.push(200, GFP_KERNEL) { +/// pr_err!("Error pushing 200: {e:?}"); +/// return Err(e.into()); +/// } +/// +/// Ok(()) +/// } +/// # example(); +/// ``` +/// +/// Instead of these verbose [`match`]/[`if let`] the [`?`]-operator or +/// [`unwrap()`](Result::unwrap)/[`expect()`](Result::expect) can be used to +/// handle the [`Result`] . However, in the kernel context, the usage of +/// [`unwrap()`](Result::unwrap) or [`expect()`](Result::expect) has a side +/// effect which is often not wanted: The [`panic`] called when using +/// [`unwrap()`](Result::unwrap) or [`expect()`](Result::expect). While +/// the console output from [`panic`] is nice and quite helpful for debugging the +/// error, stopping the whole Linux system due to the kernel panic is often **not** +/// desired: +/// +/// ``` +/// fn example () -> Result { +/// let mut numbers = KVec::new(); +/// numbers.push(72, GFP_KERNEL).expect("Error pushing 72"); // Panics the system in case of an error +/// numbers.push(108, GFP_KERNEL).expect("Error pushing 108"); // Panics the system in case of an error +/// numbers.push(200, GFP_KERNEL).expect("Error pushing 200"); // Panics the system in case of an error +/// Ok(()) +/// } +/// # example(); +/// ``` +/// +/// In consequence, using the [`?`]-operator is often the best choice to handle +/// [`Result`] in a non-verbose way as done in [samples/rust/rust_minimal.rs]: +/// +/// ``` +/// fn example () -> Result { +/// let mut numbers = KVec::new(); +/// numbers.push(72, GFP_KERNEL)?; +/// numbers.push(108, GFP_KERNEL)?; +/// numbers.push(200, GFP_KERNEL)?; +/// Ok(()) +/// } +/// # example(); +/// ``` +/// Depending on the use case using [`unwrap_or()`](Result::unwrap_or), +/// [`unwrap_or_else()`](Result::unwrap_or_else) or +/// [`unwrap_or_default()`](Result::unwrap_or_default) might be an alternative, as well. +/// +/// [`?`]: https://doc.rust-lang.org/reference/expressions/operator-expr.html#the-question-mark-operator +/// [`match`]: https://doc.rust-lang.org/reference/expressions/match-expr.html +/// [`panic`]: https://docs.kernel.org/driver-api/basics.html#c.panic +/// [`if let`]: https://doc.rust-lang.org/reference/expressions/if-expr.html#if-let-expressions +/// [samples/rust/rust_minimal.rs]: https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/samples/rust/rust_minimal.rs pub type Result <T = (),E =Error > = core::result::Result <T ,E >;/// Converts an integer as returned by a C kernel function to an error if it's negative, and
Signature · 1 line
2.48.0
Quoted 8 lines · Dirk Behme
@Miguel: I'm somehow unclear what you like to have linked with
"By the way, it may make sense to link to the relevant chapter of
the online book or similar somewhere in the explanation (on top of the Rust reference)."?
I was thinking of something like
https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html
(for details, the Rust reference links that you have are nice).
Quoted 1 line
+/// #
example();
Should these examples ignore the result? i.e. should we use the # Ok::... syntax instead?
rust/kernel/error.rs fn from(e: core::convert::Infallible) -> Error { · line 340
Quoted 5 lines
rust/kernel/error.rs +5
-0+/// effect which is often not wanted: The [`panic`] called when using +/// [`unwrap()`](Result::unwrap) or [`expect()`](Result::expect). While +/// the console output from [`panic`] is nice and quite helpful for debugging the +/// error, stopping the whole Linux system due to the kernel panic is often **not** +/// desired:
Note that a Rust panic currently calls BUG() which does not necessarily call panic() nor stop the whole system.
So perhaps we could say something slightly more relaxed/generic, like "...they trigger a Rust panic, which may destabilize a system or entirely break it as a result -- just like the C BUG() macro, these methods should be avoided unless one has a very good reason.", and link to e.g. https://docs.kernel.org/process/deprecated.html#bug-and-bug-on.
Quoted 1 line
+/// ```
Nit: newline after a code block.
I also noticed a example () -> example(), i.e. please try to ensure the examples are formatted as usual (especially important for ones targeting newcomers!).
rust/kernel/error.rs fn from(e: core::convert::Infallible) -> Error { · line 368
Quoted 3 lines
rust/kernel/error.rs +3
-0+/// Depending on the use case using [`unwrap_or()`](Result::unwrap_or), +/// [`unwrap_or_else()`](Result::unwrap_or_else) or +/// [`unwrap_or_default()`](Result::unwrap_or_default) might be an alternative, as well.
Should we list unwrap_unchecked()? Or at least say these are "some of" the alternatives (i.e. not all of them)?
Also "// Panics the system in case of an error": please end comments with a period. We also put comments generally on top rather than at the right side (does this go over the usual column limit?) -- perhaps I would just use 1 comment at the top of the 3 lines and say "// Each of these expect() calls may panic." (And by the way, like above, we should probably avoid saying "panics the kernel" since it is not always the case).
Quoted 1 line
+/// [
samples/rust/rust_minimal.rs]: https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/samples/rust/rust_minimal.rs
This one should use the srctree/ syntax.
Thanks!
Cheers,
Miguel