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