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