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
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
//! 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
//! in a very similar way 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,E0392
//! 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 if `Slice` should be
//! covariant, contravariant or invariant over `'a`. What this means is that
//! rustc doesn't know if `Slice<'static, _>` should be a subtype of `Slice<'a,
//! _>` or vice versa or neither. See [Subtyping and Variance][nom] nomicon
//! chapter for better explanation.
//!
//! To mitigate this issue and control the variance there is a type called
//! [`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 to understand 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 issue by making the original
//! intention clearer (though variance still is a hard-to-understand thing) and
//! with the second by doing some _hacks under the hood_.
//!
//! [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]) because before Rust `1.61.0` function pointers
//! in `const fn` were unstable, see [stabilization PR] for more. 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 (even on old rust)
//!     }
//! }
//! ```
//! [my_issue]: https://github.com/rust-lang/rust/issues/69459
//! [or_issue]: https://github.com/rust-lang/rust/issues/67649
//! [stabilization PR]: https://github.com/rust-lang/rust/pull/93827
//!
//! ## lifetimes
//!
//! For variance over lifetimes, use `Lt<'l>`:
//! ```
//! use phantasm::{Contravariant, Covariant, Invariant, Lt};
//!
//! # // yep, I just don't want to copy&paste everything yet again
//! struct Test<'a, 'b, 'c>(Invariant<Lt<'a>>, Covariant<Lt<'b>>, Contravariant<Lt<'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 position
//! struct NoFish<T>(Invariant<T>);
//! struct Turbofish<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)>);
//! ```
//!
//! ## MSRV
//!
//! Minimal supported rustc version is `1.40.0`.
//! I don't expect this crate to be changed much,
//! so MSRV will likely stay constant for the rest of eternity.
#![cfg_attr(not(test), no_std)] // `format!` is used in tests
#![allow(type_alias_bounds)] // for :?Sized bound to appear in docs
#![deny(missing_docs)]
//#![deny(rustdoc::broken_intra_doc_links)] // commented out to support rust < 1.52
#![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
///
/// ```
/// use phantasm::Invariant;
///
/// // This struct is invariant over `T`
/// struct Test<T>(Invariant<T> /* ... */);
///
/// let _: Test<i32> = Test(Invariant /* ... */);
/// let _ = Test::<i32>(Invariant /* ... */);
/// let _ = Test(Invariant::<i32> /* ... */);
/// ```
///
/// ```compile_fail,E0308
/// use phantasm::{Invariant, Lt};
///
/// // `F<Sub>` is **not** a subtype of `F<Super>`
/// fn covariant_fail<'l>(with_sub: Invariant<Lt<'static>>) {
///     let with_super: Invariant<Lt<'l>> = with_sub; // mismatched types
/// }
/// ```
///
/// ```compile_fail,E0308
/// use phantasm::{Invariant, Lt};
///
/// // `F<Super>` is **not** a subtype of `F<Sub>`
/// fn contravariant_fail<'l>(with_super: Invariant<Lt<'l>>) {
///     let with_sub: Invariant<Lt<'static>> = with_super; // mismatched types
/// }
/// ```
///
/// ## 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
///
/// ```
/// use phantasm::Covariant;
///
/// // This struct is covariant over `T`
/// struct Test<T>(Covariant<T> /* ... */);
///
/// let _: Test<i32> = Test(Covariant /* ... */);
/// let _ = Test::<i32>(Covariant /* ... */);
/// let _ = Test(Covariant::<i32> /* ... */);
/// ```
///
/// ```
/// use phantasm::{Covariant, Lt};
///
/// // `F<Sub>` **is** a subtype of `F<Super>`
/// fn covariant_pass<'l>(with_sub: Covariant<Lt<'static>>) {
///     let with_super: Covariant<Lt<'l>> = with_sub;
/// }
/// ```
///
/// ```compile_fail,E0308
/// use phantasm::{Covariant, Lt};
///
/// // `F<Super>` is **not** a subtype of `F<Sub>`
/// fn contravariant_fail<'l>(with_super: Covariant<Lt<'l>>) {
///     let with_sub: Covariant<Lt<'static>> = with_super; // mismatched types
/// }
/// ```
///
/// ## 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
///
/// ```
/// use phantasm::Contravariant;
///
/// // This struct is covariant over `T`
/// struct Test<T>(Contravariant<T> /* ... */);
///
/// let _: Test<i32> = Test(Contravariant /* ... */);
/// let _ = Test::<i32>(Contravariant /* ... */);
/// let _ = Test(Contravariant::<i32> /* ... */);
/// ```
///
/// ```compile_fail,E0308
/// use phantasm::{Contravariant, Lt};
///
/// // `F<Sub>` is **not** a subtype of `F<Super>`
/// fn covariant_fail<'l>(with_sub: Contravariant<Lt<'static>>) {
///     let with_super: Contravariant<Lt<'l>> = with_sub; // mismatched types
/// }
/// ```
///
/// ```
/// use phantasm::{Contravariant, Lt};
///
/// // `F<Super>` **is** a subtype of `F<Sub>`
/// fn contravariant_pass<'l>(with_super: Contravariant<Lt<'l>>) {
///     let with_sub: Contravariant<Lt<'static>> = with_super;
/// }
/// ```
///
/// ## 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>;

