├── .github ├── FUNDING.yml └── workflows │ └── ci.yml ├── .gitignore ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── src ├── derive.rs ├── lib.rs ├── parse.rs ├── variance.rs └── visibility.rs └── tests ├── autotraits.rs ├── compiletest.rs ├── doc ├── Cargo.toml └── src │ └── lib.rs ├── readme.rs └── ui ├── autotraits.rs ├── autotraits.stderr ├── contravariant.rs ├── contravariant.stderr ├── covariant.rs ├── covariant.stderr ├── ffi.rs ├── ffi.stderr ├── function-body.rs ├── function-body.stderr ├── invariant.rs ├── invariant.stderr ├── pattern-match.rs └── pattern-match.stderr /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: dtolnay 2 | -------------------------------------------------------------------------------- /.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.56.0] 28 | timeout-minutes: 45 29 | steps: 30 | - uses: actions/checkout@v4 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 | - run: cargo doc --package ghost-test-doc 39 | - uses: actions/upload-artifact@v4 40 | if: matrix.rust == 'nightly' && always() 41 | with: 42 | name: Cargo.lock 43 | path: Cargo.lock 44 | continue-on-error: true 45 | 46 | minimal: 47 | name: Minimal versions 48 | needs: pre_ci 49 | if: needs.pre_ci.outputs.continue 50 | runs-on: ubuntu-latest 51 | timeout-minutes: 45 52 | steps: 53 | - uses: actions/checkout@v4 54 | - uses: dtolnay/rust-toolchain@nightly 55 | - run: cargo generate-lockfile -Z minimal-versions 56 | - run: cargo check --locked 57 | 58 | doc: 59 | name: Documentation 60 | needs: pre_ci 61 | if: needs.pre_ci.outputs.continue 62 | runs-on: ubuntu-latest 63 | timeout-minutes: 45 64 | env: 65 | RUSTDOCFLAGS: -Dwarnings 66 | steps: 67 | - uses: actions/checkout@v4 68 | - uses: dtolnay/rust-toolchain@nightly 69 | - uses: dtolnay/install@cargo-docs-rs 70 | - run: cargo docs-rs 71 | 72 | miri: 73 | name: Miri 74 | needs: pre_ci 75 | if: needs.pre_ci.outputs.continue 76 | runs-on: ubuntu-latest 77 | timeout-minutes: 45 78 | steps: 79 | - uses: actions/checkout@v4 80 | - uses: dtolnay/rust-toolchain@miri 81 | with: 82 | toolchain: nightly-2025-05-16 # https://github.com/rust-lang/miri/issues/4323 83 | - run: cargo miri setup 84 | - run: cargo miri test 85 | env: 86 | MIRIFLAGS: -Zmiri-strict-provenance 87 | 88 | clippy: 89 | name: Clippy 90 | runs-on: ubuntu-latest 91 | if: github.event_name != 'pull_request' 92 | timeout-minutes: 45 93 | steps: 94 | - uses: actions/checkout@v4 95 | - uses: dtolnay/rust-toolchain@clippy 96 | - run: cargo clippy --tests -- -Dclippy::all -Dclippy::pedantic 97 | 98 | outdated: 99 | name: Outdated 100 | runs-on: ubuntu-latest 101 | if: github.event_name != 'pull_request' 102 | timeout-minutes: 45 103 | steps: 104 | - uses: actions/checkout@v4 105 | - uses: dtolnay/rust-toolchain@stable 106 | - uses: dtolnay/install@cargo-outdated 107 | - run: cargo outdated --workspace --exit-code 1 108 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | /Cargo.lock 3 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "ghost" 3 | version = "0.1.19" 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.56" 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.81", features = ["diff"] } 24 | 25 | [package.metadata.docs.rs] 26 | targets = ["x86_64-unknown-linux-gnu"] 27 | rustdoc-args = [ 28 | "--generate-link-to-definition", 29 | "--extern-html-root-url=core=https://doc.rust-lang.org", 30 | "--extern-html-root-url=alloc=https://doc.rust-lang.org", 31 | "--extern-html-root-url=std=https://doc.rust-lang.org", 32 | "--extern-html-root-url=proc_macro=https://doc.rust-lang.org", 33 | ] 34 | 35 | [workspace] 36 | members = ["tests/doc"] 37 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | *Supports rustc 1.31+* 18 | 19 | ### Background 20 | 21 | [`PhantomData`] as defined by the Rust standard library is magical in that the 22 | same type is impossible to define in ordinary Rust code. It is defined in the 23 | standard library like this: 24 | 25 | [`PhantomData`]: https://doc.rust-lang.org/std/marker/struct.PhantomData.html 26 | 27 | ```rust 28 | #[lang = "phantom_data"] 29 | pub struct PhantomData; 30 | ``` 31 | 32 | The `#[lang = "..."]` attribute indicates that this is a [lang item], a special 33 | case known to the compiler. It is the only type permitted to carry an unused 34 | type parameter. 35 | 36 | [lang item]: https://manishearth.github.io/blog/2017/01/11/rust-tidbits-what-is-a-lang-item/ 37 | 38 | If we try to define an equivalent unit struct with type parameter, the compiler 39 | rejects that. 40 | 41 | ```rust 42 | struct MyPhantom; 43 | ``` 44 | 45 | ```console 46 | error[E0392]: parameter `T` is never used 47 | --> src/main.rs:1:18 48 | | 49 | 1 | struct MyPhantom; 50 | | ^ unused type parameter 51 | | 52 | = help: consider removing `T` or using a marker such as `std::marker::PhantomData` 53 | ``` 54 | 55 | This crate provides a `#[phantom]` attribute that makes it possible to define 56 | unit structs with generic parameters. 57 | 58 | ### Examples 59 | 60 | ```rust 61 | use ghost::phantom; 62 | 63 | #[phantom] 64 | struct MyPhantom; 65 | 66 | fn main() { 67 | // Proof that MyPhantom behaves like PhantomData. 68 | let _: MyPhantom = MyPhantom::; 69 | assert_eq!(0, std::mem::size_of::>()); 70 | } 71 | 72 | // Proof that MyPhantom is not just a re-export of PhantomData. 73 | // If it were a re-export, these would be conflicting impls. 74 | trait Trait {} 75 | impl Trait for std::marker::PhantomData {} 76 | impl Trait for MyPhantom {} 77 | 78 | // Proof that MyPhantom is local to the current crate. 79 | impl MyPhantom { 80 | } 81 | ``` 82 | 83 | The implementation accepts where-clauses, lifetimes, multiple generic 84 | parameters, and derives. Here is a contrived invocation that demonstrates 85 | everything at once: 86 | 87 | ```rust 88 | use ghost::phantom; 89 | 90 | #[phantom] 91 | #[derive(Copy, Clone, Default, Hash, PartialOrd, Ord, PartialEq, Eq, Debug)] 92 | struct Crazy<'a, V: 'a, T> where &'a V: IntoIterator; 93 | 94 | fn main() { 95 | let _ = Crazy::<'static, Vec, &'static String>; 96 | 97 | // Lifetime elision. 98 | let crazy = Crazy::, &String>; 99 | println!("{:?}", crazy); 100 | } 101 | ``` 102 | 103 | ### Variance 104 | 105 | The `#[phantom]` attribute accepts attributes on individual generic parameters 106 | (both lifetime and type parameters) to make them contravariant or invariant. The 107 | default is covariance. 108 | 109 | - `#[contra]` — contravariant generic parameter 110 | - `#[invariant]` — invariant generic parameter 111 | 112 | The implications of variance are explained in more detail by the [Subtyping 113 | chapter] of the Rustonomicon. 114 | 115 | [Subtyping chapter]: https://doc.rust-lang.org/nomicon/subtyping.html 116 | 117 | ```rust 118 | use ghost::phantom; 119 | 120 | #[phantom] 121 | struct ContravariantLifetime<#[contra] 'a>; 122 | 123 | fn f<'a>(arg: ContravariantLifetime<'a>) -> ContravariantLifetime<'static> { 124 | // This coercion is only legal because the lifetime parameter is 125 | // contravariant. If it were covariant (the default) or invariant, 126 | // this would not compile. 127 | arg 128 | } 129 | 130 | #[phantom] 131 | struct Demo; 132 | ``` 133 | 134 | ### Documentation 135 | 136 | There are two alternatives for how to handle Rustdoc documentation on publicly 137 | exposed phantom types. 138 | 139 | You may provide documentation directly on the phantom struct in the obvious way, 140 | but Rustdoc will blithely display the somewhat distracting implementation 141 | details of the mechanism emitted by the `#[phantom]` macro. This way should be 142 | preferred if you need to document any public methods, as methods will not be 143 | visible in the other alternative. 144 | 145 | ```rust 146 | use ghost::phantom; 147 | 148 | /// Documentation. 149 | #[phantom] 150 | pub struct MyPhantom; 151 | 152 | impl MyPhantom { 153 | /// Documentation on methods. 154 | pub fn foo() {} 155 | } 156 | ``` 157 | 158 | If you aren't adding methods or don't need methods to be rendered in the 159 | documentation, the recommended idiom is as follows. Rustdoc will show a much 160 | less distracting type signature and all of your trait impls, but will not show 161 | inherent methods. 162 | 163 | ```rust 164 | mod private { 165 | use ghost::phantom; 166 | 167 | #[phantom] 168 | pub struct MyPhantom; 169 | } 170 | 171 | /// Documentation goes here. 172 | #[allow(type_alias_bounds)] 173 | pub type MyPhantom = private::MyPhantom; 174 | 175 | #[doc(hidden)] 176 | pub use self::private::*; 177 | ``` 178 | 179 | ### Use cases 180 | 181 | Entirely up to your imagination. Just to name one, how about a typed registry 182 | library that admits the following syntax for iterating over values registered of 183 | a particular type: 184 | 185 | ```rust 186 | for flag in Registry:: { 187 | /* ... */ 188 | } 189 | ``` 190 | 191 |
192 | 193 | #### License 194 | 195 | 196 | Licensed under either of Apache License, Version 197 | 2.0 or MIT license at your option. 198 | 199 | 200 |
201 | 202 | 203 | Unless you explicitly state otherwise, any contribution intentionally submitted 204 | for inclusion in this crate by you, as defined in the Apache-2.0 license, shall 205 | be dual licensed as above, without any additional terms or conditions. 206 | 207 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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.19")] 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 | )] 226 | 227 | extern crate proc_macro; 228 | 229 | mod derive; 230 | mod parse; 231 | mod variance; 232 | mod visibility; 233 | 234 | use proc_macro::TokenStream; 235 | use proc_macro2::{Ident, Span}; 236 | use quote::quote; 237 | use syn::parse::Nothing; 238 | use syn::{parse_macro_input, Error, GenericParam, Token}; 239 | 240 | use crate::parse::UnitStruct; 241 | 242 | /// Define your own PhantomData and similarly behaved unit types. 243 | /// 244 | /// Please refer to the [crate level documentation](index.html) for explanation 245 | /// and examples. 246 | #[proc_macro_attribute] 247 | pub fn phantom(args: TokenStream, input: TokenStream) -> TokenStream { 248 | parse_macro_input!(args as Nothing); 249 | let input = parse_macro_input!(input as UnitStruct); 250 | 251 | let ident = &input.ident; 252 | let call_site = Span::call_site(); 253 | let void_namespace = Ident::new(&format!("__void_{}", ident), call_site); 254 | let value_namespace = Ident::new(&format!("__value_{}", ident), call_site); 255 | 256 | let vis = &input.vis; 257 | let vis_super = visibility::vis_super(vis); 258 | 259 | let (derives, attrs) = match derive::expand(&input.attrs, &input) { 260 | Ok(split) => split, 261 | Err(err) => return err.to_compile_error().into(), 262 | }; 263 | 264 | let void = Ident::new( 265 | if ident == "Void" { "__Void" } else { "Void" }, 266 | Span::call_site(), 267 | ); 268 | 269 | let type_param = Ident::new( 270 | if ident == "TypeParam" { 271 | "__TypeParam" 272 | } else { 273 | "TypeParam" 274 | }, 275 | Span::call_site(), 276 | ); 277 | 278 | let mut generics = input.generics; 279 | let where_clause = generics.where_clause.take(); 280 | let mut impl_generics = Vec::new(); 281 | let mut ty_generics = Vec::new(); 282 | let mut phantoms = Vec::new(); 283 | for param in &mut generics.params { 284 | match param { 285 | GenericParam::Type(param) => { 286 | let ident = ¶m.ident; 287 | let elem = quote!(#ident); 288 | impl_generics.push(quote!(#ident: ?::core::marker::Sized)); 289 | ty_generics.push(quote!(#ident)); 290 | phantoms.push(variance::apply(param, elem, &type_param)); 291 | } 292 | GenericParam::Lifetime(param) => { 293 | let lifetime = ¶m.lifetime; 294 | let elem = quote!(&#lifetime ()); 295 | impl_generics.push(quote!(#lifetime)); 296 | ty_generics.push(quote!(#lifetime)); 297 | phantoms.push(variance::apply(param, elem, &type_param)); 298 | } 299 | GenericParam::Const(param) => { 300 | let msg = "const generics are not supported"; 301 | let err = Error::new_spanned(param, msg); 302 | return err.to_compile_error().into(); 303 | } 304 | } 305 | } 306 | 307 | let impl_generics = &impl_generics; 308 | let ty_generics = &ty_generics; 309 | let enum_token = Token![enum](input.struct_token.span); 310 | 311 | TokenStream::from(quote! { 312 | mod #void_namespace { 313 | enum #void {} 314 | #[automatically_derived] 315 | impl ::core::marker::Copy for #void {} 316 | #[automatically_derived] 317 | #[allow(clippy::expl_impl_clone_on_copy)] 318 | impl ::core::clone::Clone for #void { 319 | fn clone(&self) -> Self { 320 | *self 321 | } 322 | } 323 | 324 | #[repr(C, packed)] 325 | struct #type_param([*const T; 0]); 326 | #[automatically_derived] 327 | impl ::core::marker::Copy for #type_param {} 328 | #[automatically_derived] 329 | #[allow(clippy::expl_impl_clone_on_copy)] 330 | impl ::core::clone::Clone for #type_param { 331 | fn clone(&self) -> Self { 332 | *self 333 | } 334 | } 335 | #[automatically_derived] 336 | unsafe impl ::core::marker::Send for #type_param {} 337 | #[automatically_derived] 338 | unsafe impl ::core::marker::Sync for #type_param {} 339 | 340 | #[allow(non_camel_case_types)] 341 | #vis_super struct #ident <#(#impl_generics),*> ( 342 | #( 343 | self::#type_param<#phantoms>, 344 | )* 345 | self::#void, 346 | ); 347 | 348 | #[automatically_derived] 349 | impl <#(#impl_generics),*> ::core::marker::Copy 350 | for #ident <#(#ty_generics),*> {} 351 | 352 | #[automatically_derived] 353 | #[allow(clippy::expl_impl_clone_on_copy)] 354 | impl <#(#impl_generics),*> ::core::clone::Clone 355 | for #ident <#(#ty_generics),*> { 356 | fn clone(&self) -> Self { 357 | *self 358 | } 359 | } 360 | } 361 | 362 | mod #value_namespace { 363 | #[doc(hidden)] 364 | #vis_super use super::#ident::#ident; 365 | } 366 | 367 | #(#attrs)* 368 | #vis #enum_token #ident #generics #where_clause { 369 | __Phantom(#void_namespace::#ident <#(#ty_generics),*>), 370 | #ident, 371 | } 372 | 373 | #[doc(hidden)] 374 | #vis use self::#value_namespace::*; 375 | 376 | #derives 377 | }) 378 | } 379 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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/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/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/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/doc/src/lib.rs: -------------------------------------------------------------------------------- 1 | use ghost::phantom; 2 | 3 | #[phantom] 4 | pub struct MyPhantom; 5 | -------------------------------------------------------------------------------- /tests/readme.rs: -------------------------------------------------------------------------------- 1 | #![allow(clippy::let_underscore_untyped)] 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/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/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 | -------------------------------------------------------------------------------- /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/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/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/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 | -------------------------------------------------------------------------------- /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/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/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/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.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/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 | --------------------------------------------------------------------------------