summaryrefslogtreecommitdiff
path: root/pest_consume/src/lib.rs
blob: 425d8cf87f81c4eed76030a87b50068f28c56ee7 (plain)
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
use pest::error::Error;
use pest::Parser as PestParser;
use pest::RuleType;

#[proc_macro_hack::proc_macro_hack]
pub use pest_consume_macros::match_inputs;
pub use pest_consume_macros::parser;

mod node {
    use super::Parser;
    use pest::error::{Error, ErrorVariant};
    use pest::iterators::{Pair, Pairs};
    use pest::Parser as PestParser;
    use pest::{RuleType, Span};

    /// Carries a pest Pair alongside custom user data.
    #[derive(Debug, Clone)]
    pub struct Node<'input, Rule: RuleType, Data> {
        pair: Pair<'input, Rule>,
        user_data: Data,
    }

    /// Iterator over `Node`s. It is created by `Node::children` or `Nodes::new`.
    #[derive(Debug, Clone)]
    pub struct Nodes<'input, Rule: RuleType, Data> {
        pairs: Pairs<'input, Rule>,
        span: Span<'input>,
        user_data: Data,
    }

    impl<'i, R: RuleType, D> Node<'i, R, D> {
        pub fn new(pair: Pair<'i, R>, user_data: D) -> Self {
            Node { pair, user_data }
        }
        /// Create an error that points to the span of the input.
        pub fn error(&self, message: String) -> Error<R> {
            Error::new_from_span(
                ErrorVariant::CustomError { message },
                self.as_span(),
            )
        }
        /// Reconstruct the input with a new pair, passing the user data along.
        pub fn with_pair(&self, new_pair: Pair<'i, R>) -> Self
        where
            D: Clone,
        {
            Node {
                pair: new_pair,
                user_data: self.user_data.clone(),
            }
        }
        /// If the contained pair has exactly one child, return a new Self containing it.
        pub fn single_child(&self) -> Option<Self>
        where
            D: Clone,
        {
            let mut children = self.pair.clone().into_inner();
            if let Some(child) = children.next() {
                if children.next().is_none() {
                    return Some(self.with_pair(child));
                }
            }
            None
        }
        /// Return an iterator over the children of this input
        // Can't use `-> impl Iterator` because of weird lifetime limitations
        // (see https://github.com/rust-lang/rust/issues/61997).
        pub fn children(&self) -> Nodes<'i, R, D>
        where
            D: Clone,
        {
            Nodes {
                pairs: self.as_pair().clone().into_inner(),
                span: self.as_span(),
                user_data: self.user_data(),
            }
        }

        pub fn user_data(&self) -> D
        where
            D: Clone,
        {
            self.user_data.clone()
        }
        pub fn as_pair(&self) -> &Pair<'i, R> {
            &self.pair
        }
        pub fn as_span(&self) -> Span<'i> {
            self.pair.as_span()
        }
        pub fn as_str(&self) -> &'i str {
            self.pair.as_str()
        }
        pub fn as_rule(&self) -> R {
            self.pair.as_rule()
        }
        pub fn as_aliased_rule<C>(&self) -> C::AliasedRule
        where
            C: Parser<Rule = R>,
            <C as Parser>::Parser: PestParser<R>,
        {
            C::rule_alias(self.as_rule())
        }
    }

    impl<'i, R: RuleType, D> Nodes<'i, R, D> {
        /// `input` must be the _original_ input that `pairs` is pointing to.
        pub fn new(input: &'i str, pairs: Pairs<'i, R>, user_data: D) -> Self {
            let span = Span::new(input, 0, input.len()).unwrap();
            Nodes {
                pairs,
                span,
                user_data,
            }
        }
        /// Create an error that points to the span of the input.
        pub fn error(&self, message: String) -> Error<R> {
            Error::new_from_span(
                ErrorVariant::CustomError { message },
                self.span.clone(),
            )
        }
        pub fn aliased_rules<C>(&self) -> Vec<C::AliasedRule>
        where
            D: Clone,
            C: Parser<Rule = R>,
            <C as Parser>::Parser: PestParser<R>,
        {
            self.clone().map(|p| p.as_aliased_rule::<C>()).collect()
        }
        /// Reconstruct the input with a new pair, passing the user data along.
        fn with_pair(&self, new_pair: Pair<'i, R>) -> Node<'i, R, D>
        where
            D: Clone,
        {
            Node::new(new_pair, self.user_data.clone())
        }
    }

    impl<'i, R, D> Iterator for Nodes<'i, R, D>
    where
        R: RuleType,
        D: Clone,
    {
        type Item = Node<'i, R, D>;

        fn next(&mut self) -> Option<Self::Item> {
            let child_pair = self.pairs.next()?;
            let child = self.with_pair(child_pair);
            Some(child)
        }
    }

    impl<'i, R, D> DoubleEndedIterator for Nodes<'i, R, D>
    where
        R: RuleType,
        D: Clone,
    {
        fn next_back(&mut self) -> Option<Self::Item> {
            let child_pair = self.pairs.next_back()?;
            let child = self.with_pair(child_pair);
            Some(child)
        }
    }
}

pub use node::{Node, Nodes};

/// Used by the macros.
/// Do not implement manually.
pub trait Parser {
    type Rule: RuleType;
    type AliasedRule: RuleType;
    type Parser: PestParser<Self::Rule>;

    fn rule_alias(rule: Self::Rule) -> Self::AliasedRule;
    fn allows_shortcut(rule: Self::Rule) -> bool;

    /// Parses a `&str` starting from `rule`
    fn parse<'i>(
        rule: Self::Rule,
        input_str: &'i str,
    ) -> Result<Nodes<'i, Self::Rule, ()>, Error<Self::Rule>> {
        Self::parse_with_userdata(rule, input_str, ())
    }

    /// Parses a `&str` starting from `rule`, carrying `user_data` through the parser methods.
    fn parse_with_userdata<'i, D>(
        rule: Self::Rule,
        input_str: &'i str,
        user_data: D,
    ) -> Result<Nodes<'i, Self::Rule, D>, Error<Self::Rule>> {
        let pairs = Self::Parser::parse(rule, input_str)?;
        Ok(Nodes::new(input_str, pairs, user_data))
    }
}