blob: 423b19eb250c4d5745426fad1c022a37b40e27c6 [file] [log] [blame]
David Tolnay55535012018-01-05 16:39:23 -08001// Copyright 2018 Syn Developers
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6// option. This file may not be copied, modified, or distributed
7// except according to those terms.
8
David Tolnayf3198012018-01-06 20:00:42 -08009//! A punctuated sequence of syntax tree nodes separated by punctuation.
10//!
11//! Lots of things in Rust are punctuated sequences.
12//!
13//! - The fields of a struct are `Punctuated<Field, Token![,]>`.
14//! - The segments of a path are `Punctuated<PathSegment, Token![::]>`.
15//! - The bounds on a generic parameter are `Punctuated<TypeParamBound, Token![+]>`.
16//! - The arguments to a function call are `Punctuated<Expr, Token![,]>`.
17//!
18//! This module provides a common representation for these punctuated sequences
19//! in the form of the [`Punctuated<T, P>`] type. We store a vector of pairs of
20//! syntax tree node + punctuation, where every node in the sequence is followed
21//! by punctuation except for possibly the final one.
22//!
23//! [`Punctuated<T, P>`]: struct.Punctuated.html
24//!
25//! ```text
26//! a_function_call(arg1, arg2, arg3);
27//! ^^^^^ ~~~~~ ^^^^
28//! ```
29
David Tolnay6c0a6092018-03-31 22:47:39 +020030#[cfg(any(feature = "full", feature = "derive"))]
31use std::iter;
32use std::iter::FromIterator;
David Tolnaybb987132018-01-08 13:51:19 -080033use std::ops::{Index, IndexMut};
Mateusz Naściszewski14111202018-04-11 21:17:41 +020034use std::option;
Alex Crichtonccbb45d2017-05-23 10:58:24 -070035use std::slice;
36use std::vec;
Nika Layzelld73a3652017-10-24 08:57:05 -040037#[cfg(feature = "extra-traits")]
38use std::fmt::{self, Debug};
Alex Crichtonccbb45d2017-05-23 10:58:24 -070039
David Tolnayf3198012018-01-06 20:00:42 -080040#[cfg(feature = "parsing")]
41use synom::{Synom, PResult};
42#[cfg(feature = "parsing")]
43use buffer::Cursor;
44#[cfg(feature = "parsing")]
45use parse_error;
46
47/// A punctuated sequence of syntax tree nodes of type `T` separated by
48/// punctuation of type `P`.
49///
50/// Refer to the [module documentation] for details about punctuated sequences.
51///
52/// [module documentation]: index.html
Nika Layzelld73a3652017-10-24 08:57:05 -040053#[cfg_attr(feature = "extra-traits", derive(Eq, PartialEq, Hash))]
Alex Crichton7b9e02f2017-05-30 15:54:33 -070054#[cfg_attr(feature = "clone-impls", derive(Clone))]
David Tolnayf2cfd722017-12-31 18:02:51 -050055pub struct Punctuated<T, P> {
Mateusz Naściszewski14111202018-04-11 21:17:41 +020056 inner: Vec<(T, P)>,
57 last: Option<Box<T>>,
Alex Crichtonccbb45d2017-05-23 10:58:24 -070058}
59
David Tolnayf2cfd722017-12-31 18:02:51 -050060impl<T, P> Punctuated<T, P> {
David Tolnayf3198012018-01-06 20:00:42 -080061 /// Creates an empty punctuated sequence.
David Tolnayf2cfd722017-12-31 18:02:51 -050062 pub fn new() -> Punctuated<T, P> {
Mateusz Naściszewski14111202018-04-11 21:17:41 +020063 Punctuated { inner: Vec::new(), last: None }
Alex Crichtonccbb45d2017-05-23 10:58:24 -070064 }
65
David Tolnayf3198012018-01-06 20:00:42 -080066 /// Determines whether this punctuated sequence is empty, meaning it
67 /// contains no syntax tree nodes or punctuation.
Alex Crichtonccbb45d2017-05-23 10:58:24 -070068 pub fn is_empty(&self) -> bool {
Mateusz Naściszewski14111202018-04-11 21:17:41 +020069 self.inner.len() == 0 && self.last.is_none()
Alex Crichtonccbb45d2017-05-23 10:58:24 -070070 }
71
David Tolnayf3198012018-01-06 20:00:42 -080072 /// Returns the number of syntax tree nodes in this punctuated sequence.
73 ///
74 /// This is the number of nodes of type `T`, not counting the punctuation of
75 /// type `P`.
Alex Crichtonccbb45d2017-05-23 10:58:24 -070076 pub fn len(&self) -> usize {
Mateusz Naściszewski14111202018-04-11 21:17:41 +020077 self.inner.len() + if self.last.is_some() { 1 } else { 0 }
Alex Crichtonccbb45d2017-05-23 10:58:24 -070078 }
79
David Tolnayf3198012018-01-06 20:00:42 -080080 /// Borrows the first punctuated pair in this sequence.
David Tolnay56080682018-01-06 14:01:52 -080081 pub fn first(&self) -> Option<Pair<&T, &P>> {
Mateusz Naściszewski14111202018-04-11 21:17:41 +020082 self.pairs().next()
Alex Crichton0aa50e02017-07-07 20:59:03 -070083 }
84
David Tolnayf3198012018-01-06 20:00:42 -080085 /// Borrows the last punctuated pair in this sequence.
David Tolnay56080682018-01-06 14:01:52 -080086 pub fn last(&self) -> Option<Pair<&T, &P>> {
Mateusz Naściszewski14111202018-04-11 21:17:41 +020087 if self.last.is_some() {
88 self.last.as_ref()
89 .map(|t| Pair::End(t.as_ref()))
90 } else {
91 self.inner.last()
92 .map(|&(ref t, ref d)| Pair::Punctuated(t, d))
93 }
Alex Crichton0aa50e02017-07-07 20:59:03 -070094 }
95
David Tolnayf3198012018-01-06 20:00:42 -080096 /// Mutably borrows the last punctuated pair in this sequence.
David Tolnay56080682018-01-06 14:01:52 -080097 pub fn last_mut(&mut self) -> Option<Pair<&mut T, &mut P>> {
Mateusz Naściszewski14111202018-04-11 21:17:41 +020098 if self.last.is_some() {
99 self.last.as_mut()
100 .map(|t| Pair::End(t.as_mut()))
101 } else {
102 self.inner.last_mut()
103 .map(|&mut (ref mut t, ref mut d)| Pair::Punctuated(t, d))
104 }
Alex Crichton0aa50e02017-07-07 20:59:03 -0700105 }
106
David Tolnayf3198012018-01-06 20:00:42 -0800107 /// Returns an iterator over borrowed syntax tree nodes of type `&T`.
David Tolnay8095c302018-03-31 19:34:17 +0200108 pub fn iter(&self) -> Iter<T> {
David Tolnay51382052017-12-27 13:46:21 -0500109 Iter {
David Tolnay8095c302018-03-31 19:34:17 +0200110 inner: Box::new(PrivateIter {
111 inner: self.inner.iter(),
Mateusz Naściszewski14111202018-04-11 21:17:41 +0200112 last: self.last.as_ref().map(|t| t.as_ref()).into_iter(),
David Tolnay8095c302018-03-31 19:34:17 +0200113 }),
David Tolnay51382052017-12-27 13:46:21 -0500114 }
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700115 }
116
David Tolnayf3198012018-01-06 20:00:42 -0800117 /// Returns an iterator over mutably borrowed syntax tree nodes of type
118 /// `&mut T`.
David Tolnay8095c302018-03-31 19:34:17 +0200119 pub fn iter_mut(&mut self) -> IterMut<T> {
David Tolnaya0834b42018-01-01 21:30:02 -0800120 IterMut {
David Tolnay8095c302018-03-31 19:34:17 +0200121 inner: Box::new(PrivateIterMut {
122 inner: self.inner.iter_mut(),
Mateusz Naściszewski14111202018-04-11 21:17:41 +0200123 last: self.last.as_mut().map(|t| t.as_mut()).into_iter(),
David Tolnay8095c302018-03-31 19:34:17 +0200124 }),
David Tolnaya0834b42018-01-01 21:30:02 -0800125 }
126 }
127
David Tolnayf3198012018-01-06 20:00:42 -0800128 /// Returns an iterator over the contents of this sequence as borrowed
129 /// punctuated pairs.
David Tolnay56080682018-01-06 14:01:52 -0800130 pub fn pairs(&self) -> Pairs<T, P> {
131 Pairs {
David Tolnay6eff4da2018-01-01 20:27:45 -0800132 inner: self.inner.iter(),
Mateusz Naściszewski14111202018-04-11 21:17:41 +0200133 last: self.last.as_ref().map(|t| t.as_ref()).into_iter(),
David Tolnay6eff4da2018-01-01 20:27:45 -0800134 }
135 }
136
David Tolnayf3198012018-01-06 20:00:42 -0800137 /// Returns an iterator over the contents of this sequence as mutably
138 /// borrowed punctuated pairs.
David Tolnay56080682018-01-06 14:01:52 -0800139 pub fn pairs_mut(&mut self) -> PairsMut<T, P> {
140 PairsMut {
David Tolnay51382052017-12-27 13:46:21 -0500141 inner: self.inner.iter_mut(),
Mateusz Naściszewski14111202018-04-11 21:17:41 +0200142 last: self.last.as_mut().map(|t| t.as_mut()).into_iter(),
David Tolnay51382052017-12-27 13:46:21 -0500143 }
Alex Crichton164c5332017-07-06 13:18:34 -0700144 }
145
David Tolnayf3198012018-01-06 20:00:42 -0800146 /// Returns an iterator over the contents of this sequence as owned
147 /// punctuated pairs.
David Tolnay56080682018-01-06 14:01:52 -0800148 pub fn into_pairs(self) -> IntoPairs<T, P> {
149 IntoPairs {
David Tolnay6eff4da2018-01-01 20:27:45 -0800150 inner: self.inner.into_iter(),
Mateusz Naściszewski14111202018-04-11 21:17:41 +0200151 last: self.last.map(|t| *t).into_iter(),
David Tolnay6eff4da2018-01-01 20:27:45 -0800152 }
153 }
154
David Tolnayf3198012018-01-06 20:00:42 -0800155 /// Appends a syntax tree node onto the end of this punctuated sequence. The
156 /// sequence must previously have a trailing punctuation.
157 ///
158 /// Use [`push`] instead if the punctuated sequence may or may not already
159 /// have trailing punctuation.
160 ///
161 /// [`push`]: #method.push
162 ///
163 /// # Panics
164 ///
165 /// Panics if the sequence does not already have a trailing punctuation when
166 /// this method is called.
David Tolnay56080682018-01-06 14:01:52 -0800167 pub fn push_value(&mut self, value: T) {
David Tolnaydc03aec2017-12-30 01:54:18 -0500168 assert!(self.empty_or_trailing());
Mateusz Naściszewski14111202018-04-11 21:17:41 +0200169 self.last = Some(Box::new(value));
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700170 }
171
David Tolnayf3198012018-01-06 20:00:42 -0800172 /// Appends a trailing punctuation onto the end of this punctuated sequence.
173 /// The sequence must be non-empty and must not already have trailing
174 /// punctuation.
175 ///
176 /// # Panics
177 ///
178 /// Panics if the sequence is empty or already has a trailing punctuation.
David Tolnaya0834b42018-01-01 21:30:02 -0800179 pub fn push_punct(&mut self, punctuation: P) {
Mateusz Naściszewski14111202018-04-11 21:17:41 +0200180 assert!(!self.is_empty()); // redundant
181 assert!(self.last.is_some());
David Tolnay03163082018-04-11 12:10:18 -0700182 let last = self.last.take().unwrap();
183 self.inner.push((*last, punctuation));
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700184 }
185
David Tolnayf3198012018-01-06 20:00:42 -0800186 /// Removes the last punctuated pair from this sequence, or `None` if the
187 /// sequence is empty.
David Tolnay56080682018-01-06 14:01:52 -0800188 pub fn pop(&mut self) -> Option<Pair<T, P>> {
Mateusz Naściszewski14111202018-04-11 21:17:41 +0200189 if self.last.is_some() {
David Tolnay03163082018-04-11 12:10:18 -0700190 self.last.take().map(|t| Pair::End(*t))
Mateusz Naściszewski14111202018-04-11 21:17:41 +0200191 } else {
192 self.inner.pop().map(|(t, d)| Pair::Punctuated(t, d))
193 }
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700194 }
195
David Tolnayf3198012018-01-06 20:00:42 -0800196 /// Determines whether this punctuated sequence ends with a trailing
197 /// punctuation.
David Tolnaya0834b42018-01-01 21:30:02 -0800198 pub fn trailing_punct(&self) -> bool {
Mateusz Naściszewski14111202018-04-11 21:17:41 +0200199 self.last.is_none() && !self.is_empty()
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700200 }
Michael Layzell3936ceb2017-07-08 00:28:36 -0400201
David Tolnayf2cfd722017-12-31 18:02:51 -0500202 /// Returns true if either this `Punctuated` is empty, or it has a trailing
203 /// punctuation.
David Tolnaydc03aec2017-12-30 01:54:18 -0500204 ///
David Tolnaya0834b42018-01-01 21:30:02 -0800205 /// Equivalent to `punctuated.is_empty() || punctuated.trailing_punct()`.
Michael Layzell3936ceb2017-07-08 00:28:36 -0400206 pub fn empty_or_trailing(&self) -> bool {
Mateusz Naściszewski14111202018-04-11 21:17:41 +0200207 self.last.is_none()
Michael Layzell3936ceb2017-07-08 00:28:36 -0400208 }
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700209}
210
David Tolnaya0834b42018-01-01 21:30:02 -0800211impl<T, P> Punctuated<T, P>
212where
213 P: Default,
214{
David Tolnayf3198012018-01-06 20:00:42 -0800215 /// Appends a syntax tree node onto the end of this punctuated sequence.
216 ///
217 /// If there is not a trailing punctuation in this sequence when this method
218 /// is called, the default value of punctuation type `P` is inserted before
219 /// the given value of type `T`.
David Tolnay56080682018-01-06 14:01:52 -0800220 pub fn push(&mut self, value: T) {
David Tolnaya0834b42018-01-01 21:30:02 -0800221 if !self.empty_or_trailing() {
222 self.push_punct(Default::default());
223 }
David Tolnay56080682018-01-06 14:01:52 -0800224 self.push_value(value);
David Tolnaya0834b42018-01-01 21:30:02 -0800225 }
David Tolnayb77d1802018-01-11 16:18:35 -0800226
227 /// Inserts an element at position `index`.
228 ///
229 /// # Panics
230 ///
231 /// Panics if `index` is greater than the number of elements previously in
232 /// this punctuated sequence.
233 pub fn insert(&mut self, index: usize, value: T) {
234 assert!(index <= self.len());
235
236 if index == self.len() {
237 self.push(value);
238 } else {
Mateusz Naściszewski14111202018-04-11 21:17:41 +0200239 self.inner.insert(index, (value, Default::default()));
David Tolnayb77d1802018-01-11 16:18:35 -0800240 }
241 }
David Tolnaya0834b42018-01-01 21:30:02 -0800242}
243
Nika Layzelld73a3652017-10-24 08:57:05 -0400244#[cfg(feature = "extra-traits")]
David Tolnayf2cfd722017-12-31 18:02:51 -0500245impl<T: Debug, P: Debug> Debug for Punctuated<T, P> {
Nika Layzelld73a3652017-10-24 08:57:05 -0400246 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Mateusz Naściszewski14111202018-04-11 21:17:41 +0200247 let mut list = f.debug_list();
248 list.entries(&self.inner);
249 for t in self.last.iter() {
250 list.entry(&*t);
251 }
252 list.finish()
Nika Layzelld73a3652017-10-24 08:57:05 -0400253 }
254}
255
David Tolnay9ef24bc2018-01-09 10:43:55 -0800256impl<T, P> FromIterator<T> for Punctuated<T, P>
257where
258 P: Default,
259{
260 fn from_iter<I: IntoIterator<Item = T>>(i: I) -> Self {
261 let mut ret = Punctuated::new();
262 ret.extend(i);
263 ret
264 }
265}
266
267impl<T, P> Extend<T> for Punctuated<T, P>
268where
269 P: Default,
270{
271 fn extend<I: IntoIterator<Item = T>>(&mut self, i: I) {
272 for value in i {
273 self.push(value);
274 }
275 }
276}
277
David Tolnay56080682018-01-06 14:01:52 -0800278impl<T, P> FromIterator<Pair<T, P>> for Punctuated<T, P> {
279 fn from_iter<I: IntoIterator<Item = Pair<T, P>>>(i: I) -> Self {
David Tolnayf2cfd722017-12-31 18:02:51 -0500280 let mut ret = Punctuated::new();
Alex Crichton24f12822017-07-14 07:15:32 -0700281 ret.extend(i);
Alex Crichton954046c2017-05-30 21:49:42 -0700282 ret
283 }
284}
285
David Tolnay56080682018-01-06 14:01:52 -0800286impl<T, P> Extend<Pair<T, P>> for Punctuated<T, P> {
287 fn extend<I: IntoIterator<Item = Pair<T, P>>>(&mut self, i: I) {
Mateusz Naściszewski14111202018-04-11 21:17:41 +0200288 assert!(self.empty_or_trailing());
289 let mut nomore = false;
David Tolnay56080682018-01-06 14:01:52 -0800290 for pair in i {
Mateusz Naściszewski14111202018-04-11 21:17:41 +0200291 if nomore {
292 panic!("Punctuated extended with items after a Pair::End");
293 }
David Tolnay56080682018-01-06 14:01:52 -0800294 match pair {
Mateusz Naściszewski14111202018-04-11 21:17:41 +0200295 Pair::Punctuated(a, b) => self.inner.push((a, b)),
296 Pair::End(a) => {
297 self.last = Some(Box::new(a));
298 nomore = true;
299 }
Alex Crichton24f12822017-07-14 07:15:32 -0700300 }
301 }
302 }
303}
304
David Tolnayf2cfd722017-12-31 18:02:51 -0500305impl<T, P> IntoIterator for Punctuated<T, P> {
David Tolnay6eff4da2018-01-01 20:27:45 -0800306 type Item = T;
David Tolnayf2cfd722017-12-31 18:02:51 -0500307 type IntoIter = IntoIter<T, P>;
Alex Crichton954046c2017-05-30 21:49:42 -0700308
David Tolnaybb4ca9f2017-12-26 12:28:58 -0500309 fn into_iter(self) -> Self::IntoIter {
David Tolnay51382052017-12-27 13:46:21 -0500310 IntoIter {
311 inner: self.inner.into_iter(),
Mateusz Naściszewski14111202018-04-11 21:17:41 +0200312 last: self.last.map(|t| *t).into_iter(),
David Tolnay51382052017-12-27 13:46:21 -0500313 }
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700314 }
315}
316
David Tolnay6eff4da2018-01-01 20:27:45 -0800317impl<'a, T, P> IntoIterator for &'a Punctuated<T, P> {
318 type Item = &'a T;
David Tolnay8095c302018-03-31 19:34:17 +0200319 type IntoIter = Iter<'a, T>;
David Tolnay6eff4da2018-01-01 20:27:45 -0800320
321 fn into_iter(self) -> Self::IntoIter {
322 Punctuated::iter(self)
323 }
324}
325
David Tolnaya0834b42018-01-01 21:30:02 -0800326impl<'a, T, P> IntoIterator for &'a mut Punctuated<T, P> {
327 type Item = &'a mut T;
David Tolnay8095c302018-03-31 19:34:17 +0200328 type IntoIter = IterMut<'a, T>;
David Tolnaya0834b42018-01-01 21:30:02 -0800329
330 fn into_iter(self) -> Self::IntoIter {
331 Punctuated::iter_mut(self)
332 }
333}
334
David Tolnayf2cfd722017-12-31 18:02:51 -0500335impl<T, P> Default for Punctuated<T, P> {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700336 fn default() -> Self {
David Tolnayf2cfd722017-12-31 18:02:51 -0500337 Punctuated::new()
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700338 }
339}
340
David Tolnayf3198012018-01-06 20:00:42 -0800341/// An iterator over borrowed pairs of type `Pair<&T, &P>`.
342///
343/// Refer to the [module documentation] for details about punctuated sequences.
344///
345/// [module documentation]: index.html
David Tolnay56080682018-01-06 14:01:52 -0800346pub struct Pairs<'a, T: 'a, P: 'a> {
Mateusz Naściszewski14111202018-04-11 21:17:41 +0200347 inner: slice::Iter<'a, (T, P)>,
348 last: option::IntoIter<&'a T>,
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700349}
350
David Tolnay56080682018-01-06 14:01:52 -0800351impl<'a, T, P> Iterator for Pairs<'a, T, P> {
352 type Item = Pair<&'a T, &'a P>;
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700353
David Tolnay6eff4da2018-01-01 20:27:45 -0800354 fn next(&mut self) -> Option<Self::Item> {
Mateusz Naściszewski14111202018-04-11 21:17:41 +0200355 self.inner.next().map(|&(ref t, ref p)| Pair::Punctuated(t, p))
356 .or_else(|| self.last.next().map(|t| Pair::End(t)))
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700357 }
358}
359
David Tolnayf3198012018-01-06 20:00:42 -0800360/// An iterator over mutably borrowed pairs of type `Pair<&mut T, &mut P>`.
361///
362/// Refer to the [module documentation] for details about punctuated sequences.
363///
364/// [module documentation]: index.html
David Tolnay56080682018-01-06 14:01:52 -0800365pub struct PairsMut<'a, T: 'a, P: 'a> {
Mateusz Naściszewski14111202018-04-11 21:17:41 +0200366 inner: slice::IterMut<'a, (T, P)>,
367 last: option::IntoIter<&'a mut T>,
Alex Crichton164c5332017-07-06 13:18:34 -0700368}
369
David Tolnay56080682018-01-06 14:01:52 -0800370impl<'a, T, P> Iterator for PairsMut<'a, T, P> {
371 type Item = Pair<&'a mut T, &'a mut P>;
Alex Crichton164c5332017-07-06 13:18:34 -0700372
David Tolnay6eff4da2018-01-01 20:27:45 -0800373 fn next(&mut self) -> Option<Self::Item> {
Mateusz Naściszewski14111202018-04-11 21:17:41 +0200374 self.inner.next().map(|&mut (ref mut t, ref mut p)| Pair::Punctuated(t, p))
375 .or_else(|| self.last.next().map(|t| Pair::End(t)))
Alex Crichton164c5332017-07-06 13:18:34 -0700376 }
377}
378
David Tolnayf3198012018-01-06 20:00:42 -0800379/// An iterator over owned pairs of type `Pair<T, P>`.
380///
381/// Refer to the [module documentation] for details about punctuated sequences.
382///
383/// [module documentation]: index.html
David Tolnay56080682018-01-06 14:01:52 -0800384pub struct IntoPairs<T, P> {
Mateusz Naściszewski14111202018-04-11 21:17:41 +0200385 inner: vec::IntoIter<(T, P)>,
386 last: option::IntoIter<T>,
David Tolnay6eff4da2018-01-01 20:27:45 -0800387}
388
David Tolnay56080682018-01-06 14:01:52 -0800389impl<T, P> Iterator for IntoPairs<T, P> {
390 type Item = Pair<T, P>;
David Tolnay6eff4da2018-01-01 20:27:45 -0800391
392 fn next(&mut self) -> Option<Self::Item> {
Mateusz Naściszewski14111202018-04-11 21:17:41 +0200393 self.inner.next().map(|(t, p)| Pair::Punctuated(t, p))
394 .or_else(|| self.last.next().map(|t| Pair::End(t)))
David Tolnay6eff4da2018-01-01 20:27:45 -0800395 }
396}
397
David Tolnayf3198012018-01-06 20:00:42 -0800398/// An iterator over owned values of type `T`.
399///
400/// Refer to the [module documentation] for details about punctuated sequences.
401///
402/// [module documentation]: index.html
David Tolnayf2cfd722017-12-31 18:02:51 -0500403pub struct IntoIter<T, P> {
Mateusz Naściszewski14111202018-04-11 21:17:41 +0200404 inner: vec::IntoIter<(T, P)>,
405 last: option::IntoIter<T>,
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700406}
407
David Tolnayf2cfd722017-12-31 18:02:51 -0500408impl<T, P> Iterator for IntoIter<T, P> {
David Tolnay6eff4da2018-01-01 20:27:45 -0800409 type Item = T;
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700410
David Tolnay6eff4da2018-01-01 20:27:45 -0800411 fn next(&mut self) -> Option<Self::Item> {
Mateusz Naściszewski14111202018-04-11 21:17:41 +0200412 self.inner.next().map(|pair| pair.0).or_else(|| self.last.next())
David Tolnay6eff4da2018-01-01 20:27:45 -0800413 }
414}
415
David Tolnayf3198012018-01-06 20:00:42 -0800416/// An iterator over borrowed values of type `&T`.
417///
418/// Refer to the [module documentation] for details about punctuated sequences.
419///
420/// [module documentation]: index.html
David Tolnay8095c302018-03-31 19:34:17 +0200421pub struct Iter<'a, T: 'a> {
422 inner: Box<Iterator<Item = &'a T> + 'a>,
423}
424
425struct PrivateIter<'a, T: 'a, P: 'a> {
Mateusz Naściszewski14111202018-04-11 21:17:41 +0200426 inner: slice::Iter<'a, (T, P)>,
427 last: option::IntoIter<&'a T>,
David Tolnay6eff4da2018-01-01 20:27:45 -0800428}
429
David Tolnay96a09d92018-01-16 22:24:03 -0800430#[cfg(any(feature = "full", feature = "derive"))]
David Tolnay8095c302018-03-31 19:34:17 +0200431impl<'a, T> Iter<'a, T> {
David Tolnay96a09d92018-01-16 22:24:03 -0800432 // Not public API.
433 #[doc(hidden)]
434 pub fn private_empty() -> Self {
435 Iter {
David Tolnay8095c302018-03-31 19:34:17 +0200436 inner: Box::new(iter::empty()),
David Tolnay96a09d92018-01-16 22:24:03 -0800437 }
438 }
439}
440
David Tolnay8095c302018-03-31 19:34:17 +0200441impl<'a, T> Iterator for Iter<'a, T> {
442 type Item = &'a T;
443
444 fn next(&mut self) -> Option<Self::Item> {
445 self.inner.next()
446 }
447}
448
449impl<'a, T, P> Iterator for PrivateIter<'a, T, P> {
David Tolnay6eff4da2018-01-01 20:27:45 -0800450 type Item = &'a T;
451
452 fn next(&mut self) -> Option<Self::Item> {
Mateusz Naściszewski14111202018-04-11 21:17:41 +0200453 self.inner.next().map(|pair| &pair.0).or_else(|| self.last.next())
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700454 }
455}
456
David Tolnayf3198012018-01-06 20:00:42 -0800457/// An iterator over mutably borrowed values of type `&mut T`.
458///
459/// Refer to the [module documentation] for details about punctuated sequences.
460///
461/// [module documentation]: index.html
David Tolnay8095c302018-03-31 19:34:17 +0200462pub struct IterMut<'a, T: 'a> {
463 inner: Box<Iterator<Item = &'a mut T> + 'a>,
464}
465
466struct PrivateIterMut<'a, T: 'a, P: 'a> {
Mateusz Naściszewski14111202018-04-11 21:17:41 +0200467 inner: slice::IterMut<'a, (T, P)>,
468 last: option::IntoIter<&'a mut T>,
David Tolnaya0834b42018-01-01 21:30:02 -0800469}
470
David Tolnay8095c302018-03-31 19:34:17 +0200471impl<'a, T> Iterator for IterMut<'a, T> {
472 type Item = &'a mut T;
473
474 fn next(&mut self) -> Option<Self::Item> {
475 self.inner.next()
476 }
477}
478
479impl<'a, T, P> Iterator for PrivateIterMut<'a, T, P> {
David Tolnaya0834b42018-01-01 21:30:02 -0800480 type Item = &'a mut T;
481
482 fn next(&mut self) -> Option<Self::Item> {
Mateusz Naściszewski14111202018-04-11 21:17:41 +0200483 self.inner.next().map(|pair| &mut pair.0).or_else(|| self.last.next())
David Tolnaya0834b42018-01-01 21:30:02 -0800484 }
485}
486
David Tolnayf3198012018-01-06 20:00:42 -0800487/// A single syntax tree node of type `T` followed by its trailing punctuation
488/// of type `P` if any.
489///
490/// Refer to the [module documentation] for details about punctuated sequences.
491///
492/// [module documentation]: index.html
David Tolnay56080682018-01-06 14:01:52 -0800493pub enum Pair<T, P> {
David Tolnayf2cfd722017-12-31 18:02:51 -0500494 Punctuated(T, P),
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700495 End(T),
496}
497
David Tolnay56080682018-01-06 14:01:52 -0800498impl<T, P> Pair<T, P> {
David Tolnayf3198012018-01-06 20:00:42 -0800499 /// Extracts the syntax tree node from this punctuated pair, discarding the
500 /// following punctuation.
David Tolnay56080682018-01-06 14:01:52 -0800501 pub fn into_value(self) -> T {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700502 match self {
David Tolnay56080682018-01-06 14:01:52 -0800503 Pair::Punctuated(t, _) | Pair::End(t) => t,
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700504 }
505 }
506
David Tolnayf3198012018-01-06 20:00:42 -0800507 /// Borrows the syntax tree node from this punctuated pair.
David Tolnay56080682018-01-06 14:01:52 -0800508 pub fn value(&self) -> &T {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700509 match *self {
David Tolnay56080682018-01-06 14:01:52 -0800510 Pair::Punctuated(ref t, _) | Pair::End(ref t) => t,
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700511 }
512 }
513
David Tolnayf3198012018-01-06 20:00:42 -0800514 /// Mutably borrows the syntax tree node from this punctuated pair.
David Tolnay56080682018-01-06 14:01:52 -0800515 pub fn value_mut(&mut self) -> &mut T {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700516 match *self {
David Tolnay56080682018-01-06 14:01:52 -0800517 Pair::Punctuated(ref mut t, _) | Pair::End(ref mut t) => t,
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700518 }
519 }
520
David Tolnayf3198012018-01-06 20:00:42 -0800521 /// Borrows the punctuation from this punctuated pair, unless this pair is
522 /// the final one and there is no trailing punctuation.
David Tolnayf2cfd722017-12-31 18:02:51 -0500523 pub fn punct(&self) -> Option<&P> {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700524 match *self {
David Tolnay56080682018-01-06 14:01:52 -0800525 Pair::Punctuated(_, ref d) => Some(d),
526 Pair::End(_) => None,
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700527 }
528 }
Nika Layzellcda7ebd2017-10-24 23:10:44 -0400529
David Tolnayf3198012018-01-06 20:00:42 -0800530 /// Creates a punctuated pair out of a syntax tree node and an optional
531 /// following punctuation.
David Tolnayf2cfd722017-12-31 18:02:51 -0500532 pub fn new(t: T, d: Option<P>) -> Self {
David Tolnay660fd1f2017-12-31 01:52:57 -0500533 match d {
David Tolnay56080682018-01-06 14:01:52 -0800534 Some(d) => Pair::Punctuated(t, d),
535 None => Pair::End(t),
David Tolnay660fd1f2017-12-31 01:52:57 -0500536 }
537 }
538
David Tolnayf3198012018-01-06 20:00:42 -0800539 /// Produces this punctuated pair as a tuple of syntax tree node and
540 /// optional following punctuation.
David Tolnayf2cfd722017-12-31 18:02:51 -0500541 pub fn into_tuple(self) -> (T, Option<P>) {
Nika Layzellcda7ebd2017-10-24 23:10:44 -0400542 match self {
David Tolnay56080682018-01-06 14:01:52 -0800543 Pair::Punctuated(t, d) => (t, Some(d)),
544 Pair::End(t) => (t, None),
Nika Layzellcda7ebd2017-10-24 23:10:44 -0400545 }
546 }
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700547}
548
David Tolnaybb987132018-01-08 13:51:19 -0800549impl<T, P> Index<usize> for Punctuated<T, P> {
550 type Output = T;
551
552 fn index(&self, index: usize) -> &Self::Output {
Mateusz Naściszewski14111202018-04-11 21:17:41 +0200553 if index == self.len() - 1 {
554 match self.last {
555 Some(ref t) => t,
556 None => &self.inner[index].0
557 }
558 } else {
559 &self.inner[index].0
560 }
David Tolnaybb987132018-01-08 13:51:19 -0800561 }
562}
563
564impl<T, P> IndexMut<usize> for Punctuated<T, P> {
565 fn index_mut(&mut self, index: usize) -> &mut Self::Output {
Mateusz Naściszewski14111202018-04-11 21:17:41 +0200566 if index == self.len() - 1 {
567 match self.last {
568 Some(ref mut t) => t,
569 None => &mut self.inner[index].0
570 }
571 } else {
572 &mut self.inner[index].0
573 }
David Tolnaybb987132018-01-08 13:51:19 -0800574 }
575}
576
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700577#[cfg(feature = "parsing")]
David Tolnayf3198012018-01-06 20:00:42 -0800578impl<T, P> Punctuated<T, P>
579where
580 T: Synom,
581 P: Synom,
582{
583 /// Parse **zero or more** syntax tree nodes with punctuation in between and
584 /// **no trailing** punctuation.
585 pub fn parse_separated(input: Cursor) -> PResult<Self> {
586 Self::parse_separated_with(input, T::parse)
587 }
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700588
David Tolnayf3198012018-01-06 20:00:42 -0800589 /// Parse **one or more** syntax tree nodes with punctuation in bewteen and
590 /// **no trailing** punctuation.
591 /// allowing trailing punctuation.
592 pub fn parse_separated_nonempty(input: Cursor) -> PResult<Self> {
593 Self::parse_separated_nonempty_with(input, T::parse)
594 }
Alex Crichton954046c2017-05-30 21:49:42 -0700595
David Tolnayf3198012018-01-06 20:00:42 -0800596 /// Parse **zero or more** syntax tree nodes with punctuation in between and
597 /// **optional trailing** punctuation.
598 pub fn parse_terminated(input: Cursor) -> PResult<Self> {
599 Self::parse_terminated_with(input, T::parse)
600 }
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700601
David Tolnayf3198012018-01-06 20:00:42 -0800602 /// Parse **one or more** syntax tree nodes with punctuation in between and
603 /// **optional trailing** punctuation.
604 pub fn parse_terminated_nonempty(input: Cursor) -> PResult<Self> {
605 Self::parse_terminated_nonempty_with(input, T::parse)
606 }
607}
Nika Layzellb49a9e52017-12-05 13:31:52 -0500608
David Tolnayf3198012018-01-06 20:00:42 -0800609#[cfg(feature = "parsing")]
610impl<T, P> Punctuated<T, P>
611where
612 P: Synom,
613{
614 /// Parse **zero or more** syntax tree nodes using the given parser with
615 /// punctuation in between and **no trailing** punctuation.
616 pub fn parse_separated_with(
617 input: Cursor,
618 parse: fn(Cursor) -> PResult<T>,
619 ) -> PResult<Self> {
620 Self::parse(input, parse, false)
621 }
622
623 /// Parse **one or more** syntax tree nodes using the given parser with
624 /// punctuation in between and **no trailing** punctuation.
625 pub fn parse_separated_nonempty_with(
626 input: Cursor,
627 parse: fn(Cursor) -> PResult<T>,
628 ) -> PResult<Self> {
629 match Self::parse(input, parse, false) {
630 Ok((ref b, _)) if b.is_empty() => parse_error(),
631 other => other,
Nika Layzellb49a9e52017-12-05 13:31:52 -0500632 }
Alex Crichton954046c2017-05-30 21:49:42 -0700633 }
634
David Tolnayf3198012018-01-06 20:00:42 -0800635 /// Parse **zero or more** syntax tree nodes using the given parser with
636 /// punctuation in between and **optional trailing** punctuation.
637 pub fn parse_terminated_with(
638 input: Cursor,
639 parse: fn(Cursor) -> PResult<T>,
640 ) -> PResult<Self> {
641 Self::parse(input, parse, true)
642 }
643
644 /// Parse **one or more** syntax tree nodes using the given parser with
645 /// punctuation in between and **optional trailing** punctuation.
646 pub fn parse_terminated_nonempty_with(
647 input: Cursor,
648 parse: fn(Cursor) -> PResult<T>,
649 ) -> PResult<Self> {
650 match Self::parse(input, parse, true) {
651 Ok((ref b, _)) if b.is_empty() => parse_error(),
652 other => other,
David Tolnaydc03aec2017-12-30 01:54:18 -0500653 }
David Tolnayf3198012018-01-06 20:00:42 -0800654 }
David Tolnaydc03aec2017-12-30 01:54:18 -0500655
David Tolnayf3198012018-01-06 20:00:42 -0800656 fn parse(
657 mut input: Cursor,
658 parse: fn(Cursor) -> PResult<T>,
659 terminated: bool,
660 ) -> PResult<Self> {
661 let mut res = Punctuated::new();
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700662
David Tolnayf3198012018-01-06 20:00:42 -0800663 // get the first element
664 match parse(input) {
665 Err(_) => Ok((res, input)),
666 Ok((o, i)) => {
667 if i == input {
668 return parse_error();
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700669 }
David Tolnayf3198012018-01-06 20:00:42 -0800670 input = i;
671 res.push_value(o);
672
673 // get the separator first
674 while let Ok((s, i2)) = P::parse(input) {
675 if i2 == input {
676 break;
677 }
678
679 // get the element next
680 if let Ok((o3, i3)) = parse(i2) {
681 if i3 == i2 {
682 break;
683 }
684 res.push_punct(s);
685 res.push_value(o3);
686 input = i3;
687 } else {
688 break;
689 }
690 }
691 if terminated {
692 if let Ok((sep, after)) = P::parse(input) {
693 res.push_punct(sep);
694 input = after;
695 }
696 }
697 Ok((res, input))
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700698 }
699 }
700 }
701}
702
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700703#[cfg(feature = "printing")]
704mod printing {
705 use super::*;
David Tolnay51382052017-12-27 13:46:21 -0500706 use quote::{ToTokens, Tokens};
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700707
David Tolnayf2cfd722017-12-31 18:02:51 -0500708 impl<T, P> ToTokens for Punctuated<T, P>
David Tolnay51382052017-12-27 13:46:21 -0500709 where
710 T: ToTokens,
David Tolnayf2cfd722017-12-31 18:02:51 -0500711 P: ToTokens,
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700712 {
713 fn to_tokens(&self, tokens: &mut Tokens) {
David Tolnay56080682018-01-06 14:01:52 -0800714 tokens.append_all(self.pairs())
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700715 }
716 }
717
David Tolnay56080682018-01-06 14:01:52 -0800718 impl<T, P> ToTokens for Pair<T, P>
David Tolnay51382052017-12-27 13:46:21 -0500719 where
720 T: ToTokens,
David Tolnayf2cfd722017-12-31 18:02:51 -0500721 P: ToTokens,
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700722 {
723 fn to_tokens(&self, tokens: &mut Tokens) {
724 match *self {
David Tolnay56080682018-01-06 14:01:52 -0800725 Pair::Punctuated(ref a, ref b) => {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700726 a.to_tokens(tokens);
727 b.to_tokens(tokens);
728 }
David Tolnay56080682018-01-06 14:01:52 -0800729 Pair::End(ref a) => a.to_tokens(tokens),
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700730 }
731 }
732 }
733}