//! Core parser types. use std::fmt; use std::iter::FromIterator; use std::marker::PhantomData; use std::num::{ParseFloatError, ParseIntError}; use std::ops::Deref; use std::rc::Rc; use std::str; use crate::result::{Cursor, Error, ErrorKind, Result}; /// Either left or right. Used for parsers that can return /// either of two types of output. #[derive(Debug, PartialEq, Eq, Clone, Copy)] pub enum Either { /// The left case. Left(L), /// The right case. Right(R), } /// A self-describing parser combinator. pub trait Parser<'a> { /// The output of the parser, in case of success. type Output; /// Parse from the given [`Cursor`]. fn parse_at(&self, input: Cursor<'a>) -> Result<'a, Self::Output>; /// Parse an input string and return a result. On success, returns an output, and any leftover /// input. Otherwise, returns an error. fn parse(&self, input: &'a str) -> std::result::Result<(Self::Output, &'a str), Error<'a>> { self.parse_at(Cursor::from(input)) .map(|(out, rest)| (out, rest.input)) } /// Convert this parser into a boxed trait object. /// /// This is useful when you need to store parsers of different concrete types /// in the same collection, or return different parser implementations from a function. /// /// ``` /// use syntaxe::prelude::*; /// /// let parsers: Vec>> = vec![ /// symbol('!').boxed(), /// symbol('?').boxed(), /// ]; /// ``` fn boxed(self) -> Box> where Self: Sized + 'static, { Box::new(self) } /// Sequence this parser with the next one. /// /// ``` /// use syntaxe::*; /// /// let p = string("moo").then(symbol('!')).then(symbol('?')); /// assert!(p.parse("moo!?").is_ok()); /// ``` fn then>(self, next: P) -> (Self, P) where Self: Sized, { (self, next) } /// Apply this parser, then try to apply the other parser. /// Only the output from this parser is returned. /// /// ``` /// use syntaxe::prelude::*; /// /// let p = symbol('X').skip(symbol('Y')).then(symbol('Z')); /// /// assert_eq!(p.parse("XYZ"), Ok((('X', 'Z'), ""))); /// assert!(p.parse("XZ").is_err()); /// /// let p = symbol('X').skip(optional(symbol('Y'))).then(symbol('Z')); /// /// assert_eq!(p.parse("XYZ"), Ok((('X', 'Z'), ""))); /// assert_eq!(p.parse("XZ"), Ok((('X', 'Z'), ""))); /// ``` fn skip>(self, skip: P) -> impl Parser<'a, Output = Self::Output> where Self: Sized, { move |input| { let (out, rest) = self.parse_at(input)?; skip.parse_at(rest).map(|(_, skipped)| (out, skipped)) } } /// If this parser fails, try another one. /// /// ``` /// use syntaxe::prelude::*; /// /// let p = symbol('!').or(symbol('?')); /// /// assert_eq!(p.parse("?"), Ok(('?', ""))); /// ``` fn or>( self, other: P, ) -> impl Parser<'a, Output = Self::Output> where Self: Sized, { move |input| match self.parse_at(input) { Ok(result) => Ok(result), Err(_) => other.parse_at(input), } } /// Modify the parser output if it succeeds, with the provided function. /// /// ``` /// use syntaxe::prelude::*; /// /// let p = symbol('X').map(|out| (out, out)); /// /// assert_eq!(p.parse("X"), Ok((('X', 'X'), ""))); /// ``` fn map(self, f: F) -> Map where Self: Sized, F: Fn(Self::Output) -> O, { Map { parser: self, f } } /// Modify the parser output if it succeeds, with the provided fallible function. /// /// ``` /// use std::io; /// use syntaxe::prelude::*; /// /// let p = symbol('X').try_map::(|out| /// Err(io::Error::new(io::ErrorKind::Other, format!("failed to parse {out:?}"))) /// ); /// assert!(p.parse("X").is_err()) /// ``` fn try_map( self, f: impl Fn(Self::Output) -> std::result::Result, ) -> impl Parser<'a, Output = O> where E: std::error::Error + 'static, Self: Sized, { move |cursor| { self.parse_at(cursor).and_then(|(out, rest)| match f(out) { Ok(result) => Ok((result, rest)), Err(e) => Err(Error::new(ErrorKind::TryMap(Rc::new(e)), cursor)), }) } } /// Modify the parser output if it succeeds, with the provided value. /// /// ``` /// use syntaxe::*; /// /// let p = symbol('X').value('Y'); /// /// assert_eq!(p.parse("X"), Ok(('Y', ""))); /// ``` fn value(self, val: V) -> impl Parser<'a, Output = V> where Self: Sized, { self.map(move |_| val.clone()) } /// Provide a custom error message in case this parser fails. /// This is useful for more complex parsers, or when the default error is not adequate. fn with_err(self, err: ErrorKind<'a>) -> impl Parser<'a, Output = Self::Output> where Self: Sized, { move |cursor| self.parse_at(cursor).map_err(|e| Error::new(err.clone(), e.cursor)) } /// Try to convert the output of the parser from a string to the specified type. /// /// ``` /// use syntaxe::prelude::*; /// /// let p = many::<_, String>(digit()).from_str::(); /// /// assert_eq!(p.parse("12345"), Ok((12345, ""))); /// assert!(p.parse("abcde").is_err()); /// /// ``` #[allow(clippy::wrong_self_convention)] fn from_str(self) -> FromStr where Self: Sized, { FromStr(self, PhantomData) } /// Fail this parser if the predicate fails. /// /// ``` /// use syntaxe::*; /// /// let p = string("moo").followed_by(symbol('.')); /// assert_eq!(p.parse("moo."), Ok(("moo", "."))); /// assert!(p.parse("moo").is_err()); /// ``` fn followed_by

