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