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;
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;
224 /// A noop tracker that is used in the hot path of the expansion, has zero overhead thanks to monomorphization.
227 impl<'matcher> Tracker<'matcher> for NoopTracker {
228 fn before_match_loc(&mut self, _: &TtParser, _: &'matcher MatcherLoc) {}
229 fn after_arm(&mut self, _: &NamedParseResult) {}
230 fn description() -> &'static str {
235 /// Expands the rules based macro defined by `lhses` and `rhses` for a given
237 #[instrument(skip(cx, transparency, arg, lhses, rhses))]
238 fn expand_macro<'cx>(
239 cx: &'cx mut ExtCtxt<'_>,
244 transparency: Transparency,
246 lhses: &[Vec<MatcherLoc>],
247 rhses: &[mbe::TokenTree],
248 ) -> Box<dyn MacResult + 'cx> {
249 let sess = &cx.sess.parse_sess;
250 // Macros defined in the current crate have a real node id,
251 // whereas macros from an external crate have a dummy id.
252 let is_local = node_id != DUMMY_NODE_ID;
254 if cx.trace_macros() {
255 let msg = format!("expanding `{}! {{ {} }}`", name, pprust::tts_to_string(&arg));
256 trace_macros_note(&mut cx.expansions, sp, msg);
259 // Track nothing for the best performance.
260 let try_success_result = try_match_macro(sess, name, &arg, lhses, &mut NoopTracker);
262 match try_success_result {
263 Ok((i, named_matches)) => {
264 let (rhs, rhs_span): (&mbe::Delimited, DelimSpan) = match &rhses[i] {
265 mbe::TokenTree::Delimited(span, delimited) => (&delimited, *span),
266 _ => cx.span_bug(sp, "malformed macro rhs"),
268 let arm_span = rhses[i].span();
270 let rhs_spans = rhs.tts.iter().map(|t| t.span()).collect::<Vec<_>>();
271 // rhs has holes ( `$id` and `$(...)` that need filled)
272 let mut tts = match transcribe(cx, &named_matches, &rhs, rhs_span, transparency) {
276 return DummyResult::any(arm_span);
280 // Replace all the tokens for the corresponding positions in the macro, to maintain
281 // proper positions in error reporting, while maintaining the macro_backtrace.
282 if rhs_spans.len() == tts.len() {
283 tts = tts.map_enumerated(|i, tt| {
284 let mut tt = tt.clone();
285 let mut sp = rhs_spans[i];
286 sp = sp.with_ctxt(tt.span().ctxt());
292 if cx.trace_macros() {
293 let msg = format!("to `{}`", pprust::tts_to_string(&tts));
294 trace_macros_note(&mut cx.expansions, sp, msg);
297 let mut p = Parser::new(sess, tts, false, None);
298 p.last_type_ascription = cx.current_expansion.prior_type_ascription;
301 cx.resolver.record_macro_rule_usage(node_id, i);
304 // Let the context choose how to interpret the result.
305 // Weird, but useful for X-macros.
306 return Box::new(ParserAnyMacro {
309 // Pass along the original expansion site and the name of the macro
310 // so we can print a useful error message if the parse of the expanded
311 // macro leaves unparsed tokens.
314 lint_node_id: cx.current_expansion.lint_node_id,
315 is_trailing_mac: cx.current_expansion.is_trailing_mac,
320 Err(CanRetry::No(_)) => {
321 debug!("Will not retry matching as an error was emitted already");
322 return DummyResult::any(sp);
324 Err(CanRetry::Yes) => {
325 // Retry and emit a better error below.
329 // An error occurred, try the expansion again, tracking the expansion closely for better diagnostics.
330 let mut tracker = CollectTrackerAndEmitter::new(cx, sp);
332 let try_success_result = try_match_macro(sess, name, &arg, lhses, &mut tracker);
333 assert!(try_success_result.is_err(), "Macro matching returned a success on the second try");
335 if let Some(result) = tracker.result {
336 // An irrecoverable error occurred and has been emitted.
340 let Some((token, label, remaining_matcher)) = tracker.best_failure else {
341 return tracker.result.expect("must have encountered Error or ErrorReported");
344 let span = token.span.substitute_dummy(sp);
346 let mut err = cx.struct_span_err(span, &parse_failure_msg(&token));
347 err.span_label(span, label);
348 if !def_span.is_dummy() && !cx.source_map().is_imported(def_span) {
349 err.span_label(cx.source_map().guess_head_span(def_span), "when calling this macro");
352 annotate_doc_comment(&mut err, sess.source_map(), span);
354 if let Some(span) = remaining_matcher.span() {
355 err.span_note(span, format!("while trying to match {remaining_matcher}"));
357 err.note(format!("while trying to match {remaining_matcher}"));
360 // Check whether there's a missing comma in this macro call, like `println!("{}" a);`
361 if let Some((arg, comma_span)) = arg.add_comma() {
363 let parser = parser_from_cx(sess, arg.clone());
364 let mut tt_parser = TtParser::new(name);
367 tt_parser.parse_tt(&mut Cow::Borrowed(&parser), lhs, &mut NoopTracker)
369 if comma_span.is_dummy() {
370 err.note("you might be missing a comma");
372 err.span_suggestion_short(
374 "missing comma here",
376 Applicability::MachineApplicable,
383 cx.trace_macros_diag();
387 /// The tracker used for the slow error path that collects useful info for diagnostics.
388 struct CollectTrackerAndEmitter<'a, 'cx, 'matcher> {
389 cx: &'a mut ExtCtxt<'cx>,
390 remaining_matcher: Option<&'matcher MatcherLoc>,
391 /// Which arm's failure should we report? (the one furthest along)
392 best_failure: Option<(Token, &'static str, MatcherLoc)>,
394 result: Option<Box<dyn MacResult + 'cx>>,
397 impl<'a, 'cx, 'matcher> Tracker<'matcher> for CollectTrackerAndEmitter<'a, 'cx, 'matcher> {
398 fn before_match_loc(&mut self, parser: &TtParser, matcher: &'matcher MatcherLoc) {
399 if self.remaining_matcher.is_none()
400 || (parser.has_no_remaining_items_for_step() && *matcher != MatcherLoc::Eof)
402 self.remaining_matcher = Some(matcher);
406 fn after_arm(&mut self, result: &NamedParseResult) {
409 unreachable!("should not collect detailed info for successful macro match");
411 Failure(token, msg) => match self.best_failure {
412 Some((ref best_token, _, _)) if best_token.span.lo() >= token.span.lo() => {}
414 self.best_failure = Some((
417 self.remaining_matcher
418 .expect("must have collected matcher already")
423 Error(err_sp, msg) => {
424 let span = err_sp.substitute_dummy(self.root_span);
425 self.cx.struct_span_err(span, msg).emit();
426 self.result = Some(DummyResult::any(span));
428 ErrorReported(_) => self.result = Some(DummyResult::any(self.root_span)),
432 fn description() -> &'static str {
437 impl<'a, 'cx> CollectTrackerAndEmitter<'a, 'cx, '_> {
438 fn new(cx: &'a mut ExtCtxt<'cx>, root_span: Span) -> Self {
439 Self { cx, remaining_matcher: None, best_failure: None, root_span, result: None }
445 /// We are not allowed to retry macro expansion as a fatal error has been emitted already.
449 /// Try expanding the macro. Returns the index of the successful arm and its named_matches if it was successful,
450 /// and nothing if it failed. On failure, it's the callers job to use `track` accordingly to record all errors
452 #[instrument(level = "debug", skip(sess, arg, lhses, track), fields(tracking = %T::description()))]
453 fn try_match_macro<'matcher, T: Tracker<'matcher>>(
457 lhses: &'matcher [Vec<MatcherLoc>],
459 ) -> Result<(usize, NamedMatches), CanRetry> {
460 // We create a base parser that can be used for the "black box" parts.
461 // Every iteration needs a fresh copy of that parser. However, the parser
462 // is not mutated on many of the iterations, particularly when dealing with
465 // macro_rules! foo {
469 // // ... etc. (maybe hundreds more)
472 // as seen in the `html5ever` benchmark. We use a `Cow` so that the base
473 // parser is only cloned when necessary (upon mutation). Furthermore, we
474 // reinitialize the `Cow` with the base parser at the start of every
475 // iteration, so that any mutated parsers are not reused. This is all quite
476 // hacky, but speeds up the `html5ever` benchmark significantly. (Issue
477 // 68836 suggests a more comprehensive but more complex change to deal with
479 // FIXME(Nilstrieb): Stop recovery from happening on this parser and retry later with recovery if the macro failed to match.
480 let parser = parser_from_cx(sess, arg.clone());
481 // Try each arm's matchers.
482 let mut tt_parser = TtParser::new(name);
483 for (i, lhs) in lhses.iter().enumerate() {
484 let _tracing_span = trace_span!("Matching arm", %i);
486 // Take a snapshot of the state of pre-expansion gating at this point.
487 // This is used so that if a matcher is not `Success(..)`ful,
488 // then the spans which became gated when parsing the unsuccessful matcher
489 // are not recorded. On the first `Success(..)`ful matcher, the spans are merged.
490 let mut gated_spans_snapshot = mem::take(&mut *sess.gated_spans.spans.borrow_mut());
492 let result = tt_parser.parse_tt(&mut Cow::Borrowed(&parser), lhs, track);
494 track.after_arm(&result);
497 Success(named_matches) => {
498 debug!("Parsed arm successfully");
499 // The matcher was `Success(..)`ful.
500 // Merge the gated spans from parsing the matcher with the pre-existing ones.
501 sess.gated_spans.merge(gated_spans_snapshot);
503 return Ok((i, named_matches));
506 trace!("Failed to match arm, trying the next one");
510 debug!("Fatal error occurred during matching");
511 // We haven't emitted an error yet, so we can retry.
512 return Err(CanRetry::Yes);
514 ErrorReported(guarantee) => {
515 debug!("Fatal error occurred and was reported during matching");
516 // An error has been reported already, we cannot retry as that would cause duplicate errors.
517 return Err(CanRetry::No(guarantee));
521 // The matcher was not `Success(..)`ful.
522 // Restore to the state before snapshotting and maybe try again.
523 mem::swap(&mut gated_spans_snapshot, &mut sess.gated_spans.spans.borrow_mut());
529 // Note that macro-by-example's input is also matched against a token tree:
530 // $( $lhs:tt => $rhs:tt );+
532 // Holy self-referential!
534 /// Converts a macro item into a syntax extension.
535 pub fn compile_declarative_macro(
540 ) -> (SyntaxExtension, Vec<(usize, Span)>) {
541 debug!("compile_declarative_macro: {:?}", def);
542 let mk_syn_ext = |expander| {
543 SyntaxExtension::new(
545 SyntaxExtensionKind::LegacyBang(expander),
553 let dummy_syn_ext = || (mk_syn_ext(Box::new(macro_rules_dummy_expander)), Vec::new());
555 let diag = &sess.parse_sess.span_diagnostic;
556 let lhs_nm = Ident::new(sym::lhs, def.span);
557 let rhs_nm = Ident::new(sym::rhs, def.span);
558 let tt_spec = Some(NonterminalKind::TT);
560 // Parse the macro_rules! invocation
561 let (macro_rules, body) = match &def.kind {
562 ast::ItemKind::MacroDef(def) => (def.macro_rules, def.body.inner_tokens()),
566 // The pattern that macro_rules matches.
567 // The grammar for macro_rules! is:
568 // $( $lhs:tt => $rhs:tt );+
569 // ...quasiquoting this would be nice.
570 // These spans won't matter, anyways
571 let argument_gram = vec![
572 mbe::TokenTree::Sequence(
574 mbe::SequenceRepetition {
576 mbe::TokenTree::MetaVarDecl(def.span, lhs_nm, tt_spec),
577 mbe::TokenTree::token(token::FatArrow, def.span),
578 mbe::TokenTree::MetaVarDecl(def.span, rhs_nm, tt_spec),
580 separator: Some(Token::new(
581 if macro_rules { token::Semi } else { token::Comma },
584 kleene: mbe::KleeneToken::new(mbe::KleeneOp::OneOrMore, def.span),
588 // to phase into semicolon-termination instead of semicolon-separation
589 mbe::TokenTree::Sequence(
591 mbe::SequenceRepetition {
592 tts: vec![mbe::TokenTree::token(
593 if macro_rules { token::Semi } else { token::Comma },
597 kleene: mbe::KleeneToken::new(mbe::KleeneOp::ZeroOrMore, def.span),
602 // Convert it into `MatcherLoc` form.
603 let argument_gram = mbe::macro_parser::compute_locs(&argument_gram);
605 let parser = Parser::new(&sess.parse_sess, body, true, rustc_parse::MACRO_ARGUMENTS);
607 TtParser::new(Ident::with_dummy_span(if macro_rules { kw::MacroRules } else { kw::Macro }));
609 match tt_parser.parse_tt(&mut Cow::Owned(parser), &argument_gram, &mut NoopTracker) {
611 Failure(token, msg) => {
612 let s = parse_failure_msg(&token);
613 let sp = token.span.substitute_dummy(def.span);
614 let mut err = sess.parse_sess.span_diagnostic.struct_span_err(sp, &s);
615 err.span_label(sp, msg);
616 annotate_doc_comment(&mut err, sess.source_map(), sp);
618 return dummy_syn_ext();
623 .struct_span_err(sp.substitute_dummy(def.span), &msg)
625 return dummy_syn_ext();
627 ErrorReported(_) => {
628 return dummy_syn_ext();
632 let mut valid = true;
634 // Extract the arguments:
635 let lhses = match argument_map[&MacroRulesNormalizedIdent::new(lhs_nm)] {
636 MatchedSeq(ref s) => s
639 if let MatchedTokenTree(ref tt) = *m {
640 let tt = mbe::quoted::parse(
641 TokenStream::new(vec![tt.clone()]),
650 valid &= check_lhs_nt_follows(&sess.parse_sess, &def, &tt);
653 sess.parse_sess.span_diagnostic.span_bug(def.span, "wrong-structured lhs")
655 .collect::<Vec<mbe::TokenTree>>(),
656 _ => sess.parse_sess.span_diagnostic.span_bug(def.span, "wrong-structured lhs"),
659 let rhses = match argument_map[&MacroRulesNormalizedIdent::new(rhs_nm)] {
660 MatchedSeq(ref s) => s
663 if let MatchedTokenTree(ref tt) = *m {
664 return mbe::quoted::parse(
665 TokenStream::new(vec![tt.clone()]),
675 sess.parse_sess.span_diagnostic.span_bug(def.span, "wrong-structured lhs")
677 .collect::<Vec<mbe::TokenTree>>(),
678 _ => sess.parse_sess.span_diagnostic.span_bug(def.span, "wrong-structured rhs"),
682 valid &= check_rhs(&sess.parse_sess, rhs);
685 // don't abort iteration early, so that errors for multiple lhses can be reported
687 valid &= check_lhs_no_empty_seq(&sess.parse_sess, slice::from_ref(lhs));
690 valid &= macro_check::check_meta_variables(&sess.parse_sess, def.id, def.span, &lhses, &rhses);
692 let (transparency, transparency_error) = attr::find_transparency(&def.attrs, macro_rules);
693 match transparency_error {
694 Some(TransparencyError::UnknownTransparency(value, span)) => {
695 diag.span_err(span, &format!("unknown macro transparency: `{}`", value));
697 Some(TransparencyError::MultipleTransparencyAttrs(old_span, new_span)) => {
698 diag.span_err(vec![old_span, new_span], "multiple macro transparency attributes");
703 // Compute the spans of the macro rules for unused rule linting.
704 // To avoid warning noise, only consider the rules of this
705 // macro for the lint, if all rules are valid.
706 // Also, we are only interested in non-foreign macros.
707 let rule_spans = if valid && def.id != DUMMY_NODE_ID {
712 // If the rhs contains an invocation like compile_error!,
713 // don't consider the rule for the unused rule lint.
714 .filter(|(_idx, (_lhs, rhs))| !has_compile_error_macro(rhs))
715 // We only take the span of the lhs here,
716 // so that the spans of created warnings are smaller.
717 .map(|(idx, (lhs, _rhs))| (idx, lhs.span()))
723 // Convert the lhses into `MatcherLoc` form, which is better for doing the
724 // actual matching. Unless the matcher is invalid.
725 let lhses = if valid {
729 // Ignore the delimiters around the matcher.
731 mbe::TokenTree::Delimited(_, delimited) => {
732 mbe::macro_parser::compute_locs(&delimited.tts)
734 _ => sess.parse_sess.span_diagnostic.span_bug(def.span, "malformed macro lhs"),
742 let expander = Box::new(MacroRulesMacroExpander {
751 (mk_syn_ext(expander), rule_spans)
754 #[derive(Subdiagnostic)]
755 enum ExplainDocComment {
756 #[label(expand_explain_doc_comment_inner)]
761 #[label(expand_explain_doc_comment_outer)]
768 fn annotate_doc_comment(err: &mut Diagnostic, sm: &SourceMap, span: Span) {
769 if let Ok(src) = sm.span_to_snippet(span) {
770 if src.starts_with("///") || src.starts_with("/**") {
771 err.subdiagnostic(ExplainDocComment::Outer { span });
772 } else if src.starts_with("//!") || src.starts_with("/*!") {
773 err.subdiagnostic(ExplainDocComment::Inner { span });
778 fn check_lhs_nt_follows(sess: &ParseSess, def: &ast::Item, lhs: &mbe::TokenTree) -> bool {
779 // lhs is going to be like TokenTree::Delimited(...), where the
780 // entire lhs is those tts. Or, it can be a "bare sequence", not wrapped in parens.
781 if let mbe::TokenTree::Delimited(_, delimited) = lhs {
782 check_matcher(sess, def, &delimited.tts)
784 let msg = "invalid macro matcher; matchers must be contained in balanced delimiters";
785 sess.span_diagnostic.span_err(lhs.span(), msg);
788 // we don't abort on errors on rejection, the driver will do that for us
789 // after parsing/expansion. we can report every error in every macro this way.
792 /// Checks that the lhs contains no repetition which could match an empty token
793 /// tree, because then the matcher would hang indefinitely.
794 fn check_lhs_no_empty_seq(sess: &ParseSess, tts: &[mbe::TokenTree]) -> bool {
799 | TokenTree::MetaVar(..)
800 | TokenTree::MetaVarDecl(..)
801 | TokenTree::MetaVarExpr(..) => (),
802 TokenTree::Delimited(_, ref del) => {
803 if !check_lhs_no_empty_seq(sess, &del.tts) {
807 TokenTree::Sequence(span, ref seq) => {
808 if seq.separator.is_none()
809 && seq.tts.iter().all(|seq_tt| match *seq_tt {
810 TokenTree::MetaVarDecl(_, _, Some(NonterminalKind::Vis)) => true,
811 TokenTree::Sequence(_, ref sub_seq) => {
812 sub_seq.kleene.op == mbe::KleeneOp::ZeroOrMore
813 || sub_seq.kleene.op == mbe::KleeneOp::ZeroOrOne
818 let sp = span.entire();
819 sess.span_diagnostic.span_err(sp, "repetition matches empty token tree");
822 if !check_lhs_no_empty_seq(sess, &seq.tts) {
832 fn check_rhs(sess: &ParseSess, rhs: &mbe::TokenTree) -> bool {
834 mbe::TokenTree::Delimited(..) => return true,
836 sess.span_diagnostic.span_err(rhs.span(), "macro rhs must be delimited");
842 fn check_matcher(sess: &ParseSess, def: &ast::Item, matcher: &[mbe::TokenTree]) -> bool {
843 let first_sets = FirstSets::new(matcher);
844 let empty_suffix = TokenSet::empty();
845 let err = sess.span_diagnostic.err_count();
846 check_matcher_core(sess, def, &first_sets, matcher, &empty_suffix);
847 err == sess.span_diagnostic.err_count()
850 fn has_compile_error_macro(rhs: &mbe::TokenTree) -> bool {
852 mbe::TokenTree::Delimited(_sp, d) => {
853 let has_compile_error = d.tts.array_windows::<3>().any(|[ident, bang, args]| {
854 if let mbe::TokenTree::Token(ident) = ident &&
855 let TokenKind::Ident(ident, _) = ident.kind &&
856 ident == sym::compile_error &&
857 let mbe::TokenTree::Token(bang) = bang &&
858 let TokenKind::Not = bang.kind &&
859 let mbe::TokenTree::Delimited(_, del) = args &&
860 del.delim != Delimiter::Invisible
867 if has_compile_error { true } else { d.tts.iter().any(has_compile_error_macro) }
873 // `The FirstSets` for a matcher is a mapping from subsequences in the
874 // matcher to the FIRST set for that subsequence.
876 // This mapping is partially precomputed via a backwards scan over the
877 // token trees of the matcher, which provides a mapping from each
878 // repetition sequence to its *first* set.
880 // (Hypothetically, sequences should be uniquely identifiable via their
881 // spans, though perhaps that is false, e.g., for macro-generated macros
882 // that do not try to inject artificial span information. My plan is
883 // to try to catch such cases ahead of time and not include them in
884 // the precomputed mapping.)
885 struct FirstSets<'tt> {
886 // this maps each TokenTree::Sequence `$(tt ...) SEP OP` that is uniquely identified by its
887 // span in the original matcher to the First set for the inner sequence `tt ...`.
889 // If two sequences have the same span in a matcher, then map that
890 // span to None (invalidating the mapping here and forcing the code to
892 first: FxHashMap<Span, Option<TokenSet<'tt>>>,
895 impl<'tt> FirstSets<'tt> {
896 fn new(tts: &'tt [mbe::TokenTree]) -> FirstSets<'tt> {
899 let mut sets = FirstSets { first: FxHashMap::default() };
900 build_recur(&mut sets, tts);
903 // walks backward over `tts`, returning the FIRST for `tts`
904 // and updating `sets` at the same time for all sequence
905 // substructure we find within `tts`.
906 fn build_recur<'tt>(sets: &mut FirstSets<'tt>, tts: &'tt [TokenTree]) -> TokenSet<'tt> {
907 let mut first = TokenSet::empty();
908 for tt in tts.iter().rev() {
911 | TokenTree::MetaVar(..)
912 | TokenTree::MetaVarDecl(..)
913 | TokenTree::MetaVarExpr(..) => {
914 first.replace_with(TtHandle::TtRef(tt));
916 TokenTree::Delimited(span, ref delimited) => {
917 build_recur(sets, &delimited.tts);
918 first.replace_with(TtHandle::from_token_kind(
919 token::OpenDelim(delimited.delim),
923 TokenTree::Sequence(sp, ref seq_rep) => {
924 let subfirst = build_recur(sets, &seq_rep.tts);
926 match sets.first.entry(sp.entire()) {
927 Entry::Vacant(vac) => {
928 vac.insert(Some(subfirst.clone()));
930 Entry::Occupied(mut occ) => {
931 // if there is already an entry, then a span must have collided.
932 // This should not happen with typical macro_rules macros,
933 // but syntax extensions need not maintain distinct spans,
934 // so distinct syntax trees can be assigned the same span.
935 // In such a case, the map cannot be trusted; so mark this
936 // entry as unusable.
941 // If the sequence contents can be empty, then the first
942 // token could be the separator token itself.
944 if let (Some(sep), true) = (&seq_rep.separator, subfirst.maybe_empty) {
945 first.add_one_maybe(TtHandle::from_token(sep.clone()));
948 // Reverse scan: Sequence comes before `first`.
949 if subfirst.maybe_empty
950 || seq_rep.kleene.op == mbe::KleeneOp::ZeroOrMore
951 || seq_rep.kleene.op == mbe::KleeneOp::ZeroOrOne
953 // If sequence is potentially empty, then
954 // union them (preserving first emptiness).
955 first.add_all(&TokenSet { maybe_empty: true, ..subfirst });
957 // Otherwise, sequence guaranteed
958 // non-empty; replace first.
969 // walks forward over `tts` until all potential FIRST tokens are
971 fn first(&self, tts: &'tt [mbe::TokenTree]) -> TokenSet<'tt> {
974 let mut first = TokenSet::empty();
975 for tt in tts.iter() {
976 assert!(first.maybe_empty);
979 | TokenTree::MetaVar(..)
980 | TokenTree::MetaVarDecl(..)
981 | TokenTree::MetaVarExpr(..) => {
982 first.add_one(TtHandle::TtRef(tt));
985 TokenTree::Delimited(span, ref delimited) => {
986 first.add_one(TtHandle::from_token_kind(
987 token::OpenDelim(delimited.delim),
992 TokenTree::Sequence(sp, ref seq_rep) => {
994 let subfirst = match self.first.get(&sp.entire()) {
995 Some(&Some(ref subfirst)) => subfirst,
997 subfirst_owned = self.first(&seq_rep.tts);
1001 panic!("We missed a sequence during FirstSets construction");
1005 // If the sequence contents can be empty, then the first
1006 // token could be the separator token itself.
1007 if let (Some(sep), true) = (&seq_rep.separator, subfirst.maybe_empty) {
1008 first.add_one_maybe(TtHandle::from_token(sep.clone()));
1011 assert!(first.maybe_empty);
1012 first.add_all(subfirst);
1013 if subfirst.maybe_empty
1014 || seq_rep.kleene.op == mbe::KleeneOp::ZeroOrMore
1015 || seq_rep.kleene.op == mbe::KleeneOp::ZeroOrOne
1017 // Continue scanning for more first
1018 // tokens, but also make sure we
1019 // restore empty-tracking state.
1020 first.maybe_empty = true;
1029 // we only exit the loop if `tts` was empty or if every
1030 // element of `tts` matches the empty sequence.
1031 assert!(first.maybe_empty);
1036 // Most `mbe::TokenTree`s are pre-existing in the matcher, but some are defined
1037 // implicitly, such as opening/closing delimiters and sequence repetition ops.
1038 // This type encapsulates both kinds. It implements `Clone` while avoiding the
1039 // need for `mbe::TokenTree` to implement `Clone`.
1041 enum TtHandle<'tt> {
1042 /// This is used in most cases.
1043 TtRef(&'tt mbe::TokenTree),
1045 /// This is only used for implicit token trees. The `mbe::TokenTree` *must*
1046 /// be `mbe::TokenTree::Token`. No other variants are allowed. We store an
1047 /// `mbe::TokenTree` rather than a `Token` so that `get()` can return a
1048 /// `&mbe::TokenTree`.
1049 Token(mbe::TokenTree),
1052 impl<'tt> TtHandle<'tt> {
1053 fn from_token(tok: Token) -> Self {
1054 TtHandle::Token(mbe::TokenTree::Token(tok))
1057 fn from_token_kind(kind: TokenKind, span: Span) -> Self {
1058 TtHandle::from_token(Token::new(kind, span))
1061 // Get a reference to a token tree.
1062 fn get(&'tt self) -> &'tt mbe::TokenTree {
1064 TtHandle::TtRef(tt) => tt,
1065 TtHandle::Token(token_tt) => &token_tt,
1070 impl<'tt> PartialEq for TtHandle<'tt> {
1071 fn eq(&self, other: &TtHandle<'tt>) -> bool {
1072 self.get() == other.get()
1076 impl<'tt> Clone for TtHandle<'tt> {
1077 fn clone(&self) -> Self {
1079 TtHandle::TtRef(tt) => TtHandle::TtRef(tt),
1081 // This variant *must* contain a `mbe::TokenTree::Token`, and not
1082 // any other variant of `mbe::TokenTree`.
1083 TtHandle::Token(mbe::TokenTree::Token(tok)) => {
1084 TtHandle::Token(mbe::TokenTree::Token(tok.clone()))
1087 _ => unreachable!(),
1092 // A set of `mbe::TokenTree`s, which may include `TokenTree::Match`s
1093 // (for macro-by-example syntactic variables). It also carries the
1094 // `maybe_empty` flag; that is true if and only if the matcher can
1095 // match an empty token sequence.
1097 // The First set is computed on submatchers like `$($a:expr b),* $(c)* d`,
1098 // which has corresponding FIRST = {$a:expr, c, d}.
1099 // Likewise, `$($a:expr b),* $(c)+ d` has FIRST = {$a:expr, c}.
1101 // (Notably, we must allow for *-op to occur zero times.)
1102 #[derive(Clone, Debug)]
1103 struct TokenSet<'tt> {
1104 tokens: Vec<TtHandle<'tt>>,
1108 impl<'tt> TokenSet<'tt> {
1109 // Returns a set for the empty sequence.
1110 fn empty() -> Self {
1111 TokenSet { tokens: Vec::new(), maybe_empty: true }
1114 // Returns the set `{ tok }` for the single-token (and thus
1115 // non-empty) sequence [tok].
1116 fn singleton(tt: TtHandle<'tt>) -> Self {
1117 TokenSet { tokens: vec![tt], maybe_empty: false }
1120 // Changes self to be the set `{ tok }`.
1121 // Since `tok` is always present, marks self as non-empty.
1122 fn replace_with(&mut self, tt: TtHandle<'tt>) {
1123 self.tokens.clear();
1124 self.tokens.push(tt);
1125 self.maybe_empty = false;
1128 // Changes self to be the empty set `{}`; meant for use when
1129 // the particular token does not matter, but we want to
1130 // record that it occurs.
1131 fn replace_with_irrelevant(&mut self) {
1132 self.tokens.clear();
1133 self.maybe_empty = false;
1136 // Adds `tok` to the set for `self`, marking sequence as non-empty.
1137 fn add_one(&mut self, tt: TtHandle<'tt>) {
1138 if !self.tokens.contains(&tt) {
1139 self.tokens.push(tt);
1141 self.maybe_empty = false;
1144 // Adds `tok` to the set for `self`. (Leaves `maybe_empty` flag alone.)
1145 fn add_one_maybe(&mut self, tt: TtHandle<'tt>) {
1146 if !self.tokens.contains(&tt) {
1147 self.tokens.push(tt);
1151 // Adds all elements of `other` to this.
1153 // (Since this is a set, we filter out duplicates.)
1155 // If `other` is potentially empty, then preserves the previous
1156 // setting of the empty flag of `self`. If `other` is guaranteed
1157 // non-empty, then `self` is marked non-empty.
1158 fn add_all(&mut self, other: &Self) {
1159 for tt in &other.tokens {
1160 if !self.tokens.contains(tt) {
1161 self.tokens.push(tt.clone());
1164 if !other.maybe_empty {
1165 self.maybe_empty = false;
1170 // Checks that `matcher` is internally consistent and that it
1171 // can legally be followed by a token `N`, for all `N` in `follow`.
1172 // (If `follow` is empty, then it imposes no constraint on
1175 // Returns the set of NT tokens that could possibly come last in
1176 // `matcher`. (If `matcher` matches the empty sequence, then
1177 // `maybe_empty` will be set to true.)
1179 // Requires that `first_sets` is pre-computed for `matcher`;
1180 // see `FirstSets::new`.
1181 fn check_matcher_core<'tt>(
1184 first_sets: &FirstSets<'tt>,
1185 matcher: &'tt [mbe::TokenTree],
1186 follow: &TokenSet<'tt>,
1187 ) -> TokenSet<'tt> {
1190 let mut last = TokenSet::empty();
1192 // 2. For each token and suffix [T, SUFFIX] in M:
1193 // ensure that T can be followed by SUFFIX, and if SUFFIX may be empty,
1194 // then ensure T can also be followed by any element of FOLLOW.
1195 'each_token: for i in 0..matcher.len() {
1196 let token = &matcher[i];
1197 let suffix = &matcher[i + 1..];
1199 let build_suffix_first = || {
1200 let mut s = first_sets.first(suffix);
1207 // (we build `suffix_first` on demand below; you can tell
1208 // which cases are supposed to fall through by looking for the
1209 // initialization of this variable.)
1212 // First, update `last` so that it corresponds to the set
1213 // of NT tokens that might end the sequence `... token`.
1215 TokenTree::Token(..)
1216 | TokenTree::MetaVar(..)
1217 | TokenTree::MetaVarDecl(..)
1218 | TokenTree::MetaVarExpr(..) => {
1219 if token_can_be_followed_by_any(token) {
1220 // don't need to track tokens that work with any,
1221 last.replace_with_irrelevant();
1222 // ... and don't need to check tokens that can be
1223 // followed by anything against SUFFIX.
1224 continue 'each_token;
1226 last.replace_with(TtHandle::TtRef(token));
1227 suffix_first = build_suffix_first();
1230 TokenTree::Delimited(span, ref d) => {
1231 let my_suffix = TokenSet::singleton(TtHandle::from_token_kind(
1232 token::CloseDelim(d.delim),
1235 check_matcher_core(sess, def, first_sets, &d.tts, &my_suffix);
1236 // don't track non NT tokens
1237 last.replace_with_irrelevant();
1239 // also, we don't need to check delimited sequences
1241 continue 'each_token;
1243 TokenTree::Sequence(_, ref seq_rep) => {
1244 suffix_first = build_suffix_first();
1245 // The trick here: when we check the interior, we want
1246 // to include the separator (if any) as a potential
1247 // (but not guaranteed) element of FOLLOW. So in that
1248 // case, we make a temp copy of suffix and stuff
1249 // delimiter in there.
1251 // FIXME: Should I first scan suffix_first to see if
1252 // delimiter is already in it before I go through the
1253 // work of cloning it? But then again, this way I may
1254 // get a "tighter" span?
1256 let my_suffix = if let Some(sep) = &seq_rep.separator {
1257 new = suffix_first.clone();
1258 new.add_one_maybe(TtHandle::from_token(sep.clone()));
1264 // At this point, `suffix_first` is built, and
1265 // `my_suffix` is some TokenSet that we can use
1266 // for checking the interior of `seq_rep`.
1267 let next = check_matcher_core(sess, def, first_sets, &seq_rep.tts, my_suffix);
1268 if next.maybe_empty {
1269 last.add_all(&next);
1274 // the recursive call to check_matcher_core already ran the 'each_last
1275 // check below, so we can just keep going forward here.
1276 continue 'each_token;
1280 // (`suffix_first` guaranteed initialized once reaching here.)
1282 // Now `last` holds the complete set of NT tokens that could
1283 // end the sequence before SUFFIX. Check that every one works with `suffix`.
1284 for tt in &last.tokens {
1285 if let &TokenTree::MetaVarDecl(span, name, Some(kind)) = tt.get() {
1286 for next_token in &suffix_first.tokens {
1287 let next_token = next_token.get();
1289 // Check if the old pat is used and the next token is `|`
1290 // to warn about incompatibility with Rust 2021.
1291 // We only emit this lint if we're parsing the original
1292 // definition of this macro_rules, not while (re)parsing
1293 // the macro when compiling another crate that is using the
1294 // macro. (See #86567.)
1295 // Macros defined in the current crate have a real node id,
1296 // whereas macros from an external crate have a dummy id.
1297 if def.id != DUMMY_NODE_ID
1298 && matches!(kind, NonterminalKind::PatParam { inferred: true })
1299 && matches!(next_token, TokenTree::Token(token) if token.kind == BinOp(token::BinOpToken::Or))
1301 // It is suggestion to use pat_param, for example: $x:pat -> $x:pat_param.
1302 let suggestion = quoted_tt_to_string(&TokenTree::MetaVarDecl(
1305 Some(NonterminalKind::PatParam { inferred: false }),
1307 sess.buffer_lint_with_diagnostic(
1308 &RUST_2021_INCOMPATIBLE_OR_PATTERNS,
1311 "the meaning of the `pat` fragment specifier is changing in Rust 2021, which may affect this macro",
1312 BuiltinLintDiagnostics::OrPatternsBackCompat(span, suggestion),
1315 match is_in_follow(next_token, kind) {
1316 IsInFollow::Yes => {}
1317 IsInFollow::No(possible) => {
1318 let may_be = if last.tokens.len() == 1 && suffix_first.tokens.len() == 1
1325 let sp = next_token.span();
1326 let mut err = sess.span_diagnostic.struct_span_err(
1329 "`${name}:{frag}` {may_be} followed by `{next}`, which \
1330 is not allowed for `{frag}` fragments",
1333 next = quoted_tt_to_string(next_token),
1337 err.span_label(sp, format!("not allowed after `{}` fragments", kind));
1339 if kind == NonterminalKind::PatWithOr
1340 && sess.edition.rust_2021()
1341 && next_token.is_token(&BinOp(token::BinOpToken::Or))
1343 let suggestion = quoted_tt_to_string(&TokenTree::MetaVarDecl(
1346 Some(NonterminalKind::PatParam { inferred: false }),
1348 err.span_suggestion(
1350 "try a `pat_param` fragment specifier instead",
1352 Applicability::MaybeIncorrect,
1356 let msg = "allowed there are: ";
1361 "only {} is allowed after `{}` fragments",
1372 .collect::<Vec<_>>()
1388 fn token_can_be_followed_by_any(tok: &mbe::TokenTree) -> bool {
1389 if let mbe::TokenTree::MetaVarDecl(_, _, Some(kind)) = *tok {
1390 frag_can_be_followed_by_any(kind)
1392 // (Non NT's can always be followed by anything in matchers.)
1397 /// Returns `true` if a fragment of type `frag` can be followed by any sort of
1398 /// token. We use this (among other things) as a useful approximation
1399 /// for when `frag` can be followed by a repetition like `$(...)*` or
1400 /// `$(...)+`. In general, these can be a bit tricky to reason about,
1401 /// so we adopt a conservative position that says that any fragment
1402 /// specifier which consumes at most one token tree can be followed by
1403 /// a fragment specifier (indeed, these fragments can be followed by
1404 /// ANYTHING without fear of future compatibility hazards).
1405 fn frag_can_be_followed_by_any(kind: NonterminalKind) -> bool {
1408 NonterminalKind::Item // always terminated by `}` or `;`
1409 | NonterminalKind::Block // exactly one token tree
1410 | NonterminalKind::Ident // exactly one token tree
1411 | NonterminalKind::Literal // exactly one token tree
1412 | NonterminalKind::Meta // exactly one token tree
1413 | NonterminalKind::Lifetime // exactly one token tree
1414 | NonterminalKind::TT // exactly one token tree
1420 No(&'static [&'static str]),
1423 /// Returns `true` if `frag` can legally be followed by the token `tok`. For
1424 /// fragments that can consume an unbounded number of tokens, `tok`
1425 /// must be within a well-defined follow set. This is intended to
1426 /// guarantee future compatibility: for example, without this rule, if
1427 /// we expanded `expr` to include a new binary operator, we might
1428 /// break macros that were relying on that binary operator as a
1430 // when changing this do not forget to update doc/book/macros.md!
1431 fn is_in_follow(tok: &mbe::TokenTree, kind: NonterminalKind) -> IsInFollow {
1434 if let TokenTree::Token(Token { kind: token::CloseDelim(_), .. }) = *tok {
1435 // closing a token tree can never be matched by any fragment;
1436 // iow, we always require that `(` and `)` match, etc.
1440 NonterminalKind::Item => {
1441 // since items *must* be followed by either a `;` or a `}`, we can
1442 // accept anything after them
1445 NonterminalKind::Block => {
1446 // anything can follow block, the braces provide an easy boundary to
1450 NonterminalKind::Stmt | NonterminalKind::Expr => {
1451 const TOKENS: &[&str] = &["`=>`", "`,`", "`;`"];
1453 TokenTree::Token(token) => match token.kind {
1454 FatArrow | Comma | Semi => IsInFollow::Yes,
1455 _ => IsInFollow::No(TOKENS),
1457 _ => IsInFollow::No(TOKENS),
1460 NonterminalKind::PatParam { .. } => {
1461 const TOKENS: &[&str] = &["`=>`", "`,`", "`=`", "`|`", "`if`", "`in`"];
1463 TokenTree::Token(token) => match token.kind {
1464 FatArrow | Comma | Eq | BinOp(token::Or) => IsInFollow::Yes,
1465 Ident(name, false) if name == kw::If || name == kw::In => IsInFollow::Yes,
1466 _ => IsInFollow::No(TOKENS),
1468 _ => IsInFollow::No(TOKENS),
1471 NonterminalKind::PatWithOr { .. } => {
1472 const TOKENS: &[&str] = &["`=>`", "`,`", "`=`", "`if`", "`in`"];
1474 TokenTree::Token(token) => match token.kind {
1475 FatArrow | Comma | Eq => IsInFollow::Yes,
1476 Ident(name, false) if name == kw::If || name == kw::In => IsInFollow::Yes,
1477 _ => IsInFollow::No(TOKENS),
1479 _ => IsInFollow::No(TOKENS),
1482 NonterminalKind::Path | NonterminalKind::Ty => {
1483 const TOKENS: &[&str] = &[
1484 "`{`", "`[`", "`=>`", "`,`", "`>`", "`=`", "`:`", "`;`", "`|`", "`as`",
1488 TokenTree::Token(token) => match token.kind {
1489 OpenDelim(Delimiter::Brace)
1490 | OpenDelim(Delimiter::Bracket)
1498 | BinOp(token::Or) => IsInFollow::Yes,
1499 Ident(name, false) if name == kw::As || name == kw::Where => {
1502 _ => IsInFollow::No(TOKENS),
1504 TokenTree::MetaVarDecl(_, _, Some(NonterminalKind::Block)) => IsInFollow::Yes,
1505 _ => IsInFollow::No(TOKENS),
1508 NonterminalKind::Ident | NonterminalKind::Lifetime => {
1509 // being a single token, idents and lifetimes are harmless
1512 NonterminalKind::Literal => {
1513 // literals may be of a single token, or two tokens (negative numbers)
1516 NonterminalKind::Meta | NonterminalKind::TT => {
1517 // being either a single token or a delimited sequence, tt is
1521 NonterminalKind::Vis => {
1522 // Explicitly disallow `priv`, on the off chance it comes back.
1523 const TOKENS: &[&str] = &["`,`", "an ident", "a type"];
1525 TokenTree::Token(token) => match token.kind {
1526 Comma => IsInFollow::Yes,
1527 Ident(name, is_raw) if is_raw || name != kw::Priv => IsInFollow::Yes,
1529 if token.can_begin_type() {
1532 IsInFollow::No(TOKENS)
1536 TokenTree::MetaVarDecl(
1539 Some(NonterminalKind::Ident | NonterminalKind::Ty | NonterminalKind::Path),
1540 ) => IsInFollow::Yes,
1541 _ => IsInFollow::No(TOKENS),
1548 fn quoted_tt_to_string(tt: &mbe::TokenTree) -> String {
1550 mbe::TokenTree::Token(ref token) => pprust::token_to_string(&token).into(),
1551 mbe::TokenTree::MetaVar(_, name) => format!("${}", name),
1552 mbe::TokenTree::MetaVarDecl(_, name, Some(kind)) => format!("${}:{}", name, kind),
1553 mbe::TokenTree::MetaVarDecl(_, name, None) => format!("${}:", name),
1556 "unexpected mbe::TokenTree::{Sequence or Delimited} \
1557 in follow set checker"
1562 fn parser_from_cx(sess: &ParseSess, tts: TokenStream) -> Parser<'_> {
1563 Parser::new(sess, tts, true, rustc_parse::MACRO_ARGUMENTS)
1566 /// Generates an appropriate parsing failure message. For EOF, this is "unexpected end...". For
1567 /// other tokens, this is "unexpected token...".
1568 fn parse_failure_msg(tok: &Token) -> String {
1570 token::Eof => "unexpected end of macro invocation".to_string(),
1571 _ => format!("no rules expected the token `{}`", pprust::token_to_string(tok),),