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),
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_size!(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_reserved_ident())
186 || token_left.is_lit()) &&
187 ((token_right.is_ident() && !token_right.is_reserved_ident())
188 || token_right.is_lit()) => *sp,
189 ((TokenTree::Delimited(sp, ..), NonJoint), _) => sp.entire(),
192 let sp = sp.shrink_to_hi();
193 let comma = (TokenTree::Token(sp, token::Comma), NonJoint);
194 suggestion = Some((pos, comma, sp));
197 if let Some((pos, comma, sp)) = suggestion {
198 let mut new_stream = vec![];
199 let parts = stream.split_at(pos + 1);
200 new_stream.extend_from_slice(parts.0);
201 new_stream.push(comma);
202 new_stream.extend_from_slice(parts.1);
203 return Some((TokenStream::new(new_stream), sp));
210 impl From<TokenTree> for TokenStream {
211 fn from(tree: TokenTree) -> TokenStream {
212 TokenStream::new(vec![(tree, NonJoint)])
216 impl From<TokenTree> for TreeAndJoint {
217 fn from(tree: TokenTree) -> TreeAndJoint {
222 impl From<Token> for TokenStream {
223 fn from(token: Token) -> TokenStream {
224 TokenTree::Token(DUMMY_SP, token).into()
228 impl<T: Into<TokenStream>> iter::FromIterator<T> for TokenStream {
229 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
230 TokenStream::from_streams(iter.into_iter().map(Into::into).collect::<SmallVec<_>>())
234 impl Eq for TokenStream {}
236 impl PartialEq<TokenStream> for TokenStream {
237 fn eq(&self, other: &TokenStream) -> bool {
238 self.trees().eq(other.trees())
243 pub fn len(&self) -> usize {
244 if let Some(ref slice) = self.0 {
251 pub fn empty() -> TokenStream {
255 pub fn is_empty(&self) -> bool {
258 Some(ref stream) => stream.is_empty(),
262 pub(crate) fn from_streams(mut streams: SmallVec<[TokenStream; 2]>) -> TokenStream {
263 match streams.len() {
264 0 => TokenStream::empty(),
265 1 => streams.pop().unwrap(),
267 // rust-lang/rust#57735: pre-allocate vector to avoid
268 // quadratic blow-up due to on-the-fly reallocations.
269 let tree_count = streams.iter()
270 .map(|ts| match &ts.0 { None => 0, Some(s) => s.len() })
272 let mut vec = Vec::with_capacity(tree_count);
274 for stream in streams {
277 Some(stream2) => vec.extend(stream2.iter().cloned()),
280 TokenStream::new(vec)
285 pub fn new(streams: Vec<TreeAndJoint>) -> TokenStream {
286 match streams.len() {
287 0 => TokenStream(None),
288 _ => TokenStream(Some(Lrc::new(streams))),
292 pub fn append_to_tree_and_joint_vec(self, vec: &mut Vec<TreeAndJoint>) {
293 if let Some(stream) = self.0 {
294 vec.extend(stream.iter().cloned());
298 pub fn trees(&self) -> Cursor {
299 self.clone().into_trees()
302 pub fn into_trees(self) -> Cursor {
306 /// Compares two TokenStreams, checking equality without regarding span information.
307 pub fn eq_unspanned(&self, other: &TokenStream) -> bool {
308 let mut t1 = self.trees();
309 let mut t2 = other.trees();
310 for (t1, t2) in t1.by_ref().zip(t2.by_ref()) {
311 if !t1.eq_unspanned(&t2) {
315 t1.next().is_none() && t2.next().is_none()
318 // See comments in `Nonterminal::to_tokenstream` for why we care about
319 // *probably* equal here rather than actual equality
321 // This is otherwise the same as `eq_unspanned`, only recursing with a
323 pub fn probably_equal_for_proc_macro(&self, other: &TokenStream) -> bool {
324 // When checking for `probably_eq`, we ignore certain tokens that aren't
325 // preserved in the AST. Because they are not preserved, the pretty
326 // printer arbitrarily adds or removes them when printing as token
327 // streams, making a comparison between a token stream generated from an
328 // AST and a token stream which was parsed into an AST more reliable.
329 fn semantic_tree(tree: &TokenTree) -> bool {
331 // The pretty printer tends to add trailing commas to
332 // everything, and in particular, after struct fields.
333 | TokenTree::Token(_, Token::Comma)
334 // The pretty printer emits `NoDelim` as whitespace.
335 | TokenTree::Token(_, Token::OpenDelim(DelimToken::NoDelim))
336 | TokenTree::Token(_, Token::CloseDelim(DelimToken::NoDelim))
337 // The pretty printer collapses many semicolons into one.
338 | TokenTree::Token(_, Token::Semi)
339 // The pretty printer collapses whitespace arbitrarily and can
340 // introduce whitespace from `NoDelim`.
341 | TokenTree::Token(_, Token::Whitespace)
342 // The pretty printer can turn `$crate` into `::crate_name`
343 | TokenTree::Token(_, Token::ModSep) => false,
348 let mut t1 = self.trees().filter(semantic_tree);
349 let mut t2 = other.trees().filter(semantic_tree);
350 for (t1, t2) in t1.by_ref().zip(t2.by_ref()) {
351 if !t1.probably_equal_for_proc_macro(&t2) {
355 t1.next().is_none() && t2.next().is_none()
358 pub fn map_enumerated<F: FnMut(usize, TokenTree) -> TokenTree>(self, mut f: F) -> TokenStream {
359 TokenStream(self.0.map(|stream| {
364 .map(|(i, (tree, is_joint))| (f(i, tree.clone()), *is_joint))
369 pub fn map<F: FnMut(TokenTree) -> TokenTree>(self, mut f: F) -> TokenStream {
370 TokenStream(self.0.map(|stream| {
374 .map(|(tree, is_joint)| (f(tree.clone()), *is_joint))
379 fn first_tree_and_joint(&self) -> Option<TreeAndJoint> {
380 self.0.as_ref().map(|stream| {
381 stream.first().unwrap().clone()
385 fn last_tree_if_joint(&self) -> Option<TokenTree> {
388 Some(ref stream) => {
389 if let (tree, Joint) = stream.last().unwrap() {
399 // 99.5%+ of the time we have 1 or 2 elements in this vector.
401 pub struct TokenStreamBuilder(SmallVec<[TokenStream; 2]>);
403 impl TokenStreamBuilder {
404 pub fn new() -> TokenStreamBuilder {
405 TokenStreamBuilder(SmallVec::new())
408 pub fn push<T: Into<TokenStream>>(&mut self, stream: T) {
409 let stream = stream.into();
410 let last_tree_if_joint = self.0.last().and_then(TokenStream::last_tree_if_joint);
411 if let Some(TokenTree::Token(last_span, last_tok)) = last_tree_if_joint {
412 if let Some((TokenTree::Token(span, tok), is_joint)) = stream.first_tree_and_joint() {
413 if let Some(glued_tok) = last_tok.glue(tok) {
414 let last_stream = self.0.pop().unwrap();
415 self.push_all_but_last_tree(&last_stream);
416 let glued_span = last_span.to(span);
417 let glued_tt = TokenTree::Token(glued_span, glued_tok);
418 let glued_tokenstream = TokenStream::new(vec![(glued_tt, is_joint)]);
419 self.0.push(glued_tokenstream);
420 self.push_all_but_first_tree(&stream);
428 pub fn build(self) -> TokenStream {
429 TokenStream::from_streams(self.0)
432 fn push_all_but_last_tree(&mut self, stream: &TokenStream) {
433 if let Some(ref streams) = stream.0 {
434 let len = streams.len();
437 _ => self.0.push(TokenStream(Some(Lrc::new(streams[0 .. len - 1].to_vec())))),
442 fn push_all_but_first_tree(&mut self, stream: &TokenStream) {
443 if let Some(ref streams) = stream.0 {
444 let len = streams.len();
447 _ => self.0.push(TokenStream(Some(Lrc::new(streams[1 .. len].to_vec())))),
455 pub stream: TokenStream,
459 impl Iterator for Cursor {
460 type Item = TokenTree;
462 fn next(&mut self) -> Option<TokenTree> {
463 self.next_with_joint().map(|(tree, _)| tree)
468 fn new(stream: TokenStream) -> Self {
469 Cursor { stream, index: 0 }
472 pub fn next_with_joint(&mut self) -> Option<TreeAndJoint> {
473 match self.stream.0 {
475 Some(ref stream) => {
476 if self.index < stream.len() {
478 Some(stream[self.index - 1].clone())
486 pub fn append(&mut self, new_stream: TokenStream) {
487 if new_stream.is_empty() {
490 let index = self.index;
491 let stream = mem::replace(&mut self.stream, TokenStream(None));
492 *self = TokenStream::from_streams(smallvec![stream, new_stream]).into_trees();
496 pub fn look_ahead(&self, n: usize) -> Option<TokenTree> {
497 match self.stream.0 {
499 Some(ref stream) => stream[self.index ..].get(n).map(|(tree, _)| tree.clone()),
504 impl fmt::Display for TokenStream {
505 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
506 f.write_str(&pprust::tokens_to_string(self.clone()))
510 impl Encodable for TokenStream {
511 fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), E::Error> {
512 self.trees().collect::<Vec<_>>().encode(encoder)
516 impl Decodable for TokenStream {
517 fn decode<D: Decoder>(decoder: &mut D) -> Result<TokenStream, D::Error> {
518 Vec::<TokenTree>::decode(decoder).map(|vec| vec.into_iter().collect())
522 #[derive(Debug, Copy, Clone, PartialEq, RustcEncodable, RustcDecodable)]
523 pub struct DelimSpan {
529 pub fn from_single(sp: Span) -> Self {
536 pub fn from_pair(open: Span, close: Span) -> Self {
537 DelimSpan { open, close }
540 pub fn dummy() -> Self {
541 Self::from_single(DUMMY_SP)
544 pub fn entire(self) -> Span {
545 self.open.with_hi(self.close.hi())
548 pub fn apply_mark(self, mark: Mark) -> Self {
550 open: self.open.apply_mark(mark),
551 close: self.close.apply_mark(mark),
559 use crate::syntax::ast::Ident;
560 use crate::with_globals;
561 use crate::parse::token::Token;
562 use crate::util::parser_testing::string_to_stream;
563 use syntax_pos::{Span, BytePos, NO_EXPANSION};
565 fn string_to_ts(string: &str) -> TokenStream {
566 string_to_stream(string.to_owned())
569 fn sp(a: u32, b: u32) -> Span {
570 Span::new(BytePos(a), BytePos(b), NO_EXPANSION)
576 let test_res = string_to_ts("foo::bar::baz");
577 let test_fst = string_to_ts("foo::bar");
578 let test_snd = string_to_ts("::baz");
579 let eq_res = TokenStream::from_streams(smallvec![test_fst, test_snd]);
580 assert_eq!(test_res.trees().count(), 5);
581 assert_eq!(eq_res.trees().count(), 5);
582 assert_eq!(test_res.eq_unspanned(&eq_res), true);
587 fn test_to_from_bijection() {
589 let test_start = string_to_ts("foo::bar(baz)");
590 let test_end = test_start.trees().collect();
591 assert_eq!(test_start, test_end)
598 let test_res = string_to_ts("foo");
599 let test_eqs = string_to_ts("foo");
600 assert_eq!(test_res, test_eqs)
607 let test_res = string_to_ts("::bar::baz");
608 let test_eqs = string_to_ts("::bar::baz");
609 assert_eq!(test_res, test_eqs)
616 let test_res = string_to_ts("");
617 let test_eqs = string_to_ts("");
618 assert_eq!(test_res, test_eqs)
625 let test_res = string_to_ts("::bar::baz");
626 let test_eqs = string_to_ts("bar::baz");
627 assert_eq!(test_res == test_eqs, false)
634 let test_res = string_to_ts("(bar,baz)");
635 let test_eqs = string_to_ts("bar,baz");
636 assert_eq!(test_res == test_eqs, false)
643 let test0: TokenStream = Vec::<TokenTree>::new().into_iter().collect();
644 let test1: TokenStream =
645 TokenTree::Token(sp(0, 1), Token::Ident(Ident::from_str("a"), false)).into();
646 let test2 = string_to_ts("foo(bar::baz)");
648 assert_eq!(test0.is_empty(), true);
649 assert_eq!(test1.is_empty(), false);
650 assert_eq!(test2.is_empty(), false);
655 fn test_dotdotdot() {
656 let mut builder = TokenStreamBuilder::new();
657 builder.push(TokenTree::Token(sp(0, 1), Token::Dot).joint());
658 builder.push(TokenTree::Token(sp(1, 2), Token::Dot).joint());
659 builder.push(TokenTree::Token(sp(2, 3), Token::Dot));
660 let stream = builder.build();
661 assert!(stream.eq_unspanned(&string_to_ts("...")));
662 assert_eq!(stream.trees().count(), 1);