Skip to contentSkip to conversation

rust: macros: vtable: add `#[optional]` attribute

PATCH Applied Gary Guo 3 participants 8 messages Aug 11 – Oct 2

Subsystems (2)
lore
Share & tools
lore

Gary Guo

author reviewer
#0 lore raw

cover rust: macros: vtable: add `#[optional]` attribute

Currently there are a lot of boilerplate with the build_error!(VTABLE_DEFAULT_ERROR) because Rust want a default implementation but we insert NULL into C vtable and never call the Rust-side method if it is not overridden.

Add an #[optional] attribute that injects the same default implementation to avoid duplicating this everywhere. As an example, the misc device vtable trait is converted.

---
Gary Guo (3):
rust: macros: vtable: hide generated HAS_ constants for required methods
rust: macros: vtable: add #[optional] attribute
rust: misc: use #[optional] attribute of #[vtable] macro

 rust/kernel/miscdevice.rs | 35 +++++++++++++----------------------
 rust/macros/lib.rs        | 39 +++++++++++----------------------------
 rust/macros/vtable.rs     | 43 ++++++++++++++++++++++++++++++++++++++-----
 3 files changed, 62 insertions(+), 55 deletions(-)

---
base-commit: 6b8c8af514d739d0335f5579b585e02babe8a727
change-id: 20260811-vtable_macro-12a8f557381b

Best regards,

Signature · 1 line
Gary Guo <[email protected]>
author reviewer
#1 lore raw

PATCH 1/3 rust: macros: vtable: hide generated `HAS_` constants for required methods

These constants have to be generated as the implementation-site #[vtable] invocation has no way of knowing whether the methods are required or provided-but-overriden. However, these constants will have a fixed value so shouldn't be used. Thus, hide them.

---
 rust/macros/vtable.rs | 17 +++++++++++++----
 1 file changed, 13 insertions(+), 4 deletions(-)
rust/macros/vtable.rs +13 -4
index c6510b0c4ea1..e28976a5919f 100644
@@ -9,7 +9,10 @@
     Ident,
     TokenStream, //
 };
