Full Code of jpernst/rental for AI

master 61188eb97f5d cached
25 files
127.6 KB
38.3k tokens
141 symbols
1 requests
Download .txt
Repository: jpernst/rental
Branch: master
Commit: 61188eb97f5d
Files: 25
Total size: 127.6 KB

Directory structure:
gitextract_ze3z0387/

├── .gitignore
├── Cargo.toml
├── LICENSE-APACHE
├── LICENSE-MIT
├── README.md
├── rental-impl/
│   ├── Cargo.toml
│   └── src/
│       └── lib.rs
├── src/
│   └── lib.rs
└── tests/
    ├── clone.rs
    ├── complex.rs
    ├── complex_mut.rs
    ├── covariant.rs
    ├── debug.rs
    ├── drop_order.rs
    ├── generic.rs
    ├── lt_params.rs
    ├── map.rs
    ├── simple_mut.rs
    ├── simple_ref.rs
    ├── string.rs
    ├── subrental.rs
    ├── target_ty_hack.rs
    ├── trait.rs
    ├── unused.rs
    └── vec_slice.rs

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitignore
================================================
/target
/rental-impl/target
/.cargo
Cargo.lock

*.vim
*.sw[onp]
*~


================================================
FILE: Cargo.toml
================================================
[package]
name = "rental"
version = "0.5.6"
license = "MIT/Apache-2.0"
authors = ["Jameson Ernst <jameson@jpernst.com>"]
description = "A macro to generate safe self-referential structs, plus premade types for common use cases."
readme = "README.md"
keywords = ["lifetime", "ownership", "borrowing", "self", "reference"]
categories = ["rust-patterns", "no-std"]
repository = "https://github.com/jpernst/rental"
documentation = "https://docs.rs/rental"

[workspace]
members = ["rental-impl"]

[features]
default = ["std"]
std = ["stable_deref_trait/std"]

[dependencies]
rental-impl = { version = "=0.5.5", path = "rental-impl" }
stable_deref_trait = { version = "1.0.0", default-features = false }


================================================
FILE: LICENSE-APACHE
================================================
                              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.


================================================
FILE: LICENSE-MIT
================================================
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.


================================================
FILE: README.md
================================================
# WARNING: This crate is NO LONGER MAINTAINED OR SUPPORTED
I'm not going to yank the crate because it's still fit for its intended purpose, but as time goes on it will become increasingly out of step with Rust's evolution, so users are encouraged to explore other solutions. I will also not merge any pull requests, as the code is sufficiently complicated that I'm no longer confident in my ability to effectively review them. Rental can be considered "frozen" in its current state, and any further development will need to take place under a fork for whoever wishes to do so.

# 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.


================================================
FILE: rental-impl/Cargo.toml
================================================
[package]
name = "rental-impl"
version = "0.5.5"
license = "MIT/Apache-2.0"
authors = ["Jameson Ernst <jameson@jpernst.com>"]
description = "An implementation detail of rental. Should not be used directly."
repository = "https://github.com/jpernst/rental"
documentation = "https://docs.rs/rental"
homepage = "https://www.jpernst.com"

[lib]
proc-macro = true

[dependencies]
proc-macro2 = "1"
quote = "1"
syn = { version = "1", features = ["full", "fold", "visit", "extra-traits"] }


================================================
FILE: rental-impl/src/lib.rs
================================================
#![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
	}
}




================================================
FILE: src/lib.rs
================================================
//! A macro to generate safe self-referential 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>,
		}
	}
}




================================================
FILE: tests/clone.rs
================================================
#[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));
}




================================================
FILE: tests/complex.rs
================================================
#[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);
}


================================================
FILE: tests/complex_mut.rs
================================================
#[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);
}


================================================
FILE: tests/covariant.rs
================================================
#[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);
}




================================================
FILE: tests/debug.rs
================================================
#[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);
}


================================================
FILE: tests/drop_order.rs
================================================
#![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");
}



================================================
FILE: tests/generic.rs
================================================
#[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);
}


================================================
FILE: tests/lt_params.rs
================================================
#[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);
}


================================================
FILE: tests/map.rs
================================================
#[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);
}




================================================
FILE: tests/simple_mut.rs
================================================
#[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);
	}
}


================================================
FILE: tests/simple_ref.rs
================================================
#[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));
	}
}


================================================
FILE: tests/string.rs
================================================
#[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!");
}


================================================
FILE: tests/subrental.rs
================================================
#[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());
}


