Skip to content

Commit 00c3218

Browse files
tailhookandrewhickman
authored andcommitted
Implement async function support
1 parent 236193a commit 00c3218

File tree

5 files changed

+39
-3
lines changed

5 files changed

+39
-3
lines changed

src/lib.rs

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -56,9 +56,24 @@ pub fn context(args: TokenStream, input: TokenStream) -> TokenStream {
5656

5757
let body = &input.block;
5858
let return_ty = &input.sig.output;
59-
input.block = syn::parse_quote!({
60-
(|| #return_ty #body)().map_err(|err| err.context(format!(#args)).into())
61-
});
59+
if input.sig.asyncness.is_some() {
60+
match return_ty {
61+
syn::ReturnType::Default => {
62+
return syn::Error::new_spanned(return_ty,
63+
"function should return Result").to_compile_error().into()
64+
}
65+
syn::ReturnType::Type(_, return_ty) => {
66+
input.block = syn::parse_quote!({
67+
let result: #return_ty = async { #body }.await;
68+
result.map_err(|err| err.context(format!(#args)).into())
69+
});
70+
}
71+
}
72+
} else {
73+
input.block = syn::parse_quote!({
74+
(|| #return_ty #body)().map_err(|err| err.context(format!(#args)).into())
75+
});
76+
}
6277

6378
quote!(#input).into()
6479
}

tests/async_without_return.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
use fn_error_context::context;
2+
3+
#[context("context")]
4+
async fn async_something() {
5+
}
6+
7+
fn main() {
8+
}

tests/async_without_return.stderr

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
error: function should return Result
2+
--> $DIR/async_without_return.rs:3:1
3+
|
4+
3 | #[context("context")]
5+
| ^^^^^^^^^^^^^^^^^^^^^
6+
|
7+
= note: this error originates in an attribute macro (in Nightly builds, run with -Z macro-backtrace for more info)

tests/inherent.rs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,11 @@ impl Foo {
77
fn do_stuff(&self) -> anyhow::Result<()> {
88
anyhow::bail!("error {}", self.0)
99
}
10+
11+
#[context("context")]
12+
async fn do_async_stuff(&self) -> anyhow::Result<()> {
13+
anyhow::bail!("error {}", self.0)
14+
}
1015
}
1116

1217
fn main() {

tests/tests.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,4 +15,5 @@ fn tests() {
1515
tests.compile_fail("tests/fmt_missing_arg.rs");
1616
tests.compile_fail("tests/fmt_unused_arg.rs");
1717
tests.pass("tests/fmt_named_arg.rs");
18+
tests.compile_fail("tests/async_without_return.rs");
1819
}

0 commit comments

Comments
 (0)