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