]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/tokenstream.rs
Auto merge of #67831 - mati865:ci-images-upgrade, r=pietroalbini
[rust.git] / src / libsyntax / tokenstream.rs
1 //! # Token Streams
2 //!
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.
6 //!
7 //! ## Ownership
8 //!
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.
15
16 use crate::token::{self, DelimToken, Token, TokenKind};
17
18 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
19 use rustc_data_structures::sync::Lrc;
20 use rustc_macros::HashStable_Generic;
21 use rustc_span::{Span, DUMMY_SP};
22 use smallvec::{smallvec, SmallVec};
23
24 use std::{iter, mem};
25
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.
30 ///
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.
35 ///
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, HashStable_Generic)]
39 pub enum TokenTree {
40     /// A single token
41     Token(Token),
42     /// A delimited sequence of token trees
43     Delimited(DelimSpan, DelimToken, TokenStream),
44 }
45
46 // Ensure all fields of `TokenTree` is `Send` and `Sync`.
47 #[cfg(parallel_compiler)]
48 fn _dummy()
49 where
50     Token: Send + Sync,
51     DelimSpan: Send + Sync,
52     DelimToken: Send + Sync,
53     TokenStream: Send + Sync,
54 {
55 }
56
57 impl TokenTree {
58     /// Checks if this TokenTree is equal to the other, regardless of span information.
59     pub fn eq_unspanned(&self, other: &TokenTree) -> bool {
60         match (self, other) {
61             (TokenTree::Token(token), TokenTree::Token(token2)) => token.kind == token2.kind,
62             (TokenTree::Delimited(_, delim, tts), TokenTree::Delimited(_, delim2, tts2)) => {
63                 delim == delim2 && tts.eq_unspanned(&tts2)
64             }
65             _ => false,
66         }
67     }
68
69     // See comments in `Nonterminal::to_tokenstream` for why we care about
70     // *probably* equal here rather than actual equality
71     //
72     // This is otherwise the same as `eq_unspanned`, only recursing with a
73     // different method.
74     pub fn probably_equal_for_proc_macro(&self, other: &TokenTree) -> bool {
75         match (self, other) {
76             (TokenTree::Token(token), TokenTree::Token(token2)) => {
77                 token.probably_equal_for_proc_macro(token2)
78             }
79             (TokenTree::Delimited(_, delim, tts), TokenTree::Delimited(_, delim2, tts2)) => {
80                 delim == delim2 && tts.probably_equal_for_proc_macro(&tts2)
81             }
82             _ => false,
83         }
84     }
85
86     /// Retrieves the TokenTree's span.
87     pub fn span(&self) -> Span {
88         match self {
89             TokenTree::Token(token) => token.span,
90             TokenTree::Delimited(sp, ..) => sp.entire(),
91         }
92     }
93
94     /// Modify the `TokenTree`'s span in-place.
95     pub fn set_span(&mut self, span: Span) {
96         match self {
97             TokenTree::Token(token) => token.span = span,
98             TokenTree::Delimited(dspan, ..) => *dspan = DelimSpan::from_single(span),
99         }
100     }
101
102     pub fn joint(self) -> TokenStream {
103         TokenStream::new(vec![(self, Joint)])
104     }
105
106     pub fn token(kind: TokenKind, span: Span) -> TokenTree {
107         TokenTree::Token(Token::new(kind, span))
108     }
109
110     /// Returns the opening delimiter as a token tree.
111     pub fn open_tt(span: DelimSpan, delim: DelimToken) -> TokenTree {
112         TokenTree::token(token::OpenDelim(delim), span.open)
113     }
114
115     /// Returns the closing delimiter as a token tree.
116     pub fn close_tt(span: DelimSpan, delim: DelimToken) -> TokenTree {
117         TokenTree::token(token::CloseDelim(delim), span.close)
118     }
119 }
120
121 impl<CTX> HashStable<CTX> for TokenStream
122 where
123     CTX: crate::HashStableContext,
124 {
125     fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
126         for sub_tt in self.trees() {
127             sub_tt.hash_stable(hcx, hasher);
128         }
129     }
130 }
131
132 /// A `TokenStream` is an abstract sequence of tokens, organized into `TokenTree`s.
133 ///
134 /// The goal is for procedural macros to work with `TokenStream`s and `TokenTree`s
135 /// instead of a representation of the abstract syntax tree.
136 /// Today's `TokenTree`s can still contain AST via `token::Interpolated` for back-compat.
137 #[derive(Clone, Debug, Default, RustcEncodable, RustcDecodable)]
138 pub struct TokenStream(pub Lrc<Vec<TreeAndJoint>>);
139
140 pub type TreeAndJoint = (TokenTree, IsJoint);
141
142 // `TokenStream` is used a lot. Make sure it doesn't unintentionally get bigger.
143 #[cfg(target_arch = "x86_64")]
144 rustc_data_structures::static_assert_size!(TokenStream, 8);
145
146 #[derive(Clone, Copy, Debug, PartialEq, RustcEncodable, RustcDecodable)]
147 pub enum IsJoint {
148     Joint,
149     NonJoint,
150 }
151
152 use IsJoint::*;
153
154 impl TokenStream {
155     /// Given a `TokenStream` with a `Stream` of only two arguments, return a new `TokenStream`
156     /// separating the two arguments with a comma for diagnostic suggestions.
157     pub fn add_comma(&self) -> Option<(TokenStream, Span)> {
158         // Used to suggest if a user writes `foo!(a b);`
159         let mut suggestion = None;
160         let mut iter = self.0.iter().enumerate().peekable();
161         while let Some((pos, ts)) = iter.next() {
162             if let Some((_, next)) = iter.peek() {
163                 let sp = match (&ts, &next) {
164                     (_, (TokenTree::Token(Token { kind: token::Comma, .. }), _)) => continue,
165                     (
166                         (TokenTree::Token(token_left), NonJoint),
167                         (TokenTree::Token(token_right), _),
168                     ) if ((token_left.is_ident() && !token_left.is_reserved_ident())
169                         || token_left.is_lit())
170                         && ((token_right.is_ident() && !token_right.is_reserved_ident())
171                             || token_right.is_lit()) =>
172                     {
173                         token_left.span
174                     }
175                     ((TokenTree::Delimited(sp, ..), NonJoint), _) => sp.entire(),
176                     _ => continue,
177                 };
178                 let sp = sp.shrink_to_hi();
179                 let comma = (TokenTree::token(token::Comma, sp), NonJoint);
180                 suggestion = Some((pos, comma, sp));
181             }
182         }
183         if let Some((pos, comma, sp)) = suggestion {
184             let mut new_stream = vec![];
185             let parts = self.0.split_at(pos + 1);
186             new_stream.extend_from_slice(parts.0);
187             new_stream.push(comma);
188             new_stream.extend_from_slice(parts.1);
189             return Some((TokenStream::new(new_stream), sp));
190         }
191         None
192     }
193 }
194
195 impl From<TokenTree> for TokenStream {
196     fn from(tree: TokenTree) -> TokenStream {
197         TokenStream::new(vec![(tree, NonJoint)])
198     }
199 }
200
201 impl From<TokenTree> for TreeAndJoint {
202     fn from(tree: TokenTree) -> TreeAndJoint {
203         (tree, NonJoint)
204     }
205 }
206
207 impl iter::FromIterator<TokenTree> for TokenStream {
208     fn from_iter<I: IntoIterator<Item = TokenTree>>(iter: I) -> Self {
209         TokenStream::new(iter.into_iter().map(Into::into).collect::<Vec<TreeAndJoint>>())
210     }
211 }
212
213 impl Eq for TokenStream {}
214
215 impl PartialEq<TokenStream> for TokenStream {
216     fn eq(&self, other: &TokenStream) -> bool {
217         self.trees().eq(other.trees())
218     }
219 }
220
221 impl TokenStream {
222     pub fn new(streams: Vec<TreeAndJoint>) -> TokenStream {
223         TokenStream(Lrc::new(streams))
224     }
225
226     pub fn is_empty(&self) -> bool {
227         self.0.is_empty()
228     }
229
230     pub fn len(&self) -> usize {
231         self.0.len()
232     }
233
234     pub fn span(&self) -> Option<Span> {
235         match &**self.0 {
236             [] => None,
237             [(tt, _)] => Some(tt.span()),
238             [(tt_start, _), .., (tt_end, _)] => Some(tt_start.span().to(tt_end.span())),
239         }
240     }
241
242     pub fn from_streams(mut streams: SmallVec<[TokenStream; 2]>) -> TokenStream {
243         match streams.len() {
244             0 => TokenStream::default(),
245             1 => streams.pop().unwrap(),
246             _ => {
247                 // We are going to extend the first stream in `streams` with
248                 // the elements from the subsequent streams. This requires
249                 // using `make_mut()` on the first stream, and in practice this
250                 // doesn't cause cloning 99.9% of the time.
251                 //
252                 // One very common use case is when `streams` has two elements,
253                 // where the first stream has any number of elements within
254                 // (often 1, but sometimes many more) and the second stream has
255                 // a single element within.
256
257                 // Determine how much the first stream will be extended.
258                 // Needed to avoid quadratic blow up from on-the-fly
259                 // reallocations (#57735).
260                 let num_appends = streams.iter().skip(1).map(|ts| ts.len()).sum();
261
262                 // Get the first stream. If it's `None`, create an empty
263                 // stream.
264                 let mut iter = streams.drain(..);
265                 let mut first_stream_lrc = iter.next().unwrap().0;
266
267                 // Append the elements to the first stream, after reserving
268                 // space for them.
269                 let first_vec_mut = Lrc::make_mut(&mut first_stream_lrc);
270                 first_vec_mut.reserve(num_appends);
271                 for stream in iter {
272                     first_vec_mut.extend(stream.0.iter().cloned());
273                 }
274
275                 // Create the final `TokenStream`.
276                 TokenStream(first_stream_lrc)
277             }
278         }
279     }
280
281     pub fn trees(&self) -> Cursor {
282         self.clone().into_trees()
283     }
284
285     pub fn into_trees(self) -> Cursor {
286         Cursor::new(self)
287     }
288
289     /// Compares two `TokenStream`s, checking equality without regarding span information.
290     pub fn eq_unspanned(&self, other: &TokenStream) -> bool {
291         let mut t1 = self.trees();
292         let mut t2 = other.trees();
293         for (t1, t2) in t1.by_ref().zip(t2.by_ref()) {
294             if !t1.eq_unspanned(&t2) {
295                 return false;
296             }
297         }
298         t1.next().is_none() && t2.next().is_none()
299     }
300
301     // See comments in `Nonterminal::to_tokenstream` for why we care about
302     // *probably* equal here rather than actual equality
303     //
304     // This is otherwise the same as `eq_unspanned`, only recursing with a
305     // different method.
306     pub fn probably_equal_for_proc_macro(&self, other: &TokenStream) -> bool {
307         // When checking for `probably_eq`, we ignore certain tokens that aren't
308         // preserved in the AST. Because they are not preserved, the pretty
309         // printer arbitrarily adds or removes them when printing as token
310         // streams, making a comparison between a token stream generated from an
311         // AST and a token stream which was parsed into an AST more reliable.
312         fn semantic_tree(tree: &TokenTree) -> bool {
313             if let TokenTree::Token(token) = tree {
314                 if let
315                     // The pretty printer tends to add trailing commas to
316                     // everything, and in particular, after struct fields.
317                     | token::Comma
318                     // The pretty printer emits `NoDelim` as whitespace.
319                     | token::OpenDelim(DelimToken::NoDelim)
320                     | token::CloseDelim(DelimToken::NoDelim)
321                     // The pretty printer collapses many semicolons into one.
322                     | token::Semi
323                     // The pretty printer collapses whitespace arbitrarily and can
324                     // introduce whitespace from `NoDelim`.
325                     | token::Whitespace
326                     // The pretty printer can turn `$crate` into `::crate_name`
327                     | token::ModSep = token.kind {
328                     return false;
329                 }
330             }
331             true
332         }
333
334         let mut t1 = self.trees().filter(semantic_tree);
335         let mut t2 = other.trees().filter(semantic_tree);
336         for (t1, t2) in t1.by_ref().zip(t2.by_ref()) {
337             if !t1.probably_equal_for_proc_macro(&t2) {
338                 return false;
339             }
340         }
341         t1.next().is_none() && t2.next().is_none()
342     }
343
344     pub fn map_enumerated<F: FnMut(usize, TokenTree) -> TokenTree>(self, mut f: F) -> TokenStream {
345         TokenStream(Lrc::new(
346             self.0
347                 .iter()
348                 .enumerate()
349                 .map(|(i, (tree, is_joint))| (f(i, tree.clone()), *is_joint))
350                 .collect(),
351         ))
352     }
353
354     pub fn map<F: FnMut(TokenTree) -> TokenTree>(self, mut f: F) -> TokenStream {
355         TokenStream(Lrc::new(
356             self.0.iter().map(|(tree, is_joint)| (f(tree.clone()), *is_joint)).collect(),
357         ))
358     }
359 }
360
361 // 99.5%+ of the time we have 1 or 2 elements in this vector.
362 #[derive(Clone)]
363 pub struct TokenStreamBuilder(SmallVec<[TokenStream; 2]>);
364
365 impl TokenStreamBuilder {
366     pub fn new() -> TokenStreamBuilder {
367         TokenStreamBuilder(SmallVec::new())
368     }
369
370     pub fn push<T: Into<TokenStream>>(&mut self, stream: T) {
371         let mut stream = stream.into();
372
373         // If `self` is not empty and the last tree within the last stream is a
374         // token tree marked with `Joint`...
375         if let Some(TokenStream(ref mut last_stream_lrc)) = self.0.last_mut() {
376             if let Some((TokenTree::Token(last_token), Joint)) = last_stream_lrc.last() {
377                 // ...and `stream` is not empty and the first tree within it is
378                 // a token tree...
379                 let TokenStream(ref mut stream_lrc) = stream;
380                 if let Some((TokenTree::Token(token), is_joint)) = stream_lrc.first() {
381                     // ...and the two tokens can be glued together...
382                     if let Some(glued_tok) = last_token.glue(&token) {
383                         // ...then do so, by overwriting the last token
384                         // tree in `self` and removing the first token tree
385                         // from `stream`. This requires using `make_mut()`
386                         // on the last stream in `self` and on `stream`,
387                         // and in practice this doesn't cause cloning 99.9%
388                         // of the time.
389
390                         // Overwrite the last token tree with the merged
391                         // token.
392                         let last_vec_mut = Lrc::make_mut(last_stream_lrc);
393                         *last_vec_mut.last_mut().unwrap() =
394                             (TokenTree::Token(glued_tok), *is_joint);
395
396                         // Remove the first token tree from `stream`. (This
397                         // is almost always the only tree in `stream`.)
398                         let stream_vec_mut = Lrc::make_mut(stream_lrc);
399                         stream_vec_mut.remove(0);
400
401                         // Don't push `stream` if it's empty -- that could
402                         // block subsequent token gluing, by getting
403                         // between two token trees that should be glued
404                         // together.
405                         if !stream.is_empty() {
406                             self.0.push(stream);
407                         }
408                         return;
409                     }
410                 }
411             }
412         }
413         self.0.push(stream);
414     }
415
416     pub fn build(self) -> TokenStream {
417         TokenStream::from_streams(self.0)
418     }
419 }
420
421 #[derive(Clone)]
422 pub struct Cursor {
423     pub stream: TokenStream,
424     index: usize,
425 }
426
427 impl Iterator for Cursor {
428     type Item = TokenTree;
429
430     fn next(&mut self) -> Option<TokenTree> {
431         self.next_with_joint().map(|(tree, _)| tree)
432     }
433 }
434
435 impl Cursor {
436     fn new(stream: TokenStream) -> Self {
437         Cursor { stream, index: 0 }
438     }
439
440     pub fn next_with_joint(&mut self) -> Option<TreeAndJoint> {
441         if self.index < self.stream.len() {
442             self.index += 1;
443             Some(self.stream.0[self.index - 1].clone())
444         } else {
445             None
446         }
447     }
448
449     pub fn append(&mut self, new_stream: TokenStream) {
450         if new_stream.is_empty() {
451             return;
452         }
453         let index = self.index;
454         let stream = mem::take(&mut self.stream);
455         *self = TokenStream::from_streams(smallvec![stream, new_stream]).into_trees();
456         self.index = index;
457     }
458
459     pub fn look_ahead(&self, n: usize) -> Option<TokenTree> {
460         self.stream.0[self.index..].get(n).map(|(tree, _)| tree.clone())
461     }
462 }
463
464 #[derive(Debug, Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable_Generic)]
465 pub struct DelimSpan {
466     pub open: Span,
467     pub close: Span,
468 }
469
470 impl DelimSpan {
471     pub fn from_single(sp: Span) -> Self {
472         DelimSpan { open: sp, close: sp }
473     }
474
475     pub fn from_pair(open: Span, close: Span) -> Self {
476         DelimSpan { open, close }
477     }
478
479     pub fn dummy() -> Self {
480         Self::from_single(DUMMY_SP)
481     }
482
483     pub fn entire(self) -> Span {
484         self.open.with_hi(self.close.hi())
485     }
486 }