]>
git.proxmox.com Git - rustc.git/blob - vendor/pest_meta/src/optimizer/factorizer.rs
1 // pest. The Elegant Parser
2 // Copyright (c) 2018 DragoČ™ Tiselice
4 // Licensed under the Apache License, Version 2.0
5 // <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT
6 // license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. All files in the project carrying such notice may not be copied,
8 // modified, or distributed except according to those terms.
12 pub fn factor(rule
: Rule
) -> Rule
{
13 let Rule { name, ty, expr }
= rule
;
17 expr
: expr
.map_top_down(|expr
| {
18 // TODO: Use box syntax when it gets stabilized.
20 Expr
::Choice(lhs
, rhs
) => match (*lhs
, *rhs
) {
21 (Expr
::Seq(l1
, r1
), Expr
::Seq(l2
, r2
)) => {
23 Expr
::Seq(l1
, Box
::new(Expr
::Choice(r1
, r2
)))
25 Expr
::Choice(Box
::new(Expr
::Seq(l1
, r1
)), Box
::new(Expr
::Seq(l2
, r2
)))
28 // Converts `(rule ~ rest) | rule` to `rule ~ rest?`, avoiding trying to match `rule` twice.
29 (Expr
::Seq(l1
, l2
), r
) => {
31 Expr
::Seq(l1
, Box
::new(Expr
::Opt(l2
)))
33 Expr
::Choice(Box
::new(Expr
::Seq(l1
, l2
)), Box
::new(r
))
36 // Converts `rule | (rule ~ rest)` to `rule` since `(rule ~ rest)`
37 // will never match if `rule` didn't.
38 (l
, Expr
::Seq(r1
, r2
)) => {
42 Expr
::Choice(Box
::new(l
), Box
::new(Expr
::Seq(r1
, r2
)))
45 (lhs
, rhs
) => Expr
::Choice(Box
::new(lhs
), Box
::new(rhs
)),