How to Use pest for PEG Parsing in Rust

Use the pest crate and pest_derive macro to define a grammar file and generate a PEG parser for Rust.

Use the pest crate to define a grammar in a .pest file and generate a parser via the pest_derive macro.

  1. Add the pest and pest_derive dependencies to your Cargo.toml.
[dependencies]
pest = "2.7"
pest_derive = "2.7"
  1. Create a grammar file named grammar.pest in your project root and define your rules.
WHITESPACE = _{ " " | "\t" | "\n" }
start = { (number | word)+ }
number = @{ ASCII_DIGIT+ }
word = @{ ASCII_ALPHA+ }
  1. 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()); }
}
  1. Run your application to parse input strings according to the defined grammar rules.
cargo run