typeward 0.5.0

A type-driven parser combinator library for Rust.
Documentation
//! Recursive output extraction for parser wrappers.
//!
//! Parser combinators often wrap their useful output in structural types such
//! as [`Ws`](crate::combinators::Ws) or
//! [`DelimitedExact`](crate::combinators::DelimitedExact). [`Unpack`] lets a
//! caller request the output type they actually want and recursively removes
//! those transparent wrappers.
//!
//! Most users do not call [`Unpack`] directly. Deriving
//! [`Parse`](crate::parse::Parse) uses it automatically for
//! `#[parse(from(ParserType))]` fields that do not provide an explicit mapper.
//! See [`Unpack`] for the conversion rules.

use std::{borrow::Cow, marker::PhantomData};

/// Marker for types that are already their own unpacked output.
///
/// The identity [`Unpack`] implementation is limited to types implementing
/// this trait so that it cannot overlap with the transparent-wrapper
/// implementations. Types that derive [`Parse`](crate::parse::Parse) implement
/// this trait automatically.
///
/// Containers such as `Vec`, `Option`, `Span`, `Nested`, `Many1`, and `Collect`
/// intentionally do not implement this trait: they recursively unpack their
/// contents instead of being their own unpacked output when their contents are
/// wrappers.
pub trait Unpackable {}

/// Converts a parsed value into a requested output type by recursively
/// unwrapping transparent parser wrappers.
///
/// The target type is chosen by the caller, so nested wrappers can be removed
/// in a single call:
///
/// ```
/// use typeward::prelude::*;
///
/// type Values = Ws<BracketedList<Ws<i64>, Ws<Comma>>>;
///
/// let (values, rest) = Values::parse("[1, 2, 3]").unwrap();
/// assert_eq!(rest, "");
/// let values: Vec<i64> = values.unpack();
/// assert_eq!(values, [1, 2, 3]);
/// ```
///
/// # Conversion rules
///
/// - Transparent wrappers such as [`Ws`](crate::combinators::Ws),
///   [`DelimitedExact`](crate::combinators::DelimitedExact),
///   [`DelimNested`](crate::combinators::DelimNested), and
///   [`And`](crate::combinators::And) are removed.
/// - Containers recurse into their contents: `Vec<T>` becomes `Vec<U>`,
///   `Option<T>` becomes `Option<U>`, and tuples unpack each element.
///   Collection wrappers such as [`Many1`](crate::collections::Many1),
///   [`Repeat`](crate::collections::Repeat),
///   [`Separated`](crate::combinators::Separated), and
///   [`Collect`](crate::collections::Collect) unpack to their item collection.
/// - [`Span<T>`](crate::combinators::Span) and
///   [`Nested<T>`](crate::parse::Nested) preserve their wrapper while unpacking
///   the inner value, so `Span<Ws<i64>>` becomes `Span<i64>`. Call
///   `into_inner()` first to drop the wrapper.
/// - `Box<T>` is transparent: `Box<Ws<i64>>` unpacks to `i64` through Rust's
///   auto-deref. A boxed target such as `Box<i64>` is not supported because it
///   would overlap with the identity implementation; use
///   `Box::new(value.unpack())` instead.
/// - Types that implement [`Unpackable`] unpack to themselves.
///
/// # Relationship to `Into`
///
/// `Unpack` is not a replacement for [`Into`]. The natural conversion
/// `impl<T> From<Ws<T>> for T` is rejected by the orphan rule, and elementwise
/// impls for foreign containers such as `Vec` are impossible because both the
/// trait and the type are foreign. `Unpack` is local and target-directed, which
/// makes recursive container impls possible while keeping a controlled identity
/// case through [`Unpackable`].
///
/// # Derived parsers
///
/// Deriving [`Parse`](crate::parse::Parse) uses `Unpack` automatically for
/// `#[parse(from(ParserType))]` fields that do not provide an explicit mapper.
/// Omit `from` when the field type is already the parser type, and pass an
/// explicit mapper when you need a custom conversion.
pub trait Unpack<T> {
    /// Unpacks `self` into `T`.
    fn unpack(self) -> T;
}

impl<T: Unpackable> Unpack<T> for T {
    #[inline]
    fn unpack(self) -> T {
        self
    }
}

macro_rules! impl_unpack_identity {
    ($($ty:ty),+ $(,)?) => {
        $(
            impl Unpackable for $ty {}
        )+
    };
}

impl_unpack_identity!(
    (),
    char,
    &str,
    String,
    Cow<'_, str>,
    bool,
    u8,
    u16,
    u32,
    u64,
    u128,
    usize,
    i8,
    i16,
    i32,
    i64,
    i128,
    isize,
    f32,
    f64,
);

