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