operations_parser/
lib.rs

1use pest::Parser;
2use pest_derive::Parser;
3use thiserror::Error;
4
5/// The `ArithmeticParser` is a parser generated by `pest`
6/// based on the grammar defined in `grammar.pest`.
7/// 
8/// It is designed to parse arithmetic expressions and generate
9/// a parse tree according to the rules specified in the grammar file.
10#[derive(Parser)]
11#[grammar = "grammar.pest"]
12pub struct ArithmeticParser;
13
14/// The `ParseError` enum represents errors that can occur
15/// during the parsing of arithmetic expressions.
16///
17/// It wraps errors produced by the `pest` library.
18#[derive(Debug, Error)]
19pub enum ParseError {
20    /// Error that occurs when parsing fails, wrapping the `pest` error.
21    #[error("Failed to parse the arithmetic expression")]
22    PestError(#[from] pest::error::Error<Rule>),
23}
24
25/// Parses an arithmetic expression and prints its parse tree.
26///
27/// # Arguments
28///
29/// - `input`: A string slice containing the arithmetic expression to parse.
30///
31/// # Returns
32///
33/// - `Ok(())` if the parsing is successful.
34/// - `Err(ParseError)` if an error occurs during parsing.
35///
36/// # Example
37///
38/// ```rust
39/// use your_crate::parse_expression;
40///
41/// let input = "3 + 5 * 2";
42/// match parse_expression(input) {
43///     Ok(_) => println!("Parse successful!"),
44///     Err(e) => eprintln!("Parse error: {}", e),
45/// }
46/// ```
47pub fn parse_expression(input: &str) -> Result<(), ParseError> {
48    let pairs = ArithmeticParser::parse(Rule::expression, input)?;
49
50    print_parse_tree(pairs, 0);
51    Ok(())
52}
53
54/// Recursively prints the parse tree of the given `pairs` from `pest`.
55///
56/// # Arguments
57///
58/// - `pairs`: The `pest::iterators::Pairs` object representing the parse tree.
59/// - `depth`: The current depth of the recursion for pretty-printing purposes.
60///
61/// This function is primarily for debugging and educational purposes,
62/// as it visualizes the structure of the parsed input.
63fn print_parse_tree(pairs: pest::iterators::Pairs<Rule>, depth: usize) {
64    for pair in pairs {
65        for _ in 0..depth {
66            print!("  ");
67        }
68
69        println!("{:?}: {:?}", pair.as_rule(), pair.as_str());
70
71        print_parse_tree(pair.into_inner(), depth + 1);
72    }
73}