Skip to content

feat: support default implement method #28

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

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
12 changes: 12 additions & 0 deletions trait-variant/examples/variant.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,24 @@ pub trait LocalIntFactory {
fn stream(&self) -> impl Iterator<Item = i32>;
fn call(&self) -> u32;
fn another_async(&self, input: Result<(), &str>) -> Self::MyFut<'_>;
fn default_stream(&self) -> impl Iterator<Item = i32> {
[1].into_iter()
}
async fn default_method(&self) -> u32 {
1
}
fn sync_default_method(&self) -> u32 {
1
}
}

#[allow(dead_code)]
fn spawn_task(factory: impl IntFactory + 'static) {
tokio::spawn(async move {
let _int = factory.make(1, "foo").await;
let _default_int = factory.default_method().await;
let _default_stream = factory.default_stream();
let _sync_default_int = factory.sync_default_method();
});
}

Expand Down
18 changes: 18 additions & 0 deletions trait-variant/src/variant.rs
Original file line number Diff line number Diff line change
Expand Up @@ -150,12 +150,30 @@ fn transform_item(item: &TraitItem, bounds: &Vec<TypeParamBound>) -> TraitItem {
ReturnType::Default => return item.clone(),
}
};

let default_impl = fn_item.default.as_ref().map(|default_impl| {
// only wrap async fn block with async move {}
if sig.asyncness.is_some() {
syn::parse2(quote! {
{
async move {
#default_impl
}
}
})
.unwrap()
} else {
default_impl.clone()
}
});

TraitItem::Fn(TraitItemFn {
sig: Signature {
asyncness: None,
output: ReturnType::Type(arrow, Box::new(output)),
..sig.clone()
},
default: default_impl,
..fn_item.clone()
})
}
Expand Down