]> git.proxmox.com Git - rustc.git/blob - vendor/pest_meta/src/optimizer/factorizer.rs
New upstream version 1.65.0+dfsg1
[rustc.git] / vendor / pest_meta / src / optimizer / factorizer.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
10 use crate::ast::*;
11
12 pub fn factor(rule: Rule) -> Rule {
13 let Rule { name, ty, expr } = rule;
14 Rule {
15 name,
16 ty,
17 expr: expr.map_top_down(|expr| {
18 // TODO: Use box syntax when it gets stabilized.
19 match expr {
20 Expr::Choice(lhs, rhs) => match (*lhs, *rhs) {
21 (Expr::Seq(l1, r1), Expr::Seq(l2, r2)) => {
22 if l1 == l2 {
23 Expr::Seq(l1, Box::new(Expr::Choice(r1, r2)))
24 } else {
25 Expr::Choice(Box::new(Expr::Seq(l1, r1)), Box::new(Expr::Seq(l2, r2)))
26 }
27 }
28 // Converts `(rule ~ rest) | rule` to `rule ~ rest?`, avoiding trying to match `rule` twice.
29 (Expr::Seq(l1, l2), r) => {
30 if *l1 == r {
31 Expr::Seq(l1, Box::new(Expr::Opt(l2)))
32 } else {
33 Expr::Choice(Box::new(Expr::Seq(l1, l2)), Box::new(r))
34 }
35 }
36 // Converts `rule | (rule ~ rest)` to `rule` since `(rule ~ rest)`
37 // will never match if `rule` didn't.
38 (l, Expr::Seq(r1, r2)) => {
39 if l == *r1 {
40 l
41 } else {
42 Expr::Choice(Box::new(l), Box::new(Expr::Seq(r1, r2)))
43 }
44 }
45 (lhs, rhs) => Expr::Choice(Box::new(lhs), Box::new(rhs)),
46 },
47 expr => expr,
48 }
49 }),
50 }
51 }