1 // Copyright 2012-2016 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
13 //! TokenStreams represent syntactic objects before they are converted into ASTs.
14 //! A `TokenStream` is, roughly speaking, a sequence (eg stream) of `TokenTree`s,
15 //! which are themselves a single `Token` or a `Delimited` subsequence of tokens.
18 //! TokenStreams are persistent data structures constructed as ropes with reference
19 //! counted-children. In general, this means that calling an operation on a TokenStream
20 //! (such as `slice`) produces an entirely new TokenStream from the borrowed reference to
21 //! the original. This essentially coerces TokenStreams into 'views' of their subparts,
22 //! and a borrowed TokenStream is sufficient to build an owned TokenStream without taking
23 //! ownership of the original.
25 use syntax_pos::{BytePos, Span, DUMMY_SP};
27 use ext::tt::{macro_parser, quoted};
29 use parse::token::{self, Token};
31 use serialize::{Decoder, Decodable, Encoder, Encodable};
34 use std::{fmt, iter, mem};
35 use std::hash::{self, Hash};
37 /// A delimited sequence of token trees
38 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
39 pub struct Delimited {
40 /// The type of delimiter
41 pub delim: token::DelimToken,
42 /// The delimited sequence of token trees
43 pub tts: ThinTokenStream,
47 /// Returns the opening delimiter as a token.
48 pub fn open_token(&self) -> token::Token {
49 token::OpenDelim(self.delim)
52 /// Returns the closing delimiter as a token.
53 pub fn close_token(&self) -> token::Token {
54 token::CloseDelim(self.delim)
57 /// Returns the opening delimiter as a token tree.
58 pub fn open_tt(&self, span: Span) -> TokenTree {
59 let open_span = if span == DUMMY_SP {
62 Span { hi: span.lo + BytePos(self.delim.len() as u32), ..span }
64 TokenTree::Token(open_span, self.open_token())
67 /// Returns the closing delimiter as a token tree.
68 pub fn close_tt(&self, span: Span) -> TokenTree {
69 let close_span = if span == DUMMY_SP {
72 Span { lo: span.hi - BytePos(self.delim.len() as u32), ..span }
74 TokenTree::Token(close_span, self.close_token())
77 /// Returns the token trees inside the delimiters.
78 pub fn stream(&self) -> TokenStream {
79 self.tts.clone().into()
83 /// When the main rust parser encounters a syntax-extension invocation, it
84 /// parses the arguments to the invocation as a token-tree. This is a very
85 /// loose structure, such that all sorts of different AST-fragments can
86 /// be passed to syntax extensions using a uniform type.
88 /// If the syntax extension is an MBE macro, it will attempt to match its
89 /// LHS token tree against the provided token tree, and if it finds a
90 /// match, will transcribe the RHS token tree, splicing in any captured
91 /// macro_parser::matched_nonterminals into the `SubstNt`s it finds.
93 /// The RHS of an MBE macro is the only place `SubstNt`s are substituted.
94 /// Nothing special happens to misnamed or misplaced `SubstNt`s.
95 #[derive(Debug, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
98 Token(Span, token::Token),
99 /// A delimited sequence of token trees
100 Delimited(Span, Delimited),
104 /// Use this token tree as a matcher to parse given tts.
105 pub fn parse(cx: &base::ExtCtxt, mtch: &[quoted::TokenTree], tts: TokenStream)
106 -> macro_parser::NamedParseResult {
107 // `None` is because we're not interpolating
108 let directory = Directory {
109 path: cx.current_expansion.module.directory.clone(),
110 ownership: cx.current_expansion.directory_ownership,
112 macro_parser::parse(cx.parse_sess(), tts, mtch, Some(directory))
115 /// Check if this TokenTree is equal to the other, regardless of span information.
116 pub fn eq_unspanned(&self, other: &TokenTree) -> bool {
117 match (self, other) {
118 (&TokenTree::Token(_, ref tk), &TokenTree::Token(_, ref tk2)) => tk == tk2,
119 (&TokenTree::Delimited(_, ref dl), &TokenTree::Delimited(_, ref dl2)) => {
120 dl.delim == dl2.delim &&
121 dl.stream().trees().zip(dl2.stream().trees()).all(|(tt, tt2)| tt.eq_unspanned(&tt2))
127 /// Retrieve the TokenTree's span.
128 pub fn span(&self) -> Span {
130 TokenTree::Token(sp, _) | TokenTree::Delimited(sp, _) => sp,
134 /// Indicates if the stream is a token that is equal to the provided token.
135 pub fn eq_token(&self, t: Token) -> bool {
137 TokenTree::Token(_, ref tk) => *tk == t,
145 /// A `TokenStream` is an abstract sequence of tokens, organized into `TokenTree`s.
146 /// The goal is for procedural macros to work with `TokenStream`s and `TokenTree`s
147 /// instead of a representation of the abstract syntax tree.
148 /// Today's `TokenTree`s can still contain AST via `Token::Interpolated` for back-compat.
149 #[derive(Clone, Debug)]
150 pub struct TokenStream {
151 kind: TokenStreamKind,
154 #[derive(Clone, Debug)]
155 enum TokenStreamKind {
158 Stream(RcSlice<TokenStream>),
161 impl From<TokenTree> for TokenStream {
162 fn from(tt: TokenTree) -> TokenStream {
163 TokenStream { kind: TokenStreamKind::Tree(tt) }
167 impl From<Token> for TokenStream {
168 fn from(token: Token) -> TokenStream {
169 TokenTree::Token(DUMMY_SP, token).into()
173 impl<T: Into<TokenStream>> iter::FromIterator<T> for TokenStream {
174 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
175 TokenStream::concat(iter.into_iter().map(Into::into).collect::<Vec<_>>())
179 impl Eq for TokenStream {}
181 impl PartialEq<TokenStream> for TokenStream {
182 fn eq(&self, other: &TokenStream) -> bool {
183 self.trees().eq(other.trees())
188 pub fn empty() -> TokenStream {
189 TokenStream { kind: TokenStreamKind::Empty }
192 pub fn is_empty(&self) -> bool {
194 TokenStreamKind::Empty => true,
199 pub fn concat(mut streams: Vec<TokenStream>) -> TokenStream {
200 match streams.len() {
201 0 => TokenStream::empty(),
202 1 => TokenStream::from(streams.pop().unwrap()),
203 _ => TokenStream::concat_rc_slice(RcSlice::new(streams)),
207 fn concat_rc_slice(streams: RcSlice<TokenStream>) -> TokenStream {
208 TokenStream { kind: TokenStreamKind::Stream(streams) }
211 pub fn trees(&self) -> Cursor {
212 self.clone().into_trees()
215 pub fn into_trees(self) -> Cursor {
219 /// Compares two TokenStreams, checking equality without regarding span information.
220 pub fn eq_unspanned(&self, other: &TokenStream) -> bool {
221 for (t1, t2) in self.trees().zip(other.trees()) {
222 if !t1.eq_unspanned(&t2) {
230 pub struct Cursor(CursorKind);
234 Tree(TokenTree, bool /* consumed? */),
235 Stream(StreamCursor),
238 struct StreamCursor {
239 stream: RcSlice<TokenStream>,
241 stack: Vec<(RcSlice<TokenStream>, usize)>,
244 impl Iterator for Cursor {
245 type Item = TokenTree;
247 fn next(&mut self) -> Option<TokenTree> {
248 let cursor = match self.0 {
249 CursorKind::Stream(ref mut cursor) => cursor,
250 CursorKind::Tree(ref tree, ref mut consumed @ false) => {
252 return Some(tree.clone());
258 if cursor.index < cursor.stream.len() {
259 match cursor.stream[cursor.index].kind.clone() {
260 TokenStreamKind::Tree(tree) => {
264 TokenStreamKind::Stream(stream) => {
265 cursor.stack.push((mem::replace(&mut cursor.stream, stream),
266 mem::replace(&mut cursor.index, 0) + 1));
268 TokenStreamKind::Empty => {
272 } else if let Some((stream, index)) = cursor.stack.pop() {
273 cursor.stream = stream;
274 cursor.index = index;
283 fn new(stream: TokenStream) -> Self {
284 Cursor(match stream.kind {
285 TokenStreamKind::Empty => CursorKind::Empty,
286 TokenStreamKind::Tree(tree) => CursorKind::Tree(tree, false),
287 TokenStreamKind::Stream(stream) => {
288 CursorKind::Stream(StreamCursor { stream: stream, index: 0, stack: Vec::new() })
293 pub fn original_stream(self) -> TokenStream {
295 CursorKind::Empty => TokenStream::empty(),
296 CursorKind::Tree(tree, _) => tree.into(),
297 CursorKind::Stream(cursor) => TokenStream::concat_rc_slice({
298 cursor.stack.get(0).cloned().map(|(stream, _)| stream).unwrap_or(cursor.stream)
303 pub fn look_ahead(&self, n: usize) -> Option<TokenTree> {
304 fn look_ahead(streams: &[TokenStream], mut n: usize) -> Result<TokenTree, usize> {
305 for stream in streams {
306 n = match stream.kind {
307 TokenStreamKind::Tree(ref tree) if n == 0 => return Ok(tree.clone()),
308 TokenStreamKind::Tree(..) => n - 1,
309 TokenStreamKind::Stream(ref stream) => match look_ahead(stream, n) {
310 Ok(tree) => return Ok(tree),
321 CursorKind::Empty | CursorKind::Tree(_, true) => Err(n),
322 CursorKind::Tree(ref tree, false) => look_ahead(&[tree.clone().into()], n),
323 CursorKind::Stream(ref cursor) => {
324 look_ahead(&cursor.stream[cursor.index ..], n).or_else(|mut n| {
325 for &(ref stream, index) in cursor.stack.iter().rev() {
326 n = match look_ahead(&stream[index..], n) {
327 Ok(tree) => return Ok(tree),
339 /// The `TokenStream` type is large enough to represent a single `TokenTree` without allocation.
340 /// `ThinTokenStream` is smaller, but needs to allocate to represent a single `TokenTree`.
341 /// We must use `ThinTokenStream` in `TokenTree::Delimited` to avoid infinite size due to recursion.
342 #[derive(Debug, Clone)]
343 pub struct ThinTokenStream(Option<RcSlice<TokenStream>>);
345 impl From<TokenStream> for ThinTokenStream {
346 fn from(stream: TokenStream) -> ThinTokenStream {
347 ThinTokenStream(match stream.kind {
348 TokenStreamKind::Empty => None,
349 TokenStreamKind::Tree(tree) => Some(RcSlice::new(vec![tree.into()])),
350 TokenStreamKind::Stream(stream) => Some(stream),
355 impl From<ThinTokenStream> for TokenStream {
356 fn from(stream: ThinTokenStream) -> TokenStream {
357 stream.0.map(TokenStream::concat_rc_slice).unwrap_or_else(TokenStream::empty)
361 impl Eq for ThinTokenStream {}
363 impl PartialEq<ThinTokenStream> for ThinTokenStream {
364 fn eq(&self, other: &ThinTokenStream) -> bool {
365 TokenStream::from(self.clone()) == TokenStream::from(other.clone())
369 impl fmt::Display for TokenStream {
370 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
371 f.write_str(&pprust::tokens_to_string(self.clone()))
375 impl Encodable for TokenStream {
376 fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), E::Error> {
377 self.trees().collect::<Vec<_>>().encode(encoder)
381 impl Decodable for TokenStream {
382 fn decode<D: Decoder>(decoder: &mut D) -> Result<TokenStream, D::Error> {
383 Vec::<TokenTree>::decode(decoder).map(|vec| vec.into_iter().collect())
387 impl Hash for TokenStream {
388 fn hash<H: hash::Hasher>(&self, state: &mut H) {
389 for tree in self.trees() {
395 impl Encodable for ThinTokenStream {
396 fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), E::Error> {
397 TokenStream::from(self.clone()).encode(encoder)
401 impl Decodable for ThinTokenStream {
402 fn decode<D: Decoder>(decoder: &mut D) -> Result<ThinTokenStream, D::Error> {
403 TokenStream::decode(decoder).map(Into::into)
407 impl Hash for ThinTokenStream {
408 fn hash<H: hash::Hasher>(&self, state: &mut H) {
409 TokenStream::from(self.clone()).hash(state);
417 use syntax::ast::Ident;
418 use syntax_pos::{Span, BytePos, NO_EXPANSION};
419 use parse::token::Token;
420 use util::parser_testing::string_to_stream;
422 fn string_to_ts(string: &str) -> TokenStream {
423 string_to_stream(string.to_owned())
426 fn sp(a: u32, b: u32) -> Span {
436 let test_res = string_to_ts("foo::bar::baz");
437 let test_fst = string_to_ts("foo::bar");
438 let test_snd = string_to_ts("::baz");
439 let eq_res = TokenStream::concat(vec![test_fst, test_snd]);
440 assert_eq!(test_res.trees().count(), 5);
441 assert_eq!(eq_res.trees().count(), 5);
442 assert_eq!(test_res.eq_unspanned(&eq_res), true);
446 fn test_to_from_bijection() {
447 let test_start = string_to_ts("foo::bar(baz)");
448 let test_end = test_start.trees().collect();
449 assert_eq!(test_start, test_end)
454 let test_res = string_to_ts("foo");
455 let test_eqs = string_to_ts("foo");
456 assert_eq!(test_res, test_eqs)
461 let test_res = string_to_ts("::bar::baz");
462 let test_eqs = string_to_ts("::bar::baz");
463 assert_eq!(test_res, test_eqs)
468 let test_res = string_to_ts("");
469 let test_eqs = string_to_ts("");
470 assert_eq!(test_res, test_eqs)
475 let test_res = string_to_ts("::bar::baz");
476 let test_eqs = string_to_ts("bar::baz");
477 assert_eq!(test_res == test_eqs, false)
482 let test_res = string_to_ts("(bar,baz)");
483 let test_eqs = string_to_ts("bar,baz");
484 assert_eq!(test_res == test_eqs, false)
489 let test0: TokenStream = Vec::<TokenTree>::new().into_iter().collect();
490 let test1: TokenStream =
491 TokenTree::Token(sp(0, 1), Token::Ident(Ident::from_str("a"))).into();
492 let test2 = string_to_ts("foo(bar::baz)");
494 assert_eq!(test0.is_empty(), true);
495 assert_eq!(test1.is_empty(), false);
496 assert_eq!(test2.is_empty(), false);