]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/tokenstream.rs
add -Z pre-link-arg{,s} to rustc
[rust.git] / src / libsyntax / tokenstream.rs
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.
4 //
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.
10
11 //! # Token Streams
12 //!
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.
16 //!
17 //! ## Ownership
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.
24
25 use syntax_pos::{BytePos, Span, DUMMY_SP};
26 use ext::base;
27 use ext::tt::{macro_parser, quoted};
28 use parse::Directory;
29 use parse::token::{self, Token};
30 use print::pprust;
31 use serialize::{Decoder, Decodable, Encoder, Encodable};
32 use util::RcSlice;
33
34 use std::{fmt, iter, mem};
35 use std::hash::{self, Hash};
36
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,
44 }
45
46 impl Delimited {
47     /// Returns the opening delimiter as a token.
48     pub fn open_token(&self) -> token::Token {
49         token::OpenDelim(self.delim)
50     }
51
52     /// Returns the closing delimiter as a token.
53     pub fn close_token(&self) -> token::Token {
54         token::CloseDelim(self.delim)
55     }
56
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 {
60             DUMMY_SP
61         } else {
62             Span { hi: span.lo + BytePos(self.delim.len() as u32), ..span }
63         };
64         TokenTree::Token(open_span, self.open_token())
65     }
66
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 {
70             DUMMY_SP
71         } else {
72             Span { lo: span.hi - BytePos(self.delim.len() as u32), ..span }
73         };
74         TokenTree::Token(close_span, self.close_token())
75     }
76
77     /// Returns the token trees inside the delimiters.
78     pub fn stream(&self) -> TokenStream {
79         self.tts.clone().into()
80     }
81 }
82
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.
87 ///
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.
92 ///
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)]
96 pub enum TokenTree {
97     /// A single token
98     Token(Span, token::Token),
99     /// A delimited sequence of token trees
100     Delimited(Span, Delimited),
101 }
102
103 impl TokenTree {
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,
111         };
112         macro_parser::parse(cx.parse_sess(), tts, mtch, Some(directory))
113     }
114
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))
122             }
123             (_, _) => false,
124         }
125     }
126
127     /// Retrieve the TokenTree's span.
128     pub fn span(&self) -> Span {
129         match *self {
130             TokenTree::Token(sp, _) | TokenTree::Delimited(sp, _) => sp,
131         }
132     }
133
134     /// Indicates if the stream is a token that is equal to the provided token.
135     pub fn eq_token(&self, t: Token) -> bool {
136         match *self {
137             TokenTree::Token(_, ref tk) => *tk == t,
138             _ => false,
139         }
140     }
141 }
142
143 /// # Token Streams
144 ///
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,
152 }
153
154 #[derive(Clone, Debug)]
155 enum TokenStreamKind {
156     Empty,
157     Tree(TokenTree),
158     Stream(RcSlice<TokenStream>),
159 }
160
161 impl From<TokenTree> for TokenStream {
162     fn from(tt: TokenTree) -> TokenStream {
163         TokenStream { kind: TokenStreamKind::Tree(tt) }
164     }
165 }
166
167 impl From<Token> for TokenStream {
168     fn from(token: Token) -> TokenStream {
169         TokenTree::Token(DUMMY_SP, token).into()
170     }
171 }
172
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<_>>())
176     }
177 }
178
179 impl Eq for TokenStream {}
180
181 impl PartialEq<TokenStream> for TokenStream {
182     fn eq(&self, other: &TokenStream) -> bool {
183         self.trees().eq(other.trees())
184     }
185 }
186
187 impl TokenStream {
188     pub fn empty() -> TokenStream {
189         TokenStream { kind: TokenStreamKind::Empty }
190     }
191
192     pub fn is_empty(&self) -> bool {
193         match self.kind {
194             TokenStreamKind::Empty => true,
195             _ => false,
196         }
197     }
198
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)),
204         }
205     }
206
207     fn concat_rc_slice(streams: RcSlice<TokenStream>) -> TokenStream {
208         TokenStream { kind: TokenStreamKind::Stream(streams) }
209     }
210
211     pub fn trees(&self) -> Cursor {
212         self.clone().into_trees()
213     }
214
215     pub fn into_trees(self) -> Cursor {
216         Cursor::new(self)
217     }
218
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) {
223                 return false;
224             }
225         }
226         true
227     }
228 }
229
230 pub struct Cursor(CursorKind);
231
232 enum CursorKind {
233     Empty,
234     Tree(TokenTree, bool /* consumed? */),
235     Stream(StreamCursor),
236 }
237
238 struct StreamCursor {
239     stream: RcSlice<TokenStream>,
240     index: usize,
241     stack: Vec<(RcSlice<TokenStream>, usize)>,
242 }
243
244 impl Iterator for Cursor {
245     type Item = TokenTree;
246
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) => {
251                 *consumed = true;
252                 return Some(tree.clone());
253             }
254             _ => return None,
255         };
256
257         loop {
258             if cursor.index < cursor.stream.len() {
259                 match cursor.stream[cursor.index].kind.clone() {
260                     TokenStreamKind::Tree(tree) => {
261                         cursor.index += 1;
262                         return Some(tree);
263                     }
264                     TokenStreamKind::Stream(stream) => {
265                         cursor.stack.push((mem::replace(&mut cursor.stream, stream),
266                                            mem::replace(&mut cursor.index, 0) + 1));
267                     }
268                     TokenStreamKind::Empty => {
269                         cursor.index += 1;
270                     }
271                 }
272             } else if let Some((stream, index)) = cursor.stack.pop() {
273                 cursor.stream = stream;
274                 cursor.index = index;
275             } else {
276                 return None;
277             }
278         }
279     }
280 }
281
282 impl Cursor {
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() })
289             }
290         })
291     }
292
293     pub fn original_stream(self) -> TokenStream {
294         match self.0 {
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)
299             }),
300         }
301     }
302
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),
311                         Err(n) => n,
312                     },
313                     _ => n,
314                 };
315             }
316
317             Err(n)
318         }
319
320         match self.0 {
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),
328                             Err(n) => n,
329                         }
330                     }
331
332                     Err(n)
333                 })
334             }
335         }.ok()
336     }
337 }
338
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>>);
344
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),
351         })
352     }
353 }
354
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)
358     }
359 }
360
361 impl Eq for ThinTokenStream {}
362
363 impl PartialEq<ThinTokenStream> for ThinTokenStream {
364     fn eq(&self, other: &ThinTokenStream) -> bool {
365         TokenStream::from(self.clone()) == TokenStream::from(other.clone())
366     }
367 }
368
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()))
372     }
373 }
374
375 impl Encodable for TokenStream {
376     fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), E::Error> {
377         self.trees().collect::<Vec<_>>().encode(encoder)
378     }
379 }
380
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())
384     }
385 }
386
387 impl Hash for TokenStream {
388     fn hash<H: hash::Hasher>(&self, state: &mut H) {
389         for tree in self.trees() {
390             tree.hash(state);
391         }
392     }
393 }
394
395 impl Encodable for ThinTokenStream {
396     fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), E::Error> {
397         TokenStream::from(self.clone()).encode(encoder)
398     }
399 }
400
401 impl Decodable for ThinTokenStream {
402     fn decode<D: Decoder>(decoder: &mut D) -> Result<ThinTokenStream, D::Error> {
403         TokenStream::decode(decoder).map(Into::into)
404     }
405 }
406
407 impl Hash for ThinTokenStream {
408     fn hash<H: hash::Hasher>(&self, state: &mut H) {
409         TokenStream::from(self.clone()).hash(state);
410     }
411 }
412
413
414 #[cfg(test)]
415 mod tests {
416     use super::*;
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;
421
422     fn string_to_ts(string: &str) -> TokenStream {
423         string_to_stream(string.to_owned())
424     }
425
426     fn sp(a: u32, b: u32) -> Span {
427         Span {
428             lo: BytePos(a),
429             hi: BytePos(b),
430             ctxt: NO_EXPANSION,
431         }
432     }
433
434     #[test]
435     fn test_concat() {
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);
443     }
444
445     #[test]
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)
450     }
451
452     #[test]
453     fn test_eq_0() {
454         let test_res = string_to_ts("foo");
455         let test_eqs = string_to_ts("foo");
456         assert_eq!(test_res, test_eqs)
457     }
458
459     #[test]
460     fn test_eq_1() {
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)
464     }
465
466     #[test]
467     fn test_eq_3() {
468         let test_res = string_to_ts("");
469         let test_eqs = string_to_ts("");
470         assert_eq!(test_res, test_eqs)
471     }
472
473     #[test]
474     fn test_diseq_0() {
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)
478     }
479
480     #[test]
481     fn test_diseq_1() {
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)
485     }
486
487     #[test]
488     fn test_is_empty() {
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)");
493
494         assert_eq!(test0.is_empty(), true);
495         assert_eq!(test1.is_empty(), false);
496         assert_eq!(test2.is_empty(), false);
497     }
498 }