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.
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.
15 use syntax_pos::{BytePos, Mark, Span, DUMMY_SP};
17 use ext::tt::{macro_parser, quoted};
19 use parse::token::{self, DelimToken, Token};
21 use rustc_data_structures::sync::Lrc;
22 use serialize::{Decoder, Decodable, Encoder, Encodable};
25 use std::{fmt, iter, mem};
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.
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.
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)]
42 Token(Span, token::Token),
43 /// A delimited sequence of token trees
44 Delimited(DelimSpan, DelimToken, TokenStream),
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,
56 macro_parser::parse(cx.parse_sess(), tts, mtch, Some(directory), true)
59 /// Check if this TokenTree is equal to the other, regardless of span information.
60 pub fn eq_unspanned(&self, other: &TokenTree) -> bool {
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)
71 // See comments in `interpolated_to_tokenstream` for why we care about
72 // *probably* equal here rather than actual equality
74 // This is otherwise the same as `eq_unspanned`, only recursing with a
76 pub fn probably_equal_for_proc_macro(&self, other: &TokenTree) -> bool {
78 (&TokenTree::Token(_, ref tk), &TokenTree::Token(_, ref tk2)) => {
79 tk.probably_equal_for_proc_macro(tk2)
81 (&TokenTree::Delimited(_, delim, ref tts),
82 &TokenTree::Delimited(_, delim2, ref tts2)) => {
83 delim == delim2 && tts.probably_equal_for_proc_macro(&tts2)
89 /// Retrieve the TokenTree's span.
90 pub fn span(&self) -> Span {
92 TokenTree::Token(sp, _) => sp,
93 TokenTree::Delimited(sp, ..) => sp.entire(),
97 /// Modify the `TokenTree`'s span in-place.
98 pub fn set_span(&mut self, span: Span) {
100 TokenTree::Token(ref mut sp, _) => *sp = span,
101 TokenTree::Delimited(ref mut sp, ..) => *sp = DelimSpan::from_single(span),
105 /// Indicates if the stream is a token that is equal to the provided token.
106 pub fn eq_token(&self, t: Token) -> bool {
108 TokenTree::Token(_, ref tk) => *tk == t,
113 pub fn joint(self) -> TokenStream {
114 TokenStream::new(vec![(self, Joint)])
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() {
122 span.with_hi(span.lo() + BytePos(delim.len() as u32))
124 TokenTree::Token(open_span, token::OpenDelim(delim))
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() {
132 span.with_lo(span.hi() - BytePos(delim.len() as u32))
134 TokenTree::Token(close_span, token::CloseDelim(delim))
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 {
147 Stream(Lrc<Vec<TreeAndJoint>>),
150 pub type TreeAndJoint = (TokenTree, IsJoint);
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);
156 #[derive(Clone, Copy, Debug, PartialEq)]
162 use self::IsJoint::*;
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(),
181 let sp = sp.shrink_to_hi();
182 let comma = (TokenTree::Token(sp, token::Comma), NonJoint);
183 suggestion = Some((pos, comma, sp));
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));
199 impl From<TokenTree> for TokenStream {
200 fn from(tree: TokenTree) -> TokenStream {
201 TokenStream::new(vec![(tree, NonJoint)])
205 impl From<TokenTree> for TreeAndJoint {
206 fn from(tree: TokenTree) -> TreeAndJoint {
211 impl From<Token> for TokenStream {
212 fn from(token: Token) -> TokenStream {
213 TokenTree::Token(DUMMY_SP, token).into()
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<_>>())
223 impl Eq for TokenStream {}
225 impl PartialEq<TokenStream> for TokenStream {
226 fn eq(&self, other: &TokenStream) -> bool {
227 self.trees().eq(other.trees())
232 pub fn len(&self) -> usize {
233 if let TokenStream::Stream(ref slice) = self {
240 pub fn empty() -> TokenStream {
244 pub fn is_empty(&self) -> bool {
246 TokenStream::Empty => true,
251 fn from_streams(mut streams: Vec<TokenStream>) -> TokenStream {
252 match streams.len() {
253 0 => TokenStream::empty(),
254 1 => streams.pop().unwrap(),
256 let mut vec = vec![];
257 for stream in streams {
259 TokenStream::Empty => {},
260 TokenStream::Stream(stream2) => vec.extend(stream2.iter().cloned()),
263 TokenStream::new(vec)
268 pub fn new(streams: Vec<TreeAndJoint>) -> TokenStream {
269 match streams.len() {
270 0 => TokenStream::empty(),
271 _ => TokenStream::Stream(Lrc::new(streams)),
275 pub fn append_to_tree_and_joint_vec(self, vec: &mut Vec<TreeAndJoint>) {
277 TokenStream::Empty => {}
278 TokenStream::Stream(stream) => vec.extend(stream.iter().cloned()),
282 pub fn trees(&self) -> Cursor {
283 self.clone().into_trees()
286 pub fn into_trees(self) -> Cursor {
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) {
299 t1.next().is_none() && t2.next().is_none()
302 // See comments in `interpolated_to_tokenstream` for why we care about
303 // *probably* equal here rather than actual equality
305 // This is otherwise the same as `eq_unspanned`, only recursing with a
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 {
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,
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) {
339 t1.next().is_none() && t2.next().is_none()
342 pub fn map_enumerated<F: FnMut(usize, TokenTree) -> TokenTree>(self, mut f: F) -> TokenStream {
344 TokenStream::Empty => TokenStream::Empty,
345 TokenStream::Stream(stream) => TokenStream::Stream(Lrc::new(
349 .map(|(i, (tree, is_joint))| (f(i, tree.clone()), *is_joint))
355 pub fn map<F: FnMut(TokenTree) -> TokenTree>(self, mut f: F) -> TokenStream {
357 TokenStream::Empty => TokenStream::Empty,
358 TokenStream::Stream(stream) => TokenStream::Stream(Lrc::new(
361 .map(|(tree, is_joint)| (f(tree.clone()), *is_joint))
367 fn first_tree_and_joint(&self) -> Option<(TokenTree, IsJoint)> {
369 TokenStream::Empty => None,
370 TokenStream::Stream(ref stream) => Some(stream.first().unwrap().clone())
374 fn last_tree_if_joint(&self) -> Option<TokenTree> {
376 TokenStream::Empty => None,
377 TokenStream::Stream(ref stream) => {
378 if let (tree, Joint) = stream.last().unwrap() {
389 pub struct TokenStreamBuilder(Vec<TokenStream>);
391 impl TokenStreamBuilder {
392 pub fn new() -> TokenStreamBuilder {
393 TokenStreamBuilder(Vec::new())
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);
416 pub fn build(self) -> TokenStream {
417 TokenStream::from_streams(self.0)
420 fn push_all_but_last_tree(&mut self, stream: &TokenStream) {
421 if let TokenStream::Stream(ref streams) = stream {
422 let len = streams.len();
425 _ => self.0.push(TokenStream::Stream(Lrc::new(streams[0 .. len - 1].to_vec()))),
430 fn push_all_but_first_tree(&mut self, stream: &TokenStream) {
431 if let TokenStream::Stream(ref streams) = stream {
432 let len = streams.len();
435 _ => self.0.push(TokenStream::Stream(Lrc::new(streams[1 .. len].to_vec()))),
443 pub stream: TokenStream,
447 impl Iterator for Cursor {
448 type Item = TokenTree;
450 fn next(&mut self) -> Option<TokenTree> {
451 self.next_with_joint().map(|(tree, _)| tree)
456 fn new(stream: TokenStream) -> Self {
457 Cursor { stream, index: 0 }
460 pub fn next_with_joint(&mut self) -> Option<TreeAndJoint> {
462 TokenStream::Empty => None,
463 TokenStream::Stream(ref stream) => {
464 if self.index < stream.len() {
466 Some(stream[self.index - 1].clone())
474 pub fn append(&mut self, new_stream: TokenStream) {
475 if new_stream.is_empty() {
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();
484 pub fn look_ahead(&self, n: usize) -> Option<TokenTree> {
486 TokenStream::Empty => None,
487 TokenStream::Stream(ref stream) =>
488 stream[self.index ..].get(n).map(|(tree, _)| tree.clone()),
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()))
499 impl Encodable for TokenStream {
500 fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), E::Error> {
501 self.trees().collect::<Vec<_>>().encode(encoder)
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())
511 #[derive(Debug, Copy, Clone, PartialEq, RustcEncodable, RustcDecodable)]
512 pub struct DelimSpan {
518 pub fn from_single(sp: Span) -> Self {
525 pub fn from_pair(open: Span, close: Span) -> Self {
526 DelimSpan { open, close }
529 pub fn dummy() -> Self {
530 Self::from_single(DUMMY_SP)
533 pub fn entire(self) -> Span {
534 self.open.with_hi(self.close.hi())
537 pub fn apply_mark(self, mark: Mark) -> Self {
539 open: self.open.apply_mark(mark),
540 close: self.close.apply_mark(mark),
548 use syntax::ast::Ident;
550 use syntax_pos::{Span, BytePos, NO_EXPANSION};
551 use parse::token::Token;
552 use util::parser_testing::string_to_stream;
554 fn string_to_ts(string: &str) -> TokenStream {
555 string_to_stream(string.to_owned())
558 fn sp(a: u32, b: u32) -> Span {
559 Span::new(BytePos(a), BytePos(b), NO_EXPANSION)
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);
576 fn test_to_from_bijection() {
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)
587 let test_res = string_to_ts("foo");
588 let test_eqs = string_to_ts("foo");
589 assert_eq!(test_res, test_eqs)
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)
605 let test_res = string_to_ts("");
606 let test_eqs = string_to_ts("");
607 assert_eq!(test_res, test_eqs)
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)
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)
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)");
637 assert_eq!(test0.is_empty(), true);
638 assert_eq!(test1.is_empty(), false);
639 assert_eq!(test2.is_empty(), false);
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);