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 use rustc_data_structures::sync::Lrc;
20 use smallvec::{SmallVec, smallvec};
24 /// When the main rust parser encounters a syntax-extension invocation, it
25 /// parses the arguments to the invocation as a token-tree. This is a very
26 /// loose structure, such that all sorts of different AST-fragments can
27 /// be passed to syntax extensions using a uniform type.
29 /// If the syntax extension is an MBE macro, it will attempt to match its
30 /// LHS token tree against the provided token tree, and if it finds a
31 /// match, will transcribe the RHS token tree, splicing in any captured
32 /// `macro_parser::matched_nonterminals` into the `SubstNt`s it finds.
34 /// The RHS of an MBE macro is the only place `SubstNt`s are substituted.
35 /// Nothing special happens to misnamed or misplaced `SubstNt`s.
36 #[derive(Debug, Clone, PartialEq, RustcEncodable, RustcDecodable)]
40 /// A delimited sequence of token trees
41 Delimited(DelimSpan, DelimToken, TokenStream),
44 // Ensure all fields of `TokenTree` is `Send` and `Sync`.
45 #[cfg(parallel_compiler)]
49 DelimSpan: Send + Sync,
50 DelimToken: Send + Sync,
51 TokenStream: Send + Sync,
55 /// Checks if this TokenTree is equal to the other, regardless of span information.
56 pub fn eq_unspanned(&self, other: &TokenTree) -> bool {
58 (TokenTree::Token(token), TokenTree::Token(token2)) => token.kind == token2.kind,
59 (TokenTree::Delimited(_, delim, tts), TokenTree::Delimited(_, delim2, tts2)) => {
60 delim == delim2 && tts.eq_unspanned(&tts2)
66 // See comments in `Nonterminal::to_tokenstream` for why we care about
67 // *probably* equal here rather than actual equality
69 // This is otherwise the same as `eq_unspanned`, only recursing with a
71 pub fn probably_equal_for_proc_macro(&self, other: &TokenTree) -> bool {
73 (TokenTree::Token(token), TokenTree::Token(token2)) => {
74 token.probably_equal_for_proc_macro(token2)
76 (TokenTree::Delimited(_, delim, tts), TokenTree::Delimited(_, delim2, tts2)) => {
77 delim == delim2 && tts.probably_equal_for_proc_macro(&tts2)
83 /// Retrieves the TokenTree's span.
84 pub fn span(&self) -> Span {
86 TokenTree::Token(token) => token.span,
87 TokenTree::Delimited(sp, ..) => sp.entire(),
91 /// Modify the `TokenTree`'s span in-place.
92 pub fn set_span(&mut self, span: Span) {
94 TokenTree::Token(token) => token.span = span,
95 TokenTree::Delimited(dspan, ..) => *dspan = DelimSpan::from_single(span),
99 pub fn joint(self) -> TokenStream {
100 TokenStream::new(vec![(self, Joint)])
103 pub fn token(kind: TokenKind, span: Span) -> TokenTree {
104 TokenTree::Token(Token::new(kind, span))
107 /// Returns the opening delimiter as a token tree.
108 pub fn open_tt(span: DelimSpan, delim: DelimToken) -> TokenTree {
109 TokenTree::token(token::OpenDelim(delim), span.open)
112 /// Returns the closing delimiter as a token tree.
113 pub fn close_tt(span: DelimSpan, delim: DelimToken) -> TokenTree {
114 TokenTree::token(token::CloseDelim(delim), span.close)
118 /// A `TokenStream` is an abstract sequence of tokens, organized into `TokenTree`s.
120 /// The goal is for procedural macros to work with `TokenStream`s and `TokenTree`s
121 /// instead of a representation of the abstract syntax tree.
122 /// Today's `TokenTree`s can still contain AST via `token::Interpolated` for back-compat.
123 #[derive(Clone, Debug, Default, RustcEncodable, RustcDecodable)]
124 pub struct TokenStream(pub Lrc<Vec<TreeAndJoint>>);
126 pub type TreeAndJoint = (TokenTree, IsJoint);
128 // `TokenStream` is used a lot. Make sure it doesn't unintentionally get bigger.
129 #[cfg(target_arch = "x86_64")]
130 rustc_data_structures::static_assert_size!(TokenStream, 8);
132 #[derive(Clone, Copy, Debug, PartialEq, RustcEncodable, RustcDecodable)]
141 /// Given a `TokenStream` with a `Stream` of only two arguments, return a new `TokenStream`
142 /// separating the two arguments with a comma for diagnostic suggestions.
143 pub fn add_comma(&self) -> Option<(TokenStream, Span)> {
144 // Used to suggest if a user writes `foo!(a b);`
145 let mut suggestion = None;
146 let mut iter = self.0.iter().enumerate().peekable();
147 while let Some((pos, ts)) = iter.next() {
148 if let Some((_, next)) = iter.peek() {
149 let sp = match (&ts, &next) {
150 (_, (TokenTree::Token(Token { kind: token::Comma, .. }), _)) => continue,
151 ((TokenTree::Token(token_left), NonJoint),
152 (TokenTree::Token(token_right), _))
153 if ((token_left.is_ident() && !token_left.is_reserved_ident())
154 || token_left.is_lit()) &&
155 ((token_right.is_ident() && !token_right.is_reserved_ident())
156 || token_right.is_lit()) => token_left.span,
157 ((TokenTree::Delimited(sp, ..), NonJoint), _) => sp.entire(),
160 let sp = sp.shrink_to_hi();
161 let comma = (TokenTree::token(token::Comma, sp), NonJoint);
162 suggestion = Some((pos, comma, sp));
165 if let Some((pos, comma, sp)) = suggestion {
166 let mut new_stream = vec![];
167 let parts = self.0.split_at(pos + 1);
168 new_stream.extend_from_slice(parts.0);
169 new_stream.push(comma);
170 new_stream.extend_from_slice(parts.1);
171 return Some((TokenStream::new(new_stream), sp));
177 impl From<TokenTree> for TokenStream {
178 fn from(tree: TokenTree) -> TokenStream {
179 TokenStream::new(vec![(tree, NonJoint)])
183 impl From<TokenTree> for TreeAndJoint {
184 fn from(tree: TokenTree) -> TreeAndJoint {
189 impl iter::FromIterator<TokenTree> for TokenStream {
190 fn from_iter<I: IntoIterator<Item = TokenTree>>(iter: I) -> Self {
191 TokenStream::new(iter.into_iter().map(Into::into).collect::<Vec<TreeAndJoint>>())
195 impl Eq for TokenStream {}
197 impl PartialEq<TokenStream> for TokenStream {
198 fn eq(&self, other: &TokenStream) -> bool {
199 self.trees().eq(other.trees())
204 pub fn new(streams: Vec<TreeAndJoint>) -> TokenStream {
205 TokenStream(Lrc::new(streams))
208 pub fn is_empty(&self) -> bool {
212 pub fn len(&self) -> usize {
216 pub fn from_streams(mut streams: SmallVec<[TokenStream; 2]>) -> TokenStream {
217 match streams.len() {
218 0 => TokenStream::default(),
219 1 => streams.pop().unwrap(),
221 // We are going to extend the first stream in `streams` with
222 // the elements from the subsequent streams. This requires
223 // using `make_mut()` on the first stream, and in practice this
224 // doesn't cause cloning 99.9% of the time.
226 // One very common use case is when `streams` has two elements,
227 // where the first stream has any number of elements within
228 // (often 1, but sometimes many more) and the second stream has
229 // a single element within.
231 // Determine how much the first stream will be extended.
232 // Needed to avoid quadratic blow up from on-the-fly
233 // reallocations (#57735).
234 let num_appends = streams.iter()
239 // Get the first stream. If it's `None`, create an empty
241 let mut iter = streams.drain(..);
242 let mut first_stream_lrc = iter.next().unwrap().0;
244 // Append the elements to the first stream, after reserving
246 let first_vec_mut = Lrc::make_mut(&mut first_stream_lrc);
247 first_vec_mut.reserve(num_appends);
249 first_vec_mut.extend(stream.0.iter().cloned());
252 // Create the final `TokenStream`.
253 TokenStream(first_stream_lrc)
258 pub fn trees(&self) -> Cursor {
259 self.clone().into_trees()
262 pub fn into_trees(self) -> Cursor {
266 /// Compares two `TokenStream`s, checking equality without regarding span information.
267 pub fn eq_unspanned(&self, other: &TokenStream) -> bool {
268 let mut t1 = self.trees();
269 let mut t2 = other.trees();
270 for (t1, t2) in t1.by_ref().zip(t2.by_ref()) {
271 if !t1.eq_unspanned(&t2) {
275 t1.next().is_none() && t2.next().is_none()
278 // See comments in `Nonterminal::to_tokenstream` for why we care about
279 // *probably* equal here rather than actual equality
281 // This is otherwise the same as `eq_unspanned`, only recursing with a
283 pub fn probably_equal_for_proc_macro(&self, other: &TokenStream) -> bool {
284 // When checking for `probably_eq`, we ignore certain tokens that aren't
285 // preserved in the AST. Because they are not preserved, the pretty
286 // printer arbitrarily adds or removes them when printing as token
287 // streams, making a comparison between a token stream generated from an
288 // AST and a token stream which was parsed into an AST more reliable.
289 fn semantic_tree(tree: &TokenTree) -> bool {
290 if let TokenTree::Token(token) = tree {
292 // The pretty printer tends to add trailing commas to
293 // everything, and in particular, after struct fields.
295 // The pretty printer emits `NoDelim` as whitespace.
296 | token::OpenDelim(DelimToken::NoDelim)
297 | token::CloseDelim(DelimToken::NoDelim)
298 // The pretty printer collapses many semicolons into one.
300 // The pretty printer collapses whitespace arbitrarily and can
301 // introduce whitespace from `NoDelim`.
303 // The pretty printer can turn `$crate` into `::crate_name`
304 | token::ModSep = token.kind {
311 let mut t1 = self.trees().filter(semantic_tree);
312 let mut t2 = other.trees().filter(semantic_tree);
313 for (t1, t2) in t1.by_ref().zip(t2.by_ref()) {
314 if !t1.probably_equal_for_proc_macro(&t2) {
318 t1.next().is_none() && t2.next().is_none()
321 pub fn map_enumerated<F: FnMut(usize, TokenTree) -> TokenTree>(self, mut f: F) -> TokenStream {
322 TokenStream(Lrc::new(
326 .map(|(i, (tree, is_joint))| (f(i, tree.clone()), *is_joint))
331 pub fn map<F: FnMut(TokenTree) -> TokenTree>(self, mut f: F) -> TokenStream {
332 TokenStream(Lrc::new(
335 .map(|(tree, is_joint)| (f(tree.clone()), *is_joint))
341 // 99.5%+ of the time we have 1 or 2 elements in this vector.
343 pub struct TokenStreamBuilder(SmallVec<[TokenStream; 2]>);
345 impl TokenStreamBuilder {
346 pub fn new() -> TokenStreamBuilder {
347 TokenStreamBuilder(SmallVec::new())
350 pub fn push<T: Into<TokenStream>>(&mut self, stream: T) {
351 let mut stream = stream.into();
353 // If `self` is not empty and the last tree within the last stream is a
354 // token tree marked with `Joint`...
355 if let Some(TokenStream(ref mut last_stream_lrc)) = self.0.last_mut() {
356 if let Some((TokenTree::Token(last_token), Joint)) = last_stream_lrc.last() {
358 // ...and `stream` is not empty and the first tree within it is
360 let TokenStream(ref mut stream_lrc) = stream;
361 if let Some((TokenTree::Token(token), is_joint)) = stream_lrc.first() {
363 // ...and the two tokens can be glued together...
364 if let Some(glued_tok) = last_token.glue(&token) {
366 // ...then do so, by overwriting the last token
367 // tree in `self` and removing the first token tree
368 // from `stream`. This requires using `make_mut()`
369 // on the last stream in `self` and on `stream`,
370 // and in practice this doesn't cause cloning 99.9%
373 // Overwrite the last token tree with the merged
375 let last_vec_mut = Lrc::make_mut(last_stream_lrc);
376 *last_vec_mut.last_mut().unwrap() =
377 (TokenTree::Token(glued_tok), *is_joint);
379 // Remove the first token tree from `stream`. (This
380 // is almost always the only tree in `stream`.)
381 let stream_vec_mut = Lrc::make_mut(stream_lrc);
382 stream_vec_mut.remove(0);
384 // Don't push `stream` if it's empty -- that could
385 // block subsequent token gluing, by getting
386 // between two token trees that should be glued
388 if !stream.is_empty() {
399 pub fn build(self) -> TokenStream {
400 TokenStream::from_streams(self.0)
406 pub stream: TokenStream,
410 impl Iterator for Cursor {
411 type Item = TokenTree;
413 fn next(&mut self) -> Option<TokenTree> {
414 self.next_with_joint().map(|(tree, _)| tree)
419 fn new(stream: TokenStream) -> Self {
420 Cursor { stream, index: 0 }
423 pub fn next_with_joint(&mut self) -> Option<TreeAndJoint> {
424 if self.index < self.stream.len() {
426 Some(self.stream.0[self.index - 1].clone())
432 pub fn append(&mut self, new_stream: TokenStream) {
433 if new_stream.is_empty() {
436 let index = self.index;
437 let stream = mem::take(&mut self.stream);
438 *self = TokenStream::from_streams(smallvec![stream, new_stream]).into_trees();
442 pub fn look_ahead(&self, n: usize) -> Option<TokenTree> {
443 self.stream.0[self.index ..].get(n).map(|(tree, _)| tree.clone())
447 #[derive(Debug, Copy, Clone, PartialEq, RustcEncodable, RustcDecodable)]
448 pub struct DelimSpan {
454 pub fn from_single(sp: Span) -> Self {
461 pub fn from_pair(open: Span, close: Span) -> Self {
462 DelimSpan { open, close }
465 pub fn dummy() -> Self {
466 Self::from_single(DUMMY_SP)
469 pub fn entire(self) -> Span {
470 self.open.with_hi(self.close.hi())