6 releases (breaking)

Uses old Rust 2015

0.5.0 Nov 23, 2019
0.4.0 Oct 10, 2019
0.3.0 May 16, 2016
0.2.0 Mar 7, 2016
0.0.1 Nov 13, 2014

#54 in Parser tooling

Download history 131/week @ 2023-02-04 37/week @ 2023-02-11 91/week @ 2023-02-18 37/week @ 2023-02-25 56/week @ 2023-03-04 7/week @ 2023-03-11 39/week @ 2023-03-18 4/week @ 2023-03-25 43/week @ 2023-04-01 34/week @ 2023-04-08 2/week @ 2023-04-15 24/week @ 2023-04-22 37/week @ 2023-04-29 30/week @ 2023-05-06 9/week @ 2023-05-13 20/week @ 2023-05-20

98 downloads per month
Used in 9 crates (8 directly)


3.5K SLoC

cfg • Build status Latest version

Rust library for manipulating context-free grammars. You can check the documentation here.

Analyzing and modifying grammars

The following features are implemented thus far:

  • cycle detection and elimination,
  • useless rule detection and elimination,
  • grammar binarization,
  • nulling rule elimination for binarized grammars,
  • FIRST and FOLLOW set computation,
  • minimal distance computation,
  • unused symbol removal.

Building grammars

cfg includes an interface that simplifies grammar construction.

Generating symbols

The easiest way of generating symbols is with the sym method. The library is unaware of the start symbol.

let mut grammar: Cfg = Cfg::new();
let (start, expr, identifier, number,
     plus, multiply, power, l_paren, r_paren, digit) = grammar.sym();

Building grammar rules

Rules have a LHS symbol and zero or more RHS symbols.

                   .rhs([identifier, l_paren, expr, r_paren]);

Building sequence rules

Sequence rules have a LHS symbol, a RHS symbol, a range of repetitions, and optional separation. Aside from separation, they closely resemble regular expression repetitions.

grammar.sequence(number).inclusive(1, None).rhs(digit);

Building precedenced rules

Precedenced rules are the most convenient way to describe operators. Once built, they are immediately rewritten into basic grammar rules, and unique symbols are generated. Operator associativity can be set to Right or Group. It's Left by default.

use cfg::precedence::Associativity::{Right, Group};

           .rhs([l_paren, expr, r_paren])
           .rhs([expr, power, expr])
           .rhs([expr, multiply, expr])
           .rhs([expr, plus, expr]);

Using a custom grammar representation

Your grammar type has to implement several traits:

  • RuleContainer
  • ContextFree
  • ContextFreeRef
  • ContextFreeMut


Dual-licensed for compatibility with the Rust project.

Licensed under the Apache License Version 2.0: http://www.apache.org/licenses/LICENSE-2.0, or the MIT license: http://opensource.org/licenses/MIT, at your option.


~30K SLoC