]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/tokenstream.rs
Auto merge of #57760 - dlrobertson:varargs1, r=alexreg
[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), NonJoint), _) |
182                         (_, (TokenTree::Token(_, token::Token::Comma), NonJoint)) => continue,
183                         ((TokenTree::Token(sp, _), NonJoint), _) => *sp,
184                         ((TokenTree::Delimited(sp, ..), NonJoint), _) => sp.entire(),
185                         _ => continue,
186                     };
187                     let sp = sp.shrink_to_hi();
188                     let comma = (TokenTree::Token(sp, token::Comma), NonJoint);
189                     suggestion = Some((pos, comma, sp));
190                 }
191             }
192             if let Some((pos, comma, sp)) = suggestion {
193                 let mut new_stream = vec![];
194                 let parts = stream.split_at(pos + 1);
195                 new_stream.extend_from_slice(parts.0);
196                 new_stream.push(comma);
197                 new_stream.extend_from_slice(parts.1);
198                 return Some((TokenStream::new(new_stream), sp));
199             }
200         }
201         None
202     }
203 }
204
205 impl From<TokenTree> for TokenStream {
206     fn from(tree: TokenTree) -> TokenStream {
207         TokenStream::new(vec![(tree, NonJoint)])
208     }
209 }
210
211 impl From<TokenTree> for TreeAndJoint {
212     fn from(tree: TokenTree) -> TreeAndJoint {
213         (tree, NonJoint)
214     }
215 }
216
217 impl From<Token> for TokenStream {
218     fn from(token: Token) -> TokenStream {
219         TokenTree::Token(DUMMY_SP, token).into()
220     }
221 }
222
223 impl<T: Into<TokenStream>> iter::FromIterator<T> for TokenStream {
224     fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
225         TokenStream::from_streams(iter.into_iter().map(Into::into).collect::<Vec<_>>())
226     }
227 }
228
229 impl Eq for TokenStream {}
230
231 impl PartialEq<TokenStream> for TokenStream {
232     fn eq(&self, other: &TokenStream) -> bool {
233         self.trees().eq(other.trees())
234     }
235 }
236
237 impl TokenStream {
238     pub fn len(&self) -> usize {
239         if let Some(ref slice) = self.0 {
240             slice.len()
241         } else {
242             0
243         }
244     }
245
246     pub fn empty() -> TokenStream {
247         TokenStream(None)
248     }
249
250     pub fn is_empty(&self) -> bool {
251         match self.0 {
252             None => true,
253             Some(ref stream) => stream.is_empty(),
254         }
255     }
256
257     pub(crate) fn from_streams(mut streams: Vec<TokenStream>) -> TokenStream {
258         match streams.len() {
259             0 => TokenStream::empty(),
260             1 => streams.pop().unwrap(),
261             _ => {
262                 // rust-lang/rust#57735: pre-allocate vector to avoid
263                 // quadratic blow-up due to on-the-fly reallocations.
264                 let tree_count = streams.iter()
265                     .map(|ts| match &ts.0 { None => 0, Some(s) => s.len() })
266                     .sum();
267                 let mut vec = Vec::with_capacity(tree_count);
268
269                 for stream in streams {
270                     match stream.0 {
271                         None => {},
272                         Some(stream2) => vec.extend(stream2.iter().cloned()),
273                     }
274                 }
275                 TokenStream::new(vec)
276             }
277         }
278     }
279
280     pub fn new(streams: Vec<TreeAndJoint>) -> TokenStream {
281         match streams.len() {
282             0 => TokenStream(None),
283             _ => TokenStream(Some(Lrc::new(streams))),
284         }
285     }
286
287     pub fn append_to_tree_and_joint_vec(self, vec: &mut Vec<TreeAndJoint>) {
288         if let Some(stream) = self.0 {
289             vec.extend(stream.iter().cloned());
290         }
291     }
292
293     pub fn trees(&self) -> Cursor {
294         self.clone().into_trees()
295     }
296
297     pub fn into_trees(self) -> Cursor {
298         Cursor::new(self)
299     }
300
301     /// Compares two TokenStreams, checking equality without regarding span information.
302     pub fn eq_unspanned(&self, other: &TokenStream) -> bool {
303         let mut t1 = self.trees();
304         let mut t2 = other.trees();
305         for (t1, t2) in t1.by_ref().zip(t2.by_ref()) {
306             if !t1.eq_unspanned(&t2) {
307                 return false;
308             }
309         }
310         t1.next().is_none() && t2.next().is_none()
311     }
312
313     // See comments in `Nonterminal::to_tokenstream` for why we care about
314     // *probably* equal here rather than actual equality
315     //
316     // This is otherwise the same as `eq_unspanned`, only recursing with a
317     // different method.
318     pub fn probably_equal_for_proc_macro(&self, other: &TokenStream) -> bool {
319         // When checking for `probably_eq`, we ignore certain tokens that aren't
320         // preserved in the AST. Because they are not preserved, the pretty
321         // printer arbitrarily adds or removes them when printing as token
322         // streams, making a comparison between a token stream generated from an
323         // AST and a token stream which was parsed into an AST more reliable.
324         fn semantic_tree(tree: &TokenTree) -> bool {
325             match tree {
326                 // The pretty printer tends to add trailing commas to
327                 // everything, and in particular, after struct fields.
328                 | TokenTree::Token(_, Token::Comma)
329                 // The pretty printer emits `NoDelim` as whitespace.
330                 | TokenTree::Token(_, Token::OpenDelim(DelimToken::NoDelim))
331                 | TokenTree::Token(_, Token::CloseDelim(DelimToken::NoDelim))
332                 // The pretty printer collapses many semicolons into one.
333                 | TokenTree::Token(_, Token::Semi)
334                 // The pretty printer collapses whitespace arbitrarily and can
335                 // introduce whitespace from `NoDelim`.
336                 | TokenTree::Token(_, Token::Whitespace)
337                 // The pretty printer can turn `$crate` into `::crate_name`
338                 | TokenTree::Token(_, Token::ModSep) => false,
339                 _ => true
340             }
341         }
342
343         let mut t1 = self.trees().filter(semantic_tree);
344         let mut t2 = other.trees().filter(semantic_tree);
345         for (t1, t2) in t1.by_ref().zip(t2.by_ref()) {
346             if !t1.probably_equal_for_proc_macro(&t2) {
347                 return false;
348             }
349         }
350         t1.next().is_none() && t2.next().is_none()
351     }
352
353     pub fn map_enumerated<F: FnMut(usize, TokenTree) -> TokenTree>(self, mut f: F) -> TokenStream {
354         TokenStream(self.0.map(|stream| {
355             Lrc::new(
356                 stream
357                     .iter()
358                     .enumerate()
359                     .map(|(i, (tree, is_joint))| (f(i, tree.clone()), *is_joint))
360                     .collect())
361         }))
362     }
363
364     pub fn map<F: FnMut(TokenTree) -> TokenTree>(self, mut f: F) -> TokenStream {
365         TokenStream(self.0.map(|stream| {
366             Lrc::new(
367                 stream
368                     .iter()
369                     .map(|(tree, is_joint)| (f(tree.clone()), *is_joint))
370                     .collect())
371         }))
372     }
373
374     fn first_tree_and_joint(&self) -> Option<TreeAndJoint> {
375         self.0.as_ref().map(|stream| {
376             stream.first().unwrap().clone()
377         })
378     }
379
380     fn last_tree_if_joint(&self) -> Option<TokenTree> {
381         match self.0 {
382             None => None,
383             Some(ref stream) => {
384                 if let (tree, Joint) = stream.last().unwrap() {
385                     Some(tree.clone())
386                 } else {
387                     None
388                 }
389             }
390         }
391     }
392 }
393
394 #[derive(Clone)]
395 pub struct TokenStreamBuilder(Vec<TokenStream>);
396
397 impl TokenStreamBuilder {
398     pub fn new() -> TokenStreamBuilder {
399         TokenStreamBuilder(Vec::new())
400     }
401
402     pub fn push<T: Into<TokenStream>>(&mut self, stream: T) {
403         let stream = stream.into();
404         let last_tree_if_joint = self.0.last().and_then(TokenStream::last_tree_if_joint);
405         if let Some(TokenTree::Token(last_span, last_tok)) = last_tree_if_joint {
406             if let Some((TokenTree::Token(span, tok), is_joint)) = stream.first_tree_and_joint() {
407                 if let Some(glued_tok) = last_tok.glue(tok) {
408                     let last_stream = self.0.pop().unwrap();
409                     self.push_all_but_last_tree(&last_stream);
410                     let glued_span = last_span.to(span);
411                     let glued_tt = TokenTree::Token(glued_span, glued_tok);
412                     let glued_tokenstream = TokenStream::new(vec![(glued_tt, is_joint)]);
413                     self.0.push(glued_tokenstream);
414                     self.push_all_but_first_tree(&stream);
415                     return
416                 }
417             }
418         }
419         self.0.push(stream);
420     }
421
422     pub fn build(self) -> TokenStream {
423         TokenStream::from_streams(self.0)
424     }
425
426     fn push_all_but_last_tree(&mut self, stream: &TokenStream) {
427         if let Some(ref streams) = stream.0 {
428             let len = streams.len();
429             match len {
430                 1 => {}
431                 _ => self.0.push(TokenStream(Some(Lrc::new(streams[0 .. len - 1].to_vec())))),
432             }
433         }
434     }
435
436     fn push_all_but_first_tree(&mut self, stream: &TokenStream) {
437         if let Some(ref streams) = stream.0 {
438             let len = streams.len();
439             match len {
440                 1 => {}
441                 _ => self.0.push(TokenStream(Some(Lrc::new(streams[1 .. len].to_vec())))),
442             }
443         }
444     }
445 }
446
447 #[derive(Clone)]
448 pub struct Cursor {
449     pub stream: TokenStream,
450     index: usize,
451 }
452
453 impl Iterator for Cursor {
454     type Item = TokenTree;
455
456     fn next(&mut self) -> Option<TokenTree> {
457         self.next_with_joint().map(|(tree, _)| tree)
458     }
459 }
460
461 impl Cursor {
462     fn new(stream: TokenStream) -> Self {
463         Cursor { stream, index: 0 }
464     }
465
466     pub fn next_with_joint(&mut self) -> Option<TreeAndJoint> {
467         match self.stream.0 {
468             None => None,
469             Some(ref stream) => {
470                 if self.index < stream.len() {
471                     self.index += 1;
472                     Some(stream[self.index - 1].clone())
473                 } else {
474                     None
475                 }
476             }
477         }
478     }
479
480     pub fn append(&mut self, new_stream: TokenStream) {
481         if new_stream.is_empty() {
482             return;
483         }
484         let index = self.index;
485         let stream = mem::replace(&mut self.stream, TokenStream(None));
486         *self = TokenStream::from_streams(vec![stream, new_stream]).into_trees();
487         self.index = index;
488     }
489
490     pub fn look_ahead(&self, n: usize) -> Option<TokenTree> {
491         match self.stream.0 {
492             None => None,
493             Some(ref stream) => stream[self.index ..].get(n).map(|(tree, _)| tree.clone()),
494         }
495     }
496 }
497
498 impl fmt::Display for TokenStream {
499     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
500         f.write_str(&pprust::tokens_to_string(self.clone()))
501     }
502 }
503
504 impl Encodable for TokenStream {
505     fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), E::Error> {
506         self.trees().collect::<Vec<_>>().encode(encoder)
507     }
508 }
509
510 impl Decodable for TokenStream {
511     fn decode<D: Decoder>(decoder: &mut D) -> Result<TokenStream, D::Error> {
512         Vec::<TokenTree>::decode(decoder).map(|vec| vec.into_iter().collect())
513     }
514 }
515
516 #[derive(Debug, Copy, Clone, PartialEq, RustcEncodable, RustcDecodable)]
517 pub struct DelimSpan {
518     pub open: Span,
519     pub close: Span,
520 }
521
522 impl DelimSpan {
523     pub fn from_single(sp: Span) -> Self {
524         DelimSpan {
525             open: sp,
526             close: sp,
527         }
528     }
529
530     pub fn from_pair(open: Span, close: Span) -> Self {
531         DelimSpan { open, close }
532     }
533
534     pub fn dummy() -> Self {
535         Self::from_single(DUMMY_SP)
536     }
537
538     pub fn entire(self) -> Span {
539         self.open.with_hi(self.close.hi())
540     }
541
542     pub fn apply_mark(self, mark: Mark) -> Self {
543         DelimSpan {
544             open: self.open.apply_mark(mark),
545             close: self.close.apply_mark(mark),
546         }
547     }
548 }
549
550 #[cfg(test)]
551 mod tests {
552     use super::*;
553     use crate::syntax::ast::Ident;
554     use crate::with_globals;
555     use crate::parse::token::Token;
556     use crate::util::parser_testing::string_to_stream;
557     use syntax_pos::{Span, BytePos, NO_EXPANSION};
558
559     fn string_to_ts(string: &str) -> TokenStream {
560         string_to_stream(string.to_owned())
561     }
562
563     fn sp(a: u32, b: u32) -> Span {
564         Span::new(BytePos(a), BytePos(b), NO_EXPANSION)
565     }
566
567     #[test]
568     fn test_concat() {
569         with_globals(|| {
570             let test_res = string_to_ts("foo::bar::baz");
571             let test_fst = string_to_ts("foo::bar");
572             let test_snd = string_to_ts("::baz");
573             let eq_res = TokenStream::from_streams(vec![test_fst, test_snd]);
574             assert_eq!(test_res.trees().count(), 5);
575             assert_eq!(eq_res.trees().count(), 5);
576             assert_eq!(test_res.eq_unspanned(&eq_res), true);
577         })
578     }
579
580     #[test]
581     fn test_to_from_bijection() {
582         with_globals(|| {
583             let test_start = string_to_ts("foo::bar(baz)");
584             let test_end = test_start.trees().collect();
585             assert_eq!(test_start, test_end)
586         })
587     }
588
589     #[test]
590     fn test_eq_0() {
591         with_globals(|| {
592             let test_res = string_to_ts("foo");
593             let test_eqs = string_to_ts("foo");
594             assert_eq!(test_res, test_eqs)
595         })
596     }
597
598     #[test]
599     fn test_eq_1() {
600         with_globals(|| {
601             let test_res = string_to_ts("::bar::baz");
602             let test_eqs = string_to_ts("::bar::baz");
603             assert_eq!(test_res, test_eqs)
604         })
605     }
606
607     #[test]
608     fn test_eq_3() {
609         with_globals(|| {
610             let test_res = string_to_ts("");
611             let test_eqs = string_to_ts("");
612             assert_eq!(test_res, test_eqs)
613         })
614     }
615
616     #[test]
617     fn test_diseq_0() {
618         with_globals(|| {
619             let test_res = string_to_ts("::bar::baz");
620             let test_eqs = string_to_ts("bar::baz");
621             assert_eq!(test_res == test_eqs, false)
622         })
623     }
624
625     #[test]
626     fn test_diseq_1() {
627         with_globals(|| {
628             let test_res = string_to_ts("(bar,baz)");
629             let test_eqs = string_to_ts("bar,baz");
630             assert_eq!(test_res == test_eqs, false)
631         })
632     }
633
634     #[test]
635     fn test_is_empty() {
636         with_globals(|| {
637             let test0: TokenStream = Vec::<TokenTree>::new().into_iter().collect();
638             let test1: TokenStream =
639                 TokenTree::Token(sp(0, 1), Token::Ident(Ident::from_str("a"), false)).into();
640             let test2 = string_to_ts("foo(bar::baz)");
641
642             assert_eq!(test0.is_empty(), true);
643             assert_eq!(test1.is_empty(), false);
644             assert_eq!(test2.is_empty(), false);
645         })
646     }
647
648     #[test]
649     fn test_dotdotdot() {
650         let mut builder = TokenStreamBuilder::new();
651         builder.push(TokenTree::Token(sp(0, 1), Token::Dot).joint());
652         builder.push(TokenTree::Token(sp(1, 2), Token::Dot).joint());
653         builder.push(TokenTree::Token(sp(2, 3), Token::Dot));
654         let stream = builder.build();
655         assert!(stream.eq_unspanned(&string_to_ts("...")));
656         assert_eq!(stream.trees().count(), 1);
657     }
658 }