Skip to main content

DelimitedBy

Struct DelimitedBy 

Source
pub struct DelimitedBy<P, Delim> { /* private fields */ }
Available on crate feature many only.
Expand description

A parser that wraps a repetition driver in a pair of delimiter tokens.

This combinator wraps any of the four repetition builders — Repeated, RepeatedWhile, Separated, SeparatedWhile, and their bound/leading/trailing option wrappers — in opening and closing delimiters, parsing constructs like [element element element] or {item, item, item}.

The delimiter pair is a type, not a pair of classifier closures: delimited::<Delim>() takes any Delimiter, and delimited_by_brackets / _braces / _parens / _angles name the built-in pairs.

§Type Parameters

  • P: The wrapped repetition parser — which is what carries the element parser, the stopping decision, the output type, the lookahead window, the lexer, the context and the language
  • Delim: The delimiter pair marker (e.g. Bracket), a Delimiter whose Open/Close punctuators classify the two tokens

§Examples

§Basic Bracketed List

use tokora::{Accumulator, Parse, ParseInput, Parser, while_head};

// Parse: [element element element]
fn items<'a>(inp: &mut InputRef<'a, '_, CharLexer<'a>, Ctx<'a>>) -> Result<Vec<i64>, Error> {
  num
    .repeated_while(while_head(|t: &Tok| matches!(t, Tok::Num(_))))
    .delimited_by_brackets()
    .collect()
    .parse_input(inp)
}

assert_eq!(Parser::with_parser(items).parse_str("[1 2 3]").unwrap(), vec![1, 2, 3]);
assert_eq!(Parser::with_parser(items).parse_str("[7]").unwrap(), vec![7]);
assert_eq!(Parser::with_parser(items).parse_str("[]").unwrap(), Vec::<i64>::new());

§Generic Delimiters

use tokora::{Accumulator, Parse, ParseInput, Parser, while_head};

// Parse: {token token token}
fn items<'a>(inp: &mut InputRef<'a, '_, CharLexer<'a>, Ctx<'a>>) -> Result<Vec<i64>, Error> {
  num
    .repeated_while(while_head(|t: &Tok| matches!(t, Tok::Num(_))))
    .delimited_by_braces()
    .collect()
    .parse_input(inp)
}

assert_eq!(Parser::with_parser(items).parse_str("{1 2 3}").unwrap(), vec![1, 2, 3]);

§Parenthesized Expressions

use tokora::{Accumulator, Parse, ParseInput, Parser, while_head};

// Parse: (expr expr expr)
fn exprs<'a>(inp: &mut InputRef<'a, '_, CharLexer<'a>, Ctx<'a>>) -> Result<Vec<i64>, Error> {
  num
    .repeated_while(while_head(|t: &Tok| matches!(t, Tok::Num(_))))
    .delimited_by_parens()
    .collect()
    .parse_input(inp)
}

assert_eq!(Parser::with_parser(exprs).parse_str("(1 2 3)").unwrap(), vec![1, 2, 3]);

§With Bounds

use tokora::{Accumulator, Parse, ParseInput, Parser, while_head};

// Parse 1-10 elements in brackets.
fn items<'a>(inp: &mut InputRef<'a, '_, CharLexer<'a>, Ctx<'a>>) -> Result<Vec<i64>, Error> {
  num
    .repeated_while(while_head(|t: &Tok| matches!(t, Tok::Num(_))))
    .at_least(1)
    .at_most(10)
    .delimited_by_brackets()
    .collect()
    .parse_input(inp)
}

assert_eq!(Parser::with_parser(items).parse_str("[7]").unwrap(), vec![7]);
// Below the minimum: the too-few diagnostic aborts under the fail-fast context.
assert!(Parser::with_parser(items).parse_str("[]").is_err());

§How It Works

  1. Parse opening delimiter: Consume the left delimiter token
  2. Parse elements: Run the wrapped repetition driver
  3. Parse closing delimiter: Consume the right delimiter token
  4. Return: Return the collected elements

