pest_meta/optimizer/
rotater.rs

1// pest. The Elegant Parser
2// Copyright (c) 2018 DragoČ™ Tiselice
3//
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.
9
10use crate::ast::*;
11
12pub fn rotate(rule: Rule) -> Rule {
13    fn rotate_internal(expr: Expr) -> Expr {
14        match expr {
15            // TODO: Use box syntax when it gets stabilized.
16            Expr::Seq(lhs, rhs) => {
17                let lhs = *lhs;
18                match lhs {
19                    Expr::Seq(ll, lr) => {
20                        rotate_internal(Expr::Seq(ll, Box::new(Expr::Seq(lr, rhs))))
21                    }
22                    lhs => Expr::Seq(Box::new(lhs), rhs),
23                }
24            }
25            Expr::Choice(lhs, rhs) => {
26                let lhs = *lhs;
27                match lhs {
28                    Expr::Choice(ll, lr) => {
29                        rotate_internal(Expr::Choice(ll, Box::new(Expr::Choice(lr, rhs))))
30                    }
31                    lhs => Expr::Choice(Box::new(lhs), rhs),
32                }
33            }
34            expr => expr,
35        }
36    }
37
38    let Rule { name, ty, expr } = rule;
39    Rule {
40        name,
41        ty,
42        expr: expr.map_top_down(rotate_internal),
43    }
44}