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, Delimiter, NonterminalKind, Token, TokenKind};
10use rustc_ast::tokenstream::{self, DelimSpan, TokenStream};
11use rustc_ast::{self as ast, DUMMY_NODE_ID, NodeId, Safety};
12use rustc_ast_pretty::pprust;
13use rustc_attr_ir::diagnostic::Directive;
14use rustc_attr_ir::{self as attrs, find_attr};
15use rustc_data_structures::fx::{FxHashMap, FxIndexMap};
16use rustc_errors::{Applicability, Diag, ErrorGuaranteed, MultiSpan};
17use rustc_feature::Features;
18use rustc_hir::def::MacroKinds;
19use rustc_lint_defs::builtin::{
20 RUST_2021_INCOMPATIBLE_OR_PATTERNS, SEMICOLON_IN_EXPRESSIONS_FROM_MACROS,
21 SEMICOLON_IN_EXPRESSIONS_FROM_NON_LOCAL_MACROS,
22};
23use rustc_parse::exp;
24use rustc_parse::parser::{Parser, Recovery};
25use rustc_session::Session;
26use rustc_session::diagnostics::feature_err;
27use rustc_session::parse::ParseSess;
28use rustc_span::edition::Edition;
29use rustc_span::hygiene::Transparency;
30use rustc_span::{Ident, Span, Symbol, kw, sym};
31use tracing::{debug, instrument, trace, trace_span};
32
33use super::SequenceRepetition;
34use super::diagnostics::{FailedMacro, failed_to_match_macro};
35use super::macro_parser::{NamedMatches, NamedParseResult};
36use crate::base::{
37 AttrProcMacro, BangProcMacro, DummyResult, ExpandResult, ExtCtxt, MacResult,
38 MacroExpanderResult, SyntaxExtension, SyntaxExtensionKind, TTMacroExpander,
39};
40use crate::diagnostics;
41use crate::expand::{AstFragment, AstFragmentKind, ensure_complete_parse, parse_ast_fragment};
42use crate::mbe::macro_check::check_meta_variables;
43use crate::mbe::macro_parser::{Ambiguity, ErrorReported, Failure, MatcherLoc, Success, TtParser};
44use crate::mbe::quoted::{RulePart, parse_one_tt};
45use crate::mbe::transcribe::transcribe;
46use crate::mbe::{self, KleeneOp};
47
48pub(crate) struct ParserAnyMacro<'a, 'b> {
49 parser: Parser<'a>,
50
51 site_span: Span,
53 macro_ident: Ident,
55 lint_node_id: NodeId,
56 is_trailing_mac: bool,
57 arm_span: Span,
58 is_local: bool,
60 bindings: &'b [MacroRule],
61 matched_rule_bindings: &'b [MatcherLoc],
62}
63
64impl<'a, 'b> ParserAnyMacro<'a, 'b> {
65 pub(crate) fn make(
66 mut self: Box<ParserAnyMacro<'a, 'b>>,
67 kind: AstFragmentKind,
68 ) -> AstFragment {
69 let ParserAnyMacro {
70 site_span,
71 macro_ident,
72 ref mut parser,
73 lint_node_id,
74 arm_span,
75 is_trailing_mac,
76 is_local,
77 bindings,
78 matched_rule_bindings,
79 } = *self;
80 let snapshot = &mut parser.create_snapshot_for_diagnostic();
81 let fragment = match parse_ast_fragment(parser, kind) {
82 Ok(f) => f,
83 Err(err) => {
84 let guar = super::diagnostics::emit_frag_parse_err(
85 err,
86 parser,
87 snapshot,
88 site_span,
89 arm_span,
90 kind,
91 bindings,
92 matched_rule_bindings,
93 );
94 return kind.dummy(site_span, guar);
95 }
96 };
97
98 if kind == AstFragmentKind::Expr && parser.token == token::Semi {
102 let lint = if is_local {
103 SEMICOLON_IN_EXPRESSIONS_FROM_MACROS
104 } else {
105 SEMICOLON_IN_EXPRESSIONS_FROM_NON_LOCAL_MACROS
106 };
107 parser.psess.buffer_lint(
108 lint,
109 parser.token.span,
110 lint_node_id,
111 diagnostics::TrailingMacro { is_trailing: is_trailing_mac, name: macro_ident },
112 );
113 parser.bump();
114 }
115
116 let path = ast::Path::from_ident(macro_ident.with_span_pos(site_span));
118 ensure_complete_parse(parser, &path, kind.name(), site_span);
119 fragment
120 }
121
122 #[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("from_tts",
"rustc_expand::mbe::macro_rules", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_expand/src/mbe/macro_rules.rs"),
::tracing_core::__macro_support::Option::Some(122u32),
::tracing_core::__macro_support::Option::Some("rustc_expand::mbe::macro_rules"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("site_span")
}> =
::tracing::__macro_support::FieldName::new("site_span");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("arm_span")
}> =
::tracing::__macro_support::FieldName::new("arm_span");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("is_local")
}> =
::tracing::__macro_support::FieldName::new("is_local");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("macro_ident")
}> =
::tracing::__macro_support::FieldName::new("macro_ident");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::INFO <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&site_span)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&arm_span)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&is_local as
&dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(¯o_ident)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: Self = loop {};
return __tracing_attr_fake_return;
}
{
Self {
parser: Parser::new(&cx.sess.psess, tts, None),
site_span,
macro_ident,
lint_node_id: cx.current_expansion.lint_node_id,
is_trailing_mac: cx.current_expansion.is_trailing_mac,
arm_span,
is_local,
bindings,
matched_rule_bindings,
}
}
}
}#[instrument(skip(cx, tts, bindings, matched_rule_bindings))]
123 pub(crate) fn from_tts<'cx>(
124 cx: &'cx mut ExtCtxt<'a>,
125 tts: TokenStream,
126 site_span: Span,
127 arm_span: Span,
128 is_local: bool,
129 macro_ident: Ident,
130 bindings: &'b [MacroRule],
132 matched_rule_bindings: &'b [MatcherLoc],
133 ) -> Self {
134 Self {
135 parser: Parser::new(&cx.sess.psess, tts, None),
136
137 site_span,
141 macro_ident,
142 lint_node_id: cx.current_expansion.lint_node_id,
143 is_trailing_mac: cx.current_expansion.is_trailing_mac,
144 arm_span,
145 is_local,
146 bindings,
147 matched_rule_bindings,
148 }
149 }
150}
151
152pub(crate) enum MacroRule {
153 Func { lhs: Vec<MatcherLoc>, lhs_span: Span, rhs: mbe::TokenTree },
155 Attr {
157 unsafe_rule: bool,
158 args: Vec<MatcherLoc>,
159 args_span: Span,
160 body: Vec<MatcherLoc>,
161 body_span: Span,
162 rhs: mbe::TokenTree,
163 },
164 Derive { body: Vec<MatcherLoc>, body_span: Span, rhs: mbe::TokenTree },
166}
167
168#[derive(#[automatically_derived]
impl ::core::marker::Copy for WhichMatcher { }Copy, #[automatically_derived]
impl ::core::clone::Clone for WhichMatcher {
#[inline]
fn clone(&self) -> WhichMatcher { *self }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for WhichMatcher {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
WhichMatcher::Args => "Args",
WhichMatcher::Body => "Body",
})
}
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for WhichMatcher {
#[inline]
fn eq(&self, other: &WhichMatcher) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for WhichMatcher {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {}
}Eq, #[automatically_derived]
impl ::core::cmp::PartialOrd for WhichMatcher {
#[inline]
fn partial_cmp(&self, other: &WhichMatcher)
-> ::core::option::Option<::core::cmp::Ordering> {
::core::option::Option::Some(::core::cmp::Ord::cmp(self, other))
}
}PartialOrd, #[automatically_derived]
impl ::core::cmp::Ord for WhichMatcher {
#[inline]
fn cmp(&self, other: &WhichMatcher) -> ::core::cmp::Ordering {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
::core::cmp::Ord::cmp(&__self_discr, &__arg1_discr)
}
}Ord)]
176pub(crate) enum WhichMatcher {
177 Args,
179
180 Body,
184}
185
186impl WhichMatcher {
187 pub(crate) const FOR_FUNC: Self = Self::Body;
189
190 pub(crate) const FOR_DERIVE: Self = Self::Body;
192}
193
194pub struct MacroRulesMacroExpander {
195 node_id: NodeId,
196 name: Ident,
197 span: Span,
198 on_unmatched_args: Option<Directive>,
199 transparency: Transparency,
200 kinds: MacroKinds,
201 rules: Vec<MacroRule>,
202 macro_rules: bool,
203}
204
205impl MacroRulesMacroExpander {
206 pub fn get_unused_rule(&self, rule_i: usize) -> Option<(&Ident, MultiSpan)> {
207 let (span, rhs) = match self.rules[rule_i] {
209 MacroRule::Func { lhs_span, ref rhs, .. } => (MultiSpan::from_span(lhs_span), rhs),
210 MacroRule::Attr { args_span, body_span, ref rhs, .. } => {
211 (MultiSpan::from_spans(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[args_span, body_span]))vec![args_span, body_span]), rhs)
212 }
213 MacroRule::Derive { body_span, ref rhs, .. } => (MultiSpan::from_span(body_span), rhs),
214 };
215 if has_compile_error_macro(rhs) { None } else { Some((&self.name, span)) }
216 }
217
218 pub fn kinds(&self) -> MacroKinds {
219 self.kinds
220 }
221
222 pub fn nrules(&self) -> usize {
223 self.rules.len()
224 }
225
226 pub fn is_macro_rules(&self) -> bool {
227 self.macro_rules
228 }
229
230 pub fn expand_derive(
231 &self,
232 cx: &mut ExtCtxt<'_>,
233 sp: Span,
234 body: &TokenStream,
235 ) -> Result<TokenStream, ErrorGuaranteed> {
236 let name = self.name;
239 let rules = &self.rules;
240 let psess = &cx.sess.psess;
241
242 if cx.trace_macros() {
243 let msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("expanding `#[derive({1})] {0}`",
pprust::tts_to_string(body), name))
})format!("expanding `#[derive({name})] {}`", pprust::tts_to_string(body));
244 trace_macros_note(&mut cx.expansions, sp, msg);
245 }
246
247 match try_match_macro_derive(psess, name, body, rules, &mut NoopTracker) {
248 Ok((rule_index, rule, named_matches)) => {
249 let MacroRule::Derive { rhs, .. } = rule else {
250 {
::core::panicking::panic_fmt(format_args!("try_match_macro_derive returned non-derive rule"));
};panic!("try_match_macro_derive returned non-derive rule");
251 };
252 let mbe::TokenTree::Delimited(rhs_span, _, rhs) = rhs else {
253 cx.dcx().span_bug(sp, "malformed macro derive rhs");
254 };
255
256 let id = cx.current_expansion.id;
257 let tts = transcribe(psess, &named_matches, rhs, *rhs_span, self.transparency, id)
258 .map_err(|e| e.emit())?;
259
260 if cx.trace_macros() {
261 let msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("to `{0}`",
pprust::tts_to_string(&tts)))
})format!("to `{}`", pprust::tts_to_string(&tts));
262 trace_macros_note(&mut cx.expansions, sp, msg);
263 }
264
265 if is_defined_in_current_crate(self.node_id) {
266 cx.resolver.record_macro_rule_usage(self.node_id, rule_index);
267 }
268
269 Ok(tts)
270 }
271 Err(CanRetry::No(guar)) => Err(guar),
272 Err(CanRetry::Yes) => {
273 let (_, guar) = failed_to_match_macro(
274 cx.psess(),
275 sp,
276 self.span,
277 name,
278 FailedMacro::Derive,
279 body,
280 rules,
281 self.on_unmatched_args.as_ref(),
282 );
283 cx.macro_error_and_trace_macros_diag();
284 Err(guar)
285 }
286 }
287 }
288}
289
290impl TTMacroExpander for MacroRulesMacroExpander {
291 fn expand<'cx, 'a: 'cx>(
292 &'a self,
293 cx: &'cx mut ExtCtxt<'_>,
294 sp: Span,
295 input: TokenStream,
296 ) -> MacroExpanderResult<'cx> {
297 ExpandResult::Ready(expand_macro(
298 cx,
299 sp,
300 self.span,
301 self.node_id,
302 self.name,
303 self.transparency,
304 input,
305 &self.rules,
306 self.on_unmatched_args.as_ref(),
307 ))
308 }
309}
310
311impl AttrProcMacro for MacroRulesMacroExpander {
312 fn expand(
313 &self,
314 _cx: &mut ExtCtxt<'_>,
315 _sp: Span,
316 _args: TokenStream,
317 _body: TokenStream,
318 ) -> Result<TokenStream, ErrorGuaranteed> {
319 {
::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
format_args!("`expand` called on `MacroRulesMacroExpander`, expected `expand_with_safety`")));
}unreachable!("`expand` called on `MacroRulesMacroExpander`, expected `expand_with_safety`")
320 }
321
322 fn expand_with_safety(
323 &self,
324 cx: &mut ExtCtxt<'_>,
325 safety: Safety,
326 sp: Span,
327 args: TokenStream,
328 body: TokenStream,
329 ) -> Result<TokenStream, ErrorGuaranteed> {
330 expand_macro_attr(
331 cx,
332 sp,
333 self.span,
334 self.node_id,
335 self.name,
336 self.transparency,
337 safety,
338 args,
339 body,
340 &self.rules,
341 self.on_unmatched_args.as_ref(),
342 )
343 }
344}
345
346struct DummyBang(ErrorGuaranteed);
347
348impl BangProcMacro for DummyBang {
349 fn expand<'cx>(
350 &self,
351 _: &'cx mut ExtCtxt<'_>,
352 _: Span,
353 _: TokenStream,
354 ) -> Result<TokenStream, ErrorGuaranteed> {
355 Err(self.0)
356 }
357}
358
359fn trace_macros_note(cx_expansions: &mut FxIndexMap<Span, Vec<String>>, sp: Span, message: String) {
360 let sp = sp.macro_backtrace().last().map_or(sp, |trace| trace.call_site);
361 cx_expansions.entry(sp).or_default().push(message);
362}
363
364pub(super) trait Tracker<'matcher> {
365 fn prepare(&mut self, which_matcher: WhichMatcher, matcher: &'matcher [MatcherLoc]);
367
368 fn before_match_loc(&mut self, parser: &TtParser, matcher: &'matcher MatcherLoc);
370
371 fn matched_one(&mut self, parser: &Parser<'_>, loc_index: usize);
378
379 fn after_arm(&mut self, result: &NamedParseResult);
382
383 fn failure(&mut self, parser: &Parser<'_>);
391
392 fn ambiguity(&mut self, parser: &Parser<'_>);
396
397 fn description() -> &'static str;
399
400 fn recovery() -> Recovery;
401}
402
403pub(super) struct NoopTracker;
406
407impl<'matcher> Tracker<'matcher> for NoopTracker {
408 fn prepare(&mut self, _which_matcher: WhichMatcher, _matcher: &'matcher [MatcherLoc]) {}
409
410 fn before_match_loc(&mut self, _parser: &TtParser, _matcher: &'matcher MatcherLoc) {}
411
412 fn matched_one(&mut self, _parser: &Parser<'_>, _loc_index: usize) {}
413
414 fn ambiguity(&mut self, _parser: &Parser<'_>) {}
415
416 fn after_arm(&mut self, _result: &NamedParseResult) {}
417
418 fn failure(&mut self, _parser: &Parser<'_>) {}
419
420 fn description() -> &'static str {
421 "none"
422 }
423
424 fn recovery() -> Recovery {
425 Recovery::Forbidden
426 }
427}
428
429#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("expand_macro",
"rustc_expand::mbe::macro_rules", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_expand/src/mbe/macro_rules.rs"),
::tracing_core::__macro_support::Option::Some(430u32),
::tracing_core::__macro_support::Option::Some("rustc_expand::mbe::macro_rules"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("sp")
}> =
::tracing::__macro_support::FieldName::new("sp");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("def_span")
}> =
::tracing::__macro_support::FieldName::new("def_span");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("node_id")
}> =
::tracing::__macro_support::FieldName::new("node_id");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("name")
}> =
::tracing::__macro_support::FieldName::new("name");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::INFO <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&sp)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_span)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&node_id)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&name)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: Box<dyn MacResult + 'cx> =
loop {};
return __tracing_attr_fake_return;
}
{
let psess = &cx.sess.psess;
if cx.trace_macros() {
let msg =
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("expanding `{0}! {{ {1} }}`",
name, pprust::tts_to_string(&arg)))
});
trace_macros_note(&mut cx.expansions, sp, msg);
}
let try_success_result =
try_match_macro(psess, name, &arg, rules, &mut NoopTracker);
match try_success_result {
Ok((rule_index, rule, named_matches)) => {
let MacroRule::Func { lhs, rhs, .. } =
rule else {
{
::core::panicking::panic_fmt(format_args!("try_match_macro returned non-func rule"));
};
};
let mbe::TokenTree::Delimited(rhs_span, _, rhs) =
rhs else { cx.dcx().span_bug(sp, "malformed macro rhs"); };
let arm_span = rhs_span.entire();
let id = cx.current_expansion.id;
let tts =
match transcribe(psess, &named_matches, rhs, *rhs_span,
transparency, id) {
Ok(tts) => tts,
Err(err) => {
let guar = err.emit();
return DummyResult::any(arm_span, guar);
}
};
if cx.trace_macros() {
let msg =
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("to `{0}`",
pprust::tts_to_string(&tts)))
});
trace_macros_note(&mut cx.expansions, sp, msg);
}
let is_local = is_defined_in_current_crate(node_id);
if is_local {
cx.resolver.record_macro_rule_usage(node_id, rule_index);
}
Box::new(ParserAnyMacro::from_tts(cx, tts, sp, arm_span,
is_local, name, rules, lhs))
}
Err(CanRetry::No(guar)) => {
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_expand/src/mbe/macro_rules.rs:486",
"rustc_expand::mbe::macro_rules", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_expand/src/mbe/macro_rules.rs"),
::tracing_core::__macro_support::Option::Some(486u32),
::tracing_core::__macro_support::Option::Some("rustc_expand::mbe::macro_rules"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("Will not retry matching as an error was emitted already")
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
DummyResult::any(sp, guar)
}
Err(CanRetry::Yes) => {
let (span, guar) =
failed_to_match_macro(cx.psess(), sp, def_span, name,
FailedMacro::Func, &arg, rules, on_unmatched_args);
cx.macro_error_and_trace_macros_diag();
DummyResult::any(span, guar)
}
}
}
}
}#[instrument(skip(cx, transparency, arg, rules, on_unmatched_args))]
431fn expand_macro<'cx, 'a: 'cx>(
432 cx: &'cx mut ExtCtxt<'_>,
433 sp: Span,
434 def_span: Span,
435 node_id: NodeId,
436 name: Ident,
437 transparency: Transparency,
438 arg: TokenStream,
439 rules: &'a [MacroRule],
440 on_unmatched_args: Option<&Directive>,
441) -> Box<dyn MacResult + 'cx> {
442 let psess = &cx.sess.psess;
443
444 if cx.trace_macros() {
445 let msg = format!("expanding `{}! {{ {} }}`", name, pprust::tts_to_string(&arg));
446 trace_macros_note(&mut cx.expansions, sp, msg);
447 }
448
449 let try_success_result = try_match_macro(psess, name, &arg, rules, &mut NoopTracker);
451
452 match try_success_result {
453 Ok((rule_index, rule, named_matches)) => {
454 let MacroRule::Func { lhs, rhs, .. } = rule else {
455 panic!("try_match_macro returned non-func rule");
456 };
457 let mbe::TokenTree::Delimited(rhs_span, _, rhs) = rhs else {
458 cx.dcx().span_bug(sp, "malformed macro rhs");
459 };
460 let arm_span = rhs_span.entire();
461
462 let id = cx.current_expansion.id;
464 let tts = match transcribe(psess, &named_matches, rhs, *rhs_span, transparency, id) {
465 Ok(tts) => tts,
466 Err(err) => {
467 let guar = err.emit();
468 return DummyResult::any(arm_span, guar);
469 }
470 };
471
472 if cx.trace_macros() {
473 let msg = format!("to `{}`", pprust::tts_to_string(&tts));
474 trace_macros_note(&mut cx.expansions, sp, msg);
475 }
476
477 let is_local = is_defined_in_current_crate(node_id);
478 if is_local {
479 cx.resolver.record_macro_rule_usage(node_id, rule_index);
480 }
481
482 Box::new(ParserAnyMacro::from_tts(cx, tts, sp, arm_span, is_local, name, rules, lhs))
484 }
485 Err(CanRetry::No(guar)) => {
486 debug!("Will not retry matching as an error was emitted already");
487 DummyResult::any(sp, guar)
488 }
489 Err(CanRetry::Yes) => {
490 let (span, guar) = failed_to_match_macro(
492 cx.psess(),
493 sp,
494 def_span,
495 name,
496 FailedMacro::Func,
497 &arg,
498 rules,
499 on_unmatched_args,
500 );
501 cx.macro_error_and_trace_macros_diag();
502 DummyResult::any(span, guar)
503 }
504 }
505}
506
507#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("expand_macro_attr",
"rustc_expand::mbe::macro_rules", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_expand/src/mbe/macro_rules.rs"),
::tracing_core::__macro_support::Option::Some(508u32),
::tracing_core::__macro_support::Option::Some("rustc_expand::mbe::macro_rules"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("sp")
}> =
::tracing::__macro_support::FieldName::new("sp");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("def_span")
}> =
::tracing::__macro_support::FieldName::new("def_span");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("node_id")
}> =
::tracing::__macro_support::FieldName::new("node_id");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("name")
}> =
::tracing::__macro_support::FieldName::new("name");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("safety")
}> =
::tracing::__macro_support::FieldName::new("safety");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::INFO <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&sp)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_span)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&node_id)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&name)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&safety)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return:
Result<TokenStream, ErrorGuaranteed> = loop {};
return __tracing_attr_fake_return;
}
{
let psess = &cx.sess.psess;
let is_local = node_id != DUMMY_NODE_ID;
if !is_local && !cx.ecfg.features.macro_attr() {
feature_err(cx.sess, sym::macro_attr, sp,
"`macro_rules!` attributes are unstable").emit();
}
if cx.trace_macros() {
let msg =
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("expanding `#[{2}({0})] {1}`",
pprust::tts_to_string(&args), pprust::tts_to_string(&body),
name))
});
trace_macros_note(&mut cx.expansions, sp, msg);
}
match try_match_macro_attr(psess, name, &args, &body, rules,
&mut NoopTracker) {
Ok((i, rule, named_matches)) => {
let MacroRule::Attr { rhs, unsafe_rule, .. } =
rule else {
{
::core::panicking::panic_fmt(format_args!("try_macro_match_attr returned non-attr rule"));
};
};
let mbe::TokenTree::Delimited(rhs_span, _, rhs) =
rhs else { cx.dcx().span_bug(sp, "malformed macro rhs"); };
match (safety, unsafe_rule) {
(Safety::Default, false) | (Safety::Unsafe(_), true) => {}
(Safety::Default, true) => {
cx.dcx().span_err(sp,
"unsafe attribute invocation requires `unsafe`");
}
(Safety::Unsafe(span), false) => {
cx.dcx().span_err(span,
"unnecessary `unsafe` on safe attribute invocation");
}
(Safety::Safe(span), _) => {
cx.dcx().span_bug(span, "unexpected `safe` keyword");
}
}
let id = cx.current_expansion.id;
let tts =
transcribe(psess, &named_matches, rhs, *rhs_span,
transparency, id).map_err(|e| e.emit())?;
if cx.trace_macros() {
let msg =
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("to `{0}`",
pprust::tts_to_string(&tts)))
});
trace_macros_note(&mut cx.expansions, sp, msg);
}
if is_local {
cx.resolver.record_macro_rule_usage(node_id, i);
}
Ok(tts)
}
Err(CanRetry::No(guar)) => Err(guar),
Err(CanRetry::Yes) => {
let (_, guar) =
failed_to_match_macro(cx.psess(), sp, def_span, name,
FailedMacro::Attr(&args), &body, rules, on_unmatched_args);
cx.trace_macros_diag();
Err(guar)
}
}
}
}
}#[instrument(skip(cx, transparency, args, body, rules, on_unmatched_args))]
509fn expand_macro_attr(
510 cx: &mut ExtCtxt<'_>,
511 sp: Span,
512 def_span: Span,
513 node_id: NodeId,
514 name: Ident,
515 transparency: Transparency,
516 safety: Safety,
517 args: TokenStream,
518 body: TokenStream,
519 rules: &[MacroRule],
520 on_unmatched_args: Option<&Directive>,
521) -> Result<TokenStream, ErrorGuaranteed> {
522 let psess = &cx.sess.psess;
523 let is_local = node_id != DUMMY_NODE_ID;
526
527 if !is_local && !cx.ecfg.features.macro_attr() {
528 feature_err(cx.sess, sym::macro_attr, sp, "`macro_rules!` attributes are unstable").emit();
529 }
530
531 if cx.trace_macros() {
532 let msg = format!(
533 "expanding `#[{name}({})] {}`",
534 pprust::tts_to_string(&args),
535 pprust::tts_to_string(&body),
536 );
537 trace_macros_note(&mut cx.expansions, sp, msg);
538 }
539
540 match try_match_macro_attr(psess, name, &args, &body, rules, &mut NoopTracker) {
542 Ok((i, rule, named_matches)) => {
543 let MacroRule::Attr { rhs, unsafe_rule, .. } = rule else {
544 panic!("try_macro_match_attr returned non-attr rule");
545 };
546 let mbe::TokenTree::Delimited(rhs_span, _, rhs) = rhs else {
547 cx.dcx().span_bug(sp, "malformed macro rhs");
548 };
549
550 match (safety, unsafe_rule) {
551 (Safety::Default, false) | (Safety::Unsafe(_), true) => {}
552 (Safety::Default, true) => {
553 cx.dcx().span_err(sp, "unsafe attribute invocation requires `unsafe`");
554 }
555 (Safety::Unsafe(span), false) => {
556 cx.dcx().span_err(span, "unnecessary `unsafe` on safe attribute invocation");
557 }
558 (Safety::Safe(span), _) => {
559 cx.dcx().span_bug(span, "unexpected `safe` keyword");
560 }
561 }
562
563 let id = cx.current_expansion.id;
564 let tts = transcribe(psess, &named_matches, rhs, *rhs_span, transparency, id)
565 .map_err(|e| e.emit())?;
566
567 if cx.trace_macros() {
568 let msg = format!("to `{}`", pprust::tts_to_string(&tts));
569 trace_macros_note(&mut cx.expansions, sp, msg);
570 }
571
572 if is_local {
573 cx.resolver.record_macro_rule_usage(node_id, i);
574 }
575
576 Ok(tts)
577 }
578 Err(CanRetry::No(guar)) => Err(guar),
579 Err(CanRetry::Yes) => {
580 let (_, guar) = failed_to_match_macro(
582 cx.psess(),
583 sp,
584 def_span,
585 name,
586 FailedMacro::Attr(&args),
587 &body,
588 rules,
589 on_unmatched_args,
590 );
591 cx.trace_macros_diag();
592 Err(guar)
593 }
594 }
595}
596
597pub(super) enum CanRetry {
598 Yes,
599 No(ErrorGuaranteed),
601}
602
603#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("try_match_macro",
"rustc_expand::mbe::macro_rules", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_expand/src/mbe/macro_rules.rs"),
::tracing_core::__macro_support::Option::Some(606u32),
::tracing_core::__macro_support::Option::Some("rustc_expand::mbe::macro_rules"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("name")
}> =
::tracing::__macro_support::FieldName::new("name");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("tracking")
}> =
::tracing::__macro_support::FieldName::new("tracking");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&name)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::display(&T::description())
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return:
Result<(usize, &'matcher MacroRule, NamedMatches),
CanRetry> = loop {};
return __tracing_attr_fake_return;
}
{
let parser = parser_from_cx(psess, arg.clone(), T::recovery());
let mut tt_parser = TtParser::new();
for (i, rule) in rules.iter().enumerate() {
let MacroRule::Func { lhs, .. } = rule else { continue };
let _tracing_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("Matching arm",
"rustc_expand::mbe::macro_rules", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_expand/src/mbe/macro_rules.rs"),
::tracing_core::__macro_support::Option::Some(638u32),
::tracing_core::__macro_support::Option::Some("rustc_expand::mbe::macro_rules"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("i")
}> =
::tracing::__macro_support::FieldName::new("i");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::TRACE <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::display(&i)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
let mut gated_spans_snapshot =
mem::take(&mut *psess.gated_spans.spans.borrow_mut());
track.prepare(WhichMatcher::FOR_FUNC, lhs);
let result =
tt_parser.parse_tt(&mut Cow::Borrowed(&parser), lhs, track);
track.after_arm(&result);
match result {
Success(named_matches) => {
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_expand/src/mbe/macro_rules.rs:652",
"rustc_expand::mbe::macro_rules", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_expand/src/mbe/macro_rules.rs"),
::tracing_core::__macro_support::Option::Some(652u32),
::tracing_core::__macro_support::Option::Some("rustc_expand::mbe::macro_rules"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("Parsed arm successfully")
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
psess.gated_spans.merge(gated_spans_snapshot);
return Ok((i, rule, named_matches));
}
Failure => {
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_expand/src/mbe/macro_rules.rs:660",
"rustc_expand::mbe::macro_rules", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_expand/src/mbe/macro_rules.rs"),
::tracing_core::__macro_support::Option::Some(660u32),
::tracing_core::__macro_support::Option::Some("rustc_expand::mbe::macro_rules"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::TRACE <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("Failed to match arm, trying the next one")
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
}
Ambiguity => {
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_expand/src/mbe/macro_rules.rs:664",
"rustc_expand::mbe::macro_rules", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_expand/src/mbe/macro_rules.rs"),
::tracing_core::__macro_support::Option::Some(664u32),
::tracing_core::__macro_support::Option::Some("rustc_expand::mbe::macro_rules"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("Fatal error occurred during matching")
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
return Err(CanRetry::Yes);
}
ErrorReported(guarantee) => {
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_expand/src/mbe/macro_rules.rs:669",
"rustc_expand::mbe::macro_rules", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_expand/src/mbe/macro_rules.rs"),
::tracing_core::__macro_support::Option::Some(669u32),
::tracing_core::__macro_support::Option::Some("rustc_expand::mbe::macro_rules"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("Fatal error occurred and was reported during matching")
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
return Err(CanRetry::No(guarantee));
}
}
mem::swap(&mut gated_spans_snapshot,
&mut psess.gated_spans.spans.borrow_mut());
}
Err(CanRetry::Yes)
}
}
}#[instrument(level = "debug", skip(psess, arg, rules, track), fields(tracking = %T::description()))]
607pub(super) fn try_match_macro<'matcher, T: Tracker<'matcher>>(
608 psess: &ParseSess,
609 name: Ident,
610 arg: &TokenStream,
611 rules: &'matcher [MacroRule],
612 track: &mut T,
613) -> Result<(usize, &'matcher MacroRule, NamedMatches), CanRetry> {
614 let parser = parser_from_cx(psess, arg.clone(), T::recovery());
634 let mut tt_parser = TtParser::new();
636 for (i, rule) in rules.iter().enumerate() {
637 let MacroRule::Func { lhs, .. } = rule else { continue };
638 let _tracing_span = trace_span!("Matching arm", %i);
639
640 let mut gated_spans_snapshot = mem::take(&mut *psess.gated_spans.spans.borrow_mut());
645
646 track.prepare(WhichMatcher::FOR_FUNC, lhs);
647 let result = tt_parser.parse_tt(&mut Cow::Borrowed(&parser), lhs, track);
648 track.after_arm(&result);
649
650 match result {
651 Success(named_matches) => {
652 debug!("Parsed arm successfully");
653 psess.gated_spans.merge(gated_spans_snapshot);
656
657 return Ok((i, rule, named_matches));
658 }
659 Failure => {
660 trace!("Failed to match arm, trying the next one");
661 }
663 Ambiguity => {
664 debug!("Fatal error occurred during matching");
665 return Err(CanRetry::Yes);
667 }
668 ErrorReported(guarantee) => {
669 debug!("Fatal error occurred and was reported during matching");
670 return Err(CanRetry::No(guarantee));
672 }
673 }
674
675 mem::swap(&mut gated_spans_snapshot, &mut psess.gated_spans.spans.borrow_mut());
678 }
679
680 Err(CanRetry::Yes)
681}
682
683#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("try_match_macro_attr",
"rustc_expand::mbe::macro_rules", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_expand/src/mbe/macro_rules.rs"),
::tracing_core::__macro_support::Option::Some(686u32),
::tracing_core::__macro_support::Option::Some("rustc_expand::mbe::macro_rules"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("name")
}> =
::tracing::__macro_support::FieldName::new("name");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("tracking")
}> =
::tracing::__macro_support::FieldName::new("tracking");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&name)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::display(&T::description())
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return:
Result<(usize, &'matcher MacroRule, NamedMatches),
CanRetry> = loop {};
return __tracing_attr_fake_return;
}
{
let args_parser =
parser_from_cx(psess, attr_args.clone(), T::recovery());
let body_parser =
parser_from_cx(psess, attr_body.clone(), T::recovery());
let mut tt_parser = TtParser::new();
for (i, rule) in rules.iter().enumerate() {
let MacroRule::Attr { args, body, .. } =
rule else { continue };
let mut gated_spans_snapshot =
mem::take(&mut *psess.gated_spans.spans.borrow_mut());
track.prepare(WhichMatcher::Args, args);
let result =
tt_parser.parse_tt(&mut Cow::Borrowed(&args_parser), args,
track);
track.after_arm(&result);
let mut named_matches =
match result {
Success(named_matches) => named_matches,
Failure => {
mem::swap(&mut gated_spans_snapshot,
&mut psess.gated_spans.spans.borrow_mut());
continue;
}
Ambiguity => return Err(CanRetry::Yes),
ErrorReported(guar) => return Err(CanRetry::No(guar)),
};
track.prepare(WhichMatcher::Body, body);
let result =
tt_parser.parse_tt(&mut Cow::Borrowed(&body_parser), body,
track);
track.after_arm(&result);
match result {
Success(body_named_matches) => {
psess.gated_spans.merge(gated_spans_snapshot);
#[allow(rustc::potential_query_instability)]
named_matches.extend(body_named_matches);
return Ok((i, rule, named_matches));
}
Failure => {
mem::swap(&mut gated_spans_snapshot,
&mut psess.gated_spans.spans.borrow_mut())
}
Ambiguity => return Err(CanRetry::Yes),
ErrorReported(guar) => return Err(CanRetry::No(guar)),
}
}
Err(CanRetry::Yes)
}
}
}#[instrument(level = "debug", skip(psess, attr_args, attr_body, rules, track), fields(tracking = %T::description()))]
687pub(super) fn try_match_macro_attr<'matcher, T: Tracker<'matcher>>(
688 psess: &ParseSess,
689 name: Ident,
690 attr_args: &TokenStream,
691 attr_body: &TokenStream,
692 rules: &'matcher [MacroRule],
693 track: &mut T,
694) -> Result<(usize, &'matcher MacroRule, NamedMatches), CanRetry> {
695 let args_parser = parser_from_cx(psess, attr_args.clone(), T::recovery());
697 let body_parser = parser_from_cx(psess, attr_body.clone(), T::recovery());
698 let mut tt_parser = TtParser::new();
699 for (i, rule) in rules.iter().enumerate() {
700 let MacroRule::Attr { args, body, .. } = rule else { continue };
701
702 let mut gated_spans_snapshot = mem::take(&mut *psess.gated_spans.spans.borrow_mut());
703
704 track.prepare(WhichMatcher::Args, args);
705 let result = tt_parser.parse_tt(&mut Cow::Borrowed(&args_parser), args, track);
706 track.after_arm(&result);
707
708 let mut named_matches = match result {
709 Success(named_matches) => named_matches,
710 Failure => {
711 mem::swap(&mut gated_spans_snapshot, &mut psess.gated_spans.spans.borrow_mut());
712 continue;
713 }
714 Ambiguity => return Err(CanRetry::Yes),
715 ErrorReported(guar) => return Err(CanRetry::No(guar)),
716 };
717
718 track.prepare(WhichMatcher::Body, body);
719 let result = tt_parser.parse_tt(&mut Cow::Borrowed(&body_parser), body, track);
720 track.after_arm(&result);
721
722 match result {
723 Success(body_named_matches) => {
724 psess.gated_spans.merge(gated_spans_snapshot);
725 #[allow(rustc::potential_query_instability)]
726 named_matches.extend(body_named_matches);
727 return Ok((i, rule, named_matches));
728 }
729 Failure => {
730 mem::swap(&mut gated_spans_snapshot, &mut psess.gated_spans.spans.borrow_mut())
731 }
732 Ambiguity => return Err(CanRetry::Yes),
733 ErrorReported(guar) => return Err(CanRetry::No(guar)),
734 }
735 }
736
737 Err(CanRetry::Yes)
738}
739
740#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("try_match_macro_derive",
"rustc_expand::mbe::macro_rules", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_expand/src/mbe/macro_rules.rs"),
::tracing_core::__macro_support::Option::Some(743u32),
::tracing_core::__macro_support::Option::Some("rustc_expand::mbe::macro_rules"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("name")
}> =
::tracing::__macro_support::FieldName::new("name");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("tracking")
}> =
::tracing::__macro_support::FieldName::new("tracking");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&name)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::display(&T::description())
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return:
Result<(usize, &'matcher MacroRule, NamedMatches),
CanRetry> = loop {};
return __tracing_attr_fake_return;
}
{
let body_parser =
parser_from_cx(psess, body.clone(), T::recovery());
let mut tt_parser = TtParser::new();
for (i, rule) in rules.iter().enumerate() {
let MacroRule::Derive { body, .. } = rule else { continue };
let mut gated_spans_snapshot =
mem::take(&mut *psess.gated_spans.spans.borrow_mut());
track.prepare(WhichMatcher::FOR_DERIVE, body);
let result =
tt_parser.parse_tt(&mut Cow::Borrowed(&body_parser), body,
track);
track.after_arm(&result);
match result {
Success(named_matches) => {
psess.gated_spans.merge(gated_spans_snapshot);
return Ok((i, rule, named_matches));
}
Failure => {
mem::swap(&mut gated_spans_snapshot,
&mut psess.gated_spans.spans.borrow_mut())
}
Ambiguity => return Err(CanRetry::Yes),
ErrorReported(guar) => return Err(CanRetry::No(guar)),
}
}
Err(CanRetry::Yes)
}
}
}#[instrument(level = "debug", skip(psess, body, rules, track), fields(tracking = %T::description()))]
744pub(super) fn try_match_macro_derive<'matcher, T: Tracker<'matcher>>(
745 psess: &ParseSess,
746 name: Ident,
747 body: &TokenStream,
748 rules: &'matcher [MacroRule],
749 track: &mut T,
750) -> Result<(usize, &'matcher MacroRule, NamedMatches), CanRetry> {
751 let body_parser = parser_from_cx(psess, body.clone(), T::recovery());
753 let mut tt_parser = TtParser::new();
754 for (i, rule) in rules.iter().enumerate() {
755 let MacroRule::Derive { body, .. } = rule else { continue };
756
757 let mut gated_spans_snapshot = mem::take(&mut *psess.gated_spans.spans.borrow_mut());
758
759 track.prepare(WhichMatcher::FOR_DERIVE, body);
760 let result = tt_parser.parse_tt(&mut Cow::Borrowed(&body_parser), body, track);
761 track.after_arm(&result);
762
763 match result {
764 Success(named_matches) => {
765 psess.gated_spans.merge(gated_spans_snapshot);
766 return Ok((i, rule, named_matches));
767 }
768 Failure => {
769 mem::swap(&mut gated_spans_snapshot, &mut psess.gated_spans.spans.borrow_mut())
770 }
771 Ambiguity => return Err(CanRetry::Yes),
772 ErrorReported(guar) => return Err(CanRetry::No(guar)),
773 }
774 }
775
776 Err(CanRetry::Yes)
777}
778
779pub fn compile_declarative_macro(
781 sess: &Session,
782 features: &Features,
783 macro_def: &ast::MacroDef,
784 ident: Ident,
785 attrs: &[attrs::Attribute],
786 span: Span,
787 node_id: NodeId,
788 edition: Edition,
789) -> SyntaxExtension {
790 let mk_syn_ext = |kind| {
791 let is_local = is_defined_in_current_crate(node_id);
792 SyntaxExtension::new(sess, kind, span, Vec::new(), edition, ident.name, attrs, is_local)
793 };
794 let dummy_syn_ext = |guar| mk_syn_ext(SyntaxExtensionKind::Bang(Arc::new(DummyBang(guar))));
795
796 let macro_rules = macro_def.macro_rules;
797 let exp_sep = if macro_rules { ::rustc_parse::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Semi,
token_type: ::rustc_parse::parser::token_type::TokenType::Semi,
}exp!(Semi) } else { ::rustc_parse::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Comma,
token_type: ::rustc_parse::parser::token_type::TokenType::Comma,
}exp!(Comma) };
798
799 let body = macro_def.body.tokens.clone();
800 let mut p = Parser::new(&sess.psess, body, rustc_parse::MACRO_ARGUMENTS);
801
802 let mut guar = None;
805 let mut check_emission = |ret: Result<(), ErrorGuaranteed>| guar = guar.or(ret.err());
806
807 let mut kinds = MacroKinds::empty();
808 let mut rules = Vec::new();
809
810 while p.token != token::Eof {
811 let unsafe_rule = p.eat_keyword_noexpect(kw::Unsafe);
812 let unsafe_keyword_span = p.prev_token.span;
813 if unsafe_rule && let Some(guar) = check_no_eof(sess, &p, "expected `attr`") {
814 return dummy_syn_ext(guar);
815 }
816 let (args, is_derive) = if p.eat_keyword_noexpect(sym::attr) {
817 kinds |= MacroKinds::ATTR;
818 if is_defined_in_current_crate(node_id) && !features.macro_attr() {
819 feature_err(sess, sym::macro_attr, span, "`macro_rules!` attributes are unstable")
820 .emit();
821 }
822 if let Some(guar) = check_no_eof(sess, &p, "expected macro attr args") {
823 return dummy_syn_ext(guar);
824 }
825 let args = p.parse_token_tree();
826 check_args_parens(sess, sym::attr, &args);
827 let args = parse_one_tt(args, RulePart::Pattern, sess, node_id, features, edition);
828 check_emission(check_lhs(sess, features, node_id, &args));
829 if let Some(guar) = check_no_eof(sess, &p, "expected macro attr body") {
830 return dummy_syn_ext(guar);
831 }
832 (Some(args), false)
833 } else if p.eat_keyword_noexpect(sym::derive) {
834 kinds |= MacroKinds::DERIVE;
835 let derive_keyword_span = p.prev_token.span;
836 if !features.macro_derive() {
837 feature_err(sess, sym::macro_derive, span, "`macro_rules!` derives are unstable")
838 .emit();
839 }
840 if unsafe_rule {
841 sess.dcx()
842 .span_err(unsafe_keyword_span, "`unsafe` is only supported on `attr` rules");
843 }
844 if let Some(guar) = check_no_eof(sess, &p, "expected `()` after `derive`") {
845 return dummy_syn_ext(guar);
846 }
847 let args = p.parse_token_tree();
848 check_args_parens(sess, sym::derive, &args);
849 let args_empty_result = check_args_empty(sess, &args);
850 let args_not_empty = args_empty_result.is_err();
851 check_emission(args_empty_result);
852 if let Some(guar) = check_no_eof(sess, &p, "expected macro derive body") {
853 return dummy_syn_ext(guar);
854 }
855 if p.token == token::FatArrow {
858 let mut err = sess
859 .dcx()
860 .struct_span_err(p.token.span, "expected macro derive body, got `=>`");
861 if args_not_empty {
862 err.span_label(derive_keyword_span, "need `()` after this `derive`");
863 }
864 return dummy_syn_ext(err.emit());
865 }
866 (None, true)
867 } else {
868 kinds |= MacroKinds::BANG;
869 if unsafe_rule {
870 sess.dcx()
871 .span_err(unsafe_keyword_span, "`unsafe` is only supported on `attr` rules");
872 }
873 (None, false)
874 };
875 let lhs_tt = p.parse_token_tree();
876 let lhs_tt = parse_one_tt(lhs_tt, RulePart::Pattern, sess, node_id, features, edition);
877 check_emission(check_lhs(sess, features, node_id, &lhs_tt));
878 if let Err(e) = p.expect(::rustc_parse::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::FatArrow,
token_type: ::rustc_parse::parser::token_type::TokenType::FatArrow,
}exp!(FatArrow)) {
879 return dummy_syn_ext(e.emit());
880 }
881 if let Some(guar) = check_no_eof(sess, &p, "expected right-hand side of macro rule") {
882 return dummy_syn_ext(guar);
883 }
884 let rhs = p.parse_token_tree();
885 let rhs = parse_one_tt(rhs, RulePart::Body, sess, node_id, features, edition);
886 check_emission(check_rhs(sess, &rhs));
887 check_emission(check_meta_variables(&sess.psess, node_id, args.as_ref(), &lhs_tt, &rhs));
888 let lhs_span = lhs_tt.span();
889 let mbe::TokenTree::Delimited(.., delimited) = lhs_tt else {
892 return dummy_syn_ext(guar.unwrap());
893 };
894 let lhs = mbe::macro_parser::compute_locs(&delimited.tts);
895 if let Some(args) = args {
896 let args_span = args.span();
897 let mbe::TokenTree::Delimited(.., delimited) = args else {
898 return dummy_syn_ext(guar.unwrap());
899 };
900 let args = mbe::macro_parser::compute_locs(&delimited.tts);
901 let body_span = lhs_span;
902 rules.push(MacroRule::Attr { unsafe_rule, args, args_span, body: lhs, body_span, rhs });
903 } else if is_derive {
904 rules.push(MacroRule::Derive { body: lhs, body_span: lhs_span, rhs });
905 } else {
906 rules.push(MacroRule::Func { lhs, lhs_span, rhs });
907 }
908 if p.token == token::Eof {
909 break;
910 }
911 if let Err(e) = p.expect(exp_sep) {
912 return dummy_syn_ext(e.emit());
913 }
914 }
915
916 if rules.is_empty() {
917 let guar = sess.dcx().span_err(span, "macros must contain at least one rule");
918 return dummy_syn_ext(guar);
919 }
920 if !!kinds.is_empty() {
::core::panicking::panic("assertion failed: !kinds.is_empty()")
};assert!(!kinds.is_empty());
921
922 let transparency = {
'done:
{
for i in attrs {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(RustcMacroTransparency(x))
=> {
break 'done Some(*x);
}
::rustc_attr_ir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}find_attr!(attrs, RustcMacroTransparency(x) => *x)
923 .unwrap_or(Transparency::fallback(macro_rules));
924
925 if let Some(guar) = guar {
926 return dummy_syn_ext(guar);
929 }
930
931 let on_unmatched_args = {
'done:
{
for i in attrs {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(OnUnmatchedArgs {
directive, .. }) => {
break 'done Some(directive.clone());
}
::rustc_attr_ir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}find_attr!(
932 attrs,
933 OnUnmatchedArgs { directive, .. } => directive.clone()
934 )
935 .flatten()
936 .map(|directive| *directive);
937
938 let exp = MacroRulesMacroExpander {
939 name: ident,
940 kinds,
941 span,
942 node_id,
943 on_unmatched_args,
944 transparency,
945 rules,
946 macro_rules,
947 };
948 mk_syn_ext(SyntaxExtensionKind::MacroRules(Arc::new(exp)))
949}
950
951fn check_no_eof(sess: &Session, p: &Parser<'_>, msg: &'static str) -> Option<ErrorGuaranteed> {
952 if p.token == token::Eof {
953 let err_sp = p.token.span.shrink_to_hi();
954 let guar = sess
955 .dcx()
956 .struct_span_err(err_sp, "macro definition ended unexpectedly")
957 .with_span_label(err_sp, msg)
958 .emit();
959 return Some(guar);
960 }
961 None
962}
963
964fn check_args_parens(sess: &Session, rule_kw: Symbol, args: &tokenstream::TokenTree) {
965 if let tokenstream::TokenTree::Delimited(dspan, _, delim, _) = args
967 && *delim != Delimiter::Parenthesis
968 {
969 sess.dcx().emit_err(diagnostics::MacroArgsBadDelim {
970 span: dspan.entire(),
971 sugg: diagnostics::MacroArgsBadDelimSugg { open: dspan.open, close: dspan.close },
972 rule_kw,
973 });
974 }
975}
976
977fn check_args_empty(sess: &Session, args: &tokenstream::TokenTree) -> Result<(), ErrorGuaranteed> {
978 match args {
979 tokenstream::TokenTree::Delimited(.., delimited) if delimited.is_empty() => Ok(()),
980 _ => {
981 let msg = "`derive` rules do not accept arguments; `derive` must be followed by `()`";
982 Err(sess.dcx().span_err(args.span(), msg))
983 }
984 }
985}
986
987fn check_lhs(
988 sess: &Session,
989 features: &Features,
990 node_id: NodeId,
991 lhs: &mbe::TokenTree,
992) -> Result<(), ErrorGuaranteed> {
993 let e1 = check_lhs_nt_follows(sess, features, node_id, lhs);
994 let e2 = check_lhs_no_empty_seq(sess, slice::from_ref(lhs));
995 e1.and(e2)
996}
997
998fn check_lhs_nt_follows(
999 sess: &Session,
1000 features: &Features,
1001 node_id: NodeId,
1002 lhs: &mbe::TokenTree,
1003) -> Result<(), ErrorGuaranteed> {
1004 if let mbe::TokenTree::Delimited(.., delimited) = lhs {
1007 check_matcher(sess, features, node_id, &delimited.tts)
1008 } else {
1009 let msg = "invalid macro matcher; matchers must be contained in balanced delimiters";
1010 Err(sess.dcx().span_err(lhs.span(), msg))
1011 }
1012}
1013
1014fn is_empty_token_tree(sess: &Session, seq: &mbe::SequenceRepetition) -> bool {
1015 if seq.separator.is_some() {
1016 false
1017 } else {
1018 let mut is_empty = true;
1019 let mut iter = seq.tts.iter().peekable();
1020 while let Some(tt) = iter.next() {
1021 match tt {
1022 mbe::TokenTree::MetaVarDecl { kind: NonterminalKind::Vis, .. } => {}
1023 mbe::TokenTree::Token(t @ Token { kind: DocComment(..), .. }) => {
1024 let mut now = t;
1025 while let Some(&mbe::TokenTree::Token(
1026 next @ Token { kind: DocComment(..), .. },
1027 )) = iter.peek()
1028 {
1029 now = next;
1030 iter.next();
1031 }
1032 let span = t.span.to(now.span);
1033 sess.dcx().span_note(span, "doc comments are ignored in matcher position");
1034 }
1035 mbe::TokenTree::Sequence(_, sub_seq)
1036 if (sub_seq.kleene.op == mbe::KleeneOp::ZeroOrMore
1037 || sub_seq.kleene.op == mbe::KleeneOp::ZeroOrOne) => {}
1038 _ => is_empty = false,
1039 }
1040 }
1041 is_empty
1042 }
1043}
1044
1045fn check_redundant_vis_repetition(
1050 err: &mut Diag<'_>,
1051 sess: &Session,
1052 seq: &SequenceRepetition,
1053 span: &DelimSpan,
1054) {
1055 if seq.kleene.op == KleeneOp::ZeroOrOne
1056 && #[allow(non_exhaustive_omitted_patterns)] match seq.tts.first() {
Some(mbe::TokenTree::MetaVarDecl { kind: NonterminalKind::Vis, .. }) =>
true,
_ => false,
}matches!(
1057 seq.tts.first(),
1058 Some(mbe::TokenTree::MetaVarDecl { kind: NonterminalKind::Vis, .. })
1059 )
1060 {
1061 err.note("a `vis` fragment can already be empty");
1062 err.multipart_suggestion(
1063 "remove the `$(` and `)?`",
1064 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(sess.source_map().span_extend_to_prev_char_before(span.open, '$',
true), "".to_string()),
(span.close.with_hi(seq.kleene.span.hi()), "".to_string())]))vec![
1065 (
1066 sess.source_map().span_extend_to_prev_char_before(span.open, '$', true),
1067 "".to_string(),
1068 ),
1069 (span.close.with_hi(seq.kleene.span.hi()), "".to_string()),
1070 ],
1071 Applicability::MaybeIncorrect,
1072 );
1073 }
1074}
1075
1076fn check_lhs_no_empty_seq(sess: &Session, tts: &[mbe::TokenTree]) -> Result<(), ErrorGuaranteed> {
1079 use mbe::TokenTree;
1080 for tt in tts {
1081 match tt {
1082 TokenTree::Token(..)
1083 | TokenTree::MetaVar(..)
1084 | TokenTree::MetaVarDecl { .. }
1085 | TokenTree::MetaVarExpr(..) => (),
1086 TokenTree::Delimited(.., del) => check_lhs_no_empty_seq(sess, &del.tts)?,
1087 TokenTree::Sequence(span, seq) => {
1088 if is_empty_token_tree(sess, seq) {
1089 let sp = span.entire();
1090 let mut err =
1091 sess.dcx().struct_span_err(sp, "repetition matches empty token tree");
1092 check_redundant_vis_repetition(&mut err, sess, seq, span);
1093 return Err(err.emit());
1094 }
1095 check_lhs_no_empty_seq(sess, &seq.tts)?
1096 }
1097 }
1098 }
1099
1100 Ok(())
1101}
1102
1103fn check_rhs(sess: &Session, rhs: &mbe::TokenTree) -> Result<(), ErrorGuaranteed> {
1104 match *rhs {
1105 mbe::TokenTree::Delimited(..) => Ok(()),
1106 _ => Err(sess.dcx().span_err(rhs.span(), "macro rhs must be delimited")),
1107 }
1108}
1109
1110fn check_matcher(
1111 sess: &Session,
1112 features: &Features,
1113 node_id: NodeId,
1114 matcher: &[mbe::TokenTree],
1115) -> Result<(), ErrorGuaranteed> {
1116 let first_sets = FirstSets::new(matcher);
1117 let empty_suffix = TokenSet::empty();
1118 check_matcher_core(sess, features, node_id, &first_sets, matcher, &empty_suffix)?;
1119 Ok(())
1120}
1121
1122fn has_compile_error_macro(rhs: &mbe::TokenTree) -> bool {
1123 match rhs {
1124 mbe::TokenTree::Delimited(.., d) => {
1125 let has_compile_error = d.tts.array_windows::<3>().any(|[ident, bang, args]| {
1126 if let mbe::TokenTree::Token(ident) = ident
1127 && let TokenKind::Ident(ident, _) = ident.kind
1128 && ident == sym::compile_error
1129 && let mbe::TokenTree::Token(bang) = bang
1130 && let TokenKind::Bang = bang.kind
1131 && let mbe::TokenTree::Delimited(.., del) = args
1132 && !del.delim.skip()
1133 {
1134 true
1135 } else {
1136 false
1137 }
1138 });
1139 if has_compile_error { true } else { d.tts.iter().any(has_compile_error_macro) }
1140 }
1141 _ => false,
1142 }
1143}
1144
1145struct FirstSets<'tt> {
1158 first: FxHashMap<Span, Option<TokenSet<'tt>>>,
1165}
1166
1167impl<'tt> FirstSets<'tt> {
1168 fn new(tts: &'tt [mbe::TokenTree]) -> FirstSets<'tt> {
1169 use mbe::TokenTree;
1170
1171 let mut sets = FirstSets { first: FxHashMap::default() };
1172 build_recur(&mut sets, tts);
1173 return sets;
1174
1175 fn build_recur<'tt>(sets: &mut FirstSets<'tt>, tts: &'tt [TokenTree]) -> TokenSet<'tt> {
1179 let mut first = TokenSet::empty();
1180 for tt in tts.iter().rev() {
1181 match tt {
1182 TokenTree::Token(..)
1183 | TokenTree::MetaVar(..)
1184 | TokenTree::MetaVarDecl { .. }
1185 | TokenTree::MetaVarExpr(..) => {
1186 first.replace_with(TtHandle::TtRef(tt));
1187 }
1188 TokenTree::Delimited(span, _, delimited) => {
1189 build_recur(sets, &delimited.tts);
1190 first.replace_with(TtHandle::from_token_kind(
1191 delimited.delim.as_open_token_kind(),
1192 span.open,
1193 ));
1194 }
1195 TokenTree::Sequence(sp, seq_rep) => {
1196 let subfirst = build_recur(sets, &seq_rep.tts);
1197
1198 match sets.first.entry(sp.entire()) {
1199 Entry::Vacant(vac) => {
1200 vac.insert(Some(subfirst.clone()));
1201 }
1202 Entry::Occupied(mut occ) => {
1203 occ.insert(None);
1210 }
1211 }
1212
1213 if let (Some(sep), true) = (&seq_rep.separator, subfirst.maybe_empty) {
1217 first.add_one_maybe(TtHandle::from_token(*sep));
1218 }
1219
1220 if subfirst.maybe_empty
1222 || seq_rep.kleene.op == mbe::KleeneOp::ZeroOrMore
1223 || seq_rep.kleene.op == mbe::KleeneOp::ZeroOrOne
1224 {
1225 first.add_all(&TokenSet { maybe_empty: true, ..subfirst });
1228 } else {
1229 first = subfirst;
1232 }
1233 }
1234 }
1235 }
1236
1237 first
1238 }
1239 }
1240
1241 fn first(&self, tts: &'tt [mbe::TokenTree]) -> TokenSet<'tt> {
1244 use mbe::TokenTree;
1245
1246 let mut first = TokenSet::empty();
1247 for tt in tts.iter() {
1248 if !first.maybe_empty {
::core::panicking::panic("assertion failed: first.maybe_empty")
};assert!(first.maybe_empty);
1249 match tt {
1250 TokenTree::Token(..)
1251 | TokenTree::MetaVar(..)
1252 | TokenTree::MetaVarDecl { .. }
1253 | TokenTree::MetaVarExpr(..) => {
1254 first.add_one(TtHandle::TtRef(tt));
1255 return first;
1256 }
1257 TokenTree::Delimited(span, _, delimited) => {
1258 first.add_one(TtHandle::from_token_kind(
1259 delimited.delim.as_open_token_kind(),
1260 span.open,
1261 ));
1262 return first;
1263 }
1264 TokenTree::Sequence(sp, seq_rep) => {
1265 let subfirst_owned;
1266 let subfirst = match self.first.get(&sp.entire()) {
1267 Some(Some(subfirst)) => subfirst,
1268 Some(&None) => {
1269 subfirst_owned = self.first(&seq_rep.tts);
1270 &subfirst_owned
1271 }
1272 None => {
1273 {
::core::panicking::panic_fmt(format_args!("We missed a sequence during FirstSets construction"));
};panic!("We missed a sequence during FirstSets construction");
1274 }
1275 };
1276
1277 if let (Some(sep), true) = (&seq_rep.separator, subfirst.maybe_empty) {
1280 first.add_one_maybe(TtHandle::from_token(*sep));
1281 }
1282
1283 if !first.maybe_empty {
::core::panicking::panic("assertion failed: first.maybe_empty")
};assert!(first.maybe_empty);
1284 first.add_all(subfirst);
1285 if subfirst.maybe_empty
1286 || seq_rep.kleene.op == mbe::KleeneOp::ZeroOrMore
1287 || seq_rep.kleene.op == mbe::KleeneOp::ZeroOrOne
1288 {
1289 first.maybe_empty = true;
1293 continue;
1294 } else {
1295 return first;
1296 }
1297 }
1298 }
1299 }
1300
1301 if !first.maybe_empty {
::core::panicking::panic("assertion failed: first.maybe_empty")
};assert!(first.maybe_empty);
1304 first
1305 }
1306}
1307
1308#[derive(#[automatically_derived]
impl<'tt> ::core::fmt::Debug for TtHandle<'tt> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
TtHandle::TtRef(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "TtRef",
&__self_0),
TtHandle::Token(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Token",
&__self_0),
}
}
}Debug)]
1313enum TtHandle<'tt> {
1314 TtRef(&'tt mbe::TokenTree),
1316
1317 Token(mbe::TokenTree),
1322}
1323
1324impl<'tt> TtHandle<'tt> {
1325 fn from_token(tok: Token) -> Self {
1326 TtHandle::Token(mbe::TokenTree::Token(tok))
1327 }
1328
1329 fn from_token_kind(kind: TokenKind, span: Span) -> Self {
1330 TtHandle::from_token(Token::new(kind, span))
1331 }
1332
1333 fn get(&'tt self) -> &'tt mbe::TokenTree {
1335 match self {
1336 TtHandle::TtRef(tt) => tt,
1337 TtHandle::Token(token_tt) => token_tt,
1338 }
1339 }
1340}
1341
1342impl<'tt> PartialEq for TtHandle<'tt> {
1343 fn eq(&self, other: &TtHandle<'tt>) -> bool {
1344 self.get() == other.get()
1345 }
1346}
1347
1348impl<'tt> Clone for TtHandle<'tt> {
1349 fn clone(&self) -> Self {
1350 match self {
1351 TtHandle::TtRef(tt) => TtHandle::TtRef(tt),
1352
1353 TtHandle::Token(mbe::TokenTree::Token(tok)) => {
1356 TtHandle::Token(mbe::TokenTree::Token(*tok))
1357 }
1358
1359 _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1360 }
1361 }
1362}
1363
1364#[derive(#[automatically_derived]
impl<'tt> ::core::clone::Clone for TokenSet<'tt> {
#[inline]
fn clone(&self) -> TokenSet<'tt> {
TokenSet {
tokens: ::core::clone::Clone::clone(&self.tokens),
maybe_empty: ::core::clone::Clone::clone(&self.maybe_empty),
}
}
}Clone, #[automatically_derived]
impl<'tt> ::core::fmt::Debug for TokenSet<'tt> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f, "TokenSet",
"tokens", &self.tokens, "maybe_empty", &&self.maybe_empty)
}
}Debug)]
1375struct TokenSet<'tt> {
1376 tokens: Vec<TtHandle<'tt>>,
1377 maybe_empty: bool,
1378}
1379
1380impl<'tt> TokenSet<'tt> {
1381 fn empty() -> Self {
1383 TokenSet { tokens: Vec::new(), maybe_empty: true }
1384 }
1385
1386 fn singleton(tt: TtHandle<'tt>) -> Self {
1389 TokenSet { tokens: ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[tt]))vec![tt], maybe_empty: false }
1390 }
1391
1392 fn replace_with(&mut self, tt: TtHandle<'tt>) {
1395 self.tokens.clear();
1396 self.tokens.push(tt);
1397 self.maybe_empty = false;
1398 }
1399
1400 fn replace_with_irrelevant(&mut self) {
1404 self.tokens.clear();
1405 self.maybe_empty = false;
1406 }
1407
1408 fn add_one(&mut self, tt: TtHandle<'tt>) {
1410 if !self.tokens.contains(&tt) {
1411 self.tokens.push(tt);
1412 }
1413 self.maybe_empty = false;
1414 }
1415
1416 fn add_one_maybe(&mut self, tt: TtHandle<'tt>) {
1418 if !self.tokens.contains(&tt) {
1419 self.tokens.push(tt);
1420 }
1421 }
1422
1423 fn add_all(&mut self, other: &Self) {
1431 for tt in &other.tokens {
1432 if !self.tokens.contains(tt) {
1433 self.tokens.push(tt.clone());
1434 }
1435 }
1436 if !other.maybe_empty {
1437 self.maybe_empty = false;
1438 }
1439 }
1440}
1441
1442fn check_matcher_core<'tt>(
1454 sess: &Session,
1455 features: &Features,
1456 node_id: NodeId,
1457 first_sets: &FirstSets<'tt>,
1458 matcher: &'tt [mbe::TokenTree],
1459 follow: &TokenSet<'tt>,
1460) -> Result<TokenSet<'tt>, ErrorGuaranteed> {
1461 use mbe::TokenTree;
1462
1463 let mut last = TokenSet::empty();
1464
1465 let mut errored = Ok(());
1466
1467 'each_token: for i in 0..matcher.len() {
1471 let token = &matcher[i];
1472 let suffix = &matcher[i + 1..];
1473
1474 let build_suffix_first = || {
1475 let mut s = first_sets.first(suffix);
1476 if s.maybe_empty {
1477 s.add_all(follow);
1478 }
1479 s
1480 };
1481
1482 let suffix_first;
1486
1487 match token {
1490 TokenTree::Token(..)
1491 | TokenTree::MetaVar(..)
1492 | TokenTree::MetaVarDecl { .. }
1493 | TokenTree::MetaVarExpr(..) => {
1494 if let TokenTree::MetaVarDecl { kind: NonterminalKind::Guard, .. } = token
1495 && !features.macro_guard_matcher()
1496 {
1497 feature_err(
1498 sess,
1499 sym::macro_guard_matcher,
1500 token.span(),
1501 "`guard` fragments in macro are unstable",
1502 )
1503 .emit();
1504 }
1505 if token_can_be_followed_by_any(token) {
1506 last.replace_with_irrelevant();
1508 continue 'each_token;
1511 } else {
1512 last.replace_with(TtHandle::TtRef(token));
1513 suffix_first = build_suffix_first();
1514 }
1515 }
1516 TokenTree::Delimited(span, _, d) => {
1517 let my_suffix = TokenSet::singleton(TtHandle::from_token_kind(
1518 d.delim.as_close_token_kind(),
1519 span.close,
1520 ));
1521 check_matcher_core(sess, features, node_id, first_sets, &d.tts, &my_suffix)?;
1522 last.replace_with_irrelevant();
1524
1525 continue 'each_token;
1528 }
1529 TokenTree::Sequence(_, seq_rep) => {
1530 suffix_first = build_suffix_first();
1531 let mut new;
1542 let my_suffix = if let Some(sep) = &seq_rep.separator {
1543 new = suffix_first.clone();
1544 new.add_one_maybe(TtHandle::from_token(*sep));
1545 &new
1546 } else {
1547 &suffix_first
1548 };
1549
1550 let next = check_matcher_core(
1554 sess,
1555 features,
1556 node_id,
1557 first_sets,
1558 &seq_rep.tts,
1559 my_suffix,
1560 )?;
1561 if next.maybe_empty {
1562 last.add_all(&next);
1563 } else {
1564 last = next;
1565 }
1566
1567 continue 'each_token;
1570 }
1571 }
1572
1573 for tt in &last.tokens {
1578 if let &TokenTree::MetaVarDecl { span, name, kind } = tt.get() {
1579 for next_token in &suffix_first.tokens {
1580 let next_token = next_token.get();
1581
1582 if is_defined_in_current_crate(node_id)
1589 && #[allow(non_exhaustive_omitted_patterns)] match kind {
NonterminalKind::Pat(PatParam { inferred: true }) => true,
_ => false,
}matches!(kind, NonterminalKind::Pat(PatParam { inferred: true }))
1590 && #[allow(non_exhaustive_omitted_patterns)] match next_token {
TokenTree::Token(token) if *token == token::Or => true,
_ => false,
}matches!(
1591 next_token,
1592 TokenTree::Token(token) if *token == token::Or
1593 )
1594 {
1595 let suggestion = quoted_tt_to_string(&TokenTree::MetaVarDecl {
1597 span,
1598 name,
1599 kind: NonterminalKind::Pat(PatParam { inferred: false }),
1600 });
1601 sess.psess.buffer_lint(
1602 RUST_2021_INCOMPATIBLE_OR_PATTERNS,
1603 span,
1604 ast::CRATE_NODE_ID,
1605 diagnostics::OrPatternsBackCompat { span, suggestion },
1606 );
1607 }
1608 match is_in_follow(next_token, kind) {
1609 IsInFollow::Yes => {}
1610 IsInFollow::No(possible) => {
1611 let may_be = if last.tokens.len() == 1 && suffix_first.tokens.len() == 1
1612 {
1613 "is"
1614 } else {
1615 "may be"
1616 };
1617
1618 let sp = next_token.span();
1619 let mut err = sess.dcx().struct_span_err(
1620 sp,
1621 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`${0}:{1}` {3} followed by `{2}`, which is not allowed for `{1}` fragments",
name, kind, quoted_tt_to_string(next_token), may_be))
})format!(
1622 "`${name}:{frag}` {may_be} followed by `{next}`, which \
1623 is not allowed for `{frag}` fragments",
1624 name = name,
1625 frag = kind,
1626 next = quoted_tt_to_string(next_token),
1627 may_be = may_be
1628 ),
1629 );
1630 err.span_label(sp, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("not allowed after `{0}` fragments",
kind))
})format!("not allowed after `{kind}` fragments"));
1631
1632 if kind == NonterminalKind::Pat(PatWithOr)
1633 && sess.psess.edition.at_least_rust_2021()
1634 && next_token.is_token(&token::Or)
1635 {
1636 let suggestion = quoted_tt_to_string(&TokenTree::MetaVarDecl {
1637 span,
1638 name,
1639 kind: NonterminalKind::Pat(PatParam { inferred: false }),
1640 });
1641 err.span_suggestion(
1642 span,
1643 "try a `pat_param` fragment specifier instead",
1644 suggestion,
1645 Applicability::MaybeIncorrect,
1646 );
1647 }
1648
1649 let msg = "allowed there are: ";
1650 match possible {
1651 &[] => {}
1652 &[t] => {
1653 err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("only {0} is allowed after `{1}` fragments",
t, kind))
})format!(
1654 "only {t} is allowed after `{kind}` fragments",
1655 ));
1656 }
1657 ts => {
1658 err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1} or {2}", msg,
ts[..ts.len() - 1].to_vec().join(", "), ts[ts.len() - 1]))
})format!(
1659 "{}{} or {}",
1660 msg,
1661 ts[..ts.len() - 1].to_vec().join(", "),
1662 ts[ts.len() - 1],
1663 ));
1664 }
1665 }
1666 errored = Err(err.emit());
1667 }
1668 }
1669 }
1670 }
1671 }
1672 }
1673 errored?;
1674 Ok(last)
1675}
1676
1677fn token_can_be_followed_by_any(tok: &mbe::TokenTree) -> bool {
1678 if let mbe::TokenTree::MetaVarDecl { kind, .. } = *tok {
1679 frag_can_be_followed_by_any(kind)
1680 } else {
1681 true
1683 }
1684}
1685
1686fn frag_can_be_followed_by_any(kind: NonterminalKind) -> bool {
1695 #[allow(non_exhaustive_omitted_patterns)] match kind {
NonterminalKind::Item | NonterminalKind::Block | NonterminalKind::Ident |
NonterminalKind::Literal | NonterminalKind::Meta |
NonterminalKind::Lifetime | NonterminalKind::TT => true,
_ => false,
}matches!(
1696 kind,
1697 NonterminalKind::Item | NonterminalKind::Block | NonterminalKind::Ident | NonterminalKind::Literal | NonterminalKind::Meta | NonterminalKind::Lifetime | NonterminalKind::TT )
1705}
1706
1707enum IsInFollow {
1708 Yes,
1709 No(&'static [&'static str]),
1710}
1711
1712fn is_in_follow(tok: &mbe::TokenTree, kind: NonterminalKind) -> IsInFollow {
1721 use mbe::TokenTree;
1722
1723 if let TokenTree::Token(Token { kind, .. }) = tok
1724 && kind.close_delim().is_some()
1725 {
1726 IsInFollow::Yes
1729 } else {
1730 match kind {
1731 NonterminalKind::Item => {
1732 IsInFollow::Yes
1735 }
1736 NonterminalKind::Block => {
1737 IsInFollow::Yes
1740 }
1741 NonterminalKind::Stmt | NonterminalKind::Expr(_) => {
1742 const TOKENS: &[&str] = &["`=>`", "`,`", "`;`"];
1743 match tok {
1744 TokenTree::Token(token) => match token.kind {
1745 FatArrow | Comma | Semi => IsInFollow::Yes,
1746 _ => IsInFollow::No(TOKENS),
1747 },
1748 _ => IsInFollow::No(TOKENS),
1749 }
1750 }
1751 NonterminalKind::Pat(PatParam { .. }) => {
1752 const TOKENS: &[&str] = &["`=>`", "`,`", "`=`", "`|`", "`if`", "`if let`", "`in`"];
1753 match tok {
1754 TokenTree::Token(token) => match token.kind {
1755 FatArrow | Comma | Eq | Or => IsInFollow::Yes,
1756 Ident(name, IdentIsRaw::No) if name == kw::If || name == kw::In => {
1757 IsInFollow::Yes
1758 }
1759 _ => IsInFollow::No(TOKENS),
1760 },
1761 TokenTree::MetaVarDecl { kind: NonterminalKind::Guard, .. } => IsInFollow::Yes,
1762 _ => IsInFollow::No(TOKENS),
1763 }
1764 }
1765 NonterminalKind::Pat(PatWithOr) => {
1766 const TOKENS: &[&str] = &["`=>`", "`,`", "`=`", "`if`", "`if let`", "`in`"];
1767 match tok {
1768 TokenTree::Token(token) => match token.kind {
1769 FatArrow | Comma | Eq => IsInFollow::Yes,
1770 Ident(name, IdentIsRaw::No) if name == kw::If || name == kw::In => {
1771 IsInFollow::Yes
1772 }
1773 _ => IsInFollow::No(TOKENS),
1774 },
1775 TokenTree::MetaVarDecl { kind: NonterminalKind::Guard, .. } => IsInFollow::Yes,
1776 _ => IsInFollow::No(TOKENS),
1777 }
1778 }
1779 NonterminalKind::Guard => {
1780 const TOKENS: &[&str] = &["`=>`", "`,`", "`{`"];
1781 match tok {
1782 TokenTree::Token(token) => match token.kind {
1783 FatArrow | Comma | OpenBrace => IsInFollow::Yes,
1784 _ => IsInFollow::No(TOKENS),
1785 },
1786 _ => IsInFollow::No(TOKENS),
1787 }
1788 }
1789 NonterminalKind::Path | NonterminalKind::Ty => {
1790 const TOKENS: &[&str] = &[
1791 "`{`", "`[`", "`=>`", "`,`", "`>`", "`=`", "`:`", "`;`", "`|`", "`as`",
1792 "`where`",
1793 ];
1794 match tok {
1795 TokenTree::Token(token) => match token.kind {
1796 OpenBrace | OpenBracket | Comma | FatArrow | Colon | Eq | Gt | Shr
1797 | Semi | Or => IsInFollow::Yes,
1798 Ident(name, IdentIsRaw::No) if name == kw::As || name == kw::Where => {
1799 IsInFollow::Yes
1800 }
1801 _ => IsInFollow::No(TOKENS),
1802 },
1803 TokenTree::MetaVarDecl { kind: NonterminalKind::Block, .. } => IsInFollow::Yes,
1804 _ => IsInFollow::No(TOKENS),
1805 }
1806 }
1807 NonterminalKind::Ident | NonterminalKind::Lifetime => {
1808 IsInFollow::Yes
1810 }
1811 NonterminalKind::Literal => {
1812 IsInFollow::Yes
1814 }
1815 NonterminalKind::Meta | NonterminalKind::TT => {
1816 IsInFollow::Yes
1819 }
1820 NonterminalKind::Vis => {
1821 const TOKENS: &[&str] = &["`,`", "an ident", "a type"];
1823 match tok {
1824 TokenTree::Token(token) => match token.kind {
1825 Comma => IsInFollow::Yes,
1826 Ident(_, IdentIsRaw::Yes) => IsInFollow::Yes,
1827 Ident(name, _) if name != kw::Priv => IsInFollow::Yes,
1828 _ => {
1829 if token.can_begin_type() {
1830 IsInFollow::Yes
1831 } else {
1832 IsInFollow::No(TOKENS)
1833 }
1834 }
1835 },
1836 TokenTree::MetaVarDecl {
1837 kind: NonterminalKind::Ident | NonterminalKind::Ty | NonterminalKind::Path,
1838 ..
1839 } => IsInFollow::Yes,
1840 _ => IsInFollow::No(TOKENS),
1841 }
1842 }
1843 }
1844 }
1845}
1846
1847fn quoted_tt_to_string(tt: &mbe::TokenTree) -> String {
1848 match tt {
1849 mbe::TokenTree::Token(token) => pprust::token_to_string(token).into(),
1850 mbe::TokenTree::MetaVar(_, name) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("${0}", name))
})format!("${name}"),
1851 mbe::TokenTree::MetaVarDecl { name, kind, .. } => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("${0}:{1}", name, kind))
})format!("${name}:{kind}"),
1852 _ => {
::core::panicking::panic_display(&"unexpected mbe::TokenTree::{Sequence or Delimited} \
in follow set checker");
}panic!(
1853 "{}",
1854 "unexpected mbe::TokenTree::{Sequence or Delimited} \
1855 in follow set checker"
1856 ),
1857 }
1858}
1859
1860fn is_defined_in_current_crate(node_id: NodeId) -> bool {
1861 node_id != DUMMY_NODE_ID
1864}
1865
1866pub(super) fn parser_from_cx(
1867 psess: &ParseSess,
1868 mut tts: TokenStream,
1869 recovery: Recovery,
1870) -> Parser<'_> {
1871 tts.desugar_doc_comments();
1872 Parser::new(psess, tts, rustc_parse::MACRO_ARGUMENTS).recovery(recovery)
1873}