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