rustc_expand/mbe/
macro_rules.rs

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