ghost-0.1.5/.cargo_vcs_info.json0000644000000001360000000000100121630ustar { "git": { "sha1": "2d44fd27eca825ca18ded3fa3f3e8c5677e25926" }, "path_in_vcs": "" }ghost-0.1.5/.clippy.toml000064400000000000000000000000201046102023000132160ustar 00000000000000msrv = "1.31.0" ghost-0.1.5/.github/workflows/ci.yml000064400000000000000000000024741046102023000154750ustar 00000000000000name: CI on: push: pull_request: schedule: [cron: "40 1 * * *"] env: RUSTFLAGS: -Dwarnings jobs: test: name: Rust ${{matrix.rust}} runs-on: ubuntu-latest strategy: fail-fast: false matrix: rust: [nightly, beta, stable, 1.36.0] steps: - uses: actions/checkout@v3 - uses: dtolnay/rust-toolchain@master with: toolchain: ${{matrix.rust}} - run: cargo test msrv: name: Rust 1.31.0 runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: dtolnay/rust-toolchain@1.31.0 - run: cargo check miri: name: Miri runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: dtolnay/rust-toolchain@miri - run: cargo miri test env: MIRIFLAGS: -Zmiri-strict-provenance clippy: name: Clippy runs-on: ubuntu-latest if: github.event_name != 'pull_request' steps: - uses: actions/checkout@v3 - uses: dtolnay/rust-toolchain@clippy - run: cargo clippy --tests -- -Dclippy::all -Dclippy::pedantic outdated: name: Outdated runs-on: ubuntu-latest if: github.event_name != 'pull_request' steps: - uses: actions/checkout@v3 - uses: dtolnay/install@cargo-outdated - run: cargo outdated --workspace --exit-code 1 ghost-0.1.5/.gitignore000064400000000000000000000000361046102023000127420ustar 00000000000000/target **/*.rs.bk Cargo.lock ghost-0.1.5/Cargo.toml0000644000000021160000000000100101610ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2018" rust-version = "1.31" name = "ghost" version = "0.1.5" authors = ["David Tolnay "] description = "Define your own PhantomData" documentation = "https://docs.rs/ghost" readme = "README.md" license = "MIT OR Apache-2.0" repository = "https://github.com/dtolnay/ghost" [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [lib] proc-macro = true [dependencies.proc-macro2] version = "1.0" [dependencies.quote] version = "1.0" [dependencies.syn] version = "1.0" [dev-dependencies.rustversion] version = "1.0" [dev-dependencies.trybuild] version = "1.0" features = ["diff"] ghost-0.1.5/Cargo.toml.orig000064400000000000000000000010561046102023000136440ustar 00000000000000[package] name = "ghost" version = "0.1.5" authors = ["David Tolnay "] license = "MIT OR Apache-2.0" description = "Define your own PhantomData" repository = "https://github.com/dtolnay/ghost" documentation = "https://docs.rs/ghost" readme = "README.md" edition = "2018" rust-version = "1.31" [lib] proc-macro = true [dependencies] proc-macro2 = "1.0" quote = "1.0" syn = "1.0" [dev-dependencies] rustversion = "1.0" trybuild = { version = "1.0", features = ["diff"] } [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] ghost-0.1.5/LICENSE-APACHE000064400000000000000000000251371046102023000127070ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ghost-0.1.5/LICENSE-MIT000064400000000000000000000017771046102023000124230ustar 00000000000000Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ghost-0.1.5/README.md000064400000000000000000000112011046102023000122250ustar 00000000000000## Define your own PhantomData [github](https://github.com/dtolnay/ghost) [crates.io](https://crates.io/crates/ghost) [docs.rs](https://docs.rs/ghost) [build status](https://github.com/dtolnay/ghost/actions?query=branch%3Amaster) This crate makes it possible to define your own PhantomData and similarly behaved unit types with generic parameters, which is not permitted in ordinary Rust. ```toml [dependencies] ghost = "0.1" ``` *Supports rustc 1.31+* ### Background [`PhantomData`] as defined by the Rust standard library is magical in that the same type is impossible to define in ordinary Rust code. It is defined in the standard library like this: [`PhantomData`]: https://doc.rust-lang.org/std/marker/struct.PhantomData.html ```rust #[lang = "phantom_data"] pub struct PhantomData; ``` The `#[lang = "..."]` attribute indicates that this is a [lang item], a special case known to the compiler. It is the only type permitted to carry an unused type parameter. [lang item]: https://manishearth.github.io/blog/2017/01/11/rust-tidbits-what-is-a-lang-item/ If we try to define an equivalent unit struct with type parameter, the compiler rejects that. ```rust struct MyPhantom; ``` ```console error[E0392]: parameter `T` is never used --> src/main.rs:1:18 | 1 | struct MyPhantom; | ^ unused type parameter | = help: consider removing `T` or using a marker such as `std::marker::PhantomData` ``` This crate provides a `#[phantom]` attribute that makes it possible to define unit structs with generic parameters. ### Examples ```rust use ghost::phantom; #[phantom] struct MyPhantom; fn main() { // Proof that MyPhantom behaves like PhantomData. let _: MyPhantom = MyPhantom::; assert_eq!(0, std::mem::size_of::>()); } // Proof that MyPhantom is not just a re-export of PhantomData. // If it were a re-export, these would be conflicting impls. trait Trait {} impl Trait for std::marker::PhantomData {} impl Trait for MyPhantom {} // Proof that MyPhantom is local to the current crate. impl MyPhantom { } ``` The implementation accepts where-clauses, lifetimes, multiple generic parameters, and derives. Here is a contrived invocation that demonstrates everything at once: ```rust use ghost::phantom; #[phantom] #[derive(Copy, Clone, Default, Hash, PartialOrd, Ord, PartialEq, Eq, Debug)] struct Crazy<'a, V: 'a, T> where &'a V: IntoIterator; fn main() { let _ = Crazy::<'static, Vec, &'static String>; // Lifetime elision. let crazy = Crazy::, &String>; println!("{:?}", crazy); } ``` ### Variance The `#[phantom]` attribute accepts attributes on individual generic parameters (both lifetime and type parameters) to make them contravariant or invariant. The default is covariance. - `#[contra]` — contravariant generic parameter - `#[invariant]` — invariant generic parameter The implications of variance are explained in more detail by the [Subtyping chapter] of the Rustonomicon. [Subtyping chapter]: https://doc.rust-lang.org/nomicon/subtyping.html ```rust use ghost::phantom; #[phantom] struct ContravariantLifetime<#[contra] 'a>; fn f<'a>(arg: ContravariantLifetime<'a>) -> ContravariantLifetime<'static> { // This coercion is only legal because the lifetime parameter is // contravariant. If it were covariant (the default) or invariant, // this would not compile. arg } #[phantom] struct Demo; ``` ### Use cases Entirely up to your imagination. Just to name one, how about a typed registry library that admits the following syntax for iterating over values registered of a particular type: ```rust for flag in Registry:: { /* ... */ } ```
#### License Licensed under either of Apache License, Version 2.0 or MIT license at your option.
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in this crate by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. ghost-0.1.5/src/derive.rs000064400000000000000000000146651046102023000134020ustar 00000000000000use proc_macro2::TokenStream; use quote::quote; use syn::parse::{Parse, ParseStream, Parser}; use syn::punctuated::Punctuated; use syn::{parenthesized, Attribute, Error, Path, Result, Token}; use crate::parse::UnitStruct; enum Derive { Copy, Clone, Default, Hash, PartialOrd, Ord, PartialEq, Eq, Debug, } struct DeriveList { derives: Vec, } impl Parse for DeriveList { fn parse(input: ParseStream) -> Result { let content; parenthesized!(content in input); let paths: Punctuated = content.parse_terminated(Path::parse_mod_style)?; let mut derives = Vec::new(); for path in paths { if path.is_ident("Copy") { derives.push(Derive::Copy); } else if path.is_ident("Clone") { derives.push(Derive::Clone); } else if path.is_ident("Default") { derives.push(Derive::Default); } else if path.is_ident("Hash") { derives.push(Derive::Hash); } else if path.is_ident("PartialOrd") { derives.push(Derive::PartialOrd); } else if path.is_ident("Ord") { derives.push(Derive::Ord); } else if path.is_ident("PartialEq") { derives.push(Derive::PartialEq); } else if path.is_ident("Eq") { derives.push(Derive::Eq); } else if path.is_ident("Debug") { derives.push(Derive::Debug); } else { return Err(Error::new_spanned(path, "unsupported derive")); } } Ok(DeriveList { derives }) } } pub fn expand<'a>( attrs: &'a [Attribute], input: &UnitStruct, ) -> Result<(TokenStream, Vec<&'a Attribute>)> { let mut expanded = TokenStream::new(); let mut non_derives = Vec::new(); for attr in attrs { if attr.path.is_ident("derive") { let list = DeriveList::parse.parse2(attr.tokens.clone())?; for derive in list.derives { expanded.extend(apply(derive, input)); } } else { non_derives.push(attr); } } Ok((expanded, non_derives)) } fn apply(derive: Derive, input: &UnitStruct) -> TokenStream { match derive { Derive::Copy => expand_copy(input), Derive::Clone => expand_clone(input), Derive::Default => expand_default(input), Derive::Hash => expand_hash(input), Derive::PartialOrd => expand_partialord(input), Derive::Ord => expand_ord(input), Derive::PartialEq => expand_partialeq(input), Derive::Eq => expand_eq(input), Derive::Debug => expand_debug(input), } } fn expand_copy(input: &UnitStruct) -> TokenStream { let ident = &input.ident; let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl(); quote! { impl #impl_generics ::core::marker::Copy for #ident #ty_generics #where_clause {} } } fn expand_clone(input: &UnitStruct) -> TokenStream { let ident = &input.ident; let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl(); quote! { #[allow(clippy::expl_impl_clone_on_copy)] impl #impl_generics ::core::clone::Clone for #ident #ty_generics #where_clause { #[inline] fn clone(&self) -> Self { #ident } } } } fn expand_default(input: &UnitStruct) -> TokenStream { let ident = &input.ident; let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl(); quote! { impl #impl_generics ::core::default::Default for #ident #ty_generics #where_clause { #[inline] fn default() -> Self { #ident } } } } fn expand_hash(input: &UnitStruct) -> TokenStream { let ident = &input.ident; let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl(); quote! { impl #impl_generics ::core::hash::Hash for #ident #ty_generics #where_clause { #[inline] fn hash(&self, hasher: &mut H) { let _ = hasher; } } } } fn expand_partialord(input: &UnitStruct) -> TokenStream { let ident = &input.ident; let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl(); quote! { impl #impl_generics ::core::cmp::PartialOrd for #ident #ty_generics #where_clause { #[inline] fn partial_cmp(&self, other: &Self) -> ::core::option::Option<::core::cmp::Ordering> { let _ = other; ::core::option::Option::Some(::core::cmp::Ordering::Equal) } } } } fn expand_ord(input: &UnitStruct) -> TokenStream { let ident = &input.ident; let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl(); quote! { impl #impl_generics ::core::cmp::Ord for #ident #ty_generics #where_clause { #[inline] fn cmp(&self, other: &Self) -> ::core::cmp::Ordering { let _ = other; ::core::cmp::Ordering::Equal } } } } fn expand_partialeq(input: &UnitStruct) -> TokenStream { let ident = &input.ident; let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl(); quote! { impl #impl_generics ::core::cmp::PartialEq for #ident #ty_generics #where_clause { #[inline] fn eq(&self, other: &Self) -> bool { let _ = other; true } } } } fn expand_eq(input: &UnitStruct) -> TokenStream { let ident = &input.ident; let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl(); quote! { impl #impl_generics ::core::cmp::Eq for #ident #ty_generics #where_clause {} } } fn expand_debug(input: &UnitStruct) -> TokenStream { let ident = &input.ident; let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl(); let string = ident.to_string(); quote! { impl #impl_generics ::core::fmt::Debug for #ident #ty_generics #where_clause { fn fmt(&self, formatter: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { ::core::fmt::Formatter::write_str(formatter, #string) } } } } ghost-0.1.5/src/lib.rs000064400000000000000000000237261046102023000126700ustar 00000000000000//! [![github]](https://github.com/dtolnay/ghost) [![crates-io]](https://crates.io/crates/ghost) [![docs-rs]](https://docs.rs/ghost) //! //! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github //! [crates-io]: https://img.shields.io/badge/crates.io-fc8d62?style=for-the-badge&labelColor=555555&logo=rust //! [docs-rs]: https://img.shields.io/badge/docs.rs-66c2a5?style=for-the-badge&labelColor=555555&logo=docs.rs //! //!
//! //! **Define your own PhantomData and similarly behaved unit types.** //! //! # Background //! //! [`PhantomData`] as defined by the Rust standard library is magical in that //! the same type is impossible to define in ordinary Rust code. It is defined //! in the standard library like this: //! //! [`PhantomData`]: https://doc.rust-lang.org/std/marker/struct.PhantomData.html //! //! ``` //! # const IGNORE: &str = stringify! { //! #[lang = "phantom_data"] //! pub struct PhantomData; //! # }; //! ``` //! //! The `#[lang = "..."]` attribute indicates that this is a [lang item], a //! special case known to the compiler. It is the only type permitted to carry //! an unused type parameter. //! //! [lang item]: https://manishearth.github.io/blog/2017/01/11/rust-tidbits-what-is-a-lang-item/ //! //! If we try to define an equivalent unit struct with type parameter, the //! compiler rejects that. //! //! ```compile_fail //! struct MyPhantom; //! ``` //! //! ```text //! error[E0392]: parameter `T` is never used //! --> src/main.rs:1:18 //! | //! 1 | struct MyPhantom; //! | ^ unused type parameter //! | //! = help: consider removing `T` or using a marker such as `std::marker::PhantomData` //! ``` //! //! This crate provides a `#[phantom]` attribute that makes it possible to //! define unit structs with generic parameters. //! //! # Examples //! //! ``` //! use ghost::phantom; //! //! #[phantom] //! struct MyPhantom; //! //! fn main() { //! // Proof that MyPhantom behaves like PhantomData. //! let _: MyPhantom = MyPhantom::; //! assert_eq!(0, std::mem::size_of::>()); //! } //! //! // Proof that MyPhantom is not just a re-export of PhantomData. //! // If it were a re-export, these would be conflicting impls. //! trait Trait {} //! impl Trait for std::marker::PhantomData {} //! impl Trait for MyPhantom {} //! //! // Proof that MyPhantom is local to the current crate. //! impl MyPhantom { //! } //! ``` //! //! The implementation accepts where-clauses, lifetimes, multiple generic //! parameters, and derives. Here is a contrived invocation that demonstrates //! everything at once: //! //! ``` //! use ghost::phantom; //! //! #[phantom] //! #[derive(Copy, Clone, Default, Hash, PartialOrd, Ord, PartialEq, Eq, Debug)] //! struct Crazy<'a, V: 'a, T> where &'a V: IntoIterator; //! //! fn main() { //! let _ = Crazy::<'static, Vec, &'static String>; //! //! // Lifetime elision. //! let crazy = Crazy::, &String>; //! println!("{:?}", crazy); //! } //! ``` //! //! # Variance //! //! The `#[phantom]` attribute accepts attributes on individual generic //! parameters (both lifetime and type parameters) to make them contravariant or //! invariant. The default is covariance. //! //! - `#[contra]` — contravariant generic parameter //! - `#[invariant]` — invariant generic parameter //! //! The implications of variance are explained in more detail by the [Subtyping //! chapter] of the Rustonomicon. //! //! [Subtyping chapter]: https://doc.rust-lang.org/nomicon/subtyping.html //! //! ``` //! use ghost::phantom; //! //! #[phantom] //! struct ContravariantLifetime<#[contra] 'a>; //! //! fn f<'a>(arg: ContravariantLifetime<'a>) -> ContravariantLifetime<'static> { //! // This coercion is only legal because the lifetime parameter is //! // contravariant. If it were covariant (the default) or invariant, //! // this would not compile. //! arg //! } //! //! #[phantom] //! struct Demo; //! # //! # fn main() {} //! ``` //! //! # Use cases //! //! Entirely up to your imagination. Just to name one, how about a typed //! registry library that admits the following syntax for iterating over values //! registered of a particular type: //! //! ```no_run //! # use ghost::phantom; //! # //! # #[phantom] //! # struct Registry; //! # //! # impl IntoIterator for Registry { //! # type Item = T; //! # type IntoIter = Iter; //! # fn into_iter(self) -> Self::IntoIter { //! # unimplemented!() //! # } //! # } //! # //! # struct Iter(T); //! # //! # impl Iterator for Iter { //! # type Item = T; //! # fn next(&mut self) -> Option { //! # unimplemented!() //! # } //! # } //! # //! # struct Flag; //! # //! # fn main() { //! for flag in Registry:: { //! /* ... */ //! } //! # } //! ``` #![allow( clippy::doc_markdown, // https://github.com/rust-lang/rust-clippy/issues/8538 clippy::iter_with_drain, clippy::needless_doctest_main, clippy::needless_pass_by_value, clippy::too_many_lines )] extern crate proc_macro; mod derive; mod parse; mod variance; mod visibility; use proc_macro::TokenStream; use proc_macro2::{Ident, Span}; use quote::quote; use syn::parse::Nothing; use syn::{parse_macro_input, Error, GenericParam, Token}; use crate::parse::UnitStruct; /// Define your own PhantomData and similarly behaved unit types. /// /// Please refer to the [crate level documentation](index.html) for explanation /// and examples. #[proc_macro_attribute] pub fn phantom(args: TokenStream, input: TokenStream) -> TokenStream { parse_macro_input!(args as Nothing); let input = parse_macro_input!(input as UnitStruct); let ident = &input.ident; let call_site = Span::call_site(); let void_namespace = Ident::new(&format!("__void_{}", ident), call_site); let value_namespace = Ident::new(&format!("__value_{}", ident), call_site); let vis = &input.vis; let vis_super = visibility::vis_super(vis); let (derives, attrs) = match derive::expand(&input.attrs, &input) { Ok(split) => split, Err(err) => return err.to_compile_error().into(), }; let void = Ident::new( if ident == "Void" { "__Void" } else { "Void" }, Span::call_site(), ); let type_param = Ident::new( if ident == "TypeParam" { "__TypeParam" } else { "TypeParam" }, Span::call_site(), ); let mut generics = input.generics; let where_clause = generics.where_clause.take(); let mut impl_generics = Vec::new(); let mut ty_generics = Vec::new(); let mut phantoms = Vec::new(); for param in &mut generics.params { match param { GenericParam::Type(param) => { let ident = ¶m.ident; let elem = quote!(#ident); impl_generics.push(quote!(#ident: ?::core::marker::Sized)); ty_generics.push(quote!(#ident)); phantoms.push(variance::apply(param, elem, &type_param)); } GenericParam::Lifetime(param) => { let lifetime = ¶m.lifetime; let elem = quote!(&#lifetime ()); impl_generics.push(quote!(#lifetime)); ty_generics.push(quote!(#lifetime)); phantoms.push(variance::apply(param, elem, &type_param)); } GenericParam::Const(param) => { let msg = "const generics are not supported"; let err = Error::new_spanned(param, msg); return err.to_compile_error().into(); } } } let impl_generics = &impl_generics; let ty_generics = &ty_generics; let enum_token = Token![enum](input.struct_token.span); let struct_token = input.struct_token; TokenStream::from(quote! { #[cfg(not(doc))] mod #void_namespace { enum #void {} impl ::core::marker::Copy for #void {} #[allow(clippy::expl_impl_clone_on_copy)] impl ::core::clone::Clone for #void { fn clone(&self) -> Self { match *self {} } } #[repr(C, packed)] struct #type_param([*const T; 0]); impl ::core::marker::Copy for #type_param {} #[allow(clippy::expl_impl_clone_on_copy)] impl ::core::clone::Clone for #type_param { fn clone(&self) -> Self { *self } } unsafe impl ::core::marker::Send for #type_param {} unsafe impl ::core::marker::Sync for #type_param {} #[allow(non_camel_case_types)] #vis_super struct #ident <#(#impl_generics),*> ( #( self::#type_param<#phantoms>, )* self::#void, ); impl <#(#impl_generics),*> ::core::marker::Copy for #ident <#(#ty_generics),*> {} #[allow(clippy::expl_impl_clone_on_copy)] impl <#(#impl_generics),*> ::core::clone::Clone for #ident <#(#ty_generics),*> { fn clone(&self) -> Self { *self } } } #[cfg(not(doc))] mod #value_namespace { #vis_super use super::#ident::#ident; } #[cfg(not(doc))] #(#attrs)* #vis #enum_token #ident #generics #where_clause { __Phantom(#void_namespace::#ident <#(#ty_generics),*>), #ident, } #[cfg(not(doc))] #[doc(hidden)] #vis use self::#value_namespace::*; #[cfg(doc)] #(#attrs)* #vis #struct_token #ident #generics #where_clause; #derives }) } ghost-0.1.5/src/parse.rs000064400000000000000000000020201046102023000132140ustar 00000000000000use syn::parse::{Parse, ParseStream, Result}; use syn::{Attribute, Generics, Ident, Token, Visibility, WhereClause}; pub struct UnitStruct { pub attrs: Vec, pub vis: Visibility, pub struct_token: Token![struct], pub ident: Ident, pub generics: Generics, } impl Parse for UnitStruct { fn parse(input: ParseStream) -> Result { let attrs = input.call(Attribute::parse_outer)?; let vis: Visibility = input.parse()?; let struct_token: Token![struct] = input.parse()?; let ident: Ident = input.parse()?; // Require there to be generics. input.fork().parse::()?; let generics: Generics = input.parse()?; let where_clause: Option = input.parse()?; input.parse::()?; Ok(UnitStruct { attrs, vis, struct_token, ident, generics: Generics { where_clause, ..generics }, }) } } ghost-0.1.5/src/variance.rs000064400000000000000000000025611046102023000137040ustar 00000000000000use proc_macro2::{Ident, TokenStream}; use quote::quote; use syn::{Attribute, LifetimeDef, TypeParam}; enum Variance { Covariant, Contravariant, Invariant, } pub trait HasVarianceAttribute { fn attrs(&mut self) -> &mut Vec; } impl HasVarianceAttribute for TypeParam { fn attrs(&mut self) -> &mut Vec { &mut self.attrs } } impl HasVarianceAttribute for LifetimeDef { fn attrs(&mut self) -> &mut Vec { &mut self.attrs } } pub fn apply( param: &mut dyn HasVarianceAttribute, base: TokenStream, type_param: &Ident, ) -> TokenStream { let mut variance = Variance::Covariant; let attrs = param.attrs(); *attrs = attrs .drain(..) .filter(|attr| { if attr.path.is_ident("contra") && attr.tokens.is_empty() { variance = Variance::Contravariant; false } else if attr.path.is_ident("invariant") && attr.tokens.is_empty() { variance = Variance::Invariant; false } else { true } }) .collect(); let phantom = quote!(self::#type_param<#base>); match variance { Variance::Covariant => base, Variance::Contravariant => quote!(fn(#phantom)), Variance::Invariant => quote!(fn(#phantom) -> #phantom), } } ghost-0.1.5/src/visibility.rs000064400000000000000000000036421046102023000143040ustar 00000000000000use syn::{parse_quote, Visibility}; // If `vis` describes a visibility relative to some module scope, returns the // same visibility as described from a module contained within that scope. // // quote! { // #vis #A; // mod #name { // // Same visibility as super::A. // #vis_super #B; // } // } // // Note if you are considering copying this implementation into another crate: // please try not to. Visibilities in Rust are confusing and subtle, especially // around visibility specifiers of items declared inside of a function body. // This function is not a robust implementation of the transformation that it // claims to implement. Always first try to restructure your code to avoid // needing this logic. pub fn vis_super(vis: &Visibility) -> Visibility { match vis { Visibility::Public(vis) => { // pub -> pub parse_quote!(#vis) } Visibility::Crate(vis) => { // crate -> crate parse_quote!(#vis) } Visibility::Restricted(vis) => { if vis.path.segments[0].ident == "self" { // pub(self) -> pub(in super) // pub(in self::super) -> pub(in super::super) let path = vis.path.segments.iter().skip(1); parse_quote!(pub(in super #(::#path)*)) } else if vis.path.segments[0].ident == "super" { // pub(super) -> pub(in super::super) // pub(in super::super) -> pub(in super::super::super) let path = &vis.path; parse_quote!(pub(in super::#path)) } else { // pub(crate) -> pub(crate) // pub(in crate::path) -> pub(in crate::path) parse_quote!(#vis) } } Visibility::Inherited => { // private -> pub(super) parse_quote!(pub(super)) } } } ghost-0.1.5/tests/autotraits.rs000064400000000000000000000004001046102023000146540ustar 00000000000000use ghost::phantom; #[phantom] pub struct MyPhantom; // Test that #[phantom] doesn't contain its own explicit autotrait impls, which // would conflict with the following. unsafe impl Send for MyPhantom {} unsafe impl Sync for MyPhantom {} ghost-0.1.5/tests/compiletest.rs000064400000000000000000000002461046102023000150150ustar 00000000000000#[rustversion::attr(not(nightly), ignore)] #[cfg_attr(miri, ignore)] #[test] fn ui() { let t = trybuild::TestCases::new(); t.compile_fail("tests/ui/*.rs"); } ghost-0.1.5/tests/readme.rs000064400000000000000000000020331046102023000137160ustar 00000000000000mod first { use ghost::phantom; #[phantom] struct MyPhantom; #[test] fn test() { // Proof that MyPhantom behaves like PhantomData. let _: MyPhantom = MyPhantom::; assert_eq!(0, std::mem::size_of::>()); } // Proof that MyPhantom is not just a re-export of PhantomData. // If it were a re-export, these would be conflicting impls. trait Trait {} impl Trait for std::marker::PhantomData {} impl Trait for MyPhantom {} // Proof that MyPhantom is local to the current crate. impl MyPhantom {} } mod second { use ghost::phantom; #[phantom] #[derive(Copy, Clone, Default, Hash, PartialOrd, Ord, PartialEq, Eq, Debug)] struct Crazy<'a, V: 'a, T> where &'a V: IntoIterator; #[test] fn test() { let _ = Crazy::<'static, Vec, &'static String>; // Lifetime elision. let crazy = Crazy::, &String>; println!("{:?}", crazy); } } ghost-0.1.5/tests/ui/autotraits.rs000064400000000000000000000005041046102023000152760ustar 00000000000000use ghost::phantom; #[phantom] struct MyPhantom; fn require_send() {} fn require_sync() {} fn main() { // ok require_send::>(); require_sync::>(); // not ok require_send::>(); require_sync::>(); } ghost-0.1.5/tests/ui/autotraits.stderr000064400000000000000000000043731046102023000161650ustar 00000000000000error[E0277]: `*const u8` cannot be sent between threads safely --> tests/ui/autotraits.rs:15:5 | 15 | require_send::>(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `*const u8` cannot be sent between threads safely | = help: the trait `Send` is not implemented for `*const u8` note: required because of the requirements on the impl of `Send` for `TypeParam<*const u8>` --> tests/ui/autotraits.rs:3:1 | 3 | #[phantom] | ^^^^^^^^^^ note: required because it appears within the type `__void_MyPhantom::MyPhantom<*const u8>` --> tests/ui/autotraits.rs:4:8 | 4 | struct MyPhantom; | ^^^^^^^^^ note: required because it appears within the type `MyPhantom<*const u8>` --> tests/ui/autotraits.rs:4:8 | 4 | struct MyPhantom; | ^^^^^^^^^ note: required by a bound in `require_send` --> tests/ui/autotraits.rs:6:20 | 6 | fn require_send() {} | ^^^^ required by this bound in `require_send` = note: this error originates in the attribute macro `phantom` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0277]: `*const u8` cannot be shared between threads safely --> tests/ui/autotraits.rs:16:5 | 16 | require_sync::>(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `*const u8` cannot be shared between threads safely | = help: the trait `Sync` is not implemented for `*const u8` note: required because of the requirements on the impl of `Sync` for `TypeParam<*const u8>` --> tests/ui/autotraits.rs:3:1 | 3 | #[phantom] | ^^^^^^^^^^ note: required because it appears within the type `__void_MyPhantom::MyPhantom<*const u8>` --> tests/ui/autotraits.rs:4:8 | 4 | struct MyPhantom; | ^^^^^^^^^ note: required because it appears within the type `MyPhantom<*const u8>` --> tests/ui/autotraits.rs:4:8 | 4 | struct MyPhantom; | ^^^^^^^^^ note: required by a bound in `require_sync` --> tests/ui/autotraits.rs:7:20 | 7 | fn require_sync() {} | ^^^^ required by this bound in `require_sync` = note: this error originates in the attribute macro `phantom` (in Nightly builds, run with -Z macro-backtrace for more info) ghost-0.1.5/tests/ui/contravariant.rs000064400000000000000000000005141046102023000157530ustar 00000000000000use ghost::phantom; #[phantom] struct ContravariantPhantom<#[contra] T>; fn require_covariant<'a>(phantom: ContravariantPhantom<&'static str>) -> ContravariantPhantom<&'a str> { phantom } fn require_contravariant<'a>(phantom: ContravariantPhantom<&'a str>) -> ContravariantPhantom<&'static str> { phantom } fn main() {} ghost-0.1.5/tests/ui/contravariant.stderr000064400000000000000000000005231046102023000166320ustar 00000000000000error: lifetime may not live long enough --> tests/ui/contravariant.rs:7:5 | 6 | fn require_covariant<'a>(phantom: ContravariantPhantom<&'static str>) -> ContravariantPhantom<&'a str> { | -- lifetime `'a` defined here 7 | phantom | ^^^^^^^ returning this value requires that `'a` must outlive `'static` ghost-0.1.5/tests/ui/covariant.rs000064400000000000000000000004561046102023000150730ustar 00000000000000use ghost::phantom; #[phantom] struct CovariantPhantom; fn require_covariant<'a>(phantom: CovariantPhantom<&'static str>) -> CovariantPhantom<&'a str> { phantom } fn require_contravariant<'a>(phantom: CovariantPhantom<&'a str>) -> CovariantPhantom<&'static str> { phantom } fn main() {} ghost-0.1.5/tests/ui/covariant.stderr000064400000000000000000000005261046102023000157500ustar 00000000000000error: lifetime may not live long enough --> tests/ui/covariant.rs:11:5 | 10 | fn require_contravariant<'a>(phantom: CovariantPhantom<&'a str>) -> CovariantPhantom<&'static str> { | -- lifetime `'a` defined here 11 | phantom | ^^^^^^^ returning this value requires that `'a` must outlive `'static` ghost-0.1.5/tests/ui/ffi.rs000064400000000000000000000002501046102023000136410ustar 00000000000000#![deny(improper_ctypes_definitions)] use ghost::phantom; #[phantom] pub struct MyPhantom; pub extern "C" fn extern_fn(_phantom: MyPhantom) {} fn main() {} ghost-0.1.5/tests/ui/ffi.stderr000064400000000000000000000013651046102023000145300ustar 00000000000000error: `extern` fn uses type `MyPhantom`, which is not FFI-safe --> tests/ui/ffi.rs:8:39 | 8 | pub extern "C" fn extern_fn(_phantom: MyPhantom) {} | ^^^^^^^^^^^^^^ not FFI-safe | note: the lint level is defined here --> tests/ui/ffi.rs:1:9 | 1 | #![deny(improper_ctypes_definitions)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ = help: consider adding a `#[repr(C)]`, `#[repr(transparent)]`, or integer `#[repr(...)]` attribute to this enum = note: enum has no representation hint note: the type is defined here --> tests/ui/ffi.rs:5:1 | 5 | #[phantom] | ^^^^^^^^^^ = note: this error originates in the attribute macro `phantom` (in Nightly builds, run with -Z macro-backtrace for more info) ghost-0.1.5/tests/ui/function-body.rs000064400000000000000000000002241046102023000156560ustar 00000000000000use ghost::phantom; fn main() { // Not supported. https://github.com/dtolnay/ghost/issues/1 #[phantom] struct MyPhantom; } ghost-0.1.5/tests/ui/function-body.stderr000064400000000000000000000007641046102023000165460ustar 00000000000000error[E0432]: unresolved import `super::MyPhantom` --> tests/ui/function-body.rs:7:12 | 7 | struct MyPhantom; | ^^^^^^^^^ could not find `MyPhantom` in the crate root error[E0432]: unresolved import `self` --> tests/ui/function-body.rs:6:5 | 6 | #[phantom] | ^^^^^^^^^^ could not find `__value_MyPhantom` in the crate root | = note: this error originates in the attribute macro `phantom` (in Nightly builds, run with -Z macro-backtrace for more info) ghost-0.1.5/tests/ui/invariant.rs000064400000000000000000000004731046102023000150770ustar 00000000000000use ghost::phantom; #[phantom] struct InvariantPhantom<#[invariant] T>; fn require_covariant<'a>(phantom: InvariantPhantom<&'static str>) -> InvariantPhantom<&'a str> { phantom } fn require_contravariant<'a>(phantom: InvariantPhantom<&'a str>) -> InvariantPhantom<&'static str> { phantom } fn main() {} ghost-0.1.5/tests/ui/invariant.stderr000064400000000000000000000024101046102023000157470ustar 00000000000000error: lifetime may not live long enough --> tests/ui/invariant.rs:7:5 | 6 | fn require_covariant<'a>(phantom: InvariantPhantom<&'static str>) -> InvariantPhantom<&'a str> { | -- lifetime `'a` defined here 7 | phantom | ^^^^^^^ returning this value requires that `'a` must outlive `'static` | = note: requirement occurs because of the type `InvariantPhantom<&str>`, which makes the generic argument `&str` invariant = note: the enum `InvariantPhantom` is invariant over the parameter `T` = help: see for more information about variance error: lifetime may not live long enough --> tests/ui/invariant.rs:11:5 | 10 | fn require_contravariant<'a>(phantom: InvariantPhantom<&'a str>) -> InvariantPhantom<&'static str> { | -- lifetime `'a` defined here 11 | phantom | ^^^^^^^ returning this value requires that `'a` must outlive `'static` | = note: requirement occurs because of the type `InvariantPhantom<&str>`, which makes the generic argument `&str` invariant = note: the enum `InvariantPhantom` is invariant over the parameter `T` = help: see for more information about variance ghost-0.1.5/tests/ui/pattern-match.rs000064400000000000000000000003331046102023000156460ustar 00000000000000use ghost::phantom; #[phantom] struct MyPhantom; fn main() { let phantom = MyPhantom::; match phantom { MyPhantom => {} } match phantom { MyPhantom:: => {} } } ghost-0.1.5/tests/ui/pattern-match.stderr000064400000000000000000000027631046102023000165360ustar 00000000000000error[E0004]: non-exhaustive patterns: `__Phantom(_)` not covered --> tests/ui/pattern-match.rs:9:11 | 9 | match phantom { | ^^^^^^^ pattern `__Phantom(_)` not covered | note: `MyPhantom` defined here --> tests/ui/pattern-match.rs:3:1 | 3 | #[phantom] | ^^^^^^^^^^ not covered 4 | struct MyPhantom; | --------- = note: the matched value is of type `MyPhantom` = note: this error originates in the attribute macro `phantom` (in Nightly builds, run with -Z macro-backtrace for more info) help: ensure that all possible cases are being handled by adding a match arm with a wildcard pattern or an explicit pattern as shown | 10~ MyPhantom => {} 11+ __Phantom(_) => todo!() | error[E0004]: non-exhaustive patterns: `__Phantom(_)` not covered --> tests/ui/pattern-match.rs:13:11 | 13 | match phantom { | ^^^^^^^ pattern `__Phantom(_)` not covered | note: `MyPhantom` defined here --> tests/ui/pattern-match.rs:3:1 | 3 | #[phantom] | ^^^^^^^^^^ not covered 4 | struct MyPhantom; | --------- = note: the matched value is of type `MyPhantom` = note: this error originates in the attribute macro `phantom` (in Nightly builds, run with -Z macro-backtrace for more info) help: ensure that all possible cases are being handled by adding a match arm with a wildcard pattern or an explicit pattern as shown | 14 ~ MyPhantom:: => {} 15 + __Phantom(_) => todo!() |