Skip to content

Commit

Permalink
Work around incomplete lifetime elision
Browse files Browse the repository at this point in the history
  • Loading branch information
dtolnay committed Aug 4, 2018
1 parent 6f85df0 commit 5b89232
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 2 deletions.
23 changes: 21 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,19 +87,33 @@ extern crate proc_macro2;

use proc_macro::TokenStream;
use proc_macro2::Span;
use syn::{Ident, ItemFn};
use syn::{FnArg, FnDecl, Ident, ItemFn, Pat};

fn mangled_marker_name(original: &Ident) -> String {
let len = original.to_string().len();
format!("_Z22RUST_PANIC_IN_FUNCTIONI{}{}E", len, original)
}

fn captured_args(decl: &FnDecl) -> impl Iterator<Item = &Ident> {
decl.inputs
.iter()
.filter_map(|input| match input {
FnArg::Captured(captured) => Some(&captured.pat),
_ => None,
}).filter_map(|pat| match pat {
Pat::Ident(pat) => Some(&pat.ident),
_ => None,
})
}

#[proc_macro_attribute]
pub fn no_panic(args: TokenStream, function: TokenStream) -> TokenStream {
assert!(args.is_empty());

let mut function: ItemFn = syn::parse(function).unwrap();
let ident = Ident::new(&mangled_marker_name(&function.ident), Span::call_site());
let arg_pat = captured_args(&function.decl);
let arg_value = captured_args(&function.decl);
let body = function.block;
function.block = Box::new(parse_quote!({
extern crate core;
Expand All @@ -115,7 +129,12 @@ pub fn no_panic(args: TokenStream, function: TokenStream) -> TokenStream {
}
}
let __guard = __NoPanic;
let __result = (move || #body)();
let __result = (move || {
#(
let #arg_pat = #arg_value;
)*
#body
})();
core::mem::forget(__guard);
__result
}));
Expand Down
18 changes: 18 additions & 0 deletions tests/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,24 @@ assert_no_panic! {
println!("{}", S.demo());
}
}

mod test_lifetime_elision {
struct Buffer {
bytes: [u8; 24],
}

#[no_panic]
fn demo(buffer: &mut Buffer) -> &[u8] {
&buffer.bytes[..]
}

fn main() {
let mut buffer = Buffer {
bytes: [0u8; 24],
};
println!("{:?}", demo(&mut buffer));
}
}
}

assert_link_error! {
Expand Down

0 comments on commit 5b89232

Please sign in to comment.