(self, next: P) -> impl Parser<'a, Output = Self::Output> where P: Parser<'a>, Self: Sized, { self.skip(peek(next)) } /// Applies the parser at least once, separating subsequent applications /// with a separator. /// /// ``` /// use syntaxe::*; /// /// let p = natural().delimited_by(symbol(',')); /// assert_eq!(p.parse("1,2,3,4"), Ok((vec![1, 2, 3, 4], ""))); /// assert_eq!(p.parse("2"), Ok((vec![2], ""))); /// assert_eq!(p.parse(""), Ok((vec![], ""))); /// assert!(p.parse("1,").is_err()); /// /// let p = natural().delimited_by(spaces1()); /// assert_eq!(p.parse("1 2 3 4"), Ok((vec![1, 2, 3, 4], ""))); /// ``` fn delimited_by(self, separator: S) -> impl Parser<'a, Output = Vec> where S: Parser<'a>, Self: Sized, { move |cursor| { // Parse first element if it exists. let Ok((item, mut cursor)) = self.parse_at(cursor) else { return Ok((Vec::new(), cursor)); }; let mut results = vec![item]; // Keep parsing separator plus item pairs. while let Ok((_, rest)) = separator.parse_at(cursor) { let (item, rest) = self.parse_at(rest)?; if rest.input.len() >= cursor.input.len() { break; } results.push(item); cursor = rest; } Ok((results, cursor)) } } } impl<'a, O> Parser<'a> for Box> { type Output = O; fn parse_at(&self, input: Cursor<'a>) -> Result<'a, Self::Output> { self.deref().parse_at(input) } } impl<'a, F, O> Parser<'a> for F where F: Fn(Cursor<'a>) -> Result<'a, O>, { type Output = O; fn parse_at(&self, input: Cursor<'a>) -> Result<'a, O> { self(input) } } impl<'a> Parser<'a> for char { type Output = char; fn parse_at(&self, input: Cursor<'a>) -> Result<'a, Self::Output> { Symbol(*self).parse_at(input) } } /// Applies the first parser and if it succeeds, the second. impl<'a, P, Q> Parser<'a> for (P, Q) where P: Parser<'a>, Q: Parser<'a>, { type Output = (P::Output, Q::Output); fn parse_at(&self, input: Cursor<'a>) -> Result<'a, Self::Output> { self.0 .parse_at(input) .and_then(|(out0, rest)| self.1.parse_at(rest).map(|(out1, rest)| ((out0, out1), rest))) } } /// A parser that converts its output from a string. #[derive(Copy)] pub struct FromStr(P, PhantomData); impl<'a, P, O, S, E> Parser<'a> for FromStr where P: Parser<'a, Output = S>, S: AsRef, O: str::FromStr, E: std::error::Error + 'static, { type Output = O; fn parse_at(&self, input: Cursor<'a>) -> Result<'a, Self::Output> { match self.0.parse_at(input) { Ok((out, rest)) => match out.as_ref().parse::() { Ok(o) => Ok((o, rest)), Err(e) => Err(Error::new(ErrorKind::FromStr(Rc::new(e)), rest)), }, Err(err) => Err(err), } } } impl Clone for FromStr { fn clone(&self) -> Self { Self(self.0.clone(), self.1) } } /// A parser that applies a mapping function to transform its output. #[derive(Clone)] pub struct Map { parser: P, f: F, } impl<'a, P, F, O> Parser<'a> for Map where P: Parser<'a>, F: Fn(P::Output) -> O, { type Output = O; fn parse_at(&self, input: Cursor<'a>) -> Result<'a, Self::Output> { self.parser.parse_at(input).map(|(out, rest)| ((self.f)(out), rest)) } } /// Try two different parsers and return either result. /// Returns the first successful parse as `Either::Left`, or the second as `Either::Right`. /// /// ``` /// use syntaxe::prelude::*; /// /// let p = either(float(), natural()); /// /// assert_eq!(p.parse("42"), Ok((Either::Right(42), ""))); /// assert_eq!(p.parse("42.912"), Ok((Either::Left(42.912), ""))); /// ``` pub fn either<'a, L, R>(left: L, right: R) -> impl Parser<'a, Output = Either> where L: Parser<'a>, R: Parser<'a>, { move |input| match left.parse_at(input) { Ok((out, rest)) => Ok((Either::Left(out), rest)), _ => match right.parse_at(input) { Ok((out, rest)) => Ok((Either::Right(out), rest)), Err(err) => Err(err), }, } } /// Parses if the predicate returns `true` on the input's next `char`. #[derive(Clone)] pub struct Satisfy(fn(&char) -> bool); impl<'a> Parser<'a> for Satisfy { type Output = char; fn parse_at(&self, cursor: Cursor<'a>) -> Result<'a, Self::Output> { let predicate = &self.0; match cursor.input.chars().next() { Some(c) if predicate(&c) => Ok((c, cursor.advance(1))), Some(c) => Err(Error::new(ErrorKind::UnexpectedChar(c), cursor)), None => Err(Error::new(ErrorKind::UnexpectedEof, cursor)), } } } /// Tries to parse a single character. #[derive(Clone, Debug)] pub struct Symbol(char); impl<'a> Parser<'a> for Symbol { type Output = char; fn parse_at(&self, cursor: Cursor<'a>) -> Result<'a, Self::Output> { match cursor.input.chars().next() { Some(c) if c == self.0 => Ok((c, cursor.advance(1))), _ => Err(Error::new(ErrorKind::ExpectedChar(self.0), cursor)), } } } impl fmt::Display for Symbol { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "'{}'", self.0) } } /// Parse a string literal. #[derive(Clone, Debug)] pub struct Keyword<'a>(&'a str); impl<'a> Parser<'a> for Keyword<'a> { type Output = &'a str; fn parse_at(&self, cursor: Cursor<'a>) -> Result<'a, Self::Output> { match cursor.input.get(..self.0.len()) { Some(word) if word == self.0 => Ok((word, cursor.advance(word.chars().count()))), _ => Err(Error::new(ErrorKind::ExpectedString(self.0), cursor)), } } } impl fmt::Display for Keyword<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "\"{}\"", self.0) } } impl From for Symbol { fn from(c: char) -> Self { symbol(c) } } /// Fail with a message. /// /// ``` /// use syntaxe::*; /// use syntaxe::result::{Location, Error}; /// /// let parser = symbol('!').or(fail("only `!` is allowed")); /// let err = parser.parse("?").unwrap_err(); /// /// assert_eq!(err.to_string(), "only `!` is allowed"); /// ``` pub fn fail<'a, S: Into>, U>(err: S) -> impl Parser<'a, Output = U> { let err = err.into(); move |cursor: Cursor<'a>| Err(Error::new(ErrorKind::Custom(err.clone()), cursor)) } /// Call the given predicate on the next character. If it returns `true`, /// consume the character. /// Create a parser that matches a single character if it satisfies the predicate function. /// /// ``` /// use syntaxe::prelude::*; /// /// let parser = satisfy(|c| c.is_ascii_uppercase()); /// assert_eq!(parser.parse("ABC"), Ok(('A', "BC"))); /// assert!(parser.parse("abc").is_err()); /// ``` pub fn satisfy(predicate: fn(&char) -> bool) -> Satisfy { Satisfy(predicate) } /// Apply *open*, then *between*, then *close*. /// /// ``` /// use syntaxe::*; /// /// let parser = between(symbol('{'), symbol('}'), any::<_, String>(letter())); /// /// assert!(parser.parse("{acme}").is_ok()); /// assert_eq!(parser.parse("{acme}"), Ok(("acme".to_owned(), ""))); /// ``` /// Parse content between opening and closing delimiters. /// /// ``` /// use syntaxe::prelude::*; /// /// let parser = between(symbol('['), symbol(']'), many::<_, String>(letter())); /// assert_eq!(parser.parse("[hello]"), Ok(("hello".to_string(), ""))); /// assert!(parser.parse("[123]").is_err()); /// ``` pub fn between<'a, P, R, Q, O>(open: P, close: R, between: Q) -> impl Parser<'a, Output = O> where P: Parser<'a>, R: Parser<'a>, Q: Parser<'a, Output = O>, { open.then(between).then(close).map(|((_, body), _)| body) } /// Try to apply a parser, returning None if it fails without consuming input. /// /// ``` /// use syntaxe::*; /// /// let p = optional(symbol('!')); /// assert_eq!(p.parse("!"), Ok((Some('!'), ""))); /// assert_eq!(p.parse("?"), Ok((None, "?"))); /// assert_eq!(p.parse(""), Ok((None, ""))); /// ``` pub fn optional<'a, O: 'a, P>(parser: P) -> impl Parser<'a, Output = Option> where P: Parser<'a, Output = O>, { move |input| match parser.parse_at(input) { Ok((out, rest)) => Ok((Some(out), rest)), Err(_) => Ok((None, input)), } } /// Apply the parser until the other parser succeeds. /// /// ``` /// use syntaxe::*; /// /// let p = until(symbol('!')); /// let (out, rest) = p.parse("Hello World!").unwrap(); /// /// assert_eq!(out, "Hello World"); /// assert_eq!(rest, "!"); /// /// assert!(p.parse("!").is_ok()); /// assert!(p.parse("Hello World").is_err()); /// ``` pub fn until<'a, P>(parser: P) -> impl Parser<'a, Output = &'a str> where P: Parser<'a>, { move |mut cursor: Cursor<'a>| -> Result<'a, &'a str> { let input = cursor.input; let mut chars = input.chars(); let mut error; loop { match parser.parse_at(cursor) { Ok((_, _)) => return Ok((&input[..input.len() - cursor.input.len()], cursor)), Err(e) => error = e, } if chars.next().is_some() { cursor = cursor.advance(1); } else { break; } } Err(error) } } /// Succeeds when the input is empty. /// /// ``` /// use syntaxe::prelude::*; /// /// end().parse("").is_ok(); /// end().parse("#").is_err(); /// /// let (out, rest) = until(end()).parse("Hello World!").unwrap(); /// assert_eq!(out, String::from("Hello World!")); /// assert_eq!(rest, ""); /// ``` pub fn end<'a>() -> impl Parser<'a, Output = ()> { (|cursor: Cursor<'a>| { if cursor.input.is_empty() { Ok(((), cursor)) } else { Err(Error::new(ErrorKind::ExpectedEof, cursor)) } }) .with_err(ErrorKind::ExpectedEof) } /// Parses a single character. pub fn symbol(c: char) -> Symbol { Symbol(c) } /// Parses a single letter. /// /// ``` /// use syntaxe::prelude::*; /// /// let letter = satisfy(char::is_ascii_alphabetic); /// ``` pub fn letter<'a>() -> impl Parser<'a, Output = char> { satisfy(char::is_ascii_alphabetic).with_err(ErrorKind::ExpectedOther("a-Z".into())) } /// Parses any character. Always succeeds. /// Parse any single character. /// /// ``` /// use syntaxe::prelude::*; /// /// let parser = character(); /// assert_eq!(parser.parse("abc"), Ok(('a', "bc"))); /// assert_eq!(parser.parse("123"), Ok(('1', "23"))); /// assert!(parser.parse("").is_err()); /// ``` pub fn character<'a>() -> impl Parser<'a, Output = char> { satisfy(|_| true) } /// Applies the parser any number of times. /// /// ``` /// use syntaxe::prelude::*; /// /// let p = any(symbol('?')); /// /// assert_eq!(p.parse("???"), Ok((String::from("???"), ""))); /// assert!(p.parse("").is_ok()); /// assert!(p.parse("?").is_ok()); /// assert!(p.parse("??????").is_ok()); /// ``` pub fn any<'a, P, U>(parser: P) -> Any where P: Parser<'a>, { Any(parser, PhantomData) } /// Applies the underlying parser zero or more times. Never fails. /// Returns the outputs as a vector. #[derive(Debug)] pub struct Any(P, PhantomData); impl<'a, P, O> Parser<'a> for Any where P: 'a + Parser<'a>, O: 'a + FromIterator + Default + Extend, { type Output = O; fn parse_at(&self, input: Cursor<'a>) -> Result<'a, Self::Output> { let mut input = input; let mut outs = O::default(); while let Ok((out, rest)) = self.0.parse_at(input) { if rest.input.len() >= input.input.len() { break; } outs.extend(std::iter::once(out)); input = rest; } Ok((outs, input)) } } impl<'a, P: Parser<'a> + Clone, O> Clone for Any { fn clone(&self) -> Self { Self(self.0.clone(), self.1) } } /// Applies the parser one or more times. /// /// ``` /// use syntaxe::*; /// /// let p = many::<_, String>(symbol('!')); /// /// assert!(p.parse("!").is_ok()); /// assert!(p.parse("!!").is_ok()); /// assert!(p.parse("!!!").is_ok()); /// assert!(p.parse("").is_err()); /// ``` pub fn many<'a, P, O>(parser: P) -> impl Parser<'a, Output = O> + 'a where P: Parser<'a> + 'a, O: FromIterator + Default + Extend + 'a, { move |input| { let mut input = input; let mut outs = O::default(); let (out, rest) = parser.parse_at(input)?; outs.extend(std::iter::once(out)); input = rest; while let Ok((out, rest)) = parser.parse_at(input) { if rest.input.len() >= input.input.len() { break; } outs.extend(std::iter::once(out)); input = rest; } Ok((outs, input)) } } /// Tries multiple parsers in sequence until one succeeds. /// Returns the first successful parse result. /// /// ``` /// use syntaxe::*; /// /// let p = choice([symbol('?'), symbol('!'), symbol('.')]); /// /// assert_eq!(p.parse("?").ok(), Some(('?', ""))); /// assert_eq!(p.parse("!").ok(), Some(('!', ""))); /// assert_eq!(p.parse(".").ok(), Some(('.', ""))); /// /// assert!(p.parse("@").is_err()); /// assert!(p.parse(",").is_err()); /// assert!(p.parse("").is_err()); /// ``` pub fn choice<'a, P: Parser<'a>>( parsers: impl IntoIterator, ) -> impl Parser<'a, Output = P::Output> { let parsers: Vec

