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