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