blob: 25bcfc3dd69506f076f9753935813f823e2c132f [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 Tolnay94d2b792018-04-29 12:26:10 -070030#[cfg(feature = "extra-traits")]
31use std::fmt::{self, Debug};
David Tolnay6c0a6092018-03-31 22:47:39 +020032#[cfg(any(feature = "full", feature = "derive"))]
33use std::iter;
34use std::iter::FromIterator;
David Tolnaybb987132018-01-08 13:51:19 -080035use std::ops::{Index, IndexMut};
Mateusz Naściszewski14111202018-04-11 21:17:41 +020036use std::option;
Alex Crichtonccbb45d2017-05-23 10:58:24 -070037use std::slice;
38use std::vec;
39
David Tolnayf3198012018-01-06 20:00:42 -080040#[cfg(feature = "parsing")]
David Tolnayf3198012018-01-06 20:00:42 -080041use buffer::Cursor;
42#[cfg(feature = "parsing")]
43use parse_error;
David Tolnay94d2b792018-04-29 12:26:10 -070044#[cfg(feature = "parsing")]
45use synom::{PResult, Synom};
David Tolnayf3198012018-01-06 20:00:42 -080046
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> {
David Tolnay94d2b792018-04-29 12:26:10 -070063 Punctuated {
64 inner: Vec::new(),
65 last: None,
66 }
Alex Crichtonccbb45d2017-05-23 10:58:24 -070067 }
68
David Tolnayf3198012018-01-06 20:00:42 -080069 /// Determines whether this punctuated sequence is empty, meaning it
70 /// contains no syntax tree nodes or punctuation.
Alex Crichtonccbb45d2017-05-23 10:58:24 -070071 pub fn is_empty(&self) -> bool {
Mateusz Naściszewski14111202018-04-11 21:17:41 +020072 self.inner.len() == 0 && self.last.is_none()
Alex Crichtonccbb45d2017-05-23 10:58:24 -070073 }
74
David Tolnayf3198012018-01-06 20:00:42 -080075 /// Returns the number of syntax tree nodes in this punctuated sequence.
76 ///
77 /// This is the number of nodes of type `T`, not counting the punctuation of
78 /// type `P`.
Alex Crichtonccbb45d2017-05-23 10:58:24 -070079 pub fn len(&self) -> usize {
Mateusz Naściszewski14111202018-04-11 21:17:41 +020080 self.inner.len() + if self.last.is_some() { 1 } else { 0 }
Alex Crichtonccbb45d2017-05-23 10:58:24 -070081 }
82
David Tolnayf3198012018-01-06 20:00:42 -080083 /// Borrows the first punctuated pair in this sequence.
David Tolnay56080682018-01-06 14:01:52 -080084 pub fn first(&self) -> Option<Pair<&T, &P>> {
Mateusz Naściszewski14111202018-04-11 21:17:41 +020085 self.pairs().next()
Alex Crichton0aa50e02017-07-07 20:59:03 -070086 }
87
David Tolnayf3198012018-01-06 20:00:42 -080088 /// Borrows the last punctuated pair in this sequence.
David Tolnay56080682018-01-06 14:01:52 -080089 pub fn last(&self) -> Option<Pair<&T, &P>> {
Mateusz Naściszewski14111202018-04-11 21:17:41 +020090 if self.last.is_some() {
David Tolnay94d2b792018-04-29 12:26:10 -070091 self.last.as_ref().map(|t| Pair::End(t.as_ref()))
Mateusz Naściszewski14111202018-04-11 21:17:41 +020092 } else {
David Tolnay94d2b792018-04-29 12:26:10 -070093 self.inner
94 .last()
Mateusz Naściszewski14111202018-04-11 21:17:41 +020095 .map(|&(ref t, ref d)| Pair::Punctuated(t, d))
96 }
Alex Crichton0aa50e02017-07-07 20:59:03 -070097 }
98
David Tolnayf3198012018-01-06 20:00:42 -080099 /// Mutably borrows the last punctuated pair in this sequence.
David Tolnay56080682018-01-06 14:01:52 -0800100 pub fn last_mut(&mut self) -> Option<Pair<&mut T, &mut P>> {
Mateusz Naściszewski14111202018-04-11 21:17:41 +0200101 if self.last.is_some() {
David Tolnay94d2b792018-04-29 12:26:10 -0700102 self.last.as_mut().map(|t| Pair::End(t.as_mut()))
Mateusz Naściszewski14111202018-04-11 21:17:41 +0200103 } else {
David Tolnay94d2b792018-04-29 12:26:10 -0700104 self.inner
105 .last_mut()
Mateusz Naściszewski14111202018-04-11 21:17:41 +0200106 .map(|&mut (ref mut t, ref mut d)| Pair::Punctuated(t, d))
107 }
Alex Crichton0aa50e02017-07-07 20:59:03 -0700108 }
109
David Tolnayf3198012018-01-06 20:00:42 -0800110 /// Returns an iterator over borrowed syntax tree nodes of type `&T`.
David Tolnay8095c302018-03-31 19:34:17 +0200111 pub fn iter(&self) -> Iter<T> {
David Tolnay51382052017-12-27 13:46:21 -0500112 Iter {
David Tolnay8095c302018-03-31 19:34:17 +0200113 inner: Box::new(PrivateIter {
114 inner: self.inner.iter(),
Mateusz Naściszewski14111202018-04-11 21:17:41 +0200115 last: self.last.as_ref().map(|t| t.as_ref()).into_iter(),
David Tolnay8095c302018-03-31 19:34:17 +0200116 }),
David Tolnay51382052017-12-27 13:46:21 -0500117 }
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700118 }
119
David Tolnayf3198012018-01-06 20:00:42 -0800120 /// Returns an iterator over mutably borrowed syntax tree nodes of type
121 /// `&mut T`.
David Tolnay8095c302018-03-31 19:34:17 +0200122 pub fn iter_mut(&mut self) -> IterMut<T> {
David Tolnaya0834b42018-01-01 21:30:02 -0800123 IterMut {
David Tolnay8095c302018-03-31 19:34:17 +0200124 inner: Box::new(PrivateIterMut {
125 inner: self.inner.iter_mut(),
Mateusz Naściszewski14111202018-04-11 21:17:41 +0200126 last: self.last.as_mut().map(|t| t.as_mut()).into_iter(),
David Tolnay8095c302018-03-31 19:34:17 +0200127 }),
David Tolnaya0834b42018-01-01 21:30:02 -0800128 }
129 }
130
David Tolnayf3198012018-01-06 20:00:42 -0800131 /// Returns an iterator over the contents of this sequence as borrowed
132 /// punctuated pairs.
David Tolnay56080682018-01-06 14:01:52 -0800133 pub fn pairs(&self) -> Pairs<T, P> {
134 Pairs {
David Tolnay6eff4da2018-01-01 20:27:45 -0800135 inner: self.inner.iter(),
Mateusz Naściszewski14111202018-04-11 21:17:41 +0200136 last: self.last.as_ref().map(|t| t.as_ref()).into_iter(),
David Tolnay6eff4da2018-01-01 20:27:45 -0800137 }
138 }
139
David Tolnayf3198012018-01-06 20:00:42 -0800140 /// Returns an iterator over the contents of this sequence as mutably
141 /// borrowed punctuated pairs.
David Tolnay56080682018-01-06 14:01:52 -0800142 pub fn pairs_mut(&mut self) -> PairsMut<T, P> {
143 PairsMut {
David Tolnay51382052017-12-27 13:46:21 -0500144 inner: self.inner.iter_mut(),
Mateusz Naściszewski14111202018-04-11 21:17:41 +0200145 last: self.last.as_mut().map(|t| t.as_mut()).into_iter(),
David Tolnay51382052017-12-27 13:46:21 -0500146 }
Alex Crichton164c5332017-07-06 13:18:34 -0700147 }
148
David Tolnayf3198012018-01-06 20:00:42 -0800149 /// Returns an iterator over the contents of this sequence as owned
150 /// punctuated pairs.
David Tolnay56080682018-01-06 14:01:52 -0800151 pub fn into_pairs(self) -> IntoPairs<T, P> {
152 IntoPairs {
David Tolnay6eff4da2018-01-01 20:27:45 -0800153 inner: self.inner.into_iter(),
Mateusz Naściszewski14111202018-04-11 21:17:41 +0200154 last: self.last.map(|t| *t).into_iter(),
David Tolnay6eff4da2018-01-01 20:27:45 -0800155 }
156 }
157
David Tolnayf3198012018-01-06 20:00:42 -0800158 /// Appends a syntax tree node onto the end of this punctuated sequence. The
159 /// sequence must previously have a trailing punctuation.
160 ///
161 /// Use [`push`] instead if the punctuated sequence may or may not already
162 /// have trailing punctuation.
163 ///
164 /// [`push`]: #method.push
165 ///
166 /// # Panics
167 ///
168 /// Panics if the sequence does not already have a trailing punctuation when
169 /// this method is called.
David Tolnay56080682018-01-06 14:01:52 -0800170 pub fn push_value(&mut self, value: T) {
David Tolnaydc03aec2017-12-30 01:54:18 -0500171 assert!(self.empty_or_trailing());
Mateusz Naściszewski14111202018-04-11 21:17:41 +0200172 self.last = Some(Box::new(value));
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700173 }
174
David Tolnayf3198012018-01-06 20:00:42 -0800175 /// Appends a trailing punctuation onto the end of this punctuated sequence.
176 /// The sequence must be non-empty and must not already have trailing
177 /// punctuation.
178 ///
179 /// # Panics
180 ///
181 /// Panics if the sequence is empty or already has a trailing punctuation.
David Tolnaya0834b42018-01-01 21:30:02 -0800182 pub fn push_punct(&mut self, punctuation: P) {
Mateusz Naściszewski14111202018-04-11 21:17:41 +0200183 assert!(self.last.is_some());
David Tolnay03163082018-04-11 12:10:18 -0700184 let last = self.last.take().unwrap();
185 self.inner.push((*last, punctuation));
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700186 }
187
David Tolnayf3198012018-01-06 20:00:42 -0800188 /// Removes the last punctuated pair from this sequence, or `None` if the
189 /// sequence is empty.
David Tolnay56080682018-01-06 14:01:52 -0800190 pub fn pop(&mut self) -> Option<Pair<T, P>> {
Mateusz Naściszewski14111202018-04-11 21:17:41 +0200191 if self.last.is_some() {
David Tolnay03163082018-04-11 12:10:18 -0700192 self.last.take().map(|t| Pair::End(*t))
Mateusz Naściszewski14111202018-04-11 21:17:41 +0200193 } else {
194 self.inner.pop().map(|(t, d)| Pair::Punctuated(t, d))
195 }
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700196 }
197
David Tolnayf3198012018-01-06 20:00:42 -0800198 /// Determines whether this punctuated sequence ends with a trailing
199 /// punctuation.
David Tolnaya0834b42018-01-01 21:30:02 -0800200 pub fn trailing_punct(&self) -> bool {
Mateusz Naściszewski14111202018-04-11 21:17:41 +0200201 self.last.is_none() && !self.is_empty()
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700202 }
Michael Layzell3936ceb2017-07-08 00:28:36 -0400203
David Tolnayf2cfd722017-12-31 18:02:51 -0500204 /// Returns true if either this `Punctuated` is empty, or it has a trailing
205 /// punctuation.
David Tolnaydc03aec2017-12-30 01:54:18 -0500206 ///
David Tolnaya0834b42018-01-01 21:30:02 -0800207 /// Equivalent to `punctuated.is_empty() || punctuated.trailing_punct()`.
Michael Layzell3936ceb2017-07-08 00:28:36 -0400208 pub fn empty_or_trailing(&self) -> bool {
Mateusz Naściszewski14111202018-04-11 21:17:41 +0200209 self.last.is_none()
Michael Layzell3936ceb2017-07-08 00:28:36 -0400210 }
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700211}
212
David Tolnaya0834b42018-01-01 21:30:02 -0800213impl<T, P> Punctuated<T, P>
214where
215 P: Default,
216{
David Tolnayf3198012018-01-06 20:00:42 -0800217 /// Appends a syntax tree node onto the end of this punctuated sequence.
218 ///
219 /// If there is not a trailing punctuation in this sequence when this method
220 /// is called, the default value of punctuation type `P` is inserted before
221 /// the given value of type `T`.
David Tolnay56080682018-01-06 14:01:52 -0800222 pub fn push(&mut self, value: T) {
David Tolnaya0834b42018-01-01 21:30:02 -0800223 if !self.empty_or_trailing() {
224 self.push_punct(Default::default());
225 }
David Tolnay56080682018-01-06 14:01:52 -0800226 self.push_value(value);
David Tolnaya0834b42018-01-01 21:30:02 -0800227 }
David Tolnayb77d1802018-01-11 16:18:35 -0800228
229 /// Inserts an element at position `index`.
230 ///
231 /// # Panics
232 ///
233 /// Panics if `index` is greater than the number of elements previously in
234 /// this punctuated sequence.
235 pub fn insert(&mut self, index: usize, value: T) {
236 assert!(index <= self.len());
237
238 if index == self.len() {
239 self.push(value);
240 } else {
Mateusz Naściszewski14111202018-04-11 21:17:41 +0200241 self.inner.insert(index, (value, Default::default()));
David Tolnayb77d1802018-01-11 16:18:35 -0800242 }
243 }
David Tolnaya0834b42018-01-01 21:30:02 -0800244}
245
Nika Layzelld73a3652017-10-24 08:57:05 -0400246#[cfg(feature = "extra-traits")]
David Tolnayf2cfd722017-12-31 18:02:51 -0500247impl<T: Debug, P: Debug> Debug for Punctuated<T, P> {
Nika Layzelld73a3652017-10-24 08:57:05 -0400248 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Mateusz Naściszewski14111202018-04-11 21:17:41 +0200249 let mut list = f.debug_list();
250 list.entries(&self.inner);
251 for t in self.last.iter() {
252 list.entry(&*t);
253 }
254 list.finish()
Nika Layzelld73a3652017-10-24 08:57:05 -0400255 }
256}
257
David Tolnay9ef24bc2018-01-09 10:43:55 -0800258impl<T, P> FromIterator<T> for Punctuated<T, P>
259where
260 P: Default,
261{
262 fn from_iter<I: IntoIterator<Item = T>>(i: I) -> Self {
263 let mut ret = Punctuated::new();
264 ret.extend(i);
265 ret
266 }
267}
268
269impl<T, P> Extend<T> for Punctuated<T, P>
270where
271 P: Default,
272{
273 fn extend<I: IntoIterator<Item = T>>(&mut self, i: I) {
274 for value in i {
275 self.push(value);
276 }
277 }
278}
279
David Tolnay56080682018-01-06 14:01:52 -0800280impl<T, P> FromIterator<Pair<T, P>> for Punctuated<T, P> {
281 fn from_iter<I: IntoIterator<Item = Pair<T, P>>>(i: I) -> Self {
David Tolnayf2cfd722017-12-31 18:02:51 -0500282 let mut ret = Punctuated::new();
Alex Crichton24f12822017-07-14 07:15:32 -0700283 ret.extend(i);
Alex Crichton954046c2017-05-30 21:49:42 -0700284 ret
285 }
286}
287
David Tolnay56080682018-01-06 14:01:52 -0800288impl<T, P> Extend<Pair<T, P>> for Punctuated<T, P> {
289 fn extend<I: IntoIterator<Item = Pair<T, P>>>(&mut self, i: I) {
Mateusz Naściszewski14111202018-04-11 21:17:41 +0200290 assert!(self.empty_or_trailing());
291 let mut nomore = false;
David Tolnay56080682018-01-06 14:01:52 -0800292 for pair in i {
Mateusz Naściszewski14111202018-04-11 21:17:41 +0200293 if nomore {
294 panic!("Punctuated extended with items after a Pair::End");
295 }
David Tolnay56080682018-01-06 14:01:52 -0800296 match pair {
Mateusz Naściszewski14111202018-04-11 21:17:41 +0200297 Pair::Punctuated(a, b) => self.inner.push((a, b)),
298 Pair::End(a) => {
299 self.last = Some(Box::new(a));
300 nomore = true;
301 }
Alex Crichton24f12822017-07-14 07:15:32 -0700302 }
303 }
304 }
305}
306
David Tolnayf2cfd722017-12-31 18:02:51 -0500307impl<T, P> IntoIterator for Punctuated<T, P> {
David Tolnay6eff4da2018-01-01 20:27:45 -0800308 type Item = T;
David Tolnayf2cfd722017-12-31 18:02:51 -0500309 type IntoIter = IntoIter<T, P>;
Alex Crichton954046c2017-05-30 21:49:42 -0700310
David Tolnaybb4ca9f2017-12-26 12:28:58 -0500311 fn into_iter(self) -> Self::IntoIter {
David Tolnay51382052017-12-27 13:46:21 -0500312 IntoIter {
313 inner: self.inner.into_iter(),
Mateusz Naściszewski14111202018-04-11 21:17:41 +0200314 last: self.last.map(|t| *t).into_iter(),
David Tolnay51382052017-12-27 13:46:21 -0500315 }
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700316 }
317}
318
David Tolnay6eff4da2018-01-01 20:27:45 -0800319impl<'a, T, P> IntoIterator for &'a Punctuated<T, P> {
320 type Item = &'a T;
David Tolnay8095c302018-03-31 19:34:17 +0200321 type IntoIter = Iter<'a, T>;
David Tolnay6eff4da2018-01-01 20:27:45 -0800322
323 fn into_iter(self) -> Self::IntoIter {
324 Punctuated::iter(self)
325 }
326}
327
David Tolnaya0834b42018-01-01 21:30:02 -0800328impl<'a, T, P> IntoIterator for &'a mut Punctuated<T, P> {
329 type Item = &'a mut T;
David Tolnay8095c302018-03-31 19:34:17 +0200330 type IntoIter = IterMut<'a, T>;
David Tolnaya0834b42018-01-01 21:30:02 -0800331
332 fn into_iter(self) -> Self::IntoIter {
333 Punctuated::iter_mut(self)
334 }
335}
336
David Tolnayf2cfd722017-12-31 18:02:51 -0500337impl<T, P> Default for Punctuated<T, P> {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700338 fn default() -> Self {
David Tolnayf2cfd722017-12-31 18:02:51 -0500339 Punctuated::new()
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700340 }
341}
342
David Tolnayf3198012018-01-06 20:00:42 -0800343/// An iterator over borrowed pairs of type `Pair<&T, &P>`.
344///
345/// Refer to the [module documentation] for details about punctuated sequences.
346///
347/// [module documentation]: index.html
David Tolnay56080682018-01-06 14:01:52 -0800348pub struct Pairs<'a, T: 'a, P: 'a> {
Mateusz Naściszewski14111202018-04-11 21:17:41 +0200349 inner: slice::Iter<'a, (T, P)>,
350 last: option::IntoIter<&'a T>,
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700351}
352
David Tolnay56080682018-01-06 14:01:52 -0800353impl<'a, T, P> Iterator for Pairs<'a, T, P> {
354 type Item = Pair<&'a T, &'a P>;
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700355
David Tolnay6eff4da2018-01-01 20:27:45 -0800356 fn next(&mut self) -> Option<Self::Item> {
David Tolnay94d2b792018-04-29 12:26:10 -0700357 self.inner
358 .next()
359 .map(|&(ref t, ref p)| Pair::Punctuated(t, p))
David Tolnay6e4a9c22018-04-11 12:20:08 -0700360 .or_else(|| self.last.next().map(Pair::End))
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700361 }
362}
363
David Tolnay9700be02018-04-30 00:51:15 -0700364impl<'a, T, P> ExactSizeIterator for Pairs<'a, T, P> {
365 fn len(&self) -> usize {
366 self.inner.len() + self.last.len()
367 }
368}
369
David Tolnayf3198012018-01-06 20:00:42 -0800370/// An iterator over mutably borrowed pairs of type `Pair<&mut T, &mut P>`.
371///
372/// Refer to the [module documentation] for details about punctuated sequences.
373///
374/// [module documentation]: index.html
David Tolnay56080682018-01-06 14:01:52 -0800375pub struct PairsMut<'a, T: 'a, P: 'a> {
Mateusz Naściszewski14111202018-04-11 21:17:41 +0200376 inner: slice::IterMut<'a, (T, P)>,
377 last: option::IntoIter<&'a mut T>,
Alex Crichton164c5332017-07-06 13:18:34 -0700378}
379
David Tolnay56080682018-01-06 14:01:52 -0800380impl<'a, T, P> Iterator for PairsMut<'a, T, P> {
381 type Item = Pair<&'a mut T, &'a mut P>;
Alex Crichton164c5332017-07-06 13:18:34 -0700382
David Tolnay6eff4da2018-01-01 20:27:45 -0800383 fn next(&mut self) -> Option<Self::Item> {
David Tolnay94d2b792018-04-29 12:26:10 -0700384 self.inner
385 .next()
386 .map(|&mut (ref mut t, ref mut p)| Pair::Punctuated(t, p))
David Tolnay6e4a9c22018-04-11 12:20:08 -0700387 .or_else(|| self.last.next().map(Pair::End))
Alex Crichton164c5332017-07-06 13:18:34 -0700388 }
389}
390
David Tolnay9700be02018-04-30 00:51:15 -0700391impl<'a, T, P> ExactSizeIterator for PairsMut<'a, T, P> {
392 fn len(&self) -> usize {
393 self.inner.len() + self.last.len()
394 }
395}
396
David Tolnayf3198012018-01-06 20:00:42 -0800397/// An iterator over owned pairs of type `Pair<T, P>`.
398///
399/// Refer to the [module documentation] for details about punctuated sequences.
400///
401/// [module documentation]: index.html
David Tolnay56080682018-01-06 14:01:52 -0800402pub struct IntoPairs<T, P> {
Mateusz Naściszewski14111202018-04-11 21:17:41 +0200403 inner: vec::IntoIter<(T, P)>,
404 last: option::IntoIter<T>,
David Tolnay6eff4da2018-01-01 20:27:45 -0800405}
406
David Tolnay56080682018-01-06 14:01:52 -0800407impl<T, P> Iterator for IntoPairs<T, P> {
408 type Item = Pair<T, P>;
David Tolnay6eff4da2018-01-01 20:27:45 -0800409
410 fn next(&mut self) -> Option<Self::Item> {
David Tolnay94d2b792018-04-29 12:26:10 -0700411 self.inner
412 .next()
413 .map(|(t, p)| Pair::Punctuated(t, p))
David Tolnay6e4a9c22018-04-11 12:20:08 -0700414 .or_else(|| self.last.next().map(Pair::End))
David Tolnay6eff4da2018-01-01 20:27:45 -0800415 }
416}
417
David Tolnay9700be02018-04-30 00:51:15 -0700418impl<T, P> ExactSizeIterator for IntoPairs<T, P> {
419 fn len(&self) -> usize {
420 self.inner.len() + self.last.len()
421 }
422}
423
David Tolnayf3198012018-01-06 20:00:42 -0800424/// An iterator over owned values of type `T`.
425///
426/// Refer to the [module documentation] for details about punctuated sequences.
427///
428/// [module documentation]: index.html
David Tolnayf2cfd722017-12-31 18:02:51 -0500429pub struct IntoIter<T, P> {
Mateusz Naściszewski14111202018-04-11 21:17:41 +0200430 inner: vec::IntoIter<(T, P)>,
431 last: option::IntoIter<T>,
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700432}
433
David Tolnayf2cfd722017-12-31 18:02:51 -0500434impl<T, P> Iterator for IntoIter<T, P> {
David Tolnay6eff4da2018-01-01 20:27:45 -0800435 type Item = T;
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700436
David Tolnay6eff4da2018-01-01 20:27:45 -0800437 fn next(&mut self) -> Option<Self::Item> {
David Tolnay94d2b792018-04-29 12:26:10 -0700438 self.inner
439 .next()
440 .map(|pair| pair.0)
441 .or_else(|| self.last.next())
David Tolnay6eff4da2018-01-01 20:27:45 -0800442 }
443}
444
David Tolnay9700be02018-04-30 00:51:15 -0700445impl<T, P> ExactSizeIterator for IntoIter<T, P> {
446 fn len(&self) -> usize {
447 self.inner.len() + self.last.len()
448 }
449}
450
David Tolnayf3198012018-01-06 20:00:42 -0800451/// An iterator over borrowed values of type `&T`.
452///
453/// Refer to the [module documentation] for details about punctuated sequences.
454///
455/// [module documentation]: index.html
David Tolnay8095c302018-03-31 19:34:17 +0200456pub struct Iter<'a, T: 'a> {
David Tolnay9700be02018-04-30 00:51:15 -0700457 inner: Box<ExactSizeIterator<Item = &'a T> + 'a>,
David Tolnay8095c302018-03-31 19:34:17 +0200458}
459
460struct PrivateIter<'a, T: 'a, P: 'a> {
Mateusz Naściszewski14111202018-04-11 21:17:41 +0200461 inner: slice::Iter<'a, (T, P)>,
462 last: option::IntoIter<&'a T>,
David Tolnay6eff4da2018-01-01 20:27:45 -0800463}
464
David Tolnay96a09d92018-01-16 22:24:03 -0800465#[cfg(any(feature = "full", feature = "derive"))]
David Tolnay8095c302018-03-31 19:34:17 +0200466impl<'a, T> Iter<'a, T> {
David Tolnay96a09d92018-01-16 22:24:03 -0800467 // Not public API.
468 #[doc(hidden)]
469 pub fn private_empty() -> Self {
470 Iter {
David Tolnay8095c302018-03-31 19:34:17 +0200471 inner: Box::new(iter::empty()),
David Tolnay96a09d92018-01-16 22:24:03 -0800472 }
473 }
474}
475
David Tolnay8095c302018-03-31 19:34:17 +0200476impl<'a, T> Iterator for Iter<'a, T> {
477 type Item = &'a T;
478
479 fn next(&mut self) -> Option<Self::Item> {
480 self.inner.next()
481 }
482}
483
David Tolnay9700be02018-04-30 00:51:15 -0700484impl<'a, T> ExactSizeIterator for Iter<'a, T> {
485 fn len(&self) -> usize {
486 self.inner.len()
487 }
488}
489
David Tolnay8095c302018-03-31 19:34:17 +0200490impl<'a, T, P> Iterator for PrivateIter<'a, T, P> {
David Tolnay6eff4da2018-01-01 20:27:45 -0800491 type Item = &'a T;
492
493 fn next(&mut self) -> Option<Self::Item> {
David Tolnay94d2b792018-04-29 12:26:10 -0700494 self.inner
495 .next()
496 .map(|pair| &pair.0)
497 .or_else(|| self.last.next())
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700498 }
499}
500
David Tolnay9700be02018-04-30 00:51:15 -0700501impl<'a, T, P> ExactSizeIterator for PrivateIter<'a, T, P> {
502 fn len(&self) -> usize {
503 self.inner.len() + self.last.len()
504 }
505}
506
David Tolnayf3198012018-01-06 20:00:42 -0800507/// An iterator over mutably borrowed values of type `&mut T`.
508///
509/// Refer to the [module documentation] for details about punctuated sequences.
510///
511/// [module documentation]: index.html
David Tolnay8095c302018-03-31 19:34:17 +0200512pub struct IterMut<'a, T: 'a> {
David Tolnay9700be02018-04-30 00:51:15 -0700513 inner: Box<ExactSizeIterator<Item = &'a mut T> + 'a>,
David Tolnay8095c302018-03-31 19:34:17 +0200514}
515
516struct PrivateIterMut<'a, T: 'a, P: 'a> {
Mateusz Naściszewski14111202018-04-11 21:17:41 +0200517 inner: slice::IterMut<'a, (T, P)>,
518 last: option::IntoIter<&'a mut T>,
David Tolnaya0834b42018-01-01 21:30:02 -0800519}
520
David Tolnay8095c302018-03-31 19:34:17 +0200521impl<'a, T> Iterator for IterMut<'a, T> {
522 type Item = &'a mut T;
523
524 fn next(&mut self) -> Option<Self::Item> {
525 self.inner.next()
526 }
527}
528
David Tolnay9700be02018-04-30 00:51:15 -0700529impl<'a, T> ExactSizeIterator for IterMut<'a, T> {
530 fn len(&self) -> usize {
531 self.inner.len()
532 }
533}
534
David Tolnay8095c302018-03-31 19:34:17 +0200535impl<'a, T, P> Iterator for PrivateIterMut<'a, T, P> {
David Tolnaya0834b42018-01-01 21:30:02 -0800536 type Item = &'a mut T;
537
538 fn next(&mut self) -> Option<Self::Item> {
David Tolnay94d2b792018-04-29 12:26:10 -0700539 self.inner
540 .next()
541 .map(|pair| &mut pair.0)
542 .or_else(|| self.last.next())
David Tolnaya0834b42018-01-01 21:30:02 -0800543 }
544}
545
David Tolnay9700be02018-04-30 00:51:15 -0700546impl<'a, T, P> ExactSizeIterator for PrivateIterMut<'a, T, P> {
547 fn len(&self) -> usize {
548 self.inner.len() + self.last.len()
549 }
550}
551
David Tolnayf3198012018-01-06 20:00:42 -0800552/// A single syntax tree node of type `T` followed by its trailing punctuation
553/// of type `P` if any.
554///
555/// Refer to the [module documentation] for details about punctuated sequences.
556///
557/// [module documentation]: index.html
David Tolnay56080682018-01-06 14:01:52 -0800558pub enum Pair<T, P> {
David Tolnayf2cfd722017-12-31 18:02:51 -0500559 Punctuated(T, P),
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700560 End(T),
561}
562
David Tolnay56080682018-01-06 14:01:52 -0800563impl<T, P> Pair<T, P> {
David Tolnayf3198012018-01-06 20:00:42 -0800564 /// Extracts the syntax tree node from this punctuated pair, discarding the
565 /// following punctuation.
David Tolnay56080682018-01-06 14:01:52 -0800566 pub fn into_value(self) -> T {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700567 match self {
David Tolnay56080682018-01-06 14:01:52 -0800568 Pair::Punctuated(t, _) | Pair::End(t) => t,
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700569 }
570 }
571
David Tolnayf3198012018-01-06 20:00:42 -0800572 /// Borrows the syntax tree node from this punctuated pair.
David Tolnay56080682018-01-06 14:01:52 -0800573 pub fn value(&self) -> &T {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700574 match *self {
David Tolnay56080682018-01-06 14:01:52 -0800575 Pair::Punctuated(ref t, _) | Pair::End(ref t) => t,
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700576 }
577 }
578
David Tolnayf3198012018-01-06 20:00:42 -0800579 /// Mutably borrows the syntax tree node from this punctuated pair.
David Tolnay56080682018-01-06 14:01:52 -0800580 pub fn value_mut(&mut self) -> &mut T {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700581 match *self {
David Tolnay56080682018-01-06 14:01:52 -0800582 Pair::Punctuated(ref mut t, _) | Pair::End(ref mut t) => t,
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700583 }
584 }
585
David Tolnayf3198012018-01-06 20:00:42 -0800586 /// Borrows the punctuation from this punctuated pair, unless this pair is
587 /// the final one and there is no trailing punctuation.
David Tolnayf2cfd722017-12-31 18:02:51 -0500588 pub fn punct(&self) -> Option<&P> {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700589 match *self {
David Tolnay56080682018-01-06 14:01:52 -0800590 Pair::Punctuated(_, ref d) => Some(d),
591 Pair::End(_) => None,
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700592 }
593 }
Nika Layzellcda7ebd2017-10-24 23:10:44 -0400594
David Tolnayf3198012018-01-06 20:00:42 -0800595 /// Creates a punctuated pair out of a syntax tree node and an optional
596 /// following punctuation.
David Tolnayf2cfd722017-12-31 18:02:51 -0500597 pub fn new(t: T, d: Option<P>) -> Self {
David Tolnay660fd1f2017-12-31 01:52:57 -0500598 match d {
David Tolnay56080682018-01-06 14:01:52 -0800599 Some(d) => Pair::Punctuated(t, d),
600 None => Pair::End(t),
David Tolnay660fd1f2017-12-31 01:52:57 -0500601 }
602 }
603
David Tolnayf3198012018-01-06 20:00:42 -0800604 /// Produces this punctuated pair as a tuple of syntax tree node and
605 /// optional following punctuation.
David Tolnayf2cfd722017-12-31 18:02:51 -0500606 pub fn into_tuple(self) -> (T, Option<P>) {
Nika Layzellcda7ebd2017-10-24 23:10:44 -0400607 match self {
David Tolnay56080682018-01-06 14:01:52 -0800608 Pair::Punctuated(t, d) => (t, Some(d)),
609 Pair::End(t) => (t, None),
Nika Layzellcda7ebd2017-10-24 23:10:44 -0400610 }
611 }
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700612}
613
David Tolnaybb987132018-01-08 13:51:19 -0800614impl<T, P> Index<usize> for Punctuated<T, P> {
615 type Output = T;
616
617 fn index(&self, index: usize) -> &Self::Output {
Mateusz Naściszewski14111202018-04-11 21:17:41 +0200618 if index == self.len() - 1 {
619 match self.last {
620 Some(ref t) => t,
David Tolnay94d2b792018-04-29 12:26:10 -0700621 None => &self.inner[index].0,
Mateusz Naściszewski14111202018-04-11 21:17:41 +0200622 }
623 } else {
624 &self.inner[index].0
625 }
David Tolnaybb987132018-01-08 13:51:19 -0800626 }
627}
628
629impl<T, P> IndexMut<usize> for Punctuated<T, P> {
630 fn index_mut(&mut self, index: usize) -> &mut Self::Output {
Mateusz Naściszewski14111202018-04-11 21:17:41 +0200631 if index == self.len() - 1 {
632 match self.last {
633 Some(ref mut t) => t,
David Tolnay94d2b792018-04-29 12:26:10 -0700634 None => &mut self.inner[index].0,
Mateusz Naściszewski14111202018-04-11 21:17:41 +0200635 }
636 } else {
637 &mut self.inner[index].0
638 }
David Tolnaybb987132018-01-08 13:51:19 -0800639 }
640}
641
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700642#[cfg(feature = "parsing")]
David Tolnayf3198012018-01-06 20:00:42 -0800643impl<T, P> Punctuated<T, P>
644where
645 T: Synom,
646 P: Synom,
647{
648 /// Parse **zero or more** syntax tree nodes with punctuation in between and
649 /// **no trailing** punctuation.
650 pub fn parse_separated(input: Cursor) -> PResult<Self> {
651 Self::parse_separated_with(input, T::parse)
652 }
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700653
David Tolnayf3198012018-01-06 20:00:42 -0800654 /// Parse **one or more** syntax tree nodes with punctuation in bewteen and
655 /// **no trailing** punctuation.
656 /// allowing trailing punctuation.
657 pub fn parse_separated_nonempty(input: Cursor) -> PResult<Self> {
658 Self::parse_separated_nonempty_with(input, T::parse)
659 }
Alex Crichton954046c2017-05-30 21:49:42 -0700660
David Tolnayf3198012018-01-06 20:00:42 -0800661 /// Parse **zero or more** syntax tree nodes with punctuation in between and
662 /// **optional trailing** punctuation.
663 pub fn parse_terminated(input: Cursor) -> PResult<Self> {
664 Self::parse_terminated_with(input, T::parse)
665 }
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700666
David Tolnayf3198012018-01-06 20:00:42 -0800667 /// Parse **one or more** syntax tree nodes with punctuation in between and
668 /// **optional trailing** punctuation.
669 pub fn parse_terminated_nonempty(input: Cursor) -> PResult<Self> {
670 Self::parse_terminated_nonempty_with(input, T::parse)
671 }
672}
Nika Layzellb49a9e52017-12-05 13:31:52 -0500673
David Tolnayf3198012018-01-06 20:00:42 -0800674#[cfg(feature = "parsing")]
675impl<T, P> Punctuated<T, P>
676where
677 P: Synom,
678{
679 /// Parse **zero or more** syntax tree nodes using the given parser with
680 /// punctuation in between and **no trailing** punctuation.
David Tolnay94d2b792018-04-29 12:26:10 -0700681 pub fn parse_separated_with(input: Cursor, parse: fn(Cursor) -> PResult<T>) -> PResult<Self> {
David Tolnayf3198012018-01-06 20:00:42 -0800682 Self::parse(input, parse, false)
683 }
684
685 /// Parse **one or more** syntax tree nodes using the given parser with
686 /// punctuation in between and **no trailing** punctuation.
687 pub fn parse_separated_nonempty_with(
688 input: Cursor,
689 parse: fn(Cursor) -> PResult<T>,
690 ) -> PResult<Self> {
691 match Self::parse(input, parse, false) {
692 Ok((ref b, _)) if b.is_empty() => parse_error(),
693 other => other,
Nika Layzellb49a9e52017-12-05 13:31:52 -0500694 }
Alex Crichton954046c2017-05-30 21:49:42 -0700695 }
696
David Tolnayf3198012018-01-06 20:00:42 -0800697 /// Parse **zero or more** syntax tree nodes using the given parser with
698 /// punctuation in between and **optional trailing** punctuation.
David Tolnay94d2b792018-04-29 12:26:10 -0700699 pub fn parse_terminated_with(input: Cursor, parse: fn(Cursor) -> PResult<T>) -> PResult<Self> {
David Tolnayf3198012018-01-06 20:00:42 -0800700 Self::parse(input, parse, true)
701 }
702
703 /// Parse **one or more** syntax tree nodes using the given parser with
704 /// punctuation in between and **optional trailing** punctuation.
705 pub fn parse_terminated_nonempty_with(
706 input: Cursor,
707 parse: fn(Cursor) -> PResult<T>,
708 ) -> PResult<Self> {
709 match Self::parse(input, parse, true) {
710 Ok((ref b, _)) if b.is_empty() => parse_error(),
711 other => other,
David Tolnaydc03aec2017-12-30 01:54:18 -0500712 }
David Tolnayf3198012018-01-06 20:00:42 -0800713 }
David Tolnaydc03aec2017-12-30 01:54:18 -0500714
David Tolnayf3198012018-01-06 20:00:42 -0800715 fn parse(
716 mut input: Cursor,
717 parse: fn(Cursor) -> PResult<T>,
718 terminated: bool,
719 ) -> PResult<Self> {
720 let mut res = Punctuated::new();
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700721
David Tolnayf3198012018-01-06 20:00:42 -0800722 // get the first element
723 match parse(input) {
724 Err(_) => Ok((res, input)),
725 Ok((o, i)) => {
726 if i == input {
727 return parse_error();
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700728 }
David Tolnayf3198012018-01-06 20:00:42 -0800729 input = i;
730 res.push_value(o);
731
732 // get the separator first
733 while let Ok((s, i2)) = P::parse(input) {
734 if i2 == input {
735 break;
736 }
737
738 // get the element next
739 if let Ok((o3, i3)) = parse(i2) {
740 if i3 == i2 {
741 break;
742 }
743 res.push_punct(s);
744 res.push_value(o3);
745 input = i3;
746 } else {
747 break;
748 }
749 }
750 if terminated {
751 if let Ok((sep, after)) = P::parse(input) {
752 res.push_punct(sep);
753 input = after;
754 }
755 }
756 Ok((res, input))
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700757 }
758 }
759 }
760}
761
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700762#[cfg(feature = "printing")]
763mod printing {
764 use super::*;
David Tolnay51382052017-12-27 13:46:21 -0500765 use quote::{ToTokens, Tokens};
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700766
David Tolnayf2cfd722017-12-31 18:02:51 -0500767 impl<T, P> ToTokens for Punctuated<T, P>
David Tolnay51382052017-12-27 13:46:21 -0500768 where
769 T: ToTokens,
David Tolnayf2cfd722017-12-31 18:02:51 -0500770 P: ToTokens,
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700771 {
772 fn to_tokens(&self, tokens: &mut Tokens) {
David Tolnay56080682018-01-06 14:01:52 -0800773 tokens.append_all(self.pairs())
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700774 }
775 }
776
David Tolnay56080682018-01-06 14:01:52 -0800777 impl<T, P> ToTokens for Pair<T, P>
David Tolnay51382052017-12-27 13:46:21 -0500778 where
779 T: ToTokens,
David Tolnayf2cfd722017-12-31 18:02:51 -0500780 P: ToTokens,
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700781 {
782 fn to_tokens(&self, tokens: &mut Tokens) {
783 match *self {
David Tolnay56080682018-01-06 14:01:52 -0800784 Pair::Punctuated(ref a, ref b) => {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700785 a.to_tokens(tokens);
786 b.to_tokens(tokens);
787 }
David Tolnay56080682018-01-06 14:01:52 -0800788 Pair::End(ref a) => a.to_tokens(tokens),
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700789 }
790 }
791 }
792}