logical_expression_pest_parser/
parser.rs

1use pest::Parser;
2use pest::iterators::Pairs;
3use pest_derive::Parser;
4use thiserror::Error;
5
6/// The Pest parser struct.
7///
8/// The grammar is included directly from the `grammar.pest` file.
9#[derive(Parser)]
10#[grammar = "./grammar.pest"]
11pub struct Grammar;
12
13/// Custom parsing error created using the [thiserror] crate.
14#[derive(Debug, Error)]
15pub enum ParserError {
16    /// Wrapper for a [pest] crate error.
17    #[error("ParsingError: {0}")]
18    PestError(Box<pest::error::Error<Rule>>),
19
20    /// Error for empty input.
21    #[error("Empty input")]
22    EmptyInputError,
23}
24
25/// Parses an input string into `Pairs<Rule>`.
26///
27/// It checks for empty error and then uses [Grammar] to parse the input with the `file` rule.
28///
29/// # Arguments
30/// * `input` - The string to parse.
31///
32/// # Returns
33/// A [Result] containing successful `Pairs<'_, Rule>` or a [ParserError].
34///
35/// # Errors
36/// Returns [ParserError::PestError] if Pest fails to parse the input string.
37///
38/// Returns [ParserError::EmptyInputError] if `input` is empty.
39pub fn parse(input: &str) -> Result<Pairs<'_, Rule>, ParserError> {
40    if input.is_empty() {
41        return Err(ParserError::EmptyInputError);
42    }
43
44    let pairs =
45        Grammar::parse(Rule::file, input).map_err(|e| ParserError::PestError(Box::new(e)))?;
46    Ok(pairs)
47}