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