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::parse_tt;
7 use crate::mbe::macro_parser::{Error, ErrorReported, Failure, Success};
8 use crate::mbe::macro_parser::{MatchedNonterminal, MatchedSeq};
9 use crate::mbe::transcribe::transcribe;
12 use rustc_ast::token::{self, NonterminalKind, NtTT, Token, TokenKind::*};
13 use rustc_ast::tokenstream::{DelimSpan, TokenStream};
14 use rustc_ast::{NodeId, DUMMY_NODE_ID};
15 use rustc_ast_pretty::pprust;
16 use rustc_attr::{self as attr, TransparencyError};
17 use rustc_data_structures::fx::FxHashMap;
18 use rustc_data_structures::sync::Lrc;
19 use rustc_errors::{Applicability, DiagnosticBuilder};
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::symbol::{kw, sym, Ident, MacroRulesNormalizedIdent};
34 use std::collections::hash_map::Entry;
35 use std::{mem, slice};
38 crate struct ParserAnyMacro<'a> {
41 /// Span of the expansion site of the macro this parser is for
43 /// The ident of the macro we're parsing
46 is_trailing_mac: bool,
48 /// Whether or not this macro is defined in the current crate
52 crate fn annotate_err_with_kind(
53 err: &mut DiagnosticBuilder<'_>,
54 kind: AstFragmentKind,
58 AstFragmentKind::Ty => {
59 err.span_label(span, "this macro call doesn't expand to a type");
61 AstFragmentKind::Pat => {
62 err.span_label(span, "this macro call doesn't expand to a pattern");
68 fn emit_frag_parse_err(
69 mut e: DiagnosticBuilder<'_>,
71 orig_parser: &mut Parser<'_>,
74 kind: AstFragmentKind,
76 if parser.token == token::Eof && e.message().ends_with(", found `<eof>`") {
77 if !e.span.is_dummy() {
78 // early end of macro arm (#52866)
79 e.replace_span_with(parser.sess.source_map().next_point(parser.token.span));
81 let msg = &e.message[0];
84 "macro expansion ends with an incomplete expression: {}",
85 msg.0.replace(", found `<eof>`", ""),
90 if e.span.is_dummy() {
91 // Get around lack of span in error (#30128)
92 e.replace_span_with(site_span);
93 if !parser.sess.source_map().is_imported(arm_span) {
94 e.span_label(arm_span, "in this macro arm");
96 } else if parser.sess.source_map().is_imported(parser.token.span) {
97 e.span_label(site_span, "in this macro invocation");
100 // Try a statement if an expression is wanted but failed and suggest adding `;` to call.
101 AstFragmentKind::Expr => match parse_ast_fragment(orig_parser, AstFragmentKind::Stmts) {
102 Err(mut err) => err.cancel(),
105 "the macro call doesn't expand to an expression, but it can expand to a statement",
107 e.span_suggestion_verbose(
108 site_span.shrink_to_hi(),
109 "add `;` to interpret the expansion as a statement",
111 Applicability::MaybeIncorrect,
115 _ => annotate_err_with_kind(&mut e, kind, site_span),
120 impl<'a> ParserAnyMacro<'a> {
121 crate fn make(mut self: Box<ParserAnyMacro<'a>>, kind: AstFragmentKind) -> AstFragment {
131 let snapshot = &mut parser.clone();
132 let fragment = match parse_ast_fragment(parser, kind) {
135 emit_frag_parse_err(err, parser, snapshot, site_span, arm_span, kind);
136 return kind.dummy(site_span);
140 // We allow semicolons at the end of expressions -- e.g., the semicolon in
141 // `macro_rules! m { () => { panic!(); } }` isn't parsed by `.parse_expr()`,
142 // but `m!()` is allowed in expression positions (cf. issue #34706).
143 if kind == AstFragmentKind::Expr && parser.token == token::Semi {
145 parser.sess.buffer_lint_with_diagnostic(
146 SEMICOLON_IN_EXPRESSIONS_FROM_MACROS,
149 "trailing semicolon in macro used in expression position",
150 BuiltinLintDiagnostics::TrailingMacro(is_trailing_mac, macro_ident),
156 // Make sure we don't have any tokens left to parse so we don't silently drop anything.
157 let path = ast::Path::from_ident(macro_ident.with_span_pos(site_span));
158 ensure_complete_parse(parser, &path, kind.name(), site_span);
163 struct MacroRulesMacroExpander {
166 transparency: Transparency,
167 lhses: Vec<mbe::TokenTree>,
168 rhses: Vec<mbe::TokenTree>,
173 impl TTMacroExpander for MacroRulesMacroExpander {
176 cx: &'cx mut ExtCtxt<'_>,
179 ) -> Box<dyn MacResult + 'cx> {
181 return DummyResult::any(sp);
197 fn macro_rules_dummy_expander<'cx>(
198 _: &'cx mut ExtCtxt<'_>,
201 ) -> Box<dyn MacResult + 'cx> {
202 DummyResult::any(span)
205 fn trace_macros_note(cx_expansions: &mut FxHashMap<Span, Vec<String>>, sp: Span, message: String) {
206 let sp = sp.macro_backtrace().last().map_or(sp, |trace| trace.call_site);
207 cx_expansions.entry(sp).or_default().push(message);
210 /// Given `lhses` and `rhses`, this is the new macro we create
211 fn generic_extension<'cx>(
212 cx: &'cx mut ExtCtxt<'_>,
216 transparency: Transparency,
218 lhses: &[mbe::TokenTree],
219 rhses: &[mbe::TokenTree],
221 ) -> Box<dyn MacResult + 'cx> {
222 let sess = &cx.sess.parse_sess;
224 if cx.trace_macros() {
225 let msg = format!("expanding `{}! {{ {} }}`", name, pprust::tts_to_string(&arg));
226 trace_macros_note(&mut cx.expansions, sp, msg);
229 // Which arm's failure should we report? (the one furthest along)
230 let mut best_failure: Option<(Token, &str)> = None;
232 // We create a base parser that can be used for the "black box" parts.
233 // Every iteration needs a fresh copy of that parser. However, the parser
234 // is not mutated on many of the iterations, particularly when dealing with
237 // macro_rules! foo {
241 // // ... etc. (maybe hundreds more)
244 // as seen in the `html5ever` benchmark. We use a `Cow` so that the base
245 // parser is only cloned when necessary (upon mutation). Furthermore, we
246 // reinitialize the `Cow` with the base parser at the start of every
247 // iteration, so that any mutated parsers are not reused. This is all quite
248 // hacky, but speeds up the `html5ever` benchmark significantly. (Issue
249 // 68836 suggests a more comprehensive but more complex change to deal with
251 let parser = parser_from_cx(sess, arg.clone());
253 for (i, lhs) in lhses.iter().enumerate() {
254 // try each arm's matchers
255 let lhs_tt = match *lhs {
256 mbe::TokenTree::Delimited(_, ref delim) => &delim.tts[..],
257 _ => cx.span_bug(sp, "malformed macro lhs"),
260 // Take a snapshot of the state of pre-expansion gating at this point.
261 // This is used so that if a matcher is not `Success(..)`ful,
262 // then the spans which became gated when parsing the unsuccessful matcher
263 // are not recorded. On the first `Success(..)`ful matcher, the spans are merged.
264 let mut gated_spans_snapshot = mem::take(&mut *sess.gated_spans.spans.borrow_mut());
266 match parse_tt(&mut Cow::Borrowed(&parser), lhs_tt, name) {
267 Success(named_matches) => {
268 // The matcher was `Success(..)`ful.
269 // Merge the gated spans from parsing the matcher with the pre-existing ones.
270 sess.gated_spans.merge(gated_spans_snapshot);
272 let rhs = match rhses[i] {
274 mbe::TokenTree::Delimited(_, ref delimed) => delimed.tts.clone(),
275 _ => cx.span_bug(sp, "malformed macro rhs"),
277 let arm_span = rhses[i].span();
279 let rhs_spans = rhs.iter().map(|t| t.span()).collect::<Vec<_>>();
280 // rhs has holes ( `$id` and `$(...)` that need filled)
281 let mut tts = match transcribe(cx, &named_matches, rhs, transparency) {
285 return DummyResult::any(arm_span);
289 // Replace all the tokens for the corresponding positions in the macro, to maintain
290 // proper positions in error reporting, while maintaining the macro_backtrace.
291 if rhs_spans.len() == tts.len() {
292 tts = tts.map_enumerated(|i, tt| {
293 let mut tt = tt.clone();
294 let mut sp = rhs_spans[i];
295 sp = sp.with_ctxt(tt.span().ctxt());
301 if cx.trace_macros() {
302 let msg = format!("to `{}`", pprust::tts_to_string(&tts));
303 trace_macros_note(&mut cx.expansions, sp, msg);
306 let mut p = Parser::new(sess, tts, false, None);
307 p.last_type_ascription = cx.current_expansion.prior_type_ascription;
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 Failure(token, msg) => match best_failure {
326 Some((ref best_token, _)) if best_token.span.lo() >= token.span.lo() => {}
327 _ => best_failure = Some((token, msg)),
329 Error(err_sp, ref msg) => {
330 let span = err_sp.substitute_dummy(sp);
331 cx.struct_span_err(span, &msg).emit();
332 return DummyResult::any(span);
334 ErrorReported => return DummyResult::any(sp),
337 // The matcher was not `Success(..)`ful.
338 // Restore to the state before snapshotting and maybe try again.
339 mem::swap(&mut gated_spans_snapshot, &mut sess.gated_spans.spans.borrow_mut());
343 let (token, label) = best_failure.expect("ran no matchers");
344 let span = token.span.substitute_dummy(sp);
345 let mut err = cx.struct_span_err(span, &parse_failure_msg(&token));
346 err.span_label(span, label);
347 if !def_span.is_dummy() && !cx.source_map().is_imported(def_span) {
348 err.span_label(cx.source_map().guess_head_span(def_span), "when calling this macro");
351 // Check whether there's a missing comma in this macro call, like `println!("{}" a);`
352 if let Some((arg, comma_span)) = arg.add_comma() {
354 // try each arm's matchers
355 let lhs_tt = match *lhs {
356 mbe::TokenTree::Delimited(_, ref delim) => &delim.tts[..],
360 parse_tt(&mut Cow::Borrowed(&parser_from_cx(sess, arg.clone())), lhs_tt, name)
362 if comma_span.is_dummy() {
363 err.note("you might be missing a comma");
365 err.span_suggestion_short(
367 "missing comma here",
369 Applicability::MachineApplicable,
376 cx.trace_macros_diag();
380 // Note that macro-by-example's input is also matched against a token tree:
381 // $( $lhs:tt => $rhs:tt );+
383 // Holy self-referential!
385 /// Converts a macro item into a syntax extension.
386 pub fn compile_declarative_macro(
391 ) -> SyntaxExtension {
392 debug!("compile_declarative_macro: {:?}", def);
393 let mk_syn_ext = |expander| {
394 SyntaxExtension::new(
396 SyntaxExtensionKind::LegacyBang(expander),
405 let diag = &sess.parse_sess.span_diagnostic;
406 let lhs_nm = Ident::new(sym::lhs, def.span);
407 let rhs_nm = Ident::new(sym::rhs, def.span);
408 let tt_spec = Some(NonterminalKind::TT);
410 // Parse the macro_rules! invocation
411 let (macro_rules, body) = match &def.kind {
412 ast::ItemKind::MacroDef(def) => (def.macro_rules, def.body.inner_tokens()),
416 // The pattern that macro_rules matches.
417 // The grammar for macro_rules! is:
418 // $( $lhs:tt => $rhs:tt );+
419 // ...quasiquoting this would be nice.
420 // These spans won't matter, anyways
421 let argument_gram = vec![
422 mbe::TokenTree::Sequence(
424 Lrc::new(mbe::SequenceRepetition {
426 mbe::TokenTree::MetaVarDecl(def.span, lhs_nm, tt_spec),
427 mbe::TokenTree::token(token::FatArrow, def.span),
428 mbe::TokenTree::MetaVarDecl(def.span, rhs_nm, tt_spec),
430 separator: Some(Token::new(
431 if macro_rules { token::Semi } else { token::Comma },
434 kleene: mbe::KleeneToken::new(mbe::KleeneOp::OneOrMore, def.span),
438 // to phase into semicolon-termination instead of semicolon-separation
439 mbe::TokenTree::Sequence(
441 Lrc::new(mbe::SequenceRepetition {
442 tts: vec![mbe::TokenTree::token(
443 if macro_rules { token::Semi } else { token::Comma },
447 kleene: mbe::KleeneToken::new(mbe::KleeneOp::ZeroOrMore, def.span),
453 let parser = Parser::new(&sess.parse_sess, body, true, rustc_parse::MACRO_ARGUMENTS);
454 let argument_map = match parse_tt(&mut Cow::Borrowed(&parser), &argument_gram, def.ident) {
456 Failure(token, msg) => {
457 let s = parse_failure_msg(&token);
458 let sp = token.span.substitute_dummy(def.span);
459 sess.parse_sess.span_diagnostic.struct_span_err(sp, &s).span_label(sp, msg).emit();
460 return mk_syn_ext(Box::new(macro_rules_dummy_expander));
465 .struct_span_err(sp.substitute_dummy(def.span), &msg)
467 return mk_syn_ext(Box::new(macro_rules_dummy_expander));
470 return mk_syn_ext(Box::new(macro_rules_dummy_expander));
474 let mut valid = true;
476 // Extract the arguments:
477 let lhses = match argument_map[&MacroRulesNormalizedIdent::new(lhs_nm)] {
478 MatchedSeq(ref s) => s
481 if let MatchedNonterminal(ref nt) = *m {
482 if let NtTT(ref tt) = **nt {
483 let tt = mbe::quoted::parse(
493 valid &= check_lhs_nt_follows(&sess.parse_sess, features, &def, &tt);
497 sess.parse_sess.span_diagnostic.span_bug(def.span, "wrong-structured lhs")
499 .collect::<Vec<mbe::TokenTree>>(),
500 _ => sess.parse_sess.span_diagnostic.span_bug(def.span, "wrong-structured lhs"),
503 let rhses = match argument_map[&MacroRulesNormalizedIdent::new(rhs_nm)] {
504 MatchedSeq(ref s) => s
507 if let MatchedNonterminal(ref nt) = *m {
508 if let NtTT(ref tt) = **nt {
509 return mbe::quoted::parse(
521 sess.parse_sess.span_diagnostic.span_bug(def.span, "wrong-structured lhs")
523 .collect::<Vec<mbe::TokenTree>>(),
524 _ => sess.parse_sess.span_diagnostic.span_bug(def.span, "wrong-structured rhs"),
528 valid &= check_rhs(&sess.parse_sess, rhs);
531 // don't abort iteration early, so that errors for multiple lhses can be reported
533 valid &= check_lhs_no_empty_seq(&sess.parse_sess, slice::from_ref(lhs));
536 valid &= macro_check::check_meta_variables(&sess.parse_sess, def.id, def.span, &lhses, &rhses);
538 let (transparency, transparency_error) = attr::find_transparency(sess, &def.attrs, macro_rules);
539 match transparency_error {
540 Some(TransparencyError::UnknownTransparency(value, span)) => {
541 diag.span_err(span, &format!("unknown macro transparency: `{}`", value))
543 Some(TransparencyError::MultipleTransparencyAttrs(old_span, new_span)) => {
544 diag.span_err(vec![old_span, new_span], "multiple macro transparency attributes")
549 mk_syn_ext(Box::new(MacroRulesMacroExpander {
556 // Macros defined in the current crate have a real node id,
557 // whereas macros from an external crate have a dummy id.
558 is_local: def.id != DUMMY_NODE_ID,
562 fn check_lhs_nt_follows(
566 lhs: &mbe::TokenTree,
568 // lhs is going to be like TokenTree::Delimited(...), where the
569 // entire lhs is those tts. Or, it can be a "bare sequence", not wrapped in parens.
570 if let mbe::TokenTree::Delimited(_, ref tts) = *lhs {
571 check_matcher(sess, features, def, &tts.tts)
573 let msg = "invalid macro matcher; matchers must be contained in balanced delimiters";
574 sess.span_diagnostic.span_err(lhs.span(), msg);
577 // we don't abort on errors on rejection, the driver will do that for us
578 // after parsing/expansion. we can report every error in every macro this way.
581 /// Checks that the lhs contains no repetition which could match an empty token
582 /// tree, because then the matcher would hang indefinitely.
583 fn check_lhs_no_empty_seq(sess: &ParseSess, tts: &[mbe::TokenTree]) -> bool {
587 TokenTree::Token(..) | TokenTree::MetaVar(..) | TokenTree::MetaVarDecl(..) => (),
588 TokenTree::Delimited(_, ref del) => {
589 if !check_lhs_no_empty_seq(sess, &del.tts) {
593 TokenTree::Sequence(span, ref seq) => {
594 if seq.separator.is_none()
595 && seq.tts.iter().all(|seq_tt| match *seq_tt {
596 TokenTree::MetaVarDecl(_, _, Some(NonterminalKind::Vis)) => true,
597 TokenTree::Sequence(_, ref sub_seq) => {
598 sub_seq.kleene.op == mbe::KleeneOp::ZeroOrMore
599 || sub_seq.kleene.op == mbe::KleeneOp::ZeroOrOne
604 let sp = span.entire();
605 sess.span_diagnostic.span_err(sp, "repetition matches empty token tree");
608 if !check_lhs_no_empty_seq(sess, &seq.tts) {
618 fn check_rhs(sess: &ParseSess, rhs: &mbe::TokenTree) -> bool {
620 mbe::TokenTree::Delimited(..) => return true,
621 _ => sess.span_diagnostic.span_err(rhs.span(), "macro rhs must be delimited"),
630 matcher: &[mbe::TokenTree],
632 let first_sets = FirstSets::new(matcher);
633 let empty_suffix = TokenSet::empty();
634 let err = sess.span_diagnostic.err_count();
635 check_matcher_core(sess, features, def, &first_sets, matcher, &empty_suffix);
636 err == sess.span_diagnostic.err_count()
639 // `The FirstSets` for a matcher is a mapping from subsequences in the
640 // matcher to the FIRST set for that subsequence.
642 // This mapping is partially precomputed via a backwards scan over the
643 // token trees of the matcher, which provides a mapping from each
644 // repetition sequence to its *first* set.
646 // (Hypothetically, sequences should be uniquely identifiable via their
647 // spans, though perhaps that is false, e.g., for macro-generated macros
648 // that do not try to inject artificial span information. My plan is
649 // to try to catch such cases ahead of time and not include them in
650 // the precomputed mapping.)
652 // this maps each TokenTree::Sequence `$(tt ...) SEP OP` that is uniquely identified by its
653 // span in the original matcher to the First set for the inner sequence `tt ...`.
655 // If two sequences have the same span in a matcher, then map that
656 // span to None (invalidating the mapping here and forcing the code to
658 first: FxHashMap<Span, Option<TokenSet>>,
662 fn new(tts: &[mbe::TokenTree]) -> FirstSets {
665 let mut sets = FirstSets { first: FxHashMap::default() };
666 build_recur(&mut sets, tts);
669 // walks backward over `tts`, returning the FIRST for `tts`
670 // and updating `sets` at the same time for all sequence
671 // substructure we find within `tts`.
672 fn build_recur(sets: &mut FirstSets, tts: &[TokenTree]) -> TokenSet {
673 let mut first = TokenSet::empty();
674 for tt in tts.iter().rev() {
676 TokenTree::Token(..) | TokenTree::MetaVar(..) | TokenTree::MetaVarDecl(..) => {
677 first.replace_with(tt.clone());
679 TokenTree::Delimited(span, ref delimited) => {
680 build_recur(sets, &delimited.tts[..]);
681 first.replace_with(delimited.open_tt(span));
683 TokenTree::Sequence(sp, ref seq_rep) => {
684 let subfirst = build_recur(sets, &seq_rep.tts[..]);
686 match sets.first.entry(sp.entire()) {
687 Entry::Vacant(vac) => {
688 vac.insert(Some(subfirst.clone()));
690 Entry::Occupied(mut occ) => {
691 // if there is already an entry, then a span must have collided.
692 // This should not happen with typical macro_rules macros,
693 // but syntax extensions need not maintain distinct spans,
694 // so distinct syntax trees can be assigned the same span.
695 // In such a case, the map cannot be trusted; so mark this
696 // entry as unusable.
701 // If the sequence contents can be empty, then the first
702 // token could be the separator token itself.
704 if let (Some(sep), true) = (&seq_rep.separator, subfirst.maybe_empty) {
705 first.add_one_maybe(TokenTree::Token(sep.clone()));
708 // Reverse scan: Sequence comes before `first`.
709 if subfirst.maybe_empty
710 || seq_rep.kleene.op == mbe::KleeneOp::ZeroOrMore
711 || seq_rep.kleene.op == mbe::KleeneOp::ZeroOrOne
713 // If sequence is potentially empty, then
714 // union them (preserving first emptiness).
715 first.add_all(&TokenSet { maybe_empty: true, ..subfirst });
717 // Otherwise, sequence guaranteed
718 // non-empty; replace first.
729 // walks forward over `tts` until all potential FIRST tokens are
731 fn first(&self, tts: &[mbe::TokenTree]) -> TokenSet {
734 let mut first = TokenSet::empty();
735 for tt in tts.iter() {
736 assert!(first.maybe_empty);
738 TokenTree::Token(..) | TokenTree::MetaVar(..) | TokenTree::MetaVarDecl(..) => {
739 first.add_one(tt.clone());
742 TokenTree::Delimited(span, ref delimited) => {
743 first.add_one(delimited.open_tt(span));
746 TokenTree::Sequence(sp, ref seq_rep) => {
748 let subfirst = match self.first.get(&sp.entire()) {
749 Some(&Some(ref subfirst)) => subfirst,
751 subfirst_owned = self.first(&seq_rep.tts[..]);
755 panic!("We missed a sequence during FirstSets construction");
759 // If the sequence contents can be empty, then the first
760 // token could be the separator token itself.
761 if let (Some(sep), true) = (&seq_rep.separator, subfirst.maybe_empty) {
762 first.add_one_maybe(TokenTree::Token(sep.clone()));
765 assert!(first.maybe_empty);
766 first.add_all(subfirst);
767 if subfirst.maybe_empty
768 || seq_rep.kleene.op == mbe::KleeneOp::ZeroOrMore
769 || seq_rep.kleene.op == mbe::KleeneOp::ZeroOrOne
771 // Continue scanning for more first
772 // tokens, but also make sure we
773 // restore empty-tracking state.
774 first.maybe_empty = true;
783 // we only exit the loop if `tts` was empty or if every
784 // element of `tts` matches the empty sequence.
785 assert!(first.maybe_empty);
790 // A set of `mbe::TokenTree`s, which may include `TokenTree::Match`s
791 // (for macro-by-example syntactic variables). It also carries the
792 // `maybe_empty` flag; that is true if and only if the matcher can
793 // match an empty token sequence.
795 // The First set is computed on submatchers like `$($a:expr b),* $(c)* d`,
796 // which has corresponding FIRST = {$a:expr, c, d}.
797 // Likewise, `$($a:expr b),* $(c)+ d` has FIRST = {$a:expr, c}.
799 // (Notably, we must allow for *-op to occur zero times.)
800 #[derive(Clone, Debug)]
802 tokens: Vec<mbe::TokenTree>,
807 // Returns a set for the empty sequence.
809 TokenSet { tokens: Vec::new(), maybe_empty: true }
812 // Returns the set `{ tok }` for the single-token (and thus
813 // non-empty) sequence [tok].
814 fn singleton(tok: mbe::TokenTree) -> Self {
815 TokenSet { tokens: vec![tok], maybe_empty: false }
818 // Changes self to be the set `{ tok }`.
819 // Since `tok` is always present, marks self as non-empty.
820 fn replace_with(&mut self, tok: mbe::TokenTree) {
822 self.tokens.push(tok);
823 self.maybe_empty = false;
826 // Changes self to be the empty set `{}`; meant for use when
827 // the particular token does not matter, but we want to
828 // record that it occurs.
829 fn replace_with_irrelevant(&mut self) {
831 self.maybe_empty = false;
834 // Adds `tok` to the set for `self`, marking sequence as non-empy.
835 fn add_one(&mut self, tok: mbe::TokenTree) {
836 if !self.tokens.contains(&tok) {
837 self.tokens.push(tok);
839 self.maybe_empty = false;
842 // Adds `tok` to the set for `self`. (Leaves `maybe_empty` flag alone.)
843 fn add_one_maybe(&mut self, tok: mbe::TokenTree) {
844 if !self.tokens.contains(&tok) {
845 self.tokens.push(tok);
849 // Adds all elements of `other` to this.
851 // (Since this is a set, we filter out duplicates.)
853 // If `other` is potentially empty, then preserves the previous
854 // setting of the empty flag of `self`. If `other` is guaranteed
855 // non-empty, then `self` is marked non-empty.
856 fn add_all(&mut self, other: &Self) {
857 for tok in &other.tokens {
858 if !self.tokens.contains(tok) {
859 self.tokens.push(tok.clone());
862 if !other.maybe_empty {
863 self.maybe_empty = false;
868 // Checks that `matcher` is internally consistent and that it
869 // can legally be followed by a token `N`, for all `N` in `follow`.
870 // (If `follow` is empty, then it imposes no constraint on
873 // Returns the set of NT tokens that could possibly come last in
874 // `matcher`. (If `matcher` matches the empty sequence, then
875 // `maybe_empty` will be set to true.)
877 // Requires that `first_sets` is pre-computed for `matcher`;
878 // see `FirstSets::new`.
879 fn check_matcher_core(
883 first_sets: &FirstSets,
884 matcher: &[mbe::TokenTree],
889 let mut last = TokenSet::empty();
891 // 2. For each token and suffix [T, SUFFIX] in M:
892 // ensure that T can be followed by SUFFIX, and if SUFFIX may be empty,
893 // then ensure T can also be followed by any element of FOLLOW.
894 'each_token: for i in 0..matcher.len() {
895 let token = &matcher[i];
896 let suffix = &matcher[i + 1..];
898 let build_suffix_first = || {
899 let mut s = first_sets.first(suffix);
906 // (we build `suffix_first` on demand below; you can tell
907 // which cases are supposed to fall through by looking for the
908 // initialization of this variable.)
911 // First, update `last` so that it corresponds to the set
912 // of NT tokens that might end the sequence `... token`.
914 TokenTree::Token(..) | TokenTree::MetaVar(..) | TokenTree::MetaVarDecl(..) => {
915 if token_can_be_followed_by_any(token) {
916 // don't need to track tokens that work with any,
917 last.replace_with_irrelevant();
918 // ... and don't need to check tokens that can be
919 // followed by anything against SUFFIX.
920 continue 'each_token;
922 last.replace_with(token.clone());
923 suffix_first = build_suffix_first();
926 TokenTree::Delimited(span, ref d) => {
927 let my_suffix = TokenSet::singleton(d.close_tt(span));
928 check_matcher_core(sess, features, def, first_sets, &d.tts, &my_suffix);
929 // don't track non NT tokens
930 last.replace_with_irrelevant();
932 // also, we don't need to check delimited sequences
934 continue 'each_token;
936 TokenTree::Sequence(_, ref seq_rep) => {
937 suffix_first = build_suffix_first();
938 // The trick here: when we check the interior, we want
939 // to include the separator (if any) as a potential
940 // (but not guaranteed) element of FOLLOW. So in that
941 // case, we make a temp copy of suffix and stuff
942 // delimiter in there.
944 // FIXME: Should I first scan suffix_first to see if
945 // delimiter is already in it before I go through the
946 // work of cloning it? But then again, this way I may
947 // get a "tighter" span?
949 let my_suffix = if let Some(sep) = &seq_rep.separator {
950 new = suffix_first.clone();
951 new.add_one_maybe(TokenTree::Token(sep.clone()));
957 // At this point, `suffix_first` is built, and
958 // `my_suffix` is some TokenSet that we can use
959 // for checking the interior of `seq_rep`.
961 check_matcher_core(sess, features, def, first_sets, &seq_rep.tts, my_suffix);
962 if next.maybe_empty {
968 // the recursive call to check_matcher_core already ran the 'each_last
969 // check below, so we can just keep going forward here.
970 continue 'each_token;
974 // (`suffix_first` guaranteed initialized once reaching here.)
976 // Now `last` holds the complete set of NT tokens that could
977 // end the sequence before SUFFIX. Check that every one works with `suffix`.
978 for token in &last.tokens {
979 if let TokenTree::MetaVarDecl(span, name, Some(kind)) = *token {
980 for next_token in &suffix_first.tokens {
981 // Check if the old pat is used and the next token is `|`
982 // to warn about incompatibility with Rust 2021.
983 // We only emit this lint if we're parsing the original
984 // definition of this macro_rules, not while (re)parsing
985 // the macro when compiling another crate that is using the
986 // macro. (See #86567.)
987 // Macros defined in the current crate have a real node id,
988 // whereas macros from an external crate have a dummy id.
989 if def.id != DUMMY_NODE_ID
990 && matches!(kind, NonterminalKind::PatParam { inferred: true })
991 && matches!(next_token, TokenTree::Token(token) if token.kind == BinOp(token::BinOpToken::Or))
993 // It is suggestion to use pat_param, for example: $x:pat -> $x:pat_param.
994 let suggestion = quoted_tt_to_string(&TokenTree::MetaVarDecl(
997 Some(NonterminalKind::PatParam { inferred: false }),
999 sess.buffer_lint_with_diagnostic(
1000 &RUST_2021_INCOMPATIBLE_OR_PATTERNS,
1003 "the meaning of the `pat` fragment specifier is changing in Rust 2021, which may affect this macro",
1004 BuiltinLintDiagnostics::OrPatternsBackCompat(span, suggestion),
1007 match is_in_follow(next_token, kind) {
1008 IsInFollow::Yes => {}
1009 IsInFollow::No(possible) => {
1010 let may_be = if last.tokens.len() == 1 && suffix_first.tokens.len() == 1
1017 let sp = next_token.span();
1018 let mut err = sess.span_diagnostic.struct_span_err(
1021 "`${name}:{frag}` {may_be} followed by `{next}`, which \
1022 is not allowed for `{frag}` fragments",
1025 next = quoted_tt_to_string(next_token),
1029 err.span_label(sp, format!("not allowed after `{}` fragments", kind));
1030 let msg = "allowed there are: ";
1035 "only {} is allowed after `{}` fragments",
1046 .collect::<Vec<_>>()
1062 fn token_can_be_followed_by_any(tok: &mbe::TokenTree) -> bool {
1063 if let mbe::TokenTree::MetaVarDecl(_, _, Some(kind)) = *tok {
1064 frag_can_be_followed_by_any(kind)
1066 // (Non NT's can always be followed by anything in matchers.)
1071 /// Returns `true` if a fragment of type `frag` can be followed by any sort of
1072 /// token. We use this (among other things) as a useful approximation
1073 /// for when `frag` can be followed by a repetition like `$(...)*` or
1074 /// `$(...)+`. In general, these can be a bit tricky to reason about,
1075 /// so we adopt a conservative position that says that any fragment
1076 /// specifier which consumes at most one token tree can be followed by
1077 /// a fragment specifier (indeed, these fragments can be followed by
1078 /// ANYTHING without fear of future compatibility hazards).
1079 fn frag_can_be_followed_by_any(kind: NonterminalKind) -> bool {
1082 NonterminalKind::Item // always terminated by `}` or `;`
1083 | NonterminalKind::Block // exactly one token tree
1084 | NonterminalKind::Ident // exactly one token tree
1085 | NonterminalKind::Literal // exactly one token tree
1086 | NonterminalKind::Meta // exactly one token tree
1087 | NonterminalKind::Lifetime // exactly one token tree
1088 | NonterminalKind::TT // exactly one token tree
1094 No(&'static [&'static str]),
1097 /// Returns `true` if `frag` can legally be followed by the token `tok`. For
1098 /// fragments that can consume an unbounded number of tokens, `tok`
1099 /// must be within a well-defined follow set. This is intended to
1100 /// guarantee future compatibility: for example, without this rule, if
1101 /// we expanded `expr` to include a new binary operator, we might
1102 /// break macros that were relying on that binary operator as a
1104 // when changing this do not forget to update doc/book/macros.md!
1105 fn is_in_follow(tok: &mbe::TokenTree, kind: NonterminalKind) -> IsInFollow {
1108 if let TokenTree::Token(Token { kind: token::CloseDelim(_), .. }) = *tok {
1109 // closing a token tree can never be matched by any fragment;
1110 // iow, we always require that `(` and `)` match, etc.
1114 NonterminalKind::Item => {
1115 // since items *must* be followed by either a `;` or a `}`, we can
1116 // accept anything after them
1119 NonterminalKind::Block => {
1120 // anything can follow block, the braces provide an easy boundary to
1124 NonterminalKind::Stmt | NonterminalKind::Expr => {
1125 const TOKENS: &[&str] = &["`=>`", "`,`", "`;`"];
1127 TokenTree::Token(token) => match token.kind {
1128 FatArrow | Comma | Semi => IsInFollow::Yes,
1129 _ => IsInFollow::No(TOKENS),
1131 _ => IsInFollow::No(TOKENS),
1134 NonterminalKind::PatParam { .. } => {
1135 const TOKENS: &[&str] = &["`=>`", "`,`", "`=`", "`|`", "`if`", "`in`"];
1137 TokenTree::Token(token) => match token.kind {
1138 FatArrow | Comma | Eq | BinOp(token::Or) => IsInFollow::Yes,
1139 Ident(name, false) if name == kw::If || name == kw::In => IsInFollow::Yes,
1140 _ => IsInFollow::No(TOKENS),
1142 _ => IsInFollow::No(TOKENS),
1145 NonterminalKind::PatWithOr { .. } => {
1146 const TOKENS: &[&str] = &["`=>`", "`,`", "`=`", "`if`", "`in`"];
1148 TokenTree::Token(token) => match token.kind {
1149 FatArrow | Comma | Eq => IsInFollow::Yes,
1150 Ident(name, false) if name == kw::If || name == kw::In => IsInFollow::Yes,
1151 _ => IsInFollow::No(TOKENS),
1153 _ => IsInFollow::No(TOKENS),
1156 NonterminalKind::Path | NonterminalKind::Ty => {
1157 const TOKENS: &[&str] = &[
1158 "`{`", "`[`", "`=>`", "`,`", "`>`", "`=`", "`:`", "`;`", "`|`", "`as`",
1162 TokenTree::Token(token) => match token.kind {
1163 OpenDelim(token::DelimToken::Brace)
1164 | OpenDelim(token::DelimToken::Bracket)
1172 | BinOp(token::Or) => IsInFollow::Yes,
1173 Ident(name, false) if name == kw::As || name == kw::Where => {
1176 _ => IsInFollow::No(TOKENS),
1178 TokenTree::MetaVarDecl(_, _, Some(NonterminalKind::Block)) => IsInFollow::Yes,
1179 _ => IsInFollow::No(TOKENS),
1182 NonterminalKind::Ident | NonterminalKind::Lifetime => {
1183 // being a single token, idents and lifetimes are harmless
1186 NonterminalKind::Literal => {
1187 // literals may be of a single token, or two tokens (negative numbers)
1190 NonterminalKind::Meta | NonterminalKind::TT => {
1191 // being either a single token or a delimited sequence, tt is
1195 NonterminalKind::Vis => {
1196 // Explicitly disallow `priv`, on the off chance it comes back.
1197 const TOKENS: &[&str] = &["`,`", "an ident", "a type"];
1199 TokenTree::Token(token) => match token.kind {
1200 Comma => IsInFollow::Yes,
1201 Ident(name, is_raw) if is_raw || name != kw::Priv => IsInFollow::Yes,
1203 if token.can_begin_type() {
1206 IsInFollow::No(TOKENS)
1210 TokenTree::MetaVarDecl(
1213 Some(NonterminalKind::Ident | NonterminalKind::Ty | NonterminalKind::Path),
1214 ) => IsInFollow::Yes,
1215 _ => IsInFollow::No(TOKENS),
1222 fn quoted_tt_to_string(tt: &mbe::TokenTree) -> String {
1224 mbe::TokenTree::Token(ref token) => pprust::token_to_string(&token),
1225 mbe::TokenTree::MetaVar(_, name) => format!("${}", name),
1226 mbe::TokenTree::MetaVarDecl(_, name, Some(kind)) => format!("${}:{}", name, kind),
1227 mbe::TokenTree::MetaVarDecl(_, name, None) => format!("${}:", name),
1230 "unexpected mbe::TokenTree::{Sequence or Delimited} \
1231 in follow set checker"
1236 fn parser_from_cx(sess: &ParseSess, tts: TokenStream) -> Parser<'_> {
1237 Parser::new(sess, tts, true, rustc_parse::MACRO_ARGUMENTS)
1240 /// Generates an appropriate parsing failure message. For EOF, this is "unexpected end...". For
1241 /// other tokens, this is "unexpected token...".
1242 fn parse_failure_msg(tok: &Token) -> String {
1244 token::Eof => "unexpected end of macro invocation".to_string(),
1245 _ => format!("no rules expected the token `{}`", pprust::token_to_string(tok),),