]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/ptr.rs
Remove `for_each_child_stable`
[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::{slice, vec};
33
34 use rustc_serialize::{Encodable, Decodable, Encoder, Decoder};
35
36 use rustc_data_structures::stable_hasher::{StableHasher, HashStable};
37 /// An owned smart pointer.
38 #[derive(Hash, PartialEq, Eq)]
39 pub struct P<T: ?Sized> {
40     ptr: Box<T>
41 }
42
43 /// Construct a `P<T>` from a `T` value.
44 #[allow(non_snake_case)]
45 pub fn P<T: 'static>(value: T) -> P<T> {
46     P {
47         ptr: box value
48     }
49 }
50
51 impl<T: 'static> P<T> {
52     /// Move out of the pointer.
53     /// Intended for chaining transformations not covered by `map`.
54     pub fn and_then<U, F>(self, f: F) -> U where
55         F: FnOnce(T) -> U,
56     {
57         f(*self.ptr)
58     }
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 x = f(*self.ptr);
70         *self.ptr = x;
71
72         self
73     }
74
75     /// Optionally produce a new `P<T>` from `self` without reallocating.
76     pub fn filter_map<F>(mut self, f: F) -> Option<P<T>> where
77         F: FnOnce(T) -> Option<T>,
78     {
79         *self.ptr = f(*self.ptr)?;
80         Some(self)
81     }
82 }
83
84 impl<T: ?Sized> Deref for P<T> {
85     type Target = T;
86
87     fn deref(&self) -> &T {
88         &self.ptr
89     }
90 }
91
92 impl<T: ?Sized> DerefMut for P<T> {
93     fn deref_mut(&mut self) -> &mut T {
94         &mut self.ptr
95     }
96 }
97
98 impl<T: 'static + Clone> Clone for P<T> {
99     fn clone(&self) -> P<T> {
100         P((**self).clone())
101     }
102 }
103
104 impl<T: ?Sized + Debug> Debug for P<T> {
105     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
106         Debug::fmt(&self.ptr, f)
107     }
108 }
109
110 impl<T: Display> Display for P<T> {
111     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
112         Display::fmt(&**self, f)
113     }
114 }
115
116 impl<T> fmt::Pointer for P<T> {
117     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
118         fmt::Pointer::fmt(&self.ptr, f)
119     }
120 }
121
122 impl<T: 'static + Decodable> Decodable for P<T> {
123     fn decode<D: Decoder>(d: &mut D) -> Result<P<T>, D::Error> {
124         Decodable::decode(d).map(P)
125     }
126 }
127
128 impl<T: Encodable> Encodable for P<T> {
129     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
130         (**self).encode(s)
131     }
132 }
133
134 impl<T> P<[T]> {
135     pub const fn new() -> P<[T]> {
136         // HACK(eddyb) bypass the lack of a `const fn` to create an empty `Box<[T]>`
137         // (as trait methods, `default` in this case, can't be `const fn` yet).
138         P {
139             ptr: unsafe {
140                 use std::ptr::NonNull;
141                 std::mem::transmute(NonNull::<[T; 0]>::dangling() as NonNull<[T]>)
142             },
143         }
144     }
145
146     #[inline(never)]
147     pub fn from_vec(v: Vec<T>) -> P<[T]> {
148         P { ptr: v.into_boxed_slice() }
149     }
150
151     #[inline(never)]
152     pub fn into_vec(self) -> Vec<T> {
153         self.ptr.into_vec()
154     }
155 }
156
157 impl<T> Default for P<[T]> {
158     /// Creates an empty `P<[T]>`.
159     fn default() -> P<[T]> {
160         P::new()
161     }
162 }
163
164 impl<T: Clone> Clone for P<[T]> {
165     fn clone(&self) -> P<[T]> {
166         P::from_vec(self.to_vec())
167     }
168 }
169
170 impl<T> From<Vec<T>> for P<[T]> {
171     fn from(v: Vec<T>) -> Self {
172         P::from_vec(v)
173     }
174 }
175
176 impl<T> Into<Vec<T>> for P<[T]> {
177     fn into(self) -> Vec<T> {
178         self.into_vec()
179     }
180 }
181
182 impl<T> FromIterator<T> for P<[T]> {
183     fn from_iter<I: IntoIterator<Item=T>>(iter: I) -> P<[T]> {
184         P::from_vec(iter.into_iter().collect())
185     }
186 }
187
188 impl<T> IntoIterator for P<[T]> {
189     type Item = T;
190     type IntoIter = vec::IntoIter<T>;
191
192     fn into_iter(self) -> Self::IntoIter {
193         self.into_vec().into_iter()
194     }
195 }
196
197 impl<'a, T> IntoIterator for &'a P<[T]> {
198     type Item = &'a T;
199     type IntoIter = slice::Iter<'a, T>;
200     fn into_iter(self) -> Self::IntoIter {
201         self.ptr.into_iter()
202     }
203 }
204
205 impl<T: Encodable> Encodable for P<[T]> {
206     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
207         Encodable::encode(&**self, s)
208     }
209 }
210
211 impl<T: Decodable> Decodable for P<[T]> {
212     fn decode<D: Decoder>(d: &mut D) -> Result<P<[T]>, D::Error> {
213         Ok(P::from_vec(Decodable::decode(d)?))
214     }
215 }
216
217 impl<CTX, T> HashStable<CTX> for P<T>
218     where T: ?Sized + HashStable<CTX>
219 {
220     fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
221         (**self).hash_stable(hcx, hasher);
222     }
223 }