]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/tokenstream.rs
Auto merge of #61212 - alexcrichton:skip-rustc, r=pietroalbini
[rust.git] / src / libsyntax / 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 (eg stream) of `TokenTree`s,
5 //! which are themselves a single `Token` or a `Delimited` subsequence of tokens.
6 //!
7 //! ## Ownership
8 //!
9 //! `TokenStreams` 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::ext::base;
17 use crate::ext::tt::{macro_parser, quoted};
18 use crate::parse::Directory;
19 use crate::parse::token::{self, DelimToken, Token};
20 use crate::print::pprust;
21
22 use syntax_pos::{BytePos, Mark, Span, DUMMY_SP};
23 #[cfg(target_arch = "x86_64")]
24 use rustc_data_structures::static_assert_size;
25 use rustc_data_structures::sync::Lrc;
26 use serialize::{Decoder, Decodable, Encoder, Encodable};
27 use smallvec::{SmallVec, smallvec};
28
29 use std::borrow::Cow;
30 use std::{fmt, iter, mem};
31
32 /// When the main rust parser encounters a syntax-extension invocation, it
33 /// parses the arguments to the invocation as a token-tree. This is a very
34 /// loose structure, such that all sorts of different AST-fragments can
35 /// be passed to syntax extensions using a uniform type.
36 ///
37 /// If the syntax extension is an MBE macro, it will attempt to match its
38 /// LHS token tree against the provided token tree, and if it finds a
39 /// match, will transcribe the RHS token tree, splicing in any captured
40 /// `macro_parser::matched_nonterminals` into the `SubstNt`s it finds.
41 ///
42 /// The RHS of an MBE macro is the only place `SubstNt`s are substituted.
43 /// Nothing special happens to misnamed or misplaced `SubstNt`s.
44 #[derive(Debug, Clone, PartialEq, RustcEncodable, RustcDecodable)]
45 pub enum TokenTree {
46     /// A single token
47     Token(Span, token::Token),
48     /// A delimited sequence of token trees
49     Delimited(DelimSpan, DelimToken, TokenStream),
50 }
51
52 // Ensure all fields of `TokenTree` is `Send` and `Sync`.
53 #[cfg(parallel_compiler)]
54 fn _dummy()
55 where
56     Span: Send + Sync,
57     token::Token: Send + Sync,
58     DelimSpan: Send + Sync,
59     DelimToken: Send + Sync,
60     TokenStream: Send + Sync,
61 {}
62
63 // These are safe since we ensure that they hold for all fields in the `_dummy` function.
64 //
65 // These impls are only here because the compiler takes forever to compute the Send and Sync
66 // bounds without them.
67 // FIXME: Remove these impls when the compiler can compute the bounds quickly again.
68 // See https://github.com/rust-lang/rust/issues/60846
69 #[cfg(parallel_compiler)]
70 unsafe impl Send for TokenTree {}
71 #[cfg(parallel_compiler)]
72 unsafe impl Sync for TokenTree {}
73
74 impl TokenTree {
75     /// Use this token tree as a matcher to parse given tts.
76     pub fn parse(cx: &base::ExtCtxt<'_>, mtch: &[quoted::TokenTree], tts: TokenStream)
77                  -> macro_parser::NamedParseResult {
78         // `None` is because we're not interpolating
79         let directory = Directory {
80             path: Cow::from(cx.current_expansion.module.directory.as_path()),
81             ownership: cx.current_expansion.directory_ownership,
82         };
83         macro_parser::parse(cx.parse_sess(), tts, mtch, Some(directory), true)
84     }
85
86     /// Checks if this TokenTree is equal to the other, regardless of span information.
87     pub fn eq_unspanned(&self, other: &TokenTree) -> bool {
88         match (self, other) {
89             (&TokenTree::Token(_, ref tk), &TokenTree::Token(_, ref tk2)) => tk == tk2,
90             (&TokenTree::Delimited(_, delim, ref tts),
91              &TokenTree::Delimited(_, delim2, ref tts2)) => {
92                 delim == delim2 && tts.eq_unspanned(&tts2)
93             }
94             (_, _) => false,
95         }
96     }
97
98     // See comments in `Nonterminal::to_tokenstream` for why we care about
99     // *probably* equal here rather than actual equality
100     //
101     // This is otherwise the same as `eq_unspanned`, only recursing with a
102     // different method.
103     pub fn probably_equal_for_proc_macro(&self, other: &TokenTree) -> bool {
104         match (self, other) {
105             (&TokenTree::Token(_, ref tk), &TokenTree::Token(_, ref tk2)) => {
106                 tk.probably_equal_for_proc_macro(tk2)
107             }
108             (&TokenTree::Delimited(_, delim, ref tts),
109              &TokenTree::Delimited(_, delim2, ref tts2)) => {
110                 delim == delim2 && tts.probably_equal_for_proc_macro(&tts2)
111             }
112             (_, _) => false,
113         }
114     }
115
116     /// Retrieves the TokenTree's span.
117     pub fn span(&self) -> Span {
118         match *self {
119             TokenTree::Token(sp, _) => sp,
120             TokenTree::Delimited(sp, ..) => sp.entire(),
121         }
122     }
123
124     /// Modify the `TokenTree`'s span in-place.
125     pub fn set_span(&mut self, span: Span) {
126         match *self {
127             TokenTree::Token(ref mut sp, _) => *sp = span,
128             TokenTree::Delimited(ref mut sp, ..) => *sp = DelimSpan::from_single(span),
129         }
130     }
131
132     /// Indicates if the stream is a token that is equal to the provided token.
133     pub fn eq_token(&self, t: Token) -> bool {
134         match *self {
135             TokenTree::Token(_, ref tk) => *tk == t,
136             _ => false,
137         }
138     }
139
140     pub fn joint(self) -> TokenStream {
141         TokenStream::new(vec![(self, Joint)])
142     }
143
144     /// Returns the opening delimiter as a token tree.
145     pub fn open_tt(span: Span, delim: DelimToken) -> TokenTree {
146         let open_span = if span.is_dummy() {
147             span
148         } else {
149             span.with_hi(span.lo() + BytePos(delim.len() as u32))
150         };
151         TokenTree::Token(open_span, token::OpenDelim(delim))
152     }
153
154     /// Returns the closing delimiter as a token tree.
155     pub fn close_tt(span: Span, delim: DelimToken) -> TokenTree {
156         let close_span = if span.is_dummy() {
157             span
158         } else {
159             span.with_lo(span.hi() - BytePos(delim.len() as u32))
160         };
161         TokenTree::Token(close_span, token::CloseDelim(delim))
162     }
163 }
164
165 /// # Token Streams
166 ///
167 /// A `TokenStream` is an abstract sequence of tokens, organized into `TokenTree`s.
168 /// The goal is for procedural macros to work with `TokenStream`s and `TokenTree`s
169 /// instead of a representation of the abstract syntax tree.
170 /// Today's `TokenTree`s can still contain AST via `Token::Interpolated` for back-compat.
171 ///
172 /// The use of `Option` is an optimization that avoids the need for an
173 /// allocation when the stream is empty. However, it is not guaranteed that an
174 /// empty stream is represented with `None`; it may be represented as a `Some`
175 /// around an empty `Vec`.
176 #[derive(Clone, Debug)]
177 pub struct TokenStream(pub Option<Lrc<Vec<TreeAndJoint>>>);
178
179 pub type TreeAndJoint = (TokenTree, IsJoint);
180
181 // `TokenStream` is used a lot. Make sure it doesn't unintentionally get bigger.
182 #[cfg(target_arch = "x86_64")]
183 static_assert_size!(TokenStream, 8);
184
185 #[derive(Clone, Copy, Debug, PartialEq)]
186 pub enum IsJoint {
187     Joint,
188     NonJoint
189 }
190
191 use IsJoint::*;
192
193 impl TokenStream {
194     /// Given a `TokenStream` with a `Stream` of only two arguments, return a new `TokenStream`
195     /// separating the two arguments with a comma for diagnostic suggestions.
196     pub(crate) fn add_comma(&self) -> Option<(TokenStream, Span)> {
197         // Used to suggest if a user writes `foo!(a b);`
198         if let Some(ref stream) = self.0 {
199             let mut suggestion = None;
200             let mut iter = stream.iter().enumerate().peekable();
201             while let Some((pos, ts)) = iter.next() {
202                 if let Some((_, next)) = iter.peek() {
203                     let sp = match (&ts, &next) {
204                         (_, (TokenTree::Token(_, token::Token::Comma), _)) => continue,
205                         ((TokenTree::Token(sp, token_left), NonJoint),
206                          (TokenTree::Token(_, token_right), _))
207                         if ((token_left.is_ident() && !token_left.is_reserved_ident())
208                             || token_left.is_lit()) &&
209                             ((token_right.is_ident() && !token_right.is_reserved_ident())
210                             || token_right.is_lit()) => *sp,
211                         ((TokenTree::Delimited(sp, ..), NonJoint), _) => sp.entire(),
212                         _ => continue,
213                     };
214                     let sp = sp.shrink_to_hi();
215                     let comma = (TokenTree::Token(sp, token::Comma), NonJoint);
216                     suggestion = Some((pos, comma, sp));
217                 }
218             }
219             if let Some((pos, comma, sp)) = suggestion {
220                 let mut new_stream = vec![];
221                 let parts = stream.split_at(pos + 1);
222                 new_stream.extend_from_slice(parts.0);
223                 new_stream.push(comma);
224                 new_stream.extend_from_slice(parts.1);
225                 return Some((TokenStream::new(new_stream), sp));
226             }
227         }
228         None
229     }
230 }
231
232 impl From<TokenTree> for TokenStream {
233     fn from(tree: TokenTree) -> TokenStream {
234         TokenStream::new(vec![(tree, NonJoint)])
235     }
236 }
237
238 impl From<TokenTree> for TreeAndJoint {
239     fn from(tree: TokenTree) -> TreeAndJoint {
240         (tree, NonJoint)
241     }
242 }
243
244 impl From<Token> for TokenStream {
245     fn from(token: Token) -> TokenStream {
246         TokenTree::Token(DUMMY_SP, token).into()
247     }
248 }
249
250 impl<T: Into<TokenStream>> iter::FromIterator<T> for TokenStream {
251     fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
252         TokenStream::from_streams(iter.into_iter().map(Into::into).collect::<SmallVec<_>>())
253     }
254 }
255
256 impl Eq for TokenStream {}
257
258 impl PartialEq<TokenStream> for TokenStream {
259     fn eq(&self, other: &TokenStream) -> bool {
260         self.trees().eq(other.trees())
261     }
262 }
263
264 impl TokenStream {
265     pub fn len(&self) -> usize {
266         if let Some(ref slice) = self.0 {
267             slice.len()
268         } else {
269             0
270         }
271     }
272
273     pub fn empty() -> TokenStream {
274         TokenStream(None)
275     }
276
277     pub fn is_empty(&self) -> bool {
278         match self.0 {
279             None => true,
280             Some(ref stream) => stream.is_empty(),
281         }
282     }
283
284     pub(crate) fn from_streams(mut streams: SmallVec<[TokenStream; 2]>) -> TokenStream {
285         match streams.len() {
286             0 => TokenStream::empty(),
287             1 => streams.pop().unwrap(),
288             _ => {
289                 // rust-lang/rust#57735: pre-allocate vector to avoid
290                 // quadratic blow-up due to on-the-fly reallocations.
291                 let tree_count = streams.iter()
292                     .map(|ts| match &ts.0 { None => 0, Some(s) => s.len() })
293                     .sum();
294                 let mut vec = Vec::with_capacity(tree_count);
295
296                 for stream in streams {
297                     match stream.0 {
298                         None => {},
299                         Some(stream2) => vec.extend(stream2.iter().cloned()),
300                     }
301                 }
302                 TokenStream::new(vec)
303             }
304         }
305     }
306
307     pub fn new(streams: Vec<TreeAndJoint>) -> TokenStream {
308         match streams.len() {
309             0 => TokenStream(None),
310             _ => TokenStream(Some(Lrc::new(streams))),
311         }
312     }
313
314     pub fn append_to_tree_and_joint_vec(self, vec: &mut Vec<TreeAndJoint>) {
315         if let Some(stream) = self.0 {
316             vec.extend(stream.iter().cloned());
317         }
318     }
319
320     pub fn trees(&self) -> Cursor {
321         self.clone().into_trees()
322     }
323
324     pub fn into_trees(self) -> Cursor {
325         Cursor::new(self)
326     }
327
328     /// Compares two TokenStreams, checking equality without regarding span information.
329     pub fn eq_unspanned(&self, other: &TokenStream) -> bool {
330         let mut t1 = self.trees();
331         let mut t2 = other.trees();
332         for (t1, t2) in t1.by_ref().zip(t2.by_ref()) {
333             if !t1.eq_unspanned(&t2) {
334                 return false;
335             }
336         }
337         t1.next().is_none() && t2.next().is_none()
338     }
339
340     // See comments in `Nonterminal::to_tokenstream` for why we care about
341     // *probably* equal here rather than actual equality
342     //
343     // This is otherwise the same as `eq_unspanned`, only recursing with a
344     // different method.
345     pub fn probably_equal_for_proc_macro(&self, other: &TokenStream) -> bool {
346         // When checking for `probably_eq`, we ignore certain tokens that aren't
347         // preserved in the AST. Because they are not preserved, the pretty
348         // printer arbitrarily adds or removes them when printing as token
349         // streams, making a comparison between a token stream generated from an
350         // AST and a token stream which was parsed into an AST more reliable.
351         fn semantic_tree(tree: &TokenTree) -> bool {
352             match tree {
353                 // The pretty printer tends to add trailing commas to
354                 // everything, and in particular, after struct fields.
355                 | TokenTree::Token(_, Token::Comma)
356                 // The pretty printer emits `NoDelim` as whitespace.
357                 | TokenTree::Token(_, Token::OpenDelim(DelimToken::NoDelim))
358                 | TokenTree::Token(_, Token::CloseDelim(DelimToken::NoDelim))
359                 // The pretty printer collapses many semicolons into one.
360                 | TokenTree::Token(_, Token::Semi)
361                 // The pretty printer collapses whitespace arbitrarily and can
362                 // introduce whitespace from `NoDelim`.
363                 | TokenTree::Token(_, Token::Whitespace)
364                 // The pretty printer can turn `$crate` into `::crate_name`
365                 | TokenTree::Token(_, Token::ModSep) => false,
366                 _ => true
367             }
368         }
369
370         let mut t1 = self.trees().filter(semantic_tree);
371         let mut t2 = other.trees().filter(semantic_tree);
372         for (t1, t2) in t1.by_ref().zip(t2.by_ref()) {
373             if !t1.probably_equal_for_proc_macro(&t2) {
374                 return false;
375             }
376         }
377         t1.next().is_none() && t2.next().is_none()
378     }
379
380     pub fn map_enumerated<F: FnMut(usize, TokenTree) -> TokenTree>(self, mut f: F) -> TokenStream {
381         TokenStream(self.0.map(|stream| {
382             Lrc::new(
383                 stream
384                     .iter()
385                     .enumerate()
386                     .map(|(i, (tree, is_joint))| (f(i, tree.clone()), *is_joint))
387                     .collect())
388         }))
389     }
390
391     pub fn map<F: FnMut(TokenTree) -> TokenTree>(self, mut f: F) -> TokenStream {
392         TokenStream(self.0.map(|stream| {
393             Lrc::new(
394                 stream
395                     .iter()
396                     .map(|(tree, is_joint)| (f(tree.clone()), *is_joint))
397                     .collect())
398         }))
399     }
400
401     fn first_tree_and_joint(&self) -> Option<TreeAndJoint> {
402         self.0.as_ref().map(|stream| {
403             stream.first().unwrap().clone()
404         })
405     }
406
407     fn last_tree_if_joint(&self) -> Option<TokenTree> {
408         match self.0 {
409             None => None,
410             Some(ref stream) => {
411                 if let (tree, Joint) = stream.last().unwrap() {
412                     Some(tree.clone())
413                 } else {
414                     None
415                 }
416             }
417         }
418     }
419 }
420
421 // 99.5%+ of the time we have 1 or 2 elements in this vector.
422 #[derive(Clone)]
423 pub struct TokenStreamBuilder(SmallVec<[TokenStream; 2]>);
424
425 impl TokenStreamBuilder {
426     pub fn new() -> TokenStreamBuilder {
427         TokenStreamBuilder(SmallVec::new())
428     }
429
430     pub fn push<T: Into<TokenStream>>(&mut self, stream: T) {
431         let stream = stream.into();
432         let last_tree_if_joint = self.0.last().and_then(TokenStream::last_tree_if_joint);
433         if let Some(TokenTree::Token(last_span, last_tok)) = last_tree_if_joint {
434             if let Some((TokenTree::Token(span, tok), is_joint)) = stream.first_tree_and_joint() {
435                 if let Some(glued_tok) = last_tok.glue(tok) {
436                     let last_stream = self.0.pop().unwrap();
437                     self.push_all_but_last_tree(&last_stream);
438                     let glued_span = last_span.to(span);
439                     let glued_tt = TokenTree::Token(glued_span, glued_tok);
440                     let glued_tokenstream = TokenStream::new(vec![(glued_tt, is_joint)]);
441                     self.0.push(glued_tokenstream);
442                     self.push_all_but_first_tree(&stream);
443                     return
444                 }
445             }
446         }
447         self.0.push(stream);
448     }
449
450     pub fn build(self) -> TokenStream {
451         TokenStream::from_streams(self.0)
452     }
453
454     fn push_all_but_last_tree(&mut self, stream: &TokenStream) {
455         if let Some(ref streams) = stream.0 {
456             let len = streams.len();
457             match len {
458                 1 => {}
459                 _ => self.0.push(TokenStream(Some(Lrc::new(streams[0 .. len - 1].to_vec())))),
460             }
461         }
462     }
463
464     fn push_all_but_first_tree(&mut self, stream: &TokenStream) {
465         if let Some(ref streams) = stream.0 {
466             let len = streams.len();
467             match len {
468                 1 => {}
469                 _ => self.0.push(TokenStream(Some(Lrc::new(streams[1 .. len].to_vec())))),
470             }
471         }
472     }
473 }
474
475 #[derive(Clone)]
476 pub struct Cursor {
477     pub stream: TokenStream,
478     index: usize,
479 }
480
481 impl Iterator for Cursor {
482     type Item = TokenTree;
483
484     fn next(&mut self) -> Option<TokenTree> {
485         self.next_with_joint().map(|(tree, _)| tree)
486     }
487 }
488
489 impl Cursor {
490     fn new(stream: TokenStream) -> Self {
491         Cursor { stream, index: 0 }
492     }
493
494     pub fn next_with_joint(&mut self) -> Option<TreeAndJoint> {
495         match self.stream.0 {
496             None => None,
497             Some(ref stream) => {
498                 if self.index < stream.len() {
499                     self.index += 1;
500                     Some(stream[self.index - 1].clone())
501                 } else {
502                     None
503                 }
504             }
505         }
506     }
507
508     pub fn append(&mut self, new_stream: TokenStream) {
509         if new_stream.is_empty() {
510             return;
511         }
512         let index = self.index;
513         let stream = mem::replace(&mut self.stream, TokenStream(None));
514         *self = TokenStream::from_streams(smallvec![stream, new_stream]).into_trees();
515         self.index = index;
516     }
517
518     pub fn look_ahead(&self, n: usize) -> Option<TokenTree> {
519         match self.stream.0 {
520             None => None,
521             Some(ref stream) => stream[self.index ..].get(n).map(|(tree, _)| tree.clone()),
522         }
523     }
524 }
525
526 impl fmt::Display for TokenStream {
527     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
528         f.write_str(&pprust::tokens_to_string(self.clone()))
529     }
530 }
531
532 impl Encodable for TokenStream {
533     fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), E::Error> {
534         self.trees().collect::<Vec<_>>().encode(encoder)
535     }
536 }
537
538 impl Decodable for TokenStream {
539     fn decode<D: Decoder>(decoder: &mut D) -> Result<TokenStream, D::Error> {
540         Vec::<TokenTree>::decode(decoder).map(|vec| vec.into_iter().collect())
541     }
542 }
543
544 #[derive(Debug, Copy, Clone, PartialEq, RustcEncodable, RustcDecodable)]
545 pub struct DelimSpan {
546     pub open: Span,
547     pub close: Span,
548 }
549
550 impl DelimSpan {
551     pub fn from_single(sp: Span) -> Self {
552         DelimSpan {
553             open: sp,
554             close: sp,
555         }
556     }
557
558     pub fn from_pair(open: Span, close: Span) -> Self {
559         DelimSpan { open, close }
560     }
561
562     pub fn dummy() -> Self {
563         Self::from_single(DUMMY_SP)
564     }
565
566     pub fn entire(self) -> Span {
567         self.open.with_hi(self.close.hi())
568     }
569
570     pub fn apply_mark(self, mark: Mark) -> Self {
571         DelimSpan {
572             open: self.open.apply_mark(mark),
573             close: self.close.apply_mark(mark),
574         }
575     }
576 }
577
578 #[cfg(test)]
579 mod tests {
580     use super::*;
581     use crate::syntax::ast::Ident;
582     use crate::with_default_globals;
583     use crate::parse::token::Token;
584     use crate::util::parser_testing::string_to_stream;
585     use syntax_pos::{Span, BytePos, NO_EXPANSION};
586
587     fn string_to_ts(string: &str) -> TokenStream {
588         string_to_stream(string.to_owned())
589     }
590
591     fn sp(a: u32, b: u32) -> Span {
592         Span::new(BytePos(a), BytePos(b), NO_EXPANSION)
593     }
594
595     #[test]
596     fn test_concat() {
597         with_default_globals(|| {
598             let test_res = string_to_ts("foo::bar::baz");
599             let test_fst = string_to_ts("foo::bar");
600             let test_snd = string_to_ts("::baz");
601             let eq_res = TokenStream::from_streams(smallvec![test_fst, test_snd]);
602             assert_eq!(test_res.trees().count(), 5);
603             assert_eq!(eq_res.trees().count(), 5);
604             assert_eq!(test_res.eq_unspanned(&eq_res), true);
605         })
606     }
607
608     #[test]
609     fn test_to_from_bijection() {
610         with_default_globals(|| {
611             let test_start = string_to_ts("foo::bar(baz)");
612             let test_end = test_start.trees().collect();
613             assert_eq!(test_start, test_end)
614         })
615     }
616
617     #[test]
618     fn test_eq_0() {
619         with_default_globals(|| {
620             let test_res = string_to_ts("foo");
621             let test_eqs = string_to_ts("foo");
622             assert_eq!(test_res, test_eqs)
623         })
624     }
625
626     #[test]
627     fn test_eq_1() {
628         with_default_globals(|| {
629             let test_res = string_to_ts("::bar::baz");
630             let test_eqs = string_to_ts("::bar::baz");
631             assert_eq!(test_res, test_eqs)
632         })
633     }
634
635     #[test]
636     fn test_eq_3() {
637         with_default_globals(|| {
638             let test_res = string_to_ts("");
639             let test_eqs = string_to_ts("");
640             assert_eq!(test_res, test_eqs)
641         })
642     }
643
644     #[test]
645     fn test_diseq_0() {
646         with_default_globals(|| {
647             let test_res = string_to_ts("::bar::baz");
648             let test_eqs = string_to_ts("bar::baz");
649             assert_eq!(test_res == test_eqs, false)
650         })
651     }
652
653     #[test]
654     fn test_diseq_1() {
655         with_default_globals(|| {
656             let test_res = string_to_ts("(bar,baz)");
657             let test_eqs = string_to_ts("bar,baz");
658             assert_eq!(test_res == test_eqs, false)
659         })
660     }
661
662     #[test]
663     fn test_is_empty() {
664         with_default_globals(|| {
665             let test0: TokenStream = Vec::<TokenTree>::new().into_iter().collect();
666             let test1: TokenStream =
667                 TokenTree::Token(sp(0, 1), Token::Ident(Ident::from_str("a"), false)).into();
668             let test2 = string_to_ts("foo(bar::baz)");
669
670             assert_eq!(test0.is_empty(), true);
671             assert_eq!(test1.is_empty(), false);
672             assert_eq!(test2.is_empty(), false);
673         })
674     }
675
676     #[test]
677     fn test_dotdotdot() {
678         with_default_globals(|| {
679             let mut builder = TokenStreamBuilder::new();
680             builder.push(TokenTree::Token(sp(0, 1), Token::Dot).joint());
681             builder.push(TokenTree::Token(sp(1, 2), Token::Dot).joint());
682             builder.push(TokenTree::Token(sp(2, 3), Token::Dot));
683             let stream = builder.build();
684             assert!(stream.eq_unspanned(&string_to_ts("...")));
685             assert_eq!(stream.trees().count(), 1);
686         })
687     }
688 }