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 //! `TokenStream`s 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, TokenKind};
20 use crate::print::pprust;
22 use syntax_pos::{BytePos, Span, DUMMY_SP};
23 #[cfg(target_arch = "x86_64")]
24 use rustc_data_structures::static_assert_size;
25 use rustc_data_structures::sync::Lrc;
26 use rustc_serialize::{Decoder, Decodable, Encoder, Encodable};
27 use smallvec::{SmallVec, smallvec};
30 use std::{fmt, iter, mem};
35 /// When the main rust parser encounters a syntax-extension invocation, it
36 /// parses the arguments to the invocation as a token-tree. This is a very
37 /// loose structure, such that all sorts of different AST-fragments can
38 /// be passed to syntax extensions using a uniform type.
40 /// If the syntax extension is an MBE macro, it will attempt to match its
41 /// LHS token tree against the provided token tree, and if it finds a
42 /// match, will transcribe the RHS token tree, splicing in any captured
43 /// `macro_parser::matched_nonterminals` into the `SubstNt`s it finds.
45 /// The RHS of an MBE macro is the only place `SubstNt`s are substituted.
46 /// Nothing special happens to misnamed or misplaced `SubstNt`s.
47 #[derive(Debug, Clone, PartialEq, RustcEncodable, RustcDecodable)]
51 /// A delimited sequence of token trees
52 Delimited(DelimSpan, DelimToken, TokenStream),
55 // Ensure all fields of `TokenTree` is `Send` and `Sync`.
56 #[cfg(parallel_compiler)]
60 DelimSpan: Send + Sync,
61 DelimToken: Send + Sync,
62 TokenStream: Send + Sync,
66 /// Use this token tree as a matcher to parse given tts.
67 pub fn parse(cx: &base::ExtCtxt<'_>, mtch: &[quoted::TokenTree], tts: TokenStream)
68 -> macro_parser::NamedParseResult {
69 // `None` is because we're not interpolating
70 let directory = Directory {
71 path: Cow::from(cx.current_expansion.module.directory.as_path()),
72 ownership: cx.current_expansion.directory_ownership,
74 macro_parser::parse(cx.parse_sess(), tts, mtch, Some(directory), true)
77 /// Checks if this TokenTree is equal to the other, regardless of span information.
78 pub fn eq_unspanned(&self, other: &TokenTree) -> bool {
80 (TokenTree::Token(token), TokenTree::Token(token2)) => token.kind == token2.kind,
81 (TokenTree::Delimited(_, delim, tts), TokenTree::Delimited(_, delim2, tts2)) => {
82 delim == delim2 && tts.eq_unspanned(&tts2)
88 // See comments in `Nonterminal::to_tokenstream` for why we care about
89 // *probably* equal here rather than actual equality
91 // This is otherwise the same as `eq_unspanned`, only recursing with a
93 pub fn probably_equal_for_proc_macro(&self, other: &TokenTree) -> bool {
95 (TokenTree::Token(token), TokenTree::Token(token2)) => {
96 token.probably_equal_for_proc_macro(token2)
98 (TokenTree::Delimited(_, delim, tts), TokenTree::Delimited(_, delim2, tts2)) => {
99 delim == delim2 && tts.probably_equal_for_proc_macro(&tts2)
105 /// Retrieves the TokenTree's span.
106 pub fn span(&self) -> Span {
108 TokenTree::Token(token) => token.span,
109 TokenTree::Delimited(sp, ..) => sp.entire(),
113 /// Modify the `TokenTree`'s span in-place.
114 pub fn set_span(&mut self, span: Span) {
116 TokenTree::Token(token) => token.span = span,
117 TokenTree::Delimited(dspan, ..) => *dspan = DelimSpan::from_single(span),
121 pub fn joint(self) -> TokenStream {
122 TokenStream::new(vec![(self, Joint)])
125 pub fn token(kind: TokenKind, span: Span) -> TokenTree {
126 TokenTree::Token(Token::new(kind, span))
129 /// Returns the opening delimiter as a token tree.
130 pub fn open_tt(span: Span, delim: DelimToken) -> TokenTree {
131 let open_span = if span.is_dummy() {
134 span.with_hi(span.lo() + BytePos(delim.len() as u32))
136 TokenTree::token(token::OpenDelim(delim), open_span)
139 /// Returns the closing delimiter as a token tree.
140 pub fn close_tt(span: Span, delim: DelimToken) -> TokenTree {
141 let close_span = if span.is_dummy() {
144 span.with_lo(span.hi() - BytePos(delim.len() as u32))
146 TokenTree::token(token::CloseDelim(delim), close_span)
150 /// A `TokenStream` is an abstract sequence of tokens, organized into `TokenTree`s.
152 /// The goal is for procedural macros to work with `TokenStream`s and `TokenTree`s
153 /// instead of a representation of the abstract syntax tree.
154 /// Today's `TokenTree`s can still contain AST via `token::Interpolated` for back-compat.
156 /// The use of `Option` is an optimization that avoids the need for an
157 /// allocation when the stream is empty. However, it is not guaranteed that an
158 /// empty stream is represented with `None`; it may be represented as a `Some`
159 /// around an empty `Vec`.
160 #[derive(Clone, Debug)]
161 pub struct TokenStream(pub Option<Lrc<Vec<TreeAndJoint>>>);
163 pub type TreeAndJoint = (TokenTree, IsJoint);
165 // `TokenStream` is used a lot. Make sure it doesn't unintentionally get bigger.
166 #[cfg(target_arch = "x86_64")]
167 static_assert_size!(TokenStream, 8);
169 #[derive(Clone, Copy, Debug, PartialEq)]
178 /// Given a `TokenStream` with a `Stream` of only two arguments, return a new `TokenStream`
179 /// separating the two arguments with a comma for diagnostic suggestions.
180 pub(crate) fn add_comma(&self) -> Option<(TokenStream, Span)> {
181 // Used to suggest if a user writes `foo!(a b);`
182 if let Some(ref stream) = self.0 {
183 let mut suggestion = None;
184 let mut iter = stream.iter().enumerate().peekable();
185 while let Some((pos, ts)) = iter.next() {
186 if let Some((_, next)) = iter.peek() {
187 let sp = match (&ts, &next) {
188 (_, (TokenTree::Token(Token { kind: token::Comma, .. }), _)) => continue,
189 ((TokenTree::Token(token_left), NonJoint),
190 (TokenTree::Token(token_right), _))
191 if ((token_left.is_ident() && !token_left.is_reserved_ident())
192 || token_left.is_lit()) &&
193 ((token_right.is_ident() && !token_right.is_reserved_ident())
194 || token_right.is_lit()) => token_left.span,
195 ((TokenTree::Delimited(sp, ..), NonJoint), _) => sp.entire(),
198 let sp = sp.shrink_to_hi();
199 let comma = (TokenTree::token(token::Comma, sp), NonJoint);
200 suggestion = Some((pos, comma, sp));
203 if let Some((pos, comma, sp)) = suggestion {
204 let mut new_stream = vec![];
205 let parts = stream.split_at(pos + 1);
206 new_stream.extend_from_slice(parts.0);
207 new_stream.push(comma);
208 new_stream.extend_from_slice(parts.1);
209 return Some((TokenStream::new(new_stream), sp));
216 impl From<TokenTree> for TokenStream {
217 fn from(tree: TokenTree) -> TokenStream {
218 TokenStream::new(vec![(tree, NonJoint)])
222 impl From<TokenTree> for TreeAndJoint {
223 fn from(tree: TokenTree) -> TreeAndJoint {
228 impl<T: Into<TokenStream>> iter::FromIterator<T> for TokenStream {
229 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
230 TokenStream::from_streams(iter.into_iter().map(Into::into).collect::<SmallVec<_>>())
234 impl Eq for TokenStream {}
236 impl PartialEq<TokenStream> for TokenStream {
237 fn eq(&self, other: &TokenStream) -> bool {
238 self.trees().eq(other.trees())
243 pub fn len(&self) -> usize {
244 if let Some(ref slice) = self.0 {
251 pub fn empty() -> TokenStream {
255 pub fn is_empty(&self) -> bool {
258 Some(ref stream) => stream.is_empty(),
262 pub(crate) fn from_streams(mut streams: SmallVec<[TokenStream; 2]>) -> TokenStream {
263 match streams.len() {
264 0 => TokenStream::empty(),
265 1 => streams.pop().unwrap(),
267 // rust-lang/rust#57735: pre-allocate vector to avoid
268 // quadratic blow-up due to on-the-fly reallocations.
269 let tree_count = streams.iter()
270 .map(|ts| match &ts.0 { None => 0, Some(s) => s.len() })
272 let mut vec = Vec::with_capacity(tree_count);
274 for stream in streams {
277 Some(stream2) => vec.extend(stream2.iter().cloned()),
280 TokenStream::new(vec)
285 pub fn new(streams: Vec<TreeAndJoint>) -> TokenStream {
286 match streams.len() {
287 0 => TokenStream(None),
288 _ => TokenStream(Some(Lrc::new(streams))),
292 pub fn append_to_tree_and_joint_vec(self, vec: &mut Vec<TreeAndJoint>) {
293 if let Some(stream) = self.0 {
294 vec.extend(stream.iter().cloned());
298 pub fn trees(&self) -> Cursor {
299 self.clone().into_trees()
302 pub fn into_trees(self) -> Cursor {
306 /// Compares two `TokenStream`s, checking equality without regarding span information.
307 pub fn eq_unspanned(&self, other: &TokenStream) -> bool {
308 let mut t1 = self.trees();
309 let mut t2 = other.trees();
310 for (t1, t2) in t1.by_ref().zip(t2.by_ref()) {
311 if !t1.eq_unspanned(&t2) {
315 t1.next().is_none() && t2.next().is_none()
318 // See comments in `Nonterminal::to_tokenstream` for why we care about
319 // *probably* equal here rather than actual equality
321 // This is otherwise the same as `eq_unspanned`, only recursing with a
323 pub fn probably_equal_for_proc_macro(&self, other: &TokenStream) -> bool {
324 // When checking for `probably_eq`, we ignore certain tokens that aren't
325 // preserved in the AST. Because they are not preserved, the pretty
326 // printer arbitrarily adds or removes them when printing as token
327 // streams, making a comparison between a token stream generated from an
328 // AST and a token stream which was parsed into an AST more reliable.
329 fn semantic_tree(tree: &TokenTree) -> bool {
330 if let TokenTree::Token(token) = tree {
332 // The pretty printer tends to add trailing commas to
333 // everything, and in particular, after struct fields.
335 // The pretty printer emits `NoDelim` as whitespace.
336 | token::OpenDelim(DelimToken::NoDelim)
337 | token::CloseDelim(DelimToken::NoDelim)
338 // The pretty printer collapses many semicolons into one.
340 // The pretty printer collapses whitespace arbitrarily and can
341 // introduce whitespace from `NoDelim`.
343 // The pretty printer can turn `$crate` into `::crate_name`
344 | token::ModSep = token.kind {
351 let mut t1 = self.trees().filter(semantic_tree);
352 let mut t2 = other.trees().filter(semantic_tree);
353 for (t1, t2) in t1.by_ref().zip(t2.by_ref()) {
354 if !t1.probably_equal_for_proc_macro(&t2) {
358 t1.next().is_none() && t2.next().is_none()
361 pub fn map_enumerated<F: FnMut(usize, TokenTree) -> TokenTree>(self, mut f: F) -> TokenStream {
362 TokenStream(self.0.map(|stream| {
367 .map(|(i, (tree, is_joint))| (f(i, tree.clone()), *is_joint))
372 pub fn map<F: FnMut(TokenTree) -> TokenTree>(self, mut f: F) -> TokenStream {
373 TokenStream(self.0.map(|stream| {
377 .map(|(tree, is_joint)| (f(tree.clone()), *is_joint))
382 fn first_tree_and_joint(&self) -> Option<TreeAndJoint> {
383 self.0.as_ref().map(|stream| {
384 stream.first().unwrap().clone()
388 fn last_tree_if_joint(&self) -> Option<TokenTree> {
391 Some(ref stream) => {
392 if let (tree, Joint) = stream.last().unwrap() {
402 // 99.5%+ of the time we have 1 or 2 elements in this vector.
404 pub struct TokenStreamBuilder(SmallVec<[TokenStream; 2]>);
406 impl TokenStreamBuilder {
407 pub fn new() -> TokenStreamBuilder {
408 TokenStreamBuilder(SmallVec::new())
411 pub fn push<T: Into<TokenStream>>(&mut self, stream: T) {
412 let stream = stream.into();
413 let last_tree_if_joint = self.0.last().and_then(TokenStream::last_tree_if_joint);
414 if let Some(TokenTree::Token(last_token)) = last_tree_if_joint {
415 if let Some((TokenTree::Token(token), is_joint)) = stream.first_tree_and_joint() {
416 if let Some(glued_tok) = last_token.glue(&token) {
417 let last_stream = self.0.pop().unwrap();
418 self.push_all_but_last_tree(&last_stream);
419 let glued_tt = TokenTree::Token(glued_tok);
420 let glued_tokenstream = TokenStream::new(vec![(glued_tt, is_joint)]);
421 self.0.push(glued_tokenstream);
422 self.push_all_but_first_tree(&stream);
430 pub fn build(self) -> TokenStream {
431 TokenStream::from_streams(self.0)
434 fn push_all_but_last_tree(&mut self, stream: &TokenStream) {
435 if let Some(ref streams) = stream.0 {
436 let len = streams.len();
439 _ => self.0.push(TokenStream(Some(Lrc::new(streams[0 .. len - 1].to_vec())))),
444 fn push_all_but_first_tree(&mut self, stream: &TokenStream) {
445 if let Some(ref streams) = stream.0 {
446 let len = streams.len();
449 _ => self.0.push(TokenStream(Some(Lrc::new(streams[1 .. len].to_vec())))),
457 pub stream: TokenStream,
461 impl Iterator for Cursor {
462 type Item = TokenTree;
464 fn next(&mut self) -> Option<TokenTree> {
465 self.next_with_joint().map(|(tree, _)| tree)
470 fn new(stream: TokenStream) -> Self {
471 Cursor { stream, index: 0 }
474 pub fn next_with_joint(&mut self) -> Option<TreeAndJoint> {
475 match self.stream.0 {
477 Some(ref stream) => {
478 if self.index < stream.len() {
480 Some(stream[self.index - 1].clone())
488 pub fn append(&mut self, new_stream: TokenStream) {
489 if new_stream.is_empty() {
492 let index = self.index;
493 let stream = mem::replace(&mut self.stream, TokenStream(None));
494 *self = TokenStream::from_streams(smallvec![stream, new_stream]).into_trees();
498 pub fn look_ahead(&self, n: usize) -> Option<TokenTree> {
499 match self.stream.0 {
501 Some(ref stream) => stream[self.index ..].get(n).map(|(tree, _)| tree.clone()),
506 impl fmt::Display for TokenStream {
507 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
508 f.write_str(&pprust::tts_to_string(self.clone()))
512 impl Encodable for TokenStream {
513 fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), E::Error> {
514 self.trees().collect::<Vec<_>>().encode(encoder)
518 impl Decodable for TokenStream {
519 fn decode<D: Decoder>(decoder: &mut D) -> Result<TokenStream, D::Error> {
520 Vec::<TokenTree>::decode(decoder).map(|vec| vec.into_iter().collect())
524 #[derive(Debug, Copy, Clone, PartialEq, RustcEncodable, RustcDecodable)]
525 pub struct DelimSpan {
531 pub fn from_single(sp: Span) -> Self {
538 pub fn from_pair(open: Span, close: Span) -> Self {
539 DelimSpan { open, close }
542 pub fn dummy() -> Self {
543 Self::from_single(DUMMY_SP)
546 pub fn entire(self) -> Span {
547 self.open.with_hi(self.close.hi())