blob: 1794fc0e8be5961d933a1f479bfe188532e36a26 [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 Tolnayecf0fbc2018-08-30 18:28:33 -070041use parse::{Parse, ParseStream, Result};
David Tolnay94f06632018-08-31 10:17:17 -070042#[cfg(any(feature = "full", feature = "derive"))]
43use private;
David Tolnay52619f62018-08-31 09:30:01 -070044#[cfg(feature = "parsing")]
45use token::Token;
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
David Tolnayf3198012018-01-06 20:00:42 -0800212 /// Appends a syntax tree node onto the end of this punctuated sequence.
213 ///
214 /// If there is not a trailing punctuation in this sequence when this method
215 /// is called, the default value of punctuation type `P` is inserted before
216 /// the given value of type `T`.
David Tolnay8842c7e2018-09-01 12:37:32 -0700217 pub fn push(&mut self, value: T)
218 where
219 P: Default,
220 {
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.
David Tolnay8842c7e2018-09-01 12:37:32 -0700233 pub fn insert(&mut self, index: usize, value: T)
234 where
235 P: Default,
236 {
David Tolnayb77d1802018-01-11 16:18:35 -0800237 assert!(index <= self.len());
238
239 if index == self.len() {
240 self.push(value);
241 } else {
Mateusz Naściszewski14111202018-04-11 21:17:41 +0200242 self.inner.insert(index, (value, Default::default()));
David Tolnayb77d1802018-01-11 16:18:35 -0800243 }
244 }
David Tolnay8842c7e2018-09-01 12:37:32 -0700245
246 #[cfg(feature = "parsing")]
247 pub fn parse_terminated(input: ParseStream) -> Result<Self>
248 where
249 T: Parse,
250 P: Parse,
251 {
252 Self::parse_terminated_with(input, T::parse)
253 }
254
255 #[cfg(feature = "parsing")]
256 pub fn parse_terminated_with(
257 input: ParseStream,
258 parser: fn(ParseStream) -> Result<T>,
259 ) -> Result<Self>
260 where
261 P: Parse,
262 {
263 let mut punctuated = Punctuated::new();
264
265 loop {
266 if input.is_empty() {
267 break;
268 }
269 let value = parser(input)?;
270 punctuated.push_value(value);
271 if input.is_empty() {
272 break;
273 }
274 let punct = input.parse()?;
275 punctuated.push_punct(punct);
276 }
277
278 Ok(punctuated)
279 }
280
281 #[cfg(feature = "parsing")]
282 pub fn parse_separated_nonempty(input: ParseStream) -> Result<Self>
283 where
284 T: Parse,
285 P: Token + Parse,
286 {
287 Self::parse_separated_nonempty_with(input, T::parse)
288 }
289
290 #[cfg(feature = "parsing")]
291 pub fn parse_separated_nonempty_with(
292 input: ParseStream,
293 parser: fn(ParseStream) -> Result<T>,
294 ) -> Result<Self>
295 where
296 P: Token + Parse,
297 {
298 let mut punctuated = Punctuated::new();
299
300 loop {
301 let value = parser(input)?;
302 punctuated.push_value(value);
303 if !P::peek(input.cursor()) {
304 break;
305 }
306 let punct = input.parse()?;
307 punctuated.push_punct(punct);
308 }
309
310 Ok(punctuated)
311 }
David Tolnaya0834b42018-01-01 21:30:02 -0800312}
313
Nika Layzelld73a3652017-10-24 08:57:05 -0400314#[cfg(feature = "extra-traits")]
David Tolnayf2cfd722017-12-31 18:02:51 -0500315impl<T: Debug, P: Debug> Debug for Punctuated<T, P> {
Nika Layzelld73a3652017-10-24 08:57:05 -0400316 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Mateusz Naściszewski14111202018-04-11 21:17:41 +0200317 let mut list = f.debug_list();
David Tolnay0c18c512018-07-22 10:39:10 -0700318 for &(ref t, ref p) in &self.inner {
319 list.entry(t);
320 list.entry(p);
321 }
322 if let Some(ref last) = self.last {
323 list.entry(last);
Mateusz Naściszewski14111202018-04-11 21:17:41 +0200324 }
325 list.finish()
Nika Layzelld73a3652017-10-24 08:57:05 -0400326 }
327}
328
David Tolnay9ef24bc2018-01-09 10:43:55 -0800329impl<T, P> FromIterator<T> for Punctuated<T, P>
330where
331 P: Default,
332{
333 fn from_iter<I: IntoIterator<Item = T>>(i: I) -> Self {
334 let mut ret = Punctuated::new();
335 ret.extend(i);
336 ret
337 }
338}
339
340impl<T, P> Extend<T> for Punctuated<T, P>
341where
342 P: Default,
343{
344 fn extend<I: IntoIterator<Item = T>>(&mut self, i: I) {
345 for value in i {
346 self.push(value);
347 }
348 }
349}
350
David Tolnay56080682018-01-06 14:01:52 -0800351impl<T, P> FromIterator<Pair<T, P>> for Punctuated<T, P> {
352 fn from_iter<I: IntoIterator<Item = Pair<T, P>>>(i: I) -> Self {
David Tolnayf2cfd722017-12-31 18:02:51 -0500353 let mut ret = Punctuated::new();
Alex Crichton24f12822017-07-14 07:15:32 -0700354 ret.extend(i);
Alex Crichton954046c2017-05-30 21:49:42 -0700355 ret
356 }
357}
358
David Tolnay56080682018-01-06 14:01:52 -0800359impl<T, P> Extend<Pair<T, P>> for Punctuated<T, P> {
360 fn extend<I: IntoIterator<Item = Pair<T, P>>>(&mut self, i: I) {
Mateusz Naściszewski14111202018-04-11 21:17:41 +0200361 assert!(self.empty_or_trailing());
362 let mut nomore = false;
David Tolnay56080682018-01-06 14:01:52 -0800363 for pair in i {
Mateusz Naściszewski14111202018-04-11 21:17:41 +0200364 if nomore {
365 panic!("Punctuated extended with items after a Pair::End");
366 }
David Tolnay56080682018-01-06 14:01:52 -0800367 match pair {
Mateusz Naściszewski14111202018-04-11 21:17:41 +0200368 Pair::Punctuated(a, b) => self.inner.push((a, b)),
369 Pair::End(a) => {
370 self.last = Some(Box::new(a));
371 nomore = true;
372 }
Alex Crichton24f12822017-07-14 07:15:32 -0700373 }
374 }
375 }
376}
377
David Tolnayf2cfd722017-12-31 18:02:51 -0500378impl<T, P> IntoIterator for Punctuated<T, P> {
David Tolnay6eff4da2018-01-01 20:27:45 -0800379 type Item = T;
David Tolnayf2cfd722017-12-31 18:02:51 -0500380 type IntoIter = IntoIter<T, P>;
Alex Crichton954046c2017-05-30 21:49:42 -0700381
David Tolnaybb4ca9f2017-12-26 12:28:58 -0500382 fn into_iter(self) -> Self::IntoIter {
David Tolnay51382052017-12-27 13:46:21 -0500383 IntoIter {
384 inner: self.inner.into_iter(),
Mateusz Naściszewski14111202018-04-11 21:17:41 +0200385 last: self.last.map(|t| *t).into_iter(),
David Tolnay51382052017-12-27 13:46:21 -0500386 }
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700387 }
388}
389
David Tolnay6eff4da2018-01-01 20:27:45 -0800390impl<'a, T, P> IntoIterator for &'a Punctuated<T, P> {
391 type Item = &'a T;
David Tolnay8095c302018-03-31 19:34:17 +0200392 type IntoIter = Iter<'a, T>;
David Tolnay6eff4da2018-01-01 20:27:45 -0800393
394 fn into_iter(self) -> Self::IntoIter {
395 Punctuated::iter(self)
396 }
397}
398
David Tolnaya0834b42018-01-01 21:30:02 -0800399impl<'a, T, P> IntoIterator for &'a mut Punctuated<T, P> {
400 type Item = &'a mut T;
David Tolnay8095c302018-03-31 19:34:17 +0200401 type IntoIter = IterMut<'a, T>;
David Tolnaya0834b42018-01-01 21:30:02 -0800402
403 fn into_iter(self) -> Self::IntoIter {
404 Punctuated::iter_mut(self)
405 }
406}
407
David Tolnayf2cfd722017-12-31 18:02:51 -0500408impl<T, P> Default for Punctuated<T, P> {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700409 fn default() -> Self {
David Tolnayf2cfd722017-12-31 18:02:51 -0500410 Punctuated::new()
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700411 }
412}
413
David Tolnayf3198012018-01-06 20:00:42 -0800414/// An iterator over borrowed pairs of type `Pair<&T, &P>`.
415///
416/// Refer to the [module documentation] for details about punctuated sequences.
417///
418/// [module documentation]: index.html
David Tolnay56080682018-01-06 14:01:52 -0800419pub struct Pairs<'a, T: 'a, P: 'a> {
Mateusz Naściszewski14111202018-04-11 21:17:41 +0200420 inner: slice::Iter<'a, (T, P)>,
421 last: option::IntoIter<&'a T>,
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700422}
423
David Tolnay56080682018-01-06 14:01:52 -0800424impl<'a, T, P> Iterator for Pairs<'a, T, P> {
425 type Item = Pair<&'a T, &'a P>;
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700426
David Tolnay6eff4da2018-01-01 20:27:45 -0800427 fn next(&mut self) -> Option<Self::Item> {
David Tolnay94d2b792018-04-29 12:26:10 -0700428 self.inner
429 .next()
430 .map(|&(ref t, ref p)| Pair::Punctuated(t, p))
David Tolnay6e4a9c22018-04-11 12:20:08 -0700431 .or_else(|| self.last.next().map(Pair::End))
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700432 }
433}
434
David Tolnay9700be02018-04-30 00:51:15 -0700435impl<'a, T, P> ExactSizeIterator for Pairs<'a, T, P> {
436 fn len(&self) -> usize {
437 self.inner.len() + self.last.len()
438 }
439}
440
David Tolnayf3198012018-01-06 20:00:42 -0800441/// An iterator over mutably borrowed pairs of type `Pair<&mut T, &mut P>`.
442///
443/// Refer to the [module documentation] for details about punctuated sequences.
444///
445/// [module documentation]: index.html
David Tolnay56080682018-01-06 14:01:52 -0800446pub struct PairsMut<'a, T: 'a, P: 'a> {
Mateusz Naściszewski14111202018-04-11 21:17:41 +0200447 inner: slice::IterMut<'a, (T, P)>,
448 last: option::IntoIter<&'a mut T>,
Alex Crichton164c5332017-07-06 13:18:34 -0700449}
450
David Tolnay56080682018-01-06 14:01:52 -0800451impl<'a, T, P> Iterator for PairsMut<'a, T, P> {
452 type Item = Pair<&'a mut T, &'a mut P>;
Alex Crichton164c5332017-07-06 13:18:34 -0700453
David Tolnay6eff4da2018-01-01 20:27:45 -0800454 fn next(&mut self) -> Option<Self::Item> {
David Tolnay94d2b792018-04-29 12:26:10 -0700455 self.inner
456 .next()
457 .map(|&mut (ref mut t, ref mut p)| Pair::Punctuated(t, p))
David Tolnay6e4a9c22018-04-11 12:20:08 -0700458 .or_else(|| self.last.next().map(Pair::End))
Alex Crichton164c5332017-07-06 13:18:34 -0700459 }
460}
461
David Tolnay9700be02018-04-30 00:51:15 -0700462impl<'a, T, P> ExactSizeIterator for PairsMut<'a, T, P> {
463 fn len(&self) -> usize {
464 self.inner.len() + self.last.len()
465 }
466}
467
David Tolnayf3198012018-01-06 20:00:42 -0800468/// An iterator over owned pairs of type `Pair<T, P>`.
469///
470/// Refer to the [module documentation] for details about punctuated sequences.
471///
472/// [module documentation]: index.html
David Tolnay56080682018-01-06 14:01:52 -0800473pub struct IntoPairs<T, P> {
Mateusz Naściszewski14111202018-04-11 21:17:41 +0200474 inner: vec::IntoIter<(T, P)>,
475 last: option::IntoIter<T>,
David Tolnay6eff4da2018-01-01 20:27:45 -0800476}
477
David Tolnay56080682018-01-06 14:01:52 -0800478impl<T, P> Iterator for IntoPairs<T, P> {
479 type Item = Pair<T, P>;
David Tolnay6eff4da2018-01-01 20:27:45 -0800480
481 fn next(&mut self) -> Option<Self::Item> {
David Tolnay94d2b792018-04-29 12:26:10 -0700482 self.inner
483 .next()
484 .map(|(t, p)| Pair::Punctuated(t, p))
David Tolnay6e4a9c22018-04-11 12:20:08 -0700485 .or_else(|| self.last.next().map(Pair::End))
David Tolnay6eff4da2018-01-01 20:27:45 -0800486 }
487}
488
David Tolnay9700be02018-04-30 00:51:15 -0700489impl<T, P> ExactSizeIterator for IntoPairs<T, P> {
490 fn len(&self) -> usize {
491 self.inner.len() + self.last.len()
492 }
493}
494
David Tolnayf3198012018-01-06 20:00:42 -0800495/// An iterator over owned values of type `T`.
496///
497/// Refer to the [module documentation] for details about punctuated sequences.
498///
499/// [module documentation]: index.html
David Tolnayf2cfd722017-12-31 18:02:51 -0500500pub struct IntoIter<T, P> {
Mateusz Naściszewski14111202018-04-11 21:17:41 +0200501 inner: vec::IntoIter<(T, P)>,
502 last: option::IntoIter<T>,
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700503}
504
David Tolnayf2cfd722017-12-31 18:02:51 -0500505impl<T, P> Iterator for IntoIter<T, P> {
David Tolnay6eff4da2018-01-01 20:27:45 -0800506 type Item = T;
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700507
David Tolnay6eff4da2018-01-01 20:27:45 -0800508 fn next(&mut self) -> Option<Self::Item> {
David Tolnay94d2b792018-04-29 12:26:10 -0700509 self.inner
510 .next()
511 .map(|pair| pair.0)
512 .or_else(|| self.last.next())
David Tolnay6eff4da2018-01-01 20:27:45 -0800513 }
514}
515
David Tolnay9700be02018-04-30 00:51:15 -0700516impl<T, P> ExactSizeIterator for IntoIter<T, P> {
517 fn len(&self) -> usize {
518 self.inner.len() + self.last.len()
519 }
520}
521
David Tolnayf3198012018-01-06 20:00:42 -0800522/// An iterator over borrowed values of type `&T`.
523///
524/// Refer to the [module documentation] for details about punctuated sequences.
525///
526/// [module documentation]: index.html
David Tolnay8095c302018-03-31 19:34:17 +0200527pub struct Iter<'a, T: 'a> {
David Tolnay9700be02018-04-30 00:51:15 -0700528 inner: Box<ExactSizeIterator<Item = &'a T> + 'a>,
David Tolnay8095c302018-03-31 19:34:17 +0200529}
530
531struct PrivateIter<'a, T: 'a, P: 'a> {
Mateusz Naściszewski14111202018-04-11 21:17:41 +0200532 inner: slice::Iter<'a, (T, P)>,
533 last: option::IntoIter<&'a T>,
David Tolnay6eff4da2018-01-01 20:27:45 -0800534}
535
David Tolnay96a09d92018-01-16 22:24:03 -0800536#[cfg(any(feature = "full", feature = "derive"))]
David Tolnay10951d52018-08-31 10:27:39 -0700537impl private {
538 pub fn empty_punctuated_iter<'a, T>() -> Iter<'a, T> {
David Tolnay96a09d92018-01-16 22:24:03 -0800539 Iter {
David Tolnay8095c302018-03-31 19:34:17 +0200540 inner: Box::new(iter::empty()),
David Tolnay96a09d92018-01-16 22:24:03 -0800541 }
542 }
543}
544
David Tolnay8095c302018-03-31 19:34:17 +0200545impl<'a, T> Iterator for Iter<'a, T> {
546 type Item = &'a T;
547
548 fn next(&mut self) -> Option<Self::Item> {
549 self.inner.next()
550 }
551}
552
David Tolnay9700be02018-04-30 00:51:15 -0700553impl<'a, T> ExactSizeIterator for Iter<'a, T> {
554 fn len(&self) -> usize {
555 self.inner.len()
556 }
557}
558
David Tolnay8095c302018-03-31 19:34:17 +0200559impl<'a, T, P> Iterator for PrivateIter<'a, T, P> {
David Tolnay6eff4da2018-01-01 20:27:45 -0800560 type Item = &'a T;
561
562 fn next(&mut self) -> Option<Self::Item> {
David Tolnay94d2b792018-04-29 12:26:10 -0700563 self.inner
564 .next()
565 .map(|pair| &pair.0)
566 .or_else(|| self.last.next())
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700567 }
568}
569
David Tolnay9700be02018-04-30 00:51:15 -0700570impl<'a, T, P> ExactSizeIterator for PrivateIter<'a, T, P> {
571 fn len(&self) -> usize {
572 self.inner.len() + self.last.len()
573 }
574}
575
David Tolnayf3198012018-01-06 20:00:42 -0800576/// An iterator over mutably borrowed values of type `&mut T`.
577///
578/// Refer to the [module documentation] for details about punctuated sequences.
579///
580/// [module documentation]: index.html
David Tolnay8095c302018-03-31 19:34:17 +0200581pub struct IterMut<'a, T: 'a> {
David Tolnay9700be02018-04-30 00:51:15 -0700582 inner: Box<ExactSizeIterator<Item = &'a mut T> + 'a>,
David Tolnay8095c302018-03-31 19:34:17 +0200583}
584
585struct PrivateIterMut<'a, T: 'a, P: 'a> {
Mateusz Naściszewski14111202018-04-11 21:17:41 +0200586 inner: slice::IterMut<'a, (T, P)>,
587 last: option::IntoIter<&'a mut T>,
David Tolnaya0834b42018-01-01 21:30:02 -0800588}
589
Michael Bradshaw0b13ae62018-08-02 23:43:15 -0600590#[cfg(any(feature = "full", feature = "derive"))]
David Tolnay10951d52018-08-31 10:27:39 -0700591impl private {
592 pub fn empty_punctuated_iter_mut<'a, T>() -> IterMut<'a, T> {
Michael Bradshaw0b13ae62018-08-02 23:43:15 -0600593 IterMut {
594 inner: Box::new(iter::empty()),
595 }
596 }
597}
598
David Tolnay8095c302018-03-31 19:34:17 +0200599impl<'a, T> Iterator for IterMut<'a, T> {
600 type Item = &'a mut T;
601
602 fn next(&mut self) -> Option<Self::Item> {
603 self.inner.next()
604 }
605}
606
David Tolnay9700be02018-04-30 00:51:15 -0700607impl<'a, T> ExactSizeIterator for IterMut<'a, T> {
608 fn len(&self) -> usize {
609 self.inner.len()
610 }
611}
612
David Tolnay8095c302018-03-31 19:34:17 +0200613impl<'a, T, P> Iterator for PrivateIterMut<'a, T, P> {
David Tolnaya0834b42018-01-01 21:30:02 -0800614 type Item = &'a mut T;
615
616 fn next(&mut self) -> Option<Self::Item> {
David Tolnay94d2b792018-04-29 12:26:10 -0700617 self.inner
618 .next()
619 .map(|pair| &mut pair.0)
620 .or_else(|| self.last.next())
David Tolnaya0834b42018-01-01 21:30:02 -0800621 }
622}
623
David Tolnay9700be02018-04-30 00:51:15 -0700624impl<'a, T, P> ExactSizeIterator for PrivateIterMut<'a, T, P> {
625 fn len(&self) -> usize {
626 self.inner.len() + self.last.len()
627 }
628}
629
David Tolnayf3198012018-01-06 20:00:42 -0800630/// A single syntax tree node of type `T` followed by its trailing punctuation
631/// of type `P` if any.
632///
633/// Refer to the [module documentation] for details about punctuated sequences.
634///
635/// [module documentation]: index.html
David Tolnay56080682018-01-06 14:01:52 -0800636pub enum Pair<T, P> {
David Tolnayf2cfd722017-12-31 18:02:51 -0500637 Punctuated(T, P),
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700638 End(T),
639}
640
David Tolnay56080682018-01-06 14:01:52 -0800641impl<T, P> Pair<T, P> {
David Tolnayf3198012018-01-06 20:00:42 -0800642 /// Extracts the syntax tree node from this punctuated pair, discarding the
643 /// following punctuation.
David Tolnay56080682018-01-06 14:01:52 -0800644 pub fn into_value(self) -> T {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700645 match self {
David Tolnay56080682018-01-06 14:01:52 -0800646 Pair::Punctuated(t, _) | Pair::End(t) => t,
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700647 }
648 }
649
David Tolnayf3198012018-01-06 20:00:42 -0800650 /// Borrows the syntax tree node from this punctuated pair.
David Tolnay56080682018-01-06 14:01:52 -0800651 pub fn value(&self) -> &T {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700652 match *self {
David Tolnay56080682018-01-06 14:01:52 -0800653 Pair::Punctuated(ref t, _) | Pair::End(ref t) => t,
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700654 }
655 }
656
David Tolnayf3198012018-01-06 20:00:42 -0800657 /// Mutably borrows the syntax tree node from this punctuated pair.
David Tolnay56080682018-01-06 14:01:52 -0800658 pub fn value_mut(&mut self) -> &mut T {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700659 match *self {
David Tolnay56080682018-01-06 14:01:52 -0800660 Pair::Punctuated(ref mut t, _) | Pair::End(ref mut t) => t,
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700661 }
662 }
663
David Tolnayf3198012018-01-06 20:00:42 -0800664 /// Borrows the punctuation from this punctuated pair, unless this pair is
665 /// the final one and there is no trailing punctuation.
David Tolnayf2cfd722017-12-31 18:02:51 -0500666 pub fn punct(&self) -> Option<&P> {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700667 match *self {
David Tolnay56080682018-01-06 14:01:52 -0800668 Pair::Punctuated(_, ref d) => Some(d),
669 Pair::End(_) => None,
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700670 }
671 }
Nika Layzellcda7ebd2017-10-24 23:10:44 -0400672
David Tolnayf3198012018-01-06 20:00:42 -0800673 /// Creates a punctuated pair out of a syntax tree node and an optional
674 /// following punctuation.
David Tolnayf2cfd722017-12-31 18:02:51 -0500675 pub fn new(t: T, d: Option<P>) -> Self {
David Tolnay660fd1f2017-12-31 01:52:57 -0500676 match d {
David Tolnay56080682018-01-06 14:01:52 -0800677 Some(d) => Pair::Punctuated(t, d),
678 None => Pair::End(t),
David Tolnay660fd1f2017-12-31 01:52:57 -0500679 }
680 }
681
David Tolnayf3198012018-01-06 20:00:42 -0800682 /// Produces this punctuated pair as a tuple of syntax tree node and
683 /// optional following punctuation.
David Tolnayf2cfd722017-12-31 18:02:51 -0500684 pub fn into_tuple(self) -> (T, Option<P>) {
Nika Layzellcda7ebd2017-10-24 23:10:44 -0400685 match self {
David Tolnay56080682018-01-06 14:01:52 -0800686 Pair::Punctuated(t, d) => (t, Some(d)),
687 Pair::End(t) => (t, None),
Nika Layzellcda7ebd2017-10-24 23:10:44 -0400688 }
689 }
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700690}
691
David Tolnaybb987132018-01-08 13:51:19 -0800692impl<T, P> Index<usize> for Punctuated<T, P> {
693 type Output = T;
694
695 fn index(&self, index: usize) -> &Self::Output {
Mateusz Naściszewski14111202018-04-11 21:17:41 +0200696 if index == self.len() - 1 {
697 match self.last {
698 Some(ref t) => t,
David Tolnay94d2b792018-04-29 12:26:10 -0700699 None => &self.inner[index].0,
Mateusz Naściszewski14111202018-04-11 21:17:41 +0200700 }
701 } else {
702 &self.inner[index].0
703 }
David Tolnaybb987132018-01-08 13:51:19 -0800704 }
705}
706
707impl<T, P> IndexMut<usize> for Punctuated<T, P> {
708 fn index_mut(&mut self, index: usize) -> &mut Self::Output {
Mateusz Naściszewski14111202018-04-11 21:17:41 +0200709 if index == self.len() - 1 {
710 match self.last {
711 Some(ref mut t) => t,
David Tolnay94d2b792018-04-29 12:26:10 -0700712 None => &mut self.inner[index].0,
Mateusz Naściszewski14111202018-04-11 21:17:41 +0200713 }
714 } else {
715 &mut self.inner[index].0
716 }
David Tolnaybb987132018-01-08 13:51:19 -0800717 }
718}
719
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700720#[cfg(feature = "printing")]
721mod printing {
722 use super::*;
Alex Crichtona74a1c82018-05-16 10:20:44 -0700723 use proc_macro2::TokenStream;
David Tolnay65fb5662018-05-20 20:02:28 -0700724 use quote::{ToTokens, TokenStreamExt};
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700725
David Tolnayf2cfd722017-12-31 18:02:51 -0500726 impl<T, P> ToTokens for Punctuated<T, P>
David Tolnay51382052017-12-27 13:46:21 -0500727 where
728 T: ToTokens,
David Tolnayf2cfd722017-12-31 18:02:51 -0500729 P: ToTokens,
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700730 {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700731 fn to_tokens(&self, tokens: &mut TokenStream) {
David Tolnay56080682018-01-06 14:01:52 -0800732 tokens.append_all(self.pairs())
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700733 }
734 }
735
David Tolnay56080682018-01-06 14:01:52 -0800736 impl<T, P> ToTokens for Pair<T, P>
David Tolnay51382052017-12-27 13:46:21 -0500737 where
738 T: ToTokens,
David Tolnayf2cfd722017-12-31 18:02:51 -0500739 P: ToTokens,
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700740 {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700741 fn to_tokens(&self, tokens: &mut TokenStream) {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700742 match *self {
David Tolnay56080682018-01-06 14:01:52 -0800743 Pair::Punctuated(ref a, ref b) => {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700744 a.to_tokens(tokens);
745 b.to_tokens(tokens);
746 }
David Tolnay56080682018-01-06 14:01:52 -0800747 Pair::End(ref a) => a.to_tokens(tokens),
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700748 }
749 }
750 }
751}