Skip to contentSkip to conversation

rust: error: Extend the Result documentation

PATCH Superseded Dirk Behme 3 participants 3 messages Jan 20, 2025 Rust

v3 of 4 Superseded Latest is v4 →

lore
Share & tools
lore

Dirk Behme

author
#0 lore raw

PATCH v3 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 v3:
* Slight rephrase regarding panic() vs BUG(), whitespace and newline fixes, use srctree/ syntax, add Rust reference link for Result(), evaluate the result of the examples etc. (Miguel)

Changes in v2:
* Improve the linkage (Daniel & Alice)
* Reformat the examples, add if let, drop "automatically", call the example(), improve the formatting, etc (Miguel)

 rust/kernel/error.rs | 127 ++++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 126 insertions(+), 1 deletion(-)
rust/kernel/error.rs +126 -1
index 0b01975c2286c..cb5b5fbfd3266 100644
@@ -254,8 +254,133 @@ 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()?;
+/// # Ok::<(), Error>(())
+/// ```
+///
+/// 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()?;
+/// # Ok::<(), Error>(())
+/// ```
+///
+/// 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: 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:
+///
+/// ```
+/// fn example() -> Result {
+///     let mut numbers = KVec::new();
+///     // Each of the following `expect()` calls may panic.
+///     numbers.push(72, GFP_KERNEL).expect("Error pushing 72");
+///     numbers.push(108, GFP_KERNEL).expect("Error pushing 108");
+///     numbers.push(200, GFP_KERNEL).expect("Error pushing 200");
+///     Ok(())
+/// }
+/// # example()?;
+/// # Ok::<(), Error>(())
+/// ```
+///
+/// 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()?;
+/// # Ok::<(), Error>(())
+/// ```
+///
+/// Depending on the use case using [`unwrap_or()`](Result::unwrap_or),
+/// [`unwrap_or_else()`](Result::unwrap_or_else),
+/// [`unwrap_or_default()`](Result::unwrap_or_default) or
+/// [`unwrap_unchecked()`](Result::unwrap_unchecked) might be an alternative, as well.
+///
+/// For even more details see the [Rust documentation].
+///
+/// [samples/rust/rust_minimal.rs]: srctreetree/samples/rust/rust_minimal.rs
+/// [`?`]: 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
+/// [`BUG()`]: https://docs.kernel.org/process/deprecated.html#bug-and-bug-on
+/// [`if let`]: https://doc.rust-lang.org/reference/expressions/if-expr.html#if-let-expressions
+/// [Rust documentation]: https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html
 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
reviewer
#1 lore raw
Quoted 120 lines · Dirk Behme

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 v3:
* Slight rephrase regarding panic() vs BUG(), whitespace and newline fixes, use srctree/ syntax, add Rust reference link for Result(), evaluate the result of the examples etc. (Miguel)

Changes in v2:
* Improve the linkage (Daniel & Alice)
* Reformat the examples, add if let, drop "automatically", call the example(), improve the formatting, etc (Miguel)

 rust/kernel/error.rs | 127 ++++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 126 insertions(+), 1 deletion(-)
rust/kernel/error.rs +87 -1
index 0b01975c2286c..cb5b5fbfd3266 100644
@@ -254,8 +254,133 @@ 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()?;
+/// # Ok::<(), Error>(())
+/// ```
+///
+/// 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()?;
+/// # Ok::<(), Error>(())
+/// ```
+///
+/// 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: 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:
+///
+/// ```
+/// fn example() -> Result {

rust/kernel/error.rs fn from(e: core::convert::Infallible) -> Error { · line 354

Quoted 10 lines
rust/kernel/error.rs +10 -0
+///     let mut numbers = KVec::new();
+///     // Each of the following `expect()` calls may panic.
+///     numbers.push(72, GFP_KERNEL).expect("Error pushing 72");
+///     numbers.push(108, GFP_KERNEL).expect("Error pushing 108");
+///     numbers.push(200, GFP_KERNEL).expect("Error pushing 200");
+///     Ok(())
+/// }
+/// # example()?;
+/// # Ok::<(), Error>(())
+/// ```

I'm thinking that it would make sense to remove this example. Instead, I would have a paragraph like this *below* the question-mark example:

Another possibility is to call unwrap() or expect(). However, use of these functions is heavily discouraged in the kernel because they trigger a kernel panic if an error happens. Please see the documentation for the C macro BUG() for guidance on when to use these functions.

Alice

#2 lore raw
Quoted 2 lines · Alice Ryhl

I'm thinking that it would make sense to remove this example. Instead,

Removing the example that should not be written sounds good to me too. I don't mind it too much, since it shows how it looks like -- if it is kept, perhaps there could be a "Avoid this"-like comment inside just in case.

Quoted 5 lines

Another possibility is to call unwrap() or expect(). However, use of these functions is heavily discouraged in the kernel because they trigger a kernel panic if an error happens. Please see the documentation for the C macro BUG() for guidance on when to use these functions.

It doesn't necessarily trigger a kernel panic, so I would keep the wording "They trigger a Rust panic if an error happens, which may destabilize a system or entirely break it" (the latter bit comes from the docs). Or, at least, I would say "they may trigger a kernel panic".

Cheers,
Miguel