]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/tokenstream.rs
Rollup merge of #60959 - petrochenkov:sassert, 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 //! `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};
20 use crate::print::pprust;
21
22 use syntax_pos::{BytePos, Mark, 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 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(Span, token::Token),
48     /// A delimited sequence of token trees
49     Delimited(DelimSpan, DelimToken, TokenStream),
50 }
51
52 impl TokenTree {
53     /// Use this token tree as a matcher to parse given tts.
54     pub fn parse(cx: &base::ExtCtxt<'_>, mtch: &[quoted::TokenTree], tts: TokenStream)
55                  -> macro_parser::NamedParseResult {
56         // `None` is because we're not interpolating
57         let directory = Directory {
58             path: Cow::from(cx.current_expansion.module.directory.as_path()),
59             ownership: cx.current_expansion.directory_ownership,
60         };
61         macro_parser::parse(cx.parse_sess(), tts, mtch, Some(directory), true)
62     }
63
64     /// Checks if this TokenTree is equal to the other, regardless of span information.
65     pub fn eq_unspanned(&self, other: &TokenTree) -> bool {
66         match (self, other) {
67             (&TokenTree::Token(_, ref tk), &TokenTree::Token(_, ref tk2)) => tk == tk2,
68             (&TokenTree::Delimited(_, delim, ref tts),
69              &TokenTree::Delimited(_, delim2, ref tts2)) => {
70                 delim == delim2 && tts.eq_unspanned(&tts2)
71             }
72             (_, _) => false,
73         }
74     }
75
76     // See comments in `Nonterminal::to_tokenstream` for why we care about
77     // *probably* equal here rather than actual equality
78     //
79     // This is otherwise the same as `eq_unspanned`, only recursing with a
80     // different method.
81     pub fn probably_equal_for_proc_macro(&self, other: &TokenTree) -> bool {
82         match (self, other) {
83             (&TokenTree::Token(_, ref tk), &TokenTree::Token(_, ref tk2)) => {
84                 tk.probably_equal_for_proc_macro(tk2)
85             }
86             (&TokenTree::Delimited(_, delim, ref tts),
87              &TokenTree::Delimited(_, delim2, ref tts2)) => {
88                 delim == delim2 && tts.probably_equal_for_proc_macro(&tts2)
89             }
90             (_, _) => false,
91         }
92     }
93
94     /// Retrieves the TokenTree's span.
95     pub fn span(&self) -> Span {
96         match *self {
97             TokenTree::Token(sp, _) => sp,
98             TokenTree::Delimited(sp, ..) => sp.entire(),
99         }
100     }
101
102     /// Modify the `TokenTree`'s span in-place.
103     pub fn set_span(&mut self, span: Span) {
104         match *self {
105             TokenTree::Token(ref mut sp, _) => *sp = span,
106             TokenTree::Delimited(ref mut sp, ..) => *sp = DelimSpan::from_single(span),
107         }
108     }
109
110     /// Indicates if the stream is a token that is equal to the provided token.
111     pub fn eq_token(&self, t: Token) -> bool {
112         match *self {
113             TokenTree::Token(_, ref tk) => *tk == t,
114             _ => false,
115         }
116     }
117
118     pub fn joint(self) -> TokenStream {
119         TokenStream::new(vec![(self, Joint)])
120     }
121
122     /// Returns the opening delimiter as a token tree.
123     pub fn open_tt(span: Span, delim: DelimToken) -> TokenTree {
124         let open_span = if span.is_dummy() {
125             span
126         } else {
127             span.with_hi(span.lo() + BytePos(delim.len() as u32))
128         };
129         TokenTree::Token(open_span, token::OpenDelim(delim))
130     }
131
132     /// Returns the closing delimiter as a token tree.
133     pub fn close_tt(span: Span, delim: DelimToken) -> TokenTree {
134         let close_span = if span.is_dummy() {
135             span
136         } else {
137             span.with_lo(span.hi() - BytePos(delim.len() as u32))
138         };
139         TokenTree::Token(close_span, token::CloseDelim(delim))
140     }
141 }
142
143 /// # Token Streams
144 ///
145 /// A `TokenStream` is an abstract sequence of tokens, organized into `TokenTree`s.
146 /// The goal is for procedural macros to work with `TokenStream`s and `TokenTree`s
147 /// instead of a representation of the abstract syntax tree.
148 /// Today's `TokenTree`s can still contain AST via `Token::Interpolated` for back-compat.
149 ///
150 /// The use of `Option` is an optimization that avoids the need for an
151 /// allocation when the stream is empty. However, it is not guaranteed that an
152 /// empty stream is represented with `None`; it may be represented as a `Some`
153 /// around an empty `Vec`.
154 #[derive(Clone, Debug)]
155 pub struct TokenStream(pub Option<Lrc<Vec<TreeAndJoint>>>);
156
157 pub type TreeAndJoint = (TokenTree, IsJoint);
158
159 // `TokenStream` is used a lot. Make sure it doesn't unintentionally get bigger.
160 #[cfg(target_arch = "x86_64")]
161 static_assert_size!(TokenStream, 8);
162
163 #[derive(Clone, Copy, Debug, PartialEq)]
164 pub enum IsJoint {
165     Joint,
166     NonJoint
167 }
168
169 use IsJoint::*;
170
171 impl TokenStream {
172     /// Given a `TokenStream` with a `Stream` of only two arguments, return a new `TokenStream`
173     /// separating the two arguments with a comma for diagnostic suggestions.
174     pub(crate) fn add_comma(&self) -> Option<(TokenStream, Span)> {
175         // Used to suggest if a user writes `foo!(a b);`
176         if let Some(ref stream) = self.0 {
177             let mut suggestion = None;
178             let mut iter = stream.iter().enumerate().peekable();
179             while let Some((pos, ts)) = iter.next() {
180                 if let Some((_, next)) = iter.peek() {
181                     let sp = match (&ts, &next) {
182                         (_, (TokenTree::Token(_, token::Token::Comma), _)) => continue,
183                         ((TokenTree::Token(sp, token_left), NonJoint),
184                          (TokenTree::Token(_, token_right), _))
185                         if ((token_left.is_ident() && !token_left.is_reserved_ident())
186                             || token_left.is_lit()) &&
187                             ((token_right.is_ident() && !token_right.is_reserved_ident())
188                             || token_right.is_lit()) => *sp,
189                         ((TokenTree::Delimited(sp, ..), NonJoint), _) => sp.entire(),
190                         _ => continue,
191                     };
192                     let sp = sp.shrink_to_hi();
193                     let comma = (TokenTree::Token(sp, token::Comma), NonJoint);
194                     suggestion = Some((pos, comma, sp));
195                 }
196             }
197             if let Some((pos, comma, sp)) = suggestion {
198                 let mut new_stream = vec![];
199                 let parts = stream.split_at(pos + 1);
200                 new_stream.extend_from_slice(parts.0);
201                 new_stream.push(comma);
202                 new_stream.extend_from_slice(parts.1);
203                 return Some((TokenStream::new(new_stream), sp));
204             }
205         }
206         None
207     }
208 }
209
210 impl From<TokenTree> for TokenStream {
211     fn from(tree: TokenTree) -> TokenStream {
212         TokenStream::new(vec![(tree, NonJoint)])
213     }
214 }
215
216 impl From<TokenTree> for TreeAndJoint {
217     fn from(tree: TokenTree) -> TreeAndJoint {
218         (tree, NonJoint)
219     }
220 }
221
222 impl From<Token> for TokenStream {
223     fn from(token: Token) -> TokenStream {
224         TokenTree::Token(DUMMY_SP, token).into()
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 TokenStreams, 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             match tree {
331                 // The pretty printer tends to add trailing commas to
332                 // everything, and in particular, after struct fields.
333                 | TokenTree::Token(_, Token::Comma)
334                 // The pretty printer emits `NoDelim` as whitespace.
335                 | TokenTree::Token(_, Token::OpenDelim(DelimToken::NoDelim))
336                 | TokenTree::Token(_, Token::CloseDelim(DelimToken::NoDelim))
337                 // The pretty printer collapses many semicolons into one.
338                 | TokenTree::Token(_, Token::Semi)
339                 // The pretty printer collapses whitespace arbitrarily and can
340                 // introduce whitespace from `NoDelim`.
341                 | TokenTree::Token(_, Token::Whitespace)
342                 // The pretty printer can turn `$crate` into `::crate_name`
343                 | TokenTree::Token(_, Token::ModSep) => false,
344                 _ => true
345             }
346         }
347
348         let mut t1 = self.trees().filter(semantic_tree);
349         let mut t2 = other.trees().filter(semantic_tree);
350         for (t1, t2) in t1.by_ref().zip(t2.by_ref()) {
351             if !t1.probably_equal_for_proc_macro(&t2) {
352                 return false;
353             }
354         }
355         t1.next().is_none() && t2.next().is_none()
356     }
357
358     pub fn map_enumerated<F: FnMut(usize, TokenTree) -> TokenTree>(self, mut f: F) -> TokenStream {
359         TokenStream(self.0.map(|stream| {
360             Lrc::new(
361                 stream
362                     .iter()
363                     .enumerate()
364                     .map(|(i, (tree, is_joint))| (f(i, tree.clone()), *is_joint))
365                     .collect())
366         }))
367     }
368
369     pub fn map<F: FnMut(TokenTree) -> TokenTree>(self, mut f: F) -> TokenStream {
370         TokenStream(self.0.map(|stream| {
371             Lrc::new(
372                 stream
373                     .iter()
374                     .map(|(tree, is_joint)| (f(tree.clone()), *is_joint))
375                     .collect())
376         }))
377     }
378
379     fn first_tree_and_joint(&self) -> Option<TreeAndJoint> {
380         self.0.as_ref().map(|stream| {
381             stream.first().unwrap().clone()
382         })
383     }
384
385     fn last_tree_if_joint(&self) -> Option<TokenTree> {
386         match self.0 {
387             None => None,
388             Some(ref stream) => {
389                 if let (tree, Joint) = stream.last().unwrap() {
390                     Some(tree.clone())
391                 } else {
392                     None
393                 }
394             }
395         }
396     }
397 }
398
399 // 99.5%+ of the time we have 1 or 2 elements in this vector.
400 #[derive(Clone)]
401 pub struct TokenStreamBuilder(SmallVec<[TokenStream; 2]>);
402
403 impl TokenStreamBuilder {
404     pub fn new() -> TokenStreamBuilder {
405         TokenStreamBuilder(SmallVec::new())
406     }
407
408     pub fn push<T: Into<TokenStream>>(&mut self, stream: T) {
409         let stream = stream.into();
410         let last_tree_if_joint = self.0.last().and_then(TokenStream::last_tree_if_joint);
411         if let Some(TokenTree::Token(last_span, last_tok)) = last_tree_if_joint {
412             if let Some((TokenTree::Token(span, tok), is_joint)) = stream.first_tree_and_joint() {
413                 if let Some(glued_tok) = last_tok.glue(tok) {
414                     let last_stream = self.0.pop().unwrap();
415                     self.push_all_but_last_tree(&last_stream);
416                     let glued_span = last_span.to(span);
417                     let glued_tt = TokenTree::Token(glued_span, 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, mark: Mark) -> Self {
549         DelimSpan {
550             open: self.open.apply_mark(mark),
551             close: self.close.apply_mark(mark),
552         }
553     }
554 }
555
556 #[cfg(test)]
557 mod tests {
558     use super::*;
559     use crate::syntax::ast::Ident;
560     use crate::with_globals;
561     use crate::parse::token::Token;
562     use crate::util::parser_testing::string_to_stream;
563     use syntax_pos::{Span, BytePos, NO_EXPANSION};
564
565     fn string_to_ts(string: &str) -> TokenStream {
566         string_to_stream(string.to_owned())
567     }
568
569     fn sp(a: u32, b: u32) -> Span {
570         Span::new(BytePos(a), BytePos(b), NO_EXPANSION)
571     }
572
573     #[test]
574     fn test_concat() {
575         with_globals(|| {
576             let test_res = string_to_ts("foo::bar::baz");
577             let test_fst = string_to_ts("foo::bar");
578             let test_snd = string_to_ts("::baz");
579             let eq_res = TokenStream::from_streams(smallvec![test_fst, test_snd]);
580             assert_eq!(test_res.trees().count(), 5);
581             assert_eq!(eq_res.trees().count(), 5);
582             assert_eq!(test_res.eq_unspanned(&eq_res), true);
583         })
584     }
585
586     #[test]
587     fn test_to_from_bijection() {
588         with_globals(|| {
589             let test_start = string_to_ts("foo::bar(baz)");
590             let test_end = test_start.trees().collect();
591             assert_eq!(test_start, test_end)
592         })
593     }
594
595     #[test]
596     fn test_eq_0() {
597         with_globals(|| {
598             let test_res = string_to_ts("foo");
599             let test_eqs = string_to_ts("foo");
600             assert_eq!(test_res, test_eqs)
601         })
602     }
603
604     #[test]
605     fn test_eq_1() {
606         with_globals(|| {
607             let test_res = string_to_ts("::bar::baz");
608             let test_eqs = string_to_ts("::bar::baz");
609             assert_eq!(test_res, test_eqs)
610         })
611     }
612
613     #[test]
614     fn test_eq_3() {
615         with_globals(|| {
616             let test_res = string_to_ts("");
617             let test_eqs = string_to_ts("");
618             assert_eq!(test_res, test_eqs)
619         })
620     }
621
622     #[test]
623     fn test_diseq_0() {
624         with_globals(|| {
625             let test_res = string_to_ts("::bar::baz");
626             let test_eqs = string_to_ts("bar::baz");
627             assert_eq!(test_res == test_eqs, false)
628         })
629     }
630
631     #[test]
632     fn test_diseq_1() {
633         with_globals(|| {
634             let test_res = string_to_ts("(bar,baz)");
635             let test_eqs = string_to_ts("bar,baz");
636             assert_eq!(test_res == test_eqs, false)
637         })
638     }
639
640     #[test]
641     fn test_is_empty() {
642         with_globals(|| {
643             let test0: TokenStream = Vec::<TokenTree>::new().into_iter().collect();
644             let test1: TokenStream =
645                 TokenTree::Token(sp(0, 1), Token::Ident(Ident::from_str("a"), false)).into();
646             let test2 = string_to_ts("foo(bar::baz)");
647
648             assert_eq!(test0.is_empty(), true);
649             assert_eq!(test1.is_empty(), false);
650             assert_eq!(test2.is_empty(), false);
651         })
652     }
653
654     #[test]
655     fn test_dotdotdot() {
656         let mut builder = TokenStreamBuilder::new();
657         builder.push(TokenTree::Token(sp(0, 1), Token::Dot).joint());
658         builder.push(TokenTree::Token(sp(1, 2), Token::Dot).joint());
659         builder.push(TokenTree::Token(sp(2, 3), Token::Dot));
660         let stream = builder.build();
661         assert!(stream.eq_unspanned(&string_to_ts("...")));
662         assert_eq!(stream.trees().count(), 1);
663     }
664 }