Use the pest crate to define a grammar in a .pest file and generate a parser via the pest_derive macro.
- Add the
pestandpest_derivedependencies to yourCargo.toml.
[dependencies]
pest = "2.7"
pest_derive = "2.7"
- Create a grammar file named
grammar.pestin your project root and define your rules.
WHITESPACE = _{ " " | "\t" | "\n" }
start = { (number | word)+ }
number = @{ ASCII_DIGIT+ }
word = @{ ASCII_ALPHA+ }
- Import the grammar into your Rust code using the
#[grammar]attribute to generate the parser struct.
use pest_derive::Parser;
#[derive(Parser)]
#[grammar = "grammar.pest"]
struct MyParser;
fn main() {
let pairs = MyParser::parse(pest::Rule::start, "hello 123").unwrap();
for pair in pairs { println!("{:?}", pair.as_rule()); }
}
- Run your application to parse input strings according to the defined grammar rules.
cargo run