= parsers.into_iter().collect(); move |input| { let mut expected = Vec::new(); for p in &parsers { match p.parse_at(input) { Ok(result) => return Ok(result), Err(e) => { if let Some(exp) = e.expected() { expected.push(exp) } } } } Err(Error::new(ErrorKind::ExpectedOneOf(expected), input)) } } /// Parses a string literal. /// /// ``` /// use syntaxe::*; /// use syntaxe::result::Error; /// /// let p = string("set"); /// /// assert!(p.parse("set").is_ok()); /// assert!(p.parse("").is_err()); /// /// let err = p.parse("get").unwrap_err(); /// assert_eq!(err.to_string(), "expected `set`, got `get`"); /// /// let p = string("true").from_str::(); /// assert_eq!(p.parse("true!"), Ok((true, "!"))); /// ``` pub fn string(input: &str) -> Keyword<'_> { Keyword(input) } /// Optional whitespace. /// /// ``` /// use syntaxe::*; /// /// let p = whitespace(); /// /// assert!(p.parse(" ").is_ok()); /// assert!(p.parse(" ").is_ok()); /// assert!(p.parse("\t \t").is_ok()); /// assert!(p.parse("\n").is_ok()); /// assert!(p.parse("").is_ok()); /// ``` pub fn whitespace<'a>() -> impl Parser<'a, Output = &'a str> { take_while(char::is_ascii_whitespace) } /// Optional spaces. /// /// ``` /// use syntaxe::*; /// /// let p = spaces(); /// /// assert!(p.parse(" ").is_ok()); /// assert!(p.parse(" ").is_ok()); /// assert!(p.parse("\t").is_ok()); /// assert!(p.parse("").is_ok()); /// ``` pub fn spaces<'a>() -> impl Parser<'a, Output = &'a str> { take_while(|c| *c == ' ' || *c == '\t') } /// One or more horizontal spaces (space or tab). /// /// ``` /// use syntaxe::*; /// /// let p = spaces1(); /// /// assert!(p.parse(" ").is_ok()); /// assert!(p.parse(" ").is_ok()); /// assert!(p.parse("\t").is_ok()); /// assert!(p.parse("\t ").is_ok()); /// assert!(p.parse("").is_err()); /// ``` pub fn spaces1<'a>() -> impl Parser<'a, Output = &'a str> { take_while1(|c| *c == ' ' || *c == '\t') } /// Parses a single line-feed token. /// /// ``` /// use syntaxe::*; /// /// let p = linebreaks(); /// assert_eq!(p.parse("\n"), Ok(("\n", ""))); /// assert_eq!(p.parse("\r\n"), Ok(("\r\n", ""))); /// ``` /// Parse zero or more vertical whitespace characters (newline or carriage return). /// /// ``` /// use syntaxe::prelude::*; /// /// let parser = linebreaks(); /// assert_eq!(parser.parse("\n\r\n"), Ok(("\n\r\n", ""))); /// assert_eq!(parser.parse("abc"), Ok(("", "abc"))); /// ``` pub fn linebreaks<'a>() -> impl Parser<'a, Output = &'a str> { take_while(|c| *c == '\n' || *c == '\r') } /// Parses a single base ten digit. /// /// ``` /// use syntaxe::*; /// /// let digit = satisfy(|c: &char| c.is_digit(10)); /// ``` pub fn digit<'a>() -> impl Parser<'a, Output = char> { satisfy(char::is_ascii_digit).with_err(ErrorKind::ExpectedOther("0-9".into())) } /// Unsigned decimal integer. /// /// ``` /// use syntaxe::*; /// /// let p = natural::(); /// /// assert!(p.parse("0").is_ok()); /// assert!(p.parse("123").is_ok()); /// assert!(p.parse("043").is_ok()); /// assert!(p.parse("-55").is_err()); /// ``` pub fn natural<'a, O>() -> impl Parser<'a, Output = O> where O: str::FromStr + 'a, { repeat(digit()).from_str::() } /// Unsigned floating point number. /// /// ``` /// use syntaxe::*; /// /// let p = float::(); /// /// assert!(p.parse("123.456").is_ok()); /// assert!(p.parse(".42").is_ok()); /// assert!(p.parse("0").is_err()); /// assert!(p.parse("42").is_err()); /// assert!(p.parse("42.").is_err()); /// assert!(p.parse("-1.23").is_err()); /// ``` pub fn float<'a, O>() -> impl Parser<'a, Output = O> where O: str::FromStr + 'a, { let whole = repeat(digit()); let fract = repeat(digit()); (optional(whole).then(symbol('.')).then(fract)) .map(|((w, _), d)| match w { Some(w) => format!("{}.{}", w, d), None => format!("0.{}", d), }) .from_str::() } /// Makes a parser accept an optional sign prefix. /// /// ``` /// use syntaxe::*; /// /// let p = signed(float::()); /// assert_eq!(p.parse("42.019"), Ok((42.019, ""))); /// assert_eq!(p.parse("-4.23"), Ok((-4.23, ""))); /// assert_eq!(p.parse("+4.23"), Ok((4.23, ""))); /// /// let p = signed(natural::()); /// assert_eq!(p.parse("42"), Ok((42, ""))); /// assert_eq!(p.parse("-42"), Ok((-42, ""))); /// assert_eq!(p.parse("+42"), Ok((42, ""))); /// ``` pub fn signed<'a, P, O>(parser: P) -> impl Parser<'a, Output = O> where P: Parser<'a, Output = O>, O: std::ops::Neg + 'a, { let sign = optional(symbol('-').or(symbol('+'))); sign.then(parser).map(|(s, n)| match s { Some('-') => -n, _ => n, }) } /// Apply the given parser, and if it fails, don't consume any input. /// /// ``` /// use syntaxe::*; /// /// let p = choice([ /// peek(string("leave").skip(whitespace()).then(string("england"))), /// peek(string("leave").skip(whitespace()).then(string("france"))), /// ]); /// /// assert!(p.parse("leave england").is_ok()); /// assert!(p.parse("leave france").is_ok()); /// ``` pub fn peek<'a, P: Parser<'a>>(parser: P) -> impl Parser<'a, Output = P::Output> { move |input| match parser.parse_at(input) { Ok((out, _)) => Ok((out, input)), Err(err) => Err(err), } } /// Repeatedly apply a parser until it fails, returning the concatenated string of all matches. /// Returns an error if the first application fails. /// /// ``` /// use syntaxe::*; /// /// let p = repeat(letter()); /// let (out, rest) = p.parse("Bazinga!").unwrap(); /// /// assert_eq!(out, "Bazinga"); /// assert_eq!(rest, "!"); /// /// assert!(p.parse("!").is_err()); /// ``` pub fn repeat<'a, P>(parser: P) -> impl Parser<'a, Output = &'a str> where P: Parser<'a> + 'a, { move |cursor: Cursor<'a>| -> Result<'a, &'a str> { let input = cursor.input; let (_, mut cursor) = parser.parse_at(cursor)?; while let Ok((_, rest)) = parser.parse_at(cursor) { if rest.input.len() >= cursor.input.len() { break; } cursor = rest; } let len = input.len() - cursor.input.len(); Ok((&input[..len], cursor)) } } /// Parse characters as long as they match the predicate function. /// Returns all matching characters as a string slice. /// Returns an empty string if no characters match. /// /// ``` /// use syntaxe::prelude::*; /// /// let parser = take_while(|c| c.is_ascii_digit()); /// assert_eq!(parser.parse("123abc"), Ok(("123", "abc"))); /// assert_eq!(parser.parse("abc"), Ok(("", "abc"))); // No match returns empty string /// ``` pub fn take_while<'a, F: Fn(&char) -> bool>(pred: F) -> impl Parser<'a, Output = &'a str> { move |cursor: Cursor<'a>| { let input = cursor.input; let count = input.chars().take_while(&pred).count(); let rest = cursor.advance(count); let len = input.len() - rest.input.len(); Ok((&input[..len], rest)) } } /// Like [`take_while`], but requires at least one matching character. /// Parse one or more characters matching a predicate. /// Returns an error if no characters match. /// /// ``` /// use syntaxe::prelude::*; /// /// let parser = take_while1(|c| c.is_ascii_digit()); /// assert_eq!(parser.parse("123abc"), Ok(("123", "abc"))); /// assert!(parser.parse("abc").is_err()); /// ``` pub fn take_while1<'a, F: Fn(&char) -> bool + Copy + 'static>( pred: F, ) -> impl Parser<'a, Output = &'a str> { move |cursor: Cursor<'a>| { let Some(c) = cursor.input.chars().next() else { return Err(Error::new(ErrorKind::UnexpectedEof, cursor)); }; if !pred(&c) { return Err(Error::new(ErrorKind::UnexpectedChar(c), cursor)); } take_while(pred).parse_at(cursor) } } /// Parse characters until one matches the predicate function. /// Returns all non-matching characters as a string slice. /// Returns an error if the input is empty or if no terminating character is found. /// /// ``` /// use syntaxe::prelude::*; /// /// let parser = take_until(|c| c == '.'); /// assert_eq!(parser.parse("abc.def"), Ok(("abc", ".def"))); /// assert!(parser.parse("abc").is_err()); // No terminator found /// ``` pub fn take_until<'a, F: Fn(char) -> bool + Copy + 'static>( term: F, ) -> impl Parser<'a, Output = &'a str> { move |cursor: Cursor<'a>| { let input = cursor.input; let mut rest = cursor; for c in input.chars() { if term(c) { let len = input.len() - rest.input.len(); return Ok((&input[..len], rest)); } rest = rest.advance(1); } Err(Error::new(ErrorKind::UnexpectedEof, rest)) } } /// Takes the rest of the input as a string slice. /// Always succeeds. /// /// ``` /// use syntaxe::prelude::*; /// /// let parser = take_str(); /// assert_eq!(parser.parse("hello world"), Ok(("hello world", ""))); /// assert!(parser.parse("").is_ok()); /// ``` pub fn take_str<'a>() -> impl Parser<'a, Output = &'a str> { move |cursor: Cursor<'a>| Ok((cursor.input, cursor.advance(cursor.input.chars().count()))) } /// Takes exactly `n` characters from the input. /// Fails if there aren't enough characters available. /// /// ``` /// use syntaxe::prelude::*; /// /// let parser = take(5); /// assert_eq!(parser.parse("hello world"), Ok(("hello", " world"))); /// assert!(parser.parse("hi").is_err()); /// ``` pub fn take<'a>(n: usize) -> impl Parser<'a, Output = &'a str> { move |cursor: Cursor<'a>| { let mut chars = cursor.input.chars(); for _ in 0..n { if chars.next().is_none() { return Err(Error::new(ErrorKind::UnexpectedEof, cursor)); } } let len = cursor.input.len() - chars.as_str().len(); Ok((&cursor.input[..len], cursor.advance(n))) } } /// Attempt to parse, and if it fails, backtrack as if no input had been consumed. /// /// ``` /// use syntaxe::prelude::*; /// /// // Without `backtrack`. /// let parser = string("hello").skip(whitespace()).then(string("tom")); /// let result = parser.parse("hello bob").unwrap_err(); /// assert_eq!(result.unparsed(), "bob"); /// /// // With `backtrack`. /// let parser = backtrack(string("hello").skip(whitespace()).then(string("tom"))); /// let result = parser.parse("hello bob").unwrap_err(); /// assert_eq!(result.unparsed(), "hello bob"); /// ``` pub fn backtrack<'a, P>(parser: P) -> impl Parser<'a, Output = P::Output> where P: Parser<'a>, { move |cursor: Cursor<'a>| parser.parse_at(cursor).map_err(|e| Error::new(e.kind, cursor)) } /// Silence a parser. Discard its output and return `()` instead. /// Useful when you need to match a pattern but don't care about capturing its value. pub fn hush<'a, P>(parser: P) -> impl Parser<'a, Output = ()> where P: Parser<'a>, { parser.value(()) } #[cfg(test)] #[allow(clippy::unwrap_used)] mod test { use super::*; use crate::result::Location; #[test] fn test_repetition_without_progress() { let calls = std::cell::Cell::new(0); let empty = |cursor| { calls.set(calls.get() + 1); assert!( calls.get() <= 8, "repetition must stop without input progress" ); Ok(((), cursor)) }; assert_eq!(any::<_, Vec<_>>(&empty).parse("a"), Ok((vec![], "a"))); assert_eq!(many::<_, Vec<_>>(&empty).parse("a"), Ok((vec![()], "a"))); assert_eq!(repeat(&empty).parse("a"), Ok(("", "a"))); assert_eq!( empty.delimited_by(string("")).parse("a"), Ok((vec![()], "a")) ); } #[test] fn test_choice_backtracking() { let p = choice([ string("leave").skip(whitespace()).then(string("england")), string("learn").skip(whitespace()).then(string("english")), string("leave").skip(whitespace()).then(string("britain")), ]); assert!(p.parse("learn english").is_ok()); assert!(p.parse("leave england").is_ok()); assert!(p.parse("leave britain").is_ok()); let err = p.parse("leave english").err().unwrap(); assert_eq!(err.unparsed(), "leave english"); } #[test] fn test_choice_backtracking_skip() { let p = choice([ string("leave").skip(whitespace()).skip(string("england")).boxed(), string("leave/england").boxed(), ]); assert!(p.parse("leave england").is_ok()); assert!(p.parse("leave/england").is_ok()); let p = choice([ backtrack(string("leave").skip(whitespace())) .skip(string("england")) .boxed(), string("leave/england").boxed(), ]); assert!(p.parse("leave england").is_ok()); assert!(p.parse("leave/england").is_ok()); } #[test] fn test_or() { let p = string("leave") .skip(whitespace()) .then(string("england")) .or(string("learn").skip(whitespace()).then(string("english"))) .or(string("leave").skip(whitespace()).then(string("britain"))); // Test backtracking. assert!(p.parse("learn english").is_ok()); assert!(p.parse("leave england").is_ok()); assert!(p.parse("leave britain").is_ok()); let err = p.parse("leave english").err().unwrap(); assert_eq!(err.unparsed(), "english"); assert_eq!(err.to_string(), "expected `britain`, got `english`"); } #[test] fn test_zero_copy() { let input = "fnord!"; let (result, rest) = string("fnord").parse(input).unwrap(); assert_eq!(result, "fnord".to_owned()); assert_eq!(rest, "!"); assert_eq!(input[5..6].as_ptr(), rest.as_ptr()); } #[test] fn test_lisp() { #[derive(PartialEq, Debug)] enum Expr { List(Vec), Op(char), Num(u8), } fn expr<'a>() -> impl Parser<'a, Output = Expr> { let num = natural::().map(Expr::Num); let op = choice([symbol('*'), symbol('+'), symbol('^')]).map(Expr::Op); let list = between('(', ')', (|c| expr().parse_at(c)).delimited_by(spaces1())).map(Expr::List); list.or(num).or(op) } let (output, rest) = expr().parse("(+ 1 (* (^ 2 3) 4))").unwrap(); assert_eq!( output, Expr::List(vec![ Expr::Op('+'), Expr::Num(1), Expr::List(vec![ Expr::Op('*'), Expr::List(vec![Expr::Op('^'), Expr::Num(2), Expr::Num(3)]), Expr::Num(4) ]), ]) ); assert_eq!(rest, ""); } #[test] fn test_errors() { struct TestCase { input: &'static str, parser: Box>, location: Location, message: &'static str, } let cases = vec![ TestCase { input: "abc\ndef\nghi", parser: string("xyz").value(()).boxed(), location: Location { index: 0, line: 1, column: 1, }, message: ":1:1: error: expected `xyz`, got `abc`", }, TestCase { input: "123\n456\n789", parser: many::<_, String>(digit()).then(symbol('x')).value(()).boxed(), location: Location { index: 3, line: 1, column: 4, }, message: ":1:4: error: expected 'x', got `\n`", }, TestCase { input: "hello\nworld!", parser: string("hello") .then(linebreaks()) .then(string("earth")) .value(()) .boxed(), location: Location { index: 6, line: 2, column: 1, }, message: ":2:1: error: expected `earth`, got `world!`", }, TestCase { input: "", parser: digit().value(()).boxed(), location: Location { index: 0, line: 1, column: 1, }, message: ":1:1: error: expected 0-9, got end-of-input", }, TestCase { input: "hello\nworld", parser: until(symbol('!')).value(()).boxed(), location: Location { index: 11, line: 2, column: 6, }, message: ":2:6: error: expected '!', got end-of-input", }, TestCase { input: "#@!", parser: end().boxed(), location: Location { index: 0, line: 1, column: 1, }, message: ":1:1: error: expected end-of-input, got `#@!`", }, ]; for (i, case) in cases.into_iter().enumerate() { let result = case.parser.parse(case.input); let err = result.expect_err(&format!( "Case #{i}: expected error for input: `{}`", case.input )); assert_eq!( err.explain(), case.message, "Case #{i}: wrong error message for input: expected {:?}, got {:?}", case.input, err ); assert_eq!( err.cursor.location, case.location, "Case #{i}: wrong location for input: expected {:?}, got {:?}", case.location, err.cursor.location, ); } } }