Skip to content

Commit aeabc92

Browse files
committed
rust: pin-init: add #[default_error(<type>)] attribute to initializer macros
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)* ) } } Tested-by: Andreas Hindborg <a.hindborg@kernel.org> Reviewed-by: Gary Guo <gary@garyguo.net> Signed-off-by: Benno Lossin <lossin@kernel.org>
1 parent 4883830 commit aeabc92

1 file changed

Lines changed: 41 additions & 3 deletions

File tree

rust/pin-init/internal/src/init.rs

Lines changed: 41 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,13 @@ use syn::{
88
parse_quote,
99
punctuated::Punctuated,
1010
spanned::Spanned,
11-
token, Block, Expr, ExprCall, ExprPath, Ident, Path, Token, Type,
11+
token, Attribute, Block, Expr, ExprCall, ExprPath, Ident, Path, Token, Type,
1212
};
1313

1414
use crate::diagnostics::{DiagCtxt, ErrorGuaranteed};
1515

1616
pub(crate) struct Initializer {
17+
attrs: Vec<InitializerAttribute>,
1718
this: Option<This>,
1819
path: Path,
1920
brace_token: token::Brace,
@@ -54,8 +55,17 @@ impl InitializerField {
5455
}
5556
}
5657

58+
enum InitializerAttribute {
59+
DefaultError(DefaultErrorAttribute),
60+
}
61+
62+
struct DefaultErrorAttribute {
63+
ty: Box<Type>,
64+
}
65+
5766
pub(crate) fn expand(
5867
Initializer {
68+
attrs,
5969
this,
6070
path,
6171
brace_token,
@@ -69,14 +79,23 @@ pub(crate) fn expand(
6979
) -> Result<TokenStream, ErrorGuaranteed> {
7080
let error = error.map_or_else(
7181
|| {
72-
if let Some(default_error) = default_error {
82+
if let Some(default_error) = attrs.iter().fold(None, |acc, attr| {
83+
#[expect(irrefutable_let_patterns)]
84+
if let InitializerAttribute::DefaultError(DefaultErrorAttribute { ty }) = attr {
85+
Some(ty.clone())
86+
} else {
87+
acc
88+
}
89+
}) {
90+
default_error
91+
} else if let Some(default_error) = default_error {
7392
syn::parse_str(default_error).unwrap()
7493
} else {
7594
dcx.error(brace_token.span.close(), "expected `? <type>` after `}`");
7695
parse_quote!(::core::convert::Infallible)
7796
}
7897
},
79-
|(_, err)| err,
98+
|(_, err)| Box::new(err),
8099
);
81100
let slot = format_ident!("slot");
82101
let (has_data_trait, data_trait, get_data, init_from_closure) = if pinned {
@@ -358,6 +377,7 @@ fn make_field_check(
358377

359378
impl Parse for Initializer {
360379
fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> {
380+
let attrs = input.call(Attribute::parse_outer)?;
361381
let this = input.peek(Token![&]).then(|| input.parse()).transpose()?;
362382
let path = input.parse()?;
363383
let content;
@@ -389,7 +409,19 @@ impl Parse for Initializer {
389409
.peek(Token![?])
390410
.then(|| Ok::<_, syn::Error>((input.parse()?, input.parse()?)))
391411
.transpose()?;
412+
let attrs = attrs
413+
.into_iter()
414+
.map(|a| {
415+
if a.path().is_ident("default_error") {
416+
a.parse_args::<DefaultErrorAttribute>()
417+
.map(InitializerAttribute::DefaultError)
418+
} else {
419+
Err(syn::Error::new_spanned(a, "unknown initializer attribute"))
420+
}
421+
})
422+
.collect::<Result<Vec<_>, _>>()?;
392423
Ok(Self {
424+
attrs,
393425
this,
394426
path,
395427
brace_token,
@@ -400,6 +432,12 @@ impl Parse for Initializer {
400432
}
401433
}
402434

435+
impl Parse for DefaultErrorAttribute {
436+
fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> {
437+
Ok(Self { ty: input.parse()? })
438+
}
439+
}
440+
403441
impl Parse for This {
404442
fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> {
405443
Ok(Self {

0 commit comments

Comments
 (0)