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, Mark, 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 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,
62 // These are safe since we ensure that they hold for all fields in the `_dummy` function.
64 // These impls are only here because the compiler takes forever to compute the Send and Sync
65 // bounds without them.
66 // FIXME: Remove these impls when the compiler can compute the bounds quickly again.
67 // See https://github.com/rust-lang/rust/issues/60846
68 #[cfg(parallel_compiler)]
69 unsafe impl Send for TokenTree {}
70 #[cfg(parallel_compiler)]
71 unsafe impl Sync for TokenTree {}
74 /// Use this token tree as a matcher to parse given tts.
75 pub fn parse(cx: &base::ExtCtxt<'_>, mtch: &[quoted::TokenTree], tts: TokenStream)
76 -> macro_parser::NamedParseResult {
77 // `None` is because we're not interpolating
78 let directory = Directory {
79 path: Cow::from(cx.current_expansion.module.directory.as_path()),
80 ownership: cx.current_expansion.directory_ownership,
82 macro_parser::parse(cx.parse_sess(), tts, mtch, Some(directory), true)
85 /// Checks if this TokenTree is equal to the other, regardless of span information.
86 pub fn eq_unspanned(&self, other: &TokenTree) -> bool {
88 (TokenTree::Token(token), TokenTree::Token(token2)) => token.kind == token2.kind,
89 (TokenTree::Delimited(_, delim, tts), TokenTree::Delimited(_, delim2, tts2)) => {
90 delim == delim2 && tts.eq_unspanned(&tts2)
96 // See comments in `Nonterminal::to_tokenstream` for why we care about
97 // *probably* equal here rather than actual equality
99 // This is otherwise the same as `eq_unspanned`, only recursing with a
101 pub fn probably_equal_for_proc_macro(&self, other: &TokenTree) -> bool {
102 match (self, other) {
103 (TokenTree::Token(token), TokenTree::Token(token2)) => {
104 token.probably_equal_for_proc_macro(token2)
106 (TokenTree::Delimited(_, delim, tts), TokenTree::Delimited(_, delim2, tts2)) => {
107 delim == delim2 && tts.probably_equal_for_proc_macro(&tts2)
113 /// Retrieves the TokenTree's span.
114 pub fn span(&self) -> Span {
116 TokenTree::Token(token) => token.span,
117 TokenTree::Delimited(sp, ..) => sp.entire(),
121 /// Modify the `TokenTree`'s span in-place.
122 pub fn set_span(&mut self, span: Span) {
124 TokenTree::Token(token) => token.span = span,
125 TokenTree::Delimited(dspan, ..) => *dspan = DelimSpan::from_single(span),
129 pub fn joint(self) -> TokenStream {
130 TokenStream::new(vec![(self, Joint)])
133 pub fn token(kind: TokenKind, span: Span) -> TokenTree {
134 TokenTree::Token(Token::new(kind, span))
137 /// Returns the opening delimiter as a token tree.
138 pub fn open_tt(span: Span, delim: DelimToken) -> TokenTree {
139 let open_span = if span.is_dummy() {
142 span.with_hi(span.lo() + BytePos(delim.len() as u32))
144 TokenTree::token(token::OpenDelim(delim), open_span)
147 /// Returns the closing delimiter as a token tree.
148 pub fn close_tt(span: Span, delim: DelimToken) -> TokenTree {
149 let close_span = if span.is_dummy() {
152 span.with_lo(span.hi() - BytePos(delim.len() as u32))
154 TokenTree::token(token::CloseDelim(delim), close_span)
160 /// A `TokenStream` is an abstract sequence of tokens, organized into `TokenTree`s.
161 /// The goal is for procedural macros to work with `TokenStream`s and `TokenTree`s
162 /// instead of a representation of the abstract syntax tree.
163 /// Today's `TokenTree`s can still contain AST via `token::Interpolated` for back-compat.
165 /// The use of `Option` is an optimization that avoids the need for an
166 /// allocation when the stream is empty. However, it is not guaranteed that an
167 /// empty stream is represented with `None`; it may be represented as a `Some`
168 /// around an empty `Vec`.
169 #[derive(Clone, Debug)]
170 pub struct TokenStream(pub Option<Lrc<Vec<TreeAndJoint>>>);
172 pub type TreeAndJoint = (TokenTree, IsJoint);
174 // `TokenStream` is used a lot. Make sure it doesn't unintentionally get bigger.
175 #[cfg(target_arch = "x86_64")]
176 static_assert_size!(TokenStream, 8);
178 #[derive(Clone, Copy, Debug, PartialEq)]
187 /// Given a `TokenStream` with a `Stream` of only two arguments, return a new `TokenStream`
188 /// separating the two arguments with a comma for diagnostic suggestions.
189 pub(crate) fn add_comma(&self) -> Option<(TokenStream, Span)> {
190 // Used to suggest if a user writes `foo!(a b);`
191 if let Some(ref stream) = self.0 {
192 let mut suggestion = None;
193 let mut iter = stream.iter().enumerate().peekable();
194 while let Some((pos, ts)) = iter.next() {
195 if let Some((_, next)) = iter.peek() {
196 let sp = match (&ts, &next) {
197 (_, (TokenTree::Token(Token { kind: token::Comma, .. }), _)) => continue,
198 ((TokenTree::Token(token_left), NonJoint),
199 (TokenTree::Token(token_right), _))
200 if ((token_left.is_ident() && !token_left.is_reserved_ident())
201 || token_left.is_lit()) &&
202 ((token_right.is_ident() && !token_right.is_reserved_ident())
203 || token_right.is_lit()) => token_left.span,
204 ((TokenTree::Delimited(sp, ..), NonJoint), _) => sp.entire(),
207 let sp = sp.shrink_to_hi();
208 let comma = (TokenTree::token(token::Comma, sp), NonJoint);
209 suggestion = Some((pos, comma, sp));
212 if let Some((pos, comma, sp)) = suggestion {
213 let mut new_stream = vec![];
214 let parts = stream.split_at(pos + 1);
215 new_stream.extend_from_slice(parts.0);
216 new_stream.push(comma);
217 new_stream.extend_from_slice(parts.1);
218 return Some((TokenStream::new(new_stream), sp));
225 impl From<TokenTree> for TokenStream {
226 fn from(tree: TokenTree) -> TokenStream {
227 TokenStream::new(vec![(tree, NonJoint)])
231 impl From<TokenTree> for TreeAndJoint {
232 fn from(tree: TokenTree) -> TreeAndJoint {
237 impl<T: Into<TokenStream>> iter::FromIterator<T> for TokenStream {
238 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
239 TokenStream::from_streams(iter.into_iter().map(Into::into).collect::<SmallVec<_>>())
243 impl Eq for TokenStream {}
245 impl PartialEq<TokenStream> for TokenStream {
246 fn eq(&self, other: &TokenStream) -> bool {
247 self.trees().eq(other.trees())
252 pub fn len(&self) -> usize {
253 if let Some(ref slice) = self.0 {
260 pub fn empty() -> TokenStream {
264 pub fn is_empty(&self) -> bool {
267 Some(ref stream) => stream.is_empty(),
271 pub(crate) fn from_streams(mut streams: SmallVec<[TokenStream; 2]>) -> TokenStream {
272 match streams.len() {
273 0 => TokenStream::empty(),
274 1 => streams.pop().unwrap(),
276 // rust-lang/rust#57735: pre-allocate vector to avoid
277 // quadratic blow-up due to on-the-fly reallocations.
278 let tree_count = streams.iter()
279 .map(|ts| match &ts.0 { None => 0, Some(s) => s.len() })
281 let mut vec = Vec::with_capacity(tree_count);
283 for stream in streams {
286 Some(stream2) => vec.extend(stream2.iter().cloned()),
289 TokenStream::new(vec)
294 pub fn new(streams: Vec<TreeAndJoint>) -> TokenStream {
295 match streams.len() {
296 0 => TokenStream(None),
297 _ => TokenStream(Some(Lrc::new(streams))),
301 pub fn append_to_tree_and_joint_vec(self, vec: &mut Vec<TreeAndJoint>) {
302 if let Some(stream) = self.0 {
303 vec.extend(stream.iter().cloned());
307 pub fn trees(&self) -> Cursor {
308 self.clone().into_trees()
311 pub fn into_trees(self) -> Cursor {
315 /// Compares two TokenStreams, checking equality without regarding span information.
316 pub fn eq_unspanned(&self, other: &TokenStream) -> bool {
317 let mut t1 = self.trees();
318 let mut t2 = other.trees();
319 for (t1, t2) in t1.by_ref().zip(t2.by_ref()) {
320 if !t1.eq_unspanned(&t2) {
324 t1.next().is_none() && t2.next().is_none()
327 // See comments in `Nonterminal::to_tokenstream` for why we care about
328 // *probably* equal here rather than actual equality
330 // This is otherwise the same as `eq_unspanned`, only recursing with a
332 pub fn probably_equal_for_proc_macro(&self, other: &TokenStream) -> bool {
333 // When checking for `probably_eq`, we ignore certain tokens that aren't
334 // preserved in the AST. Because they are not preserved, the pretty
335 // printer arbitrarily adds or removes them when printing as token
336 // streams, making a comparison between a token stream generated from an
337 // AST and a token stream which was parsed into an AST more reliable.
338 fn semantic_tree(tree: &TokenTree) -> bool {
339 if let TokenTree::Token(token) = tree {
341 // The pretty printer tends to add trailing commas to
342 // everything, and in particular, after struct fields.
344 // The pretty printer emits `NoDelim` as whitespace.
345 | token::OpenDelim(DelimToken::NoDelim)
346 | token::CloseDelim(DelimToken::NoDelim)
347 // The pretty printer collapses many semicolons into one.
349 // The pretty printer collapses whitespace arbitrarily and can
350 // introduce whitespace from `NoDelim`.
352 // The pretty printer can turn `$crate` into `::crate_name`
353 | token::ModSep = token.kind {
360 let mut t1 = self.trees().filter(semantic_tree);
361 let mut t2 = other.trees().filter(semantic_tree);
362 for (t1, t2) in t1.by_ref().zip(t2.by_ref()) {
363 if !t1.probably_equal_for_proc_macro(&t2) {
367 t1.next().is_none() && t2.next().is_none()
370 pub fn map_enumerated<F: FnMut(usize, TokenTree) -> TokenTree>(self, mut f: F) -> TokenStream {
371 TokenStream(self.0.map(|stream| {
376 .map(|(i, (tree, is_joint))| (f(i, tree.clone()), *is_joint))
381 pub fn map<F: FnMut(TokenTree) -> TokenTree>(self, mut f: F) -> TokenStream {
382 TokenStream(self.0.map(|stream| {
386 .map(|(tree, is_joint)| (f(tree.clone()), *is_joint))
391 fn first_tree_and_joint(&self) -> Option<TreeAndJoint> {
392 self.0.as_ref().map(|stream| {
393 stream.first().unwrap().clone()
397 fn last_tree_if_joint(&self) -> Option<TokenTree> {
400 Some(ref stream) => {
401 if let (tree, Joint) = stream.last().unwrap() {
411 // 99.5%+ of the time we have 1 or 2 elements in this vector.
413 pub struct TokenStreamBuilder(SmallVec<[TokenStream; 2]>);
415 impl TokenStreamBuilder {
416 pub fn new() -> TokenStreamBuilder {
417 TokenStreamBuilder(SmallVec::new())
420 pub fn push<T: Into<TokenStream>>(&mut self, stream: T) {
421 let stream = stream.into();
422 let last_tree_if_joint = self.0.last().and_then(TokenStream::last_tree_if_joint);
423 if let Some(TokenTree::Token(last_token)) = last_tree_if_joint {
424 if let Some((TokenTree::Token(token), is_joint)) = stream.first_tree_and_joint() {
425 if let Some(glued_tok) = last_token.glue(token) {
426 let last_stream = self.0.pop().unwrap();
427 self.push_all_but_last_tree(&last_stream);
428 let glued_tt = TokenTree::Token(glued_tok);
429 let glued_tokenstream = TokenStream::new(vec![(glued_tt, is_joint)]);
430 self.0.push(glued_tokenstream);
431 self.push_all_but_first_tree(&stream);
439 pub fn build(self) -> TokenStream {
440 TokenStream::from_streams(self.0)
443 fn push_all_but_last_tree(&mut self, stream: &TokenStream) {
444 if let Some(ref streams) = stream.0 {
445 let len = streams.len();
448 _ => self.0.push(TokenStream(Some(Lrc::new(streams[0 .. len - 1].to_vec())))),
453 fn push_all_but_first_tree(&mut self, stream: &TokenStream) {
454 if let Some(ref streams) = stream.0 {
455 let len = streams.len();
458 _ => self.0.push(TokenStream(Some(Lrc::new(streams[1 .. len].to_vec())))),
466 pub stream: TokenStream,
470 impl Iterator for Cursor {
471 type Item = TokenTree;
473 fn next(&mut self) -> Option<TokenTree> {
474 self.next_with_joint().map(|(tree, _)| tree)
479 fn new(stream: TokenStream) -> Self {
480 Cursor { stream, index: 0 }
483 pub fn next_with_joint(&mut self) -> Option<TreeAndJoint> {
484 match self.stream.0 {
486 Some(ref stream) => {
487 if self.index < stream.len() {
489 Some(stream[self.index - 1].clone())
497 pub fn append(&mut self, new_stream: TokenStream) {
498 if new_stream.is_empty() {
501 let index = self.index;
502 let stream = mem::replace(&mut self.stream, TokenStream(None));
503 *self = TokenStream::from_streams(smallvec![stream, new_stream]).into_trees();
507 pub fn look_ahead(&self, n: usize) -> Option<TokenTree> {
508 match self.stream.0 {
510 Some(ref stream) => stream[self.index ..].get(n).map(|(tree, _)| tree.clone()),
515 impl fmt::Display for TokenStream {
516 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
517 f.write_str(&pprust::tokens_to_string(self.clone()))
521 impl Encodable for TokenStream {
522 fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), E::Error> {
523 self.trees().collect::<Vec<_>>().encode(encoder)
527 impl Decodable for TokenStream {
528 fn decode<D: Decoder>(decoder: &mut D) -> Result<TokenStream, D::Error> {
529 Vec::<TokenTree>::decode(decoder).map(|vec| vec.into_iter().collect())
533 #[derive(Debug, Copy, Clone, PartialEq, RustcEncodable, RustcDecodable)]
534 pub struct DelimSpan {
540 pub fn from_single(sp: Span) -> Self {
547 pub fn from_pair(open: Span, close: Span) -> Self {
548 DelimSpan { open, close }
551 pub fn dummy() -> Self {
552 Self::from_single(DUMMY_SP)
555 pub fn entire(self) -> Span {
556 self.open.with_hi(self.close.hi())
559 pub fn apply_mark(self, mark: Mark) -> Self {
561 open: self.open.apply_mark(mark),
562 close: self.close.apply_mark(mark),
570 use crate::ast::Name;
571 use crate::with_default_globals;
572 use crate::util::parser_testing::string_to_stream;
573 use syntax_pos::{Span, BytePos, NO_EXPANSION};
575 fn string_to_ts(string: &str) -> TokenStream {
576 string_to_stream(string.to_owned())
579 fn sp(a: u32, b: u32) -> Span {
580 Span::new(BytePos(a), BytePos(b), NO_EXPANSION)
585 with_default_globals(|| {
586 let test_res = string_to_ts("foo::bar::baz");
587 let test_fst = string_to_ts("foo::bar");
588 let test_snd = string_to_ts("::baz");
589 let eq_res = TokenStream::from_streams(smallvec![test_fst, test_snd]);
590 assert_eq!(test_res.trees().count(), 5);
591 assert_eq!(eq_res.trees().count(), 5);
592 assert_eq!(test_res.eq_unspanned(&eq_res), true);
597 fn test_to_from_bijection() {
598 with_default_globals(|| {
599 let test_start = string_to_ts("foo::bar(baz)");
600 let test_end = test_start.trees().collect();
601 assert_eq!(test_start, test_end)
607 with_default_globals(|| {
608 let test_res = string_to_ts("foo");
609 let test_eqs = string_to_ts("foo");
610 assert_eq!(test_res, test_eqs)
616 with_default_globals(|| {
617 let test_res = string_to_ts("::bar::baz");
618 let test_eqs = string_to_ts("::bar::baz");
619 assert_eq!(test_res, test_eqs)
625 with_default_globals(|| {
626 let test_res = string_to_ts("");
627 let test_eqs = string_to_ts("");
628 assert_eq!(test_res, test_eqs)
634 with_default_globals(|| {
635 let test_res = string_to_ts("::bar::baz");
636 let test_eqs = string_to_ts("bar::baz");
637 assert_eq!(test_res == test_eqs, false)
643 with_default_globals(|| {
644 let test_res = string_to_ts("(bar,baz)");
645 let test_eqs = string_to_ts("bar,baz");
646 assert_eq!(test_res == test_eqs, false)
652 with_default_globals(|| {
653 let test0: TokenStream = Vec::<TokenTree>::new().into_iter().collect();
654 let test1: TokenStream =
655 TokenTree::token(token::Ident(Name::intern("a"), false), sp(0, 1)).into();
656 let test2 = string_to_ts("foo(bar::baz)");
658 assert_eq!(test0.is_empty(), true);
659 assert_eq!(test1.is_empty(), false);
660 assert_eq!(test2.is_empty(), false);
665 fn test_dotdotdot() {
666 with_default_globals(|| {
667 let mut builder = TokenStreamBuilder::new();
668 builder.push(TokenTree::token(token::Dot, sp(0, 1)).joint());
669 builder.push(TokenTree::token(token::Dot, sp(1, 2)).joint());
670 builder.push(TokenTree::token(token::Dot, sp(2, 3)));
671 let stream = builder.build();
672 assert!(stream.eq_unspanned(&string_to_ts("...")));
673 assert_eq!(stream.trees().count(), 1);