§Separated variants

The same wrapper carries a separated driver, so [a, b, c] is DelimitedBy<SeparatedWhile<..>, Bracket<..>> — built by the identical delimited_by_* call on a separated/separated_while builder.

Featureover a repeated driverover a separated driver
SeparatorsNo separatorsElements separated by a separator token
Base ParserRepeated / RepeatedWhileSeparated / SeparatedWhile
Example[a b c][a, b, c]
Use CaseConsecutive itemsSeparated lists

§Performance

  • Memory: O(1) for the parser structure
  • Runtime: O(n) where n is the number of elements
  • Delimiter matching: O(1) per delimiter

§See Also

  • RepeatedWhile - One of the four repetition drivers this can wrap
  • delimited - How to create this combinator
  • Collect - Wrapper for collecting elements into a container

Implementations§

Source§

impl<P, Delim> DelimitedBy<P, Delim>

Source

pub const fn new(parser: P) -> Self

Creates a new DelimitedBy combinator wrapping the given parser.

Source

pub fn map_parser_mut<'a, Q, F>(&'a mut self, f: F) -> DelimitedBy<Q, Delim>
where F: FnOnce(&'a mut P) -> Q, Q: 'a,

Maps the inner parser via a mutable reference, returning a new DelimitedBy.

Trait Implementations§

Source§

impl<P: Clone, Delim: Clone> Clone for DelimitedBy<P, Delim>

Source§

fn clone(&self) -> DelimitedBy<P, Delim>

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<P: Debug, Delim: Debug> Debug for DelimitedBy<P, Delim>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<P: Eq, Delim: Eq> Eq for DelimitedBy<P, Delim>

Source§

impl<P: Hash, Delim: Hash> Hash for DelimitedBy<P, Delim>

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl<P: PartialEq, Delim: PartialEq> PartialEq for DelimitedBy<P, Delim>

Source§

fn eq(&self, other: &DelimitedBy<P, Delim>) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl<P: PartialEq, Delim: PartialEq> StructuralPartialEq for DelimitedBy<P, Delim>

Auto Trait Implementations§

§

impl<P, Delim> Freeze for DelimitedBy<P, Delim>
where P: Freeze, PhantomData<Delim>: Freeze,

§

impl<P, Delim> RefUnwindSafe for DelimitedBy<P, Delim>

§

impl<P, Delim> Send for DelimitedBy<P, Delim>
where P: Send, PhantomData<Delim>: Send,

§

impl<P, Delim> Sync for DelimitedBy<P, Delim>
where P: Sync, PhantomData<Delim>: Sync,

§

impl<P, Delim> Unpin for DelimitedBy<P, Delim>
where P: Unpin, PhantomData<Delim>: Unpin,

§

impl<P, Delim> UnsafeUnpin for DelimitedBy<P, Delim>

§

impl<P, Delim> UnwindSafe for DelimitedBy<P, Delim>
where P: UnwindSafe, PhantomData<Delim>: UnwindSafe,

Blanket Implementations§

Source§

impl<'inp, P, Container, L, Ctx, Lang, Cmpl> Accumulator<'inp, L, Container, Ctx, Lang, Cmpl> for P
where Collect<P, Container, Ctx, Lang, Cmpl>: ParseInput<'inp, L, Container, Ctx, Lang, Cmpl>, Lang: ?Sized,

Source§

fn collect(self) -> Collect<Self, Container, Ctx, Lang, Cmpl>
where Self: Sized, Container: Default, Collect<Self, Container, Ctx, Lang, Cmpl>: ParseInput<'inp, L, Container, Ctx, Lang, Cmpl>,

Collects the parsed elements into the specified container.
Source§

fn collect_with( self, container: Container, ) -> Collect<Self, Container, Ctx, Lang, Cmpl>
where Self: Sized, Collect<Self, Container, Ctx, Lang, Cmpl>: ParseInput<'inp, L, Container, Ctx, Lang, Cmpl>,

Collects the parsed elements with the given container. Read more
Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.