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