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