public inbox for linux-kernel@vger.kernel.org
 help / color / mirror / Atom feed
From: "Gary Guo" <gary@garyguo.net>
To: "Benno Lossin" <lossin@kernel.org>, "Gary Guo" <gary@garyguo.net>,
	"Miguel Ojeda" <ojeda@kernel.org>,
	"Boqun Feng" <boqun.feng@gmail.com>,
	"Björn Roy Baron" <bjorn3_gh@protonmail.com>,
	"Andreas Hindborg" <a.hindborg@kernel.org>,
	"Alice Ryhl" <aliceryhl@google.com>,
	"Trevor Gross" <tmgross@umich.edu>,
	"Danilo Krummrich" <dakr@kernel.org>
Cc: <rust-for-linux@vger.kernel.org>, <linux-kernel@vger.kernel.org>
Subject: Re: [PATCH 09/12] rust: pin-init: add `#[default_error(<type>)]` attribute to initializer macros
Date: Fri, 09 Jan 2026 13:52:27 +0000	[thread overview]
Message-ID: <DFK3WN80DXEF.28VZXRATOJ4A8@garyguo.net> (raw)
In-Reply-To: <20260108135127.3153925-10-lossin@kernel.org>

On Thu Jan 8, 2026 at 1:50 PM GMT, Benno Lossin wrote:
> The `#[default_error(<type>)]` attribute can be used to supply a default
> type as the error used for the `[pin_]init!` macros. This way one can
> easily define custom `try_[pin_]init!` variants that default to your
> project specific error type. Just write the following declarative macro:
>
>     macro_rules! try_init {
>         ($($args:tt)*) => {
>             ::pin_init::init!(
>                 #[default_error(YourCustomErrorType)]
>                 $($args)*
>             )
>         }
>     }
>
> Signed-off-by: Benno Lossin <lossin@kernel.org>
> ---
>  rust/pin-init/internal/src/init.rs | 53 +++++++++++++++++++++++++++---
>  1 file changed, 49 insertions(+), 4 deletions(-)
>
> diff --git a/rust/pin-init/internal/src/init.rs b/rust/pin-init/internal/src/init.rs
> index c02a99692980..e14bacc88f41 100644
> --- a/rust/pin-init/internal/src/init.rs
> +++ b/rust/pin-init/internal/src/init.rs
> @@ -6,10 +6,11 @@
>      parse_quote,
>      punctuated::Punctuated,
>      spanned::Spanned,
> -    token, Block, Expr, ExprCall, ExprPath, Ident, Path, Token, Type,
> +    token, Attribute, Block, Expr, ExprCall, ExprPath, Ident, Path, Token, Type,
>  };
>  
>  pub struct Initializer {
> +    attrs: Vec<InitializerAttribute>,
>      this: Option<This>,
>      path: Path,
>      brace_token: token::Brace,
> @@ -50,23 +51,44 @@ fn ident(&self) -> Option<&Ident> {
>      }
>  }
>  
> +enum InitializerAttribute {
> +    DefaultError(DefaultErrorAttribute),
> +}
> +
> +struct DefaultErrorAttribute {
> +    ty: Type,
> +}
> +
>  pub(crate) fn expand(
>      Initializer {
> +        attrs,
>          this,
>          path,
>          brace_token,
>          fields,
>          rest,
> -        mut error,
> +        error,
>      }: Initializer,
>      default_error: Option<&'static str>,
>      pinned: bool,
>  ) -> TokenStream {
>      let mut errors = TokenStream::new();
> +    let mut error = error.map(|(_, err)| err);
> +    if let Some(default_error) = attrs.iter().fold(None, |acc, attr| {
> +        #[expect(irrefutable_let_patterns)]
> +        if let InitializerAttribute::DefaultError(DefaultErrorAttribute { ty }) = attr {
> +            Some(ty.clone())
> +        } else {
> +            acc
> +        }
> +    }) {
> +        error.get_or_insert(default_error);
> +    }
>      if let Some(default_error) = default_error {
> -        error.get_or_insert((Default::default(), syn::parse_str(default_error).unwrap()));
> +        error.get_or_insert(syn::parse_str(default_error).unwrap());
>      }
> -    let error = error.map(|(_, err)| err).unwrap_or_else(|| {
> +
> +    let error = error.unwrap_or_else(|| {
>          errors.extend(quote_spanned!(brace_token.span.close()=>
>              ::core::compile_error!("expected `? <type>` after `}`");
>          ));
> @@ -350,6 +372,7 @@ fn make_field_check(
>  
>  impl Parse for Initializer {
>      fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
> +        let attrs = input.call(Attribute::parse_outer)?;
>          let this = input.peek(Token![&]).then(|| input.parse()).transpose()?;
>          let path = input.parse()?;
>          let content;
> @@ -381,7 +404,19 @@ fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
>              .peek(Token![?])
>              .then(|| Ok::<_, syn::Error>((input.parse()?, input.parse()?)))
>              .transpose()?;
> +        let attrs = attrs
> +            .into_iter()
> +            .map(|a| {
> +                if a.path().is_ident("default_error") {
> +                    a.parse_args::<DefaultErrorAttribute>()
> +                        .map(InitializerAttribute::DefaultError)
> +                } else {
> +                    Err(syn::Error::new_spanned(a, "unknown initializer attribute"))
> +                }
> +            })
> +            .collect::<Result<Vec<_>, _>>()?;
>          Ok(Self {
> +            attrs,
>              this,
>              path,
>              brace_token,
> @@ -392,6 +427,16 @@ fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
>      }
>  }
>  
> +impl Parse for DefaultErrorAttribute {
> +    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
> +        let ty = input.parse()?;
> +        if !input.peek(End) {
> +            return Err(input.error("expected end of input"));
> +        }

I don't think you need to handle end of input explicitly. Most of `syn` will
complain if a stream has token left unparsed.

Best,
Gary

> +        Ok(Self { ty })
> +    }
> +}
> +
>  impl Parse for This {
>      fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
>          Ok(Self {


  reply	other threads:[~2026-01-09 13:52 UTC|newest]

Thread overview: 40+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2026-01-08 13:50 [PATCH 00/13] `syn` rewrite of pin-init Benno Lossin
2026-01-08 13:50 ` [PATCH 01/12] rust: pin-init: remove `try_` versions of the initializer macros Benno Lossin
2026-01-08 13:50 ` [PATCH 02/12] rust: pin-init: allow the crate to refer to itself as `pin-init` in doc tests Benno Lossin
2026-01-08 13:50 ` [PATCH 03/12] rust: pin-init: add `syn` dependency and remove `proc-macro[2]` and `quote` workarounds Benno Lossin
2026-01-08 13:50 ` [PATCH 04/12] rust: pin-init: rewrite `derive(Zeroable)` and `derive(MaybeZeroable)` using `syn` Benno Lossin
2026-01-09 12:02   ` Gary Guo
2026-01-08 13:50 ` [PATCH 05/12] rust: pin-init: rewrite the `#[pinned_drop]` attribute macro " Benno Lossin
2026-01-09 12:12   ` Gary Guo
2026-01-09 15:34     ` Benno Lossin
2026-01-09 16:42       ` Gary Guo
2026-01-08 13:50 ` [PATCH 06/12] rust: pin-init: rewrite `#[pin_data]` " Benno Lossin
2026-01-09  7:45   ` kernel test robot
2026-01-09 12:47   ` Gary Guo
2026-01-09 16:39     ` Benno Lossin
2026-01-09 16:46       ` Gary Guo
2026-01-10 16:41         ` Benno Lossin
2026-01-10 19:18           ` Gary Guo
2026-01-08 13:50 ` [PATCH 07/12] rust: pin-init: add `?Sized` bounds to traits in `#[pin_data]` macro Benno Lossin
2026-01-08 13:50 ` [PATCH 08/12] rust: pin-init: rewrite the initializer macros using `syn` Benno Lossin
2026-01-09  8:44   ` kernel test robot
2026-01-09 13:45   ` Gary Guo
2026-01-09 17:24     ` Benno Lossin
2026-01-10 16:21       ` Benno Lossin
2026-01-10 18:14     ` Benno Lossin
2026-01-10 19:20       ` Gary Guo
2026-01-10 23:18         ` Benno Lossin
2026-01-11  1:10           ` Gary Guo
2026-01-11 10:04             ` Benno Lossin
2026-01-08 13:50 ` [PATCH 09/12] rust: pin-init: add `#[default_error(<type>)]` attribute to initializer macros Benno Lossin
2026-01-09 13:52   ` Gary Guo [this message]
2026-01-08 13:50 ` [PATCH 10/12] rust: init: use `#[default_error(err)]` for the " Benno Lossin
2026-01-08 13:50 ` [PATCH 11/12] rust: pin-init: internal: init: add support for attributes on initializer fields Benno Lossin
2026-01-09 13:55   ` Gary Guo
2026-01-09 18:02     ` Benno Lossin
2026-01-09 21:16       ` Gary Guo
2026-01-08 13:50 ` [PATCH 12/12] rust: pin-init: internal: init: add escape hatch for referencing initialized fields Benno Lossin
2026-01-09  9:44   ` kernel test robot
2026-01-09 13:58   ` Gary Guo
2026-01-09 18:04     ` Benno Lossin
2026-01-08 13:50 ` [PATCH 13/13] MAINTAINERS: add Gary Guo to pin-init Benno Lossin

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=DFK3WN80DXEF.28VZXRATOJ4A8@garyguo.net \
    --to=gary@garyguo.net \
    --cc=a.hindborg@kernel.org \
    --cc=aliceryhl@google.com \
    --cc=bjorn3_gh@protonmail.com \
    --cc=boqun.feng@gmail.com \
    --cc=dakr@kernel.org \
    --cc=linux-kernel@vger.kernel.org \
    --cc=lossin@kernel.org \
    --cc=ojeda@kernel.org \
    --cc=rust-for-linux@vger.kernel.org \
    --cc=tmgross@umich.edu \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox