taggables 0.2.0

Tagged types à rebours
Documentation
// Read the README - it's in the name.
#![doc = include_str!("../README.md")]
#![deny(missing_docs)]
#![no_std]

mod macros;
mod wrapper;
pub use wrapper::{Tagged, WrapWithTag};

/// Type used as semantic tags.
///
/// Technically, any type can be used as a tag, but the
/// most idiomatic way is to define an empty enum:
/// ```rust
/// pub enum SurnameTag {}
/// impl taggables::SemanticTag for SurnameTag {
///     fn name() -> &'static str {
///         "Surname"
///     }
/// }
/// ```
///
/// For 99% of cases you should not implement this trait manually
/// and use the [semantic_tags] macro instead.
///
/// Implementations are also provided for `()` and [Infallible].
/// While these types carry no information, they naturally map
/// onto important elements in type lattices and categories,
/// which makes them useful for modelling.
///
/// Additionally, by this crate's convention `()` is used as the
/// default "no semantic" tag of types generated by [taggables].
///
/// [Infallible]: core::convert::Infallible
pub trait SemanticTag {
    /// Human-readable name of this tag's semantic.
    fn name() -> &'static str;
}

impl SemanticTag for () {
    fn name() -> &'static str {
        "()"
    }
}

impl SemanticTag for core::convert::Infallible {
    fn name() -> &'static str {
        "!"
    }
}

/// Type that carries a semantic tag parameter.
///
/// # Usage
///
/// ```rust
/// # use std::marker::PhantomData;
///
/// pub struct TaggableString<S = ()>(String, PhantomData<fn(S) -> S>);
///
/// impl<S> taggables::Taggable for TaggableString<S> {
///     type Tag = S;
///     type This<T> = TaggableString<T>;
///     fn retag<T>(self) -> TaggableString<T> {
///         TaggableString(self.0, PhantomData)
///     }
/// }
///
/// taggables::semantic_tags! {
///     pub FirstNameTag,
///     pub SurnameTag,
/// }
///
/// pub type FirstName = TaggableString<FirstNameTag>;
/// pub type Surname = TaggableString<SurnameTag>;
/// ```
pub trait Taggable: Sized {
    /// Semantic tag of this instantiation.
    type Tag;

    /// Type constructor of `Self` with all parameters fixed except the tag.
    ///
    /// `This<Self::Tag>` should be equal to `Self`.
    type This<S>;

    /// Change the semantic tag of `self` to `S`.
    fn retag<S>(self) -> Self::This<S>;

    /// Change the tag of `self` and return `That`.
    fn retag_into<That: Taggable>(self) -> That
    where
        Self: Taggable<This<That::Tag> = That>,
    {
        self.retag::<That::Tag>()
    }

    /// Replace the semantic tag with meaningless `()`.
    fn untag(self) -> Self::This<()> {
        self.retag::<()>()
    }

    /// Name of `self`'s semantic.
    fn tag_name() -> &'static str
    where
        Self::Tag: SemanticTag,
    {
        <Self::Tag as SemanticTag>::name()
    }
}