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, TokenKind};
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)]
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 DelimSpan: Send + Sync,
58 DelimToken: Send + Sync,
59 TokenStream: Send + Sync,
62 // These are safe since we ensure that they hold for all fields in the `_dummy` function.
64 // These impls are only here because the compiler takes forever to compute the Send and Sync
65 // bounds without them.
66 // FIXME: Remove these impls when the compiler can compute the bounds quickly again.
67 // See https://github.com/rust-lang/rust/issues/60846
68 #[cfg(parallel_compiler)]
69 unsafe impl Send for TokenTree {}
70 #[cfg(parallel_compiler)]
71 unsafe impl Sync for TokenTree {}
74 /// Use this token tree as a matcher to parse given tts.
75 pub fn parse(cx: &base::ExtCtxt<'_>, mtch: &[quoted::TokenTree], tts: TokenStream)
76 -> macro_parser::NamedParseResult {
77 // `None` is because we're not interpolating
78 let directory = Directory {
79 path: Cow::from(cx.current_expansion.module.directory.as_path()),
80 ownership: cx.current_expansion.directory_ownership,
82 macro_parser::parse(cx.parse_sess(), tts, mtch, Some(directory), true)
85 /// Checks if this TokenTree is equal to the other, regardless of span information.
86 pub fn eq_unspanned(&self, other: &TokenTree) -> bool {
88 (TokenTree::Token(token), TokenTree::Token(token2)) => token.kind == token2.kind,
89 (TokenTree::Delimited(_, delim, tts), TokenTree::Delimited(_, delim2, tts2)) => {
90 delim == delim2 && tts.eq_unspanned(&tts2)
96 // See comments in `Nonterminal::to_tokenstream` for why we care about
97 // *probably* equal here rather than actual equality
99 // This is otherwise the same as `eq_unspanned`, only recursing with a
101 pub fn probably_equal_for_proc_macro(&self, other: &TokenTree) -> bool {
102 match (self, other) {
103 (TokenTree::Token(token), TokenTree::Token(token2)) => {
104 token.probably_equal_for_proc_macro(token2)
106 (TokenTree::Delimited(_, delim, tts), TokenTree::Delimited(_, delim2, tts2)) => {
107 delim == delim2 && tts.probably_equal_for_proc_macro(&tts2)
113 /// Retrieves the TokenTree's span.
114 pub fn span(&self) -> Span {
116 TokenTree::Token(token) => token.span,
117 TokenTree::Delimited(sp, ..) => sp.entire(),
121 /// Modify the `TokenTree`'s span in-place.
122 pub fn set_span(&mut self, span: Span) {
124 TokenTree::Token(token) => token.span = span,
125 TokenTree::Delimited(dspan, ..) => *dspan = DelimSpan::from_single(span),
129 /// Indicates if the stream is a token that is equal to the provided token.
130 pub fn eq_token(&self, t: TokenKind) -> bool {
132 TokenTree::Token(token) => *token == t,
137 pub fn joint(self) -> TokenStream {
138 TokenStream::new(vec![(self, Joint)])
141 pub fn token(span: Span, kind: TokenKind) -> TokenTree {
142 TokenTree::Token(Token { kind, span })
145 /// Returns the opening delimiter as a token tree.
146 pub fn open_tt(span: Span, delim: DelimToken) -> TokenTree {
147 let open_span = if span.is_dummy() {
150 span.with_hi(span.lo() + BytePos(delim.len() as u32))
152 TokenTree::token(open_span, token::OpenDelim(delim))
155 /// Returns the closing delimiter as a token tree.
156 pub fn close_tt(span: Span, delim: DelimToken) -> TokenTree {
157 let close_span = if span.is_dummy() {
160 span.with_lo(span.hi() - BytePos(delim.len() as u32))
162 TokenTree::token(close_span, token::CloseDelim(delim))
168 /// A `TokenStream` is an abstract sequence of tokens, organized into `TokenTree`s.
169 /// The goal is for procedural macros to work with `TokenStream`s and `TokenTree`s
170 /// instead of a representation of the abstract syntax tree.
171 /// Today's `TokenTree`s can still contain AST via `token::Interpolated` for back-compat.
173 /// The use of `Option` is an optimization that avoids the need for an
174 /// allocation when the stream is empty. However, it is not guaranteed that an
175 /// empty stream is represented with `None`; it may be represented as a `Some`
176 /// around an empty `Vec`.
177 #[derive(Clone, Debug)]
178 pub struct TokenStream(pub Option<Lrc<Vec<TreeAndJoint>>>);
180 pub type TreeAndJoint = (TokenTree, IsJoint);
182 // `TokenStream` is used a lot. Make sure it doesn't unintentionally get bigger.
183 #[cfg(target_arch = "x86_64")]
184 static_assert_size!(TokenStream, 8);
186 #[derive(Clone, Copy, Debug, PartialEq)]
195 /// Given a `TokenStream` with a `Stream` of only two arguments, return a new `TokenStream`
196 /// separating the two arguments with a comma for diagnostic suggestions.
197 pub(crate) fn add_comma(&self) -> Option<(TokenStream, Span)> {
198 // Used to suggest if a user writes `foo!(a b);`
199 if let Some(ref stream) = self.0 {
200 let mut suggestion = None;
201 let mut iter = stream.iter().enumerate().peekable();
202 while let Some((pos, ts)) = iter.next() {
203 if let Some((_, next)) = iter.peek() {
204 let sp = match (&ts, &next) {
205 (_, (TokenTree::Token(Token { kind: token::Comma, .. }), _)) => continue,
206 ((TokenTree::Token(token_left), NonJoint), (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()) => token_left.span,
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<T: Into<TokenStream>> iter::FromIterator<T> for TokenStream {
245 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
246 TokenStream::from_streams(iter.into_iter().map(Into::into).collect::<SmallVec<_>>())
250 impl Eq for TokenStream {}
252 impl PartialEq<TokenStream> for TokenStream {
253 fn eq(&self, other: &TokenStream) -> bool {
254 self.trees().eq(other.trees())
259 pub fn len(&self) -> usize {
260 if let Some(ref slice) = self.0 {
267 pub fn empty() -> TokenStream {
271 pub fn is_empty(&self) -> bool {
274 Some(ref stream) => stream.is_empty(),
278 pub(crate) fn from_streams(mut streams: SmallVec<[TokenStream; 2]>) -> TokenStream {
279 match streams.len() {
280 0 => TokenStream::empty(),
281 1 => streams.pop().unwrap(),
283 // rust-lang/rust#57735: pre-allocate vector to avoid
284 // quadratic blow-up due to on-the-fly reallocations.
285 let tree_count = streams.iter()
286 .map(|ts| match &ts.0 { None => 0, Some(s) => s.len() })
288 let mut vec = Vec::with_capacity(tree_count);
290 for stream in streams {
293 Some(stream2) => vec.extend(stream2.iter().cloned()),
296 TokenStream::new(vec)
301 pub fn new(streams: Vec<TreeAndJoint>) -> TokenStream {
302 match streams.len() {
303 0 => TokenStream(None),
304 _ => TokenStream(Some(Lrc::new(streams))),
308 pub fn append_to_tree_and_joint_vec(self, vec: &mut Vec<TreeAndJoint>) {
309 if let Some(stream) = self.0 {
310 vec.extend(stream.iter().cloned());
314 pub fn trees(&self) -> Cursor {
315 self.clone().into_trees()
318 pub fn into_trees(self) -> Cursor {
322 /// Compares two TokenStreams, checking equality without regarding span information.
323 pub fn eq_unspanned(&self, other: &TokenStream) -> bool {
324 let mut t1 = self.trees();
325 let mut t2 = other.trees();
326 for (t1, t2) in t1.by_ref().zip(t2.by_ref()) {
327 if !t1.eq_unspanned(&t2) {
331 t1.next().is_none() && t2.next().is_none()
334 // See comments in `Nonterminal::to_tokenstream` for why we care about
335 // *probably* equal here rather than actual equality
337 // This is otherwise the same as `eq_unspanned`, only recursing with a
339 pub fn probably_equal_for_proc_macro(&self, other: &TokenStream) -> bool {
340 // When checking for `probably_eq`, we ignore certain tokens that aren't
341 // preserved in the AST. Because they are not preserved, the pretty
342 // printer arbitrarily adds or removes them when printing as token
343 // streams, making a comparison between a token stream generated from an
344 // AST and a token stream which was parsed into an AST more reliable.
345 fn semantic_tree(tree: &TokenTree) -> bool {
346 if let TokenTree::Token(token) = tree {
348 // The pretty printer tends to add trailing commas to
349 // everything, and in particular, after struct fields.
351 // The pretty printer emits `NoDelim` as whitespace.
352 | token::OpenDelim(DelimToken::NoDelim)
353 | token::CloseDelim(DelimToken::NoDelim)
354 // The pretty printer collapses many semicolons into one.
356 // The pretty printer collapses whitespace arbitrarily and can
357 // introduce whitespace from `NoDelim`.
359 // The pretty printer can turn `$crate` into `::crate_name`
360 | token::ModSep = token.kind {
367 let mut t1 = self.trees().filter(semantic_tree);
368 let mut t2 = other.trees().filter(semantic_tree);
369 for (t1, t2) in t1.by_ref().zip(t2.by_ref()) {
370 if !t1.probably_equal_for_proc_macro(&t2) {
374 t1.next().is_none() && t2.next().is_none()
377 pub fn map_enumerated<F: FnMut(usize, TokenTree) -> TokenTree>(self, mut f: F) -> TokenStream {
378 TokenStream(self.0.map(|stream| {
383 .map(|(i, (tree, is_joint))| (f(i, tree.clone()), *is_joint))
388 pub fn map<F: FnMut(TokenTree) -> TokenTree>(self, mut f: F) -> TokenStream {
389 TokenStream(self.0.map(|stream| {
393 .map(|(tree, is_joint)| (f(tree.clone()), *is_joint))
398 fn first_tree_and_joint(&self) -> Option<TreeAndJoint> {
399 self.0.as_ref().map(|stream| {
400 stream.first().unwrap().clone()
404 fn last_tree_if_joint(&self) -> Option<TokenTree> {
407 Some(ref stream) => {
408 if let (tree, Joint) = stream.last().unwrap() {
418 // 99.5%+ of the time we have 1 or 2 elements in this vector.
420 pub struct TokenStreamBuilder(SmallVec<[TokenStream; 2]>);
422 impl TokenStreamBuilder {
423 pub fn new() -> TokenStreamBuilder {
424 TokenStreamBuilder(SmallVec::new())
427 pub fn push<T: Into<TokenStream>>(&mut self, stream: T) {
428 let stream = stream.into();
429 let last_tree_if_joint = self.0.last().and_then(TokenStream::last_tree_if_joint);
430 if let Some(TokenTree::Token(last_token)) = last_tree_if_joint {
431 if let Some((TokenTree::Token(token), is_joint)) = stream.first_tree_and_joint() {
432 if let Some(glued_tok) = last_token.kind.glue(token.kind) {
433 let last_stream = self.0.pop().unwrap();
434 self.push_all_but_last_tree(&last_stream);
435 let glued_span = last_token.span.to(token.span);
436 let glued_tt = TokenTree::token(glued_span, glued_tok);
437 let glued_tokenstream = TokenStream::new(vec![(glued_tt, is_joint)]);
438 self.0.push(glued_tokenstream);
439 self.push_all_but_first_tree(&stream);
447 pub fn build(self) -> TokenStream {
448 TokenStream::from_streams(self.0)
451 fn push_all_but_last_tree(&mut self, stream: &TokenStream) {
452 if let Some(ref streams) = stream.0 {
453 let len = streams.len();
456 _ => self.0.push(TokenStream(Some(Lrc::new(streams[0 .. len - 1].to_vec())))),
461 fn push_all_but_first_tree(&mut self, stream: &TokenStream) {
462 if let Some(ref streams) = stream.0 {
463 let len = streams.len();
466 _ => self.0.push(TokenStream(Some(Lrc::new(streams[1 .. len].to_vec())))),
474 pub stream: TokenStream,
478 impl Iterator for Cursor {
479 type Item = TokenTree;
481 fn next(&mut self) -> Option<TokenTree> {
482 self.next_with_joint().map(|(tree, _)| tree)
487 fn new(stream: TokenStream) -> Self {
488 Cursor { stream, index: 0 }
491 pub fn next_with_joint(&mut self) -> Option<TreeAndJoint> {
492 match self.stream.0 {
494 Some(ref stream) => {
495 if self.index < stream.len() {
497 Some(stream[self.index - 1].clone())
505 pub fn append(&mut self, new_stream: TokenStream) {
506 if new_stream.is_empty() {
509 let index = self.index;
510 let stream = mem::replace(&mut self.stream, TokenStream(None));
511 *self = TokenStream::from_streams(smallvec![stream, new_stream]).into_trees();
515 pub fn look_ahead(&self, n: usize) -> Option<TokenTree> {
516 match self.stream.0 {
518 Some(ref stream) => stream[self.index ..].get(n).map(|(tree, _)| tree.clone()),
523 impl fmt::Display for TokenStream {
524 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
525 f.write_str(&pprust::tokens_to_string(self.clone()))
529 impl Encodable for TokenStream {
530 fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), E::Error> {
531 self.trees().collect::<Vec<_>>().encode(encoder)
535 impl Decodable for TokenStream {
536 fn decode<D: Decoder>(decoder: &mut D) -> Result<TokenStream, D::Error> {
537 Vec::<TokenTree>::decode(decoder).map(|vec| vec.into_iter().collect())
541 #[derive(Debug, Copy, Clone, PartialEq, RustcEncodable, RustcDecodable)]
542 pub struct DelimSpan {
548 pub fn from_single(sp: Span) -> Self {
555 pub fn from_pair(open: Span, close: Span) -> Self {
556 DelimSpan { open, close }
559 pub fn dummy() -> Self {
560 Self::from_single(DUMMY_SP)
563 pub fn entire(self) -> Span {
564 self.open.with_hi(self.close.hi())
567 pub fn apply_mark(self, mark: Mark) -> Self {
569 open: self.open.apply_mark(mark),
570 close: self.close.apply_mark(mark),
578 use crate::syntax::ast::Ident;
579 use crate::with_default_globals;
580 use crate::util::parser_testing::string_to_stream;
581 use syntax_pos::{Span, BytePos, NO_EXPANSION};
583 fn string_to_ts(string: &str) -> TokenStream {
584 string_to_stream(string.to_owned())
587 fn sp(a: u32, b: u32) -> Span {
588 Span::new(BytePos(a), BytePos(b), NO_EXPANSION)
593 with_default_globals(|| {
594 let test_res = string_to_ts("foo::bar::baz");
595 let test_fst = string_to_ts("foo::bar");
596 let test_snd = string_to_ts("::baz");
597 let eq_res = TokenStream::from_streams(smallvec![test_fst, test_snd]);
598 assert_eq!(test_res.trees().count(), 5);
599 assert_eq!(eq_res.trees().count(), 5);
600 assert_eq!(test_res.eq_unspanned(&eq_res), true);
605 fn test_to_from_bijection() {
606 with_default_globals(|| {
607 let test_start = string_to_ts("foo::bar(baz)");
608 let test_end = test_start.trees().collect();
609 assert_eq!(test_start, test_end)
615 with_default_globals(|| {
616 let test_res = string_to_ts("foo");
617 let test_eqs = string_to_ts("foo");
618 assert_eq!(test_res, test_eqs)
624 with_default_globals(|| {
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)
633 with_default_globals(|| {
634 let test_res = string_to_ts("");
635 let test_eqs = string_to_ts("");
636 assert_eq!(test_res, test_eqs)
642 with_default_globals(|| {
643 let test_res = string_to_ts("::bar::baz");
644 let test_eqs = string_to_ts("bar::baz");
645 assert_eq!(test_res == test_eqs, false)
651 with_default_globals(|| {
652 let test_res = string_to_ts("(bar,baz)");
653 let test_eqs = string_to_ts("bar,baz");
654 assert_eq!(test_res == test_eqs, false)
660 with_default_globals(|| {
661 let test0: TokenStream = Vec::<TokenTree>::new().into_iter().collect();
662 let test1: TokenStream =
663 TokenTree::token(sp(0, 1), token::Ident(Ident::from_str("a"), false)).into();
664 let test2 = string_to_ts("foo(bar::baz)");
666 assert_eq!(test0.is_empty(), true);
667 assert_eq!(test1.is_empty(), false);
668 assert_eq!(test2.is_empty(), false);
673 fn test_dotdotdot() {
674 with_default_globals(|| {
675 let mut builder = TokenStreamBuilder::new();
676 builder.push(TokenTree::token(sp(0, 1), token::Dot).joint());
677 builder.push(TokenTree::token(sp(1, 2), token::Dot).joint());
678 builder.push(TokenTree::token(sp(2, 3), token::Dot));
679 let stream = builder.build();
680 assert!(stream.eq_unspanned(&string_to_ts("...")));
681 assert_eq!(stream.trees().count(), 1);