Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

Parsing Expression Grammar (PEG) parser generator for Rust

License

NotificationsYou must be signed in to change notification settings

kevinmehall/rust-peg

Repository files navigation

Documentation |Release Notes

rust-peg is a simple yet flexible parser generator that makes it easy to write robust parsers. Based on theParsing Expression Grammar formalism, it provides a Rust macro that builds a recursive descent parser from a concise definition of the grammar.

Features

  • Parse input from&str,&[u8],&[T] or custom types implementing traits
  • Customizable reporting of parse errors
  • Rules can accept arguments to create reusable rule templates
  • Precedence climbing for prefix/postfix/infix expressions
  • Helpfulrustc error messages for errors in the grammar definition or the Rustcode embedded within it
  • Rule-level tracing to debug grammars

Example

Parse a comma-separated list of numbers surrounded by brackets into aVec<u32>:

peg::parser!{  grammar list_parser()forstr{    rule number() ->u32      = n:$(['0'..='9']+){? n.parse().or(Err("u32"))}pub rule list() ->Vec<u32>      ="[" l:(number()**",")"]"{ l}}}pubfnmain(){assert_eq!(list_parser::list("[1,1,2,3,5,8]"),Ok(vec![1,1,2,3,5,8]));}

See the tests for more examples
Grammar rule syntax reference in rustdoc

Comparison with similar parser generators

crateparser typeaction codeintegrationinput typeprecedence climbingparameterized rulesstreaming input
pegPEGin grammarproc macro (block)&str,&[T], customYesYesNo
pestPEGexternalproc macro (file)&strYesNoNo
nomcombinatorsin sourcelibrary&[u8], customNoYesYes
lalrpopLR(1)in grammarbuild script&strNoYesNo

See also

Development

Therust-peg grammar is written inrust-peg:peg-macros/grammar.rustpeg. To avoid the circular dependency, a precompiled grammar is checked in aspeg-macros/grammar.rs. To regenerate this, run the./bootstrap.sh script.

There is a large test suite which usestrybuild to test both functionality (tests/run-pass) and error messages for incorrect grammars (tests/compile-fail). Becauserustc error messages change, thecompile-fail tests are only run on the minimum supported Rust version to avoid spurious failures.

Usecargo test to run the entire suite,orcargo test -- trybuild trybuild=lifetimes.rs to test just the indicated file.Add--features trace to trace these tests.


[8]ページ先頭

©2009-2025 Movatter.jp