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