Re: [PATCH v4] rust: sync: add #[must_use] to Lock::try_lock

Alice Ryhl
2024-12-11T09:17:24Z

On Wed, Dec 11, 2024 at 3:05 AM Jason Devers <dev.json2@gmail.com> wrote:
>
> The `Lock::try_lock` function returns an `Option<Guard<...>>`, but it
> currently does not issue a warning if the return value is unused.
> To avoid potential bugs, the `#[must_use]` annotation is added to ensure proper usage.
>
> Note that `T` is `#[must_use]` but `Option<T>` is not.
> For more context, see: https://github.com/rust-lang/rust/issues/71368.
>
> Suggested-by: Alice Ryhl <aliceryhl@google.com>
> Link: https://github.com/Rust-for-Linux/linux/issues/1133
> Signed-off-by: Jason Devers <dev.json2@gmail.com>
> ---
> rust/kernel/sync/lock.rs | 2 ++
> 1 file changed, 2 insertions(+)
>
> diff --git a/rust/kernel/sync/lock.rs b/rust/kernel/sync/lock.rs
> index 41dcddac69e2..39f8c07d2287 100644
> --- a/rust/kernel/sync/lock.rs
> +++ b/rust/kernel/sync/lock.rs
> @@ -147,6 +147,8 @@ pub fn lock(&self) -> Guard<'_, T, B> {
> /// Tries to acquire the lock.
> ///
> /// Returns a guard that can be used to access the data protected by the lock if successful.
> + /// Note that `T` is `#[must_use]` but `Option<T>` is not.
> + #[must_use = "if unused, leads to an empty critical section"]

Can't we use the same warning message as Guard?

#[must_use = "the lock unlocks immediately when the guard is unused"]

Alice