summaryrefslogtreecommitdiffstats
path: root/third_party/rust/rental
diff options
context:
space:
mode:
authorDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-28 14:29:10 +0000
committerDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-28 14:29:10 +0000
commit2aa4a82499d4becd2284cdb482213d541b8804dd (patch)
treeb80bf8bf13c3766139fbacc530efd0dd9d54394c /third_party/rust/rental
parentInitial commit. (diff)
downloadfirefox-upstream.tar.xz
firefox-upstream.zip
Adding upstream version 86.0.1.upstream/86.0.1upstream
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to '')
-rw-r--r--third_party/rust/rental-impl/.cargo-checksum.json1
-rw-r--r--third_party/rust/rental-impl/Cargo.toml33
-rw-r--r--third_party/rust/rental-impl/src/lib.rs1595
-rw-r--r--third_party/rust/rental/.cargo-checksum.json1
-rw-r--r--third_party/rust/rental/Cargo.toml33
-rw-r--r--third_party/rust/rental/LICENSE-APACHE201
-rw-r--r--third_party/rust/rental/LICENSE-MIT25
-rw-r--r--third_party/rust/rental/README.md47
-rw-r--r--third_party/rust/rental/src/lib.rs487
-rw-r--r--third_party/rust/rental/tests/clone.rs50
-rw-r--r--third_party/rust/rental/tests/complex.rs115
-rw-r--r--third_party/rust/rental/tests/complex_mut.rs136
-rw-r--r--third_party/rust/rental/tests/covariant.rs52
-rw-r--r--third_party/rust/rental/tests/debug.rs39
-rw-r--r--third_party/rust/rental/tests/drop_order.rs129
-rw-r--r--third_party/rust/rental/tests/generic.rs53
-rw-r--r--third_party/rust/rental/tests/lt_params.rs65
-rw-r--r--third_party/rust/rental/tests/map.rs42
-rw-r--r--third_party/rust/rental/tests/simple_mut.rs67
-rw-r--r--third_party/rust/rental/tests/simple_ref.rs103
-rw-r--r--third_party/rust/rental/tests/string.rs30
-rw-r--r--third_party/rust/rental/tests/subrental.rs88
-rw-r--r--third_party/rust/rental/tests/target_ty_hack.rs54
-rw-r--r--third_party/rust/rental/tests/trait.rs33
-rw-r--r--third_party/rust/rental/tests/unused.rs28
-rw-r--r--third_party/rust/rental/tests/vec_slice.rs47
26 files changed, 3554 insertions, 0 deletions
diff --git a/third_party/rust/rental-impl/.cargo-checksum.json b/third_party/rust/rental-impl/.cargo-checksum.json
new file mode 100644
index 0000000000..1e2a75adb4
--- /dev/null
+++ b/third_party/rust/rental-impl/.cargo-checksum.json
@@ -0,0 +1 @@
+{"files":{"Cargo.toml":"02a12362b4ac9ac229d1eb74ee1d3cb2706b2057a39165161d8862d7e85ee3ac","src/lib.rs":"622d874509d1cc6f170558faf577a08d792f514eb0112a033b530bcb59c2b82b"},"package":"475e68978dc5b743f2f40d8e0a8fdc83f1c5e78cbf4b8fa5e74e73beebc340de"} \ No newline at end of file
diff --git a/third_party/rust/rental-impl/Cargo.toml b/third_party/rust/rental-impl/Cargo.toml
new file mode 100644
index 0000000000..74f4222fec
--- /dev/null
+++ b/third_party/rust/rental-impl/Cargo.toml
@@ -0,0 +1,33 @@
+# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
+#
+# When uploading crates to the registry Cargo will automatically
+# "normalize" Cargo.toml files for maximal compatibility
+# with all versions of Cargo and also rewrite `path` dependencies
+# to registry (e.g., crates.io) dependencies
+#
+# If you believe there's an error in this file please file an
+# issue against the rust-lang/cargo repository. If you're
+# editing this file be aware that the upstream Cargo.toml
+# will likely look very different (and much more reasonable)
+
+[package]
+name = "rental-impl"
+version = "0.5.5"
+authors = ["Jameson Ernst <jameson@jpernst.com>"]
+description = "An implementation detail of rental. Should not be used directly."
+homepage = "https://www.jpernst.com"
+documentation = "https://docs.rs/rental"
+license = "MIT/Apache-2.0"
+repository = "https://github.com/jpernst/rental"
+
+[lib]
+proc-macro = true
+[dependencies.proc-macro2]
+version = "1"
+
+[dependencies.quote]
+version = "1"
+
+[dependencies.syn]
+version = "1"
+features = ["full", "fold", "visit", "extra-traits"]
diff --git a/third_party/rust/rental-impl/src/lib.rs b/third_party/rust/rental-impl/src/lib.rs
new file mode 100644
index 0000000000..beb3434d4f
--- /dev/null
+++ b/third_party/rust/rental-impl/src/lib.rs
@@ -0,0 +1,1595 @@
+#![recursion_limit = "512"]
+
+extern crate proc_macro;
+extern crate proc_macro2;
+#[macro_use]
+extern crate syn;
+#[macro_use]
+extern crate quote;
+
+use std::iter::{self, FromIterator};
+use syn::spanned::Spanned;
+use syn::visit::Visit;
+use syn::fold::Fold;
+use quote::ToTokens;
+use proc_macro2::Span;
+
+
+/// From `procedural_masquerade` crate
+#[doc(hidden)]
+fn _extract_input(derive_input: &str) -> &str {
+ let mut input = derive_input;
+
+ for expected in &["#[allow(unused)]", "enum", "ProceduralMasqueradeDummyType", "{", "Input", "=", "(0,", "stringify!", "("] {
+ input = input.trim_start();
+ assert!(input.starts_with(expected), "expected prefix {:?} not found in {:?}", expected, derive_input);
+ input = &input[expected.len()..];
+ }
+
+ for expected in [")", ").0,", "}"].iter().rev() {
+ input = input.trim_end();
+ assert!(input.ends_with(expected), "expected suffix {:?} not found in {:?}", expected, derive_input);
+ let end = input.len() - expected.len();
+ input = &input[..end];
+ }
+
+ input
+}
+
+
+#[doc(hidden)]
+#[allow(non_snake_case)]
+#[proc_macro_derive(__rental_traits)]
+pub fn __rental_traits(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
+ let mut tokens = proc_macro2::TokenStream::new();
+
+ let max_arity = _extract_input(&input.to_string()).parse::<usize>().expect("Input must be an integer literal.");
+ write_rental_traits(&mut tokens, max_arity);
+
+ tokens.into()
+}
+
+
+#[doc(hidden)]
+#[allow(non_snake_case)]
+#[proc_macro_derive(__rental_structs_and_impls)]
+pub fn __rental_structs_and_impls(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
+ let mut tokens = proc_macro2::TokenStream::new();
+
+ for item in syn::parse_str::<syn::File>(_extract_input(&input.to_string())).expect("Failed to parse items in module body.").items.iter() {
+ match *item {
+ syn::Item::Use(..) => {
+ item.to_tokens(&mut tokens);
+ },
+ syn::Item::Type(..) => {
+ item.to_tokens(&mut tokens);
+ },
+ syn::Item::Struct(ref struct_info) => {
+ write_rental_struct_and_impls(&mut tokens, &struct_info);
+ },
+ _ => panic!("Item must be a `use` or `struct`."),
+ }
+ }
+
+ tokens.into()
+}
+
+
+fn write_rental_traits(tokens: &mut proc_macro2::TokenStream, max_arity: usize) {
+ let call_site: Span = Span::call_site();
+
+ let mut lt_params = vec![syn::LifetimeDef::new(syn::Lifetime::new("'a0", call_site))];
+
+ for arity in 2 .. max_arity + 1 {
+ let trait_ident = &syn::Ident::new(&format!("Rental{}", arity), call_site);
+ let lt_param = syn::LifetimeDef::new(syn::Lifetime::new(&format!("'a{}", arity - 1), call_site));
+ lt_params[arity - 2].bounds.push(lt_param.lifetime.clone());
+ lt_params.push(lt_param);
+
+ let lt_params_iter = &lt_params;
+ quote!(
+ #[doc(hidden)]
+ pub unsafe trait #trait_ident<#(#lt_params_iter),*> {
+ type Borrow;
+ type BorrowMut;
+ }
+ ).to_tokens(tokens);
+ }
+}
+
+
+fn write_rental_struct_and_impls(tokens: &mut proc_macro2::TokenStream, struct_info: &syn::ItemStruct) {
+ let def_site: Span = Span::call_site(); // FIXME: hygiene
+ let call_site: Span = Span::call_site();
+
+ if let syn::Visibility::Inherited = struct_info.vis {
+ panic!("Struct `{}` must be non-private.", struct_info.ident);
+ }
+
+ let attribs = get_struct_attribs(struct_info);
+ let (fields, fields_brace) = prepare_fields(struct_info);
+
+ let struct_generics = &struct_info.generics;
+ let struct_rlt_args = &fields.iter().fold(Vec::new(), |mut rlt_args, field| { rlt_args.extend(field.self_rlt_args.iter()); rlt_args });
+ if let Some(collide) = struct_rlt_args.iter().find(|rlt_arg| struct_generics.lifetimes().any(|lt_def| lt_def.lifetime == ***rlt_arg)) {
+ panic!("Struct `{}` lifetime parameter `{}` collides with rental lifetime.", struct_info.ident, collide);
+ }
+ let last_rlt_arg = &struct_rlt_args[struct_rlt_args.len() - 1];
+ let static_rlt_args = &iter::repeat(syn::Lifetime::new("'static", def_site)).take(struct_rlt_args.len()).collect::<Vec<_>>();
+ let self_rlt_args = &iter::repeat(syn::Lifetime::new("'__s", def_site)).take(struct_rlt_args.len()).collect::<Vec<_>>();
+
+ let item_ident = &struct_info.ident;
+ let item_vis = &struct_info.vis;
+ let item_ident_str = syn::LitStr::new(&item_ident.to_string(), item_ident.span());
+
+ let (struct_impl_params, struct_impl_args, struct_where_clause) = struct_generics.split_for_impl();
+ let where_extra = if let Some(ref struct_where_clause) = struct_where_clause {
+ if struct_where_clause.predicates.is_empty() {
+ quote!(where)
+ } else if struct_where_clause.predicates.trailing_punct() {
+ quote!()
+ } else {
+ quote!(,)
+ }
+ } else {
+ quote!(where)
+ };
+ let struct_lt_params = &struct_generics.lifetimes().collect::<Vec<_>>();
+ let struct_nonlt_params = &struct_generics.params.iter().filter(|param| if let syn::GenericParam::Lifetime(..) = **param { false } else { true }).collect::<Vec<_>>();
+ let struct_lt_args = &struct_lt_params.iter().map(|lt_def| &lt_def.lifetime).collect::<Vec<_>>();
+
+ let struct_nonlt_args = &struct_nonlt_params.iter().map(|param| match **param {
+ syn::GenericParam::Type(ref ty) => &ty.ident,
+ syn::GenericParam::Const(ref co) => &co.ident,
+ syn::GenericParam::Lifetime(..) => unreachable!(),
+ }).collect::<Vec<_>>();
+
+ let rental_trait_ident = syn::Ident::new(&format!("Rental{}", struct_rlt_args.len()), def_site);
+ let field_idents = &fields.iter().map(|field| &field.name).collect::<Vec<_>>();
+ let local_idents = field_idents;
+ let field_ident_strs = &field_idents.iter().map(|ident| syn::LitStr::new(&ident.to_string(), ident.span())).collect::<Vec<_>>();
+
+ let (ref self_ref_param, ref self_lt_ref_param, ref self_mut_param, ref self_move_param, ref self_arg) = if attribs.is_deref_suffix {
+ (quote!(_self: &Self), quote!(_self: &'__s Self), quote!(_self: &mut Self), quote!(_self: Self), quote!(_self))
+ } else {
+ (quote!(&self), quote!(&'__s self), quote!(&mut self), quote!(self), quote!(self))
+ };
+
+ let borrow_ident = syn::Ident::new(&(struct_info.ident.to_string() + "_Borrow"), call_site);
+ let borrow_mut_ident = syn::Ident::new(&(struct_info.ident.to_string() + "_BorrowMut"), call_site);
+ let borrow_quotes = &make_borrow_quotes(self_arg, &fields, attribs.is_rental_mut);
+ let borrow_tys = &borrow_quotes.iter().map(|&BorrowQuotes{ref ty, ..}| ty).collect::<Vec<_>>();
+ let borrow_ty_hacks = &borrow_quotes.iter().map(|&BorrowQuotes{ref ty_hack, ..}| ty_hack).collect::<Vec<_>>();
+ let borrow_suffix_ty = &borrow_tys[fields.len() - 1];
+ let borrow_exprs = &borrow_quotes.iter().map(|&BorrowQuotes{ref expr, ..}| expr).collect::<Vec<_>>();
+ let borrow_suffix_expr = &borrow_exprs[fields.len() - 1];
+ let borrow_mut_tys = &borrow_quotes.iter().map(|&BorrowQuotes{ref mut_ty, ..}| mut_ty).collect::<Vec<_>>();
+ let borrow_mut_ty_hacks = &borrow_quotes.iter().map(|&BorrowQuotes{ref mut_ty_hack, ..}| mut_ty_hack).collect::<Vec<_>>();
+ let borrow_mut_suffix_ty = &borrow_mut_tys[fields.len() - 1];
+ let borrow_mut_exprs = &borrow_quotes.iter().map(|&BorrowQuotes{ref mut_expr, ..}| mut_expr).collect::<Vec<_>>();
+ let borrow_mut_suffix_expr = &borrow_mut_exprs[fields.len() - 1];
+
+ let struct_rlt_params = &struct_rlt_args.iter().zip(struct_rlt_args.iter().skip(1)).map(|(rlt_arg, next_rlt_arg)| {
+ syn::LifetimeDef {
+ attrs: Vec::with_capacity(0),
+ lifetime: (*rlt_arg).clone(),
+ bounds: vec![(*next_rlt_arg).clone()].into_iter().collect(),
+ colon_token: Default::default(),
+ }
+ }).chain(Some(syn::LifetimeDef {
+ attrs: Vec::with_capacity(0),
+ lifetime: struct_rlt_args[struct_rlt_args.len() - 1].clone(),
+ bounds: syn::punctuated::Punctuated::new(),
+ colon_token: Default::default(),
+ })).collect::<Vec<_>>();
+
+ let borrow_lt_params = &struct_rlt_params.iter().cloned()
+ .chain( struct_lt_params.iter().map(|lt_def| {
+ let mut lt_def = (*lt_def).clone();
+ lt_def.bounds.push(struct_rlt_args[0].clone());
+ lt_def
+ })).collect::<Vec<_>>();
+
+ let field_tys = &fields.iter().map(|field| &field.erased.ty).collect::<Vec<_>>();
+ let head_ident = &local_idents[0];
+ let head_ident_rep = &iter::repeat(&head_ident).take(fields.len() - 1).collect::<Vec<_>>();
+ let head_ty = &fields[0].orig_ty;
+ let tail_tys = &field_tys.iter().skip(1).collect::<Vec<_>>();
+ let tail_idents = &local_idents.iter().skip(1).collect::<Vec<_>>();
+ let tail_closure_tys = &fields.iter().skip(1).map(|field| syn::Ident::new(&format!("__F{}", field.name), call_site)).collect::<Vec<_>>();
+ let tail_closure_quotes = make_tail_closure_quotes(&fields, borrow_quotes, attribs.is_rental_mut);
+ let tail_closure_bounds = &tail_closure_quotes.iter().map(|&ClosureQuotes{ref bound, ..}| bound).collect::<Vec<_>>();
+ let tail_closure_exprs = &tail_closure_quotes.iter().map(|&ClosureQuotes{ref expr, ..}| expr).collect::<Vec<_>>();
+ let tail_try_closure_bounds = &tail_closure_quotes.iter().map(|&ClosureQuotes{ref try_bound, ..}| try_bound).collect::<Vec<_>>();
+ let tail_try_closure_exprs = &tail_closure_quotes.iter().map(|&ClosureQuotes{ref try_expr, ..}| try_expr).collect::<Vec<_>>();
+ let suffix_ident = &field_idents[fields.len() - 1];
+ let suffix_ty = &fields[fields.len() - 1].erased.ty;
+ let suffix_rlt_args = &fields[fields.len() - 1].self_rlt_args.iter().chain(fields[fields.len() - 1].used_rlt_args.iter()).collect::<Vec<_>>();
+ let suffix_ident_str = syn::LitStr::new(&suffix_ident.to_string(), suffix_ident.span());
+ let suffix_orig_ty = &fields[fields.len() - 1].orig_ty;
+
+ let rstruct = syn::ItemStruct{
+ ident: struct_info.ident.clone(),
+ vis: item_vis.clone(),
+ attrs: attribs.doc.clone(),
+ fields: syn::Fields::Named(syn::FieldsNamed{
+ brace_token: fields_brace,
+ named: fields.iter().enumerate().map(|(i, field)| {
+ let mut field_erased = field.erased.clone();
+ if i < fields.len() - 1 {
+ field_erased.attrs.push(parse_quote!(#[allow(dead_code)]));
+ }
+ field_erased
+ }).rev().collect(),
+ }),
+ generics: struct_info.generics.clone(),
+ struct_token: struct_info.struct_token,
+ semi_token: None,
+ };
+
+ let borrow_struct = syn::ItemStruct{
+ ident: borrow_ident.clone(),
+ vis: item_vis.clone(),
+ attrs: Vec::with_capacity(0),
+ fields: syn::Fields::Named(syn::FieldsNamed{
+ brace_token: Default::default(),
+ named: fields.iter().zip(borrow_tys).enumerate().map(|(idx, (field, borrow_ty))| {
+ let mut field = field.erased.clone();
+ field.vis = if !attribs.is_rental_mut || idx == fields.len() - 1 { item_vis.clone() } else { syn::Visibility::Inherited };
+ field.ty = syn::parse::<syn::Type>((**borrow_ty).clone().into()).unwrap();
+ field
+ }).collect(),
+ }),
+ generics: {
+ let mut gen = struct_generics.clone();
+ let params = borrow_lt_params.iter().map(|lt| syn::GenericParam::Lifetime(lt.clone()))
+ .chain(gen.type_params().map(|p| syn::GenericParam::Type(p.clone())))
+ .chain(gen.const_params().map(|p| syn::GenericParam::Const(p.clone())))
+ .collect();
+ gen.params = params;
+ gen
+ },
+ struct_token: Default::default(),
+ semi_token: None,
+ };
+
+ let borrow_mut_struct = syn::ItemStruct{
+ ident: borrow_mut_ident.clone(),
+ vis: item_vis.clone(),
+ attrs: Vec::with_capacity(0),
+ fields: syn::Fields::Named(syn::FieldsNamed{
+ brace_token: Default::default(),
+ named: fields.iter().zip(borrow_mut_tys).enumerate().map(|(idx, (field, borrow_mut_ty))| {
+ let mut field = field.erased.clone();
+ field.vis = if idx == fields.len() - 1 || !attribs.is_rental_mut { (*item_vis).clone() } else { syn::Visibility::Inherited };
+ field.ty = syn::parse::<syn::Type>((**borrow_mut_ty).clone().into()).unwrap();
+ field
+ }).collect(),
+ }),
+ generics: {
+ let mut gen = struct_generics.clone();
+ let params = borrow_lt_params.iter().map(|lt| syn::GenericParam::Lifetime(lt.clone()))
+ .chain(gen.type_params().map(|p| syn::GenericParam::Type(p.clone())))
+ .chain(gen.const_params().map(|p| syn::GenericParam::Const(p.clone())))
+ .collect();
+ gen.params = params;
+ gen
+ },
+ struct_token: Default::default(),
+ semi_token: None,
+ };
+
+ let prefix_tys = &fields.iter().map(|field| &field.erased.ty).take(fields.len() - 1).collect::<Vec<_>>();
+ let static_assert_prefix_stable_derefs = &prefix_tys.iter().map(|field| {
+ if attribs.is_rental_mut {
+ quote_spanned!(field.span()/*.resolved_at(def_site)*/ => __rental_prelude::static_assert_mut_stable_deref::<#field>();)
+ } else {
+ quote_spanned!(field.span()/*.resolved_at(def_site)*/ => __rental_prelude::static_assert_stable_deref::<#field>();)
+ }
+ }).collect::<Vec<_>>();
+ let prefix_clone_traits = iter::repeat(quote!(__rental_prelude::CloneStableDeref)).take(prefix_tys.len());
+
+ let struct_span = struct_info.span()/*.resolved_at(def_site)*/;
+ let suffix_ty_span = suffix_ty.span()/*.resolved_at(def_site)*/;
+
+ quote_spanned!(struct_span =>
+ #rstruct
+
+ /// Shared borrow of a rental struct.
+ #[allow(non_camel_case_types, non_snake_case, dead_code)]
+ #borrow_struct
+
+ /// Mutable borrow of a rental struct.
+ #[allow(non_camel_case_types, non_snake_case, dead_code)]
+ #borrow_mut_struct
+ ).to_tokens(tokens);
+
+ quote_spanned!(struct_span =>
+ #[allow(dead_code)]
+ impl<#(#borrow_lt_params,)* #(#struct_nonlt_params),*> #borrow_ident<#(#struct_rlt_args,)* #(#struct_lt_args,)* #(#struct_nonlt_args),*> #struct_where_clause {
+ fn unify_tys_hack(#(#local_idents: #borrow_ty_hacks),*) -> #borrow_ident<#(#struct_rlt_args,)* #(#struct_lt_args,)* #(#struct_nonlt_args),*> {
+ #borrow_ident {
+ #(#field_idents: #local_idents,)*
+ }
+ }
+ }
+ ).to_tokens(tokens);
+
+ quote_spanned!(struct_span =>
+ #[allow(dead_code)]
+ impl<#(#borrow_lt_params,)* #(#struct_nonlt_params),*> #borrow_mut_ident<#(#struct_rlt_args,)* #(#struct_lt_args,)* #(#struct_nonlt_args),*> #struct_where_clause {
+ fn unify_tys_hack(#(#local_idents: #borrow_mut_ty_hacks),*) -> #borrow_mut_ident<#(#struct_rlt_args,)* #(#struct_lt_args,)* #(#struct_nonlt_args),*> {
+ #borrow_mut_ident {
+ #(#field_idents: #local_idents,)*
+ }
+ }
+ }
+ ).to_tokens(tokens);
+
+ quote_spanned!(struct_span =>
+ unsafe impl<#(#borrow_lt_params,)* #(#struct_nonlt_params),*> __rental_prelude::#rental_trait_ident<#(#struct_rlt_args),*> for #item_ident #struct_impl_args #struct_where_clause {
+ type Borrow = #borrow_ident<#(#struct_rlt_args,)* #(#struct_lt_args,)* #(#struct_nonlt_args),*>;
+ type BorrowMut = #borrow_mut_ident<#(#struct_rlt_args,)* #(#struct_lt_args,)* #(#struct_nonlt_args),*>;
+ }
+ ).to_tokens(tokens);
+
+ quote_spanned!(struct_span =>
+ #[allow(dead_code, unused_mut, unused_unsafe, non_camel_case_types)]
+ impl #struct_impl_params #item_ident #struct_impl_args #struct_where_clause {
+ /// Create a new instance of the rental struct.
+ ///
+ /// The first argument provided is the head, followed by a series of closures, one for each tail field. Each of these closures will receive, as its arguments, a borrow of the previous field, followed by borrows of the remaining prefix fields if the struct is a shared rental. If the struct is a mutable rental, only the immediately preceding field is passed.
+ pub fn new<#(#tail_closure_tys),*>(
+ mut #head_ident: #head_ty,
+ #(#tail_idents: #tail_closure_tys),*
+ ) -> Self where #(#tail_closure_tys: #tail_closure_bounds),*
+ {
+ #(#static_assert_prefix_stable_derefs)*
+
+ #(let mut #tail_idents = unsafe { __rental_prelude::transmute::<_, #tail_tys>(#tail_closure_exprs) };)*
+
+ #item_ident {
+ #(#field_idents: #local_idents,)*
+ }
+ }
+
+ /// Attempt to create a new instance of the rental struct.
+ ///
+ /// As `new`, but each closure returns a `Result`. If one of them fails, execution is short-circuited and a tuple of the error and the original head value is returned to you.
+ pub fn try_new<#(#tail_closure_tys,)* __E>(
+ mut #head_ident: #head_ty,
+ #(#tail_idents: #tail_closure_tys),*
+ ) -> __rental_prelude::RentalResult<Self, __E, #head_ty> where
+ #(#tail_closure_tys: #tail_try_closure_bounds,)*
+ {
+ #(#static_assert_prefix_stable_derefs)*
+
+ #(let mut #tail_idents = {
+ let temp = #tail_try_closure_exprs.map(|t| unsafe { __rental_prelude::transmute::<_, #tail_tys>(t) });
+ match temp {
+ __rental_prelude::Result::Ok(t) => t,
+ __rental_prelude::Result::Err(e) => return __rental_prelude::Result::Err(__rental_prelude::RentalError(e.into(), #head_ident_rep)),
+ }
+ };)*
+
+ __rental_prelude::Result::Ok(#item_ident {
+ #(#field_idents: #local_idents,)*
+ })
+ }
+
+ /// Attempt to create a new instance of the rental struct.
+ ///
+ /// As `try_new`, but only the error value is returned upon failure; the head value is dropped. This method interacts more smoothly with existing error conversions.
+ pub fn try_new_or_drop<#(#tail_closure_tys,)* __E>(
+ mut #head_ident: #head_ty,
+ #(#tail_idents: #tail_closure_tys),*
+ ) -> __rental_prelude::Result<Self, __E> where
+ #(#tail_closure_tys: #tail_try_closure_bounds,)*
+ {
+ #(#static_assert_prefix_stable_derefs)*
+
+ #(let mut #tail_idents = {
+ let temp = #tail_try_closure_exprs.map(|t| unsafe { __rental_prelude::transmute::<_, #tail_tys>(t) });
+ match temp {
+ __rental_prelude::Result::Ok(t) => t,
+ __rental_prelude::Result::Err(e) => return __rental_prelude::Result::Err(e.into()),
+ }
+ };)*
+
+ __rental_prelude::Result::Ok(#item_ident {
+ #(#field_idents: #local_idents,)*
+ })
+ }
+
+ /// Return lifetime-erased shared borrows of the fields of the struct.
+ ///
+ /// This is unsafe because the erased lifetimes are fake. Use this only if absolutely necessary and be very mindful of what the true lifetimes are.
+ pub unsafe fn all_erased(#self_ref_param) -> <Self as __rental_prelude::#rental_trait_ident>::Borrow {
+ #borrow_ident::unify_tys_hack(#(__rental_prelude::transmute(#borrow_exprs),)*)
+ }
+
+ /// Return a lifetime-erased mutable borrow of the suffix of the struct.
+ ///
+ /// This is unsafe because the erased lifetimes are fake. Use this only if absolutely necessary and be very mindful of what the true lifetimes are.
+ pub unsafe fn all_mut_erased(#self_mut_param) -> <Self as __rental_prelude::#rental_trait_ident>::BorrowMut {
+ #borrow_mut_ident::unify_tys_hack(#(__rental_prelude::transmute(#borrow_mut_exprs),)*)
+ }
+
+ /// Execute a closure on the shared suffix of the struct.
+ ///
+ /// The closure may return any value not bounded by one of the special rental lifetimes of the struct.
+ pub fn rent<__F, __R>(#self_ref_param, f: __F) -> __R where
+ __F: for<#(#suffix_rlt_args,)*> __rental_prelude::FnOnce(#borrow_suffix_ty) -> __R,
+ __R: #(#struct_lt_args +)*,
+ {
+ f(#borrow_suffix_expr)
+ }
+
+ /// Execute a closure on the mutable suffix of the struct.
+ ///
+ /// The closure may return any value not bounded by one of the special rental lifetimes of the struct.
+ pub fn rent_mut<__F, __R>(#self_mut_param, f: __F) -> __R where
+ __F: for<#(#suffix_rlt_args,)*> __rental_prelude::FnOnce(#borrow_mut_suffix_ty) -> __R,
+ __R: #(#struct_lt_args +)*,
+ {
+ f(#borrow_mut_suffix_expr)
+ }
+
+ /// Return a shared reference from the shared suffix of the struct.
+ ///
+ /// This is a subtle variation of `rent` where it is legal to return a reference bounded by a rental lifetime, because that lifetime is reborrowed away before it is returned to you.
+ pub fn ref_rent<__F, __R>(#self_ref_param, f: __F) -> &__R where
+ __F: for<#(#suffix_rlt_args,)*> __rental_prelude::FnOnce(#borrow_suffix_ty) -> &#last_rlt_arg __R,
+ __R: ?Sized //#(#struct_lt_args +)*,
+ {
+ f(#borrow_suffix_expr)
+ }
+
+ /// Optionally return a shared reference from the shared suffix of the struct.
+ ///
+ /// This is a subtle variation of `rent` where it is legal to return a reference bounded by a rental lifetime, because that lifetime is reborrowed away before it is returned to you.
+ pub fn maybe_ref_rent<__F, __R>(#self_ref_param, f: __F) -> __rental_prelude::Option<&__R> where
+ __F: for<#(#suffix_rlt_args,)*> __rental_prelude::FnOnce(#borrow_suffix_ty) -> __rental_prelude::Option<&#last_rlt_arg __R>,
+ __R: ?Sized //#(#struct_lt_args +)*,
+ {
+ f(#borrow_suffix_expr)
+ }
+
+ /// Try to return a shared reference from the shared suffix of the struct, or an error on failure.
+ ///
+ /// This is a subtle variation of `rent` where it is legal to return a reference bounded by a rental lifetime, because that lifetime is reborrowed away before it is returned to you.
+ pub fn try_ref_rent<__F, __R, __E>(#self_ref_param, f: __F) -> __rental_prelude::Result<&__R, __E> where
+ __F: for<#(#suffix_rlt_args,)*> __rental_prelude::FnOnce(#borrow_suffix_ty) -> __rental_prelude::Result<&#last_rlt_arg __R, __E>,
+ __R: ?Sized //#(#struct_lt_args +)*,
+ {
+ f(#borrow_suffix_expr)
+ }
+
+ /// Return a mutable reference from the mutable suffix of the struct.
+ ///
+ /// This is a subtle variation of `rent_mut` where it is legal to return a reference bounded by a rental lifetime, because that lifetime is reborrowed away before it is returned to you.
+ pub fn ref_rent_mut<__F, __R>(#self_mut_param, f: __F) -> &mut __R where
+ __F: for<#(#suffix_rlt_args,)*> __rental_prelude::FnOnce(#borrow_mut_suffix_ty) -> &#last_rlt_arg mut __R,
+ __R: ?Sized //#(#struct_lt_args +)*,
+ {
+ f(#borrow_mut_suffix_expr)
+ }
+
+ /// Optionally return a mutable reference from the mutable suffix of the struct.
+ ///
+ /// This is a subtle variation of `rent_mut` where it is legal to return a reference bounded by a rental lifetime, because that lifetime is reborrowed away before it is returned to you.
+ pub fn maybe_ref_rent_mut<__F, __R>(#self_mut_param, f: __F) -> __rental_prelude::Option<&mut __R> where
+ __F: for<#(#suffix_rlt_args,)*> __rental_prelude::FnOnce(#borrow_mut_suffix_ty) -> __rental_prelude::Option<&#last_rlt_arg mut __R>,
+ __R: ?Sized //#(#struct_lt_args +)*,
+ {
+ f(#borrow_mut_suffix_expr)
+ }
+
+ /// Try to return a mutable reference from the mutable suffix of the struct, or an error on failure.
+ ///
+ /// This is a subtle variation of `rent_mut` where it is legal to return a reference bounded by a rental lifetime, because that lifetime is reborrowed away before it is returned to you.
+ pub fn try_ref_rent_mut<__F, __R, __E>(#self_mut_param, f: __F) -> __rental_prelude::Result<&mut __R, __E> where
+ __F: for<#(#suffix_rlt_args,)*> __rental_prelude::FnOnce(#borrow_mut_suffix_ty) -> __rental_prelude::Result<&#last_rlt_arg mut __R, __E>,
+ __R: ?Sized //#(#struct_lt_args +)*,
+ {
+ f(#borrow_mut_suffix_expr)
+ }
+
+ /// Drop the rental struct and return the original head value to you.
+ pub fn into_head(#self_move_param) -> #head_ty {
+ let Self{#head_ident, ..} = #self_arg;
+ #head_ident
+ }
+ }
+ ).to_tokens(tokens);
+
+ if !attribs.is_rental_mut {
+ quote_spanned!(struct_span =>
+ #[allow(dead_code)]
+ impl #struct_impl_params #item_ident #struct_impl_args #struct_where_clause {
+ /// Return a shared reference to the head field of the struct.
+ pub fn head(#self_ref_param) -> &<#head_ty as __rental_prelude::Deref>::Target {
+ &*#self_arg.#head_ident
+ }
+
+ /// Execute a closure on shared borrows of the fields of the struct.
+ ///
+ /// The closure may return any value not bounded by one of the special rental lifetimes of the struct.
+ pub fn rent_all<__F, __R>(#self_ref_param, f: __F) -> __R where
+ __F: for<#(#struct_rlt_args,)*> __rental_prelude::FnOnce(#borrow_ident<#(#struct_rlt_args,)* #(#struct_lt_args,)* #(#struct_nonlt_args),*>) -> __R,
+ __R: #(#struct_lt_args +)*,
+ {
+ f(unsafe { #item_ident::all_erased(#self_arg) })
+ }
+
+ /// Return a shared reference from shared borrows of the fields of the struct.
+ ///
+ /// This is a subtle variation of `rent_all` where it is legal to return a reference bounded by a rental lifetime, because that lifetime is reborrowed away before it is returned to you.
+ pub fn ref_rent_all<__F, __R>(#self_ref_param, f: __F) -> &__R where
+ __F: for<#(#struct_rlt_args,)*> __rental_prelude::FnOnce(#borrow_ident<#(#struct_rlt_args,)* #(#struct_lt_args,)* #(#struct_nonlt_args),*>) -> &#last_rlt_arg __R,
+ __R: ?Sized //#(#struct_lt_args +)*,
+ {
+ f(unsafe { #item_ident::all_erased(#self_arg) })
+ }
+
+ /// Optionally return a shared reference from shared borrows of the fields of the struct.
+ ///
+ /// This is a subtle variation of `rent_all` where it is legal to return a reference bounded by a rental lifetime, because that lifetime is reborrowed away before it is returned to you.
+ pub fn maybe_ref_rent_all<__F, __R>(#self_ref_param, f: __F) -> __rental_prelude::Option<&__R> where
+ __F: for<#(#struct_rlt_args,)*> __rental_prelude::FnOnce(#borrow_ident<#(#struct_rlt_args,)* #(#struct_lt_args,)* #(#struct_nonlt_args),*>) -> __rental_prelude::Option<&#last_rlt_arg __R>,
+ __R: ?Sized //#(#struct_lt_args +)*,
+ {
+ f(unsafe { #item_ident::all_erased(#self_arg) })
+ }
+
+ /// Try to return a shared reference from shared borrows of the fields of the struct, or an error on failure.
+ ///
+ /// This is a subtle variation of `rent_all` where it is legal to return a reference bounded by a rental lifetime, because that lifetime is reborrowed away before it is returned to you.
+ pub fn try_ref_rent_all<__F, __R, __E>(#self_ref_param, f: __F) -> __rental_prelude::Result<&__R, __E> where
+ __F: for<#(#struct_rlt_args,)*> __rental_prelude::FnOnce(#borrow_ident<#(#struct_rlt_args,)* #(#struct_lt_args,)* #(#struct_nonlt_args),*>) -> __rental_prelude::Result<&#last_rlt_arg __R, __E>,
+ __R: ?Sized //#(#struct_lt_args +)*,
+ {
+ f(unsafe { #item_ident::all_erased(#self_arg) })
+ }
+
+ /// Execute a closure on shared borrows of the prefix fields and a mutable borrow of the suffix field of the struct.
+ ///
+ /// The closure may return any value not bounded by one of the special rental lifetimes of the struct.
+ pub fn rent_all_mut<__F, __R>(#self_mut_param, f: __F) -> __R where
+ __F: for<#(#struct_rlt_args,)*> __rental_prelude::FnOnce(#borrow_mut_ident<#(#struct_rlt_args,)* #(#struct_lt_args,)* #(#struct_nonlt_args),*>) -> __R,
+ __R: #(#struct_lt_args +)*,
+ {
+ f(unsafe { #item_ident::all_mut_erased(#self_arg) })
+ }
+
+ /// Return a mutable reference from shared borrows of the prefix fields and a mutable borrow of the suffix field of the struct.
+ ///
+ /// This is a subtle variation of `rent_all_mut` where it is legal to return a reference bounded by a rental lifetime, because that lifetime is reborrowed away before it is returned to you.
+ pub fn ref_rent_all_mut<__F, __R>(#self_mut_param, f: __F) -> &mut __R where
+ __F: for<#(#struct_rlt_args,)*> __rental_prelude::FnOnce(#borrow_mut_ident<#(#struct_rlt_args,)* #(#struct_lt_args,)* #(#struct_nonlt_args),*>) -> &#last_rlt_arg mut __R,
+ __R: ?Sized //#(#struct_lt_args +)*,
+ {
+ f(unsafe { #item_ident::all_mut_erased(#self_arg) })
+ }
+
+ /// Optionally return a mutable reference from shared borrows of the prefix fields and a mutable borrow of the suffix field of the struct.
+ ///
+ /// This is a subtle variation of `rent_all_mut` where it is legal to return a reference bounded by a rental lifetime, because that lifetime is reborrowed away before it is returned to you.
+ pub fn maybe_ref_rent_all_mut<__F, __R>(#self_mut_param, f: __F) -> __rental_prelude::Option<&mut __R> where
+ __F: for<#(#struct_rlt_args,)*> __rental_prelude::FnOnce(#borrow_mut_ident<#(#struct_rlt_args,)* #(#struct_lt_args,)* #(#struct_nonlt_args),*>) -> __rental_prelude::Option<&#last_rlt_arg mut __R>,
+ __R: ?Sized //#(#struct_lt_args +)*,
+ {
+ f(unsafe { #item_ident::all_mut_erased(#self_arg) })
+ }
+
+ /// Try to return a mutable reference from shared borrows of the prefix fields and a mutable borrow of the suffix field of the struct, or an error on failure.
+ ///
+ /// This is a subtle variation of `rent_all_mut` where it is legal to return a reference bounded by a rental lifetime, because that lifetime is reborrowed away before it is returned to you.
+ pub fn try_ref_rent_all_mut<__F, __R, __E>(#self_mut_param, f: __F) -> __rental_prelude::Result<&mut __R, __E> where
+ __F: for<#(#struct_rlt_args,)*> __rental_prelude::FnOnce(#borrow_mut_ident<#(#struct_rlt_args,)* #(#struct_lt_args,)* #(#struct_nonlt_args),*>) -> __rental_prelude::Result<&#last_rlt_arg mut __R, __E>,
+ __R: ?Sized //#(#struct_lt_args +)*,
+ {
+ f(unsafe { #item_ident::all_mut_erased(#self_arg) })
+ }
+ }
+ ).to_tokens(tokens);
+ }
+
+ if attribs.is_debug {
+ if attribs.is_rental_mut {
+ quote_spanned!(struct_info.ident.span()/*.resolved_at(def_site)*/ =>
+ impl #struct_impl_params __rental_prelude::fmt::Debug for #item_ident #struct_impl_args #struct_where_clause #where_extra #suffix_ty: __rental_prelude::fmt::Debug {
+ fn fmt(&self, f: &mut __rental_prelude::fmt::Formatter) -> __rental_prelude::fmt::Result {
+ f.debug_struct(#item_ident_str)
+ .field(#suffix_ident_str, &self.#suffix_ident)
+ .finish()
+ }
+ }
+ ).to_tokens(tokens);
+ } else {
+ quote_spanned!(struct_info.ident.span()/*.resolved_at(def_site)*/ =>
+ impl #struct_impl_params __rental_prelude::fmt::Debug for #item_ident #struct_impl_args #struct_where_clause #where_extra #(#field_tys: __rental_prelude::fmt::Debug),* {
+ fn fmt(&self, f: &mut __rental_prelude::fmt::Formatter) -> __rental_prelude::fmt::Result {
+ f.debug_struct(#item_ident_str)
+ #(.field(#field_ident_strs, &self.#field_idents))*
+ .finish()
+ }
+ }
+ ).to_tokens(tokens);
+ }
+ }
+
+ if attribs.is_clone {
+ quote_spanned!(struct_info.ident.span()/*.resolved_at(def_site)*/ =>
+ impl #struct_impl_params __rental_prelude::Clone for #item_ident #struct_impl_args #struct_where_clause #where_extra #(#prefix_tys: #prefix_clone_traits,)* #suffix_ty: __rental_prelude::Clone {
+ fn clone(&self) -> Self {
+ #item_ident {
+ #(#local_idents: __rental_prelude::Clone::clone(&self.#field_idents),)*
+ }
+ }
+ }
+ ).to_tokens(tokens);
+ }
+
+// if fields[fields.len() - 1].subrental.is_some() {
+// quote_spanned!(struct_span =>
+// impl<#(#borrow_lt_params,)* #(#struct_nonlt_params),*> __rental_prelude::IntoSuffix for #borrow_ident<#(#struct_rlt_args,)* #(#struct_lt_args,)* #(#struct_nonlt_args),*> #struct_where_clause {
+// type Suffix = <#borrow_suffix_ty as __rental_prelude::IntoSuffix>::Suffix;
+//
+// #[allow(non_shorthand_field_patterns)]
+// fn into_suffix(self) -> <Self as __rental_prelude::IntoSuffix>::Suffix {
+// let #borrow_ident{#suffix_ident: suffix, ..};
+// suffix.into_suffix()
+// }
+// }
+// ).to_tokens(tokens);
+//
+// quote_spanned!(struct_span =>
+// impl<#(#borrow_lt_params,)* #(#struct_nonlt_params),*> __rental_prelude::IntoSuffix for #borrow_mut_ident<#(#struct_rlt_args,)* #(#struct_lt_args,)* #(#struct_nonlt_args),*> #struct_where_clause {
+// type Suffix = <#borrow_mut_suffix_ty as __rental_prelude::IntoSuffix>::Suffix;
+//
+// #[allow(non_shorthand_field_patterns)]
+// fn into_suffix(self) -> <Self as __rental_prelude::IntoSuffix>::Suffix {
+// let #borrow_mut_ident{#suffix_ident: suffix, ..};
+// suffix.into_suffix()
+// }
+// }
+// ).to_tokens(tokens);
+//
+// if attribs.is_deref_suffix {
+// quote_spanned!(suffix_ty_span =>
+// impl #struct_impl_params __rental_prelude::Deref for #item_ident #struct_impl_args #struct_where_clause {
+// type Target = <#suffix_ty as __rental_prelude::Deref>::Target;
+//
+// fn deref(&self) -> &<Self as __rental_prelude::Deref>::Target {
+// #item_ident::ref_rent(self, |suffix| &**__rental_prelude::IntoSuffix::into_suffix(suffix))
+// }
+// }
+// ).to_tokens(tokens);
+// }
+//
+// if attribs.is_deref_mut_suffix {
+// quote_spanned!(suffix_ty_span =>
+// impl #struct_impl_params __rental_prelude::DerefMut for #item_ident #struct_impl_args #struct_where_clause {
+// fn deref_mut(&mut self) -> &mut <Self as __rental_prelude::Deref>::Target {
+// #item_ident.ref_rent_mut(self, |suffix| &mut **__rental_prelude::IntoSuffix::into_suffix(suffix))
+// }
+// }
+// ).to_tokens(tokens);
+// }
+// } else {
+ quote_spanned!(struct_span =>
+ impl<#(#borrow_lt_params,)* #(#struct_nonlt_params),*> __rental_prelude::IntoSuffix for #borrow_ident<#(#struct_rlt_args,)* #(#struct_lt_args,)* #(#struct_nonlt_args),*> #struct_where_clause {
+ type Suffix = #borrow_suffix_ty;
+
+ #[allow(non_shorthand_field_patterns)]
+ fn into_suffix(self) -> <Self as __rental_prelude::IntoSuffix>::Suffix {
+ let #borrow_ident{#suffix_ident: suffix, ..} = self;
+ suffix
+ }
+ }
+ ).to_tokens(tokens);
+
+ quote_spanned!(struct_span =>
+ impl<#(#borrow_lt_params,)* #(#struct_nonlt_params),*> __rental_prelude::IntoSuffix for #borrow_mut_ident<#(#struct_rlt_args,)* #(#struct_lt_args,)* #(#struct_nonlt_args),*> #struct_where_clause {
+ type Suffix = #borrow_mut_suffix_ty;
+
+ #[allow(non_shorthand_field_patterns)]
+ fn into_suffix(self) -> <Self as __rental_prelude::IntoSuffix>::Suffix {
+ let #borrow_mut_ident{#suffix_ident: suffix, ..} = self;
+ suffix
+ }
+ }
+ ).to_tokens(tokens);
+
+ if attribs.is_deref_suffix {
+ quote_spanned!(suffix_ty_span =>
+ impl #struct_impl_params __rental_prelude::Deref for #item_ident #struct_impl_args #struct_where_clause #where_extra {
+ type Target = <#suffix_ty as __rental_prelude::Deref>::Target;
+
+ fn deref(&self) -> &<Self as __rental_prelude::Deref>::Target {
+ #item_ident::ref_rent(self, |suffix| &**suffix)
+ }
+ }
+ ).to_tokens(tokens);
+ }
+
+ if attribs.is_deref_mut_suffix {
+ quote_spanned!(suffix_ty_span =>
+ impl #struct_impl_params __rental_prelude::DerefMut for #item_ident #struct_impl_args #struct_where_clause {
+ fn deref_mut(&mut self) -> &mut <Self as __rental_prelude::Deref>::Target {
+ #item_ident::ref_rent_mut(self, |suffix| &mut **suffix)
+ }
+ }
+ ).to_tokens(tokens);
+ }
+// }
+
+ if attribs.is_deref_suffix {
+ quote_spanned!(suffix_ty_span =>
+ impl #struct_impl_params __rental_prelude::AsRef<<Self as __rental_prelude::Deref>::Target> for #item_ident #struct_impl_args #struct_where_clause {
+ fn as_ref(&self) -> &<Self as __rental_prelude::Deref>::Target {
+ &**self
+ }
+ }
+ ).to_tokens(tokens);
+ }
+
+ if attribs.is_deref_mut_suffix {
+ quote_spanned!(suffix_ty_span =>
+ impl #struct_impl_params __rental_prelude::AsMut<<Self as __rental_prelude::Deref>::Target> for #item_ident #struct_impl_args #struct_where_clause {
+ fn as_mut(&mut self) -> &mut <Self as __rental_prelude::Deref>::Target {
+ &mut **self
+ }
+ }
+ ).to_tokens(tokens);
+ }
+
+ if attribs.is_covariant {
+ quote_spanned!(struct_info.ident.span()/*.resolved_at(def_site)*/ =>
+ #[allow(dead_code)]
+ impl #struct_impl_params #item_ident #struct_impl_args #struct_where_clause {
+ /// Borrow all fields of the struct by reborrowing away the rental lifetimes.
+ ///
+ /// This is safe because the lifetimes are verified to be covariant first.
+ pub fn all<'__s>(#self_lt_ref_param) -> <Self as __rental_prelude::#rental_trait_ident>::Borrow {
+ unsafe {
+ let _covariant = __rental_prelude::PhantomData::<#borrow_ident<#(#static_rlt_args,)* #(#struct_lt_args,)* #(#struct_nonlt_args),*>>;
+ let _covariant: __rental_prelude::PhantomData<#borrow_ident<#(#self_rlt_args,)* #(#struct_lt_args,)* #(#struct_nonlt_args),*>> = _covariant;
+
+ #item_ident::all_erased(#self_arg)
+ }
+ }
+
+ /// Borrow the suffix field of the struct by reborrowing away the rental lifetimes.
+ ///
+ /// This is safe because the lifetimes are verified to be covariant first.
+ pub fn suffix(#self_ref_param) -> <<Self as __rental_prelude::#rental_trait_ident>::Borrow as __rental_prelude::IntoSuffix>::Suffix {
+ &#self_arg.#suffix_ident
+ }
+ }
+ ).to_tokens(tokens);
+ }
+
+ if let Some(ref map_suffix_param) = attribs.map_suffix_param {
+ let mut replacer = MapTyParamReplacer{
+ ty_param: map_suffix_param,
+ };
+
+ let mapped_suffix_param = replacer.fold_type_param(map_suffix_param.clone());
+ let mapped_ty = replacer.fold_path(parse_quote!(#item_ident #struct_impl_args));
+ let mapped_suffix_ty = replacer.fold_type(suffix_orig_ty.clone());
+
+ let mut map_where_clause = syn::WhereClause{
+ where_token: Default::default(),
+ predicates: syn::punctuated::Punctuated::from_iter(
+ struct_generics.type_params().filter(|p| p.ident != map_suffix_param.ident).filter_map(|p| {
+ let mut mapped_param = p.clone();
+ mapped_param.bounds = syn::punctuated::Punctuated::new();
+
+ for mapped_bound in p.bounds.iter().filter(|b| {
+ let mut finder = MapTyParamFinder {
+ ty_param: map_suffix_param,
+ found: false,
+ };
+ finder.visit_type_param_bound(b);
+ finder.found
+ }).map(|b| {
+ let mut replacer = MapTyParamReplacer{
+ ty_param: map_suffix_param,
+ };
+
+ replacer.fold_type_param_bound(b.clone())
+ }) {
+ mapped_param.bounds.push(mapped_bound)
+ }
+
+ if mapped_param.bounds.len() > 0 {
+ Some(syn::punctuated::Pair::Punctuated(parse_quote!(#mapped_param), Default::default()))
+ } else {
+ None
+ }
+ }).chain(
+ struct_where_clause.iter().flat_map(|w| w.predicates.iter()).filter(|p| {
+ let mut finder = MapTyParamFinder {
+ ty_param: map_suffix_param,
+ found: false,
+ };
+ finder.visit_where_predicate(p);
+ finder.found
+ }).map(|p| {
+ let mut replacer = MapTyParamReplacer{
+ ty_param: map_suffix_param,
+ };
+
+ syn::punctuated::Pair::Punctuated(replacer.fold_where_predicate(p.clone()), Default::default())
+ })
+ )
+ )
+ };
+
+ let mut try_map_where_clause = map_where_clause.clone();
+ map_where_clause.predicates.push(parse_quote!(
+ __F: for<#(#suffix_rlt_args),*> __rental_prelude::FnOnce(#suffix_orig_ty) -> #mapped_suffix_ty
+ ));
+ try_map_where_clause.predicates.push(parse_quote!(
+ __F: for<#(#suffix_rlt_args),*> __rental_prelude::FnOnce(#suffix_orig_ty) -> __rental_prelude::Result<#mapped_suffix_ty, __E>
+ ));
+
+ quote_spanned!(struct_span =>
+ #[allow(dead_code)]
+ impl #struct_impl_params #item_ident #struct_impl_args #struct_where_clause {
+ /// Maps the suffix field of the rental struct to a different type.
+ ///
+ /// Consumes the rental struct and applies the closure to the suffix field. A new rental struct is then constructed with the original prefix and new suffix.
+ pub fn map<#mapped_suffix_param, __F>(#self_move_param, __f: __F) -> #mapped_ty #map_where_clause {
+ let #item_ident{ #(#field_idents,)* } = #self_arg;
+
+ let #suffix_ident = __f(#suffix_ident);
+
+ #item_ident{ #(#field_idents: #local_idents,)* }
+ }
+
+ /// Try to map the suffix field of the rental struct to a different type.
+ ///
+ /// As `map`, but the closure may fail. Upon failure, the tail is dropped, and the error is returned to you along with the head.
+ pub fn try_map<#mapped_suffix_param, __F, __E>(#self_move_param, __f: __F) -> __rental_prelude::RentalResult<#mapped_ty, __E, #head_ty> #try_map_where_clause {
+ let #item_ident{ #(#field_idents,)* } = #self_arg;
+
+ match __f(#suffix_ident) {
+ __rental_prelude::Result::Ok(#suffix_ident) => __rental_prelude::Result::Ok(#item_ident { #(#field_idents: #local_idents,)* }),
+ __rental_prelude::Result::Err(__e) => __rental_prelude::Result::Err(__rental_prelude::RentalError(__e, #head_ident)),
+ }
+ }
+
+ /// Try to map the suffix field of the rental struct to a different type.
+ ///
+ /// As `map`, but the closure may fail. Upon failure, the struct is dropped and the error is returned.
+ pub fn try_map_or_drop<#mapped_suffix_param, __F, __E>(#self_move_param, __f: __F) -> __rental_prelude::Result<#mapped_ty, __E> #try_map_where_clause {
+ let #item_ident{ #(#field_idents,)* } = #self_arg;
+
+ let #suffix_ident = __f(#suffix_ident)?;
+
+ Ok(#item_ident{ #(#field_idents: #local_idents,)* })
+ }
+ }
+ ).to_tokens(tokens);
+ }
+}
+
+
+fn get_struct_attribs(struct_info: &syn::ItemStruct) -> RentalStructAttribs
+{
+ let mut rattribs = struct_info.attrs.clone();
+
+ let mut is_rental_mut = false;
+ let mut is_debug = false;
+ let mut is_clone = false;
+ let mut is_deref_suffix = false;
+ let mut is_deref_mut_suffix = false;
+ let mut is_covariant = false;
+ let mut map_suffix_param = None;
+
+ if let Some(rental_pos) = rattribs.iter()/*.filter(|attr| !attr.is_sugared_doc)*/.position(|attr| match attr.parse_meta().expect(&format!("Struct `{}` Attribute `{}` is not properly formatted.", struct_info.ident, attr.path.clone().into_token_stream())) {
+ syn::Meta::Path(ref attr_ident) => {
+ is_rental_mut = match attr_ident.segments.first().map(|s| s.ident.to_string()).as_ref().map(String::as_str) {
+ Some("rental") => false,
+ Some("rental_mut") => true,
+ _ => return false,
+ };
+
+ true
+ },
+ syn::Meta::List(ref list) => {
+ is_rental_mut = match list.path.segments.first().map(|s| s.ident.to_string()).as_ref().map(String::as_str) {
+ Some("rental") => false,
+ Some("rental_mut") => true,
+ _ => return false,
+ };
+
+ let leftover = list.nested.iter().filter(|nested| {
+ if let syn::NestedMeta::Meta(ref meta) = **nested {
+ match *meta {
+ syn::Meta::Path(ref ident) => {
+ match ident.segments.first().map(|s| s.ident.to_string()).as_ref().map(String::as_str) {
+ Some("debug") => {
+ is_debug = true;
+ false
+ },
+ Some("clone") => {
+ is_clone = true;
+ false
+ },
+ Some("deref_suffix") => {
+ is_deref_suffix = true;
+ false
+ },
+ Some("deref_mut_suffix") => {
+ is_deref_suffix = true;
+ is_deref_mut_suffix = true;
+ false
+ },
+ Some("covariant") => {
+ is_covariant = true;
+ false
+ },
+ Some("map_suffix") => {
+ panic!("Struct `{}` `map_suffix` flag expects ` = \"T\"`.", struct_info.ident);
+ },
+ _ => true,
+ }
+ },
+ syn::Meta::NameValue(ref name_value) => {
+ match name_value.path.segments.first().map(|s| s.ident.to_string()).as_ref().map(String::as_str) {
+ Some("map_suffix") => {
+ if let syn::Lit::Str(ref ty_param_str) = name_value.lit {
+ let ty_param_str = ty_param_str.value();
+ let ty_param = struct_info.generics.type_params().find(|ty_param| {
+ if ty_param.ident.to_string() == ty_param_str {
+ return true;
+ }
+
+ false
+ }).unwrap_or_else(|| {
+ panic!("Struct `{}` `map_suffix` param `{}` does not name a type parameter.", struct_info.ident, ty_param_str);
+ });
+
+ let mut finder = MapTyParamFinder{
+ ty_param: &ty_param,
+ found: false,
+ };
+
+ if struct_info.fields.iter().take(struct_info.fields.iter().count() - 1).any(|f| {
+ finder.found = false;
+ finder.visit_field(f);
+ finder.found
+ }) {
+ panic!("Struct `{}` `map_suffix` type param `{}` appears in a prefix field.", struct_info.ident, ty_param_str);
+ }
+
+ finder.found = false;
+ finder.visit_field(struct_info.fields.iter().last().unwrap());
+ if !finder.found {
+ panic!("Struct `{}` `map_suffix` type param `{}` does not appear in the suffix field.", struct_info.ident, ty_param_str);
+ }
+
+ map_suffix_param = Some(ty_param.clone());
+ false
+ } else {
+ panic!("Struct `{}` `map_suffix` flag expects ` = \"T\"`.", struct_info.ident);
+ }
+ },
+ _ => true,
+ }
+ },
+ _ => true,
+ }
+ } else {
+ true
+ }
+ }).count();
+
+ if leftover > 0 {
+ panic!("Struct `{}` rental attribute takes optional arguments: `debug`, `clone`, `deref_suffix`, `deref_mut_suffix`, `covariant`, and `map_suffix = \"T\"`.", struct_info.ident);
+ }
+
+ true
+ },
+ _ => false,
+ }) {
+ rattribs.remove(rental_pos);
+ } else {
+ panic!("Struct `{}` must have a `rental` or `rental_mut` attribute.", struct_info.ident);
+ }
+
+ if rattribs.iter().any(|attr| attr.path != syn::parse_str::<syn::Path>("doc").unwrap()) {
+ panic!("Struct `{}` must not have attributes other than one `rental` or `rental_mut`.", struct_info.ident);
+ }
+
+ if is_rental_mut && is_clone {
+ panic!("Struct `{}` cannot be both `rental_mut` and `clone`.", struct_info.ident);
+ }
+
+ RentalStructAttribs{
+ doc: rattribs,
+ is_rental_mut: is_rental_mut,
+ is_debug: is_debug,
+ is_clone: is_clone,
+ is_deref_suffix: is_deref_suffix,
+ is_deref_mut_suffix: is_deref_mut_suffix,
+ is_covariant: is_covariant,
+ map_suffix_param: map_suffix_param,
+ }
+}
+
+
+fn prepare_fields(struct_info: &syn::ItemStruct) -> (Vec<RentalField>, syn::token::Brace) {
+ let def_site: Span = Span::call_site(); // FIXME: hygiene
+ let call_site: Span = Span::call_site();
+
+ let (fields, fields_brace) = match struct_info.fields {
+ syn::Fields::Named(ref fields) => (&fields.named, fields.brace_token),
+ syn::Fields::Unnamed(..) => panic!("Struct `{}` must not be a tuple struct.", struct_info.ident),
+ _ => panic!("Struct `{}` must have at least 2 fields.", struct_info.ident),
+ };
+
+ if fields.len() < 2 {
+ panic!("Struct `{}` must have at least 2 fields.", struct_info.ident);
+ }
+
+ let mut rfields = Vec::with_capacity(fields.len());
+ for (field_idx, field) in fields.iter().enumerate() {
+ if field.vis != syn::Visibility::Inherited {
+ panic!(
+ "Struct `{}` field `{}` must be private.",
+ struct_info.ident,
+ field.ident.as_ref().map(|ident| ident.to_string()).unwrap_or_else(|| field_idx.to_string())
+ );
+ }
+
+ let mut rfattribs = field.attrs.clone();
+ let mut subrental = None;
+ let mut target_ty_hack = None;
+
+ if let Some(sr_pos) = rfattribs.iter().position(|attr| match attr.parse_meta() {
+ Ok(syn::Meta::List(ref list)) if list.path.segments.first().map(|s| s.ident.to_string()).as_ref().map(String::as_str) == Some("subrental") => {
+ panic!(
+ "`subrental` attribute on struct `{}` field `{}` expects ` = arity`.",
+ struct_info.ident,
+ field.ident.as_ref().map(|ident| ident.to_string()).unwrap_or_else(|| field_idx.to_string())
+ );
+ },
+ Ok(syn::Meta::Path(ref word)) if word.segments.first().map(|s| s.ident.to_string()).as_ref().map(String::as_str) == Some("subrental") => {
+ panic!(
+ "`subrental` attribute on struct `{}` field `{}` expects ` = arity`.",
+ struct_info.ident,
+ field.ident.as_ref().map(|ident| ident.to_string()).unwrap_or_else(|| field_idx.to_string())
+ );
+ },
+ Ok(syn::Meta::NameValue(ref name_value)) if name_value.path.segments.first().map(|s| s.ident.to_string()).as_ref().map(String::as_str) == Some("subrental") => {
+ match name_value.lit {
+ syn::Lit::Int(ref arity) => {
+ subrental = Some(Subrental{
+ arity: arity.base10_parse::<usize>().unwrap(),
+ rental_trait_ident: syn::Ident::new(&format!("Rental{}", arity.base10_parse::<usize>().unwrap()), def_site),
+ })
+ },
+ _ => panic!(
+ "`subrental` attribute on struct `{}` field `{}` expects ` = arity`.",
+ struct_info.ident,
+ field.ident.as_ref().map(|ident| ident.to_string()).unwrap_or_else(|| field_idx.to_string())
+ ),
+ }
+
+ true
+ },
+ _ => false,
+ }) {
+ rfattribs.remove(sr_pos);
+ }
+
+ if subrental.is_some() && field_idx == fields.len() - 1 {
+ panic!(
+ "struct `{}` field `{}` cannot be a subrental because it is the suffix field.",
+ struct_info.ident,
+ field.ident.as_ref().map(|ident| ident.to_string()).unwrap_or_else(|| field_idx.to_string())
+ );
+ }
+
+ if let Some(tth_pos) = rfattribs.iter().position(|a|
+ match a.parse_meta() {
+ Ok(syn::Meta::NameValue(syn::MetaNameValue{ref path, lit: syn::Lit::Str(ref ty_str), ..})) if path.segments.first().map(|s| s.ident.to_string()).as_ref().map(String::as_str) == Some("target_ty") => {
+ if let Ok(ty) = syn::parse_str::<syn::Type>(&ty_str.value()) {
+ target_ty_hack = Some(ty);
+
+ true
+ } else {
+ panic!(
+ "`target_ty` attribute on struct `{}` field `{}` has an invalid ty string.",
+ struct_info.ident,
+ field.ident.as_ref().map(|ident| ident.to_string()).unwrap_or_else(|| field_idx.to_string())
+ );
+ }
+ },
+ _ => false,
+ }
+ ) {
+ rfattribs.remove(tth_pos);
+ }
+
+ if field_idx == fields.len() - 1 && target_ty_hack.is_some() {
+ panic!(
+ "Struct `{}` field `{}` cannot have `target_ty` attribute because it is the suffix field.",
+ struct_info.ident,
+ field.ident.as_ref().map(|ident| ident.to_string()).unwrap_or_else(|| field_idx.to_string())
+ );
+ }
+
+ let target_ty_hack = target_ty_hack.as_ref().map(|ty| (*ty).clone()).or_else(|| if field_idx < fields.len() - 1 {
+ let guess = if let syn::Type::Path(ref ty_path) = field.ty {
+ match ty_path.path.segments[ty_path.path.segments.len() - 1] {
+ syn::PathSegment{ref ident, arguments: syn::PathArguments::AngleBracketed(syn::AngleBracketedGenericArguments{ref args, ..})} => {
+ if let Some(&syn::GenericArgument::Type(ref ty)) = args.first() {
+ if ident == "Vec" {
+ Some(syn::Type::Slice(syn::TypeSlice{bracket_token: Default::default(), elem: Box::new(ty.clone())}))
+ } else {
+ Some(ty.clone())
+ }
+ } else {
+ None
+ }
+ },
+ syn::PathSegment{ref ident, arguments: syn::PathArguments::None} => {
+ if ident == "String" {
+ Some(parse_quote!(str))
+ } else {
+ None
+ }
+ },
+ _ => {
+ None
+ },
+ }
+ } else if let syn::Type::Reference(syn::TypeReference{elem: ref box_ty, ..}) = field.ty {
+ Some((**box_ty).clone())
+ } else {
+ None
+ };
+
+ let guess = guess.or_else(|| if field_idx == 0 {
+ let field_ty = &field.ty;
+ Some(parse_quote!(<#field_ty as __rental_prelude::Deref>::Target))
+ } else {
+ None
+ });
+
+ if guess.is_none() {
+ panic!("Struct `{}` field `{}` must be a type path with 1 type param, `String`, or a reference.", struct_info.ident, field.ident.as_ref().unwrap())
+ }
+
+ guess
+ } else {
+ None
+ });
+
+ if subrental.is_some() {
+ if match target_ty_hack {
+ Some(syn::Type::Path(ref ty_path)) => ty_path.qself.is_some(),
+ Some(_) => true,
+ _ => false,
+ } {
+ panic!(
+ "Struct `{}` field `{}` must have an unqualified path for its `target_ty` to be a valid subrental.",
+ struct_info.ident,
+ field.ident.as_ref().map(|ident| ident.to_string()).unwrap_or_else(|| field_idx.to_string())
+ );
+ }
+ }
+
+ let target_ty_hack_erased = target_ty_hack.as_ref().map(|tth| {
+ let mut eraser = RentalLifetimeEraser{
+ fields: &rfields,
+ used_rlt_args: &mut Vec::new(),
+ };
+
+ eraser.fold_type(tth.clone())
+ });
+
+ let mut self_rlt_args = Vec::new();
+ if let Some(Subrental{arity: sr_arity, ..}) = subrental {
+ let field_ident = field.ident.as_ref().unwrap();
+ for sr_idx in 0 .. sr_arity {
+ self_rlt_args.push(syn::Lifetime::new(&format!("'{}_{}", field_ident, sr_idx), call_site));
+ }
+ } else {
+ let field_ident = field.ident.as_ref().unwrap();
+ self_rlt_args.push(syn::Lifetime::new(&format!("'{}", field_ident), call_site));
+ }
+
+ let mut used_rlt_args = Vec::new();
+ let rty = {
+ let mut eraser = RentalLifetimeEraser{
+ fields: &rfields,
+ used_rlt_args: &mut used_rlt_args,
+ };
+
+ eraser.fold_type(field.ty.clone())
+ };
+
+ if rfattribs.iter().any(|attr| match attr.parse_meta() { Ok(syn::Meta::NameValue(syn::MetaNameValue{ref path, ..})) if path.segments.first().map(|s| s.ident.to_string()).as_ref().map(String::as_str) == Some("doc") => false, _ => true }) {
+ panic!(
+ "Struct `{}` field `{}` must not have attributes other than one `subrental` and `target_ty`.",
+ struct_info.ident,
+ field.ident.as_ref().map(|ident| ident.to_string()).unwrap_or_else(|| field_idx.to_string())
+ );
+ }
+
+ rfields.push(RentalField{
+ name: field.ident.as_ref().unwrap().clone(),
+ orig_ty: field.ty.clone(),
+ erased: syn::Field{
+ colon_token: field.colon_token,
+ ident: field.ident.clone(),
+ vis: field.vis.clone(),
+ attrs: rfattribs,
+ ty: rty,
+ },
+ subrental: subrental,
+ self_rlt_args: self_rlt_args,
+ used_rlt_args: used_rlt_args,
+ target_ty_hack: target_ty_hack,
+ target_ty_hack_erased: target_ty_hack_erased,
+ });
+ }
+
+ (rfields, fields_brace)
+}
+
+
+fn make_borrow_quotes(self_arg: &proc_macro2::TokenStream, fields: &[RentalField], is_rental_mut: bool) -> Vec<BorrowQuotes> {
+ let call_site: Span = Span::call_site();
+
+ (0 .. fields.len()).map(|idx| {
+ let (field_ty, deref) = if idx == fields.len() - 1 {
+ let orig_ty = &fields[idx].orig_ty;
+ (
+ quote!(#orig_ty),
+ quote!()
+ )
+ } else {
+ let orig_ty = &fields[idx].orig_ty;
+ (
+ quote!(<#orig_ty as __rental_prelude::Deref>::Target),
+ quote!(*)
+ )
+ };
+
+ let field_ty_hack = fields[idx].target_ty_hack.as_ref().unwrap_or(&fields[idx].orig_ty);
+ let field_ty_hack_erased = fields[idx].target_ty_hack_erased.as_ref().unwrap_or(&fields[idx].erased.ty);
+
+ if let Some(ref subrental) = fields[idx].subrental {
+ let field_ident = &fields[idx].name;
+ let rental_trait_ident = &subrental.rental_trait_ident;
+ let field_rlt_args = &fields[idx].self_rlt_args;
+
+ let (ref borrow_ty_hack, ref borrow_mut_ty_hack, ref field_args) = if let syn::Type::Path(syn::TypePath{ref qself, path: ref ty_path}) = *field_ty_hack {
+ let seg_idx = ty_path.segments.len() - 1;
+ let ty_name = &ty_path.segments[seg_idx].ident.to_string();
+
+ let mut borrow_ty_path = ty_path.clone();
+ borrow_ty_path.segments[seg_idx].ident = syn::Ident::new(&format!("{}_Borrow", ty_name), call_site);
+ borrow_ty_path.segments[seg_idx].arguments = syn::PathArguments::None;
+
+ let mut borrow_mut_ty_path = ty_path.clone();
+ borrow_mut_ty_path.segments[seg_idx].ident = syn::Ident::new(&format!("{}_BorrowMut", ty_name), call_site);
+ borrow_mut_ty_path.segments[seg_idx].arguments = syn::PathArguments::None;
+
+ match ty_path.segments[seg_idx].arguments {
+ syn::PathArguments::AngleBracketed(ref args) => {
+ (
+ syn::Type::Path(syn::TypePath{qself: qself.clone(), path: borrow_ty_path}),
+ syn::Type::Path(syn::TypePath{qself: qself.clone(), path: borrow_mut_ty_path}),
+ args.args.iter().collect::<Vec<_>>(),
+ )
+ },
+ syn::PathArguments::None => {
+ (
+ syn::Type::Path(syn::TypePath{qself: qself.clone(), path: borrow_ty_path}),
+ syn::Type::Path(syn::TypePath{qself: qself.clone(), path: borrow_mut_ty_path}),
+ Vec::with_capacity(0),
+ )
+ },
+ _ => panic!("Field `{}` must have angle-bracketed args.", fields[idx].name),
+ }
+ } else {
+ panic!("Field `{}` must be a type path.", fields[idx].name)
+ };
+
+ BorrowQuotes {
+ ty: if idx == fields.len() - 1 || !is_rental_mut {
+ quote!(<#field_ty as __rental_prelude::#rental_trait_ident<#(#field_rlt_args),*>>::Borrow)
+ } else {
+ quote!(__rental_prelude::PhantomData<<#field_ty as __rental_prelude::#rental_trait_ident<#(#field_rlt_args),*>>::Borrow>)
+ },
+ ty_hack: if idx == fields.len() - 1 || !is_rental_mut {
+ quote!(#borrow_ty_hack<#(#field_rlt_args,)* #(#field_args),*>)
+ } else {
+ quote!(__rental_prelude::PhantomData<#borrow_ty_hack<#(#field_rlt_args,)* #(#field_args),*>>)
+ },
+ expr: if idx == fields.len() - 1 || !is_rental_mut {
+ quote!(unsafe { <#field_ty_hack_erased>::all_erased(&#deref #self_arg.#field_ident) })
+ } else {
+ quote!(__rental_prelude::PhantomData::<()>)
+ },
+
+ mut_ty: if idx == fields.len() - 1 {
+ quote!(<#field_ty as __rental_prelude::#rental_trait_ident<#(#field_rlt_args),*>>::BorrowMut)
+ } else if !is_rental_mut {
+ quote!(<#field_ty as __rental_prelude::#rental_trait_ident<#(#field_rlt_args),*>>::Borrow)
+ } else {
+ quote!(__rental_prelude::PhantomData<<#field_ty as __rental_prelude::#rental_trait_ident<#(#field_rlt_args),*>>::BorrowMut>)
+ },
+ mut_ty_hack: if idx == fields.len() - 1 {
+ quote!(#borrow_mut_ty_hack<#(#field_rlt_args,)* #(#field_args),*>)
+ } else if !is_rental_mut {
+ quote!(#borrow_ty_hack<#(#field_rlt_args,)* #(#field_args),*>)
+ } else {
+ quote!(__rental_prelude::PhantomData<#borrow_mut_ty_hack<#(#field_rlt_args,)* #(#field_args),*>>)
+ },
+ mut_expr: if idx == fields.len() - 1 {
+ quote!(unsafe { <#field_ty_hack_erased>::all_mut_erased(&mut #deref #self_arg.#field_ident) })
+ } else if !is_rental_mut {
+ quote!(unsafe { <#field_ty_hack_erased>::all_erased(&#deref #self_arg.#field_ident) })
+ } else {
+ quote!(__rental_prelude::PhantomData::<()>)
+ },
+
+ new_ty: if !is_rental_mut {
+ //quote!(<#field_ty as __rental_prelude::#rental_trait_ident<#(#field_rlt_args),*>>::Borrow)
+ quote!(#borrow_ty_hack<#(#field_rlt_args,)* #(#field_args),*>)
+ } else {
+ //quote!(<#field_ty as __rental_prelude::#rental_trait_ident<#(#field_rlt_args),*>>::BorrowMut)
+ quote!(#borrow_mut_ty_hack<#(#field_rlt_args,)* #(#field_args),*>)
+ },
+ new_expr: if !is_rental_mut {
+ quote!(unsafe { <#field_ty_hack_erased>::all_erased(&#deref #field_ident) })
+ } else {
+ quote!(unsafe { <#field_ty_hack_erased>::all_mut_erased(&mut #deref #field_ident) })
+ },
+ }
+ } else {
+ let field_ident = &fields[idx].name;
+ let field_rlt_arg = &fields[idx].self_rlt_args[0];
+
+ BorrowQuotes {
+ ty: if idx == fields.len() - 1 || !is_rental_mut {
+ quote!(&#field_rlt_arg (#field_ty))
+ } else {
+ quote!(__rental_prelude::PhantomData<&#field_rlt_arg #field_ty>)
+ },
+ ty_hack: if idx == fields.len() - 1 || !is_rental_mut {
+ quote!(&#field_rlt_arg (#field_ty_hack))
+ } else {
+ quote!(__rental_prelude::PhantomData<&#field_rlt_arg #field_ty_hack>)
+ },
+ expr: if idx == fields.len() - 1 || !is_rental_mut {
+ quote!(&#deref #self_arg.#field_ident)
+ } else {
+ quote!(__rental_prelude::PhantomData::<()>)
+ },
+
+ mut_ty: if idx == fields.len() - 1 {
+ quote!(&#field_rlt_arg mut (#field_ty))
+ } else if !is_rental_mut {
+ quote!(&#field_rlt_arg (#field_ty))
+ } else {
+ quote!(__rental_prelude::PhantomData<&#field_rlt_arg mut #field_ty>)
+ },
+ mut_ty_hack: if idx == fields.len() - 1 {
+ quote!(&#field_rlt_arg mut (#field_ty_hack))
+ } else if !is_rental_mut {
+ quote!(&#field_rlt_arg (#field_ty_hack))
+ } else {
+ quote!(__rental_prelude::PhantomData<&#field_rlt_arg mut #field_ty_hack>)
+ },
+ mut_expr: if idx == fields.len() - 1 {
+ quote!(&mut #deref #self_arg.#field_ident)
+ } else if !is_rental_mut {
+ quote!(&#deref #self_arg.#field_ident)
+ } else {
+ quote!(__rental_prelude::PhantomData::<()>)
+ },
+
+ new_ty: if !is_rental_mut {
+ //quote!(&#field_rlt_arg #field_ty)
+ quote!(&#field_rlt_arg (#field_ty_hack))
+ } else {
+ //quote!(&#field_rlt_arg mut #field_ty)
+ quote!(&#field_rlt_arg mut (#field_ty_hack))
+ },
+ new_expr: if !is_rental_mut {
+ quote!(& #deref #field_ident)
+ } else {
+ quote!(&mut #deref #field_ident)
+ },
+ }
+ }
+ }).collect()
+}
+
+
+fn make_tail_closure_quotes(fields: &[RentalField], borrows: &[BorrowQuotes], is_rental_mut: bool) -> Vec<ClosureQuotes> {
+ (1 .. fields.len()).map(|idx| {
+ let local_name = &fields[idx].name;
+ let field_ty = &fields[idx].orig_ty;
+
+ if !is_rental_mut {
+ let prev_new_tys_reverse = &borrows[0 .. idx].iter().map(|b| &b.new_ty).rev().collect::<Vec<_>>();
+ let prev_new_exprs_reverse = &borrows[0 .. idx].iter().map(|b| &b.new_expr).rev().collect::<Vec<_>>();;
+ let mut prev_rlt_args = Vec::<syn::Lifetime>::new();
+ for prev_field in &fields[0 .. idx] {
+ prev_rlt_args.extend(prev_field.self_rlt_args.iter().cloned());
+ }
+ let prev_rlt_args = &prev_rlt_args;
+
+ ClosureQuotes {
+ bound: quote!(for<#(#prev_rlt_args),*> __rental_prelude::FnOnce(#(#prev_new_tys_reverse),*) -> #field_ty),
+ expr: quote!(#local_name(#(#prev_new_exprs_reverse),*)),
+ try_bound: quote!(for<#(#prev_rlt_args),*> __rental_prelude::FnOnce(#(#prev_new_tys_reverse),*) -> __rental_prelude::Result<#field_ty, __E>),
+ try_expr: quote!(#local_name(#(#prev_new_exprs_reverse),*)),
+ }
+ } else {
+ let prev_new_ty = &borrows[idx - 1].new_ty;
+ let prev_new_expr = &borrows[idx - 1].new_expr;
+ let prev_rlt_args = &fields[idx - 1].self_rlt_args.iter().chain(&fields[idx - 1].used_rlt_args).collect::<Vec<_>>();
+
+ ClosureQuotes {
+ bound: quote!(for<#(#prev_rlt_args),*> __rental_prelude::FnOnce(#prev_new_ty) -> #field_ty),
+ expr: quote!(#local_name(#prev_new_expr)),
+ try_bound: quote!(for<#(#prev_rlt_args),*> __rental_prelude::FnOnce(#prev_new_ty) -> __rental_prelude::Result<#field_ty, __E>),
+ try_expr: quote!(#local_name(#prev_new_expr)),
+ }
+ }
+ }).collect()
+}
+
+
+struct RentalStructAttribs {
+ pub doc: Vec<syn::Attribute>,
+ pub is_rental_mut: bool,
+ pub is_debug: bool,
+ pub is_clone: bool,
+ pub is_deref_suffix: bool,
+ pub is_deref_mut_suffix: bool,
+ pub is_covariant: bool,
+ pub map_suffix_param: Option<syn::TypeParam>,
+}
+
+
+struct RentalField {
+ pub name: syn::Ident,
+ pub orig_ty: syn::Type,
+ pub erased: syn::Field,
+ pub subrental: Option<Subrental>,
+ pub self_rlt_args: Vec<syn::Lifetime>,
+ pub used_rlt_args: Vec<syn::Lifetime>,
+ pub target_ty_hack: Option<syn::Type>,
+ pub target_ty_hack_erased: Option<syn::Type>,
+}
+
+
+struct Subrental {
+ arity: usize,
+ rental_trait_ident: syn::Ident,
+}
+
+
+struct BorrowQuotes {
+ pub ty: proc_macro2::TokenStream,
+ pub ty_hack: proc_macro2::TokenStream,
+ pub expr: proc_macro2::TokenStream,
+ pub mut_ty: proc_macro2::TokenStream,
+ pub mut_ty_hack: proc_macro2::TokenStream,
+ pub mut_expr: proc_macro2::TokenStream,
+ pub new_ty: proc_macro2::TokenStream,
+ pub new_expr: proc_macro2::TokenStream,
+}
+
+
+struct ClosureQuotes {
+ pub bound: proc_macro2::TokenStream,
+ pub expr: proc_macro2::TokenStream,
+ pub try_bound: proc_macro2::TokenStream,
+ pub try_expr: proc_macro2::TokenStream,
+}
+
+
+struct RentalLifetimeEraser<'a> {
+ pub fields: &'a [RentalField],
+ pub used_rlt_args: &'a mut Vec<syn::Lifetime>,
+}
+
+
+impl<'a> syn::fold::Fold for RentalLifetimeEraser<'a> {
+ fn fold_lifetime(&mut self, lifetime: syn::Lifetime) -> syn::Lifetime {
+ let def_site: Span = Span::call_site(); // FIXME: hygiene
+
+ if self.fields.iter().any(|field| field.self_rlt_args.contains(&lifetime)) {
+ if !self.used_rlt_args.contains(&lifetime) {
+ self.used_rlt_args.push(lifetime.clone());
+ }
+
+ syn::Lifetime::new("'static", def_site)
+ } else {
+ lifetime
+ }
+ }
+}
+
+
+struct MapTyParamFinder<'p> {
+ pub ty_param: &'p syn::TypeParam,
+ pub found: bool,
+}
+
+
+impl<'p, 'ast> syn::visit::Visit<'ast> for MapTyParamFinder<'p> {
+ fn visit_path(&mut self, path: &'ast syn::Path) {
+ if path.leading_colon.is_none() && path.segments.len() == 1 && path.segments[0].ident == self.ty_param.ident && path.segments[0].arguments == syn::PathArguments::None {
+ self.found = true;
+ } else {
+ for seg in &path.segments {
+ self.visit_path_segment(seg)
+ };
+ }
+ }
+}
+
+
+struct MapTyParamReplacer<'p> {
+ pub ty_param: &'p syn::TypeParam,
+}
+
+
+impl<'p> syn::fold::Fold for MapTyParamReplacer<'p> {
+ fn fold_path(&mut self, path: syn::Path) -> syn::Path {
+ if path.leading_colon.is_none() && path.segments.len() == 1 && path.segments[0].ident == self.ty_param.ident && path.segments[0].arguments == syn::PathArguments::None {
+ let def_site: Span = Span::call_site(); // FIXME: hygiene
+
+ syn::Path{
+ leading_colon: None,
+ segments: syn::punctuated::Punctuated::from_iter(Some(
+ syn::punctuated::Pair::End(syn::PathSegment{ident: syn::Ident::new("__U", def_site), arguments: syn::PathArguments::None})
+ )),
+ }
+ } else {
+ let syn::Path{
+ leading_colon,
+ segments,
+ } = path;
+
+ syn::Path{
+ leading_colon: leading_colon,
+ segments: syn::punctuated::Punctuated::from_iter(segments.into_pairs().map(|p| match p {
+ syn::punctuated::Pair::Punctuated(seg, punc) => syn::punctuated::Pair::Punctuated(self.fold_path_segment(seg), punc),
+ syn::punctuated::Pair::End(seg) => syn::punctuated::Pair::End(self.fold_path_segment(seg)),
+ }))
+ }
+ }
+ }
+
+
+ fn fold_type_param(&mut self, mut ty_param: syn::TypeParam) -> syn::TypeParam {
+ if ty_param.ident == self.ty_param.ident {
+ let def_site: Span = Span::call_site(); // FIXME: hygiene
+ ty_param.ident = syn::Ident::new("__U", def_site);
+ }
+
+ let bounds = syn::punctuated::Punctuated::from_iter(ty_param.bounds.iter().map(|b| self.fold_type_param_bound(b.clone())));
+ ty_param.bounds = bounds;
+
+ ty_param
+ }
+}
+
+
diff --git a/third_party/rust/rental/.cargo-checksum.json b/third_party/rust/rental/.cargo-checksum.json
new file mode 100644
index 0000000000..24a3467710
--- /dev/null
+++ b/third_party/rust/rental/.cargo-checksum.json
@@ -0,0 +1 @@
+{"files":{"Cargo.toml":"99e1c578dbb4b110ee59a7ba54e0812067bda50b2e39954a86c95db0cbcbc460","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"0caa93d2b69a83cfb0c2d4db6b782a5dba5ecc4f9fa1f54b04b268af739bf868","README.md":"f45eef4d1177d0b66657e49fbda9dfc963b2a0110e5825e9c9b19d9d9a26dd3d","src/lib.rs":"2cfcf8833642107e34dab2a4457a9c9be144b21dd6d37090444f055067fd551b","tests/clone.rs":"0bf3267771ef8b3bf3c0d0ab98b7e99597c808f50596e0b6c12dfd5598eaf820","tests/complex.rs":"7c7f685e7ae7435698e34f8c29bd5bd8b89143ea43c3381a4627d366902b1285","tests/complex_mut.rs":"374d4a0782b00a5679b55d73b112c424977c0dba525072fadf0fc96ed00f632a","tests/covariant.rs":"fc5697208f44b96047e6423f8b9621a379e29cc5709dcf91f860f1424ef2a0d1","tests/debug.rs":"38e345ca450effc80898a267a1214a72d615441fa31697410ed1465638b85813","tests/drop_order.rs":"8c98fef9f0ea4eac8cebbd384be8c8e8db6d5aaffe42b83a6390e74d91dfd1ac","tests/generic.rs":"2f9d7aa9cc3dd3887b7270835cad8d914150b9809fb41430dc317b14788d3fa5","tests/lt_params.rs":"4f3e9252a35836c4a3a76a68b4fe4eeedb002169b278a0cbc82705716b2a3e6a","tests/map.rs":"314c5cd5163e6bef174fd7a4e37d9b8b9248d4e71f3387f5d6aa29ee784332b7","tests/simple_mut.rs":"beaabd34ed1c06c2f60d05c19c103c32588f52621e7a953e1bf3e2a0759cb09d","tests/simple_ref.rs":"aa64fa94f08926957293129cd26c128c6be21934f026bd052aa9b49a2e8987c7","tests/string.rs":"4e12df6b4e67991c8d912422935f75f2b0016dfa2d26a3305532fc98facc7c67","tests/subrental.rs":"dad1f751c9c8ef3b76e1be6513ae7419ddd16032e5fd71d8baa445d3d3f9e044","tests/target_ty_hack.rs":"d13301dbfb36646eb461928edbb088fe4ed5b01934c12fa1c2b3cd486f7bfb8d","tests/trait.rs":"b3697d80b7b61238401d133f53d058d2e3ad17e6925cc45ed8b8718bcf755e1a","tests/unused.rs":"e420e6d13bcd8b8e3def4a77e8de6502fdf5fd55d44ccad611f16e57c2d67704","tests/vec_slice.rs":"bd2826caeba5ae64268c0e2aed870afacc6d8ba3da850a309b19c7f0b17428eb"},"package":"8545debe98b2b139fb04cad8618b530e9b07c152d99a5de83c860b877d67847f"} \ No newline at end of file
diff --git a/third_party/rust/rental/Cargo.toml b/third_party/rust/rental/Cargo.toml
new file mode 100644
index 0000000000..2634b4881d
--- /dev/null
+++ b/third_party/rust/rental/Cargo.toml
@@ -0,0 +1,33 @@
+# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
+#
+# When uploading crates to the registry Cargo will automatically
+# "normalize" Cargo.toml files for maximal compatibility
+# with all versions of Cargo and also rewrite `path` dependencies
+# to registry (e.g., crates.io) dependencies
+#
+# If you believe there's an error in this file please file an
+# issue against the rust-lang/cargo repository. If you're
+# editing this file be aware that the upstream Cargo.toml
+# will likely look very different (and much more reasonable)
+
+[package]
+name = "rental"
+version = "0.5.5"
+authors = ["Jameson Ernst <jameson@jpernst.com>"]
+description = "A macro to generate safe self-referential structs, plus premade types for common use cases."
+documentation = "https://docs.rs/rental"
+readme = "README.md"
+keywords = ["lifetime", "ownership", "borrowing", "self", "reference"]
+categories = ["rust-patterns", "no-std"]
+license = "MIT/Apache-2.0"
+repository = "https://github.com/jpernst/rental"
+[dependencies.rental-impl]
+version = "=0.5.5"
+
+[dependencies.stable_deref_trait]
+version = "1.0.0"
+default-features = false
+
+[features]
+default = ["std"]
+std = ["stable_deref_trait/std"]
diff --git a/third_party/rust/rental/LICENSE-APACHE b/third_party/rust/rental/LICENSE-APACHE
new file mode 100644
index 0000000000..16fe87b06e
--- /dev/null
+++ b/third_party/rust/rental/LICENSE-APACHE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+END OF TERMS AND CONDITIONS
+
+APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+Copyright [yyyy] [name of copyright owner]
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
diff --git a/third_party/rust/rental/LICENSE-MIT b/third_party/rust/rental/LICENSE-MIT
new file mode 100644
index 0000000000..3e0417e5c0
--- /dev/null
+++ b/third_party/rust/rental/LICENSE-MIT
@@ -0,0 +1,25 @@
+Copyright (c) 2016 Jameson Ernst
+
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
diff --git a/third_party/rust/rental/README.md b/third_party/rust/rental/README.md
new file mode 100644
index 0000000000..4124f178cf
--- /dev/null
+++ b/third_party/rust/rental/README.md
@@ -0,0 +1,47 @@
+# Rental - A macro to generate safe self-referential structs, plus premade types for common use cases.
+
+[Documentation](http://docs.rs/rental)
+
+# Overview
+It can sometimes occur in the course of designing an API that it would be convenient, or even necessary, to allow fields within a struct to hold references to other fields within that same struct. Rust's concept of ownership and borrowing is powerful, but can't express such a scenario yet.
+//!
+Creating such a struct manually would require unsafe code to erase lifetime parameters from the field types. Accessing the fields directly would be completely unsafe as a result. This library addresses that issue by allowing access to the internal fields only under carefully controlled circumstances, through closures that are bounded by generic lifetimes to prevent infiltration or exfiltration of any data with an incorrect lifetime. In short, while the struct internally uses unsafe code to store the fields, the interface exposed to the consumer of the struct is completely safe. The implementation of this interface is subtle and verbose, hence the macro to automate the process.
+
+The API of this crate consists of the `rental` macro that generates safe self-referential structs, a few example instantiations to demonstrate the API provided by such structs (see `examples`), and a module of premade instantiations to cover common use cases (see `common`).
+
+# Example
+One instance where this crate is useful is when working with `libloading`. That crate provides a `Library` struct that defines methods to borrow `Symbol`s from it. These symbols are bounded by the lifetime of the library, and are thus considered a borrow. Under normal circumstances, one would be unable to store both the library and the symbols within a single struct, but the macro defined in this crate allows you to define a struct that is capable of storing both simultaneously, like so:
+
+```rust,ignore
+rental! {
+ pub mod rent_libloading {
+ use libloading;
+
+ #[rental(deref_suffix)] // This struct will deref to the Deref::Target of Symbol.
+ pub struct RentSymbol<S: 'static> {
+ lib: Box<libloading::Library>, // Library is boxed for StableDeref.
+ sym: libloading::Symbol<'lib, S>, // The 'lib lifetime borrows lib.
+ }
+ }
+}
+
+fn main() {
+ let lib = libloading::Library::new("my_lib.so").unwrap(); // Open our dylib.
+ if let Ok(rs) = rent_libloading::RentSymbol::try_new(
+ Box::new(lib),
+ |lib| unsafe { lib.get::<extern "C" fn()>(b"my_symbol") }) // Loading symbols is unsafe.
+ {
+ (*rs)(); // Call our function
+ };
+}
+```
+
+In this way we can store both the `Library` and the `Symbol` that borrows it in a single struct. We can even tell our struct to deref to the function pointer itself so we can easily call it. This is legal because the function pointer does not contain any of the special lifetimes introduced by the rental struct in its type signature, which means reborrowing will not expose them to the outside world. As an aside, the `unsafe` block for loading the symbol is necessary because the act of loading a symbol from a dylib is unsafe, and is unrelated to rental.
+
+# Limitations
+There are a few limitations with the current implementation due to bugs or pending features in rust itself. These will be lifted once the underlying language allows it.
+
+* Currently, the rental struct itself can only take lifetime parameters under certain conditions. These conditions are difficult to fully describe, but in general, a lifetime param of the rental struct itself must appear "outside" of any special rental lifetimes in the type signatures of the struct fields. To put it another way, replacing the rental lifetimes with `'static` must still produce legal types, otherwise it will not compile. In most situations this is fine, since most of the use cases for this library involve erasing all of the lifetimes anyway, but there's no reason why the head element of a rental struct shouldn't be able to take arbitrary lifetime params. This is currently impossible to fully support due to lack of an `'unsafe` lifetime or equivalent feature.
+* Prefix fields, and the head field if it IS a subrental, must be of the form `Foo<T>` where `Foo` is some `StableDeref` container, or rental will not be able to correctly guess the `Deref::Target` of the type. If you are using a custom type that does not fit this pattern, you can use the `target_ty` attribute on the field to manually specify the target type. If the head field is NOT a subrental, then it may have any form as long as it is `StableDeref`.
+* Rental structs can only have a maximum of 32 rental lifetimes, including transitive rental lifetimes from subrentals. This limitation is the result of needing to implement a new trait for each rental arity. This limit can be easily increased if necessary.
+* The references received in the constructor closures don't currently have their lifetime relationship to eachother expressed in bounds, since HRTB lifetimes do not currently support bounds. This is not a soundness hole, but it does prevent some otherwise valid uses from compiling.
diff --git a/third_party/rust/rental/src/lib.rs b/third_party/rust/rental/src/lib.rs
new file mode 100644
index 0000000000..d7c9f8aaaf
--- /dev/null
+++ b/third_party/rust/rental/src/lib.rs
@@ -0,0 +1,487 @@
+//! A macro to generate safe self-referntial structs, plus premade types for common use cases.
+//!
+//! # Overview
+//! It can sometimes occur in the course of designing an API that it would be convenient, or even necessary, to allow fields within a struct to hold references to other fields within that same struct. Rust's concept of ownership and borrowing is powerful, but can't express such a scenario yet.
+//!
+//! Creating such a struct manually would require unsafe code to erase lifetime parameters from the field types. Accessing the fields directly would be completely unsafe as a result. This library addresses that issue by allowing access to the internal fields only under carefully controlled circumstances, through closures that are bounded by generic lifetimes to prevent infiltration or exfiltration of any data with an incorrect lifetime. In short, while the struct internally uses unsafe code to store the fields, the interface exposed to the consumer of the struct is completely safe. The implementation of this interface is subtle and verbose, hence the macro to automate the process.
+//!
+//! The API of this crate consists of the [`rental`](macro.rental.html) macro that generates safe self-referential structs, a few example instantiations to demonstrate the API provided by such structs (see [`examples`](examples/index.html)), and a module of premade instantiations to cover common use cases (see [`common`](common/index.html)).
+//!
+//! # Example
+//! One instance where this crate is useful is when working with `libloading`. That crate provides a `Library` struct that defines methods to borrow `Symbol`s from it. These symbols are bounded by the lifetime of the library, and are thus considered a borrow. Under normal circumstances, one would be unable to store both the library and the symbols within a single struct, but the macro defined in this crate allows you to define a struct that is capable of storing both simultaneously, like so:
+//!
+//! ```rust,ignore
+//! rental! {
+//! pub mod rent_libloading {
+//! use libloading;
+//!
+//! #[rental(deref_suffix)] // This struct will deref to the Deref::Target of Symbol.
+//! pub struct RentSymbol<S: 'static> {
+//! lib: Box<libloading::Library>, // Library is boxed for StableDeref.
+//! sym: libloading::Symbol<'lib, S>, // The 'lib lifetime borrows lib.
+//! }
+//! }
+//! }
+//!
+//! fn main() {
+//! let lib = libloading::Library::new("my_lib.so").unwrap(); // Open our dylib.
+//! if let Ok(rs) = rent_libloading::RentSymbol::try_new(
+//! Box::new(lib),
+//! |lib| unsafe { lib.get::<extern "C" fn()>(b"my_symbol") }) // Loading symbols is unsafe.
+//! {
+//! (*rs)(); // Call our function
+//! };
+//! }
+//! ```
+//!
+//! In this way we can store both the `Library` and the `Symbol` that borrows it in a single struct. We can even tell our struct to deref to the function pointer itself so we can easily call it. This is legal because the function pointer does not contain any of the special lifetimes introduced by the rental struct in its type signature, which means reborrowing will not expose them to the outside world. As an aside, the `unsafe` block for loading the symbol is necessary because the act of loading a symbol from a dylib is unsafe, and is unrelated to rental.
+//!
+//! **NOTE for Rust 2018:** Relying on implicit crate imports may cause compile errors in code generated by this macro. To avoid this, import the crate manually like so:
+//! ```rust,ignore
+//! #[macro_use]
+//! extern crate rental;
+//! ```
+//!
+//! # Limitations
+//! There are a few limitations with the current implementation due to bugs or pending features in rust itself. These will be lifted once the underlying language allows it.
+//!
+//! * Currently, the rental struct itself can only take lifetime parameters under certain conditions. These conditions are difficult to fully describe, but in general, a lifetime param of the rental struct itself must appear "outside" of any special rental lifetimes in the type signatures of the struct fields. To put it another way, replacing the rental lifetimes with `'static` must still produce legal types, otherwise it will not compile. In most situations this is fine, since most of the use cases for this library involve erasing all of the lifetimes anyway, but there's no reason why the head element of a rental struct shouldn't be able to take arbitrary lifetime params. This is currently impossible to fully support due to lack of an `'unsafe` lifetime or equivalent feature.
+//! * Prefix fields, and the head field if it IS a subrental, must be of the form `Foo<T>` where `Foo` is some `StableDeref` container, or rental will not be able to correctly guess the `Deref::Target` of the type. If you are using a custom type that does not fit this pattern, you can use the `target_ty` attribute on the field to manually specify the target type. If the head field is NOT a subrental, then it may have any form as long as it is `StableDeref`.
+//! * Rental structs can only have a maximum of 32 rental lifetimes, including transitive rental lifetimes from subrentals. This limitation is the result of needing to implement a new trait for each rental arity. This limit can be easily increased if necessary.
+//! * The references received in the constructor closures don't currently have their lifetime relationship to eachother expressed in bounds, since HRTB lifetimes do not currently support bounds. This is not a soundness hole, but it does prevent some otherwise valid uses from compiling.
+
+
+#![cfg_attr(not(feature = "std"), no_std)]
+
+#[cfg(feature = "std")]
+extern crate core;
+#[macro_use]
+extern crate rental_impl;
+extern crate stable_deref_trait;
+
+#[doc(hidden)]
+pub use rental_impl::*;
+
+
+/// This trait converts any `*_Borrow` or `*_BorrowMut` structs generated by the [`rental`](macro.rental.html) macro into their suffix (most dependent) field.
+///
+/// When you own a borrow struct, such as in the body of the closure provided to the `rent_all` or `ref_rent_all` methods of a rental struct, you can call `into_suffix()` to discard the borrow struct and obtain the suffix field if you don't need any of the other fields.
+pub trait IntoSuffix {
+ /// Type of the transitive suffix of the borrow struct.
+ ///
+ /// If the suffix field of the borrow struct is itself a borrow struct of a subrental, then this type is the suffix of that nested borrow struct, recursively.
+ type Suffix;
+
+ /// Discard the borrow struct and return the transitive suffix field.
+ ///
+ /// If the suffix field of the borrow struct is itself a borrow struct of a subrental, then this function will return the nested suffix of that borrow struct, recursively.
+ fn into_suffix(self) -> <Self as IntoSuffix>::Suffix;
+}
+
+
+/// An error wrapper returned by the `try_new` method of a rental struct.
+///
+/// This will contain the first error returned by the closure chain, as well as the original head value you passed in so you can do something else with it.
+pub struct RentalError<E, H> (pub E, pub H);
+
+pub type RentalResult<T, E, H> = Result<T, RentalError<E, H>>;
+
+
+macro_rules! define_rental_traits {
+ ($max_arity:expr) => {
+ #[allow(unused)]
+ #[derive(__rental_traits)]
+ enum ProceduralMasqueradeDummyType {
+ Input = (0, stringify!($max_arity)).0
+ }
+ };
+}
+
+
+#[doc(hidden)]
+pub mod __rental_prelude {
+ pub use core::marker::PhantomData;
+ pub use core::clone::Clone;
+ pub use core::ops::{FnOnce, Deref, DerefMut, Drop};
+ pub use core::convert::{AsRef, AsMut, Into};
+ pub use core::borrow::{Borrow, BorrowMut};
+ pub use core::mem::transmute;
+ pub use core::result::Result;
+ pub use core::option::Option;
+ pub use core::fmt;
+ pub use stable_deref_trait::{StableDeref, CloneStableDeref};
+
+ pub use super::{IntoSuffix, RentalError, RentalResult};
+
+
+ define_rental_traits!(32);
+
+
+ #[inline(always)]
+ pub fn static_assert_stable_deref<T: StableDeref>() { }
+ #[inline(always)]
+ pub fn static_assert_mut_stable_deref<T: DerefMut + StableDeref>() { }
+}
+
+
+/// The bedrock of this crate, this macro will generate self-referential structs.
+///
+/// This macro is invoked in item position. The body parses as valid rust and contains no special syntax. Only certain constructs are allowed, and a few special attributes and lifetimes are recognized.
+///
+/// To start, the top level item of the macro invocation must be a single module. This module will contain all items that the macro generates and export them to you. Within the module, only three types of items are accepted: `use` statements, type aliases, and struct definitions. The `use` statements and type aliases are passed directly through with no special consideration; the primary concern is the struct definitions.
+///
+/// First, all struct definitions must have a `#[rental]` or `#[rental_mut]` attribute to indicate that they are self-referential. The `mut` variant indicates that the struct mutably borrows itself, while the normal attribute assumes shared borrows. These attributes also accept certain flags to enable specific features, described below.
+///
+/// Next, the structs must have named fields (no tuple structs) and they must have at least 2 fields, since a struct with 1 field can't meaningfully reference itself anyway.
+///
+/// The order of the fields is significant, as they are declared in order of least to most dependent. The first field, also referred to as the "head" of the struct, contains no self-references, the second field may borrow the first, the third field may borrow the second or first, and so on. The chain of fields after the head is called the "tail".
+///
+/// Because rental structs are self-referential, special care is taken to ensure that moving the struct will not invalidate any internal references. This is accomplished by requiring all fields but the last one, collectively known as the "prefix" of the struct, to implement [`StableDeref`](https://crates.io/crates/stable_deref_trait). This is not required for the final field of the struct, known as the "suffix", since nothing holds a reference to it.
+///
+/// NOTE: Because of a workaround for a compiler bug, rental might not always correctly determine the `Deref::Target` type of your prefix fields. If you receive type errors when compiling, you can try using the `target_ty` attribute on the field of the struct. Set this attribute equal to a string that names the correct target type (e.g. `#[target_ty = "[u8]"]` for `Vec<u8>`.
+///
+/// Each field that you declare creates a special lifetime of the same name that can be used by later fields to borrow it. This is how the referential relationships are established in the struct definition.
+///
+/// This is a all a bit to chew on so far, so let's stop and take a look at an example:
+///
+/// ```rust
+/// # #[macro_use] extern crate rental;
+/// pub struct Foo { i: i32 }
+/// pub struct Bar<'a> { foo: &'a Foo }
+/// pub struct Qux<'a: 'b, 'b> { bar: &'b Bar<'a> }
+///
+/// rental! {
+/// mod my_rentals {
+/// use super::*;
+///
+/// #[rental]
+/// pub struct MyRental {
+/// foo: Box<Foo>,
+/// bar: Box<Bar<'foo>>,
+/// qux: Qux<'foo, 'bar>,
+/// }
+/// }
+/// }
+/// # fn main () { }
+/// ```
+///
+/// Here we see each field use the special lifetimes of the previous fields to establish the borrowing chain.
+///
+/// In addition to the rental struct itself, two other structs are generated, with `_Borrow` and `_BorrowMut` appended to the original struct name (e.g. `MyRental_Borrow` and `MyRental_BorrowMut`). These structs contain the same fields as the original struct, but are borrows of the originals. These structs are passed into certain closures that you provide to the [`rent_all`](examples/struct.RentRef.html#method.rent_all) suite of methods to allow you access to the struct's fields. For mutable rentals, these structs will only contain a borrow of the suffix; the other fields will be erased with `PhantomData`.
+///
+/// # Attribute Flags
+///
+/// A `rental` or `rental_mut` attribute accepts various options that affect the code generated by the macro to add certain features if your type supports them. These flags are placed in parens after the attribute, similar to the `cfg` attribute, e.g. `#[rental(debug)]`.
+///
+/// ## debug
+/// If all the fields of your struct implement `Debug` then you can use the `debug` option on the rental attribute to gain a `Debug` impl on the struct itself. For mutable rental structs, only the suffix field needs to be `Debug`, as it is the only one that will be printed. The prefix fields are mutably borrowed so cannot be accessed while the suffix exists.
+///
+/// ## clone
+/// If the prefix fields of your struct impl `CloneStableDeref` (which means clones still deref to the same object), and the suffix field is `Clone`, then your rental struct can be `Clone` as well.
+///
+/// ## deref_suffix / deref_mut_suffix
+/// If the suffix field of the struct implements `Deref` or `DerefMut`, you can add a `deref_suffix` or `deref_mut_suffix` argument to the `rental` attribute on the struct. This will generate a `Deref` implementation for the rental struct itself that will deref through the suffix and return the borrow to you, for convenience. Note, however, that this will only be legal if none of the special rental lifetimes appear in the type signature of the deref target. If they do, exposing them to the outside world could result in unsafety, so this is not allowed and such a scenario will not compile.
+///
+/// ## covariant
+/// Since the true lifetime of a self-referential field is currently inexpressible in rust, the lifetimes the fields use internally are fake. This means that directly borrowing the fields of the struct would be quite unsafe. However, if we know that the type is covariant over its lifetime parameters, then we can reborrow away the fake rental lifetimes to something concrete and safe. This tag will provide methods that access the fields of the struct directly, while also ensuring that the covariance requirement is met, otherwise the struct will fail to compile. For an exmaple see [`SimpleRefCovariant`](examples/struct.SimpleRefCovariant.html).
+///
+/// ## map_suffix = "T"
+/// For rental structs that contain some kind of smart reference as their suffix field, such as a `Ref` or `MutexGuard`, it can be useful to be able to map the reference to another type. This option allows you to do so, given certain conditions. First, your rental struct must have a type parameter in the position that you want to map, such as `Ref<'head, T>` or `MutexGuard<'head, T>`. Second, this type param must ONLY be used in the suffix field. Specify the type parameter you wish to use with `map_suffix = "T"` where `T` is the name of the type param that satisfies these conditions. For an example of the methods this option provides, see [`SimpleRefMap`](examples/struct.SimpleRefMap.html).
+///
+/// # Subrentals
+///
+/// Finally, there is one other capability to discuss. If a rental struct has been defined elsewhere, either in our own crate or in a dependency, we'd like to be able to chain our own rental struct off of it. In this way, we can use another rental struct as a sort of pre-packaged prefix of our own. As a variation on the above example, it would look like this:
+///
+/// ```rust
+/// # #[macro_use] extern crate rental;
+/// pub struct Foo { i: i32 }
+/// pub struct Bar<'a> { foo: &'a Foo }
+/// pub struct Qux<'a: 'b, 'b> { bar: &'b Bar<'a> }
+///
+/// rental! {
+/// mod my_rentals {
+/// use super::*;
+///
+/// #[rental]
+/// pub struct OtherRental {
+/// foo: Box<Foo>,
+/// bar: Bar<'foo>,
+/// }
+///
+/// #[rental]
+/// pub struct MyRental {
+/// #[subrental = 2]
+/// prefix: Box<OtherRental>,
+/// qux: Qux<'prefix_0, 'prefix_1>,
+/// }
+/// }
+/// }
+/// # fn main () { }
+/// ```
+///
+/// The first rental struct is fairly standard, so we'll focus on the second one. The head field is given a `subrental` attribute and set equal to an integer indicating the arity. The arity of a rental struct is the number of special lifetimes it creates. As can be seen above, the first struct has two fields, neither of which is itself a subrental, so it has an arity of 2. The arity of the second struct would be 3, since it includes the two fields of the first rental as well as one new one. In this way, arity is transitive. So if we used our new struct itself as a subrental of yet another struct, we'd need to declare the field with `subrental = 3`. The special lifetimes created by a subrental are the field name followed by a `_` and a zero-based index. Also note that the suffix field cannot itself be a subrental, only prefix fields.
+///
+/// This covers the essential capabilities of the macro itself. For details on the API of the structs themselves, see the [`examples`](examples/index.html) module.
+#[macro_export]
+macro_rules! rental {
+ {
+ $(#[$attr:meta])*
+ mod $rental_mod:ident {
+ $($body:tt)*
+ }
+ } => {
+ $(#[$attr])*
+ mod $rental_mod {
+ #[allow(unused_imports)]
+ use $crate::__rental_prelude;
+
+ #[allow(unused)]
+ #[derive(__rental_structs_and_impls)]
+ enum ProceduralMasqueradeDummyType {
+ Input = (0, stringify!($($body)*)).0
+ }
+ }
+ };
+ {
+ $(#[$attr:meta])*
+ pub mod $rental_mod:ident {
+ $($body:tt)*
+ }
+ } => {
+ $(#[$attr])*
+ pub mod $rental_mod {
+ #[allow(unused_imports)]
+ use $crate::__rental_prelude;
+
+ #[allow(unused)]
+ #[derive(__rental_structs_and_impls)]
+ enum ProceduralMasqueradeDummyType {
+ Input = (0, stringify!($($body)*)).0
+ }
+ }
+ };
+ {
+ $(#[$attr:meta])*
+ pub($($vis:tt)*) mod $rental_mod:ident {
+ $($body:tt)*
+ }
+ } => {
+ $(#[$attr])*
+ pub($($vis)*) mod $rental_mod {
+ #[allow(unused_imports)]
+ use $crate::__rental_prelude;
+
+ #[allow(unused)]
+ #[derive(__rental_structs_and_impls)]
+ enum ProceduralMasqueradeDummyType {
+ Input = (0, stringify!($($body)*)).0
+ }
+ }
+ };
+}
+
+
+#[cfg(feature = "std")]
+rental! {
+ /// Example types that demonstrate the API generated by the rental macro.
+ pub mod examples {
+ use std::sync;
+
+ /// The simplest shared rental. The head is a boxed integer, and the suffix is a ref to that integer. This struct demonstrates the basic API that all shared rental structs have. See [`SimpleMut`](struct.SimpleMut.html) for the mutable analog.
+ #[rental]
+ pub struct SimpleRef {
+ head: Box<i32>,
+ iref: &'head i32,
+ }
+
+ /// The simplest mutable rental. Mutable rentals have a slightly different API; compare this struct to [`SimpleRef`](struct.SimpleRef.html) for the clearest picture of how they differ.
+ #[rental_mut]
+ pub struct SimpleMut {
+ head: Box<i32>,
+ iref: &'head mut i32,
+ }
+
+ /// Identical to [`SimpleRef`](struct.SimpleRef.html), but with the `debug` flag enabled. This will provide a `Debug` impl for the struct as long as all of the fields are `Debug`.
+ #[rental(debug)]
+ pub struct SimpleRefDebug {
+ head: Box<i32>,
+ iref: &'head i32,
+ }
+
+ /// Similar to [`SimpleRef`](struct.SimpleRef.html), but with the `clone` flag enabled. This will provide a `Clone` impl for the struct as long as the prefix fields are `CloneStableDeref` and the suffix is `Clone` . Notice that the head is an `Arc`, since a clone of an `Arc` will deref to the same object as the original.
+ #[rental(clone)]
+ pub struct SimpleRefClone {
+ head: sync::Arc<i32>,
+ iref: &'head i32,
+ }
+
+ /// Identical to [`SimpleRef`](struct.SimpleRef.html), but with the `deref_suffix` flag enabled. This will provide a `Deref` impl for the struct, which will in turn deref the suffix. Notice that this flag also removes the `self` param from all methods, replacing it with an explicit param. This prevents any rental methods from blocking deref.
+ #[rental(deref_suffix)]
+ pub struct SimpleRefDeref {
+ head: Box<i32>,
+ iref: &'head i32,
+ }
+
+ /// Identical to [`SimpleMut`](struct.SimpleMut.html), but with the `deref_mut_suffix` flag enabled. This will provide a `DerefMut` impl for the struct, which will in turn deref the suffix.Notice that this flag also removes the `self` param from all methods, replacing it with an explicit param. This prevents any rental methods from blocking deref.
+ #[rental_mut(deref_mut_suffix)]
+ pub struct SimpleMutDeref {
+ head: Box<i32>,
+ iref: &'head mut i32,
+ }
+
+ /// Identical to [`SimpleRef`](struct.SimpleRef.html), but with the `covariant` flag enabled. For rental structs where the field types have covariant lifetimes, this will allow you to directly borrow the fields, as they can be safely reborrowed to a shorter lifetime. See the [`all`](struct.SimpleRefCovariant.html#method.all) and [`suffix`](struct.SimpleRefCovariant.html#method.suffix) methods.
+ #[rental(covariant)]
+ pub struct SimpleRefCovariant {
+ head: Box<i32>,
+ iref: &'head i32,
+ }
+
+ /// Identical to [`SimpleRef`](struct.SimpleRef.html), but with the `map_suffix` flag enabled. This will allow the type of the suffix to be changed by mapping it to another instantiation of the same struct with the different type param. See the [`map`](struct.SimpleRefMap.html#method.map), [`try_map`](struct.SimpleRefMap.html#method.try_map), and [`try_map_or_drop`](struct.SimpleRefMap.html#method.try_map_or_drop) methods.
+ #[rental(map_suffix = "T")]
+ pub struct SimpleRefMap<T: 'static> {
+ head: Box<i32>,
+ iref: &'head T,
+ }
+ }
+}
+
+
+#[cfg(feature = "std")]
+rental! {
+ /// Premade types for the most common use cases.
+ pub mod common {
+ use std::ops::DerefMut;
+ use stable_deref_trait::StableDeref;
+ use std::cell;
+ use std::sync;
+
+ /// Stores an owner and a shared reference in the same struct.
+ ///
+ /// ```rust
+ /// # extern crate rental;
+ /// # use rental::common::RentRef;
+ /// # fn main() {
+ /// let r = RentRef::new(Box::new(5), |i| &*i);
+ /// assert_eq!(*r, RentRef::rent(&r, |iref| **iref));
+ /// # }
+ /// ```
+ #[rental(debug, clone, deref_suffix, covariant, map_suffix = "T")]
+ pub struct RentRef<H: 'static + StableDeref, T: 'static> {
+ head: H,
+ suffix: &'head T,
+ }
+
+ /// Stores an owner and a mutable reference in the same struct.
+ ///
+ /// ```rust
+ /// # extern crate rental;
+ /// # use rental::common::RentMut;
+ /// # fn main() {
+ /// let mut r = RentMut::new(Box::new(5), |i| &mut *i);
+ /// *r = 12;
+ /// assert_eq!(12, RentMut::rent(&mut r, |iref| **iref));
+ /// # }
+ /// ```
+ #[rental_mut(debug, deref_mut_suffix, covariant, map_suffix = "T")]
+ pub struct RentMut<H: 'static + StableDeref + DerefMut, T: 'static> {
+ head: H,
+ suffix: &'head mut T,
+ }
+
+ /// Stores a `RefCell` and a `Ref` in the same struct.
+ ///
+ /// ```rust
+ /// # extern crate rental;
+ /// # use rental::common::RentRefCell;
+ /// # fn main() {
+ /// use std::cell;
+ ///
+ /// let r = RentRefCell::new(Box::new(cell::RefCell::new(5)), |c| c.borrow());
+ /// assert_eq!(*r, RentRefCell::rent(&r, |c| **c));
+ /// # }
+ /// ```
+ #[rental(debug, clone, deref_suffix, covariant, map_suffix = "T")]
+ pub struct RentRefCell<H: 'static + StableDeref, T: 'static> {
+ head: H,
+ suffix: cell::Ref<'head, T>,
+ }
+
+ /// Stores a `RefCell` and a `RefMut` in the same struct.
+ ///
+ /// ```rust
+ /// # extern crate rental;
+ /// # use rental::common::RentRefCellMut;
+ /// # fn main() {
+ /// use std::cell;
+ ///
+ /// let mut r = RentRefCellMut::new(Box::new(cell::RefCell::new(5)), |c| c.borrow_mut());
+ /// *r = 12;
+ /// assert_eq!(12, RentRefCellMut::rent(&r, |c| **c));
+ /// # }
+ /// ```
+ #[rental_mut(debug, deref_mut_suffix, covariant, map_suffix = "T")]
+ pub struct RentRefCellMut<H: 'static + StableDeref + DerefMut, T: 'static> {
+ head: H,
+ suffix: cell::RefMut<'head, T>,
+ }
+
+
+ /// Stores a `Mutex` and a `MutexGuard` in the same struct.
+ ///
+ /// ```rust
+ /// # extern crate rental;
+ /// # use rental::common::RentMutex;
+ /// # fn main() {
+ /// use std::sync;
+ ///
+ /// let mut r = RentMutex::new(Box::new(sync::Mutex::new(5)), |c| c.lock().unwrap());
+ /// *r = 12;
+ /// assert_eq!(12, RentMutex::rent(&r, |c| **c));
+ /// # }
+ /// ```
+ #[rental(debug, clone, deref_mut_suffix, covariant, map_suffix = "T")]
+ pub struct RentMutex<H: 'static + StableDeref + DerefMut, T: 'static> {
+ head: H,
+ suffix: sync::MutexGuard<'head, T>,
+ }
+
+ /// Stores an `RwLock` and an `RwLockReadGuard` in the same struct.
+ ///
+ /// ```rust
+ /// # extern crate rental;
+ /// # use rental::common::RentRwLock;
+ /// # fn main() {
+ /// use std::sync;
+ ///
+ /// let r = RentRwLock::new(Box::new(sync::RwLock::new(5)), |c| c.read().unwrap());
+ /// assert_eq!(*r, RentRwLock::rent(&r, |c| **c));
+ /// # }
+ /// ```
+ #[rental(debug, clone, deref_suffix, covariant, map_suffix = "T")]
+ pub struct RentRwLock<H: 'static + StableDeref, T: 'static> {
+ head: H,
+ suffix: sync::RwLockReadGuard<'head, T>,
+ }
+
+ /// Stores an `RwLock` and an `RwLockWriteGuard` in the same struct.
+ ///
+ /// ```rust
+ /// # extern crate rental;
+ /// # use rental::common::RentRwLockMut;
+ /// # fn main() {
+ /// use std::sync;
+ ///
+ /// let mut r = RentRwLockMut::new(Box::new(sync::RwLock::new(5)), |c| c.write().unwrap());
+ /// *r = 12;
+ /// assert_eq!(12, RentRwLockMut::rent(&r, |c| **c));
+ /// # }
+ /// ```
+ #[rental(debug, clone, deref_mut_suffix, covariant, map_suffix = "T")]
+ pub struct RentRwLockMut<H: 'static + StableDeref, T: 'static> {
+ head: H,
+ suffix: sync::RwLockWriteGuard<'head, T>,
+ }
+ }
+}
+
+
diff --git a/third_party/rust/rental/tests/clone.rs b/third_party/rust/rental/tests/clone.rs
new file mode 100644
index 0000000000..043f84a895
--- /dev/null
+++ b/third_party/rust/rental/tests/clone.rs
@@ -0,0 +1,50 @@
+#[macro_use]
+extern crate rental;
+
+
+pub struct Foo {
+ i: i32,
+}
+
+pub struct Bar<'i> {
+ iref: &'i i32,
+ misc: i32,
+}
+
+impl <'i> Clone for Bar<'i> {
+ fn clone (&self) -> Self {
+ Bar{
+ iref: Clone::clone(&self.iref),
+ misc: Clone::clone(&self.misc),
+ }
+ }
+}
+
+
+rental! {
+ mod rentals {
+ use super::*;
+ use std::sync::Arc;
+
+ #[rental(clone)]
+ pub struct FooClone {
+ foo: Arc<Foo>,
+ fr: Bar<'foo>,
+ }
+ }
+}
+
+
+#[test]
+fn clone() {
+ use std::sync::Arc;
+
+ let foo = Foo { i: 5 };
+ let rf = rentals::FooClone::new(Arc::new(foo), |foo| Bar{ iref: &foo.i, misc: 12 });
+ assert_eq!(5, rf.rent(|f| *f.iref));
+
+ let rfc = rf.clone();
+ assert_eq!(5, rfc.rent(|f| *f.iref));
+}
+
+
diff --git a/third_party/rust/rental/tests/complex.rs b/third_party/rust/rental/tests/complex.rs
new file mode 100644
index 0000000000..187e976807
--- /dev/null
+++ b/third_party/rust/rental/tests/complex.rs
@@ -0,0 +1,115 @@
+#[macro_use]
+extern crate rental;
+
+
+pub struct Foo {
+ i: i32,
+}
+
+pub struct Bar<'a> {
+ foo: &'a Foo,
+}
+
+pub struct Baz<'a: 'b, 'b> {
+ bar: &'b Bar<'a>
+}
+
+pub struct Qux<'a: 'b, 'b: 'c, 'c> {
+ baz: &'c Baz<'a, 'b>
+}
+
+pub struct Xyzzy<'a: 'b, 'b: 'c, 'c: 'd, 'd> {
+ qux: &'d Qux<'a, 'b, 'c>
+}
+
+
+impl Foo {
+ pub fn borrow<'a>(&'a self) -> Bar<'a> { Bar { foo: self } }
+ pub fn try_borrow<'a>(&'a self) -> Result<Bar<'a>, ()> { Ok(Bar { foo: self }) }
+ pub fn fail_borrow<'a>(&'a self) -> Result<Bar<'a>, ()> { Err(()) }
+}
+
+impl<'a> Bar<'a> {
+ pub fn borrow<'b>(&'b self) -> Baz<'a, 'b> { Baz { bar: self } }
+ pub fn try_borrow<'b>(&'b self) -> Result<Baz<'a, 'b>, ()> { Ok(Baz { bar: self }) }
+ pub fn fail_borrow<'b>(&'b self) -> Result<Baz<'a, 'b>, ()> { Err(()) }
+}
+
+impl<'a: 'b, 'b> Baz<'a, 'b> {
+ pub fn borrow<'c>(&'c self) -> Qux<'a, 'b, 'c> { Qux { baz: self } }
+ pub fn try_borrow<'c>(&'c self) -> Result<Qux<'a, 'b, 'c>, ()> { Ok(Qux { baz: self }) }
+ pub fn fail_borrow<'c>(&'c self) -> Result<Qux<'a, 'b, 'c>, ()> { Err(()) }
+}
+
+impl<'a: 'b, 'b: 'c, 'c> Qux<'a, 'b, 'c> {
+ pub fn borrow<'d>(&'d self) -> Xyzzy<'a, 'b, 'c, 'd> { Xyzzy { qux: self } }
+ pub fn try_borrow<'d>(&'d self) -> Result<Xyzzy<'a, 'b, 'c, 'd>, ()> { Ok(Xyzzy { qux: self }) }
+ pub fn fail_borrow<'d>(&'d self) -> Result<Xyzzy<'a, 'b, 'c, 'd>, ()> { Err(()) }
+}
+
+
+rental! {
+ mod rentals {
+ use super::*;
+
+ #[rental]
+ pub struct ComplexRent {
+ foo: Box<Foo>,
+ bar: Box<Bar<'foo>>,
+ baz: Box<Baz<'foo, 'bar>>,
+ qux: Box<Qux<'foo, 'bar, 'baz>>,
+ xyzzy: Xyzzy<'foo, 'bar, 'baz, 'qux>,
+ }
+ }
+}
+
+
+#[test]
+fn new() {
+ let foo = Foo { i: 5 };
+ let _ = rentals::ComplexRent::new(
+ Box::new(foo),
+ |foo| Box::new(foo.borrow()),
+ |bar, _| Box::new(bar.borrow()),
+ |baz, _, _| Box::new(baz.borrow()),
+ |qux, _, _, _| qux.borrow()
+ );
+
+ let foo = Foo { i: 5 };
+ let cr = rentals::ComplexRent::try_new(
+ Box::new(foo),
+ |foo| foo.try_borrow().map(|bar| Box::new(bar)),
+ |bar, _| bar.try_borrow().map(|baz| Box::new(baz)),
+ |baz, _, _| baz.try_borrow().map(|qux| Box::new(qux)),
+ |qux, _, _, _| qux.try_borrow()
+ );
+ assert!(cr.is_ok());
+
+ let foo = Foo { i: 5 };
+ let cr = rentals::ComplexRent::try_new(
+ Box::new(foo),
+ |foo| foo.try_borrow().map(|bar| Box::new(bar)),
+ |bar, _| bar.try_borrow().map(|baz| Box::new(baz)),
+ |baz, _, _| baz.try_borrow().map(|qux| Box::new(qux)),
+ |qux, _, _, _| qux.fail_borrow()
+ );
+ assert!(cr.is_err());
+}
+
+
+#[test]
+fn read() {
+ let foo = Foo { i: 5 };
+ let cr = rentals::ComplexRent::new(
+ Box::new(foo),
+ |foo| Box::new(foo.borrow()),
+ |bar, _| Box::new(bar.borrow()),
+ |baz, _, _| Box::new(baz.borrow()),
+ |qux, _, _, _| qux.borrow()
+ );
+ let i = cr.rent(|xyzzy| xyzzy.qux.baz.bar.foo.i);
+ assert_eq!(i, 5);
+
+ let iref = cr.ref_rent(|xyzzy| &xyzzy.qux.baz.bar.foo.i);
+ assert_eq!(*iref, 5);
+}
diff --git a/third_party/rust/rental/tests/complex_mut.rs b/third_party/rust/rental/tests/complex_mut.rs
new file mode 100644
index 0000000000..3ea44440ab
--- /dev/null
+++ b/third_party/rust/rental/tests/complex_mut.rs
@@ -0,0 +1,136 @@
+#[macro_use]
+extern crate rental;
+
+
+pub struct Foo {
+ i: i32,
+}
+
+pub struct Bar<'a> {
+ foo: &'a mut Foo,
+}
+
+pub struct Baz<'a: 'b, 'b> {
+ bar: &'b mut Bar<'a>
+}
+
+pub struct Qux<'a: 'b, 'b: 'c, 'c> {
+ baz: &'c mut Baz<'a, 'b>
+}
+
+pub struct Xyzzy<'a: 'b, 'b: 'c, 'c: 'd, 'd> {
+ qux: &'d mut Qux<'a, 'b, 'c>
+}
+
+
+impl Foo {
+ pub fn borrow_mut<'a>(&'a mut self) -> Bar<'a> { Bar { foo: self } }
+ pub fn try_borrow_mut<'a>(&'a mut self) -> Result<Bar<'a>, ()> { Ok(Bar { foo: self }) }
+ pub fn fail_borrow_mut<'a>(&'a mut self) -> Result<Bar<'a>, ()> { Err(()) }
+}
+
+impl<'a> Bar<'a> {
+ pub fn borrow_mut<'b>(&'b mut self) -> Baz<'a, 'b> { Baz { bar: self } }
+ pub fn try_borrow_mut<'b>(&'b mut self) -> Result<Baz<'a, 'b>, ()> { Ok(Baz { bar: self }) }
+ pub fn fail_borrow_mut<'b>(&'b mut self) -> Result<Baz<'a, 'b>, ()> { Err(()) }
+}
+
+impl<'a: 'b, 'b> Baz<'a, 'b> {
+ pub fn borrow_mut<'c>(&'c mut self) -> Qux<'a, 'b, 'c> { Qux { baz: self } }
+ pub fn try_borrow_mut<'c>(&'c mut self) -> Result<Qux<'a, 'b, 'c>, ()> { Ok(Qux { baz: self }) }
+ pub fn fail_borrow_mut<'c>(&'c mut self) -> Result<Qux<'a, 'b, 'c>, ()> { Err(()) }
+}
+
+impl<'a: 'b, 'b: 'c, 'c> Qux<'a, 'b, 'c> {
+ pub fn borrow_mut<'d>(&'d mut self) -> Xyzzy<'a, 'b, 'c, 'd> { Xyzzy { qux: self } }
+ pub fn try_borrow_mut<'d>(&'d mut self) -> Result<Xyzzy<'a, 'b, 'c, 'd>, ()> { Ok(Xyzzy { qux: self }) }
+ pub fn fail_borrow_mut<'d>(&'d mut self) -> Result<Xyzzy<'a, 'b, 'c, 'd>, ()> { Err(()) }
+}
+
+
+rental! {
+ mod rentals {
+ use super::*;
+
+ #[rental_mut]
+ pub struct ComplexRent {
+ foo: Box<Foo>,
+ bar: Box<Bar<'foo>>,
+ baz: Box<Baz<'foo, 'bar>>,
+ qux: Box<Qux<'foo, 'bar, 'baz>>,
+ xyzzy: Xyzzy<'foo, 'bar, 'baz, 'qux>,
+ }
+ }
+}
+
+
+#[test]
+fn new() {
+ let foo = Foo { i: 5 };
+ let _ = rentals::ComplexRent::new(
+ Box::new(foo),
+ |foo| Box::new(foo.borrow_mut()),
+ |bar| Box::new(bar.borrow_mut()),
+ |baz| Box::new(baz.borrow_mut()),
+ |qux| qux.borrow_mut()
+ );
+
+ let foo = Foo { i: 5 };
+ let cm = rentals::ComplexRent::try_new(
+ Box::new(foo),
+ |foo| foo.try_borrow_mut().map(|bar| Box::new(bar)),
+ |bar| bar.try_borrow_mut().map(|baz| Box::new(baz)),
+ |baz| baz.try_borrow_mut().map(|qux| Box::new(qux)),
+ |qux| qux.try_borrow_mut()
+ );
+ assert!(cm.is_ok());
+
+ let foo = Foo { i: 5 };
+ let cm = rentals::ComplexRent::try_new(
+ Box::new(foo),
+ |foo| foo.try_borrow_mut().map(|bar| Box::new(bar)),
+ |bar| bar.try_borrow_mut().map(|baz| Box::new(baz)),
+ |baz| baz.try_borrow_mut().map(|qux| Box::new(qux)),
+ |qux| qux.fail_borrow_mut()
+ );
+ assert!(cm.is_err());
+}
+
+
+#[test]
+fn read() {
+ let foo = Foo { i: 5 };
+ let cm = rentals::ComplexRent::new(
+ Box::new(foo),
+ |foo| Box::new(foo.borrow_mut()),
+ |bar| Box::new(bar.borrow_mut()),
+ |baz| Box::new(baz.borrow_mut()),
+ |qux| qux.borrow_mut()
+ );
+ let i = cm.rent(|xyzzy| xyzzy.qux.baz.bar.foo.i);
+ assert_eq!(i, 5);
+
+ let iref = cm.ref_rent(|xyzzy| &xyzzy.qux.baz.bar.foo.i);
+ assert_eq!(*iref, 5);
+}
+
+
+#[test]
+fn write() {
+ let foo = Foo { i: 5 };
+ let mut cm = rentals::ComplexRent::new(
+ Box::new(foo),
+ |foo| Box::new(foo.borrow_mut()),
+ |bar| Box::new(bar.borrow_mut()),
+ |baz| Box::new(baz.borrow_mut()),
+ |qux| qux.borrow_mut()
+ );
+
+ {
+ let iref: &mut i32 = cm.ref_rent_mut(|xyzzy| &mut xyzzy.qux.baz.bar.foo.i);
+ *iref = 12;
+ }
+
+ let i = cm.rent(|xyzzy| xyzzy.qux.baz.bar.foo.i);
+ assert_eq!(i, 12);
+}
diff --git a/third_party/rust/rental/tests/covariant.rs b/third_party/rust/rental/tests/covariant.rs
new file mode 100644
index 0000000000..545c2714ae
--- /dev/null
+++ b/third_party/rust/rental/tests/covariant.rs
@@ -0,0 +1,52 @@
+#[macro_use]
+extern crate rental;
+
+
+//use std::marker::PhantomData;
+
+
+pub struct Foo {
+ i: i32,
+}
+
+
+//pub struct Invariant<'a> {
+// iref: &'a i32,
+// inv: PhantomData<&'a mut &'a ()>,
+//}
+
+
+rental! {
+ mod rentals {
+ use super::*;
+
+ #[rental(covariant)]
+ pub struct SimpleRef {
+ foo: Box<Foo>,
+ iref: &'foo i32,
+ }
+
+ #[rental_mut(covariant)]
+ pub struct SimpleMut {
+ foo: Box<Foo>,
+ iref: &'foo mut i32,
+ }
+
+// #[rental(covariant)]
+// pub struct ShouldBreak {
+// foo: Box<Foo>,
+// inv: Invariant<'foo>,
+// }
+ }
+}
+
+
+#[test]
+fn borrow() {
+ let foo = Foo { i: 5 };
+ let fr = rentals::SimpleRef::new(Box::new(foo), |foo| &foo.i);
+ let b = fr.all();
+ assert_eq!(**b.iref, 5);
+}
+
+
diff --git a/third_party/rust/rental/tests/debug.rs b/third_party/rust/rental/tests/debug.rs
new file mode 100644
index 0000000000..59cf183b9b
--- /dev/null
+++ b/third_party/rust/rental/tests/debug.rs
@@ -0,0 +1,39 @@
+#[macro_use]
+extern crate rental;
+
+
+#[derive(Debug)]
+pub struct Foo {
+ i: i32,
+}
+
+
+rental! {
+ mod rentals {
+ use super::*;
+
+ #[rental(debug, deref_suffix)]
+ pub struct SimpleRef {
+ foo: Box<Foo>,
+ iref: &'foo i32,
+ }
+
+ #[rental_mut(debug, deref_suffix)]
+ pub struct SimpleMut {
+ foo: Box<Foo>,
+ iref: &'foo mut i32,
+ }
+ }
+}
+
+
+#[test]
+fn print() {
+ let foo = Foo { i: 5 };
+ let sr = rentals::SimpleRef::new(Box::new(foo), |foo| &foo.i);
+ println!("{:?}", sr);
+
+ let foo = Foo { i: 5 };
+ let sm = rentals::SimpleMut::new(Box::new(foo), |foo| &mut foo.i);
+ println!("{:?}", sm);
+}
diff --git a/third_party/rust/rental/tests/drop_order.rs b/third_party/rust/rental/tests/drop_order.rs
new file mode 100644
index 0000000000..642438b8d2
--- /dev/null
+++ b/third_party/rust/rental/tests/drop_order.rs
@@ -0,0 +1,129 @@
+#![allow(dead_code)]
+
+#[macro_use]
+extern crate rental;
+
+use std::cell::RefCell;
+use std::rc::Rc;
+
+
+pub struct Foo {
+ i: i32,
+ d: Rc<RefCell<String>>,
+}
+
+pub struct Bar<'a> {
+ foo: &'a Foo,
+ d: Rc<RefCell<String>>,
+}
+
+pub struct Baz<'a: 'b, 'b> {
+ bar: &'b Bar<'a>,
+ d: Rc<RefCell<String>>,
+}
+
+pub struct Qux<'a: 'b, 'b: 'c, 'c> {
+ baz: &'c Baz<'a, 'b>,
+ d: Rc<RefCell<String>>,
+}
+
+pub struct Xyzzy<'a: 'b, 'b: 'c, 'c: 'd, 'd> {
+ qux: &'d Qux<'a, 'b, 'c>,
+ d: Rc<RefCell<String>>,
+}
+
+
+impl Foo {
+ pub fn borrow<'a>(&'a self) -> Bar<'a> { Bar { foo: self, d: self.d.clone() } }
+}
+
+impl Drop for Foo {
+ fn drop(&mut self) {
+ self.d.borrow_mut().push_str("Foo");
+ }
+}
+
+impl<'a> Bar<'a> {
+ pub fn borrow<'b>(&'b self) -> Baz<'a, 'b> { Baz { bar: self, d: self.d.clone() } }
+}
+
+impl<'a> Drop for Bar<'a> {
+ fn drop(&mut self) {
+ self.d.borrow_mut().push_str("Bar");
+ }
+}
+
+impl<'a: 'b, 'b> Baz<'a, 'b> {
+ pub fn borrow<'c>(&'c self) -> Qux<'a, 'b, 'c> { Qux { baz: self, d: self.d.clone() } }
+}
+
+impl<'a: 'b, 'b> Drop for Baz<'a, 'b> {
+ fn drop(&mut self) {
+ self.d.borrow_mut().push_str("Baz");
+ }
+}
+
+impl<'a: 'b, 'b: 'c, 'c> Qux<'a, 'b, 'c> {
+ pub fn borrow<'d>(&'d self) -> Xyzzy<'a, 'b, 'c, 'd> { Xyzzy { qux: self, d: self.d.clone() } }
+}
+
+impl<'a: 'b, 'b: 'c, 'c> Drop for Qux<'a, 'b, 'c> {
+ fn drop(&mut self) {
+ self.d.borrow_mut().push_str("Qux");
+ }
+}
+
+impl<'a: 'b, 'b: 'c, 'c: 'd, 'd> Drop for Xyzzy<'a, 'b, 'c, 'd> {
+ fn drop(&mut self) {
+ self.d.borrow_mut().push_str("Xyzzy");
+ }
+}
+
+
+rental! {
+ pub mod rentals {
+ use super::*;
+
+ #[rental]
+ pub struct DropTestRent {
+ foo: Box<Foo>,
+ bar: Box<Bar<'foo>>,
+ baz: Box<Baz<'foo, 'bar>>,
+ qux: Box<Qux<'foo, 'bar, 'baz>>,
+ xyzzy: Xyzzy<'foo, 'bar, 'baz, 'qux>,
+ }
+ }
+}
+
+
+#[test]
+fn drop_order() {
+ let d = Rc::new(RefCell::new(String::new()));
+ {
+ let foo = Foo { i: 5, d: d.clone() };
+ let _ = rentals::DropTestRent::new(
+ Box::new(foo),
+ |foo| Box::new(foo.borrow()),
+ |bar, _| Box::new(bar.borrow()),
+ |baz, _, _| Box::new(baz.borrow()),
+ |qux, _, _, _| qux.borrow()
+ );
+ }
+ assert_eq!(*d.borrow(), "XyzzyQuxBazBarFoo");
+
+ let d = Rc::new(RefCell::new(String::new()));
+ {
+ let foo = Foo { i: 5, d: d.clone() };
+ let r = rentals::DropTestRent::new(
+ Box::new(foo),
+ |foo| Box::new(foo.borrow()),
+ |bar, _| Box::new(bar.borrow()),
+ |baz, _, _| Box::new(baz.borrow()),
+ |qux, _, _, _| qux.borrow()
+ );
+
+ let _head = r.into_head();
+ }
+ assert_eq!(*d.borrow(), "XyzzyQuxBazBarFoo");
+}
+
diff --git a/third_party/rust/rental/tests/generic.rs b/third_party/rust/rental/tests/generic.rs
new file mode 100644
index 0000000000..9043025d62
--- /dev/null
+++ b/third_party/rust/rental/tests/generic.rs
@@ -0,0 +1,53 @@
+#[macro_use]
+extern crate rental;
+
+
+pub struct Foo<T: 'static> {
+ t: T,
+}
+
+impl<T: 'static> Foo<T> {
+ fn try_borrow(&self) -> Result<&T, ()> { Ok(&self.t) }
+ fn fail_borrow(&self) -> Result<&T, ()> { Err(()) }
+}
+
+
+rental! {
+ mod rentals {
+ type FooAlias<T> = super::Foo<T>;
+
+ #[rental]
+ pub struct SimpleRef<T: 'static> {
+ foo: Box<FooAlias<T>>,
+ tref: &'foo T,
+ }
+ }
+}
+
+
+#[test]
+fn new() {
+ let foo = Foo { t: 5 };
+ let _ = rentals::SimpleRef::new(Box::new(foo), |foo| &foo.t);
+
+ let foo = Foo { t: 5 };
+ let sr = rentals::SimpleRef::try_new(Box::new(foo), |foo| foo.try_borrow());
+ assert!(sr.is_ok());
+
+ let foo = Foo { t: 5 };
+ let sr = rentals::SimpleRef::try_new(Box::new(foo), |foo| foo.fail_borrow());
+ assert!(sr.is_err());
+}
+
+
+#[test]
+fn read() {
+ let foo = Foo { t: 5 };
+
+ let sr = rentals::SimpleRef::new(Box::new(foo), |foo| &foo.t);
+ let t: i32 = sr.rent(|tref| **tref);
+ assert_eq!(t, 5);
+
+ let tref: &i32 = sr.ref_rent(|tref| *tref);
+ assert_eq!(*tref, 5);
+}
diff --git a/third_party/rust/rental/tests/lt_params.rs b/third_party/rust/rental/tests/lt_params.rs
new file mode 100644
index 0000000000..3ce6d3eee7
--- /dev/null
+++ b/third_party/rust/rental/tests/lt_params.rs
@@ -0,0 +1,65 @@
+#[macro_use]
+extern crate rental;
+
+
+pub struct Foo<'a> {
+ i: &'a i32,
+}
+
+impl<'a> Foo<'a> {
+ fn borrow(&self) -> &i32 { self.i }
+ fn try_borrow(&self) -> Result<&i32, ()> { Ok(self.i) }
+ fn fail_borrow(&self) -> Result<&i32, ()> { Err(()) }
+}
+
+
+rental! {
+ mod rentals {
+ use super::*;
+
+ #[rental]
+ pub struct LtParam<'a> {
+ foo: Box<Foo<'a>>,
+ iref: &'foo i32,
+ }
+ }
+}
+
+
+#[test]
+fn new() {
+ let i = 5;
+
+ let foo = Foo { i: &i };
+ let _ = rentals::LtParam::new(Box::new(foo), |foo| foo.borrow());
+
+ let foo = Foo { i: &i };
+ let sr = rentals::LtParam::try_new(Box::new(foo), |foo| foo.try_borrow());
+ assert!(sr.is_ok());
+
+ let foo = Foo { i: &i };
+ let sr = rentals::LtParam::try_new(Box::new(foo), |foo| foo.fail_borrow());
+ assert!(sr.is_err());
+}
+
+
+#[test]
+fn read() {
+ let i = 5;
+
+ let foo = Foo { i: &i };
+
+ let mut sr = rentals::LtParam::new(Box::new(foo), |foo| foo.borrow());
+
+ {
+ let i: i32 = sr.rent(|iref| **iref);
+ assert_eq!(i, 5);
+ }
+
+ {
+ let iref: &i32 = sr.ref_rent(|iref| *iref);
+ assert_eq!(*iref, 5);
+ }
+
+ assert_eq!(sr.rent_all_mut(|borrows| *borrows.foo.i), 5);
+}
diff --git a/third_party/rust/rental/tests/map.rs b/third_party/rust/rental/tests/map.rs
new file mode 100644
index 0000000000..3ef3b94810
--- /dev/null
+++ b/third_party/rust/rental/tests/map.rs
@@ -0,0 +1,42 @@
+#[macro_use]
+extern crate rental;
+
+
+pub struct Foo {
+ i: i32,
+}
+
+
+rental! {
+ mod rentals {
+ use super::*;
+
+ #[rental(map_suffix = "T")]
+ pub struct SimpleRef<T: 'static> {
+ foo: Box<Foo>,
+ fr: &'foo T,
+ }
+
+ #[rental_mut(map_suffix = "T")]
+ pub struct SimpleMut<T: 'static> {
+ foo: Box<Foo>,
+ fr: &'foo mut T,
+ }
+ }
+}
+
+
+#[test]
+fn map() {
+ let foo = Foo { i: 5 };
+ let sr = rentals::SimpleRef::new(Box::new(foo), |foo| foo);
+ let sr = sr.map(|fr| &fr.i);
+ assert_eq!(sr.rent(|ir| **ir), 5);
+
+ let foo = Foo { i: 12 };
+ let sm = rentals::SimpleMut::new(Box::new(foo), |foo| foo);
+ let sm = sm.map(|fr| &mut fr.i);
+ assert_eq!(sm.rent(|ir| **ir), 12);
+}
+
+
diff --git a/third_party/rust/rental/tests/simple_mut.rs b/third_party/rust/rental/tests/simple_mut.rs
new file mode 100644
index 0000000000..c7af358998
--- /dev/null
+++ b/third_party/rust/rental/tests/simple_mut.rs
@@ -0,0 +1,67 @@
+#[macro_use]
+extern crate rental;
+
+
+pub struct Foo {
+ i: i32,
+}
+
+impl Foo {
+ fn try_borrow_mut(&mut self) -> Result<&mut i32, ()> { Ok(&mut self.i) }
+ fn fail_borrow_mut(&mut self) -> Result<&mut i32, ()> { Err(()) }
+}
+
+
+rental! {
+ mod rentals {
+ use super::*;
+
+ #[rental_mut]
+ pub struct SimpleMut {
+ foo: Box<Foo>,
+ iref: &'foo mut i32,
+ }
+ }
+}
+
+
+#[test]
+fn new() {
+ let foo = Foo { i: 5 };
+ let _ = rentals::SimpleMut::new(Box::new(foo), |foo| &mut foo.i);
+
+ let foo = Foo { i: 5 };
+ let sm = rentals::SimpleMut::try_new(Box::new(foo), |foo| foo.try_borrow_mut());
+ assert!(sm.is_ok());
+
+ let foo = Foo { i: 5 };
+ let sm = rentals::SimpleMut::try_new(Box::new(foo), |foo| foo.fail_borrow_mut());
+ assert!(sm.is_err());
+}
+
+
+#[test]
+fn read() {
+ let foo = Foo { i: 5 };
+
+ let sm = rentals::SimpleMut::new(Box::new(foo), |foo| &mut foo.i);
+ let i: i32 = sm.rent(|iref| **iref);
+ assert_eq!(i, 5);
+
+ let iref: &i32 = sm.ref_rent(|iref| *iref);
+ assert_eq!(*iref, 5);
+}
+
+
+#[test]
+fn write() {
+ let foo = Foo { i: 5 };
+
+ let mut sm = rentals::SimpleMut::new(Box::new(foo), |foo| &mut foo.i);
+
+ {
+ let iref: &mut i32 = sm.ref_rent_mut(|iref| *iref);
+ *iref = 12;
+ assert_eq!(*iref, 12);
+ }
+}
diff --git a/third_party/rust/rental/tests/simple_ref.rs b/third_party/rust/rental/tests/simple_ref.rs
new file mode 100644
index 0000000000..2cb7765578
--- /dev/null
+++ b/third_party/rust/rental/tests/simple_ref.rs
@@ -0,0 +1,103 @@
+#[macro_use]
+extern crate rental;
+
+
+pub struct Foo {
+ i: i32,
+}
+
+impl Foo {
+ fn try_borrow(&self) -> Result<&i32, ()> { Ok(&self.i) }
+ fn fail_borrow(&self) -> Result<&i32, ()> { Err(()) }
+}
+
+pub struct FooRef<'i> {
+ iref: &'i i32,
+ misc: i32,
+}
+
+
+impl<'i> ::std::ops::Deref for FooRef<'i> {
+ type Target = i32;
+
+ fn deref(&self) -> &i32 { self.iref }
+}
+
+
+rental! {
+ mod rentals {
+ use super::*;
+
+ #[rental]
+ pub struct SimpleRef {
+ foo: Box<Foo>,
+ fr: FooRef<'foo>,
+ }
+ }
+}
+
+
+#[test]
+fn new() {
+ let foo = Foo { i: 5 };
+ let _ = rentals::SimpleRef::new(Box::new(foo), |foo| FooRef{ iref: &foo.i, misc: 12 });
+
+ let foo = Foo { i: 5 };
+ let sr: rental::RentalResult<rentals::SimpleRef, (), _> = rentals::SimpleRef::try_new(Box::new(foo), |foo| Ok(FooRef{ iref: foo.try_borrow()?, misc: 12 }));
+ assert!(sr.is_ok());
+
+ let foo = Foo { i: 5 };
+ let sr: rental::RentalResult<rentals::SimpleRef, (), _> = rentals::SimpleRef::try_new(Box::new(foo), |foo| Ok(FooRef{ iref: foo.fail_borrow()?, misc: 12 }));
+ assert!(sr.is_err());
+}
+
+
+#[test]
+fn read() {
+ let foo = Foo { i: 5 };
+
+ let mut sr = rentals::SimpleRef::new(Box::new(foo), |foo| FooRef{ iref: &foo.i, misc: 12 });
+
+ {
+ let i: i32 = sr.rent(|iref| **iref);
+ assert_eq!(i, 5);
+ }
+
+ {
+ let iref: &i32 = sr.ref_rent(|fr| fr.iref);
+ assert_eq!(*iref, 5);
+ let iref: Option<&i32> = sr.maybe_ref_rent(|fr| Some(fr.iref));
+ assert_eq!(iref, Some(&5));
+ let iref: Result<&i32, ()> = sr.try_ref_rent(|fr| Ok(fr.iref));
+ assert_eq!(iref, Ok(&5));
+ }
+
+ {
+ assert_eq!(sr.head().i, 5);
+ assert_eq!(sr.rent_all(|borrows| borrows.foo.i), 5);
+ assert_eq!(sr.rent_all_mut(|borrows| borrows.foo.i), 5);
+ }
+
+ {
+ let iref: Option<&i32> = sr.maybe_ref_rent_all(|borrows| Some(borrows.fr.iref));
+ assert_eq!(iref, Some(&5));
+ let iref: Result<&i32, ()> = sr.try_ref_rent_all(|borrows| Ok(borrows.fr.iref));
+ assert_eq!(iref, Ok(&5));
+ }
+
+ {
+ let iref: &mut i32 = sr.ref_rent_all_mut(|borrows| &mut borrows.fr.misc);
+ *iref = 57;
+ assert_eq!(*iref, 57);
+ }
+
+ {
+ let iref: Option<&mut i32> = sr.maybe_ref_rent_all_mut(|borrows| Some(&mut borrows.fr.misc));
+ assert_eq!(iref, Some(&mut 57));
+ }
+
+ {
+ let iref: Result<&mut i32, ()> = sr.try_ref_rent_all_mut(|borrows| Ok(&mut borrows.fr.misc));
+ assert_eq!(iref, Ok(&mut 57));
+ }
+}
diff --git a/third_party/rust/rental/tests/string.rs b/third_party/rust/rental/tests/string.rs
new file mode 100644
index 0000000000..9f6c7ea9da
--- /dev/null
+++ b/third_party/rust/rental/tests/string.rs
@@ -0,0 +1,30 @@
+#[macro_use]
+extern crate rental;
+
+
+rental! {
+ pub mod rent_string {
+ #[rental(deref_suffix)]
+ pub struct OwnedStr {
+ buffer: String,
+ slice: &'buffer str,
+ slice_2: &'slice str,
+ }
+ }
+}
+
+
+#[test]
+fn new() {
+ let buf = "Hello, World!".to_string();
+ let _ = rent_string::OwnedStr::new(buf, |slice| slice, |slice, _| slice);
+}
+
+
+#[test]
+fn read() {
+ let buf = "Hello, World!".to_string();
+ let rbuf = rent_string::OwnedStr::new(buf, |slice| slice, |slice, _| slice);
+
+ assert_eq!(&*rbuf, "Hello, World!");
+}
diff --git a/third_party/rust/rental/tests/subrental.rs b/third_party/rust/rental/tests/subrental.rs
new file mode 100644
index 0000000000..f44a072aee
--- /dev/null
+++ b/third_party/rust/rental/tests/subrental.rs
@@ -0,0 +1,88 @@
+#[macro_use]
+extern crate rental;
+
+
+pub struct Foo {
+ pub i: i32,
+}
+
+pub struct Bar<'a> {
+ pub foo: &'a Foo,
+}
+
+pub struct Qux<'a: 'b, 'b> {
+ pub bar: &'b Bar<'a>,
+}
+
+
+impl Foo {
+ pub fn borrow(&self) -> Bar { Bar { foo: self } }
+ pub fn try_borrow<'a>(&'a self) -> Result<Bar<'a>, ()> { Ok(Bar { foo: self }) }
+ pub fn fail_borrow<'a>(&'a self) -> Result<Bar<'a>, ()> { Err(()) }
+}
+
+impl<'a> Bar<'a> {
+ pub fn borrow<'b>(&'b self) -> Qux<'a, 'b> { Qux { bar: self } }
+ pub fn try_borrow<'b>(&'b self) -> Result<Qux<'a, 'b>, ()> { Ok(Qux { bar: self }) }
+ pub fn fail_borrow<'b>(&'b self) -> Result<Qux<'a, 'b>, ()> { Err(()) }
+}
+
+
+rental! {
+ pub mod rentals {
+ use super::*;
+
+ #[rental]
+ pub struct Sub {
+ foo: Box<Foo>,
+ bar: Bar<'foo>,
+ }
+
+ #[rental]
+ pub struct Rent {
+ #[subrental = 2]
+ sub: Box<Sub>,
+ qux: Qux<'sub_0, 'sub_1>,
+ }
+
+ #[rental]
+ pub struct BorrowSub<'f> {
+ foo: &'f Foo,
+ bar: Bar<'foo>,
+ }
+
+ #[rental]
+ pub struct TailRent {
+ foo: Box<Foo>,
+ #[subrental = 2]
+ sub: Box<BorrowSub<'foo>>,
+ iref: &'sub_1 i32,
+ }
+ }
+}
+
+
+#[test]
+fn new() {
+ let foo = Foo { i: 5 };
+ let sub = rentals::Sub::new(Box::new(foo), |foo| foo.borrow());
+ let _ = rentals::Rent::new(Box::new(sub), |sub| sub.bar.borrow());
+
+ let foo = Foo { i: 5 };
+ let sub = rentals::Sub::new(Box::new(foo), |foo| foo.borrow());
+ let rent = rentals::Rent::try_new(Box::new(sub), |sub| sub.bar.try_borrow());
+ assert!(rent.is_ok());
+
+ let foo = Foo { i: 5 };
+ let sub = rentals::Sub::new(Box::new(foo), |foo| foo.borrow());
+ let rent = rentals::Rent::try_new(Box::new(sub), |sub| sub.bar.fail_borrow());
+ assert!(rent.is_err());
+}
+
+
+#[test]
+fn read() {
+ let foo = Foo { i: 5 };
+ let sub = rentals::Sub::new(Box::new(foo), |foo| foo.borrow());
+ let _ = rentals::Rent::new(Box::new(sub), |sub| sub.bar.borrow());
+}
diff --git a/third_party/rust/rental/tests/target_ty_hack.rs b/third_party/rust/rental/tests/target_ty_hack.rs
new file mode 100644
index 0000000000..d98bd0d7b5
--- /dev/null
+++ b/third_party/rust/rental/tests/target_ty_hack.rs
@@ -0,0 +1,54 @@
+#[macro_use]
+extern crate rental;
+
+
+type MyVec<T> = Vec<T>;
+
+
+rental! {
+ pub mod rent_vec_slice {
+ use super::*;
+
+ #[rental]
+ pub struct OwnedSlice {
+ #[target_ty = "[u8]"]
+ buffer: MyVec<u8>,
+ slice: &'buffer [u8],
+ }
+
+ #[rental_mut]
+ pub struct OwnedMutSlice {
+ #[target_ty = "[u8]"]
+ buffer: MyVec<u8>,
+ slice: &'buffer mut [u8],
+ }
+ }
+}
+
+
+#[test]
+fn new() {
+ let vec = vec![1, 2, 3];
+ let _ = rent_vec_slice::OwnedSlice::new(vec, |slice| slice);
+}
+
+
+#[test]
+fn read() {
+ let vec = vec![1, 2, 3];
+ let rvec = rent_vec_slice::OwnedSlice::new(vec, |slice| slice);
+
+ assert_eq!(rvec.rent(|slice| slice[1]), 2);
+ assert_eq!(rvec.rent(|slice| slice[1]), rvec.rent(|slice| slice[1]));
+}
+
+
+#[test]
+fn write() {
+ let vec = vec![1, 2, 3];
+ let mut rvec = rent_vec_slice::OwnedMutSlice::new(vec, |slice| slice);
+
+ rvec.rent_mut(|slice| slice[1] = 4);
+ assert_eq!(rvec.rent(|slice| slice[1]), 4);
+ assert_eq!(rvec.rent(|slice| slice[1]), rvec.rent(|slice| slice[1]));
+}
diff --git a/third_party/rust/rental/tests/trait.rs b/third_party/rust/rental/tests/trait.rs
new file mode 100644
index 0000000000..180e328ce1
--- /dev/null
+++ b/third_party/rust/rental/tests/trait.rs
@@ -0,0 +1,33 @@
+#[macro_use]
+extern crate rental;
+
+
+pub trait MyTrait { }
+
+
+pub struct MyStruct { }
+
+
+impl MyTrait for MyStruct { }
+
+
+rental! {
+ pub mod rentals {
+ use ::MyTrait;
+
+ #[rental]
+ pub struct RentTrait {
+ my_trait: Box<MyTrait + 'static>,
+ my_suffix: &'my_trait (MyTrait + 'static),
+ }
+ }
+}
+
+
+#[test]
+fn new() {
+ let _tr = rentals::RentTrait::new(
+ Box::new(MyStruct{}),
+ |t| &*t,
+ );
+}
diff --git a/third_party/rust/rental/tests/unused.rs b/third_party/rust/rental/tests/unused.rs
new file mode 100644
index 0000000000..a8962a050c
--- /dev/null
+++ b/third_party/rust/rental/tests/unused.rs
@@ -0,0 +1,28 @@
+use std::rc::Rc;
+
+#[macro_use]
+extern crate rental;
+
+pub struct Sample {
+ field: i32,
+}
+
+rental! {
+ mod sample_rental {
+ use super::*;
+
+ #[rental]
+ pub struct SampleRental {
+ sample: Rc<Sample>,
+ sref: &'sample i32,
+ }
+ }
+}
+use self::sample_rental::SampleRental;
+
+#[test]
+fn unused() {
+ let sample = Rc::new(Sample { field: 42 });
+ let rental = SampleRental::new(sample, |sample_rc| &sample_rc.field);
+ rental.rent(|this| println!("{}", this));
+}
diff --git a/third_party/rust/rental/tests/vec_slice.rs b/third_party/rust/rental/tests/vec_slice.rs
new file mode 100644
index 0000000000..afc46edf7c
--- /dev/null
+++ b/third_party/rust/rental/tests/vec_slice.rs
@@ -0,0 +1,47 @@
+#[macro_use]
+extern crate rental;
+
+
+rental! {
+ pub mod rent_vec_slice {
+ #[rental]
+ pub struct OwnedSlice {
+ buffer: Vec<u8>,
+ slice: &'buffer [u8],
+ }
+
+ #[rental_mut]
+ pub struct OwnedMutSlice {
+ buffer: Vec<u8>,
+ slice: &'buffer mut [u8],
+ }
+ }
+}
+
+
+#[test]
+fn new() {
+ let vec = vec![1, 2, 3];
+ let _ = rent_vec_slice::OwnedSlice::new(vec, |slice| slice);
+}
+
+
+#[test]
+fn read() {
+ let vec = vec![1, 2, 3];
+ let rvec = rent_vec_slice::OwnedSlice::new(vec, |slice| slice);
+
+ assert_eq!(rvec.rent(|slice| slice[1]), 2);
+ assert_eq!(rvec.rent(|slice| slice[1]), rvec.rent(|slice| slice[1]));
+}
+
+
+#[test]
+fn write() {
+ let vec = vec![1, 2, 3];
+ let mut rvec = rent_vec_slice::OwnedMutSlice::new(vec, |slice| slice);
+
+ rvec.rent_mut(|slice| slice[1] = 4);
+ assert_eq!(rvec.rent(|slice| slice[1]), 4);
+ assert_eq!(rvec.rent(|slice| slice[1]), rvec.rent(|slice| slice[1]));
+}