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.
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.
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.
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.
25 use syntax_pos::{BytePos, Mark, Span, DUMMY_SP};
27 use ext::tt::{macro_parser, quoted};
29 use parse::token::{self, DelimToken, Token};
31 use serialize::{Decoder, Decodable, Encoder, Encodable};
35 use std::{fmt, iter, mem};
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.
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.
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)]
52 Token(Span, token::Token),
53 /// A delimited sequence of token trees
54 Delimited(DelimSpan, DelimToken, ThinTokenStream),
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,
66 macro_parser::parse(cx.parse_sess(), tts, mtch, Some(directory), true)
69 /// Check if this TokenTree is equal to the other, regardless of span information.
70 pub fn eq_unspanned(&self, other: &TokenTree) -> bool {
72 (&TokenTree::Token(_, ref tk), &TokenTree::Token(_, ref tk2)) => tk == tk2,
73 (&TokenTree::Delimited(_, delim, ref tts),
74 &TokenTree::Delimited(_, delim2, ref tts2)) => {
76 tts.stream().eq_unspanned(&tts2.stream())
82 // See comments in `interpolated_to_tokenstream` for why we care about
83 // *probably* equal here rather than actual equality
85 // This is otherwise the same as `eq_unspanned`, only recursing with a
87 pub fn probably_equal_for_proc_macro(&self, other: &TokenTree) -> bool {
89 (&TokenTree::Token(_, ref tk), &TokenTree::Token(_, ref tk2)) => {
90 tk.probably_equal_for_proc_macro(tk2)
92 (&TokenTree::Delimited(_, delim, ref tts),
93 &TokenTree::Delimited(_, delim2, ref tts2)) => {
95 tts.stream().probably_equal_for_proc_macro(&tts2.stream())
101 /// Retrieve the TokenTree's span.
102 pub fn span(&self) -> Span {
104 TokenTree::Token(sp, _) => sp,
105 TokenTree::Delimited(sp, ..) => sp.entire(),
109 /// Modify the `TokenTree`'s span in-place.
110 pub fn set_span(&mut self, span: Span) {
112 TokenTree::Token(ref mut sp, _) => *sp = span,
113 TokenTree::Delimited(ref mut sp, ..) => *sp = DelimSpan::from_single(span),
117 /// Indicates if the stream is a token that is equal to the provided token.
118 pub fn eq_token(&self, t: Token) -> bool {
120 TokenTree::Token(_, ref tk) => *tk == t,
125 pub fn joint(self) -> TokenStream {
126 TokenStream { kind: TokenStreamKind::JointTree(self) }
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() {
134 span.with_hi(span.lo() + BytePos(delim.len() as u32))
136 TokenTree::Token(open_span, token::OpenDelim(delim))
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() {
144 span.with_lo(span.hi() - BytePos(delim.len() as u32))
146 TokenTree::Token(close_span, token::CloseDelim(delim))
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,
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);
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))) => {
180 (TokenStreamKind::Tree(TokenTree::Token(sp, _)), _) => *sp,
181 (TokenStreamKind::Tree(TokenTree::Delimited(sp, ..)), _) => sp.entire(),
184 let sp = sp.shrink_to_hi();
185 let comma = TokenStream {
186 kind: TokenStreamKind::Tree(TokenTree::Token(sp, token::Comma)),
188 suggestion = Some((pos, comma, sp));
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));
205 #[derive(Clone, Debug)]
206 enum TokenStreamKind {
209 JointTree(TokenTree),
210 Stream(RcVec<TokenStream>),
213 impl From<TokenTree> for TokenStream {
214 fn from(tt: TokenTree) -> TokenStream {
215 TokenStream { kind: TokenStreamKind::Tree(tt) }
219 impl From<Token> for TokenStream {
220 fn from(token: Token) -> TokenStream {
221 TokenTree::Token(DUMMY_SP, token).into()
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<_>>())
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);
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);
243 TokenStreamKind::Tree(_) | TokenStreamKind::JointTree(_) => {
244 let mut vec = Vec::new();
245 vec.reserve(1 + iter.size_hint().0);
246 vec.push(TokenStream { kind });
249 TokenStreamKind::Stream(rc_vec) => match RcVec::try_unwrap(rc_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);
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);
267 // Perform the extend, joining tokens as needed along the way.
268 let mut builder = TokenStreamBuilder(tts);
270 builder.push(stream);
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)),
285 impl Eq for TokenStream {}
287 impl PartialEq<TokenStream> for TokenStream {
288 fn eq(&self, other: &TokenStream) -> bool {
289 self.trees().eq(other.trees())
294 pub fn len(&self) -> usize {
295 if let TokenStreamKind::Stream(ref slice) = self.kind {
302 pub fn empty() -> TokenStream {
303 TokenStream { kind: TokenStreamKind::Empty }
306 pub fn is_empty(&self) -> bool {
308 TokenStreamKind::Empty => true,
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)),
321 fn concat_rc_vec(streams: RcVec<TokenStream>) -> TokenStream {
322 TokenStream { kind: TokenStreamKind::Stream(streams) }
325 pub fn trees(&self) -> Cursor {
326 self.clone().into_trees()
329 pub fn into_trees(self) -> Cursor {
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) {
342 t1.next().is_none() && t2.next().is_none()
345 // See comments in `interpolated_to_tokenstream` for why we care about
346 // *probably* equal here rather than actual equality
348 // This is otherwise the same as `eq_unspanned`, only recursing with a
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 {
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,
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) {
380 t1.next().is_none() && t2.next().is_none()
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? */) {
387 TokenStreamKind::Tree(tree) => (tree, false),
388 TokenStreamKind::JointTree(tree) => (tree, true),
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();
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(),
405 TokenStream::concat(result)
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(),
418 TokenStream::concat(result)
421 fn first_tree_and_joint(&self) -> Option<(TokenTree, bool)> {
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(),
430 fn last_tree_if_joint(&self) -> Option<TokenTree> {
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(),
440 pub struct TokenStreamBuilder(Vec<TokenStream>);
442 impl TokenStreamBuilder {
443 pub fn new() -> TokenStreamBuilder {
444 TokenStreamBuilder(Vec::new())
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 {
462 self.0.push(glued_tokenstream);
463 self.push_all_but_first_tree(&stream);
471 pub fn add<T: Into<TokenStream>>(mut self, stream: T) -> Self {
476 pub fn build(self) -> TokenStream {
477 TokenStream::concat(self.0)
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();
485 2 => self.0.push(streams[0].clone().into()),
486 _ => self.0.push(TokenStream::concat_rc_vec(streams.sub_slice(0 .. len - 1))),
488 self.push_all_but_last_tree(&streams[len - 1])
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();
497 2 => self.0.push(streams[1].clone().into()),
498 _ => self.0.push(TokenStream::concat_rc_vec(streams.sub_slice(1 .. len))),
500 self.push_all_but_first_tree(&streams[0])
506 pub struct Cursor(CursorKind);
511 Tree(TokenTree, bool /* consumed? */),
512 JointTree(TokenTree, bool /* consumed? */),
513 Stream(StreamCursor),
517 struct StreamCursor {
518 stream: RcVec<TokenStream>,
520 stack: Vec<(RcVec<TokenStream>, usize)>,
524 fn new(stream: RcVec<TokenStream>) -> Self {
525 StreamCursor { stream: stream, index: 0, stack: Vec::new() }
528 fn next_as_stream(&mut self) -> Option<TokenStream> {
530 if self.index < self.stream.len() {
532 let next = self.stream[self.index - 1].clone();
534 TokenStreamKind::Tree(..) | TokenStreamKind::JointTree(..) => return Some(next),
535 TokenStreamKind::Stream(stream) => self.insert(stream),
536 TokenStreamKind::Empty => {}
538 } else if let Some((stream, index)) = self.stack.pop() {
539 self.stream = stream;
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)));
553 impl Iterator for Cursor {
554 type Item = TokenTree;
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,
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)),
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(),
588 pub fn insert(&mut self, stream: TokenStream) {
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();
598 CursorKind::Stream(ref mut cursor) => {
599 cursor.insert(ThinTokenStream::from(stream).0.unwrap());
604 pub fn original_stream(&self) -> TokenStream {
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())
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),
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),
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>>);
661 impl ThinTokenStream {
662 pub fn stream(&self) -> TokenStream {
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),
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)
684 impl Eq for ThinTokenStream {}
686 impl PartialEq<ThinTokenStream> for ThinTokenStream {
687 fn eq(&self, other: &ThinTokenStream) -> bool {
688 TokenStream::from(self.clone()) == TokenStream::from(other.clone())
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()))
698 impl Encodable for TokenStream {
699 fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), E::Error> {
700 self.trees().collect::<Vec<_>>().encode(encoder)
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())
710 impl Encodable for ThinTokenStream {
711 fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), E::Error> {
712 TokenStream::from(self.clone()).encode(encoder)
716 impl Decodable for ThinTokenStream {
717 fn decode<D: Decoder>(decoder: &mut D) -> Result<ThinTokenStream, D::Error> {
718 TokenStream::decode(decoder).map(Into::into)
722 #[derive(Debug, Copy, Clone, PartialEq, RustcEncodable, RustcDecodable)]
723 pub struct DelimSpan {
729 pub fn from_single(sp: Span) -> Self {
736 pub fn from_pair(open: Span, close: Span) -> Self {
737 DelimSpan { open, close }
740 pub fn dummy() -> Self {
741 Self::from_single(DUMMY_SP)
744 pub fn entire(self) -> Span {
745 self.open.with_hi(self.close.hi())
748 pub fn apply_mark(self, mark: Mark) -> Self {
750 open: self.open.apply_mark(mark),
751 close: self.close.apply_mark(mark),
759 use syntax::ast::Ident;
761 use syntax_pos::{Span, BytePos, NO_EXPANSION};
762 use parse::token::Token;
763 use util::parser_testing::string_to_stream;
765 fn string_to_ts(string: &str) -> TokenStream {
766 string_to_stream(string.to_owned())
769 fn sp(a: u32, b: u32) -> Span {
770 Span::new(BytePos(a), BytePos(b), NO_EXPANSION)
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);
787 fn test_to_from_bijection() {
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)
798 let test_res = string_to_ts("foo");
799 let test_eqs = string_to_ts("foo");
800 assert_eq!(test_res, test_eqs)
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)
816 let test_res = string_to_ts("");
817 let test_eqs = string_to_ts("");
818 assert_eq!(test_res, test_eqs)
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)
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)
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)");
848 assert_eq!(test0.is_empty(), true);
849 assert_eq!(test1.is_empty(), false);
850 assert_eq!(test2.is_empty(), false);
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);
866 fn test_extend_empty() {
868 // Append a token onto an empty token stream.
869 let mut stream = TokenStream::empty();
870 stream.extend(vec![string_to_ts("t")]);
872 let expected = string_to_ts("t");
873 assert!(stream.eq_unspanned(&expected));
878 fn test_extend_nothing() {
880 // Append nothing onto a token stream containing one token.
881 let mut stream = string_to_ts("t");
882 stream.extend(vec![]);
884 let expected = string_to_ts("t");
885 assert!(stream.eq_unspanned(&expected));
890 fn test_extend_single() {
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")]);
896 let expected = string_to_ts("t1 t2");
897 assert!(stream.eq_unspanned(&expected));
902 fn test_extend_in_place() {
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")]);
910 let expected = string_to_ts("t1 t2 t3");
911 assert!(stream.eq_unspanned(&expected));
916 fn test_extend_copy() {
918 // Append a token onto token stream containing a reference counted
919 // vec of tokens. The token stream is shared so the extend takes
921 let mut stream = string_to_ts("t1 t2");
922 let _incref = stream.clone();
923 stream.extend(vec![string_to_ts("t3")]);
925 let expected = string_to_ts("t1 t2 t3");
926 assert!(stream.eq_unspanned(&expected));
931 fn test_extend_no_join() {
933 let first = TokenTree::Token(DUMMY_SP, Token::Dot);
934 let second = TokenTree::Token(DUMMY_SP, Token::Dot);
936 // Append a dot onto a token stream containing a dot, but do not
938 let mut stream = TokenStream::from(first);
939 stream.extend(vec![TokenStream::from(second)]);
941 let expected = string_to_ts(". .");
942 assert!(stream.eq_unspanned(&expected));
944 let unexpected = string_to_ts("..");
945 assert!(!stream.eq_unspanned(&unexpected));
950 fn test_extend_join() {
952 let first = TokenTree::Token(DUMMY_SP, Token::Dot).joint();
953 let second = TokenTree::Token(DUMMY_SP, Token::Dot);
955 // Append a dot onto a token stream containing a dot, forming a
957 let mut stream = first;
958 stream.extend(vec![TokenStream::from(second)]);
960 let expected = string_to_ts("..");
961 assert!(stream.eq_unspanned(&expected));
963 let unexpected = string_to_ts(". .");
964 assert!(!stream.eq_unspanned(&unexpected));