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};
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;
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};
18 Applicability, Diagnostic, DiagnosticBuilder, DiagnosticMessage, ErrorGuaranteed,
20 use rustc_feature::Features;
21 use rustc_lint_defs::builtin::{
22 RUST_2021_INCOMPATIBLE_OR_PATTERNS, SEMICOLON_IN_EXPRESSIONS_FROM_MACROS,
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};
35 use std::collections::hash_map::Entry;
36 use std::{mem, slice};
38 use super::macro_parser::{NamedMatches, NamedParseResult};
40 pub(crate) struct ParserAnyMacro<'a> {
43 /// Span of the expansion site of the macro this parser is for
45 /// The ident of the macro we're parsing
48 is_trailing_mac: bool,
50 /// Whether or not this macro is defined in the current crate
54 pub(crate) fn annotate_err_with_kind(err: &mut Diagnostic, kind: AstFragmentKind, span: Span) {
56 AstFragmentKind::Ty => {
57 err.span_label(span, "this macro call doesn't expand to a type");
59 AstFragmentKind::Pat => {
60 err.span_label(span, "this macro call doesn't expand to a pattern");
66 fn emit_frag_parse_err(
67 mut e: DiagnosticBuilder<'_, rustc_errors::ErrorGuaranteed>,
69 orig_parser: &mut Parser<'_>,
72 kind: AstFragmentKind,
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>`")
79 let msg = &e.message[0];
81 DiagnosticMessage::Str(format!(
82 "macro expansion ends with an incomplete expression: {}",
83 message.replace(", found `<eof>`", ""),
87 if !e.span.is_dummy() {
88 // early end of macro arm (#52866)
89 e.replace_span_with(parser.token.span.shrink_to_hi());
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");
98 } else if parser.sess.source_map().is_imported(parser.token.span) {
99 e.span_label(site_span, "in this macro invocation");
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(),
107 "the macro call doesn't expand to an expression, but it can expand to a statement",
109 e.span_suggestion_verbose(
110 site_span.shrink_to_hi(),
111 "add `;` to interpret the expansion as a statement",
113 Applicability::MaybeIncorrect,
117 _ => annotate_err_with_kind(&mut e, kind, site_span),
122 impl<'a> ParserAnyMacro<'a> {
123 pub(crate) fn make(mut self: Box<ParserAnyMacro<'a>>, kind: AstFragmentKind) -> AstFragment {
133 let snapshot = &mut parser.create_snapshot_for_diagnostic();
134 let fragment = match parse_ast_fragment(parser, kind) {
137 emit_frag_parse_err(err, parser, snapshot, site_span, arm_span, kind);
138 return kind.dummy(site_span);
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 {
147 parser.sess.buffer_lint_with_diagnostic(
148 SEMICOLON_IN_EXPRESSIONS_FROM_MACROS,
151 "trailing semicolon in macro used in expression position",
152 BuiltinLintDiagnostics::TrailingMacro(is_trailing_mac, macro_ident),
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);
165 struct MacroRulesMacroExpander {
169 transparency: Transparency,
170 lhses: Vec<Vec<MatcherLoc>>,
171 rhses: Vec<mbe::TokenTree>,
175 impl TTMacroExpander for MacroRulesMacroExpander {
178 cx: &'cx mut ExtCtxt<'_>,
181 ) -> Box<dyn MacResult + 'cx> {
183 return DummyResult::any(sp);
199 fn macro_rules_dummy_expander<'cx>(
200 _: &'cx mut ExtCtxt<'_>,
203 ) -> Box<dyn MacResult + 'cx> {
204 DummyResult::any(span)
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);
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);
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);
221 fn description() -> &'static str;
223 fn recovery() -> Recovery;
226 /// A noop tracker that is used in the hot path of the expansion, has zero overhead thanks to monomorphization.
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 {
235 fn recovery() -> Recovery {
240 /// Expands the rules based macro defined by `lhses` and `rhses` for a given
242 #[instrument(skip(cx, transparency, arg, lhses, rhses))]
243 fn expand_macro<'cx>(
244 cx: &'cx mut ExtCtxt<'_>,
249 transparency: Transparency,
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;
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);
264 // Track nothing for the best performance.
265 let try_success_result = try_match_macro(sess, name, &arg, lhses, &mut NoopTracker);
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"),
273 let arm_span = rhses[i].span();
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) {
281 return DummyResult::any(arm_span);
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());
297 if cx.trace_macros() {
298 let msg = format!("to `{}`", pprust::tts_to_string(&tts));
299 trace_macros_note(&mut cx.expansions, sp, msg);
302 let mut p = Parser::new(sess, tts, false, None);
303 p.last_type_ascription = cx.current_expansion.prior_type_ascription;
306 cx.resolver.record_macro_rule_usage(node_id, i);
309 // Let the context choose how to interpret the result.
310 // Weird, but useful for X-macros.
311 return Box::new(ParserAnyMacro {
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.
319 lint_node_id: cx.current_expansion.lint_node_id,
320 is_trailing_mac: cx.current_expansion.is_trailing_mac,
325 Err(CanRetry::No(_)) => {
326 debug!("Will not retry matching as an error was emitted already");
327 return DummyResult::any(sp);
329 Err(CanRetry::Yes) => {
330 // Retry and emit a better error below.
334 // An error occurred, try the expansion again, tracking the expansion closely for better diagnostics.
335 let mut tracker = CollectTrackerAndEmitter::new(cx, sp);
337 let try_success_result = try_match_macro(sess, name, &arg, lhses, &mut tracker);
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");
345 if let Some(result) = tracker.result {
346 // An irrecoverable error occurred and has been emitted.
350 let Some((token, label, remaining_matcher)) = tracker.best_failure else {
351 return DummyResult::any(sp);
354 let span = token.span.substitute_dummy(sp);
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");
362 annotate_doc_comment(&mut err, sess.source_map(), span);
364 if let Some(span) = remaining_matcher.span() {
365 err.span_note(span, format!("while trying to match {remaining_matcher}"));
367 err.note(format!("while trying to match {remaining_matcher}"));
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() {
373 let parser = parser_from_cx(sess, arg.clone(), Recovery::Allowed);
374 let mut tt_parser = TtParser::new(name);
377 tt_parser.parse_tt(&mut Cow::Borrowed(&parser), lhs, &mut NoopTracker)
379 if comma_span.is_dummy() {
380 err.note("you might be missing a comma");
382 err.span_suggestion_short(
384 "missing comma here",
386 Applicability::MachineApplicable,
393 cx.trace_macros_diag();
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)>,
404 result: Option<Box<dyn MacResult + 'cx>>,
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)
412 self.remaining_matcher = Some(matcher);
416 fn after_arm(&mut self, result: &NamedParseResult) {
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(
423 "should not collect detailed info for successful macro match",
426 Failure(token, msg) => match self.best_failure {
427 Some((ref best_token, _, _)) if best_token.span.lo() >= token.span.lo() => {}
429 self.best_failure = Some((
432 self.remaining_matcher
433 .expect("must have collected matcher already")
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));
443 ErrorReported(_) => self.result = Some(DummyResult::any(self.root_span)),
447 fn description() -> &'static str {
451 fn recovery() -> Recovery {
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 }
464 /// We are not allowed to retry macro expansion as a fatal error has been emitted already.
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
471 #[instrument(level = "debug", skip(sess, arg, lhses, track), fields(tracking = %T::description()))]
472 fn try_match_macro<'matcher, T: Tracker<'matcher>>(
476 lhses: &'matcher [Vec<MatcherLoc>],
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
484 // macro_rules! foo {
488 // // ... etc. (maybe hundreds more)
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
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);
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());
511 let result = tt_parser.parse_tt(&mut Cow::Borrowed(&parser), lhs, track);
513 track.after_arm(&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);
522 return Ok((i, named_matches));
525 trace!("Failed to match arm, trying the next one");
529 debug!("Fatal error occurred during matching");
530 // We haven't emitted an error yet, so we can retry.
531 return Err(CanRetry::Yes);
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));
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());
548 // Note that macro-by-example's input is also matched against a token tree:
549 // $( $lhs:tt => $rhs:tt );+
551 // Holy self-referential!
553 /// Converts a macro item into a syntax extension.
554 pub fn compile_declarative_macro(
559 ) -> (SyntaxExtension, Vec<(usize, Span)>) {
560 debug!("compile_declarative_macro: {:?}", def);
561 let mk_syn_ext = |expander| {
562 SyntaxExtension::new(
564 SyntaxExtensionKind::LegacyBang(expander),
572 let dummy_syn_ext = || (mk_syn_ext(Box::new(macro_rules_dummy_expander)), Vec::new());
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);
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()),
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(
593 mbe::SequenceRepetition {
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),
599 separator: Some(Token::new(
600 if macro_rules { token::Semi } else { token::Comma },
603 kleene: mbe::KleeneToken::new(mbe::KleeneOp::OneOrMore, def.span),
607 // to phase into semicolon-termination instead of semicolon-separation
608 mbe::TokenTree::Sequence(
610 mbe::SequenceRepetition {
611 tts: vec![mbe::TokenTree::token(
612 if macro_rules { token::Semi } else { token::Comma },
616 kleene: mbe::KleeneToken::new(mbe::KleeneOp::ZeroOrMore, def.span),
621 // Convert it into `MatcherLoc` form.
622 let argument_gram = mbe::macro_parser::compute_locs(&argument_gram);
624 let parser = Parser::new(&sess.parse_sess, body, true, rustc_parse::MACRO_ARGUMENTS);
626 TtParser::new(Ident::with_dummy_span(if macro_rules { kw::MacroRules } else { kw::Macro }));
628 match tt_parser.parse_tt(&mut Cow::Owned(parser), &argument_gram, &mut NoopTracker) {
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);
637 return dummy_syn_ext();
642 .struct_span_err(sp.substitute_dummy(def.span), &msg)
644 return dummy_syn_ext();
646 ErrorReported(_) => {
647 return dummy_syn_ext();
651 let mut valid = true;
653 // Extract the arguments:
654 let lhses = match argument_map[&MacroRulesNormalizedIdent::new(lhs_nm)] {
655 MatchedSeq(ref s) => s
658 if let MatchedTokenTree(ref tt) = *m {
659 let tt = mbe::quoted::parse(
660 TokenStream::new(vec![tt.clone()]),
669 valid &= check_lhs_nt_follows(&sess.parse_sess, &def, &tt);
672 sess.parse_sess.span_diagnostic.span_bug(def.span, "wrong-structured lhs")
674 .collect::<Vec<mbe::TokenTree>>(),
675 _ => sess.parse_sess.span_diagnostic.span_bug(def.span, "wrong-structured lhs"),
678 let rhses = match argument_map[&MacroRulesNormalizedIdent::new(rhs_nm)] {
679 MatchedSeq(ref s) => s
682 if let MatchedTokenTree(ref tt) = *m {
683 return mbe::quoted::parse(
684 TokenStream::new(vec![tt.clone()]),
694 sess.parse_sess.span_diagnostic.span_bug(def.span, "wrong-structured lhs")
696 .collect::<Vec<mbe::TokenTree>>(),
697 _ => sess.parse_sess.span_diagnostic.span_bug(def.span, "wrong-structured rhs"),
701 valid &= check_rhs(&sess.parse_sess, rhs);
704 // don't abort iteration early, so that errors for multiple lhses can be reported
706 valid &= check_lhs_no_empty_seq(&sess.parse_sess, slice::from_ref(lhs));
709 valid &= macro_check::check_meta_variables(&sess.parse_sess, def.id, def.span, &lhses, &rhses);
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));
716 Some(TransparencyError::MultipleTransparencyAttrs(old_span, new_span)) => {
717 diag.span_err(vec![old_span, new_span], "multiple macro transparency attributes");
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 {
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()))
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 {
748 // Ignore the delimiters around the matcher.
750 mbe::TokenTree::Delimited(_, delimited) => {
751 mbe::macro_parser::compute_locs(&delimited.tts)
753 _ => sess.parse_sess.span_diagnostic.span_bug(def.span, "malformed macro lhs"),
761 let expander = Box::new(MacroRulesMacroExpander {
770 (mk_syn_ext(expander), rule_spans)
773 #[derive(Subdiagnostic)]
774 enum ExplainDocComment {
775 #[label(expand_explain_doc_comment_inner)]
780 #[label(expand_explain_doc_comment_outer)]
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 });
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)
803 let msg = "invalid macro matcher; matchers must be contained in balanced delimiters";
804 sess.span_diagnostic.span_err(lhs.span(), msg);
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.
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 {
818 | TokenTree::MetaVar(..)
819 | TokenTree::MetaVarDecl(..)
820 | TokenTree::MetaVarExpr(..) => (),
821 TokenTree::Delimited(_, ref del) => {
822 if !check_lhs_no_empty_seq(sess, &del.tts) {
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
837 let sp = span.entire();
838 sess.span_diagnostic.span_err(sp, "repetition matches empty token tree");
841 if !check_lhs_no_empty_seq(sess, &seq.tts) {
851 fn check_rhs(sess: &ParseSess, rhs: &mbe::TokenTree) -> bool {
853 mbe::TokenTree::Delimited(..) => return true,
855 sess.span_diagnostic.span_err(rhs.span(), "macro rhs must be delimited");
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()
869 fn has_compile_error_macro(rhs: &mbe::TokenTree) -> bool {
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
886 if has_compile_error { true } else { d.tts.iter().any(has_compile_error_macro) }
892 // `The FirstSets` for a matcher is a mapping from subsequences in the
893 // matcher to the FIRST set for that subsequence.
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.
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 ...`.
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
911 first: FxHashMap<Span, Option<TokenSet<'tt>>>,
914 impl<'tt> FirstSets<'tt> {
915 fn new(tts: &'tt [mbe::TokenTree]) -> FirstSets<'tt> {
918 let mut sets = FirstSets { first: FxHashMap::default() };
919 build_recur(&mut sets, tts);
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() {
930 | TokenTree::MetaVar(..)
931 | TokenTree::MetaVarDecl(..)
932 | TokenTree::MetaVarExpr(..) => {
933 first.replace_with(TtHandle::TtRef(tt));
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),
942 TokenTree::Sequence(sp, ref seq_rep) => {
943 let subfirst = build_recur(sets, &seq_rep.tts);
945 match sets.first.entry(sp.entire()) {
946 Entry::Vacant(vac) => {
947 vac.insert(Some(subfirst.clone()));
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.
960 // If the sequence contents can be empty, then the first
961 // token could be the separator token itself.
963 if let (Some(sep), true) = (&seq_rep.separator, subfirst.maybe_empty) {
964 first.add_one_maybe(TtHandle::from_token(sep.clone()));
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
972 // If sequence is potentially empty, then
973 // union them (preserving first emptiness).
974 first.add_all(&TokenSet { maybe_empty: true, ..subfirst });
976 // Otherwise, sequence guaranteed
977 // non-empty; replace first.
988 // walks forward over `tts` until all potential FIRST tokens are
990 fn first(&self, tts: &'tt [mbe::TokenTree]) -> TokenSet<'tt> {
993 let mut first = TokenSet::empty();
994 for tt in tts.iter() {
995 assert!(first.maybe_empty);
998 | TokenTree::MetaVar(..)
999 | TokenTree::MetaVarDecl(..)
1000 | TokenTree::MetaVarExpr(..) => {
1001 first.add_one(TtHandle::TtRef(tt));
1004 TokenTree::Delimited(span, ref delimited) => {
1005 first.add_one(TtHandle::from_token_kind(
1006 token::OpenDelim(delimited.delim),
1011 TokenTree::Sequence(sp, ref seq_rep) => {
1013 let subfirst = match self.first.get(&sp.entire()) {
1014 Some(&Some(ref subfirst)) => subfirst,
1016 subfirst_owned = self.first(&seq_rep.tts);
1020 panic!("We missed a sequence during FirstSets construction");
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()));
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
1036 // Continue scanning for more first
1037 // tokens, but also make sure we
1038 // restore empty-tracking state.
1039 first.maybe_empty = true;
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);
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`.
1060 enum TtHandle<'tt> {
1061 /// This is used in most cases.
1062 TtRef(&'tt mbe::TokenTree),
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),
1071 impl<'tt> TtHandle<'tt> {
1072 fn from_token(tok: Token) -> Self {
1073 TtHandle::Token(mbe::TokenTree::Token(tok))
1076 fn from_token_kind(kind: TokenKind, span: Span) -> Self {
1077 TtHandle::from_token(Token::new(kind, span))
1080 // Get a reference to a token tree.
1081 fn get(&'tt self) -> &'tt mbe::TokenTree {
1083 TtHandle::TtRef(tt) => tt,
1084 TtHandle::Token(token_tt) => &token_tt,
1089 impl<'tt> PartialEq for TtHandle<'tt> {
1090 fn eq(&self, other: &TtHandle<'tt>) -> bool {
1091 self.get() == other.get()
1095 impl<'tt> Clone for TtHandle<'tt> {
1096 fn clone(&self) -> Self {
1098 TtHandle::TtRef(tt) => TtHandle::TtRef(tt),
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()))
1106 _ => unreachable!(),
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.
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}.
1120 // (Notably, we must allow for *-op to occur zero times.)
1121 #[derive(Clone, Debug)]
1122 struct TokenSet<'tt> {
1123 tokens: Vec<TtHandle<'tt>>,
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 }
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 }
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;
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;
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);
1160 self.maybe_empty = false;
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);
1170 // Adds all elements of `other` to this.
1172 // (Since this is a set, we filter out duplicates.)
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());
1183 if !other.maybe_empty {
1184 self.maybe_empty = false;
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
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.)
1198 // Requires that `first_sets` is pre-computed for `matcher`;
1199 // see `FirstSets::new`.
1200 fn check_matcher_core<'tt>(
1203 first_sets: &FirstSets<'tt>,
1204 matcher: &'tt [mbe::TokenTree],
1205 follow: &TokenSet<'tt>,
1206 ) -> TokenSet<'tt> {
1209 let mut last = TokenSet::empty();
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..];
1218 let build_suffix_first = || {
1219 let mut s = first_sets.first(suffix);
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.)
1231 // First, update `last` so that it corresponds to the set
1232 // of NT tokens that might end the sequence `... 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;
1245 last.replace_with(TtHandle::TtRef(token));
1246 suffix_first = build_suffix_first();
1249 TokenTree::Delimited(span, ref d) => {
1250 let my_suffix = TokenSet::singleton(TtHandle::from_token_kind(
1251 token::CloseDelim(d.delim),
1254 check_matcher_core(sess, def, first_sets, &d.tts, &my_suffix);
1255 // don't track non NT tokens
1256 last.replace_with_irrelevant();
1258 // also, we don't need to check delimited sequences
1260 continue 'each_token;
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.
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?
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()));
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);
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;
1299 // (`suffix_first` guaranteed initialized once reaching here.)
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();
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))
1320 // It is suggestion to use pat_param, for example: $x:pat -> $x:pat_param.
1321 let suggestion = quoted_tt_to_string(&TokenTree::MetaVarDecl(
1324 Some(NonterminalKind::PatParam { inferred: false }),
1326 sess.buffer_lint_with_diagnostic(
1327 &RUST_2021_INCOMPATIBLE_OR_PATTERNS,
1330 "the meaning of the `pat` fragment specifier is changing in Rust 2021, which may affect this macro",
1331 BuiltinLintDiagnostics::OrPatternsBackCompat(span, suggestion),
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
1344 let sp = next_token.span();
1345 let mut err = sess.span_diagnostic.struct_span_err(
1348 "`${name}:{frag}` {may_be} followed by `{next}`, which \
1349 is not allowed for `{frag}` fragments",
1352 next = quoted_tt_to_string(next_token),
1356 err.span_label(sp, format!("not allowed after `{}` fragments", kind));
1358 if kind == NonterminalKind::PatWithOr
1359 && sess.edition.rust_2021()
1360 && next_token.is_token(&BinOp(token::BinOpToken::Or))
1362 let suggestion = quoted_tt_to_string(&TokenTree::MetaVarDecl(
1365 Some(NonterminalKind::PatParam { inferred: false }),
1367 err.span_suggestion(
1369 "try a `pat_param` fragment specifier instead",
1371 Applicability::MaybeIncorrect,
1375 let msg = "allowed there are: ";
1380 "only {} is allowed after `{}` fragments",
1391 .collect::<Vec<_>>()
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)
1411 // (Non NT's can always be followed by anything in matchers.)
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 {
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
1439 No(&'static [&'static str]),
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
1449 // when changing this do not forget to update doc/book/macros.md!
1450 fn is_in_follow(tok: &mbe::TokenTree, kind: NonterminalKind) -> IsInFollow {
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.
1459 NonterminalKind::Item => {
1460 // since items *must* be followed by either a `;` or a `}`, we can
1461 // accept anything after them
1464 NonterminalKind::Block => {
1465 // anything can follow block, the braces provide an easy boundary to
1469 NonterminalKind::Stmt | NonterminalKind::Expr => {
1470 const TOKENS: &[&str] = &["`=>`", "`,`", "`;`"];
1472 TokenTree::Token(token) => match token.kind {
1473 FatArrow | Comma | Semi => IsInFollow::Yes,
1474 _ => IsInFollow::No(TOKENS),
1476 _ => IsInFollow::No(TOKENS),
1479 NonterminalKind::PatParam { .. } => {
1480 const TOKENS: &[&str] = &["`=>`", "`,`", "`=`", "`|`", "`if`", "`in`"];
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),
1487 _ => IsInFollow::No(TOKENS),
1490 NonterminalKind::PatWithOr { .. } => {
1491 const TOKENS: &[&str] = &["`=>`", "`,`", "`=`", "`if`", "`in`"];
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),
1498 _ => IsInFollow::No(TOKENS),
1501 NonterminalKind::Path | NonterminalKind::Ty => {
1502 const TOKENS: &[&str] = &[
1503 "`{`", "`[`", "`=>`", "`,`", "`>`", "`=`", "`:`", "`;`", "`|`", "`as`",
1507 TokenTree::Token(token) => match token.kind {
1508 OpenDelim(Delimiter::Brace)
1509 | OpenDelim(Delimiter::Bracket)
1517 | BinOp(token::Or) => IsInFollow::Yes,
1518 Ident(name, false) if name == kw::As || name == kw::Where => {
1521 _ => IsInFollow::No(TOKENS),
1523 TokenTree::MetaVarDecl(_, _, Some(NonterminalKind::Block)) => IsInFollow::Yes,
1524 _ => IsInFollow::No(TOKENS),
1527 NonterminalKind::Ident | NonterminalKind::Lifetime => {
1528 // being a single token, idents and lifetimes are harmless
1531 NonterminalKind::Literal => {
1532 // literals may be of a single token, or two tokens (negative numbers)
1535 NonterminalKind::Meta | NonterminalKind::TT => {
1536 // being either a single token or a delimited sequence, tt is
1540 NonterminalKind::Vis => {
1541 // Explicitly disallow `priv`, on the off chance it comes back.
1542 const TOKENS: &[&str] = &["`,`", "an ident", "a type"];
1544 TokenTree::Token(token) => match token.kind {
1545 Comma => IsInFollow::Yes,
1546 Ident(name, is_raw) if is_raw || name != kw::Priv => IsInFollow::Yes,
1548 if token.can_begin_type() {
1551 IsInFollow::No(TOKENS)
1555 TokenTree::MetaVarDecl(
1558 Some(NonterminalKind::Ident | NonterminalKind::Ty | NonterminalKind::Path),
1559 ) => IsInFollow::Yes,
1560 _ => IsInFollow::No(TOKENS),
1567 fn quoted_tt_to_string(tt: &mbe::TokenTree) -> String {
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),
1575 "unexpected mbe::TokenTree::{Sequence or Delimited} \
1576 in follow set checker"
1581 fn parser_from_cx(sess: &ParseSess, tts: TokenStream, recovery: Recovery) -> Parser<'_> {
1582 Parser::new(sess, tts, true, rustc_parse::MACRO_ARGUMENTS).recovery(recovery)
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 {
1589 token::Eof => "unexpected end of macro invocation".to_string(),
1590 _ => format!("no rules expected the token `{}`", pprust::token_to_string(tok),),