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.
16 use crate::parse::token::{self, DelimToken, Token, TokenKind};
17 use crate::print::pprust;
19 use syntax_pos::{BytePos, Span, DUMMY_SP};
20 #[cfg(target_arch = "x86_64")]
21 use rustc_data_structures::static_assert_size;
22 use rustc_data_structures::sync::Lrc;
23 use rustc_serialize::{Decoder, Decodable, Encoder, Encodable};
24 use smallvec::{SmallVec, smallvec};
26 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)]
47 /// A delimited sequence of token trees
48 Delimited(DelimSpan, DelimToken, TokenStream),
51 // Ensure all fields of `TokenTree` is `Send` and `Sync`.
52 #[cfg(parallel_compiler)]
56 DelimSpan: Send + Sync,
57 DelimToken: Send + Sync,
58 TokenStream: Send + Sync,
62 /// Checks if this TokenTree is equal to the other, regardless of span information.
63 pub fn eq_unspanned(&self, other: &TokenTree) -> bool {
65 (TokenTree::Token(token), TokenTree::Token(token2)) => token.kind == token2.kind,
66 (TokenTree::Delimited(_, delim, tts), TokenTree::Delimited(_, delim2, tts2)) => {
67 delim == delim2 && tts.eq_unspanned(&tts2)
73 // See comments in `Nonterminal::to_tokenstream` for why we care about
74 // *probably* equal here rather than actual equality
76 // This is otherwise the same as `eq_unspanned`, only recursing with a
78 pub fn probably_equal_for_proc_macro(&self, other: &TokenTree) -> bool {
80 (TokenTree::Token(token), TokenTree::Token(token2)) => {
81 token.probably_equal_for_proc_macro(token2)
83 (TokenTree::Delimited(_, delim, tts), TokenTree::Delimited(_, delim2, tts2)) => {
84 delim == delim2 && tts.probably_equal_for_proc_macro(&tts2)
90 /// Retrieves the TokenTree's span.
91 pub fn span(&self) -> Span {
93 TokenTree::Token(token) => token.span,
94 TokenTree::Delimited(sp, ..) => sp.entire(),
98 /// Modify the `TokenTree`'s span in-place.
99 pub fn set_span(&mut self, span: Span) {
101 TokenTree::Token(token) => token.span = span,
102 TokenTree::Delimited(dspan, ..) => *dspan = DelimSpan::from_single(span),
106 pub fn joint(self) -> TokenStream {
107 TokenStream::new(vec![(self, Joint)])
110 pub fn token(kind: TokenKind, span: Span) -> TokenTree {
111 TokenTree::Token(Token::new(kind, span))
114 /// Returns the opening delimiter as a token tree.
115 pub fn open_tt(span: Span, delim: DelimToken) -> TokenTree {
116 let open_span = if span.is_dummy() {
119 span.with_hi(span.lo() + BytePos(delim.len() as u32))
121 TokenTree::token(token::OpenDelim(delim), open_span)
124 /// Returns the closing delimiter as a token tree.
125 pub fn close_tt(span: Span, delim: DelimToken) -> TokenTree {
126 let close_span = if span.is_dummy() {
129 span.with_lo(span.hi() - BytePos(delim.len() as u32))
131 TokenTree::token(token::CloseDelim(delim), close_span)
135 /// A `TokenStream` is an abstract sequence of tokens, organized into `TokenTree`s.
137 /// The goal is for procedural macros to work with `TokenStream`s and `TokenTree`s
138 /// instead of a representation of the abstract syntax tree.
139 /// Today's `TokenTree`s can still contain AST via `token::Interpolated` for back-compat.
141 /// The use of `Option` is an optimization that avoids the need for an
142 /// allocation when the stream is empty. However, it is not guaranteed that an
143 /// empty stream is represented with `None`; it may be represented as a `Some`
144 /// around an empty `Vec`.
145 #[derive(Clone, Debug)]
146 pub struct TokenStream(pub Option<Lrc<Vec<TreeAndJoint>>>);
148 pub type TreeAndJoint = (TokenTree, IsJoint);
150 // `TokenStream` is used a lot. Make sure it doesn't unintentionally get bigger.
151 #[cfg(target_arch = "x86_64")]
152 static_assert_size!(TokenStream, 8);
154 #[derive(Clone, Copy, Debug, PartialEq)]
163 /// Given a `TokenStream` with a `Stream` of only two arguments, return a new `TokenStream`
164 /// separating the two arguments with a comma for diagnostic suggestions.
165 pub(crate) fn add_comma(&self) -> Option<(TokenStream, Span)> {
166 // Used to suggest if a user writes `foo!(a b);`
167 if let Some(ref stream) = self.0 {
168 let mut suggestion = None;
169 let mut iter = stream.iter().enumerate().peekable();
170 while let Some((pos, ts)) = iter.next() {
171 if let Some((_, next)) = iter.peek() {
172 let sp = match (&ts, &next) {
173 (_, (TokenTree::Token(Token { kind: token::Comma, .. }), _)) => continue,
174 ((TokenTree::Token(token_left), NonJoint),
175 (TokenTree::Token(token_right), _))
176 if ((token_left.is_ident() && !token_left.is_reserved_ident())
177 || token_left.is_lit()) &&
178 ((token_right.is_ident() && !token_right.is_reserved_ident())
179 || token_right.is_lit()) => token_left.span,
180 ((TokenTree::Delimited(sp, ..), NonJoint), _) => sp.entire(),
183 let sp = sp.shrink_to_hi();
184 let comma = (TokenTree::token(token::Comma, sp), 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<T: Into<TokenStream>> iter::FromIterator<T> for TokenStream {
214 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
215 TokenStream::from_streams(iter.into_iter().map(Into::into).collect::<SmallVec<_>>())
219 impl Eq for TokenStream {}
221 impl PartialEq<TokenStream> for TokenStream {
222 fn eq(&self, other: &TokenStream) -> bool {
223 self.trees().eq(other.trees())
228 pub fn len(&self) -> usize {
229 if let Some(ref slice) = self.0 {
236 pub fn empty() -> TokenStream {
240 pub fn is_empty(&self) -> bool {
243 Some(ref stream) => stream.is_empty(),
247 pub(crate) fn from_streams(mut streams: SmallVec<[TokenStream; 2]>) -> TokenStream {
248 match streams.len() {
249 0 => TokenStream::empty(),
250 1 => streams.pop().unwrap(),
252 // rust-lang/rust#57735: pre-allocate vector to avoid
253 // quadratic blow-up due to on-the-fly reallocations.
254 let tree_count = streams.iter()
255 .map(|ts| match &ts.0 { None => 0, Some(s) => s.len() })
257 let mut vec = Vec::with_capacity(tree_count);
259 for stream in streams {
262 Some(stream2) => vec.extend(stream2.iter().cloned()),
265 TokenStream::new(vec)
270 pub fn new(streams: Vec<TreeAndJoint>) -> TokenStream {
271 match streams.len() {
272 0 => TokenStream(None),
273 _ => TokenStream(Some(Lrc::new(streams))),
277 pub fn append_to_tree_and_joint_vec(self, vec: &mut Vec<TreeAndJoint>) {
278 if let Some(stream) = self.0 {
279 vec.extend(stream.iter().cloned());
283 pub fn trees(&self) -> Cursor {
284 self.clone().into_trees()
287 pub fn into_trees(self) -> Cursor {
291 /// Compares two `TokenStream`s, checking equality without regarding span information.
292 pub fn eq_unspanned(&self, other: &TokenStream) -> bool {
293 let mut t1 = self.trees();
294 let mut t2 = other.trees();
295 for (t1, t2) in t1.by_ref().zip(t2.by_ref()) {
296 if !t1.eq_unspanned(&t2) {
300 t1.next().is_none() && t2.next().is_none()
303 // See comments in `Nonterminal::to_tokenstream` for why we care about
304 // *probably* equal here rather than actual equality
306 // This is otherwise the same as `eq_unspanned`, only recursing with a
308 pub fn probably_equal_for_proc_macro(&self, other: &TokenStream) -> bool {
309 // When checking for `probably_eq`, we ignore certain tokens that aren't
310 // preserved in the AST. Because they are not preserved, the pretty
311 // printer arbitrarily adds or removes them when printing as token
312 // streams, making a comparison between a token stream generated from an
313 // AST and a token stream which was parsed into an AST more reliable.
314 fn semantic_tree(tree: &TokenTree) -> bool {
315 if let TokenTree::Token(token) = tree {
317 // The pretty printer tends to add trailing commas to
318 // everything, and in particular, after struct fields.
320 // The pretty printer emits `NoDelim` as whitespace.
321 | token::OpenDelim(DelimToken::NoDelim)
322 | token::CloseDelim(DelimToken::NoDelim)
323 // The pretty printer collapses many semicolons into one.
325 // The pretty printer collapses whitespace arbitrarily and can
326 // introduce whitespace from `NoDelim`.
328 // The pretty printer can turn `$crate` into `::crate_name`
329 | token::ModSep = token.kind {
336 let mut t1 = self.trees().filter(semantic_tree);
337 let mut t2 = other.trees().filter(semantic_tree);
338 for (t1, t2) in t1.by_ref().zip(t2.by_ref()) {
339 if !t1.probably_equal_for_proc_macro(&t2) {
343 t1.next().is_none() && t2.next().is_none()
346 pub fn map_enumerated<F: FnMut(usize, TokenTree) -> TokenTree>(self, mut f: F) -> TokenStream {
347 TokenStream(self.0.map(|stream| {
352 .map(|(i, (tree, is_joint))| (f(i, tree.clone()), *is_joint))
357 pub fn map<F: FnMut(TokenTree) -> TokenTree>(self, mut f: F) -> TokenStream {
358 TokenStream(self.0.map(|stream| {
362 .map(|(tree, is_joint)| (f(tree.clone()), *is_joint))
367 fn first_tree_and_joint(&self) -> Option<TreeAndJoint> {
368 self.0.as_ref().map(|stream| {
369 stream.first().unwrap().clone()
373 fn last_tree_if_joint(&self) -> Option<TokenTree> {
376 Some(ref stream) => {
377 if let (tree, Joint) = stream.last().unwrap() {
387 // 99.5%+ of the time we have 1 or 2 elements in this vector.
389 pub struct TokenStreamBuilder(SmallVec<[TokenStream; 2]>);
391 impl TokenStreamBuilder {
392 pub fn new() -> TokenStreamBuilder {
393 TokenStreamBuilder(SmallVec::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_token)) = last_tree_if_joint {
400 if let Some((TokenTree::Token(token), is_joint)) = stream.first_tree_and_joint() {
401 if let Some(glued_tok) = last_token.glue(&token) {
402 let last_stream = self.0.pop().unwrap();
403 self.push_all_but_last_tree(&last_stream);
404 let glued_tt = TokenTree::Token(glued_tok);
405 let glued_tokenstream = TokenStream::new(vec![(glued_tt, is_joint)]);
406 self.0.push(glued_tokenstream);
407 self.push_all_but_first_tree(&stream);
415 pub fn build(self) -> TokenStream {
416 TokenStream::from_streams(self.0)
419 fn push_all_but_last_tree(&mut self, stream: &TokenStream) {
420 if let Some(ref streams) = stream.0 {
421 let len = streams.len();
424 _ => self.0.push(TokenStream(Some(Lrc::new(streams[0 .. len - 1].to_vec())))),
429 fn push_all_but_first_tree(&mut self, stream: &TokenStream) {
430 if let Some(ref streams) = stream.0 {
431 let len = streams.len();
434 _ => self.0.push(TokenStream(Some(Lrc::new(streams[1 .. len].to_vec())))),
442 pub stream: TokenStream,
446 impl Iterator for Cursor {
447 type Item = TokenTree;
449 fn next(&mut self) -> Option<TokenTree> {
450 self.next_with_joint().map(|(tree, _)| tree)
455 fn new(stream: TokenStream) -> Self {
456 Cursor { stream, index: 0 }
459 pub fn next_with_joint(&mut self) -> Option<TreeAndJoint> {
460 match self.stream.0 {
462 Some(ref stream) => {
463 if self.index < stream.len() {
465 Some(stream[self.index - 1].clone())
473 pub fn append(&mut self, new_stream: TokenStream) {
474 if new_stream.is_empty() {
477 let index = self.index;
478 let stream = mem::replace(&mut self.stream, TokenStream(None));
479 *self = TokenStream::from_streams(smallvec![stream, new_stream]).into_trees();
483 pub fn look_ahead(&self, n: usize) -> Option<TokenTree> {
484 match self.stream.0 {
486 Some(ref stream) => stream[self.index ..].get(n).map(|(tree, _)| tree.clone()),
491 impl fmt::Display for TokenStream {
492 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
493 f.write_str(&pprust::tts_to_string(self.clone()))
497 impl Encodable for TokenStream {
498 fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), E::Error> {
499 self.trees().collect::<Vec<_>>().encode(encoder)
503 impl Decodable for TokenStream {
504 fn decode<D: Decoder>(decoder: &mut D) -> Result<TokenStream, D::Error> {
505 Vec::<TokenTree>::decode(decoder).map(|vec| vec.into_iter().collect())
509 #[derive(Debug, Copy, Clone, PartialEq, RustcEncodable, RustcDecodable)]
510 pub struct DelimSpan {
516 pub fn from_single(sp: Span) -> Self {
523 pub fn from_pair(open: Span, close: Span) -> Self {
524 DelimSpan { open, close }
527 pub fn dummy() -> Self {
528 Self::from_single(DUMMY_SP)
531 pub fn entire(self) -> Span {
532 self.open.with_hi(self.close.hi())