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, 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)
152 /// A `TokenStream` is an abstract sequence of tokens, organized into `TokenTree`s.
153 /// The goal is for procedural macros to work with `TokenStream`s and `TokenTree`s
154 /// instead of a representation of the abstract syntax tree.
155 /// Today's `TokenTree`s can still contain AST via `token::Interpolated` for back-compat.
157 /// The use of `Option` is an optimization that avoids the need for an
158 /// allocation when the stream is empty. However, it is not guaranteed that an
159 /// empty stream is represented with `None`; it may be represented as a `Some`
160 /// around an empty `Vec`.
161 #[derive(Clone, Debug)]
162 pub struct TokenStream(pub Option<Lrc<Vec<TreeAndJoint>>>);
164 pub type TreeAndJoint = (TokenTree, IsJoint);
166 // `TokenStream` is used a lot. Make sure it doesn't unintentionally get bigger.
167 #[cfg(target_arch = "x86_64")]
168 static_assert_size!(TokenStream, 8);
170 #[derive(Clone, Copy, Debug, PartialEq)]
179 /// Given a `TokenStream` with a `Stream` of only two arguments, return a new `TokenStream`
180 /// separating the two arguments with a comma for diagnostic suggestions.
181 pub(crate) fn add_comma(&self) -> Option<(TokenStream, Span)> {
182 // Used to suggest if a user writes `foo!(a b);`
183 if let Some(ref stream) = self.0 {
184 let mut suggestion = None;
185 let mut iter = stream.iter().enumerate().peekable();
186 while let Some((pos, ts)) = iter.next() {
187 if let Some((_, next)) = iter.peek() {
188 let sp = match (&ts, &next) {
189 (_, (TokenTree::Token(Token { kind: token::Comma, .. }), _)) => continue,
190 ((TokenTree::Token(token_left), NonJoint),
191 (TokenTree::Token(token_right), _))
192 if ((token_left.is_ident() && !token_left.is_reserved_ident())
193 || token_left.is_lit()) &&
194 ((token_right.is_ident() && !token_right.is_reserved_ident())
195 || token_right.is_lit()) => token_left.span,
196 ((TokenTree::Delimited(sp, ..), NonJoint), _) => sp.entire(),
199 let sp = sp.shrink_to_hi();
200 let comma = (TokenTree::token(token::Comma, sp), NonJoint);
201 suggestion = Some((pos, comma, sp));
204 if let Some((pos, comma, sp)) = suggestion {
205 let mut new_stream = vec![];
206 let parts = stream.split_at(pos + 1);
207 new_stream.extend_from_slice(parts.0);
208 new_stream.push(comma);
209 new_stream.extend_from_slice(parts.1);
210 return Some((TokenStream::new(new_stream), sp));
217 impl From<TokenTree> for TokenStream {
218 fn from(tree: TokenTree) -> TokenStream {
219 TokenStream::new(vec![(tree, NonJoint)])
223 impl From<TokenTree> for TreeAndJoint {
224 fn from(tree: TokenTree) -> TreeAndJoint {
229 impl<T: Into<TokenStream>> iter::FromIterator<T> for TokenStream {
230 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
231 TokenStream::from_streams(iter.into_iter().map(Into::into).collect::<SmallVec<_>>())
235 impl Eq for TokenStream {}
237 impl PartialEq<TokenStream> for TokenStream {
238 fn eq(&self, other: &TokenStream) -> bool {
239 self.trees().eq(other.trees())
244 pub fn len(&self) -> usize {
245 if let Some(ref slice) = self.0 {
252 pub fn empty() -> TokenStream {
256 pub fn is_empty(&self) -> bool {
259 Some(ref stream) => stream.is_empty(),
263 pub(crate) fn from_streams(mut streams: SmallVec<[TokenStream; 2]>) -> TokenStream {
264 match streams.len() {
265 0 => TokenStream::empty(),
266 1 => streams.pop().unwrap(),
268 // rust-lang/rust#57735: pre-allocate vector to avoid
269 // quadratic blow-up due to on-the-fly reallocations.
270 let tree_count = streams.iter()
271 .map(|ts| match &ts.0 { None => 0, Some(s) => s.len() })
273 let mut vec = Vec::with_capacity(tree_count);
275 for stream in streams {
278 Some(stream2) => vec.extend(stream2.iter().cloned()),
281 TokenStream::new(vec)
286 pub fn new(streams: Vec<TreeAndJoint>) -> TokenStream {
287 match streams.len() {
288 0 => TokenStream(None),
289 _ => TokenStream(Some(Lrc::new(streams))),
293 pub fn append_to_tree_and_joint_vec(self, vec: &mut Vec<TreeAndJoint>) {
294 if let Some(stream) = self.0 {
295 vec.extend(stream.iter().cloned());
299 pub fn trees(&self) -> Cursor {
300 self.clone().into_trees()
303 pub fn into_trees(self) -> Cursor {
307 /// Compares two TokenStreams, checking equality without regarding span information.
308 pub fn eq_unspanned(&self, other: &TokenStream) -> bool {
309 let mut t1 = self.trees();
310 let mut t2 = other.trees();
311 for (t1, t2) in t1.by_ref().zip(t2.by_ref()) {
312 if !t1.eq_unspanned(&t2) {
316 t1.next().is_none() && t2.next().is_none()
319 // See comments in `Nonterminal::to_tokenstream` for why we care about
320 // *probably* equal here rather than actual equality
322 // This is otherwise the same as `eq_unspanned`, only recursing with a
324 pub fn probably_equal_for_proc_macro(&self, other: &TokenStream) -> bool {
325 // When checking for `probably_eq`, we ignore certain tokens that aren't
326 // preserved in the AST. Because they are not preserved, the pretty
327 // printer arbitrarily adds or removes them when printing as token
328 // streams, making a comparison between a token stream generated from an
329 // AST and a token stream which was parsed into an AST more reliable.
330 fn semantic_tree(tree: &TokenTree) -> bool {
331 if let TokenTree::Token(token) = tree {
333 // The pretty printer tends to add trailing commas to
334 // everything, and in particular, after struct fields.
336 // The pretty printer emits `NoDelim` as whitespace.
337 | token::OpenDelim(DelimToken::NoDelim)
338 | token::CloseDelim(DelimToken::NoDelim)
339 // The pretty printer collapses many semicolons into one.
341 // The pretty printer collapses whitespace arbitrarily and can
342 // introduce whitespace from `NoDelim`.
344 // The pretty printer can turn `$crate` into `::crate_name`
345 | token::ModSep = token.kind {
352 let mut t1 = self.trees().filter(semantic_tree);
353 let mut t2 = other.trees().filter(semantic_tree);
354 for (t1, t2) in t1.by_ref().zip(t2.by_ref()) {
355 if !t1.probably_equal_for_proc_macro(&t2) {
359 t1.next().is_none() && t2.next().is_none()
362 pub fn map_enumerated<F: FnMut(usize, TokenTree) -> TokenTree>(self, mut f: F) -> TokenStream {
363 TokenStream(self.0.map(|stream| {
368 .map(|(i, (tree, is_joint))| (f(i, tree.clone()), *is_joint))
373 pub fn map<F: FnMut(TokenTree) -> TokenTree>(self, mut f: F) -> TokenStream {
374 TokenStream(self.0.map(|stream| {
378 .map(|(tree, is_joint)| (f(tree.clone()), *is_joint))
383 fn first_tree_and_joint(&self) -> Option<TreeAndJoint> {
384 self.0.as_ref().map(|stream| {
385 stream.first().unwrap().clone()
389 fn last_tree_if_joint(&self) -> Option<TokenTree> {
392 Some(ref stream) => {
393 if let (tree, Joint) = stream.last().unwrap() {
403 // 99.5%+ of the time we have 1 or 2 elements in this vector.
405 pub struct TokenStreamBuilder(SmallVec<[TokenStream; 2]>);
407 impl TokenStreamBuilder {
408 pub fn new() -> TokenStreamBuilder {
409 TokenStreamBuilder(SmallVec::new())
412 pub fn push<T: Into<TokenStream>>(&mut self, stream: T) {
413 let stream = stream.into();
414 let last_tree_if_joint = self.0.last().and_then(TokenStream::last_tree_if_joint);
415 if let Some(TokenTree::Token(last_token)) = last_tree_if_joint {
416 if let Some((TokenTree::Token(token), is_joint)) = stream.first_tree_and_joint() {
417 if let Some(glued_tok) = last_token.glue(&token) {
418 let last_stream = self.0.pop().unwrap();
419 self.push_all_but_last_tree(&last_stream);
420 let glued_tt = TokenTree::Token(glued_tok);
421 let glued_tokenstream = TokenStream::new(vec![(glued_tt, is_joint)]);
422 self.0.push(glued_tokenstream);
423 self.push_all_but_first_tree(&stream);
431 pub fn build(self) -> TokenStream {
432 TokenStream::from_streams(self.0)
435 fn push_all_but_last_tree(&mut self, stream: &TokenStream) {
436 if let Some(ref streams) = stream.0 {
437 let len = streams.len();
440 _ => self.0.push(TokenStream(Some(Lrc::new(streams[0 .. len - 1].to_vec())))),
445 fn push_all_but_first_tree(&mut self, stream: &TokenStream) {
446 if let Some(ref streams) = stream.0 {
447 let len = streams.len();
450 _ => self.0.push(TokenStream(Some(Lrc::new(streams[1 .. len].to_vec())))),
458 pub stream: TokenStream,
462 impl Iterator for Cursor {
463 type Item = TokenTree;
465 fn next(&mut self) -> Option<TokenTree> {
466 self.next_with_joint().map(|(tree, _)| tree)
471 fn new(stream: TokenStream) -> Self {
472 Cursor { stream, index: 0 }
475 pub fn next_with_joint(&mut self) -> Option<TreeAndJoint> {
476 match self.stream.0 {
478 Some(ref stream) => {
479 if self.index < stream.len() {
481 Some(stream[self.index - 1].clone())
489 pub fn append(&mut self, new_stream: TokenStream) {
490 if new_stream.is_empty() {
493 let index = self.index;
494 let stream = mem::replace(&mut self.stream, TokenStream(None));
495 *self = TokenStream::from_streams(smallvec![stream, new_stream]).into_trees();
499 pub fn look_ahead(&self, n: usize) -> Option<TokenTree> {
500 match self.stream.0 {
502 Some(ref stream) => stream[self.index ..].get(n).map(|(tree, _)| tree.clone()),
507 impl fmt::Display for TokenStream {
508 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
509 f.write_str(&pprust::tokens_to_string(self.clone()))
513 impl Encodable for TokenStream {
514 fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), E::Error> {
515 self.trees().collect::<Vec<_>>().encode(encoder)
519 impl Decodable for TokenStream {
520 fn decode<D: Decoder>(decoder: &mut D) -> Result<TokenStream, D::Error> {
521 Vec::<TokenTree>::decode(decoder).map(|vec| vec.into_iter().collect())
525 #[derive(Debug, Copy, Clone, PartialEq, RustcEncodable, RustcDecodable)]
526 pub struct DelimSpan {
532 pub fn from_single(sp: Span) -> Self {
539 pub fn from_pair(open: Span, close: Span) -> Self {
540 DelimSpan { open, close }
543 pub fn dummy() -> Self {
544 Self::from_single(DUMMY_SP)
547 pub fn entire(self) -> Span {
548 self.open.with_hi(self.close.hi())