]> git.proxmox.com Git - rustc.git/blob - src/libsyntax/ptr.rs
Imported Upstream version 1.8.0+dfsg1
[rustc.git] / src / libsyntax / ptr.rs
1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! The AST pointer
12 //!
13 //! Provides `P<T>`, a frozen owned smart pointer, as a replacement for `@T` in
14 //! the AST.
15 //!
16 //! # Motivations and benefits
17 //!
18 //! * **Identity**: sharing AST nodes is problematic for the various analysis
19 //! passes (e.g. one may be able to bypass the borrow checker with a shared
20 //! `ExprKind::AddrOf` node taking a mutable borrow). The only reason `@T` in the
21 //! AST hasn't caused issues is because of inefficient folding passes which
22 //! would always deduplicate any such shared nodes. Even if the AST were to
23 //! switch to an arena, this would still hold, i.e. it couldn't use `&'a T`,
24 //! but rather a wrapper like `P<'a, T>`.
25 //!
26 //! * **Immutability**: `P<T>` disallows mutating its inner `T`, unlike `Box<T>`
27 //! (unless it contains an `Unsafe` interior, but that may be denied later).
28 //! This mainly prevents mistakes, but can also enforces a kind of "purity".
29 //!
30 //! * **Efficiency**: folding can reuse allocation space for `P<T>` and `Vec<T>`,
31 //! the latter even when the input and output types differ (as it would be the
32 //! case with arenas or a GADT AST using type parameters to toggle features).
33 //!
34 //! * **Maintainability**: `P<T>` provides a fixed interface - `Deref`,
35 //! `and_then` and `map` - which can remain fully functional even if the
36 //! implementation changes (using a special thread-local heap, for example).
37 //! Moreover, a switch to, e.g. `P<'a, T>` would be easy and mostly automated.
38
39 use std::fmt::{self, Display, Debug};
40 use std::iter::FromIterator;
41 use std::ops::Deref;
42 use std::{ptr, slice, vec};
43
44 use serialize::{Encodable, Decodable, Encoder, Decoder};
45
46 /// An owned smart pointer.
47 #[derive(Hash, PartialEq, Eq, PartialOrd, Ord)]
48 pub struct P<T: ?Sized> {
49 ptr: Box<T>
50 }
51
52 #[allow(non_snake_case)]
53 /// Construct a `P<T>` from a `T` value.
54 pub fn P<T: 'static>(value: T) -> P<T> {
55 P {
56 ptr: Box::new(value)
57 }
58 }
59
60 impl<T: 'static> P<T> {
61 /// Move out of the pointer.
62 /// Intended for chaining transformations not covered by `map`.
63 pub fn and_then<U, F>(self, f: F) -> U where
64 F: FnOnce(T) -> U,
65 {
66 f(*self.ptr)
67 }
68 /// Equivalent to and_then(|x| x)
69 pub fn unwrap(self) -> T {
70 *self.ptr
71 }
72
73 /// Transform the inner value, consuming `self` and producing a new `P<T>`.
74 pub fn map<F>(mut self, f: F) -> P<T> where
75 F: FnOnce(T) -> T,
76 {
77 unsafe {
78 let p = &mut *self.ptr;
79 // FIXME(#5016) this shouldn't need to drop-fill to be safe.
80 ptr::write(p, f(ptr::read_and_drop(p)));
81 }
82 self
83 }
84 }
85
86 impl<T> Deref for P<T> {
87 type Target = T;
88
89 fn deref<'a>(&'a self) -> &'a T {
90 &self.ptr
91 }
92 }
93
94 impl<T: 'static + Clone> Clone for P<T> {
95 fn clone(&self) -> P<T> {
96 P((**self).clone())
97 }
98 }
99
100 impl<T: Debug> Debug for P<T> {
101 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
102 Debug::fmt(&**self, f)
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<T: 'static + Decodable> Decodable for P<T> {
118 fn decode<D: Decoder>(d: &mut D) -> Result<P<T>, D::Error> {
119 Decodable::decode(d).map(P)
120 }
121 }
122
123 impl<T: Encodable> Encodable for P<T> {
124 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
125 (**self).encode(s)
126 }
127 }
128
129
130 impl<T:fmt::Debug> fmt::Debug for P<[T]> {
131 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
132 self.ptr.fmt(fmt)
133 }
134 }
135
136 impl<T> P<[T]> {
137 pub fn new() -> P<[T]> {
138 P::empty()
139 }
140
141 pub fn empty() -> P<[T]> {
142 P { ptr: Default::default() }
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 pub fn as_slice<'a>(&'a self) -> &'a [T] {
156 &self.ptr
157 }
158
159 pub fn move_iter(self) -> vec::IntoIter<T> {
160 self.into_vec().into_iter()
161 }
162
163 pub fn map<U, F: FnMut(&T) -> U>(&self, f: F) -> P<[U]> {
164 self.iter().map(f).collect()
165 }
166 }
167
168 impl<T> Deref for P<[T]> {
169 type Target = [T];
170
171 fn deref(&self) -> &[T] {
172 self.as_slice()
173 }
174 }
175
176 impl<T> Default for P<[T]> {
177 fn default() -> P<[T]> {
178 P::empty()
179 }
180 }
181
182 impl<T: Clone> Clone for P<[T]> {
183 fn clone(&self) -> P<[T]> {
184 P::from_vec(self.to_vec())
185 }
186 }
187
188 impl<T> From<Vec<T>> for P<[T]> {
189 fn from(v: Vec<T>) -> Self {
190 P::from_vec(v)
191 }
192 }
193
194 impl<T> Into<Vec<T>> for P<[T]> {
195 fn into(self) -> Vec<T> {
196 self.into_vec()
197 }
198 }
199
200 impl<T> FromIterator<T> for P<[T]> {
201 fn from_iter<I: IntoIterator<Item=T>>(iter: I) -> P<[T]> {
202 P::from_vec(iter.into_iter().collect())
203 }
204 }
205
206 impl<T> IntoIterator for P<[T]> {
207 type Item = T;
208 type IntoIter = vec::IntoIter<T>;
209
210 fn into_iter(self) -> Self::IntoIter {
211 self.into_vec().into_iter()
212 }
213 }
214
215 impl<'a, T> IntoIterator for &'a P<[T]> {
216 type Item = &'a T;
217 type IntoIter = slice::Iter<'a, T>;
218 fn into_iter(self) -> Self::IntoIter {
219 self.ptr.into_iter()
220 }
221 }
222
223 impl<T: Encodable> Encodable for P<[T]> {
224 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
225 Encodable::encode(&**self, s)
226 }
227 }
228
229 impl<T: Decodable> Decodable for P<[T]> {
230 fn decode<D: Decoder>(d: &mut D) -> Result<P<[T]>, D::Error> {
231 Ok(P::from_vec(match Decodable::decode(d) {
232 Ok(t) => t,
233 Err(e) => return Err(e)
234 }))
235 }
236 }