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