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