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