3 //! `TokenStream`s represent syntactic objects before they are converted into ASTs.
4 //! A `TokenStream` is, roughly speaking, a sequence (eg stream) of `TokenTree`s,
5 //! which are themselves a single `Token` or a `Delimited` subsequence of tokens.
9 //! `TokenStreams` are persistent data structures constructed as ropes with reference
10 //! counted-children. In general, this means that calling an operation on a `TokenStream`
11 //! (such as `slice`) produces an entirely new `TokenStream` from the borrowed reference to
12 //! the original. This essentially coerces `TokenStream`s into 'views' of their subparts,
13 //! and a borrowed `TokenStream` is sufficient to build an owned `TokenStream` without taking
14 //! ownership of the original.
17 use crate::ext::tt::{macro_parser, quoted};
18 use crate::parse::Directory;
19 use crate::parse::token::{self, DelimToken, Token};
20 use crate::print::pprust;
22 use syntax_pos::{BytePos, Mark, Span, DUMMY_SP};
23 #[cfg(target_arch = "x86_64")]
24 use rustc_data_structures::static_assert_size;
25 use rustc_data_structures::sync::Lrc;
26 use serialize::{Decoder, Decodable, Encoder, Encodable};
27 use smallvec::{SmallVec, smallvec};
30 use std::{fmt, iter, mem};
32 /// When the main rust parser encounters a syntax-extension invocation, it
33 /// parses the arguments to the invocation as a token-tree. This is a very
34 /// loose structure, such that all sorts of different AST-fragments can
35 /// be passed to syntax extensions using a uniform type.
37 /// If the syntax extension is an MBE macro, it will attempt to match its
38 /// LHS token tree against the provided token tree, and if it finds a
39 /// match, will transcribe the RHS token tree, splicing in any captured
40 /// `macro_parser::matched_nonterminals` into the `SubstNt`s it finds.
42 /// The RHS of an MBE macro is the only place `SubstNt`s are substituted.
43 /// Nothing special happens to misnamed or misplaced `SubstNt`s.
44 #[derive(Debug, Clone, PartialEq, RustcEncodable, RustcDecodable)]
47 Token(Span, token::Token),
48 /// A delimited sequence of token trees
49 Delimited(DelimSpan, DelimToken, TokenStream),
52 // Ensure all fields of `TokenTree` is `Send` and `Sync`.
53 #[cfg(parallel_compiler)]
57 token::Token: Send + Sync,
58 DelimSpan: Send + Sync,
59 DelimToken: Send + Sync,
60 TokenStream: Send + Sync,
63 // These are safe since we ensure that they hold for all fields in the `_dummy` function.
65 // These impls are only here because the compiler takes forever to compute the Send and Sync
66 // bounds without them.
67 // FIXME: Remove these impls when the compiler can compute the bounds quickly again.
68 // See https://github.com/rust-lang/rust/issues/60846
69 #[cfg(parallel_compiler)]
70 unsafe impl Send for TokenTree {}
71 #[cfg(parallel_compiler)]
72 unsafe impl Sync for TokenTree {}
75 /// Use this token tree as a matcher to parse given tts.
76 pub fn parse(cx: &base::ExtCtxt<'_>, mtch: &[quoted::TokenTree], tts: TokenStream)
77 -> macro_parser::NamedParseResult {
78 // `None` is because we're not interpolating
79 let directory = Directory {
80 path: Cow::from(cx.current_expansion.module.directory.as_path()),
81 ownership: cx.current_expansion.directory_ownership,
83 macro_parser::parse(cx.parse_sess(), tts, mtch, Some(directory), true)
86 /// Checks if this TokenTree is equal to the other, regardless of span information.
87 pub fn eq_unspanned(&self, other: &TokenTree) -> bool {
89 (&TokenTree::Token(_, ref tk), &TokenTree::Token(_, ref tk2)) => tk == tk2,
90 (&TokenTree::Delimited(_, delim, ref tts),
91 &TokenTree::Delimited(_, delim2, ref tts2)) => {
92 delim == delim2 && tts.eq_unspanned(&tts2)
98 // See comments in `Nonterminal::to_tokenstream` for why we care about
99 // *probably* equal here rather than actual equality
101 // This is otherwise the same as `eq_unspanned`, only recursing with a
103 pub fn probably_equal_for_proc_macro(&self, other: &TokenTree) -> bool {
104 match (self, other) {
105 (&TokenTree::Token(_, ref tk), &TokenTree::Token(_, ref tk2)) => {
106 tk.probably_equal_for_proc_macro(tk2)
108 (&TokenTree::Delimited(_, delim, ref tts),
109 &TokenTree::Delimited(_, delim2, ref tts2)) => {
110 delim == delim2 && tts.probably_equal_for_proc_macro(&tts2)
116 /// Retrieves the TokenTree's span.
117 pub fn span(&self) -> Span {
119 TokenTree::Token(sp, _) => sp,
120 TokenTree::Delimited(sp, ..) => sp.entire(),
124 /// Modify the `TokenTree`'s span in-place.
125 pub fn set_span(&mut self, span: Span) {
127 TokenTree::Token(ref mut sp, _) => *sp = span,
128 TokenTree::Delimited(ref mut sp, ..) => *sp = DelimSpan::from_single(span),
132 /// Indicates if the stream is a token that is equal to the provided token.
133 pub fn eq_token(&self, t: Token) -> bool {
135 TokenTree::Token(_, ref tk) => *tk == t,
140 pub fn joint(self) -> TokenStream {
141 TokenStream::new(vec![(self, Joint)])
144 /// Returns the opening delimiter as a token tree.
145 pub fn open_tt(span: Span, delim: DelimToken) -> TokenTree {
146 let open_span = if span.is_dummy() {
149 span.with_hi(span.lo() + BytePos(delim.len() as u32))
151 TokenTree::Token(open_span, token::OpenDelim(delim))
154 /// Returns the closing delimiter as a token tree.
155 pub fn close_tt(span: Span, delim: DelimToken) -> TokenTree {
156 let close_span = if span.is_dummy() {
159 span.with_lo(span.hi() - BytePos(delim.len() as u32))
161 TokenTree::Token(close_span, token::CloseDelim(delim))
167 /// A `TokenStream` is an abstract sequence of tokens, organized into `TokenTree`s.
168 /// The goal is for procedural macros to work with `TokenStream`s and `TokenTree`s
169 /// instead of a representation of the abstract syntax tree.
170 /// Today's `TokenTree`s can still contain AST via `Token::Interpolated` for back-compat.
172 /// The use of `Option` is an optimization that avoids the need for an
173 /// allocation when the stream is empty. However, it is not guaranteed that an
174 /// empty stream is represented with `None`; it may be represented as a `Some`
175 /// around an empty `Vec`.
176 #[derive(Clone, Debug)]
177 pub struct TokenStream(pub Option<Lrc<Vec<TreeAndJoint>>>);
179 pub type TreeAndJoint = (TokenTree, IsJoint);
181 // `TokenStream` is used a lot. Make sure it doesn't unintentionally get bigger.
182 #[cfg(target_arch = "x86_64")]
183 static_assert_size!(TokenStream, 8);
185 #[derive(Clone, Copy, Debug, PartialEq)]
194 /// Given a `TokenStream` with a `Stream` of only two arguments, return a new `TokenStream`
195 /// separating the two arguments with a comma for diagnostic suggestions.
196 pub(crate) fn add_comma(&self) -> Option<(TokenStream, Span)> {
197 // Used to suggest if a user writes `foo!(a b);`
198 if let Some(ref stream) = self.0 {
199 let mut suggestion = None;
200 let mut iter = stream.iter().enumerate().peekable();
201 while let Some((pos, ts)) = iter.next() {
202 if let Some((_, next)) = iter.peek() {
203 let sp = match (&ts, &next) {
204 (_, (TokenTree::Token(_, token::Token::Comma), _)) => continue,
205 ((TokenTree::Token(sp, token_left), NonJoint),
206 (TokenTree::Token(_, token_right), _))
207 if ((token_left.is_ident() && !token_left.is_reserved_ident())
208 || token_left.is_lit()) &&
209 ((token_right.is_ident() && !token_right.is_reserved_ident())
210 || token_right.is_lit()) => *sp,
211 ((TokenTree::Delimited(sp, ..), NonJoint), _) => sp.entire(),
214 let sp = sp.shrink_to_hi();
215 let comma = (TokenTree::Token(sp, token::Comma), NonJoint);
216 suggestion = Some((pos, comma, sp));
219 if let Some((pos, comma, sp)) = suggestion {
220 let mut new_stream = vec![];
221 let parts = stream.split_at(pos + 1);
222 new_stream.extend_from_slice(parts.0);
223 new_stream.push(comma);
224 new_stream.extend_from_slice(parts.1);
225 return Some((TokenStream::new(new_stream), sp));
232 impl From<TokenTree> for TokenStream {
233 fn from(tree: TokenTree) -> TokenStream {
234 TokenStream::new(vec![(tree, NonJoint)])
238 impl From<TokenTree> for TreeAndJoint {
239 fn from(tree: TokenTree) -> TreeAndJoint {
244 impl From<Token> for TokenStream {
245 fn from(token: Token) -> TokenStream {
246 TokenTree::Token(DUMMY_SP, token).into()
250 impl<T: Into<TokenStream>> iter::FromIterator<T> for TokenStream {
251 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
252 TokenStream::from_streams(iter.into_iter().map(Into::into).collect::<SmallVec<_>>())
256 impl Eq for TokenStream {}
258 impl PartialEq<TokenStream> for TokenStream {
259 fn eq(&self, other: &TokenStream) -> bool {
260 self.trees().eq(other.trees())
265 pub fn len(&self) -> usize {
266 if let Some(ref slice) = self.0 {
273 pub fn empty() -> TokenStream {
277 pub fn is_empty(&self) -> bool {
280 Some(ref stream) => stream.is_empty(),
284 pub(crate) fn from_streams(mut streams: SmallVec<[TokenStream; 2]>) -> TokenStream {
285 match streams.len() {
286 0 => TokenStream::empty(),
287 1 => streams.pop().unwrap(),
289 // rust-lang/rust#57735: pre-allocate vector to avoid
290 // quadratic blow-up due to on-the-fly reallocations.
291 let tree_count = streams.iter()
292 .map(|ts| match &ts.0 { None => 0, Some(s) => s.len() })
294 let mut vec = Vec::with_capacity(tree_count);
296 for stream in streams {
299 Some(stream2) => vec.extend(stream2.iter().cloned()),
302 TokenStream::new(vec)
307 pub fn new(streams: Vec<TreeAndJoint>) -> TokenStream {
308 match streams.len() {
309 0 => TokenStream(None),
310 _ => TokenStream(Some(Lrc::new(streams))),
314 pub fn append_to_tree_and_joint_vec(self, vec: &mut Vec<TreeAndJoint>) {
315 if let Some(stream) = self.0 {
316 vec.extend(stream.iter().cloned());
320 pub fn trees(&self) -> Cursor {
321 self.clone().into_trees()
324 pub fn into_trees(self) -> Cursor {
328 /// Compares two TokenStreams, checking equality without regarding span information.
329 pub fn eq_unspanned(&self, other: &TokenStream) -> bool {
330 let mut t1 = self.trees();
331 let mut t2 = other.trees();
332 for (t1, t2) in t1.by_ref().zip(t2.by_ref()) {
333 if !t1.eq_unspanned(&t2) {
337 t1.next().is_none() && t2.next().is_none()
340 // See comments in `Nonterminal::to_tokenstream` for why we care about
341 // *probably* equal here rather than actual equality
343 // This is otherwise the same as `eq_unspanned`, only recursing with a
345 pub fn probably_equal_for_proc_macro(&self, other: &TokenStream) -> bool {
346 // When checking for `probably_eq`, we ignore certain tokens that aren't
347 // preserved in the AST. Because they are not preserved, the pretty
348 // printer arbitrarily adds or removes them when printing as token
349 // streams, making a comparison between a token stream generated from an
350 // AST and a token stream which was parsed into an AST more reliable.
351 fn semantic_tree(tree: &TokenTree) -> bool {
353 // The pretty printer tends to add trailing commas to
354 // everything, and in particular, after struct fields.
355 | TokenTree::Token(_, Token::Comma)
356 // The pretty printer emits `NoDelim` as whitespace.
357 | TokenTree::Token(_, Token::OpenDelim(DelimToken::NoDelim))
358 | TokenTree::Token(_, Token::CloseDelim(DelimToken::NoDelim))
359 // The pretty printer collapses many semicolons into one.
360 | TokenTree::Token(_, Token::Semi)
361 // The pretty printer collapses whitespace arbitrarily and can
362 // introduce whitespace from `NoDelim`.
363 | TokenTree::Token(_, Token::Whitespace)
364 // The pretty printer can turn `$crate` into `::crate_name`
365 | TokenTree::Token(_, Token::ModSep) => false,
370 let mut t1 = self.trees().filter(semantic_tree);
371 let mut t2 = other.trees().filter(semantic_tree);
372 for (t1, t2) in t1.by_ref().zip(t2.by_ref()) {
373 if !t1.probably_equal_for_proc_macro(&t2) {
377 t1.next().is_none() && t2.next().is_none()
380 pub fn map_enumerated<F: FnMut(usize, TokenTree) -> TokenTree>(self, mut f: F) -> TokenStream {
381 TokenStream(self.0.map(|stream| {
386 .map(|(i, (tree, is_joint))| (f(i, tree.clone()), *is_joint))
391 pub fn map<F: FnMut(TokenTree) -> TokenTree>(self, mut f: F) -> TokenStream {
392 TokenStream(self.0.map(|stream| {
396 .map(|(tree, is_joint)| (f(tree.clone()), *is_joint))
401 fn first_tree_and_joint(&self) -> Option<TreeAndJoint> {
402 self.0.as_ref().map(|stream| {
403 stream.first().unwrap().clone()
407 fn last_tree_if_joint(&self) -> Option<TokenTree> {
410 Some(ref stream) => {
411 if let (tree, Joint) = stream.last().unwrap() {
421 // 99.5%+ of the time we have 1 or 2 elements in this vector.
423 pub struct TokenStreamBuilder(SmallVec<[TokenStream; 2]>);
425 impl TokenStreamBuilder {
426 pub fn new() -> TokenStreamBuilder {
427 TokenStreamBuilder(SmallVec::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 = TokenStream::new(vec![(glued_tt, is_joint)]);
441 self.0.push(glued_tokenstream);
442 self.push_all_but_first_tree(&stream);
450 pub fn build(self) -> TokenStream {
451 TokenStream::from_streams(self.0)
454 fn push_all_but_last_tree(&mut self, stream: &TokenStream) {
455 if let Some(ref streams) = stream.0 {
456 let len = streams.len();
459 _ => self.0.push(TokenStream(Some(Lrc::new(streams[0 .. len - 1].to_vec())))),
464 fn push_all_but_first_tree(&mut self, stream: &TokenStream) {
465 if let Some(ref streams) = stream.0 {
466 let len = streams.len();
469 _ => self.0.push(TokenStream(Some(Lrc::new(streams[1 .. len].to_vec())))),
477 pub stream: TokenStream,
481 impl Iterator for Cursor {
482 type Item = TokenTree;
484 fn next(&mut self) -> Option<TokenTree> {
485 self.next_with_joint().map(|(tree, _)| tree)
490 fn new(stream: TokenStream) -> Self {
491 Cursor { stream, index: 0 }
494 pub fn next_with_joint(&mut self) -> Option<TreeAndJoint> {
495 match self.stream.0 {
497 Some(ref stream) => {
498 if self.index < stream.len() {
500 Some(stream[self.index - 1].clone())
508 pub fn append(&mut self, new_stream: TokenStream) {
509 if new_stream.is_empty() {
512 let index = self.index;
513 let stream = mem::replace(&mut self.stream, TokenStream(None));
514 *self = TokenStream::from_streams(smallvec![stream, new_stream]).into_trees();
518 pub fn look_ahead(&self, n: usize) -> Option<TokenTree> {
519 match self.stream.0 {
521 Some(ref stream) => stream[self.index ..].get(n).map(|(tree, _)| tree.clone()),
526 impl fmt::Display for TokenStream {
527 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
528 f.write_str(&pprust::tokens_to_string(self.clone()))
532 impl Encodable for TokenStream {
533 fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), E::Error> {
534 self.trees().collect::<Vec<_>>().encode(encoder)
538 impl Decodable for TokenStream {
539 fn decode<D: Decoder>(decoder: &mut D) -> Result<TokenStream, D::Error> {
540 Vec::<TokenTree>::decode(decoder).map(|vec| vec.into_iter().collect())
544 #[derive(Debug, Copy, Clone, PartialEq, RustcEncodable, RustcDecodable)]
545 pub struct DelimSpan {
551 pub fn from_single(sp: Span) -> Self {
558 pub fn from_pair(open: Span, close: Span) -> Self {
559 DelimSpan { open, close }
562 pub fn dummy() -> Self {
563 Self::from_single(DUMMY_SP)
566 pub fn entire(self) -> Span {
567 self.open.with_hi(self.close.hi())
570 pub fn apply_mark(self, mark: Mark) -> Self {
572 open: self.open.apply_mark(mark),
573 close: self.close.apply_mark(mark),
581 use crate::syntax::ast::Ident;
582 use crate::with_default_globals;
583 use crate::parse::token::Token;
584 use crate::util::parser_testing::string_to_stream;
585 use syntax_pos::{Span, BytePos, NO_EXPANSION};
587 fn string_to_ts(string: &str) -> TokenStream {
588 string_to_stream(string.to_owned())
591 fn sp(a: u32, b: u32) -> Span {
592 Span::new(BytePos(a), BytePos(b), NO_EXPANSION)
597 with_default_globals(|| {
598 let test_res = string_to_ts("foo::bar::baz");
599 let test_fst = string_to_ts("foo::bar");
600 let test_snd = string_to_ts("::baz");
601 let eq_res = TokenStream::from_streams(smallvec![test_fst, test_snd]);
602 assert_eq!(test_res.trees().count(), 5);
603 assert_eq!(eq_res.trees().count(), 5);
604 assert_eq!(test_res.eq_unspanned(&eq_res), true);
609 fn test_to_from_bijection() {
610 with_default_globals(|| {
611 let test_start = string_to_ts("foo::bar(baz)");
612 let test_end = test_start.trees().collect();
613 assert_eq!(test_start, test_end)
619 with_default_globals(|| {
620 let test_res = string_to_ts("foo");
621 let test_eqs = string_to_ts("foo");
622 assert_eq!(test_res, test_eqs)
628 with_default_globals(|| {
629 let test_res = string_to_ts("::bar::baz");
630 let test_eqs = string_to_ts("::bar::baz");
631 assert_eq!(test_res, test_eqs)
637 with_default_globals(|| {
638 let test_res = string_to_ts("");
639 let test_eqs = string_to_ts("");
640 assert_eq!(test_res, test_eqs)
646 with_default_globals(|| {
647 let test_res = string_to_ts("::bar::baz");
648 let test_eqs = string_to_ts("bar::baz");
649 assert_eq!(test_res == test_eqs, false)
655 with_default_globals(|| {
656 let test_res = string_to_ts("(bar,baz)");
657 let test_eqs = string_to_ts("bar,baz");
658 assert_eq!(test_res == test_eqs, false)
664 with_default_globals(|| {
665 let test0: TokenStream = Vec::<TokenTree>::new().into_iter().collect();
666 let test1: TokenStream =
667 TokenTree::Token(sp(0, 1), Token::Ident(Ident::from_str("a"), false)).into();
668 let test2 = string_to_ts("foo(bar::baz)");
670 assert_eq!(test0.is_empty(), true);
671 assert_eq!(test1.is_empty(), false);
672 assert_eq!(test2.is_empty(), false);
677 fn test_dotdotdot() {
678 with_default_globals(|| {
679 let mut builder = TokenStreamBuilder::new();
680 builder.push(TokenTree::Token(sp(0, 1), Token::Dot).joint());
681 builder.push(TokenTree::Token(sp(1, 2), Token::Dot).joint());
682 builder.push(TokenTree::Token(sp(2, 3), Token::Dot));
683 let stream = builder.build();
684 assert!(stream.eq_unspanned(&string_to_ts("...")));
685 assert_eq!(stream.trees().count(), 1);