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 `Nonterminal::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), _)) => continue,
182 ((TokenTree::Token(sp, token_left), NonJoint),
183 (TokenTree::Token(_, token_right), _))
184 if (token_left.is_ident() || token_left.is_lit()) &&
185 (token_right.is_ident() || token_right.is_lit()) => *sp,
186 ((TokenTree::Delimited(sp, ..), NonJoint), _) => sp.entire(),
189 let sp = sp.shrink_to_hi();
190 let comma = (TokenTree::Token(sp, token::Comma), NonJoint);
191 suggestion = Some((pos, comma, sp));
194 if let Some((pos, comma, sp)) = suggestion {
195 let mut new_stream = vec![];
196 let parts = stream.split_at(pos + 1);
197 new_stream.extend_from_slice(parts.0);
198 new_stream.push(comma);
199 new_stream.extend_from_slice(parts.1);
200 return Some((TokenStream::new(new_stream), sp));
207 impl From<TokenTree> for TokenStream {
208 fn from(tree: TokenTree) -> TokenStream {
209 TokenStream::new(vec![(tree, NonJoint)])
213 impl From<TokenTree> for TreeAndJoint {
214 fn from(tree: TokenTree) -> TreeAndJoint {
219 impl From<Token> for TokenStream {
220 fn from(token: Token) -> TokenStream {
221 TokenTree::Token(DUMMY_SP, token).into()
225 impl<T: Into<TokenStream>> iter::FromIterator<T> for TokenStream {
226 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
227 TokenStream::from_streams(iter.into_iter().map(Into::into).collect::<Vec<_>>())
231 impl Eq for TokenStream {}
233 impl PartialEq<TokenStream> for TokenStream {
234 fn eq(&self, other: &TokenStream) -> bool {
235 self.trees().eq(other.trees())
240 pub fn len(&self) -> usize {
241 if let Some(ref slice) = self.0 {
248 pub fn empty() -> TokenStream {
252 pub fn is_empty(&self) -> bool {
255 Some(ref stream) => stream.is_empty(),
259 pub(crate) fn from_streams(mut streams: Vec<TokenStream>) -> TokenStream {
260 match streams.len() {
261 0 => TokenStream::empty(),
262 1 => streams.pop().unwrap(),
264 // rust-lang/rust#57735: pre-allocate vector to avoid
265 // quadratic blow-up due to on-the-fly reallocations.
266 let tree_count = streams.iter()
267 .map(|ts| match &ts.0 { None => 0, Some(s) => s.len() })
269 let mut vec = Vec::with_capacity(tree_count);
271 for stream in streams {
274 Some(stream2) => vec.extend(stream2.iter().cloned()),
277 TokenStream::new(vec)
282 pub fn new(streams: Vec<TreeAndJoint>) -> TokenStream {
283 match streams.len() {
284 0 => TokenStream(None),
285 _ => TokenStream(Some(Lrc::new(streams))),
289 pub fn append_to_tree_and_joint_vec(self, vec: &mut Vec<TreeAndJoint>) {
290 if let Some(stream) = self.0 {
291 vec.extend(stream.iter().cloned());
295 pub fn trees(&self) -> Cursor {
296 self.clone().into_trees()
299 pub fn into_trees(self) -> Cursor {
303 /// Compares two TokenStreams, checking equality without regarding span information.
304 pub fn eq_unspanned(&self, other: &TokenStream) -> bool {
305 let mut t1 = self.trees();
306 let mut t2 = other.trees();
307 for (t1, t2) in t1.by_ref().zip(t2.by_ref()) {
308 if !t1.eq_unspanned(&t2) {
312 t1.next().is_none() && t2.next().is_none()
315 // See comments in `Nonterminal::to_tokenstream` for why we care about
316 // *probably* equal here rather than actual equality
318 // This is otherwise the same as `eq_unspanned`, only recursing with a
320 pub fn probably_equal_for_proc_macro(&self, other: &TokenStream) -> bool {
321 // When checking for `probably_eq`, we ignore certain tokens that aren't
322 // preserved in the AST. Because they are not preserved, the pretty
323 // printer arbitrarily adds or removes them when printing as token
324 // streams, making a comparison between a token stream generated from an
325 // AST and a token stream which was parsed into an AST more reliable.
326 fn semantic_tree(tree: &TokenTree) -> bool {
328 // The pretty printer tends to add trailing commas to
329 // everything, and in particular, after struct fields.
330 | TokenTree::Token(_, Token::Comma)
331 // The pretty printer emits `NoDelim` as whitespace.
332 | TokenTree::Token(_, Token::OpenDelim(DelimToken::NoDelim))
333 | TokenTree::Token(_, Token::CloseDelim(DelimToken::NoDelim))
334 // The pretty printer collapses many semicolons into one.
335 | TokenTree::Token(_, Token::Semi)
336 // The pretty printer collapses whitespace arbitrarily and can
337 // introduce whitespace from `NoDelim`.
338 | TokenTree::Token(_, Token::Whitespace)
339 // The pretty printer can turn `$crate` into `::crate_name`
340 | TokenTree::Token(_, Token::ModSep) => false,
345 let mut t1 = self.trees().filter(semantic_tree);
346 let mut t2 = other.trees().filter(semantic_tree);
347 for (t1, t2) in t1.by_ref().zip(t2.by_ref()) {
348 if !t1.probably_equal_for_proc_macro(&t2) {
352 t1.next().is_none() && t2.next().is_none()
355 pub fn map_enumerated<F: FnMut(usize, TokenTree) -> TokenTree>(self, mut f: F) -> TokenStream {
356 TokenStream(self.0.map(|stream| {
361 .map(|(i, (tree, is_joint))| (f(i, tree.clone()), *is_joint))
366 pub fn map<F: FnMut(TokenTree) -> TokenTree>(self, mut f: F) -> TokenStream {
367 TokenStream(self.0.map(|stream| {
371 .map(|(tree, is_joint)| (f(tree.clone()), *is_joint))
376 fn first_tree_and_joint(&self) -> Option<TreeAndJoint> {
377 self.0.as_ref().map(|stream| {
378 stream.first().unwrap().clone()
382 fn last_tree_if_joint(&self) -> Option<TokenTree> {
385 Some(ref stream) => {
386 if let (tree, Joint) = stream.last().unwrap() {
397 pub struct TokenStreamBuilder(Vec<TokenStream>);
399 impl TokenStreamBuilder {
400 pub fn new() -> TokenStreamBuilder {
401 TokenStreamBuilder(Vec::new())
404 pub fn push<T: Into<TokenStream>>(&mut self, stream: T) {
405 let stream = stream.into();
406 let last_tree_if_joint = self.0.last().and_then(TokenStream::last_tree_if_joint);
407 if let Some(TokenTree::Token(last_span, last_tok)) = last_tree_if_joint {
408 if let Some((TokenTree::Token(span, tok), is_joint)) = stream.first_tree_and_joint() {
409 if let Some(glued_tok) = last_tok.glue(tok) {
410 let last_stream = self.0.pop().unwrap();
411 self.push_all_but_last_tree(&last_stream);
412 let glued_span = last_span.to(span);
413 let glued_tt = TokenTree::Token(glued_span, glued_tok);
414 let glued_tokenstream = TokenStream::new(vec![(glued_tt, is_joint)]);
415 self.0.push(glued_tokenstream);
416 self.push_all_but_first_tree(&stream);
424 pub fn build(self) -> TokenStream {
425 TokenStream::from_streams(self.0)
428 fn push_all_but_last_tree(&mut self, stream: &TokenStream) {
429 if let Some(ref streams) = stream.0 {
430 let len = streams.len();
433 _ => self.0.push(TokenStream(Some(Lrc::new(streams[0 .. len - 1].to_vec())))),
438 fn push_all_but_first_tree(&mut self, stream: &TokenStream) {
439 if let Some(ref streams) = stream.0 {
440 let len = streams.len();
443 _ => self.0.push(TokenStream(Some(Lrc::new(streams[1 .. len].to_vec())))),
451 pub stream: TokenStream,
455 impl Iterator for Cursor {
456 type Item = TokenTree;
458 fn next(&mut self) -> Option<TokenTree> {
459 self.next_with_joint().map(|(tree, _)| tree)
464 fn new(stream: TokenStream) -> Self {
465 Cursor { stream, index: 0 }
468 pub fn next_with_joint(&mut self) -> Option<TreeAndJoint> {
469 match self.stream.0 {
471 Some(ref stream) => {
472 if self.index < stream.len() {
474 Some(stream[self.index - 1].clone())
482 pub fn append(&mut self, new_stream: TokenStream) {
483 if new_stream.is_empty() {
486 let index = self.index;
487 let stream = mem::replace(&mut self.stream, TokenStream(None));
488 *self = TokenStream::from_streams(vec![stream, new_stream]).into_trees();
492 pub fn look_ahead(&self, n: usize) -> Option<TokenTree> {
493 match self.stream.0 {
495 Some(ref stream) => stream[self.index ..].get(n).map(|(tree, _)| tree.clone()),
500 impl fmt::Display for TokenStream {
501 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
502 f.write_str(&pprust::tokens_to_string(self.clone()))
506 impl Encodable for TokenStream {
507 fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), E::Error> {
508 self.trees().collect::<Vec<_>>().encode(encoder)
512 impl Decodable for TokenStream {
513 fn decode<D: Decoder>(decoder: &mut D) -> Result<TokenStream, D::Error> {
514 Vec::<TokenTree>::decode(decoder).map(|vec| vec.into_iter().collect())
518 #[derive(Debug, Copy, Clone, PartialEq, RustcEncodable, RustcDecodable)]
519 pub struct DelimSpan {
525 pub fn from_single(sp: Span) -> Self {
532 pub fn from_pair(open: Span, close: Span) -> Self {
533 DelimSpan { open, close }
536 pub fn dummy() -> Self {
537 Self::from_single(DUMMY_SP)
540 pub fn entire(self) -> Span {
541 self.open.with_hi(self.close.hi())
544 pub fn apply_mark(self, mark: Mark) -> Self {
546 open: self.open.apply_mark(mark),
547 close: self.close.apply_mark(mark),
555 use crate::syntax::ast::Ident;
556 use crate::with_globals;
557 use crate::parse::token::Token;
558 use crate::util::parser_testing::string_to_stream;
559 use syntax_pos::{Span, BytePos, NO_EXPANSION};
561 fn string_to_ts(string: &str) -> TokenStream {
562 string_to_stream(string.to_owned())
565 fn sp(a: u32, b: u32) -> Span {
566 Span::new(BytePos(a), BytePos(b), NO_EXPANSION)
572 let test_res = string_to_ts("foo::bar::baz");
573 let test_fst = string_to_ts("foo::bar");
574 let test_snd = string_to_ts("::baz");
575 let eq_res = TokenStream::from_streams(vec![test_fst, test_snd]);
576 assert_eq!(test_res.trees().count(), 5);
577 assert_eq!(eq_res.trees().count(), 5);
578 assert_eq!(test_res.eq_unspanned(&eq_res), true);
583 fn test_to_from_bijection() {
585 let test_start = string_to_ts("foo::bar(baz)");
586 let test_end = test_start.trees().collect();
587 assert_eq!(test_start, test_end)
594 let test_res = string_to_ts("foo");
595 let test_eqs = string_to_ts("foo");
596 assert_eq!(test_res, test_eqs)
603 let test_res = string_to_ts("::bar::baz");
604 let test_eqs = string_to_ts("::bar::baz");
605 assert_eq!(test_res, test_eqs)
612 let test_res = string_to_ts("");
613 let test_eqs = string_to_ts("");
614 assert_eq!(test_res, test_eqs)
621 let test_res = string_to_ts("::bar::baz");
622 let test_eqs = string_to_ts("bar::baz");
623 assert_eq!(test_res == test_eqs, false)
630 let test_res = string_to_ts("(bar,baz)");
631 let test_eqs = string_to_ts("bar,baz");
632 assert_eq!(test_res == test_eqs, false)
639 let test0: TokenStream = Vec::<TokenTree>::new().into_iter().collect();
640 let test1: TokenStream =
641 TokenTree::Token(sp(0, 1), Token::Ident(Ident::from_str("a"), false)).into();
642 let test2 = string_to_ts("foo(bar::baz)");
644 assert_eq!(test0.is_empty(), true);
645 assert_eq!(test1.is_empty(), false);
646 assert_eq!(test2.is_empty(), false);
651 fn test_dotdotdot() {
652 let mut builder = TokenStreamBuilder::new();
653 builder.push(TokenTree::Token(sp(0, 1), Token::Dot).joint());
654 builder.push(TokenTree::Token(sp(1, 2), Token::Dot).joint());
655 builder.push(TokenTree::Token(sp(2, 3), Token::Dot));
656 let stream = builder.build();
657 assert!(stream.eq_unspanned(&string_to_ts("...")));
658 assert_eq!(stream.trees().count(), 1);