typeward 0.6.0

A type-driven parser combinator library for Rust.
Documentation
use std::borrow::Cow;

use crate::token::Token;
use crate::{
    error::{ParseResult, SourceSpan},
    input::{BorrowInput, FromInputStr, Input},
    parse::{Parse, ParseOffsetInput, current_parse_offset},
};

impl<'a, I> Parse<'a, I> for &'a str
where
    I: BorrowInput<'a> + ParseOffsetInput<'a>,
{
    #[inline]
    fn parse_with_context(
        input: I,
        context: &mut crate::parse::ParseOffsetContext,
    ) -> ParseResult<(Self, I)> {
        if input.try_is_empty()? {
            let start = current_parse_offset(context, input);
            return Err(
                crate::error::ParseError::custom("expected string, found end of input")
                    .with_span(SourceSpan::point(start)),
            );
        }

        let (token, rest) = input.take_while_borrowed(|c: char| !c.is_whitespace())?;
        if token.is_empty() {
            let start = current_parse_offset(context, input);
            let preview = crate::error::preview_input(
                input.display().as_ref(),
                crate::error::DEFAULT_INPUT_PREVIEW,
            );
            return Err(crate::error::ParseError::custom(format!(
                "expected string, found '{preview}'"
            ))
            .with_span(SourceSpan::point(start)));
        }

        Ok((token, rest))
    }
}

impl<'a, I> Parse<'a, I> for String
where
    I: ParseOffsetInput<'a>,
{
    #[inline]
    fn parse_with_context(
        input: I,
        context: &mut crate::parse::ParseOffsetContext,
    ) -> ParseResult<(Self, I)> {
        if input.try_is_empty()? {
            let start = current_parse_offset(context, input);
            return Err(
                crate::error::ParseError::custom("expected string, found end of input")
                    .with_span(SourceSpan::point(start)),
            );
        }

        let (token, rest) = input.take_while(|c: char| !c.is_whitespace())?;
        if token.is_empty() {
            let start = current_parse_offset(context, input);
            let preview = crate::error::preview_input(
                input.display().as_ref(),
                crate::error::DEFAULT_INPUT_PREVIEW,
            );
            return Err(crate::error::ParseError::custom(format!(
                "expected string, found '{preview}'"
            ))
            .with_span(SourceSpan::point(start)));
        }

        Ok((token.into_owned(), rest))
    }
}

/// Parses input up to the next occurrence of token `T`.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(
    feature = "serde",
    serde(bound(
        serialize = "S: serde::Serialize",
        deserialize = "S: serde::Deserialize<'de>"
    ))
)]
pub struct TakeTillToken<T, S = String>
where
    S: AsRef<str>,
{
    value: S,
    #[cfg_attr(feature = "serde", serde(skip))]
    _marker: std::marker::PhantomData<T>,
}

impl<T, S> TakeTillToken<T, S>
where
    S: AsRef<str>,
{
    /// Returns the parsed text and consumes the wrapper.
    #[must_use]
    pub fn into_inner(self) -> S {
        self.value
    }

    /// Returns the parsed text as a string slice.
    #[must_use]
    pub fn as_str(&self) -> &str {
        self.value.as_ref()
    }
}

impl<T, S: AsRef<str>> std::ops::Deref for TakeTillToken<T, S> {
    type Target = str;

    fn deref(&self) -> &Self::Target {
        self.value.as_ref()
    }
}

impl<T, S: AsRef<str>, O: AsRef<str>> PartialEq<O> for TakeTillToken<T, S> {
    fn eq(&self, other: &O) -> bool {
        self.value.as_ref() == other.as_ref()
    }
}

impl<T, S> crate::parse::Unpack<S> for TakeTillToken<T, S>
where
    S: AsRef<str>,
{
    #[inline]
    fn unpack(self) -> S {
        self.into_inner()
    }
}

impl<'a, I, T, S> Parse<'a, I> for TakeTillToken<T, S>
where
    I: Input<'a>,
    T: Token,
    S: AsRef<str> + FromInputStr<'a, I>,
{
    #[inline]
    fn parse_with_context(
        input: I,
        _context: &mut crate::parse::ParseOffsetContext,
    ) -> ParseResult<(Self, I)> {
        let (value, rest) = input.take_till_str(T::TEXT)?;
        Ok((
            Self {
                value: S::from_input_str(value)?,
                _marker: std::marker::PhantomData,
            },
            rest,
        ))
    }
}

/// Borrowed string output for [`TakeTillToken`].
pub type TakeTillTokenStr<'a, T> = TakeTillToken<T, &'a str>;
/// Copy-on-write string output for [`TakeTillToken`].
pub type TakeTillTokenCow<'a, T> = TakeTillToken<T, Cow<'a, str>>;
/// Owned string output for [`TakeTillToken`].
pub type TakeTillTokenString<T> = TakeTillToken<T, String>;

#[cfg(test)]
mod tests {
    use crate::literals::Comma;
    use crate::primitives::prelude::AlphaString;

    use super::*;

    #[test]
    fn test_cow_parse() {
        let input = "hello world";
        let (cow, rest) = Cow::parse(input).unwrap();
        assert_eq!(cow, "hello");
        assert_eq!(rest, " world");
    }

    #[test]
    fn test_alpha_parse_bytes() {
        let (word, rest) = AlphaString::parse(b"hello world".as_slice()).unwrap();
        assert_eq!(word.value, "hello");
        assert_eq!(rest, b" world");
    }

    #[test]
    fn test_take_till_token() {
        let (value, rest) = TakeTillToken::<Comma>::parse("hello,world").unwrap();
        assert_eq!(value, "hello");
        assert_eq!(rest, ",world");
    }

    #[test]
    fn test_owned_parser_supports_minimal_custom_input() {
        #[derive(Clone, Copy)]
        struct StreamingStub<'a>(&'a str);

        impl<'a> Input<'a> for StreamingStub<'a> {
            fn input_len(self) -> usize {
                self.0.len()
            }

            fn position(self) -> Option<usize> {
                Some(self.0.as_ptr() as usize)
            }

            fn display(self) -> Cow<'a, str> {
                self.0.into()
            }

            fn take_char(self) -> ParseResult<Option<(char, Self)>> {
                let mut chars = self.0.chars();
                Ok(chars.next().map(|ch| (ch, Self(chars.as_str()))))
            }

            fn slice_to(self, end: Self) -> ParseResult<Self> {
                let consumed = self
                    .0
                    .len()
                    .checked_sub(end.0.len())
                    .ok_or_else(|| crate::error::ParseError::custom("invalid input bounds"))?;
                Ok(Self(&self.0[..consumed]))
            }
        }

        let (parsed, rest) = String::parse(StreamingStub("hello world")).unwrap();
        assert_eq!(parsed, "hello");
        assert_eq!(rest.0, " world");

        // The default implementations should cover the rest of the input API.
        let (matched, rest) = StreamingStub("  abcXYZdef").take_till_str("XYZ").unwrap();
        assert_eq!(matched, "  abc");
        assert_eq!(rest.0, "XYZdef");

        assert_eq!(StreamingStub("  value").trim_start().0, "value");
        assert!(StreamingStub("").is_empty());
        assert_eq!(
            StreamingStub("abcdef").find("cd").unwrap().unwrap().0,
            "cdef"
        );

        // Offset tracking also works without a manual ParseOffsetInput impl.
        let spanned =
            crate::parse::parse_complete_input_spanned::<_, char>(StreamingStub("a")).unwrap();
        assert_eq!(spanned.span, crate::error::SourceSpan::new(0, 1));
    }
}