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