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