]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_ast/src/tokenstream.rs
Auto merge of #98866 - nagisa:nagisa/align-offset-wroom, r=Mark-Simulacrum
[rust.git] / compiler / rustc_ast / src / tokenstream.rs
1 //! # Token Streams
2 //!
3 //! `TokenStream`s represent syntactic objects before they are converted into ASTs.
4 //! A `TokenStream` is, roughly speaking, a sequence of [`TokenTree`]s,
5 //! which are themselves a single [`Token`] or a `Delimited` subsequence of tokens.
6 //!
7 //! ## Ownership
8 //!
9 //! `TokenStream`s are persistent data structures constructed as ropes with reference
10 //! counted-children. In general, this means that calling an operation on a `TokenStream`
11 //! (such as `slice`) produces an entirely new `TokenStream` from the borrowed reference to
12 //! the original. This essentially coerces `TokenStream`s into "views" of their subparts,
13 //! and a borrowed `TokenStream` is sufficient to build an owned `TokenStream` without taking
14 //! ownership of the original.
15
16 use crate::ast::StmtKind;
17 use crate::ast_traits::{HasAttrs, HasSpan, HasTokens};
18 use crate::token::{self, Delimiter, Nonterminal, Token, TokenKind};
19 use crate::AttrVec;
20
21 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
22 use rustc_data_structures::sync::{self, Lrc};
23 use rustc_macros::HashStable_Generic;
24 use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
25 use rustc_span::{Span, DUMMY_SP};
26 use smallvec::{smallvec, SmallVec};
27
28 use std::{fmt, iter};
29
30 /// When the main Rust parser encounters a syntax-extension invocation, it
31 /// parses the arguments to the invocation as a token tree. This is a very
32 /// loose structure, such that all sorts of different AST fragments can
33 /// be passed to syntax extensions using a uniform type.
34 ///
35 /// If the syntax extension is an MBE macro, it will attempt to match its
36 /// LHS token tree against the provided token tree, and if it finds a
37 /// match, will transcribe the RHS token tree, splicing in any captured
38 /// `macro_parser::matched_nonterminals` into the `SubstNt`s it finds.
39 ///
40 /// The RHS of an MBE macro is the only place `SubstNt`s are substituted.
41 /// Nothing special happens to misnamed or misplaced `SubstNt`s.
42 #[derive(Debug, Clone, PartialEq, Encodable, Decodable, HashStable_Generic)]
43 pub enum TokenTree {
44     /// A single token.
45     Token(Token),
46     /// A delimited sequence of token trees.
47     Delimited(DelimSpan, Delimiter, TokenStream),
48 }
49
50 // Ensure all fields of `TokenTree` is `Send` and `Sync`.
51 #[cfg(parallel_compiler)]
52 fn _dummy()
53 where
54     Token: Send + Sync,
55     DelimSpan: Send + Sync,
56     Delimiter: Send + Sync,
57     TokenStream: Send + Sync,
58 {
59 }
60
61 impl TokenTree {
62     /// Checks if this `TokenTree` is equal to the other, regardless of span information.
63     pub fn eq_unspanned(&self, other: &TokenTree) -> bool {
64         match (self, other) {
65             (TokenTree::Token(token), TokenTree::Token(token2)) => token.kind == token2.kind,
66             (TokenTree::Delimited(_, delim, tts), TokenTree::Delimited(_, delim2, tts2)) => {
67                 delim == delim2 && tts.eq_unspanned(&tts2)
68             }
69             _ => false,
70         }
71     }
72
73     /// Retrieves the `TokenTree`'s span.
74     pub fn span(&self) -> Span {
75         match self {
76             TokenTree::Token(token) => token.span,
77             TokenTree::Delimited(sp, ..) => sp.entire(),
78         }
79     }
80
81     /// Modify the `TokenTree`'s span in-place.
82     pub fn set_span(&mut self, span: Span) {
83         match self {
84             TokenTree::Token(token) => token.span = span,
85             TokenTree::Delimited(dspan, ..) => *dspan = DelimSpan::from_single(span),
86         }
87     }
88
89     pub fn token(kind: TokenKind, span: Span) -> TokenTree {
90         TokenTree::Token(Token::new(kind, span))
91     }
92
93     pub fn uninterpolate(self) -> TokenTree {
94         match self {
95             TokenTree::Token(token) => TokenTree::Token(token.uninterpolate().into_owned()),
96             tt => tt,
97         }
98     }
99 }
100
101 impl<CTX> HashStable<CTX> for TokenStream
102 where
103     CTX: crate::HashStableContext,
104 {
105     fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
106         for sub_tt in self.trees() {
107             sub_tt.hash_stable(hcx, hasher);
108         }
109     }
110 }
111
112 pub trait CreateTokenStream: sync::Send + sync::Sync {
113     fn create_token_stream(&self) -> AttrAnnotatedTokenStream;
114 }
115
116 impl CreateTokenStream for AttrAnnotatedTokenStream {
117     fn create_token_stream(&self) -> AttrAnnotatedTokenStream {
118         self.clone()
119     }
120 }
121
122 /// A lazy version of [`TokenStream`], which defers creation
123 /// of an actual `TokenStream` until it is needed.
124 /// `Box` is here only to reduce the structure size.
125 #[derive(Clone)]
126 pub struct LazyTokenStream(Lrc<Box<dyn CreateTokenStream>>);
127
128 impl LazyTokenStream {
129     pub fn new(inner: impl CreateTokenStream + 'static) -> LazyTokenStream {
130         LazyTokenStream(Lrc::new(Box::new(inner)))
131     }
132
133     pub fn create_token_stream(&self) -> AttrAnnotatedTokenStream {
134         self.0.create_token_stream()
135     }
136 }
137
138 impl fmt::Debug for LazyTokenStream {
139     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
140         write!(f, "LazyTokenStream({:?})", self.create_token_stream())
141     }
142 }
143
144 impl<S: Encoder> Encodable<S> for LazyTokenStream {
145     fn encode(&self, s: &mut S) {
146         // Used by AST json printing.
147         Encodable::encode(&self.create_token_stream(), s);
148     }
149 }
150
151 impl<D: Decoder> Decodable<D> for LazyTokenStream {
152     fn decode(_d: &mut D) -> Self {
153         panic!("Attempted to decode LazyTokenStream");
154     }
155 }
156
157 impl<CTX> HashStable<CTX> for LazyTokenStream {
158     fn hash_stable(&self, _hcx: &mut CTX, _hasher: &mut StableHasher) {
159         panic!("Attempted to compute stable hash for LazyTokenStream");
160     }
161 }
162
163 /// A `AttrAnnotatedTokenStream` is similar to a `TokenStream`, but with extra
164 /// information about the tokens for attribute targets. This is used
165 /// during expansion to perform early cfg-expansion, and to process attributes
166 /// during proc-macro invocations.
167 #[derive(Clone, Debug, Default, Encodable, Decodable)]
168 pub struct AttrAnnotatedTokenStream(pub Lrc<Vec<(AttrAnnotatedTokenTree, Spacing)>>);
169
170 /// Like `TokenTree`, but for `AttrAnnotatedTokenStream`
171 #[derive(Clone, Debug, Encodable, Decodable)]
172 pub enum AttrAnnotatedTokenTree {
173     Token(Token),
174     Delimited(DelimSpan, Delimiter, AttrAnnotatedTokenStream),
175     /// Stores the attributes for an attribute target,
176     /// along with the tokens for that attribute target.
177     /// See `AttributesData` for more information
178     Attributes(AttributesData),
179 }
180
181 impl AttrAnnotatedTokenStream {
182     pub fn new(tokens: Vec<(AttrAnnotatedTokenTree, Spacing)>) -> AttrAnnotatedTokenStream {
183         AttrAnnotatedTokenStream(Lrc::new(tokens))
184     }
185
186     /// Converts this `AttrAnnotatedTokenStream` to a plain `TokenStream
187     /// During conversion, `AttrAnnotatedTokenTree::Attributes` get 'flattened'
188     /// back to a `TokenStream` of the form `outer_attr attr_target`.
189     /// If there are inner attributes, they are inserted into the proper
190     /// place in the attribute target tokens.
191     pub fn to_tokenstream(&self) -> TokenStream {
192         let trees: Vec<_> = self
193             .0
194             .iter()
195             .flat_map(|tree| match &tree.0 {
196                 AttrAnnotatedTokenTree::Token(inner) => {
197                     smallvec![(TokenTree::Token(inner.clone()), tree.1)].into_iter()
198                 }
199                 AttrAnnotatedTokenTree::Delimited(span, delim, stream) => smallvec![(
200                     TokenTree::Delimited(*span, *delim, stream.to_tokenstream()),
201                     tree.1,
202                 )]
203                 .into_iter(),
204                 AttrAnnotatedTokenTree::Attributes(data) => {
205                     let mut outer_attrs = Vec::new();
206                     let mut inner_attrs = Vec::new();
207                     for attr in &data.attrs {
208                         match attr.style {
209                             crate::AttrStyle::Outer => {
210                                 outer_attrs.push(attr);
211                             }
212                             crate::AttrStyle::Inner => {
213                                 inner_attrs.push(attr);
214                             }
215                         }
216                     }
217
218                     let mut target_tokens: Vec<_> = data
219                         .tokens
220                         .create_token_stream()
221                         .to_tokenstream()
222                         .0
223                         .iter()
224                         .cloned()
225                         .collect();
226                     if !inner_attrs.is_empty() {
227                         let mut found = false;
228                         // Check the last two trees (to account for a trailing semi)
229                         for (tree, _) in target_tokens.iter_mut().rev().take(2) {
230                             if let TokenTree::Delimited(span, delim, delim_tokens) = tree {
231                                 // Inner attributes are only supported on extern blocks, functions, impls,
232                                 // and modules. All of these have their inner attributes placed at
233                                 // the beginning of the rightmost outermost braced group:
234                                 // e.g. fn foo() { #![my_attr} }
235                                 //
236                                 // Therefore, we can insert them back into the right location
237                                 // without needing to do any extra position tracking.
238                                 //
239                                 // Note: Outline modules are an exception - they can
240                                 // have attributes like `#![my_attr]` at the start of a file.
241                                 // Support for custom attributes in this position is not
242                                 // properly implemented - we always synthesize fake tokens,
243                                 // so we never reach this code.
244
245                                 let mut builder = TokenStreamBuilder::new();
246                                 for inner_attr in inner_attrs {
247                                     builder.push(inner_attr.tokens().to_tokenstream());
248                                 }
249                                 builder.push(delim_tokens.clone());
250                                 *tree = TokenTree::Delimited(*span, *delim, builder.build());
251                                 found = true;
252                                 break;
253                             }
254                         }
255
256                         assert!(
257                             found,
258                             "Failed to find trailing delimited group in: {:?}",
259                             target_tokens
260                         );
261                     }
262                     let mut flat: SmallVec<[_; 1]> = SmallVec::new();
263                     for attr in outer_attrs {
264                         // FIXME: Make this more efficient
265                         flat.extend(attr.tokens().to_tokenstream().0.clone().iter().cloned());
266                     }
267                     flat.extend(target_tokens);
268                     flat.into_iter()
269                 }
270             })
271             .collect();
272         TokenStream::new(trees)
273     }
274 }
275
276 /// Stores the tokens for an attribute target, along
277 /// with its attributes.
278 ///
279 /// This is constructed during parsing when we need to capture
280 /// tokens.
281 ///
282 /// For example, `#[cfg(FALSE)] struct Foo {}` would
283 /// have an `attrs` field containing the `#[cfg(FALSE)]` attr,
284 /// and a `tokens` field storing the (unparsed) tokens `struct Foo {}`
285 #[derive(Clone, Debug, Encodable, Decodable)]
286 pub struct AttributesData {
287     /// Attributes, both outer and inner.
288     /// These are stored in the original order that they were parsed in.
289     pub attrs: AttrVec,
290     /// The underlying tokens for the attribute target that `attrs`
291     /// are applied to
292     pub tokens: LazyTokenStream,
293 }
294
295 /// A `TokenStream` is an abstract sequence of tokens, organized into [`TokenTree`]s.
296 ///
297 /// The goal is for procedural macros to work with `TokenStream`s and `TokenTree`s
298 /// instead of a representation of the abstract syntax tree.
299 /// Today's `TokenTree`s can still contain AST via `token::Interpolated` for
300 /// backwards compatibility.
301 #[derive(Clone, Debug, Default, Encodable, Decodable)]
302 pub struct TokenStream(pub(crate) Lrc<Vec<TreeAndSpacing>>);
303
304 pub type TreeAndSpacing = (TokenTree, Spacing);
305
306 // `TokenStream` is used a lot. Make sure it doesn't unintentionally get bigger.
307 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
308 rustc_data_structures::static_assert_size!(TokenStream, 8);
309
310 #[derive(Clone, Copy, Debug, PartialEq, Encodable, Decodable)]
311 pub enum Spacing {
312     Alone,
313     Joint,
314 }
315
316 impl TokenStream {
317     /// Given a `TokenStream` with a `Stream` of only two arguments, return a new `TokenStream`
318     /// separating the two arguments with a comma for diagnostic suggestions.
319     pub fn add_comma(&self) -> Option<(TokenStream, Span)> {
320         // Used to suggest if a user writes `foo!(a b);`
321         let mut suggestion = None;
322         let mut iter = self.0.iter().enumerate().peekable();
323         while let Some((pos, ts)) = iter.next() {
324             if let Some((_, next)) = iter.peek() {
325                 let sp = match (&ts, &next) {
326                     (_, (TokenTree::Token(Token { kind: token::Comma, .. }), _)) => continue,
327                     (
328                         (TokenTree::Token(token_left), Spacing::Alone),
329                         (TokenTree::Token(token_right), _),
330                     ) if ((token_left.is_ident() && !token_left.is_reserved_ident())
331                         || token_left.is_lit())
332                         && ((token_right.is_ident() && !token_right.is_reserved_ident())
333                             || token_right.is_lit()) =>
334                     {
335                         token_left.span
336                     }
337                     ((TokenTree::Delimited(sp, ..), Spacing::Alone), _) => sp.entire(),
338                     _ => continue,
339                 };
340                 let sp = sp.shrink_to_hi();
341                 let comma = (TokenTree::token(token::Comma, sp), Spacing::Alone);
342                 suggestion = Some((pos, comma, sp));
343             }
344         }
345         if let Some((pos, comma, sp)) = suggestion {
346             let mut new_stream = Vec::with_capacity(self.0.len() + 1);
347             let parts = self.0.split_at(pos + 1);
348             new_stream.extend_from_slice(parts.0);
349             new_stream.push(comma);
350             new_stream.extend_from_slice(parts.1);
351             return Some((TokenStream::new(new_stream), sp));
352         }
353         None
354     }
355 }
356
357 impl From<(AttrAnnotatedTokenTree, Spacing)> for AttrAnnotatedTokenStream {
358     fn from((tree, spacing): (AttrAnnotatedTokenTree, Spacing)) -> AttrAnnotatedTokenStream {
359         AttrAnnotatedTokenStream::new(vec![(tree, spacing)])
360     }
361 }
362
363 impl From<TokenTree> for TokenStream {
364     fn from(tree: TokenTree) -> TokenStream {
365         TokenStream::new(vec![(tree, Spacing::Alone)])
366     }
367 }
368
369 impl From<TokenTree> for TreeAndSpacing {
370     fn from(tree: TokenTree) -> TreeAndSpacing {
371         (tree, Spacing::Alone)
372     }
373 }
374
375 impl iter::FromIterator<TokenTree> for TokenStream {
376     fn from_iter<I: IntoIterator<Item = TokenTree>>(iter: I) -> Self {
377         TokenStream::new(iter.into_iter().map(Into::into).collect::<Vec<TreeAndSpacing>>())
378     }
379 }
380
381 impl Eq for TokenStream {}
382
383 impl PartialEq<TokenStream> for TokenStream {
384     fn eq(&self, other: &TokenStream) -> bool {
385         self.trees().eq(other.trees())
386     }
387 }
388
389 impl TokenStream {
390     pub fn new(streams: Vec<TreeAndSpacing>) -> TokenStream {
391         TokenStream(Lrc::new(streams))
392     }
393
394     pub fn is_empty(&self) -> bool {
395         self.0.is_empty()
396     }
397
398     pub fn len(&self) -> usize {
399         self.0.len()
400     }
401
402     pub fn trees(&self) -> CursorRef<'_> {
403         CursorRef::new(self)
404     }
405
406     pub fn into_trees(self) -> Cursor {
407         Cursor::new(self)
408     }
409
410     /// Compares two `TokenStream`s, checking equality without regarding span information.
411     pub fn eq_unspanned(&self, other: &TokenStream) -> bool {
412         let mut t1 = self.trees();
413         let mut t2 = other.trees();
414         for (t1, t2) in iter::zip(&mut t1, &mut t2) {
415             if !t1.eq_unspanned(&t2) {
416                 return false;
417             }
418         }
419         t1.next().is_none() && t2.next().is_none()
420     }
421
422     pub fn map_enumerated<F: FnMut(usize, &TokenTree) -> TokenTree>(self, mut f: F) -> TokenStream {
423         TokenStream(Lrc::new(
424             self.0
425                 .iter()
426                 .enumerate()
427                 .map(|(i, (tree, is_joint))| (f(i, tree), *is_joint))
428                 .collect(),
429         ))
430     }
431
432     fn opt_from_ast(node: &(impl HasAttrs + HasTokens)) -> Option<TokenStream> {
433         let tokens = node.tokens()?;
434         let attrs = node.attrs();
435         let attr_annotated = if attrs.is_empty() {
436             tokens.create_token_stream()
437         } else {
438             let attr_data = AttributesData { attrs: attrs.to_vec().into(), tokens: tokens.clone() };
439             AttrAnnotatedTokenStream::new(vec![(
440                 AttrAnnotatedTokenTree::Attributes(attr_data),
441                 Spacing::Alone,
442             )])
443         };
444         Some(attr_annotated.to_tokenstream())
445     }
446
447     pub fn from_ast(node: &(impl HasAttrs + HasSpan + HasTokens + fmt::Debug)) -> TokenStream {
448         TokenStream::opt_from_ast(node)
449             .unwrap_or_else(|| panic!("missing tokens for node at {:?}: {:?}", node.span(), node))
450     }
451
452     pub fn from_nonterminal_ast(nt: &Nonterminal) -> TokenStream {
453         match nt {
454             Nonterminal::NtIdent(ident, is_raw) => {
455                 TokenTree::token(token::Ident(ident.name, *is_raw), ident.span).into()
456             }
457             Nonterminal::NtLifetime(ident) => {
458                 TokenTree::token(token::Lifetime(ident.name), ident.span).into()
459             }
460             Nonterminal::NtItem(item) => TokenStream::from_ast(item),
461             Nonterminal::NtBlock(block) => TokenStream::from_ast(block),
462             Nonterminal::NtStmt(stmt) if let StmtKind::Empty = stmt.kind => {
463                 // FIXME: Properly collect tokens for empty statements.
464                 TokenTree::token(token::Semi, stmt.span).into()
465             }
466             Nonterminal::NtStmt(stmt) => TokenStream::from_ast(stmt),
467             Nonterminal::NtPat(pat) => TokenStream::from_ast(pat),
468             Nonterminal::NtTy(ty) => TokenStream::from_ast(ty),
469             Nonterminal::NtMeta(attr) => TokenStream::from_ast(attr),
470             Nonterminal::NtPath(path) => TokenStream::from_ast(path),
471             Nonterminal::NtVis(vis) => TokenStream::from_ast(vis),
472             Nonterminal::NtExpr(expr) | Nonterminal::NtLiteral(expr) => TokenStream::from_ast(expr),
473         }
474     }
475
476     fn flatten_token(token: &Token) -> TokenTree {
477         match &token.kind {
478             token::Interpolated(nt) if let token::NtIdent(ident, is_raw) = **nt => {
479                 TokenTree::token(token::Ident(ident.name, is_raw), ident.span)
480             }
481             token::Interpolated(nt) => TokenTree::Delimited(
482                 DelimSpan::from_single(token.span),
483                 Delimiter::Invisible,
484                 TokenStream::from_nonterminal_ast(&nt).flattened(),
485             ),
486             _ => TokenTree::Token(token.clone()),
487         }
488     }
489
490     fn flatten_token_tree(tree: &TokenTree) -> TokenTree {
491         match tree {
492             TokenTree::Token(token) => TokenStream::flatten_token(token),
493             TokenTree::Delimited(span, delim, tts) => {
494                 TokenTree::Delimited(*span, *delim, tts.flattened())
495             }
496         }
497     }
498
499     #[must_use]
500     pub fn flattened(&self) -> TokenStream {
501         fn can_skip(stream: &TokenStream) -> bool {
502             stream.trees().all(|tree| match tree {
503                 TokenTree::Token(token) => !matches!(token.kind, token::Interpolated(_)),
504                 TokenTree::Delimited(_, _, inner) => can_skip(inner),
505             })
506         }
507
508         if can_skip(self) {
509             return self.clone();
510         }
511
512         self.trees().map(|tree| TokenStream::flatten_token_tree(tree)).collect()
513     }
514 }
515
516 // 99.5%+ of the time we have 1 or 2 elements in this vector.
517 #[derive(Clone)]
518 pub struct TokenStreamBuilder(SmallVec<[TokenStream; 2]>);
519
520 impl TokenStreamBuilder {
521     pub fn new() -> TokenStreamBuilder {
522         TokenStreamBuilder(SmallVec::new())
523     }
524
525     pub fn push<T: Into<TokenStream>>(&mut self, stream: T) {
526         self.0.push(stream.into());
527     }
528
529     pub fn build(self) -> TokenStream {
530         let mut streams = self.0;
531         match streams.len() {
532             0 => TokenStream::default(),
533             1 => streams.pop().unwrap(),
534             _ => {
535                 // We will extend the first stream in `streams` with the
536                 // elements from the subsequent streams. This requires using
537                 // `make_mut()` on the first stream, and in practice this
538                 // doesn't cause cloning 99.9% of the time.
539                 //
540                 // One very common use case is when `streams` has two elements,
541                 // where the first stream has any number of elements within
542                 // (often 1, but sometimes many more) and the second stream has
543                 // a single element within.
544
545                 // Determine how much the first stream will be extended.
546                 // Needed to avoid quadratic blow up from on-the-fly
547                 // reallocations (#57735).
548                 let num_appends = streams.iter().skip(1).map(|ts| ts.len()).sum();
549
550                 // Get the first stream, which will become the result stream.
551                 // If it's `None`, create an empty stream.
552                 let mut iter = streams.drain(..);
553                 let mut res_stream_lrc = iter.next().unwrap().0;
554
555                 // Append the subsequent elements to the result stream, after
556                 // reserving space for them.
557                 let res_vec_mut = Lrc::make_mut(&mut res_stream_lrc);
558                 res_vec_mut.reserve(num_appends);
559                 for stream in iter {
560                     let stream_iter = stream.0.iter().cloned();
561
562                     // If (a) `res_mut_vec` is not empty and the last tree
563                     // within it is a token tree marked with `Joint`, and (b)
564                     // `stream` is not empty and the first tree within it is a
565                     // token tree, and (c) the two tokens can be glued
566                     // together...
567                     if let Some((TokenTree::Token(last_tok), Spacing::Joint)) = res_vec_mut.last()
568                         && let Some((TokenTree::Token(tok), spacing)) = stream.0.first()
569                         && let Some(glued_tok) = last_tok.glue(&tok)
570                     {
571                         // ...then overwrite the last token tree in
572                         // `res_vec_mut` with the glued token, and skip the
573                         // first token tree from `stream`.
574                         *res_vec_mut.last_mut().unwrap() = (TokenTree::Token(glued_tok), *spacing);
575                         res_vec_mut.extend(stream_iter.skip(1));
576                     } else {
577                         // Append all of `stream`.
578                         res_vec_mut.extend(stream_iter);
579                     }
580                 }
581
582                 TokenStream(res_stream_lrc)
583             }
584         }
585     }
586 }
587
588 /// By-reference iterator over a [`TokenStream`].
589 #[derive(Clone)]
590 pub struct CursorRef<'t> {
591     stream: &'t TokenStream,
592     index: usize,
593 }
594
595 impl<'t> CursorRef<'t> {
596     fn new(stream: &'t TokenStream) -> Self {
597         CursorRef { stream, index: 0 }
598     }
599
600     #[inline]
601     fn next_with_spacing(&mut self) -> Option<&'t TreeAndSpacing> {
602         self.stream.0.get(self.index).map(|tree| {
603             self.index += 1;
604             tree
605         })
606     }
607
608     pub fn look_ahead(&self, n: usize) -> Option<&TokenTree> {
609         self.stream.0[self.index..].get(n).map(|(tree, _)| tree)
610     }
611 }
612
613 impl<'t> Iterator for CursorRef<'t> {
614     type Item = &'t TokenTree;
615
616     fn next(&mut self) -> Option<&'t TokenTree> {
617         self.next_with_spacing().map(|(tree, _)| tree)
618     }
619 }
620
621 /// Owning by-value iterator over a [`TokenStream`].
622 // FIXME: Many uses of this can be replaced with by-reference iterator to avoid clones.
623 #[derive(Clone)]
624 pub struct Cursor {
625     pub stream: TokenStream,
626     index: usize,
627 }
628
629 impl Iterator for Cursor {
630     type Item = TokenTree;
631
632     fn next(&mut self) -> Option<TokenTree> {
633         self.next_with_spacing().map(|(tree, _)| tree)
634     }
635 }
636
637 impl Cursor {
638     fn new(stream: TokenStream) -> Self {
639         Cursor { stream, index: 0 }
640     }
641
642     #[inline]
643     pub fn next_with_spacing(&mut self) -> Option<TreeAndSpacing> {
644         self.stream.0.get(self.index).map(|tree| {
645             self.index += 1;
646             tree.clone()
647         })
648     }
649
650     #[inline]
651     pub fn next_with_spacing_ref(&mut self) -> Option<&TreeAndSpacing> {
652         self.stream.0.get(self.index).map(|tree| {
653             self.index += 1;
654             tree
655         })
656     }
657
658     pub fn look_ahead(&self, n: usize) -> Option<&TokenTree> {
659         self.stream.0[self.index..].get(n).map(|(tree, _)| tree)
660     }
661 }
662
663 #[derive(Debug, Copy, Clone, PartialEq, Encodable, Decodable, HashStable_Generic)]
664 pub struct DelimSpan {
665     pub open: Span,
666     pub close: Span,
667 }
668
669 impl DelimSpan {
670     pub fn from_single(sp: Span) -> Self {
671         DelimSpan { open: sp, close: sp }
672     }
673
674     pub fn from_pair(open: Span, close: Span) -> Self {
675         DelimSpan { open, close }
676     }
677
678     pub fn dummy() -> Self {
679         Self::from_single(DUMMY_SP)
680     }
681
682     pub fn entire(self) -> Span {
683         self.open.with_hi(self.close.hi())
684     }
685 }