]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/tokenstream.rs
Remove `tokenstream::Delimited`.
[rust.git] / src / libsyntax / tokenstream.rs
1 // Copyright 2012-2016 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! # Token Streams
12 //!
13 //! `TokenStream`s represent syntactic objects before they are converted into ASTs.
14 //! A `TokenStream` is, roughly speaking, a sequence (eg stream) of `TokenTree`s,
15 //! which are themselves a single `Token` or a `Delimited` subsequence of tokens.
16 //!
17 //! ## Ownership
18 //! `TokenStreams` are persistent data structures constructed as ropes with reference
19 //! counted-children. In general, this means that calling an operation on a `TokenStream`
20 //! (such as `slice`) produces an entirely new `TokenStream` from the borrowed reference to
21 //! the original. This essentially coerces `TokenStream`s into 'views' of their subparts,
22 //! and a borrowed `TokenStream` is sufficient to build an owned `TokenStream` without taking
23 //! ownership of the original.
24
25 use syntax_pos::{BytePos, Mark, Span, DUMMY_SP};
26 use ext::base;
27 use ext::tt::{macro_parser, quoted};
28 use parse::Directory;
29 use parse::token::{self, DelimToken, Token};
30 use print::pprust;
31 use serialize::{Decoder, Decodable, Encoder, Encodable};
32 use util::RcVec;
33
34 use std::borrow::Cow;
35 use std::{fmt, iter, mem};
36
37 /// When the main rust parser encounters a syntax-extension invocation, it
38 /// parses the arguments to the invocation as a token-tree. This is a very
39 /// loose structure, such that all sorts of different AST-fragments can
40 /// be passed to syntax extensions using a uniform type.
41 ///
42 /// If the syntax extension is an MBE macro, it will attempt to match its
43 /// LHS token tree against the provided token tree, and if it finds a
44 /// match, will transcribe the RHS token tree, splicing in any captured
45 /// `macro_parser::matched_nonterminals` into the `SubstNt`s it finds.
46 ///
47 /// The RHS of an MBE macro is the only place `SubstNt`s are substituted.
48 /// Nothing special happens to misnamed or misplaced `SubstNt`s.
49 #[derive(Debug, Clone, PartialEq, RustcEncodable, RustcDecodable)]
50 pub enum TokenTree {
51     /// A single token
52     Token(Span, token::Token),
53     /// A delimited sequence of token trees
54     Delimited(DelimSpan, DelimToken, ThinTokenStream),
55 }
56
57 impl TokenTree {
58     /// Use this token tree as a matcher to parse given tts.
59     pub fn parse(cx: &base::ExtCtxt, mtch: &[quoted::TokenTree], tts: TokenStream)
60                  -> macro_parser::NamedParseResult {
61         // `None` is because we're not interpolating
62         let directory = Directory {
63             path: Cow::from(cx.current_expansion.module.directory.as_path()),
64             ownership: cx.current_expansion.directory_ownership,
65         };
66         macro_parser::parse(cx.parse_sess(), tts, mtch, Some(directory), true)
67     }
68
69     /// Check if this TokenTree is equal to the other, regardless of span information.
70     pub fn eq_unspanned(&self, other: &TokenTree) -> bool {
71         match (self, other) {
72             (&TokenTree::Token(_, ref tk), &TokenTree::Token(_, ref tk2)) => tk == tk2,
73             (&TokenTree::Delimited(_, delim, ref tts),
74              &TokenTree::Delimited(_, delim2, ref tts2)) => {
75                 delim == delim2 &&
76                 tts.stream().eq_unspanned(&tts2.stream())
77             }
78             (_, _) => false,
79         }
80     }
81
82     // See comments in `interpolated_to_tokenstream` for why we care about
83     // *probably* equal here rather than actual equality
84     //
85     // This is otherwise the same as `eq_unspanned`, only recursing with a
86     // different method.
87     pub fn probably_equal_for_proc_macro(&self, other: &TokenTree) -> bool {
88         match (self, other) {
89             (&TokenTree::Token(_, ref tk), &TokenTree::Token(_, ref tk2)) => {
90                 tk.probably_equal_for_proc_macro(tk2)
91             }
92             (&TokenTree::Delimited(_, delim, ref tts),
93              &TokenTree::Delimited(_, delim2, ref tts2)) => {
94                 delim == delim2 &&
95                 tts.stream().probably_equal_for_proc_macro(&tts2.stream())
96             }
97             (_, _) => false,
98         }
99     }
100
101     /// Retrieve the TokenTree's span.
102     pub fn span(&self) -> Span {
103         match *self {
104             TokenTree::Token(sp, _) => sp,
105             TokenTree::Delimited(sp, ..) => sp.entire(),
106         }
107     }
108
109     /// Modify the `TokenTree`'s span in-place.
110     pub fn set_span(&mut self, span: Span) {
111         match *self {
112             TokenTree::Token(ref mut sp, _) => *sp = span,
113             TokenTree::Delimited(ref mut sp, ..) => *sp = DelimSpan::from_single(span),
114         }
115     }
116
117     /// Indicates if the stream is a token that is equal to the provided token.
118     pub fn eq_token(&self, t: Token) -> bool {
119         match *self {
120             TokenTree::Token(_, ref tk) => *tk == t,
121             _ => false,
122         }
123     }
124
125     pub fn joint(self) -> TokenStream {
126         TokenStream { kind: TokenStreamKind::JointTree(self) }
127     }
128
129     /// Returns the opening delimiter as a token tree.
130     pub fn open_tt(span: Span, delim: DelimToken) -> TokenTree {
131         let open_span = if span.is_dummy() {
132             span
133         } else {
134             span.with_hi(span.lo() + BytePos(delim.len() as u32))
135         };
136         TokenTree::Token(open_span, token::OpenDelim(delim))
137     }
138
139     /// Returns the closing delimiter as a token tree.
140     pub fn close_tt(span: Span, delim: DelimToken) -> TokenTree {
141         let close_span = if span.is_dummy() {
142             span
143         } else {
144             span.with_lo(span.hi() - BytePos(delim.len() as u32))
145         };
146         TokenTree::Token(close_span, token::CloseDelim(delim))
147     }
148 }
149
150 /// # Token Streams
151 ///
152 /// A `TokenStream` is an abstract sequence of tokens, organized into `TokenTree`s.
153 /// The goal is for procedural macros to work with `TokenStream`s and `TokenTree`s
154 /// instead of a representation of the abstract syntax tree.
155 /// Today's `TokenTree`s can still contain AST via `Token::Interpolated` for back-compat.
156 #[derive(Clone, Debug)]
157 pub struct TokenStream {
158     kind: TokenStreamKind,
159 }
160
161 // `TokenStream` is used a lot. Make sure it doesn't unintentionally get bigger.
162 #[cfg(target_arch = "x86_64")]
163 static_assert!(MEM_SIZE_OF_TOKEN_STREAM: mem::size_of::<TokenStream>() == 40);
164
165 impl TokenStream {
166     /// Given a `TokenStream` with a `Stream` of only two arguments, return a new `TokenStream`
167     /// separating the two arguments with a comma for diagnostic suggestions.
168     pub(crate) fn add_comma(&self) -> Option<(TokenStream, Span)> {
169         // Used to suggest if a user writes `foo!(a b);`
170         if let TokenStreamKind::Stream(ref slice) = self.kind {
171             let mut suggestion = None;
172             let mut iter = slice.iter().enumerate().peekable();
173             while let Some((pos, ts)) = iter.next() {
174                 if let Some((_, next)) = iter.peek() {
175                     let sp = match (&ts.kind, &next.kind) {
176                         (TokenStreamKind::Tree(TokenTree::Token(_, token::Token::Comma)), _) |
177                         (_, TokenStreamKind::Tree(TokenTree::Token(_, token::Token::Comma))) => {
178                             continue;
179                         }
180                         (TokenStreamKind::Tree(TokenTree::Token(sp, _)), _) => *sp,
181                         (TokenStreamKind::Tree(TokenTree::Delimited(sp, ..)), _) => sp.entire(),
182                         _ => continue,
183                     };
184                     let sp = sp.shrink_to_hi();
185                     let comma = TokenStream {
186                         kind: TokenStreamKind::Tree(TokenTree::Token(sp, token::Comma)),
187                     };
188                     suggestion = Some((pos, comma, sp));
189                 }
190             }
191             if let Some((pos, comma, sp)) = suggestion {
192                 let mut new_slice = vec![];
193                 let parts = slice.split_at(pos + 1);
194                 new_slice.extend_from_slice(parts.0);
195                 new_slice.push(comma);
196                 new_slice.extend_from_slice(parts.1);
197                 let slice = RcVec::new(new_slice);
198                 return Some((TokenStream { kind: TokenStreamKind::Stream(slice) }, sp));
199             }
200         }
201         None
202     }
203 }
204
205 #[derive(Clone, Debug)]
206 enum TokenStreamKind {
207     Empty,
208     Tree(TokenTree),
209     JointTree(TokenTree),
210     Stream(RcVec<TokenStream>),
211 }
212
213 impl From<TokenTree> for TokenStream {
214     fn from(tt: TokenTree) -> TokenStream {
215         TokenStream { kind: TokenStreamKind::Tree(tt) }
216     }
217 }
218
219 impl From<Token> for TokenStream {
220     fn from(token: Token) -> TokenStream {
221         TokenTree::Token(DUMMY_SP, token).into()
222     }
223 }
224
225 impl<T: Into<TokenStream>> iter::FromIterator<T> for TokenStream {
226     fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
227         TokenStream::concat(iter.into_iter().map(Into::into).collect::<Vec<_>>())
228     }
229 }
230
231 impl Extend<TokenStream> for TokenStream {
232     fn extend<I: IntoIterator<Item = TokenStream>>(&mut self, iter: I) {
233         let iter = iter.into_iter();
234         let kind = mem::replace(&mut self.kind, TokenStreamKind::Empty);
235
236         // Vector of token streams originally in self.
237         let tts: Vec<TokenStream> = match kind {
238             TokenStreamKind::Empty => {
239                 let mut vec = Vec::new();
240                 vec.reserve(iter.size_hint().0);
241                 vec
242             }
243             TokenStreamKind::Tree(_) | TokenStreamKind::JointTree(_) => {
244                 let mut vec = Vec::new();
245                 vec.reserve(1 + iter.size_hint().0);
246                 vec.push(TokenStream { kind });
247                 vec
248             }
249             TokenStreamKind::Stream(rc_vec) => match RcVec::try_unwrap(rc_vec) {
250                 Ok(mut vec) => {
251                     // Extend in place using the existing capacity if possible.
252                     // This is the fast path for libraries like `quote` that
253                     // build a token stream.
254                     vec.reserve(iter.size_hint().0);
255                     vec
256                 }
257                 Err(rc_vec) => {
258                     // Self is shared so we need to copy and extend that.
259                     let mut vec = Vec::new();
260                     vec.reserve(rc_vec.len() + iter.size_hint().0);
261                     vec.extend_from_slice(&rc_vec);
262                     vec
263                 }
264             }
265         };
266
267         // Perform the extend, joining tokens as needed along the way.
268         let mut builder = TokenStreamBuilder(tts);
269         for stream in iter {
270             builder.push(stream);
271         }
272
273         // Build the resulting token stream. If it contains more than one token,
274         // preserve capacity in the vector in anticipation of the caller
275         // performing additional calls to extend.
276         let mut tts = builder.0;
277         *self = match tts.len() {
278             0 => TokenStream::empty(),
279             1 => tts.pop().unwrap(),
280             _ => TokenStream::concat_rc_vec(RcVec::new_preserving_capacity(tts)),
281         };
282     }
283 }
284
285 impl Eq for TokenStream {}
286
287 impl PartialEq<TokenStream> for TokenStream {
288     fn eq(&self, other: &TokenStream) -> bool {
289         self.trees().eq(other.trees())
290     }
291 }
292
293 impl TokenStream {
294     pub fn len(&self) -> usize {
295         if let TokenStreamKind::Stream(ref slice) = self.kind {
296             slice.len()
297         } else {
298             0
299         }
300     }
301
302     pub fn empty() -> TokenStream {
303         TokenStream { kind: TokenStreamKind::Empty }
304     }
305
306     pub fn is_empty(&self) -> bool {
307         match self.kind {
308             TokenStreamKind::Empty => true,
309             _ => false,
310         }
311     }
312
313     pub fn concat(mut streams: Vec<TokenStream>) -> TokenStream {
314         match streams.len() {
315             0 => TokenStream::empty(),
316             1 => streams.pop().unwrap(),
317             _ => TokenStream::concat_rc_vec(RcVec::new(streams)),
318         }
319     }
320
321     fn concat_rc_vec(streams: RcVec<TokenStream>) -> TokenStream {
322         TokenStream { kind: TokenStreamKind::Stream(streams) }
323     }
324
325     pub fn trees(&self) -> Cursor {
326         self.clone().into_trees()
327     }
328
329     pub fn into_trees(self) -> Cursor {
330         Cursor::new(self)
331     }
332
333     /// Compares two TokenStreams, checking equality without regarding span information.
334     pub fn eq_unspanned(&self, other: &TokenStream) -> bool {
335         let mut t1 = self.trees();
336         let mut t2 = other.trees();
337         for (t1, t2) in t1.by_ref().zip(t2.by_ref()) {
338             if !t1.eq_unspanned(&t2) {
339                 return false;
340             }
341         }
342         t1.next().is_none() && t2.next().is_none()
343     }
344
345     // See comments in `interpolated_to_tokenstream` for why we care about
346     // *probably* equal here rather than actual equality
347     //
348     // This is otherwise the same as `eq_unspanned`, only recursing with a
349     // different method.
350     pub fn probably_equal_for_proc_macro(&self, other: &TokenStream) -> bool {
351         // When checking for `probably_eq`, we ignore certain tokens that aren't
352         // preserved in the AST. Because they are not preserved, the pretty
353         // printer arbitrarily adds or removes them when printing as token
354         // streams, making a comparison between a token stream generated from an
355         // AST and a token stream which was parsed into an AST more reliable.
356         fn semantic_tree(tree: &TokenTree) -> bool {
357             match tree {
358                 // The pretty printer tends to add trailing commas to
359                 // everything, and in particular, after struct fields.
360                 | TokenTree::Token(_, Token::Comma)
361                 // The pretty printer emits `NoDelim` as whitespace.
362                 | TokenTree::Token(_, Token::OpenDelim(DelimToken::NoDelim))
363                 | TokenTree::Token(_, Token::CloseDelim(DelimToken::NoDelim))
364                 // The pretty printer collapses many semicolons into one.
365                 | TokenTree::Token(_, Token::Semi)
366                 // The pretty printer collapses whitespace arbitrarily and can
367                 // introduce whitespace from `NoDelim`.
368                 | TokenTree::Token(_, Token::Whitespace) => false,
369                 _ => true
370             }
371         }
372
373         let mut t1 = self.trees().filter(semantic_tree);
374         let mut t2 = other.trees().filter(semantic_tree);
375         for (t1, t2) in t1.by_ref().zip(t2.by_ref()) {
376             if !t1.probably_equal_for_proc_macro(&t2) {
377                 return false;
378             }
379         }
380         t1.next().is_none() && t2.next().is_none()
381     }
382
383     /// Precondition: `self` consists of a single token tree.
384     /// Returns true if the token tree is a joint operation w.r.t. `proc_macro::TokenNode`.
385     pub fn as_tree(self) -> (TokenTree, bool /* joint? */) {
386         match self.kind {
387             TokenStreamKind::Tree(tree) => (tree, false),
388             TokenStreamKind::JointTree(tree) => (tree, true),
389             _ => unreachable!(),
390         }
391     }
392
393     pub fn map_enumerated<F: FnMut(usize, TokenTree) -> TokenTree>(self, mut f: F) -> TokenStream {
394         let mut trees = self.into_trees();
395         let mut result = Vec::new();
396         let mut i = 0;
397         while let Some(stream) = trees.next_as_stream() {
398             result.push(match stream.kind {
399                 TokenStreamKind::Tree(tree) => f(i, tree).into(),
400                 TokenStreamKind::JointTree(tree) => f(i, tree).joint(),
401                 _ => unreachable!()
402             });
403             i += 1;
404         }
405         TokenStream::concat(result)
406     }
407
408     pub fn map<F: FnMut(TokenTree) -> TokenTree>(self, mut f: F) -> TokenStream {
409         let mut trees = self.into_trees();
410         let mut result = Vec::new();
411         while let Some(stream) = trees.next_as_stream() {
412             result.push(match stream.kind {
413                 TokenStreamKind::Tree(tree) => f(tree).into(),
414                 TokenStreamKind::JointTree(tree) => f(tree).joint(),
415                 _ => unreachable!()
416             });
417         }
418         TokenStream::concat(result)
419     }
420
421     fn first_tree_and_joint(&self) -> Option<(TokenTree, bool)> {
422         match self.kind {
423             TokenStreamKind::Empty => None,
424             TokenStreamKind::Tree(ref tree) => Some((tree.clone(), false)),
425             TokenStreamKind::JointTree(ref tree) => Some((tree.clone(), true)),
426             TokenStreamKind::Stream(ref stream) => stream.first().unwrap().first_tree_and_joint(),
427         }
428     }
429
430     fn last_tree_if_joint(&self) -> Option<TokenTree> {
431         match self.kind {
432             TokenStreamKind::Empty | TokenStreamKind::Tree(..) => None,
433             TokenStreamKind::JointTree(ref tree) => Some(tree.clone()),
434             TokenStreamKind::Stream(ref stream) => stream.last().unwrap().last_tree_if_joint(),
435         }
436     }
437 }
438
439 #[derive(Clone)]
440 pub struct TokenStreamBuilder(Vec<TokenStream>);
441
442 impl TokenStreamBuilder {
443     pub fn new() -> TokenStreamBuilder {
444         TokenStreamBuilder(Vec::new())
445     }
446
447     pub fn push<T: Into<TokenStream>>(&mut self, stream: T) {
448         let stream = stream.into();
449         let last_tree_if_joint = self.0.last().and_then(TokenStream::last_tree_if_joint);
450         if let Some(TokenTree::Token(last_span, last_tok)) = last_tree_if_joint {
451             if let Some((TokenTree::Token(span, tok), is_joint)) = stream.first_tree_and_joint() {
452                 if let Some(glued_tok) = last_tok.glue(tok) {
453                     let last_stream = self.0.pop().unwrap();
454                     self.push_all_but_last_tree(&last_stream);
455                     let glued_span = last_span.to(span);
456                     let glued_tt = TokenTree::Token(glued_span, glued_tok);
457                     let glued_tokenstream = if is_joint {
458                         glued_tt.joint()
459                     } else {
460                         glued_tt.into()
461                     };
462                     self.0.push(glued_tokenstream);
463                     self.push_all_but_first_tree(&stream);
464                     return
465                 }
466             }
467         }
468         self.0.push(stream);
469     }
470
471     pub fn add<T: Into<TokenStream>>(mut self, stream: T) -> Self {
472         self.push(stream);
473         self
474     }
475
476     pub fn build(self) -> TokenStream {
477         TokenStream::concat(self.0)
478     }
479
480     fn push_all_but_last_tree(&mut self, stream: &TokenStream) {
481         if let TokenStreamKind::Stream(ref streams) = stream.kind {
482             let len = streams.len();
483             match len {
484                 1 => {}
485                 2 => self.0.push(streams[0].clone().into()),
486                 _ => self.0.push(TokenStream::concat_rc_vec(streams.sub_slice(0 .. len - 1))),
487             }
488             self.push_all_but_last_tree(&streams[len - 1])
489         }
490     }
491
492     fn push_all_but_first_tree(&mut self, stream: &TokenStream) {
493         if let TokenStreamKind::Stream(ref streams) = stream.kind {
494             let len = streams.len();
495             match len {
496                 1 => {}
497                 2 => self.0.push(streams[1].clone().into()),
498                 _ => self.0.push(TokenStream::concat_rc_vec(streams.sub_slice(1 .. len))),
499             }
500             self.push_all_but_first_tree(&streams[0])
501         }
502     }
503 }
504
505 #[derive(Clone)]
506 pub struct Cursor(CursorKind);
507
508 #[derive(Clone)]
509 enum CursorKind {
510     Empty,
511     Tree(TokenTree, bool /* consumed? */),
512     JointTree(TokenTree, bool /* consumed? */),
513     Stream(StreamCursor),
514 }
515
516 #[derive(Clone)]
517 struct StreamCursor {
518     stream: RcVec<TokenStream>,
519     index: usize,
520     stack: Vec<(RcVec<TokenStream>, usize)>,
521 }
522
523 impl StreamCursor {
524     fn new(stream: RcVec<TokenStream>) -> Self {
525         StreamCursor { stream: stream, index: 0, stack: Vec::new() }
526     }
527
528     fn next_as_stream(&mut self) -> Option<TokenStream> {
529         loop {
530             if self.index < self.stream.len() {
531                 self.index += 1;
532                 let next = self.stream[self.index - 1].clone();
533                 match next.kind {
534                     TokenStreamKind::Tree(..) | TokenStreamKind::JointTree(..) => return Some(next),
535                     TokenStreamKind::Stream(stream) => self.insert(stream),
536                     TokenStreamKind::Empty => {}
537                 }
538             } else if let Some((stream, index)) = self.stack.pop() {
539                 self.stream = stream;
540                 self.index = index;
541             } else {
542                 return None;
543             }
544         }
545     }
546
547     fn insert(&mut self, stream: RcVec<TokenStream>) {
548         self.stack.push((mem::replace(&mut self.stream, stream),
549                          mem::replace(&mut self.index, 0)));
550     }
551 }
552
553 impl Iterator for Cursor {
554     type Item = TokenTree;
555
556     fn next(&mut self) -> Option<TokenTree> {
557         self.next_as_stream().map(|stream| match stream.kind {
558             TokenStreamKind::Tree(tree) | TokenStreamKind::JointTree(tree) => tree,
559             _ => unreachable!()
560         })
561     }
562 }
563
564 impl Cursor {
565     fn new(stream: TokenStream) -> Self {
566         Cursor(match stream.kind {
567             TokenStreamKind::Empty => CursorKind::Empty,
568             TokenStreamKind::Tree(tree) => CursorKind::Tree(tree, false),
569             TokenStreamKind::JointTree(tree) => CursorKind::JointTree(tree, false),
570             TokenStreamKind::Stream(stream) => CursorKind::Stream(StreamCursor::new(stream)),
571         })
572     }
573
574     pub fn next_as_stream(&mut self) -> Option<TokenStream> {
575         let (stream, consumed) = match self.0 {
576             CursorKind::Tree(ref tree, ref mut consumed @ false) =>
577                 (tree.clone().into(), consumed),
578             CursorKind::JointTree(ref tree, ref mut consumed @ false) =>
579                 (tree.clone().joint(), consumed),
580             CursorKind::Stream(ref mut cursor) => return cursor.next_as_stream(),
581             _ => return None,
582         };
583
584         *consumed = true;
585         Some(stream)
586     }
587
588     pub fn insert(&mut self, stream: TokenStream) {
589         match self.0 {
590             _ if stream.is_empty() => return,
591             CursorKind::Empty => *self = stream.trees(),
592             CursorKind::Tree(_, consumed) | CursorKind::JointTree(_, consumed) => {
593                 *self = TokenStream::concat(vec![self.original_stream(), stream]).trees();
594                 if consumed {
595                     self.next();
596                 }
597             }
598             CursorKind::Stream(ref mut cursor) => {
599                 cursor.insert(ThinTokenStream::from(stream).0.unwrap());
600             }
601         }
602     }
603
604     pub fn original_stream(&self) -> TokenStream {
605         match self.0 {
606             CursorKind::Empty => TokenStream::empty(),
607             CursorKind::Tree(ref tree, _) => tree.clone().into(),
608             CursorKind::JointTree(ref tree, _) => tree.clone().joint(),
609             CursorKind::Stream(ref cursor) => TokenStream::concat_rc_vec({
610                 cursor.stack.get(0).cloned().map(|(stream, _)| stream)
611                     .unwrap_or_else(|| cursor.stream.clone())
612             }),
613         }
614     }
615
616     pub fn look_ahead(&self, n: usize) -> Option<TokenTree> {
617         fn look_ahead(streams: &[TokenStream], mut n: usize) -> Result<TokenTree, usize> {
618             for stream in streams {
619                 n = match stream.kind {
620                     TokenStreamKind::Tree(ref tree) | TokenStreamKind::JointTree(ref tree)
621                         if n == 0 => return Ok(tree.clone()),
622                     TokenStreamKind::Tree(..) | TokenStreamKind::JointTree(..) => n - 1,
623                     TokenStreamKind::Stream(ref stream) => match look_ahead(stream, n) {
624                         Ok(tree) => return Ok(tree),
625                         Err(n) => n,
626                     },
627                     _ => n,
628                 };
629             }
630             Err(n)
631         }
632
633         match self.0 {
634             CursorKind::Empty |
635             CursorKind::Tree(_, true) |
636             CursorKind::JointTree(_, true) => Err(n),
637             CursorKind::Tree(ref tree, false) |
638             CursorKind::JointTree(ref tree, false) => look_ahead(&[tree.clone().into()], n),
639             CursorKind::Stream(ref cursor) => {
640                 look_ahead(&cursor.stream[cursor.index ..], n).or_else(|mut n| {
641                     for &(ref stream, index) in cursor.stack.iter().rev() {
642                         n = match look_ahead(&stream[index..], n) {
643                             Ok(tree) => return Ok(tree),
644                             Err(n) => n,
645                         }
646                     }
647
648                     Err(n)
649                 })
650             }
651         }.ok()
652     }
653 }
654
655 /// The `TokenStream` type is large enough to represent a single `TokenTree` without allocation.
656 /// `ThinTokenStream` is smaller, but needs to allocate to represent a single `TokenTree`.
657 /// We must use `ThinTokenStream` in `TokenTree::Delimited` to avoid infinite size due to recursion.
658 #[derive(Debug, Clone)]
659 pub struct ThinTokenStream(Option<RcVec<TokenStream>>);
660
661 impl ThinTokenStream {
662     pub fn stream(&self) -> TokenStream {
663         self.clone().into()
664     }
665 }
666
667 impl From<TokenStream> for ThinTokenStream {
668     fn from(stream: TokenStream) -> ThinTokenStream {
669         ThinTokenStream(match stream.kind {
670             TokenStreamKind::Empty => None,
671             TokenStreamKind::Tree(tree) => Some(RcVec::new(vec![tree.into()])),
672             TokenStreamKind::JointTree(tree) => Some(RcVec::new(vec![tree.joint()])),
673             TokenStreamKind::Stream(stream) => Some(stream),
674         })
675     }
676 }
677
678 impl From<ThinTokenStream> for TokenStream {
679     fn from(stream: ThinTokenStream) -> TokenStream {
680         stream.0.map(TokenStream::concat_rc_vec).unwrap_or_else(TokenStream::empty)
681     }
682 }
683
684 impl Eq for ThinTokenStream {}
685
686 impl PartialEq<ThinTokenStream> for ThinTokenStream {
687     fn eq(&self, other: &ThinTokenStream) -> bool {
688         TokenStream::from(self.clone()) == TokenStream::from(other.clone())
689     }
690 }
691
692 impl fmt::Display for TokenStream {
693     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
694         f.write_str(&pprust::tokens_to_string(self.clone()))
695     }
696 }
697
698 impl Encodable for TokenStream {
699     fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), E::Error> {
700         self.trees().collect::<Vec<_>>().encode(encoder)
701     }
702 }
703
704 impl Decodable for TokenStream {
705     fn decode<D: Decoder>(decoder: &mut D) -> Result<TokenStream, D::Error> {
706         Vec::<TokenTree>::decode(decoder).map(|vec| vec.into_iter().collect())
707     }
708 }
709
710 impl Encodable for ThinTokenStream {
711     fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), E::Error> {
712         TokenStream::from(self.clone()).encode(encoder)
713     }
714 }
715
716 impl Decodable for ThinTokenStream {
717     fn decode<D: Decoder>(decoder: &mut D) -> Result<ThinTokenStream, D::Error> {
718         TokenStream::decode(decoder).map(Into::into)
719     }
720 }
721
722 #[derive(Debug, Copy, Clone, PartialEq, RustcEncodable, RustcDecodable)]
723 pub struct DelimSpan {
724     pub open: Span,
725     pub close: Span,
726 }
727
728 impl DelimSpan {
729     pub fn from_single(sp: Span) -> Self {
730         DelimSpan {
731             open: sp,
732             close: sp,
733         }
734     }
735
736     pub fn from_pair(open: Span, close: Span) -> Self {
737         DelimSpan { open, close }
738     }
739
740     pub fn dummy() -> Self {
741         Self::from_single(DUMMY_SP)
742     }
743
744     pub fn entire(self) -> Span {
745         self.open.with_hi(self.close.hi())
746     }
747
748     pub fn apply_mark(self, mark: Mark) -> Self {
749         DelimSpan {
750             open: self.open.apply_mark(mark),
751             close: self.close.apply_mark(mark),
752         }
753     }
754 }
755
756 #[cfg(test)]
757 mod tests {
758     use super::*;
759     use syntax::ast::Ident;
760     use with_globals;
761     use syntax_pos::{Span, BytePos, NO_EXPANSION};
762     use parse::token::Token;
763     use util::parser_testing::string_to_stream;
764
765     fn string_to_ts(string: &str) -> TokenStream {
766         string_to_stream(string.to_owned())
767     }
768
769     fn sp(a: u32, b: u32) -> Span {
770         Span::new(BytePos(a), BytePos(b), NO_EXPANSION)
771     }
772
773     #[test]
774     fn test_concat() {
775         with_globals(|| {
776             let test_res = string_to_ts("foo::bar::baz");
777             let test_fst = string_to_ts("foo::bar");
778             let test_snd = string_to_ts("::baz");
779             let eq_res = TokenStream::concat(vec![test_fst, test_snd]);
780             assert_eq!(test_res.trees().count(), 5);
781             assert_eq!(eq_res.trees().count(), 5);
782             assert_eq!(test_res.eq_unspanned(&eq_res), true);
783         })
784     }
785
786     #[test]
787     fn test_to_from_bijection() {
788         with_globals(|| {
789             let test_start = string_to_ts("foo::bar(baz)");
790             let test_end = test_start.trees().collect();
791             assert_eq!(test_start, test_end)
792         })
793     }
794
795     #[test]
796     fn test_eq_0() {
797         with_globals(|| {
798             let test_res = string_to_ts("foo");
799             let test_eqs = string_to_ts("foo");
800             assert_eq!(test_res, test_eqs)
801         })
802     }
803
804     #[test]
805     fn test_eq_1() {
806         with_globals(|| {
807             let test_res = string_to_ts("::bar::baz");
808             let test_eqs = string_to_ts("::bar::baz");
809             assert_eq!(test_res, test_eqs)
810         })
811     }
812
813     #[test]
814     fn test_eq_3() {
815         with_globals(|| {
816             let test_res = string_to_ts("");
817             let test_eqs = string_to_ts("");
818             assert_eq!(test_res, test_eqs)
819         })
820     }
821
822     #[test]
823     fn test_diseq_0() {
824         with_globals(|| {
825             let test_res = string_to_ts("::bar::baz");
826             let test_eqs = string_to_ts("bar::baz");
827             assert_eq!(test_res == test_eqs, false)
828         })
829     }
830
831     #[test]
832     fn test_diseq_1() {
833         with_globals(|| {
834             let test_res = string_to_ts("(bar,baz)");
835             let test_eqs = string_to_ts("bar,baz");
836             assert_eq!(test_res == test_eqs, false)
837         })
838     }
839
840     #[test]
841     fn test_is_empty() {
842         with_globals(|| {
843             let test0: TokenStream = Vec::<TokenTree>::new().into_iter().collect();
844             let test1: TokenStream =
845                 TokenTree::Token(sp(0, 1), Token::Ident(Ident::from_str("a"), false)).into();
846             let test2 = string_to_ts("foo(bar::baz)");
847
848             assert_eq!(test0.is_empty(), true);
849             assert_eq!(test1.is_empty(), false);
850             assert_eq!(test2.is_empty(), false);
851         })
852     }
853
854     #[test]
855     fn test_dotdotdot() {
856         let mut builder = TokenStreamBuilder::new();
857         builder.push(TokenTree::Token(sp(0, 1), Token::Dot).joint());
858         builder.push(TokenTree::Token(sp(1, 2), Token::Dot).joint());
859         builder.push(TokenTree::Token(sp(2, 3), Token::Dot));
860         let stream = builder.build();
861         assert!(stream.eq_unspanned(&string_to_ts("...")));
862         assert_eq!(stream.trees().count(), 1);
863     }
864
865     #[test]
866     fn test_extend_empty() {
867         with_globals(|| {
868             // Append a token onto an empty token stream.
869             let mut stream = TokenStream::empty();
870             stream.extend(vec![string_to_ts("t")]);
871
872             let expected = string_to_ts("t");
873             assert!(stream.eq_unspanned(&expected));
874         });
875     }
876
877     #[test]
878     fn test_extend_nothing() {
879         with_globals(|| {
880             // Append nothing onto a token stream containing one token.
881             let mut stream = string_to_ts("t");
882             stream.extend(vec![]);
883
884             let expected = string_to_ts("t");
885             assert!(stream.eq_unspanned(&expected));
886         });
887     }
888
889     #[test]
890     fn test_extend_single() {
891         with_globals(|| {
892             // Append a token onto token stream containing a single token.
893             let mut stream = string_to_ts("t1");
894             stream.extend(vec![string_to_ts("t2")]);
895
896             let expected = string_to_ts("t1 t2");
897             assert!(stream.eq_unspanned(&expected));
898         });
899     }
900
901     #[test]
902     fn test_extend_in_place() {
903         with_globals(|| {
904             // Append a token onto token stream containing a reference counted
905             // vec of tokens. The token stream has a reference count of 1 so
906             // this can happen in place.
907             let mut stream = string_to_ts("t1 t2");
908             stream.extend(vec![string_to_ts("t3")]);
909
910             let expected = string_to_ts("t1 t2 t3");
911             assert!(stream.eq_unspanned(&expected));
912         });
913     }
914
915     #[test]
916     fn test_extend_copy() {
917         with_globals(|| {
918             // Append a token onto token stream containing a reference counted
919             // vec of tokens. The token stream is shared so the extend takes
920             // place on a copy.
921             let mut stream = string_to_ts("t1 t2");
922             let _incref = stream.clone();
923             stream.extend(vec![string_to_ts("t3")]);
924
925             let expected = string_to_ts("t1 t2 t3");
926             assert!(stream.eq_unspanned(&expected));
927         });
928     }
929
930     #[test]
931     fn test_extend_no_join() {
932         with_globals(|| {
933             let first = TokenTree::Token(DUMMY_SP, Token::Dot);
934             let second = TokenTree::Token(DUMMY_SP, Token::Dot);
935
936             // Append a dot onto a token stream containing a dot, but do not
937             // join them.
938             let mut stream = TokenStream::from(first);
939             stream.extend(vec![TokenStream::from(second)]);
940
941             let expected = string_to_ts(". .");
942             assert!(stream.eq_unspanned(&expected));
943
944             let unexpected = string_to_ts("..");
945             assert!(!stream.eq_unspanned(&unexpected));
946         });
947     }
948
949     #[test]
950     fn test_extend_join() {
951         with_globals(|| {
952             let first = TokenTree::Token(DUMMY_SP, Token::Dot).joint();
953             let second = TokenTree::Token(DUMMY_SP, Token::Dot);
954
955             // Append a dot onto a token stream containing a dot, forming a
956             // dotdot.
957             let mut stream = first;
958             stream.extend(vec![TokenStream::from(second)]);
959
960             let expected = string_to_ts("..");
961             assert!(stream.eq_unspanned(&expected));
962
963             let unexpected = string_to_ts(". .");
964             assert!(!stream.eq_unspanned(&unexpected));
965         });
966     }
967 }