Skip to main content

PairsBuilder

Struct PairsBuilder 

Source
pub struct PairsBuilder<'i, R> { /* private fields */ }
Expand description

A builder that constructs Pairs manually, without running a parser.

This is meant for unit tests: code that consumes parser output often takes a Pair or Pairs as input, and testing it would otherwise require running a real parse just to obtain the right shape of tokens. With a PairsBuilder the expected tree can be spelled out directly.

A pair is described by a Rule, a start byte offset and an end byte offset into input (the same [start, end) convention used by Span), and, optionally, inner pairs and a node tag.

§Examples

Building a single leaf pair — the motivating use case, a Pair handed to a function under test without invoking the parser:

enum Rule {
    integer,
}

let pairs = PairsBuilder::new("42").rule(Rule::integer, 0, 2).build();
let pair = pairs.peek().unwrap();

assert_eq!(pair.as_rule(), Rule::integer);
assert_eq!(pair.as_str(), "42");

Nesting inner pairs with rule_with and attaching tags with tag:

enum Rule {
    sum,
    number,
}

// Describes the parse tree of "1+2": a `sum` containing two `number`s.
let pairs = PairsBuilder::new("1+2")
    .rule_with(Rule::sum, 0, 3, |inner| {
        inner
            .rule(Rule::number, 0, 1)
            .tag("lhs")
            .rule(Rule::number, 2, 3)
            .tag("rhs")
    })
    .build();

let sum = pairs.peek().unwrap();
assert_eq!(sum.as_rule(), Rule::sum);

let numbers: Vec<_> = sum.into_inner().map(|p| p.as_str()).collect();
assert_eq!(numbers, ["1", "2"]);

Implementations§

Source§

impl<'i, R: RuleType> PairsBuilder<'i, R>

Source

pub fn new(input: &'i str) -> Self

Creates an empty builder over input.

All offsets passed to rule and rule_with index into this string.

Source

pub fn rule(self, rule: R, start: usize, end: usize) -> Self

Appends a leaf Pair for rule spanning input[start..end].

§Examples
let pairs = PairsBuilder::new("a b")
    .rule(Rule::a, 0, 1)
    .rule(Rule::b, 2, 3)
    .build();

let strings: Vec<_> = pairs.map(|p| p.as_str()).collect();
assert_eq!(strings, ["a", "b"]);
Source

pub fn rule_with<F>( self, rule: R, start: usize, end: usize, build_children: F, ) -> Self
where F: FnOnce(PairsBuilder<'i, R>) -> PairsBuilder<'i, R>,

Appends a Pair for rule spanning input[start..end], whose inner Pairs are produced by build_children.

build_children receives a fresh builder over the same input; the pairs it appends become the inner pairs of this rule, in the order they are added.

§Examples
let pairs = PairsBuilder::new("[a,b]")
    .rule_with(Rule::list, 0, 5, |inner| {
        inner.rule(Rule::item, 1, 2).rule(Rule::item, 3, 4)
    })
    .build();

let list = pairs.peek().unwrap();
assert_eq!(list.into_inner().count(), 2);
Source

pub fn tag(self, tag: &'i str) -> Self

Attaches tag to the most recently appended pair, so that it can be looked up with Pairs::find_first_tagged, Pairs::find_tagged or Pair::as_node_tag.

§Panics

Panics if called before any rule has been appended to this builder.

§Examples
let pairs = PairsBuilder::new("7").rule(Rule::number, 0, 1).tag("answer").build();

assert_eq!(pairs.find_first_tagged("answer").unwrap().as_str(), "7");
Source

pub fn build(self) -> Pairs<'i, R> ⓘ

Consumes the builder and produces the Pairs.

§Panics

Panics if any appended rule’s [start, end) is not a valid range into input — that is, if start > end, end is past the end of input, or either offset does not fall on a UTF-8 character boundary. This mirrors the invariant enforced by Span::new, which the resulting pairs would otherwise violate.

Trait Implementations§

Source§

impl<'i, R: Clone> Clone for PairsBuilder<'i, R>

Source§

fn clone(&self) -> Self

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<'i, R: Debug> Debug for PairsBuilder<'i, R>

Source§

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

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<'i, R> Freeze for PairsBuilder<'i, R>
where Vec<BuilderNode<'i, R>>: Freeze,

§

impl<'i, R> RefUnwindSafe for PairsBuilder<'i, R>
where Vec<BuilderNode<'i, R>>: RefUnwindSafe,

§

impl<'i, R> Send for PairsBuilder<'i, R>
where Vec<BuilderNode<'i, R>>: Send,

§

impl<'i, R> Sync for PairsBuilder<'i, R>
where Vec<BuilderNode<'i, R>>: Sync,

§

impl<'i, R> Unpin for PairsBuilder<'i, R>
where Vec<BuilderNode<'i, R>>: Unpin,

§

impl<'i, R> UnsafeUnpin for PairsBuilder<'i, R>
where Vec<BuilderNode<'i, R>>: UnsafeUnpin,

§

impl<'i, R> UnwindSafe for PairsBuilder<'i, R>
where Vec<BuilderNode<'i, R>>: UnwindSafe,

Blanket Implementations§

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<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> 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.