]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_ast/src/tokenstream.rs
Auto merge of #80790 - JohnTitor:rollup-js1noez, r=JohnTitor
[rust.git] / compiler / rustc_ast / src / 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 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::{self, Lrc};
20 use rustc_macros::HashStable_Generic;
21 use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
22 use rustc_span::{Span, DUMMY_SP};
23 use smallvec::{smallvec, SmallVec};
24
25 use std::{fmt, iter, mem};
26
27 /// When the main Rust parser encounters a syntax-extension invocation, it
28 /// parses the arguments to the invocation as a token tree. This is a very
29 /// loose structure, such that all sorts of different AST fragments can
30 /// be passed to syntax extensions using a uniform type.
31 ///
32 /// If the syntax extension is an MBE macro, it will attempt to match its
33 /// LHS token tree against the provided token tree, and if it finds a
34 /// match, will transcribe the RHS token tree, splicing in any captured
35 /// `macro_parser::matched_nonterminals` into the `SubstNt`s it finds.
36 ///
37 /// The RHS of an MBE macro is the only place `SubstNt`s are substituted.
38 /// Nothing special happens to misnamed or misplaced `SubstNt`s.
39 #[derive(Debug, Clone, PartialEq, Encodable, Decodable, HashStable_Generic)]
40 pub enum TokenTree {
41     /// A single token.
42     Token(Token),
43     /// A delimited sequence of token trees.
44     Delimited(DelimSpan, DelimToken, TokenStream),
45 }
46
47 #[derive(Copy, Clone)]
48 pub enum CanSynthesizeMissingTokens {
49     Yes,
50     No,
51 }
52
53 // Ensure all fields of `TokenTree` is `Send` and `Sync`.
54 #[cfg(parallel_compiler)]
55 fn _dummy()
56 where
57     Token: Send + Sync,
58     DelimSpan: Send + Sync,
59     DelimToken: Send + Sync,
60     TokenStream: Send + Sync,
61 {
62 }
63
64 impl TokenTree {
65     /// Checks if this `TokenTree` is equal to the other, regardless of span information.
66     pub fn eq_unspanned(&self, other: &TokenTree) -> bool {
67         match (self, other) {
68             (TokenTree::Token(token), TokenTree::Token(token2)) => token.kind == token2.kind,
69             (TokenTree::Delimited(_, delim, tts), TokenTree::Delimited(_, delim2, tts2)) => {
70                 delim == delim2 && tts.eq_unspanned(&tts2)
71             }
72             _ => false,
73         }
74     }
75
76     /// Retrieves the `TokenTree`'s span.
77     pub fn span(&self) -> Span {
78         match self {
79             TokenTree::Token(token) => token.span,
80             TokenTree::Delimited(sp, ..) => sp.entire(),
81         }
82     }
83
84     /// Modify the `TokenTree`'s span in-place.
85     pub fn set_span(&mut self, span: Span) {
86         match self {
87             TokenTree::Token(token) => token.span = span,
88             TokenTree::Delimited(dspan, ..) => *dspan = DelimSpan::from_single(span),
89         }
90     }
91
92     pub fn joint(self) -> TokenStream {
93         TokenStream::new(vec![(self, Spacing::Joint)])
94     }
95
96     pub fn token(kind: TokenKind, span: Span) -> TokenTree {
97         TokenTree::Token(Token::new(kind, span))
98     }
99
100     /// Returns the opening delimiter as a token tree.
101     pub fn open_tt(span: DelimSpan, delim: DelimToken) -> TokenTree {
102         TokenTree::token(token::OpenDelim(delim), span.open)
103     }
104
105     /// Returns the closing delimiter as a token tree.
106     pub fn close_tt(span: DelimSpan, delim: DelimToken) -> TokenTree {
107         TokenTree::token(token::CloseDelim(delim), span.close)
108     }
109
110     pub fn uninterpolate(self) -> TokenTree {
111         match self {
112             TokenTree::Token(token) => TokenTree::Token(token.uninterpolate().into_owned()),
113             tt => tt,
114         }
115     }
116 }
117
118 impl<CTX> HashStable<CTX> for TokenStream
119 where
120     CTX: crate::HashStableContext,
121 {
122     fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
123         for sub_tt in self.trees() {
124             sub_tt.hash_stable(hcx, hasher);
125         }
126     }
127 }
128
129 pub trait CreateTokenStream: sync::Send + sync::Sync {
130     fn add_trailing_semi(&self) -> Box<dyn CreateTokenStream>;
131     fn create_token_stream(&self) -> TokenStream;
132 }
133
134 impl CreateTokenStream for TokenStream {
135     fn add_trailing_semi(&self) -> Box<dyn CreateTokenStream> {
136         panic!("Cannot call `add_trailing_semi` on a `TokenStream`!");
137     }
138     fn create_token_stream(&self) -> TokenStream {
139         self.clone()
140     }
141 }
142
143 /// A lazy version of [`TokenStream`], which defers creation
144 /// of an actual `TokenStream` until it is needed.
145 /// `Box` is here only to reduce the structure size.
146 #[derive(Clone)]
147 pub struct LazyTokenStream(Lrc<Box<dyn CreateTokenStream>>);
148
149 impl LazyTokenStream {
150     pub fn new(inner: impl CreateTokenStream + 'static) -> LazyTokenStream {
151         LazyTokenStream(Lrc::new(Box::new(inner)))
152     }
153
154     /// Extends the captured stream by one token,
155     /// which must be a trailing semicolon. This
156     /// affects the `TokenStream` created by `make_tokenstream`.
157     pub fn add_trailing_semi(&self) -> LazyTokenStream {
158         LazyTokenStream(Lrc::new(self.0.add_trailing_semi()))
159     }
160
161     pub fn create_token_stream(&self) -> TokenStream {
162         self.0.create_token_stream()
163     }
164 }
165
166 impl fmt::Debug for LazyTokenStream {
167     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
168         fmt::Debug::fmt("LazyTokenStream", f)
169     }
170 }
171
172 impl<S: Encoder> Encodable<S> for LazyTokenStream {
173     fn encode(&self, s: &mut S) -> Result<(), S::Error> {
174         // Used by AST json printing.
175         Encodable::encode(&self.create_token_stream(), s)
176     }
177 }
178
179 impl<D: Decoder> Decodable<D> for LazyTokenStream {
180     fn decode(_d: &mut D) -> Result<Self, D::Error> {
181         panic!("Attempted to decode LazyTokenStream");
182     }
183 }
184
185 impl<CTX> HashStable<CTX> for LazyTokenStream {
186     fn hash_stable(&self, _hcx: &mut CTX, _hasher: &mut StableHasher) {
187         panic!("Attempted to compute stable hash for LazyTokenStream");
188     }
189 }
190
191 /// A `TokenStream` is an abstract sequence of tokens, organized into [`TokenTree`]s.
192 ///
193 /// The goal is for procedural macros to work with `TokenStream`s and `TokenTree`s
194 /// instead of a representation of the abstract syntax tree.
195 /// Today's `TokenTree`s can still contain AST via `token::Interpolated` for
196 /// backwards compatability.
197 #[derive(Clone, Debug, Default, Encodable, Decodable)]
198 pub struct TokenStream(pub(crate) Lrc<Vec<TreeAndSpacing>>);
199
200 pub type TreeAndSpacing = (TokenTree, Spacing);
201
202 // `TokenStream` is used a lot. Make sure it doesn't unintentionally get bigger.
203 #[cfg(target_arch = "x86_64")]
204 rustc_data_structures::static_assert_size!(TokenStream, 8);
205
206 #[derive(Clone, Copy, Debug, PartialEq, Encodable, Decodable)]
207 pub enum Spacing {
208     Alone,
209     Joint,
210 }
211
212 impl TokenStream {
213     /// Given a `TokenStream` with a `Stream` of only two arguments, return a new `TokenStream`
214     /// separating the two arguments with a comma for diagnostic suggestions.
215     pub fn add_comma(&self) -> Option<(TokenStream, Span)> {
216         // Used to suggest if a user writes `foo!(a b);`
217         let mut suggestion = None;
218         let mut iter = self.0.iter().enumerate().peekable();
219         while let Some((pos, ts)) = iter.next() {
220             if let Some((_, next)) = iter.peek() {
221                 let sp = match (&ts, &next) {
222                     (_, (TokenTree::Token(Token { kind: token::Comma, .. }), _)) => continue,
223                     (
224                         (TokenTree::Token(token_left), Spacing::Alone),
225                         (TokenTree::Token(token_right), _),
226                     ) if ((token_left.is_ident() && !token_left.is_reserved_ident())
227                         || token_left.is_lit())
228                         && ((token_right.is_ident() && !token_right.is_reserved_ident())
229                             || token_right.is_lit()) =>
230                     {
231                         token_left.span
232                     }
233                     ((TokenTree::Delimited(sp, ..), Spacing::Alone), _) => sp.entire(),
234                     _ => continue,
235                 };
236                 let sp = sp.shrink_to_hi();
237                 let comma = (TokenTree::token(token::Comma, sp), Spacing::Alone);
238                 suggestion = Some((pos, comma, sp));
239             }
240         }
241         if let Some((pos, comma, sp)) = suggestion {
242             let mut new_stream = Vec::with_capacity(self.0.len() + 1);
243             let parts = self.0.split_at(pos + 1);
244             new_stream.extend_from_slice(parts.0);
245             new_stream.push(comma);
246             new_stream.extend_from_slice(parts.1);
247             return Some((TokenStream::new(new_stream), sp));
248         }
249         None
250     }
251 }
252
253 impl From<TokenTree> for TokenStream {
254     fn from(tree: TokenTree) -> TokenStream {
255         TokenStream::new(vec![(tree, Spacing::Alone)])
256     }
257 }
258
259 impl From<TokenTree> for TreeAndSpacing {
260     fn from(tree: TokenTree) -> TreeAndSpacing {
261         (tree, Spacing::Alone)
262     }
263 }
264
265 impl iter::FromIterator<TokenTree> for TokenStream {
266     fn from_iter<I: IntoIterator<Item = TokenTree>>(iter: I) -> Self {
267         TokenStream::new(iter.into_iter().map(Into::into).collect::<Vec<TreeAndSpacing>>())
268     }
269 }
270
271 impl Eq for TokenStream {}
272
273 impl PartialEq<TokenStream> for TokenStream {
274     fn eq(&self, other: &TokenStream) -> bool {
275         self.trees().eq(other.trees())
276     }
277 }
278
279 impl TokenStream {
280     pub fn new(streams: Vec<TreeAndSpacing>) -> TokenStream {
281         TokenStream(Lrc::new(streams))
282     }
283
284     pub fn is_empty(&self) -> bool {
285         self.0.is_empty()
286     }
287
288     pub fn len(&self) -> usize {
289         self.0.len()
290     }
291
292     pub fn span(&self) -> Option<Span> {
293         match &**self.0 {
294             [] => None,
295             [(tt, _)] => Some(tt.span()),
296             [(tt_start, _), .., (tt_end, _)] => Some(tt_start.span().to(tt_end.span())),
297         }
298     }
299
300     pub fn from_streams(mut streams: SmallVec<[TokenStream; 2]>) -> TokenStream {
301         match streams.len() {
302             0 => TokenStream::default(),
303             1 => streams.pop().unwrap(),
304             _ => {
305                 // We are going to extend the first stream in `streams` with
306                 // the elements from the subsequent streams. This requires
307                 // using `make_mut()` on the first stream, and in practice this
308                 // doesn't cause cloning 99.9% of the time.
309                 //
310                 // One very common use case is when `streams` has two elements,
311                 // where the first stream has any number of elements within
312                 // (often 1, but sometimes many more) and the second stream has
313                 // a single element within.
314
315                 // Determine how much the first stream will be extended.
316                 // Needed to avoid quadratic blow up from on-the-fly
317                 // reallocations (#57735).
318                 let num_appends = streams.iter().skip(1).map(|ts| ts.len()).sum();
319
320                 // Get the first stream. If it's `None`, create an empty
321                 // stream.
322                 let mut iter = streams.drain(..);
323                 let mut first_stream_lrc = iter.next().unwrap().0;
324
325                 // Append the elements to the first stream, after reserving
326                 // space for them.
327                 let first_vec_mut = Lrc::make_mut(&mut first_stream_lrc);
328                 first_vec_mut.reserve(num_appends);
329                 for stream in iter {
330                     first_vec_mut.extend(stream.0.iter().cloned());
331                 }
332
333                 // Create the final `TokenStream`.
334                 TokenStream(first_stream_lrc)
335             }
336         }
337     }
338
339     pub fn trees_ref(&self) -> CursorRef<'_> {
340         CursorRef::new(self)
341     }
342
343     pub fn trees(&self) -> Cursor {
344         self.clone().into_trees()
345     }
346
347     pub fn into_trees(self) -> Cursor {
348         Cursor::new(self)
349     }
350
351     /// Compares two `TokenStream`s, checking equality without regarding span information.
352     pub fn eq_unspanned(&self, other: &TokenStream) -> bool {
353         let mut t1 = self.trees();
354         let mut t2 = other.trees();
355         for (t1, t2) in t1.by_ref().zip(t2.by_ref()) {
356             if !t1.eq_unspanned(&t2) {
357                 return false;
358             }
359         }
360         t1.next().is_none() && t2.next().is_none()
361     }
362
363     pub fn map_enumerated<F: FnMut(usize, &TokenTree) -> TokenTree>(self, mut f: F) -> TokenStream {
364         TokenStream(Lrc::new(
365             self.0
366                 .iter()
367                 .enumerate()
368                 .map(|(i, (tree, is_joint))| (f(i, tree), *is_joint))
369                 .collect(),
370         ))
371     }
372 }
373
374 // 99.5%+ of the time we have 1 or 2 elements in this vector.
375 #[derive(Clone)]
376 pub struct TokenStreamBuilder(SmallVec<[TokenStream; 2]>);
377
378 impl TokenStreamBuilder {
379     pub fn new() -> TokenStreamBuilder {
380         TokenStreamBuilder(SmallVec::new())
381     }
382
383     pub fn push<T: Into<TokenStream>>(&mut self, stream: T) {
384         let mut stream = stream.into();
385
386         // If `self` is not empty and the last tree within the last stream is a
387         // token tree marked with `Joint`...
388         if let Some(TokenStream(ref mut last_stream_lrc)) = self.0.last_mut() {
389             if let Some((TokenTree::Token(last_token), Spacing::Joint)) = last_stream_lrc.last() {
390                 // ...and `stream` is not empty and the first tree within it is
391                 // a token tree...
392                 let TokenStream(ref mut stream_lrc) = stream;
393                 if let Some((TokenTree::Token(token), spacing)) = stream_lrc.first() {
394                     // ...and the two tokens can be glued together...
395                     if let Some(glued_tok) = last_token.glue(&token) {
396                         // ...then do so, by overwriting the last token
397                         // tree in `self` and removing the first token tree
398                         // from `stream`. This requires using `make_mut()`
399                         // on the last stream in `self` and on `stream`,
400                         // and in practice this doesn't cause cloning 99.9%
401                         // of the time.
402
403                         // Overwrite the last token tree with the merged
404                         // token.
405                         let last_vec_mut = Lrc::make_mut(last_stream_lrc);
406                         *last_vec_mut.last_mut().unwrap() = (TokenTree::Token(glued_tok), *spacing);
407
408                         // Remove the first token tree from `stream`. (This
409                         // is almost always the only tree in `stream`.)
410                         let stream_vec_mut = Lrc::make_mut(stream_lrc);
411                         stream_vec_mut.remove(0);
412
413                         // Don't push `stream` if it's empty -- that could
414                         // block subsequent token gluing, by getting
415                         // between two token trees that should be glued
416                         // together.
417                         if !stream.is_empty() {
418                             self.0.push(stream);
419                         }
420                         return;
421                     }
422                 }
423             }
424         }
425         self.0.push(stream);
426     }
427
428     pub fn build(self) -> TokenStream {
429         TokenStream::from_streams(self.0)
430     }
431 }
432
433 /// By-reference iterator over a [`TokenStream`].
434 #[derive(Clone)]
435 pub struct CursorRef<'t> {
436     stream: &'t TokenStream,
437     index: usize,
438 }
439
440 impl<'t> CursorRef<'t> {
441     fn new(stream: &TokenStream) -> CursorRef<'_> {
442         CursorRef { stream, index: 0 }
443     }
444
445     fn next_with_spacing(&mut self) -> Option<&'t TreeAndSpacing> {
446         self.stream.0.get(self.index).map(|tree| {
447             self.index += 1;
448             tree
449         })
450     }
451 }
452
453 impl<'t> Iterator for CursorRef<'t> {
454     type Item = &'t TokenTree;
455
456     fn next(&mut self) -> Option<&'t TokenTree> {
457         self.next_with_spacing().map(|(tree, _)| tree)
458     }
459 }
460
461 /// Owning by-value iterator over a [`TokenStream`].
462 // FIXME: Many uses of this can be replaced with by-reference iterator to avoid clones.
463 #[derive(Clone)]
464 pub struct Cursor {
465     pub stream: TokenStream,
466     index: usize,
467 }
468
469 impl Iterator for Cursor {
470     type Item = TokenTree;
471
472     fn next(&mut self) -> Option<TokenTree> {
473         self.next_with_spacing().map(|(tree, _)| tree)
474     }
475 }
476
477 impl Cursor {
478     fn new(stream: TokenStream) -> Self {
479         Cursor { stream, index: 0 }
480     }
481
482     pub fn next_with_spacing(&mut self) -> Option<TreeAndSpacing> {
483         if self.index < self.stream.len() {
484             self.index += 1;
485             Some(self.stream.0[self.index - 1].clone())
486         } else {
487             None
488         }
489     }
490
491     pub fn append(&mut self, new_stream: TokenStream) {
492         if new_stream.is_empty() {
493             return;
494         }
495         let index = self.index;
496         let stream = mem::take(&mut self.stream);
497         *self = TokenStream::from_streams(smallvec![stream, new_stream]).into_trees();
498         self.index = index;
499     }
500
501     pub fn look_ahead(&self, n: usize) -> Option<&TokenTree> {
502         self.stream.0[self.index..].get(n).map(|(tree, _)| tree)
503     }
504 }
505
506 #[derive(Debug, Copy, Clone, PartialEq, Encodable, Decodable, HashStable_Generic)]
507 pub struct DelimSpan {
508     pub open: Span,
509     pub close: Span,
510 }
511
512 impl DelimSpan {
513     pub fn from_single(sp: Span) -> Self {
514         DelimSpan { open: sp, close: sp }
515     }
516
517     pub fn from_pair(open: Span, close: Span) -> Self {
518         DelimSpan { open, close }
519     }
520
521     pub fn dummy() -> Self {
522         Self::from_single(DUMMY_SP)
523     }
524
525     pub fn entire(self) -> Span {
526         self.open.with_hi(self.close.hi())
527     }
528 }