1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453
//! This crate is aiming to make work with [variance][var] easier. //! The crate exposes 3 types - [`Invariant<T>`][inv], [`Covariant<T>`][cov] and //! [`Contravariant<T>`][cnt] with corresponding variance over `T` those work //! very similar to [`PhantomData<_>`][phd]. //! //! [var]: https://doc.rust-lang.org/nomicon/subtyping.html //! [inv]: crate::Invariant#type //! [cov]: crate::Covariant#type //! [cnt]: crate::Contravariant#type //! [phd]: core::marker::PhantomData //! //! ## motivation //! //! In rust it's an error to have an unused generic param in struct: //! ```compile_fail //! struct Slice<'a, T> { //! start: *const T, //! end: *const T, //! } //! ``` //! ```text //! error[E0392]: parameter `'a` is never used //! --> src/lib.rs:16:14 //! | //! 3 | struct Slice<'a, T> { //! | ^^ unused parameter //! | //! = help: consider removing `'a`, referring to it in a field, or using a marker such as `std::marker::PhantomData` //! ``` //! This is an error because rust compiler doesn't know should `Slice` be //! covariant, contravariant or invariant over `'a`. (What it means is that //! rustc doesn't know if `Slice<'static, _>` should be `Slice<'a, _>` or vice //! versa or none of this. See [Subtyping and Variance][nom] nomicon chapter for //! better explanation) //! //! To mitigate this issue and control the variance there is a type called //! [`core::marker::PhantomData<T>`][phd]. [`PhantomData<T>`][phd] is a //! zero-sized type that acts like it owns `T`. //! //! However, [`PhantomData`][phd] comes with a number of issues: //! 1. Variance is a hard thing by itself, but [`PhantomData`][phd] makes it //! even harder to understand. It's not straightforward to understand what //! statement like `PhantomData<fn(A, B) -> B>` does (contravariant over `A` //! and invariant over `B`) //! 2. Sometimes it works badly in `const` context (see next //! [paragraph](#function-pointers-in-const-fn-are-unstable)) //! //! `phantasm`'s naming helps with the first by making the original intention //! clearer (though variance still is a hard-to-understand thing) //! //! [nom]: https://doc.rust-lang.org/nomicon/subtyping.html#subtyping-and-variance //! //! ## function pointers in `const fn` are unstable //! //! It's common practice to make a type invariant over `T` with //! `PhantomData<fn(T) -> T>`. However, if you've ever tried to use it in a //! `const fn`, you know that it's painful (see [rust-lang/69459][my_issue] and //! [rust-lang/67649][or_issue]). This crate helps with this problem: //! //! ``` //! use phantasm::Invariant; //! //! pub struct Test<T>(Invariant<T>); //! //! impl<T> Test<T> { //! pub const fn new() -> Self { //! Self(Invariant) // just works //! } //! } //! ``` //! [my_issue]: https://github.com/rust-lang/rust/issues/69459 //! [or_issue]: https://github.com/rust-lang/rust/issues/67649 //! //! ## life //! //! For variance over lifetimes, use `&'l ()`: //! ``` //! use phantasm::{Contravariant, Covariant, Invariant}; //! //! # // yep, I just don't want to copy&paste everything yet again //! struct Test<'a, 'b, 'c>(Invariant<&'a ()>, Covariant<&'b ()>, Contravariant<&'c ()>); //! ``` //! //! ## comparison operators cannot be chained //! //! Note: you can't use `Invariant<Ty>` as a value (just as //! [`PhantomData`][phd]). To create `Invariant<Ty>` value use turbofish: //! `Invariant::<Ty>` (same goes for both [`Covariant<T>`][cov] and //! [`Contravariant<T>`][cnt]) //! //! ```compile_fail //! // won't compile //! let _ = phantasm::Invariant<i32>; //! ``` //! ``` //! use phantasm::Invariant; //! // ok //! let _ = Invariant::<i32>; //! // Both forms are acceptable in type possition //! struct A<T>(Invariant<T>); //! struct B<T>(Invariant<T>); //! ``` //! //! ## many types //! //! When you need to set variance of many types at once, just use a tuple: //! ``` //! struct Test<A, B>(phantasm::Covariant<(A, B)>); //! ``` #![cfg_attr(not(test), no_std)] // `format!` is used in tests #![allow(type_alias_bounds)] // for :?Sized bound #![deny(missing_docs)] #![forbid(unsafe_code)] /// Marker zero-sized type that is invariant over `T`. /// /// "Invariant" means that given `F<_>`, `Super` and `Sub` (where `Sub` is a /// subtype of `Super`), `F<Sub>` is **not** a subtype of `F<Super>` and vice /// versa - `F<Super>` is **not** a subtype of `F<Sub>` /// /// ## Examples /// /// ``` /// // This struct is invariant over `T` /// struct Test<T>(phantasm::Invariant<T> /* ... */); /// /// let _: Test<i32> = Test(phantasm::Invariant); /// let _ = Test(phantasm::Invariant::<i32>); /// ``` /// /// ```compile_fail /// // `F<Super>` is **not** a subtype of `F<Sub>` /// fn fail<'l>(arg: Invariant<&'l ()>) -> Invariant<&'static ()> { /// arg /// } /// ``` /// ```compile_fail /// // `F<Sub>` is **not** a subtype of `F<Super>` /// fn fail<'l>(arg: Invariant<&'static ()>) -> Invariant<&'l ()> { /// arg /// } /// ``` /// /// ## See also /// /// - [crate docs](crate) /// - [`PhantomData`](core::marker::PhantomData) /// - [Subtyping and Variance](https://doc.rust-lang.org/nomicon/subtyping.html) /// nomicon chapter pub type Invariant<T: ?Sized> = r#impl::Invariant<T>; /// Marker zero-sized type that is covariant over `T`. /// /// "Covariant" means that given `F<_>`, `Super` and `Sub` (where `Sub` is a /// subtype of `Super`), `F<Sub>` **is** a subtype of `F<Super>` (but `F<Super>` /// is **not** a subtype of `F<Sub>`) /// /// ## Examples /// /// ``` /// // This struct is covariant over `T` /// struct Test<T>(phantasm::Covariant<T> /* ... */); /// /// let _: Test<i32> = Test(phantasm::Covariant); /// let _ = Test(phantasm::Covariant::<i32>); /// ``` /// /// ```compile_fail /// use phantasm::Covariant; /// // `F<Super>` is **not** a subtype of `F<Sub>` /// fn fail<'l>(arg: Covariant<&'l ()>) -> Covariant<&'static ()> { /// arg /// } /// ``` /// ``` /// use phantasm::Covariant; /// // `F<Sub>` **is** a subtype of `F<Super>` /// fn pass<'l>(arg: Covariant<&'static ()>) -> Covariant<&'l ()> { /// arg /// } /// ``` /// /// ## See also /// /// - [crate docs](crate) /// - [`PhantomData`](core::marker::PhantomData) /// - [Subtyping and Variance](https://doc.rust-lang.org/nomicon/subtyping.html) /// nomicon chapter pub type Covariant<T: ?Sized> = r#impl::Covariant<T>; /// Marker zero-sized type that is contravariant over `T`. /// /// "Contravariant" means that given `F<_>`, `Super` and `Sub` (where `Sub` is a /// subtype of `Super`), `F<Super>` **is** a subtype of `F<Sub>` (but `F<Sub>` /// is **not** a subtype of `F<Super>`) /// /// ## Examples /// /// ``` /// // This struct is covariant over `T` /// struct Test<T>(phantasm::Contravariant<T> /* ... */); /// /// let _: Test<i32> = Test(phantasm::Contravariant); /// let _ = Test(phantasm::Contravariant::<i32>); /// ``` /// /// ```compile_fail /// use phantasm::Contravariant; /// // `F<Sub>` is **not** a subtype of `F<Super>` /// fn fail<'l>(arg: Contravariant<&'static ()>) -> Contravariant<&'l ()> { /// arg /// } /// ``` /// ``` /// use phantasm::Contravariant; /// // `F<Super>` **is** a subtype of `F<Sub>` /// fn pass<'l>(arg: Contravariant<&'l ()>) -> Contravariant<&'static ()> { /// arg /// } /// ``` /// /// ## See also /// /// - [crate docs](crate) /// - [`PhantomData`](core::marker::PhantomData) /// - [Subtyping and Variance](https://doc.rust-lang.org/nomicon/subtyping.html) /// nomicon chapter pub type Contravariant<T: ?Sized> = r#impl::Contravariant<T>; /// Brings `Invariant`/`Covariant`/`Contravariant` values to scope (in addition /// to types) #[doc(hidden)] pub use crate::r#impl::reexport_hack::*; /// Implementation of the types in the crate. /// /// This is a private module to hide ugly enum implementation details and make /// doc cleaner. mod r#impl { // Note: the idea of the implementation is actually copy-pasted from // dtolnay's ghost <https://docs.rs/ghost/> (I haven't used it to be 0-dep, yep, I'm a bad guy) /// A hack to have both type and variant in the same namespace. /// /// This allows to do the following: /// /// ``` /// use phantasm::Invariant; /// /// let _: Invariant<i32> = Invariant::<i32>; // (same goes for `Covariant` and `Contravariant`) /// // |^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^\ /// // *--- type value (variant) /// ``` /// /// (idk how it works, but it works) pub mod reexport_hack { pub use super::{Contravariant::Contravariant, Covariant::Covariant, Invariant::Invariant}; } /// Replacement for `!` aka never that will never be stabilized. #[derive(Copy, Clone, Debug, Ord, PartialOrd, Eq, PartialEq, Hash)] pub enum Never {} /// For documentation see [`Invariant`](crate::Invariant#type)'s docs. pub enum Invariant<T: ?Sized> { /// Uninhabited variant that uses `T`. #[doc(hidden)] #[deprecated( since = "0.1.0", note = "you shouldn't use `Invariant` as a enum and/or use `__Phantom` variant of it. \ This variant is only used to use the generic parameter. It's implementation \ detail and may change at any time." )] __Phantom(core::marker::PhantomData<fn(T) -> T>, Never), // /^^^^^^^^^^ // `fn(T) -> U` is **contra**variant // over `T` and covariant over `U`, so // `fn(T) -> T` is invariant over `T` /// The only possible [`Invariant<_>`][inv] value. For type see /// [`Invariant`][inv] docs. /// /// [inv]: crate::Invariant#type Invariant, } /// For documentation see [`Covariant`](crate::Covariant#type)'s docs. pub enum Covariant<T: ?Sized> { /// Uninhabited variant that uses `T`. #[doc(hidden)] #[deprecated( since = "0.1.0", note = "you shouldn't use `Covariant` as a enum and/or use `__Phantom` variant of it. \ This variant is only used to use the generic parameter. It's implementation \ detail and may change at any time." )] __Phantom(core::marker::PhantomData<fn(()) -> T>, Never), // /^^^^^^^^^^^ // `fn(_) -> U` is covariant over `U` /// The only possible [`Covariant<_>`][cov] value. For type see /// [`Covariant`][cov] docs. /// /// [cov]: crate::Covariant#type Covariant, } /// For documentation, see [`Contravariant`](crate::Contravariant#type)'s /// docs. pub enum Contravariant<T: ?Sized> { /// Uninhibited variant that uses `T`. #[doc(hidden)] #[deprecated( since = "0.1.0", note = "you shouldn't use `Contravariant` as a enum and/or use `__Phantom` variant of \ it. This variant is only used to use the generic parameter. It's \ implementation detail and may change at any time." )] __Phantom(core::marker::PhantomData<fn(T) -> ()>, Never), // /^^^^^^^^^^^ // `fn(T) -> _` is **contra**variant // over `T` /// The only possible [`Contravariant<_>`][cnt] value. For type see /// [`Contravariant`][cnt] docs. /// /// [cnt]: crate::Contravariant#type Contravariant, } macro_rules! impls { (for $T:ident) => { impl<T: ?Sized> Copy for $T<T> {} impl<T: ?Sized> Clone for $T<T> { fn clone(&self) -> Self { crate::$T } } impl<T: ?Sized> Default for $T<T> { fn default() -> Self { crate::$T } } impl<T: ?Sized> core::fmt::Debug for $T<T> { fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { f.write_str(stringify!($T)) } } impl<T: ?Sized> Ord for $T<T> { fn cmp(&self, _: &Self) -> core::cmp::Ordering { // There is only one possible value, so it's always equal to itself core::cmp::Ordering::Equal } } impl<T: ?Sized> PartialOrd for $T<T> { fn partial_cmp(&self, _: &Self) -> Option<core::cmp::Ordering> { // There is only one possible value, so it's always equal to itself Some(core::cmp::Ordering::Equal) } } impl<T: ?Sized> Eq for $T<T> {} impl<T: ?Sized> PartialEq for $T<T> { fn eq(&self, _: &Self) -> bool { // There is only one possible value, so it's always equal to itself true } } impl<T: ?Sized> core::hash::Hash for $T<T> { fn hash<H: core::hash::Hasher>(&self, _: &mut H) {} } }; } impls!(for Invariant); impls!(for Covariant); impls!(for Contravariant); } #[cfg(any(test, doctest /* needed for compile_fail tests */))] mod tests { use crate::{Contravariant, Covariant, Invariant}; use core::mem::size_of; type T = [u8]; // Just an example type. Can be any type actually. /// Tests that `Invariant` can be created in const context. const _: Invariant<T> = Invariant::<T>; /// Tests that `Covariant` can be created in const context. const _: Covariant<T> = Covariant::<T>; /// Tests that `Contravariant` can be created in const context. const _: Contravariant<T> = Contravariant::<T>; #[test] fn zstness() { assert_eq!(size_of::<Invariant<T>>(), 0); assert_eq!(size_of::<Covariant<T>>(), 0); assert_eq!(size_of::<Contravariant<T>>(), 0); } #[test] fn debug() { assert_eq!(format!("{:?}", Invariant::<T>), "Invariant"); assert_eq!(format!("{:?}", Covariant::<T>), "Covariant"); assert_eq!(format!("{:?}", Contravariant::<T>), "Contravariant"); } /// ```compile_fail /// use phantasm::Invariant; /// fn fail<'l>(arg: Invariant<&'l ()>) -> Invariant<&'static ()> { /// arg /// } /// ``` /// ```compile_fail /// use phantasm::Invariant; /// fn fail<'l>(arg: Invariant<&'static ()>) -> Invariant<&'l ()> { /// arg /// } /// ``` #[allow(dead_code)] fn invariance() {} /// ```compile_fail /// use phantasm::Covariant; /// fn fail<'l>(arg: Covariant<&'l ()>) -> Covariant<&'static ()> { /// arg /// } /// ``` #[allow(dead_code)] fn covariance<'l>(arg: Covariant<&'static ()>) -> Covariant<&'l ()> { // This coercion is only legal because the lifetime parameter is // covariant. If it were contravariant or invariant, // this would not compile. arg } /// ```compile_fail /// use phantasm::Contravariant; /// fn fail<'l>(arg: Contravariant<&'static ()>) -> Contravariant<&'l ()> { /// arg /// } /// ``` #[allow(dead_code)] fn contravariance<'l>(arg: Contravariant<&'l ()>) -> Contravariant<&'static ()> { // This coercion is only legal because the lifetime parameter is // contravariant. If it were covariant or invariant, // this would not compile. arg } }