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