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