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