Skip to content
Closed
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
57 changes: 51 additions & 6 deletions fehler-macros/src/throws.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ impl Fold for Throws {
fn fold_expr_return(&mut self, i: syn::ExprReturn) -> syn::ExprReturn {
let ok = match &i.expr {
Some(expr) => ok(expr),
None => ok_unit(),
None => ok_unit(false),
};
syn::ExprReturn { expr: Some(Box::new(ok)), ..i }
}
Expand All @@ -117,13 +117,30 @@ fn modify_tail(is_unit_fn: bool, stmts: &mut Vec<syn::Stmt>) {
let new = syn::parse2(quote::quote!(#e;)).unwrap();
stmts.pop();
stmts.push(new);
stmts.push(syn::Stmt::Expr(ok_unit()));
stmts.push(syn::Stmt::Expr(ok_unit(true)));
}
Some(syn::Stmt::Expr(e)) => {
*e = ok(e);
// In this case, it is necessary to keep the original attributes
// before wrapping the expression. The generated code will have
// attributes attached outside of Ok-wrapping as follows:
//
// // from
// #[allow(unreachable_code, ...)]
// tail_expr
//
// // to
// #[allow(unreachable_code, ...)]
// <_ as ::fehler::__internal::_Succeed>::from_ok(tail_expr)
//
let attrs = take_attrs(e);
let ok = ok(e);
*e = syn::Expr::Verbatim(quote::quote! {
#(#attrs)*
#ok
});
}
_ if is_unit_fn => {
stmts.push(syn::Stmt::Expr(ok_unit()));
stmts.push(syn::Stmt::Expr(ok_unit(true)));
}
_ => { }
}
Expand All @@ -145,6 +162,34 @@ fn ok(expr: &syn::Expr) -> syn::Expr {
syn::parse2(quote::quote!(<_ as ::fehler::__internal::_Succeed>::from_ok(#expr))).unwrap()
}

fn ok_unit() -> syn::Expr {
syn::parse2(quote::quote!(<_ as ::fehler::__internal::_Succeed>::from_ok(()))).unwrap()
fn ok_unit(with_attr: bool) -> syn::Expr {
let attr = if with_attr {
Some(quote::quote!( #[allow(unreachable_code)] ))
} else {
None
};
syn::parse2(quote::quote! {
#attr
<_ as ::fehler::__internal::_Succeed>::from_ok(())
}).unwrap()
}

fn take_attrs(e: &mut syn::Expr) -> Vec<syn::Attribute> {
macro_rules! body {
($($Variant:ident),*) => {
match e {
$(
syn::Expr::$Variant(e) => e.attrs.drain(..).collect(),
)*
_ => unreachable!(),
}
}
}
body!(
Array, Assign, AssignOp, Async, Await, Binary, Block,
Box, Break, Call, Cast, Closure, Continue, Field, ForLoop,
Group, If, Index, Let, Lit, Loop, Macro, Match, MethodCall,
Paren, Path, Range, Reference, Repeat, Return, Struct,
Try, TryBlock, Tuple, Type, Unary, Unsafe, While, Yield
)
}