blob: 38363b63bab0c9e9988b6947a40353135864119c [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
Alex Crichtonccbb45d2017-05-23 10:58:24 -070030use std::iter::FromIterator;
David Tolnaybb987132018-01-08 13:51:19 -080031use std::ops::{Index, IndexMut};
Alex Crichtonccbb45d2017-05-23 10:58:24 -070032use std::slice;
33use std::vec;
Nika Layzelld73a3652017-10-24 08:57:05 -040034#[cfg(feature = "extra-traits")]
35use std::fmt::{self, Debug};
Alex Crichtonccbb45d2017-05-23 10:58:24 -070036
David Tolnayf3198012018-01-06 20:00:42 -080037#[cfg(feature = "parsing")]
38use synom::{Synom, PResult};
39#[cfg(feature = "parsing")]
40use buffer::Cursor;
41#[cfg(feature = "parsing")]
42use parse_error;
43
44/// A punctuated sequence of syntax tree nodes of type `T` separated by
45/// punctuation of type `P`.
46///
47/// Refer to the [module documentation] for details about punctuated sequences.
48///
49/// [module documentation]: index.html
Nika Layzelld73a3652017-10-24 08:57:05 -040050#[cfg_attr(feature = "extra-traits", derive(Eq, PartialEq, Hash))]
Alex Crichton7b9e02f2017-05-30 15:54:33 -070051#[cfg_attr(feature = "clone-impls", derive(Clone))]
David Tolnayf2cfd722017-12-31 18:02:51 -050052pub struct Punctuated<T, P> {
53 inner: Vec<(T, Option<P>)>,
Alex Crichtonccbb45d2017-05-23 10:58:24 -070054}
55
David Tolnayf2cfd722017-12-31 18:02:51 -050056impl<T, P> Punctuated<T, P> {
David Tolnayf3198012018-01-06 20:00:42 -080057 /// Creates an empty punctuated sequence.
David Tolnayf2cfd722017-12-31 18:02:51 -050058 pub fn new() -> Punctuated<T, P> {
59 Punctuated { inner: Vec::new() }
Alex Crichtonccbb45d2017-05-23 10:58:24 -070060 }
61
David Tolnayf3198012018-01-06 20:00:42 -080062 /// Determines whether this punctuated sequence is empty, meaning it
63 /// contains no syntax tree nodes or punctuation.
Alex Crichtonccbb45d2017-05-23 10:58:24 -070064 pub fn is_empty(&self) -> bool {
65 self.inner.len() == 0
66 }
67
David Tolnayf3198012018-01-06 20:00:42 -080068 /// Returns the number of syntax tree nodes in this punctuated sequence.
69 ///
70 /// This is the number of nodes of type `T`, not counting the punctuation of
71 /// type `P`.
Alex Crichtonccbb45d2017-05-23 10:58:24 -070072 pub fn len(&self) -> usize {
73 self.inner.len()
74 }
75
David Tolnayf3198012018-01-06 20:00:42 -080076 /// Borrows the first punctuated pair in this sequence.
David Tolnay56080682018-01-06 14:01:52 -080077 pub fn first(&self) -> Option<Pair<&T, &P>> {
David Tolnay51382052017-12-27 13:46:21 -050078 self.inner.first().map(|&(ref t, ref d)| match *d {
David Tolnay56080682018-01-06 14:01:52 -080079 Some(ref d) => Pair::Punctuated(t, d),
80 None => Pair::End(t),
Alex Crichton0aa50e02017-07-07 20:59:03 -070081 })
82 }
83
David Tolnayf3198012018-01-06 20:00:42 -080084 /// Borrows the last punctuated pair in this sequence.
David Tolnay56080682018-01-06 14:01:52 -080085 pub fn last(&self) -> Option<Pair<&T, &P>> {
David Tolnay51382052017-12-27 13:46:21 -050086 self.inner.last().map(|&(ref t, ref d)| match *d {
David Tolnay56080682018-01-06 14:01:52 -080087 Some(ref d) => Pair::Punctuated(t, d),
88 None => Pair::End(t),
Alex Crichton0aa50e02017-07-07 20:59:03 -070089 })
90 }
91
David Tolnayf3198012018-01-06 20:00:42 -080092 /// Mutably borrows the last punctuated pair in this sequence.
David Tolnay56080682018-01-06 14:01:52 -080093 pub fn last_mut(&mut self) -> Option<Pair<&mut T, &mut P>> {
David Tolnay51382052017-12-27 13:46:21 -050094 self.inner
95 .last_mut()
96 .map(|&mut (ref mut t, ref mut d)| match *d {
David Tolnay56080682018-01-06 14:01:52 -080097 Some(ref mut d) => Pair::Punctuated(t, d),
98 None => Pair::End(t),
David Tolnay51382052017-12-27 13:46:21 -050099 })
Alex Crichton0aa50e02017-07-07 20:59:03 -0700100 }
101
David Tolnayf3198012018-01-06 20:00:42 -0800102 /// Returns an iterator over borrowed syntax tree nodes of type `&T`.
David Tolnayf2cfd722017-12-31 18:02:51 -0500103 pub fn iter(&self) -> Iter<T, P> {
David Tolnay51382052017-12-27 13:46:21 -0500104 Iter {
105 inner: self.inner.iter(),
106 }
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700107 }
108
David Tolnayf3198012018-01-06 20:00:42 -0800109 /// Returns an iterator over mutably borrowed syntax tree nodes of type
110 /// `&mut T`.
David Tolnaya0834b42018-01-01 21:30:02 -0800111 pub fn iter_mut(&mut self) -> IterMut<T, P> {
112 IterMut {
113 inner: self.inner.iter_mut(),
114 }
115 }
116
David Tolnayf3198012018-01-06 20:00:42 -0800117 /// Returns an iterator over the contents of this sequence as borrowed
118 /// punctuated pairs.
David Tolnay56080682018-01-06 14:01:52 -0800119 pub fn pairs(&self) -> Pairs<T, P> {
120 Pairs {
David Tolnay6eff4da2018-01-01 20:27:45 -0800121 inner: self.inner.iter(),
122 }
123 }
124
David Tolnayf3198012018-01-06 20:00:42 -0800125 /// Returns an iterator over the contents of this sequence as mutably
126 /// borrowed punctuated pairs.
David Tolnay56080682018-01-06 14:01:52 -0800127 pub fn pairs_mut(&mut self) -> PairsMut<T, P> {
128 PairsMut {
David Tolnay51382052017-12-27 13:46:21 -0500129 inner: self.inner.iter_mut(),
130 }
Alex Crichton164c5332017-07-06 13:18:34 -0700131 }
132
David Tolnayf3198012018-01-06 20:00:42 -0800133 /// Returns an iterator over the contents of this sequence as owned
134 /// punctuated pairs.
David Tolnay56080682018-01-06 14:01:52 -0800135 pub fn into_pairs(self) -> IntoPairs<T, P> {
136 IntoPairs {
David Tolnay6eff4da2018-01-01 20:27:45 -0800137 inner: self.inner.into_iter(),
138 }
139 }
140
David Tolnayf3198012018-01-06 20:00:42 -0800141 /// Appends a syntax tree node onto the end of this punctuated sequence. The
142 /// sequence must previously have a trailing punctuation.
143 ///
144 /// Use [`push`] instead if the punctuated sequence may or may not already
145 /// have trailing punctuation.
146 ///
147 /// [`push`]: #method.push
148 ///
149 /// # Panics
150 ///
151 /// Panics if the sequence does not already have a trailing punctuation when
152 /// this method is called.
David Tolnay56080682018-01-06 14:01:52 -0800153 pub fn push_value(&mut self, value: T) {
David Tolnaydc03aec2017-12-30 01:54:18 -0500154 assert!(self.empty_or_trailing());
David Tolnay56080682018-01-06 14:01:52 -0800155 self.inner.push((value, None));
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700156 }
157
David Tolnayf3198012018-01-06 20:00:42 -0800158 /// Appends a trailing punctuation onto the end of this punctuated sequence.
159 /// The sequence must be non-empty and must not already have trailing
160 /// punctuation.
161 ///
162 /// # Panics
163 ///
164 /// Panics if the sequence is empty or already has a trailing punctuation.
David Tolnaya0834b42018-01-01 21:30:02 -0800165 pub fn push_punct(&mut self, punctuation: P) {
David Tolnay660fd1f2017-12-31 01:52:57 -0500166 assert!(!self.is_empty());
167 let last = self.inner.last_mut().unwrap();
168 assert!(last.1.is_none());
David Tolnayf2cfd722017-12-31 18:02:51 -0500169 last.1 = Some(punctuation);
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700170 }
171
David Tolnayf3198012018-01-06 20:00:42 -0800172 /// Removes the last punctuated pair from this sequence, or `None` if the
173 /// sequence is empty.
David Tolnay56080682018-01-06 14:01:52 -0800174 pub fn pop(&mut self) -> Option<Pair<T, P>> {
175 self.inner.pop().map(|(t, d)| Pair::new(t, d))
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700176 }
177
David Tolnayf3198012018-01-06 20:00:42 -0800178 /// Determines whether this punctuated sequence ends with a trailing
179 /// punctuation.
David Tolnaya0834b42018-01-01 21:30:02 -0800180 pub fn trailing_punct(&self) -> bool {
David Tolnay61037c62018-01-05 16:21:03 -0800181 self.inner
182 .last()
183 .map(|last| last.1.is_some())
184 .unwrap_or(false)
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700185 }
Michael Layzell3936ceb2017-07-08 00:28:36 -0400186
David Tolnayf2cfd722017-12-31 18:02:51 -0500187 /// Returns true if either this `Punctuated` is empty, or it has a trailing
188 /// punctuation.
David Tolnaydc03aec2017-12-30 01:54:18 -0500189 ///
David Tolnaya0834b42018-01-01 21:30:02 -0800190 /// Equivalent to `punctuated.is_empty() || punctuated.trailing_punct()`.
Michael Layzell3936ceb2017-07-08 00:28:36 -0400191 pub fn empty_or_trailing(&self) -> bool {
David Tolnay61037c62018-01-05 16:21:03 -0800192 self.inner
193 .last()
194 .map(|last| last.1.is_some())
195 .unwrap_or(true)
Michael Layzell3936ceb2017-07-08 00:28:36 -0400196 }
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700197}
198
David Tolnaya0834b42018-01-01 21:30:02 -0800199impl<T, P> Punctuated<T, P>
200where
201 P: Default,
202{
David Tolnayf3198012018-01-06 20:00:42 -0800203 /// Appends a syntax tree node onto the end of this punctuated sequence.
204 ///
205 /// If there is not a trailing punctuation in this sequence when this method
206 /// is called, the default value of punctuation type `P` is inserted before
207 /// the given value of type `T`.
David Tolnay56080682018-01-06 14:01:52 -0800208 pub fn push(&mut self, value: T) {
David Tolnaya0834b42018-01-01 21:30:02 -0800209 if !self.empty_or_trailing() {
210 self.push_punct(Default::default());
211 }
David Tolnay56080682018-01-06 14:01:52 -0800212 self.push_value(value);
David Tolnaya0834b42018-01-01 21:30:02 -0800213 }
214}
215
Nika Layzelld73a3652017-10-24 08:57:05 -0400216#[cfg(feature = "extra-traits")]
David Tolnayf2cfd722017-12-31 18:02:51 -0500217impl<T: Debug, P: Debug> Debug for Punctuated<T, P> {
Nika Layzelld73a3652017-10-24 08:57:05 -0400218 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
219 self.inner.fmt(f)
220 }
221}
222
David Tolnay56080682018-01-06 14:01:52 -0800223impl<T, P> FromIterator<Pair<T, P>> for Punctuated<T, P> {
224 fn from_iter<I: IntoIterator<Item = Pair<T, P>>>(i: I) -> Self {
David Tolnayf2cfd722017-12-31 18:02:51 -0500225 let mut ret = Punctuated::new();
Alex Crichton24f12822017-07-14 07:15:32 -0700226 ret.extend(i);
Alex Crichton954046c2017-05-30 21:49:42 -0700227 ret
228 }
229}
230
David Tolnay56080682018-01-06 14:01:52 -0800231impl<T, P> Extend<Pair<T, P>> for Punctuated<T, P> {
232 fn extend<I: IntoIterator<Item = Pair<T, P>>>(&mut self, i: I) {
233 for pair in i {
234 match pair {
235 Pair::Punctuated(a, b) => self.inner.push((a, Some(b))),
236 Pair::End(a) => self.inner.push((a, None)),
Alex Crichton24f12822017-07-14 07:15:32 -0700237 }
238 }
239 }
240}
241
David Tolnayf2cfd722017-12-31 18:02:51 -0500242impl<T, P> IntoIterator for Punctuated<T, P> {
David Tolnay6eff4da2018-01-01 20:27:45 -0800243 type Item = T;
David Tolnayf2cfd722017-12-31 18:02:51 -0500244 type IntoIter = IntoIter<T, P>;
Alex Crichton954046c2017-05-30 21:49:42 -0700245
David Tolnaybb4ca9f2017-12-26 12:28:58 -0500246 fn into_iter(self) -> Self::IntoIter {
David Tolnay51382052017-12-27 13:46:21 -0500247 IntoIter {
248 inner: self.inner.into_iter(),
249 }
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700250 }
251}
252
David Tolnay6eff4da2018-01-01 20:27:45 -0800253impl<'a, T, P> IntoIterator for &'a Punctuated<T, P> {
254 type Item = &'a T;
255 type IntoIter = Iter<'a, T, P>;
256
257 fn into_iter(self) -> Self::IntoIter {
258 Punctuated::iter(self)
259 }
260}
261
David Tolnaya0834b42018-01-01 21:30:02 -0800262impl<'a, T, P> IntoIterator for &'a mut Punctuated<T, P> {
263 type Item = &'a mut T;
264 type IntoIter = IterMut<'a, T, P>;
265
266 fn into_iter(self) -> Self::IntoIter {
267 Punctuated::iter_mut(self)
268 }
269}
270
David Tolnayf2cfd722017-12-31 18:02:51 -0500271impl<T, P> Default for Punctuated<T, P> {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700272 fn default() -> Self {
David Tolnayf2cfd722017-12-31 18:02:51 -0500273 Punctuated::new()
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700274 }
275}
276
David Tolnayf3198012018-01-06 20:00:42 -0800277/// An iterator over borrowed pairs of type `Pair<&T, &P>`.
278///
279/// Refer to the [module documentation] for details about punctuated sequences.
280///
281/// [module documentation]: index.html
David Tolnay56080682018-01-06 14:01:52 -0800282pub struct Pairs<'a, T: 'a, P: 'a> {
David Tolnayf2cfd722017-12-31 18:02:51 -0500283 inner: slice::Iter<'a, (T, Option<P>)>,
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700284}
285
David Tolnay56080682018-01-06 14:01:52 -0800286impl<'a, T, P> Iterator for Pairs<'a, T, P> {
287 type Item = Pair<&'a T, &'a P>;
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700288
David Tolnay6eff4da2018-01-01 20:27:45 -0800289 fn next(&mut self) -> Option<Self::Item> {
David Tolnay51382052017-12-27 13:46:21 -0500290 self.inner.next().map(|pair| match pair.1 {
David Tolnay56080682018-01-06 14:01:52 -0800291 Some(ref p) => Pair::Punctuated(&pair.0, p),
292 None => Pair::End(&pair.0),
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700293 })
294 }
295}
296
David Tolnayf3198012018-01-06 20:00:42 -0800297/// An iterator over mutably borrowed pairs of type `Pair<&mut T, &mut P>`.
298///
299/// Refer to the [module documentation] for details about punctuated sequences.
300///
301/// [module documentation]: index.html
David Tolnay56080682018-01-06 14:01:52 -0800302pub struct PairsMut<'a, T: 'a, P: 'a> {
David Tolnayf2cfd722017-12-31 18:02:51 -0500303 inner: slice::IterMut<'a, (T, Option<P>)>,
Alex Crichton164c5332017-07-06 13:18:34 -0700304}
305
David Tolnay56080682018-01-06 14:01:52 -0800306impl<'a, T, P> Iterator for PairsMut<'a, T, P> {
307 type Item = Pair<&'a mut T, &'a mut P>;
Alex Crichton164c5332017-07-06 13:18:34 -0700308
David Tolnay6eff4da2018-01-01 20:27:45 -0800309 fn next(&mut self) -> Option<Self::Item> {
David Tolnay51382052017-12-27 13:46:21 -0500310 self.inner.next().map(|pair| match pair.1 {
David Tolnay56080682018-01-06 14:01:52 -0800311 Some(ref mut p) => Pair::Punctuated(&mut pair.0, p),
312 None => Pair::End(&mut pair.0),
Alex Crichton164c5332017-07-06 13:18:34 -0700313 })
314 }
315}
316
David Tolnayf3198012018-01-06 20:00:42 -0800317/// An iterator over owned pairs of type `Pair<T, P>`.
318///
319/// Refer to the [module documentation] for details about punctuated sequences.
320///
321/// [module documentation]: index.html
David Tolnay56080682018-01-06 14:01:52 -0800322pub struct IntoPairs<T, P> {
David Tolnay6eff4da2018-01-01 20:27:45 -0800323 inner: vec::IntoIter<(T, Option<P>)>,
324}
325
David Tolnay56080682018-01-06 14:01:52 -0800326impl<T, P> Iterator for IntoPairs<T, P> {
327 type Item = Pair<T, P>;
David Tolnay6eff4da2018-01-01 20:27:45 -0800328
329 fn next(&mut self) -> Option<Self::Item> {
330 self.inner.next().map(|pair| match pair.1 {
David Tolnay56080682018-01-06 14:01:52 -0800331 Some(p) => Pair::Punctuated(pair.0, p),
332 None => Pair::End(pair.0),
David Tolnay6eff4da2018-01-01 20:27:45 -0800333 })
334 }
335}
336
David Tolnayf3198012018-01-06 20:00:42 -0800337/// An iterator over owned values of type `T`.
338///
339/// Refer to the [module documentation] for details about punctuated sequences.
340///
341/// [module documentation]: index.html
David Tolnayf2cfd722017-12-31 18:02:51 -0500342pub struct IntoIter<T, P> {
343 inner: vec::IntoIter<(T, Option<P>)>,
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700344}
345
David Tolnayf2cfd722017-12-31 18:02:51 -0500346impl<T, P> Iterator for IntoIter<T, P> {
David Tolnay6eff4da2018-01-01 20:27:45 -0800347 type Item = T;
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700348
David Tolnay6eff4da2018-01-01 20:27:45 -0800349 fn next(&mut self) -> Option<Self::Item> {
350 self.inner.next().map(|pair| pair.0)
351 }
352}
353
David Tolnayf3198012018-01-06 20:00:42 -0800354/// An iterator over borrowed values of type `&T`.
355///
356/// Refer to the [module documentation] for details about punctuated sequences.
357///
358/// [module documentation]: index.html
David Tolnay6eff4da2018-01-01 20:27:45 -0800359pub struct Iter<'a, T: 'a, P: 'a> {
360 inner: slice::Iter<'a, (T, Option<P>)>,
361}
362
363impl<'a, T, P> Iterator for Iter<'a, T, P> {
364 type Item = &'a T;
365
366 fn next(&mut self) -> Option<Self::Item> {
367 self.inner.next().map(|pair| &pair.0)
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700368 }
369}
370
David Tolnayf3198012018-01-06 20:00:42 -0800371/// An iterator over mutably borrowed values of type `&mut T`.
372///
373/// Refer to the [module documentation] for details about punctuated sequences.
374///
375/// [module documentation]: index.html
David Tolnaya0834b42018-01-01 21:30:02 -0800376pub struct IterMut<'a, T: 'a, P: 'a> {
377 inner: slice::IterMut<'a, (T, Option<P>)>,
378}
379
380impl<'a, T, P> Iterator for IterMut<'a, T, P> {
381 type Item = &'a mut T;
382
383 fn next(&mut self) -> Option<Self::Item> {
384 self.inner.next().map(|pair| &mut pair.0)
385 }
386}
387
David Tolnayf3198012018-01-06 20:00:42 -0800388/// A single syntax tree node of type `T` followed by its trailing punctuation
389/// of type `P` if any.
390///
391/// Refer to the [module documentation] for details about punctuated sequences.
392///
393/// [module documentation]: index.html
David Tolnay56080682018-01-06 14:01:52 -0800394pub enum Pair<T, P> {
David Tolnayf2cfd722017-12-31 18:02:51 -0500395 Punctuated(T, P),
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700396 End(T),
397}
398
David Tolnay56080682018-01-06 14:01:52 -0800399impl<T, P> Pair<T, P> {
David Tolnayf3198012018-01-06 20:00:42 -0800400 /// Extracts the syntax tree node from this punctuated pair, discarding the
401 /// following punctuation.
David Tolnay56080682018-01-06 14:01:52 -0800402 pub fn into_value(self) -> T {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700403 match self {
David Tolnay56080682018-01-06 14:01:52 -0800404 Pair::Punctuated(t, _) | Pair::End(t) => t,
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700405 }
406 }
407
David Tolnayf3198012018-01-06 20:00:42 -0800408 /// Borrows the syntax tree node from this punctuated pair.
David Tolnay56080682018-01-06 14:01:52 -0800409 pub fn value(&self) -> &T {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700410 match *self {
David Tolnay56080682018-01-06 14:01:52 -0800411 Pair::Punctuated(ref t, _) | Pair::End(ref t) => t,
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700412 }
413 }
414
David Tolnayf3198012018-01-06 20:00:42 -0800415 /// Mutably borrows the syntax tree node from this punctuated pair.
David Tolnay56080682018-01-06 14:01:52 -0800416 pub fn value_mut(&mut self) -> &mut T {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700417 match *self {
David Tolnay56080682018-01-06 14:01:52 -0800418 Pair::Punctuated(ref mut t, _) | Pair::End(ref mut t) => t,
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700419 }
420 }
421
David Tolnayf3198012018-01-06 20:00:42 -0800422 /// Borrows the punctuation from this punctuated pair, unless this pair is
423 /// the final one and there is no trailing punctuation.
David Tolnayf2cfd722017-12-31 18:02:51 -0500424 pub fn punct(&self) -> Option<&P> {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700425 match *self {
David Tolnay56080682018-01-06 14:01:52 -0800426 Pair::Punctuated(_, ref d) => Some(d),
427 Pair::End(_) => None,
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700428 }
429 }
Nika Layzellcda7ebd2017-10-24 23:10:44 -0400430
David Tolnayf3198012018-01-06 20:00:42 -0800431 /// Creates a punctuated pair out of a syntax tree node and an optional
432 /// following punctuation.
David Tolnayf2cfd722017-12-31 18:02:51 -0500433 pub fn new(t: T, d: Option<P>) -> Self {
David Tolnay660fd1f2017-12-31 01:52:57 -0500434 match d {
David Tolnay56080682018-01-06 14:01:52 -0800435 Some(d) => Pair::Punctuated(t, d),
436 None => Pair::End(t),
David Tolnay660fd1f2017-12-31 01:52:57 -0500437 }
438 }
439
David Tolnayf3198012018-01-06 20:00:42 -0800440 /// Produces this punctuated pair as a tuple of syntax tree node and
441 /// optional following punctuation.
David Tolnayf2cfd722017-12-31 18:02:51 -0500442 pub fn into_tuple(self) -> (T, Option<P>) {
Nika Layzellcda7ebd2017-10-24 23:10:44 -0400443 match self {
David Tolnay56080682018-01-06 14:01:52 -0800444 Pair::Punctuated(t, d) => (t, Some(d)),
445 Pair::End(t) => (t, None),
Nika Layzellcda7ebd2017-10-24 23:10:44 -0400446 }
447 }
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700448}
449
David Tolnaybb987132018-01-08 13:51:19 -0800450impl<T, P> Index<usize> for Punctuated<T, P> {
451 type Output = T;
452
453 fn index(&self, index: usize) -> &Self::Output {
454 &self.inner[index].0
455 }
456}
457
458impl<T, P> IndexMut<usize> for Punctuated<T, P> {
459 fn index_mut(&mut self, index: usize) -> &mut Self::Output {
460 &mut self.inner[index].0
461 }
462}
463
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700464#[cfg(feature = "parsing")]
David Tolnayf3198012018-01-06 20:00:42 -0800465impl<T, P> Punctuated<T, P>
466where
467 T: Synom,
468 P: Synom,
469{
470 /// Parse **zero or more** syntax tree nodes with punctuation in between and
471 /// **no trailing** punctuation.
472 pub fn parse_separated(input: Cursor) -> PResult<Self> {
473 Self::parse_separated_with(input, T::parse)
474 }
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700475
David Tolnayf3198012018-01-06 20:00:42 -0800476 /// Parse **one or more** syntax tree nodes with punctuation in bewteen and
477 /// **no trailing** punctuation.
478 /// allowing trailing punctuation.
479 pub fn parse_separated_nonempty(input: Cursor) -> PResult<Self> {
480 Self::parse_separated_nonempty_with(input, T::parse)
481 }
Alex Crichton954046c2017-05-30 21:49:42 -0700482
David Tolnayf3198012018-01-06 20:00:42 -0800483 /// Parse **zero or more** syntax tree nodes with punctuation in between and
484 /// **optional trailing** punctuation.
485 pub fn parse_terminated(input: Cursor) -> PResult<Self> {
486 Self::parse_terminated_with(input, T::parse)
487 }
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700488
David Tolnayf3198012018-01-06 20:00:42 -0800489 /// Parse **one or more** syntax tree nodes with punctuation in between and
490 /// **optional trailing** punctuation.
491 pub fn parse_terminated_nonempty(input: Cursor) -> PResult<Self> {
492 Self::parse_terminated_nonempty_with(input, T::parse)
493 }
494}
Nika Layzellb49a9e52017-12-05 13:31:52 -0500495
David Tolnayf3198012018-01-06 20:00:42 -0800496#[cfg(feature = "parsing")]
497impl<T, P> Punctuated<T, P>
498where
499 P: Synom,
500{
501 /// Parse **zero or more** syntax tree nodes using the given parser with
502 /// punctuation in between and **no trailing** punctuation.
503 pub fn parse_separated_with(
504 input: Cursor,
505 parse: fn(Cursor) -> PResult<T>,
506 ) -> PResult<Self> {
507 Self::parse(input, parse, false)
508 }
509
510 /// Parse **one or more** syntax tree nodes using the given parser with
511 /// punctuation in between and **no trailing** punctuation.
512 pub fn parse_separated_nonempty_with(
513 input: Cursor,
514 parse: fn(Cursor) -> PResult<T>,
515 ) -> PResult<Self> {
516 match Self::parse(input, parse, false) {
517 Ok((ref b, _)) if b.is_empty() => parse_error(),
518 other => other,
Nika Layzellb49a9e52017-12-05 13:31:52 -0500519 }
Alex Crichton954046c2017-05-30 21:49:42 -0700520 }
521
David Tolnayf3198012018-01-06 20:00:42 -0800522 /// Parse **zero or more** syntax tree nodes using the given parser with
523 /// punctuation in between and **optional trailing** punctuation.
524 pub fn parse_terminated_with(
525 input: Cursor,
526 parse: fn(Cursor) -> PResult<T>,
527 ) -> PResult<Self> {
528 Self::parse(input, parse, true)
529 }
530
531 /// Parse **one or more** syntax tree nodes using the given parser with
532 /// punctuation in between and **optional trailing** punctuation.
533 pub fn parse_terminated_nonempty_with(
534 input: Cursor,
535 parse: fn(Cursor) -> PResult<T>,
536 ) -> PResult<Self> {
537 match Self::parse(input, parse, true) {
538 Ok((ref b, _)) if b.is_empty() => parse_error(),
539 other => other,
David Tolnaydc03aec2017-12-30 01:54:18 -0500540 }
David Tolnayf3198012018-01-06 20:00:42 -0800541 }
David Tolnaydc03aec2017-12-30 01:54:18 -0500542
David Tolnayf3198012018-01-06 20:00:42 -0800543 fn parse(
544 mut input: Cursor,
545 parse: fn(Cursor) -> PResult<T>,
546 terminated: bool,
547 ) -> PResult<Self> {
548 let mut res = Punctuated::new();
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700549
David Tolnayf3198012018-01-06 20:00:42 -0800550 // get the first element
551 match parse(input) {
552 Err(_) => Ok((res, input)),
553 Ok((o, i)) => {
554 if i == input {
555 return parse_error();
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700556 }
David Tolnayf3198012018-01-06 20:00:42 -0800557 input = i;
558 res.push_value(o);
559
560 // get the separator first
561 while let Ok((s, i2)) = P::parse(input) {
562 if i2 == input {
563 break;
564 }
565
566 // get the element next
567 if let Ok((o3, i3)) = parse(i2) {
568 if i3 == i2 {
569 break;
570 }
571 res.push_punct(s);
572 res.push_value(o3);
573 input = i3;
574 } else {
575 break;
576 }
577 }
578 if terminated {
579 if let Ok((sep, after)) = P::parse(input) {
580 res.push_punct(sep);
581 input = after;
582 }
583 }
584 Ok((res, input))
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700585 }
586 }
587 }
588}
589
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700590#[cfg(feature = "printing")]
591mod printing {
592 use super::*;
David Tolnay51382052017-12-27 13:46:21 -0500593 use quote::{ToTokens, Tokens};
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700594
David Tolnayf2cfd722017-12-31 18:02:51 -0500595 impl<T, P> ToTokens for Punctuated<T, P>
David Tolnay51382052017-12-27 13:46:21 -0500596 where
597 T: ToTokens,
David Tolnayf2cfd722017-12-31 18:02:51 -0500598 P: ToTokens,
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700599 {
600 fn to_tokens(&self, tokens: &mut Tokens) {
David Tolnay56080682018-01-06 14:01:52 -0800601 tokens.append_all(self.pairs())
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700602 }
603 }
604
David Tolnay56080682018-01-06 14:01:52 -0800605 impl<T, P> ToTokens for Pair<T, P>
David Tolnay51382052017-12-27 13:46:21 -0500606 where
607 T: ToTokens,
David Tolnayf2cfd722017-12-31 18:02:51 -0500608 P: ToTokens,
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700609 {
610 fn to_tokens(&self, tokens: &mut Tokens) {
611 match *self {
David Tolnay56080682018-01-06 14:01:52 -0800612 Pair::Punctuated(ref a, ref b) => {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700613 a.to_tokens(tokens);
614 b.to_tokens(tokens);
615 }
David Tolnay56080682018-01-06 14:01:52 -0800616 Pair::End(ref a) => a.to_tokens(tokens),
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700617 }
618 }
619 }
620}