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