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