punctuated.rs 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157
  1. // SPDX-License-Identifier: Apache-2.0 OR MIT
  2. //! A punctuated sequence of syntax tree nodes separated by punctuation.
  3. //!
  4. //! Lots of things in Rust are punctuated sequences.
  5. //!
  6. //! - The fields of a struct are `Punctuated<Field, Token![,]>`.
  7. //! - The segments of a path are `Punctuated<PathSegment, Token![::]>`.
  8. //! - The bounds on a generic parameter are `Punctuated<TypeParamBound,
  9. //! Token![+]>`.
  10. //! - The arguments to a function call are `Punctuated<Expr, Token![,]>`.
  11. //!
  12. //! This module provides a common representation for these punctuated sequences
  13. //! in the form of the [`Punctuated<T, P>`] type. We store a vector of pairs of
  14. //! syntax tree node + punctuation, where every node in the sequence is followed
  15. //! by punctuation except for possibly the final one.
  16. //!
  17. //! [`Punctuated<T, P>`]: Punctuated
  18. //!
  19. //! ```text
  20. //! a_function_call(arg1, arg2, arg3);
  21. //! ~~~~^ ~~~~^ ~~~~
  22. //! ```
  23. use crate::drops::{NoDrop, TrivialDrop};
  24. #[cfg(feature = "parsing")]
  25. use crate::error::Result;
  26. #[cfg(feature = "parsing")]
  27. use crate::parse::{Parse, ParseStream};
  28. #[cfg(feature = "parsing")]
  29. use crate::token::Token;
  30. #[cfg(feature = "extra-traits")]
  31. use std::fmt::{self, Debug};
  32. #[cfg(feature = "extra-traits")]
  33. use std::hash::{Hash, Hasher};
  34. #[cfg(any(feature = "full", feature = "derive"))]
  35. use std::iter;
  36. use std::ops::{Index, IndexMut};
  37. use std::option;
  38. use std::slice;
  39. use std::vec;
  40. /// **A punctuated sequence of syntax tree nodes of type `T` separated by
  41. /// punctuation of type `P`.**
  42. ///
  43. /// Refer to the [module documentation] for details about punctuated sequences.
  44. ///
  45. /// [module documentation]: self
  46. pub struct Punctuated<T, P> {
  47. inner: Vec<(T, P)>,
  48. last: Option<Box<T>>,
  49. }
  50. impl<T, P> Punctuated<T, P> {
  51. /// Creates an empty punctuated sequence.
  52. pub const fn new() -> Self {
  53. Punctuated {
  54. inner: Vec::new(),
  55. last: None,
  56. }
  57. }
  58. /// Determines whether this punctuated sequence is empty, meaning it
  59. /// contains no syntax tree nodes or punctuation.
  60. pub fn is_empty(&self) -> bool {
  61. self.inner.len() == 0 && self.last.is_none()
  62. }
  63. /// Returns the number of syntax tree nodes in this punctuated sequence.
  64. ///
  65. /// This is the number of nodes of type `T`, not counting the punctuation of
  66. /// type `P`.
  67. pub fn len(&self) -> usize {
  68. self.inner.len() + if self.last.is_some() { 1 } else { 0 }
  69. }
  70. /// Borrows the first element in this sequence.
  71. pub fn first(&self) -> Option<&T> {
  72. self.iter().next()
  73. }
  74. /// Mutably borrows the first element in this sequence.
  75. pub fn first_mut(&mut self) -> Option<&mut T> {
  76. self.iter_mut().next()
  77. }
  78. /// Borrows the last element in this sequence.
  79. pub fn last(&self) -> Option<&T> {
  80. self.iter().next_back()
  81. }
  82. /// Mutably borrows the last element in this sequence.
  83. pub fn last_mut(&mut self) -> Option<&mut T> {
  84. self.iter_mut().next_back()
  85. }
  86. /// Borrows the element at the given index.
  87. pub fn get(&self, index: usize) -> Option<&T> {
  88. if let Some((value, _punct)) = self.inner.get(index) {
  89. Some(value)
  90. } else if index == self.inner.len() {
  91. self.last.as_deref()
  92. } else {
  93. None
  94. }
  95. }
  96. /// Mutably borrows the element at the given index.
  97. pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
  98. let inner_len = self.inner.len();
  99. if let Some((value, _punct)) = self.inner.get_mut(index) {
  100. Some(value)
  101. } else if index == inner_len {
  102. self.last.as_deref_mut()
  103. } else {
  104. None
  105. }
  106. }
  107. /// Returns an iterator over borrowed syntax tree nodes of type `&T`.
  108. pub fn iter(&self) -> Iter<T> {
  109. Iter {
  110. inner: Box::new(NoDrop::new(PrivateIter {
  111. inner: self.inner.iter(),
  112. last: self.last.as_ref().map(Box::as_ref).into_iter(),
  113. })),
  114. }
  115. }
  116. /// Returns an iterator over mutably borrowed syntax tree nodes of type
  117. /// `&mut T`.
  118. pub fn iter_mut(&mut self) -> IterMut<T> {
  119. IterMut {
  120. inner: Box::new(NoDrop::new(PrivateIterMut {
  121. inner: self.inner.iter_mut(),
  122. last: self.last.as_mut().map(Box::as_mut).into_iter(),
  123. })),
  124. }
  125. }
  126. /// Returns an iterator over the contents of this sequence as borrowed
  127. /// punctuated pairs.
  128. pub fn pairs(&self) -> Pairs<T, P> {
  129. Pairs {
  130. inner: self.inner.iter(),
  131. last: self.last.as_ref().map(Box::as_ref).into_iter(),
  132. }
  133. }
  134. /// Returns an iterator over the contents of this sequence as mutably
  135. /// borrowed punctuated pairs.
  136. pub fn pairs_mut(&mut self) -> PairsMut<T, P> {
  137. PairsMut {
  138. inner: self.inner.iter_mut(),
  139. last: self.last.as_mut().map(Box::as_mut).into_iter(),
  140. }
  141. }
  142. /// Returns an iterator over the contents of this sequence as owned
  143. /// punctuated pairs.
  144. pub fn into_pairs(self) -> IntoPairs<T, P> {
  145. IntoPairs {
  146. inner: self.inner.into_iter(),
  147. last: self.last.map(|t| *t).into_iter(),
  148. }
  149. }
  150. /// Appends a syntax tree node onto the end of this punctuated sequence. The
  151. /// sequence must already have a trailing punctuation, or be empty.
  152. ///
  153. /// Use [`push`] instead if the punctuated sequence may or may not already
  154. /// have trailing punctuation.
  155. ///
  156. /// [`push`]: Punctuated::push
  157. ///
  158. /// # Panics
  159. ///
  160. /// Panics if the sequence is nonempty and does not already have a trailing
  161. /// punctuation.
  162. pub fn push_value(&mut self, value: T) {
  163. assert!(
  164. self.empty_or_trailing(),
  165. "Punctuated::push_value: cannot push value if Punctuated is missing trailing punctuation",
  166. );
  167. self.last = Some(Box::new(value));
  168. }
  169. /// Appends a trailing punctuation onto the end of this punctuated sequence.
  170. /// The sequence must be non-empty and must not already have trailing
  171. /// punctuation.
  172. ///
  173. /// # Panics
  174. ///
  175. /// Panics if the sequence is empty or already has a trailing punctuation.
  176. pub fn push_punct(&mut self, punctuation: P) {
  177. assert!(
  178. self.last.is_some(),
  179. "Punctuated::push_punct: cannot push punctuation if Punctuated is empty or already has trailing punctuation",
  180. );
  181. let last = self.last.take().unwrap();
  182. self.inner.push((*last, punctuation));
  183. }
  184. /// Removes the last punctuated pair from this sequence, or `None` if the
  185. /// sequence is empty.
  186. pub fn pop(&mut self) -> Option<Pair<T, P>> {
  187. if self.last.is_some() {
  188. self.last.take().map(|t| Pair::End(*t))
  189. } else {
  190. self.inner.pop().map(|(t, p)| Pair::Punctuated(t, p))
  191. }
  192. }
  193. /// Removes the trailing punctuation from this punctuated sequence, or
  194. /// `None` if there isn't any.
  195. pub fn pop_punct(&mut self) -> Option<P> {
  196. if self.last.is_some() {
  197. None
  198. } else {
  199. let (t, p) = self.inner.pop()?;
  200. self.last = Some(Box::new(t));
  201. Some(p)
  202. }
  203. }
  204. /// Determines whether this punctuated sequence ends with a trailing
  205. /// punctuation.
  206. pub fn trailing_punct(&self) -> bool {
  207. self.last.is_none() && !self.is_empty()
  208. }
  209. /// Returns true if either this `Punctuated` is empty, or it has a trailing
  210. /// punctuation.
  211. ///
  212. /// Equivalent to `punctuated.is_empty() || punctuated.trailing_punct()`.
  213. pub fn empty_or_trailing(&self) -> bool {
  214. self.last.is_none()
  215. }
  216. /// Appends a syntax tree node onto the end of this punctuated sequence.
  217. ///
  218. /// If there is not a trailing punctuation in this sequence when this method
  219. /// is called, the default value of punctuation type `P` is inserted before
  220. /// the given value of type `T`.
  221. pub fn push(&mut self, value: T)
  222. where
  223. P: Default,
  224. {
  225. if !self.empty_or_trailing() {
  226. self.push_punct(Default::default());
  227. }
  228. self.push_value(value);
  229. }
  230. /// Inserts an element at position `index`.
  231. ///
  232. /// # Panics
  233. ///
  234. /// Panics if `index` is greater than the number of elements previously in
  235. /// this punctuated sequence.
  236. pub fn insert(&mut self, index: usize, value: T)
  237. where
  238. P: Default,
  239. {
  240. assert!(
  241. index <= self.len(),
  242. "Punctuated::insert: index out of range",
  243. );
  244. if index == self.len() {
  245. self.push(value);
  246. } else {
  247. self.inner.insert(index, (value, Default::default()));
  248. }
  249. }
  250. /// Clears the sequence of all values and punctuation, making it empty.
  251. pub fn clear(&mut self) {
  252. self.inner.clear();
  253. self.last = None;
  254. }
  255. /// Parses zero or more occurrences of `T` separated by punctuation of type
  256. /// `P`, with optional trailing punctuation.
  257. ///
  258. /// Parsing continues until the end of this parse stream. The entire content
  259. /// of this parse stream must consist of `T` and `P`.
  260. #[cfg(feature = "parsing")]
  261. #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
  262. pub fn parse_terminated(input: ParseStream) -> Result<Self>
  263. where
  264. T: Parse,
  265. P: Parse,
  266. {
  267. Self::parse_terminated_with(input, T::parse)
  268. }
  269. /// Parses zero or more occurrences of `T` using the given parse function,
  270. /// separated by punctuation of type `P`, with optional trailing
  271. /// punctuation.
  272. ///
  273. /// Like [`parse_terminated`], the entire content of this stream is expected
  274. /// to be parsed.
  275. ///
  276. /// [`parse_terminated`]: Punctuated::parse_terminated
  277. #[cfg(feature = "parsing")]
  278. #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
  279. pub fn parse_terminated_with<'a>(
  280. input: ParseStream<'a>,
  281. parser: fn(ParseStream<'a>) -> Result<T>,
  282. ) -> Result<Self>
  283. where
  284. P: Parse,
  285. {
  286. let mut punctuated = Punctuated::new();
  287. loop {
  288. if input.is_empty() {
  289. break;
  290. }
  291. let value = parser(input)?;
  292. punctuated.push_value(value);
  293. if input.is_empty() {
  294. break;
  295. }
  296. let punct = input.parse()?;
  297. punctuated.push_punct(punct);
  298. }
  299. Ok(punctuated)
  300. }
  301. /// Parses one or more occurrences of `T` separated by punctuation of type
  302. /// `P`, not accepting trailing punctuation.
  303. ///
  304. /// Parsing continues as long as punctuation `P` is present at the head of
  305. /// the stream. This method returns upon parsing a `T` and observing that it
  306. /// is not followed by a `P`, even if there are remaining tokens in the
  307. /// stream.
  308. #[cfg(feature = "parsing")]
  309. #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
  310. pub fn parse_separated_nonempty(input: ParseStream) -> Result<Self>
  311. where
  312. T: Parse,
  313. P: Token + Parse,
  314. {
  315. Self::parse_separated_nonempty_with(input, T::parse)
  316. }
  317. /// Parses one or more occurrences of `T` using the given parse function,
  318. /// separated by punctuation of type `P`, not accepting trailing
  319. /// punctuation.
  320. ///
  321. /// Like [`parse_separated_nonempty`], may complete early without parsing
  322. /// the entire content of this stream.
  323. ///
  324. /// [`parse_separated_nonempty`]: Punctuated::parse_separated_nonempty
  325. #[cfg(feature = "parsing")]
  326. #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
  327. pub fn parse_separated_nonempty_with<'a>(
  328. input: ParseStream<'a>,
  329. parser: fn(ParseStream<'a>) -> Result<T>,
  330. ) -> Result<Self>
  331. where
  332. P: Token + Parse,
  333. {
  334. let mut punctuated = Punctuated::new();
  335. loop {
  336. let value = parser(input)?;
  337. punctuated.push_value(value);
  338. if !P::peek(input.cursor()) {
  339. break;
  340. }
  341. let punct = input.parse()?;
  342. punctuated.push_punct(punct);
  343. }
  344. Ok(punctuated)
  345. }
  346. }
  347. #[cfg(feature = "clone-impls")]
  348. #[cfg_attr(docsrs, doc(cfg(feature = "clone-impls")))]
  349. impl<T, P> Clone for Punctuated<T, P>
  350. where
  351. T: Clone,
  352. P: Clone,
  353. {
  354. fn clone(&self) -> Self {
  355. Punctuated {
  356. inner: self.inner.clone(),
  357. last: self.last.clone(),
  358. }
  359. }
  360. fn clone_from(&mut self, other: &Self) {
  361. self.inner.clone_from(&other.inner);
  362. self.last.clone_from(&other.last);
  363. }
  364. }
  365. #[cfg(feature = "extra-traits")]
  366. #[cfg_attr(docsrs, doc(cfg(feature = "extra-traits")))]
  367. impl<T, P> Eq for Punctuated<T, P>
  368. where
  369. T: Eq,
  370. P: Eq,
  371. {
  372. }
  373. #[cfg(feature = "extra-traits")]
  374. #[cfg_attr(docsrs, doc(cfg(feature = "extra-traits")))]
  375. impl<T, P> PartialEq for Punctuated<T, P>
  376. where
  377. T: PartialEq,
  378. P: PartialEq,
  379. {
  380. fn eq(&self, other: &Self) -> bool {
  381. let Punctuated { inner, last } = self;
  382. *inner == other.inner && *last == other.last
  383. }
  384. }
  385. #[cfg(feature = "extra-traits")]
  386. #[cfg_attr(docsrs, doc(cfg(feature = "extra-traits")))]
  387. impl<T, P> Hash for Punctuated<T, P>
  388. where
  389. T: Hash,
  390. P: Hash,
  391. {
  392. fn hash<H: Hasher>(&self, state: &mut H) {
  393. let Punctuated { inner, last } = self;
  394. inner.hash(state);
  395. last.hash(state);
  396. }
  397. }
  398. #[cfg(feature = "extra-traits")]
  399. #[cfg_attr(docsrs, doc(cfg(feature = "extra-traits")))]
  400. impl<T: Debug, P: Debug> Debug for Punctuated<T, P> {
  401. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  402. let mut list = f.debug_list();
  403. for (t, p) in &self.inner {
  404. list.entry(t);
  405. list.entry(p);
  406. }
  407. if let Some(last) = &self.last {
  408. list.entry(last);
  409. }
  410. list.finish()
  411. }
  412. }
  413. impl<T, P> FromIterator<T> for Punctuated<T, P>
  414. where
  415. P: Default,
  416. {
  417. fn from_iter<I: IntoIterator<Item = T>>(i: I) -> Self {
  418. let mut ret = Punctuated::new();
  419. ret.extend(i);
  420. ret
  421. }
  422. }
  423. impl<T, P> Extend<T> for Punctuated<T, P>
  424. where
  425. P: Default,
  426. {
  427. fn extend<I: IntoIterator<Item = T>>(&mut self, i: I) {
  428. for value in i {
  429. self.push(value);
  430. }
  431. }
  432. }
  433. impl<T, P> FromIterator<Pair<T, P>> for Punctuated<T, P> {
  434. fn from_iter<I: IntoIterator<Item = Pair<T, P>>>(i: I) -> Self {
  435. let mut ret = Punctuated::new();
  436. do_extend(&mut ret, i.into_iter());
  437. ret
  438. }
  439. }
  440. impl<T, P> Extend<Pair<T, P>> for Punctuated<T, P>
  441. where
  442. P: Default,
  443. {
  444. fn extend<I: IntoIterator<Item = Pair<T, P>>>(&mut self, i: I) {
  445. if !self.empty_or_trailing() {
  446. self.push_punct(P::default());
  447. }
  448. do_extend(self, i.into_iter());
  449. }
  450. }
  451. fn do_extend<T, P, I>(punctuated: &mut Punctuated<T, P>, i: I)
  452. where
  453. I: Iterator<Item = Pair<T, P>>,
  454. {
  455. let mut nomore = false;
  456. for pair in i {
  457. if nomore {
  458. panic!("punctuated extended with items after a Pair::End");
  459. }
  460. match pair {
  461. Pair::Punctuated(a, b) => punctuated.inner.push((a, b)),
  462. Pair::End(a) => {
  463. punctuated.last = Some(Box::new(a));
  464. nomore = true;
  465. }
  466. }
  467. }
  468. }
  469. impl<T, P> IntoIterator for Punctuated<T, P> {
  470. type Item = T;
  471. type IntoIter = IntoIter<T>;
  472. fn into_iter(self) -> Self::IntoIter {
  473. let mut elements = Vec::with_capacity(self.len());
  474. elements.extend(self.inner.into_iter().map(|pair| pair.0));
  475. elements.extend(self.last.map(|t| *t));
  476. IntoIter {
  477. inner: elements.into_iter(),
  478. }
  479. }
  480. }
  481. impl<'a, T, P> IntoIterator for &'a Punctuated<T, P> {
  482. type Item = &'a T;
  483. type IntoIter = Iter<'a, T>;
  484. fn into_iter(self) -> Self::IntoIter {
  485. Punctuated::iter(self)
  486. }
  487. }
  488. impl<'a, T, P> IntoIterator for &'a mut Punctuated<T, P> {
  489. type Item = &'a mut T;
  490. type IntoIter = IterMut<'a, T>;
  491. fn into_iter(self) -> Self::IntoIter {
  492. Punctuated::iter_mut(self)
  493. }
  494. }
  495. impl<T, P> Default for Punctuated<T, P> {
  496. fn default() -> Self {
  497. Punctuated::new()
  498. }
  499. }
  500. /// An iterator over borrowed pairs of type `Pair<&T, &P>`.
  501. ///
  502. /// Refer to the [module documentation] for details about punctuated sequences.
  503. ///
  504. /// [module documentation]: self
  505. pub struct Pairs<'a, T: 'a, P: 'a> {
  506. inner: slice::Iter<'a, (T, P)>,
  507. last: option::IntoIter<&'a T>,
  508. }
  509. impl<'a, T, P> Iterator for Pairs<'a, T, P> {
  510. type Item = Pair<&'a T, &'a P>;
  511. fn next(&mut self) -> Option<Self::Item> {
  512. self.inner
  513. .next()
  514. .map(|(t, p)| Pair::Punctuated(t, p))
  515. .or_else(|| self.last.next().map(Pair::End))
  516. }
  517. fn size_hint(&self) -> (usize, Option<usize>) {
  518. (self.len(), Some(self.len()))
  519. }
  520. }
  521. impl<'a, T, P> DoubleEndedIterator for Pairs<'a, T, P> {
  522. fn next_back(&mut self) -> Option<Self::Item> {
  523. self.last
  524. .next()
  525. .map(Pair::End)
  526. .or_else(|| self.inner.next_back().map(|(t, p)| Pair::Punctuated(t, p)))
  527. }
  528. }
  529. impl<'a, T, P> ExactSizeIterator for Pairs<'a, T, P> {
  530. fn len(&self) -> usize {
  531. self.inner.len() + self.last.len()
  532. }
  533. }
  534. // No Clone bound on T or P.
  535. impl<'a, T, P> Clone for Pairs<'a, T, P> {
  536. fn clone(&self) -> Self {
  537. Pairs {
  538. inner: self.inner.clone(),
  539. last: self.last.clone(),
  540. }
  541. }
  542. }
  543. /// An iterator over mutably borrowed pairs of type `Pair<&mut T, &mut P>`.
  544. ///
  545. /// Refer to the [module documentation] for details about punctuated sequences.
  546. ///
  547. /// [module documentation]: self
  548. pub struct PairsMut<'a, T: 'a, P: 'a> {
  549. inner: slice::IterMut<'a, (T, P)>,
  550. last: option::IntoIter<&'a mut T>,
  551. }
  552. impl<'a, T, P> Iterator for PairsMut<'a, T, P> {
  553. type Item = Pair<&'a mut T, &'a mut P>;
  554. fn next(&mut self) -> Option<Self::Item> {
  555. self.inner
  556. .next()
  557. .map(|(t, p)| Pair::Punctuated(t, p))
  558. .or_else(|| self.last.next().map(Pair::End))
  559. }
  560. fn size_hint(&self) -> (usize, Option<usize>) {
  561. (self.len(), Some(self.len()))
  562. }
  563. }
  564. impl<'a, T, P> DoubleEndedIterator for PairsMut<'a, T, P> {
  565. fn next_back(&mut self) -> Option<Self::Item> {
  566. self.last
  567. .next()
  568. .map(Pair::End)
  569. .or_else(|| self.inner.next_back().map(|(t, p)| Pair::Punctuated(t, p)))
  570. }
  571. }
  572. impl<'a, T, P> ExactSizeIterator for PairsMut<'a, T, P> {
  573. fn len(&self) -> usize {
  574. self.inner.len() + self.last.len()
  575. }
  576. }
  577. /// An iterator over owned pairs of type `Pair<T, P>`.
  578. ///
  579. /// Refer to the [module documentation] for details about punctuated sequences.
  580. ///
  581. /// [module documentation]: self
  582. pub struct IntoPairs<T, P> {
  583. inner: vec::IntoIter<(T, P)>,
  584. last: option::IntoIter<T>,
  585. }
  586. impl<T, P> Iterator for IntoPairs<T, P> {
  587. type Item = Pair<T, P>;
  588. fn next(&mut self) -> Option<Self::Item> {
  589. self.inner
  590. .next()
  591. .map(|(t, p)| Pair::Punctuated(t, p))
  592. .or_else(|| self.last.next().map(Pair::End))
  593. }
  594. fn size_hint(&self) -> (usize, Option<usize>) {
  595. (self.len(), Some(self.len()))
  596. }
  597. }
  598. impl<T, P> DoubleEndedIterator for IntoPairs<T, P> {
  599. fn next_back(&mut self) -> Option<Self::Item> {
  600. self.last
  601. .next()
  602. .map(Pair::End)
  603. .or_else(|| self.inner.next_back().map(|(t, p)| Pair::Punctuated(t, p)))
  604. }
  605. }
  606. impl<T, P> ExactSizeIterator for IntoPairs<T, P> {
  607. fn len(&self) -> usize {
  608. self.inner.len() + self.last.len()
  609. }
  610. }
  611. impl<T, P> Clone for IntoPairs<T, P>
  612. where
  613. T: Clone,
  614. P: Clone,
  615. {
  616. fn clone(&self) -> Self {
  617. IntoPairs {
  618. inner: self.inner.clone(),
  619. last: self.last.clone(),
  620. }
  621. }
  622. }
  623. /// An iterator over owned values of type `T`.
  624. ///
  625. /// Refer to the [module documentation] for details about punctuated sequences.
  626. ///
  627. /// [module documentation]: self
  628. pub struct IntoIter<T> {
  629. inner: vec::IntoIter<T>,
  630. }
  631. impl<T> Iterator for IntoIter<T> {
  632. type Item = T;
  633. fn next(&mut self) -> Option<Self::Item> {
  634. self.inner.next()
  635. }
  636. fn size_hint(&self) -> (usize, Option<usize>) {
  637. (self.len(), Some(self.len()))
  638. }
  639. }
  640. impl<T> DoubleEndedIterator for IntoIter<T> {
  641. fn next_back(&mut self) -> Option<Self::Item> {
  642. self.inner.next_back()
  643. }
  644. }
  645. impl<T> ExactSizeIterator for IntoIter<T> {
  646. fn len(&self) -> usize {
  647. self.inner.len()
  648. }
  649. }
  650. impl<T> Clone for IntoIter<T>
  651. where
  652. T: Clone,
  653. {
  654. fn clone(&self) -> Self {
  655. IntoIter {
  656. inner: self.inner.clone(),
  657. }
  658. }
  659. }
  660. /// An iterator over borrowed values of type `&T`.
  661. ///
  662. /// Refer to the [module documentation] for details about punctuated sequences.
  663. ///
  664. /// [module documentation]: self
  665. pub struct Iter<'a, T: 'a> {
  666. inner: Box<NoDrop<dyn IterTrait<'a, T> + 'a>>,
  667. }
  668. trait IterTrait<'a, T: 'a>: Iterator<Item = &'a T> + DoubleEndedIterator + ExactSizeIterator {
  669. fn clone_box(&self) -> Box<NoDrop<dyn IterTrait<'a, T> + 'a>>;
  670. }
  671. struct PrivateIter<'a, T: 'a, P: 'a> {
  672. inner: slice::Iter<'a, (T, P)>,
  673. last: option::IntoIter<&'a T>,
  674. }
  675. impl<'a, T, P> TrivialDrop for PrivateIter<'a, T, P>
  676. where
  677. slice::Iter<'a, (T, P)>: TrivialDrop,
  678. option::IntoIter<&'a T>: TrivialDrop,
  679. {
  680. }
  681. #[cfg(any(feature = "full", feature = "derive"))]
  682. pub(crate) fn empty_punctuated_iter<'a, T>() -> Iter<'a, T> {
  683. Iter {
  684. inner: Box::new(NoDrop::new(iter::empty())),
  685. }
  686. }
  687. // No Clone bound on T.
  688. impl<'a, T> Clone for Iter<'a, T> {
  689. fn clone(&self) -> Self {
  690. Iter {
  691. inner: self.inner.clone_box(),
  692. }
  693. }
  694. }
  695. impl<'a, T> Iterator for Iter<'a, T> {
  696. type Item = &'a T;
  697. fn next(&mut self) -> Option<Self::Item> {
  698. self.inner.next()
  699. }
  700. fn size_hint(&self) -> (usize, Option<usize>) {
  701. (self.len(), Some(self.len()))
  702. }
  703. }
  704. impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
  705. fn next_back(&mut self) -> Option<Self::Item> {
  706. self.inner.next_back()
  707. }
  708. }
  709. impl<'a, T> ExactSizeIterator for Iter<'a, T> {
  710. fn len(&self) -> usize {
  711. self.inner.len()
  712. }
  713. }
  714. impl<'a, T, P> Iterator for PrivateIter<'a, T, P> {
  715. type Item = &'a T;
  716. fn next(&mut self) -> Option<Self::Item> {
  717. self.inner
  718. .next()
  719. .map(|pair| &pair.0)
  720. .or_else(|| self.last.next())
  721. }
  722. }
  723. impl<'a, T, P> DoubleEndedIterator for PrivateIter<'a, T, P> {
  724. fn next_back(&mut self) -> Option<Self::Item> {
  725. self.last
  726. .next()
  727. .or_else(|| self.inner.next_back().map(|pair| &pair.0))
  728. }
  729. }
  730. impl<'a, T, P> ExactSizeIterator for PrivateIter<'a, T, P> {
  731. fn len(&self) -> usize {
  732. self.inner.len() + self.last.len()
  733. }
  734. }
  735. // No Clone bound on T or P.
  736. impl<'a, T, P> Clone for PrivateIter<'a, T, P> {
  737. fn clone(&self) -> Self {
  738. PrivateIter {
  739. inner: self.inner.clone(),
  740. last: self.last.clone(),
  741. }
  742. }
  743. }
  744. impl<'a, T, I> IterTrait<'a, T> for I
  745. where
  746. T: 'a,
  747. I: DoubleEndedIterator<Item = &'a T>
  748. + ExactSizeIterator<Item = &'a T>
  749. + Clone
  750. + TrivialDrop
  751. + 'a,
  752. {
  753. fn clone_box(&self) -> Box<NoDrop<dyn IterTrait<'a, T> + 'a>> {
  754. Box::new(NoDrop::new(self.clone()))
  755. }
  756. }
  757. /// An iterator over mutably borrowed values of type `&mut T`.
  758. ///
  759. /// Refer to the [module documentation] for details about punctuated sequences.
  760. ///
  761. /// [module documentation]: self
  762. pub struct IterMut<'a, T: 'a> {
  763. inner: Box<NoDrop<dyn IterMutTrait<'a, T, Item = &'a mut T> + 'a>>,
  764. }
  765. trait IterMutTrait<'a, T: 'a>:
  766. DoubleEndedIterator<Item = &'a mut T> + ExactSizeIterator<Item = &'a mut T>
  767. {
  768. }
  769. struct PrivateIterMut<'a, T: 'a, P: 'a> {
  770. inner: slice::IterMut<'a, (T, P)>,
  771. last: option::IntoIter<&'a mut T>,
  772. }
  773. impl<'a, T, P> TrivialDrop for PrivateIterMut<'a, T, P>
  774. where
  775. slice::IterMut<'a, (T, P)>: TrivialDrop,
  776. option::IntoIter<&'a mut T>: TrivialDrop,
  777. {
  778. }
  779. #[cfg(any(feature = "full", feature = "derive"))]
  780. pub(crate) fn empty_punctuated_iter_mut<'a, T>() -> IterMut<'a, T> {
  781. IterMut {
  782. inner: Box::new(NoDrop::new(iter::empty())),
  783. }
  784. }
  785. impl<'a, T> Iterator for IterMut<'a, T> {
  786. type Item = &'a mut T;
  787. fn next(&mut self) -> Option<Self::Item> {
  788. self.inner.next()
  789. }
  790. fn size_hint(&self) -> (usize, Option<usize>) {
  791. (self.len(), Some(self.len()))
  792. }
  793. }
  794. impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
  795. fn next_back(&mut self) -> Option<Self::Item> {
  796. self.inner.next_back()
  797. }
  798. }
  799. impl<'a, T> ExactSizeIterator for IterMut<'a, T> {
  800. fn len(&self) -> usize {
  801. self.inner.len()
  802. }
  803. }
  804. impl<'a, T, P> Iterator for PrivateIterMut<'a, T, P> {
  805. type Item = &'a mut T;
  806. fn next(&mut self) -> Option<Self::Item> {
  807. self.inner
  808. .next()
  809. .map(|pair| &mut pair.0)
  810. .or_else(|| self.last.next())
  811. }
  812. }
  813. impl<'a, T, P> DoubleEndedIterator for PrivateIterMut<'a, T, P> {
  814. fn next_back(&mut self) -> Option<Self::Item> {
  815. self.last
  816. .next()
  817. .or_else(|| self.inner.next_back().map(|pair| &mut pair.0))
  818. }
  819. }
  820. impl<'a, T, P> ExactSizeIterator for PrivateIterMut<'a, T, P> {
  821. fn len(&self) -> usize {
  822. self.inner.len() + self.last.len()
  823. }
  824. }
  825. impl<'a, T, I> IterMutTrait<'a, T> for I
  826. where
  827. T: 'a,
  828. I: DoubleEndedIterator<Item = &'a mut T> + ExactSizeIterator<Item = &'a mut T> + 'a,
  829. {
  830. }
  831. /// A single syntax tree node of type `T` followed by its trailing punctuation
  832. /// of type `P` if any.
  833. ///
  834. /// Refer to the [module documentation] for details about punctuated sequences.
  835. ///
  836. /// [module documentation]: self
  837. pub enum Pair<T, P> {
  838. Punctuated(T, P),
  839. End(T),
  840. }
  841. impl<T, P> Pair<T, P> {
  842. /// Extracts the syntax tree node from this punctuated pair, discarding the
  843. /// following punctuation.
  844. pub fn into_value(self) -> T {
  845. match self {
  846. Pair::Punctuated(t, _) | Pair::End(t) => t,
  847. }
  848. }
  849. /// Borrows the syntax tree node from this punctuated pair.
  850. pub fn value(&self) -> &T {
  851. match self {
  852. Pair::Punctuated(t, _) | Pair::End(t) => t,
  853. }
  854. }
  855. /// Mutably borrows the syntax tree node from this punctuated pair.
  856. pub fn value_mut(&mut self) -> &mut T {
  857. match self {
  858. Pair::Punctuated(t, _) | Pair::End(t) => t,
  859. }
  860. }
  861. /// Borrows the punctuation from this punctuated pair, unless this pair is
  862. /// the final one and there is no trailing punctuation.
  863. pub fn punct(&self) -> Option<&P> {
  864. match self {
  865. Pair::Punctuated(_, p) => Some(p),
  866. Pair::End(_) => None,
  867. }
  868. }
  869. /// Mutably borrows the punctuation from this punctuated pair, unless the
  870. /// pair is the final one and there is no trailing punctuation.
  871. ///
  872. /// # Example
  873. ///
  874. /// ```
  875. /// # use proc_macro2::Span;
  876. /// # use syn::punctuated::Punctuated;
  877. /// # use syn::{parse_quote, Token, TypeParamBound};
  878. /// #
  879. /// # let mut punctuated = Punctuated::<TypeParamBound, Token![+]>::new();
  880. /// # let span = Span::call_site();
  881. /// #
  882. /// punctuated.insert(0, parse_quote!('lifetime));
  883. /// if let Some(punct) = punctuated.pairs_mut().next().unwrap().punct_mut() {
  884. /// punct.span = span;
  885. /// }
  886. /// ```
  887. pub fn punct_mut(&mut self) -> Option<&mut P> {
  888. match self {
  889. Pair::Punctuated(_, p) => Some(p),
  890. Pair::End(_) => None,
  891. }
  892. }
  893. /// Creates a punctuated pair out of a syntax tree node and an optional
  894. /// following punctuation.
  895. pub fn new(t: T, p: Option<P>) -> Self {
  896. match p {
  897. Some(p) => Pair::Punctuated(t, p),
  898. None => Pair::End(t),
  899. }
  900. }
  901. /// Produces this punctuated pair as a tuple of syntax tree node and
  902. /// optional following punctuation.
  903. pub fn into_tuple(self) -> (T, Option<P>) {
  904. match self {
  905. Pair::Punctuated(t, p) => (t, Some(p)),
  906. Pair::End(t) => (t, None),
  907. }
  908. }
  909. }
  910. #[cfg(feature = "clone-impls")]
  911. #[cfg_attr(docsrs, doc(cfg(feature = "clone-impls")))]
  912. impl<T, P> Pair<&T, &P> {
  913. pub fn cloned(self) -> Pair<T, P>
  914. where
  915. T: Clone,
  916. P: Clone,
  917. {
  918. match self {
  919. Pair::Punctuated(t, p) => Pair::Punctuated(t.clone(), p.clone()),
  920. Pair::End(t) => Pair::End(t.clone()),
  921. }
  922. }
  923. }
  924. #[cfg(feature = "clone-impls")]
  925. #[cfg_attr(docsrs, doc(cfg(feature = "clone-impls")))]
  926. impl<T, P> Clone for Pair<T, P>
  927. where
  928. T: Clone,
  929. P: Clone,
  930. {
  931. fn clone(&self) -> Self {
  932. match self {
  933. Pair::Punctuated(t, p) => Pair::Punctuated(t.clone(), p.clone()),
  934. Pair::End(t) => Pair::End(t.clone()),
  935. }
  936. }
  937. }
  938. #[cfg(feature = "clone-impls")]
  939. #[cfg_attr(docsrs, doc(cfg(feature = "clone-impls")))]
  940. impl<T, P> Copy for Pair<T, P>
  941. where
  942. T: Copy,
  943. P: Copy,
  944. {
  945. }
  946. impl<T, P> Index<usize> for Punctuated<T, P> {
  947. type Output = T;
  948. fn index(&self, index: usize) -> &Self::Output {
  949. if index == self.len() - 1 {
  950. match &self.last {
  951. Some(t) => t,
  952. None => &self.inner[index].0,
  953. }
  954. } else {
  955. &self.inner[index].0
  956. }
  957. }
  958. }
  959. impl<T, P> IndexMut<usize> for Punctuated<T, P> {
  960. fn index_mut(&mut self, index: usize) -> &mut Self::Output {
  961. if index == self.len() - 1 {
  962. match &mut self.last {
  963. Some(t) => t,
  964. None => &mut self.inner[index].0,
  965. }
  966. } else {
  967. &mut self.inner[index].0
  968. }
  969. }
  970. }
  971. #[cfg(all(feature = "fold", any(feature = "full", feature = "derive")))]
  972. pub(crate) fn fold<T, P, V, F>(
  973. punctuated: Punctuated<T, P>,
  974. fold: &mut V,
  975. mut f: F,
  976. ) -> Punctuated<T, P>
  977. where
  978. V: ?Sized,
  979. F: FnMut(&mut V, T) -> T,
  980. {
  981. Punctuated {
  982. inner: punctuated
  983. .inner
  984. .into_iter()
  985. .map(|(t, p)| (f(fold, t), p))
  986. .collect(),
  987. last: match punctuated.last {
  988. Some(t) => Some(Box::new(f(fold, *t))),
  989. None => None,
  990. },
  991. }
  992. }
  993. #[cfg(feature = "printing")]
  994. mod printing {
  995. use crate::punctuated::{Pair, Punctuated};
  996. use proc_macro2::TokenStream;
  997. use quote::{ToTokens, TokenStreamExt};
  998. #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
  999. impl<T, P> ToTokens for Punctuated<T, P>
  1000. where
  1001. T: ToTokens,
  1002. P: ToTokens,
  1003. {
  1004. fn to_tokens(&self, tokens: &mut TokenStream) {
  1005. tokens.append_all(self.pairs());
  1006. }
  1007. }
  1008. #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
  1009. impl<T, P> ToTokens for Pair<T, P>
  1010. where
  1011. T: ToTokens,
  1012. P: ToTokens,
  1013. {
  1014. fn to_tokens(&self, tokens: &mut TokenStream) {
  1015. match self {
  1016. Pair::Punctuated(a, b) => {
  1017. a.to_tokens(tokens);
  1018. b.to_tokens(tokens);
  1019. }
  1020. Pair::End(a) => a.to_tokens(tokens),
  1021. }
  1022. }
  1023. }
  1024. }