├── .github ├── FUNDING.yml └── workflows │ └── ci.yml ├── .gitignore ├── tests ├── doc │ ├── src │ │ └── lib.rs │ └── Cargo.toml ├── ui │ ├── function-body.rs │ ├── ffi.rs │ ├── pattern-match.rs │ ├── contravariant.stderr │ ├── covariant.rs │ ├── covariant.stderr │ ├── invariant.rs │ ├── contravariant.rs │ ├── autotraits.rs │ ├── function-body.stderr │ ├── ffi.stderr │ ├── invariant.stderr │ ├── pattern-match.stderr │ └── autotraits.stderr ├── compiletest.rs ├── autotraits.rs ├── test.rs └── readme.rs ├── LICENSE-MIT ├── Cargo.toml ├── src ├── parse.rs ├── variance.rs ├── visibility.rs ├── derive.rs └── lib.rs ├── README.md └── LICENSE-APACHE /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: dtolnay 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | /Cargo.lock 3 | -------------------------------------------------------------------------------- /tests/doc/src/lib.rs: -------------------------------------------------------------------------------- 1 | use ghost::phantom; 2 | 3 | #[phantom] 4 | pub struct MyPhantom; 5 | -------------------------------------------------------------------------------- /tests/ui/function-body.rs: -------------------------------------------------------------------------------- 1 | use ghost::phantom; 2 | 3 | fn main() { 4 | // Not supported. https://github.com/dtolnay/ghost/issues/1 5 | 6 | #[phantom] 7 | struct MyPhantom; 8 | } 9 | -------------------------------------------------------------------------------- /tests/ui/ffi.rs: -------------------------------------------------------------------------------- 1 | #![deny(improper_ctypes_definitions)] 2 | 3 | use ghost::phantom; 4 | 5 | #[phantom] 6 | pub struct MyPhantom; 7 | 8 | pub extern "C" fn extern_fn(_phantom: MyPhantom) {} 9 | 10 | fn main() {} 11 | -------------------------------------------------------------------------------- /tests/doc/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "ghost-test-doc" 3 | version = "0.0.0" 4 | authors = ["David Tolnay "] 5 | edition = "2021" 6 | publish = false 7 | 8 | [dependencies] 9 | ghost = { path = "../.." } 10 | -------------------------------------------------------------------------------- /tests/compiletest.rs: -------------------------------------------------------------------------------- 1 | #[rustversion::attr(not(nightly), ignore = "requires nightly")] 2 | #[cfg_attr(miri, ignore = "incompatible with miri")] 3 | #[test] 4 | fn ui() { 5 | let t = trybuild::TestCases::new(); 6 | t.compile_fail("tests/ui/*.rs"); 7 | } 8 | -------------------------------------------------------------------------------- /tests/autotraits.rs: -------------------------------------------------------------------------------- 1 | use ghost::phantom; 2 | 3 | #[phantom] 4 | pub struct MyPhantom; 5 | 6 | // Test that #[phantom] doesn't contain its own explicit autotrait impls, which 7 | // would conflict with the following. 8 | unsafe impl Send for MyPhantom {} 9 | unsafe impl Sync for MyPhantom {} 10 | -------------------------------------------------------------------------------- /tests/ui/pattern-match.rs: -------------------------------------------------------------------------------- 1 | use ghost::phantom; 2 | 3 | #[phantom] 4 | struct MyPhantom; 5 | 6 | fn main() { 7 | let phantom = MyPhantom::; 8 | 9 | match phantom { 10 | MyPhantom => {} 11 | } 12 | 13 | match phantom { 14 | MyPhantom:: => {} 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /tests/ui/contravariant.stderr: -------------------------------------------------------------------------------- 1 | error: lifetime may not live long enough 2 | --> tests/ui/contravariant.rs:7:5 3 | | 4 | 6 | fn require_covariant<'a>(phantom: ContravariantPhantom<&'static str>) -> ContravariantPhantom<&'a str> { 5 | | -- lifetime `'a` defined here 6 | 7 | phantom 7 | | ^^^^^^^ returning this value requires that `'a` must outlive `'static` 8 | -------------------------------------------------------------------------------- /tests/ui/covariant.rs: -------------------------------------------------------------------------------- 1 | use ghost::phantom; 2 | 3 | #[phantom] 4 | struct CovariantPhantom; 5 | 6 | fn require_covariant<'a>(phantom: CovariantPhantom<&'static str>) -> CovariantPhantom<&'a str> { 7 | phantom 8 | } 9 | 10 | fn require_contravariant<'a>(phantom: CovariantPhantom<&'a str>) -> CovariantPhantom<&'static str> { 11 | phantom 12 | } 13 | 14 | fn main() {} 15 | -------------------------------------------------------------------------------- /tests/ui/covariant.stderr: -------------------------------------------------------------------------------- 1 | error: lifetime may not live long enough 2 | --> tests/ui/covariant.rs:11:5 3 | | 4 | 10 | fn require_contravariant<'a>(phantom: CovariantPhantom<&'a str>) -> CovariantPhantom<&'static str> { 5 | | -- lifetime `'a` defined here 6 | 11 | phantom 7 | | ^^^^^^^ returning this value requires that `'a` must outlive `'static` 8 | -------------------------------------------------------------------------------- /tests/ui/invariant.rs: -------------------------------------------------------------------------------- 1 | use ghost::phantom; 2 | 3 | #[phantom] 4 | struct InvariantPhantom<#[invariant] T>; 5 | 6 | fn require_covariant<'a>(phantom: InvariantPhantom<&'static str>) -> InvariantPhantom<&'a str> { 7 | phantom 8 | } 9 | 10 | fn require_contravariant<'a>(phantom: InvariantPhantom<&'a str>) -> InvariantPhantom<&'static str> { 11 | phantom 12 | } 13 | 14 | fn main() {} 15 | -------------------------------------------------------------------------------- /tests/ui/contravariant.rs: -------------------------------------------------------------------------------- 1 | use ghost::phantom; 2 | 3 | #[phantom] 4 | struct ContravariantPhantom<#[contra] T>; 5 | 6 | fn require_covariant<'a>(phantom: ContravariantPhantom<&'static str>) -> ContravariantPhantom<&'a str> { 7 | phantom 8 | } 9 | 10 | fn require_contravariant<'a>(phantom: ContravariantPhantom<&'a str>) -> ContravariantPhantom<&'static str> { 11 | phantom 12 | } 13 | 14 | fn main() {} 15 | -------------------------------------------------------------------------------- /tests/ui/autotraits.rs: -------------------------------------------------------------------------------- 1 | use ghost::phantom; 2 | 3 | #[phantom] 4 | struct MyPhantom; 5 | 6 | fn require_send() {} 7 | fn require_sync() {} 8 | 9 | fn main() { 10 | // ok 11 | require_send::>(); 12 | require_sync::>(); 13 | 14 | // not ok 15 | require_send::>(); 16 | require_sync::>(); 17 | } 18 | -------------------------------------------------------------------------------- /tests/test.rs: -------------------------------------------------------------------------------- 1 | #![allow(clippy::no_effect_underscore_binding)] 2 | 3 | use ghost::phantom; 4 | 5 | pub trait Trait {} 6 | 7 | #[phantom] 8 | pub struct Independent; 9 | 10 | #[phantom] 11 | pub struct Dependent>; 12 | 13 | #[test] 14 | fn test_const() { 15 | let _phantom_v = Independent::; 16 | let _phantom_t: Independent = Independent; 17 | } 18 | -------------------------------------------------------------------------------- /tests/ui/function-body.stderr: -------------------------------------------------------------------------------- 1 | error[E0432]: unresolved import `super::MyPhantom` 2 | --> tests/ui/function-body.rs:7:12 3 | | 4 | 7 | struct MyPhantom; 5 | | ^^^^^^^^^ could not find `MyPhantom` in the crate root 6 | 7 | error[E0432]: unresolved import `self` 8 | --> tests/ui/function-body.rs:6:5 9 | | 10 | 6 | #[phantom] 11 | | ^^^^^^^^^^ could not find `__value_MyPhantom` in the crate root 12 | | 13 | = note: this error originates in the attribute macro `phantom` (in Nightly builds, run with -Z macro-backtrace for more info) 14 | -------------------------------------------------------------------------------- /tests/ui/ffi.stderr: -------------------------------------------------------------------------------- 1 | error: `extern` fn uses type `MyPhantom`, which is not FFI-safe 2 | --> tests/ui/ffi.rs:8:39 3 | | 4 | 8 | pub extern "C" fn extern_fn(_phantom: MyPhantom) {} 5 | | ^^^^^^^^^^^^^^ not FFI-safe 6 | | 7 | = help: consider adding a `#[repr(C)]`, `#[repr(transparent)]`, or integer `#[repr(...)]` attribute to this enum 8 | = note: enum has no representation hint 9 | note: the type is defined here 10 | --> tests/ui/ffi.rs:5:1 11 | | 12 | 5 | #[phantom] 13 | | ^^^^^^^^^^ 14 | note: the lint level is defined here 15 | --> tests/ui/ffi.rs:1:9 16 | | 17 | 1 | #![deny(improper_ctypes_definitions)] 18 | | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ 19 | = note: this error originates in the attribute macro `phantom` (in Nightly builds, run with -Z macro-backtrace for more info) 20 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Permission is hereby granted, free of charge, to any 2 | person obtaining a copy of this software and associated 3 | documentation files (the "Software"), to deal in the 4 | Software without restriction, including without 5 | limitation the rights to use, copy, modify, merge, 6 | publish, distribute, sublicense, and/or sell copies of 7 | the Software, and to permit persons to whom the Software 8 | is furnished to do so, subject to the following 9 | conditions: 10 | 11 | The above copyright notice and this permission notice 12 | shall be included in all copies or substantial portions 13 | of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 16 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 17 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 18 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 19 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 20 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 21 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 22 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 23 | DEALINGS IN THE SOFTWARE. 24 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "ghost" 3 | version = "0.1.20" 4 | authors = ["David Tolnay "] 5 | categories = ["rust-patterns", "no-std", "no-std::no-alloc"] 6 | description = "Define your own PhantomData" 7 | documentation = "https://docs.rs/ghost" 8 | edition = "2021" 9 | license = "MIT OR Apache-2.0" 10 | repository = "https://github.com/dtolnay/ghost" 11 | rust-version = "1.68" 12 | 13 | [lib] 14 | proc-macro = true 15 | 16 | [dependencies] 17 | proc-macro2 = "1.0.74" 18 | quote = "1.0.35" 19 | syn = "2.0.46" 20 | 21 | [dev-dependencies] 22 | rustversion = "1.0.13" 23 | trybuild = { version = "1.0.114", features = ["diff"] } 24 | 25 | [package.metadata.docs.rs] 26 | targets = ["x86_64-unknown-linux-gnu"] 27 | rustdoc-args = [ 28 | "--generate-link-to-definition", 29 | "--generate-macro-expansion", 30 | "--extern-html-root-url=core=https://doc.rust-lang.org", 31 | "--extern-html-root-url=alloc=https://doc.rust-lang.org", 32 | "--extern-html-root-url=std=https://doc.rust-lang.org", 33 | "--extern-html-root-url=proc_macro=https://doc.rust-lang.org", 34 | ] 35 | 36 | [workspace] 37 | members = ["tests/doc"] 38 | -------------------------------------------------------------------------------- /src/parse.rs: -------------------------------------------------------------------------------- 1 | use syn::parse::{Parse, ParseStream, Result}; 2 | use syn::{Attribute, Generics, Ident, Token, Visibility, WhereClause}; 3 | 4 | pub struct UnitStruct { 5 | pub attrs: Vec, 6 | pub vis: Visibility, 7 | pub struct_token: Token![struct], 8 | pub ident: Ident, 9 | pub generics: Generics, 10 | } 11 | 12 | impl Parse for UnitStruct { 13 | fn parse(input: ParseStream) -> Result { 14 | let attrs = input.call(Attribute::parse_outer)?; 15 | let vis: Visibility = input.parse()?; 16 | let struct_token: Token![struct] = input.parse()?; 17 | let ident: Ident = input.parse()?; 18 | 19 | // Require there to be generics. 20 | input.fork().parse::()?; 21 | let generics: Generics = input.parse()?; 22 | let where_clause: Option = input.parse()?; 23 | 24 | input.parse::()?; 25 | 26 | Ok(UnitStruct { 27 | attrs, 28 | vis, 29 | struct_token, 30 | ident, 31 | generics: Generics { 32 | where_clause, 33 | ..generics 34 | }, 35 | }) 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /tests/readme.rs: -------------------------------------------------------------------------------- 1 | #![allow(clippy::let_underscore_untyped, clippy::uninlined_format_args)] 2 | 3 | mod first { 4 | use ghost::phantom; 5 | 6 | #[phantom] 7 | struct MyPhantom; 8 | 9 | #[test] 10 | fn test() { 11 | // Proof that MyPhantom behaves like PhantomData. 12 | let _: MyPhantom = MyPhantom::; 13 | assert_eq!(0, std::mem::size_of::>()); 14 | } 15 | 16 | // Proof that MyPhantom is not just a re-export of PhantomData. 17 | // If it were a re-export, these would be conflicting impls. 18 | #[allow(dead_code)] 19 | trait Trait {} 20 | impl Trait for std::marker::PhantomData {} 21 | impl Trait for MyPhantom {} 22 | 23 | // Proof that MyPhantom is local to the current crate. 24 | impl MyPhantom {} 25 | } 26 | 27 | mod second { 28 | use ghost::phantom; 29 | 30 | #[phantom] 31 | #[derive(Copy, Clone, Default, Hash, PartialOrd, Ord, PartialEq, Eq, Debug)] 32 | struct Crazy<'a, V: 'a, T> 33 | where 34 | &'a V: IntoIterator; 35 | 36 | #[test] 37 | fn test() { 38 | let _ = Crazy::<'static, Vec, &'static String>; 39 | 40 | // Lifetime elision. 41 | let crazy = Crazy::, &String>; 42 | println!("{:?}", crazy); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /tests/ui/invariant.stderr: -------------------------------------------------------------------------------- 1 | error: lifetime may not live long enough 2 | --> tests/ui/invariant.rs:7:5 3 | | 4 | 6 | fn require_covariant<'a>(phantom: InvariantPhantom<&'static str>) -> InvariantPhantom<&'a str> { 5 | | -- lifetime `'a` defined here 6 | 7 | phantom 7 | | ^^^^^^^ returning this value requires that `'a` must outlive `'static` 8 | | 9 | = note: requirement occurs because of the type `InvariantPhantom<&str>`, which makes the generic argument `&str` invariant 10 | = note: the enum `InvariantPhantom` is invariant over the parameter `T` 11 | = help: see for more information about variance 12 | 13 | error: lifetime may not live long enough 14 | --> tests/ui/invariant.rs:11:5 15 | | 16 | 10 | fn require_contravariant<'a>(phantom: InvariantPhantom<&'a str>) -> InvariantPhantom<&'static str> { 17 | | -- lifetime `'a` defined here 18 | 11 | phantom 19 | | ^^^^^^^ returning this value requires that `'a` must outlive `'static` 20 | | 21 | = note: requirement occurs because of the type `InvariantPhantom<&str>`, which makes the generic argument `&str` invariant 22 | = note: the enum `InvariantPhantom` is invariant over the parameter `T` 23 | = help: see for more information about variance 24 | -------------------------------------------------------------------------------- /tests/ui/pattern-match.stderr: -------------------------------------------------------------------------------- 1 | error[E0004]: non-exhaustive patterns: `MyPhantom::__Phantom(_)` not covered 2 | --> tests/ui/pattern-match.rs:9:11 3 | | 4 | 9 | match phantom { 5 | | ^^^^^^^ pattern `MyPhantom::__Phantom(_)` not covered 6 | | 7 | note: `MyPhantom` defined here 8 | --> tests/ui/pattern-match.rs:4:8 9 | | 10 | 3 | #[phantom] 11 | | ---------- not covered 12 | 4 | struct MyPhantom; 13 | | ^^^^^^^^^ 14 | = note: the matched value is of type `MyPhantom` 15 | help: ensure that all possible cases are being handled by adding a match arm with a wildcard pattern or an explicit pattern as shown 16 | | 17 | 10 ~ MyPhantom => {}, 18 | 11 + MyPhantom::__Phantom(_) => todo!() 19 | | 20 | 21 | error[E0004]: non-exhaustive patterns: `MyPhantom::__Phantom(_)` not covered 22 | --> tests/ui/pattern-match.rs:13:11 23 | | 24 | 13 | match phantom { 25 | | ^^^^^^^ pattern `MyPhantom::__Phantom(_)` not covered 26 | | 27 | note: `MyPhantom` defined here 28 | --> tests/ui/pattern-match.rs:4:8 29 | | 30 | 3 | #[phantom] 31 | | ---------- not covered 32 | 4 | struct MyPhantom; 33 | | ^^^^^^^^^ 34 | = note: the matched value is of type `MyPhantom` 35 | help: ensure that all possible cases are being handled by adding a match arm with a wildcard pattern or an explicit pattern as shown 36 | | 37 | 14 ~ MyPhantom:: => {}, 38 | 15 + MyPhantom::__Phantom(_) => todo!() 39 | | 40 | -------------------------------------------------------------------------------- /src/variance.rs: -------------------------------------------------------------------------------- 1 | use proc_macro2::{Ident, TokenStream}; 2 | use quote::quote; 3 | use syn::{Attribute, LifetimeParam, Meta, TypeParam}; 4 | 5 | enum Variance { 6 | Covariant, 7 | Contravariant, 8 | Invariant, 9 | } 10 | 11 | pub trait HasVarianceAttribute { 12 | fn attrs(&mut self) -> &mut Vec; 13 | } 14 | 15 | impl HasVarianceAttribute for TypeParam { 16 | fn attrs(&mut self) -> &mut Vec { 17 | &mut self.attrs 18 | } 19 | } 20 | 21 | impl HasVarianceAttribute for LifetimeParam { 22 | fn attrs(&mut self) -> &mut Vec { 23 | &mut self.attrs 24 | } 25 | } 26 | 27 | pub fn apply( 28 | param: &mut dyn HasVarianceAttribute, 29 | base: TokenStream, 30 | type_param: &Ident, 31 | ) -> TokenStream { 32 | let mut variance = Variance::Covariant; 33 | 34 | let attrs = param.attrs(); 35 | *attrs = attrs 36 | .drain(..) 37 | .filter(|attr| { 38 | if let Meta::Path(attr_path) = &attr.meta { 39 | if attr_path.is_ident("contra") { 40 | variance = Variance::Contravariant; 41 | return false; 42 | } else if attr_path.is_ident("invariant") { 43 | variance = Variance::Invariant; 44 | return false; 45 | } 46 | } 47 | true 48 | }) 49 | .collect(); 50 | 51 | let phantom = quote!(self::#type_param<#base>); 52 | match variance { 53 | Variance::Covariant => base, 54 | Variance::Contravariant => quote!(fn(#phantom)), 55 | Variance::Invariant => quote!(fn(#phantom) -> #phantom), 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/visibility.rs: -------------------------------------------------------------------------------- 1 | use syn::{parse_quote, Visibility}; 2 | 3 | // If `vis` describes a visibility relative to some module scope, returns the 4 | // same visibility as described from a module contained within that scope. 5 | // 6 | // quote! { 7 | // #vis #A; 8 | // mod #name { 9 | // // Same visibility as super::A. 10 | // #vis_super #B; 11 | // } 12 | // } 13 | // 14 | // Note if you are considering copying this implementation into another crate: 15 | // please try not to. Visibilities in Rust are confusing and subtle, especially 16 | // around visibility specifiers of items declared inside of a function body. 17 | // This function is not a robust implementation of the transformation that it 18 | // claims to implement. Always first try to restructure your code to avoid 19 | // needing this logic. 20 | pub fn vis_super(vis: &Visibility) -> Visibility { 21 | match vis { 22 | Visibility::Public(vis) => { 23 | // pub -> pub 24 | parse_quote!(#vis) 25 | } 26 | Visibility::Restricted(vis) => { 27 | if vis.path.segments[0].ident == "self" { 28 | // pub(self) -> pub(in super) 29 | // pub(in self::super) -> pub(in super::super) 30 | let path = vis.path.segments.iter().skip(1); 31 | parse_quote!(pub(in super #(::#path)*)) 32 | } else if vis.path.segments[0].ident == "super" { 33 | // pub(super) -> pub(in super::super) 34 | // pub(in super::super) -> pub(in super::super::super) 35 | let path = &vis.path; 36 | parse_quote!(pub(in super::#path)) 37 | } else { 38 | // pub(crate) -> pub(crate) 39 | // pub(in crate::path) -> pub(in crate::path) 40 | parse_quote!(#vis) 41 | } 42 | } 43 | Visibility::Inherited => { 44 | // private -> pub(super) 45 | parse_quote!(pub(super)) 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /tests/ui/autotraits.stderr: -------------------------------------------------------------------------------- 1 | error[E0277]: `*const u8` cannot be sent between threads safely 2 | --> tests/ui/autotraits.rs:15:20 3 | | 4 | 15 | require_send::>(); 5 | | ^^^^^^^^^^^^^^^^^^^^ `*const u8` cannot be sent between threads safely 6 | | 7 | = help: the trait `Send` is not implemented for `*const u8` 8 | note: required for `TypeParam<*const u8>` to implement `Send` 9 | --> tests/ui/autotraits.rs:3:1 10 | | 11 | 3 | #[phantom] 12 | | ^^^^^^^^^^ 13 | note: required because it appears within the type `__void_MyPhantom::MyPhantom<*const u8>` 14 | --> tests/ui/autotraits.rs:4:8 15 | | 16 | 4 | struct MyPhantom; 17 | | ^^^^^^^^^ 18 | note: required because it appears within the type `MyPhantom<*const u8>` 19 | --> tests/ui/autotraits.rs:4:8 20 | | 21 | 4 | struct MyPhantom; 22 | | ^^^^^^^^^ 23 | note: required by a bound in `require_send` 24 | --> tests/ui/autotraits.rs:6:20 25 | | 26 | 6 | fn require_send() {} 27 | | ^^^^ required by this bound in `require_send` 28 | = note: this error originates in the attribute macro `phantom` (in Nightly builds, run with -Z macro-backtrace for more info) 29 | 30 | error[E0277]: `*const u8` cannot be shared between threads safely 31 | --> tests/ui/autotraits.rs:16:20 32 | | 33 | 16 | require_sync::>(); 34 | | ^^^^^^^^^^^^^^^^^^^^ `*const u8` cannot be shared between threads safely 35 | | 36 | = help: the trait `Sync` is not implemented for `*const u8` 37 | note: required for `TypeParam<*const u8>` to implement `Sync` 38 | --> tests/ui/autotraits.rs:3:1 39 | | 40 | 3 | #[phantom] 41 | | ^^^^^^^^^^ 42 | note: required because it appears within the type `__void_MyPhantom::MyPhantom<*const u8>` 43 | --> tests/ui/autotraits.rs:4:8 44 | | 45 | 4 | struct MyPhantom; 46 | | ^^^^^^^^^ 47 | note: required because it appears within the type `MyPhantom<*const u8>` 48 | --> tests/ui/autotraits.rs:4:8 49 | | 50 | 4 | struct MyPhantom; 51 | | ^^^^^^^^^ 52 | note: required by a bound in `require_sync` 53 | --> tests/ui/autotraits.rs:7:20 54 | | 55 | 7 | fn require_sync() {} 56 | | ^^^^ required by this bound in `require_sync` 57 | = note: this error originates in the attribute macro `phantom` (in Nightly builds, run with -Z macro-backtrace for more info) 58 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | push: 5 | pull_request: 6 | workflow_dispatch: 7 | schedule: [cron: "40 1 * * *"] 8 | 9 | permissions: 10 | contents: read 11 | 12 | env: 13 | RUSTFLAGS: -Dwarnings 14 | 15 | jobs: 16 | pre_ci: 17 | uses: dtolnay/.github/.github/workflows/pre_ci.yml@master 18 | 19 | test: 20 | name: Rust ${{matrix.rust}} 21 | needs: pre_ci 22 | if: needs.pre_ci.outputs.continue 23 | runs-on: ubuntu-latest 24 | strategy: 25 | fail-fast: false 26 | matrix: 27 | rust: [nightly, beta, stable, 1.76.0, 1.68.0] 28 | timeout-minutes: 45 29 | steps: 30 | - uses: actions/checkout@v6 31 | - uses: dtolnay/rust-toolchain@master 32 | with: 33 | toolchain: ${{matrix.rust}} 34 | - name: Enable type layout randomization 35 | run: echo RUSTFLAGS=${RUSTFLAGS}\ -Zrandomize-layout >> $GITHUB_ENV 36 | if: matrix.rust == 'nightly' 37 | - run: cargo test 38 | if: matrix.rust != '1.68.0' 39 | - run: cargo doc --package ghost-test-doc 40 | - uses: actions/upload-artifact@v6 41 | if: matrix.rust == 'nightly' && always() 42 | with: 43 | name: Cargo.lock 44 | path: Cargo.lock 45 | continue-on-error: true 46 | 47 | minimal: 48 | name: Minimal versions 49 | needs: pre_ci 50 | if: needs.pre_ci.outputs.continue 51 | runs-on: ubuntu-latest 52 | timeout-minutes: 45 53 | steps: 54 | - uses: actions/checkout@v6 55 | - uses: dtolnay/rust-toolchain@nightly 56 | - run: cargo generate-lockfile -Z minimal-versions 57 | - run: cargo check --locked 58 | 59 | doc: 60 | name: Documentation 61 | needs: pre_ci 62 | if: needs.pre_ci.outputs.continue 63 | runs-on: ubuntu-latest 64 | timeout-minutes: 45 65 | env: 66 | RUSTDOCFLAGS: -Dwarnings 67 | steps: 68 | - uses: actions/checkout@v6 69 | - uses: dtolnay/rust-toolchain@nightly 70 | - uses: dtolnay/install@cargo-docs-rs 71 | - run: cargo docs-rs 72 | 73 | miri: 74 | name: Miri 75 | needs: pre_ci 76 | if: needs.pre_ci.outputs.continue 77 | runs-on: ubuntu-latest 78 | timeout-minutes: 45 79 | steps: 80 | - uses: actions/checkout@v6 81 | - uses: dtolnay/rust-toolchain@miri 82 | - run: cargo miri setup 83 | - run: cargo miri test 84 | env: 85 | MIRIFLAGS: -Zmiri-strict-provenance 86 | 87 | clippy: 88 | name: Clippy 89 | runs-on: ubuntu-latest 90 | if: github.event_name != 'pull_request' 91 | timeout-minutes: 45 92 | steps: 93 | - uses: actions/checkout@v6 94 | - uses: dtolnay/rust-toolchain@clippy 95 | - run: cargo clippy --tests -- -Dclippy::all -Dclippy::pedantic 96 | 97 | outdated: 98 | name: Outdated 99 | runs-on: ubuntu-latest 100 | if: github.event_name != 'pull_request' 101 | timeout-minutes: 45 102 | steps: 103 | - uses: actions/checkout@v6 104 | - uses: dtolnay/rust-toolchain@stable 105 | - uses: dtolnay/install@cargo-outdated 106 | - run: cargo outdated --workspace --exit-code 1 107 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## Define your own PhantomData 2 | 3 | [github](https://github.com/dtolnay/ghost) 4 | [crates.io](https://crates.io/crates/ghost) 5 | [docs.rs](https://docs.rs/ghost) 6 | [build status](https://github.com/dtolnay/ghost/actions?query=branch%3Amaster) 7 | 8 | This crate makes it possible to define your own PhantomData and similarly 9 | behaved unit types with generic parameters, which is not permitted in ordinary 10 | Rust. 11 | 12 | ```toml 13 | [dependencies] 14 | ghost = "0.1" 15 | ``` 16 | 17 | ### Background 18 | 19 | [`PhantomData`] as defined by the Rust standard library is magical in that the 20 | same type is impossible to define in ordinary Rust code. It is defined in the 21 | standard library like this: 22 | 23 | [`PhantomData`]: https://doc.rust-lang.org/std/marker/struct.PhantomData.html 24 | 25 | ```rust 26 | #[lang = "phantom_data"] 27 | pub struct PhantomData; 28 | ``` 29 | 30 | The `#[lang = "..."]` attribute indicates that this is a [lang item], a special 31 | case known to the compiler. It is the only type permitted to carry an unused 32 | type parameter. 33 | 34 | [lang item]: https://manishearth.github.io/blog/2017/01/11/rust-tidbits-what-is-a-lang-item/ 35 | 36 | If we try to define an equivalent unit struct with type parameter, the compiler 37 | rejects that. 38 | 39 | ```rust 40 | struct MyPhantom; 41 | ``` 42 | 43 | ```console 44 | error[E0392]: parameter `T` is never used 45 | --> src/main.rs:1:18 46 | | 47 | 1 | struct MyPhantom; 48 | | ^ unused type parameter 49 | | 50 | = help: consider removing `T` or using a marker such as `std::marker::PhantomData` 51 | ``` 52 | 53 | This crate provides a `#[phantom]` attribute that makes it possible to define 54 | unit structs with generic parameters. 55 | 56 | ### Examples 57 | 58 | ```rust 59 | use ghost::phantom; 60 | 61 | #[phantom] 62 | struct MyPhantom; 63 | 64 | fn main() { 65 | // Proof that MyPhantom behaves like PhantomData. 66 | let _: MyPhantom = MyPhantom::; 67 | assert_eq!(0, std::mem::size_of::>()); 68 | } 69 | 70 | // Proof that MyPhantom is not just a re-export of PhantomData. 71 | // If it were a re-export, these would be conflicting impls. 72 | trait Trait {} 73 | impl Trait for std::marker::PhantomData {} 74 | impl Trait for MyPhantom {} 75 | 76 | // Proof that MyPhantom is local to the current crate. 77 | impl MyPhantom { 78 | } 79 | ``` 80 | 81 | The implementation accepts where-clauses, lifetimes, multiple generic 82 | parameters, and derives. Here is a contrived invocation that demonstrates 83 | everything at once: 84 | 85 | ```rust 86 | use ghost::phantom; 87 | 88 | #[phantom] 89 | #[derive(Copy, Clone, Default, Hash, PartialOrd, Ord, PartialEq, Eq, Debug)] 90 | struct Crazy<'a, V: 'a, T> where &'a V: IntoIterator; 91 | 92 | fn main() { 93 | let _ = Crazy::<'static, Vec, &'static String>; 94 | 95 | // Lifetime elision. 96 | let crazy = Crazy::, &String>; 97 | println!("{:?}", crazy); 98 | } 99 | ``` 100 | 101 | ### Variance 102 | 103 | The `#[phantom]` attribute accepts attributes on individual generic parameters 104 | (both lifetime and type parameters) to make them contravariant or invariant. The 105 | default is covariance. 106 | 107 | - `#[contra]` — contravariant generic parameter 108 | - `#[invariant]` — invariant generic parameter 109 | 110 | The implications of variance are explained in more detail by the [Subtyping 111 | chapter] of the Rustonomicon. 112 | 113 | [Subtyping chapter]: https://doc.rust-lang.org/nomicon/subtyping.html 114 | 115 | ```rust 116 | use ghost::phantom; 117 | 118 | #[phantom] 119 | struct ContravariantLifetime<#[contra] 'a>; 120 | 121 | fn f<'a>(arg: ContravariantLifetime<'a>) -> ContravariantLifetime<'static> { 122 | // This coercion is only legal because the lifetime parameter is 123 | // contravariant. If it were covariant (the default) or invariant, 124 | // this would not compile. 125 | arg 126 | } 127 | 128 | #[phantom] 129 | struct Demo; 130 | ``` 131 | 132 | ### Documentation 133 | 134 | There are two alternatives for how to handle Rustdoc documentation on publicly 135 | exposed phantom types. 136 | 137 | You may provide documentation directly on the phantom struct in the obvious way, 138 | but Rustdoc will blithely display the somewhat distracting implementation 139 | details of the mechanism emitted by the `#[phantom]` macro. This way should be 140 | preferred if you need to document any public methods, as methods will not be 141 | visible in the other alternative. 142 | 143 | ```rust 144 | use ghost::phantom; 145 | 146 | /// Documentation. 147 | #[phantom] 148 | pub struct MyPhantom; 149 | 150 | impl MyPhantom { 151 | /// Documentation on methods. 152 | pub fn foo() {} 153 | } 154 | ``` 155 | 156 | If you aren't adding methods or don't need methods to be rendered in the 157 | documentation, the recommended idiom is as follows. Rustdoc will show a much 158 | less distracting type signature and all of your trait impls, but will not show 159 | inherent methods. 160 | 161 | ```rust 162 | mod private { 163 | use ghost::phantom; 164 | 165 | #[phantom] 166 | pub struct MyPhantom; 167 | } 168 | 169 | /// Documentation goes here. 170 | #[allow(type_alias_bounds)] 171 | pub type MyPhantom = private::MyPhantom; 172 | 173 | #[doc(hidden)] 174 | pub use self::private::*; 175 | ``` 176 | 177 | ### Use cases 178 | 179 | Entirely up to your imagination. Just to name one, how about a typed registry 180 | library that admits the following syntax for iterating over values registered of 181 | a particular type: 182 | 183 | ```rust 184 | for flag in Registry:: { 185 | /* ... */ 186 | } 187 | ``` 188 | 189 |
190 | 191 | #### License 192 | 193 | 194 | Licensed under either of Apache License, Version 195 | 2.0 or MIT license at your option. 196 | 197 | 198 |
199 | 200 | 201 | Unless you explicitly state otherwise, any contribution intentionally submitted 202 | for inclusion in this crate by you, as defined in the Apache-2.0 license, shall 203 | be dual licensed as above, without any additional terms or conditions. 204 | 205 | -------------------------------------------------------------------------------- /src/derive.rs: -------------------------------------------------------------------------------- 1 | use proc_macro2::TokenStream; 2 | use quote::quote; 3 | use syn::parse::{Parse, ParseStream}; 4 | use syn::{Attribute, Error, Path, Result, Token}; 5 | 6 | use crate::parse::UnitStruct; 7 | 8 | enum Derive { 9 | Copy, 10 | Clone, 11 | Default, 12 | Hash, 13 | PartialOrd, 14 | Ord, 15 | PartialEq, 16 | Eq, 17 | Debug, 18 | } 19 | 20 | struct DeriveList { 21 | derives: Vec, 22 | } 23 | 24 | impl Parse for DeriveList { 25 | fn parse(input: ParseStream) -> Result { 26 | let paths = input.parse_terminated(Path::parse_mod_style, Token![,])?; 27 | 28 | let mut derives = Vec::new(); 29 | for path in paths { 30 | if path.is_ident("Copy") { 31 | derives.push(Derive::Copy); 32 | } else if path.is_ident("Clone") { 33 | derives.push(Derive::Clone); 34 | } else if path.is_ident("Default") { 35 | derives.push(Derive::Default); 36 | } else if path.is_ident("Hash") { 37 | derives.push(Derive::Hash); 38 | } else if path.is_ident("PartialOrd") { 39 | derives.push(Derive::PartialOrd); 40 | } else if path.is_ident("Ord") { 41 | derives.push(Derive::Ord); 42 | } else if path.is_ident("PartialEq") { 43 | derives.push(Derive::PartialEq); 44 | } else if path.is_ident("Eq") { 45 | derives.push(Derive::Eq); 46 | } else if path.is_ident("Debug") { 47 | derives.push(Derive::Debug); 48 | } else { 49 | return Err(Error::new_spanned(path, "unsupported derive")); 50 | } 51 | } 52 | 53 | Ok(DeriveList { derives }) 54 | } 55 | } 56 | 57 | pub fn expand<'a>( 58 | attrs: &'a [Attribute], 59 | input: &UnitStruct, 60 | ) -> Result<(TokenStream, Vec<&'a Attribute>)> { 61 | let mut expanded = TokenStream::new(); 62 | let mut non_derives = Vec::new(); 63 | 64 | for attr in attrs { 65 | if attr.path().is_ident("derive") { 66 | let list = attr.parse_args_with(DeriveList::parse)?; 67 | for derive in list.derives { 68 | expanded.extend(apply(derive, input)); 69 | } 70 | } else { 71 | non_derives.push(attr); 72 | } 73 | } 74 | 75 | Ok((expanded, non_derives)) 76 | } 77 | 78 | fn apply(derive: Derive, input: &UnitStruct) -> TokenStream { 79 | match derive { 80 | Derive::Copy => expand_copy(input), 81 | Derive::Clone => expand_clone(input), 82 | Derive::Default => expand_default(input), 83 | Derive::Hash => expand_hash(input), 84 | Derive::PartialOrd => expand_partialord(input), 85 | Derive::Ord => expand_ord(input), 86 | Derive::PartialEq => expand_partialeq(input), 87 | Derive::Eq => expand_eq(input), 88 | Derive::Debug => expand_debug(input), 89 | } 90 | } 91 | 92 | fn expand_copy(input: &UnitStruct) -> TokenStream { 93 | let ident = &input.ident; 94 | let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl(); 95 | 96 | quote! { 97 | #[automatically_derived] 98 | impl #impl_generics ::core::marker::Copy 99 | for #ident #ty_generics #where_clause {} 100 | } 101 | } 102 | 103 | fn expand_clone(input: &UnitStruct) -> TokenStream { 104 | let ident = &input.ident; 105 | let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl(); 106 | 107 | quote! { 108 | #[automatically_derived] 109 | impl #impl_generics ::core::clone::Clone 110 | for #ident #ty_generics #where_clause { 111 | #[inline] 112 | fn clone(&self) -> Self { 113 | #ident 114 | } 115 | } 116 | } 117 | } 118 | 119 | fn expand_default(input: &UnitStruct) -> TokenStream { 120 | let ident = &input.ident; 121 | let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl(); 122 | 123 | quote! { 124 | #[automatically_derived] 125 | impl #impl_generics ::core::default::Default 126 | for #ident #ty_generics #where_clause { 127 | #[inline] 128 | fn default() -> Self { 129 | #ident 130 | } 131 | } 132 | } 133 | } 134 | 135 | fn expand_hash(input: &UnitStruct) -> TokenStream { 136 | let ident = &input.ident; 137 | let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl(); 138 | 139 | quote! { 140 | #[automatically_derived] 141 | impl #impl_generics ::core::hash::Hash 142 | for #ident #ty_generics #where_clause { 143 | #[inline] 144 | fn hash(&self, hasher: &mut H) { 145 | let _ = hasher; 146 | } 147 | } 148 | } 149 | } 150 | 151 | fn expand_partialord(input: &UnitStruct) -> TokenStream { 152 | let ident = &input.ident; 153 | let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl(); 154 | 155 | quote! { 156 | #[automatically_derived] 157 | impl #impl_generics ::core::cmp::PartialOrd 158 | for #ident #ty_generics #where_clause { 159 | #[inline] 160 | fn partial_cmp(&self, other: &Self) -> ::core::option::Option<::core::cmp::Ordering> { 161 | let _ = other; 162 | ::core::option::Option::Some(::core::cmp::Ordering::Equal) 163 | } 164 | } 165 | } 166 | } 167 | 168 | fn expand_ord(input: &UnitStruct) -> TokenStream { 169 | let ident = &input.ident; 170 | let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl(); 171 | 172 | quote! { 173 | #[automatically_derived] 174 | impl #impl_generics ::core::cmp::Ord 175 | for #ident #ty_generics #where_clause { 176 | #[inline] 177 | fn cmp(&self, other: &Self) -> ::core::cmp::Ordering { 178 | let _ = other; 179 | ::core::cmp::Ordering::Equal 180 | } 181 | } 182 | } 183 | } 184 | 185 | fn expand_partialeq(input: &UnitStruct) -> TokenStream { 186 | let ident = &input.ident; 187 | let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl(); 188 | 189 | quote! { 190 | #[automatically_derived] 191 | impl #impl_generics ::core::cmp::PartialEq 192 | for #ident #ty_generics #where_clause { 193 | #[inline] 194 | fn eq(&self, other: &Self) -> bool { 195 | let _ = other; 196 | true 197 | } 198 | } 199 | } 200 | } 201 | 202 | fn expand_eq(input: &UnitStruct) -> TokenStream { 203 | let ident = &input.ident; 204 | let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl(); 205 | 206 | quote! { 207 | #[automatically_derived] 208 | impl #impl_generics ::core::cmp::Eq 209 | for #ident #ty_generics #where_clause {} 210 | } 211 | } 212 | 213 | fn expand_debug(input: &UnitStruct) -> TokenStream { 214 | let ident = &input.ident; 215 | let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl(); 216 | let string = ident.to_string(); 217 | 218 | quote! { 219 | #[automatically_derived] 220 | impl #impl_generics ::core::fmt::Debug 221 | for #ident #ty_generics #where_clause { 222 | fn fmt(&self, formatter: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { 223 | ::core::fmt::Formatter::write_str(formatter, #string) 224 | } 225 | } 226 | } 227 | } 228 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 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 | //!
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`]: core::marker::PhantomData 18 | //! 19 | //! ``` 20 | //! # const IGNORE: &str = stringify! { 21 | //! #[lang = "phantom_data"] 22 | //! pub struct PhantomData; 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; 37 | //! ``` 38 | //! 39 | //! ```text 40 | //! error[E0392]: parameter `T` is never used 41 | //! --> src/main.rs:1:18 42 | //! | 43 | //! 1 | struct MyPhantom; 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; 59 | //! 60 | //! fn main() { 61 | //! // Proof that MyPhantom behaves like PhantomData. 62 | //! let _: MyPhantom = MyPhantom::; 63 | //! assert_eq!(0, std::mem::size_of::>()); 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 Trait for std::marker::PhantomData {} 70 | //! impl Trait for MyPhantom {} 71 | //! 72 | //! // Proof that MyPhantom is local to the current crate. 73 | //! impl MyPhantom { 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; 87 | //! 88 | //! fn main() { 89 | //! let _ = Crazy::<'static, Vec, &'static String>; 90 | //! 91 | //! // Lifetime elision. 92 | //! let crazy = Crazy::, &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; 126 | //! # 127 | //! # fn main() {} 128 | //! ``` 129 | //! 130 | //! # Documentation 131 | //! 132 | //! There are two alternatives for how to handle Rustdoc documentation on 133 | //! publicly exposed phantom types. 134 | //! 135 | //! You may provide documentation directly on the phantom struct in the obvious 136 | //! way, but Rustdoc will blithely display the somewhat distracting 137 | //! implementation details of the mechanism emitted by the `#[phantom]` macro. 138 | //! This way should be preferred if you need to document any public methods, as 139 | //! methods will not be visible in the other alternative. 140 | //! 141 | //! ``` 142 | //! use ghost::phantom; 143 | //! 144 | //! /// Documentation. 145 | //! #[phantom] 146 | //! pub struct MyPhantom; 147 | //! 148 | //! impl MyPhantom { 149 | //! /// Documentation on methods. 150 | //! pub fn foo() {} 151 | //! } 152 | //! # 153 | //! # fn main() {} 154 | //! ``` 155 | //! 156 | //! If you aren't adding methods or don't need methods to be rendered in the 157 | //! documentation, the recommended idiom is as follows. Rustdoc will show a much 158 | //! less distracting type signature and all of your trait impls, but will not 159 | //! show inherent methods. 160 | //! 161 | //! ``` 162 | //! mod private { 163 | //! use ghost::phantom; 164 | //! 165 | //! #[phantom] 166 | //! pub struct MyPhantom; 167 | //! } 168 | //! 169 | //! /// Documentation goes here. 170 | //! #[allow(type_alias_bounds)] 171 | //! pub type MyPhantom = private::MyPhantom; 172 | //! 173 | //! #[doc(hidden)] 174 | //! pub use self::private::*; 175 | //! # 176 | //! # fn main() {} 177 | //! ``` 178 | //! 179 | //! # Use cases 180 | //! 181 | //! Entirely up to your imagination. Just to name one, how about a typed 182 | //! registry library that admits the following syntax for iterating over values 183 | //! registered of a particular type: 184 | //! 185 | //! ```no_run 186 | //! # use ghost::phantom; 187 | //! # 188 | //! # #[phantom] 189 | //! # struct Registry; 190 | //! # 191 | //! # impl IntoIterator for Registry { 192 | //! # type Item = T; 193 | //! # type IntoIter = Iter; 194 | //! # fn into_iter(self) -> Self::IntoIter { 195 | //! # unimplemented!() 196 | //! # } 197 | //! # } 198 | //! # 199 | //! # struct Iter(T); 200 | //! # 201 | //! # impl Iterator for Iter { 202 | //! # type Item = T; 203 | //! # fn next(&mut self) -> Option { 204 | //! # unimplemented!() 205 | //! # } 206 | //! # } 207 | //! # 208 | //! # struct Flag; 209 | //! # 210 | //! # fn main() { 211 | //! for flag in Registry:: { 212 | //! /* ... */ 213 | //! } 214 | //! # } 215 | //! ``` 216 | 217 | #![doc(html_root_url = "https://docs.rs/ghost/0.1.20")] 218 | #![allow( 219 | clippy::doc_markdown, 220 | // https://github.com/rust-lang/rust-clippy/issues/8538 221 | clippy::iter_with_drain, 222 | clippy::needless_doctest_main, 223 | clippy::needless_pass_by_value, 224 | clippy::too_many_lines, 225 | clippy::uninlined_format_args 226 | )] 227 | 228 | extern crate proc_macro; 229 | 230 | mod derive; 231 | mod parse; 232 | mod variance; 233 | mod visibility; 234 | 235 | use proc_macro::TokenStream; 236 | use proc_macro2::{Ident, Span}; 237 | use quote::quote; 238 | use syn::parse::Nothing; 239 | use syn::{parse_macro_input, GenericParam, Token}; 240 | 241 | use crate::parse::UnitStruct; 242 | 243 | /// Define your own PhantomData and similarly behaved unit types. 244 | /// 245 | /// Please refer to the [crate level documentation](index.html) for explanation 246 | /// and examples. 247 | #[proc_macro_attribute] 248 | pub fn phantom(args: TokenStream, input: TokenStream) -> TokenStream { 249 | parse_macro_input!(args as Nothing); 250 | let input = parse_macro_input!(input as UnitStruct); 251 | 252 | let ident = &input.ident; 253 | let call_site = Span::call_site(); 254 | let void_namespace = Ident::new(&format!("__void_{}", ident), call_site); 255 | let value_namespace = Ident::new(&format!("__value_{}", ident), call_site); 256 | 257 | let vis = &input.vis; 258 | let vis_super = visibility::vis_super(vis); 259 | 260 | let (derives, attrs) = match derive::expand(&input.attrs, &input) { 261 | Ok(split) => split, 262 | Err(err) => return err.to_compile_error().into(), 263 | }; 264 | 265 | let void = Ident::new( 266 | if ident == "Void" { "__Void" } else { "Void" }, 267 | Span::call_site(), 268 | ); 269 | 270 | let type_param = Ident::new( 271 | if ident == "TypeParam" { 272 | "__TypeParam" 273 | } else { 274 | "TypeParam" 275 | }, 276 | Span::call_site(), 277 | ); 278 | 279 | let mut generics = input.generics; 280 | let where_clause = generics.where_clause.take(); 281 | let mut impl_generics = Vec::new(); 282 | let mut ty_generics = Vec::new(); 283 | let mut phantoms = Vec::new(); 284 | for param in &mut generics.params { 285 | match param { 286 | GenericParam::Type(param) => { 287 | let ident = ¶m.ident; 288 | let elem = quote!(#ident); 289 | impl_generics.push(quote!(#ident: ?::core::marker::Sized)); 290 | ty_generics.push(quote!(#ident)); 291 | phantoms.push(variance::apply(param, elem, &type_param)); 292 | } 293 | GenericParam::Lifetime(param) => { 294 | let lifetime = ¶m.lifetime; 295 | let elem = quote!(&#lifetime ()); 296 | impl_generics.push(quote!(#lifetime)); 297 | ty_generics.push(quote!(#lifetime)); 298 | phantoms.push(variance::apply(param, elem, &type_param)); 299 | } 300 | GenericParam::Const(_) => {} 301 | } 302 | } 303 | 304 | let impl_generics = &impl_generics; 305 | let ty_generics = &ty_generics; 306 | let enum_token = Token![enum](input.struct_token.span); 307 | 308 | TokenStream::from(quote! { 309 | mod #void_namespace { 310 | enum #void {} 311 | #[automatically_derived] 312 | impl ::core::marker::Copy for #void {} 313 | #[automatically_derived] 314 | #[allow(clippy::expl_impl_clone_on_copy)] 315 | impl ::core::clone::Clone for #void { 316 | fn clone(&self) -> Self { 317 | *self 318 | } 319 | } 320 | 321 | #[repr(C, packed)] 322 | struct #type_param([*const T; 0]); 323 | #[automatically_derived] 324 | impl ::core::marker::Copy for #type_param {} 325 | #[automatically_derived] 326 | #[allow(clippy::expl_impl_clone_on_copy)] 327 | impl ::core::clone::Clone for #type_param { 328 | fn clone(&self) -> Self { 329 | *self 330 | } 331 | } 332 | #[automatically_derived] 333 | unsafe impl ::core::marker::Send for #type_param {} 334 | #[automatically_derived] 335 | unsafe impl ::core::marker::Sync for #type_param {} 336 | 337 | #[allow(non_camel_case_types)] 338 | #vis_super struct #ident <#(#impl_generics),*> ( 339 | #( 340 | self::#type_param<#phantoms>, 341 | )* 342 | self::#void, 343 | ); 344 | 345 | #[automatically_derived] 346 | impl <#(#impl_generics),*> ::core::marker::Copy 347 | for #ident <#(#ty_generics),*> {} 348 | 349 | #[automatically_derived] 350 | #[allow(clippy::expl_impl_clone_on_copy)] 351 | impl <#(#impl_generics),*> ::core::clone::Clone 352 | for #ident <#(#ty_generics),*> { 353 | fn clone(&self) -> Self { 354 | *self 355 | } 356 | } 357 | } 358 | 359 | mod #value_namespace { 360 | #[doc(hidden)] 361 | #vis_super use super::#ident::#ident; 362 | } 363 | 364 | #(#attrs)* 365 | #vis #enum_token #ident #generics #where_clause { 366 | __Phantom(#void_namespace::#ident <#(#ty_generics),*>), 367 | #ident, 368 | } 369 | 370 | #[doc(hidden)] 371 | #vis use self::#value_namespace::*; 372 | 373 | #derives 374 | }) 375 | } 376 | --------------------------------------------------------------------------------