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