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