]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/tokenstream.rs
Rollup merge of #64895 - davidtwco:issue-64130-async-error-definition, r=nikomatsakis
[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                 // rust-lang/rust#57735: pre-allocate vector to avoid
253                 // quadratic blow-up due to on-the-fly reallocations.
254                 let tree_count = streams.iter()
255                     .map(|ts| match &ts.0 { None => 0, Some(s) => s.len() })
256                     .sum();
257                 let mut vec = Vec::with_capacity(tree_count);
258
259                 for stream in streams {
260                     match stream.0 {
261                         None => {},
262                         Some(stream2) => vec.extend(stream2.iter().cloned()),
263                     }
264                 }
265                 TokenStream::new(vec)
266             }
267         }
268     }
269
270     pub fn new(streams: Vec<TreeAndJoint>) -> TokenStream {
271         match streams.len() {
272             0 => TokenStream(None),
273             _ => TokenStream(Some(Lrc::new(streams))),
274         }
275     }
276
277     pub fn append_to_tree_and_joint_vec(self, vec: &mut Vec<TreeAndJoint>) {
278         if let Some(stream) = self.0 {
279             vec.extend(stream.iter().cloned());
280         }
281     }
282
283     pub fn trees(&self) -> Cursor {
284         self.clone().into_trees()
285     }
286
287     pub fn into_trees(self) -> Cursor {
288         Cursor::new(self)
289     }
290
291     /// Compares two `TokenStream`s, checking equality without regarding span information.
292     pub fn eq_unspanned(&self, other: &TokenStream) -> bool {
293         let mut t1 = self.trees();
294         let mut t2 = other.trees();
295         for (t1, t2) in t1.by_ref().zip(t2.by_ref()) {
296             if !t1.eq_unspanned(&t2) {
297                 return false;
298             }
299         }
300         t1.next().is_none() && t2.next().is_none()
301     }
302
303     // See comments in `Nonterminal::to_tokenstream` for why we care about
304     // *probably* equal here rather than actual equality
305     //
306     // This is otherwise the same as `eq_unspanned`, only recursing with a
307     // different method.
308     pub fn probably_equal_for_proc_macro(&self, other: &TokenStream) -> bool {
309         // When checking for `probably_eq`, we ignore certain tokens that aren't
310         // preserved in the AST. Because they are not preserved, the pretty
311         // printer arbitrarily adds or removes them when printing as token
312         // streams, making a comparison between a token stream generated from an
313         // AST and a token stream which was parsed into an AST more reliable.
314         fn semantic_tree(tree: &TokenTree) -> bool {
315             if let TokenTree::Token(token) = tree {
316                 if let
317                     // The pretty printer tends to add trailing commas to
318                     // everything, and in particular, after struct fields.
319                     | token::Comma
320                     // The pretty printer emits `NoDelim` as whitespace.
321                     | token::OpenDelim(DelimToken::NoDelim)
322                     | token::CloseDelim(DelimToken::NoDelim)
323                     // The pretty printer collapses many semicolons into one.
324                     | token::Semi
325                     // The pretty printer collapses whitespace arbitrarily and can
326                     // introduce whitespace from `NoDelim`.
327                     | token::Whitespace
328                     // The pretty printer can turn `$crate` into `::crate_name`
329                     | token::ModSep = token.kind {
330                     return false;
331                 }
332             }
333             true
334         }
335
336         let mut t1 = self.trees().filter(semantic_tree);
337         let mut t2 = other.trees().filter(semantic_tree);
338         for (t1, t2) in t1.by_ref().zip(t2.by_ref()) {
339             if !t1.probably_equal_for_proc_macro(&t2) {
340                 return false;
341             }
342         }
343         t1.next().is_none() && t2.next().is_none()
344     }
345
346     pub fn map_enumerated<F: FnMut(usize, TokenTree) -> TokenTree>(self, mut f: F) -> TokenStream {
347         TokenStream(self.0.map(|stream| {
348             Lrc::new(
349                 stream
350                     .iter()
351                     .enumerate()
352                     .map(|(i, (tree, is_joint))| (f(i, tree.clone()), *is_joint))
353                     .collect())
354         }))
355     }
356
357     pub fn map<F: FnMut(TokenTree) -> TokenTree>(self, mut f: F) -> TokenStream {
358         TokenStream(self.0.map(|stream| {
359             Lrc::new(
360                 stream
361                     .iter()
362                     .map(|(tree, is_joint)| (f(tree.clone()), *is_joint))
363                     .collect())
364         }))
365     }
366
367     fn first_tree_and_joint(&self) -> Option<TreeAndJoint> {
368         self.0.as_ref().map(|stream| {
369             stream.first().unwrap().clone()
370         })
371     }
372
373     fn last_tree_if_joint(&self) -> Option<TokenTree> {
374         match self.0 {
375             None => None,
376             Some(ref stream) => {
377                 if let (tree, Joint) = stream.last().unwrap() {
378                     Some(tree.clone())
379                 } else {
380                     None
381                 }
382             }
383         }
384     }
385 }
386
387 // 99.5%+ of the time we have 1 or 2 elements in this vector.
388 #[derive(Clone)]
389 pub struct TokenStreamBuilder(SmallVec<[TokenStream; 2]>);
390
391 impl TokenStreamBuilder {
392     pub fn new() -> TokenStreamBuilder {
393         TokenStreamBuilder(SmallVec::new())
394     }
395
396     pub fn push<T: Into<TokenStream>>(&mut self, stream: T) {
397         let stream = stream.into();
398         let last_tree_if_joint = self.0.last().and_then(TokenStream::last_tree_if_joint);
399         if let Some(TokenTree::Token(last_token)) = last_tree_if_joint {
400             if let Some((TokenTree::Token(token), is_joint)) = stream.first_tree_and_joint() {
401                 if let Some(glued_tok) = last_token.glue(&token) {
402                     let last_stream = self.0.pop().unwrap();
403                     self.push_all_but_last_tree(&last_stream);
404                     let glued_tt = TokenTree::Token(glued_tok);
405                     let glued_tokenstream = TokenStream::new(vec![(glued_tt, is_joint)]);
406                     self.0.push(glued_tokenstream);
407                     self.push_all_but_first_tree(&stream);
408                     return
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     fn push_all_but_last_tree(&mut self, stream: &TokenStream) {
420         if let Some(ref streams) = stream.0 {
421             let len = streams.len();
422             match len {
423                 1 => {}
424                 _ => self.0.push(TokenStream(Some(Lrc::new(streams[0 .. len - 1].to_vec())))),
425             }
426         }
427     }
428
429     fn push_all_but_first_tree(&mut self, stream: &TokenStream) {
430         if let Some(ref streams) = stream.0 {
431             let len = streams.len();
432             match len {
433                 1 => {}
434                 _ => self.0.push(TokenStream(Some(Lrc::new(streams[1 .. len].to_vec())))),
435             }
436         }
437     }
438 }
439
440 #[derive(Clone)]
441 pub struct Cursor {
442     pub stream: TokenStream,
443     index: usize,
444 }
445
446 impl Iterator for Cursor {
447     type Item = TokenTree;
448
449     fn next(&mut self) -> Option<TokenTree> {
450         self.next_with_joint().map(|(tree, _)| tree)
451     }
452 }
453
454 impl Cursor {
455     fn new(stream: TokenStream) -> Self {
456         Cursor { stream, index: 0 }
457     }
458
459     pub fn next_with_joint(&mut self) -> Option<TreeAndJoint> {
460         match self.stream.0 {
461             None => None,
462             Some(ref stream) => {
463                 if self.index < stream.len() {
464                     self.index += 1;
465                     Some(stream[self.index - 1].clone())
466                 } else {
467                     None
468                 }
469             }
470         }
471     }
472
473     pub fn append(&mut self, new_stream: TokenStream) {
474         if new_stream.is_empty() {
475             return;
476         }
477         let index = self.index;
478         let stream = mem::replace(&mut self.stream, TokenStream(None));
479         *self = TokenStream::from_streams(smallvec![stream, new_stream]).into_trees();
480         self.index = index;
481     }
482
483     pub fn look_ahead(&self, n: usize) -> Option<TokenTree> {
484         match self.stream.0 {
485             None => None,
486             Some(ref stream) => stream[self.index ..].get(n).map(|(tree, _)| tree.clone()),
487         }
488     }
489 }
490
491 impl fmt::Display for TokenStream {
492     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
493         f.write_str(&pprust::tts_to_string(self.clone()))
494     }
495 }
496
497 impl Encodable for TokenStream {
498     fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), E::Error> {
499         self.trees().collect::<Vec<_>>().encode(encoder)
500     }
501 }
502
503 impl Decodable for TokenStream {
504     fn decode<D: Decoder>(decoder: &mut D) -> Result<TokenStream, D::Error> {
505         Vec::<TokenTree>::decode(decoder).map(|vec| vec.into_iter().collect())
506     }
507 }
508
509 #[derive(Debug, Copy, Clone, PartialEq, RustcEncodable, RustcDecodable)]
510 pub struct DelimSpan {
511     pub open: Span,
512     pub close: Span,
513 }
514
515 impl DelimSpan {
516     pub fn from_single(sp: Span) -> Self {
517         DelimSpan {
518             open: sp,
519             close: sp,
520         }
521     }
522
523     pub fn from_pair(open: Span, close: Span) -> Self {
524         DelimSpan { open, close }
525     }
526
527     pub fn dummy() -> Self {
528         Self::from_single(DUMMY_SP)
529     }
530
531     pub fn entire(self) -> Span {
532         self.open.with_hi(self.close.hi())
533     }
534 }