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