]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/tokenstream.rs
2d47b982ebdd9b7140d1760d0206cc6cd3a1278b
[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 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!(MEM_SIZE_OF_TOKEN_STREAM: mem::size_of::<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_lit()) &&
186                             (token_right.is_ident() || token_right.is_lit()) => *sp,
187                         ((TokenTree::Delimited(sp, ..), NonJoint), _) => sp.entire(),
188                         _ => continue,
189                     };
190                     let sp = sp.shrink_to_hi();
191                     let comma = (TokenTree::Token(sp, token::Comma), NonJoint);
192                     suggestion = Some((pos, comma, sp));
193                 }
194             }
195             if let Some((pos, comma, sp)) = suggestion {
196                 let mut new_stream = vec![];
197                 let parts = stream.split_at(pos + 1);
198                 new_stream.extend_from_slice(parts.0);
199                 new_stream.push(comma);
200                 new_stream.extend_from_slice(parts.1);
201                 return Some((TokenStream::new(new_stream), sp));
202             }
203         }
204         None
205     }
206 }
207
208 impl From<TokenTree> for TokenStream {
209     fn from(tree: TokenTree) -> TokenStream {
210         TokenStream::new(vec![(tree, NonJoint)])
211     }
212 }
213
214 impl From<TokenTree> for TreeAndJoint {
215     fn from(tree: TokenTree) -> TreeAndJoint {
216         (tree, NonJoint)
217     }
218 }
219
220 impl From<Token> for TokenStream {
221     fn from(token: Token) -> TokenStream {
222         TokenTree::Token(DUMMY_SP, token).into()
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             match tree {
329                 // The pretty printer tends to add trailing commas to
330                 // everything, and in particular, after struct fields.
331                 | TokenTree::Token(_, Token::Comma)
332                 // The pretty printer emits `NoDelim` as whitespace.
333                 | TokenTree::Token(_, Token::OpenDelim(DelimToken::NoDelim))
334                 | TokenTree::Token(_, Token::CloseDelim(DelimToken::NoDelim))
335                 // The pretty printer collapses many semicolons into one.
336                 | TokenTree::Token(_, Token::Semi)
337                 // The pretty printer collapses whitespace arbitrarily and can
338                 // introduce whitespace from `NoDelim`.
339                 | TokenTree::Token(_, Token::Whitespace)
340                 // The pretty printer can turn `$crate` into `::crate_name`
341                 | TokenTree::Token(_, Token::ModSep) => false,
342                 _ => true
343             }
344         }
345
346         let mut t1 = self.trees().filter(semantic_tree);
347         let mut t2 = other.trees().filter(semantic_tree);
348         for (t1, t2) in t1.by_ref().zip(t2.by_ref()) {
349             if !t1.probably_equal_for_proc_macro(&t2) {
350                 return false;
351             }
352         }
353         t1.next().is_none() && t2.next().is_none()
354     }
355
356     pub fn map_enumerated<F: FnMut(usize, TokenTree) -> TokenTree>(self, mut f: F) -> TokenStream {
357         TokenStream(self.0.map(|stream| {
358             Lrc::new(
359                 stream
360                     .iter()
361                     .enumerate()
362                     .map(|(i, (tree, is_joint))| (f(i, tree.clone()), *is_joint))
363                     .collect())
364         }))
365     }
366
367     pub fn map<F: FnMut(TokenTree) -> TokenTree>(self, mut f: F) -> TokenStream {
368         TokenStream(self.0.map(|stream| {
369             Lrc::new(
370                 stream
371                     .iter()
372                     .map(|(tree, is_joint)| (f(tree.clone()), *is_joint))
373                     .collect())
374         }))
375     }
376
377     fn first_tree_and_joint(&self) -> Option<TreeAndJoint> {
378         self.0.as_ref().map(|stream| {
379             stream.first().unwrap().clone()
380         })
381     }
382
383     fn last_tree_if_joint(&self) -> Option<TokenTree> {
384         match self.0 {
385             None => None,
386             Some(ref stream) => {
387                 if let (tree, Joint) = stream.last().unwrap() {
388                     Some(tree.clone())
389                 } else {
390                     None
391                 }
392             }
393         }
394     }
395 }
396
397 // 99.5%+ of the time we have 1 or 2 elements in this vector.
398 #[derive(Clone)]
399 pub struct TokenStreamBuilder(SmallVec<[TokenStream; 2]>);
400
401 impl TokenStreamBuilder {
402     pub fn new() -> TokenStreamBuilder {
403         TokenStreamBuilder(SmallVec::new())
404     }
405
406     pub fn push<T: Into<TokenStream>>(&mut self, stream: T) {
407         let stream = stream.into();
408         let last_tree_if_joint = self.0.last().and_then(TokenStream::last_tree_if_joint);
409         if let Some(TokenTree::Token(last_span, last_tok)) = last_tree_if_joint {
410             if let Some((TokenTree::Token(span, tok), is_joint)) = stream.first_tree_and_joint() {
411                 if let Some(glued_tok) = last_tok.glue(tok) {
412                     let last_stream = self.0.pop().unwrap();
413                     self.push_all_but_last_tree(&last_stream);
414                     let glued_span = last_span.to(span);
415                     let glued_tt = TokenTree::Token(glued_span, glued_tok);
416                     let glued_tokenstream = TokenStream::new(vec![(glued_tt, is_joint)]);
417                     self.0.push(glued_tokenstream);
418                     self.push_all_but_first_tree(&stream);
419                     return
420                 }
421             }
422         }
423         self.0.push(stream);
424     }
425
426     pub fn build(self) -> TokenStream {
427         TokenStream::from_streams(self.0)
428     }
429
430     fn push_all_but_last_tree(&mut self, stream: &TokenStream) {
431         if let Some(ref streams) = stream.0 {
432             let len = streams.len();
433             match len {
434                 1 => {}
435                 _ => self.0.push(TokenStream(Some(Lrc::new(streams[0 .. len - 1].to_vec())))),
436             }
437         }
438     }
439
440     fn push_all_but_first_tree(&mut self, stream: &TokenStream) {
441         if let Some(ref streams) = stream.0 {
442             let len = streams.len();
443             match len {
444                 1 => {}
445                 _ => self.0.push(TokenStream(Some(Lrc::new(streams[1 .. len].to_vec())))),
446             }
447         }
448     }
449 }
450
451 #[derive(Clone)]
452 pub struct Cursor {
453     pub stream: TokenStream,
454     index: usize,
455 }
456
457 impl Iterator for Cursor {
458     type Item = TokenTree;
459
460     fn next(&mut self) -> Option<TokenTree> {
461         self.next_with_joint().map(|(tree, _)| tree)
462     }
463 }
464
465 impl Cursor {
466     fn new(stream: TokenStream) -> Self {
467         Cursor { stream, index: 0 }
468     }
469
470     pub fn next_with_joint(&mut self) -> Option<TreeAndJoint> {
471         match self.stream.0 {
472             None => None,
473             Some(ref stream) => {
474                 if self.index < stream.len() {
475                     self.index += 1;
476                     Some(stream[self.index - 1].clone())
477                 } else {
478                     None
479                 }
480             }
481         }
482     }
483
484     pub fn append(&mut self, new_stream: TokenStream) {
485         if new_stream.is_empty() {
486             return;
487         }
488         let index = self.index;
489         let stream = mem::replace(&mut self.stream, TokenStream(None));
490         *self = TokenStream::from_streams(smallvec![stream, new_stream]).into_trees();
491         self.index = index;
492     }
493
494     pub fn look_ahead(&self, n: usize) -> Option<TokenTree> {
495         match self.stream.0 {
496             None => None,
497             Some(ref stream) => stream[self.index ..].get(n).map(|(tree, _)| tree.clone()),
498         }
499     }
500 }
501
502 impl fmt::Display for TokenStream {
503     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
504         f.write_str(&pprust::tokens_to_string(self.clone()))
505     }
506 }
507
508 impl Encodable for TokenStream {
509     fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), E::Error> {
510         self.trees().collect::<Vec<_>>().encode(encoder)
511     }
512 }
513
514 impl Decodable for TokenStream {
515     fn decode<D: Decoder>(decoder: &mut D) -> Result<TokenStream, D::Error> {
516         Vec::<TokenTree>::decode(decoder).map(|vec| vec.into_iter().collect())
517     }
518 }
519
520 #[derive(Debug, Copy, Clone, PartialEq, RustcEncodable, RustcDecodable)]
521 pub struct DelimSpan {
522     pub open: Span,
523     pub close: Span,
524 }
525
526 impl DelimSpan {
527     pub fn from_single(sp: Span) -> Self {
528         DelimSpan {
529             open: sp,
530             close: sp,
531         }
532     }
533
534     pub fn from_pair(open: Span, close: Span) -> Self {
535         DelimSpan { open, close }
536     }
537
538     pub fn dummy() -> Self {
539         Self::from_single(DUMMY_SP)
540     }
541
542     pub fn entire(self) -> Span {
543         self.open.with_hi(self.close.hi())
544     }
545
546     pub fn apply_mark(self, mark: Mark) -> Self {
547         DelimSpan {
548             open: self.open.apply_mark(mark),
549             close: self.close.apply_mark(mark),
550         }
551     }
552 }
553
554 #[cfg(test)]
555 mod tests {
556     use super::*;
557     use crate::syntax::ast::Ident;
558     use crate::with_globals;
559     use crate::parse::token::Token;
560     use crate::util::parser_testing::string_to_stream;
561     use syntax_pos::{Span, BytePos, NO_EXPANSION};
562
563     fn string_to_ts(string: &str) -> TokenStream {
564         string_to_stream(string.to_owned())
565     }
566
567     fn sp(a: u32, b: u32) -> Span {
568         Span::new(BytePos(a), BytePos(b), NO_EXPANSION)
569     }
570
571     #[test]
572     fn test_concat() {
573         with_globals(|| {
574             let test_res = string_to_ts("foo::bar::baz");
575             let test_fst = string_to_ts("foo::bar");
576             let test_snd = string_to_ts("::baz");
577             let eq_res = TokenStream::from_streams(smallvec![test_fst, test_snd]);
578             assert_eq!(test_res.trees().count(), 5);
579             assert_eq!(eq_res.trees().count(), 5);
580             assert_eq!(test_res.eq_unspanned(&eq_res), true);
581         })
582     }
583
584     #[test]
585     fn test_to_from_bijection() {
586         with_globals(|| {
587             let test_start = string_to_ts("foo::bar(baz)");
588             let test_end = test_start.trees().collect();
589             assert_eq!(test_start, test_end)
590         })
591     }
592
593     #[test]
594     fn test_eq_0() {
595         with_globals(|| {
596             let test_res = string_to_ts("foo");
597             let test_eqs = string_to_ts("foo");
598             assert_eq!(test_res, test_eqs)
599         })
600     }
601
602     #[test]
603     fn test_eq_1() {
604         with_globals(|| {
605             let test_res = string_to_ts("::bar::baz");
606             let test_eqs = string_to_ts("::bar::baz");
607             assert_eq!(test_res, test_eqs)
608         })
609     }
610
611     #[test]
612     fn test_eq_3() {
613         with_globals(|| {
614             let test_res = string_to_ts("");
615             let test_eqs = string_to_ts("");
616             assert_eq!(test_res, test_eqs)
617         })
618     }
619
620     #[test]
621     fn test_diseq_0() {
622         with_globals(|| {
623             let test_res = string_to_ts("::bar::baz");
624             let test_eqs = string_to_ts("bar::baz");
625             assert_eq!(test_res == test_eqs, false)
626         })
627     }
628
629     #[test]
630     fn test_diseq_1() {
631         with_globals(|| {
632             let test_res = string_to_ts("(bar,baz)");
633             let test_eqs = string_to_ts("bar,baz");
634             assert_eq!(test_res == test_eqs, false)
635         })
636     }
637
638     #[test]
639     fn test_is_empty() {
640         with_globals(|| {
641             let test0: TokenStream = Vec::<TokenTree>::new().into_iter().collect();
642             let test1: TokenStream =
643                 TokenTree::Token(sp(0, 1), Token::Ident(Ident::from_str("a"), false)).into();
644             let test2 = string_to_ts("foo(bar::baz)");
645
646             assert_eq!(test0.is_empty(), true);
647             assert_eq!(test1.is_empty(), false);
648             assert_eq!(test2.is_empty(), false);
649         })
650     }
651
652     #[test]
653     fn test_dotdotdot() {
654         let mut builder = TokenStreamBuilder::new();
655         builder.push(TokenTree::Token(sp(0, 1), Token::Dot).joint());
656         builder.push(TokenTree::Token(sp(1, 2), Token::Dot).joint());
657         builder.push(TokenTree::Token(sp(2, 3), Token::Dot));
658         let stream = builder.build();
659         assert!(stream.eq_unspanned(&string_to_ts("...")));
660         assert_eq!(stream.trees().count(), 1);
661     }
662 }