================================================
FILE: tests/target_ty_hack.rs
================================================
#[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]));
}


================================================
FILE: tests/trait.rs
================================================
#[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,
	);
}


================================================
FILE: tests/unused.rs
================================================
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));
}


================================================
FILE: tests/vec_slice.rs
================================================
#[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]));
}
Download .txt
gitextract_ze3z0387/

├── .gitignore
├── Cargo.toml
├── LICENSE-APACHE
├── LICENSE-MIT
├── README.md
├── rental-impl/
│   ├── Cargo.toml
│   └── src/
│       └── lib.rs
├── src/
│   └── lib.rs
└── tests/
    ├── clone.rs
    ├── complex.rs
    ├── complex_mut.rs
    ├── covariant.rs
    ├── debug.rs
    ├── drop_order.rs
    ├── generic.rs
    ├── lt_params.rs
    ├── map.rs
    ├── simple_mut.rs
    ├── simple_ref.rs
    ├── string.rs
    ├── subrental.rs
    ├── target_ty_hack.rs
    ├── trait.rs
    ├── unused.rs
    └── vec_slice.rs
Download .txt
SYMBOL INDEX (141 symbols across 19 files)

FILE: rental-impl/src/lib.rs
  function _extract_input (line 20) | fn _extract_input(derive_input: &str) -> &str {
  function __rental_traits (line 43) | pub fn __rental_traits(input: proc_macro::TokenStream) -> proc_macro::To...
  function __rental_structs_and_impls (line 56) | pub fn __rental_structs_and_impls(input: proc_macro::TokenStream) -> pro...
  function write_rental_traits (line 78) | fn write_rental_traits(tokens: &mut proc_macro2::TokenStream, max_arity:...
  function write_rental_struct_and_impls (line 101) | fn write_rental_struct_and_impls(tokens: &mut proc_macro2::TokenStream, ...
  function get_struct_attribs (line 881) | fn get_struct_attribs(struct_info: &syn::ItemStruct) -> RentalStructAttribs
  function prepare_fields (line 1026) | fn prepare_fields(struct_info: &syn::ItemStruct) -> (Vec<RentalField>, s...
  function make_borrow_quotes (line 1249) | fn make_borrow_quotes(self_arg: &proc_macro2::TokenStream, fields: &[Ren...
  function make_tail_closure_quotes (line 1421) | fn make_tail_closure_quotes(fields: &[RentalField], borrows: &[BorrowQuo...
  type RentalStructAttribs (line 1457) | struct RentalStructAttribs {
  type RentalField (line 1469) | struct RentalField {
  type Subrental (line 1481) | struct Subrental {
  type BorrowQuotes (line 1487) | struct BorrowQuotes {
  type ClosureQuotes (line 1499) | struct ClosureQuotes {
  type RentalLifetimeEraser (line 1507) | struct RentalLifetimeEraser<'a> {
  function fold_lifetime (line 1514) | fn fold_lifetime(&mut self, lifetime: syn::Lifetime) -> syn::Lifetime {
  type MapTyParamFinder (line 1530) | struct MapTyParamFinder<'p> {
  function visit_path (line 1537) | fn visit_path(&mut self, path: &'ast syn::Path) {
  type MapTyParamReplacer (line 1549) | struct MapTyParamReplacer<'p> {
  function fold_path (line 1555) | fn fold_path(&mut self, path: syn::Path) -> syn::Path {
  function fold_type_param (line 1582) | fn fold_type_param(&mut self, mut ty_param: syn::TypeParam) -> syn::Type...

FILE: src/lib.rs
  type IntoSuffix (line 69) | pub trait IntoSuffix {
    method into_suffix (line 78) | fn into_suffix(self) -> <Self as IntoSuffix>::Suffix;
  type RentalError (line 85) | pub struct RentalError<E, H> (pub E, pub H);
  type RentalResult (line 87) | pub type RentalResult<T, E, H> = Result<T, RentalError<E, H>>;
  function static_assert_stable_deref (line 121) | pub fn static_assert_stable_deref<T: StableDeref>() { }
  function static_assert_mut_stable_deref (line 123) | pub fn static_assert_mut_stable_deref<T: DerefMut + StableDeref>() { }

FILE: tests/clone.rs
  type Foo (line 5) | pub struct Foo {
  type Bar (line 9) | pub struct Bar<'i> {
  method clone (line 15) | fn clone (&self) -> Self {
  function clone (line 39) | fn clone() {

FILE: tests/complex.rs
  type Foo (line 5) | pub struct Foo {
    method borrow (line 27) | pub fn borrow<'a>(&'a self) -> Bar<'a> { Bar { foo: self } }
    method try_borrow (line 28) | pub fn try_borrow<'a>(&'a self) -> Result<Bar<'a>, ()> { Ok(Bar { foo:...
    method fail_borrow (line 29) | pub fn fail_borrow<'a>(&'a self) -> Result<Bar<'a>, ()> { Err(()) }
  type Bar (line 9) | pub struct Bar<'a> {
  type Baz (line 13) | pub struct Baz<'a: 'b, 'b> {
  type Qux (line 17) | pub struct Qux<'a: 'b, 'b: 'c, 'c> {
  type Xyzzy (line 21) | pub struct Xyzzy<'a: 'b, 'b: 'c, 'c: 'd, 'd> {
  function borrow (line 33) | pub fn borrow<'b>(&'b self) -> Baz<'a, 'b> { Baz { bar: self } }
  function try_borrow (line 34) | pub fn try_borrow<'b>(&'b self) -> Result<Baz<'a, 'b>, ()> { Ok(Baz { ba...
  function fail_borrow (line 35) | pub fn fail_borrow<'b>(&'b self) -> Result<Baz<'a, 'b>, ()> { Err(()) }
  function borrow (line 39) | pub fn borrow<'c>(&'c self) -> Qux<'a, 'b, 'c> { Qux { baz: self } }
  function try_borrow (line 40) | pub fn try_borrow<'c>(&'c self) -> Result<Qux<'a, 'b, 'c>, ()> { Ok(Qux ...
  function fail_borrow (line 41) | pub fn fail_borrow<'c>(&'c self) -> Result<Qux<'a, 'b, 'c>, ()> { Err(()) }
  function borrow (line 45) | pub fn borrow<'d>(&'d self) -> Xyzzy<'a, 'b, 'c, 'd> { Xyzzy { qux: self...
  function try_borrow (line 46) | pub fn try_borrow<'d>(&'d self) -> Result<Xyzzy<'a, 'b, 'c, 'd>, ()> { O...
  function fail_borrow (line 47) | pub fn fail_borrow<'d>(&'d self) -> Result<Xyzzy<'a, 'b, 'c, 'd>, ()> { ...
  function new (line 68) | fn new() {
  function read (line 101) | fn read() {

FILE: tests/complex_mut.rs
  type Foo (line 5) | pub struct Foo {
    method borrow_mut (line 27) | pub fn borrow_mut<'a>(&'a mut self) -> Bar<'a> { Bar { foo: self } }
    method try_borrow_mut (line 28) | pub fn try_borrow_mut<'a>(&'a mut self) -> Result<Bar<'a>, ()> { Ok(Ba...
    method fail_borrow_mut (line 29) | pub fn fail_borrow_mut<'a>(&'a mut self) -> Result<Bar<'a>, ()> { Err(...
  type Bar (line 9) | pub struct Bar<'a> {
  type Baz (line 13) | pub struct Baz<'a: 'b, 'b> {
  type Qux (line 17) | pub struct Qux<'a: 'b, 'b: 'c, 'c> {
  type Xyzzy (line 21) | pub struct Xyzzy<'a: 'b, 'b: 'c, 'c: 'd, 'd> {
  function borrow_mut (line 33) | pub fn borrow_mut<'b>(&'b mut self) -> Baz<'a, 'b> { Baz { bar: self } }
  function try_borrow_mut (line 34) | pub fn try_borrow_mut<'b>(&'b mut self) -> Result<Baz<'a, 'b>, ()> { Ok(...
  function fail_borrow_mut (line 35) | pub fn fail_borrow_mut<'b>(&'b mut self) -> Result<Baz<'a, 'b>, ()> { Er...
  function borrow_mut (line 39) | pub fn borrow_mut<'c>(&'c mut self) -> Qux<'a, 'b, 'c> { Qux { baz: self...
  function try_borrow_mut (line 40) | pub fn try_borrow_mut<'c>(&'c mut self) -> Result<Qux<'a, 'b, 'c>, ()> {...
  function fail_borrow_mut (line 41) | pub fn fail_borrow_mut<'c>(&'c mut self) -> Result<Qux<'a, 'b, 'c>, ()> ...
  function borrow_mut (line 45) | pub fn borrow_mut<'d>(&'d mut self) -> Xyzzy<'a, 'b, 'c, 'd> { Xyzzy { q...
  function try_borrow_mut (line 46) | pub fn try_borrow_mut<'d>(&'d mut self) -> Result<Xyzzy<'a, 'b, 'c, 'd>,...
  function fail_borrow_mut (line 47) | pub fn fail_borrow_mut<'d>(&'d mut self) -> Result<Xyzzy<'a, 'b, 'c, 'd>...
  function new (line 68) | fn new() {
  function read (line 101) | fn read() {
  function write (line 119) | fn write() {

FILE: tests/covariant.rs
  type Foo (line 8) | pub struct Foo {
  function borrow (line 45) | fn borrow() {

FILE: tests/debug.rs
  type Foo (line 6) | pub struct Foo {
  function print (line 31) | fn print() {

FILE: tests/drop_order.rs
  type Foo (line 10) | pub struct Foo {
    method borrow (line 37) | pub fn borrow<'a>(&'a self) -> Bar<'a> { Bar { foo: self, d: self.d.cl...
  type Bar (line 15) | pub struct Bar<'a> {
  type Baz (line 20) | pub struct Baz<'a: 'b, 'b> {
  type Qux (line 25) | pub struct Qux<'a: 'b, 'b: 'c, 'c> {
  type Xyzzy (line 30) | pub struct Xyzzy<'a: 'b, 'b: 'c, 'c: 'd, 'd> {
  method drop (line 41) | fn drop(&mut self) {
  function borrow (line 47) | pub fn borrow<'b>(&'b self) -> Baz<'a, 'b> { Baz { bar: self, d: self.d....
  method drop (line 51) | fn drop(&mut self) {
  function borrow (line 57) | pub fn borrow<'c>(&'c self) -> Qux<'a, 'b, 'c> { Qux { baz: self, d: sel...
  method drop (line 61) | fn drop(&mut self) {
  function borrow (line 67) | pub fn borrow<'d>(&'d self) -> Xyzzy<'a, 'b, 'c, 'd> { Xyzzy { qux: self...
  method drop (line 71) | fn drop(&mut self) {
  method drop (line 77) | fn drop(&mut self) {
  function drop_order (line 100) | fn drop_order() {

FILE: tests/generic.rs
  type Foo (line 5) | pub struct Foo<T: 'static> {
  function try_borrow (line 10) | fn try_borrow(&self) -> Result<&T, ()> { Ok(&self.t) }
  function fail_borrow (line 11) | fn fail_borrow(&self) -> Result<&T, ()> { Err(()) }
  function new (line 29) | fn new() {
  function read (line 44) | fn read() {

FILE: tests/lt_params.rs
  type Foo (line 5) | pub struct Foo<'a> {
  function borrow (line 10) | fn borrow(&self) -> &i32 { self.i }
  function try_borrow (line 11) | fn try_borrow(&self) -> Result<&i32, ()> { Ok(self.i) }
  function fail_borrow (line 12) | fn fail_borrow(&self) -> Result<&i32, ()> { Err(()) }
  function new (line 30) | fn new() {
  function read (line 47) | fn read() {

FILE: tests/map.rs
  type Foo (line 5) | pub struct Foo {
  function map (line 30) | fn map() {

FILE: tests/simple_mut.rs
  type Foo (line 5) | pub struct Foo {
    method try_borrow_mut (line 10) | fn try_borrow_mut(&mut self) -> Result<&mut i32, ()> { Ok(&mut self.i) }
    method fail_borrow_mut (line 11) | fn fail_borrow_mut(&mut self) -> Result<&mut i32, ()> { Err(()) }
  function new (line 29) | fn new() {
  function read (line 44) | fn read() {
  function write (line 57) | fn write() {

FILE: tests/simple_ref.rs
  type Foo (line 5) | pub struct Foo {
    method try_borrow (line 10) | fn try_borrow(&self) -> Result<&i32, ()> { Ok(&self.i) }
    method fail_borrow (line 11) | fn fail_borrow(&self) -> Result<&i32, ()> { Err(()) }
  type FooRef (line 14) | pub struct FooRef<'i> {
  type Target (line 21) | type Target = i32;
  function deref (line 23) | fn deref(&self) -> &i32 { self.iref }
  function new (line 41) | fn new() {
  function read (line 56) | fn read() {

FILE: tests/string.rs
  function new (line 18) | fn new() {
  function read (line 25) | fn read() {

FILE: tests/subrental.rs
  type Foo (line 5) | pub struct Foo {
    method borrow (line 19) | pub fn borrow(&self) -> Bar { Bar { foo: self } }
    method try_borrow (line 20) | pub fn try_borrow<'a>(&'a self) -> Result<Bar<'a>, ()> { Ok(Bar { foo:...
    method fail_borrow (line 21) | pub fn fail_borrow<'a>(&'a self) -> Result<Bar<'a>, ()> { Err(()) }
  type Bar (line 9) | pub struct Bar<'a> {
  type Qux (line 13) | pub struct Qux<'a: 'b, 'b> {
  function borrow (line 25) | pub fn borrow<'b>(&'b self) -> Qux<'a, 'b> { Qux { bar: self } }
  function try_borrow (line 26) | pub fn try_borrow<'b>(&'b self) -> Result<Qux<'a, 'b>, ()> { Ok(Qux { ba...
  function fail_borrow (line 27) | pub fn fail_borrow<'b>(&'b self) -> Result<Qux<'a, 'b>, ()> { Err(()) }
  function new (line 66) | fn new() {
  function read (line 84) | fn read() {

FILE: tests/target_ty_hack.rs
  type MyVec (line 5) | type MyVec<T> = Vec<T>;
  function new (line 30) | fn new() {
  function read (line 37) | fn read() {
  function write (line 47) | fn write() {

FILE: tests/trait.rs
  type MyTrait (line 5) | pub trait MyTrait { }
  type MyStruct (line 8) | pub struct MyStruct { }
  function new (line 28) | fn new() {

FILE: tests/unused.rs
  type Sample (line 6) | pub struct Sample {
  function unused (line 24) | fn unused() {

FILE: tests/vec_slice.rs
  function new (line 23) | fn new() {
  function read (line 30) | fn read() {
  function write (line 40) | fn write() {
Condensed preview — 25 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (142K chars).
[
  {
    "path": ".gitignore",
    "chars": 67,
    "preview": "/target\n/rental-impl/target\n/.cargo\nCargo.lock\n\n*.vim\n*.sw[onp]\n*~\n"
  },
  {
    "path": "Cargo.toml",
    "chars": 698,
    "preview": "[package]\nname = \"rental\"\nversion = \"0.5.6\"\nlicense = \"MIT/Apache-2.0\"\nauthors = [\"Jameson Ernst <jameson@jpernst.com>\"]"
  },
  {
    "path": "LICENSE-APACHE",
    "chars": 10847,
    "preview": "                              Apache License\n                        Version 2.0, January 2004\n                     http"
  },
  {
    "path": "LICENSE-MIT",
    "chars": 1057,
    "preview": "Copyright (c) 2016 Jameson Ernst\n\nPermission is hereby granted, free of charge, to any\nperson obtaining a copy of this s"
  },
  {
    "path": "README.md",
    "chars": 5740,
    "preview": "# WARNING: This crate is NO LONGER MAINTAINED OR SUPPORTED\nI'm not going to yank the crate because it's still fit for it"
  },
  {
    "path": "rental-impl/Cargo.toml",
    "chars": 483,
    "preview": "[package]\nname = \"rental-impl\"\nversion = \"0.5.5\"\nlicense = \"MIT/Apache-2.0\"\nauthors = [\"Jameson Ernst <jameson@jpernst.c"
  },
  {
    "path": "rental-impl/src/lib.rs",
    "chars": 64341,
    "preview": "#![recursion_limit = \"512\"]\n\nextern crate proc_macro;\nextern crate proc_macro2;\n#[macro_use]\nextern crate syn;\n#[macro_u"
  },
  {
    "path": "src/lib.rs",
    "chars": 25483,
    "preview": "//! A macro to generate safe self-referential structs, plus premade types for common use cases.\n//! \n//! # Overview\n//! "
  },
  {
    "path": "tests/clone.rs",
    "chars": 676,
    "preview": "#[macro_use]\nextern crate rental;\n\n\npub struct Foo {\n\ti: i32,\n}\n\npub struct Bar<'i> {\n\tiref: &'i i32,\n\tmisc: i32,\n}\n\nimp"
  },
  {
    "path": "tests/complex.rs",
    "chars": 2832,
    "preview": "#[macro_use]\nextern crate rental;\n\n\npub struct Foo {\n\ti: i32,\n}\n\npub struct Bar<'a> {\n\tfoo: &'a Foo,\n}\n\npub struct Baz<'"
  },
  {
    "path": "tests/complex_mut.rs",
    "chars": 3356,
    "preview": "#[macro_use]\nextern crate rental;\n\n\npub struct Foo {\n\ti: i32,\n}\n\npub struct Bar<'a> {\n\tfoo: &'a mut Foo,\n}\n\npub struct B"
  },
  {
    "path": "tests/covariant.rs",
    "chars": 696,
    "preview": "#[macro_use]\nextern crate rental;\n\n\n//use std::marker::PhantomData;\n\n\npub struct Foo {\n\ti: i32,\n}\n\n\n//pub struct Invaria"
  },
  {
    "path": "tests/debug.rs",
    "chars": 593,
    "preview": "#[macro_use]\nextern crate rental;\n\n\n#[derive(Debug)]\npub struct Foo {\n\ti: i32,\n}\n\n\nrental! {\n\tmod rentals {\n\t\tuse super:"
  },
  {
    "path": "tests/drop_order.rs",
    "chars": 2483,
    "preview": "#![allow(dead_code)]\n\n#[macro_use]\nextern crate rental;\n\nuse std::cell::RefCell;\nuse std::rc::Rc;\n\n\npub struct Foo {\n\ti:"
  },
  {
    "path": "tests/generic.rs",
    "chars": 983,
    "preview": "#[macro_use]\nextern crate rental;\n\n\npub struct Foo<T: 'static> {\n\tt: T,\n}\n\nimpl<T: 'static> Foo<T> {\n\tfn try_borrow(&sel"
  },
  {
    "path": "tests/lt_params.rs",
    "chars": 1097,
    "preview": "#[macro_use]\nextern crate rental;\n\n\npub struct Foo<'a> {\n\ti: &'a i32,\n}\n\nimpl<'a> Foo<'a> {\n\tfn borrow(&self) -> &i32 { "
  },
  {
    "path": "tests/map.rs",
    "chars": 668,
    "preview": "#[macro_use]\nextern crate rental;\n\n\npub struct Foo {\n\ti: i32,\n}\n\n\nrental! {\n\tmod rentals {\n\t\tuse super::*;\n\n\t\t#[rental(m"
  },
  {
    "path": "tests/simple_mut.rs",
    "chars": 1199,
    "preview": "#[macro_use]\nextern crate rental;\n\n\npub struct Foo {\n\ti: i32,\n}\n\nimpl Foo {\n\tfn try_borrow_mut(&mut self) -> Result<&mut"
  },
  {
    "path": "tests/simple_ref.rs",
    "chars": 2289,
    "preview": "#[macro_use]\nextern crate rental;\n\n\npub struct Foo {\n\ti: i32,\n}\n\nimpl Foo {\n\tfn try_borrow(&self) -> Result<&i32, ()> { "
  },
  {
    "path": "tests/string.rs",
    "chars": 515,
    "preview": "#[macro_use]\nextern crate rental;\n\n\nrental! {\n\tpub mod rent_string {\n\t\t#[rental(deref_suffix)]\n\t\tpub struct OwnedStr {\n\t"
  },
  {
    "path": "tests/subrental.rs",
    "chars": 1825,
    "preview": "#[macro_use]\nextern crate rental;\n\n\npub struct Foo {\n\tpub i: i32,\n}\n\npub struct Bar<'a> {\n\tpub foo: &'a Foo,\n}\n\npub stru"
  },
  {
    "path": "tests/target_ty_hack.rs",
    "chars": 981,
    "preview": "#[macro_use]\nextern crate rental;\n\n\ntype MyVec<T> = Vec<T>;\n\n\nrental! {\n\tpub mod rent_vec_slice {\n\t\tuse super::*;\n\n\t\t#[r"
  },
  {
    "path": "tests/trait.rs",
    "chars": 395,
    "preview": "#[macro_use]\nextern crate rental;\n\n\npub trait MyTrait { }\n\n\npub struct MyStruct { }\n\n\nimpl MyTrait for MyStruct { }\n\n\nre"
  },
  {
    "path": "tests/unused.rs",
    "chars": 515,
    "preview": "use std::rc::Rc;\n\n#[macro_use]\nextern crate rental;\n\npub struct Sample {\n    field: i32,\n}\n\nrental! {\n    mod sample_ren"
  },
  {
    "path": "tests/vec_slice.rs",
    "chars": 884,
    "preview": "#[macro_use]\nextern crate rental;\n\n\nrental! {\n\tpub mod rent_vec_slice {\n\t\t#[rental]\n\t\tpub struct OwnedSlice {\n\t\t\tbuffer:"
  }
]

About this extraction

This page contains the full source code of the jpernst/rental GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 25 files (127.6 KB), approximately 38.3k tokens, and a symbol index with 141 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!