impl<T, U> Unpack<Vec<U>> for Vec<T>
where
    T: Unpack<U>,
{
    #[inline]
    fn unpack(self) -> Vec<U> {
        self.into_iter().map(crate::parse::Unpack::unpack).collect()
    }
}

impl<T, U> Unpack<Option<U>> for Option<T>
where
    T: Unpack<U>,
{
    #[inline]
    fn unpack(self) -> Option<U> {
        self.map(crate::parse::Unpack::unpack)
    }
}

macro_rules! unpack_tuple {
    ($($ty:ty),*) => {
      pastey::paste! {
        impl<$($ty),* , $([< T $ty >]),*> Unpack<($([< T $ty >]),*)> for ($($ty),*)
        where
            $($ty: Unpack<[< T $ty >]>),*
        {
            #[inline]
            fn unpack(self) -> ($([< T $ty >]),*) {
                let ($([<$ty:lower>]),*) = self;
                ($([<$ty:lower>].unpack()),*)
            }
        }
      }
    };
}

for_all_tuples!(unpack_tuple);

impl<T> Unpackable for PhantomData<T> {}

impl<T> Unpack<()> for PhantomData<T> {
    #[inline]
    fn unpack(self) {}
}

#[cfg(test)]
mod tests {
    use std::marker::PhantomData;

    use crate::prelude::*;

    type Quoted = DelimitedExact<Ws<DoubleQuote>, DoubleQuote, TakeTillToken<DoubleQuote>>;
    type Values = Ws<BracketedList<Ws<i64>, Ws<Comma>>>;
    type Member = and!(Quoted, Ws<Colon>, Ws<i64>);

    #[test]
    fn identity_unpacks_to_itself() {
        let value: i64 = Unpack::unpack(42);
        assert_eq!(value, 42);
    }

    #[test]
    fn tuple_unpacks_to_tuple() {
        let value: (i64, i64) = Unpack::unpack((42, 43));
        assert_eq!(value, (42, 43));
    }

    #[test]
    fn vec_unpacks_wrapped_values() {
        let values: Vec<Ws<i64>> = vec![Ws(1), Ws(2)];
        let values: Vec<i64> = values.unpack();
        assert_eq!(values, [1, 2]);
    }

    #[test]
    fn option_unpacks_wrapped_value() {
        let value: Option<Ws<i64>> = Some(Ws(7));
        let value: Option<i64> = value.unpack();
        assert_eq!(value, Some(7));
    }

    #[test]
    fn box_unpacks_transparently() {
        let value: Box<Ws<i64>> = Box::new(Ws(7));
        let value: i64 = value.unpack();
        assert_eq!(value, 7);
    }

    #[test]
    fn phantom_data_unpacks_to_unit_and_itself() {
        let unit: () = PhantomData::<i64>.unpack();
        assert_eq!(unit, ());

        let identity: PhantomData<i64> = PhantomData::<i64>.unpack();
        assert_eq!(identity, PhantomData);
    }

    #[test]
    fn tuple_unpacks_wrapped_values() {
        let value: (i64, i64) = Unpack::unpack((Ws(42), Ws(43)));
        assert_eq!(value, (42, 43));
    }

    #[test]
    fn tuple_unpacks_one_wrapped_value() {
        let value: (i64, i64) = Unpack::unpack((42, Ws(43)));
        assert_eq!(value, (42, 43));
    }

    #[test]
    fn unpacks_quoted_string() {
        let (value, rest) = Quoted::parse(r#""hello""#).unwrap();
        assert_eq!(rest, "");
        let value: String = value.unpack();
        assert_eq!(value, "hello");
    }

    #[test]
    fn unpacks_nested_list() {
        let (value, rest) = Values::parse("[1, 2, 3]").unwrap();
        assert_eq!(rest, "");
        let value: Vec<i64> = value.unpack();
        assert_eq!(value, [1, 2, 3]);
    }

    #[test]
    fn unpacks_nested_option() {
        let value = Ws::<Option<Ws<i64>>>::parse("42 43").unwrap().0;
        let value: Option<i64> = value.unpack();
        assert_eq!(value, Some(42));
    }

    #[test]
    fn unpacks_filtered_string() {
        let (value, rest) = Ws::<Identifier>::parse("name").unwrap();
        assert_eq!(rest, "");
        let value: String = value.unpack();
        assert_eq!(value, "name");
    }

    #[test]
    fn unpacks_and_into_tuple() {
        let (value, rest) = Member::parse(r#""x": 1"#).unwrap();
        assert_eq!(rest, "");
        let (key, _colon, value): (String, Colon, i64) = value.unpack();
        assert_eq!(key, "x");
        assert_eq!(value, 1);
    }
}