]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_ast/src/tokenstream.rs
fabd43a1618a4387fa8af8680fe8a52f17af90d1
[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, Spacing),
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     /// Create a `TokenTree::Token` with alone spacing.
90     pub fn token_alone(kind: TokenKind, span: Span) -> TokenTree {
91         TokenTree::Token(Token::new(kind, span), Spacing::Alone)
92     }
93
94     /// Create a `TokenTree::Token` with joint spacing.
95     pub fn token_joint(kind: TokenKind, span: Span) -> TokenTree {
96         TokenTree::Token(Token::new(kind, span), Spacing::Joint)
97     }
98
99     pub fn uninterpolate(self) -> TokenTree {
100         match self {
101             TokenTree::Token(token, spacing) => {
102                 TokenTree::Token(token.uninterpolate().into_owned(), spacing)
103             }
104             tt => tt,
105         }
106     }
107 }
108
109 impl<CTX> HashStable<CTX> for TokenStream
110 where
111     CTX: crate::HashStableContext,
112 {
113     fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
114         for sub_tt in self.trees() {
115             sub_tt.hash_stable(hcx, hasher);
116         }
117     }
118 }
119
120 pub trait ToAttrTokenStream: sync::Send + sync::Sync {
121     fn to_attr_token_stream(&self) -> AttrTokenStream;
122 }
123
124 impl ToAttrTokenStream for AttrTokenStream {
125     fn to_attr_token_stream(&self) -> AttrTokenStream {
126         self.clone()
127     }
128 }
129
130 /// A lazy version of [`TokenStream`], which defers creation
131 /// of an actual `TokenStream` until it is needed.
132 /// `Box` is here only to reduce the structure size.
133 #[derive(Clone)]
134 pub struct LazyAttrTokenStream(Lrc<Box<dyn ToAttrTokenStream>>);
135
136 impl LazyAttrTokenStream {
137     pub fn new(inner: impl ToAttrTokenStream + 'static) -> LazyAttrTokenStream {
138         LazyAttrTokenStream(Lrc::new(Box::new(inner)))
139     }
140
141     pub fn to_attr_token_stream(&self) -> AttrTokenStream {
142         self.0.to_attr_token_stream()
143     }
144 }
145
146 impl fmt::Debug for LazyAttrTokenStream {
147     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
148         write!(f, "LazyAttrTokenStream({:?})", self.to_attr_token_stream())
149     }
150 }
151
152 impl<S: Encoder> Encodable<S> for LazyAttrTokenStream {
153     fn encode(&self, s: &mut S) {
154         // Used by AST json printing.
155         Encodable::encode(&self.to_attr_token_stream(), s);
156     }
157 }
158
159 impl<D: Decoder> Decodable<D> for LazyAttrTokenStream {
160     fn decode(_d: &mut D) -> Self {
161         panic!("Attempted to decode LazyAttrTokenStream");
162     }
163 }
164
165 impl<CTX> HashStable<CTX> for LazyAttrTokenStream {
166     fn hash_stable(&self, _hcx: &mut CTX, _hasher: &mut StableHasher) {
167         panic!("Attempted to compute stable hash for LazyAttrTokenStream");
168     }
169 }
170
171 /// An `AttrTokenStream` is similar to a `TokenStream`, but with extra
172 /// information about the tokens for attribute targets. This is used
173 /// during expansion to perform early cfg-expansion, and to process attributes
174 /// during proc-macro invocations.
175 #[derive(Clone, Debug, Default, Encodable, Decodable)]
176 pub struct AttrTokenStream(pub Lrc<Vec<AttrTokenTree>>);
177
178 /// Like `TokenTree`, but for `AttrTokenStream`.
179 #[derive(Clone, Debug, Encodable, Decodable)]
180 pub enum AttrTokenTree {
181     Token(Token, Spacing),
182     Delimited(DelimSpan, Delimiter, AttrTokenStream),
183     /// Stores the attributes for an attribute target,
184     /// along with the tokens for that attribute target.
185     /// See `AttributesData` for more information
186     Attributes(AttributesData),
187 }
188
189 impl AttrTokenStream {
190     pub fn new(tokens: Vec<AttrTokenTree>) -> AttrTokenStream {
191         AttrTokenStream(Lrc::new(tokens))
192     }
193
194     /// Converts this `AttrTokenStream` to a plain `TokenStream`.
195     /// During conversion, `AttrTokenTree::Attributes` get 'flattened'
196     /// back to a `TokenStream` of the form `outer_attr attr_target`.
197     /// If there are inner attributes, they are inserted into the proper
198     /// place in the attribute target tokens.
199     pub fn to_tokenstream(&self) -> TokenStream {
200         let trees: Vec<_> = self
201             .0
202             .iter()
203             .flat_map(|tree| match &tree {
204                 AttrTokenTree::Token(inner, spacing) => {
205                     smallvec![TokenTree::Token(inner.clone(), *spacing)].into_iter()
206                 }
207                 AttrTokenTree::Delimited(span, delim, stream) => {
208                     smallvec![TokenTree::Delimited(*span, *delim, stream.to_tokenstream()),]
209                         .into_iter()
210                 }
211                 AttrTokenTree::Attributes(data) => {
212                     let mut outer_attrs = Vec::new();
213                     let mut inner_attrs = Vec::new();
214                     for attr in &data.attrs {
215                         match attr.style {
216                             crate::AttrStyle::Outer => outer_attrs.push(attr),
217                             crate::AttrStyle::Inner => inner_attrs.push(attr),
218                         }
219                     }
220
221                     let mut target_tokens: Vec<_> = data
222                         .tokens
223                         .to_attr_token_stream()
224                         .to_tokenstream()
225                         .0
226                         .iter()
227                         .cloned()
228                         .collect();
229                     if !inner_attrs.is_empty() {
230                         let mut found = false;
231                         // Check the last two trees (to account for a trailing semi)
232                         for tree in target_tokens.iter_mut().rev().take(2) {
233                             if let TokenTree::Delimited(span, delim, delim_tokens) = tree {
234                                 // Inner attributes are only supported on extern blocks, functions,
235                                 // impls, and modules. All of these have their inner attributes
236                                 // placed at the beginning of the rightmost outermost braced group:
237                                 // e.g. fn foo() { #![my_attr} }
238                                 //
239                                 // Therefore, we can insert them back into the right location
240                                 // without needing to do any extra position tracking.
241                                 //
242                                 // Note: Outline modules are an exception - they can
243                                 // have attributes like `#![my_attr]` at the start of a file.
244                                 // Support for custom attributes in this position is not
245                                 // properly implemented - we always synthesize fake tokens,
246                                 // so we never reach this code.
247
248                                 let mut stream = TokenStream::default();
249                                 for inner_attr in inner_attrs {
250                                     stream.push_stream(inner_attr.tokens());
251                                 }
252                                 stream.push_stream(delim_tokens.clone());
253                                 *tree = TokenTree::Delimited(*span, *delim, stream);
254                                 found = true;
255                                 break;
256                             }
257                         }
258
259                         assert!(
260                             found,
261                             "Failed to find trailing delimited group in: {target_tokens:?}"
262                         );
263                     }
264                     let mut flat: SmallVec<[_; 1]> = SmallVec::new();
265                     for attr in outer_attrs {
266                         // FIXME: Make this more efficient
267                         flat.extend(attr.tokens().0.clone().iter().cloned());
268                     }
269                     flat.extend(target_tokens);
270                     flat.into_iter()
271                 }
272             })
273             .collect();
274         TokenStream::new(trees)
275     }
276 }
277
278 /// Stores the tokens for an attribute target, along
279 /// with its attributes.
280 ///
281 /// This is constructed during parsing when we need to capture
282 /// tokens.
283 ///
284 /// For example, `#[cfg(FALSE)] struct Foo {}` would
285 /// have an `attrs` field containing the `#[cfg(FALSE)]` attr,
286 /// and a `tokens` field storing the (unparsed) tokens `struct Foo {}`
287 #[derive(Clone, Debug, Encodable, Decodable)]
288 pub struct AttributesData {
289     /// Attributes, both outer and inner.
290     /// These are stored in the original order that they were parsed in.
291     pub attrs: AttrVec,
292     /// The underlying tokens for the attribute target that `attrs`
293     /// are applied to
294     pub tokens: LazyAttrTokenStream,
295 }
296
297 /// A `TokenStream` is an abstract sequence of tokens, organized into [`TokenTree`]s.
298 ///
299 /// The goal is for procedural macros to work with `TokenStream`s and `TokenTree`s
300 /// instead of a representation of the abstract syntax tree.
301 /// Today's `TokenTree`s can still contain AST via `token::Interpolated` for
302 /// backwards compatibility.
303 #[derive(Clone, Debug, Default, Encodable, Decodable)]
304 pub struct TokenStream(pub(crate) Lrc<Vec<TokenTree>>);
305
306 /// Similar to `proc_macro::Spacing`, but for tokens.
307 ///
308 /// Note that all `ast::TokenTree::Token` instances have a `Spacing`, but when
309 /// we convert to `proc_macro::TokenTree` for proc macros only `Punct`
310 /// `TokenTree`s have a `proc_macro::Spacing`.
311 #[derive(Clone, Copy, Debug, PartialEq, Encodable, Decodable, HashStable_Generic)]
312 pub enum Spacing {
313     /// The token is not immediately followed by an operator token (as
314     /// determined by `Token::is_op`). E.g. a `+` token is `Alone` in `+ =`,
315     /// `+/*foo*/=`, `+ident`, and `+()`.
316     Alone,
317
318     /// The token is immediately followed by an operator token. E.g. a `+`
319     /// token is `Joint` in `+=` and `++`.
320     Joint,
321 }
322
323 impl TokenStream {
324     /// Given a `TokenStream` with a `Stream` of only two arguments, return a new `TokenStream`
325     /// separating the two arguments with a comma for diagnostic suggestions.
326     pub fn add_comma(&self) -> Option<(TokenStream, Span)> {
327         // Used to suggest if a user writes `foo!(a b);`
328         let mut suggestion = None;
329         let mut iter = self.0.iter().enumerate().peekable();
330         while let Some((pos, ts)) = iter.next() {
331             if let Some((_, next)) = iter.peek() {
332                 let sp = match (&ts, &next) {
333                     (_, TokenTree::Token(Token { kind: token::Comma, .. }, _)) => continue,
334                     (
335                         TokenTree::Token(token_left, Spacing::Alone),
336                         TokenTree::Token(token_right, _),
337                     ) if ((token_left.is_ident() && !token_left.is_reserved_ident())
338                         || token_left.is_lit())
339                         && ((token_right.is_ident() && !token_right.is_reserved_ident())
340                             || token_right.is_lit()) =>
341                     {
342                         token_left.span
343                     }
344                     (TokenTree::Delimited(sp, ..), _) => sp.entire(),
345                     _ => continue,
346                 };
347                 let sp = sp.shrink_to_hi();
348                 let comma = TokenTree::token_alone(token::Comma, sp);
349                 suggestion = Some((pos, comma, sp));
350             }
351         }
352         if let Some((pos, comma, sp)) = suggestion {
353             let mut new_stream = Vec::with_capacity(self.0.len() + 1);
354             let parts = self.0.split_at(pos + 1);
355             new_stream.extend_from_slice(parts.0);
356             new_stream.push(comma);
357             new_stream.extend_from_slice(parts.1);
358             return Some((TokenStream::new(new_stream), sp));
359         }
360         None
361     }
362 }
363
364 impl FromIterator<TokenTree> for TokenStream {
365     fn from_iter<I: IntoIterator<Item = TokenTree>>(iter: I) -> Self {
366         TokenStream::new(iter.into_iter().collect::<Vec<TokenTree>>())
367     }
368 }
369
370 impl Eq for TokenStream {}
371
372 impl PartialEq<TokenStream> for TokenStream {
373     fn eq(&self, other: &TokenStream) -> bool {
374         self.trees().eq(other.trees())
375     }
376 }
377
378 impl TokenStream {
379     pub fn new(streams: Vec<TokenTree>) -> TokenStream {
380         TokenStream(Lrc::new(streams))
381     }
382
383     pub fn is_empty(&self) -> bool {
384         self.0.is_empty()
385     }
386
387     pub fn len(&self) -> usize {
388         self.0.len()
389     }
390
391     pub fn trees(&self) -> CursorRef<'_> {
392         CursorRef::new(self)
393     }
394
395     pub fn into_trees(self) -> Cursor {
396         Cursor::new(self)
397     }
398
399     /// Compares two `TokenStream`s, checking equality without regarding span information.
400     pub fn eq_unspanned(&self, other: &TokenStream) -> bool {
401         let mut t1 = self.trees();
402         let mut t2 = other.trees();
403         for (t1, t2) in iter::zip(&mut t1, &mut t2) {
404             if !t1.eq_unspanned(t2) {
405                 return false;
406             }
407         }
408         t1.next().is_none() && t2.next().is_none()
409     }
410
411     pub fn map_enumerated<F: FnMut(usize, &TokenTree) -> TokenTree>(self, mut f: F) -> TokenStream {
412         TokenStream(Lrc::new(self.0.iter().enumerate().map(|(i, tree)| f(i, tree)).collect()))
413     }
414
415     /// Create a token stream containing a single token with alone spacing.
416     pub fn token_alone(kind: TokenKind, span: Span) -> TokenStream {
417         TokenStream::new(vec![TokenTree::token_alone(kind, span)])
418     }
419
420     /// Create a token stream containing a single token with joint spacing.
421     pub fn token_joint(kind: TokenKind, span: Span) -> TokenStream {
422         TokenStream::new(vec![TokenTree::token_joint(kind, span)])
423     }
424
425     /// Create a token stream containing a single `Delimited`.
426     pub fn delimited(span: DelimSpan, delim: Delimiter, tts: TokenStream) -> TokenStream {
427         TokenStream::new(vec![TokenTree::Delimited(span, delim, tts)])
428     }
429
430     pub fn from_ast(node: &(impl HasAttrs + HasSpan + HasTokens + fmt::Debug)) -> TokenStream {
431         let Some(tokens) = node.tokens() else {
432             panic!("missing tokens for node at {:?}: {:?}", node.span(), node);
433         };
434         let attrs = node.attrs();
435         let attr_stream = if attrs.is_empty() {
436             tokens.to_attr_token_stream()
437         } else {
438             let attr_data =
439                 AttributesData { attrs: attrs.iter().cloned().collect(), tokens: tokens.clone() };
440             AttrTokenStream::new(vec![AttrTokenTree::Attributes(attr_data)])
441         };
442         attr_stream.to_tokenstream()
443     }
444
445     pub fn from_nonterminal_ast(nt: &Nonterminal) -> TokenStream {
446         match nt {
447             Nonterminal::NtIdent(ident, is_raw) => {
448                 TokenStream::token_alone(token::Ident(ident.name, *is_raw), ident.span)
449             }
450             Nonterminal::NtLifetime(ident) => {
451                 TokenStream::token_alone(token::Lifetime(ident.name), ident.span)
452             }
453             Nonterminal::NtItem(item) => TokenStream::from_ast(item),
454             Nonterminal::NtBlock(block) => TokenStream::from_ast(block),
455             Nonterminal::NtStmt(stmt) if let StmtKind::Empty = stmt.kind => {
456                 // FIXME: Properly collect tokens for empty statements.
457                 TokenStream::token_alone(token::Semi, stmt.span)
458             }
459             Nonterminal::NtStmt(stmt) => TokenStream::from_ast(stmt),
460             Nonterminal::NtPat(pat) => TokenStream::from_ast(pat),
461             Nonterminal::NtTy(ty) => TokenStream::from_ast(ty),
462             Nonterminal::NtMeta(attr) => TokenStream::from_ast(attr),
463             Nonterminal::NtPath(path) => TokenStream::from_ast(path),
464             Nonterminal::NtVis(vis) => TokenStream::from_ast(vis),
465             Nonterminal::NtExpr(expr) | Nonterminal::NtLiteral(expr) => TokenStream::from_ast(expr),
466         }
467     }
468
469     fn flatten_token(token: &Token, spacing: Spacing) -> TokenTree {
470         match &token.kind {
471             token::Interpolated(nt) if let token::NtIdent(ident, is_raw) = **nt => {
472                 TokenTree::Token(Token::new(token::Ident(ident.name, is_raw), ident.span), spacing)
473             }
474             token::Interpolated(nt) => TokenTree::Delimited(
475                 DelimSpan::from_single(token.span),
476                 Delimiter::Invisible,
477                 TokenStream::from_nonterminal_ast(nt).flattened(),
478             ),
479             _ => TokenTree::Token(token.clone(), spacing),
480         }
481     }
482
483     fn flatten_token_tree(tree: &TokenTree) -> TokenTree {
484         match tree {
485             TokenTree::Token(token, spacing) => TokenStream::flatten_token(token, *spacing),
486             TokenTree::Delimited(span, delim, tts) => {
487                 TokenTree::Delimited(*span, *delim, tts.flattened())
488             }
489         }
490     }
491
492     #[must_use]
493     pub fn flattened(&self) -> TokenStream {
494         fn can_skip(stream: &TokenStream) -> bool {
495             stream.trees().all(|tree| match tree {
496                 TokenTree::Token(token, _) => !matches!(token.kind, token::Interpolated(_)),
497                 TokenTree::Delimited(_, _, inner) => can_skip(inner),
498             })
499         }
500
501         if can_skip(self) {
502             return self.clone();
503         }
504
505         self.trees().map(|tree| TokenStream::flatten_token_tree(tree)).collect()
506     }
507
508     // If `vec` is not empty, try to glue `tt` onto its last token. The return
509     // value indicates if gluing took place.
510     fn try_glue_to_last(vec: &mut Vec<TokenTree>, tt: &TokenTree) -> bool {
511         if let Some(TokenTree::Token(last_tok, Spacing::Joint)) = vec.last()
512             && let TokenTree::Token(tok, spacing) = tt
513             && let Some(glued_tok) = last_tok.glue(tok)
514         {
515             // ...then overwrite the last token tree in `vec` with the
516             // glued token, and skip the first token tree from `stream`.
517             *vec.last_mut().unwrap() = TokenTree::Token(glued_tok, *spacing);
518             true
519         } else {
520             false
521         }
522     }
523
524     /// Push `tt` onto the end of the stream, possibly gluing it to the last
525     /// token. Uses `make_mut` to maximize efficiency.
526     pub fn push_tree(&mut self, tt: TokenTree) {
527         let vec_mut = Lrc::make_mut(&mut self.0);
528
529         if Self::try_glue_to_last(vec_mut, &tt) {
530             // nothing else to do
531         } else {
532             vec_mut.push(tt);
533         }
534     }
535
536     /// Push `stream` onto the end of the stream, possibly gluing the first
537     /// token tree to the last token. (No other token trees will be glued.)
538     /// Uses `make_mut` to maximize efficiency.
539     pub fn push_stream(&mut self, stream: TokenStream) {
540         let vec_mut = Lrc::make_mut(&mut self.0);
541
542         let stream_iter = stream.0.iter().cloned();
543
544         if let Some(first) = stream.0.first() && Self::try_glue_to_last(vec_mut, first) {
545             // Now skip the first token tree from `stream`.
546             vec_mut.extend(stream_iter.skip(1));
547         } else {
548             // Append all of `stream`.
549             vec_mut.extend(stream_iter);
550         }
551     }
552 }
553
554 /// By-reference iterator over a [`TokenStream`].
555 #[derive(Clone)]
556 pub struct CursorRef<'t> {
557     stream: &'t TokenStream,
558     index: usize,
559 }
560
561 impl<'t> CursorRef<'t> {
562     fn new(stream: &'t TokenStream) -> Self {
563         CursorRef { stream, index: 0 }
564     }
565
566     pub fn look_ahead(&self, n: usize) -> Option<&TokenTree> {
567         self.stream.0.get(self.index + n)
568     }
569 }
570
571 impl<'t> Iterator for CursorRef<'t> {
572     type Item = &'t TokenTree;
573
574     fn next(&mut self) -> Option<&'t TokenTree> {
575         self.stream.0.get(self.index).map(|tree| {
576             self.index += 1;
577             tree
578         })
579     }
580 }
581
582 /// Owning by-value iterator over a [`TokenStream`].
583 // FIXME: Many uses of this can be replaced with by-reference iterator to avoid clones.
584 #[derive(Clone)]
585 pub struct Cursor {
586     pub stream: TokenStream,
587     index: usize,
588 }
589
590 impl Iterator for Cursor {
591     type Item = TokenTree;
592
593     fn next(&mut self) -> Option<TokenTree> {
594         self.stream.0.get(self.index).map(|tree| {
595             self.index += 1;
596             tree.clone()
597         })
598     }
599 }
600
601 impl Cursor {
602     fn new(stream: TokenStream) -> Self {
603         Cursor { stream, index: 0 }
604     }
605
606     #[inline]
607     pub fn next_ref(&mut self) -> Option<&TokenTree> {
608         self.stream.0.get(self.index).map(|tree| {
609             self.index += 1;
610             tree
611         })
612     }
613
614     pub fn look_ahead(&self, n: usize) -> Option<&TokenTree> {
615         self.stream.0.get(self.index + n)
616     }
617 }
618
619 #[derive(Debug, Copy, Clone, PartialEq, Encodable, Decodable, HashStable_Generic)]
620 pub struct DelimSpan {
621     pub open: Span,
622     pub close: Span,
623 }
624
625 impl DelimSpan {
626     pub fn from_single(sp: Span) -> Self {
627         DelimSpan { open: sp, close: sp }
628     }
629
630     pub fn from_pair(open: Span, close: Span) -> Self {
631         DelimSpan { open, close }
632     }
633
634     pub fn dummy() -> Self {
635         Self::from_single(DUMMY_SP)
636     }
637
638     pub fn entire(self) -> Span {
639         self.open.with_hi(self.close.hi())
640     }
641 }
642
643 // Some types are used a lot. Make sure they don't unintentionally get bigger.
644 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
645 mod size_asserts {
646     use super::*;
647     use rustc_data_structures::static_assert_size;
648     // tidy-alphabetical-start
649     static_assert_size!(AttrTokenStream, 8);
650     static_assert_size!(AttrTokenTree, 32);
651     static_assert_size!(LazyAttrTokenStream, 8);
652     static_assert_size!(TokenStream, 8);
653     static_assert_size!(TokenTree, 32);
654     // tidy-alphabetical-end
655 }