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