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 rustc_data_structures::sync::Lrc;
32 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::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 enum TokenStream {
160 JointTree(TokenTree),
161 Stream(Lrc<Vec<TokenStream>>),
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);
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))) => {
183 (TokenStream::Tree(TokenTree::Token(sp, _)), _) => *sp,
184 (TokenStream::Tree(TokenTree::Delimited(sp, ..)), _) => sp.entire(),
187 let sp = sp.shrink_to_hi();
188 let comma = TokenStream::Tree(TokenTree::Token(sp, token::Comma));
189 suggestion = Some((pos, comma, sp));
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));
205 impl From<TokenTree> for TokenStream {
206 fn from(tt: TokenTree) -> TokenStream {
207 TokenStream::Tree(tt)
211 impl From<Token> for TokenStream {
212 fn from(token: Token) -> TokenStream {
213 TokenTree::Token(DUMMY_SP, token).into()
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<_>>())
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);
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);
235 TokenStream::Tree(_) | TokenStream::JointTree(_) => {
236 let mut vec = Vec::new();
237 vec.reserve(1 + iter.size_hint().0);
241 TokenStream::Stream(rc_vec) => match Lrc::try_unwrap(rc_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);
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);
259 // Perform the extend, joining tokens as needed along the way.
260 let mut builder = TokenStreamBuilder(tts);
262 builder.push(stream);
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);
272 impl Eq for TokenStream {}
274 impl PartialEq<TokenStream> for TokenStream {
275 fn eq(&self, other: &TokenStream) -> bool {
276 self.trees().eq(other.trees())
281 pub fn len(&self) -> usize {
282 if let TokenStream::Stream(ref slice) = self {
289 pub fn empty() -> TokenStream {
293 pub fn is_empty(&self) -> bool {
295 TokenStream::Empty => true,
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)),
308 pub fn trees(&self) -> Cursor {
309 self.clone().into_trees()
312 pub fn into_trees(self) -> Cursor {
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) {
325 t1.next().is_none() && t2.next().is_none()
328 // See comments in `interpolated_to_tokenstream` for why we care about
329 // *probably* equal here rather than actual equality
331 // This is otherwise the same as `eq_unspanned`, only recursing with a
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 {
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,
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) {
363 t1.next().is_none() && t2.next().is_none()
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? */) {
370 TokenStream::Tree(tree) => (tree, false),
371 TokenStream::JointTree(tree) => (tree, true),
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();
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(),
388 TokenStream::new(result)
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(),
401 TokenStream::new(result)
404 fn first_tree_and_joint(&self) -> Option<(TokenTree, bool)> {
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(),
413 fn last_tree_if_joint(&self) -> Option<TokenTree> {
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(),
423 pub struct TokenStreamBuilder(Vec<TokenStream>);
425 impl TokenStreamBuilder {
426 pub fn new() -> TokenStreamBuilder {
427 TokenStreamBuilder(Vec::new())
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 {
445 self.0.push(glued_tokenstream);
446 self.push_all_but_first_tree(&stream);
454 pub fn add<T: Into<TokenStream>>(mut self, stream: T) -> Self {
459 pub fn build(self) -> TokenStream {
460 TokenStream::new(self.0)
463 fn push_all_but_last_tree(&mut self, stream: &TokenStream) {
464 if let TokenStream::Stream(ref streams) = stream {
465 let len = streams.len();
468 2 => self.0.push(streams[0].clone().into()),
469 _ => self.0.push(TokenStream::new(streams[0 .. len - 1].to_vec())),
471 self.push_all_but_last_tree(&streams[len - 1])
475 fn push_all_but_first_tree(&mut self, stream: &TokenStream) {
476 if let TokenStream::Stream(ref streams) = stream {
477 let len = streams.len();
480 2 => self.0.push(streams[1].clone().into()),
481 _ => self.0.push(TokenStream::new(streams[1 .. len].to_vec())),
483 self.push_all_but_first_tree(&streams[0])
489 pub struct Cursor(CursorKind);
494 Tree(TokenTree, bool /* consumed? */),
495 JointTree(TokenTree, bool /* consumed? */),
496 Stream(StreamCursor),
500 struct StreamCursor {
501 stream: Lrc<Vec<TokenStream>>,
503 stack: Vec<(Lrc<Vec<TokenStream>>, usize)>,
507 fn new(stream: Lrc<Vec<TokenStream>>) -> Self {
508 StreamCursor { stream: stream, index: 0, stack: Vec::new() }
511 fn next_as_stream(&mut self) -> Option<TokenStream> {
513 if self.index < self.stream.len() {
515 let next = self.stream[self.index - 1].clone();
517 TokenStream::Tree(..) | TokenStream::JointTree(..) => return Some(next),
518 TokenStream::Stream(stream) => self.insert(stream),
519 TokenStream::Empty => {}
521 } else if let Some((stream, index)) = self.stack.pop() {
522 self.stream = stream;
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)));
536 impl Iterator for Cursor {
537 type Item = TokenTree;
539 fn next(&mut self) -> Option<TokenTree> {
540 self.next_as_stream().map(|stream| match stream {
541 TokenStream::Tree(tree) | TokenStream::JointTree(tree) => tree,
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)),
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(),
571 pub fn insert(&mut self, stream: TokenStream) {
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();
581 CursorKind::Stream(ref mut cursor) => {
582 cursor.insert(ThinTokenStream::from(stream).0.unwrap());
587 pub fn original_stream(&self) -> TokenStream {
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())
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 {
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),
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),
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>>>);
644 impl ThinTokenStream {
645 pub fn stream(&self) -> TokenStream {
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),
661 impl From<ThinTokenStream> for TokenStream {
662 fn from(stream: ThinTokenStream) -> TokenStream {
663 stream.0.map(TokenStream::Stream).unwrap_or_else(TokenStream::empty)
667 impl Eq for ThinTokenStream {}
669 impl PartialEq<ThinTokenStream> for ThinTokenStream {
670 fn eq(&self, other: &ThinTokenStream) -> bool {
671 TokenStream::from(self.clone()) == TokenStream::from(other.clone())
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()))
681 impl Encodable for TokenStream {
682 fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), E::Error> {
683 self.trees().collect::<Vec<_>>().encode(encoder)
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())
693 impl Encodable for ThinTokenStream {
694 fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), E::Error> {
695 TokenStream::from(self.clone()).encode(encoder)
699 impl Decodable for ThinTokenStream {
700 fn decode<D: Decoder>(decoder: &mut D) -> Result<ThinTokenStream, D::Error> {
701 TokenStream::decode(decoder).map(Into::into)
705 #[derive(Debug, Copy, Clone, PartialEq, RustcEncodable, RustcDecodable)]
706 pub struct DelimSpan {
712 pub fn from_single(sp: Span) -> Self {
719 pub fn from_pair(open: Span, close: Span) -> Self {
720 DelimSpan { open, close }
723 pub fn dummy() -> Self {
724 Self::from_single(DUMMY_SP)
727 pub fn entire(self) -> Span {
728 self.open.with_hi(self.close.hi())
731 pub fn apply_mark(self, mark: Mark) -> Self {
733 open: self.open.apply_mark(mark),
734 close: self.close.apply_mark(mark),
742 use syntax::ast::Ident;
744 use syntax_pos::{Span, BytePos, NO_EXPANSION};
745 use parse::token::Token;
746 use util::parser_testing::string_to_stream;
748 fn string_to_ts(string: &str) -> TokenStream {
749 string_to_stream(string.to_owned())
752 fn sp(a: u32, b: u32) -> Span {
753 Span::new(BytePos(a), BytePos(b), NO_EXPANSION)
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);
770 fn test_to_from_bijection() {
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)
781 let test_res = string_to_ts("foo");
782 let test_eqs = string_to_ts("foo");
783 assert_eq!(test_res, test_eqs)
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)
799 let test_res = string_to_ts("");
800 let test_eqs = string_to_ts("");
801 assert_eq!(test_res, test_eqs)
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)
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)
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)");
831 assert_eq!(test0.is_empty(), true);
832 assert_eq!(test1.is_empty(), false);
833 assert_eq!(test2.is_empty(), false);
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);
849 fn test_extend_empty() {
851 // Append a token onto an empty token stream.
852 let mut stream = TokenStream::empty();
853 stream.extend(vec![string_to_ts("t")]);
855 let expected = string_to_ts("t");
856 assert!(stream.eq_unspanned(&expected));
861 fn test_extend_nothing() {
863 // Append nothing onto a token stream containing one token.
864 let mut stream = string_to_ts("t");
865 stream.extend(vec![]);
867 let expected = string_to_ts("t");
868 assert!(stream.eq_unspanned(&expected));
873 fn test_extend_single() {
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")]);
879 let expected = string_to_ts("t1 t2");
880 assert!(stream.eq_unspanned(&expected));
885 fn test_extend_in_place() {
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")]);
893 let expected = string_to_ts("t1 t2 t3");
894 assert!(stream.eq_unspanned(&expected));
899 fn test_extend_copy() {
901 // Append a token onto token stream containing a reference counted
902 // vec of tokens. The token stream is shared so the extend takes
904 let mut stream = string_to_ts("t1 t2");
905 let _incref = stream.clone();
906 stream.extend(vec![string_to_ts("t3")]);
908 let expected = string_to_ts("t1 t2 t3");
909 assert!(stream.eq_unspanned(&expected));
914 fn test_extend_no_join() {
916 let first = TokenTree::Token(DUMMY_SP, Token::Dot);
917 let second = TokenTree::Token(DUMMY_SP, Token::Dot);
919 // Append a dot onto a token stream containing a dot, but do not
921 let mut stream = TokenStream::from(first);
922 stream.extend(vec![TokenStream::from(second)]);
924 let expected = string_to_ts(". .");
925 assert!(stream.eq_unspanned(&expected));
927 let unexpected = string_to_ts("..");
928 assert!(!stream.eq_unspanned(&unexpected));
933 fn test_extend_join() {
935 let first = TokenTree::Token(DUMMY_SP, Token::Dot).joint();
936 let second = TokenTree::Token(DUMMY_SP, Token::Dot);
938 // Append a dot onto a token stream containing a dot, forming a
940 let mut stream = first;
941 stream.extend(vec![TokenStream::from(second)]);
943 let expected = string_to_ts("..");
944 assert!(stream.eq_unspanned(&expected));
946 let unexpected = string_to_ts(". .");
947 assert!(!stream.eq_unspanned(&unexpected));