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, Token};
31 use serialize::{Decoder, Decodable, Encoder, Encodable};
35 use std::{fmt, iter, mem};
37 /// A delimited sequence of token trees
38 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
39 pub struct Delimited {
40 /// The type of delimiter
41 pub delim: token::DelimToken,
42 /// The delimited sequence of token trees
43 pub tts: ThinTokenStream,
47 /// Returns the opening delimiter as a token.
48 pub fn open_token(&self) -> token::Token {
49 token::OpenDelim(self.delim)
52 /// Returns the closing delimiter as a token.
53 pub fn close_token(&self) -> token::Token {
54 token::CloseDelim(self.delim)
57 /// Returns the opening delimiter as a token tree.
58 pub fn open_tt(&self, span: Span) -> TokenTree {
59 let open_span = if span.is_dummy() {
62 span.with_hi(span.lo() + BytePos(self.delim.len() as u32))
64 TokenTree::Token(open_span, self.open_token())
67 /// Returns the closing delimiter as a token tree.
68 pub fn close_tt(&self, span: Span) -> TokenTree {
69 let close_span = if span.is_dummy() {
72 span.with_lo(span.hi() - BytePos(self.delim.len() as u32))
74 TokenTree::Token(close_span, self.close_token())
77 /// Returns the token trees inside the delimiters.
78 pub fn stream(&self) -> TokenStream {
79 self.tts.clone().into()
83 /// When the main rust parser encounters a syntax-extension invocation, it
84 /// parses the arguments to the invocation as a token-tree. This is a very
85 /// loose structure, such that all sorts of different AST-fragments can
86 /// be passed to syntax extensions using a uniform type.
88 /// If the syntax extension is an MBE macro, it will attempt to match its
89 /// LHS token tree against the provided token tree, and if it finds a
90 /// match, will transcribe the RHS token tree, splicing in any captured
91 /// `macro_parser::matched_nonterminals` into the `SubstNt`s it finds.
93 /// The RHS of an MBE macro is the only place `SubstNt`s are substituted.
94 /// Nothing special happens to misnamed or misplaced `SubstNt`s.
95 #[derive(Debug, Clone, PartialEq, RustcEncodable, RustcDecodable)]
98 Token(Span, token::Token),
99 /// A delimited sequence of token trees
100 Delimited(DelimSpan, Delimited),
104 /// Use this token tree as a matcher to parse given tts.
105 pub fn parse(cx: &base::ExtCtxt, mtch: &[quoted::TokenTree], tts: TokenStream)
106 -> macro_parser::NamedParseResult {
107 // `None` is because we're not interpolating
108 let directory = Directory {
109 path: Cow::from(cx.current_expansion.module.directory.as_path()),
110 ownership: cx.current_expansion.directory_ownership,
112 macro_parser::parse(cx.parse_sess(), tts, mtch, Some(directory), true)
115 /// Check if this TokenTree is equal to the other, regardless of span information.
116 pub fn eq_unspanned(&self, other: &TokenTree) -> bool {
117 match (self, other) {
118 (&TokenTree::Token(_, ref tk), &TokenTree::Token(_, ref tk2)) => tk == tk2,
119 (&TokenTree::Delimited(_, ref dl), &TokenTree::Delimited(_, ref dl2)) => {
120 dl.delim == dl2.delim &&
121 dl.stream().eq_unspanned(&dl2.stream())
127 // See comments in `interpolated_to_tokenstream` for why we care about
128 // *probably* equal here rather than actual equality
130 // This is otherwise the same as `eq_unspanned`, only recursing with a
132 pub fn probably_equal_for_proc_macro(&self, other: &TokenTree) -> bool {
133 match (self, other) {
134 (&TokenTree::Token(_, ref tk), &TokenTree::Token(_, ref tk2)) => {
135 tk.probably_equal_for_proc_macro(tk2)
137 (&TokenTree::Delimited(_, ref dl), &TokenTree::Delimited(_, ref dl2)) => {
138 dl.delim == dl2.delim &&
139 dl.stream().probably_equal_for_proc_macro(&dl2.stream())
145 /// Retrieve the TokenTree's span.
146 pub fn span(&self) -> Span {
148 TokenTree::Token(sp, _) => sp,
149 TokenTree::Delimited(sp, _) => sp.entire(),
153 /// Modify the `TokenTree`'s span inplace.
154 pub fn set_span(&mut self, span: Span) {
156 TokenTree::Token(ref mut sp, _) => *sp = span,
157 TokenTree::Delimited(ref mut sp, _) => *sp = DelimSpan::from_single(span),
161 /// Indicates if the stream is a token that is equal to the provided token.
162 pub fn eq_token(&self, t: Token) -> bool {
164 TokenTree::Token(_, ref tk) => *tk == t,
169 pub fn joint(self) -> TokenStream {
170 TokenStream { kind: TokenStreamKind::JointTree(self) }
176 /// A `TokenStream` is an abstract sequence of tokens, organized into `TokenTree`s.
177 /// The goal is for procedural macros to work with `TokenStream`s and `TokenTree`s
178 /// instead of a representation of the abstract syntax tree.
179 /// Today's `TokenTree`s can still contain AST via `Token::Interpolated` for back-compat.
180 #[derive(Clone, Debug)]
181 pub struct TokenStream {
182 kind: TokenStreamKind,
186 /// Given a `TokenStream` with a `Stream` of only two arguments, return a new `TokenStream`
187 /// separating the two arguments with a comma for diagnostic suggestions.
188 pub(crate) fn add_comma(&self) -> Option<(TokenStream, Span)> {
189 // Used to suggest if a user writes `foo!(a b);`
190 if let TokenStreamKind::Stream(ref slice) = self.kind {
191 let mut suggestion = None;
192 let mut iter = slice.iter().enumerate().peekable();
193 while let Some((pos, ts)) = iter.next() {
194 if let Some((_, next)) = iter.peek() {
195 let sp = match (&ts.kind, &next.kind) {
196 (TokenStreamKind::Tree(TokenTree::Token(_, token::Token::Comma)), _) |
197 (_, TokenStreamKind::Tree(TokenTree::Token(_, token::Token::Comma))) => {
200 (TokenStreamKind::Tree(TokenTree::Token(sp, _)), _) => *sp,
201 (TokenStreamKind::Tree(TokenTree::Delimited(sp, _)), _) => sp.entire(),
204 let sp = sp.shrink_to_hi();
205 let comma = TokenStream {
206 kind: TokenStreamKind::Tree(TokenTree::Token(sp, token::Comma)),
208 suggestion = Some((pos, comma, sp));
211 if let Some((pos, comma, sp)) = suggestion {
212 let mut new_slice = vec![];
213 let parts = slice.split_at(pos + 1);
214 new_slice.extend_from_slice(parts.0);
215 new_slice.push(comma);
216 new_slice.extend_from_slice(parts.1);
217 let slice = RcVec::new(new_slice);
218 return Some((TokenStream { kind: TokenStreamKind::Stream(slice) }, sp));
225 #[derive(Clone, Debug)]
226 enum TokenStreamKind {
229 JointTree(TokenTree),
230 Stream(RcVec<TokenStream>),
233 impl From<TokenTree> for TokenStream {
234 fn from(tt: TokenTree) -> TokenStream {
235 TokenStream { kind: TokenStreamKind::Tree(tt) }
239 impl From<Token> for TokenStream {
240 fn from(token: Token) -> TokenStream {
241 TokenTree::Token(DUMMY_SP, token).into()
245 impl<T: Into<TokenStream>> iter::FromIterator<T> for TokenStream {
246 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
247 TokenStream::concat(iter.into_iter().map(Into::into).collect::<Vec<_>>())
251 impl Extend<TokenStream> for TokenStream {
252 fn extend<I: IntoIterator<Item = TokenStream>>(&mut self, iter: I) {
253 let iter = iter.into_iter();
254 let kind = mem::replace(&mut self.kind, TokenStreamKind::Empty);
256 // Vector of token streams originally in self.
257 let tts: Vec<TokenStream> = match kind {
258 TokenStreamKind::Empty => {
259 let mut vec = Vec::new();
260 vec.reserve(iter.size_hint().0);
263 TokenStreamKind::Tree(_) | TokenStreamKind::JointTree(_) => {
264 let mut vec = Vec::new();
265 vec.reserve(1 + iter.size_hint().0);
266 vec.push(TokenStream { kind });
269 TokenStreamKind::Stream(rc_vec) => match RcVec::try_unwrap(rc_vec) {
271 // Extend in place using the existing capacity if possible.
272 // This is the fast path for libraries like `quote` that
273 // build a token stream.
274 vec.reserve(iter.size_hint().0);
278 // Self is shared so we need to copy and extend that.
279 let mut vec = Vec::new();
280 vec.reserve(rc_vec.len() + iter.size_hint().0);
281 vec.extend_from_slice(&rc_vec);
287 // Perform the extend, joining tokens as needed along the way.
288 let mut builder = TokenStreamBuilder(tts);
290 builder.push(stream);
293 // Build the resulting token stream. If it contains more than one token,
294 // preserve capacity in the vector in anticipation of the caller
295 // performing additional calls to extend.
296 let mut tts = builder.0;
297 *self = match tts.len() {
298 0 => TokenStream::empty(),
299 1 => tts.pop().unwrap(),
300 _ => TokenStream::concat_rc_vec(RcVec::new_preserving_capacity(tts)),
305 impl Eq for TokenStream {}
307 impl PartialEq<TokenStream> for TokenStream {
308 fn eq(&self, other: &TokenStream) -> bool {
309 self.trees().eq(other.trees())
314 pub fn len(&self) -> usize {
315 if let TokenStreamKind::Stream(ref slice) = self.kind {
322 pub fn empty() -> TokenStream {
323 TokenStream { kind: TokenStreamKind::Empty }
326 pub fn is_empty(&self) -> bool {
328 TokenStreamKind::Empty => true,
333 pub fn concat(mut streams: Vec<TokenStream>) -> TokenStream {
334 match streams.len() {
335 0 => TokenStream::empty(),
336 1 => streams.pop().unwrap(),
337 _ => TokenStream::concat_rc_vec(RcVec::new(streams)),
341 fn concat_rc_vec(streams: RcVec<TokenStream>) -> TokenStream {
342 TokenStream { kind: TokenStreamKind::Stream(streams) }
345 pub fn trees(&self) -> Cursor {
346 self.clone().into_trees()
349 pub fn into_trees(self) -> Cursor {
353 /// Compares two TokenStreams, checking equality without regarding span information.
354 pub fn eq_unspanned(&self, other: &TokenStream) -> bool {
355 let mut t1 = self.trees();
356 let mut t2 = other.trees();
357 for (t1, t2) in t1.by_ref().zip(t2.by_ref()) {
358 if !t1.eq_unspanned(&t2) {
362 t1.next().is_none() && t2.next().is_none()
365 // See comments in `interpolated_to_tokenstream` for why we care about
366 // *probably* equal here rather than actual equality
368 // This is otherwise the same as `eq_unspanned`, only recursing with a
370 pub fn probably_equal_for_proc_macro(&self, other: &TokenStream) -> bool {
371 let mut t1 = self.trees();
372 let mut t2 = other.trees();
373 for (t1, t2) in t1.by_ref().zip(t2.by_ref()) {
374 if !t1.probably_equal_for_proc_macro(&t2) {
378 t1.next().is_none() && t2.next().is_none()
381 /// Precondition: `self` consists of a single token tree.
382 /// Returns true if the token tree is a joint operation w.r.t. `proc_macro::TokenNode`.
383 pub fn as_tree(self) -> (TokenTree, bool /* joint? */) {
385 TokenStreamKind::Tree(tree) => (tree, false),
386 TokenStreamKind::JointTree(tree) => (tree, true),
391 pub fn map_enumerated<F: FnMut(usize, TokenTree) -> TokenTree>(self, mut f: F) -> TokenStream {
392 let mut trees = self.into_trees();
393 let mut result = Vec::new();
395 while let Some(stream) = trees.next_as_stream() {
396 result.push(match stream.kind {
397 TokenStreamKind::Tree(tree) => f(i, tree).into(),
398 TokenStreamKind::JointTree(tree) => f(i, tree).joint(),
403 TokenStream::concat(result)
406 pub fn map<F: FnMut(TokenTree) -> TokenTree>(self, mut f: F) -> TokenStream {
407 let mut trees = self.into_trees();
408 let mut result = Vec::new();
409 while let Some(stream) = trees.next_as_stream() {
410 result.push(match stream.kind {
411 TokenStreamKind::Tree(tree) => f(tree).into(),
412 TokenStreamKind::JointTree(tree) => f(tree).joint(),
416 TokenStream::concat(result)
419 fn first_tree_and_joint(&self) -> Option<(TokenTree, bool)> {
421 TokenStreamKind::Empty => None,
422 TokenStreamKind::Tree(ref tree) => Some((tree.clone(), false)),
423 TokenStreamKind::JointTree(ref tree) => Some((tree.clone(), true)),
424 TokenStreamKind::Stream(ref stream) => stream.first().unwrap().first_tree_and_joint(),
428 fn last_tree_if_joint(&self) -> Option<TokenTree> {
430 TokenStreamKind::Empty | TokenStreamKind::Tree(..) => None,
431 TokenStreamKind::JointTree(ref tree) => Some(tree.clone()),
432 TokenStreamKind::Stream(ref stream) => stream.last().unwrap().last_tree_if_joint(),
438 pub struct TokenStreamBuilder(Vec<TokenStream>);
440 impl TokenStreamBuilder {
441 pub fn new() -> TokenStreamBuilder {
442 TokenStreamBuilder(Vec::new())
445 pub fn push<T: Into<TokenStream>>(&mut self, stream: T) {
446 let stream = stream.into();
447 let last_tree_if_joint = self.0.last().and_then(TokenStream::last_tree_if_joint);
448 if let Some(TokenTree::Token(last_span, last_tok)) = last_tree_if_joint {
449 if let Some((TokenTree::Token(span, tok), is_joint)) = stream.first_tree_and_joint() {
450 if let Some(glued_tok) = last_tok.glue(tok) {
451 let last_stream = self.0.pop().unwrap();
452 self.push_all_but_last_tree(&last_stream);
453 let glued_span = last_span.to(span);
454 let glued_tt = TokenTree::Token(glued_span, glued_tok);
455 let glued_tokenstream = if is_joint {
460 self.0.push(glued_tokenstream);
461 self.push_all_but_first_tree(&stream);
469 pub fn add<T: Into<TokenStream>>(mut self, stream: T) -> Self {
474 pub fn build(self) -> TokenStream {
475 TokenStream::concat(self.0)
478 fn push_all_but_last_tree(&mut self, stream: &TokenStream) {
479 if let TokenStreamKind::Stream(ref streams) = stream.kind {
480 let len = streams.len();
483 2 => self.0.push(streams[0].clone().into()),
484 _ => self.0.push(TokenStream::concat_rc_vec(streams.sub_slice(0 .. len - 1))),
486 self.push_all_but_last_tree(&streams[len - 1])
490 fn push_all_but_first_tree(&mut self, stream: &TokenStream) {
491 if let TokenStreamKind::Stream(ref streams) = stream.kind {
492 let len = streams.len();
495 2 => self.0.push(streams[1].clone().into()),
496 _ => self.0.push(TokenStream::concat_rc_vec(streams.sub_slice(1 .. len))),
498 self.push_all_but_first_tree(&streams[0])
504 pub struct Cursor(CursorKind);
509 Tree(TokenTree, bool /* consumed? */),
510 JointTree(TokenTree, bool /* consumed? */),
511 Stream(StreamCursor),
515 struct StreamCursor {
516 stream: RcVec<TokenStream>,
518 stack: Vec<(RcVec<TokenStream>, usize)>,
522 fn new(stream: RcVec<TokenStream>) -> Self {
523 StreamCursor { stream: stream, index: 0, stack: Vec::new() }
526 fn next_as_stream(&mut self) -> Option<TokenStream> {
528 if self.index < self.stream.len() {
530 let next = self.stream[self.index - 1].clone();
532 TokenStreamKind::Tree(..) | TokenStreamKind::JointTree(..) => return Some(next),
533 TokenStreamKind::Stream(stream) => self.insert(stream),
534 TokenStreamKind::Empty => {}
536 } else if let Some((stream, index)) = self.stack.pop() {
537 self.stream = stream;
545 fn insert(&mut self, stream: RcVec<TokenStream>) {
546 self.stack.push((mem::replace(&mut self.stream, stream),
547 mem::replace(&mut self.index, 0)));
551 impl Iterator for Cursor {
552 type Item = TokenTree;
554 fn next(&mut self) -> Option<TokenTree> {
555 self.next_as_stream().map(|stream| match stream.kind {
556 TokenStreamKind::Tree(tree) | TokenStreamKind::JointTree(tree) => tree,
563 fn new(stream: TokenStream) -> Self {
564 Cursor(match stream.kind {
565 TokenStreamKind::Empty => CursorKind::Empty,
566 TokenStreamKind::Tree(tree) => CursorKind::Tree(tree, false),
567 TokenStreamKind::JointTree(tree) => CursorKind::JointTree(tree, false),
568 TokenStreamKind::Stream(stream) => CursorKind::Stream(StreamCursor::new(stream)),
572 pub fn next_as_stream(&mut self) -> Option<TokenStream> {
573 let (stream, consumed) = match self.0 {
574 CursorKind::Tree(ref tree, ref mut consumed @ false) =>
575 (tree.clone().into(), consumed),
576 CursorKind::JointTree(ref tree, ref mut consumed @ false) =>
577 (tree.clone().joint(), consumed),
578 CursorKind::Stream(ref mut cursor) => return cursor.next_as_stream(),
586 pub fn insert(&mut self, stream: TokenStream) {
588 _ if stream.is_empty() => return,
589 CursorKind::Empty => *self = stream.trees(),
590 CursorKind::Tree(_, consumed) | CursorKind::JointTree(_, consumed) => {
591 *self = TokenStream::concat(vec![self.original_stream(), stream]).trees();
596 CursorKind::Stream(ref mut cursor) => {
597 cursor.insert(ThinTokenStream::from(stream).0.unwrap());
602 pub fn original_stream(&self) -> TokenStream {
604 CursorKind::Empty => TokenStream::empty(),
605 CursorKind::Tree(ref tree, _) => tree.clone().into(),
606 CursorKind::JointTree(ref tree, _) => tree.clone().joint(),
607 CursorKind::Stream(ref cursor) => TokenStream::concat_rc_vec({
608 cursor.stack.get(0).cloned().map(|(stream, _)| stream)
609 .unwrap_or(cursor.stream.clone())
614 pub fn look_ahead(&self, n: usize) -> Option<TokenTree> {
615 fn look_ahead(streams: &[TokenStream], mut n: usize) -> Result<TokenTree, usize> {
616 for stream in streams {
617 n = match stream.kind {
618 TokenStreamKind::Tree(ref tree) | TokenStreamKind::JointTree(ref tree)
619 if n == 0 => return Ok(tree.clone()),
620 TokenStreamKind::Tree(..) | TokenStreamKind::JointTree(..) => n - 1,
621 TokenStreamKind::Stream(ref stream) => match look_ahead(stream, n) {
622 Ok(tree) => return Ok(tree),
633 CursorKind::Tree(_, true) |
634 CursorKind::JointTree(_, true) => Err(n),
635 CursorKind::Tree(ref tree, false) |
636 CursorKind::JointTree(ref tree, false) => look_ahead(&[tree.clone().into()], n),
637 CursorKind::Stream(ref cursor) => {
638 look_ahead(&cursor.stream[cursor.index ..], n).or_else(|mut n| {
639 for &(ref stream, index) in cursor.stack.iter().rev() {
640 n = match look_ahead(&stream[index..], n) {
641 Ok(tree) => return Ok(tree),
653 /// The `TokenStream` type is large enough to represent a single `TokenTree` without allocation.
654 /// `ThinTokenStream` is smaller, but needs to allocate to represent a single `TokenTree`.
655 /// We must use `ThinTokenStream` in `TokenTree::Delimited` to avoid infinite size due to recursion.
656 #[derive(Debug, Clone)]
657 pub struct ThinTokenStream(Option<RcVec<TokenStream>>);
659 impl From<TokenStream> for ThinTokenStream {
660 fn from(stream: TokenStream) -> ThinTokenStream {
661 ThinTokenStream(match stream.kind {
662 TokenStreamKind::Empty => None,
663 TokenStreamKind::Tree(tree) => Some(RcVec::new(vec![tree.into()])),
664 TokenStreamKind::JointTree(tree) => Some(RcVec::new(vec![tree.joint()])),
665 TokenStreamKind::Stream(stream) => Some(stream),
670 impl From<ThinTokenStream> for TokenStream {
671 fn from(stream: ThinTokenStream) -> TokenStream {
672 stream.0.map(TokenStream::concat_rc_vec).unwrap_or_else(TokenStream::empty)
676 impl Eq for ThinTokenStream {}
678 impl PartialEq<ThinTokenStream> for ThinTokenStream {
679 fn eq(&self, other: &ThinTokenStream) -> bool {
680 TokenStream::from(self.clone()) == TokenStream::from(other.clone())
684 impl fmt::Display for TokenStream {
685 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
686 f.write_str(&pprust::tokens_to_string(self.clone()))
690 impl Encodable for TokenStream {
691 fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), E::Error> {
692 self.trees().collect::<Vec<_>>().encode(encoder)
696 impl Decodable for TokenStream {
697 fn decode<D: Decoder>(decoder: &mut D) -> Result<TokenStream, D::Error> {
698 Vec::<TokenTree>::decode(decoder).map(|vec| vec.into_iter().collect())
702 impl Encodable for ThinTokenStream {
703 fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), E::Error> {
704 TokenStream::from(self.clone()).encode(encoder)
708 impl Decodable for ThinTokenStream {
709 fn decode<D: Decoder>(decoder: &mut D) -> Result<ThinTokenStream, D::Error> {
710 TokenStream::decode(decoder).map(Into::into)
714 #[derive(Debug, Copy, Clone, PartialEq, RustcEncodable, RustcDecodable)]
715 pub struct DelimSpan {
721 pub fn from_single(sp: Span) -> Self {
728 pub fn from_pair(open: Span, close: Span) -> Self {
729 DelimSpan { open, close }
732 pub fn dummy() -> Self {
733 Self::from_single(DUMMY_SP)
736 pub fn entire(self) -> Span {
737 self.open.with_hi(self.close.hi())
740 pub fn apply_mark(self, mark: Mark) -> Self {
742 open: self.open.apply_mark(mark),
743 close: self.close.apply_mark(mark),
751 use syntax::ast::Ident;
753 use syntax_pos::{Span, BytePos, NO_EXPANSION};
754 use parse::token::Token;
755 use util::parser_testing::string_to_stream;
757 fn string_to_ts(string: &str) -> TokenStream {
758 string_to_stream(string.to_owned())
761 fn sp(a: u32, b: u32) -> Span {
762 Span::new(BytePos(a), BytePos(b), NO_EXPANSION)
768 let test_res = string_to_ts("foo::bar::baz");
769 let test_fst = string_to_ts("foo::bar");
770 let test_snd = string_to_ts("::baz");
771 let eq_res = TokenStream::concat(vec![test_fst, test_snd]);
772 assert_eq!(test_res.trees().count(), 5);
773 assert_eq!(eq_res.trees().count(), 5);
774 assert_eq!(test_res.eq_unspanned(&eq_res), true);
779 fn test_to_from_bijection() {
781 let test_start = string_to_ts("foo::bar(baz)");
782 let test_end = test_start.trees().collect();
783 assert_eq!(test_start, test_end)
790 let test_res = string_to_ts("foo");
791 let test_eqs = string_to_ts("foo");
792 assert_eq!(test_res, test_eqs)
799 let test_res = string_to_ts("::bar::baz");
800 let test_eqs = string_to_ts("::bar::baz");
801 assert_eq!(test_res, test_eqs)
808 let test_res = string_to_ts("");
809 let test_eqs = string_to_ts("");
810 assert_eq!(test_res, test_eqs)
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 test_res = string_to_ts("(bar,baz)");
827 let test_eqs = string_to_ts("bar,baz");
828 assert_eq!(test_res == test_eqs, false)
835 let test0: TokenStream = Vec::<TokenTree>::new().into_iter().collect();
836 let test1: TokenStream =
837 TokenTree::Token(sp(0, 1), Token::Ident(Ident::from_str("a"), false)).into();
838 let test2 = string_to_ts("foo(bar::baz)");
840 assert_eq!(test0.is_empty(), true);
841 assert_eq!(test1.is_empty(), false);
842 assert_eq!(test2.is_empty(), false);
847 fn test_dotdotdot() {
848 let mut builder = TokenStreamBuilder::new();
849 builder.push(TokenTree::Token(sp(0, 1), Token::Dot).joint());
850 builder.push(TokenTree::Token(sp(1, 2), Token::Dot).joint());
851 builder.push(TokenTree::Token(sp(2, 3), Token::Dot));
852 let stream = builder.build();
853 assert!(stream.eq_unspanned(&string_to_ts("...")));
854 assert_eq!(stream.trees().count(), 1);
858 fn test_extend_empty() {
860 // Append a token onto an empty token stream.
861 let mut stream = TokenStream::empty();
862 stream.extend(vec![string_to_ts("t")]);
864 let expected = string_to_ts("t");
865 assert!(stream.eq_unspanned(&expected));
870 fn test_extend_nothing() {
872 // Append nothing onto a token stream containing one token.
873 let mut stream = string_to_ts("t");
874 stream.extend(vec![]);
876 let expected = string_to_ts("t");
877 assert!(stream.eq_unspanned(&expected));
882 fn test_extend_single() {
884 // Append a token onto token stream containing a single token.
885 let mut stream = string_to_ts("t1");
886 stream.extend(vec![string_to_ts("t2")]);
888 let expected = string_to_ts("t1 t2");
889 assert!(stream.eq_unspanned(&expected));
894 fn test_extend_in_place() {
896 // Append a token onto token stream containing a reference counted
897 // vec of tokens. The token stream has a reference count of 1 so
898 // this can happen in place.
899 let mut stream = string_to_ts("t1 t2");
900 stream.extend(vec![string_to_ts("t3")]);
902 let expected = string_to_ts("t1 t2 t3");
903 assert!(stream.eq_unspanned(&expected));
908 fn test_extend_copy() {
910 // Append a token onto token stream containing a reference counted
911 // vec of tokens. The token stream is shared so the extend takes
913 let mut stream = string_to_ts("t1 t2");
914 let _incref = stream.clone();
915 stream.extend(vec![string_to_ts("t3")]);
917 let expected = string_to_ts("t1 t2 t3");
918 assert!(stream.eq_unspanned(&expected));
923 fn test_extend_no_join() {
925 let first = TokenTree::Token(DUMMY_SP, Token::Dot);
926 let second = TokenTree::Token(DUMMY_SP, Token::Dot);
928 // Append a dot onto a token stream containing a dot, but do not
930 let mut stream = TokenStream::from(first);
931 stream.extend(vec![TokenStream::from(second)]);
933 let expected = string_to_ts(". .");
934 assert!(stream.eq_unspanned(&expected));
936 let unexpected = string_to_ts("..");
937 assert!(!stream.eq_unspanned(&unexpected));
942 fn test_extend_join() {
944 let first = TokenTree::Token(DUMMY_SP, Token::Dot).joint();
945 let second = TokenTree::Token(DUMMY_SP, Token::Dot);
947 // Append a dot onto a token stream containing a dot, forming a
949 let mut stream = first;
950 stream.extend(vec![TokenStream::from(second)]);
952 let expected = string_to_ts("..");
953 assert!(stream.eq_unspanned(&expected));
955 let unexpected = string_to_ts(". .");
956 assert!(!stream.eq_unspanned(&unexpected));