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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
use crate::ast;
use crate::{Parse, ParseError, Parser, Peek, Peeker, Spanned, ToTokens};

macro_rules! grouped {
    ($(#[$meta:meta])* $name:ident { $field:ident, $open:ty, $close:ty }) => {
        $(#[$meta])*
        #[derive(Debug, Clone, PartialEq, Eq, Spanned, ToTokens)]
        pub struct $name<T, S> {
            /// The open parenthesis.
            pub open: $open,
            /// Values in the type.
            pub $field: Vec<(T, Option<S>)>,
            /// The close parenthesis.
            pub close: $close,
        }

        impl<T, S> $name<T, S> {
            /// Test if empty.
            pub fn is_empty(&self) -> bool {
                self.$field.is_empty()
            }

            /// Get the length of the parsed elements.
            pub fn len(&self) -> usize {
                self.$field.len()
            }

            /// Get the first element.
            pub fn first(&self) -> Option<&(T, Option<S>)> {
                self.$field.first()
            }

            /// Get the last element.
            pub fn last(&self) -> Option<&(T, Option<S>)> {
                self.$field.last()
            }

            /// Iterate over elements.
            pub fn iter(&self) -> std::slice::Iter<'_, (T, Option<S>)> {
                self.$field.iter()
            }

            /// Iterate mutably over elements.
            pub fn iter_mut(&mut self) -> std::slice::IterMut<'_, (T, Option<S>)> {
                self.$field.iter_mut()
            }

            /// Get the values as a slice.
            pub fn as_slice(&self) -> &[(T, Option<S>)] {
                &*self.$field
            }
        }

        impl<'a, T, S> IntoIterator for &'a $name<T, S> {
            type Item = &'a (T, Option<S>);
            type IntoIter = std::slice::Iter<'a, (T, Option<S>)>;

            fn into_iter(self) -> Self::IntoIter {
                self.iter()
            }
        }

        impl<'a, T, S> IntoIterator for &'a mut $name<T, S> {
            type Item = &'a mut (T, Option<S>);
            type IntoIter = std::slice::IterMut<'a, (T, Option<S>)>;

            fn into_iter(self) -> Self::IntoIter {
                self.iter_mut()
            }
        }

        impl<T, S> IntoIterator for $name<T, S> {
            type Item = (T, Option<S>);
            type IntoIter = std::vec::IntoIter<(T, Option<S>)>;

            fn into_iter(self) -> Self::IntoIter {
                self.$field.into_iter()
            }
        }

        impl<T, S> $name<T, S>
        where
            T: Parse,
            S: Peek + Parse,
        {
            /// Parse with the first element already specified.
            pub fn parse_from_first(
                parser: &mut Parser<'_>,
                open: $open,
                mut current: T,
            ) -> Result<Self, ParseError> {
                let mut $field = Vec::new();

                loop {
                    let comma = parser.parse::<Option<S>>()?;
                    let is_end = comma.is_none();
                    $field.push((current, comma));

                    if is_end || parser.peek::<$close>()? {
                        break;
                    }

                    current = parser.parse()?;
                }

                let close = parser.parse()?;

                Ok(Self {
                    open,
                    $field,
                    close,
                })
            }
        }

        impl<T, S> Parse for $name<T, S>
        where
            T: Parse,
            S: Peek + Parse,
        {
            fn parse(parser: &mut Parser<'_>) -> Result<Self, ParseError> {
                let open = parser.parse()?;

                let mut $field = Vec::new();

                while !parser.peek::<$close>()? {
                    let expr = parser.parse()?;
                    let sep = parser.parse::<Option<S>>()?;
                    let is_end = sep.is_none();
                    $field.push((expr, sep));

                    if is_end {
                        break;
                    }
                }

                let close = parser.parse()?;

                Ok(Self {
                    open,
                    $field,
                    close,
                })
            }
        }

        impl<T, S> Peek for $name<T, S> {
            fn peek(p: &mut Peeker<'_>) -> bool {
                <$open>::peek(p)
            }
        }
    }
}

grouped! {
    /// Parse something parenthesis, that is separated by `((T, S?)*)`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rune::{T, testing, ast};
    ///
    /// testing::roundtrip::<ast::Parenthesized<ast::Expr, T![,]>>("(1, \"two\")");
    /// testing::roundtrip::<ast::Parenthesized<ast::Expr, T![,]>>("(1, 2,)");
    /// testing::roundtrip::<ast::Parenthesized<ast::Expr, T![,]>>("(1, 2, foo())");
    /// ```
    Parenthesized { parenthesized, ast::OpenParen, ast::CloseParen }
}

grouped! {
    /// Parse something bracketed, that is separated by `[(T, S?)*]`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rune::{T, testing, ast};
    ///
    /// testing::roundtrip::<ast::Bracketed<ast::Expr, T![,]>>("[1, \"two\"]");
    /// testing::roundtrip::<ast::Bracketed<ast::Expr, T![,]>>("[1, 2,]");
    /// testing::roundtrip::<ast::Bracketed<ast::Expr, T![,]>>("[1, 2, foo()]");
    /// ```
    Bracketed { bracketed, ast::OpenBracket, ast::CloseBracket }
}

grouped! {
    /// Parse something braced, that is separated by `{(T, S?)*}`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rune::{T, testing, ast};
    ///
    /// testing::roundtrip::<ast::Braced<ast::Expr, T![,]>>("{1, \"two\"}");
    /// testing::roundtrip::<ast::Braced<ast::Expr, T![,]>>("{1, 2,}");
    /// testing::roundtrip::<ast::Braced<ast::Expr, T![,]>>("{1, 2, foo()}");
    /// ```
    Braced { braced, ast::OpenBrace, ast::CloseBrace }
}

grouped! {
    /// Parse something bracketed, that is separated by `<(T, S?)*>`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rune::{T, testing, ast};
    ///
    /// testing::roundtrip::<ast::AngleBracketed<ast::Path, T![,]>>("<Foo, Bar>");
    /// testing::roundtrip::<ast::AngleBracketed<ast::ExprWithoutBinary, T![,]>>("<1, \"two\">");
    /// testing::roundtrip::<ast::AngleBracketed<ast::ExprWithoutBinary, T![,]>>("<1, 2,>");
    /// testing::roundtrip::<ast::AngleBracketed<ast::ExprWithoutBinary, T![,]>>("<1, 2, foo()>");
    /// ```
    AngleBracketed { angle_bracketed, ast::generated::Lt, ast::generated::Gt }
}