| 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_macrorust-analyzer cargo ghost 0.1.5 proc_macro/; |
| 178 | |
| 179 | mod deriverust-analyzer cargo ghost 0.1.5 derive/; |
| 180 | mod parserust-analyzer cargo ghost 0.1.5 parse/; |
| 181 | mod variancerust-analyzer cargo ghost 0.1.5 variance/; |
| 182 | mod visibilityrust-analyzer cargo ghost 0.1.5 visibility/; |
| 183 | |
| 184 | use proc_macrorust-analyzer cargo proc_macro https://github.com/rust-lang/rust/library/proc_macro crate/::TokenStreamrust-analyzer cargo proc_macro https://github.com/rust-lang/rust/library/proc_macro TokenStream#; |
| 185 | use proc_macro2rust-analyzer cargo proc-macro2 1.0.107 crate/::{Identrust-analyzer cargo proc-macro2 1.0.107 Ident#, Spanrust-analyzer cargo proc-macro2 1.0.107 Span#}; |
| 186 | use quoterust-analyzer cargo quote 1.0.47 crate/::quoterust-analyzer cargo quote 1.0.47 quote!; |
| 187 | use synrust-analyzer cargo syn 1.0.109 crate/::parserust-analyzer cargo syn 1.0.109 parse/::Nothingrust-analyzer cargo syn 1.0.109 parse/Nothing#; |
| 188 | use synrust-analyzer cargo syn 1.0.109 crate/::{parse_macro_inputrust-analyzer cargo syn 1.0.109 parse_macro_input/, Errorrust-analyzer cargo syn 1.0.109 error/Error#, GenericParamrust-analyzer cargo syn 1.0.109 generics/GenericParam#, Tokenrust-analyzer cargo syn 1.0.109 token/Token!}; |
| 189 | |
| 190 | use craterust-analyzer cargo ghost 0.1.5 crate/::parserust-analyzer cargo ghost 0.1.5 parse/::UnitStructrust-analyzer cargo ghost 0.1.5 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 phantomrust-analyzer cargo ghost 0.1.5 phantom:(args: TokenStreamrust-analyzer cargo proc_macro https://github.com/rust-lang/rust/library/proc_macro TokenStream#, input: TokenStreamrust-analyzer cargo proc_macro https://github.com/rust-lang/rust/library/proc_macro TokenStream#) -> TokenStreamrust-analyzer cargo proc_macro https://github.com/rust-lang/rust/library/proc_macro TokenStream# { |
| 198 | parse_macro_inputrust-analyzer cargo syn 1.0.109 parse_macro_input/parse_macro_input!!(args as Nothingrust-analyzer cargo syn 1.0.109 parse/Nothing#); |
| 199 | let input = parse_macro_inputrust-analyzer cargo syn 1.0.109 parse_macro_input/parse_macro_input!!(input as UnitStructrust-analyzer cargo ghost 0.1.5 parse/UnitStruct#); |
| 200 | |
| 201 | let ident = &input.identrust-analyzer cargo ghost 0.1.5 parse/UnitStruct#ident.; |
| 202 | let call_site = Spanrust-analyzer cargo proc-macro2 1.0.107 Span#::call_siterust-analyzer cargo proc-macro2 1.0.107 impl#[Span]call_site().(); |
| 203 | let void_namespace = Identrust-analyzer cargo proc-macro2 1.0.107 Ident#::newrust-analyzer cargo proc-macro2 1.0.107 impl#[Ident]new().(&formatrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc macros/format!!("__void_{}", ident), call_site); |
| 204 | let value_namespace = Identrust-analyzer cargo proc-macro2 1.0.107 Ident#::newrust-analyzer cargo proc-macro2 1.0.107 impl#[Ident]new().(&formatrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc macros/format!!("__value_{}", ident), call_site); |
| 205 | |
| 206 | let vis = &input.visrust-analyzer cargo ghost 0.1.5 parse/UnitStruct#vis.; |
| 207 | let vis_super = visibilityrust-analyzer cargo ghost 0.1.5 visibility/::vis_superrust-analyzer cargo ghost 0.1.5 visibility/vis_super().(vis); |
| 208 | |
| 209 | let (derives, attrs) = match deriverust-analyzer cargo ghost 0.1.5 derive/::expandrust-analyzer cargo ghost 0.1.5 derive/expand().(&input.attrsrust-analyzer cargo ghost 0.1.5 parse/UnitStruct#attrs., &input) { |
| 210 | Okrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#Ok#(split) => split, |
| 211 | Errrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#Err#(err) => return err.to_compile_errorrust-analyzer cargo syn 1.0.109 error/impl#[Error]to_compile_error().().intorust-analyzer cargo core https://github.com/rust-lang/rust/library/core convert/impl#[T][`Into<U>`]into().(), |
| 212 | }; |
| 213 | |
| 214 | let void = Identrust-analyzer cargo proc-macro2 1.0.107 Ident#::newrust-analyzer cargo proc-macro2 1.0.107 impl#[Ident]new().( |
| 215 | if ident rust-analyzer cargo core https://github.com/rust-lang/rust/library/core cmp/impls/impl#[`&A`][`PartialEq<&B>`]eq().==rust-analyzer cargo core https://github.com/rust-lang/rust/library/core cmp/impls/impl#[`&A`][`PartialEq<&B>`]eq(). rust-analyzer cargo core https://github.com/rust-lang/rust/library/core cmp/impls/impl#[`&A`][`PartialEq<&B>`]eq()."Void" { "__Void" } else { "Void" }, |
| 216 | Spanrust-analyzer cargo proc-macro2 1.0.107 Span#::call_siterust-analyzer cargo proc-macro2 1.0.107 impl#[Span]call_site().(), |
| 217 | ); |
| 218 | |
| 219 | let type_param = Identrust-analyzer cargo proc-macro2 1.0.107 Ident#::newrust-analyzer cargo proc-macro2 1.0.107 impl#[Ident]new().( |
| 220 | if ident rust-analyzer cargo core https://github.com/rust-lang/rust/library/core cmp/impls/impl#[`&A`][`PartialEq<&B>`]eq().==rust-analyzer cargo core https://github.com/rust-lang/rust/library/core cmp/impls/impl#[`&A`][`PartialEq<&B>`]eq(). rust-analyzer cargo core https://github.com/rust-lang/rust/library/core cmp/impls/impl#[`&A`][`PartialEq<&B>`]eq()."TypeParam" { |
| 221 | "__TypeParam" |
| 222 | } else { |
| 223 | "TypeParam" |
| 224 | }, |
| 225 | Spanrust-analyzer cargo proc-macro2 1.0.107 Span#::call_siterust-analyzer cargo proc-macro2 1.0.107 impl#[Span]call_site().(), |
| 226 | ); |
| 227 | |
| 228 | let mut generics = input.genericsrust-analyzer cargo ghost 0.1.5 parse/UnitStruct#generics.; |
| 229 | let where_clause = generics.where_clauserust-analyzer cargo syn 1.0.109 generics/Generics#where_clause..takerust-analyzer cargo core https://github.com/rust-lang/rust/library/core option/impl#[`Option<T>`]take().(); |
| 230 | let mut impl_generics = Vecrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc vec/Vec#::newrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc vec/impl#[`Vec<T>`]new().(); |
| 231 | let mut ty_generics = Vecrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc vec/Vec#::newrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc vec/impl#[`Vec<T>`]new().(); |
| 232 | let mut phantoms = Vecrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc vec/Vec#::newrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc vec/impl#[`Vec<T>`]new().(); |
| 233 | for param in &mut generics.paramsrust-analyzer cargo syn 1.0.109 generics/Generics#params. { |
| 234 | match param { |
| 235 | GenericParamrust-analyzer cargo syn 1.0.109 generics/GenericParam#::Typerust-analyzer cargo syn 1.0.109 generics/GenericParam#Type#(param) => { |
| 236 | let ident = ¶m.identrust-analyzer cargo syn 1.0.109 generics/TypeParam#ident.; |
| 237 | let elem = quoterust-analyzer cargo quote 1.0.47 quote!!(#ident); |
| 238 | impl_generics.pushrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc vec/impl#[`Vec<T, A>`]push().(quoterust-analyzer cargo quote 1.0.47 quote!!(#ident: ?::core::marker::Sized)); |
| 239 | ty_generics.pushrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc vec/impl#[`Vec<T, A>`]push().(quoterust-analyzer cargo quote 1.0.47 quote!!(#ident)); |
| 240 | phantoms.pushrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc vec/impl#[`Vec<T, A>`]push().(variancerust-analyzer cargo ghost 0.1.5 variance/::applyrust-analyzer cargo ghost 0.1.5 variance/apply().(param, elem, &type_param)); |
| 241 | } |
| 242 | GenericParamrust-analyzer cargo syn 1.0.109 generics/GenericParam#::Lifetimerust-analyzer cargo syn 1.0.109 generics/GenericParam#Lifetime#(param) => { |
| 243 | let lifetime = ¶m.lifetimerust-analyzer cargo syn 1.0.109 generics/LifetimeDef#lifetime.; |
| 244 | let elem = quoterust-analyzer cargo quote 1.0.47 quote!!(&#lifetime ()); |
| 245 | impl_generics.pushrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc vec/impl#[`Vec<T, A>`]push().(quoterust-analyzer cargo quote 1.0.47 quote!!(#lifetime)); |
| 246 | ty_generics.pushrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc vec/impl#[`Vec<T, A>`]push().(quoterust-analyzer cargo quote 1.0.47 quote!!(#lifetime)); |
| 247 | phantoms.pushrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc vec/impl#[`Vec<T, A>`]push().(variancerust-analyzer cargo ghost 0.1.5 variance/::applyrust-analyzer cargo ghost 0.1.5 variance/apply().(param, elem, &type_param)); |
| 248 | } |
| 249 | GenericParamrust-analyzer cargo syn 1.0.109 generics/GenericParam#::Construst-analyzer cargo syn 1.0.109 generics/GenericParam#Const#(param) => { |
| 250 | let msg = "const generics are not supported"; |
| 251 | let err = Errorrust-analyzer cargo syn 1.0.109 error/Error#::new_spannedrust-analyzer cargo syn 1.0.109 error/impl#[Error]new_spanned().(param, msg); |
| 252 | return err.to_compile_errorrust-analyzer cargo syn 1.0.109 error/impl#[Error]to_compile_error().().intorust-analyzer cargo core https://github.com/rust-lang/rust/library/core convert/impl#[T][`Into<U>`]into().(); |
| 253 | } |
| 254 | } |
| 255 | } |
| 256 | |
| 257 | let impl_generics = &impl_generics; |
| 258 | let ty_generics = &ty_generics; |
| 259 | let enum_token = Tokenrust-analyzer cargo syn 1.0.109 token/Token!; |
| 260 | let struct_token = input.struct_tokenrust-analyzer cargo ghost 0.1.5 parse/UnitStruct#struct_token.; |
| 261 | |
| 262 | TokenStreamrust-analyzer cargo proc_macro https://github.com/rust-lang/rust/library/proc_macro TokenStream#::fromrust-analyzer cargo proc-macro2 1.0.107 impl#[`proc_macro::TokenStream`][`From<TokenStream>`]from().(quoterust-analyzer cargo quote 1.0.47 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 | } |