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