1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
use crate::{error::ParseErrorKind, Span};

use super::Rule;

#[derive(Clone)]
pub struct Lookaround<'i> {
    pub kind: LookaroundKind,
    pub rule: Rule<'i>,
    pub span: Span,
}

#[derive(Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "dbg", derive(Debug))]
pub enum LookaroundKind {
    Ahead,
    Behind,
    AheadNegative,
    BehindNegative,
}

impl<'i> Lookaround<'i> {
    pub(crate) fn new(rule: Rule<'i>, kind: LookaroundKind, span: Span) -> Self {
        Lookaround { kind, rule, span }
    }

    pub(crate) fn negate(&mut self) -> Result<(), ParseErrorKind> {
        match self.kind {
            LookaroundKind::AheadNegative | LookaroundKind::BehindNegative => {
                Err(ParseErrorKind::UnallowedMultiNot(2))
            }
            LookaroundKind::Ahead => {
                self.kind = LookaroundKind::AheadNegative;
                Ok(())
            }
            LookaroundKind::Behind => {
                self.kind = LookaroundKind::BehindNegative;
                Ok(())
            }
        }
    }

    #[cfg(feature = "dbg")]
    pub(super) fn pretty_print(&self, buf: &mut crate::PrettyPrinter, needs_parens: bool) {
        let s = match self.kind {
            LookaroundKind::Ahead => ">>",
            LookaroundKind::Behind => "<<",
            LookaroundKind::AheadNegative => "!>>",
            LookaroundKind::BehindNegative => "!<<",
        };
        if needs_parens {
            buf.push('(');
            buf.start_indentation(s);
        } else {
            buf.push_str(s);
            buf.push(' ');
        }

        self.rule.pretty_print(buf, false);

        if needs_parens {
            buf.end_indentation(")");
        }
    }
}