1use std::borrow::Cow;
2use std::collections::hash_map::Entry;
3use std::sync::Arc;
4use std::{mem, slice};
5
6use ast::token::IdentIsRaw;
7use rustc_ast::token::NtPatKind::*;
8use rustc_ast::token::TokenKind::*;
9use rustc_ast::token::{self, NonterminalKind, Token, TokenKind};
10use rustc_ast::tokenstream::{DelimSpan, TokenStream};
11use rustc_ast::{self as ast, DUMMY_NODE_ID, NodeId};
12use rustc_ast_pretty::pprust;
13use rustc_data_structures::fx::{FxHashMap, FxIndexMap};
14use rustc_errors::{Applicability, Diag, ErrorGuaranteed};
15use rustc_feature::Features;
16use rustc_hir as hir;
17use rustc_hir::attrs::AttributeKind;
18use rustc_hir::find_attr;
19use rustc_lint_defs::BuiltinLintDiag;
20use rustc_lint_defs::builtin::{
21 RUST_2021_INCOMPATIBLE_OR_PATTERNS, SEMICOLON_IN_EXPRESSIONS_FROM_MACROS,
22};
23use rustc_parse::exp;
24use rustc_parse::parser::{Parser, Recovery};
25use rustc_session::Session;
26use rustc_session::parse::ParseSess;
27use rustc_span::edition::Edition;
28use rustc_span::hygiene::Transparency;
29use rustc_span::{Ident, Span, kw, sym};
30use tracing::{debug, instrument, trace, trace_span};
31
32use super::macro_parser::{NamedMatches, NamedParseResult};
33use super::{SequenceRepetition, diagnostics};
34use crate::base::{
35 DummyResult, ExpandResult, ExtCtxt, MacResult, MacroExpanderResult, SyntaxExtension,
36 SyntaxExtensionKind, TTMacroExpander,
37};
38use crate::expand::{AstFragment, AstFragmentKind, ensure_complete_parse, parse_ast_fragment};
39use crate::mbe::macro_parser::{Error, ErrorReported, Failure, MatcherLoc, Success, TtParser};
40use crate::mbe::quoted::{RulePart, parse_one_tt};
41use crate::mbe::transcribe::transcribe;
42use crate::mbe::{self, KleeneOp, macro_check};
43
44pub(crate) struct ParserAnyMacro<'a> {
45 parser: Parser<'a>,
46
47 site_span: Span,
49 macro_ident: Ident,
51 lint_node_id: NodeId,
52 is_trailing_mac: bool,
53 arm_span: Span,
54 is_local: bool,
56}
57
58impl<'a> ParserAnyMacro<'a> {
59 pub(crate) fn make(mut self: Box<ParserAnyMacro<'a>>, kind: AstFragmentKind) -> AstFragment {
60 let ParserAnyMacro {
61 site_span,
62 macro_ident,
63 ref mut parser,
64 lint_node_id,
65 arm_span,
66 is_trailing_mac,
67 is_local,
68 } = *self;
69 let snapshot = &mut parser.create_snapshot_for_diagnostic();
70 let fragment = match parse_ast_fragment(parser, kind) {
71 Ok(f) => f,
72 Err(err) => {
73 let guar = diagnostics::emit_frag_parse_err(
74 err, parser, snapshot, site_span, arm_span, kind,
75 );
76 return kind.dummy(site_span, guar);
77 }
78 };
79
80 if kind == AstFragmentKind::Expr && parser.token == token::Semi {
84 if is_local {
85 parser.psess.buffer_lint(
86 SEMICOLON_IN_EXPRESSIONS_FROM_MACROS,
87 parser.token.span,
88 lint_node_id,
89 BuiltinLintDiag::TrailingMacro(is_trailing_mac, macro_ident),
90 );
91 }
92 parser.bump();
93 }
94
95 let path = ast::Path::from_ident(macro_ident.with_span_pos(site_span));
97 ensure_complete_parse(parser, &path, kind.name(), site_span);
98 fragment
99 }
100
101 #[instrument(skip(cx, tts))]
102 pub(crate) fn from_tts<'cx>(
103 cx: &'cx mut ExtCtxt<'a>,
104 tts: TokenStream,
105 site_span: Span,
106 arm_span: Span,
107 is_local: bool,
108 macro_ident: Ident,
109 ) -> Self {
110 Self {
111 parser: Parser::new(&cx.sess.psess, tts, None),
112
113 site_span,
117 macro_ident,
118 lint_node_id: cx.current_expansion.lint_node_id,
119 is_trailing_mac: cx.current_expansion.is_trailing_mac,
120 arm_span,
121 is_local,
122 }
123 }
124}
125
126pub(super) struct MacroRule {
127 pub(super) lhs: Vec<MatcherLoc>,
128 lhs_span: Span,
129 rhs: mbe::TokenTree,
130}
131
132pub struct MacroRulesMacroExpander {
133 node_id: NodeId,
134 name: Ident,
135 span: Span,
136 transparency: Transparency,
137 rules: Vec<MacroRule>,
138}
139
140impl MacroRulesMacroExpander {
141 pub fn get_unused_rule(&self, rule_i: usize) -> Option<(&Ident, Span)> {
142 let rule = &self.rules[rule_i];
144 if has_compile_error_macro(&rule.rhs) { None } else { Some((&self.name, rule.lhs_span)) }
145 }
146}
147
148impl TTMacroExpander for MacroRulesMacroExpander {
149 fn expand<'cx>(
150 &self,
151 cx: &'cx mut ExtCtxt<'_>,
152 sp: Span,
153 input: TokenStream,
154 ) -> MacroExpanderResult<'cx> {
155 ExpandResult::Ready(expand_macro(
156 cx,
157 sp,
158 self.span,
159 self.node_id,
160 self.name,
161 self.transparency,
162 input,
163 &self.rules,
164 ))
165 }
166}
167
168struct DummyExpander(ErrorGuaranteed);
169
170impl TTMacroExpander for DummyExpander {
171 fn expand<'cx>(
172 &self,
173 _: &'cx mut ExtCtxt<'_>,
174 span: Span,
175 _: TokenStream,
176 ) -> ExpandResult<Box<dyn MacResult + 'cx>, ()> {
177 ExpandResult::Ready(DummyResult::any(span, self.0))
178 }
179}
180
181fn trace_macros_note(cx_expansions: &mut FxIndexMap<Span, Vec<String>>, sp: Span, message: String) {
182 let sp = sp.macro_backtrace().last().map_or(sp, |trace| trace.call_site);
183 cx_expansions.entry(sp).or_default().push(message);
184}
185
186pub(super) trait Tracker<'matcher> {
187 type Failure;
189
190 fn build_failure(tok: Token, position: u32, msg: &'static str) -> Self::Failure;
194
195 fn before_match_loc(&mut self, _parser: &TtParser, _matcher: &'matcher MatcherLoc) {}
197
198 fn after_arm(&mut self, _result: &NamedParseResult<Self::Failure>) {}
201
202 fn description() -> &'static str;
204
205 fn recovery() -> Recovery {
206 Recovery::Forbidden
207 }
208}
209
210pub(super) struct NoopTracker;
213
214impl<'matcher> Tracker<'matcher> for NoopTracker {
215 type Failure = ();
216
217 fn build_failure(_tok: Token, _position: u32, _msg: &'static str) -> Self::Failure {}
218
219 fn description() -> &'static str {
220 "none"
221 }
222}
223
224#[instrument(skip(cx, transparency, arg, rules))]
226fn expand_macro<'cx>(
227 cx: &'cx mut ExtCtxt<'_>,
228 sp: Span,
229 def_span: Span,
230 node_id: NodeId,
231 name: Ident,
232 transparency: Transparency,
233 arg: TokenStream,
234 rules: &[MacroRule],
235) -> Box<dyn MacResult + 'cx> {
236 let psess = &cx.sess.psess;
237
238 if cx.trace_macros() {
239 let msg = format!("expanding `{}! {{ {} }}`", name, pprust::tts_to_string(&arg));
240 trace_macros_note(&mut cx.expansions, sp, msg);
241 }
242
243 let try_success_result = try_match_macro(psess, name, &arg, rules, &mut NoopTracker);
245
246 match try_success_result {
247 Ok((rule_index, rule, named_matches)) => {
248 let mbe::TokenTree::Delimited(rhs_span, _, ref rhs) = rule.rhs else {
249 cx.dcx().span_bug(sp, "malformed macro rhs");
250 };
251 let arm_span = rule.rhs.span();
252
253 let id = cx.current_expansion.id;
255 let tts = match transcribe(psess, &named_matches, rhs, rhs_span, transparency, id) {
256 Ok(tts) => tts,
257 Err(err) => {
258 let guar = err.emit();
259 return DummyResult::any(arm_span, guar);
260 }
261 };
262
263 if cx.trace_macros() {
264 let msg = format!("to `{}`", pprust::tts_to_string(&tts));
265 trace_macros_note(&mut cx.expansions, sp, msg);
266 }
267
268 let is_local = is_defined_in_current_crate(node_id);
269 if is_local {
270 cx.resolver.record_macro_rule_usage(node_id, rule_index);
271 }
272
273 Box::new(ParserAnyMacro::from_tts(cx, tts, sp, arm_span, is_local, name))
275 }
276 Err(CanRetry::No(guar)) => {
277 debug!("Will not retry matching as an error was emitted already");
278 DummyResult::any(sp, guar)
279 }
280 Err(CanRetry::Yes) => {
281 let (span, guar) =
283 diagnostics::failed_to_match_macro(cx.psess(), sp, def_span, name, arg, rules);
284 cx.macro_error_and_trace_macros_diag();
285 DummyResult::any(span, guar)
286 }
287 }
288}
289
290pub(super) enum CanRetry {
291 Yes,
292 No(ErrorGuaranteed),
294}
295
296#[instrument(level = "debug", skip(psess, arg, rules, track), fields(tracking = %T::description()))]
300pub(super) fn try_match_macro<'matcher, T: Tracker<'matcher>>(
301 psess: &ParseSess,
302 name: Ident,
303 arg: &TokenStream,
304 rules: &'matcher [MacroRule],
305 track: &mut T,
306) -> Result<(usize, &'matcher MacroRule, NamedMatches), CanRetry> {
307 let parser = parser_from_cx(psess, arg.clone(), T::recovery());
327 let mut tt_parser = TtParser::new(name);
329 for (i, rule) in rules.iter().enumerate() {
330 let _tracing_span = trace_span!("Matching arm", %i);
331
332 let mut gated_spans_snapshot = mem::take(&mut *psess.gated_spans.spans.borrow_mut());
337
338 let result = tt_parser.parse_tt(&mut Cow::Borrowed(&parser), &rule.lhs, track);
339
340 track.after_arm(&result);
341
342 match result {
343 Success(named_matches) => {
344 debug!("Parsed arm successfully");
345 psess.gated_spans.merge(gated_spans_snapshot);
348
349 return Ok((i, rule, named_matches));
350 }
351 Failure(_) => {
352 trace!("Failed to match arm, trying the next one");
353 }
355 Error(_, _) => {
356 debug!("Fatal error occurred during matching");
357 return Err(CanRetry::Yes);
359 }
360 ErrorReported(guarantee) => {
361 debug!("Fatal error occurred and was reported during matching");
362 return Err(CanRetry::No(guarantee));
364 }
365 }
366
367 mem::swap(&mut gated_spans_snapshot, &mut psess.gated_spans.spans.borrow_mut());
370 }
371
372 Err(CanRetry::Yes)
373}
374
375pub fn compile_declarative_macro(
377 sess: &Session,
378 features: &Features,
379 macro_def: &ast::MacroDef,
380 ident: Ident,
381 attrs: &[hir::Attribute],
382 span: Span,
383 node_id: NodeId,
384 edition: Edition,
385) -> (SyntaxExtension, usize) {
386 let mk_syn_ext = |expander| {
387 let kind = SyntaxExtensionKind::LegacyBang(expander);
388 let is_local = is_defined_in_current_crate(node_id);
389 SyntaxExtension::new(sess, kind, span, Vec::new(), edition, ident.name, attrs, is_local)
390 };
391 let dummy_syn_ext = |guar| (mk_syn_ext(Arc::new(DummyExpander(guar))), 0);
392
393 let macro_rules = macro_def.macro_rules;
394 let exp_sep = if macro_rules { exp!(Semi) } else { exp!(Comma) };
395
396 let body = macro_def.body.tokens.clone();
397 let mut p = Parser::new(&sess.psess, body, rustc_parse::MACRO_ARGUMENTS);
398
399 let mut guar = None;
402 let mut check_emission = |ret: Result<(), ErrorGuaranteed>| guar = guar.or(ret.err());
403
404 let mut rules = Vec::new();
405
406 while p.token != token::Eof {
407 let lhs_tt = p.parse_token_tree();
408 let lhs_tt = parse_one_tt(lhs_tt, RulePart::Pattern, sess, node_id, features, edition);
409 check_emission(check_lhs(sess, node_id, &lhs_tt));
410 if let Err(e) = p.expect(exp!(FatArrow)) {
411 return dummy_syn_ext(e.emit());
412 }
413 if let Some(guar) = check_no_eof(sess, &p, "expected right-hand side of macro rule") {
414 return dummy_syn_ext(guar);
415 }
416 let rhs_tt = p.parse_token_tree();
417 let rhs_tt = parse_one_tt(rhs_tt, RulePart::Body, sess, node_id, features, edition);
418 check_emission(check_rhs(sess, &rhs_tt));
419 check_emission(macro_check::check_meta_variables(&sess.psess, node_id, &lhs_tt, &rhs_tt));
420 let lhs_span = lhs_tt.span();
421 let lhs = if let mbe::TokenTree::Delimited(.., delimited) = lhs_tt {
424 mbe::macro_parser::compute_locs(&delimited.tts)
425 } else {
426 return dummy_syn_ext(guar.unwrap());
427 };
428 rules.push(MacroRule { lhs, lhs_span, rhs: rhs_tt });
429 if p.token == token::Eof {
430 break;
431 }
432 if let Err(e) = p.expect(exp_sep) {
433 return dummy_syn_ext(e.emit());
434 }
435 }
436
437 if rules.is_empty() {
438 let guar = sess.dcx().span_err(span, "macros must contain at least one rule");
439 return dummy_syn_ext(guar);
440 }
441
442 let transparency = find_attr!(attrs, AttributeKind::MacroTransparency(x) => *x)
443 .unwrap_or(Transparency::fallback(macro_rules));
444
445 if let Some(guar) = guar {
446 return dummy_syn_ext(guar);
449 }
450
451 let nrules = if is_defined_in_current_crate(node_id) { rules.len() } else { 0 };
453
454 let expander =
455 Arc::new(MacroRulesMacroExpander { name: ident, span, node_id, transparency, rules });
456 (mk_syn_ext(expander), nrules)
457}
458
459fn check_no_eof(sess: &Session, p: &Parser<'_>, msg: &'static str) -> Option<ErrorGuaranteed> {
460 if p.token == token::Eof {
461 let err_sp = p.token.span.shrink_to_hi();
462 let guar = sess
463 .dcx()
464 .struct_span_err(err_sp, "macro definition ended unexpectedly")
465 .with_span_label(err_sp, msg)
466 .emit();
467 return Some(guar);
468 }
469 None
470}
471
472fn check_lhs(sess: &Session, node_id: NodeId, lhs: &mbe::TokenTree) -> Result<(), ErrorGuaranteed> {
473 let e1 = check_lhs_nt_follows(sess, node_id, lhs);
474 let e2 = check_lhs_no_empty_seq(sess, slice::from_ref(lhs));
475 e1.and(e2)
476}
477
478fn check_lhs_nt_follows(
479 sess: &Session,
480 node_id: NodeId,
481 lhs: &mbe::TokenTree,
482) -> Result<(), ErrorGuaranteed> {
483 if let mbe::TokenTree::Delimited(.., delimited) = lhs {
486 check_matcher(sess, node_id, &delimited.tts)
487 } else {
488 let msg = "invalid macro matcher; matchers must be contained in balanced delimiters";
489 Err(sess.dcx().span_err(lhs.span(), msg))
490 }
491}
492
493fn is_empty_token_tree(sess: &Session, seq: &mbe::SequenceRepetition) -> bool {
494 if seq.separator.is_some() {
495 false
496 } else {
497 let mut is_empty = true;
498 let mut iter = seq.tts.iter().peekable();
499 while let Some(tt) = iter.next() {
500 match tt {
501 mbe::TokenTree::MetaVarDecl { kind: NonterminalKind::Vis, .. } => {}
502 mbe::TokenTree::Token(t @ Token { kind: DocComment(..), .. }) => {
503 let mut now = t;
504 while let Some(&mbe::TokenTree::Token(
505 next @ Token { kind: DocComment(..), .. },
506 )) = iter.peek()
507 {
508 now = next;
509 iter.next();
510 }
511 let span = t.span.to(now.span);
512 sess.dcx().span_note(span, "doc comments are ignored in matcher position");
513 }
514 mbe::TokenTree::Sequence(_, sub_seq)
515 if (sub_seq.kleene.op == mbe::KleeneOp::ZeroOrMore
516 || sub_seq.kleene.op == mbe::KleeneOp::ZeroOrOne) => {}
517 _ => is_empty = false,
518 }
519 }
520 is_empty
521 }
522}
523
524fn check_redundant_vis_repetition(
529 err: &mut Diag<'_>,
530 sess: &Session,
531 seq: &SequenceRepetition,
532 span: &DelimSpan,
533) {
534 let is_zero_or_one: bool = seq.kleene.op == KleeneOp::ZeroOrOne;
535 let is_vis = seq.tts.first().map_or(false, |tt| {
536 matches!(tt, mbe::TokenTree::MetaVarDecl { kind: NonterminalKind::Vis, .. })
537 });
538
539 if is_vis && is_zero_or_one {
540 err.note("a `vis` fragment can already be empty");
541 err.multipart_suggestion(
542 "remove the `$(` and `)?`",
543 vec![
544 (
545 sess.source_map().span_extend_to_prev_char_before(span.open, '$', true),
546 "".to_string(),
547 ),
548 (span.close.with_hi(seq.kleene.span.hi()), "".to_string()),
549 ],
550 Applicability::MaybeIncorrect,
551 );
552 }
553}
554
555fn check_lhs_no_empty_seq(sess: &Session, tts: &[mbe::TokenTree]) -> Result<(), ErrorGuaranteed> {
558 use mbe::TokenTree;
559 for tt in tts {
560 match tt {
561 TokenTree::Token(..)
562 | TokenTree::MetaVar(..)
563 | TokenTree::MetaVarDecl { .. }
564 | TokenTree::MetaVarExpr(..) => (),
565 TokenTree::Delimited(.., del) => check_lhs_no_empty_seq(sess, &del.tts)?,
566 TokenTree::Sequence(span, seq) => {
567 if is_empty_token_tree(sess, seq) {
568 let sp = span.entire();
569 let mut err =
570 sess.dcx().struct_span_err(sp, "repetition matches empty token tree");
571 check_redundant_vis_repetition(&mut err, sess, seq, span);
572 return Err(err.emit());
573 }
574 check_lhs_no_empty_seq(sess, &seq.tts)?
575 }
576 }
577 }
578
579 Ok(())
580}
581
582fn check_rhs(sess: &Session, rhs: &mbe::TokenTree) -> Result<(), ErrorGuaranteed> {
583 match *rhs {
584 mbe::TokenTree::Delimited(..) => Ok(()),
585 _ => Err(sess.dcx().span_err(rhs.span(), "macro rhs must be delimited")),
586 }
587}
588
589fn check_matcher(
590 sess: &Session,
591 node_id: NodeId,
592 matcher: &[mbe::TokenTree],
593) -> Result<(), ErrorGuaranteed> {
594 let first_sets = FirstSets::new(matcher);
595 let empty_suffix = TokenSet::empty();
596 check_matcher_core(sess, node_id, &first_sets, matcher, &empty_suffix)?;
597 Ok(())
598}
599
600fn has_compile_error_macro(rhs: &mbe::TokenTree) -> bool {
601 match rhs {
602 mbe::TokenTree::Delimited(.., d) => {
603 let has_compile_error = d.tts.array_windows::<3>().any(|[ident, bang, args]| {
604 if let mbe::TokenTree::Token(ident) = ident
605 && let TokenKind::Ident(ident, _) = ident.kind
606 && ident == sym::compile_error
607 && let mbe::TokenTree::Token(bang) = bang
608 && let TokenKind::Bang = bang.kind
609 && let mbe::TokenTree::Delimited(.., del) = args
610 && !del.delim.skip()
611 {
612 true
613 } else {
614 false
615 }
616 });
617 if has_compile_error { true } else { d.tts.iter().any(has_compile_error_macro) }
618 }
619 _ => false,
620 }
621}
622
623struct FirstSets<'tt> {
636 first: FxHashMap<Span, Option<TokenSet<'tt>>>,
643}
644
645impl<'tt> FirstSets<'tt> {
646 fn new(tts: &'tt [mbe::TokenTree]) -> FirstSets<'tt> {
647 use mbe::TokenTree;
648
649 let mut sets = FirstSets { first: FxHashMap::default() };
650 build_recur(&mut sets, tts);
651 return sets;
652
653 fn build_recur<'tt>(sets: &mut FirstSets<'tt>, tts: &'tt [TokenTree]) -> TokenSet<'tt> {
657 let mut first = TokenSet::empty();
658 for tt in tts.iter().rev() {
659 match tt {
660 TokenTree::Token(..)
661 | TokenTree::MetaVar(..)
662 | TokenTree::MetaVarDecl { .. }
663 | TokenTree::MetaVarExpr(..) => {
664 first.replace_with(TtHandle::TtRef(tt));
665 }
666 TokenTree::Delimited(span, _, delimited) => {
667 build_recur(sets, &delimited.tts);
668 first.replace_with(TtHandle::from_token_kind(
669 delimited.delim.as_open_token_kind(),
670 span.open,
671 ));
672 }
673 TokenTree::Sequence(sp, seq_rep) => {
674 let subfirst = build_recur(sets, &seq_rep.tts);
675
676 match sets.first.entry(sp.entire()) {
677 Entry::Vacant(vac) => {
678 vac.insert(Some(subfirst.clone()));
679 }
680 Entry::Occupied(mut occ) => {
681 occ.insert(None);
688 }
689 }
690
691 if let (Some(sep), true) = (&seq_rep.separator, subfirst.maybe_empty) {
695 first.add_one_maybe(TtHandle::from_token(*sep));
696 }
697
698 if subfirst.maybe_empty
700 || seq_rep.kleene.op == mbe::KleeneOp::ZeroOrMore
701 || seq_rep.kleene.op == mbe::KleeneOp::ZeroOrOne
702 {
703 first.add_all(&TokenSet { maybe_empty: true, ..subfirst });
706 } else {
707 first = subfirst;
710 }
711 }
712 }
713 }
714
715 first
716 }
717 }
718
719 fn first(&self, tts: &'tt [mbe::TokenTree]) -> TokenSet<'tt> {
722 use mbe::TokenTree;
723
724 let mut first = TokenSet::empty();
725 for tt in tts.iter() {
726 assert!(first.maybe_empty);
727 match tt {
728 TokenTree::Token(..)
729 | TokenTree::MetaVar(..)
730 | TokenTree::MetaVarDecl { .. }
731 | TokenTree::MetaVarExpr(..) => {
732 first.add_one(TtHandle::TtRef(tt));
733 return first;
734 }
735 TokenTree::Delimited(span, _, delimited) => {
736 first.add_one(TtHandle::from_token_kind(
737 delimited.delim.as_open_token_kind(),
738 span.open,
739 ));
740 return first;
741 }
742 TokenTree::Sequence(sp, seq_rep) => {
743 let subfirst_owned;
744 let subfirst = match self.first.get(&sp.entire()) {
745 Some(Some(subfirst)) => subfirst,
746 Some(&None) => {
747 subfirst_owned = self.first(&seq_rep.tts);
748 &subfirst_owned
749 }
750 None => {
751 panic!("We missed a sequence during FirstSets construction");
752 }
753 };
754
755 if let (Some(sep), true) = (&seq_rep.separator, subfirst.maybe_empty) {
758 first.add_one_maybe(TtHandle::from_token(*sep));
759 }
760
761 assert!(first.maybe_empty);
762 first.add_all(subfirst);
763 if subfirst.maybe_empty
764 || seq_rep.kleene.op == mbe::KleeneOp::ZeroOrMore
765 || seq_rep.kleene.op == mbe::KleeneOp::ZeroOrOne
766 {
767 first.maybe_empty = true;
771 continue;
772 } else {
773 return first;
774 }
775 }
776 }
777 }
778
779 assert!(first.maybe_empty);
782 first
783 }
784}
785
786#[derive(Debug)]
791enum TtHandle<'tt> {
792 TtRef(&'tt mbe::TokenTree),
794
795 Token(mbe::TokenTree),
800}
801
802impl<'tt> TtHandle<'tt> {
803 fn from_token(tok: Token) -> Self {
804 TtHandle::Token(mbe::TokenTree::Token(tok))
805 }
806
807 fn from_token_kind(kind: TokenKind, span: Span) -> Self {
808 TtHandle::from_token(Token::new(kind, span))
809 }
810
811 fn get(&'tt self) -> &'tt mbe::TokenTree {
813 match self {
814 TtHandle::TtRef(tt) => tt,
815 TtHandle::Token(token_tt) => token_tt,
816 }
817 }
818}
819
820impl<'tt> PartialEq for TtHandle<'tt> {
821 fn eq(&self, other: &TtHandle<'tt>) -> bool {
822 self.get() == other.get()
823 }
824}
825
826impl<'tt> Clone for TtHandle<'tt> {
827 fn clone(&self) -> Self {
828 match self {
829 TtHandle::TtRef(tt) => TtHandle::TtRef(tt),
830
831 TtHandle::Token(mbe::TokenTree::Token(tok)) => {
834 TtHandle::Token(mbe::TokenTree::Token(*tok))
835 }
836
837 _ => unreachable!(),
838 }
839 }
840}
841
842#[derive(Clone, Debug)]
853struct TokenSet<'tt> {
854 tokens: Vec<TtHandle<'tt>>,
855 maybe_empty: bool,
856}
857
858impl<'tt> TokenSet<'tt> {
859 fn empty() -> Self {
861 TokenSet { tokens: Vec::new(), maybe_empty: true }
862 }
863
864 fn singleton(tt: TtHandle<'tt>) -> Self {
867 TokenSet { tokens: vec![tt], maybe_empty: false }
868 }
869
870 fn replace_with(&mut self, tt: TtHandle<'tt>) {
873 self.tokens.clear();
874 self.tokens.push(tt);
875 self.maybe_empty = false;
876 }
877
878 fn replace_with_irrelevant(&mut self) {
882 self.tokens.clear();
883 self.maybe_empty = false;
884 }
885
886 fn add_one(&mut self, tt: TtHandle<'tt>) {
888 if !self.tokens.contains(&tt) {
889 self.tokens.push(tt);
890 }
891 self.maybe_empty = false;
892 }
893
894 fn add_one_maybe(&mut self, tt: TtHandle<'tt>) {
896 if !self.tokens.contains(&tt) {
897 self.tokens.push(tt);
898 }
899 }
900
901 fn add_all(&mut self, other: &Self) {
909 for tt in &other.tokens {
910 if !self.tokens.contains(tt) {
911 self.tokens.push(tt.clone());
912 }
913 }
914 if !other.maybe_empty {
915 self.maybe_empty = false;
916 }
917 }
918}
919
920fn check_matcher_core<'tt>(
932 sess: &Session,
933 node_id: NodeId,
934 first_sets: &FirstSets<'tt>,
935 matcher: &'tt [mbe::TokenTree],
936 follow: &TokenSet<'tt>,
937) -> Result<TokenSet<'tt>, ErrorGuaranteed> {
938 use mbe::TokenTree;
939
940 let mut last = TokenSet::empty();
941
942 let mut errored = Ok(());
943
944 'each_token: for i in 0..matcher.len() {
948 let token = &matcher[i];
949 let suffix = &matcher[i + 1..];
950
951 let build_suffix_first = || {
952 let mut s = first_sets.first(suffix);
953 if s.maybe_empty {
954 s.add_all(follow);
955 }
956 s
957 };
958
959 let suffix_first;
963
964 match token {
967 TokenTree::Token(..)
968 | TokenTree::MetaVar(..)
969 | TokenTree::MetaVarDecl { .. }
970 | TokenTree::MetaVarExpr(..) => {
971 if token_can_be_followed_by_any(token) {
972 last.replace_with_irrelevant();
974 continue 'each_token;
977 } else {
978 last.replace_with(TtHandle::TtRef(token));
979 suffix_first = build_suffix_first();
980 }
981 }
982 TokenTree::Delimited(span, _, d) => {
983 let my_suffix = TokenSet::singleton(TtHandle::from_token_kind(
984 d.delim.as_close_token_kind(),
985 span.close,
986 ));
987 check_matcher_core(sess, node_id, first_sets, &d.tts, &my_suffix)?;
988 last.replace_with_irrelevant();
990
991 continue 'each_token;
994 }
995 TokenTree::Sequence(_, seq_rep) => {
996 suffix_first = build_suffix_first();
997 let mut new;
1008 let my_suffix = if let Some(sep) = &seq_rep.separator {
1009 new = suffix_first.clone();
1010 new.add_one_maybe(TtHandle::from_token(*sep));
1011 &new
1012 } else {
1013 &suffix_first
1014 };
1015
1016 let next = check_matcher_core(sess, node_id, first_sets, &seq_rep.tts, my_suffix)?;
1020 if next.maybe_empty {
1021 last.add_all(&next);
1022 } else {
1023 last = next;
1024 }
1025
1026 continue 'each_token;
1029 }
1030 }
1031
1032 for tt in &last.tokens {
1037 if let &TokenTree::MetaVarDecl { span, name, kind } = tt.get() {
1038 for next_token in &suffix_first.tokens {
1039 let next_token = next_token.get();
1040
1041 if is_defined_in_current_crate(node_id)
1048 && matches!(kind, NonterminalKind::Pat(PatParam { inferred: true }))
1049 && matches!(
1050 next_token,
1051 TokenTree::Token(token) if *token == token::Or
1052 )
1053 {
1054 let suggestion = quoted_tt_to_string(&TokenTree::MetaVarDecl {
1056 span,
1057 name,
1058 kind: NonterminalKind::Pat(PatParam { inferred: false }),
1059 });
1060 sess.psess.buffer_lint(
1061 RUST_2021_INCOMPATIBLE_OR_PATTERNS,
1062 span,
1063 ast::CRATE_NODE_ID,
1064 BuiltinLintDiag::OrPatternsBackCompat(span, suggestion),
1065 );
1066 }
1067 match is_in_follow(next_token, kind) {
1068 IsInFollow::Yes => {}
1069 IsInFollow::No(possible) => {
1070 let may_be = if last.tokens.len() == 1 && suffix_first.tokens.len() == 1
1071 {
1072 "is"
1073 } else {
1074 "may be"
1075 };
1076
1077 let sp = next_token.span();
1078 let mut err = sess.dcx().struct_span_err(
1079 sp,
1080 format!(
1081 "`${name}:{frag}` {may_be} followed by `{next}`, which \
1082 is not allowed for `{frag}` fragments",
1083 name = name,
1084 frag = kind,
1085 next = quoted_tt_to_string(next_token),
1086 may_be = may_be
1087 ),
1088 );
1089 err.span_label(sp, format!("not allowed after `{kind}` fragments"));
1090
1091 if kind == NonterminalKind::Pat(PatWithOr)
1092 && sess.psess.edition.at_least_rust_2021()
1093 && next_token.is_token(&token::Or)
1094 {
1095 let suggestion = quoted_tt_to_string(&TokenTree::MetaVarDecl {
1096 span,
1097 name,
1098 kind: NonterminalKind::Pat(PatParam { inferred: false }),
1099 });
1100 err.span_suggestion(
1101 span,
1102 "try a `pat_param` fragment specifier instead",
1103 suggestion,
1104 Applicability::MaybeIncorrect,
1105 );
1106 }
1107
1108 let msg = "allowed there are: ";
1109 match possible {
1110 &[] => {}
1111 &[t] => {
1112 err.note(format!(
1113 "only {t} is allowed after `{kind}` fragments",
1114 ));
1115 }
1116 ts => {
1117 err.note(format!(
1118 "{}{} or {}",
1119 msg,
1120 ts[..ts.len() - 1].to_vec().join(", "),
1121 ts[ts.len() - 1],
1122 ));
1123 }
1124 }
1125 errored = Err(err.emit());
1126 }
1127 }
1128 }
1129 }
1130 }
1131 }
1132 errored?;
1133 Ok(last)
1134}
1135
1136fn token_can_be_followed_by_any(tok: &mbe::TokenTree) -> bool {
1137 if let mbe::TokenTree::MetaVarDecl { kind, .. } = *tok {
1138 frag_can_be_followed_by_any(kind)
1139 } else {
1140 true
1142 }
1143}
1144
1145fn frag_can_be_followed_by_any(kind: NonterminalKind) -> bool {
1154 matches!(
1155 kind,
1156 NonterminalKind::Item | NonterminalKind::Block | NonterminalKind::Ident | NonterminalKind::Literal | NonterminalKind::Meta | NonterminalKind::Lifetime | NonterminalKind::TT )
1164}
1165
1166enum IsInFollow {
1167 Yes,
1168 No(&'static [&'static str]),
1169}
1170
1171fn is_in_follow(tok: &mbe::TokenTree, kind: NonterminalKind) -> IsInFollow {
1180 use mbe::TokenTree;
1181
1182 if let TokenTree::Token(Token { kind, .. }) = tok
1183 && kind.close_delim().is_some()
1184 {
1185 IsInFollow::Yes
1188 } else {
1189 match kind {
1190 NonterminalKind::Item => {
1191 IsInFollow::Yes
1194 }
1195 NonterminalKind::Block => {
1196 IsInFollow::Yes
1199 }
1200 NonterminalKind::Stmt | NonterminalKind::Expr(_) => {
1201 const TOKENS: &[&str] = &["`=>`", "`,`", "`;`"];
1202 match tok {
1203 TokenTree::Token(token) => match token.kind {
1204 FatArrow | Comma | Semi => IsInFollow::Yes,
1205 _ => IsInFollow::No(TOKENS),
1206 },
1207 _ => IsInFollow::No(TOKENS),
1208 }
1209 }
1210 NonterminalKind::Pat(PatParam { .. }) => {
1211 const TOKENS: &[&str] = &["`=>`", "`,`", "`=`", "`|`", "`if`", "`in`"];
1212 match tok {
1213 TokenTree::Token(token) => match token.kind {
1214 FatArrow | Comma | Eq | Or => IsInFollow::Yes,
1215 Ident(name, IdentIsRaw::No) if name == kw::If || name == kw::In => {
1216 IsInFollow::Yes
1217 }
1218 _ => IsInFollow::No(TOKENS),
1219 },
1220 _ => IsInFollow::No(TOKENS),
1221 }
1222 }
1223 NonterminalKind::Pat(PatWithOr) => {
1224 const TOKENS: &[&str] = &["`=>`", "`,`", "`=`", "`if`", "`in`"];
1225 match tok {
1226 TokenTree::Token(token) => match token.kind {
1227 FatArrow | Comma | Eq => IsInFollow::Yes,
1228 Ident(name, IdentIsRaw::No) if name == kw::If || name == kw::In => {
1229 IsInFollow::Yes
1230 }
1231 _ => IsInFollow::No(TOKENS),
1232 },
1233 _ => IsInFollow::No(TOKENS),
1234 }
1235 }
1236 NonterminalKind::Path | NonterminalKind::Ty => {
1237 const TOKENS: &[&str] = &[
1238 "`{`", "`[`", "`=>`", "`,`", "`>`", "`=`", "`:`", "`;`", "`|`", "`as`",
1239 "`where`",
1240 ];
1241 match tok {
1242 TokenTree::Token(token) => match token.kind {
1243 OpenBrace | OpenBracket | Comma | FatArrow | Colon | Eq | Gt | Shr
1244 | Semi | Or => IsInFollow::Yes,
1245 Ident(name, IdentIsRaw::No) if name == kw::As || name == kw::Where => {
1246 IsInFollow::Yes
1247 }
1248 _ => IsInFollow::No(TOKENS),
1249 },
1250 TokenTree::MetaVarDecl { kind: NonterminalKind::Block, .. } => IsInFollow::Yes,
1251 _ => IsInFollow::No(TOKENS),
1252 }
1253 }
1254 NonterminalKind::Ident | NonterminalKind::Lifetime => {
1255 IsInFollow::Yes
1257 }
1258 NonterminalKind::Literal => {
1259 IsInFollow::Yes
1261 }
1262 NonterminalKind::Meta | NonterminalKind::TT => {
1263 IsInFollow::Yes
1266 }
1267 NonterminalKind::Vis => {
1268 const TOKENS: &[&str] = &["`,`", "an ident", "a type"];
1270 match tok {
1271 TokenTree::Token(token) => match token.kind {
1272 Comma => IsInFollow::Yes,
1273 Ident(_, IdentIsRaw::Yes) => IsInFollow::Yes,
1274 Ident(name, _) if name != kw::Priv => IsInFollow::Yes,
1275 _ => {
1276 if token.can_begin_type() {
1277 IsInFollow::Yes
1278 } else {
1279 IsInFollow::No(TOKENS)
1280 }
1281 }
1282 },
1283 TokenTree::MetaVarDecl {
1284 kind: NonterminalKind::Ident | NonterminalKind::Ty | NonterminalKind::Path,
1285 ..
1286 } => IsInFollow::Yes,
1287 _ => IsInFollow::No(TOKENS),
1288 }
1289 }
1290 }
1291 }
1292}
1293
1294fn quoted_tt_to_string(tt: &mbe::TokenTree) -> String {
1295 match tt {
1296 mbe::TokenTree::Token(token) => pprust::token_to_string(token).into(),
1297 mbe::TokenTree::MetaVar(_, name) => format!("${name}"),
1298 mbe::TokenTree::MetaVarDecl { name, kind, .. } => format!("${name}:{kind}"),
1299 _ => panic!(
1300 "{}",
1301 "unexpected mbe::TokenTree::{Sequence or Delimited} \
1302 in follow set checker"
1303 ),
1304 }
1305}
1306
1307fn is_defined_in_current_crate(node_id: NodeId) -> bool {
1308 node_id != DUMMY_NODE_ID
1311}
1312
1313pub(super) fn parser_from_cx(
1314 psess: &ParseSess,
1315 mut tts: TokenStream,
1316 recovery: Recovery,
1317) -> Parser<'_> {
1318 tts.desugar_doc_comments();
1319 Parser::new(psess, tts, rustc_parse::MACRO_ARGUMENTS).recovery(recovery)
1320}