]> git.lizzy.rs Git - rust.git/blob - src/librustc_ast/tokenstream.rs
Rollup merge of #72583 - CAD97:vec-iter-asref-slice, r=dtolnay
[rust.git] / src / librustc_ast / 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 log::debug;
25
26 use std::{iter, mem};
27
28 /// When the main rust parser encounters a syntax-extension invocation, it
29 /// parses the arguments to the invocation as a token-tree. This is a very
30 /// loose structure, such that all sorts of different AST-fragments can
31 /// be passed to syntax extensions using a uniform type.
32 ///
33 /// If the syntax extension is an MBE macro, it will attempt to match its
34 /// LHS token tree against the provided token tree, and if it finds a
35 /// match, will transcribe the RHS token tree, splicing in any captured
36 /// `macro_parser::matched_nonterminals` into the `SubstNt`s it finds.
37 ///
38 /// The RHS of an MBE macro is the only place `SubstNt`s are substituted.
39 /// Nothing special happens to misnamed or misplaced `SubstNt`s.
40 #[derive(Debug, Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable_Generic)]
41 pub enum TokenTree {
42     /// A single token
43     Token(Token),
44     /// A delimited sequence of token trees
45     Delimited(DelimSpan, DelimToken, TokenStream),
46 }
47
48 // Ensure all fields of `TokenTree` is `Send` and `Sync`.
49 #[cfg(parallel_compiler)]
50 fn _dummy()
51 where
52     Token: Send + Sync,
53     DelimSpan: Send + Sync,
54     DelimToken: Send + Sync,
55     TokenStream: Send + Sync,
56 {
57 }
58
59 impl TokenTree {
60     /// Checks if this TokenTree is equal to the other, regardless of span information.
61     pub fn eq_unspanned(&self, other: &TokenTree) -> bool {
62         match (self, other) {
63             (TokenTree::Token(token), TokenTree::Token(token2)) => token.kind == token2.kind,
64             (TokenTree::Delimited(_, delim, tts), TokenTree::Delimited(_, delim2, tts2)) => {
65                 delim == delim2 && tts.eq_unspanned(&tts2)
66             }
67             _ => false,
68         }
69     }
70
71     // See comments in `Nonterminal::to_tokenstream` for why we care about
72     // *probably* equal here rather than actual equality
73     //
74     // This is otherwise the same as `eq_unspanned`, only recursing with a
75     // different method.
76     pub fn probably_equal_for_proc_macro(&self, other: &TokenTree) -> bool {
77         match (self, other) {
78             (TokenTree::Token(token), TokenTree::Token(token2)) => {
79                 token.probably_equal_for_proc_macro(token2)
80             }
81             (TokenTree::Delimited(_, delim, tts), TokenTree::Delimited(_, delim2, tts2)) => {
82                 delim == delim2 && tts.probably_equal_for_proc_macro(&tts2)
83             }
84             _ => false,
85         }
86     }
87
88     /// Retrieves the TokenTree's span.
89     pub fn span(&self) -> Span {
90         match self {
91             TokenTree::Token(token) => token.span,
92             TokenTree::Delimited(sp, ..) => sp.entire(),
93         }
94     }
95
96     /// Modify the `TokenTree`'s span in-place.
97     pub fn set_span(&mut self, span: Span) {
98         match self {
99             TokenTree::Token(token) => token.span = span,
100             TokenTree::Delimited(dspan, ..) => *dspan = DelimSpan::from_single(span),
101         }
102     }
103
104     pub fn joint(self) -> TokenStream {
105         TokenStream::new(vec![(self, Joint)])
106     }
107
108     pub fn token(kind: TokenKind, span: Span) -> TokenTree {
109         TokenTree::Token(Token::new(kind, span))
110     }
111
112     /// Returns the opening delimiter as a token tree.
113     pub fn open_tt(span: DelimSpan, delim: DelimToken) -> TokenTree {
114         TokenTree::token(token::OpenDelim(delim), span.open)
115     }
116
117     /// Returns the closing delimiter as a token tree.
118     pub fn close_tt(span: DelimSpan, delim: DelimToken) -> TokenTree {
119         TokenTree::token(token::CloseDelim(delim), span.close)
120     }
121
122     pub fn uninterpolate(self) -> TokenTree {
123         match self {
124             TokenTree::Token(token) => TokenTree::Token(token.uninterpolate().into_owned()),
125             tt => tt,
126         }
127     }
128 }
129
130 impl<CTX> HashStable<CTX> for TokenStream
131 where
132     CTX: crate::HashStableContext,
133 {
134     fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
135         for sub_tt in self.trees() {
136             sub_tt.hash_stable(hcx, hasher);
137         }
138     }
139 }
140
141 /// A `TokenStream` is an abstract sequence of tokens, organized into `TokenTree`s.
142 ///
143 /// The goal is for procedural macros to work with `TokenStream`s and `TokenTree`s
144 /// instead of a representation of the abstract syntax tree.
145 /// Today's `TokenTree`s can still contain AST via `token::Interpolated` for back-compat.
146 #[derive(Clone, Debug, Default, RustcEncodable, RustcDecodable)]
147 pub struct TokenStream(pub Lrc<Vec<TreeAndJoint>>);
148
149 pub type TreeAndJoint = (TokenTree, IsJoint);
150
151 // `TokenStream` is used a lot. Make sure it doesn't unintentionally get bigger.
152 #[cfg(target_arch = "x86_64")]
153 rustc_data_structures::static_assert_size!(TokenStream, 8);
154
155 #[derive(Clone, Copy, Debug, PartialEq, RustcEncodable, RustcDecodable)]
156 pub enum IsJoint {
157     Joint,
158     NonJoint,
159 }
160
161 use IsJoint::*;
162
163 impl TokenStream {
164     /// Given a `TokenStream` with a `Stream` of only two arguments, return a new `TokenStream`
165     /// separating the two arguments with a comma for diagnostic suggestions.
166     pub fn add_comma(&self) -> Option<(TokenStream, Span)> {
167         // Used to suggest if a user writes `foo!(a b);`
168         let mut suggestion = None;
169         let mut iter = self.0.iter().enumerate().peekable();
170         while let Some((pos, ts)) = iter.next() {
171             if let Some((_, next)) = iter.peek() {
172                 let sp = match (&ts, &next) {
173                     (_, (TokenTree::Token(Token { kind: token::Comma, .. }), _)) => continue,
174                     (
175                         (TokenTree::Token(token_left), NonJoint),
176                         (TokenTree::Token(token_right), _),
177                     ) if ((token_left.is_ident() && !token_left.is_reserved_ident())
178                         || token_left.is_lit())
179                         && ((token_right.is_ident() && !token_right.is_reserved_ident())
180                             || token_right.is_lit()) =>
181                     {
182                         token_left.span
183                     }
184                     ((TokenTree::Delimited(sp, ..), NonJoint), _) => sp.entire(),
185                     _ => continue,
186                 };
187                 let sp = sp.shrink_to_hi();
188                 let comma = (TokenTree::token(token::Comma, sp), NonJoint);
189                 suggestion = Some((pos, comma, sp));
190             }
191         }
192         if let Some((pos, comma, sp)) = suggestion {
193             let mut new_stream = vec![];
194             let parts = self.0.split_at(pos + 1);
195             new_stream.extend_from_slice(parts.0);
196             new_stream.push(comma);
197             new_stream.extend_from_slice(parts.1);
198             return Some((TokenStream::new(new_stream), sp));
199         }
200         None
201     }
202 }
203
204 impl From<TokenTree> for TokenStream {
205     fn from(tree: TokenTree) -> TokenStream {
206         TokenStream::new(vec![(tree, NonJoint)])
207     }
208 }
209
210 impl From<TokenTree> for TreeAndJoint {
211     fn from(tree: TokenTree) -> TreeAndJoint {
212         (tree, NonJoint)
213     }
214 }
215
216 impl iter::FromIterator<TokenTree> for TokenStream {
217     fn from_iter<I: IntoIterator<Item = TokenTree>>(iter: I) -> Self {
218         TokenStream::new(iter.into_iter().map(Into::into).collect::<Vec<TreeAndJoint>>())
219     }
220 }
221
222 impl Eq for TokenStream {}
223
224 impl PartialEq<TokenStream> for TokenStream {
225     fn eq(&self, other: &TokenStream) -> bool {
226         self.trees().eq(other.trees())
227     }
228 }
229
230 impl TokenStream {
231     pub fn new(streams: Vec<TreeAndJoint>) -> TokenStream {
232         TokenStream(Lrc::new(streams))
233     }
234
235     pub fn is_empty(&self) -> bool {
236         self.0.is_empty()
237     }
238
239     pub fn len(&self) -> usize {
240         self.0.len()
241     }
242
243     pub fn span(&self) -> Option<Span> {
244         match &**self.0 {
245             [] => None,
246             [(tt, _)] => Some(tt.span()),
247             [(tt_start, _), .., (tt_end, _)] => Some(tt_start.span().to(tt_end.span())),
248         }
249     }
250
251     pub fn from_streams(mut streams: SmallVec<[TokenStream; 2]>) -> TokenStream {
252         match streams.len() {
253             0 => TokenStream::default(),
254             1 => streams.pop().unwrap(),
255             _ => {
256                 // We are going to extend the first stream in `streams` with
257                 // the elements from the subsequent streams. This requires
258                 // using `make_mut()` on the first stream, and in practice this
259                 // doesn't cause cloning 99.9% of the time.
260                 //
261                 // One very common use case is when `streams` has two elements,
262                 // where the first stream has any number of elements within
263                 // (often 1, but sometimes many more) and the second stream has
264                 // a single element within.
265
266                 // Determine how much the first stream will be extended.
267                 // Needed to avoid quadratic blow up from on-the-fly
268                 // reallocations (#57735).
269                 let num_appends = streams.iter().skip(1).map(|ts| ts.len()).sum();
270
271                 // Get the first stream. If it's `None`, create an empty
272                 // stream.
273                 let mut iter = streams.drain(..);
274                 let mut first_stream_lrc = iter.next().unwrap().0;
275
276                 // Append the elements to the first stream, after reserving
277                 // space for them.
278                 let first_vec_mut = Lrc::make_mut(&mut first_stream_lrc);
279                 first_vec_mut.reserve(num_appends);
280                 for stream in iter {
281                     first_vec_mut.extend(stream.0.iter().cloned());
282                 }
283
284                 // Create the final `TokenStream`.
285                 TokenStream(first_stream_lrc)
286             }
287         }
288     }
289
290     pub fn trees(&self) -> Cursor {
291         self.clone().into_trees()
292     }
293
294     pub fn into_trees(self) -> Cursor {
295         Cursor::new(self)
296     }
297
298     /// Compares two `TokenStream`s, checking equality without regarding span information.
299     pub fn eq_unspanned(&self, other: &TokenStream) -> bool {
300         let mut t1 = self.trees();
301         let mut t2 = other.trees();
302         for (t1, t2) in t1.by_ref().zip(t2.by_ref()) {
303             if !t1.eq_unspanned(&t2) {
304                 return false;
305             }
306         }
307         t1.next().is_none() && t2.next().is_none()
308     }
309
310     // See comments in `Nonterminal::to_tokenstream` for why we care about
311     // *probably* equal here rather than actual equality
312     //
313     // This is otherwise the same as `eq_unspanned`, only recursing with a
314     // different method.
315     pub fn probably_equal_for_proc_macro(&self, other: &TokenStream) -> bool {
316         // When checking for `probably_eq`, we ignore certain tokens that aren't
317         // preserved in the AST. Because they are not preserved, the pretty
318         // printer arbitrarily adds or removes them when printing as token
319         // streams, making a comparison between a token stream generated from an
320         // AST and a token stream which was parsed into an AST more reliable.
321         fn semantic_tree(tree: &TokenTree) -> bool {
322             if let TokenTree::Token(token) = tree {
323                 if let
324                     // The pretty printer tends to add trailing commas to
325                     // everything, and in particular, after struct fields.
326                     | token::Comma
327                     // The pretty printer emits `NoDelim` as whitespace.
328                     | token::OpenDelim(DelimToken::NoDelim)
329                     | token::CloseDelim(DelimToken::NoDelim)
330                     // The pretty printer collapses many semicolons into one.
331                     | token::Semi
332                     // The pretty printer collapses whitespace arbitrarily and can
333                     // introduce whitespace from `NoDelim`.
334                     | token::Whitespace
335                     // The pretty printer can turn `$crate` into `::crate_name`
336                     | token::ModSep = token.kind {
337                     return false;
338                 }
339             }
340             true
341         }
342
343         // When comparing two `TokenStream`s, we ignore the `IsJoint` information.
344         //
345         // However, `rustc_parse::lexer::tokentrees::TokenStreamBuilder` will
346         // use `Token.glue` on adjacent tokens with the proper `IsJoint`.
347         // Since we are ignoreing `IsJoint`, a 'glued' token (e.g. `BinOp(Shr)`)
348         // and its 'split'/'unglued' compoenents (e.g. `Gt, Gt`) are equivalent
349         // when determining if two `TokenStream`s are 'probably equal'.
350         //
351         // Therefore, we use `break_two_token_op` to convert all tokens
352         // to the 'unglued' form (if it exists). This ensures that two
353         // `TokenStream`s which differ only in how their tokens are glued
354         // will be considered 'probably equal', which allows us to keep spans.
355         //
356         // This is important when the original `TokenStream` contained
357         // extra spaces (e.g. `f :: < Vec < _ > > ( ) ;'). These extra spaces
358         // will be omitted when we pretty-print, which can cause the original
359         // and reparsed `TokenStream`s to differ in the assignment of `IsJoint`,
360         // leading to some tokens being 'glued' together in one stream but not
361         // the other. See #68489 for more details.
362         fn break_tokens(tree: TokenTree) -> impl Iterator<Item = TokenTree> {
363             // In almost all cases, we should have either zero or one levels
364             // of 'unglueing'. However, in some unusual cases, we may need
365             // to iterate breaking tokens mutliple times. For example:
366             // '[BinOpEq(Shr)] => [Gt, Ge] -> [Gt, Gt, Eq]'
367             let mut token_trees: SmallVec<[_; 2]>;
368             if let TokenTree::Token(token) = &tree {
369                 let mut out = SmallVec::<[_; 2]>::new();
370                 out.push(token.clone());
371                 // Iterate to fixpoint:
372                 // * We start off with 'out' containing our initial token, and `temp` empty
373                 // * If we are able to break any tokens in `out`, then `out` will have
374                 //   at least one more element than 'temp', so we will try to break tokens
375                 //   again.
376                 // * If we cannot break any tokens in 'out', we are done
377                 loop {
378                     let mut temp = SmallVec::<[_; 2]>::new();
379                     let mut changed = false;
380
381                     for token in out.into_iter() {
382                         if let Some((first, second)) = token.kind.break_two_token_op() {
383                             temp.push(Token::new(first, DUMMY_SP));
384                             temp.push(Token::new(second, DUMMY_SP));
385                             changed = true;
386                         } else {
387                             temp.push(token);
388                         }
389                     }
390                     out = temp;
391                     if !changed {
392                         break;
393                     }
394                 }
395                 token_trees = out.into_iter().map(|t| TokenTree::Token(t)).collect();
396                 if token_trees.len() != 1 {
397                     debug!("break_tokens: broke {:?} to {:?}", tree, token_trees);
398                 }
399             } else {
400                 token_trees = SmallVec::new();
401                 token_trees.push(tree);
402             }
403             token_trees.into_iter()
404         }
405
406         let mut t1 = self.trees().filter(semantic_tree).flat_map(break_tokens);
407         let mut t2 = other.trees().filter(semantic_tree).flat_map(break_tokens);
408         for (t1, t2) in t1.by_ref().zip(t2.by_ref()) {
409             if !t1.probably_equal_for_proc_macro(&t2) {
410                 return false;
411             }
412         }
413         t1.next().is_none() && t2.next().is_none()
414     }
415
416     pub fn map_enumerated<F: FnMut(usize, TokenTree) -> TokenTree>(self, mut f: F) -> TokenStream {
417         TokenStream(Lrc::new(
418             self.0
419                 .iter()
420                 .enumerate()
421                 .map(|(i, (tree, is_joint))| (f(i, tree.clone()), *is_joint))
422                 .collect(),
423         ))
424     }
425
426     pub fn map<F: FnMut(TokenTree) -> TokenTree>(self, mut f: F) -> TokenStream {
427         TokenStream(Lrc::new(
428             self.0.iter().map(|(tree, is_joint)| (f(tree.clone()), *is_joint)).collect(),
429         ))
430     }
431 }
432
433 // 99.5%+ of the time we have 1 or 2 elements in this vector.
434 #[derive(Clone)]
435 pub struct TokenStreamBuilder(SmallVec<[TokenStream; 2]>);
436
437 impl TokenStreamBuilder {
438     pub fn new() -> TokenStreamBuilder {
439         TokenStreamBuilder(SmallVec::new())
440     }
441
442     pub fn push<T: Into<TokenStream>>(&mut self, stream: T) {
443         let mut stream = stream.into();
444
445         // If `self` is not empty and the last tree within the last stream is a
446         // token tree marked with `Joint`...
447         if let Some(TokenStream(ref mut last_stream_lrc)) = self.0.last_mut() {
448             if let Some((TokenTree::Token(last_token), Joint)) = last_stream_lrc.last() {
449                 // ...and `stream` is not empty and the first tree within it is
450                 // a token tree...
451                 let TokenStream(ref mut stream_lrc) = stream;
452                 if let Some((TokenTree::Token(token), is_joint)) = stream_lrc.first() {
453                     // ...and the two tokens can be glued together...
454                     if let Some(glued_tok) = last_token.glue(&token) {
455                         // ...then do so, by overwriting the last token
456                         // tree in `self` and removing the first token tree
457                         // from `stream`. This requires using `make_mut()`
458                         // on the last stream in `self` and on `stream`,
459                         // and in practice this doesn't cause cloning 99.9%
460                         // of the time.
461
462                         // Overwrite the last token tree with the merged
463                         // token.
464                         let last_vec_mut = Lrc::make_mut(last_stream_lrc);
465                         *last_vec_mut.last_mut().unwrap() =
466                             (TokenTree::Token(glued_tok), *is_joint);
467
468                         // Remove the first token tree from `stream`. (This
469                         // is almost always the only tree in `stream`.)
470                         let stream_vec_mut = Lrc::make_mut(stream_lrc);
471                         stream_vec_mut.remove(0);
472
473                         // Don't push `stream` if it's empty -- that could
474                         // block subsequent token gluing, by getting
475                         // between two token trees that should be glued
476                         // together.
477                         if !stream.is_empty() {
478                             self.0.push(stream);
479                         }
480                         return;
481                     }
482                 }
483             }
484         }
485         self.0.push(stream);
486     }
487
488     pub fn build(self) -> TokenStream {
489         TokenStream::from_streams(self.0)
490     }
491 }
492
493 #[derive(Clone)]
494 pub struct Cursor {
495     pub stream: TokenStream,
496     index: usize,
497 }
498
499 impl Iterator for Cursor {
500     type Item = TokenTree;
501
502     fn next(&mut self) -> Option<TokenTree> {
503         self.next_with_joint().map(|(tree, _)| tree)
504     }
505 }
506
507 impl Cursor {
508     fn new(stream: TokenStream) -> Self {
509         Cursor { stream, index: 0 }
510     }
511
512     pub fn next_with_joint(&mut self) -> Option<TreeAndJoint> {
513         if self.index < self.stream.len() {
514             self.index += 1;
515             Some(self.stream.0[self.index - 1].clone())
516         } else {
517             None
518         }
519     }
520
521     pub fn append(&mut self, new_stream: TokenStream) {
522         if new_stream.is_empty() {
523             return;
524         }
525         let index = self.index;
526         let stream = mem::take(&mut self.stream);
527         *self = TokenStream::from_streams(smallvec![stream, new_stream]).into_trees();
528         self.index = index;
529     }
530
531     pub fn look_ahead(&self, n: usize) -> Option<TokenTree> {
532         self.stream.0[self.index..].get(n).map(|(tree, _)| tree.clone())
533     }
534 }
535
536 #[derive(Debug, Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable_Generic)]
537 pub struct DelimSpan {
538     pub open: Span,
539     pub close: Span,
540 }
541
542 impl DelimSpan {
543     pub fn from_single(sp: Span) -> Self {
544         DelimSpan { open: sp, close: sp }
545     }
546
547     pub fn from_pair(open: Span, close: Span) -> Self {
548         DelimSpan { open, close }
549     }
550
551     pub fn dummy() -> Self {
552         Self::from_single(DUMMY_SP)
553     }
554
555     pub fn entire(self) -> Span {
556         self.open.with_hi(self.close.hi())
557     }
558 }