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