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, ExpnId, 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};
32 /// When the main rust parser encounters a syntax-extension invocation, it
33 /// parses the arguments to the invocation as a token-tree. This is a very
34 /// loose structure, such that all sorts of different AST-fragments can
35 /// be passed to syntax extensions using a uniform type.
37 /// If the syntax extension is an MBE macro, it will attempt to match its
38 /// LHS token tree against the provided token tree, and if it finds a
39 /// match, will transcribe the RHS token tree, splicing in any captured
40 /// `macro_parser::matched_nonterminals` into the `SubstNt`s it finds.
42 /// The RHS of an MBE macro is the only place `SubstNt`s are substituted.
43 /// Nothing special happens to misnamed or misplaced `SubstNt`s.
44 #[derive(Debug, Clone, PartialEq, RustcEncodable, RustcDecodable)]
48 /// A delimited sequence of token trees
49 Delimited(DelimSpan, DelimToken, TokenStream),
52 // Ensure all fields of `TokenTree` is `Send` and `Sync`.
53 #[cfg(parallel_compiler)]
57 DelimSpan: Send + Sync,
58 DelimToken: Send + Sync,
59 TokenStream: Send + Sync,
63 /// Use this token tree as a matcher to parse given tts.
64 pub fn parse(cx: &base::ExtCtxt<'_>, mtch: &[quoted::TokenTree], tts: TokenStream)
65 -> macro_parser::NamedParseResult {
66 // `None` is because we're not interpolating
67 let directory = Directory {
68 path: Cow::from(cx.current_expansion.module.directory.as_path()),
69 ownership: cx.current_expansion.directory_ownership,
71 macro_parser::parse(cx.parse_sess(), tts, mtch, Some(directory), true)
74 /// Checks if this TokenTree is equal to the other, regardless of span information.
75 pub fn eq_unspanned(&self, other: &TokenTree) -> bool {
77 (TokenTree::Token(token), TokenTree::Token(token2)) => token.kind == token2.kind,
78 (TokenTree::Delimited(_, delim, tts), TokenTree::Delimited(_, delim2, tts2)) => {
79 delim == delim2 && tts.eq_unspanned(&tts2)
85 // See comments in `Nonterminal::to_tokenstream` for why we care about
86 // *probably* equal here rather than actual equality
88 // This is otherwise the same as `eq_unspanned`, only recursing with a
90 pub fn probably_equal_for_proc_macro(&self, other: &TokenTree) -> bool {
92 (TokenTree::Token(token), TokenTree::Token(token2)) => {
93 token.probably_equal_for_proc_macro(token2)
95 (TokenTree::Delimited(_, delim, tts), TokenTree::Delimited(_, delim2, tts2)) => {
96 delim == delim2 && tts.probably_equal_for_proc_macro(&tts2)
102 /// Retrieves the TokenTree's span.
103 pub fn span(&self) -> Span {
105 TokenTree::Token(token) => token.span,
106 TokenTree::Delimited(sp, ..) => sp.entire(),
110 /// Modify the `TokenTree`'s span in-place.
111 pub fn set_span(&mut self, span: Span) {
113 TokenTree::Token(token) => token.span = span,
114 TokenTree::Delimited(dspan, ..) => *dspan = DelimSpan::from_single(span),
118 pub fn joint(self) -> TokenStream {
119 TokenStream::new(vec![(self, Joint)])
122 pub fn token(kind: TokenKind, span: Span) -> TokenTree {
123 TokenTree::Token(Token::new(kind, span))
126 /// Returns the opening delimiter as a token tree.
127 pub fn open_tt(span: Span, delim: DelimToken) -> TokenTree {
128 let open_span = if span.is_dummy() {
131 span.with_hi(span.lo() + BytePos(delim.len() as u32))
133 TokenTree::token(token::OpenDelim(delim), open_span)
136 /// Returns the closing delimiter as a token tree.
137 pub fn close_tt(span: Span, delim: DelimToken) -> TokenTree {
138 let close_span = if span.is_dummy() {
141 span.with_lo(span.hi() - BytePos(delim.len() as u32))
143 TokenTree::token(token::CloseDelim(delim), close_span)
149 /// A `TokenStream` is an abstract sequence of tokens, organized into `TokenTree`s.
150 /// The goal is for procedural macros to work with `TokenStream`s and `TokenTree`s
151 /// instead of a representation of the abstract syntax tree.
152 /// Today's `TokenTree`s can still contain AST via `token::Interpolated` for back-compat.
154 /// The use of `Option` is an optimization that avoids the need for an
155 /// allocation when the stream is empty. However, it is not guaranteed that an
156 /// empty stream is represented with `None`; it may be represented as a `Some`
157 /// around an empty `Vec`.
158 #[derive(Clone, Debug)]
159 pub struct TokenStream(pub Option<Lrc<Vec<TreeAndJoint>>>);
161 pub type TreeAndJoint = (TokenTree, IsJoint);
163 // `TokenStream` is used a lot. Make sure it doesn't unintentionally get bigger.
164 #[cfg(target_arch = "x86_64")]
165 static_assert_size!(TokenStream, 8);
167 #[derive(Clone, Copy, Debug, PartialEq)]
176 /// Given a `TokenStream` with a `Stream` of only two arguments, return a new `TokenStream`
177 /// separating the two arguments with a comma for diagnostic suggestions.
178 pub(crate) fn add_comma(&self) -> Option<(TokenStream, Span)> {
179 // Used to suggest if a user writes `foo!(a b);`
180 if let Some(ref stream) = self.0 {
181 let mut suggestion = None;
182 let mut iter = stream.iter().enumerate().peekable();
183 while let Some((pos, ts)) = iter.next() {
184 if let Some((_, next)) = iter.peek() {
185 let sp = match (&ts, &next) {
186 (_, (TokenTree::Token(Token { kind: token::Comma, .. }), _)) => continue,
187 ((TokenTree::Token(token_left), NonJoint),
188 (TokenTree::Token(token_right), _))
189 if ((token_left.is_ident() && !token_left.is_reserved_ident())
190 || token_left.is_lit()) &&
191 ((token_right.is_ident() && !token_right.is_reserved_ident())
192 || token_right.is_lit()) => token_left.span,
193 ((TokenTree::Delimited(sp, ..), NonJoint), _) => sp.entire(),
196 let sp = sp.shrink_to_hi();
197 let comma = (TokenTree::token(token::Comma, sp), NonJoint);
198 suggestion = Some((pos, comma, sp));
201 if let Some((pos, comma, sp)) = suggestion {
202 let mut new_stream = vec![];
203 let parts = stream.split_at(pos + 1);
204 new_stream.extend_from_slice(parts.0);
205 new_stream.push(comma);
206 new_stream.extend_from_slice(parts.1);
207 return Some((TokenStream::new(new_stream), sp));
214 impl From<TokenTree> for TokenStream {
215 fn from(tree: TokenTree) -> TokenStream {
216 TokenStream::new(vec![(tree, NonJoint)])
220 impl From<TokenTree> for TreeAndJoint {
221 fn from(tree: TokenTree) -> TreeAndJoint {
226 impl<T: Into<TokenStream>> iter::FromIterator<T> for TokenStream {
227 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
228 TokenStream::from_streams(iter.into_iter().map(Into::into).collect::<SmallVec<_>>())
232 impl Eq for TokenStream {}
234 impl PartialEq<TokenStream> for TokenStream {
235 fn eq(&self, other: &TokenStream) -> bool {
236 self.trees().eq(other.trees())
241 pub fn len(&self) -> usize {
242 if let Some(ref slice) = self.0 {
249 pub fn empty() -> TokenStream {
253 pub fn is_empty(&self) -> bool {
256 Some(ref stream) => stream.is_empty(),
260 pub(crate) fn from_streams(mut streams: SmallVec<[TokenStream; 2]>) -> TokenStream {
261 match streams.len() {
262 0 => TokenStream::empty(),
263 1 => streams.pop().unwrap(),
265 // rust-lang/rust#57735: pre-allocate vector to avoid
266 // quadratic blow-up due to on-the-fly reallocations.
267 let tree_count = streams.iter()
268 .map(|ts| match &ts.0 { None => 0, Some(s) => s.len() })
270 let mut vec = Vec::with_capacity(tree_count);
272 for stream in streams {
275 Some(stream2) => vec.extend(stream2.iter().cloned()),
278 TokenStream::new(vec)
283 pub fn new(streams: Vec<TreeAndJoint>) -> TokenStream {
284 match streams.len() {
285 0 => TokenStream(None),
286 _ => TokenStream(Some(Lrc::new(streams))),
290 pub fn append_to_tree_and_joint_vec(self, vec: &mut Vec<TreeAndJoint>) {
291 if let Some(stream) = self.0 {
292 vec.extend(stream.iter().cloned());
296 pub fn trees(&self) -> Cursor {
297 self.clone().into_trees()
300 pub fn into_trees(self) -> Cursor {
304 /// Compares two TokenStreams, checking equality without regarding span information.
305 pub fn eq_unspanned(&self, other: &TokenStream) -> bool {
306 let mut t1 = self.trees();
307 let mut t2 = other.trees();
308 for (t1, t2) in t1.by_ref().zip(t2.by_ref()) {
309 if !t1.eq_unspanned(&t2) {
313 t1.next().is_none() && t2.next().is_none()
316 // See comments in `Nonterminal::to_tokenstream` for why we care about
317 // *probably* equal here rather than actual equality
319 // This is otherwise the same as `eq_unspanned`, only recursing with a
321 pub fn probably_equal_for_proc_macro(&self, other: &TokenStream) -> bool {
322 // When checking for `probably_eq`, we ignore certain tokens that aren't
323 // preserved in the AST. Because they are not preserved, the pretty
324 // printer arbitrarily adds or removes them when printing as token
325 // streams, making a comparison between a token stream generated from an
326 // AST and a token stream which was parsed into an AST more reliable.
327 fn semantic_tree(tree: &TokenTree) -> bool {
328 if let TokenTree::Token(token) = tree {
330 // The pretty printer tends to add trailing commas to
331 // everything, and in particular, after struct fields.
333 // The pretty printer emits `NoDelim` as whitespace.
334 | token::OpenDelim(DelimToken::NoDelim)
335 | token::CloseDelim(DelimToken::NoDelim)
336 // The pretty printer collapses many semicolons into one.
338 // The pretty printer collapses whitespace arbitrarily and can
339 // introduce whitespace from `NoDelim`.
341 // The pretty printer can turn `$crate` into `::crate_name`
342 | token::ModSep = token.kind {
349 let mut t1 = self.trees().filter(semantic_tree);
350 let mut t2 = other.trees().filter(semantic_tree);
351 for (t1, t2) in t1.by_ref().zip(t2.by_ref()) {
352 if !t1.probably_equal_for_proc_macro(&t2) {
356 t1.next().is_none() && t2.next().is_none()
359 pub fn map_enumerated<F: FnMut(usize, TokenTree) -> TokenTree>(self, mut f: F) -> TokenStream {
360 TokenStream(self.0.map(|stream| {
365 .map(|(i, (tree, is_joint))| (f(i, tree.clone()), *is_joint))
370 pub fn map<F: FnMut(TokenTree) -> TokenTree>(self, mut f: F) -> TokenStream {
371 TokenStream(self.0.map(|stream| {
375 .map(|(tree, is_joint)| (f(tree.clone()), *is_joint))
380 fn first_tree_and_joint(&self) -> Option<TreeAndJoint> {
381 self.0.as_ref().map(|stream| {
382 stream.first().unwrap().clone()
386 fn last_tree_if_joint(&self) -> Option<TokenTree> {
389 Some(ref stream) => {
390 if let (tree, Joint) = stream.last().unwrap() {
400 // 99.5%+ of the time we have 1 or 2 elements in this vector.
402 pub struct TokenStreamBuilder(SmallVec<[TokenStream; 2]>);
404 impl TokenStreamBuilder {
405 pub fn new() -> TokenStreamBuilder {
406 TokenStreamBuilder(SmallVec::new())
409 pub fn push<T: Into<TokenStream>>(&mut self, stream: T) {
410 let stream = stream.into();
411 let last_tree_if_joint = self.0.last().and_then(TokenStream::last_tree_if_joint);
412 if let Some(TokenTree::Token(last_token)) = last_tree_if_joint {
413 if let Some((TokenTree::Token(token), is_joint)) = stream.first_tree_and_joint() {
414 if let Some(glued_tok) = last_token.glue(token) {
415 let last_stream = self.0.pop().unwrap();
416 self.push_all_but_last_tree(&last_stream);
417 let glued_tt = TokenTree::Token(glued_tok);
418 let glued_tokenstream = TokenStream::new(vec![(glued_tt, is_joint)]);
419 self.0.push(glued_tokenstream);
420 self.push_all_but_first_tree(&stream);
428 pub fn build(self) -> TokenStream {
429 TokenStream::from_streams(self.0)
432 fn push_all_but_last_tree(&mut self, stream: &TokenStream) {
433 if let Some(ref streams) = stream.0 {
434 let len = streams.len();
437 _ => self.0.push(TokenStream(Some(Lrc::new(streams[0 .. len - 1].to_vec())))),
442 fn push_all_but_first_tree(&mut self, stream: &TokenStream) {
443 if let Some(ref streams) = stream.0 {
444 let len = streams.len();
447 _ => self.0.push(TokenStream(Some(Lrc::new(streams[1 .. len].to_vec())))),
455 pub stream: TokenStream,
459 impl Iterator for Cursor {
460 type Item = TokenTree;
462 fn next(&mut self) -> Option<TokenTree> {
463 self.next_with_joint().map(|(tree, _)| tree)
468 fn new(stream: TokenStream) -> Self {
469 Cursor { stream, index: 0 }
472 pub fn next_with_joint(&mut self) -> Option<TreeAndJoint> {
473 match self.stream.0 {
475 Some(ref stream) => {
476 if self.index < stream.len() {
478 Some(stream[self.index - 1].clone())
486 pub fn append(&mut self, new_stream: TokenStream) {
487 if new_stream.is_empty() {
490 let index = self.index;
491 let stream = mem::replace(&mut self.stream, TokenStream(None));
492 *self = TokenStream::from_streams(smallvec![stream, new_stream]).into_trees();
496 pub fn look_ahead(&self, n: usize) -> Option<TokenTree> {
497 match self.stream.0 {
499 Some(ref stream) => stream[self.index ..].get(n).map(|(tree, _)| tree.clone()),
504 impl fmt::Display for TokenStream {
505 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
506 f.write_str(&pprust::tokens_to_string(self.clone()))
510 impl Encodable for TokenStream {
511 fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), E::Error> {
512 self.trees().collect::<Vec<_>>().encode(encoder)
516 impl Decodable for TokenStream {
517 fn decode<D: Decoder>(decoder: &mut D) -> Result<TokenStream, D::Error> {
518 Vec::<TokenTree>::decode(decoder).map(|vec| vec.into_iter().collect())
522 #[derive(Debug, Copy, Clone, PartialEq, RustcEncodable, RustcDecodable)]
523 pub struct DelimSpan {
529 pub fn from_single(sp: Span) -> Self {
536 pub fn from_pair(open: Span, close: Span) -> Self {
537 DelimSpan { open, close }
540 pub fn dummy() -> Self {
541 Self::from_single(DUMMY_SP)
544 pub fn entire(self) -> Span {
545 self.open.with_hi(self.close.hi())
548 pub fn apply_mark(self, expn_id: ExpnId) -> Self {
550 open: self.open.apply_mark(expn_id),
551 close: self.close.apply_mark(expn_id),
559 use crate::ast::Name;
560 use crate::with_default_globals;
561 use crate::util::parser_testing::string_to_stream;
562 use syntax_pos::{Span, BytePos, NO_EXPANSION};
564 fn string_to_ts(string: &str) -> TokenStream {
565 string_to_stream(string.to_owned())
568 fn sp(a: u32, b: u32) -> Span {
569 Span::new(BytePos(a), BytePos(b), NO_EXPANSION)
574 with_default_globals(|| {
575 let test_res = string_to_ts("foo::bar::baz");
576 let test_fst = string_to_ts("foo::bar");
577 let test_snd = string_to_ts("::baz");
578 let eq_res = TokenStream::from_streams(smallvec![test_fst, test_snd]);
579 assert_eq!(test_res.trees().count(), 5);
580 assert_eq!(eq_res.trees().count(), 5);
581 assert_eq!(test_res.eq_unspanned(&eq_res), true);
586 fn test_to_from_bijection() {
587 with_default_globals(|| {
588 let test_start = string_to_ts("foo::bar(baz)");
589 let test_end = test_start.trees().collect();
590 assert_eq!(test_start, test_end)
596 with_default_globals(|| {
597 let test_res = string_to_ts("foo");
598 let test_eqs = string_to_ts("foo");
599 assert_eq!(test_res, test_eqs)
605 with_default_globals(|| {
606 let test_res = string_to_ts("::bar::baz");
607 let test_eqs = string_to_ts("::bar::baz");
608 assert_eq!(test_res, test_eqs)
614 with_default_globals(|| {
615 let test_res = string_to_ts("");
616 let test_eqs = string_to_ts("");
617 assert_eq!(test_res, test_eqs)
623 with_default_globals(|| {
624 let test_res = string_to_ts("::bar::baz");
625 let test_eqs = string_to_ts("bar::baz");
626 assert_eq!(test_res == test_eqs, false)
632 with_default_globals(|| {
633 let test_res = string_to_ts("(bar,baz)");
634 let test_eqs = string_to_ts("bar,baz");
635 assert_eq!(test_res == test_eqs, false)
641 with_default_globals(|| {
642 let test0: TokenStream = Vec::<TokenTree>::new().into_iter().collect();
643 let test1: TokenStream =
644 TokenTree::token(token::Ident(Name::intern("a"), false), sp(0, 1)).into();
645 let test2 = string_to_ts("foo(bar::baz)");
647 assert_eq!(test0.is_empty(), true);
648 assert_eq!(test1.is_empty(), false);
649 assert_eq!(test2.is_empty(), false);
654 fn test_dotdotdot() {
655 with_default_globals(|| {
656 let mut builder = TokenStreamBuilder::new();
657 builder.push(TokenTree::token(token::Dot, sp(0, 1)).joint());
658 builder.push(TokenTree::token(token::Dot, sp(1, 2)).joint());
659 builder.push(TokenTree::token(token::Dot, sp(2, 3)));
660 let stream = builder.build();
661 assert!(stream.eq_unspanned(&string_to_ts("...")));
662 assert_eq!(stream.trees().count(), 1);