Struct Parser

Source
pub struct Parser<T> {
    pub expectation: String,
    /* private fields */
}
Expand description

A Parser has a function that consumes input and returns an object of type Output.

Fields§

§expectation: String

Implementations§

Source§

impl<T> Parser<T>
where T: 'static + Clone,

Source

pub fn new( parser: impl Fn(&str) -> Output<T> + 'static, expectation: impl ToString, ) -> Self

Create a new parser from a function that returns an Output. This is mainly used to define the atomic combinators

Source

pub fn expects(self, expectation: impl ToString) -> Self

Source

pub fn parse(&self, input: &str) -> Result<T, Error>

This parses a string using this combinator, and returns a result containing either the successfully lexed and parsed data, or an error containing info about the failure.

Examples found in repository?
examples/json.rs (lines 53-64)
50fn main() {
51    println!(
52        "{:#?}",
53        json().parse(
54            r#"
55{
56    "testing" : null,
57    "recursion" : {
58        "WOW": 1.2345
59    },
60    "array": [1, 2, {"test": "123"}, 4],
61    "test": "testing"
62}
63"#
64        )
65    );
66}
More examples
Hide additional examples
examples/calculator.rs (line 107)
103fn main() {
104    loop {
105        let output = input(">>> ");
106
107        match math().parse(&output) {
108            Ok(m) => println!("{:#?}\n\nResult: {}", m.clone(), eval(m)),
109            Err(_) => println!("Invalid math expression!"),
110        }
111    }
112}
examples/language.rs (lines 7-30)
4fn main() {
5    println!(
6        "{:?}",
7        (token() * (..)).parse(
8            r#"
9
10h123213ey
11jasdf2212eude
12"hey jude dude"
131234 jude
14
15
16fn testing() {
17    println("hello world!");
18}
19
20
21struct Point {
22    fn testing() {
23        println!(
24            "yo dude", 3, []
25        );
26    }
27}
28
29"#
30        )
31    );
32}
examples/markup.rs (lines 43-70)
40fn main() {
41    println!(
42        "{:#?}",
43        (markup() * (1..)).parse(
44            r#"
45
46row {
47    column1 {
48        width { 5 }
49        height { 10 }
50    }
51
52    column2 {
53        width { 5 }
54        height { 10 }
55    }
56
57    column3 {
58        width { 5 }
59        height { 10 }
60    }
61
62    columnlist {
63        - 1
64        - 2
65        - 3
66    }
67}
68
69"#
70        )
71    );
72}
examples/sentence.rs (lines 50-66)
47fn main() {
48    println!(
49        "{:#?}",
50        paragraph().parse(
51            r#"
52
53I look at you all see the love there thats sleeping,
54While my guitar gently weeps.
55I look at the floor and I see it needs sweeping
56Still my guitar gently weeps.
57I dont know why nobody told you
58How to unfold your love.
59I dont know how someone controlled you.
60They bought and sold you.
61I look at the world and I notice its turning
62While my guitar gently weeps.
63With every mistake we must surely be learning,
64Still my guitar gently weeps.
65"#
66        )
67    );
68}
Source

pub fn parse_internal(&self, input: &str) -> Output<T>

This is used by the atomic combinators for things like control flow and passing the output of one parser into another.

Source

pub fn map<O>(self, map_fn: fn(T) -> O) -> Parser<O>
where O: 'static + Clone,

This method takes a function that takes the output of this Parser, and converts it to the output of another data type. This allows us to lex our input as we parse it.

Source

pub fn convert<O, E>(self, convert_fn: fn(T) -> Result<O, E>) -> Parser<O>
where O: 'static + Clone, E: 'static,

This method takes a function that takes the output of this Parser, and TRIES to convert it to the output of another data type. If the given function returns an Err, this parser fails.

Source

pub fn prefixes<O>(self, operand: Parser<O>) -> Parser<O>
where O: 'static + Clone,

This parser “prefixes” another. When the returned parser is used, it will require this parser and the operand parser to succeed, and return the result of the second.

Source

pub fn suffix<O>(self, operand: Parser<O>) -> Parser<T>
where O: 'static + Clone,

This parser will use the operand as a “suffix”. The parser will only succeed if the “suffix” parser succeeds afterwards, but the input of the “suffix” parser will be discarded.

Examples found in repository?
examples/calculator.rs (line 30)
28fn operation(symbol: char, map_fn: fn((Math, Math)) -> Math) -> Parser<Math> {
29    (number() - to_number - Math::Number | rec(math))
30        .suffix(space() & sym(symbol) & space())
31        .and(rec(math))
32        - map_fn
33}
Source

pub fn is(self) -> Parser<()>

This method returns a parser that does not consume input, but succeeds if this parser succeeds. This can be used to make assertions for our input.

Examples found in repository?
examples/sentence.rs (line 36)
35fn sentence() -> Parser<Sentence> {
36    (word().is() >> (((word() << opt(seq_no_ws(","))) * (1..)) & punctuation()))
37        - |phrase: (Vec<Word>, Punctuation)| Sentence {
38            words: phrase.0,
39            punctuation: phrase.1,
40        }
41}
More examples
Hide additional examples
examples/calculator.rs (line 64)
59fn math() -> Parser<Math> {
60    exit()
61        | eof() - (|_| Math::EOF)
62        | clear()
63        | token("(") >> rec(math) << token(")")
64        | (number().is()
65            >> (multiply() | divide() | add() | subtract() | (number() - to_number - Math::Number)))
66}
Source

pub fn isnt(self) -> Parser<()>

This method returns a parser that does not consume input, but succeeds if this parser does not succeed. This can be used to make assertions for our input.

Source

pub fn and<O>(self, operand: Parser<O>) -> Parser<(T, O)>
where O: 'static + Clone,

Combine two parsers into one, and combine their consumed inputs into a tuple. Parser & Parser -> Parser<A, B>. The resulting parser will only succeed if BOTH sub-parsers succeed.

Examples found in repository?
examples/calculator.rs (line 31)
28fn operation(symbol: char, map_fn: fn((Math, Math)) -> Math) -> Parser<Math> {
29    (number() - to_number - Math::Number | rec(math))
30        .suffix(space() & sym(symbol) & space())
31        .and(rec(math))
32        - map_fn
33}
Source

pub fn or(self, operand: Self) -> Self

If this parser does not succeed, try this other parser

Source

pub fn repeat(self, range: impl RangeBounds<usize>) -> Parser<Vec<T>>

Repeat this parser N..M times This can also be repeated ..N times, N.. times, or even .. times

Trait Implementations§

Source§

impl<A: 'static + Clone, B: 'static + Clone> BitAnd<Parser<B>> for Parser<A>

The & operator can be used as an alternative to the .and method

Source§

type Output = Parser<(A, B)>

The resulting type after applying the & operator.
Source§

fn bitand(self, rhs: Parser<B>) -> Self::Output

Performs the & operation. Read more
Source§

impl<T: 'static + Clone> BitOr for Parser<T>

The | operator can be used as an alternative to the .or method

Source§

type Output = Parser<T>

The resulting type after applying the | operator.
Source§

fn bitor(self, rhs: Self) -> Self::Output

Performs the | operation. Read more
Source§

impl<O, T, E> BitXor<fn(T) -> Result<O, E>> for Parser<T>
where O: 'static + Clone, T: 'static + Clone, E: 'static,

The ^ operator is used as an alternative to the .convert method.

Source§

type Output = Parser<O>

The resulting type after applying the ^ operator.
Source§

fn bitxor(self, rhs: fn(T) -> Result<O, E>) -> Self::Output

Performs the ^ operation. Read more
Source§

impl<T: Clone> Clone for Parser<T>

Source§

fn clone(&self) -> Parser<T>

Returns a duplicate of the value. Read more
1.0.0 · Source§

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

Performs copy-assignment from source. Read more
Source§

impl<T: 'static + Clone, R: RangeBounds<usize>> Mul<R> for Parser<T>

A parser can be multiplied by a range as an alternative to .repeat. Here’s an example: sym('a') * (..7)

Source§

type Output = Parser<Vec<T>>

The resulting type after applying the * operator.
Source§

fn mul(self, rhs: R) -> Self::Output

Performs the * operation. Read more
Source§

impl<T: 'static + Clone> Not for Parser<T>

The ! operator can be used as an alternative to the .not method

Source§

type Output = Parser<()>

The resulting type after applying the ! operator.
Source§

fn not(self) -> Self::Output

Performs the unary ! operation. Read more
Source§

impl<T: 'static + Clone, S: ToString> Rem<S> for Parser<T>

The | operator can be used as an alternative to the .or method

Source§

type Output = Parser<T>

The resulting type after applying the % operator.
Source§

fn rem(self, rhs: S) -> Self::Output

Performs the % operation. Read more
Source§

impl<A: 'static + Clone, B: 'static + Clone> Shl<Parser<B>> for Parser<A>

Discard the consumed data of the RHS

Source§

type Output = Parser<A>

The resulting type after applying the << operator.
Source§

fn shl(self, rhs: Parser<B>) -> Self::Output

Performs the << operation. Read more
Source§

impl<A: 'static + Clone, B: 'static + Clone> Shr<Parser<B>> for Parser<A>

Discard the consumed data of the LHS

Source§

type Output = Parser<B>

The resulting type after applying the >> operator.
Source§

fn shr(self, rhs: Parser<B>) -> Self::Output

Performs the >> operation. Read more
Source§

impl<O, T> Sub<fn(T) -> O> for Parser<T>
where O: 'static + Clone, T: 'static + Clone,

The - operator is used as an alternative to the .map method.

Source§

type Output = Parser<O>

The resulting type after applying the - operator.
Source§

fn sub(self, rhs: fn(T) -> O) -> Self::Output

Performs the - operation. Read more

Auto Trait Implementations§

§

impl<T> Freeze for Parser<T>

§

impl<T> !RefUnwindSafe for Parser<T>

§

impl<T> !Send for Parser<T>

§

impl<T> !Sync for Parser<T>

§

impl<T> Unpin for Parser<T>

§

impl<T> !UnwindSafe for Parser<T>

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 = Infallible

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

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.