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 = match span {
61 _ => Span { hi: span.lo + BytePos(self.delim.len() as u32), ..span },
63 TokenTree::Token(open_span, self.open_token())
66 /// Returns the closing delimiter as a token tree.
67 pub fn close_tt(&self, span: Span) -> TokenTree {
68 let close_span = match span {
70 _ => Span { lo: span.hi - BytePos(self.delim.len() as u32), ..span },
72 TokenTree::Token(close_span, self.close_token())
75 /// Returns the token trees inside the delimiters.
76 pub fn stream(&self) -> TokenStream {
77 self.tts.clone().into()
81 /// When the main rust parser encounters a syntax-extension invocation, it
82 /// parses the arguments to the invocation as a token-tree. This is a very
83 /// loose structure, such that all sorts of different AST-fragments can
84 /// be passed to syntax extensions using a uniform type.
86 /// If the syntax extension is an MBE macro, it will attempt to match its
87 /// LHS token tree against the provided token tree, and if it finds a
88 /// match, will transcribe the RHS token tree, splicing in any captured
89 /// macro_parser::matched_nonterminals into the `SubstNt`s it finds.
91 /// The RHS of an MBE macro is the only place `SubstNt`s are substituted.
92 /// Nothing special happens to misnamed or misplaced `SubstNt`s.
93 #[derive(Debug, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
96 Token(Span, token::Token),
97 /// A delimited sequence of token trees
98 Delimited(Span, Delimited),
102 /// Use this token tree as a matcher to parse given tts.
103 pub fn parse(cx: &base::ExtCtxt, mtch: &[quoted::TokenTree], tts: TokenStream)
104 -> macro_parser::NamedParseResult {
105 // `None` is because we're not interpolating
106 let directory = Directory {
107 path: cx.current_expansion.module.directory.clone(),
108 ownership: cx.current_expansion.directory_ownership,
110 macro_parser::parse(cx.parse_sess(), tts, mtch, Some(directory))
113 /// Check if this TokenTree is equal to the other, regardless of span information.
114 pub fn eq_unspanned(&self, other: &TokenTree) -> bool {
115 match (self, other) {
116 (&TokenTree::Token(_, ref tk), &TokenTree::Token(_, ref tk2)) => tk == tk2,
117 (&TokenTree::Delimited(_, ref dl), &TokenTree::Delimited(_, ref dl2)) => {
118 dl.delim == dl2.delim &&
119 dl.stream().trees().zip(dl2.stream().trees()).all(|(tt, tt2)| tt.eq_unspanned(&tt2))
125 /// Retrieve the TokenTree's span.
126 pub fn span(&self) -> Span {
128 TokenTree::Token(sp, _) | TokenTree::Delimited(sp, _) => sp,
132 /// Indicates if the stream is a token that is equal to the provided token.
133 pub fn eq_token(&self, t: Token) -> bool {
135 TokenTree::Token(_, ref tk) => *tk == t,
143 /// A `TokenStream` is an abstract sequence of tokens, organized into `TokenTree`s.
144 /// The goal is for procedural macros to work with `TokenStream`s and `TokenTree`s
145 /// instead of a representation of the abstract syntax tree.
146 /// Today's `TokenTree`s can still contain AST via `Token::Interpolated` for back-compat.
147 #[derive(Clone, Debug)]
148 pub struct TokenStream {
149 kind: TokenStreamKind,
152 #[derive(Clone, Debug)]
153 enum TokenStreamKind {
156 Stream(RcSlice<TokenStream>),
159 impl From<TokenTree> for TokenStream {
160 fn from(tt: TokenTree) -> TokenStream {
161 TokenStream { kind: TokenStreamKind::Tree(tt) }
165 impl<T: Into<TokenStream>> iter::FromIterator<T> for TokenStream {
166 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
167 TokenStream::concat(iter.into_iter().map(Into::into).collect::<Vec<_>>())
171 impl Eq for TokenStream {}
173 impl PartialEq<TokenStream> for TokenStream {
174 fn eq(&self, other: &TokenStream) -> bool {
175 self.trees().eq(other.trees())
180 pub fn empty() -> TokenStream {
181 TokenStream { kind: TokenStreamKind::Empty }
184 pub fn is_empty(&self) -> bool {
186 TokenStreamKind::Empty => true,
191 pub fn concat(mut streams: Vec<TokenStream>) -> TokenStream {
192 match streams.len() {
193 0 => TokenStream::empty(),
194 1 => TokenStream::from(streams.pop().unwrap()),
195 _ => TokenStream::concat_rc_slice(RcSlice::new(streams)),
199 fn concat_rc_slice(streams: RcSlice<TokenStream>) -> TokenStream {
200 TokenStream { kind: TokenStreamKind::Stream(streams) }
203 pub fn trees(&self) -> Cursor {
204 self.clone().into_trees()
207 pub fn into_trees(self) -> Cursor {
211 /// Compares two TokenStreams, checking equality without regarding span information.
212 pub fn eq_unspanned(&self, other: &TokenStream) -> bool {
213 for (t1, t2) in self.trees().zip(other.trees()) {
214 if !t1.eq_unspanned(&t2) {
222 pub struct Cursor(CursorKind);
226 Tree(TokenTree, bool /* consumed? */),
227 Stream(StreamCursor),
230 struct StreamCursor {
231 stream: RcSlice<TokenStream>,
233 stack: Vec<(RcSlice<TokenStream>, usize)>,
236 impl Iterator for Cursor {
237 type Item = TokenTree;
239 fn next(&mut self) -> Option<TokenTree> {
240 let cursor = match self.0 {
241 CursorKind::Stream(ref mut cursor) => cursor,
242 CursorKind::Tree(ref tree, ref mut consumed @ false) => {
244 return Some(tree.clone());
250 if cursor.index < cursor.stream.len() {
251 match cursor.stream[cursor.index].kind.clone() {
252 TokenStreamKind::Tree(tree) => {
256 TokenStreamKind::Stream(stream) => {
257 cursor.stack.push((mem::replace(&mut cursor.stream, stream),
258 mem::replace(&mut cursor.index, 0) + 1));
260 TokenStreamKind::Empty => {
264 } else if let Some((stream, index)) = cursor.stack.pop() {
265 cursor.stream = stream;
266 cursor.index = index;
275 fn new(stream: TokenStream) -> Self {
276 Cursor(match stream.kind {
277 TokenStreamKind::Empty => CursorKind::Empty,
278 TokenStreamKind::Tree(tree) => CursorKind::Tree(tree, false),
279 TokenStreamKind::Stream(stream) => {
280 CursorKind::Stream(StreamCursor { stream: stream, index: 0, stack: Vec::new() })
285 pub fn original_stream(self) -> TokenStream {
287 CursorKind::Empty => TokenStream::empty(),
288 CursorKind::Tree(tree, _) => tree.into(),
289 CursorKind::Stream(cursor) => TokenStream::concat_rc_slice({
290 cursor.stack.get(0).cloned().map(|(stream, _)| stream).unwrap_or(cursor.stream)
295 pub fn look_ahead(&self, n: usize) -> Option<TokenTree> {
296 fn look_ahead(streams: &[TokenStream], mut n: usize) -> Result<TokenTree, usize> {
297 for stream in streams {
298 n = match stream.kind {
299 TokenStreamKind::Tree(ref tree) if n == 0 => return Ok(tree.clone()),
300 TokenStreamKind::Tree(..) => n - 1,
301 TokenStreamKind::Stream(ref stream) => match look_ahead(stream, n) {
302 Ok(tree) => return Ok(tree),
313 CursorKind::Empty | CursorKind::Tree(_, true) => Err(n),
314 CursorKind::Tree(ref tree, false) => look_ahead(&[tree.clone().into()], n),
315 CursorKind::Stream(ref cursor) => {
316 look_ahead(&cursor.stream[cursor.index ..], n).or_else(|mut n| {
317 for &(ref stream, index) in cursor.stack.iter().rev() {
318 n = match look_ahead(&stream[index..], n) {
319 Ok(tree) => return Ok(tree),
331 /// The `TokenStream` type is large enough to represent a single `TokenTree` without allocation.
332 /// `ThinTokenStream` is smaller, but needs to allocate to represent a single `TokenTree`.
333 /// We must use `ThinTokenStream` in `TokenTree::Delimited` to avoid infinite size due to recursion.
334 #[derive(Debug, Clone)]
335 pub struct ThinTokenStream(Option<RcSlice<TokenStream>>);
337 impl From<TokenStream> for ThinTokenStream {
338 fn from(stream: TokenStream) -> ThinTokenStream {
339 ThinTokenStream(match stream.kind {
340 TokenStreamKind::Empty => None,
341 TokenStreamKind::Tree(tree) => Some(RcSlice::new(vec![tree.into()])),
342 TokenStreamKind::Stream(stream) => Some(stream),
347 impl From<ThinTokenStream> for TokenStream {
348 fn from(stream: ThinTokenStream) -> TokenStream {
349 stream.0.map(TokenStream::concat_rc_slice).unwrap_or_else(TokenStream::empty)
353 impl Eq for ThinTokenStream {}
355 impl PartialEq<ThinTokenStream> for ThinTokenStream {
356 fn eq(&self, other: &ThinTokenStream) -> bool {
357 TokenStream::from(self.clone()) == TokenStream::from(other.clone())
361 impl fmt::Display for TokenStream {
362 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
363 f.write_str(&pprust::tts_to_string(&self.trees().collect::<Vec<_>>()))
367 impl Encodable for TokenStream {
368 fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), E::Error> {
369 self.trees().collect::<Vec<_>>().encode(encoder)
373 impl Decodable for TokenStream {
374 fn decode<D: Decoder>(decoder: &mut D) -> Result<TokenStream, D::Error> {
375 Vec::<TokenTree>::decode(decoder).map(|vec| vec.into_iter().collect())
379 impl Hash for TokenStream {
380 fn hash<H: hash::Hasher>(&self, state: &mut H) {
381 for tree in self.trees() {
387 impl Encodable for ThinTokenStream {
388 fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), E::Error> {
389 TokenStream::from(self.clone()).encode(encoder)
393 impl Decodable for ThinTokenStream {
394 fn decode<D: Decoder>(decoder: &mut D) -> Result<ThinTokenStream, D::Error> {
395 TokenStream::decode(decoder).map(Into::into)
399 impl Hash for ThinTokenStream {
400 fn hash<H: hash::Hasher>(&self, state: &mut H) {
401 TokenStream::from(self.clone()).hash(state);
409 use syntax::ast::Ident;
410 use syntax_pos::{Span, BytePos, NO_EXPANSION};
411 use parse::token::Token;
412 use util::parser_testing::string_to_stream;
414 fn string_to_ts(string: &str) -> TokenStream {
415 string_to_stream(string.to_owned())
418 fn sp(a: u32, b: u32) -> Span {
422 expn_id: NO_EXPANSION,
428 let test_res = string_to_ts("foo::bar::baz");
429 let test_fst = string_to_ts("foo::bar");
430 let test_snd = string_to_ts("::baz");
431 let eq_res = TokenStream::concat(vec![test_fst, test_snd]);
432 assert_eq!(test_res.trees().count(), 5);
433 assert_eq!(eq_res.trees().count(), 5);
434 assert_eq!(test_res.eq_unspanned(&eq_res), true);
438 fn test_to_from_bijection() {
439 let test_start = string_to_ts("foo::bar(baz)");
440 let test_end = test_start.trees().collect();
441 assert_eq!(test_start, test_end)
446 let test_res = string_to_ts("foo");
447 let test_eqs = string_to_ts("foo");
448 assert_eq!(test_res, test_eqs)
453 let test_res = string_to_ts("::bar::baz");
454 let test_eqs = string_to_ts("::bar::baz");
455 assert_eq!(test_res, test_eqs)
460 let test_res = string_to_ts("");
461 let test_eqs = string_to_ts("");
462 assert_eq!(test_res, test_eqs)
467 let test_res = string_to_ts("::bar::baz");
468 let test_eqs = string_to_ts("bar::baz");
469 assert_eq!(test_res == test_eqs, false)
474 let test_res = string_to_ts("(bar,baz)");
475 let test_eqs = string_to_ts("bar,baz");
476 assert_eq!(test_res == test_eqs, false)
481 let test0: TokenStream = Vec::<TokenTree>::new().into_iter().collect();
482 let test1: TokenStream =
483 TokenTree::Token(sp(0, 1), Token::Ident(Ident::from_str("a"))).into();
484 let test2 = string_to_ts("foo(bar::baz)");
486 assert_eq!(test0.is_empty(), true);
487 assert_eq!(test1.is_empty(), false);
488 assert_eq!(test2.is_empty(), false);