]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_expand/src/mbe/macro_rules.rs
Rollup merge of #96917 - marti4d:master, r=ChrisDenton
[rust.git] / compiler / rustc_expand / src / mbe / macro_rules.rs
1 use crate::base::{DummyResult, ExtCtxt, MacResult, TTMacroExpander};
2 use crate::base::{SyntaxExtension, SyntaxExtensionKind};
3 use crate::expand::{ensure_complete_parse, parse_ast_fragment, AstFragment, AstFragmentKind};
4 use crate::mbe;
5 use crate::mbe::macro_check;
6 use crate::mbe::macro_parser::{Error, ErrorReported, Failure, Success, TtParser};
7 use crate::mbe::macro_parser::{MatchedSeq, MatchedTokenTree, MatcherLoc};
8 use crate::mbe::transcribe::transcribe;
9
10 use rustc_ast as ast;
11 use rustc_ast::token::{self, Delimiter, NonterminalKind, Token, TokenKind, TokenKind::*};
12 use rustc_ast::tokenstream::{DelimSpan, TokenStream};
13 use rustc_ast::{NodeId, DUMMY_NODE_ID};
14 use rustc_ast_pretty::pprust;
15 use rustc_attr::{self as attr, TransparencyError};
16 use rustc_data_structures::fx::FxHashMap;
17 use rustc_errors::{Applicability, Diagnostic, DiagnosticBuilder};
18 use rustc_feature::Features;
19 use rustc_lint_defs::builtin::{
20     RUST_2021_INCOMPATIBLE_OR_PATTERNS, SEMICOLON_IN_EXPRESSIONS_FROM_MACROS,
21 };
22 use rustc_lint_defs::BuiltinLintDiagnostics;
23 use rustc_parse::parser::Parser;
24 use rustc_session::parse::ParseSess;
25 use rustc_session::Session;
26 use rustc_span::edition::Edition;
27 use rustc_span::hygiene::Transparency;
28 use rustc_span::symbol::{kw, sym, Ident, MacroRulesNormalizedIdent};
29 use rustc_span::Span;
30
31 use std::borrow::Cow;
32 use std::collections::hash_map::Entry;
33 use std::{mem, slice};
34 use tracing::debug;
35
36 crate struct ParserAnyMacro<'a> {
37     parser: Parser<'a>,
38
39     /// Span of the expansion site of the macro this parser is for
40     site_span: Span,
41     /// The ident of the macro we're parsing
42     macro_ident: Ident,
43     lint_node_id: NodeId,
44     is_trailing_mac: bool,
45     arm_span: Span,
46     /// Whether or not this macro is defined in the current crate
47     is_local: bool,
48 }
49
50 crate fn annotate_err_with_kind(err: &mut Diagnostic, kind: AstFragmentKind, span: Span) {
51     match kind {
52         AstFragmentKind::Ty => {
53             err.span_label(span, "this macro call doesn't expand to a type");
54         }
55         AstFragmentKind::Pat => {
56             err.span_label(span, "this macro call doesn't expand to a pattern");
57         }
58         _ => {}
59     };
60 }
61
62 fn emit_frag_parse_err(
63     mut e: DiagnosticBuilder<'_, rustc_errors::ErrorGuaranteed>,
64     parser: &Parser<'_>,
65     orig_parser: &mut Parser<'_>,
66     site_span: Span,
67     arm_span: Span,
68     kind: AstFragmentKind,
69 ) {
70     // FIXME(davidtwco): avoid depending on the error message text
71     if parser.token == token::Eof && e.message[0].0.expect_str().ends_with(", found `<eof>`") {
72         if !e.span.is_dummy() {
73             // early end of macro arm (#52866)
74             e.replace_span_with(parser.sess.source_map().next_point(parser.token.span));
75         }
76         let msg = &e.message[0];
77         e.message[0] = (
78             rustc_errors::DiagnosticMessage::Str(format!(
79                 "macro expansion ends with an incomplete expression: {}",
80                 msg.0.expect_str().replace(", found `<eof>`", ""),
81             )),
82             msg.1,
83         );
84     }
85     if e.span.is_dummy() {
86         // Get around lack of span in error (#30128)
87         e.replace_span_with(site_span);
88         if !parser.sess.source_map().is_imported(arm_span) {
89             e.span_label(arm_span, "in this macro arm");
90         }
91     } else if parser.sess.source_map().is_imported(parser.token.span) {
92         e.span_label(site_span, "in this macro invocation");
93     }
94     match kind {
95         // Try a statement if an expression is wanted but failed and suggest adding `;` to call.
96         AstFragmentKind::Expr => match parse_ast_fragment(orig_parser, AstFragmentKind::Stmts) {
97             Err(err) => err.cancel(),
98             Ok(_) => {
99                 e.note(
100                     "the macro call doesn't expand to an expression, but it can expand to a statement",
101                 );
102                 e.span_suggestion_verbose(
103                     site_span.shrink_to_hi(),
104                     "add `;` to interpret the expansion as a statement",
105                     ";".to_string(),
106                     Applicability::MaybeIncorrect,
107                 );
108             }
109         },
110         _ => annotate_err_with_kind(&mut e, kind, site_span),
111     };
112     e.emit();
113 }
114
115 impl<'a> ParserAnyMacro<'a> {
116     crate fn make(mut self: Box<ParserAnyMacro<'a>>, kind: AstFragmentKind) -> AstFragment {
117         let ParserAnyMacro {
118             site_span,
119             macro_ident,
120             ref mut parser,
121             lint_node_id,
122             arm_span,
123             is_trailing_mac,
124             is_local,
125         } = *self;
126         let snapshot = &mut parser.clone();
127         let fragment = match parse_ast_fragment(parser, kind) {
128             Ok(f) => f,
129             Err(err) => {
130                 emit_frag_parse_err(err, parser, snapshot, site_span, arm_span, kind);
131                 return kind.dummy(site_span);
132             }
133         };
134
135         // We allow semicolons at the end of expressions -- e.g., the semicolon in
136         // `macro_rules! m { () => { panic!(); } }` isn't parsed by `.parse_expr()`,
137         // but `m!()` is allowed in expression positions (cf. issue #34706).
138         if kind == AstFragmentKind::Expr && parser.token == token::Semi {
139             if is_local {
140                 parser.sess.buffer_lint_with_diagnostic(
141                     SEMICOLON_IN_EXPRESSIONS_FROM_MACROS,
142                     parser.token.span,
143                     lint_node_id,
144                     "trailing semicolon in macro used in expression position",
145                     BuiltinLintDiagnostics::TrailingMacro(is_trailing_mac, macro_ident),
146                 );
147             }
148             parser.bump();
149         }
150
151         // Make sure we don't have any tokens left to parse so we don't silently drop anything.
152         let path = ast::Path::from_ident(macro_ident.with_span_pos(site_span));
153         ensure_complete_parse(parser, &path, kind.name(), site_span);
154         fragment
155     }
156 }
157
158 struct MacroRulesMacroExpander {
159     node_id: NodeId,
160     name: Ident,
161     span: Span,
162     transparency: Transparency,
163     lhses: Vec<Vec<MatcherLoc>>,
164     rhses: Vec<mbe::TokenTree>,
165     valid: bool,
166 }
167
168 impl TTMacroExpander for MacroRulesMacroExpander {
169     fn expand<'cx>(
170         &self,
171         cx: &'cx mut ExtCtxt<'_>,
172         sp: Span,
173         input: TokenStream,
174     ) -> Box<dyn MacResult + 'cx> {
175         if !self.valid {
176             return DummyResult::any(sp);
177         }
178         expand_macro(
179             cx,
180             sp,
181             self.span,
182             self.node_id,
183             self.name,
184             self.transparency,
185             input,
186             &self.lhses,
187             &self.rhses,
188         )
189     }
190 }
191
192 fn macro_rules_dummy_expander<'cx>(
193     _: &'cx mut ExtCtxt<'_>,
194     span: Span,
195     _: TokenStream,
196 ) -> Box<dyn MacResult + 'cx> {
197     DummyResult::any(span)
198 }
199
200 fn trace_macros_note(cx_expansions: &mut FxHashMap<Span, Vec<String>>, sp: Span, message: String) {
201     let sp = sp.macro_backtrace().last().map_or(sp, |trace| trace.call_site);
202     cx_expansions.entry(sp).or_default().push(message);
203 }
204
205 /// Expands the rules based macro defined by `lhses` and `rhses` for a given
206 /// input `arg`.
207 fn expand_macro<'cx, 'tt>(
208     cx: &'cx mut ExtCtxt<'_>,
209     sp: Span,
210     def_span: Span,
211     node_id: NodeId,
212     name: Ident,
213     transparency: Transparency,
214     arg: TokenStream,
215     lhses: &'tt [Vec<MatcherLoc>],
216     rhses: &'tt [mbe::TokenTree],
217 ) -> Box<dyn MacResult + 'cx> {
218     let sess = &cx.sess.parse_sess;
219     // Macros defined in the current crate have a real node id,
220     // whereas macros from an external crate have a dummy id.
221     let is_local = node_id != DUMMY_NODE_ID;
222
223     if cx.trace_macros() {
224         let msg = format!("expanding `{}! {{ {} }}`", name, pprust::tts_to_string(&arg));
225         trace_macros_note(&mut cx.expansions, sp, msg);
226     }
227
228     // Which arm's failure should we report? (the one furthest along)
229     let mut best_failure: Option<(Token, &str)> = None;
230
231     // We create a base parser that can be used for the "black box" parts.
232     // Every iteration needs a fresh copy of that parser. However, the parser
233     // is not mutated on many of the iterations, particularly when dealing with
234     // macros like this:
235     //
236     // macro_rules! foo {
237     //     ("a") => (A);
238     //     ("b") => (B);
239     //     ("c") => (C);
240     //     // ... etc. (maybe hundreds more)
241     // }
242     //
243     // as seen in the `html5ever` benchmark. We use a `Cow` so that the base
244     // parser is only cloned when necessary (upon mutation). Furthermore, we
245     // reinitialize the `Cow` with the base parser at the start of every
246     // iteration, so that any mutated parsers are not reused. This is all quite
247     // hacky, but speeds up the `html5ever` benchmark significantly. (Issue
248     // 68836 suggests a more comprehensive but more complex change to deal with
249     // this situation.)
250     let parser = parser_from_cx(sess, arg.clone());
251
252     // Try each arm's matchers.
253     let mut tt_parser = TtParser::new(name);
254     for (i, lhs) in lhses.iter().enumerate() {
255         // Take a snapshot of the state of pre-expansion gating at this point.
256         // This is used so that if a matcher is not `Success(..)`ful,
257         // then the spans which became gated when parsing the unsuccessful matcher
258         // are not recorded. On the first `Success(..)`ful matcher, the spans are merged.
259         let mut gated_spans_snapshot = mem::take(&mut *sess.gated_spans.spans.borrow_mut());
260
261         match tt_parser.parse_tt(&mut Cow::Borrowed(&parser), lhs) {
262             Success(named_matches) => {
263                 // The matcher was `Success(..)`ful.
264                 // Merge the gated spans from parsing the matcher with the pre-existing ones.
265                 sess.gated_spans.merge(gated_spans_snapshot);
266
267                 let (rhs, rhs_span): (&mbe::Delimited, DelimSpan) = match &rhses[i] {
268                     mbe::TokenTree::Delimited(span, delimited) => (&delimited, *span),
269                     _ => cx.span_bug(sp, "malformed macro rhs"),
270                 };
271                 let arm_span = rhses[i].span();
272
273                 let rhs_spans = rhs.tts.iter().map(|t| t.span()).collect::<Vec<_>>();
274                 // rhs has holes ( `$id` and `$(...)` that need filled)
275                 let mut tts = match transcribe(cx, &named_matches, &rhs, rhs_span, transparency) {
276                     Ok(tts) => tts,
277                     Err(mut err) => {
278                         err.emit();
279                         return DummyResult::any(arm_span);
280                     }
281                 };
282
283                 // Replace all the tokens for the corresponding positions in the macro, to maintain
284                 // proper positions in error reporting, while maintaining the macro_backtrace.
285                 if rhs_spans.len() == tts.len() {
286                     tts = tts.map_enumerated(|i, tt| {
287                         let mut tt = tt.clone();
288                         let mut sp = rhs_spans[i];
289                         sp = sp.with_ctxt(tt.span().ctxt());
290                         tt.set_span(sp);
291                         tt
292                     });
293                 }
294
295                 if cx.trace_macros() {
296                     let msg = format!("to `{}`", pprust::tts_to_string(&tts));
297                     trace_macros_note(&mut cx.expansions, sp, msg);
298                 }
299
300                 let mut p = Parser::new(sess, tts, false, None);
301                 p.last_type_ascription = cx.current_expansion.prior_type_ascription;
302
303                 if is_local {
304                     cx.resolver.record_macro_rule_usage(node_id, i);
305                 }
306
307                 // Let the context choose how to interpret the result.
308                 // Weird, but useful for X-macros.
309                 return Box::new(ParserAnyMacro {
310                     parser: p,
311
312                     // Pass along the original expansion site and the name of the macro
313                     // so we can print a useful error message if the parse of the expanded
314                     // macro leaves unparsed tokens.
315                     site_span: sp,
316                     macro_ident: name,
317                     lint_node_id: cx.current_expansion.lint_node_id,
318                     is_trailing_mac: cx.current_expansion.is_trailing_mac,
319                     arm_span,
320                     is_local,
321                 });
322             }
323             Failure(token, msg) => match best_failure {
324                 Some((ref best_token, _)) if best_token.span.lo() >= token.span.lo() => {}
325                 _ => best_failure = Some((token, msg)),
326             },
327             Error(err_sp, ref msg) => {
328                 let span = err_sp.substitute_dummy(sp);
329                 cx.struct_span_err(span, &msg).emit();
330                 return DummyResult::any(span);
331             }
332             ErrorReported => return DummyResult::any(sp),
333         }
334
335         // The matcher was not `Success(..)`ful.
336         // Restore to the state before snapshotting and maybe try again.
337         mem::swap(&mut gated_spans_snapshot, &mut sess.gated_spans.spans.borrow_mut());
338     }
339     drop(parser);
340
341     let (token, label) = best_failure.expect("ran no matchers");
342     let span = token.span.substitute_dummy(sp);
343     let mut err = cx.struct_span_err(span, &parse_failure_msg(&token));
344     err.span_label(span, label);
345     if !def_span.is_dummy() && !cx.source_map().is_imported(def_span) {
346         err.span_label(cx.source_map().guess_head_span(def_span), "when calling this macro");
347     }
348
349     // Check whether there's a missing comma in this macro call, like `println!("{}" a);`
350     if let Some((arg, comma_span)) = arg.add_comma() {
351         for lhs in lhses {
352             let parser = parser_from_cx(sess, arg.clone());
353             if let Success(_) = tt_parser.parse_tt(&mut Cow::Borrowed(&parser), lhs) {
354                 if comma_span.is_dummy() {
355                     err.note("you might be missing a comma");
356                 } else {
357                     err.span_suggestion_short(
358                         comma_span,
359                         "missing comma here",
360                         ", ".to_string(),
361                         Applicability::MachineApplicable,
362                     );
363                 }
364             }
365         }
366     }
367     err.emit();
368     cx.trace_macros_diag();
369     DummyResult::any(sp)
370 }
371
372 // Note that macro-by-example's input is also matched against a token tree:
373 //                   $( $lhs:tt => $rhs:tt );+
374 //
375 // Holy self-referential!
376
377 /// Converts a macro item into a syntax extension.
378 pub fn compile_declarative_macro(
379     sess: &Session,
380     features: &Features,
381     def: &ast::Item,
382     edition: Edition,
383 ) -> (SyntaxExtension, Vec<Span>) {
384     debug!("compile_declarative_macro: {:?}", def);
385     let mk_syn_ext = |expander| {
386         SyntaxExtension::new(
387             sess,
388             SyntaxExtensionKind::LegacyBang(expander),
389             def.span,
390             Vec::new(),
391             edition,
392             def.ident.name,
393             &def.attrs,
394         )
395     };
396     let dummy_syn_ext = || (mk_syn_ext(Box::new(macro_rules_dummy_expander)), Vec::new());
397
398     let diag = &sess.parse_sess.span_diagnostic;
399     let lhs_nm = Ident::new(sym::lhs, def.span);
400     let rhs_nm = Ident::new(sym::rhs, def.span);
401     let tt_spec = Some(NonterminalKind::TT);
402
403     // Parse the macro_rules! invocation
404     let (macro_rules, body) = match &def.kind {
405         ast::ItemKind::MacroDef(def) => (def.macro_rules, def.body.inner_tokens()),
406         _ => unreachable!(),
407     };
408
409     // The pattern that macro_rules matches.
410     // The grammar for macro_rules! is:
411     // $( $lhs:tt => $rhs:tt );+
412     // ...quasiquoting this would be nice.
413     // These spans won't matter, anyways
414     let argument_gram = vec![
415         mbe::TokenTree::Sequence(
416             DelimSpan::dummy(),
417             mbe::SequenceRepetition {
418                 tts: vec![
419                     mbe::TokenTree::MetaVarDecl(def.span, lhs_nm, tt_spec),
420                     mbe::TokenTree::token(token::FatArrow, def.span),
421                     mbe::TokenTree::MetaVarDecl(def.span, rhs_nm, tt_spec),
422                 ],
423                 separator: Some(Token::new(
424                     if macro_rules { token::Semi } else { token::Comma },
425                     def.span,
426                 )),
427                 kleene: mbe::KleeneToken::new(mbe::KleeneOp::OneOrMore, def.span),
428                 num_captures: 2,
429             },
430         ),
431         // to phase into semicolon-termination instead of semicolon-separation
432         mbe::TokenTree::Sequence(
433             DelimSpan::dummy(),
434             mbe::SequenceRepetition {
435                 tts: vec![mbe::TokenTree::token(
436                     if macro_rules { token::Semi } else { token::Comma },
437                     def.span,
438                 )],
439                 separator: None,
440                 kleene: mbe::KleeneToken::new(mbe::KleeneOp::ZeroOrMore, def.span),
441                 num_captures: 0,
442             },
443         ),
444     ];
445     // Convert it into `MatcherLoc` form.
446     let argument_gram = mbe::macro_parser::compute_locs(&argument_gram);
447
448     let parser = Parser::new(&sess.parse_sess, body, true, rustc_parse::MACRO_ARGUMENTS);
449     let mut tt_parser =
450         TtParser::new(Ident::with_dummy_span(if macro_rules { kw::MacroRules } else { kw::Macro }));
451     let argument_map = match tt_parser.parse_tt(&mut Cow::Borrowed(&parser), &argument_gram) {
452         Success(m) => m,
453         Failure(token, msg) => {
454             let s = parse_failure_msg(&token);
455             let sp = token.span.substitute_dummy(def.span);
456             sess.parse_sess.span_diagnostic.struct_span_err(sp, &s).span_label(sp, msg).emit();
457             return dummy_syn_ext();
458         }
459         Error(sp, msg) => {
460             sess.parse_sess
461                 .span_diagnostic
462                 .struct_span_err(sp.substitute_dummy(def.span), &msg)
463                 .emit();
464             return dummy_syn_ext();
465         }
466         ErrorReported => {
467             return dummy_syn_ext();
468         }
469     };
470
471     let mut valid = true;
472
473     // Extract the arguments:
474     let lhses = match argument_map[&MacroRulesNormalizedIdent::new(lhs_nm)] {
475         MatchedSeq(ref s) => s
476             .iter()
477             .map(|m| {
478                 if let MatchedTokenTree(ref tt) = *m {
479                     let tt = mbe::quoted::parse(
480                         tt.clone().into(),
481                         true,
482                         &sess.parse_sess,
483                         def.id,
484                         features,
485                         edition,
486                     )
487                     .pop()
488                     .unwrap();
489                     valid &= check_lhs_nt_follows(&sess.parse_sess, &def, &tt);
490                     return tt;
491                 }
492                 sess.parse_sess.span_diagnostic.span_bug(def.span, "wrong-structured lhs")
493             })
494             .collect::<Vec<mbe::TokenTree>>(),
495         _ => sess.parse_sess.span_diagnostic.span_bug(def.span, "wrong-structured lhs"),
496     };
497
498     let rhses = match argument_map[&MacroRulesNormalizedIdent::new(rhs_nm)] {
499         MatchedSeq(ref s) => s
500             .iter()
501             .map(|m| {
502                 if let MatchedTokenTree(ref tt) = *m {
503                     return mbe::quoted::parse(
504                         tt.clone().into(),
505                         false,
506                         &sess.parse_sess,
507                         def.id,
508                         features,
509                         edition,
510                     )
511                     .pop()
512                     .unwrap();
513                 }
514                 sess.parse_sess.span_diagnostic.span_bug(def.span, "wrong-structured lhs")
515             })
516             .collect::<Vec<mbe::TokenTree>>(),
517         _ => sess.parse_sess.span_diagnostic.span_bug(def.span, "wrong-structured rhs"),
518     };
519
520     for rhs in &rhses {
521         valid &= check_rhs(&sess.parse_sess, rhs);
522     }
523
524     // don't abort iteration early, so that errors for multiple lhses can be reported
525     for lhs in &lhses {
526         valid &= check_lhs_no_empty_seq(&sess.parse_sess, slice::from_ref(lhs));
527     }
528
529     valid &= macro_check::check_meta_variables(&sess.parse_sess, def.id, def.span, &lhses, &rhses);
530
531     let (transparency, transparency_error) = attr::find_transparency(&def.attrs, macro_rules);
532     match transparency_error {
533         Some(TransparencyError::UnknownTransparency(value, span)) => {
534             diag.span_err(span, &format!("unknown macro transparency: `{}`", value));
535         }
536         Some(TransparencyError::MultipleTransparencyAttrs(old_span, new_span)) => {
537             diag.span_err(vec![old_span, new_span], "multiple macro transparency attributes");
538         }
539         None => {}
540     }
541
542     // Compute the spans of the macro rules
543     // We only take the span of the lhs here,
544     // so that the spans of created warnings are smaller.
545     let rule_spans = if def.id != DUMMY_NODE_ID {
546         lhses.iter().map(|lhs| lhs.span()).collect::<Vec<_>>()
547     } else {
548         Vec::new()
549     };
550
551     // Convert the lhses into `MatcherLoc` form, which is better for doing the
552     // actual matching. Unless the matcher is invalid.
553     let lhses = if valid {
554         lhses
555             .iter()
556             .map(|lhs| {
557                 // Ignore the delimiters around the matcher.
558                 match lhs {
559                     mbe::TokenTree::Delimited(_, delimited) => {
560                         mbe::macro_parser::compute_locs(&delimited.tts)
561                     }
562                     _ => sess.parse_sess.span_diagnostic.span_bug(def.span, "malformed macro lhs"),
563                 }
564             })
565             .collect()
566     } else {
567         vec![]
568     };
569
570     let expander = Box::new(MacroRulesMacroExpander {
571         name: def.ident,
572         span: def.span,
573         node_id: def.id,
574         transparency,
575         lhses,
576         rhses,
577         valid,
578     });
579     (mk_syn_ext(expander), rule_spans)
580 }
581
582 fn check_lhs_nt_follows(sess: &ParseSess, def: &ast::Item, lhs: &mbe::TokenTree) -> bool {
583     // lhs is going to be like TokenTree::Delimited(...), where the
584     // entire lhs is those tts. Or, it can be a "bare sequence", not wrapped in parens.
585     if let mbe::TokenTree::Delimited(_, delimited) = lhs {
586         check_matcher(sess, def, &delimited.tts)
587     } else {
588         let msg = "invalid macro matcher; matchers must be contained in balanced delimiters";
589         sess.span_diagnostic.span_err(lhs.span(), msg);
590         false
591     }
592     // we don't abort on errors on rejection, the driver will do that for us
593     // after parsing/expansion. we can report every error in every macro this way.
594 }
595
596 /// Checks that the lhs contains no repetition which could match an empty token
597 /// tree, because then the matcher would hang indefinitely.
598 fn check_lhs_no_empty_seq(sess: &ParseSess, tts: &[mbe::TokenTree]) -> bool {
599     use mbe::TokenTree;
600     for tt in tts {
601         match *tt {
602             TokenTree::Token(..)
603             | TokenTree::MetaVar(..)
604             | TokenTree::MetaVarDecl(..)
605             | TokenTree::MetaVarExpr(..) => (),
606             TokenTree::Delimited(_, ref del) => {
607                 if !check_lhs_no_empty_seq(sess, &del.tts) {
608                     return false;
609                 }
610             }
611             TokenTree::Sequence(span, ref seq) => {
612                 if seq.separator.is_none()
613                     && seq.tts.iter().all(|seq_tt| match *seq_tt {
614                         TokenTree::MetaVarDecl(_, _, Some(NonterminalKind::Vis)) => true,
615                         TokenTree::Sequence(_, ref sub_seq) => {
616                             sub_seq.kleene.op == mbe::KleeneOp::ZeroOrMore
617                                 || sub_seq.kleene.op == mbe::KleeneOp::ZeroOrOne
618                         }
619                         _ => false,
620                     })
621                 {
622                     let sp = span.entire();
623                     sess.span_diagnostic.span_err(sp, "repetition matches empty token tree");
624                     return false;
625                 }
626                 if !check_lhs_no_empty_seq(sess, &seq.tts) {
627                     return false;
628                 }
629             }
630         }
631     }
632
633     true
634 }
635
636 fn check_rhs(sess: &ParseSess, rhs: &mbe::TokenTree) -> bool {
637     match *rhs {
638         mbe::TokenTree::Delimited(..) => return true,
639         _ => {
640             sess.span_diagnostic.span_err(rhs.span(), "macro rhs must be delimited");
641         }
642     }
643     false
644 }
645
646 fn check_matcher(sess: &ParseSess, def: &ast::Item, matcher: &[mbe::TokenTree]) -> bool {
647     let first_sets = FirstSets::new(matcher);
648     let empty_suffix = TokenSet::empty();
649     let err = sess.span_diagnostic.err_count();
650     check_matcher_core(sess, def, &first_sets, matcher, &empty_suffix);
651     err == sess.span_diagnostic.err_count()
652 }
653
654 // `The FirstSets` for a matcher is a mapping from subsequences in the
655 // matcher to the FIRST set for that subsequence.
656 //
657 // This mapping is partially precomputed via a backwards scan over the
658 // token trees of the matcher, which provides a mapping from each
659 // repetition sequence to its *first* set.
660 //
661 // (Hypothetically, sequences should be uniquely identifiable via their
662 // spans, though perhaps that is false, e.g., for macro-generated macros
663 // that do not try to inject artificial span information. My plan is
664 // to try to catch such cases ahead of time and not include them in
665 // the precomputed mapping.)
666 struct FirstSets<'tt> {
667     // this maps each TokenTree::Sequence `$(tt ...) SEP OP` that is uniquely identified by its
668     // span in the original matcher to the First set for the inner sequence `tt ...`.
669     //
670     // If two sequences have the same span in a matcher, then map that
671     // span to None (invalidating the mapping here and forcing the code to
672     // use a slow path).
673     first: FxHashMap<Span, Option<TokenSet<'tt>>>,
674 }
675
676 impl<'tt> FirstSets<'tt> {
677     fn new(tts: &'tt [mbe::TokenTree]) -> FirstSets<'tt> {
678         use mbe::TokenTree;
679
680         let mut sets = FirstSets { first: FxHashMap::default() };
681         build_recur(&mut sets, tts);
682         return sets;
683
684         // walks backward over `tts`, returning the FIRST for `tts`
685         // and updating `sets` at the same time for all sequence
686         // substructure we find within `tts`.
687         fn build_recur<'tt>(sets: &mut FirstSets<'tt>, tts: &'tt [TokenTree]) -> TokenSet<'tt> {
688             let mut first = TokenSet::empty();
689             for tt in tts.iter().rev() {
690                 match *tt {
691                     TokenTree::Token(..)
692                     | TokenTree::MetaVar(..)
693                     | TokenTree::MetaVarDecl(..)
694                     | TokenTree::MetaVarExpr(..) => {
695                         first.replace_with(TtHandle::TtRef(tt));
696                     }
697                     TokenTree::Delimited(span, ref delimited) => {
698                         build_recur(sets, &delimited.tts);
699                         first.replace_with(TtHandle::from_token_kind(
700                             token::OpenDelim(delimited.delim),
701                             span.open,
702                         ));
703                     }
704                     TokenTree::Sequence(sp, ref seq_rep) => {
705                         let subfirst = build_recur(sets, &seq_rep.tts);
706
707                         match sets.first.entry(sp.entire()) {
708                             Entry::Vacant(vac) => {
709                                 vac.insert(Some(subfirst.clone()));
710                             }
711                             Entry::Occupied(mut occ) => {
712                                 // if there is already an entry, then a span must have collided.
713                                 // This should not happen with typical macro_rules macros,
714                                 // but syntax extensions need not maintain distinct spans,
715                                 // so distinct syntax trees can be assigned the same span.
716                                 // In such a case, the map cannot be trusted; so mark this
717                                 // entry as unusable.
718                                 occ.insert(None);
719                             }
720                         }
721
722                         // If the sequence contents can be empty, then the first
723                         // token could be the separator token itself.
724
725                         if let (Some(sep), true) = (&seq_rep.separator, subfirst.maybe_empty) {
726                             first.add_one_maybe(TtHandle::from_token(sep.clone()));
727                         }
728
729                         // Reverse scan: Sequence comes before `first`.
730                         if subfirst.maybe_empty
731                             || seq_rep.kleene.op == mbe::KleeneOp::ZeroOrMore
732                             || seq_rep.kleene.op == mbe::KleeneOp::ZeroOrOne
733                         {
734                             // If sequence is potentially empty, then
735                             // union them (preserving first emptiness).
736                             first.add_all(&TokenSet { maybe_empty: true, ..subfirst });
737                         } else {
738                             // Otherwise, sequence guaranteed
739                             // non-empty; replace first.
740                             first = subfirst;
741                         }
742                     }
743                 }
744             }
745
746             first
747         }
748     }
749
750     // walks forward over `tts` until all potential FIRST tokens are
751     // identified.
752     fn first(&self, tts: &'tt [mbe::TokenTree]) -> TokenSet<'tt> {
753         use mbe::TokenTree;
754
755         let mut first = TokenSet::empty();
756         for tt in tts.iter() {
757             assert!(first.maybe_empty);
758             match *tt {
759                 TokenTree::Token(..)
760                 | TokenTree::MetaVar(..)
761                 | TokenTree::MetaVarDecl(..)
762                 | TokenTree::MetaVarExpr(..) => {
763                     first.add_one(TtHandle::TtRef(tt));
764                     return first;
765                 }
766                 TokenTree::Delimited(span, ref delimited) => {
767                     first.add_one(TtHandle::from_token_kind(
768                         token::OpenDelim(delimited.delim),
769                         span.open,
770                     ));
771                     return first;
772                 }
773                 TokenTree::Sequence(sp, ref seq_rep) => {
774                     let subfirst_owned;
775                     let subfirst = match self.first.get(&sp.entire()) {
776                         Some(&Some(ref subfirst)) => subfirst,
777                         Some(&None) => {
778                             subfirst_owned = self.first(&seq_rep.tts);
779                             &subfirst_owned
780                         }
781                         None => {
782                             panic!("We missed a sequence during FirstSets construction");
783                         }
784                     };
785
786                     // If the sequence contents can be empty, then the first
787                     // token could be the separator token itself.
788                     if let (Some(sep), true) = (&seq_rep.separator, subfirst.maybe_empty) {
789                         first.add_one_maybe(TtHandle::from_token(sep.clone()));
790                     }
791
792                     assert!(first.maybe_empty);
793                     first.add_all(subfirst);
794                     if subfirst.maybe_empty
795                         || seq_rep.kleene.op == mbe::KleeneOp::ZeroOrMore
796                         || seq_rep.kleene.op == mbe::KleeneOp::ZeroOrOne
797                     {
798                         // Continue scanning for more first
799                         // tokens, but also make sure we
800                         // restore empty-tracking state.
801                         first.maybe_empty = true;
802                         continue;
803                     } else {
804                         return first;
805                     }
806                 }
807             }
808         }
809
810         // we only exit the loop if `tts` was empty or if every
811         // element of `tts` matches the empty sequence.
812         assert!(first.maybe_empty);
813         first
814     }
815 }
816
817 // Most `mbe::TokenTree`s are pre-existing in the matcher, but some are defined
818 // implicitly, such as opening/closing delimiters and sequence repetition ops.
819 // This type encapsulates both kinds. It implements `Clone` while avoiding the
820 // need for `mbe::TokenTree` to implement `Clone`.
821 #[derive(Debug)]
822 enum TtHandle<'tt> {
823     /// This is used in most cases.
824     TtRef(&'tt mbe::TokenTree),
825
826     /// This is only used for implicit token trees. The `mbe::TokenTree` *must*
827     /// be `mbe::TokenTree::Token`. No other variants are allowed. We store an
828     /// `mbe::TokenTree` rather than a `Token` so that `get()` can return a
829     /// `&mbe::TokenTree`.
830     Token(mbe::TokenTree),
831 }
832
833 impl<'tt> TtHandle<'tt> {
834     fn from_token(tok: Token) -> Self {
835         TtHandle::Token(mbe::TokenTree::Token(tok))
836     }
837
838     fn from_token_kind(kind: TokenKind, span: Span) -> Self {
839         TtHandle::from_token(Token::new(kind, span))
840     }
841
842     // Get a reference to a token tree.
843     fn get(&'tt self) -> &'tt mbe::TokenTree {
844         match self {
845             TtHandle::TtRef(tt) => tt,
846             TtHandle::Token(token_tt) => &token_tt,
847         }
848     }
849 }
850
851 impl<'tt> PartialEq for TtHandle<'tt> {
852     fn eq(&self, other: &TtHandle<'tt>) -> bool {
853         self.get() == other.get()
854     }
855 }
856
857 impl<'tt> Clone for TtHandle<'tt> {
858     fn clone(&self) -> Self {
859         match self {
860             TtHandle::TtRef(tt) => TtHandle::TtRef(tt),
861
862             // This variant *must* contain a `mbe::TokenTree::Token`, and not
863             // any other variant of `mbe::TokenTree`.
864             TtHandle::Token(mbe::TokenTree::Token(tok)) => {
865                 TtHandle::Token(mbe::TokenTree::Token(tok.clone()))
866             }
867
868             _ => unreachable!(),
869         }
870     }
871 }
872
873 // A set of `mbe::TokenTree`s, which may include `TokenTree::Match`s
874 // (for macro-by-example syntactic variables). It also carries the
875 // `maybe_empty` flag; that is true if and only if the matcher can
876 // match an empty token sequence.
877 //
878 // The First set is computed on submatchers like `$($a:expr b),* $(c)* d`,
879 // which has corresponding FIRST = {$a:expr, c, d}.
880 // Likewise, `$($a:expr b),* $(c)+ d` has FIRST = {$a:expr, c}.
881 //
882 // (Notably, we must allow for *-op to occur zero times.)
883 #[derive(Clone, Debug)]
884 struct TokenSet<'tt> {
885     tokens: Vec<TtHandle<'tt>>,
886     maybe_empty: bool,
887 }
888
889 impl<'tt> TokenSet<'tt> {
890     // Returns a set for the empty sequence.
891     fn empty() -> Self {
892         TokenSet { tokens: Vec::new(), maybe_empty: true }
893     }
894
895     // Returns the set `{ tok }` for the single-token (and thus
896     // non-empty) sequence [tok].
897     fn singleton(tt: TtHandle<'tt>) -> Self {
898         TokenSet { tokens: vec![tt], maybe_empty: false }
899     }
900
901     // Changes self to be the set `{ tok }`.
902     // Since `tok` is always present, marks self as non-empty.
903     fn replace_with(&mut self, tt: TtHandle<'tt>) {
904         self.tokens.clear();
905         self.tokens.push(tt);
906         self.maybe_empty = false;
907     }
908
909     // Changes self to be the empty set `{}`; meant for use when
910     // the particular token does not matter, but we want to
911     // record that it occurs.
912     fn replace_with_irrelevant(&mut self) {
913         self.tokens.clear();
914         self.maybe_empty = false;
915     }
916
917     // Adds `tok` to the set for `self`, marking sequence as non-empy.
918     fn add_one(&mut self, tt: TtHandle<'tt>) {
919         if !self.tokens.contains(&tt) {
920             self.tokens.push(tt);
921         }
922         self.maybe_empty = false;
923     }
924
925     // Adds `tok` to the set for `self`. (Leaves `maybe_empty` flag alone.)
926     fn add_one_maybe(&mut self, tt: TtHandle<'tt>) {
927         if !self.tokens.contains(&tt) {
928             self.tokens.push(tt);
929         }
930     }
931
932     // Adds all elements of `other` to this.
933     //
934     // (Since this is a set, we filter out duplicates.)
935     //
936     // If `other` is potentially empty, then preserves the previous
937     // setting of the empty flag of `self`. If `other` is guaranteed
938     // non-empty, then `self` is marked non-empty.
939     fn add_all(&mut self, other: &Self) {
940         for tt in &other.tokens {
941             if !self.tokens.contains(tt) {
942                 self.tokens.push(tt.clone());
943             }
944         }
945         if !other.maybe_empty {
946             self.maybe_empty = false;
947         }
948     }
949 }
950
951 // Checks that `matcher` is internally consistent and that it
952 // can legally be followed by a token `N`, for all `N` in `follow`.
953 // (If `follow` is empty, then it imposes no constraint on
954 // the `matcher`.)
955 //
956 // Returns the set of NT tokens that could possibly come last in
957 // `matcher`. (If `matcher` matches the empty sequence, then
958 // `maybe_empty` will be set to true.)
959 //
960 // Requires that `first_sets` is pre-computed for `matcher`;
961 // see `FirstSets::new`.
962 fn check_matcher_core<'tt>(
963     sess: &ParseSess,
964     def: &ast::Item,
965     first_sets: &FirstSets<'tt>,
966     matcher: &'tt [mbe::TokenTree],
967     follow: &TokenSet<'tt>,
968 ) -> TokenSet<'tt> {
969     use mbe::TokenTree;
970
971     let mut last = TokenSet::empty();
972
973     // 2. For each token and suffix  [T, SUFFIX] in M:
974     // ensure that T can be followed by SUFFIX, and if SUFFIX may be empty,
975     // then ensure T can also be followed by any element of FOLLOW.
976     'each_token: for i in 0..matcher.len() {
977         let token = &matcher[i];
978         let suffix = &matcher[i + 1..];
979
980         let build_suffix_first = || {
981             let mut s = first_sets.first(suffix);
982             if s.maybe_empty {
983                 s.add_all(follow);
984             }
985             s
986         };
987
988         // (we build `suffix_first` on demand below; you can tell
989         // which cases are supposed to fall through by looking for the
990         // initialization of this variable.)
991         let suffix_first;
992
993         // First, update `last` so that it corresponds to the set
994         // of NT tokens that might end the sequence `... token`.
995         match *token {
996             TokenTree::Token(..)
997             | TokenTree::MetaVar(..)
998             | TokenTree::MetaVarDecl(..)
999             | TokenTree::MetaVarExpr(..) => {
1000                 if token_can_be_followed_by_any(token) {
1001                     // don't need to track tokens that work with any,
1002                     last.replace_with_irrelevant();
1003                     // ... and don't need to check tokens that can be
1004                     // followed by anything against SUFFIX.
1005                     continue 'each_token;
1006                 } else {
1007                     last.replace_with(TtHandle::TtRef(token));
1008                     suffix_first = build_suffix_first();
1009                 }
1010             }
1011             TokenTree::Delimited(span, ref d) => {
1012                 let my_suffix = TokenSet::singleton(TtHandle::from_token_kind(
1013                     token::CloseDelim(d.delim),
1014                     span.close,
1015                 ));
1016                 check_matcher_core(sess, def, first_sets, &d.tts, &my_suffix);
1017                 // don't track non NT tokens
1018                 last.replace_with_irrelevant();
1019
1020                 // also, we don't need to check delimited sequences
1021                 // against SUFFIX
1022                 continue 'each_token;
1023             }
1024             TokenTree::Sequence(_, ref seq_rep) => {
1025                 suffix_first = build_suffix_first();
1026                 // The trick here: when we check the interior, we want
1027                 // to include the separator (if any) as a potential
1028                 // (but not guaranteed) element of FOLLOW. So in that
1029                 // case, we make a temp copy of suffix and stuff
1030                 // delimiter in there.
1031                 //
1032                 // FIXME: Should I first scan suffix_first to see if
1033                 // delimiter is already in it before I go through the
1034                 // work of cloning it? But then again, this way I may
1035                 // get a "tighter" span?
1036                 let mut new;
1037                 let my_suffix = if let Some(sep) = &seq_rep.separator {
1038                     new = suffix_first.clone();
1039                     new.add_one_maybe(TtHandle::from_token(sep.clone()));
1040                     &new
1041                 } else {
1042                     &suffix_first
1043                 };
1044
1045                 // At this point, `suffix_first` is built, and
1046                 // `my_suffix` is some TokenSet that we can use
1047                 // for checking the interior of `seq_rep`.
1048                 let next = check_matcher_core(sess, def, first_sets, &seq_rep.tts, my_suffix);
1049                 if next.maybe_empty {
1050                     last.add_all(&next);
1051                 } else {
1052                     last = next;
1053                 }
1054
1055                 // the recursive call to check_matcher_core already ran the 'each_last
1056                 // check below, so we can just keep going forward here.
1057                 continue 'each_token;
1058             }
1059         }
1060
1061         // (`suffix_first` guaranteed initialized once reaching here.)
1062
1063         // Now `last` holds the complete set of NT tokens that could
1064         // end the sequence before SUFFIX. Check that every one works with `suffix`.
1065         for tt in &last.tokens {
1066             if let &TokenTree::MetaVarDecl(span, name, Some(kind)) = tt.get() {
1067                 for next_token in &suffix_first.tokens {
1068                     let next_token = next_token.get();
1069
1070                     // Check if the old pat is used and the next token is `|`
1071                     // to warn about incompatibility with Rust 2021.
1072                     // We only emit this lint if we're parsing the original
1073                     // definition of this macro_rules, not while (re)parsing
1074                     // the macro when compiling another crate that is using the
1075                     // macro. (See #86567.)
1076                     // Macros defined in the current crate have a real node id,
1077                     // whereas macros from an external crate have a dummy id.
1078                     if def.id != DUMMY_NODE_ID
1079                         && matches!(kind, NonterminalKind::PatParam { inferred: true })
1080                         && matches!(next_token, TokenTree::Token(token) if token.kind == BinOp(token::BinOpToken::Or))
1081                     {
1082                         // It is suggestion to use pat_param, for example: $x:pat -> $x:pat_param.
1083                         let suggestion = quoted_tt_to_string(&TokenTree::MetaVarDecl(
1084                             span,
1085                             name,
1086                             Some(NonterminalKind::PatParam { inferred: false }),
1087                         ));
1088                         sess.buffer_lint_with_diagnostic(
1089                             &RUST_2021_INCOMPATIBLE_OR_PATTERNS,
1090                             span,
1091                             ast::CRATE_NODE_ID,
1092                             "the meaning of the `pat` fragment specifier is changing in Rust 2021, which may affect this macro",
1093                             BuiltinLintDiagnostics::OrPatternsBackCompat(span, suggestion),
1094                         );
1095                     }
1096                     match is_in_follow(next_token, kind) {
1097                         IsInFollow::Yes => {}
1098                         IsInFollow::No(possible) => {
1099                             let may_be = if last.tokens.len() == 1 && suffix_first.tokens.len() == 1
1100                             {
1101                                 "is"
1102                             } else {
1103                                 "may be"
1104                             };
1105
1106                             let sp = next_token.span();
1107                             let mut err = sess.span_diagnostic.struct_span_err(
1108                                 sp,
1109                                 &format!(
1110                                     "`${name}:{frag}` {may_be} followed by `{next}`, which \
1111                                      is not allowed for `{frag}` fragments",
1112                                     name = name,
1113                                     frag = kind,
1114                                     next = quoted_tt_to_string(next_token),
1115                                     may_be = may_be
1116                                 ),
1117                             );
1118                             err.span_label(sp, format!("not allowed after `{}` fragments", kind));
1119
1120                             if kind == NonterminalKind::PatWithOr
1121                                 && sess.edition.rust_2021()
1122                                 && next_token.is_token(&BinOp(token::BinOpToken::Or))
1123                             {
1124                                 let suggestion = quoted_tt_to_string(&TokenTree::MetaVarDecl(
1125                                     span,
1126                                     name,
1127                                     Some(NonterminalKind::PatParam { inferred: false }),
1128                                 ));
1129                                 err.span_suggestion(
1130                                     span,
1131                                     "try a `pat_param` fragment specifier instead",
1132                                     suggestion,
1133                                     Applicability::MaybeIncorrect,
1134                                 );
1135                             }
1136
1137                             let msg = "allowed there are: ";
1138                             match possible {
1139                                 &[] => {}
1140                                 &[t] => {
1141                                     err.note(&format!(
1142                                         "only {} is allowed after `{}` fragments",
1143                                         t, kind,
1144                                     ));
1145                                 }
1146                                 ts => {
1147                                     err.note(&format!(
1148                                         "{}{} or {}",
1149                                         msg,
1150                                         ts[..ts.len() - 1]
1151                                             .iter()
1152                                             .copied()
1153                                             .collect::<Vec<_>>()
1154                                             .join(", "),
1155                                         ts[ts.len() - 1],
1156                                     ));
1157                                 }
1158                             }
1159                             err.emit();
1160                         }
1161                     }
1162                 }
1163             }
1164         }
1165     }
1166     last
1167 }
1168
1169 fn token_can_be_followed_by_any(tok: &mbe::TokenTree) -> bool {
1170     if let mbe::TokenTree::MetaVarDecl(_, _, Some(kind)) = *tok {
1171         frag_can_be_followed_by_any(kind)
1172     } else {
1173         // (Non NT's can always be followed by anything in matchers.)
1174         true
1175     }
1176 }
1177
1178 /// Returns `true` if a fragment of type `frag` can be followed by any sort of
1179 /// token. We use this (among other things) as a useful approximation
1180 /// for when `frag` can be followed by a repetition like `$(...)*` or
1181 /// `$(...)+`. In general, these can be a bit tricky to reason about,
1182 /// so we adopt a conservative position that says that any fragment
1183 /// specifier which consumes at most one token tree can be followed by
1184 /// a fragment specifier (indeed, these fragments can be followed by
1185 /// ANYTHING without fear of future compatibility hazards).
1186 fn frag_can_be_followed_by_any(kind: NonterminalKind) -> bool {
1187     matches!(
1188         kind,
1189         NonterminalKind::Item           // always terminated by `}` or `;`
1190         | NonterminalKind::Block        // exactly one token tree
1191         | NonterminalKind::Ident        // exactly one token tree
1192         | NonterminalKind::Literal      // exactly one token tree
1193         | NonterminalKind::Meta         // exactly one token tree
1194         | NonterminalKind::Lifetime     // exactly one token tree
1195         | NonterminalKind::TT // exactly one token tree
1196     )
1197 }
1198
1199 enum IsInFollow {
1200     Yes,
1201     No(&'static [&'static str]),
1202 }
1203
1204 /// Returns `true` if `frag` can legally be followed by the token `tok`. For
1205 /// fragments that can consume an unbounded number of tokens, `tok`
1206 /// must be within a well-defined follow set. This is intended to
1207 /// guarantee future compatibility: for example, without this rule, if
1208 /// we expanded `expr` to include a new binary operator, we might
1209 /// break macros that were relying on that binary operator as a
1210 /// separator.
1211 // when changing this do not forget to update doc/book/macros.md!
1212 fn is_in_follow(tok: &mbe::TokenTree, kind: NonterminalKind) -> IsInFollow {
1213     use mbe::TokenTree;
1214
1215     if let TokenTree::Token(Token { kind: token::CloseDelim(_), .. }) = *tok {
1216         // closing a token tree can never be matched by any fragment;
1217         // iow, we always require that `(` and `)` match, etc.
1218         IsInFollow::Yes
1219     } else {
1220         match kind {
1221             NonterminalKind::Item => {
1222                 // since items *must* be followed by either a `;` or a `}`, we can
1223                 // accept anything after them
1224                 IsInFollow::Yes
1225             }
1226             NonterminalKind::Block => {
1227                 // anything can follow block, the braces provide an easy boundary to
1228                 // maintain
1229                 IsInFollow::Yes
1230             }
1231             NonterminalKind::Stmt | NonterminalKind::Expr => {
1232                 const TOKENS: &[&str] = &["`=>`", "`,`", "`;`"];
1233                 match tok {
1234                     TokenTree::Token(token) => match token.kind {
1235                         FatArrow | Comma | Semi => IsInFollow::Yes,
1236                         _ => IsInFollow::No(TOKENS),
1237                     },
1238                     _ => IsInFollow::No(TOKENS),
1239                 }
1240             }
1241             NonterminalKind::PatParam { .. } => {
1242                 const TOKENS: &[&str] = &["`=>`", "`,`", "`=`", "`|`", "`if`", "`in`"];
1243                 match tok {
1244                     TokenTree::Token(token) => match token.kind {
1245                         FatArrow | Comma | Eq | BinOp(token::Or) => IsInFollow::Yes,
1246                         Ident(name, false) if name == kw::If || name == kw::In => IsInFollow::Yes,
1247                         _ => IsInFollow::No(TOKENS),
1248                     },
1249                     _ => IsInFollow::No(TOKENS),
1250                 }
1251             }
1252             NonterminalKind::PatWithOr { .. } => {
1253                 const TOKENS: &[&str] = &["`=>`", "`,`", "`=`", "`if`", "`in`"];
1254                 match tok {
1255                     TokenTree::Token(token) => match token.kind {
1256                         FatArrow | Comma | Eq => IsInFollow::Yes,
1257                         Ident(name, false) if name == kw::If || name == kw::In => IsInFollow::Yes,
1258                         _ => IsInFollow::No(TOKENS),
1259                     },
1260                     _ => IsInFollow::No(TOKENS),
1261                 }
1262             }
1263             NonterminalKind::Path | NonterminalKind::Ty => {
1264                 const TOKENS: &[&str] = &[
1265                     "`{`", "`[`", "`=>`", "`,`", "`>`", "`=`", "`:`", "`;`", "`|`", "`as`",
1266                     "`where`",
1267                 ];
1268                 match tok {
1269                     TokenTree::Token(token) => match token.kind {
1270                         OpenDelim(Delimiter::Brace)
1271                         | OpenDelim(Delimiter::Bracket)
1272                         | Comma
1273                         | FatArrow
1274                         | Colon
1275                         | Eq
1276                         | Gt
1277                         | BinOp(token::Shr)
1278                         | Semi
1279                         | BinOp(token::Or) => IsInFollow::Yes,
1280                         Ident(name, false) if name == kw::As || name == kw::Where => {
1281                             IsInFollow::Yes
1282                         }
1283                         _ => IsInFollow::No(TOKENS),
1284                     },
1285                     TokenTree::MetaVarDecl(_, _, Some(NonterminalKind::Block)) => IsInFollow::Yes,
1286                     _ => IsInFollow::No(TOKENS),
1287                 }
1288             }
1289             NonterminalKind::Ident | NonterminalKind::Lifetime => {
1290                 // being a single token, idents and lifetimes are harmless
1291                 IsInFollow::Yes
1292             }
1293             NonterminalKind::Literal => {
1294                 // literals may be of a single token, or two tokens (negative numbers)
1295                 IsInFollow::Yes
1296             }
1297             NonterminalKind::Meta | NonterminalKind::TT => {
1298                 // being either a single token or a delimited sequence, tt is
1299                 // harmless
1300                 IsInFollow::Yes
1301             }
1302             NonterminalKind::Vis => {
1303                 // Explicitly disallow `priv`, on the off chance it comes back.
1304                 const TOKENS: &[&str] = &["`,`", "an ident", "a type"];
1305                 match tok {
1306                     TokenTree::Token(token) => match token.kind {
1307                         Comma => IsInFollow::Yes,
1308                         Ident(name, is_raw) if is_raw || name != kw::Priv => IsInFollow::Yes,
1309                         _ => {
1310                             if token.can_begin_type() {
1311                                 IsInFollow::Yes
1312                             } else {
1313                                 IsInFollow::No(TOKENS)
1314                             }
1315                         }
1316                     },
1317                     TokenTree::MetaVarDecl(
1318                         _,
1319                         _,
1320                         Some(NonterminalKind::Ident | NonterminalKind::Ty | NonterminalKind::Path),
1321                     ) => IsInFollow::Yes,
1322                     _ => IsInFollow::No(TOKENS),
1323                 }
1324             }
1325         }
1326     }
1327 }
1328
1329 fn quoted_tt_to_string(tt: &mbe::TokenTree) -> String {
1330     match *tt {
1331         mbe::TokenTree::Token(ref token) => pprust::token_to_string(&token).into(),
1332         mbe::TokenTree::MetaVar(_, name) => format!("${}", name),
1333         mbe::TokenTree::MetaVarDecl(_, name, Some(kind)) => format!("${}:{}", name, kind),
1334         mbe::TokenTree::MetaVarDecl(_, name, None) => format!("${}:", name),
1335         _ => panic!(
1336             "{}",
1337             "unexpected mbe::TokenTree::{Sequence or Delimited} \
1338              in follow set checker"
1339         ),
1340     }
1341 }
1342
1343 fn parser_from_cx(sess: &ParseSess, tts: TokenStream) -> Parser<'_> {
1344     Parser::new(sess, tts, true, rustc_parse::MACRO_ARGUMENTS)
1345 }
1346
1347 /// Generates an appropriate parsing failure message. For EOF, this is "unexpected end...". For
1348 /// other tokens, this is "unexpected token...".
1349 fn parse_failure_msg(tok: &Token) -> String {
1350     match tok.kind {
1351         token::Eof => "unexpected end of macro invocation".to_string(),
1352         _ => format!("no rules expected the token `{}`", pprust::token_to_string(tok),),
1353     }
1354 }