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.
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>>>);
152 pub type TreeAndJoint = (TokenTree, IsJoint);
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);
158 #[derive(Clone, Copy, Debug, PartialEq)]
164 use self::IsJoint::*;
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(),
183 let sp = sp.shrink_to_hi();
184 let comma = (TokenTree::Token(sp, token::Comma), NonJoint);
185 suggestion = Some((pos, comma, sp));
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));
201 impl From<TokenTree> for TokenStream {
202 fn from(tree: TokenTree) -> TokenStream {
203 TokenStream::new(vec![(tree, NonJoint)])
207 impl From<TokenTree> for TreeAndJoint {
208 fn from(tree: TokenTree) -> TreeAndJoint {
213 impl From<Token> for TokenStream {
214 fn from(token: Token) -> TokenStream {
215 TokenTree::Token(DUMMY_SP, token).into()
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<_>>())
225 impl Eq for TokenStream {}
227 impl PartialEq<TokenStream> for TokenStream {
228 fn eq(&self, other: &TokenStream) -> bool {
229 self.trees().eq(other.trees())
234 pub fn len(&self) -> usize {
235 if let Some(ref slice) = self.0 {
242 pub fn empty() -> TokenStream {
246 pub fn is_empty(&self) -> bool {
249 Some(ref stream) => stream.is_empty(),
253 fn from_streams(mut streams: Vec<TokenStream>) -> TokenStream {
254 match streams.len() {
255 0 => TokenStream::empty(),
256 1 => streams.pop().unwrap(),
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() })
263 let mut vec = Vec::with_capacity(tree_count);
265 for stream in streams {
268 Some(stream2) => vec.extend(stream2.iter().cloned()),
271 TokenStream::new(vec)
276 pub fn new(streams: Vec<TreeAndJoint>) -> TokenStream {
277 match streams.len() {
278 0 => TokenStream(None),
279 _ => TokenStream(Some(Lrc::new(streams))),
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());
289 pub fn trees(&self) -> Cursor {
290 self.clone().into_trees()
293 pub fn into_trees(self) -> Cursor {
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) {
306 t1.next().is_none() && t2.next().is_none()
309 // See comments in `interpolated_to_tokenstream` for why we care about
310 // *probably* equal here rather than actual equality
312 // This is otherwise the same as `eq_unspanned`, only recursing with a
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 {
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,
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) {
346 t1.next().is_none() && t2.next().is_none()
349 pub fn map_enumerated<F: FnMut(usize, TokenTree) -> TokenTree>(self, mut f: F) -> TokenStream {
350 TokenStream(self.0.map(|stream| {
355 .map(|(i, (tree, is_joint))| (f(i, tree.clone()), *is_joint))
360 pub fn map<F: FnMut(TokenTree) -> TokenTree>(self, mut f: F) -> TokenStream {
361 TokenStream(self.0.map(|stream| {
365 .map(|(tree, is_joint)| (f(tree.clone()), *is_joint))
370 fn first_tree_and_joint(&self) -> Option<TreeAndJoint> {
371 self.0.as_ref().map(|stream| {
372 stream.first().unwrap().clone()
376 fn last_tree_if_joint(&self) -> Option<TokenTree> {
379 Some(ref stream) => {
380 if let (tree, Joint) = stream.last().unwrap() {
391 pub struct TokenStreamBuilder(Vec<TokenStream>);
393 impl TokenStreamBuilder {
394 pub fn new() -> TokenStreamBuilder {
395 TokenStreamBuilder(Vec::new())
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);
418 pub fn build(self) -> TokenStream {
419 TokenStream::from_streams(self.0)
422 fn push_all_but_last_tree(&mut self, stream: &TokenStream) {
423 if let Some(ref streams) = stream.0 {
424 let len = streams.len();
427 _ => self.0.push(TokenStream(Some(Lrc::new(streams[0 .. len - 1].to_vec())))),
432 fn push_all_but_first_tree(&mut self, stream: &TokenStream) {
433 if let Some(ref streams) = stream.0 {
434 let len = streams.len();
437 _ => self.0.push(TokenStream(Some(Lrc::new(streams[1 .. len].to_vec())))),
445 pub stream: TokenStream,
449 impl Iterator for Cursor {
450 type Item = TokenTree;
452 fn next(&mut self) -> Option<TokenTree> {
453 self.next_with_joint().map(|(tree, _)| tree)
458 fn new(stream: TokenStream) -> Self {
459 Cursor { stream, index: 0 }
462 pub fn next_with_joint(&mut self) -> Option<TreeAndJoint> {
463 match self.stream.0 {
465 Some(ref stream) => {
466 if self.index < stream.len() {
468 Some(stream[self.index - 1].clone())
476 pub fn append(&mut self, new_stream: TokenStream) {
477 if new_stream.is_empty() {
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();
486 pub fn look_ahead(&self, n: usize) -> Option<TokenTree> {
487 match self.stream.0 {
489 Some(ref stream) => stream[self.index ..].get(n).map(|(tree, _)| tree.clone()),
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()))
500 impl Encodable for TokenStream {
501 fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), E::Error> {
502 self.trees().collect::<Vec<_>>().encode(encoder)
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())
512 #[derive(Debug, Copy, Clone, PartialEq, RustcEncodable, RustcDecodable)]
513 pub struct DelimSpan {
519 pub fn from_single(sp: Span) -> Self {
526 pub fn from_pair(open: Span, close: Span) -> Self {
527 DelimSpan { open, close }
530 pub fn dummy() -> Self {
531 Self::from_single(DUMMY_SP)
534 pub fn entire(self) -> Span {
535 self.open.with_hi(self.close.hi())
538 pub fn apply_mark(self, mark: Mark) -> Self {
540 open: self.open.apply_mark(mark),
541 close: self.close.apply_mark(mark),
549 use syntax::ast::Ident;
551 use syntax_pos::{Span, BytePos, NO_EXPANSION};
552 use parse::token::Token;
553 use util::parser_testing::string_to_stream;
555 fn string_to_ts(string: &str) -> TokenStream {
556 string_to_stream(string.to_owned())
559 fn sp(a: u32, b: u32) -> Span {
560 Span::new(BytePos(a), BytePos(b), NO_EXPANSION)
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);
577 fn test_to_from_bijection() {
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)
588 let test_res = string_to_ts("foo");
589 let test_eqs = string_to_ts("foo");
590 assert_eq!(test_res, test_eqs)
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)
606 let test_res = string_to_ts("");
607 let test_eqs = string_to_ts("");
608 assert_eq!(test_res, test_eqs)
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)
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)
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)");
638 assert_eq!(test0.is_empty(), true);
639 assert_eq!(test1.is_empty(), false);
640 assert_eq!(test2.is_empty(), false);
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);