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