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)]
46 /// A delimited sequence of token trees.
47 Delimited(DelimSpan, Delimiter, TokenStream),
50 // Ensure all fields of `TokenTree` is `Send` and `Sync`.
51 #[cfg(parallel_compiler)]
55 DelimSpan: Send + Sync,
56 Delimiter: Send + Sync,
57 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 /// Retrieves the `TokenTree`'s span.
74 pub fn span(&self) -> Span {
76 TokenTree::Token(token) => token.span,
77 TokenTree::Delimited(sp, ..) => sp.entire(),
81 /// Modify the `TokenTree`'s span in-place.
82 pub fn set_span(&mut self, span: Span) {
84 TokenTree::Token(token) => token.span = span,
85 TokenTree::Delimited(dspan, ..) => *dspan = DelimSpan::from_single(span),
89 pub fn token(kind: TokenKind, span: Span) -> TokenTree {
90 TokenTree::Token(Token::new(kind, span))
93 pub fn uninterpolate(self) -> TokenTree {
95 TokenTree::Token(token) => TokenTree::Token(token.uninterpolate().into_owned()),
101 impl<CTX> HashStable<CTX> for TokenStream
103 CTX: crate::HashStableContext,
105 fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
106 for sub_tt in self.trees() {
107 sub_tt.hash_stable(hcx, hasher);
112 pub trait CreateTokenStream: sync::Send + sync::Sync {
113 fn create_token_stream(&self) -> AttrAnnotatedTokenStream;
116 impl CreateTokenStream for AttrAnnotatedTokenStream {
117 fn create_token_stream(&self) -> AttrAnnotatedTokenStream {
122 /// A lazy version of [`TokenStream`], which defers creation
123 /// of an actual `TokenStream` until it is needed.
124 /// `Box` is here only to reduce the structure size.
126 pub struct LazyTokenStream(Lrc<Box<dyn CreateTokenStream>>);
128 impl LazyTokenStream {
129 pub fn new(inner: impl CreateTokenStream + 'static) -> LazyTokenStream {
130 LazyTokenStream(Lrc::new(Box::new(inner)))
133 pub fn create_token_stream(&self) -> AttrAnnotatedTokenStream {
134 self.0.create_token_stream()
138 impl fmt::Debug for LazyTokenStream {
139 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
140 write!(f, "LazyTokenStream({:?})", self.create_token_stream())
144 impl<S: Encoder> Encodable<S> for LazyTokenStream {
145 fn encode(&self, s: &mut S) {
146 // Used by AST json printing.
147 Encodable::encode(&self.create_token_stream(), s);
151 impl<D: Decoder> Decodable<D> for LazyTokenStream {
152 fn decode(_d: &mut D) -> Self {
153 panic!("Attempted to decode LazyTokenStream");
157 impl<CTX> HashStable<CTX> for LazyTokenStream {
158 fn hash_stable(&self, _hcx: &mut CTX, _hasher: &mut StableHasher) {
159 panic!("Attempted to compute stable hash for LazyTokenStream");
163 /// A `AttrAnnotatedTokenStream` is similar to a `TokenStream`, but with extra
164 /// information about the tokens for attribute targets. This is used
165 /// during expansion to perform early cfg-expansion, and to process attributes
166 /// during proc-macro invocations.
167 #[derive(Clone, Debug, Default, Encodable, Decodable)]
168 pub struct AttrAnnotatedTokenStream(pub Lrc<Vec<(AttrAnnotatedTokenTree, Spacing)>>);
170 /// Like `TokenTree`, but for `AttrAnnotatedTokenStream`
171 #[derive(Clone, Debug, Encodable, Decodable)]
172 pub enum AttrAnnotatedTokenTree {
174 Delimited(DelimSpan, Delimiter, AttrAnnotatedTokenStream),
175 /// Stores the attributes for an attribute target,
176 /// along with the tokens for that attribute target.
177 /// See `AttributesData` for more information
178 Attributes(AttributesData),
181 impl AttrAnnotatedTokenStream {
182 pub fn new(tokens: Vec<(AttrAnnotatedTokenTree, Spacing)>) -> AttrAnnotatedTokenStream {
183 AttrAnnotatedTokenStream(Lrc::new(tokens))
186 /// Converts this `AttrAnnotatedTokenStream` to a plain `TokenStream
187 /// During conversion, `AttrAnnotatedTokenTree::Attributes` get 'flattened'
188 /// back to a `TokenStream` of the form `outer_attr attr_target`.
189 /// If there are inner attributes, they are inserted into the proper
190 /// place in the attribute target tokens.
191 pub fn to_tokenstream(&self) -> TokenStream {
192 let trees: Vec<_> = self
195 .flat_map(|tree| match &tree.0 {
196 AttrAnnotatedTokenTree::Token(inner) => {
197 smallvec![(TokenTree::Token(inner.clone()), tree.1)].into_iter()
199 AttrAnnotatedTokenTree::Delimited(span, delim, stream) => smallvec![(
200 TokenTree::Delimited(*span, *delim, stream.to_tokenstream()),
204 AttrAnnotatedTokenTree::Attributes(data) => {
205 let mut outer_attrs = Vec::new();
206 let mut inner_attrs = Vec::new();
207 for attr in &data.attrs {
209 crate::AttrStyle::Outer => {
210 outer_attrs.push(attr);
212 crate::AttrStyle::Inner => {
213 inner_attrs.push(attr);
218 let mut target_tokens: Vec<_> = data
220 .create_token_stream()
226 if !inner_attrs.is_empty() {
227 let mut found = false;
228 // Check the last two trees (to account for a trailing semi)
229 for (tree, _) in target_tokens.iter_mut().rev().take(2) {
230 if let TokenTree::Delimited(span, delim, delim_tokens) = tree {
231 // Inner attributes are only supported on extern blocks, functions, impls,
232 // and modules. All of these have their inner attributes placed at
233 // the beginning of the rightmost outermost braced group:
234 // e.g. fn foo() { #![my_attr} }
236 // Therefore, we can insert them back into the right location
237 // without needing to do any extra position tracking.
239 // Note: Outline modules are an exception - they can
240 // have attributes like `#![my_attr]` at the start of a file.
241 // Support for custom attributes in this position is not
242 // properly implemented - we always synthesize fake tokens,
243 // so we never reach this code.
245 let mut builder = TokenStreamBuilder::new();
246 for inner_attr in inner_attrs {
247 builder.push(inner_attr.tokens().to_tokenstream());
249 builder.push(delim_tokens.clone());
250 *tree = TokenTree::Delimited(*span, *delim, builder.build());
258 "Failed to find trailing delimited group in: {:?}",
262 let mut flat: SmallVec<[_; 1]> = SmallVec::new();
263 for attr in outer_attrs {
264 // FIXME: Make this more efficient
265 flat.extend(attr.tokens().to_tokenstream().0.clone().iter().cloned());
267 flat.extend(target_tokens);
272 TokenStream::new(trees)
276 /// Stores the tokens for an attribute target, along
277 /// with its attributes.
279 /// This is constructed during parsing when we need to capture
282 /// For example, `#[cfg(FALSE)] struct Foo {}` would
283 /// have an `attrs` field containing the `#[cfg(FALSE)]` attr,
284 /// and a `tokens` field storing the (unparsed) tokens `struct Foo {}`
285 #[derive(Clone, Debug, Encodable, Decodable)]
286 pub struct AttributesData {
287 /// Attributes, both outer and inner.
288 /// These are stored in the original order that they were parsed in.
290 /// The underlying tokens for the attribute target that `attrs`
292 pub tokens: LazyTokenStream,
295 /// A `TokenStream` is an abstract sequence of tokens, organized into [`TokenTree`]s.
297 /// The goal is for procedural macros to work with `TokenStream`s and `TokenTree`s
298 /// instead of a representation of the abstract syntax tree.
299 /// Today's `TokenTree`s can still contain AST via `token::Interpolated` for
300 /// backwards compatibility.
301 #[derive(Clone, Debug, Default, Encodable, Decodable)]
302 pub struct TokenStream(pub(crate) Lrc<Vec<TreeAndSpacing>>);
304 pub type TreeAndSpacing = (TokenTree, Spacing);
306 // `TokenStream` is used a lot. Make sure it doesn't unintentionally get bigger.
307 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
308 rustc_data_structures::static_assert_size!(TokenStream, 8);
310 #[derive(Clone, Copy, Debug, PartialEq, Encodable, Decodable)]
317 /// Given a `TokenStream` with a `Stream` of only two arguments, return a new `TokenStream`
318 /// separating the two arguments with a comma for diagnostic suggestions.
319 pub fn add_comma(&self) -> Option<(TokenStream, Span)> {
320 // Used to suggest if a user writes `foo!(a b);`
321 let mut suggestion = None;
322 let mut iter = self.0.iter().enumerate().peekable();
323 while let Some((pos, ts)) = iter.next() {
324 if let Some((_, next)) = iter.peek() {
325 let sp = match (&ts, &next) {
326 (_, (TokenTree::Token(Token { kind: token::Comma, .. }), _)) => continue,
328 (TokenTree::Token(token_left), Spacing::Alone),
329 (TokenTree::Token(token_right), _),
330 ) if ((token_left.is_ident() && !token_left.is_reserved_ident())
331 || token_left.is_lit())
332 && ((token_right.is_ident() && !token_right.is_reserved_ident())
333 || token_right.is_lit()) =>
337 ((TokenTree::Delimited(sp, ..), Spacing::Alone), _) => sp.entire(),
340 let sp = sp.shrink_to_hi();
341 let comma = (TokenTree::token(token::Comma, sp), Spacing::Alone);
342 suggestion = Some((pos, comma, sp));
345 if let Some((pos, comma, sp)) = suggestion {
346 let mut new_stream = Vec::with_capacity(self.0.len() + 1);
347 let parts = self.0.split_at(pos + 1);
348 new_stream.extend_from_slice(parts.0);
349 new_stream.push(comma);
350 new_stream.extend_from_slice(parts.1);
351 return Some((TokenStream::new(new_stream), sp));
357 impl From<(AttrAnnotatedTokenTree, Spacing)> for AttrAnnotatedTokenStream {
358 fn from((tree, spacing): (AttrAnnotatedTokenTree, Spacing)) -> AttrAnnotatedTokenStream {
359 AttrAnnotatedTokenStream::new(vec![(tree, spacing)])
363 impl From<TokenTree> for TokenStream {
364 fn from(tree: TokenTree) -> TokenStream {
365 TokenStream::new(vec![(tree, Spacing::Alone)])
369 impl From<TokenTree> for TreeAndSpacing {
370 fn from(tree: TokenTree) -> TreeAndSpacing {
371 (tree, Spacing::Alone)
375 impl iter::FromIterator<TokenTree> for TokenStream {
376 fn from_iter<I: IntoIterator<Item = TokenTree>>(iter: I) -> Self {
377 TokenStream::new(iter.into_iter().map(Into::into).collect::<Vec<TreeAndSpacing>>())
381 impl Eq for TokenStream {}
383 impl PartialEq<TokenStream> for TokenStream {
384 fn eq(&self, other: &TokenStream) -> bool {
385 self.trees().eq(other.trees())
390 pub fn new(streams: Vec<TreeAndSpacing>) -> TokenStream {
391 TokenStream(Lrc::new(streams))
394 pub fn is_empty(&self) -> bool {
398 pub fn len(&self) -> usize {
402 pub fn trees(&self) -> CursorRef<'_> {
406 pub fn into_trees(self) -> Cursor {
410 /// Compares two `TokenStream`s, checking equality without regarding span information.
411 pub fn eq_unspanned(&self, other: &TokenStream) -> bool {
412 let mut t1 = self.trees();
413 let mut t2 = other.trees();
414 for (t1, t2) in iter::zip(&mut t1, &mut t2) {
415 if !t1.eq_unspanned(&t2) {
419 t1.next().is_none() && t2.next().is_none()
422 pub fn map_enumerated<F: FnMut(usize, &TokenTree) -> TokenTree>(self, mut f: F) -> TokenStream {
423 TokenStream(Lrc::new(
427 .map(|(i, (tree, is_joint))| (f(i, tree), *is_joint))
432 fn opt_from_ast(node: &(impl HasAttrs + HasTokens)) -> Option<TokenStream> {
433 let tokens = node.tokens()?;
434 let attrs = node.attrs();
435 let attr_annotated = if attrs.is_empty() {
436 tokens.create_token_stream()
438 let attr_data = AttributesData { attrs: attrs.to_vec().into(), tokens: tokens.clone() };
439 AttrAnnotatedTokenStream::new(vec![(
440 AttrAnnotatedTokenTree::Attributes(attr_data),
444 Some(attr_annotated.to_tokenstream())
447 pub fn from_ast(node: &(impl HasAttrs + HasSpan + HasTokens + fmt::Debug)) -> TokenStream {
448 TokenStream::opt_from_ast(node)
449 .unwrap_or_else(|| panic!("missing tokens for node at {:?}: {:?}", node.span(), node))
452 pub fn from_nonterminal_ast(nt: &Nonterminal) -> TokenStream {
454 Nonterminal::NtIdent(ident, is_raw) => {
455 TokenTree::token(token::Ident(ident.name, *is_raw), ident.span).into()
457 Nonterminal::NtLifetime(ident) => {
458 TokenTree::token(token::Lifetime(ident.name), ident.span).into()
460 Nonterminal::NtItem(item) => TokenStream::from_ast(item),
461 Nonterminal::NtBlock(block) => TokenStream::from_ast(block),
462 Nonterminal::NtStmt(stmt) if let StmtKind::Empty = stmt.kind => {
463 // FIXME: Properly collect tokens for empty statements.
464 TokenTree::token(token::Semi, stmt.span).into()
466 Nonterminal::NtStmt(stmt) => TokenStream::from_ast(stmt),
467 Nonterminal::NtPat(pat) => TokenStream::from_ast(pat),
468 Nonterminal::NtTy(ty) => TokenStream::from_ast(ty),
469 Nonterminal::NtMeta(attr) => TokenStream::from_ast(attr),
470 Nonterminal::NtPath(path) => TokenStream::from_ast(path),
471 Nonterminal::NtVis(vis) => TokenStream::from_ast(vis),
472 Nonterminal::NtExpr(expr) | Nonterminal::NtLiteral(expr) => TokenStream::from_ast(expr),
476 fn flatten_token(token: &Token) -> TokenTree {
478 token::Interpolated(nt) if let token::NtIdent(ident, is_raw) = **nt => {
479 TokenTree::token(token::Ident(ident.name, is_raw), ident.span)
481 token::Interpolated(nt) => TokenTree::Delimited(
482 DelimSpan::from_single(token.span),
483 Delimiter::Invisible,
484 TokenStream::from_nonterminal_ast(&nt).flattened(),
486 _ => TokenTree::Token(token.clone()),
490 fn flatten_token_tree(tree: &TokenTree) -> TokenTree {
492 TokenTree::Token(token) => TokenStream::flatten_token(token),
493 TokenTree::Delimited(span, delim, tts) => {
494 TokenTree::Delimited(*span, *delim, tts.flattened())
500 pub fn flattened(&self) -> TokenStream {
501 fn can_skip(stream: &TokenStream) -> bool {
502 stream.trees().all(|tree| match tree {
503 TokenTree::Token(token) => !matches!(token.kind, token::Interpolated(_)),
504 TokenTree::Delimited(_, _, inner) => can_skip(inner),
512 self.trees().map(|tree| TokenStream::flatten_token_tree(tree)).collect()
516 // 99.5%+ of the time we have 1 or 2 elements in this vector.
518 pub struct TokenStreamBuilder(SmallVec<[TokenStream; 2]>);
520 impl TokenStreamBuilder {
521 pub fn new() -> TokenStreamBuilder {
522 TokenStreamBuilder(SmallVec::new())
525 pub fn push<T: Into<TokenStream>>(&mut self, stream: T) {
526 self.0.push(stream.into());
529 pub fn build(self) -> TokenStream {
530 let mut streams = self.0;
531 match streams.len() {
532 0 => TokenStream::default(),
533 1 => streams.pop().unwrap(),
535 // We will extend the first stream in `streams` with the
536 // elements from the subsequent streams. This requires using
537 // `make_mut()` on the first stream, and in practice this
538 // doesn't cause cloning 99.9% of the time.
540 // One very common use case is when `streams` has two elements,
541 // where the first stream has any number of elements within
542 // (often 1, but sometimes many more) and the second stream has
543 // a single element within.
545 // Determine how much the first stream will be extended.
546 // Needed to avoid quadratic blow up from on-the-fly
547 // reallocations (#57735).
548 let num_appends = streams.iter().skip(1).map(|ts| ts.len()).sum();
550 // Get the first stream, which will become the result stream.
551 // If it's `None`, create an empty stream.
552 let mut iter = streams.drain(..);
553 let mut res_stream_lrc = iter.next().unwrap().0;
555 // Append the subsequent elements to the result stream, after
556 // reserving space for them.
557 let res_vec_mut = Lrc::make_mut(&mut res_stream_lrc);
558 res_vec_mut.reserve(num_appends);
560 let stream_iter = stream.0.iter().cloned();
562 // If (a) `res_mut_vec` is not empty and the last tree
563 // within it is a token tree marked with `Joint`, and (b)
564 // `stream` is not empty and the first tree within it is a
565 // token tree, and (c) the two tokens can be glued
567 if let Some((TokenTree::Token(last_tok), Spacing::Joint)) = res_vec_mut.last()
568 && let Some((TokenTree::Token(tok), spacing)) = stream.0.first()
569 && let Some(glued_tok) = last_tok.glue(&tok)
571 // ...then overwrite the last token tree in
572 // `res_vec_mut` with the glued token, and skip the
573 // first token tree from `stream`.
574 *res_vec_mut.last_mut().unwrap() = (TokenTree::Token(glued_tok), *spacing);
575 res_vec_mut.extend(stream_iter.skip(1));
577 // Append all of `stream`.
578 res_vec_mut.extend(stream_iter);
582 TokenStream(res_stream_lrc)
588 /// By-reference iterator over a [`TokenStream`].
590 pub struct CursorRef<'t> {
591 stream: &'t TokenStream,
595 impl<'t> CursorRef<'t> {
596 fn new(stream: &'t TokenStream) -> Self {
597 CursorRef { stream, index: 0 }
601 fn next_with_spacing(&mut self) -> Option<&'t TreeAndSpacing> {
602 self.stream.0.get(self.index).map(|tree| {
608 pub fn look_ahead(&self, n: usize) -> Option<&TokenTree> {
609 self.stream.0[self.index..].get(n).map(|(tree, _)| tree)
613 impl<'t> Iterator for CursorRef<'t> {
614 type Item = &'t TokenTree;
616 fn next(&mut self) -> Option<&'t TokenTree> {
617 self.next_with_spacing().map(|(tree, _)| tree)
621 /// Owning by-value iterator over a [`TokenStream`].
622 // FIXME: Many uses of this can be replaced with by-reference iterator to avoid clones.
625 pub stream: TokenStream,
629 impl Iterator for Cursor {
630 type Item = TokenTree;
632 fn next(&mut self) -> Option<TokenTree> {
633 self.next_with_spacing().map(|(tree, _)| tree)
638 fn new(stream: TokenStream) -> Self {
639 Cursor { stream, index: 0 }
643 pub fn next_with_spacing(&mut self) -> Option<TreeAndSpacing> {
644 self.stream.0.get(self.index).map(|tree| {
651 pub fn next_with_spacing_ref(&mut self) -> Option<&TreeAndSpacing> {
652 self.stream.0.get(self.index).map(|tree| {
658 pub fn look_ahead(&self, n: usize) -> Option<&TokenTree> {
659 self.stream.0[self.index..].get(n).map(|(tree, _)| tree)
663 #[derive(Debug, Copy, Clone, PartialEq, Encodable, Decodable, HashStable_Generic)]
664 pub struct DelimSpan {
670 pub fn from_single(sp: Span) -> Self {
671 DelimSpan { open: sp, close: sp }
674 pub fn from_pair(open: Span, close: Span) -> Self {
675 DelimSpan { open, close }
678 pub fn dummy() -> Self {
679 Self::from_single(DUMMY_SP)
682 pub fn entire(self) -> Span {
683 self.open.with_hi(self.close.hi())