]> git.lizzy.rs Git - rust.git/blob - src/librustc/arena.rs
Update inherent_impls
[rust.git] / src / librustc / arena.rs
1 use arena::{TypedArena, DroplessArena};
2 use std::mem;
3 use std::ptr;
4 use std::slice;
5 use std::cell::RefCell;
6 use std::marker::PhantomData;
7 use smallvec::SmallVec;
8
9 #[macro_export]
10 macro_rules! arena_types {
11     ($macro:path, $args:tt, $tcx:lifetime) => (
12         $macro!($args, [
13             [] vtable_method: Option<(
14                 rustc::hir::def_id::DefId,
15                 rustc::ty::subst::SubstsRef<$tcx>
16             )>,
17             [few] mir_keys: rustc::util::nodemap::DefIdSet,
18             [decode] specialization_graph: rustc::traits::specialization_graph::Graph,
19             [] region_scope_tree: rustc::middle::region::ScopeTree,
20             [] item_local_set: rustc::util::nodemap::ItemLocalSet,
21             [decode] mir_const_qualif: rustc_data_structures::bit_set::BitSet<rustc::mir::Local>,
22             [] trait_impls_of: rustc::ty::trait_def::TraitImpls,
23             [] dropck_outlives:
24                 rustc::infer::canonical::Canonical<'tcx,
25                     rustc::infer::canonical::QueryResponse<'tcx,
26                         rustc::traits::query::dropck_outlives::DropckOutlivesResult<'tcx>
27                     >
28                 >,
29             [] normalize_projection_ty:
30                 rustc::infer::canonical::Canonical<'tcx,
31                     rustc::infer::canonical::QueryResponse<'tcx,
32                         rustc::traits::query::normalize::NormalizationResult<'tcx>
33                     >
34                 >,
35             [] implied_outlives_bounds:
36                 rustc::infer::canonical::Canonical<'tcx,
37                     rustc::infer::canonical::QueryResponse<'tcx,
38                         Vec<rustc::traits::query::outlives_bounds::OutlivesBound<'tcx>>
39                     >
40                 >,
41             [] type_op_subtype:
42                 rustc::infer::canonical::Canonical<'tcx,
43                     rustc::infer::canonical::QueryResponse<'tcx, ()>
44                 >,
45             [] type_op_normalize_poly_fn_sig:
46                 rustc::infer::canonical::Canonical<'tcx,
47                     rustc::infer::canonical::QueryResponse<'tcx, rustc::ty::PolyFnSig<'tcx>>
48                 >,
49             [] type_op_normalize_fn_sig:
50                 rustc::infer::canonical::Canonical<'tcx,
51                     rustc::infer::canonical::QueryResponse<'tcx, rustc::ty::FnSig<'tcx>>
52                 >,
53             [] type_op_normalize_predicate:
54                 rustc::infer::canonical::Canonical<'tcx,
55                     rustc::infer::canonical::QueryResponse<'tcx, rustc::ty::Predicate<'tcx>>
56                 >,
57             [] type_op_normalize_ty:
58                 rustc::infer::canonical::Canonical<'tcx,
59                     rustc::infer::canonical::QueryResponse<'tcx, rustc::ty::Ty<'tcx>>
60                 >,
61             [few] crate_inherent_impls: rustc::ty::CrateInherentImpls,
62         ], $tcx);
63     )
64 }
65
66 macro_rules! arena_for_type {
67     ([][$ty:ty]) => {
68         TypedArena<$ty>
69     };
70     ([few $(, $attrs:ident)*][$ty:ty]) => {
71         PhantomData<$ty>
72     };
73     ([$ignore:ident $(, $attrs:ident)*]$args:tt) => {
74         arena_for_type!([$($attrs),*]$args)
75     };
76 }
77
78 macro_rules! declare_arena {
79     ([], [$($a:tt $name:ident: $ty:ty,)*], $tcx:lifetime) => {
80         #[derive(Default)]
81         pub struct Arena<$tcx> {
82             dropless: DroplessArena,
83             drop: DropArena,
84             $($name: arena_for_type!($a[$ty]),)*
85         }
86     }
87 }
88
89 macro_rules! which_arena_for_type {
90     ([][$arena:expr]) => {
91         Some($arena)
92     };
93     ([few$(, $attrs:ident)*][$arena:expr]) => {
94         None
95     };
96     ([$ignore:ident$(, $attrs:ident)*]$args:tt) => {
97         which_arena_for_type!([$($attrs),*]$args)
98     };
99 }
100
101 macro_rules! impl_arena_allocatable {
102     ([], [$($a:tt $name:ident: $ty:ty,)*], $tcx:lifetime) => {
103         $(
104             impl ArenaAllocatable for $ty {}
105             unsafe impl<$tcx> ArenaField<$tcx> for $ty {
106                 #[inline]
107                 fn arena<'a>(_arena: &'a Arena<$tcx>) -> Option<&'a TypedArena<Self>> {
108                     which_arena_for_type!($a[&_arena.$name])
109                 }
110             }
111         )*
112     }
113 }
114
115 arena_types!(declare_arena, [], 'tcx);
116
117 arena_types!(impl_arena_allocatable, [], 'tcx);
118
119 pub trait ArenaAllocatable {}
120
121 impl<T: Copy> ArenaAllocatable for T {}
122
123 pub unsafe trait ArenaField<'tcx>: Sized {
124     /// Returns a specific arena to allocate from.
125     /// If None is returned, the DropArena will be used.
126     fn arena<'a>(arena: &'a Arena<'tcx>) -> Option<&'a TypedArena<Self>>;
127 }
128
129 unsafe impl<'tcx, T> ArenaField<'tcx> for T {
130     #[inline]
131     default fn arena<'a>(_: &'a Arena<'tcx>) -> Option<&'a TypedArena<Self>> {
132         panic!()
133     }
134 }
135
136 impl<'tcx> Arena<'tcx> {
137     #[inline]
138     pub fn alloc<T: ArenaAllocatable>(&self, value: T) -> &mut T {
139         if !mem::needs_drop::<T>() {
140             return self.dropless.alloc(value);
141         }
142         match <T as ArenaField<'tcx>>::arena(self) {
143             Some(arena) => arena.alloc(value),
144             None => unsafe { self.drop.alloc(value) },
145         }
146     }
147
148     #[inline]
149     pub fn alloc_slice<T: Copy>(&self, value: &[T]) -> &mut [T] {
150         if value.len() == 0 {
151             return &mut []
152         }
153         self.dropless.alloc_slice(value)
154     }
155
156     pub fn alloc_from_iter<
157         T: ArenaAllocatable,
158         I: IntoIterator<Item = T>
159     >(
160         &'a self,
161         iter: I
162     ) -> &'a mut [T] {
163         if !mem::needs_drop::<T>() {
164             return self.dropless.alloc_from_iter(iter);
165         }
166         match <T as ArenaField<'tcx>>::arena(self) {
167             Some(arena) => arena.alloc_from_iter(iter),
168             None => unsafe { self.drop.alloc_from_iter(iter) },
169         }
170     }
171 }
172
173 /// Calls the destructor for an object when dropped.
174 struct DropType {
175     drop_fn: unsafe fn(*mut u8),
176     obj: *mut u8,
177 }
178
179 unsafe fn drop_for_type<T>(to_drop: *mut u8) {
180     std::ptr::drop_in_place(to_drop as *mut T)
181 }
182
183 impl Drop for DropType {
184     fn drop(&mut self) {
185         unsafe {
186             (self.drop_fn)(self.obj)
187         }
188     }
189 }
190
191 /// An arena which can be used to allocate any type.
192 /// Allocating in this arena is unsafe since the type system
193 /// doesn't know which types it contains. In order to
194 /// allocate safely, you must store a PhantomData<T>
195 /// alongside this arena for each type T you allocate.
196 #[derive(Default)]
197 struct DropArena {
198     /// A list of destructors to run when the arena drops.
199     /// Ordered so `destructors` gets dropped before the arena
200     /// since its destructor can reference memory in the arena.
201     destructors: RefCell<Vec<DropType>>,
202     arena: DroplessArena,
203 }
204
205 impl DropArena {
206     #[inline]
207     unsafe fn alloc<T>(&self, object: T) -> &mut T {
208         let mem = self.arena.alloc_raw(
209             mem::size_of::<T>(),
210             mem::align_of::<T>()
211         ) as *mut _ as *mut T;
212         // Write into uninitialized memory.
213         ptr::write(mem, object);
214         let result = &mut *mem;
215         // Record the destructor after doing the allocation as that may panic
216         // and would cause `object`'s destuctor to run twice if it was recorded before
217         self.destructors.borrow_mut().push(DropType {
218             drop_fn: drop_for_type::<T>,
219             obj: result as *mut T as *mut u8,
220         });
221         result
222     }
223
224     #[inline]
225     unsafe fn alloc_from_iter<T, I: IntoIterator<Item = T>>(&self, iter: I) -> &mut [T] {
226         let mut vec: SmallVec<[_; 8]> = iter.into_iter().collect();
227         if vec.is_empty() {
228             return &mut [];
229         }
230         let len = vec.len();
231
232         let start_ptr = self.arena.alloc_raw(
233             len.checked_mul(mem::size_of::<T>()).unwrap(),
234             mem::align_of::<T>()
235         ) as *mut _ as *mut T;
236
237         let mut destructors = self.destructors.borrow_mut();
238         // Reserve space for the destructors so we can't panic while adding them
239         destructors.reserve(len);
240
241         // Move the content to the arena by copying it and then forgetting
242         // the content of the SmallVec
243         vec.as_ptr().copy_to_nonoverlapping(start_ptr, len);
244         mem::forget(vec.drain());
245
246         // Record the destructors after doing the allocation as that may panic
247         // and would cause `object`'s destuctor to run twice if it was recorded before
248         for i in 0..len {
249             destructors.push(DropType {
250                 drop_fn: drop_for_type::<T>,
251                 obj: start_ptr.offset(i as isize) as *mut u8,
252             });
253         }
254
255         slice::from_raw_parts_mut(start_ptr, len)
256     }
257 }