]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/ext/tt/quoted.rs
Add an unstable FileTypeExt extension trait for Windows
[rust.git] / src / libsyntax / ext / tt / quoted.rs
1 // Copyright 2017 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 use ast;
12 use ext::tt::macro_parser;
13 use parse::{token, ParseSess};
14 use print::pprust;
15 use symbol::keywords;
16 use syntax_pos::{BytePos, Span, DUMMY_SP};
17 use tokenstream;
18
19 use std::rc::Rc;
20
21 /// Contains the sub-token-trees of a "delimited" token tree, such as the contents of `(`. Note
22 /// that the delimiter itself might be `NoDelim`.
23 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
24 pub struct Delimited {
25     pub delim: token::DelimToken,
26     pub tts: Vec<TokenTree>,
27 }
28
29 impl Delimited {
30     /// Return the opening delimiter (possibly `NoDelim`).
31     pub fn open_token(&self) -> token::Token {
32         token::OpenDelim(self.delim)
33     }
34
35     /// Return the closing delimiter (possibly `NoDelim`).
36     pub fn close_token(&self) -> token::Token {
37         token::CloseDelim(self.delim)
38     }
39
40     /// Return a `self::TokenTree` with a `Span` corresponding to the opening delimiter.
41     pub fn open_tt(&self, span: Span) -> TokenTree {
42         let open_span = if span == DUMMY_SP {
43             DUMMY_SP
44         } else {
45             span.with_lo(span.lo() + BytePos(self.delim.len() as u32))
46         };
47         TokenTree::Token(open_span, self.open_token())
48     }
49
50     /// Return a `self::TokenTree` with a `Span` corresponding to the closing delimiter.
51     pub fn close_tt(&self, span: Span) -> TokenTree {
52         let close_span = if span == DUMMY_SP {
53             DUMMY_SP
54         } else {
55             span.with_lo(span.hi() - BytePos(self.delim.len() as u32))
56         };
57         TokenTree::Token(close_span, self.close_token())
58     }
59 }
60
61 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
62 pub struct SequenceRepetition {
63     /// The sequence of token trees
64     pub tts: Vec<TokenTree>,
65     /// The optional separator
66     pub separator: Option<token::Token>,
67     /// Whether the sequence can be repeated zero (*), or one or more times (+)
68     pub op: KleeneOp,
69     /// The number of `Match`s that appear in the sequence (and subsequences)
70     pub num_captures: usize,
71 }
72
73 /// A Kleene-style [repetition operator](http://en.wikipedia.org/wiki/Kleene_star)
74 /// for token sequences.
75 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
76 pub enum KleeneOp {
77     /// Kleene star (`*`) for zero or more repetitions
78     ZeroOrMore,
79     /// Kleene plus (`+`) for one or more repetitions
80     OneOrMore,
81 }
82
83 /// Similar to `tokenstream::TokenTree`, except that `$i`, `$i:ident`, and `$(...)`
84 /// are "first-class" token trees. Useful for parsing macros.
85 #[derive(Debug, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
86 pub enum TokenTree {
87     Token(Span, token::Token),
88     Delimited(Span, Rc<Delimited>),
89     /// A kleene-style repetition sequence
90     Sequence(Span, Rc<SequenceRepetition>),
91     /// E.g. `$var`
92     MetaVar(Span, ast::Ident),
93     /// E.g. `$var:expr`. This is only used in the left hand side of MBE macros.
94     MetaVarDecl(
95         Span,
96         ast::Ident, /* name to bind */
97         ast::Ident, /* kind of nonterminal */
98     ),
99 }
100
101 impl TokenTree {
102     /// Return the number of tokens in the tree.
103     pub fn len(&self) -> usize {
104         match *self {
105             TokenTree::Delimited(_, ref delimed) => match delimed.delim {
106                 token::NoDelim => delimed.tts.len(),
107                 _ => delimed.tts.len() + 2,
108             },
109             TokenTree::Sequence(_, ref seq) => seq.tts.len(),
110             _ => 0,
111         }
112     }
113
114     /// Returns true if the given token tree contains no other tokens. This is vacuously true for
115     /// single tokens or metavar/decls, but may be false for delimited trees or sequences.
116     pub fn is_empty(&self) -> bool {
117         match *self {
118             TokenTree::Delimited(_, ref delimed) => match delimed.delim {
119                 token::NoDelim => delimed.tts.is_empty(),
120                 _ => false,
121             },
122             TokenTree::Sequence(_, ref seq) => seq.tts.is_empty(),
123             _ => true,
124         }
125     }
126
127     /// Get the `index`-th sub-token-tree. This only makes sense for delimited trees and sequences.
128     pub fn get_tt(&self, index: usize) -> TokenTree {
129         match (self, index) {
130             (&TokenTree::Delimited(_, ref delimed), _) if delimed.delim == token::NoDelim => {
131                 delimed.tts[index].clone()
132             }
133             (&TokenTree::Delimited(span, ref delimed), _) => {
134                 if index == 0 {
135                     return delimed.open_tt(span);
136                 }
137                 if index == delimed.tts.len() + 1 {
138                     return delimed.close_tt(span);
139                 }
140                 delimed.tts[index - 1].clone()
141             }
142             (&TokenTree::Sequence(_, ref seq), _) => seq.tts[index].clone(),
143             _ => panic!("Cannot expand a token tree"),
144         }
145     }
146
147     /// Retrieve the `TokenTree`'s span.
148     pub fn span(&self) -> Span {
149         match *self {
150             TokenTree::Token(sp, _)
151             | TokenTree::MetaVar(sp, _)
152             | TokenTree::MetaVarDecl(sp, _, _)
153             | TokenTree::Delimited(sp, _)
154             | TokenTree::Sequence(sp, _) => sp,
155         }
156     }
157 }
158
159 /// Takes a `tokenstream::TokenStream` and returns a `Vec<self::TokenTree>`. Specifically, this
160 /// takes a generic `TokenStream`, such as is used in the rest of the compiler, and returns a
161 /// collection of `TokenTree` for use in parsing a macro.
162 ///
163 /// # Parameters
164 ///
165 /// - `input`: a token stream to read from, the contents of which we are parsing.
166 /// - `expect_matchers`: `parse` can be used to parse either the "patterns" or the "body" of a
167 ///   macro. Both take roughly the same form _except_ that in a pattern, metavars are declared with
168 ///   their "matcher" type. For example `$var:expr` or `$id:ident`. In this example, `expr` and
169 ///   `ident` are "matchers". They are not present in the body of a macro rule -- just in the
170 ///   pattern, so we pass a parameter to indicate whether to expect them or not.
171 /// - `sess`: the parsing session. Any errors will be emitted to this session.
172 ///
173 /// # Returns
174 ///
175 /// A collection of `self::TokenTree`. There may also be some errors emitted to `sess`.
176 pub fn parse(
177     input: tokenstream::TokenStream,
178     expect_matchers: bool,
179     sess: &ParseSess,
180 ) -> Vec<TokenTree> {
181     // Will contain the final collection of `self::TokenTree`
182     let mut result = Vec::new();
183
184     // For each token tree in `input`, parse the token into a `self::TokenTree`, consuming
185     // additional trees if need be.
186     let mut trees = input.trees();
187     while let Some(tree) = trees.next() {
188         let tree = parse_tree(tree, &mut trees, expect_matchers, sess);
189
190         // Given the parsed tree, if there is a metavar and we are expecting matchers, actually
191         // parse out the matcher (i.e. in `$id:ident` this would parse the `:` and `ident`).
192         match tree {
193             TokenTree::MetaVar(start_sp, ident) if expect_matchers => {
194                 let span = match trees.next() {
195                     Some(tokenstream::TokenTree::Token(span, token::Colon)) => match trees.next() {
196                         Some(tokenstream::TokenTree::Token(end_sp, ref tok)) => match tok.ident() {
197                             Some(kind) => {
198                                 let span = end_sp.with_lo(start_sp.lo());
199                                 result.push(TokenTree::MetaVarDecl(span, ident, kind));
200                                 continue;
201                             }
202                             _ => end_sp,
203                         },
204                         tree => tree.as_ref()
205                             .map(tokenstream::TokenTree::span)
206                             .unwrap_or(span),
207                     },
208                     tree => tree.as_ref()
209                         .map(tokenstream::TokenTree::span)
210                         .unwrap_or(start_sp),
211                 };
212                 sess.missing_fragment_specifiers.borrow_mut().insert(span);
213                 result.push(TokenTree::MetaVarDecl(
214                     span,
215                     ident,
216                     keywords::Invalid.ident(),
217                 ));
218             }
219
220             // Not a metavar or no matchers allowed, so just return the tree
221             _ => result.push(tree),
222         }
223     }
224     result
225 }
226
227 /// Takes a `tokenstream::TokenTree` and returns a `self::TokenTree`. Specifically, this takes a
228 /// generic `TokenTree`, such as is used in the rest of the compiler, and returns a `TokenTree`
229 /// for use in parsing a macro.
230 ///
231 /// Converting the given tree may involve reading more tokens.
232 ///
233 /// # Parameters
234 ///
235 /// - `tree`: the tree we wish to convert.
236 /// - `trees`: an iterator over trees. We may need to read more tokens from it in order to finish
237 ///   converting `tree`
238 /// - `expect_matchers`: same as for `parse` (see above).
239 /// - `sess`: the parsing session. Any errors will be emitted to this session.
240 fn parse_tree<I>(
241     tree: tokenstream::TokenTree,
242     trees: &mut I,
243     expect_matchers: bool,
244     sess: &ParseSess,
245 ) -> TokenTree
246 where
247     I: Iterator<Item = tokenstream::TokenTree>,
248 {
249     // Depending on what `tree` is, we could be parsing different parts of a macro
250     match tree {
251         // `tree` is a `$` token. Look at the next token in `trees`
252         tokenstream::TokenTree::Token(span, token::Dollar) => match trees.next() {
253             // `tree` is followed by a delimited set of token trees. This indicates the beginning
254             // of a repetition sequence in the macro (e.g. `$(pat)*`).
255             Some(tokenstream::TokenTree::Delimited(span, delimited)) => {
256                 // Must have `(` not `{` or `[`
257                 if delimited.delim != token::Paren {
258                     let tok = pprust::token_to_string(&token::OpenDelim(delimited.delim));
259                     let msg = format!("expected `(`, found `{}`", tok);
260                     sess.span_diagnostic.span_err(span, &msg);
261                 }
262                 // Parse the contents of the sequence itself
263                 let sequence = parse(delimited.tts.into(), expect_matchers, sess);
264                 // Get the Kleene operator and optional separator
265                 let (separator, op) = parse_sep_and_kleene_op(trees, span, sess);
266                 // Count the number of captured "names" (i.e. named metavars)
267                 let name_captures = macro_parser::count_names(&sequence);
268                 TokenTree::Sequence(
269                     span,
270                     Rc::new(SequenceRepetition {
271                         tts: sequence,
272                         separator,
273                         op,
274                         num_captures: name_captures,
275                     }),
276                 )
277             }
278
279             // `tree` is followed by an `ident`. This could be `$meta_var` or the `$crate` special
280             // metavariable that names the crate of the invokation.
281             Some(tokenstream::TokenTree::Token(ident_span, ref token)) if token.is_ident() => {
282                 let ident = token.ident().unwrap();
283                 let span = ident_span.with_lo(span.lo());
284                 if ident.name == keywords::Crate.name() {
285                     let ident = ast::Ident {
286                         name: keywords::DollarCrate.name(),
287                         ..ident
288                     };
289                     TokenTree::Token(span, token::Ident(ident))
290                 } else {
291                     TokenTree::MetaVar(span, ident)
292                 }
293             }
294
295             // `tree` is followed by a random token. This is an error.
296             Some(tokenstream::TokenTree::Token(span, tok)) => {
297                 let msg = format!(
298                     "expected identifier, found `{}`",
299                     pprust::token_to_string(&tok)
300                 );
301                 sess.span_diagnostic.span_err(span, &msg);
302                 TokenTree::MetaVar(span, keywords::Invalid.ident())
303             }
304
305             // There are no more tokens. Just return the `$` we already have.
306             None => TokenTree::Token(span, token::Dollar),
307         },
308
309         // `tree` is an arbitrary token. Keep it.
310         tokenstream::TokenTree::Token(span, tok) => TokenTree::Token(span, tok),
311
312         // `tree` is the beginning of a delimited set of tokens (e.g. `(` or `{`). We need to
313         // descend into the delimited set and further parse it.
314         tokenstream::TokenTree::Delimited(span, delimited) => TokenTree::Delimited(
315             span,
316             Rc::new(Delimited {
317                 delim: delimited.delim,
318                 tts: parse(delimited.tts.into(), expect_matchers, sess),
319             }),
320         ),
321     }
322 }
323
324 /// Attempt to parse a single Kleene star, possibly with a separator.
325 ///
326 /// For example, in a pattern such as `$(a),*`, `a` is the pattern to be repeated, `,` is the
327 /// separator, and `*` is the Kleene operator. This function is specifically concerned with parsing
328 /// the last two tokens of such a pattern: namely, the optional separator and the Kleene operator
329 /// itself. Note that here we are parsing the _macro_ itself, rather than trying to match some
330 /// stream of tokens in an invocation of a macro.
331 ///
332 /// This function will take some input iterator `input` corresponding to `span` and a parsing
333 /// session `sess`. If the next one (or possibly two) tokens in `input` correspond to a Kleene
334 /// operator and separator, then a tuple with `(separator, KleeneOp)` is returned. Otherwise, an
335 /// error with the appropriate span is emitted to `sess` and a dummy value is returned.
336 fn parse_sep_and_kleene_op<I>(
337     input: &mut I,
338     span: Span,
339     sess: &ParseSess,
340 ) -> (Option<token::Token>, KleeneOp)
341 where
342     I: Iterator<Item = tokenstream::TokenTree>,
343 {
344     fn kleene_op(token: &token::Token) -> Option<KleeneOp> {
345         match *token {
346             token::BinOp(token::Star) => Some(KleeneOp::ZeroOrMore),
347             token::BinOp(token::Plus) => Some(KleeneOp::OneOrMore),
348             _ => None,
349         }
350     }
351
352     // We attempt to look at the next two token trees in `input`. I will call the first #1 and the
353     // second #2. If #1 and #2 don't match a valid KleeneOp with/without separator, that is an
354     // error, and we should emit an error on the most specific span possible.
355     let span = match input.next() {
356         // #1 is a token
357         Some(tokenstream::TokenTree::Token(span, tok)) => match kleene_op(&tok) {
358             // #1 is a KleeneOp with no separator
359             Some(op) => return (None, op),
360
361             // #1 is not a KleeneOp, but may be a separator... need to look at #2
362             None => match input.next() {
363                 // #2 is a token
364                 Some(tokenstream::TokenTree::Token(span, tok2)) => match kleene_op(&tok2) {
365                     // #2 is a KleeneOp, so #1 must be a separator
366                     Some(op) => return (Some(tok), op),
367
368                     // #2 is not a KleeneOp... error
369                     None => span,
370                 },
371
372                 // #2 is not a token at all... error
373                 tree => tree.as_ref()
374                     .map(tokenstream::TokenTree::span)
375                     .unwrap_or(span),
376             },
377         },
378
379         // #1 is not a token at all... error
380         tree => tree.as_ref()
381             .map(tokenstream::TokenTree::span)
382             .unwrap_or(span),
383     };
384
385     // Error...
386     sess.span_diagnostic.span_err(span, "expected `*` or `+`");
387     (None, KleeneOp::ZeroOrMore)
388 }