1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
//! A parser for ABNF, utilized for parsing in accordance with RFC 5234.
// cspell: words Naur
#![allow(missing_docs)] // TODO(apskhem): Temporary, to bo removed in a subsequent PR
use derive_more::From;
pub use pest::Parser;
use pest::{error::Error, iterators::Pairs};
pub mod abnf {
pub use pest::Parser;
#[derive(pest_derive::Parser)]
#[grammar = "grammar/rfc_5234.pest"]
pub struct ABNFParser;
}
pub mod abnf_test {
pub use pest::Parser;
#[derive(pest_derive::Parser)]
#[grammar = "grammar/rfc_5234.pest"]
#[grammar = "grammar/abnf_test.pest"]
pub struct ABNFTestParser;
}
/// Abstract Syntax Tree (AST) representing parsed ABNF syntax.
#[derive(Debug)]
#[allow(dead_code)]
pub struct AST<'a>(Pairs<'a, abnf::Rule>);
/// Represents an error that may occur during ABNF parsing.
#[derive(thiserror::Error, Debug, From)]
#[error("{0}")]
pub struct ABNFError(Error<abnf::Rule>);
/// Parses the input string containing ABNF (Augmented Backus-Naur Form) syntax and
/// returns the Abstract Syntax Tree (AST).
///
/// # Arguments
///
/// * `input` - A reference to a string slice containing the ABNF syntax to parse.
///
/// # Returns
///
/// Returns a `Result` where the successful variant contains the Abstract Syntax Tree
/// (AST) representing the parsed ABNF, and the error variant contains a boxed
/// `ABNFError`.
///
/// # Errors
///
/// This function may return an error in the following cases:
///
/// - If there is an issue with parsing the ABNF input.
///
/// # Examples
///
/// ```rs
/// use cbork_abnf_parser::parse_abnf;
/// use std:fs;
///
/// let input = fs::read_to_string("path/to/your/file.abnf").unwrap();
/// let result = parse_abnf(&input);
/// ```
pub fn parse_abnf(input: &str) -> Result<AST<'_>, Box<ABNFError>> {
let result: Result<AST<'_>, _> = abnf::ABNFParser::parse(abnf::Rule::abnf, input)
.map(AST)
.map_err(ABNFError);
result.map_err(Box::new)
}
#[cfg(test)]
mod tests {
use crate::*;
#[test]
fn it_works() {
let input = String::new();
let result = parse_abnf(&input);
match result {
Ok(c) => println!("{c:?}"),
Err(e) => {
println!("{e:?}");
println!("{e}");
},
}
}
}