Skip to content

Add attribute #[boxing] to allow automatic boxing #419

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions impl/src/attr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ pub struct Attrs<'a> {
pub from: Option<From<'a>>,
pub transparent: Option<Transparent<'a>>,
pub fmt: Option<Fmt<'a>>,
pub boxing: Option<Boxing<'a>>,
}

#[derive(Clone)]
Expand Down Expand Up @@ -53,6 +54,12 @@ pub struct Fmt<'a> {
pub path: ExprPath,
}

#[derive(Copy, Clone)]
pub struct Boxing<'a> {
pub original: &'a Attribute,
pub span: Span,
}

#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Debug)]
pub enum Trait {
Debug,
Expand All @@ -74,6 +81,7 @@ pub fn get(input: &[Attribute]) -> Result<Attrs> {
from: None,
transparent: None,
fmt: None,
boxing: None,
};

for attr in input {
Expand Down Expand Up @@ -115,6 +123,18 @@ pub fn get(input: &[Attribute]) -> Result<Attrs> {
original: attr,
span,
});
} else if attr.path().is_ident("boxing") {
if attrs.boxing.is_some() {
return Err(Error::new_spanned(attr, "duplicate #[boxing] attribute"));
}

let span = (attr.pound_token.span)
.join(attr.bracket_token.span.join())
.unwrap_or(attr.path().get_ident().unwrap().span());
attrs.boxing = Some(Boxing {
original: attr,
span,
});
}
}

Expand Down
55 changes: 55 additions & 0 deletions impl/src/expand.rs
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,32 @@ fn impl_struct(input: Struct) -> TokenStream {
})
});

let boxing_impl = input.boxing_field().map(|from_field| {
let span = from_field.attrs.from.unwrap().span;
let from = unoptional_type(from_field.ty);
let source_var = Ident::new("source", span);
let from_function = quote! {
fn from(#source_var: #from) -> Self {
::std::boxed::Box::new(From::from(#source_var))
}
};
let boxing_impl = quote_spanned! {span=>
#[automatically_derived]
impl #impl_generics ::core::convert::From<#from> for ::std::boxed::Box < #ty #ty_generics > #where_clause {
#from_function
}
};
Some(quote! {
#[allow(
deprecated,
unused_qualifications,
clippy::elidable_lifetime_names,
clippy::needless_lifetimes,
)]
#boxing_impl
})
});

if input.generics.type_params().next().is_some() {
let self_token = <Token![Self]>::default();
error_inferred_bounds.insert(self_token, Trait::Debug);
Expand All @@ -207,6 +233,7 @@ fn impl_struct(input: Struct) -> TokenStream {
}
#display_impl
#from_impl
#boxing_impl
}
}

Expand Down Expand Up @@ -466,6 +493,33 @@ fn impl_enum(input: Enum) -> TokenStream {
})
});

let boxing_impls = input.variants.iter().filter_map(|variant| {
let from_field = variant.boxing_field()?;
let span = from_field.attrs.boxing.unwrap().span;
let from = unoptional_type(from_field.ty);
let source_var = Ident::new("source", span);
let from_function = quote! {
fn from(#source_var: #from) -> Self {
::std::boxed::Box::new(From::from(#source_var))
}
};
let from_impl = quote_spanned! {span=>
#[automatically_derived]
impl #impl_generics ::core::convert::From<#from> for ::std::boxed::Box < #ty #ty_generics > #where_clause {
#from_function
}
};
Some(quote! {
#[allow(
deprecated,
unused_qualifications,
clippy::elidable_lifetime_names,
clippy::needless_lifetimes,
)]
#from_impl
})
});

if input.generics.type_params().next().is_some() {
let self_token = <Token![Self]>::default();
error_inferred_bounds.insert(self_token, Trait::Debug);
Expand All @@ -482,6 +536,7 @@ fn impl_enum(input: Enum) -> TokenStream {
}
#display_impl
#(#from_impls)*
#(#boxing_impls)*
}
}

Expand Down
2 changes: 1 addition & 1 deletion impl/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ mod valid;
use proc_macro::TokenStream;
use syn::{parse_macro_input, DeriveInput};

