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