]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/ptr.rs
remove extern_in_paths.
[rust.git] / src / libsyntax / ptr.rs
1 //! The AST pointer
2 //!
3 //! Provides `P<T>`, a frozen owned smart pointer, as a replacement for `@T` in
4 //! the AST.
5 //!
6 //! # Motivations and benefits
7 //!
8 //! * **Identity**: sharing AST nodes is problematic for the various analysis
9 //!   passes (e.g., one may be able to bypass the borrow checker with a shared
10 //!   `ExprKind::AddrOf` node taking a mutable borrow). The only reason `@T` in the
11 //!   AST hasn't caused issues is because of inefficient folding passes which
12 //!   would always deduplicate any such shared nodes. Even if the AST were to
13 //!   switch to an arena, this would still hold, i.e., it couldn't use `&'a T`,
14 //!   but rather a wrapper like `P<'a, T>`.
15 //!
16 //! * **Immutability**: `P<T>` disallows mutating its inner `T`, unlike `Box<T>`
17 //!   (unless it contains an `Unsafe` interior, but that may be denied later).
18 //!   This mainly prevents mistakes, but can also enforces a kind of "purity".
19 //!
20 //! * **Efficiency**: folding can reuse allocation space for `P<T>` and `Vec<T>`,
21 //!   the latter even when the input and output types differ (as it would be the
22 //!   case with arenas or a GADT AST using type parameters to toggle features).
23 //!
24 //! * **Maintainability**: `P<T>` provides a fixed interface - `Deref`,
25 //!   `and_then` and `map` - which can remain fully functional even if the
26 //!   implementation changes (using a special thread-local heap, for example).
27 //!   Moreover, a switch to, e.g., `P<'a, T>` would be easy and mostly automated.
28
29 use std::fmt::{self, Display, Debug};
30 use std::iter::FromIterator;
31 use std::ops::{Deref, DerefMut};
32 use std::{mem, ptr, slice, vec};
33
34 use serialize::{Encodable, Decodable, Encoder, Decoder};
35
36 use rustc_data_structures::stable_hasher::{StableHasher, StableHasherResult,
37                                            HashStable};
38 /// An owned smart pointer.
39 #[derive(Hash, PartialEq, Eq)]
40 pub struct P<T: ?Sized> {
41     ptr: Box<T>
42 }
43
44 #[allow(non_snake_case)]
45 /// Construct a `P<T>` from a `T` value.
46 pub fn P<T: 'static>(value: T) -> P<T> {
47     P {
48         ptr: Box::new(value)
49     }
50 }
51
52 impl<T: 'static> P<T> {
53     /// Move out of the pointer.
54     /// Intended for chaining transformations not covered by `map`.
55     pub fn and_then<U, F>(self, f: F) -> U where
56         F: FnOnce(T) -> U,
57     {
58         f(*self.ptr)
59     }
60     /// Equivalent to and_then(|x| x)
61     pub fn into_inner(self) -> T {
62         *self.ptr
63     }
64
65     /// Produce a new `P<T>` from `self` without reallocating.
66     pub fn map<F>(mut self, f: F) -> P<T> where
67         F: FnOnce(T) -> T,
68     {
69         let p: *mut T = &mut *self.ptr;
70
71         // Leak self in case of panic.
72         // FIXME(eddyb) Use some sort of "free guard" that
73         // only deallocates, without dropping the pointee,
74         // in case the call the `f` below ends in a panic.
75         mem::forget(self);
76
77         unsafe {
78             ptr::write(p, f(ptr::read(p)));
79
80             // Recreate self from the raw pointer.
81             P { ptr: Box::from_raw(p) }
82         }
83     }
84
85     /// Optionally produce a new `P<T>` from `self` without reallocating.
86     pub fn filter_map<F>(mut self, f: F) -> Option<P<T>> where
87         F: FnOnce(T) -> Option<T>,
88     {
89         let p: *mut T = &mut *self.ptr;
90
91         // Leak self in case of panic.
92         // FIXME(eddyb) Use some sort of "free guard" that
93         // only deallocates, without dropping the pointee,
94         // in case the call the `f` below ends in a panic.
95         mem::forget(self);
96
97         unsafe {
98             if let Some(v) = f(ptr::read(p)) {
99                 ptr::write(p, v);
100
101                 // Recreate self from the raw pointer.
102                 Some(P { ptr: Box::from_raw(p) })
103             } else {
104                 None
105             }
106         }
107     }
108 }
109
110 impl<T: ?Sized> Deref for P<T> {
111     type Target = T;
112
113     fn deref(&self) -> &T {
114         &self.ptr
115     }
116 }
117
118 impl<T: ?Sized> DerefMut for P<T> {
119     fn deref_mut(&mut self) -> &mut T {
120         &mut self.ptr
121     }
122 }
123
124 impl<T: 'static + Clone> Clone for P<T> {
125     fn clone(&self) -> P<T> {
126         P((**self).clone())
127     }
128 }
129
130 impl<T: ?Sized + Debug> Debug for P<T> {
131     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
132         Debug::fmt(&self.ptr, f)
133     }
134 }
135
136 impl<T: Display> Display for P<T> {
137     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
138         Display::fmt(&**self, f)
139     }
140 }
141
142 impl<T> fmt::Pointer for P<T> {
143     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
144         fmt::Pointer::fmt(&self.ptr, f)
145     }
146 }
147
148 impl<T: 'static + Decodable> Decodable for P<T> {
149     fn decode<D: Decoder>(d: &mut D) -> Result<P<T>, D::Error> {
150         Decodable::decode(d).map(P)
151     }
152 }
153
154 impl<T: Encodable> Encodable for P<T> {
155     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
156         (**self).encode(s)
157     }
158 }
159
160 impl<T> P<[T]> {
161     pub fn new() -> P<[T]> {
162         P { ptr: Default::default() }
163     }
164
165     #[inline(never)]
166     pub fn from_vec(v: Vec<T>) -> P<[T]> {
167         P { ptr: v.into_boxed_slice() }
168     }
169
170     #[inline(never)]
171     pub fn into_vec(self) -> Vec<T> {
172         self.ptr.into_vec()
173     }
174 }
175
176 impl<T> Default for P<[T]> {
177     /// Creates an empty `P<[T]>`.
178     fn default() -> P<[T]> {
179         P::new()
180     }
181 }
182
183 impl<T: Clone> Clone for P<[T]> {
184     fn clone(&self) -> P<[T]> {
185         P::from_vec(self.to_vec())
186     }
187 }
188
189 impl<T> From<Vec<T>> for P<[T]> {
190     fn from(v: Vec<T>) -> Self {
191         P::from_vec(v)
192     }
193 }
194
195 impl<T> Into<Vec<T>> for P<[T]> {
196     fn into(self) -> Vec<T> {
197         self.into_vec()
198     }
199 }
200
201 impl<T> FromIterator<T> for P<[T]> {
202     fn from_iter<I: IntoIterator<Item=T>>(iter: I) -> P<[T]> {
203         P::from_vec(iter.into_iter().collect())
204     }
205 }
206
207 impl<T> IntoIterator for P<[T]> {
208     type Item = T;
209     type IntoIter = vec::IntoIter<T>;
210
211     fn into_iter(self) -> Self::IntoIter {
212         self.into_vec().into_iter()
213     }
214 }
215
216 impl<'a, T> IntoIterator for &'a P<[T]> {
217     type Item = &'a T;
218     type IntoIter = slice::Iter<'a, T>;
219     fn into_iter(self) -> Self::IntoIter {
220         self.ptr.into_iter()
221     }
222 }
223
224 impl<T: Encodable> Encodable for P<[T]> {
225     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
226         Encodable::encode(&**self, s)
227     }
228 }
229
230 impl<T: Decodable> Decodable for P<[T]> {
231     fn decode<D: Decoder>(d: &mut D) -> Result<P<[T]>, D::Error> {
232         Ok(P::from_vec(Decodable::decode(d)?))
233     }
234 }
235
236 impl<CTX, T> HashStable<CTX> for P<T>
237     where T: ?Sized + HashStable<CTX>
238 {
239     fn hash_stable<W: StableHasherResult>(&self,
240                                           hcx: &mut CTX,
241                                           hasher: &mut StableHasher<W>) {
242         (**self).hash_stable(hcx, hasher);
243     }
244 }