-use quote::ToTokens;
+use quote::{
+    quote,
+    ToTokens, //
+};
 use syn::{
     parse_quote,
     Error,
@@ -40,12 +43,18 @@ fn handle_trait(mut item: ItemTrait) -> Result<ItemTrait> {
 
             // We don't know on the implementation-site whether a method is required or provided
             // so we have to generate a const for all methods.
+            // However, hide it for required methods as it will always be true.
+            let doc = if fn_item.default.is_some() {
+                let comment =
+                    format!("Indicates if the `{name}` method is overridden by the implementor.");
+                quote!(#[doc = #comment])
+            } else {
+                quote!(#[doc(hidden)])
+            };
             let cfg_attrs = crate::helpers::gather_cfg_attrs(&fn_item.attrs);
-            let comment =
-                format!("Indicates if the `{name}` method is overridden by the implementor.");
             gen_items.push(parse_quote! {
                 #(#cfg_attrs)*
-                #[doc = #comment]
+                #doc
                 const #gen_const_name: bool = false;
             });
         }
Signature · 1 line
2.54.0
author reviewer
#2 lore raw

PATCH 2/3 rust: macros: vtable: add `#[optional]` attribute

In reply to Gary Guo

For most users of the #[vtable] macro, the optional methods do not have a Rust-side default implementation; a NULL pointer is inserted to the vtable and the C subsystem does thing differently when it sees NULL.

Streamline this use case by providing a #[optional] attribute that does what the build_error!(VTABLE_DEFAULT_ERROR) boilerplate does.

---
 rust/macros/lib.rs    | 39 +++++++++++----------------------------
 rust/macros/vtable.rs | 26 +++++++++++++++++++++++++-
 2 files changed, 36 insertions(+), 29 deletions(-)
rust/macros/lib.rs +11 -28
index 0514fc7c0a55..de55dee4d866 100644
@@ -156,44 +156,29 @@ pub fn module(input: TokenStream) -> TokenStream {
 /// associated constant bool for each method in the trait that is set to true if
 /// the implementer has overridden the associated method.
 ///
-/// For a trait method to be optional, it must have a default implementation.
-/// This is also the case for traits annotated with `#[vtable]`, but in this
-/// case the default implementation will never be executed. The reason for this
-/// is that the functions will be called through function pointers installed in
-/// C side vtables. When an optional method is not implemented on a `#[vtable]`
-/// trait, a `NULL` entry is installed in the vtable. Thus the default
-/// implementation is never called. Since these traits are not designed to be
-/// used on the Rust side, it should not be possible to call the default
-/// implementation. This is done to ensure that we call the vtable methods
-/// through the C vtable, and not through the Rust vtable. Therefore, the
-/// default implementation should call `build_error!`, which prevents
-/// calls to this function at compile time:
-///
-/// ```compile_fail
-/// # // Intentionally missing `use`s to simplify `rusttest`.
-/// build_error!(VTABLE_DEFAULT_ERROR)
-/// ```
-///
-/// Note that you might need to import [`kernel::error::VTABLE_DEFAULT_ERROR`].
+/// For a trait method to be optional for normal traits, it must have a default implementation.
+/// However, for many users of `#[vtable]`, the functions will be called through function pointers
+/// installed in C side vtables. When an optional method is not implemented on a `#[vtable]` trait,
+/// a `NULL` entry is installed in the vtable; thus the default implementation is never called. If
+/// this is the case, `#[optional]` can be applied on the optional method. Methods annotated as such
+/// do not need to be implemented nor need a default implementation. Calling these methods on types
+/// that do not implement them will fail to build using the `build_error!` mechanism.
 ///
 /// This macro should not be used when all functions are required.
 ///
 /// # Examples
 ///
 /// ```
-/// use kernel::error::VTABLE_DEFAULT_ERROR;
 /// use kernel::prelude::*;
 ///
 /// // Declares a `#[vtable]` trait
 /// #[vtable]
 /// pub trait Operations: Send + Sync + Sized {
-///     fn foo(&self) -> Result<()> {
-///         build_error!(VTABLE_DEFAULT_ERROR)
-///     }
+///     #[optional]
+///     fn foo(&self) -> Result<()>;
 ///
-///     fn bar(&self) -> Result<()> {
-///         build_error!(VTABLE_DEFAULT_ERROR)
-///     }
+///     #[optional]
+///     fn bar(&self) -> Result<()>;
 /// }
 ///
 /// struct Foo;
@@ -210,8 +195,6 @@ pub fn module(input: TokenStream) -> TokenStream {
 /// assert_eq!(<Foo as Operations>::HAS_FOO, true);
 /// assert_eq!(<Foo as Operations>::HAS_BAR, false);
 /// ```
-///
-/// [`kernel::error::VTABLE_DEFAULT_ERROR`]: ../kernel/error/constant.VTABLE_DEFAULT_ERROR.html
 #[proc_macro_attribute]
 pub fn vtable(attr: TokenStream, input: TokenStream) -> TokenStream {
     parse_macro_input!(attr as syn::parse::Nothing);
rust/macros/vtable.rs +25 -1
index e28976a5919f..54bd32e82a9c 100644
@@ -33,7 +33,7 @@ fn handle_trait(mut item: ItemTrait) -> Result<ItemTrait> {
          const USE_VTABLE_ATTR: ();
     });
 
-    for item in &item.items {
+    for item in &mut item.items {
         if let TraitItem::Fn(fn_item) = item {
             let name = &fn_item.sig.ident;
             let gen_const_name = Ident::new(
@@ -41,6 +41,30 @@ fn handle_trait(mut item: ItemTrait) -> Result<ItemTrait> {
                 name.span(),
             );
 
+            if fn_item
+                .attrs
+                .extract_if(.., |attr| attr.path().is_ident("optional"))
+                .count()
+                != 0
+            {
+                if let Some(default) = &fn_item.default {
+                    Err(Error::new_spanned(
+                        default,
+                        "`#[optional]` methods must not have default implementation",
+                    ))?;
+                }
+
+                // Optional methods in Rust need a default implementation. Inject one that fails
+                // the build in compile-time if not overridden.
+                fn_item.default = Some(parse_quote!({
+                    ::kernel::build_assert::build_error!(
+                        "This function must not be called, see the #[vtable] documentation."
+                    );
+                }));
+                // Ensure that the function is never code generated unless used.
+                fn_item.attrs.push(parse_quote!(#[inline]));
+            }
+
             // We don't know on the implementation-site whether a method is required or provided
             // so we have to generate a const for all methods.
             // However, hide it for required methods as it will always be true.
Signature · 1 line
2.54.0
author reviewer
#3 lore raw

PATCH 3/3 rust: misc: use `#[optional]` attribute of `#[vtable]` macro

In reply to Gary Guo

Replace the build_error!(VTABLE_DEFAULT_ERROR) boilerplate with the #[optional] attribute.

---
 rust/kernel/miscdevice.rs | 35 +++++++++++++----------------------
 1 file changed, 13 insertions(+), 22 deletions(-)
rust/kernel/miscdevice.rs +13 -22
index 3abef1b8543d..76cb45e2a5ee 100644
@@ -11,10 +11,7 @@
 use crate::{
     bindings,
     device::Device,
-    error::{
-        to_result,
-        VTABLE_DEFAULT_ERROR, //
-    },
+    error::to_result,
     fs::{
         File,
         Kiocb, //
@@ -144,37 +141,33 @@ fn release(device: Self::Ptr, _file: &File) {
     /// the VMA initialization by calling methods of `vma`. If the function does not return an
     /// error, the kernel will complete initialization of the VMA according to the properties of
     /// `vma`.
+    #[optional]
     fn mmap(
         _device: <Self::Ptr as ForeignOwnable>::Borrowed<'_>,
         _file: &File,
         _vma: &VmaNew,
-    ) -> Result {
-        build_error!(VTABLE_DEFAULT_ERROR)
-    }
+    ) -> Result;
 
     /// Read from this miscdevice.
-    fn read_iter(_kiocb: Kiocb<'_, Self::Ptr>, _iov: &mut IovIterDest<'_>) -> Result<usize> {
-        build_error!(VTABLE_DEFAULT_ERROR)
-    }
+    #[optional]
+    fn read_iter(_kiocb: Kiocb<'_, Self::Ptr>, _iov: &mut IovIterDest<'_>) -> Result<usize>;
 
     /// Write to this miscdevice.
-    fn write_iter(_kiocb: Kiocb<'_, Self::Ptr>, _iov: &mut IovIterSource<'_>) -> Result<usize> {
-        build_error!(VTABLE_DEFAULT_ERROR)
-    }
+    #[optional]
+    fn write_iter(_kiocb: Kiocb<'_, Self::Ptr>, _iov: &mut IovIterSource<'_>) -> Result<usize>;
 
     /// Handler for ioctls.
     ///
     /// The `cmd` argument is usually manipulated using the utilities in [`kernel::ioctl`].
     ///
     /// [`kernel::ioctl`]: mod@crate::ioctl
+    #[optional]
     fn ioctl(
         _device: <Self::Ptr as ForeignOwnable>::Borrowed<'_>,
         _file: &File,
         _cmd: u32,
         _arg: usize,
-    ) -> Result<isize> {
-        build_error!(VTABLE_DEFAULT_ERROR)
-    }
+    ) -> Result<isize>;
 
     /// Handler for ioctls.
     ///
@@ -184,23 +177,21 @@ fn ioctl(
     /// that have different layout on 32-bit and 64-bit userspace. If no implementation is
     /// provided, then `compat_ptr_ioctl` will be used instead.
     #[cfg(CONFIG_COMPAT)]
+    #[optional]
     fn compat_ioctl(
         _device: <Self::Ptr as ForeignOwnable>::Borrowed<'_>,
         _file: &File,
         _cmd: u32,
         _arg: usize,
-    ) -> Result<isize> {
-        build_error!(VTABLE_DEFAULT_ERROR)
-    }
+    ) -> Result<isize>;
 
     /// Show info for this fd.
+    #[optional]
     fn show_fdinfo(
         _device: <Self::Ptr as ForeignOwnable>::Borrowed<'_>,
         _m: &SeqFile,
         _file: &File,
-    ) {
-        build_error!(VTABLE_DEFAULT_ERROR)
-    }
+    );
 }
 
 /// A vtable for the file operations of a Rust miscdevice.
Signature · 1 line
2.54.0
#4 lore raw

Re: [PATCH 3/3] rust: misc: use `#[optional]` attribute of `#[vtable]` macro

Quoted 5 lines · Gary Guo

Replace the build_error!(VTABLE_DEFAULT_ERROR) boilerplate with the #[optional] attribute.

Arnd, Greg: may I get a quick Acked-by on this patch?

It is a change that simplifies boilerplate -- no "real" change for you; miscdevice is just the example for the series.

Thanks!

Cheers,
Miguel

maintainer Acked-by
#5 lore raw

Re: [PATCH 3/3] rust: misc: use `#[optional]` attribute of `#[vtable]` macro

Quoted 11 lines · Miguel Ojeda
Quoted 5 lines · Gary Guo

Replace the build_error!(VTABLE_DEFAULT_ERROR) boilerplate with the #[optional] attribute.

Arnd, Greg: may I get a quick Acked-by on this patch?

It is a change that simplifies boilerplate -- no "real" change for you; miscdevice is just the example for the series.

Applied
#6 lore raw
In reply to Gary Guo
Quoted 11 lines · Gary Guo

Currently there are a lot of boilerplate with the build_error!(VTABLE_DEFAULT_ERROR) because Rust want a default implementation but we insert NULL into C vtable and never call the Rust-side method if it is not overridden.

Add an #[optional] attribute that injects the same default implementation to avoid duplicating this everywhere. As an example, the misc device vtable trait is converted.

Applied to rust-next -- thanks everyone!

[ Reworded for typo. - Miguel ]

[ Rewrapped docs. Reworded message, comment and error for typos. Rebased.
- Miguel ]

[ Reworded title for prefix. - Miguel ]

I was tempted to replace the hardcoded message with the VTABLE_DEFAULT_ERROR constant, but I assume you did it so that we can just remove the constant later when everyone is migrated.

By the way, did you consider allowing unused_variables? It could be nice to not have to use _ in the signatures.

Cheers,
Miguel

author reviewer
#7 lore raw
Quoted 17 lines · Miguel Ojeda
Quoted 11 lines · Gary Guo

Currently there are a lot of boilerplate with the build_error!(VTABLE_DEFAULT_ERROR) because Rust want a default implementation but we insert NULL into C vtable and never call the Rust-side method if it is not overridden.

Add an #[optional] attribute that injects the same default implementation to avoid duplicating this everywhere. As an example, the misc device vtable trait is converted.

Applied to rust-next -- thanks everyone!

[ Reworded for typo. - Miguel ]

Quoted 8 lines

[ Rewrapped docs. Reworded message, comment and error for typos. Rebased.
- Miguel ]

[ Reworded title for prefix. - Miguel ]

I was tempted to replace the hardcoded message with the VTABLE_DEFAULT_ERROR constant, but I assume you did it so that we can just remove the constant later when everyone is migrated.

Correct.

Quoted 3 lines

By the way, did you consider allowing unused_variables? It could be nice to not have to use _ in the signatures.

I didn't because existing users are all _ prefixed already. But it does make sense to add that to avoid having to prefix them, just like mandatory methods.

Best,
Gary