/// Marker zero-sized type that is covariant over `'lifetime`.
///
/// You can use it with other types from this crate to denote variance over a
/// particular lifetime, instead of a type.
pub type Lt<'lifetime> = r#impl::Lt<'lifetime>;

/// 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, Lt::Lt,
        };
    }

    /// 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> {
        /// The only possible [`Invariant<_>`][inv] value. For type see
        /// [`Invariant`][inv] docs.
        ///
        /// [inv]: crate::Invariant#type
        Invariant,

        /// 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`
    }

    /// For documentation see [`Covariant`](crate::Covariant#type)'s docs.
    pub enum Covariant<T: ?Sized> {
        /// The only possible [`Covariant<_>`][cov] value. For type see
        /// [`Covariant`][cov] docs.
        ///
        /// [cov]: crate::Covariant#type
        Covariant,

        /// 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`
    }

    /// For documentation, see [`Contravariant`](crate::Contravariant#type)'s
    /// docs.
    pub enum Contravariant<T: ?Sized> {
        /// The only possible [`Contravariant<_>`][cnt] value. For type see
        /// [`Contravariant`][cnt] docs.
        ///
        /// [cnt]: crate::Contravariant#type
        Contravariant,

        /// 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`
    }

    /// For documentation see [`Life`](crate::Life#type)'s docs.
    #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
    pub enum Lt<'a> {
        /// The only possible [`Lt<_>`][life] value. For type see
        /// [`Lt`][life] docs.
        ///
        /// [life]: crate::Lt#type
        Lt,

        /// Uninhibited variant that uses `'a`.
        #[doc(hidden)]
        #[deprecated(
            since = "0.1.3",
            note = "you shouldn't use `Life` 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<&'a ()>, Never),
    }

    // #[derive] doesn't work for us since it adds unnecessary bounds to generics
    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);

    impl core::fmt::Debug for Lt<'_> {
        fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
            f.write_str("Lt")
        }
    }
}

#[cfg(any(test, doctest /* needed for compile_fail tests */))]
mod tests {
    use crate::{Contravariant, Covariant, Invariant, Lt};
    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>;
    const _: Lt<'static> = Lt::<'static>;

    #[test]
    fn zstness() {
        assert_eq!(size_of::<Invariant<T>>(), 0);
        assert_eq!(size_of::<Covariant<T>>(), 0);
        assert_eq!(size_of::<Contravariant<T>>(), 0);
        assert_eq!(size_of::<Lt<'static>>(), 0);
    }

    #[test]
    fn debug() {
        assert_eq!(format!("{:?}", Invariant::<T>), "Invariant");
        assert_eq!(format!("{:?}", Covariant::<T>), "Covariant");
        assert_eq!(format!("{:?}", Contravariant::<T>), "Contravariant");
        assert_eq!(format!("{:?}", Lt::<'static>), "Lt");
    }

    /// ```compile_fail,E0308
    /// use phantasm::{Invariant, Lt};
    /// fn contravariant_fail<'l>(arg: Invariant<Lt<'l>>) -> Invariant<Lt<'static>> {
    ///     arg
    /// }
    /// ```
    /// ```compile_fail,E0308
    /// use phantasm::{Invariant, Lt};
    /// fn covariant_fail<'l>(arg: Invariant<Lt<'static>>) -> Invariant<Lt<'l>> {
    ///     arg
    /// }
    /// ```
    #[allow(dead_code)]
    fn invariance() {}

    /// ```compile_fail,E0308
    /// use phantasm::{Covariant, Lt};
    /// fn contravariant_fail<'l>(arg: Covariant<Lt<'l>>) -> Covariant<Lt<'static>> {
    ///     arg
    /// }
    /// ```
    #[allow(dead_code)]
    fn covariance<'l>(arg: Covariant<Lt<'static>>) -> Covariant<Lt<'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,E0308
    /// use phantasm::{Contravariant, Lt};
    /// fn covariant_fail<'l>(arg: Contravariant<Lt<'static>>) -> Contravariant<Lt<'l>> {
    ///     arg
    /// }
    /// ```
    #[allow(dead_code)]
    fn contravariance<'l>(arg: Contravariant<Lt<'l>>) -> Contravariant<Lt<'static>> {
        // This coercion is only legal because the lifetime parameter is
        // contravariant. If it were covariant or invariant,
        // this would not compile.
        arg
    }
}