pest_meta/optimizer/lister.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 list(rule: Rule) -> Rule {
13 let Rule { name, ty, expr } = rule;
14 Rule {
15 name,
16 ty,
17 expr: expr.map_bottom_up(|expr| {
18 // TODO: Use box syntax when it gets stabilized.
19 match expr {
20 Expr::Seq(l, r) => match *l {
21 Expr::Rep(l) => {
22 let l = *l;
23 match l {
24 Expr::Seq(l1, l2) => {
25 // Converts `(rule ~ rest)* ~ rule` to `rule ~ (rest ~ rule)*`,
26 // avoiding matching the last `rule` twice.
27 if l1 == r {
28 Expr::Seq(l1, Box::new(Expr::Rep(Box::new(Expr::Seq(l2, r)))))
29 } else {
30 Expr::Seq(Box::new(Expr::Rep(Box::new(Expr::Seq(l1, l2)))), r)
31 }
32 }
33 expr => Expr::Seq(Box::new(Expr::Rep(Box::new(expr))), r),
34 }
35 }
36 expr => Expr::Seq(Box::new(expr), r),
37 },
38 expr => expr,
39 }
40 }),
41 }
42}