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