3 //! `TokenStream`s represent syntactic objects before they are converted into ASTs.
4 //! A `TokenStream` is, roughly speaking, a sequence 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::ast::StmtKind;
17 use crate::ast_traits::{HasAttrs, HasSpan, HasTokens};
18 use crate::token::{self, Delimiter, Nonterminal, Token, TokenKind};
21 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
22 use rustc_data_structures::sync::{self, Lrc};
23 use rustc_macros::HashStable_Generic;
24 use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
25 use rustc_span::{Span, DUMMY_SP};
26 use smallvec::{smallvec, SmallVec};
30 /// When the main Rust parser encounters a syntax-extension invocation, it
31 /// parses the arguments to the invocation as a token tree. This is a very
32 /// loose structure, such that all sorts of different AST fragments can
33 /// be passed to syntax extensions using a uniform type.
35 /// If the syntax extension is an MBE macro, it will attempt to match its
36 /// LHS token tree against the provided token tree, and if it finds a
37 /// match, will transcribe the RHS token tree, splicing in any captured
38 /// `macro_parser::matched_nonterminals` into the `SubstNt`s it finds.
40 /// The RHS of an MBE macro is the only place `SubstNt`s are substituted.
41 /// Nothing special happens to misnamed or misplaced `SubstNt`s.
42 #[derive(Debug, Clone, PartialEq, Encodable, Decodable, HashStable_Generic)]
45 Token(Token, Spacing),
46 /// A delimited sequence of token trees.
47 Delimited(DelimSpan, Delimiter, TokenStream),
50 // This type is used a lot. Make sure it doesn't unintentionally get bigger.
51 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
52 rustc_data_structures::static_assert_size!(TokenTree, 32);
54 // Ensure all fields of `TokenTree` is `Send` and `Sync`.
55 #[cfg(parallel_compiler)]
59 DelimSpan: Send + Sync,
60 Delimiter: Send + Sync,
61 TokenStream: Send + Sync,
66 /// Checks if this `TokenTree` is equal to the other, regardless of span information.
67 pub fn eq_unspanned(&self, other: &TokenTree) -> bool {
69 (TokenTree::Token(token, _), TokenTree::Token(token2, _)) => token.kind == token2.kind,
70 (TokenTree::Delimited(_, delim, tts), TokenTree::Delimited(_, delim2, tts2)) => {
71 delim == delim2 && tts.eq_unspanned(&tts2)
77 /// Retrieves the `TokenTree`'s span.
78 pub fn span(&self) -> Span {
80 TokenTree::Token(token, _) => token.span,
81 TokenTree::Delimited(sp, ..) => sp.entire(),
85 /// Modify the `TokenTree`'s span in-place.
86 pub fn set_span(&mut self, span: Span) {
88 TokenTree::Token(token, _) => token.span = span,
89 TokenTree::Delimited(dspan, ..) => *dspan = DelimSpan::from_single(span),
93 // Create a `TokenTree::Token` with alone spacing.
94 pub fn token_alone(kind: TokenKind, span: Span) -> TokenTree {
95 TokenTree::Token(Token::new(kind, span), Spacing::Alone)
98 // Create a `TokenTree::Token` with joint spacing.
99 pub fn token_joint(kind: TokenKind, span: Span) -> TokenTree {
100 TokenTree::Token(Token::new(kind, span), Spacing::Joint)
103 pub fn uninterpolate(self) -> TokenTree {
105 TokenTree::Token(token, spacing) => {
106 TokenTree::Token(token.uninterpolate().into_owned(), spacing)
113 impl<CTX> HashStable<CTX> for TokenStream
115 CTX: crate::HashStableContext,
117 fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
118 for sub_tt in self.trees() {
119 sub_tt.hash_stable(hcx, hasher);
124 pub trait CreateTokenStream: sync::Send + sync::Sync {
125 fn create_token_stream(&self) -> AttrAnnotatedTokenStream;
128 impl CreateTokenStream for AttrAnnotatedTokenStream {
129 fn create_token_stream(&self) -> AttrAnnotatedTokenStream {
134 /// A lazy version of [`TokenStream`], which defers creation
135 /// of an actual `TokenStream` until it is needed.
136 /// `Box` is here only to reduce the structure size.
138 pub struct LazyTokenStream(Lrc<Box<dyn CreateTokenStream>>);
140 impl LazyTokenStream {
141 pub fn new(inner: impl CreateTokenStream + 'static) -> LazyTokenStream {
142 LazyTokenStream(Lrc::new(Box::new(inner)))
145 pub fn create_token_stream(&self) -> AttrAnnotatedTokenStream {
146 self.0.create_token_stream()
150 impl fmt::Debug for LazyTokenStream {
151 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
152 write!(f, "LazyTokenStream({:?})", self.create_token_stream())
156 impl<S: Encoder> Encodable<S> for LazyTokenStream {
157 fn encode(&self, s: &mut S) {
158 // Used by AST json printing.
159 Encodable::encode(&self.create_token_stream(), s);
163 impl<D: Decoder> Decodable<D> for LazyTokenStream {
164 fn decode(_d: &mut D) -> Self {
165 panic!("Attempted to decode LazyTokenStream");
169 impl<CTX> HashStable<CTX> for LazyTokenStream {
170 fn hash_stable(&self, _hcx: &mut CTX, _hasher: &mut StableHasher) {
171 panic!("Attempted to compute stable hash for LazyTokenStream");
175 /// A `AttrAnnotatedTokenStream` is similar to a `TokenStream`, but with extra
176 /// information about the tokens for attribute targets. This is used
177 /// during expansion to perform early cfg-expansion, and to process attributes
178 /// during proc-macro invocations.
179 #[derive(Clone, Debug, Default, Encodable, Decodable)]
180 pub struct AttrAnnotatedTokenStream(pub Lrc<Vec<(AttrAnnotatedTokenTree, Spacing)>>);
182 /// Like `TokenTree`, but for `AttrAnnotatedTokenStream`
183 #[derive(Clone, Debug, Encodable, Decodable)]
184 pub enum AttrAnnotatedTokenTree {
186 Delimited(DelimSpan, Delimiter, AttrAnnotatedTokenStream),
187 /// Stores the attributes for an attribute target,
188 /// along with the tokens for that attribute target.
189 /// See `AttributesData` for more information
190 Attributes(AttributesData),
193 impl AttrAnnotatedTokenStream {
194 pub fn new(tokens: Vec<(AttrAnnotatedTokenTree, Spacing)>) -> AttrAnnotatedTokenStream {
195 AttrAnnotatedTokenStream(Lrc::new(tokens))
198 /// Converts this `AttrAnnotatedTokenStream` to a plain `TokenStream
199 /// During conversion, `AttrAnnotatedTokenTree::Attributes` get 'flattened'
200 /// back to a `TokenStream` of the form `outer_attr attr_target`.
201 /// If there are inner attributes, they are inserted into the proper
202 /// place in the attribute target tokens.
203 pub fn to_tokenstream(&self) -> TokenStream {
204 let trees: Vec<_> = self
207 .flat_map(|tree| match &tree.0 {
208 AttrAnnotatedTokenTree::Token(inner) => {
209 smallvec![TokenTree::Token(inner.clone(), tree.1)].into_iter()
211 AttrAnnotatedTokenTree::Delimited(span, delim, stream) => {
212 smallvec![TokenTree::Delimited(*span, *delim, stream.to_tokenstream()),]
215 AttrAnnotatedTokenTree::Attributes(data) => {
216 let mut outer_attrs = Vec::new();
217 let mut inner_attrs = Vec::new();
218 for attr in &data.attrs {
220 crate::AttrStyle::Outer => {
221 outer_attrs.push(attr);
223 crate::AttrStyle::Inner => {
224 inner_attrs.push(attr);
229 let mut target_tokens: Vec<_> = data
231 .create_token_stream()
237 if !inner_attrs.is_empty() {
238 let mut found = false;
239 // Check the last two trees (to account for a trailing semi)
240 for tree in target_tokens.iter_mut().rev().take(2) {
241 if let TokenTree::Delimited(span, delim, delim_tokens) = tree {
242 // Inner attributes are only supported on extern blocks, functions, impls,
243 // and modules. All of these have their inner attributes placed at
244 // the beginning of the rightmost outermost braced group:
245 // e.g. fn foo() { #![my_attr} }
247 // Therefore, we can insert them back into the right location
248 // without needing to do any extra position tracking.
250 // Note: Outline modules are an exception - they can
251 // have attributes like `#![my_attr]` at the start of a file.
252 // Support for custom attributes in this position is not
253 // properly implemented - we always synthesize fake tokens,
254 // so we never reach this code.
256 let mut builder = TokenStreamBuilder::new();
257 for inner_attr in inner_attrs {
258 builder.push(inner_attr.tokens().to_tokenstream());
260 builder.push(delim_tokens.clone());
261 *tree = TokenTree::Delimited(*span, *delim, builder.build());
269 "Failed to find trailing delimited group in: {:?}",
273 let mut flat: SmallVec<[_; 1]> = SmallVec::new();
274 for attr in outer_attrs {
275 // FIXME: Make this more efficient
276 flat.extend(attr.tokens().to_tokenstream().0.clone().iter().cloned());
278 flat.extend(target_tokens);
283 TokenStream::new(trees)
287 /// Stores the tokens for an attribute target, along
288 /// with its attributes.
290 /// This is constructed during parsing when we need to capture
293 /// For example, `#[cfg(FALSE)] struct Foo {}` would
294 /// have an `attrs` field containing the `#[cfg(FALSE)]` attr,
295 /// and a `tokens` field storing the (unparsed) tokens `struct Foo {}`
296 #[derive(Clone, Debug, Encodable, Decodable)]
297 pub struct AttributesData {
298 /// Attributes, both outer and inner.
299 /// These are stored in the original order that they were parsed in.
301 /// The underlying tokens for the attribute target that `attrs`
303 pub tokens: LazyTokenStream,
306 /// A `TokenStream` is an abstract sequence of tokens, organized into [`TokenTree`]s.
308 /// The goal is for procedural macros to work with `TokenStream`s and `TokenTree`s
309 /// instead of a representation of the abstract syntax tree.
310 /// Today's `TokenTree`s can still contain AST via `token::Interpolated` for
311 /// backwards compatibility.
312 #[derive(Clone, Debug, Default, Encodable, Decodable)]
313 pub struct TokenStream(pub(crate) Lrc<Vec<TokenTree>>);
315 // `TokenStream` is used a lot. Make sure it doesn't unintentionally get bigger.
316 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
317 rustc_data_structures::static_assert_size!(TokenStream, 8);
319 #[derive(Clone, Copy, Debug, PartialEq, Encodable, Decodable, HashStable_Generic)]
326 /// Given a `TokenStream` with a `Stream` of only two arguments, return a new `TokenStream`
327 /// separating the two arguments with a comma for diagnostic suggestions.
328 pub fn add_comma(&self) -> Option<(TokenStream, Span)> {
329 // Used to suggest if a user writes `foo!(a b);`
330 let mut suggestion = None;
331 let mut iter = self.0.iter().enumerate().peekable();
332 while let Some((pos, ts)) = iter.next() {
333 if let Some((_, next)) = iter.peek() {
334 let sp = match (&ts, &next) {
335 (_, TokenTree::Token(Token { kind: token::Comma, .. }, _)) => continue,
337 TokenTree::Token(token_left, Spacing::Alone),
338 TokenTree::Token(token_right, _),
339 ) if ((token_left.is_ident() && !token_left.is_reserved_ident())
340 || token_left.is_lit())
341 && ((token_right.is_ident() && !token_right.is_reserved_ident())
342 || token_right.is_lit()) =>
346 (TokenTree::Delimited(sp, ..), _) => sp.entire(),
349 let sp = sp.shrink_to_hi();
350 let comma = TokenTree::token_alone(token::Comma, sp);
351 suggestion = Some((pos, comma, sp));
354 if let Some((pos, comma, sp)) = suggestion {
355 let mut new_stream = Vec::with_capacity(self.0.len() + 1);
356 let parts = self.0.split_at(pos + 1);
357 new_stream.extend_from_slice(parts.0);
358 new_stream.push(comma);
359 new_stream.extend_from_slice(parts.1);
360 return Some((TokenStream::new(new_stream), sp));
366 impl From<(AttrAnnotatedTokenTree, Spacing)> for AttrAnnotatedTokenStream {
367 fn from((tree, spacing): (AttrAnnotatedTokenTree, Spacing)) -> AttrAnnotatedTokenStream {
368 AttrAnnotatedTokenStream::new(vec![(tree, spacing)])
372 impl iter::FromIterator<TokenTree> for TokenStream {
373 fn from_iter<I: IntoIterator<Item = TokenTree>>(iter: I) -> Self {
374 TokenStream::new(iter.into_iter().collect::<Vec<TokenTree>>())
378 impl Eq for TokenStream {}
380 impl PartialEq<TokenStream> for TokenStream {
381 fn eq(&self, other: &TokenStream) -> bool {
382 self.trees().eq(other.trees())
387 pub fn new(streams: Vec<TokenTree>) -> TokenStream {
388 TokenStream(Lrc::new(streams))
391 pub fn is_empty(&self) -> bool {
395 pub fn len(&self) -> usize {
399 pub fn trees(&self) -> CursorRef<'_> {
403 pub fn into_trees(self) -> Cursor {
407 /// Compares two `TokenStream`s, checking equality without regarding span information.
408 pub fn eq_unspanned(&self, other: &TokenStream) -> bool {
409 let mut t1 = self.trees();
410 let mut t2 = other.trees();
411 for (t1, t2) in iter::zip(&mut t1, &mut t2) {
412 if !t1.eq_unspanned(&t2) {
416 t1.next().is_none() && t2.next().is_none()
419 pub fn map_enumerated<F: FnMut(usize, &TokenTree) -> TokenTree>(self, mut f: F) -> TokenStream {
420 TokenStream(Lrc::new(self.0.iter().enumerate().map(|(i, tree)| f(i, tree)).collect()))
423 fn opt_from_ast(node: &(impl HasAttrs + HasTokens)) -> Option<TokenStream> {
424 let tokens = node.tokens()?;
425 let attrs = node.attrs();
426 let attr_annotated = if attrs.is_empty() {
427 tokens.create_token_stream()
429 let attr_data = AttributesData { attrs: attrs.to_vec().into(), tokens: tokens.clone() };
430 AttrAnnotatedTokenStream::new(vec![(
431 AttrAnnotatedTokenTree::Attributes(attr_data),
435 Some(attr_annotated.to_tokenstream())
438 // Create a token stream containing a single token with alone spacing.
439 pub fn token_alone(kind: TokenKind, span: Span) -> TokenStream {
440 TokenStream::new(vec![TokenTree::token_alone(kind, span)])
443 // Create a token stream containing a single token with joint spacing.
444 pub fn token_joint(kind: TokenKind, span: Span) -> TokenStream {
445 TokenStream::new(vec![TokenTree::token_joint(kind, span)])
448 // Create a token stream containing a single `Delimited`.
449 pub fn delimited(span: DelimSpan, delim: Delimiter, tts: TokenStream) -> TokenStream {
450 TokenStream::new(vec![TokenTree::Delimited(span, delim, tts)])
453 pub fn from_ast(node: &(impl HasAttrs + HasSpan + HasTokens + fmt::Debug)) -> TokenStream {
454 TokenStream::opt_from_ast(node)
455 .unwrap_or_else(|| panic!("missing tokens for node at {:?}: {:?}", node.span(), node))
458 pub fn from_nonterminal_ast(nt: &Nonterminal) -> TokenStream {
460 Nonterminal::NtIdent(ident, is_raw) => {
461 TokenStream::token_alone(token::Ident(ident.name, *is_raw), ident.span)
463 Nonterminal::NtLifetime(ident) => {
464 TokenStream::token_alone(token::Lifetime(ident.name), ident.span)
466 Nonterminal::NtItem(item) => TokenStream::from_ast(item),
467 Nonterminal::NtBlock(block) => TokenStream::from_ast(block),
468 Nonterminal::NtStmt(stmt) if let StmtKind::Empty = stmt.kind => {
469 // FIXME: Properly collect tokens for empty statements.
470 TokenStream::token_alone(token::Semi, stmt.span)
472 Nonterminal::NtStmt(stmt) => TokenStream::from_ast(stmt),
473 Nonterminal::NtPat(pat) => TokenStream::from_ast(pat),
474 Nonterminal::NtTy(ty) => TokenStream::from_ast(ty),
475 Nonterminal::NtMeta(attr) => TokenStream::from_ast(attr),
476 Nonterminal::NtPath(path) => TokenStream::from_ast(path),
477 Nonterminal::NtVis(vis) => TokenStream::from_ast(vis),
478 Nonterminal::NtExpr(expr) | Nonterminal::NtLiteral(expr) => TokenStream::from_ast(expr),
482 fn flatten_token(token: &Token, spacing: Spacing) -> TokenTree {
484 token::Interpolated(nt) if let token::NtIdent(ident, is_raw) = **nt => {
485 TokenTree::Token(Token::new(token::Ident(ident.name, is_raw), ident.span), spacing)
487 token::Interpolated(nt) => TokenTree::Delimited(
488 DelimSpan::from_single(token.span),
489 Delimiter::Invisible,
490 TokenStream::from_nonterminal_ast(&nt).flattened(),
492 _ => TokenTree::Token(token.clone(), spacing),
496 fn flatten_token_tree(tree: &TokenTree) -> TokenTree {
498 TokenTree::Token(token, spacing) => TokenStream::flatten_token(token, *spacing),
499 TokenTree::Delimited(span, delim, tts) => {
500 TokenTree::Delimited(*span, *delim, tts.flattened())
506 pub fn flattened(&self) -> TokenStream {
507 fn can_skip(stream: &TokenStream) -> bool {
508 stream.trees().all(|tree| match tree {
509 TokenTree::Token(token, _) => !matches!(token.kind, token::Interpolated(_)),
510 TokenTree::Delimited(_, _, inner) => can_skip(inner),
518 self.trees().map(|tree| TokenStream::flatten_token_tree(tree)).collect()
522 // 99.5%+ of the time we have 1 or 2 elements in this vector.
524 pub struct TokenStreamBuilder(SmallVec<[TokenStream; 2]>);
526 impl TokenStreamBuilder {
527 pub fn new() -> TokenStreamBuilder {
528 TokenStreamBuilder(SmallVec::new())
531 pub fn push(&mut self, stream: TokenStream) {
535 pub fn build(self) -> TokenStream {
536 let mut streams = self.0;
537 match streams.len() {
538 0 => TokenStream::default(),
539 1 => streams.pop().unwrap(),
541 // We will extend the first stream in `streams` with the
542 // elements from the subsequent streams. This requires using
543 // `make_mut()` on the first stream, and in practice this
544 // doesn't cause cloning 99.9% of the time.
546 // One very common use case is when `streams` has two elements,
547 // where the first stream has any number of elements within
548 // (often 1, but sometimes many more) and the second stream has
549 // a single element within.
551 // Determine how much the first stream will be extended.
552 // Needed to avoid quadratic blow up from on-the-fly
553 // reallocations (#57735).
554 let num_appends = streams.iter().skip(1).map(|ts| ts.len()).sum();
556 // Get the first stream, which will become the result stream.
557 // If it's `None`, create an empty stream.
558 let mut iter = streams.drain(..);
559 let mut res_stream_lrc = iter.next().unwrap().0;
561 // Append the subsequent elements to the result stream, after
562 // reserving space for them.
563 let res_vec_mut = Lrc::make_mut(&mut res_stream_lrc);
564 res_vec_mut.reserve(num_appends);
566 let stream_iter = stream.0.iter().cloned();
568 // If (a) `res_mut_vec` is not empty and the last tree
569 // within it is a token tree marked with `Joint`, and (b)
570 // `stream` is not empty and the first tree within it is a
571 // token tree, and (c) the two tokens can be glued
573 if let Some(TokenTree::Token(last_tok, Spacing::Joint)) = res_vec_mut.last()
574 && let Some(TokenTree::Token(tok, spacing)) = stream.0.first()
575 && let Some(glued_tok) = last_tok.glue(&tok)
577 // ...then overwrite the last token tree in
578 // `res_vec_mut` with the glued token, and skip the
579 // first token tree from `stream`.
580 *res_vec_mut.last_mut().unwrap() = TokenTree::Token(glued_tok, *spacing);
581 res_vec_mut.extend(stream_iter.skip(1));
583 // Append all of `stream`.
584 res_vec_mut.extend(stream_iter);
588 TokenStream(res_stream_lrc)
594 /// By-reference iterator over a [`TokenStream`].
596 pub struct CursorRef<'t> {
597 stream: &'t TokenStream,
601 impl<'t> CursorRef<'t> {
602 fn new(stream: &'t TokenStream) -> Self {
603 CursorRef { stream, index: 0 }
606 pub fn look_ahead(&self, n: usize) -> Option<&TokenTree> {
607 self.stream.0.get(self.index + n)
611 impl<'t> Iterator for CursorRef<'t> {
612 type Item = &'t TokenTree;
614 fn next(&mut self) -> Option<&'t TokenTree> {
615 self.stream.0.get(self.index).map(|tree| {
622 /// Owning by-value iterator over a [`TokenStream`].
623 // FIXME: Many uses of this can be replaced with by-reference iterator to avoid clones.
626 pub stream: TokenStream,
630 impl Iterator for Cursor {
631 type Item = TokenTree;
633 fn next(&mut self) -> Option<TokenTree> {
634 self.stream.0.get(self.index).map(|tree| {
642 fn new(stream: TokenStream) -> Self {
643 Cursor { stream, index: 0 }
647 pub fn next_ref(&mut self) -> Option<&TokenTree> {
648 self.stream.0.get(self.index).map(|tree| {
654 pub fn look_ahead(&self, n: usize) -> Option<&TokenTree> {
655 self.stream.0.get(self.index + n)
659 #[derive(Debug, Copy, Clone, PartialEq, Encodable, Decodable, HashStable_Generic)]
660 pub struct DelimSpan {
666 pub fn from_single(sp: Span) -> Self {
667 DelimSpan { open: sp, close: sp }
670 pub fn from_pair(open: Span, close: Span) -> Self {
671 DelimSpan { open, close }
674 pub fn dummy() -> Self {
675 Self::from_single(DUMMY_SP)
678 pub fn entire(self) -> Span {
679 self.open.with_hi(self.close.hi())