#[proc_macro_derive(Error, attributes(backtrace, error, from, source))]
#[proc_macro_derive(Error, attributes(backtrace, error, from, source, boxing))]
pub fn derive_error(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
expand::derive(&input).into()
Expand Down
14 changes: 14 additions & 0 deletions impl/src/prop.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@ impl Struct<'_> {
let backtrace_field = self.backtrace_field()?;
distinct_backtrace_field(backtrace_field, self.from_field())
}

pub(crate) fn boxing_field(&self) -> Option<&Field> {
boxing_field(&self.fields)
}
}

impl Enum<'_> {
Expand Down Expand Up @@ -67,6 +71,10 @@ impl Variant<'_> {
let backtrace_field = self.backtrace_field()?;
distinct_backtrace_field(backtrace_field, self.from_field())
}

pub(crate) fn boxing_field(&self) -> Option<&Field> {
boxing_field(&self.fields)
}
}

impl Field<'_> {
Expand Down Expand Up @@ -137,6 +145,12 @@ fn distinct_backtrace_field<'a, 'b>(
}
}

fn boxing_field<'a, 'b>(fields: &'a [Field<'b>]) -> Option<&'a Field<'b>> {
fields
.iter()
.find(|Field { attrs, .. }| attrs.from.is_some() && attrs.boxing.is_some())
}

fn type_is_backtrace(ty: &Type) -> bool {
let path = match ty {
Type::Path(ty) => &ty.path,
Expand Down
26 changes: 26 additions & 0 deletions impl/src/valid.rs
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,13 @@ fn check_non_field_attrs(attrs: &Attrs) -> Result<()> {
));
}

if let Some(boxing) = &attrs.boxing {
return Err(Error::new_spanned(
boxing.original,
"attribute #[boxing] expected on a specific field also having #[from] attribute ",
));
}

Ok(())
}

Expand All @@ -153,6 +160,7 @@ fn check_field_attrs(fields: &[Field]) -> Result<()> {
let mut source_field = None;
let mut backtrace_field = None;
let mut has_backtrace = false;
let mut boxing_field = None;
for field in fields {
if let Some(from) = field.attrs.from {
if from_field.is_some() {
Expand Down Expand Up @@ -189,6 +197,16 @@ fn check_field_attrs(fields: &[Field]) -> Result<()> {
));
}
has_backtrace |= field.is_backtrace();

if let Some(boxing) = field.attrs.boxing {
if boxing_field.is_some() {
return Err(Error::new_spanned(
boxing.original,
"duplicate #[boxing] attribute",
));
}
boxing_field = Some(field);
}
}
if let (Some(from_field), Some(source_field)) = (from_field, source_field) {
if from_field.member != source_field.member {
Expand Down Expand Up @@ -218,6 +236,14 @@ fn check_field_attrs(fields: &[Field]) -> Result<()> {
));
}
}

if let (None, Some(boxing_field)) = (from_field, boxing_field) {
return Err(Error::new_spanned(
boxing_field.attrs.boxing.unwrap().original,
"attribute #[boxing] requires the field to also have a #[from] attribute",
));
}

Ok(())
}

Expand Down
35 changes: 35 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,41 @@
//! }
//! ```
//!
//! - Additionally, the `#[from]` attribute may be augmented with a `#[boxing]` attribute, for conveniently boxing source errors:
//! This is especially useful for ensuring large source errors do not needlessly enlarge every stack frame in which they may be used.
//! See also: <https://rust-lang.github.io/rust-clippy/master/index.html#result_large_err>.
//!
//! ```
//! # use thiserror::Error;
//! #
//! #[derive(Error, Debug)]
//! #[error("...")]
//! pub struct ExternalError([u8; 2048]);
//!
//! #[derive(Error, Debug)]
//! pub enum MyError {
//! #[error(transparent)]
//! ExternalCause(#[from] #[boxing] ExternalError),
//!
//! #[error("other")]
//! Other,
//! }
//!
//! pub fn do_something() -> Result<(), ExternalError> {
//! # /*
//! ...
//! # */
//! # Ok(())
//! }
//!
//! // Automatically boxed
//! pub fn something_else() -> Result<(), Box<MyError>> {
//! do_something()?;
//!
//! Ok(())
//! }
//! ```
//!
//! - See also the [`anyhow`] library for a convenient single error type to use
//! in application code.
//!
Expand Down
Loading