Debian Codegraph @

src/lib.rs

raw symbols SCIP
1 //! [![github]](https://github.com/dtolnay/ghost) [![crates-io]](https://crates.io/crates/ghost) [![docs-rs]](https://docs.rs/ghost)
2 //!
3 //! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github
4 //! [crates-io]: https://img.shields.io/badge/crates.io-fc8d62?style=for-the-badge&labelColor=555555&logo=rust
5 //! [docs-rs]: https://img.shields.io/badge/docs.rs-66c2a5?style=for-the-badge&labelColor=555555&logo=docs.rs
6 //!
7 //! <br>
8 //!
9 //! **Define your own PhantomData and similarly behaved unit types.**
10 //!
11 //! # Background
12 //!
13 //! [`PhantomData`] as defined by the Rust standard library is magical in that
14 //! the same type is impossible to define in ordinary Rust code. It is defined
15 //! in the standard library like this:
16 //!
17 //! [`PhantomData`]: https://doc.rust-lang.org/std/marker/struct.PhantomData.html
18 //!
19 //! ```
20 //! # const IGNORE: &str = stringify! {
21 //! #[lang = "phantom_data"]
22 //! pub struct PhantomData<T: ?Sized>;
23 //! # };
24 //! ```
25 //!
26 //! The `#[lang = "..."]` attribute indicates that this is a [lang item], a
27 //! special case known to the compiler. It is the only type permitted to carry
28 //! an unused type parameter.
29 //!
30 //! [lang item]: https://manishearth.github.io/blog/2017/01/11/rust-tidbits-what-is-a-lang-item/
31 //!
32 //! If we try to define an equivalent unit struct with type parameter, the
33 //! compiler rejects that.
34 //!
35 //! ```compile_fail
36 //! struct MyPhantom<T: ?Sized>;
37 //! ```
38 //!
39 //! ```text
40 //! error[E0392]: parameter `T` is never used
41 //! --> src/main.rs:1:18
42 //! |
43 //! 1 | struct MyPhantom<T: ?Sized>;
44 //! | ^ unused type parameter
45 //! |
46 //! = help: consider removing `T` or using a marker such as `std::marker::PhantomData`
47 //! ```
48 //!
49 //! This crate provides a `#[phantom]` attribute that makes it possible to
50 //! define unit structs with generic parameters.
51 //!
52 //! # Examples
53 //!
54 //! ```
55 //! use ghost::phantom;
56 //!
57 //! #[phantom]
58 //! struct MyPhantom<T: ?Sized>;
59 //!
60 //! fn main() {
61 //! // Proof that MyPhantom behaves like PhantomData.
62 //! let _: MyPhantom<u8> = MyPhantom::<u8>;
63 //! assert_eq!(0, std::mem::size_of::<MyPhantom<u8>>());
64 //! }
65 //!
66 //! // Proof that MyPhantom is not just a re-export of PhantomData.
67 //! // If it were a re-export, these would be conflicting impls.
68 //! trait Trait {}
69 //! impl<T> Trait for std::marker::PhantomData<T> {}
70 //! impl<T> Trait for MyPhantom<T> {}
71 //!
72 //! // Proof that MyPhantom is local to the current crate.
73 //! impl<T> MyPhantom<T> {
74 //! }
75 //! ```
76 //!
77 //! The implementation accepts where-clauses, lifetimes, multiple generic
78 //! parameters, and derives. Here is a contrived invocation that demonstrates
79 //! everything at once:
80 //!
81 //! ```
82 //! use ghost::phantom;
83 //!
84 //! #[phantom]
85 //! #[derive(Copy, Clone, Default, Hash, PartialOrd, Ord, PartialEq, Eq, Debug)]
86 //! struct Crazy<'a, V: 'a, T> where &'a V: IntoIterator<Item = T>;
87 //!
88 //! fn main() {
89 //! let _ = Crazy::<'static, Vec<String>, &'static String>;
90 //!
91 //! // Lifetime elision.
92 //! let crazy = Crazy::<Vec<String>, &String>;
93 //! println!("{:?}", crazy);
94 //! }
95 //! ```
96 //!
97 //! # Variance
98 //!
99 //! The `#[phantom]` attribute accepts attributes on individual generic
100 //! parameters (both lifetime and type parameters) to make them contravariant or
101 //! invariant. The default is covariance.
102 //!
103 //! - `#[contra]` — contravariant generic parameter
104 //! - `#[invariant]` — invariant generic parameter
105 //!
106 //! The implications of variance are explained in more detail by the [Subtyping
107 //! chapter] of the Rustonomicon.
108 //!
109 //! [Subtyping chapter]: https://doc.rust-lang.org/nomicon/subtyping.html
110 //!
111 //! ```
112 //! use ghost::phantom;
113 //!
114 //! #[phantom]
115 //! struct ContravariantLifetime<#[contra] 'a>;
116 //!
117 //! fn f<'a>(arg: ContravariantLifetime<'a>) -> ContravariantLifetime<'static> {
118 //! // This coercion is only legal because the lifetime parameter is
119 //! // contravariant. If it were covariant (the default) or invariant,
120 //! // this would not compile.
121 //! arg
122 //! }
123 //!
124 //! #[phantom]
125 //! struct Demo<A, #[contra] B, #[invariant] C>;
126 //! #
127 //! # fn main() {}
128 //! ```
129 //!
130 //! # Use cases
131 //!
132 //! Entirely up to your imagination. Just to name one, how about a typed
133 //! registry library that admits the following syntax for iterating over values
134 //! registered of a particular type:
135 //!
136 //! ```no_run
137 //! # use ghost::phantom;
138 //! #
139 //! # #[phantom]
140 //! # struct Registry<T>;
141 //! #
142 //! # impl<T> IntoIterator for Registry<T> {
143 //! # type Item = T;
144 //! # type IntoIter = Iter<T>;
145 //! # fn into_iter(self) -> Self::IntoIter {
146 //! # unimplemented!()
147 //! # }
148 //! # }
149 //! #
150 //! # struct Iter<T>(T);
151 //! #
152 //! # impl<T> Iterator for Iter<T> {
153 //! # type Item = T;
154 //! # fn next(&mut self) -> Option<Self::Item> {
155 //! # unimplemented!()
156 //! # }
157 //! # }
158 //! #
159 //! # struct Flag;
160 //! #
161 //! # fn main() {
162 //! for flag in Registry::<Flag> {
163 //! /* ... */
164 //! }
165 //! # }
166 //! ```
167
168 #![allow(
169 clippy::doc_markdown,
170 // https://github.com/rust-lang/rust-clippy/issues/8538
171 clippy::iter_with_drain,
172 clippy::needless_doctest_main,
173 clippy::needless_pass_by_value,
174 clippy::too_many_lines
175 )]
176
177 extern crate proc_macro;
178
179 mod derive;
180 mod parse;
181 mod variance;
182 mod visibility;
183
184 use proc_macro::TokenStream;
185 use proc_macro2::{Ident, Span};
186 use quote::quote;
187 use syn::parse::Nothing;
188 use syn::{parse_macro_input, Error, GenericParam, Token};
189
190 use crate::parse::UnitStruct;
191
192 /// Define your own PhantomData and similarly behaved unit types.
193 ///
194 /// Please refer to the [crate level documentation](index.html) for explanation
195 /// and examples.
196 #[proc_macro_attribute]
197 pub fn phantom(args: TokenStream, input: TokenStream) -> TokenStream {
198 parse_macro_input!(args as Nothing);
199 let input = parse_macro_input!(input as UnitStruct);
200
201 let ident = &input.ident;
202 let call_site = Span::call_site();
203 let void_namespace = Ident::new(&format!("__void_{}", ident), call_site);
204 let value_namespace = Ident::new(&format!("__value_{}", ident), call_site);
205
206 let vis = &input.vis;
207 let vis_super = visibility::vis_super(vis);
208
209 let (derives, attrs) = match derive::expand(&input.attrs, &input) {
210 Ok(split) => split,
211 Err(err) => return err.to_compile_error().into(),
212 };
213
214 let void = Ident::new(
215 if ident == "Void" { "__Void" } else { "Void" },
216 Span::call_site(),
217 );
218
219 let type_param = Ident::new(
220 if ident == "TypeParam" {
221 "__TypeParam"
222 } else {
223 "TypeParam"
224 },
225 Span::call_site(),
226 );
227
228 let mut generics = input.generics;
229 let where_clause = generics.where_clause.take();
230 let mut impl_generics = Vec::new();
231 let mut ty_generics = Vec::new();
232 let mut phantoms = Vec::new();
233 for param in &mut generics.params {
234 match param {
235 GenericParam::Type(param) => {
236 let ident = &param.ident;
237 let elem = quote!(#ident);
238 impl_generics.push(quote!(#ident: ?::core::marker::Sized));
239 ty_generics.push(quote!(#ident));
240 phantoms.push(variance::apply(param, elem, &type_param));
241 }
242 GenericParam::Lifetime(param) => {
243 let lifetime = &param.lifetime;
244 let elem = quote!(&#lifetime ());
245 impl_generics.push(quote!(#lifetime));
246 ty_generics.push(quote!(#lifetime));
247 phantoms.push(variance::apply(param, elem, &type_param));
248 }
249 GenericParam::Const(param) => {
250 let msg = "const generics are not supported";
251 let err = Error::new_spanned(param, msg);
252 return err.to_compile_error().into();
253 }
254 }
255 }
256
257 let impl_generics = &impl_generics;
258 let ty_generics = &ty_generics;
259 let enum_token = Token![enum](input.struct_token.span);
260 let struct_token = input.struct_token;
261
262 TokenStream::from(quote! {
263 #[cfg(not(doc))]
264 mod #void_namespace {
265 enum #void {}
266 impl ::core::marker::Copy for #void {}
267 #[allow(clippy::expl_impl_clone_on_copy)]
268 impl ::core::clone::Clone for #void {
269 fn clone(&self) -> Self {
270 match *self {}
271 }
272 }
273
274 #[repr(C, packed)]
275 struct #type_param<T: ?::core::marker::Sized>([*const T; 0]);
276 impl<T: ?::core::marker::Sized> ::core::marker::Copy for #type_param<T> {}
277 #[allow(clippy::expl_impl_clone_on_copy)]
278 impl<T: ?::core::marker::Sized> ::core::clone::Clone for #type_param<T> {
279 fn clone(&self) -> Self {
280 *self
281 }
282 }
283 unsafe impl<T: ?::core::marker::Sized + ::core::marker::Send> ::core::marker::Send for #type_param<T> {}
284 unsafe impl<T: ?::core::marker::Sized + ::core::marker::Sync> ::core::marker::Sync for #type_param<T> {}
285
286 #[allow(non_camel_case_types)]
287 #vis_super struct #ident <#(#impl_generics),*> (
288 #(
289 self::#type_param<#phantoms>,
290 )*
291 self::#void,
292 );
293
294 impl <#(#impl_generics),*> ::core::marker::Copy
295 for #ident <#(#ty_generics),*> {}
296
297 #[allow(clippy::expl_impl_clone_on_copy)]
298 impl <#(#impl_generics),*> ::core::clone::Clone
299 for #ident <#(#ty_generics),*> {
300 fn clone(&self) -> Self {
301 *self
302 }
303 }
304 }
305
306 #[cfg(not(doc))]
307 mod #value_namespace {
308 #vis_super use super::#ident::#ident;
309 }
310
311 #[cfg(not(doc))]
312 #(#attrs)*
313 #vis #enum_token #ident #generics #where_clause {
314 __Phantom(#void_namespace::#ident <#(#ty_generics),*>),
315 #ident,
316 }
317
318 #[cfg(not(doc))]
319 #[doc(hidden)]
320 #vis use self::#value_namespace::*;
321
322 #[cfg(doc)]
323 #(#attrs)*
324 #vis #struct_token #ident #generics #where_clause;
325
326 #derives
327 })
328 }