pomsky_syntax/exprs/
intersection.rs

1//! Implements intersection: `'alt1' & 'alt2' & 'alt3'`. This is not a common feature,
2//! and only makes sense in certain scenarios.
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 Intersection {
18    pub rules: Vec<Rule>,
19    pub span: Span,
20}
21
22impl Intersection {
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 = matches!(
32                rule,
33                Rule::Intersection(_)
34                    | Rule::Alternation(_)
35                    | Rule::Lookaround(_)
36                    | Rule::StmtExpr(_)
37            );
38
39            buf.push_str("& ");
40            buf.increase_indentation(2);
41            rule.pretty_print(buf, needs_parens);
42            buf.decrease_indentation(2);
43            if i < len - 1 {
44                buf.write("\n");
45            }
46        }
47
48        if needs_parens {
49            buf.end_indentation(")");
50        }
51    }
52}