pomsky_syntax/exprs/
alternation.rs

1//! Implements [alternation](https://www.regular-expressions.info/alternation.html):
2//! `('alt1' | 'alt2' | 'alt3')`.
3
4use crate::Span;
5
6use super::Rule;
7
8/// An [alternation](https://www.regular-expressions.info/alternation.html).
9/// This is a list of alternatives. Each alternative is a [`Rule`].
10///
11/// If an alternative consists of multiple expressions (e.g. `'a' | 'b' 'c'`),
12/// that alternative is a [`Rule::Group`]. Note that a group's parentheses are
13/// removed when compiling to a regex if they aren't required. In other words,
14/// `'a' | ('b' 'c')` compiles to `a|bc`.
15#[derive(Debug, Clone)]
16#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
17pub struct Alternation {
18    pub rules: Vec<Rule>,
19    pub(crate) span: Span,
20}
21
22impl Alternation {
23    #[cfg(feature = "dbg")]
24    pub(super) fn pretty_print(&self, buf: &mut crate::PrettyPrinter, needs_parens: bool) {
25        if needs_parens {
26            buf.start_indentation("(");
27        }
28
29        let len = self.rules.len();
30        for (i, rule) in self.rules.iter().enumerate() {
31            let needs_parens =
32                matches!(rule, Rule::Alternation(_) | Rule::Lookaround(_) | Rule::StmtExpr(_));
33
34            buf.push_str("| ");
35            buf.increase_indentation(2);
36            rule.pretty_print(buf, needs_parens);
37            buf.decrease_indentation(2);
38            if i < len - 1 {
39                buf.write("\n");
40            }
41        }
42
43        if needs_parens {
44            buf.end_indentation(")");
45        }
46    }
47}