3 //! Provides `P<T>`, a frozen owned smart pointer, as a replacement for `@T` in
6 //! # Motivations and benefits
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>`.
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".
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).
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.
29 use std::fmt::{self, Display, Debug};
30 use std::iter::FromIterator;
31 use std::ops::{Deref, DerefMut};
32 use std::{slice, vec};
34 use serialize::{Encodable, Decodable, Encoder, Decoder};
36 use rustc_data_structures::stable_hasher::{StableHasher, StableHasherResult,
38 /// An owned smart pointer.
39 #[derive(Hash, PartialEq, Eq)]
40 pub struct P<T: ?Sized> {
44 #[allow(non_snake_case)]
45 /// Construct a `P<T>` from a `T` value.
46 pub fn P<T: 'static>(value: T) -> P<T> {
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
61 /// Equivalent to `and_then(|x| x)`.
62 pub fn into_inner(self) -> T {
66 /// Produce a new `P<T>` from `self` without reallocating.
67 pub fn map<F>(mut self, f: F) -> P<T> where
76 /// Optionally produce a new `P<T>` from `self` without reallocating.
77 pub fn filter_map<F>(mut self, f: F) -> Option<P<T>> where
78 F: FnOnce(T) -> Option<T>,
80 *self.ptr = f(*self.ptr)?;
85 impl<T: ?Sized> Deref for P<T> {
88 fn deref(&self) -> &T {
93 impl<T: ?Sized> DerefMut for P<T> {
94 fn deref_mut(&mut self) -> &mut T {
99 impl<T: 'static + Clone> Clone for P<T> {
100 fn clone(&self) -> P<T> {
105 impl<T: ?Sized + Debug> Debug for P<T> {
106 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
107 Debug::fmt(&self.ptr, f)
111 impl<T: Display> Display for P<T> {
112 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
113 Display::fmt(&**self, f)
117 impl<T> fmt::Pointer for P<T> {
118 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
119 fmt::Pointer::fmt(&self.ptr, f)
123 impl<T: 'static + Decodable> Decodable for P<T> {
124 fn decode<D: Decoder>(d: &mut D) -> Result<P<T>, D::Error> {
125 Decodable::decode(d).map(P)
129 impl<T: Encodable> Encodable for P<T> {
130 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
136 pub fn new() -> P<[T]> {
137 P { ptr: Default::default() }
141 pub fn from_vec(v: Vec<T>) -> P<[T]> {
142 P { ptr: v.into_boxed_slice() }
146 pub fn into_vec(self) -> Vec<T> {
151 impl<T> Default for P<[T]> {
152 /// Creates an empty `P<[T]>`.
153 fn default() -> P<[T]> {
158 impl<T: Clone> Clone for P<[T]> {
159 fn clone(&self) -> P<[T]> {
160 P::from_vec(self.to_vec())
164 impl<T> From<Vec<T>> for P<[T]> {
165 fn from(v: Vec<T>) -> Self {
170 impl<T> Into<Vec<T>> for P<[T]> {
171 fn into(self) -> Vec<T> {
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())
182 impl<T> IntoIterator for P<[T]> {
184 type IntoIter = vec::IntoIter<T>;
186 fn into_iter(self) -> Self::IntoIter {
187 self.into_vec().into_iter()
191 impl<'a, T> IntoIterator for &'a P<[T]> {
193 type IntoIter = slice::Iter<'a, T>;
194 fn into_iter(self) -> Self::IntoIter {
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)
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)?))
211 impl<CTX, T> HashStable<CTX> for P<T>
212 where T: ?Sized + HashStable<CTX>
214 fn hash_stable<W: StableHasherResult>(&self,
216 hasher: &mut StableHasher<W>) {
217 (**self).hash_stable(hcx, hasher);