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;
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),
53 /// Use this token tree as a matcher to parse given tts.
54 pub fn parse(cx: &base::ExtCtxt<'_>, mtch: &[quoted::TokenTree], tts: TokenStream)
55 -> macro_parser::NamedParseResult {
56 // `None` is because we're not interpolating
57 let directory = Directory {
58 path: Cow::from(cx.current_expansion.module.directory.as_path()),
59 ownership: cx.current_expansion.directory_ownership,
61 macro_parser::parse(cx.parse_sess(), tts, mtch, Some(directory), true)
64 /// Checks if this TokenTree is equal to the other, regardless of span information.
65 pub fn eq_unspanned(&self, other: &TokenTree) -> bool {
67 (&TokenTree::Token(_, ref tk), &TokenTree::Token(_, ref tk2)) => tk == tk2,
68 (&TokenTree::Delimited(_, delim, ref tts),
69 &TokenTree::Delimited(_, delim2, ref tts2)) => {
70 delim == delim2 && tts.eq_unspanned(&tts2)
76 // See comments in `Nonterminal::to_tokenstream` for why we care about
77 // *probably* equal here rather than actual equality
79 // This is otherwise the same as `eq_unspanned`, only recursing with a
81 pub fn probably_equal_for_proc_macro(&self, other: &TokenTree) -> bool {
83 (&TokenTree::Token(_, ref tk), &TokenTree::Token(_, ref tk2)) => {
84 tk.probably_equal_for_proc_macro(tk2)
86 (&TokenTree::Delimited(_, delim, ref tts),
87 &TokenTree::Delimited(_, delim2, ref tts2)) => {
88 delim == delim2 && tts.probably_equal_for_proc_macro(&tts2)
94 /// Retrieves the TokenTree's span.
95 pub fn span(&self) -> Span {
97 TokenTree::Token(sp, _) => sp,
98 TokenTree::Delimited(sp, ..) => sp.entire(),
102 /// Modify the `TokenTree`'s span in-place.
103 pub fn set_span(&mut self, span: Span) {
105 TokenTree::Token(ref mut sp, _) => *sp = span,
106 TokenTree::Delimited(ref mut sp, ..) => *sp = DelimSpan::from_single(span),
110 /// Indicates if the stream is a token that is equal to the provided token.
111 pub fn eq_token(&self, t: Token) -> bool {
113 TokenTree::Token(_, ref tk) => *tk == t,
118 pub fn joint(self) -> TokenStream {
119 TokenStream::new(vec![(self, Joint)])
122 /// Returns the opening delimiter as a token tree.
123 pub fn open_tt(span: Span, delim: DelimToken) -> TokenTree {
124 let open_span = if span.is_dummy() {
127 span.with_hi(span.lo() + BytePos(delim.len() as u32))
129 TokenTree::Token(open_span, token::OpenDelim(delim))
132 /// Returns the closing delimiter as a token tree.
133 pub fn close_tt(span: Span, delim: DelimToken) -> TokenTree {
134 let close_span = if span.is_dummy() {
137 span.with_lo(span.hi() - BytePos(delim.len() as u32))
139 TokenTree::Token(close_span, token::CloseDelim(delim))
145 /// A `TokenStream` is an abstract sequence of tokens, organized into `TokenTree`s.
146 /// The goal is for procedural macros to work with `TokenStream`s and `TokenTree`s
147 /// instead of a representation of the abstract syntax tree.
148 /// Today's `TokenTree`s can still contain AST via `Token::Interpolated` for back-compat.
150 /// The use of `Option` is an optimization that avoids the need for an
151 /// allocation when the stream is empty. However, it is not guaranteed that an
152 /// empty stream is represented with `None`; it may be represented as a `Some`
153 /// around an empty `Vec`.
154 #[derive(Clone, Debug)]
155 pub struct TokenStream(pub Option<Lrc<Vec<TreeAndJoint>>>);
157 pub type TreeAndJoint = (TokenTree, IsJoint);
159 // `TokenStream` is used a lot. Make sure it doesn't unintentionally get bigger.
160 #[cfg(target_arch = "x86_64")]
161 static_assert!(MEM_SIZE_OF_TOKEN_STREAM: mem::size_of::<TokenStream>() == 8);
163 #[derive(Clone, Copy, Debug, PartialEq)]
172 /// Given a `TokenStream` with a `Stream` of only two arguments, return a new `TokenStream`
173 /// separating the two arguments with a comma for diagnostic suggestions.
174 pub(crate) fn add_comma(&self) -> Option<(TokenStream, Span)> {
175 // Used to suggest if a user writes `foo!(a b);`
176 if let Some(ref stream) = self.0 {
177 let mut suggestion = None;
178 let mut iter = stream.iter().enumerate().peekable();
179 while let Some((pos, ts)) = iter.next() {
180 if let Some((_, next)) = iter.peek() {
181 let sp = match (&ts, &next) {
182 (_, (TokenTree::Token(_, token::Token::Comma), _)) => continue,
183 ((TokenTree::Token(sp, token_left), NonJoint),
184 (TokenTree::Token(_, token_right), _))
185 if (token_left.is_ident() || token_left.is_lit()) &&
186 (token_right.is_ident() || token_right.is_lit()) => *sp,
187 ((TokenTree::Delimited(sp, ..), NonJoint), _) => sp.entire(),
190 let sp = sp.shrink_to_hi();
191 let comma = (TokenTree::Token(sp, token::Comma), NonJoint);
192 suggestion = Some((pos, comma, sp));
195 if let Some((pos, comma, sp)) = suggestion {
196 let mut new_stream = vec![];
197 let parts = stream.split_at(pos + 1);
198 new_stream.extend_from_slice(parts.0);
199 new_stream.push(comma);
200 new_stream.extend_from_slice(parts.1);
201 return Some((TokenStream::new(new_stream), sp));
208 impl From<TokenTree> for TokenStream {
209 fn from(tree: TokenTree) -> TokenStream {
210 TokenStream::new(vec![(tree, NonJoint)])
214 impl From<TokenTree> for TreeAndJoint {
215 fn from(tree: TokenTree) -> TreeAndJoint {
220 impl From<Token> for TokenStream {
221 fn from(token: Token) -> TokenStream {
222 TokenTree::Token(DUMMY_SP, token).into()
226 impl<T: Into<TokenStream>> iter::FromIterator<T> for TokenStream {
227 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
228 TokenStream::from_streams(iter.into_iter().map(Into::into).collect::<SmallVec<_>>())
232 impl Eq for TokenStream {}
234 impl PartialEq<TokenStream> for TokenStream {
235 fn eq(&self, other: &TokenStream) -> bool {
236 self.trees().eq(other.trees())
241 pub fn len(&self) -> usize {
242 if let Some(ref slice) = self.0 {
249 pub fn empty() -> TokenStream {
253 pub fn is_empty(&self) -> bool {
256 Some(ref stream) => stream.is_empty(),
260 pub(crate) fn from_streams(mut streams: SmallVec<[TokenStream; 2]>) -> TokenStream {
261 match streams.len() {
262 0 => TokenStream::empty(),
263 1 => streams.pop().unwrap(),
265 // rust-lang/rust#57735: pre-allocate vector to avoid
266 // quadratic blow-up due to on-the-fly reallocations.
267 let tree_count = streams.iter()
268 .map(|ts| match &ts.0 { None => 0, Some(s) => s.len() })
270 let mut vec = Vec::with_capacity(tree_count);
272 for stream in streams {
275 Some(stream2) => vec.extend(stream2.iter().cloned()),
278 TokenStream::new(vec)
283 pub fn new(streams: Vec<TreeAndJoint>) -> TokenStream {
284 match streams.len() {
285 0 => TokenStream(None),
286 _ => TokenStream(Some(Lrc::new(streams))),
290 pub fn append_to_tree_and_joint_vec(self, vec: &mut Vec<TreeAndJoint>) {
291 if let Some(stream) = self.0 {
292 vec.extend(stream.iter().cloned());
296 pub fn trees(&self) -> Cursor {
297 self.clone().into_trees()
300 pub fn into_trees(self) -> Cursor {
304 /// Compares two TokenStreams, checking equality without regarding span information.
305 pub fn eq_unspanned(&self, other: &TokenStream) -> bool {
306 let mut t1 = self.trees();
307 let mut t2 = other.trees();
308 for (t1, t2) in t1.by_ref().zip(t2.by_ref()) {
309 if !t1.eq_unspanned(&t2) {
313 t1.next().is_none() && t2.next().is_none()
316 // See comments in `Nonterminal::to_tokenstream` for why we care about
317 // *probably* equal here rather than actual equality
319 // This is otherwise the same as `eq_unspanned`, only recursing with a
321 pub fn probably_equal_for_proc_macro(&self, other: &TokenStream) -> bool {
322 // When checking for `probably_eq`, we ignore certain tokens that aren't
323 // preserved in the AST. Because they are not preserved, the pretty
324 // printer arbitrarily adds or removes them when printing as token
325 // streams, making a comparison between a token stream generated from an
326 // AST and a token stream which was parsed into an AST more reliable.
327 fn semantic_tree(tree: &TokenTree) -> bool {
329 // The pretty printer tends to add trailing commas to
330 // everything, and in particular, after struct fields.
331 | TokenTree::Token(_, Token::Comma)
332 // The pretty printer emits `NoDelim` as whitespace.
333 | TokenTree::Token(_, Token::OpenDelim(DelimToken::NoDelim))
334 | TokenTree::Token(_, Token::CloseDelim(DelimToken::NoDelim))
335 // The pretty printer collapses many semicolons into one.
336 | TokenTree::Token(_, Token::Semi)
337 // The pretty printer collapses whitespace arbitrarily and can
338 // introduce whitespace from `NoDelim`.
339 | TokenTree::Token(_, Token::Whitespace)
340 // The pretty printer can turn `$crate` into `::crate_name`
341 | TokenTree::Token(_, Token::ModSep) => false,
346 let mut t1 = self.trees().filter(semantic_tree);
347 let mut t2 = other.trees().filter(semantic_tree);
348 for (t1, t2) in t1.by_ref().zip(t2.by_ref()) {
349 if !t1.probably_equal_for_proc_macro(&t2) {
353 t1.next().is_none() && t2.next().is_none()
356 pub fn map_enumerated<F: FnMut(usize, TokenTree) -> TokenTree>(self, mut f: F) -> TokenStream {
357 TokenStream(self.0.map(|stream| {
362 .map(|(i, (tree, is_joint))| (f(i, tree.clone()), *is_joint))
367 pub fn map<F: FnMut(TokenTree) -> TokenTree>(self, mut f: F) -> TokenStream {
368 TokenStream(self.0.map(|stream| {
372 .map(|(tree, is_joint)| (f(tree.clone()), *is_joint))
377 fn first_tree_and_joint(&self) -> Option<TreeAndJoint> {
378 self.0.as_ref().map(|stream| {
379 stream.first().unwrap().clone()
383 fn last_tree_if_joint(&self) -> Option<TokenTree> {
386 Some(ref stream) => {
387 if let (tree, Joint) = stream.last().unwrap() {
397 // 99.5%+ of the time we have 1 or 2 elements in this vector.
399 pub struct TokenStreamBuilder(SmallVec<[TokenStream; 2]>);
401 impl TokenStreamBuilder {
402 pub fn new() -> TokenStreamBuilder {
403 TokenStreamBuilder(SmallVec::new())
406 pub fn push<T: Into<TokenStream>>(&mut self, stream: T) {
407 let stream = stream.into();
408 let last_tree_if_joint = self.0.last().and_then(TokenStream::last_tree_if_joint);
409 if let Some(TokenTree::Token(last_span, last_tok)) = last_tree_if_joint {
410 if let Some((TokenTree::Token(span, tok), is_joint)) = stream.first_tree_and_joint() {
411 if let Some(glued_tok) = last_tok.glue(tok) {
412 let last_stream = self.0.pop().unwrap();
413 self.push_all_but_last_tree(&last_stream);
414 let glued_span = last_span.to(span);
415 let glued_tt = TokenTree::Token(glued_span, glued_tok);
416 let glued_tokenstream = TokenStream::new(vec![(glued_tt, is_joint)]);
417 self.0.push(glued_tokenstream);
418 self.push_all_but_first_tree(&stream);
426 pub fn build(self) -> TokenStream {
427 TokenStream::from_streams(self.0)
430 fn push_all_but_last_tree(&mut self, stream: &TokenStream) {
431 if let Some(ref streams) = stream.0 {
432 let len = streams.len();
435 _ => self.0.push(TokenStream(Some(Lrc::new(streams[0 .. len - 1].to_vec())))),
440 fn push_all_but_first_tree(&mut self, stream: &TokenStream) {
441 if let Some(ref streams) = stream.0 {
442 let len = streams.len();
445 _ => self.0.push(TokenStream(Some(Lrc::new(streams[1 .. len].to_vec())))),
453 pub stream: TokenStream,
457 impl Iterator for Cursor {
458 type Item = TokenTree;
460 fn next(&mut self) -> Option<TokenTree> {
461 self.next_with_joint().map(|(tree, _)| tree)
466 fn new(stream: TokenStream) -> Self {
467 Cursor { stream, index: 0 }
470 pub fn next_with_joint(&mut self) -> Option<TreeAndJoint> {
471 match self.stream.0 {
473 Some(ref stream) => {
474 if self.index < stream.len() {
476 Some(stream[self.index - 1].clone())
484 pub fn append(&mut self, new_stream: TokenStream) {
485 if new_stream.is_empty() {
488 let index = self.index;
489 let stream = mem::replace(&mut self.stream, TokenStream(None));
490 *self = TokenStream::from_streams(smallvec![stream, new_stream]).into_trees();
494 pub fn look_ahead(&self, n: usize) -> Option<TokenTree> {
495 match self.stream.0 {
497 Some(ref stream) => stream[self.index ..].get(n).map(|(tree, _)| tree.clone()),
502 impl fmt::Display for TokenStream {
503 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
504 f.write_str(&pprust::tokens_to_string(self.clone()))
508 impl Encodable for TokenStream {
509 fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), E::Error> {
510 self.trees().collect::<Vec<_>>().encode(encoder)
514 impl Decodable for TokenStream {
515 fn decode<D: Decoder>(decoder: &mut D) -> Result<TokenStream, D::Error> {
516 Vec::<TokenTree>::decode(decoder).map(|vec| vec.into_iter().collect())
520 #[derive(Debug, Copy, Clone, PartialEq, RustcEncodable, RustcDecodable)]
521 pub struct DelimSpan {
527 pub fn from_single(sp: Span) -> Self {
534 pub fn from_pair(open: Span, close: Span) -> Self {
535 DelimSpan { open, close }
538 pub fn dummy() -> Self {
539 Self::from_single(DUMMY_SP)
542 pub fn entire(self) -> Span {
543 self.open.with_hi(self.close.hi())
546 pub fn apply_mark(self, mark: Mark) -> Self {
548 open: self.open.apply_mark(mark),
549 close: self.close.apply_mark(mark),
557 use crate::syntax::ast::Ident;
558 use crate::with_globals;
559 use crate::parse::token::Token;
560 use crate::util::parser_testing::string_to_stream;
561 use syntax_pos::{Span, BytePos, NO_EXPANSION};
563 fn string_to_ts(string: &str) -> TokenStream {
564 string_to_stream(string.to_owned())
567 fn sp(a: u32, b: u32) -> Span {
568 Span::new(BytePos(a), BytePos(b), NO_EXPANSION)
574 let test_res = string_to_ts("foo::bar::baz");
575 let test_fst = string_to_ts("foo::bar");
576 let test_snd = string_to_ts("::baz");
577 let eq_res = TokenStream::from_streams(smallvec![test_fst, test_snd]);
578 assert_eq!(test_res.trees().count(), 5);
579 assert_eq!(eq_res.trees().count(), 5);
580 assert_eq!(test_res.eq_unspanned(&eq_res), true);
585 fn test_to_from_bijection() {
587 let test_start = string_to_ts("foo::bar(baz)");
588 let test_end = test_start.trees().collect();
589 assert_eq!(test_start, test_end)
596 let test_res = string_to_ts("foo");
597 let test_eqs = string_to_ts("foo");
598 assert_eq!(test_res, test_eqs)
605 let test_res = string_to_ts("::bar::baz");
606 let test_eqs = string_to_ts("::bar::baz");
607 assert_eq!(test_res, test_eqs)
614 let test_res = string_to_ts("");
615 let test_eqs = string_to_ts("");
616 assert_eq!(test_res, test_eqs)
623 let test_res = string_to_ts("::bar::baz");
624 let test_eqs = string_to_ts("bar::baz");
625 assert_eq!(test_res == test_eqs, false)
632 let test_res = string_to_ts("(bar,baz)");
633 let test_eqs = string_to_ts("bar,baz");
634 assert_eq!(test_res == test_eqs, false)
641 let test0: TokenStream = Vec::<TokenTree>::new().into_iter().collect();
642 let test1: TokenStream =
643 TokenTree::Token(sp(0, 1), Token::Ident(Ident::from_str("a"), false)).into();
644 let test2 = string_to_ts("foo(bar::baz)");
646 assert_eq!(test0.is_empty(), true);
647 assert_eq!(test1.is_empty(), false);
648 assert_eq!(test2.is_empty(), false);
653 fn test_dotdotdot() {
654 let mut builder = TokenStreamBuilder::new();
655 builder.push(TokenTree::Token(sp(0, 1), Token::Dot).joint());
656 builder.push(TokenTree::Token(sp(1, 2), Token::Dot).joint());
657 builder.push(TokenTree::Token(sp(2, 3), Token::Dot));
658 let stream = builder.build();
659 assert!(stream.eq_unspanned(&string_to_ts("...")));
660 assert_eq!(stream.trees().count(), 1);