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 //! `TokenStream`s 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.
16 use crate::parse::token::{self, DelimToken, Token, TokenKind};
17 use crate::print::pprust;
19 use syntax_pos::{BytePos, Span, DUMMY_SP};
20 #[cfg(target_arch = "x86_64")]
21 use rustc_data_structures::static_assert_size;
22 use rustc_data_structures::sync::Lrc;
23 use rustc_serialize::{Decoder, Decodable, Encoder, Encodable};
24 use smallvec::{SmallVec, smallvec};
26 use std::{fmt, iter, mem};
31 /// When the main rust parser encounters a syntax-extension invocation, it
32 /// parses the arguments to the invocation as a token-tree. This is a very
33 /// loose structure, such that all sorts of different AST-fragments can
34 /// be passed to syntax extensions using a uniform type.
36 /// If the syntax extension is an MBE macro, it will attempt to match its
37 /// LHS token tree against the provided token tree, and if it finds a
38 /// match, will transcribe the RHS token tree, splicing in any captured
39 /// `macro_parser::matched_nonterminals` into the `SubstNt`s it finds.
41 /// The RHS of an MBE macro is the only place `SubstNt`s are substituted.
42 /// Nothing special happens to misnamed or misplaced `SubstNt`s.
43 #[derive(Debug, Clone, PartialEq, RustcEncodable, RustcDecodable)]
47 /// A delimited sequence of token trees
48 Delimited(DelimSpan, DelimToken, TokenStream),
51 // Ensure all fields of `TokenTree` is `Send` and `Sync`.
52 #[cfg(parallel_compiler)]
56 DelimSpan: Send + Sync,
57 DelimToken: Send + Sync,
58 TokenStream: Send + Sync,
62 /// Checks if this TokenTree is equal to the other, regardless of span information.
63 pub fn eq_unspanned(&self, other: &TokenTree) -> bool {
65 (TokenTree::Token(token), TokenTree::Token(token2)) => token.kind == token2.kind,
66 (TokenTree::Delimited(_, delim, tts), TokenTree::Delimited(_, delim2, tts2)) => {
67 delim == delim2 && tts.eq_unspanned(&tts2)
73 // See comments in `Nonterminal::to_tokenstream` for why we care about
74 // *probably* equal here rather than actual equality
76 // This is otherwise the same as `eq_unspanned`, only recursing with a
78 pub fn probably_equal_for_proc_macro(&self, other: &TokenTree) -> bool {
80 (TokenTree::Token(token), TokenTree::Token(token2)) => {
81 token.probably_equal_for_proc_macro(token2)
83 (TokenTree::Delimited(_, delim, tts), TokenTree::Delimited(_, delim2, tts2)) => {
84 delim == delim2 && tts.probably_equal_for_proc_macro(&tts2)
90 /// Retrieves the TokenTree's span.
91 pub fn span(&self) -> Span {
93 TokenTree::Token(token) => token.span,
94 TokenTree::Delimited(sp, ..) => sp.entire(),
98 /// Modify the `TokenTree`'s span in-place.
99 pub fn set_span(&mut self, span: Span) {
101 TokenTree::Token(token) => token.span = span,
102 TokenTree::Delimited(dspan, ..) => *dspan = DelimSpan::from_single(span),
106 pub fn joint(self) -> TokenStream {
107 TokenStream::new(vec![(self, Joint)])
110 pub fn token(kind: TokenKind, span: Span) -> TokenTree {
111 TokenTree::Token(Token::new(kind, span))
114 /// Returns the opening delimiter as a token tree.
115 pub fn open_tt(span: Span, delim: DelimToken) -> TokenTree {
116 let open_span = if span.is_dummy() {
119 span.with_hi(span.lo() + BytePos(delim.len() as u32))
121 TokenTree::token(token::OpenDelim(delim), open_span)
124 /// Returns the closing delimiter as a token tree.
125 pub fn close_tt(span: Span, delim: DelimToken) -> TokenTree {
126 let close_span = if span.is_dummy() {
129 span.with_lo(span.hi() - BytePos(delim.len() as u32))
131 TokenTree::token(token::CloseDelim(delim), close_span)
135 /// A `TokenStream` is an abstract sequence of tokens, organized into `TokenTree`s.
137 /// The goal is for procedural macros to work with `TokenStream`s and `TokenTree`s
138 /// instead of a representation of the abstract syntax tree.
139 /// Today's `TokenTree`s can still contain AST via `token::Interpolated` for back-compat.
141 /// The use of `Option` is an optimization that avoids the need for an
142 /// allocation when the stream is empty. However, it is not guaranteed that an
143 /// empty stream is represented with `None`; it may be represented as a `Some`
144 /// around an empty `Vec`.
145 #[derive(Clone, Debug)]
146 pub struct TokenStream(pub Option<Lrc<Vec<TreeAndJoint>>>);
148 pub type TreeAndJoint = (TokenTree, IsJoint);
150 // `TokenStream` is used a lot. Make sure it doesn't unintentionally get bigger.
151 #[cfg(target_arch = "x86_64")]
152 static_assert_size!(TokenStream, 8);
154 #[derive(Clone, Copy, Debug, PartialEq)]
163 /// Given a `TokenStream` with a `Stream` of only two arguments, return a new `TokenStream`
164 /// separating the two arguments with a comma for diagnostic suggestions.
165 pub(crate) fn add_comma(&self) -> Option<(TokenStream, Span)> {
166 // Used to suggest if a user writes `foo!(a b);`
167 if let Some(ref stream) = self.0 {
168 let mut suggestion = None;
169 let mut iter = stream.iter().enumerate().peekable();
170 while let Some((pos, ts)) = iter.next() {
171 if let Some((_, next)) = iter.peek() {
172 let sp = match (&ts, &next) {
173 (_, (TokenTree::Token(Token { kind: token::Comma, .. }), _)) => continue,
174 ((TokenTree::Token(token_left), NonJoint),
175 (TokenTree::Token(token_right), _))
176 if ((token_left.is_ident() && !token_left.is_reserved_ident())
177 || token_left.is_lit()) &&
178 ((token_right.is_ident() && !token_right.is_reserved_ident())
179 || token_right.is_lit()) => token_left.span,
180 ((TokenTree::Delimited(sp, ..), NonJoint), _) => sp.entire(),
183 let sp = sp.shrink_to_hi();
184 let comma = (TokenTree::token(token::Comma, sp), NonJoint);
185 suggestion = Some((pos, comma, sp));
188 if let Some((pos, comma, sp)) = suggestion {
189 let mut new_stream = vec![];
190 let parts = stream.split_at(pos + 1);
191 new_stream.extend_from_slice(parts.0);
192 new_stream.push(comma);
193 new_stream.extend_from_slice(parts.1);
194 return Some((TokenStream::new(new_stream), sp));
201 impl From<TokenTree> for TokenStream {
202 fn from(tree: TokenTree) -> TokenStream {
203 TokenStream::new(vec![(tree, NonJoint)])
207 impl From<TokenTree> for TreeAndJoint {
208 fn from(tree: TokenTree) -> TreeAndJoint {
213 impl<T: Into<TokenStream>> iter::FromIterator<T> for TokenStream {
214 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
215 TokenStream::from_streams(iter.into_iter().map(Into::into).collect::<SmallVec<_>>())
219 impl Eq for TokenStream {}
221 impl PartialEq<TokenStream> for TokenStream {
222 fn eq(&self, other: &TokenStream) -> bool {
223 self.trees().eq(other.trees())
228 pub fn len(&self) -> usize {
229 if let Some(ref slice) = self.0 {
236 pub fn empty() -> TokenStream {
240 pub fn is_empty(&self) -> bool {
243 Some(ref stream) => stream.is_empty(),
247 pub(crate) fn from_streams(mut streams: SmallVec<[TokenStream; 2]>) -> TokenStream {
248 match streams.len() {
249 0 => TokenStream::empty(),
250 1 => streams.pop().unwrap(),
252 // We are going to extend the first stream in `streams` with
253 // the elements from the subsequent streams. This requires
254 // using `make_mut()` on the first stream, and in practice this
255 // doesn't cause cloning 99.9% of the time.
257 // One very common use case is when `streams` has two elements,
258 // where the first stream has any number of elements within
259 // (often 1, but sometimes many more) and the second stream has
260 // a single element within.
262 // Determine how much the first stream will be extended.
263 // Needed to avoid quadratic blow up from on-the-fly
264 // reallocations (#57735).
265 let num_appends = streams.iter()
270 // Get the first stream. If it's `None`, create an empty
272 let mut iter = streams.drain();
273 let mut first_stream_lrc = match iter.next().unwrap().0 {
274 Some(first_stream_lrc) => first_stream_lrc,
275 None => Lrc::new(vec![]),
278 // Append the elements to the first stream, after reserving
280 let first_vec_mut = Lrc::make_mut(&mut first_stream_lrc);
281 first_vec_mut.reserve(num_appends);
283 if let Some(stream) = stream.0 {
284 first_vec_mut.extend(stream.iter().cloned());
288 // Create the final `TokenStream`.
289 match first_vec_mut.len() {
290 0 => TokenStream(None),
291 _ => TokenStream(Some(first_stream_lrc)),
297 pub fn new(streams: Vec<TreeAndJoint>) -> TokenStream {
298 match streams.len() {
299 0 => TokenStream(None),
300 _ => TokenStream(Some(Lrc::new(streams))),
304 pub fn append_to_tree_and_joint_vec(self, vec: &mut Vec<TreeAndJoint>) {
305 if let Some(stream) = self.0 {
306 vec.extend(stream.iter().cloned());
310 pub fn trees(&self) -> Cursor {
311 self.clone().into_trees()
314 pub fn into_trees(self) -> Cursor {
318 /// Compares two `TokenStream`s, checking equality without regarding span information.
319 pub fn eq_unspanned(&self, other: &TokenStream) -> bool {
320 let mut t1 = self.trees();
321 let mut t2 = other.trees();
322 for (t1, t2) in t1.by_ref().zip(t2.by_ref()) {
323 if !t1.eq_unspanned(&t2) {
327 t1.next().is_none() && t2.next().is_none()
330 // See comments in `Nonterminal::to_tokenstream` for why we care about
331 // *probably* equal here rather than actual equality
333 // This is otherwise the same as `eq_unspanned`, only recursing with a
335 pub fn probably_equal_for_proc_macro(&self, other: &TokenStream) -> bool {
336 // When checking for `probably_eq`, we ignore certain tokens that aren't
337 // preserved in the AST. Because they are not preserved, the pretty
338 // printer arbitrarily adds or removes them when printing as token
339 // streams, making a comparison between a token stream generated from an
340 // AST and a token stream which was parsed into an AST more reliable.
341 fn semantic_tree(tree: &TokenTree) -> bool {
342 if let TokenTree::Token(token) = tree {
344 // The pretty printer tends to add trailing commas to
345 // everything, and in particular, after struct fields.
347 // The pretty printer emits `NoDelim` as whitespace.
348 | token::OpenDelim(DelimToken::NoDelim)
349 | token::CloseDelim(DelimToken::NoDelim)
350 // The pretty printer collapses many semicolons into one.
352 // The pretty printer collapses whitespace arbitrarily and can
353 // introduce whitespace from `NoDelim`.
355 // The pretty printer can turn `$crate` into `::crate_name`
356 | token::ModSep = token.kind {
363 let mut t1 = self.trees().filter(semantic_tree);
364 let mut t2 = other.trees().filter(semantic_tree);
365 for (t1, t2) in t1.by_ref().zip(t2.by_ref()) {
366 if !t1.probably_equal_for_proc_macro(&t2) {
370 t1.next().is_none() && t2.next().is_none()
373 pub fn map_enumerated<F: FnMut(usize, TokenTree) -> TokenTree>(self, mut f: F) -> TokenStream {
374 TokenStream(self.0.map(|stream| {
379 .map(|(i, (tree, is_joint))| (f(i, tree.clone()), *is_joint))
384 pub fn map<F: FnMut(TokenTree) -> TokenTree>(self, mut f: F) -> TokenStream {
385 TokenStream(self.0.map(|stream| {
389 .map(|(tree, is_joint)| (f(tree.clone()), *is_joint))
395 // 99.5%+ of the time we have 1 or 2 elements in this vector.
397 pub struct TokenStreamBuilder(SmallVec<[TokenStream; 2]>);
399 impl TokenStreamBuilder {
400 pub fn new() -> TokenStreamBuilder {
401 TokenStreamBuilder(SmallVec::new())
404 pub fn push<T: Into<TokenStream>>(&mut self, stream: T) {
405 let mut stream = stream.into();
407 // If `self` is not empty and the last tree within the last stream is a
408 // token tree marked with `Joint`...
409 if let Some(TokenStream(Some(ref mut last_stream_lrc))) = self.0.last_mut() {
410 if let Some((TokenTree::Token(last_token), Joint)) = last_stream_lrc.last() {
412 // ...and `stream` is not empty and the first tree within it is
414 if let TokenStream(Some(ref mut stream_lrc)) = stream {
415 if let Some((TokenTree::Token(token), is_joint)) = stream_lrc.first() {
417 // ...and the two tokens can be glued together...
418 if let Some(glued_tok) = last_token.glue(&token) {
420 // ...then do so, by overwriting the last token
421 // tree in `self` and removing the first token tree
422 // from `stream`. This requires using `make_mut()`
423 // on the last stream in `self` and on `stream`,
424 // and in practice this doesn't cause cloning 99.9%
427 // Overwrite the last token tree with the merged
429 let last_vec_mut = Lrc::make_mut(last_stream_lrc);
430 *last_vec_mut.last_mut().unwrap() =
431 (TokenTree::Token(glued_tok), *is_joint);
433 // Remove the first token tree from `stream`. (This
434 // is almost always the only tree in `stream`.)
435 let stream_vec_mut = Lrc::make_mut(stream_lrc);
436 stream_vec_mut.remove(0);
438 // Don't push `stream` if it's empty -- that could
439 // block subsequent token gluing, by getting
440 // between two token trees that should be glued
442 if !stream.is_empty() {
454 pub fn build(self) -> TokenStream {
455 TokenStream::from_streams(self.0)
461 pub stream: TokenStream,
465 impl Iterator for Cursor {
466 type Item = TokenTree;
468 fn next(&mut self) -> Option<TokenTree> {
469 self.next_with_joint().map(|(tree, _)| tree)
474 fn new(stream: TokenStream) -> Self {
475 Cursor { stream, index: 0 }
478 pub fn next_with_joint(&mut self) -> Option<TreeAndJoint> {
479 match self.stream.0 {
481 Some(ref stream) => {
482 if self.index < stream.len() {
484 Some(stream[self.index - 1].clone())
492 pub fn append(&mut self, new_stream: TokenStream) {
493 if new_stream.is_empty() {
496 let index = self.index;
497 let stream = mem::replace(&mut self.stream, TokenStream(None));
498 *self = TokenStream::from_streams(smallvec![stream, new_stream]).into_trees();
502 pub fn look_ahead(&self, n: usize) -> Option<TokenTree> {
503 match self.stream.0 {
505 Some(ref stream) => stream[self.index ..].get(n).map(|(tree, _)| tree.clone()),
510 impl fmt::Display for TokenStream {
511 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
512 f.write_str(&pprust::tts_to_string(self.clone()))
516 impl Encodable for TokenStream {
517 fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), E::Error> {
518 self.trees().collect::<Vec<_>>().encode(encoder)
522 impl Decodable for TokenStream {
523 fn decode<D: Decoder>(decoder: &mut D) -> Result<TokenStream, D::Error> {
524 Vec::<TokenTree>::decode(decoder).map(|vec| vec.into_iter().collect())
528 #[derive(Debug, Copy, Clone, PartialEq, RustcEncodable, RustcDecodable)]
529 pub struct DelimSpan {
535 pub fn from_single(sp: Span) -> Self {
542 pub fn from_pair(open: Span, close: Span) -> Self {
543 DelimSpan { open, close }
546 pub fn dummy() -> Self {
547 Self::from_single(DUMMY_SP)
550 pub fn entire(self) -> Span {
551 self.open.with_hi(self.close.hi())