Skip to content

Commit

Permalink
fix: do not require reduce when there is only one impl
Browse files Browse the repository at this point in the history
  • Loading branch information
SOF3 committed Jan 18, 2025
1 parent a5134bb commit 281cf2f
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 10 deletions.
21 changes: 12 additions & 9 deletions codegen/src/derive_fillers/derive_delegate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -318,23 +318,26 @@ fn transform_return(
) -> syn::Result<Vec<syn::Stmt>> {
let exprs = transform_arg_fields(item, fn_args, trait_path, fields, ctor_path, is_refutable)?;

let exprs = match exprs.try_into() {
Ok::<[_; 1], _>([(single, _, _)]) => return Ok(vec![syn::Stmt::Expr(single, None)]),
Err(err) => err,
};

Ok(match (&fn_args.reduce.0, output_ty) {
(Some((_, reduce_fn)), _) => {
let mut exprs_iter = exprs.into_iter();

let mut stack;

if let Some((_, reduce_base)) = &fn_args.reduce_base.0 {
stack = reduce_base.clone();
let mut stack = if let Some((_, reduce_base)) = &fn_args.reduce_base.0 {
reduce_base.clone()
} else {
let Some((first, _, _)) = exprs_iter.next() else {
return Err(syn::Error::new(
Span::call_site(),
"derive_delegate(reduce) is not applicable for empty structs",
));
};
stack = first;
}
first
};

for (expr, _, field) in exprs_iter {
stack = syn::parse_quote_spanned! { field.span() =>
Expand Down Expand Up @@ -383,9 +386,9 @@ fn transform_return(
return Err(syn::Error::new_spanned(
output_ty,
"Cannot determine how to aggregate the return value. Supported return types are \
`()`, `Self` or arbitrary types with the `#[portrait(derive_delegate(reduce = \
_))]` attribute, or `Option<>`/`Result<>` wrapping them with \
`#[portrait(derive_delegate(with_try))]`.",
`()`, `Self` or arbitrary types with the `#[portrait(derive_delegate(reduce = \
_))]` attribute, or `Option<>`/`Result<>` wrapping them with \
`#[portrait(derive_delegate(with_try))]`.",
))
}
})
Expand Down
2 changes: 1 addition & 1 deletion tests/derive_delegate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ trait Foo {
}

#[portrait::fill(portrait::default)]
impl Foo for i32 { }
impl Foo for i32 {}

#[portrait::fill(portrait::default)]
impl Foo for String {}
Expand Down
22 changes: 22 additions & 0 deletions tests/derive_delegate_single.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
#[portrait::make]
trait Foo {
fn foo(&self, arg1: i32, arg2: &str, arg3: &mut i64) -> bool;
}

#[portrait::fill(portrait::default)]
impl Foo for i32 {}

#[portrait::fill(portrait::default)]
impl Foo for String {}

#[portrait::derive(Foo with portrait::derive_delegate)]
enum Impls {
A(i32),
B(String),
}

fn main() {
fn assert(_: impl Foo) {}

assert(Impls::A(1));
}

0 comments on commit 281cf2f

Please sign in to comment.