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.
9 //! `TokenStreams` are persistent data structures constructed as ropes with reference
10 //! counted-children. In general, this means that calling an operation on a `TokenStream`
11 //! (such as `slice`) produces an entirely new `TokenStream` from the borrowed reference to
12 //! the original. This essentially coerces `TokenStream`s into 'views' of their subparts,
13 //! and a borrowed `TokenStream` is sufficient to build an owned `TokenStream` without taking
14 //! ownership of the original.
17 use crate::ext::tt::{macro_parser, quoted};
18 use crate::parse::Directory;
19 use crate::parse::token::{self, DelimToken, Token};
20 use crate::print::pprust;
22 use syntax_pos::{BytePos, Mark, Span, DUMMY_SP};
23 #[cfg(target_arch = "x86_64")]
24 use rustc_data_structures::static_assert;
25 use rustc_data_structures::sync::Lrc;
26 use serialize::{Decoder, Decodable, Encoder, Encodable};
29 use std::{fmt, iter, mem};
31 /// When the main rust parser encounters a syntax-extension invocation, it
32 /// parses the arguments to the invocation as a token-tree. This is a very
33 /// loose structure, such that all sorts of different AST-fragments can
34 /// be passed to syntax extensions using a uniform type.
36 /// If the syntax extension is an MBE macro, it will attempt to match its
37 /// LHS token tree against the provided token tree, and if it finds a
38 /// match, will transcribe the RHS token tree, splicing in any captured
39 /// `macro_parser::matched_nonterminals` into the `SubstNt`s it finds.
41 /// The RHS of an MBE macro is the only place `SubstNt`s are substituted.
42 /// Nothing special happens to misnamed or misplaced `SubstNt`s.
43 #[derive(Debug, Clone, PartialEq, RustcEncodable, RustcDecodable)]
46 Token(Span, token::Token),
47 /// A delimited sequence of token trees
48 Delimited(DelimSpan, DelimToken, TokenStream),
52 /// Use this token tree as a matcher to parse given tts.
53 pub fn parse(cx: &base::ExtCtxt<'_>, mtch: &[quoted::TokenTree], tts: TokenStream)
54 -> macro_parser::NamedParseResult {
55 // `None` is because we're not interpolating
56 let directory = Directory {
57 path: Cow::from(cx.current_expansion.module.directory.as_path()),
58 ownership: cx.current_expansion.directory_ownership,
60 macro_parser::parse(cx.parse_sess(), tts, mtch, Some(directory), true)
63 /// Checks if this TokenTree is equal to the other, regardless of span information.
64 pub fn eq_unspanned(&self, other: &TokenTree) -> bool {
66 (&TokenTree::Token(_, ref tk), &TokenTree::Token(_, ref tk2)) => tk == tk2,
67 (&TokenTree::Delimited(_, delim, ref tts),
68 &TokenTree::Delimited(_, delim2, ref tts2)) => {
69 delim == delim2 && tts.eq_unspanned(&tts2)
75 // See comments in `interpolated_to_tokenstream` for why we care about
76 // *probably* equal here rather than actual equality
78 // This is otherwise the same as `eq_unspanned`, only recursing with a
80 pub fn probably_equal_for_proc_macro(&self, other: &TokenTree) -> bool {
82 (&TokenTree::Token(_, ref tk), &TokenTree::Token(_, ref tk2)) => {
83 tk.probably_equal_for_proc_macro(tk2)
85 (&TokenTree::Delimited(_, delim, ref tts),
86 &TokenTree::Delimited(_, delim2, ref tts2)) => {
87 delim == delim2 && tts.probably_equal_for_proc_macro(&tts2)
93 /// Retrieves the TokenTree's span.
94 pub fn span(&self) -> Span {
96 TokenTree::Token(sp, _) => sp,
97 TokenTree::Delimited(sp, ..) => sp.entire(),
101 /// Modify the `TokenTree`'s span in-place.
102 pub fn set_span(&mut self, span: Span) {
104 TokenTree::Token(ref mut sp, _) => *sp = span,
105 TokenTree::Delimited(ref mut sp, ..) => *sp = DelimSpan::from_single(span),
109 /// Indicates if the stream is a token that is equal to the provided token.
110 pub fn eq_token(&self, t: Token) -> bool {
112 TokenTree::Token(_, ref tk) => *tk == t,
117 pub fn joint(self) -> TokenStream {
118 TokenStream::new(vec![(self, Joint)])
121 /// Returns the opening delimiter as a token tree.
122 pub fn open_tt(span: Span, delim: DelimToken) -> TokenTree {
123 let open_span = if span.is_dummy() {
126 span.with_hi(span.lo() + BytePos(delim.len() as u32))
128 TokenTree::Token(open_span, token::OpenDelim(delim))
131 /// Returns the closing delimiter as a token tree.
132 pub fn close_tt(span: Span, delim: DelimToken) -> TokenTree {
133 let close_span = if span.is_dummy() {
136 span.with_lo(span.hi() - BytePos(delim.len() as u32))
138 TokenTree::Token(close_span, token::CloseDelim(delim))
144 /// A `TokenStream` is an abstract sequence of tokens, organized into `TokenTree`s.
145 /// The goal is for procedural macros to work with `TokenStream`s and `TokenTree`s
146 /// instead of a representation of the abstract syntax tree.
147 /// Today's `TokenTree`s can still contain AST via `Token::Interpolated` for back-compat.
149 /// The use of `Option` is an optimization that avoids the need for an
150 /// allocation when the stream is empty. However, it is not guaranteed that an
151 /// empty stream is represented with `None`; it may be represented as a `Some`
152 /// around an empty `Vec`.
153 #[derive(Clone, Debug)]
154 pub struct TokenStream(pub Option<Lrc<Vec<TreeAndJoint>>>);
156 pub type TreeAndJoint = (TokenTree, IsJoint);
158 // `TokenStream` is used a lot. Make sure it doesn't unintentionally get bigger.
159 #[cfg(target_arch = "x86_64")]
160 static_assert!(MEM_SIZE_OF_TOKEN_STREAM: mem::size_of::<TokenStream>() == 8);
162 #[derive(Clone, Copy, Debug, PartialEq)]
171 /// Given a `TokenStream` with a `Stream` of only two arguments, return a new `TokenStream`
172 /// separating the two arguments with a comma for diagnostic suggestions.
173 pub(crate) fn add_comma(&self) -> Option<(TokenStream, Span)> {
174 // Used to suggest if a user writes `foo!(a b);`
175 if let Some(ref stream) = self.0 {
176 let mut suggestion = None;
177 let mut iter = stream.iter().enumerate().peekable();
178 while let Some((pos, ts)) = iter.next() {
179 if let Some((_, next)) = iter.peek() {
180 let sp = match (&ts, &next) {
181 ((TokenTree::Token(_, token::Token::Comma), NonJoint), _) |
182 (_, (TokenTree::Token(_, token::Token::Comma), NonJoint)) => continue,
183 ((TokenTree::Token(sp, _), NonJoint), _) => *sp,
184 ((TokenTree::Delimited(sp, ..), NonJoint), _) => sp.entire(),
187 let sp = sp.shrink_to_hi();
188 let comma = (TokenTree::Token(sp, token::Comma), NonJoint);
189 suggestion = Some((pos, comma, sp));
192 if let Some((pos, comma, sp)) = suggestion {
193 let mut new_stream = vec![];
194 let parts = stream.split_at(pos + 1);
195 new_stream.extend_from_slice(parts.0);
196 new_stream.push(comma);
197 new_stream.extend_from_slice(parts.1);
198 return Some((TokenStream::new(new_stream), sp));
205 impl From<TokenTree> for TokenStream {
206 fn from(tree: TokenTree) -> TokenStream {
207 TokenStream::new(vec![(tree, NonJoint)])
211 impl From<TokenTree> for TreeAndJoint {
212 fn from(tree: TokenTree) -> TreeAndJoint {
217 impl From<Token> for TokenStream {
218 fn from(token: Token) -> TokenStream {
219 TokenTree::Token(DUMMY_SP, token).into()
223 impl<T: Into<TokenStream>> iter::FromIterator<T> for TokenStream {
224 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
225 TokenStream::from_streams(iter.into_iter().map(Into::into).collect::<Vec<_>>())
229 impl Eq for TokenStream {}
231 impl PartialEq<TokenStream> for TokenStream {
232 fn eq(&self, other: &TokenStream) -> bool {
233 self.trees().eq(other.trees())
238 pub fn len(&self) -> usize {
239 if let Some(ref slice) = self.0 {
246 pub fn empty() -> TokenStream {
250 pub fn is_empty(&self) -> bool {
253 Some(ref stream) => stream.is_empty(),
257 fn from_streams(mut streams: Vec<TokenStream>) -> TokenStream {
258 match streams.len() {
259 0 => TokenStream::empty(),
260 1 => streams.pop().unwrap(),
262 // rust-lang/rust#57735: pre-allocate vector to avoid
263 // quadratic blow-up due to on-the-fly reallocations.
264 let tree_count = streams.iter()
265 .map(|ts| match &ts.0 { None => 0, Some(s) => s.len() })
267 let mut vec = Vec::with_capacity(tree_count);
269 for stream in streams {
272 Some(stream2) => vec.extend(stream2.iter().cloned()),
275 TokenStream::new(vec)
280 pub fn new(streams: Vec<TreeAndJoint>) -> TokenStream {
281 match streams.len() {
282 0 => TokenStream(None),
283 _ => TokenStream(Some(Lrc::new(streams))),
287 pub fn append_to_tree_and_joint_vec(self, vec: &mut Vec<TreeAndJoint>) {
288 if let Some(stream) = self.0 {
289 vec.extend(stream.iter().cloned());
293 pub fn trees(&self) -> Cursor {
294 self.clone().into_trees()
297 pub fn into_trees(self) -> Cursor {
301 /// Compares two TokenStreams, checking equality without regarding span information.
302 pub fn eq_unspanned(&self, other: &TokenStream) -> bool {
303 let mut t1 = self.trees();
304 let mut t2 = other.trees();
305 for (t1, t2) in t1.by_ref().zip(t2.by_ref()) {
306 if !t1.eq_unspanned(&t2) {
310 t1.next().is_none() && t2.next().is_none()
313 // See comments in `interpolated_to_tokenstream` for why we care about
314 // *probably* equal here rather than actual equality
316 // This is otherwise the same as `eq_unspanned`, only recursing with a
318 pub fn probably_equal_for_proc_macro(&self, other: &TokenStream) -> bool {
319 // When checking for `probably_eq`, we ignore certain tokens that aren't
320 // preserved in the AST. Because they are not preserved, the pretty
321 // printer arbitrarily adds or removes them when printing as token
322 // streams, making a comparison between a token stream generated from an
323 // AST and a token stream which was parsed into an AST more reliable.
324 fn semantic_tree(tree: &TokenTree) -> bool {
326 // The pretty printer tends to add trailing commas to
327 // everything, and in particular, after struct fields.
328 | TokenTree::Token(_, Token::Comma)
329 // The pretty printer emits `NoDelim` as whitespace.
330 | TokenTree::Token(_, Token::OpenDelim(DelimToken::NoDelim))
331 | TokenTree::Token(_, Token::CloseDelim(DelimToken::NoDelim))
332 // The pretty printer collapses many semicolons into one.
333 | TokenTree::Token(_, Token::Semi)
334 // The pretty printer collapses whitespace arbitrarily and can
335 // introduce whitespace from `NoDelim`.
336 | TokenTree::Token(_, Token::Whitespace)
337 // The pretty printer can turn `$crate` into `::crate_name`
338 | TokenTree::Token(_, Token::ModSep) => false,
343 let mut t1 = self.trees().filter(semantic_tree);
344 let mut t2 = other.trees().filter(semantic_tree);
345 for (t1, t2) in t1.by_ref().zip(t2.by_ref()) {
346 if !t1.probably_equal_for_proc_macro(&t2) {
350 t1.next().is_none() && t2.next().is_none()
353 pub fn map_enumerated<F: FnMut(usize, TokenTree) -> TokenTree>(self, mut f: F) -> TokenStream {
354 TokenStream(self.0.map(|stream| {
359 .map(|(i, (tree, is_joint))| (f(i, tree.clone()), *is_joint))
364 pub fn map<F: FnMut(TokenTree) -> TokenTree>(self, mut f: F) -> TokenStream {
365 TokenStream(self.0.map(|stream| {
369 .map(|(tree, is_joint)| (f(tree.clone()), *is_joint))
374 fn first_tree_and_joint(&self) -> Option<TreeAndJoint> {
375 self.0.as_ref().map(|stream| {
376 stream.first().unwrap().clone()
380 fn last_tree_if_joint(&self) -> Option<TokenTree> {
383 Some(ref stream) => {
384 if let (tree, Joint) = stream.last().unwrap() {
395 pub struct TokenStreamBuilder(Vec<TokenStream>);
397 impl TokenStreamBuilder {
398 pub fn new() -> TokenStreamBuilder {
399 TokenStreamBuilder(Vec::new())
402 pub fn push<T: Into<TokenStream>>(&mut self, stream: T) {
403 let stream = stream.into();
404 let last_tree_if_joint = self.0.last().and_then(TokenStream::last_tree_if_joint);
405 if let Some(TokenTree::Token(last_span, last_tok)) = last_tree_if_joint {
406 if let Some((TokenTree::Token(span, tok), is_joint)) = stream.first_tree_and_joint() {
407 if let Some(glued_tok) = last_tok.glue(tok) {
408 let last_stream = self.0.pop().unwrap();
409 self.push_all_but_last_tree(&last_stream);
410 let glued_span = last_span.to(span);
411 let glued_tt = TokenTree::Token(glued_span, glued_tok);
412 let glued_tokenstream = TokenStream::new(vec![(glued_tt, is_joint)]);
413 self.0.push(glued_tokenstream);
414 self.push_all_but_first_tree(&stream);
422 pub fn build(self) -> TokenStream {
423 TokenStream::from_streams(self.0)
426 fn push_all_but_last_tree(&mut self, stream: &TokenStream) {
427 if let Some(ref streams) = stream.0 {
428 let len = streams.len();
431 _ => self.0.push(TokenStream(Some(Lrc::new(streams[0 .. len - 1].to_vec())))),
436 fn push_all_but_first_tree(&mut self, stream: &TokenStream) {
437 if let Some(ref streams) = stream.0 {
438 let len = streams.len();
441 _ => self.0.push(TokenStream(Some(Lrc::new(streams[1 .. len].to_vec())))),
449 pub stream: TokenStream,
453 impl Iterator for Cursor {
454 type Item = TokenTree;
456 fn next(&mut self) -> Option<TokenTree> {
457 self.next_with_joint().map(|(tree, _)| tree)
462 fn new(stream: TokenStream) -> Self {
463 Cursor { stream, index: 0 }
466 pub fn next_with_joint(&mut self) -> Option<TreeAndJoint> {
467 match self.stream.0 {
469 Some(ref stream) => {
470 if self.index < stream.len() {
472 Some(stream[self.index - 1].clone())
480 pub fn append(&mut self, new_stream: TokenStream) {
481 if new_stream.is_empty() {
484 let index = self.index;
485 let stream = mem::replace(&mut self.stream, TokenStream(None));
486 *self = TokenStream::from_streams(vec![stream, new_stream]).into_trees();
490 pub fn look_ahead(&self, n: usize) -> Option<TokenTree> {
491 match self.stream.0 {
493 Some(ref stream) => stream[self.index ..].get(n).map(|(tree, _)| tree.clone()),
498 impl fmt::Display for TokenStream {
499 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
500 f.write_str(&pprust::tokens_to_string(self.clone()))
504 impl Encodable for TokenStream {
505 fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), E::Error> {
506 self.trees().collect::<Vec<_>>().encode(encoder)
510 impl Decodable for TokenStream {
511 fn decode<D: Decoder>(decoder: &mut D) -> Result<TokenStream, D::Error> {
512 Vec::<TokenTree>::decode(decoder).map(|vec| vec.into_iter().collect())
516 #[derive(Debug, Copy, Clone, PartialEq, RustcEncodable, RustcDecodable)]
517 pub struct DelimSpan {
523 pub fn from_single(sp: Span) -> Self {
530 pub fn from_pair(open: Span, close: Span) -> Self {
531 DelimSpan { open, close }
534 pub fn dummy() -> Self {
535 Self::from_single(DUMMY_SP)
538 pub fn entire(self) -> Span {
539 self.open.with_hi(self.close.hi())
542 pub fn apply_mark(self, mark: Mark) -> Self {
544 open: self.open.apply_mark(mark),
545 close: self.close.apply_mark(mark),
553 use crate::syntax::ast::Ident;
554 use crate::with_globals;
555 use crate::parse::token::Token;
556 use crate::util::parser_testing::string_to_stream;
557 use syntax_pos::{Span, BytePos, NO_EXPANSION};
559 fn string_to_ts(string: &str) -> TokenStream {
560 string_to_stream(string.to_owned())
563 fn sp(a: u32, b: u32) -> Span {
564 Span::new(BytePos(a), BytePos(b), NO_EXPANSION)
570 let test_res = string_to_ts("foo::bar::baz");
571 let test_fst = string_to_ts("foo::bar");
572 let test_snd = string_to_ts("::baz");
573 let eq_res = TokenStream::from_streams(vec![test_fst, test_snd]);
574 assert_eq!(test_res.trees().count(), 5);
575 assert_eq!(eq_res.trees().count(), 5);
576 assert_eq!(test_res.eq_unspanned(&eq_res), true);
581 fn test_to_from_bijection() {
583 let test_start = string_to_ts("foo::bar(baz)");
584 let test_end = test_start.trees().collect();
585 assert_eq!(test_start, test_end)
592 let test_res = string_to_ts("foo");
593 let test_eqs = string_to_ts("foo");
594 assert_eq!(test_res, test_eqs)
601 let test_res = string_to_ts("::bar::baz");
602 let test_eqs = string_to_ts("::bar::baz");
603 assert_eq!(test_res, test_eqs)
610 let test_res = string_to_ts("");
611 let test_eqs = string_to_ts("");
612 assert_eq!(test_res, test_eqs)
619 let test_res = string_to_ts("::bar::baz");
620 let test_eqs = string_to_ts("bar::baz");
621 assert_eq!(test_res == test_eqs, false)
628 let test_res = string_to_ts("(bar,baz)");
629 let test_eqs = string_to_ts("bar,baz");
630 assert_eq!(test_res == test_eqs, false)
637 let test0: TokenStream = Vec::<TokenTree>::new().into_iter().collect();
638 let test1: TokenStream =
639 TokenTree::Token(sp(0, 1), Token::Ident(Ident::from_str("a"), false)).into();
640 let test2 = string_to_ts("foo(bar::baz)");
642 assert_eq!(test0.is_empty(), true);
643 assert_eq!(test1.is_empty(), false);
644 assert_eq!(test2.is_empty(), false);
649 fn test_dotdotdot() {
650 let mut builder = TokenStreamBuilder::new();
651 builder.push(TokenTree::Token(sp(0, 1), Token::Dot).joint());
652 builder.push(TokenTree::Token(sp(1, 2), Token::Dot).joint());
653 builder.push(TokenTree::Token(sp(2, 3), Token::Dot));
654 let stream = builder.build();
655 assert!(stream.eq_unspanned(&string_to_ts("...")));
656 assert_eq!(stream.trees().count(), 1);