| Crates.io | backus_naur_form_parser_and_compiler |
| lib.rs | backus_naur_form_parser_and_compiler |
| version | 0.1.1 |
| created_at | 2025-01-03 17:24:50.923023+00 |
| updated_at | 2025-01-03 17:41:56.267031+00 |
| description | A parser and compiler that uses Backus Naur Forms to create the AST with a option to compile the AST. |
| homepage | |
| repository | |
| max_upload_size | |
| id | 1502640 |
| size | 76,665 |
Uses backus naur forms to parse and compile strings.
The BackusNaurForm struct represents a backus naur form. To create one, the macro is recommended. A rule consists of up to 3 things:
The below code is a example that doubles the digits of a equation
let bnf = backus_naur_form!(
priority 0 => r#"<digit> ::= "1" | "2" | "3""# => |digit_token, _bnf| {
(digit_token
.get_terminals()
.parse::<usize>()
.expect("failed to parse <digit> to usize")
* 2)
.to_string()
}
priority 0 => r#"<operator> ::= "+" | "-" | "*" | "/""#
priority 0 => r#"<expression> ::= <digit> <operator> <digit>"# => |token, _bnf| {
let digits =
token.get_child_tokens_of_type(&Symbol::NonTerminal("digit".to_string()));
let _operator =
token.get_child_tokens_of_type(&Symbol::NonTerminal("operator".to_string()));
// let t = token
let parsed_and_doubled = digits
.into_iter()
.map(|digit| {
(digit
.get_terminals()
.parse::<usize>()
.expect("failed to parse <digit> to usize")
* 2)
.to_string()
})
.collect::<Vec<_>>();
let a = parsed_and_doubled
.first()
.expect("failed to parse first digit")
.to_owned()
+ "<here comes the operator>"
+ parsed_and_doubled
.last()
.expect("failed to parse last digit");
println!("{a}");
a
}
);
assert_eq!(
bnf.compile_string("2+3"),
"4<here comes the operator>6".to_string()
);