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::token::{self, DelimToken, Token, TokenKind};
18 use syntax_pos::{Span, DUMMY_SP};
19 #[cfg(target_arch = "x86_64")]
20 use rustc_data_structures::static_assert_size;
21 use rustc_data_structures::sync::Lrc;
22 use smallvec::{SmallVec, smallvec};
26 /// When the main rust parser encounters a syntax-extension invocation, it
27 /// parses the arguments to the invocation as a token-tree. This is a very
28 /// loose structure, such that all sorts of different AST-fragments can
29 /// be passed to syntax extensions using a uniform type.
31 /// If the syntax extension is an MBE macro, it will attempt to match its
32 /// LHS token tree against the provided token tree, and if it finds a
33 /// match, will transcribe the RHS token tree, splicing in any captured
34 /// `macro_parser::matched_nonterminals` into the `SubstNt`s it finds.
36 /// The RHS of an MBE macro is the only place `SubstNt`s are substituted.
37 /// Nothing special happens to misnamed or misplaced `SubstNt`s.
38 #[derive(Debug, Clone, PartialEq, RustcEncodable, RustcDecodable)]
42 /// A delimited sequence of token trees
43 Delimited(DelimSpan, DelimToken, TokenStream),
46 // Ensure all fields of `TokenTree` is `Send` and `Sync`.
47 #[cfg(parallel_compiler)]
51 DelimSpan: Send + Sync,
52 DelimToken: Send + Sync,
53 TokenStream: Send + Sync,
57 /// Checks if this TokenTree is equal to the other, regardless of span information.
58 pub fn eq_unspanned(&self, other: &TokenTree) -> bool {
60 (TokenTree::Token(token), TokenTree::Token(token2)) => token.kind == token2.kind,
61 (TokenTree::Delimited(_, delim, tts), TokenTree::Delimited(_, delim2, tts2)) => {
62 delim == delim2 && tts.eq_unspanned(&tts2)
68 // See comments in `Nonterminal::to_tokenstream` for why we care about
69 // *probably* equal here rather than actual equality
71 // This is otherwise the same as `eq_unspanned`, only recursing with a
73 pub fn probably_equal_for_proc_macro(&self, other: &TokenTree) -> bool {
75 (TokenTree::Token(token), TokenTree::Token(token2)) => {
76 token.probably_equal_for_proc_macro(token2)
78 (TokenTree::Delimited(_, delim, tts), TokenTree::Delimited(_, delim2, tts2)) => {
79 delim == delim2 && tts.probably_equal_for_proc_macro(&tts2)
85 /// Retrieves the TokenTree's span.
86 pub fn span(&self) -> Span {
88 TokenTree::Token(token) => token.span,
89 TokenTree::Delimited(sp, ..) => sp.entire(),
93 /// Modify the `TokenTree`'s span in-place.
94 pub fn set_span(&mut self, span: Span) {
96 TokenTree::Token(token) => token.span = span,
97 TokenTree::Delimited(dspan, ..) => *dspan = DelimSpan::from_single(span),
101 pub fn joint(self) -> TokenStream {
102 TokenStream::new(vec![(self, Joint)])
105 pub fn token(kind: TokenKind, span: Span) -> TokenTree {
106 TokenTree::Token(Token::new(kind, span))
109 /// Returns the opening delimiter as a token tree.
110 pub fn open_tt(span: DelimSpan, delim: DelimToken) -> TokenTree {
111 TokenTree::token(token::OpenDelim(delim), span.open)
114 /// Returns the closing delimiter as a token tree.
115 pub fn close_tt(span: DelimSpan, delim: DelimToken) -> TokenTree {
116 TokenTree::token(token::CloseDelim(delim), span.close)
120 /// A `TokenStream` is an abstract sequence of tokens, organized into `TokenTree`s.
122 /// The goal is for procedural macros to work with `TokenStream`s and `TokenTree`s
123 /// instead of a representation of the abstract syntax tree.
124 /// Today's `TokenTree`s can still contain AST via `token::Interpolated` for back-compat.
125 #[derive(Clone, Debug, Default, RustcEncodable, RustcDecodable)]
126 pub struct TokenStream(pub Lrc<Vec<TreeAndJoint>>);
128 pub type TreeAndJoint = (TokenTree, IsJoint);
130 // `TokenStream` is used a lot. Make sure it doesn't unintentionally get bigger.
131 #[cfg(target_arch = "x86_64")]
132 static_assert_size!(TokenStream, 8);
134 #[derive(Clone, Copy, Debug, PartialEq, RustcEncodable, RustcDecodable)]
143 /// Given a `TokenStream` with a `Stream` of only two arguments, return a new `TokenStream`
144 /// separating the two arguments with a comma for diagnostic suggestions.
145 pub fn add_comma(&self) -> Option<(TokenStream, Span)> {
146 // Used to suggest if a user writes `foo!(a b);`
147 let mut suggestion = None;
148 let mut iter = self.0.iter().enumerate().peekable();
149 while let Some((pos, ts)) = iter.next() {
150 if let Some((_, next)) = iter.peek() {
151 let sp = match (&ts, &next) {
152 (_, (TokenTree::Token(Token { kind: token::Comma, .. }), _)) => continue,
153 ((TokenTree::Token(token_left), NonJoint),
154 (TokenTree::Token(token_right), _))
155 if ((token_left.is_ident() && !token_left.is_reserved_ident())
156 || token_left.is_lit()) &&
157 ((token_right.is_ident() && !token_right.is_reserved_ident())
158 || token_right.is_lit()) => token_left.span,
159 ((TokenTree::Delimited(sp, ..), NonJoint), _) => sp.entire(),
162 let sp = sp.shrink_to_hi();
163 let comma = (TokenTree::token(token::Comma, sp), NonJoint);
164 suggestion = Some((pos, comma, sp));
167 if let Some((pos, comma, sp)) = suggestion {
168 let mut new_stream = vec![];
169 let parts = self.0.split_at(pos + 1);
170 new_stream.extend_from_slice(parts.0);
171 new_stream.push(comma);
172 new_stream.extend_from_slice(parts.1);
173 return Some((TokenStream::new(new_stream), sp));
179 impl From<TokenTree> for TokenStream {
180 fn from(tree: TokenTree) -> TokenStream {
181 TokenStream::new(vec![(tree, NonJoint)])
185 impl From<TokenTree> for TreeAndJoint {
186 fn from(tree: TokenTree) -> TreeAndJoint {
191 impl iter::FromIterator<TokenTree> for TokenStream {
192 fn from_iter<I: IntoIterator<Item = TokenTree>>(iter: I) -> Self {
193 TokenStream::new(iter.into_iter().map(Into::into).collect::<Vec<TreeAndJoint>>())
197 impl Eq for TokenStream {}
199 impl PartialEq<TokenStream> for TokenStream {
200 fn eq(&self, other: &TokenStream) -> bool {
201 self.trees().eq(other.trees())
206 pub fn new(streams: Vec<TreeAndJoint>) -> TokenStream {
207 TokenStream(Lrc::new(streams))
210 pub fn is_empty(&self) -> bool {
214 pub fn len(&self) -> usize {
218 pub fn from_streams(mut streams: SmallVec<[TokenStream; 2]>) -> TokenStream {
219 match streams.len() {
220 0 => TokenStream::default(),
221 1 => streams.pop().unwrap(),
223 // We are going to extend the first stream in `streams` with
224 // the elements from the subsequent streams. This requires
225 // using `make_mut()` on the first stream, and in practice this
226 // doesn't cause cloning 99.9% of the time.
228 // One very common use case is when `streams` has two elements,
229 // where the first stream has any number of elements within
230 // (often 1, but sometimes many more) and the second stream has
231 // a single element within.
233 // Determine how much the first stream will be extended.
234 // Needed to avoid quadratic blow up from on-the-fly
235 // reallocations (#57735).
236 let num_appends = streams.iter()
241 // Get the first stream. If it's `None`, create an empty
243 let mut iter = streams.drain(..);
244 let mut first_stream_lrc = iter.next().unwrap().0;
246 // Append the elements to the first stream, after reserving
248 let first_vec_mut = Lrc::make_mut(&mut first_stream_lrc);
249 first_vec_mut.reserve(num_appends);
251 first_vec_mut.extend(stream.0.iter().cloned());
254 // Create the final `TokenStream`.
255 TokenStream(first_stream_lrc)
260 pub fn trees(&self) -> Cursor {
261 self.clone().into_trees()
264 pub fn into_trees(self) -> Cursor {
268 /// Compares two `TokenStream`s, checking equality without regarding span information.
269 pub fn eq_unspanned(&self, other: &TokenStream) -> bool {
270 let mut t1 = self.trees();
271 let mut t2 = other.trees();
272 for (t1, t2) in t1.by_ref().zip(t2.by_ref()) {
273 if !t1.eq_unspanned(&t2) {
277 t1.next().is_none() && t2.next().is_none()
280 // See comments in `Nonterminal::to_tokenstream` for why we care about
281 // *probably* equal here rather than actual equality
283 // This is otherwise the same as `eq_unspanned`, only recursing with a
285 pub fn probably_equal_for_proc_macro(&self, other: &TokenStream) -> bool {
286 // When checking for `probably_eq`, we ignore certain tokens that aren't
287 // preserved in the AST. Because they are not preserved, the pretty
288 // printer arbitrarily adds or removes them when printing as token
289 // streams, making a comparison between a token stream generated from an
290 // AST and a token stream which was parsed into an AST more reliable.
291 fn semantic_tree(tree: &TokenTree) -> bool {
292 if let TokenTree::Token(token) = tree {
294 // The pretty printer tends to add trailing commas to
295 // everything, and in particular, after struct fields.
297 // The pretty printer emits `NoDelim` as whitespace.
298 | token::OpenDelim(DelimToken::NoDelim)
299 | token::CloseDelim(DelimToken::NoDelim)
300 // The pretty printer collapses many semicolons into one.
302 // The pretty printer collapses whitespace arbitrarily and can
303 // introduce whitespace from `NoDelim`.
305 // The pretty printer can turn `$crate` into `::crate_name`
306 | token::ModSep = token.kind {
313 let mut t1 = self.trees().filter(semantic_tree);
314 let mut t2 = other.trees().filter(semantic_tree);
315 for (t1, t2) in t1.by_ref().zip(t2.by_ref()) {
316 if !t1.probably_equal_for_proc_macro(&t2) {
320 t1.next().is_none() && t2.next().is_none()
323 pub fn map_enumerated<F: FnMut(usize, TokenTree) -> TokenTree>(self, mut f: F) -> TokenStream {
324 TokenStream(Lrc::new(
328 .map(|(i, (tree, is_joint))| (f(i, tree.clone()), *is_joint))
333 pub fn map<F: FnMut(TokenTree) -> TokenTree>(self, mut f: F) -> TokenStream {
334 TokenStream(Lrc::new(
337 .map(|(tree, is_joint)| (f(tree.clone()), *is_joint))
343 // 99.5%+ of the time we have 1 or 2 elements in this vector.
345 pub struct TokenStreamBuilder(SmallVec<[TokenStream; 2]>);
347 impl TokenStreamBuilder {
348 pub fn new() -> TokenStreamBuilder {
349 TokenStreamBuilder(SmallVec::new())
352 pub fn push<T: Into<TokenStream>>(&mut self, stream: T) {
353 let mut stream = stream.into();
355 // If `self` is not empty and the last tree within the last stream is a
356 // token tree marked with `Joint`...
357 if let Some(TokenStream(ref mut last_stream_lrc)) = self.0.last_mut() {
358 if let Some((TokenTree::Token(last_token), Joint)) = last_stream_lrc.last() {
360 // ...and `stream` is not empty and the first tree within it is
362 let TokenStream(ref mut stream_lrc) = stream;
363 if let Some((TokenTree::Token(token), is_joint)) = stream_lrc.first() {
365 // ...and the two tokens can be glued together...
366 if let Some(glued_tok) = last_token.glue(&token) {
368 // ...then do so, by overwriting the last token
369 // tree in `self` and removing the first token tree
370 // from `stream`. This requires using `make_mut()`
371 // on the last stream in `self` and on `stream`,
372 // and in practice this doesn't cause cloning 99.9%
375 // Overwrite the last token tree with the merged
377 let last_vec_mut = Lrc::make_mut(last_stream_lrc);
378 *last_vec_mut.last_mut().unwrap() =
379 (TokenTree::Token(glued_tok), *is_joint);
381 // Remove the first token tree from `stream`. (This
382 // is almost always the only tree in `stream`.)
383 let stream_vec_mut = Lrc::make_mut(stream_lrc);
384 stream_vec_mut.remove(0);
386 // Don't push `stream` if it's empty -- that could
387 // block subsequent token gluing, by getting
388 // between two token trees that should be glued
390 if !stream.is_empty() {
401 pub fn build(self) -> TokenStream {
402 TokenStream::from_streams(self.0)
408 pub stream: TokenStream,
412 impl Iterator for Cursor {
413 type Item = TokenTree;
415 fn next(&mut self) -> Option<TokenTree> {
416 self.next_with_joint().map(|(tree, _)| tree)
421 fn new(stream: TokenStream) -> Self {
422 Cursor { stream, index: 0 }
425 pub fn next_with_joint(&mut self) -> Option<TreeAndJoint> {
426 if self.index < self.stream.len() {
428 Some(self.stream.0[self.index - 1].clone())
434 pub fn append(&mut self, new_stream: TokenStream) {
435 if new_stream.is_empty() {
438 let index = self.index;
439 let stream = mem::take(&mut self.stream);
440 *self = TokenStream::from_streams(smallvec![stream, new_stream]).into_trees();
444 pub fn look_ahead(&self, n: usize) -> Option<TokenTree> {
445 self.stream.0[self.index ..].get(n).map(|(tree, _)| tree.clone())
449 #[derive(Debug, Copy, Clone, PartialEq, RustcEncodable, RustcDecodable)]
450 pub struct DelimSpan {
456 pub fn from_single(sp: Span) -> Self {
463 pub fn from_pair(open: Span, close: Span) -> Self {
464 DelimSpan { open, close }
467 pub fn dummy() -> Self {
468 Self::from_single(DUMMY_SP)
471 pub fn entire(self) -> Span {
472 self.open.with_hi(self.close.hi())