]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/tokenstream.rs
Rename `TokenStream::concat` and remove `TokenStream::concat_rc_vec`.
[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 rustc_data_structures::sync::Lrc;
32 use serialize::{Decoder, Decodable, Encoder, Encodable};
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::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 enum TokenStream {
158     Empty,
159     Tree(TokenTree),
160     JointTree(TokenTree),
161     Stream(Lrc<Vec<TokenStream>>),
162 }
163
164 // `TokenStream` is used a lot. Make sure it doesn't unintentionally get bigger.
165 #[cfg(target_arch = "x86_64")]
166 static_assert!(MEM_SIZE_OF_TOKEN_STREAM: mem::size_of::<TokenStream>() == 32);
167
168 impl TokenStream {
169     /// Given a `TokenStream` with a `Stream` of only two arguments, return a new `TokenStream`
170     /// separating the two arguments with a comma for diagnostic suggestions.
171     pub(crate) fn add_comma(&self) -> Option<(TokenStream, Span)> {
172         // Used to suggest if a user writes `foo!(a b);`
173         if let TokenStream::Stream(ref stream) = self {
174             let mut suggestion = None;
175             let mut iter = stream.iter().enumerate().peekable();
176             while let Some((pos, ts)) = iter.next() {
177                 if let Some((_, next)) = iter.peek() {
178                     let sp = match (&ts, &next) {
179                         (TokenStream::Tree(TokenTree::Token(_, token::Token::Comma)), _) |
180                         (_, TokenStream::Tree(TokenTree::Token(_, token::Token::Comma))) => {
181                             continue;
182                         }
183                         (TokenStream::Tree(TokenTree::Token(sp, _)), _) => *sp,
184                         (TokenStream::Tree(TokenTree::Delimited(sp, ..)), _) => sp.entire(),
185                         _ => continue,
186                     };
187                     let sp = sp.shrink_to_hi();
188                     let comma = TokenStream::Tree(TokenTree::Token(sp, token::Comma));
189                     suggestion = Some((pos, comma, sp));
190                 }
191             }
192             if let Some((pos, comma, sp)) = suggestion {
193                 let mut new_stream = vec![];
194                 let parts = stream.split_at(pos + 1);
195                 new_stream.extend_from_slice(parts.0);
196                 new_stream.push(comma);
197                 new_stream.extend_from_slice(parts.1);
198                 return Some((TokenStream::new(new_stream), sp));
199             }
200         }
201         None
202     }
203 }
204
205 impl From<TokenTree> for TokenStream {
206     fn from(tt: TokenTree) -> TokenStream {
207         TokenStream::Tree(tt)
208     }
209 }
210
211 impl From<Token> for TokenStream {
212     fn from(token: Token) -> TokenStream {
213         TokenTree::Token(DUMMY_SP, token).into()
214     }
215 }
216
217 impl<T: Into<TokenStream>> iter::FromIterator<T> for TokenStream {
218     fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
219         TokenStream::new(iter.into_iter().map(Into::into).collect::<Vec<_>>())
220     }
221 }
222
223 impl Extend<TokenStream> for TokenStream {
224     fn extend<I: IntoIterator<Item = TokenStream>>(&mut self, iter: I) {
225         let iter = iter.into_iter();
226         let this = mem::replace(self, TokenStream::Empty);
227
228         // Vector of token streams originally in self.
229         let tts: Vec<TokenStream> = match this {
230             TokenStream::Empty => {
231                 let mut vec = Vec::new();
232                 vec.reserve(iter.size_hint().0);
233                 vec
234             }
235             TokenStream::Tree(_) | TokenStream::JointTree(_) => {
236                 let mut vec = Vec::new();
237                 vec.reserve(1 + iter.size_hint().0);
238                 vec.push(this);
239                 vec
240             }
241             TokenStream::Stream(rc_vec) => match Lrc::try_unwrap(rc_vec) {
242                 Ok(mut vec) => {
243                     // Extend in place using the existing capacity if possible.
244                     // This is the fast path for libraries like `quote` that
245                     // build a token stream.
246                     vec.reserve(iter.size_hint().0);
247                     vec
248                 }
249                 Err(rc_vec) => {
250                     // Self is shared so we need to copy and extend that.
251                     let mut vec = Vec::new();
252                     vec.reserve(rc_vec.len() + iter.size_hint().0);
253                     vec.extend_from_slice(&rc_vec);
254                     vec
255                 }
256             }
257         };
258
259         // Perform the extend, joining tokens as needed along the way.
260         let mut builder = TokenStreamBuilder(tts);
261         for stream in iter {
262             builder.push(stream);
263         }
264
265         // Build the resulting token stream. If it contains more than one token,
266         // preserve capacity in the vector in anticipation of the caller
267         // performing additional calls to extend.
268         *self = TokenStream::new(builder.0);
269     }
270 }
271
272 impl Eq for TokenStream {}
273
274 impl PartialEq<TokenStream> for TokenStream {
275     fn eq(&self, other: &TokenStream) -> bool {
276         self.trees().eq(other.trees())
277     }
278 }
279
280 impl TokenStream {
281     pub fn len(&self) -> usize {
282         if let TokenStream::Stream(ref slice) = self {
283             slice.len()
284         } else {
285             0
286         }
287     }
288
289     pub fn empty() -> TokenStream {
290         TokenStream::Empty
291     }
292
293     pub fn is_empty(&self) -> bool {
294         match self {
295             TokenStream::Empty => true,
296             _ => false,
297         }
298     }
299
300     pub fn new(mut streams: Vec<TokenStream>) -> TokenStream {
301         match streams.len() {
302             0 => TokenStream::empty(),
303             1 => streams.pop().unwrap(),
304             _ => TokenStream::Stream(Lrc::new(streams)),
305         }
306     }
307
308     pub fn trees(&self) -> Cursor {
309         self.clone().into_trees()
310     }
311
312     pub fn into_trees(self) -> Cursor {
313         Cursor::new(self)
314     }
315
316     /// Compares two TokenStreams, checking equality without regarding span information.
317     pub fn eq_unspanned(&self, other: &TokenStream) -> bool {
318         let mut t1 = self.trees();
319         let mut t2 = other.trees();
320         for (t1, t2) in t1.by_ref().zip(t2.by_ref()) {
321             if !t1.eq_unspanned(&t2) {
322                 return false;
323             }
324         }
325         t1.next().is_none() && t2.next().is_none()
326     }
327
328     // See comments in `interpolated_to_tokenstream` for why we care about
329     // *probably* equal here rather than actual equality
330     //
331     // This is otherwise the same as `eq_unspanned`, only recursing with a
332     // different method.
333     pub fn probably_equal_for_proc_macro(&self, other: &TokenStream) -> bool {
334         // When checking for `probably_eq`, we ignore certain tokens that aren't
335         // preserved in the AST. Because they are not preserved, the pretty
336         // printer arbitrarily adds or removes them when printing as token
337         // streams, making a comparison between a token stream generated from an
338         // AST and a token stream which was parsed into an AST more reliable.
339         fn semantic_tree(tree: &TokenTree) -> bool {
340             match tree {
341                 // The pretty printer tends to add trailing commas to
342                 // everything, and in particular, after struct fields.
343                 | TokenTree::Token(_, Token::Comma)
344                 // The pretty printer emits `NoDelim` as whitespace.
345                 | TokenTree::Token(_, Token::OpenDelim(DelimToken::NoDelim))
346                 | TokenTree::Token(_, Token::CloseDelim(DelimToken::NoDelim))
347                 // The pretty printer collapses many semicolons into one.
348                 | TokenTree::Token(_, Token::Semi)
349                 // The pretty printer collapses whitespace arbitrarily and can
350                 // introduce whitespace from `NoDelim`.
351                 | TokenTree::Token(_, Token::Whitespace) => false,
352                 _ => true
353             }
354         }
355
356         let mut t1 = self.trees().filter(semantic_tree);
357         let mut t2 = other.trees().filter(semantic_tree);
358         for (t1, t2) in t1.by_ref().zip(t2.by_ref()) {
359             if !t1.probably_equal_for_proc_macro(&t2) {
360                 return false;
361             }
362         }
363         t1.next().is_none() && t2.next().is_none()
364     }
365
366     /// Precondition: `self` consists of a single token tree.
367     /// Returns true if the token tree is a joint operation w.r.t. `proc_macro::TokenNode`.
368     pub fn as_tree(self) -> (TokenTree, bool /* joint? */) {
369         match self {
370             TokenStream::Tree(tree) => (tree, false),
371             TokenStream::JointTree(tree) => (tree, true),
372             _ => unreachable!(),
373         }
374     }
375
376     pub fn map_enumerated<F: FnMut(usize, TokenTree) -> TokenTree>(self, mut f: F) -> TokenStream {
377         let mut trees = self.into_trees();
378         let mut result = Vec::new();
379         let mut i = 0;
380         while let Some(stream) = trees.next_as_stream() {
381             result.push(match stream {
382                 TokenStream::Tree(tree) => f(i, tree).into(),
383                 TokenStream::JointTree(tree) => f(i, tree).joint(),
384                 _ => unreachable!()
385             });
386             i += 1;
387         }
388         TokenStream::new(result)
389     }
390
391     pub fn map<F: FnMut(TokenTree) -> TokenTree>(self, mut f: F) -> TokenStream {
392         let mut trees = self.into_trees();
393         let mut result = Vec::new();
394         while let Some(stream) = trees.next_as_stream() {
395             result.push(match stream {
396                 TokenStream::Tree(tree) => f(tree).into(),
397                 TokenStream::JointTree(tree) => f(tree).joint(),
398                 _ => unreachable!()
399             });
400         }
401         TokenStream::new(result)
402     }
403
404     fn first_tree_and_joint(&self) -> Option<(TokenTree, bool)> {
405         match self {
406             TokenStream::Empty => None,
407             TokenStream::Tree(ref tree) => Some((tree.clone(), false)),
408             TokenStream::JointTree(ref tree) => Some((tree.clone(), true)),
409             TokenStream::Stream(ref stream) => stream.first().unwrap().first_tree_and_joint(),
410         }
411     }
412
413     fn last_tree_if_joint(&self) -> Option<TokenTree> {
414         match self {
415             TokenStream::Empty | TokenStream::Tree(..) => None,
416             TokenStream::JointTree(ref tree) => Some(tree.clone()),
417             TokenStream::Stream(ref stream) => stream.last().unwrap().last_tree_if_joint(),
418         }
419     }
420 }
421
422 #[derive(Clone)]
423 pub struct TokenStreamBuilder(Vec<TokenStream>);
424
425 impl TokenStreamBuilder {
426     pub fn new() -> TokenStreamBuilder {
427         TokenStreamBuilder(Vec::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 = if is_joint {
441                         glued_tt.joint()
442                     } else {
443                         glued_tt.into()
444                     };
445                     self.0.push(glued_tokenstream);
446                     self.push_all_but_first_tree(&stream);
447                     return
448                 }
449             }
450         }
451         self.0.push(stream);
452     }
453
454     pub fn add<T: Into<TokenStream>>(mut self, stream: T) -> Self {
455         self.push(stream);
456         self
457     }
458
459     pub fn build(self) -> TokenStream {
460         TokenStream::new(self.0)
461     }
462
463     fn push_all_but_last_tree(&mut self, stream: &TokenStream) {
464         if let TokenStream::Stream(ref streams) = stream {
465             let len = streams.len();
466             match len {
467                 1 => {}
468                 2 => self.0.push(streams[0].clone().into()),
469                 _ => self.0.push(TokenStream::new(streams[0 .. len - 1].to_vec())),
470             }
471             self.push_all_but_last_tree(&streams[len - 1])
472         }
473     }
474
475     fn push_all_but_first_tree(&mut self, stream: &TokenStream) {
476         if let TokenStream::Stream(ref streams) = stream {
477             let len = streams.len();
478             match len {
479                 1 => {}
480                 2 => self.0.push(streams[1].clone().into()),
481                 _ => self.0.push(TokenStream::new(streams[1 .. len].to_vec())),
482             }
483             self.push_all_but_first_tree(&streams[0])
484         }
485     }
486 }
487
488 #[derive(Clone)]
489 pub struct Cursor(CursorKind);
490
491 #[derive(Clone)]
492 enum CursorKind {
493     Empty,
494     Tree(TokenTree, bool /* consumed? */),
495     JointTree(TokenTree, bool /* consumed? */),
496     Stream(StreamCursor),
497 }
498
499 #[derive(Clone)]
500 struct StreamCursor {
501     stream: Lrc<Vec<TokenStream>>,
502     index: usize,
503     stack: Vec<(Lrc<Vec<TokenStream>>, usize)>,
504 }
505
506 impl StreamCursor {
507     fn new(stream: Lrc<Vec<TokenStream>>) -> Self {
508         StreamCursor { stream: stream, index: 0, stack: Vec::new() }
509     }
510
511     fn next_as_stream(&mut self) -> Option<TokenStream> {
512         loop {
513             if self.index < self.stream.len() {
514                 self.index += 1;
515                 let next = self.stream[self.index - 1].clone();
516                 match next {
517                     TokenStream::Tree(..) | TokenStream::JointTree(..) => return Some(next),
518                     TokenStream::Stream(stream) => self.insert(stream),
519                     TokenStream::Empty => {}
520                 }
521             } else if let Some((stream, index)) = self.stack.pop() {
522                 self.stream = stream;
523                 self.index = index;
524             } else {
525                 return None;
526             }
527         }
528     }
529
530     fn insert(&mut self, stream: Lrc<Vec<TokenStream>>) {
531         self.stack.push((mem::replace(&mut self.stream, stream),
532                          mem::replace(&mut self.index, 0)));
533     }
534 }
535
536 impl Iterator for Cursor {
537     type Item = TokenTree;
538
539     fn next(&mut self) -> Option<TokenTree> {
540         self.next_as_stream().map(|stream| match stream {
541             TokenStream::Tree(tree) | TokenStream::JointTree(tree) => tree,
542             _ => unreachable!()
543         })
544     }
545 }
546
547 impl Cursor {
548     fn new(stream: TokenStream) -> Self {
549         Cursor(match stream {
550             TokenStream::Empty => CursorKind::Empty,
551             TokenStream::Tree(tree) => CursorKind::Tree(tree, false),
552             TokenStream::JointTree(tree) => CursorKind::JointTree(tree, false),
553             TokenStream::Stream(stream) => CursorKind::Stream(StreamCursor::new(stream)),
554         })
555     }
556
557     pub fn next_as_stream(&mut self) -> Option<TokenStream> {
558         let (stream, consumed) = match self.0 {
559             CursorKind::Tree(ref tree, ref mut consumed @ false) =>
560                 (tree.clone().into(), consumed),
561             CursorKind::JointTree(ref tree, ref mut consumed @ false) =>
562                 (tree.clone().joint(), consumed),
563             CursorKind::Stream(ref mut cursor) => return cursor.next_as_stream(),
564             _ => return None,
565         };
566
567         *consumed = true;
568         Some(stream)
569     }
570
571     pub fn insert(&mut self, stream: TokenStream) {
572         match self.0 {
573             _ if stream.is_empty() => return,
574             CursorKind::Empty => *self = stream.trees(),
575             CursorKind::Tree(_, consumed) | CursorKind::JointTree(_, consumed) => {
576                 *self = TokenStream::new(vec![self.original_stream(), stream]).trees();
577                 if consumed {
578                     self.next();
579                 }
580             }
581             CursorKind::Stream(ref mut cursor) => {
582                 cursor.insert(ThinTokenStream::from(stream).0.unwrap());
583             }
584         }
585     }
586
587     pub fn original_stream(&self) -> TokenStream {
588         match self.0 {
589             CursorKind::Empty => TokenStream::empty(),
590             CursorKind::Tree(ref tree, _) => tree.clone().into(),
591             CursorKind::JointTree(ref tree, _) => tree.clone().joint(),
592             CursorKind::Stream(ref cursor) => TokenStream::Stream(
593                 cursor.stack.get(0).cloned().map(|(stream, _)| stream)
594                     .unwrap_or_else(|| cursor.stream.clone())
595             ),
596         }
597     }
598
599     pub fn look_ahead(&self, n: usize) -> Option<TokenTree> {
600         fn look_ahead(streams: &[TokenStream], mut n: usize) -> Result<TokenTree, usize> {
601             for stream in streams {
602                 n = match stream {
603                     TokenStream::Tree(ref tree) | TokenStream::JointTree(ref tree)
604                         if n == 0 => return Ok(tree.clone()),
605                     TokenStream::Tree(..) | TokenStream::JointTree(..) => n - 1,
606                     TokenStream::Stream(ref stream) => match look_ahead(stream, n) {
607                         Ok(tree) => return Ok(tree),
608                         Err(n) => n,
609                     },
610                     _ => n,
611                 };
612             }
613             Err(n)
614         }
615
616         match self.0 {
617             CursorKind::Empty |
618             CursorKind::Tree(_, true) |
619             CursorKind::JointTree(_, true) => Err(n),
620             CursorKind::Tree(ref tree, false) |
621             CursorKind::JointTree(ref tree, false) => look_ahead(&[tree.clone().into()], n),
622             CursorKind::Stream(ref cursor) => {
623                 look_ahead(&cursor.stream[cursor.index ..], n).or_else(|mut n| {
624                     for &(ref stream, index) in cursor.stack.iter().rev() {
625                         n = match look_ahead(&stream[index..], n) {
626                             Ok(tree) => return Ok(tree),
627                             Err(n) => n,
628                         }
629                     }
630
631                     Err(n)
632                 })
633             }
634         }.ok()
635     }
636 }
637
638 /// The `TokenStream` type is large enough to represent a single `TokenTree` without allocation.
639 /// `ThinTokenStream` is smaller, but needs to allocate to represent a single `TokenTree`.
640 /// We must use `ThinTokenStream` in `TokenTree::Delimited` to avoid infinite size due to recursion.
641 #[derive(Debug, Clone)]
642 pub struct ThinTokenStream(Option<Lrc<Vec<TokenStream>>>);
643
644 impl ThinTokenStream {
645     pub fn stream(&self) -> TokenStream {
646         self.clone().into()
647     }
648 }
649
650 impl From<TokenStream> for ThinTokenStream {
651     fn from(stream: TokenStream) -> ThinTokenStream {
652         ThinTokenStream(match stream {
653             TokenStream::Empty => None,
654             TokenStream::Tree(tree) => Some(Lrc::new(vec![tree.into()])),
655             TokenStream::JointTree(tree) => Some(Lrc::new(vec![tree.joint()])),
656             TokenStream::Stream(stream) => Some(stream),
657         })
658     }
659 }
660
661 impl From<ThinTokenStream> for TokenStream {
662     fn from(stream: ThinTokenStream) -> TokenStream {
663         stream.0.map(TokenStream::Stream).unwrap_or_else(TokenStream::empty)
664     }
665 }
666
667 impl Eq for ThinTokenStream {}
668
669 impl PartialEq<ThinTokenStream> for ThinTokenStream {
670     fn eq(&self, other: &ThinTokenStream) -> bool {
671         TokenStream::from(self.clone()) == TokenStream::from(other.clone())
672     }
673 }
674
675 impl fmt::Display for TokenStream {
676     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
677         f.write_str(&pprust::tokens_to_string(self.clone()))
678     }
679 }
680
681 impl Encodable for TokenStream {
682     fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), E::Error> {
683         self.trees().collect::<Vec<_>>().encode(encoder)
684     }
685 }
686
687 impl Decodable for TokenStream {
688     fn decode<D: Decoder>(decoder: &mut D) -> Result<TokenStream, D::Error> {
689         Vec::<TokenTree>::decode(decoder).map(|vec| vec.into_iter().collect())
690     }
691 }
692
693 impl Encodable for ThinTokenStream {
694     fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), E::Error> {
695         TokenStream::from(self.clone()).encode(encoder)
696     }
697 }
698
699 impl Decodable for ThinTokenStream {
700     fn decode<D: Decoder>(decoder: &mut D) -> Result<ThinTokenStream, D::Error> {
701         TokenStream::decode(decoder).map(Into::into)
702     }
703 }
704
705 #[derive(Debug, Copy, Clone, PartialEq, RustcEncodable, RustcDecodable)]
706 pub struct DelimSpan {
707     pub open: Span,
708     pub close: Span,
709 }
710
711 impl DelimSpan {
712     pub fn from_single(sp: Span) -> Self {
713         DelimSpan {
714             open: sp,
715             close: sp,
716         }
717     }
718
719     pub fn from_pair(open: Span, close: Span) -> Self {
720         DelimSpan { open, close }
721     }
722
723     pub fn dummy() -> Self {
724         Self::from_single(DUMMY_SP)
725     }
726
727     pub fn entire(self) -> Span {
728         self.open.with_hi(self.close.hi())
729     }
730
731     pub fn apply_mark(self, mark: Mark) -> Self {
732         DelimSpan {
733             open: self.open.apply_mark(mark),
734             close: self.close.apply_mark(mark),
735         }
736     }
737 }
738
739 #[cfg(test)]
740 mod tests {
741     use super::*;
742     use syntax::ast::Ident;
743     use with_globals;
744     use syntax_pos::{Span, BytePos, NO_EXPANSION};
745     use parse::token::Token;
746     use util::parser_testing::string_to_stream;
747
748     fn string_to_ts(string: &str) -> TokenStream {
749         string_to_stream(string.to_owned())
750     }
751
752     fn sp(a: u32, b: u32) -> Span {
753         Span::new(BytePos(a), BytePos(b), NO_EXPANSION)
754     }
755
756     #[test]
757     fn test_concat() {
758         with_globals(|| {
759             let test_res = string_to_ts("foo::bar::baz");
760             let test_fst = string_to_ts("foo::bar");
761             let test_snd = string_to_ts("::baz");
762             let eq_res = TokenStream::new(vec![test_fst, test_snd]);
763             assert_eq!(test_res.trees().count(), 5);
764             assert_eq!(eq_res.trees().count(), 5);
765             assert_eq!(test_res.eq_unspanned(&eq_res), true);
766         })
767     }
768
769     #[test]
770     fn test_to_from_bijection() {
771         with_globals(|| {
772             let test_start = string_to_ts("foo::bar(baz)");
773             let test_end = test_start.trees().collect();
774             assert_eq!(test_start, test_end)
775         })
776     }
777
778     #[test]
779     fn test_eq_0() {
780         with_globals(|| {
781             let test_res = string_to_ts("foo");
782             let test_eqs = string_to_ts("foo");
783             assert_eq!(test_res, test_eqs)
784         })
785     }
786
787     #[test]
788     fn test_eq_1() {
789         with_globals(|| {
790             let test_res = string_to_ts("::bar::baz");
791             let test_eqs = string_to_ts("::bar::baz");
792             assert_eq!(test_res, test_eqs)
793         })
794     }
795
796     #[test]
797     fn test_eq_3() {
798         with_globals(|| {
799             let test_res = string_to_ts("");
800             let test_eqs = string_to_ts("");
801             assert_eq!(test_res, test_eqs)
802         })
803     }
804
805     #[test]
806     fn test_diseq_0() {
807         with_globals(|| {
808             let test_res = string_to_ts("::bar::baz");
809             let test_eqs = string_to_ts("bar::baz");
810             assert_eq!(test_res == test_eqs, false)
811         })
812     }
813
814     #[test]
815     fn test_diseq_1() {
816         with_globals(|| {
817             let test_res = string_to_ts("(bar,baz)");
818             let test_eqs = string_to_ts("bar,baz");
819             assert_eq!(test_res == test_eqs, false)
820         })
821     }
822
823     #[test]
824     fn test_is_empty() {
825         with_globals(|| {
826             let test0: TokenStream = Vec::<TokenTree>::new().into_iter().collect();
827             let test1: TokenStream =
828                 TokenTree::Token(sp(0, 1), Token::Ident(Ident::from_str("a"), false)).into();
829             let test2 = string_to_ts("foo(bar::baz)");
830
831             assert_eq!(test0.is_empty(), true);
832             assert_eq!(test1.is_empty(), false);
833             assert_eq!(test2.is_empty(), false);
834         })
835     }
836
837     #[test]
838     fn test_dotdotdot() {
839         let mut builder = TokenStreamBuilder::new();
840         builder.push(TokenTree::Token(sp(0, 1), Token::Dot).joint());
841         builder.push(TokenTree::Token(sp(1, 2), Token::Dot).joint());
842         builder.push(TokenTree::Token(sp(2, 3), Token::Dot));
843         let stream = builder.build();
844         assert!(stream.eq_unspanned(&string_to_ts("...")));
845         assert_eq!(stream.trees().count(), 1);
846     }
847
848     #[test]
849     fn test_extend_empty() {
850         with_globals(|| {
851             // Append a token onto an empty token stream.
852             let mut stream = TokenStream::empty();
853             stream.extend(vec![string_to_ts("t")]);
854
855             let expected = string_to_ts("t");
856             assert!(stream.eq_unspanned(&expected));
857         });
858     }
859
860     #[test]
861     fn test_extend_nothing() {
862         with_globals(|| {
863             // Append nothing onto a token stream containing one token.
864             let mut stream = string_to_ts("t");
865             stream.extend(vec![]);
866
867             let expected = string_to_ts("t");
868             assert!(stream.eq_unspanned(&expected));
869         });
870     }
871
872     #[test]
873     fn test_extend_single() {
874         with_globals(|| {
875             // Append a token onto token stream containing a single token.
876             let mut stream = string_to_ts("t1");
877             stream.extend(vec![string_to_ts("t2")]);
878
879             let expected = string_to_ts("t1 t2");
880             assert!(stream.eq_unspanned(&expected));
881         });
882     }
883
884     #[test]
885     fn test_extend_in_place() {
886         with_globals(|| {
887             // Append a token onto token stream containing a reference counted
888             // vec of tokens. The token stream has a reference count of 1 so
889             // this can happen in place.
890             let mut stream = string_to_ts("t1 t2");
891             stream.extend(vec![string_to_ts("t3")]);
892
893             let expected = string_to_ts("t1 t2 t3");
894             assert!(stream.eq_unspanned(&expected));
895         });
896     }
897
898     #[test]
899     fn test_extend_copy() {
900         with_globals(|| {
901             // Append a token onto token stream containing a reference counted
902             // vec of tokens. The token stream is shared so the extend takes
903             // place on a copy.
904             let mut stream = string_to_ts("t1 t2");
905             let _incref = stream.clone();
906             stream.extend(vec![string_to_ts("t3")]);
907
908             let expected = string_to_ts("t1 t2 t3");
909             assert!(stream.eq_unspanned(&expected));
910         });
911     }
912
913     #[test]
914     fn test_extend_no_join() {
915         with_globals(|| {
916             let first = TokenTree::Token(DUMMY_SP, Token::Dot);
917             let second = TokenTree::Token(DUMMY_SP, Token::Dot);
918
919             // Append a dot onto a token stream containing a dot, but do not
920             // join them.
921             let mut stream = TokenStream::from(first);
922             stream.extend(vec![TokenStream::from(second)]);
923
924             let expected = string_to_ts(". .");
925             assert!(stream.eq_unspanned(&expected));
926
927             let unexpected = string_to_ts("..");
928             assert!(!stream.eq_unspanned(&unexpected));
929         });
930     }
931
932     #[test]
933     fn test_extend_join() {
934         with_globals(|| {
935             let first = TokenTree::Token(DUMMY_SP, Token::Dot).joint();
936             let second = TokenTree::Token(DUMMY_SP, Token::Dot);
937
938             // Append a dot onto a token stream containing a dot, forming a
939             // dotdot.
940             let mut stream = first;
941             stream.extend(vec![TokenStream::from(second)]);
942
943             let expected = string_to_ts("..");
944             assert!(stream.eq_unspanned(&expected));
945
946             let unexpected = string_to_ts(". .");
947             assert!(!stream.eq_unspanned(&unexpected));
948         });
949     }
950 }