1use std::path::PathBuf;
2use std::rc::Rc;
3use std::sync::Arc;
4use std::{iter, mem, slice};
5
6use rustc_ast::mut_visit::*;
7use rustc_ast::tokenstream::TokenStream;
8use rustc_ast::visit::{AssocCtxt, Visitor, VisitorResult, try_visit, walk_list};
9use rustc_ast::{
10 self as ast, AssocItemKind, AstNodeWrapper, AttrArgs, AttrKind, AttrStyle, AttrVec,
11 DUMMY_NODE_ID, DelegationSource, DelegationSuffixes, ExprKind, ForeignItemKind, HasAttrs,
12 HasNodeId, Inline, ItemKind, MacStmtStyle, MetaItemInner, MetaItemKind, ModKind, NodeId,
13 PatKind, StmtKind, SyntheticAttr, TyKind, token,
14};
15use rustc_ast_pretty::pprust;
16use rustc_attr_ir::target::{AstTarget, Target};
17use rustc_attr_parsing::parser::AllowExprMetavar;
18use rustc_attr_parsing::{
19 AttributeParser, AttributeSafety, CFG_TEMPLATE, EvalConfigResult, ShouldEmit,
20 eval_config_entry, parse_cfg, validate_attr,
21};
22use rustc_data_structures::flat_map_in_place::FlatMapInPlace;
23use rustc_errors::PResult;
24use rustc_feature::Features;
25use rustc_hir::def::MacroKinds;
26use rustc_parse::parser::{
27 AllowConstBlockItems, AttemptLocalParseRecovery, CommaRecoveryMode, ForceCollect, Parser,
28 RecoverColon, RecoverComma, Recovery, token_descr,
29};
30use rustc_session::diagnostics::feature_err;
31use rustc_span::hygiene::SyntaxContext;
32use rustc_span::{ErrorGuaranteed, FileName, Ident, LocalExpnId, Span, Symbol, sym};
33use rustc_structures::Limit;
34use smallvec::SmallVec;
35
36use crate::base::*;
37use crate::config::StripUnconfigured;
38use crate::diagnostics::{
39 CfgNotSupportedInPosition, EmptyDelegationMac, GlobDelegationOutsideImpls,
40 GlobDelegationTraitlessQpath, IncompleteParse, RecursionLimitReached, RemoveExprNotSupported,
41 UnsupportedKeyValue, WrongFragmentKind,
42};
43use crate::module::{
44 DirOwnership, ParsedExternalMod, mod_dir_path, mod_file_path_from_attr, parse_external_mod,
45};
46use crate::placeholders::{PlaceholderExpander, placeholder};
47use crate::stats::*;
48
49macro_rules! ast_fragments {
50 (
51 $($Kind:ident($AstTy:ty) {
52 $kind_name:expr;
53 $(one
54 fn $visit_ast:ident;
55 )?
56 $(many
57 fn $flat_map_ast_elt:ident;
58 fn $visit_ast_elt:ident($($args:tt)*);
59 )?
60 fn $make_ast:ident;
61 })*
62 ) => {
63 pub enum AstFragment {
66 OptExpr(Option<Box<ast::Expr>>),
67 MethodReceiverExpr(Box<ast::Expr>),
68 $($Kind($AstTy),)*
69 }
70
71 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
73 pub enum AstFragmentKind {
74 OptExpr,
75 MethodReceiverExpr,
76 $($Kind,)*
77 }
78
79 impl AstFragmentKind {
80 pub fn name(self) -> &'static str {
81 match self {
82 AstFragmentKind::OptExpr => "expression",
83 AstFragmentKind::MethodReceiverExpr => "expression",
84 $(AstFragmentKind::$Kind => $kind_name,)*
85 }
86 }
87
88 fn make_from(self, result: Box<dyn MacResult + '_>) -> Option<AstFragment> {
89 match self {
90 AstFragmentKind::OptExpr =>
91 result.make_expr().map(Some).map(AstFragment::OptExpr),
92 AstFragmentKind::MethodReceiverExpr =>
93 result.make_expr().map(AstFragment::MethodReceiverExpr),
94 $(AstFragmentKind::$Kind => result.$make_ast().map(AstFragment::$Kind),)*
95 }
96 }
97 }
98
99 impl AstFragment {
100 fn add_placeholders(&mut self, placeholders: &[NodeId]) {
101 if placeholders.is_empty() {
102 return;
103 }
104 match self {
105 $($(AstFragment::$Kind(ast) => ast.extend(placeholders.iter().flat_map(|id| {
106 ${ignore($flat_map_ast_elt)}
107 placeholder(AstFragmentKind::$Kind, *id, None).$make_ast()
108 })),)?)*
109 _ => panic!("unexpected AST fragment kind")
110 }
111 }
112
113 pub(crate) fn make_opt_expr(self) -> Option<Box<ast::Expr>> {
114 match self {
115 AstFragment::OptExpr(expr) => expr,
116 _ => panic!("AstFragment::make_opt_expr called on the wrong kind of fragment"),
117 }
118 }
119
120 pub(crate) fn make_method_receiver_expr(self) -> Box<ast::Expr> {
121 match self {
122 AstFragment::MethodReceiverExpr(expr) => expr,
123 _ => panic!("AstFragment::make_method_receiver_expr called on the wrong kind of fragment"),
124 }
125 }
126
127 $(pub fn $make_ast(self) -> $AstTy {
128 match self {
129 AstFragment::$Kind(ast) => ast,
130 _ => panic!("AstFragment::{} called on the wrong kind of fragment", stringify!($make_ast)),
131 }
132 })*
133
134 fn make_ast<T: InvocationCollectorNode>(self) -> T::OutputTy {
135 T::fragment_to_output(self)
136 }
137
138 pub(crate) fn mut_visit_with(&mut self, vis: &mut impl MutVisitor) {
139 match self {
140 AstFragment::OptExpr(opt_expr) => {
141 if let Some(expr) = opt_expr.take() {
142 *opt_expr = vis.filter_map_expr(expr)
143 }
144 }
145 AstFragment::MethodReceiverExpr(expr) => vis.visit_method_receiver_expr(expr),
146 $($(AstFragment::$Kind(ast) => vis.$visit_ast(ast),)?)*
147 $($(AstFragment::$Kind(ast) =>
148 ast.flat_map_in_place(|ast| vis.$flat_map_ast_elt(ast, $($args)*)),)?)*
149 }
150 }
151
152 pub fn visit_with<'a, V: Visitor<'a>>(&'a self, visitor: &mut V) -> V::Result {
153 match self {
154 AstFragment::OptExpr(Some(expr)) => try_visit!(visitor.visit_expr(expr)),
155 AstFragment::OptExpr(None) => {}
156 AstFragment::MethodReceiverExpr(expr) => try_visit!(visitor.visit_method_receiver_expr(expr)),
157 $($(AstFragment::$Kind(ast) => try_visit!(visitor.$visit_ast(ast)),)?)*
158 $($(AstFragment::$Kind(ast) => walk_list!(visitor, $visit_ast_elt, &ast[..], $($args)*),)?)*
159 }
160 V::Result::output()
161 }
162 }
163
164 impl<'a, 'b> MacResult for crate::mbe::macro_rules::ParserAnyMacro<'a, 'b> {
165 $(fn $make_ast(self: Box<crate::mbe::macro_rules::ParserAnyMacro<'a, 'b>>)
166 -> Option<$AstTy> {
167 Some(self.make(AstFragmentKind::$Kind).$make_ast())
168 })*
169 }
170 }
171}
172
173pub enum AstFragment {
OptExpr(Option<Box<ast::Expr>>),
MethodReceiverExpr(Box<ast::Expr>),
Expr(Box<ast::Expr>),
Pat(Box<ast::Pat>),
Ty(Box<ast::Ty>),
Stmts(SmallVec<[ast::Stmt; 1]>),
Items(SmallVec<[Box<ast::Item>; 1]>),
TraitItems(SmallVec<[Box<ast::AssocItem>; 1]>),
ImplItems(SmallVec<[Box<ast::AssocItem>; 1]>),
TraitImplItems(SmallVec<[Box<ast::AssocItem>; 1]>),
ForeignItems(SmallVec<[Box<ast::ForeignItem>; 1]>),
Arms(SmallVec<[ast::Arm; 1]>),
ExprFields(SmallVec<[ast::ExprField; 1]>),
PatFields(SmallVec<[ast::PatField; 1]>),
GenericParams(SmallVec<[ast::GenericParam; 1]>),
Params(SmallVec<[ast::Param; 1]>),
FieldDefs(SmallVec<[ast::FieldDef; 1]>),
Variants(SmallVec<[ast::Variant; 1]>),
WherePredicates(SmallVec<[ast::WherePredicate; 1]>),
Crate(ast::Crate),
}
pub enum AstFragmentKind {
OptExpr,
MethodReceiverExpr,
Expr,
Pat,
Ty,
Stmts,
Items,
TraitItems,
ImplItems,
TraitImplItems,
ForeignItems,
Arms,
ExprFields,
PatFields,
GenericParams,
Params,
FieldDefs,
Variants,
WherePredicates,
Crate,
}
#[automatically_derived]impl ::core::marker::Copy for AstFragmentKind { }
#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for AstFragmentKind {
}
#[automatically_derived]impl ::core::clone::Clone for AstFragmentKind {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self { *self }
}
#[automatically_derived]impl ::core::fmt::Debug for AstFragmentKind {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_c_like_enum_write_str(f,
"OptExpr MethodReceiverExpr Expr Pat Ty Stmts Items TraitItems ImplItems TraitImplItems ForeignItems Arms ExprFields PatFields GenericParams Params FieldDefs Variants WherePredicates Crate",
match self {
AstFragmentKind::OptExpr => 0usize,
AstFragmentKind::MethodReceiverExpr => 8usize,
AstFragmentKind::Expr => 27usize,
AstFragmentKind::Pat => 32usize,
AstFragmentKind::Ty => 36usize,
AstFragmentKind::Stmts => 39usize,
AstFragmentKind::Items => 45usize,
AstFragmentKind::TraitItems => 51usize,
AstFragmentKind::ImplItems => 62usize,
AstFragmentKind::TraitImplItems => 72usize,
AstFragmentKind::ForeignItems => 87usize,
AstFragmentKind::Arms => 100usize,
AstFragmentKind::ExprFields => 105usize,
AstFragmentKind::PatFields => 116usize,
AstFragmentKind::GenericParams => 126usize,
AstFragmentKind::Params => 140usize,
AstFragmentKind::FieldDefs => 147usize,
AstFragmentKind::Variants => 157usize,
AstFragmentKind::WherePredicates => 166usize,
AstFragmentKind::Crate => 182usize,
})
}
}
#[automatically_derived]impl ::core::marker::StructuralPartialEq for
AstFragmentKind {
}
#[automatically_derived]impl ::core::cmp::PartialEq for AstFragmentKind {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other)
}
}
#[automatically_derived]impl ::core::cmp::Eq for AstFragmentKind { }
impl AstFragmentKind {
pub fn name(self) -> &'static str {
match self {
AstFragmentKind::OptExpr => "expression",
AstFragmentKind::MethodReceiverExpr => "expression",
AstFragmentKind::Expr => "expression",
AstFragmentKind::Pat => "pattern",
AstFragmentKind::Ty => "type",
AstFragmentKind::Stmts => "statement",
AstFragmentKind::Items => "item",
AstFragmentKind::TraitItems => "trait item",
AstFragmentKind::ImplItems => "impl item",
AstFragmentKind::TraitImplItems => "impl item",
AstFragmentKind::ForeignItems => "foreign item",
AstFragmentKind::Arms => "match arm",
AstFragmentKind::ExprFields => "field expression",
AstFragmentKind::PatFields => "field pattern",
AstFragmentKind::GenericParams => "generic parameter",
AstFragmentKind::Params => "function parameter",
AstFragmentKind::FieldDefs => "field",
AstFragmentKind::Variants => "variant",
AstFragmentKind::WherePredicates => "where predicate",
AstFragmentKind::Crate => "crate",
}
}
fn make_from(self, result: Box<dyn MacResult + '_>)
-> Option<AstFragment> {
match self {
AstFragmentKind::OptExpr =>
result.make_expr().map(Some).map(AstFragment::OptExpr),
AstFragmentKind::MethodReceiverExpr =>
result.make_expr().map(AstFragment::MethodReceiverExpr),
AstFragmentKind::Expr =>
result.make_expr().map(AstFragment::Expr),
AstFragmentKind::Pat => result.make_pat().map(AstFragment::Pat),
AstFragmentKind::Ty => result.make_ty().map(AstFragment::Ty),
AstFragmentKind::Stmts =>
result.make_stmts().map(AstFragment::Stmts),
AstFragmentKind::Items =>
result.make_items().map(AstFragment::Items),
AstFragmentKind::TraitItems =>
result.make_trait_items().map(AstFragment::TraitItems),
AstFragmentKind::ImplItems =>
result.make_impl_items().map(AstFragment::ImplItems),
AstFragmentKind::TraitImplItems =>
result.make_trait_impl_items().map(AstFragment::TraitImplItems),
AstFragmentKind::ForeignItems =>
result.make_foreign_items().map(AstFragment::ForeignItems),
AstFragmentKind::Arms =>
result.make_arms().map(AstFragment::Arms),
AstFragmentKind::ExprFields =>
result.make_expr_fields().map(AstFragment::ExprFields),
AstFragmentKind::PatFields =>
result.make_pat_fields().map(AstFragment::PatFields),
AstFragmentKind::GenericParams =>
result.make_generic_params().map(AstFragment::GenericParams),
AstFragmentKind::Params =>
result.make_params().map(AstFragment::Params),
AstFragmentKind::FieldDefs =>
result.make_field_defs().map(AstFragment::FieldDefs),
AstFragmentKind::Variants =>
result.make_variants().map(AstFragment::Variants),
AstFragmentKind::WherePredicates =>
result.make_where_predicates().map(AstFragment::WherePredicates),
AstFragmentKind::Crate =>
result.make_crate().map(AstFragment::Crate),
}
}
}
impl AstFragment {
fn add_placeholders(&mut self, placeholders: &[NodeId]) {
if placeholders.is_empty() { return; }
match self {
AstFragment::Stmts(ast) =>
ast.extend(placeholders.iter().flat_map(|id|
{
placeholder(AstFragmentKind::Stmts, *id, None).make_stmts()
})),
AstFragment::Items(ast) =>
ast.extend(placeholders.iter().flat_map(|id|
{
placeholder(AstFragmentKind::Items, *id, None).make_items()
})),
AstFragment::TraitItems(ast) =>
ast.extend(placeholders.iter().flat_map(|id|
{
placeholder(AstFragmentKind::TraitItems, *id,
None).make_trait_items()
})),
AstFragment::ImplItems(ast) =>
ast.extend(placeholders.iter().flat_map(|id|
{
placeholder(AstFragmentKind::ImplItems, *id,
None).make_impl_items()
})),
AstFragment::TraitImplItems(ast) =>
ast.extend(placeholders.iter().flat_map(|id|
{
placeholder(AstFragmentKind::TraitImplItems, *id,
None).make_trait_impl_items()
})),
AstFragment::ForeignItems(ast) =>
ast.extend(placeholders.iter().flat_map(|id|
{
placeholder(AstFragmentKind::ForeignItems, *id,
None).make_foreign_items()
})),
AstFragment::Arms(ast) =>
ast.extend(placeholders.iter().flat_map(|id|
{
placeholder(AstFragmentKind::Arms, *id, None).make_arms()
})),
AstFragment::ExprFields(ast) =>
ast.extend(placeholders.iter().flat_map(|id|
{
placeholder(AstFragmentKind::ExprFields, *id,
None).make_expr_fields()
})),
AstFragment::PatFields(ast) =>
ast.extend(placeholders.iter().flat_map(|id|
{
placeholder(AstFragmentKind::PatFields, *id,
None).make_pat_fields()
})),
AstFragment::GenericParams(ast) =>
ast.extend(placeholders.iter().flat_map(|id|
{
placeholder(AstFragmentKind::GenericParams, *id,
None).make_generic_params()
})),
AstFragment::Params(ast) =>
ast.extend(placeholders.iter().flat_map(|id|
{
placeholder(AstFragmentKind::Params, *id,
None).make_params()
})),
AstFragment::FieldDefs(ast) =>
ast.extend(placeholders.iter().flat_map(|id|
{
placeholder(AstFragmentKind::FieldDefs, *id,
None).make_field_defs()
})),
AstFragment::Variants(ast) =>
ast.extend(placeholders.iter().flat_map(|id|
{
placeholder(AstFragmentKind::Variants, *id,
None).make_variants()
})),
AstFragment::WherePredicates(ast) =>
ast.extend(placeholders.iter().flat_map(|id|
{
placeholder(AstFragmentKind::WherePredicates, *id,
None).make_where_predicates()
})),
_ => {
::core::panicking::panic_fmt(format_args!("unexpected AST fragment kind"));
}
}
}
pub(crate) fn make_opt_expr(self) -> Option<Box<ast::Expr>> {
match self {
AstFragment::OptExpr(expr) => expr,
_ => {
::core::panicking::panic_fmt(format_args!("AstFragment::make_opt_expr called on the wrong kind of fragment"));
}
}
}
pub(crate) fn make_method_receiver_expr(self) -> Box<ast::Expr> {
match self {
AstFragment::MethodReceiverExpr(expr) => expr,
_ => {
::core::panicking::panic_fmt(format_args!("AstFragment::make_method_receiver_expr called on the wrong kind of fragment"));
}
}
}
pub fn make_expr(self) -> Box<ast::Expr> {
match self {
AstFragment::Expr(ast) => ast,
_ => {
::core::panicking::panic_fmt(format_args!("AstFragment::{0} called on the wrong kind of fragment",
"make_expr"));
}
}
}
pub fn make_pat(self) -> Box<ast::Pat> {
match self {
AstFragment::Pat(ast) => ast,
_ => {
::core::panicking::panic_fmt(format_args!("AstFragment::{0} called on the wrong kind of fragment",
"make_pat"));
}
}
}
pub fn make_ty(self) -> Box<ast::Ty> {
match self {
AstFragment::Ty(ast) => ast,
_ => {
::core::panicking::panic_fmt(format_args!("AstFragment::{0} called on the wrong kind of fragment",
"make_ty"));
}
}
}
pub fn make_stmts(self) -> SmallVec<[ast::Stmt; 1]> {
match self {
AstFragment::Stmts(ast) => ast,
_ => {
::core::panicking::panic_fmt(format_args!("AstFragment::{0} called on the wrong kind of fragment",
"make_stmts"));
}
}
}
pub fn make_items(self) -> SmallVec<[Box<ast::Item>; 1]> {
match self {
AstFragment::Items(ast) => ast,
_ => {
::core::panicking::panic_fmt(format_args!("AstFragment::{0} called on the wrong kind of fragment",
"make_items"));
}
}
}
pub fn make_trait_items(self) -> SmallVec<[Box<ast::AssocItem>; 1]> {
match self {
AstFragment::TraitItems(ast) => ast,
_ => {
::core::panicking::panic_fmt(format_args!("AstFragment::{0} called on the wrong kind of fragment",
"make_trait_items"));
}
}
}
pub fn make_impl_items(self) -> SmallVec<[Box<ast::AssocItem>; 1]> {
match self {
AstFragment::ImplItems(ast) => ast,
_ => {
::core::panicking::panic_fmt(format_args!("AstFragment::{0} called on the wrong kind of fragment",
"make_impl_items"));
}
}
}
pub fn make_trait_impl_items(self) -> SmallVec<[Box<ast::AssocItem>; 1]> {
match self {
AstFragment::TraitImplItems(ast) => ast,
_ => {
::core::panicking::panic_fmt(format_args!("AstFragment::{0} called on the wrong kind of fragment",
"make_trait_impl_items"));
}
}
}
pub fn make_foreign_items(self) -> SmallVec<[Box<ast::ForeignItem>; 1]> {
match self {
AstFragment::ForeignItems(ast) => ast,
_ => {
::core::panicking::panic_fmt(format_args!("AstFragment::{0} called on the wrong kind of fragment",
"make_foreign_items"));
}
}
}
pub fn make_arms(self) -> SmallVec<[ast::Arm; 1]> {
match self {
AstFragment::Arms(ast) => ast,
_ => {
::core::panicking::panic_fmt(format_args!("AstFragment::{0} called on the wrong kind of fragment",
"make_arms"));
}
}
}
pub fn make_expr_fields(self) -> SmallVec<[ast::ExprField; 1]> {
match self {
AstFragment::ExprFields(ast) => ast,
_ => {
::core::panicking::panic_fmt(format_args!("AstFragment::{0} called on the wrong kind of fragment",
"make_expr_fields"));
}
}
}
pub fn make_pat_fields(self) -> SmallVec<[ast::PatField; 1]> {
match self {
AstFragment::PatFields(ast) => ast,
_ => {
::core::panicking::panic_fmt(format_args!("AstFragment::{0} called on the wrong kind of fragment",
"make_pat_fields"));
}
}
}
pub fn make_generic_params(self) -> SmallVec<[ast::GenericParam; 1]> {
match self {
AstFragment::GenericParams(ast) => ast,
_ => {
::core::panicking::panic_fmt(format_args!("AstFragment::{0} called on the wrong kind of fragment",
"make_generic_params"));
}
}
}
pub fn make_params(self) -> SmallVec<[ast::Param; 1]> {
match self {
AstFragment::Params(ast) => ast,
_ => {
::core::panicking::panic_fmt(format_args!("AstFragment::{0} called on the wrong kind of fragment",
"make_params"));
}
}
}
pub fn make_field_defs(self) -> SmallVec<[ast::FieldDef; 1]> {
match self {
AstFragment::FieldDefs(ast) => ast,
_ => {
::core::panicking::panic_fmt(format_args!("AstFragment::{0} called on the wrong kind of fragment",
"make_field_defs"));
}
}
}
pub fn make_variants(self) -> SmallVec<[ast::Variant; 1]> {
match self {
AstFragment::Variants(ast) => ast,
_ => {
::core::panicking::panic_fmt(format_args!("AstFragment::{0} called on the wrong kind of fragment",
"make_variants"));
}
}
}
pub fn make_where_predicates(self) -> SmallVec<[ast::WherePredicate; 1]> {
match self {
AstFragment::WherePredicates(ast) => ast,
_ => {
::core::panicking::panic_fmt(format_args!("AstFragment::{0} called on the wrong kind of fragment",
"make_where_predicates"));
}
}
}
pub fn make_crate(self) -> ast::Crate {
match self {
AstFragment::Crate(ast) => ast,
_ => {
::core::panicking::panic_fmt(format_args!("AstFragment::{0} called on the wrong kind of fragment",
"make_crate"));
}
}
}
fn make_ast<T: InvocationCollectorNode>(self) -> T::OutputTy {
T::fragment_to_output(self)
}
pub(crate) fn mut_visit_with(&mut self, vis: &mut impl MutVisitor) {
match self {
AstFragment::OptExpr(opt_expr) => {
if let Some(expr) = opt_expr.take() {
*opt_expr = vis.filter_map_expr(expr)
}
}
AstFragment::MethodReceiverExpr(expr) =>
vis.visit_method_receiver_expr(expr),
AstFragment::Expr(ast) => vis.visit_expr(ast),
AstFragment::Pat(ast) => vis.visit_pat(ast),
AstFragment::Ty(ast) => vis.visit_ty(ast),
AstFragment::Crate(ast) => vis.visit_crate(ast),
AstFragment::Stmts(ast) =>
ast.flat_map_in_place(|ast| vis.flat_map_stmt(ast)),
AstFragment::Items(ast) =>
ast.flat_map_in_place(|ast| vis.flat_map_item(ast)),
AstFragment::TraitItems(ast) =>
ast.flat_map_in_place(|ast|
vis.flat_map_assoc_item(ast, AssocCtxt::Trait)),
AstFragment::ImplItems(ast) =>
ast.flat_map_in_place(|ast|
vis.flat_map_assoc_item(ast,
AssocCtxt::Impl { of_trait: false })),
AstFragment::TraitImplItems(ast) =>
ast.flat_map_in_place(|ast|
vis.flat_map_assoc_item(ast,
AssocCtxt::Impl { of_trait: true })),
AstFragment::ForeignItems(ast) =>
ast.flat_map_in_place(|ast| vis.flat_map_foreign_item(ast)),
AstFragment::Arms(ast) =>
ast.flat_map_in_place(|ast| vis.flat_map_arm(ast)),
AstFragment::ExprFields(ast) =>
ast.flat_map_in_place(|ast| vis.flat_map_expr_field(ast)),
AstFragment::PatFields(ast) =>
ast.flat_map_in_place(|ast| vis.flat_map_pat_field(ast)),
AstFragment::GenericParams(ast) =>
ast.flat_map_in_place(|ast| vis.flat_map_generic_param(ast)),
AstFragment::Params(ast) =>
ast.flat_map_in_place(|ast| vis.flat_map_param(ast)),
AstFragment::FieldDefs(ast) =>
ast.flat_map_in_place(|ast| vis.flat_map_field_def(ast)),
AstFragment::Variants(ast) =>
ast.flat_map_in_place(|ast| vis.flat_map_variant(ast)),
AstFragment::WherePredicates(ast) =>
ast.flat_map_in_place(|ast|
vis.flat_map_where_predicate(ast)),
}
}
pub fn visit_with<'a, V: Visitor<'a>>(&'a self, visitor: &mut V)
-> V::Result {
match self {
AstFragment::OptExpr(Some(expr)) =>
match ::rustc_ast_ir::visit::VisitorResult::branch(visitor.visit_expr(expr))
{
core::ops::ControlFlow::Continue(()) =>
(),
#[allow(unreachable_code)]
core::ops::ControlFlow::Break(r) => {
return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
}
},
AstFragment::OptExpr(None) => {}
AstFragment::MethodReceiverExpr(expr) =>
match ::rustc_ast_ir::visit::VisitorResult::branch(visitor.visit_method_receiver_expr(expr))
{
core::ops::ControlFlow::Continue(()) =>
(),
#[allow(unreachable_code)]
core::ops::ControlFlow::Break(r) => {
return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
}
},
AstFragment::Expr(ast) =>
match ::rustc_ast_ir::visit::VisitorResult::branch(visitor.visit_expr(ast))
{
core::ops::ControlFlow::Continue(()) =>
(),
#[allow(unreachable_code)]
core::ops::ControlFlow::Break(r) => {
return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
}
},
AstFragment::Pat(ast) =>
match ::rustc_ast_ir::visit::VisitorResult::branch(visitor.visit_pat(ast))
{
core::ops::ControlFlow::Continue(()) =>
(),
#[allow(unreachable_code)]
core::ops::ControlFlow::Break(r) => {
return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
}
},
AstFragment::Ty(ast) =>
match ::rustc_ast_ir::visit::VisitorResult::branch(visitor.visit_ty(ast))
{
core::ops::ControlFlow::Continue(()) =>
(),
#[allow(unreachable_code)]
core::ops::ControlFlow::Break(r) => {
return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
}
},
AstFragment::Crate(ast) =>
match ::rustc_ast_ir::visit::VisitorResult::branch(visitor.visit_crate(ast))
{
core::ops::ControlFlow::Continue(()) =>
(),
#[allow(unreachable_code)]
core::ops::ControlFlow::Break(r) => {
return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
}
},
AstFragment::Stmts(ast) =>
for elem in &ast[..] {
match ::rustc_ast_ir::visit::VisitorResult::branch(visitor.visit_stmt(elem))
{
core::ops::ControlFlow::Continue(()) =>
(),
#[allow(unreachable_code)]
core::ops::ControlFlow::Break(r) => {
return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
}
};
},
AstFragment::Items(ast) =>
for elem in &ast[..] {
match ::rustc_ast_ir::visit::VisitorResult::branch(visitor.visit_item(elem))
{
core::ops::ControlFlow::Continue(()) =>
(),
#[allow(unreachable_code)]
core::ops::ControlFlow::Break(r) => {
return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
}
};
},
AstFragment::TraitItems(ast) =>
for elem in &ast[..] {
match ::rustc_ast_ir::visit::VisitorResult::branch(visitor.visit_assoc_item(elem,
AssocCtxt::Trait)) {
core::ops::ControlFlow::Continue(()) =>
(),
#[allow(unreachable_code)]
core::ops::ControlFlow::Break(r) => {
return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
}
};
},
AstFragment::ImplItems(ast) =>
for elem in &ast[..] {
match ::rustc_ast_ir::visit::VisitorResult::branch(visitor.visit_assoc_item(elem,
AssocCtxt::Impl { of_trait: false })) {
core::ops::ControlFlow::Continue(()) =>
(),
#[allow(unreachable_code)]
core::ops::ControlFlow::Break(r) => {
return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
}
};
},
AstFragment::TraitImplItems(ast) =>
for elem in &ast[..] {
match ::rustc_ast_ir::visit::VisitorResult::branch(visitor.visit_assoc_item(elem,
AssocCtxt::Impl { of_trait: true })) {
core::ops::ControlFlow::Continue(()) =>
(),
#[allow(unreachable_code)]
core::ops::ControlFlow::Break(r) => {
return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
}
};
},
AstFragment::ForeignItems(ast) =>
for elem in &ast[..] {
match ::rustc_ast_ir::visit::VisitorResult::branch(visitor.visit_foreign_item(elem))
{
core::ops::ControlFlow::Continue(()) =>
(),
#[allow(unreachable_code)]
core::ops::ControlFlow::Break(r) => {
return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
}
};
},
AstFragment::Arms(ast) =>
for elem in &ast[..] {
match ::rustc_ast_ir::visit::VisitorResult::branch(visitor.visit_arm(elem))
{
core::ops::ControlFlow::Continue(()) =>
(),
#[allow(unreachable_code)]
core::ops::ControlFlow::Break(r) => {
return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
}
};
},
AstFragment::ExprFields(ast) =>
for elem in &ast[..] {
match ::rustc_ast_ir::visit::VisitorResult::branch(visitor.visit_expr_field(elem))
{
core::ops::ControlFlow::Continue(()) =>
(),
#[allow(unreachable_code)]
core::ops::ControlFlow::Break(r) => {
return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
}
};
},
AstFragment::PatFields(ast) =>
for elem in &ast[..] {
match ::rustc_ast_ir::visit::VisitorResult::branch(visitor.visit_pat_field(elem))
{
core::ops::ControlFlow::Continue(()) =>
(),
#[allow(unreachable_code)]
core::ops::ControlFlow::Break(r) => {
return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
}
};
},
AstFragment::GenericParams(ast) =>
for elem in &ast[..] {
match ::rustc_ast_ir::visit::VisitorResult::branch(visitor.visit_generic_param(elem))
{
core::ops::ControlFlow::Continue(()) =>
(),
#[allow(unreachable_code)]
core::ops::ControlFlow::Break(r) => {
return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
}
};
},
AstFragment::Params(ast) =>
for elem in &ast[..] {
match ::rustc_ast_ir::visit::VisitorResult::branch(visitor.visit_param(elem))
{
core::ops::ControlFlow::Continue(()) =>
(),
#[allow(unreachable_code)]
core::ops::ControlFlow::Break(r) => {
return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
}
};
},
AstFragment::FieldDefs(ast) =>
for elem in &ast[..] {
match ::rustc_ast_ir::visit::VisitorResult::branch(visitor.visit_field_def(elem))
{
core::ops::ControlFlow::Continue(()) =>
(),
#[allow(unreachable_code)]
core::ops::ControlFlow::Break(r) => {
return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
}
};
},
AstFragment::Variants(ast) =>
for elem in &ast[..] {
match ::rustc_ast_ir::visit::VisitorResult::branch(visitor.visit_variant(elem))
{
core::ops::ControlFlow::Continue(()) =>
(),
#[allow(unreachable_code)]
core::ops::ControlFlow::Break(r) => {
return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
}
};
},
AstFragment::WherePredicates(ast) =>
for elem in &ast[..] {
match ::rustc_ast_ir::visit::VisitorResult::branch(visitor.visit_where_predicate(elem))
{
core::ops::ControlFlow::Continue(()) =>
(),
#[allow(unreachable_code)]
core::ops::ControlFlow::Break(r) => {
return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
}
};
},
}
V::Result::output()
}
}
impl<'a, 'b> MacResult for crate::mbe::macro_rules::ParserAnyMacro<'a, 'b> {
fn make_expr(self: Box<crate::mbe::macro_rules::ParserAnyMacro<'a, 'b>>)
-> Option<Box<ast::Expr>> {
Some(self.make(AstFragmentKind::Expr).make_expr())
}
fn make_pat(self: Box<crate::mbe::macro_rules::ParserAnyMacro<'a, 'b>>)
-> Option<Box<ast::Pat>> {
Some(self.make(AstFragmentKind::Pat).make_pat())
}
fn make_ty(self: Box<crate::mbe::macro_rules::ParserAnyMacro<'a, 'b>>)
-> Option<Box<ast::Ty>> {
Some(self.make(AstFragmentKind::Ty).make_ty())
}
fn make_stmts(self: Box<crate::mbe::macro_rules::ParserAnyMacro<'a, 'b>>)
-> Option<SmallVec<[ast::Stmt; 1]>> {
Some(self.make(AstFragmentKind::Stmts).make_stmts())
}
fn make_items(self: Box<crate::mbe::macro_rules::ParserAnyMacro<'a, 'b>>)
-> Option<SmallVec<[Box<ast::Item>; 1]>> {
Some(self.make(AstFragmentKind::Items).make_items())
}
fn make_trait_items(self:
Box<crate::mbe::macro_rules::ParserAnyMacro<'a, 'b>>)
-> Option<SmallVec<[Box<ast::AssocItem>; 1]>> {
Some(self.make(AstFragmentKind::TraitItems).make_trait_items())
}
fn make_impl_items(self:
Box<crate::mbe::macro_rules::ParserAnyMacro<'a, 'b>>)
-> Option<SmallVec<[Box<ast::AssocItem>; 1]>> {
Some(self.make(AstFragmentKind::ImplItems).make_impl_items())
}
fn make_trait_impl_items(self:
Box<crate::mbe::macro_rules::ParserAnyMacro<'a, 'b>>)
-> Option<SmallVec<[Box<ast::AssocItem>; 1]>> {
Some(self.make(AstFragmentKind::TraitImplItems).make_trait_impl_items())
}
fn make_foreign_items(self:
Box<crate::mbe::macro_rules::ParserAnyMacro<'a, 'b>>)
-> Option<SmallVec<[Box<ast::ForeignItem>; 1]>> {
Some(self.make(AstFragmentKind::ForeignItems).make_foreign_items())
}
fn make_arms(self: Box<crate::mbe::macro_rules::ParserAnyMacro<'a, 'b>>)
-> Option<SmallVec<[ast::Arm; 1]>> {
Some(self.make(AstFragmentKind::Arms).make_arms())
}
fn make_expr_fields(self:
Box<crate::mbe::macro_rules::ParserAnyMacro<'a, 'b>>)
-> Option<SmallVec<[ast::ExprField; 1]>> {
Some(self.make(AstFragmentKind::ExprFields).make_expr_fields())
}
fn make_pat_fields(self:
Box<crate::mbe::macro_rules::ParserAnyMacro<'a, 'b>>)
-> Option<SmallVec<[ast::PatField; 1]>> {
Some(self.make(AstFragmentKind::PatFields).make_pat_fields())
}
fn make_generic_params(self:
Box<crate::mbe::macro_rules::ParserAnyMacro<'a, 'b>>)
-> Option<SmallVec<[ast::GenericParam; 1]>> {
Some(self.make(AstFragmentKind::GenericParams).make_generic_params())
}
fn make_params(self: Box<crate::mbe::macro_rules::ParserAnyMacro<'a, 'b>>)
-> Option<SmallVec<[ast::Param; 1]>> {
Some(self.make(AstFragmentKind::Params).make_params())
}
fn make_field_defs(self:
Box<crate::mbe::macro_rules::ParserAnyMacro<'a, 'b>>)
-> Option<SmallVec<[ast::FieldDef; 1]>> {
Some(self.make(AstFragmentKind::FieldDefs).make_field_defs())
}
fn make_variants(self:
Box<crate::mbe::macro_rules::ParserAnyMacro<'a, 'b>>)
-> Option<SmallVec<[ast::Variant; 1]>> {
Some(self.make(AstFragmentKind::Variants).make_variants())
}
fn make_where_predicates(self:
Box<crate::mbe::macro_rules::ParserAnyMacro<'a, 'b>>)
-> Option<SmallVec<[ast::WherePredicate; 1]>> {
Some(self.make(AstFragmentKind::WherePredicates).make_where_predicates())
}
fn make_crate(self: Box<crate::mbe::macro_rules::ParserAnyMacro<'a, 'b>>)
-> Option<ast::Crate> {
Some(self.make(AstFragmentKind::Crate).make_crate())
}
}ast_fragments! {
174 Expr(Box<ast::Expr>) {
175 "expression";
176 one fn visit_expr;
177 fn make_expr;
178 }
179 Pat(Box<ast::Pat>) {
180 "pattern";
181 one fn visit_pat;
182 fn make_pat;
183 }
184 Ty(Box<ast::Ty>) {
185 "type";
186 one fn visit_ty;
187 fn make_ty;
188 }
189 Stmts(SmallVec<[ast::Stmt; 1]>) {
190 "statement";
191 many fn flat_map_stmt; fn visit_stmt();
192 fn make_stmts;
193 }
194 Items(SmallVec<[Box<ast::Item>; 1]>) {
195 "item";
196 many fn flat_map_item; fn visit_item();
197 fn make_items;
198 }
199 TraitItems(SmallVec<[Box<ast::AssocItem>; 1]>) {
200 "trait item";
201 many fn flat_map_assoc_item; fn visit_assoc_item(AssocCtxt::Trait);
202 fn make_trait_items;
203 }
204 ImplItems(SmallVec<[Box<ast::AssocItem>; 1]>) {
205 "impl item";
206 many fn flat_map_assoc_item; fn visit_assoc_item(AssocCtxt::Impl { of_trait: false });
207 fn make_impl_items;
208 }
209 TraitImplItems(SmallVec<[Box<ast::AssocItem>; 1]>) {
210 "impl item";
211 many fn flat_map_assoc_item; fn visit_assoc_item(AssocCtxt::Impl { of_trait: true });
212 fn make_trait_impl_items;
213 }
214 ForeignItems(SmallVec<[Box<ast::ForeignItem>; 1]>) {
215 "foreign item";
216 many fn flat_map_foreign_item; fn visit_foreign_item();
217 fn make_foreign_items;
218 }
219 Arms(SmallVec<[ast::Arm; 1]>) {
220 "match arm";
221 many fn flat_map_arm; fn visit_arm();
222 fn make_arms;
223 }
224 ExprFields(SmallVec<[ast::ExprField; 1]>) {
225 "field expression";
226 many fn flat_map_expr_field; fn visit_expr_field();
227 fn make_expr_fields;
228 }
229 PatFields(SmallVec<[ast::PatField; 1]>) {
230 "field pattern";
231 many fn flat_map_pat_field; fn visit_pat_field();
232 fn make_pat_fields;
233 }
234 GenericParams(SmallVec<[ast::GenericParam; 1]>) {
235 "generic parameter";
236 many fn flat_map_generic_param; fn visit_generic_param();
237 fn make_generic_params;
238 }
239 Params(SmallVec<[ast::Param; 1]>) {
240 "function parameter";
241 many fn flat_map_param; fn visit_param();
242 fn make_params;
243 }
244 FieldDefs(SmallVec<[ast::FieldDef; 1]>) {
245 "field";
246 many fn flat_map_field_def; fn visit_field_def();
247 fn make_field_defs;
248 }
249 Variants(SmallVec<[ast::Variant; 1]>) {
250 "variant";
251 many fn flat_map_variant; fn visit_variant();
252 fn make_variants;
253 }
254 WherePredicates(SmallVec<[ast::WherePredicate; 1]>) {
255 "where predicate";
256 many fn flat_map_where_predicate; fn visit_where_predicate();
257 fn make_where_predicates;
258 }
259 Crate(ast::Crate) {
260 "crate";
261 one fn visit_crate;
262 fn make_crate;
263 }
264}
265
266pub enum SupportsMacroExpansion {
267 No,
268 Yes { supports_inner_attrs: bool },
269}
270
271impl AstFragmentKind {
272 pub(crate) fn dummy(self, span: Span, guar: ErrorGuaranteed) -> AstFragment {
273 self.make_from(DummyResult::any(span, guar)).expect("couldn't create a dummy AST fragment")
274 }
275
276 pub fn supports_macro_expansion(self) -> SupportsMacroExpansion {
277 match self {
278 AstFragmentKind::OptExpr
279 | AstFragmentKind::Expr
280 | AstFragmentKind::MethodReceiverExpr
281 | AstFragmentKind::Stmts
282 | AstFragmentKind::Ty
283 | AstFragmentKind::Pat => SupportsMacroExpansion::Yes { supports_inner_attrs: false },
284 AstFragmentKind::Items
285 | AstFragmentKind::TraitItems
286 | AstFragmentKind::ImplItems
287 | AstFragmentKind::TraitImplItems
288 | AstFragmentKind::ForeignItems
289 | AstFragmentKind::Crate => SupportsMacroExpansion::Yes { supports_inner_attrs: true },
290 AstFragmentKind::Arms
291 | AstFragmentKind::ExprFields
292 | AstFragmentKind::PatFields
293 | AstFragmentKind::GenericParams
294 | AstFragmentKind::Params
295 | AstFragmentKind::FieldDefs
296 | AstFragmentKind::Variants
297 | AstFragmentKind::WherePredicates => SupportsMacroExpansion::No,
298 }
299 }
300
301 pub(crate) fn expect_from_annotatables(
302 self,
303 items: impl IntoIterator<Item = Annotatable>,
304 ) -> AstFragment {
305 let mut items = items.into_iter();
306 match self {
307 AstFragmentKind::Arms => {
308 AstFragment::Arms(items.map(Annotatable::expect_arm).collect())
309 }
310 AstFragmentKind::ExprFields => {
311 AstFragment::ExprFields(items.map(Annotatable::expect_expr_field).collect())
312 }
313 AstFragmentKind::PatFields => {
314 AstFragment::PatFields(items.map(Annotatable::expect_pat_field).collect())
315 }
316 AstFragmentKind::GenericParams => {
317 AstFragment::GenericParams(items.map(Annotatable::expect_generic_param).collect())
318 }
319 AstFragmentKind::Params => {
320 AstFragment::Params(items.map(Annotatable::expect_param).collect())
321 }
322 AstFragmentKind::FieldDefs => {
323 AstFragment::FieldDefs(items.map(Annotatable::expect_field_def).collect())
324 }
325 AstFragmentKind::Variants => {
326 AstFragment::Variants(items.map(Annotatable::expect_variant).collect())
327 }
328 AstFragmentKind::WherePredicates => AstFragment::WherePredicates(
329 items.map(Annotatable::expect_where_predicate).collect(),
330 ),
331 AstFragmentKind::Items => {
332 AstFragment::Items(items.map(Annotatable::expect_item).collect())
333 }
334 AstFragmentKind::ImplItems => {
335 AstFragment::ImplItems(items.map(Annotatable::expect_impl_item).collect())
336 }
337 AstFragmentKind::TraitImplItems => {
338 AstFragment::TraitImplItems(items.map(Annotatable::expect_impl_item).collect())
339 }
340 AstFragmentKind::TraitItems => {
341 AstFragment::TraitItems(items.map(Annotatable::expect_trait_item).collect())
342 }
343 AstFragmentKind::ForeignItems => {
344 AstFragment::ForeignItems(items.map(Annotatable::expect_foreign_item).collect())
345 }
346 AstFragmentKind::Stmts => {
347 AstFragment::Stmts(items.map(Annotatable::expect_stmt).collect())
348 }
349 AstFragmentKind::Expr => AstFragment::Expr(
350 items.next().expect("expected exactly one expression").expect_expr(),
351 ),
352 AstFragmentKind::MethodReceiverExpr => AstFragment::MethodReceiverExpr(
353 items.next().expect("expected exactly one expression").expect_expr(),
354 ),
355 AstFragmentKind::OptExpr => {
356 AstFragment::OptExpr(items.next().map(Annotatable::expect_expr))
357 }
358 AstFragmentKind::Crate => {
359 AstFragment::Crate(items.next().expect("expected exactly one crate").expect_crate())
360 }
361 AstFragmentKind::Pat | AstFragmentKind::Ty => {
362 {
::core::panicking::panic_fmt(format_args!("patterns and types aren\'t annotatable"));
}panic!("patterns and types aren't annotatable")
363 }
364 }
365 }
366}
367
368pub struct Invocation {
369 pub kind: InvocationKind,
370 pub fragment_kind: AstFragmentKind,
371 pub expansion_data: ExpansionData,
372}
373
374pub enum InvocationKind {
375 Bang {
376 mac: Box<ast::MacCall>,
377 span: Span,
378 },
379 Attr {
380 attr: ast::Attribute,
381 pos: usize,
383 item: Annotatable,
384 derives: Vec<ast::Path>,
386 },
387 Derive {
388 path: ast::Path,
389 is_const: bool,
390 item: Annotatable,
391 },
392 GlobDelegation {
393 item: Box<ast::AssocItem>,
394 of_trait: bool,
396 },
397}
398
399impl InvocationKind {
400 fn placeholder_visibility(&self) -> Option<ast::Visibility> {
401 match self {
407 InvocationKind::Attr { item: Annotatable::FieldDef(field), .. }
408 | InvocationKind::Derive { item: Annotatable::FieldDef(field), .. }
409 if field.ident.is_none() =>
410 {
411 Some(field.vis.clone())
412 }
413 _ => None,
414 }
415 }
416}
417
418impl Invocation {
419 pub fn span(&self) -> Span {
420 match &self.kind {
421 InvocationKind::Bang { span, .. } => *span,
422 InvocationKind::Attr { attr, .. } => attr.span,
423 InvocationKind::Derive { path, .. } => path.span,
424 InvocationKind::GlobDelegation { item, .. } => item.span,
425 }
426 }
427
428 fn span_mut(&mut self) -> &mut Span {
429 match &mut self.kind {
430 InvocationKind::Bang { span, .. } => span,
431 InvocationKind::Attr { attr, .. } => &mut attr.span,
432 InvocationKind::Derive { path, .. } => &mut path.span,
433 InvocationKind::GlobDelegation { item, .. } => &mut item.span,
434 }
435 }
436}
437
438pub struct MacroExpander<'a, 'b> {
439 pub cx: &'a mut ExtCtxt<'b>,
440 monotonic: bool, }
442
443impl<'a, 'b> MacroExpander<'a, 'b> {
444 pub fn new(cx: &'a mut ExtCtxt<'b>, monotonic: bool) -> Self {
445 MacroExpander { cx, monotonic }
446 }
447
448 pub fn expand_crate(&mut self, krate: ast::Crate) -> ast::Crate {
449 let file_path = match self.cx.source_map().span_to_filename(krate.spans.inner_span) {
450 FileName::Real(name) => name
451 .into_local_path()
452 .expect("attempting to resolve a file path in an external file"),
453 other => PathBuf::from(other.prefer_local_unconditionally().to_string()),
454 };
455 let dir_path = file_path.parent().unwrap_or(&file_path).to_owned();
456 self.cx.root_path = dir_path.clone();
457 self.cx.current_expansion.module = Rc::new(ModuleData {
458 mod_path: ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[Ident::with_dummy_span(self.cx.ecfg.crate_name)]))vec![Ident::with_dummy_span(self.cx.ecfg.crate_name)],
459 file_path_stack: ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[file_path]))vec![file_path],
460 dir_path,
461 });
462 let krate = self.fully_expand_fragment(AstFragment::Crate(krate)).make_crate();
463 {
match (&krate.id, &ast::CRATE_NODE_ID) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(krate.id, ast::CRATE_NODE_ID);
464 self.cx.trace_macros_diag();
465 krate
466 }
467
468 pub fn fully_expand_fragment(&mut self, input_fragment: AstFragment) -> AstFragment {
470 let orig_expansion_data = self.cx.current_expansion.clone();
471 let orig_force_mode = self.cx.force_mode;
472
473 let (mut fragment_with_placeholders, mut invocations) =
475 self.collect_invocations(input_fragment, &[]);
476
477 self.resolve_imports();
480
481 invocations.reverse();
486 let mut expanded_fragments = Vec::new();
487 let mut expanded_fragments_len = 0;
488 let mut undetermined_invocations = Vec::new();
489 let (mut progress, mut force) = (false, !self.monotonic);
490 loop {
491 let Some((invoc, ext)) = invocations.pop() else {
492 self.resolve_imports();
493 if undetermined_invocations.is_empty() {
494 break;
495 }
496 invocations = mem::take(&mut undetermined_invocations);
497 force = !progress;
498 progress = false;
499 if force && self.monotonic {
500 self.cx.dcx().span_delayed_bug(
501 invocations.last().unwrap().0.span(),
502 "expansion entered force mode without producing any errors",
503 );
504 }
505 continue;
506 };
507
508 let ext = match ext {
509 Some(ext) => ext,
510 None => {
511 let eager_expansion_root = if self.monotonic {
512 invoc.expansion_data.id
513 } else {
514 orig_expansion_data.id
515 };
516 match self.cx.resolver.resolve_macro_invocation(
517 &invoc,
518 eager_expansion_root,
519 force,
520 ) {
521 Ok(ext) => ext,
522 Err(Indeterminate) => {
523 undetermined_invocations.push((invoc, None));
525 continue;
526 }
527 }
528 }
529 };
530
531 let ExpansionData { depth, id: expn_id, .. } = invoc.expansion_data;
532 let depth = depth - orig_expansion_data.depth;
533 self.cx.current_expansion = invoc.expansion_data.clone();
534 self.cx.force_mode = force;
535
536 let fragment_kind = invoc.fragment_kind;
537 match self.expand_invoc(invoc, &ext.kind) {
538 ExpandResult::Ready(fragment) => {
539 let mut derive_invocations = Vec::new();
540 let derive_placeholders = self
541 .cx
542 .resolver
543 .take_derive_resolutions(expn_id)
544 .map(|derives| {
545 derive_invocations.reserve(derives.len());
546 derives
547 .into_iter()
548 .map(|DeriveResolution { path, item, exts: _, is_const }| {
549 let expn_id = LocalExpnId::fresh_empty();
553 derive_invocations.push((
554 Invocation {
555 kind: InvocationKind::Derive { path, item, is_const },
556 fragment_kind,
557 expansion_data: ExpansionData {
558 id: expn_id,
559 ..self.cx.current_expansion.clone()
560 },
561 },
562 None,
563 ));
564 NodeId::placeholder_from_expn_id(expn_id)
565 })
566 .collect::<Vec<_>>()
567 })
568 .unwrap_or_default();
569
570 let (expanded_fragment, collected_invocations) =
571 self.collect_invocations(fragment, &derive_placeholders);
572 derive_invocations.extend(collected_invocations);
576
577 progress = true;
578 if expanded_fragments.len() < depth {
579 expanded_fragments.push(Vec::new());
580 }
581 expanded_fragments[depth - 1].push((expn_id, expanded_fragment));
582 expanded_fragments_len += 1;
583 invocations.extend(derive_invocations.into_iter().rev());
584 }
585 ExpandResult::Retry(invoc) => {
586 if force {
587 self.cx.dcx().span_bug(
588 invoc.span(),
589 "expansion entered force mode but is still stuck",
590 );
591 } else {
592 undetermined_invocations.push((invoc, Some(ext)));
594 }
595 }
596 }
597 }
598
599 self.cx.current_expansion = orig_expansion_data;
600 self.cx.force_mode = orig_force_mode;
601
602 let mut placeholder_expander = PlaceholderExpander::with_capacity(expanded_fragments_len);
604 while let Some(expanded_fragments) = expanded_fragments.pop() {
605 for (expn_id, expanded_fragment) in expanded_fragments.into_iter().rev() {
606 placeholder_expander
607 .add(NodeId::placeholder_from_expn_id(expn_id), expanded_fragment);
608 }
609 }
610 fragment_with_placeholders.mut_visit_with(&mut placeholder_expander);
611 fragment_with_placeholders
612 }
613
614 fn resolve_imports(&mut self) {
615 if self.monotonic {
616 self.cx.resolver.resolve_imports();
617 }
618 }
619
620 fn collect_invocations(
625 &mut self,
626 mut fragment: AstFragment,
627 extra_placeholders: &[NodeId],
628 ) -> (AstFragment, Vec<(Invocation, Option<Arc<SyntaxExtension>>)>) {
629 self.cx.resolver.resolve_dollar_crates();
631
632 let mut invocations = {
633 let mut collector = InvocationCollector {
634 cx: self.cx,
640 invocations: Vec::new(),
641 monotonic: self.monotonic,
642 };
643 fragment.mut_visit_with(&mut collector);
644 fragment.add_placeholders(extra_placeholders);
645 collector.invocations
646 };
647
648 if self.monotonic {
649 self.cx
650 .resolver
651 .visit_ast_fragment_with_placeholders(self.cx.current_expansion.id, &fragment);
652
653 if self.cx.sess.opts.incremental.is_some() {
654 for (invoc, _) in invocations.iter_mut() {
655 let expn_id = invoc.expansion_data.id;
656 let parent_def = self.cx.resolver.invocation_parent(expn_id);
657 let span = invoc.span_mut();
658 *span = span.with_parent(Some(parent_def));
659 }
660 }
661 }
662
663 (fragment, invocations)
664 }
665
666 fn error_recursion_limit_reached(&mut self) -> ErrorGuaranteed {
667 let expn_data = self.cx.current_expansion.id.expn_data();
668 let suggested_limit = match self.cx.ecfg.recursion_limit {
669 Limit(0) => Limit(2),
670 limit => limit * 2,
671 };
672
673 let guar = self.cx.dcx().emit_err(RecursionLimitReached {
674 span: expn_data.call_site,
675 descr: expn_data.kind.descr(),
676 suggested_limit,
677 crate_name: self.cx.ecfg.crate_name,
678 });
679
680 self.cx.macro_error_and_trace_macros_diag();
681 guar
682 }
683
684 fn error_wrong_fragment_kind(
687 &mut self,
688 kind: AstFragmentKind,
689 mac: &ast::MacCall,
690 span: Span,
691 ) -> ErrorGuaranteed {
692 let name = pprust::path_to_string(&mac.path);
693 let guar = self.cx.dcx().emit_err(WrongFragmentKind { span, kind: kind.name(), name });
694 self.cx.macro_error_and_trace_macros_diag();
695 guar
696 }
697
698 fn expand_invoc(
699 &mut self,
700 invoc: Invocation,
701 ext: &SyntaxExtensionKind,
702 ) -> ExpandResult<AstFragment, Invocation> {
703 let recursion_limit = match self.cx.reduced_recursion_limit {
704 Some((limit, _)) => limit,
705 None => self.cx.ecfg.recursion_limit,
706 };
707
708 if !recursion_limit.value_within_limit(self.cx.current_expansion.depth) {
709 let guar = match self.cx.reduced_recursion_limit {
710 Some((_, guar)) => guar,
711 None => self.error_recursion_limit_reached(),
712 };
713
714 self.cx.reduced_recursion_limit = Some((recursion_limit / 2, guar));
716
717 return ExpandResult::Ready(invoc.fragment_kind.dummy(invoc.span(), guar));
718 }
719
720 let macro_stats = self.cx.sess.opts.unstable_opts.macro_stats;
721
722 let (fragment_kind, span) = (invoc.fragment_kind, invoc.span());
723 ExpandResult::Ready(match invoc.kind {
724 InvocationKind::Bang { mac, span } => {
725 if let SyntaxExtensionKind::Bang(expander) = ext {
726 match expander.expand(self.cx, span, mac.args.tokens.clone()) {
727 Ok(tok_result) => {
728 let fragment =
729 self.parse_ast_fragment(tok_result, fragment_kind, &mac.path, span);
730 if macro_stats {
731 update_bang_macro_stats(
732 self.cx,
733 fragment_kind,
734 span,
735 mac,
736 &fragment,
737 );
738 }
739 fragment
740 }
741 Err(guar) => return ExpandResult::Ready(fragment_kind.dummy(span, guar)),
742 }
743 } else if let Some(expander) = ext.as_ast_bang() {
744 let tok_result = match expander.expand(self.cx, span, mac.args.tokens.clone()) {
745 ExpandResult::Ready(tok_result) => tok_result,
746 ExpandResult::Retry(_) => {
747 return ExpandResult::Retry(Invocation {
749 kind: InvocationKind::Bang { mac, span },
750 ..invoc
751 });
752 }
753 };
754 if let Some(fragment) = fragment_kind.make_from(tok_result) {
755 if macro_stats {
756 update_bang_macro_stats(self.cx, fragment_kind, span, mac, &fragment);
757 }
758 fragment
759 } else {
760 let guar = self.error_wrong_fragment_kind(fragment_kind, &mac, span);
761 fragment_kind.dummy(span, guar)
762 }
763 } else {
764 ::core::panicking::unreachable_default_msg();unreachable!();
765 }
766 }
767 InvocationKind::Attr { attr, pos, mut item, derives } => {
768 if let Some(expander) = ext.as_attr() {
769 self.gate_proc_macro_attr_item(span, &item);
770 let tokens = match &item {
771 Annotatable::Crate(krate) => {
777 rustc_parse::fake_token_stream_for_crate(&self.cx.sess.psess, krate)
778 }
779 Annotatable::Item(item_inner)
780 if #[allow(non_exhaustive_omitted_patterns)] match attr.style {
AttrStyle::Inner => true,
_ => false,
}matches!(attr.style, AttrStyle::Inner)
781 && #[allow(non_exhaustive_omitted_patterns)] match item_inner.kind {
ItemKind::Mod(_, _,
ModKind::Unloaded | ModKind::Loaded(_, Inline::No { .. }, _)) => true,
_ => false,
}matches!(
782 item_inner.kind,
783 ItemKind::Mod(
784 _,
785 _,
786 ModKind::Unloaded
787 | ModKind::Loaded(_, Inline::No { .. }, _),
788 )
789 ) =>
790 {
791 rustc_parse::fake_token_stream_for_item(
792 &self.cx.sess.psess,
793 item_inner,
794 Some(&attr),
795 )
796 }
797 Annotatable::Item(item_inner) if item_inner.tokens.is_none() => {
798 rustc_parse::fake_token_stream_for_item(
799 &self.cx.sess.psess,
800 item_inner,
801 None,
802 )
803 }
804 Annotatable::Item(item_inner)
811 if #[allow(non_exhaustive_omitted_patterns)] match &item_inner.kind {
ItemKind::Fn(f) if f.eii_impl.is_some() => true,
_ => false,
}matches!(&item_inner.kind,
812 ItemKind::Fn(f) if f.eii_impl.is_some()) =>
813 {
814 rustc_parse::fake_token_stream_for_item(
815 &self.cx.sess.psess,
816 item_inner,
817 None,
818 )
819 }
820 Annotatable::ForeignItem(item_inner) if item_inner.tokens.is_none() => {
821 rustc_parse::fake_token_stream_for_foreign_item(
822 &self.cx.sess.psess,
823 item_inner,
824 )
825 }
826 _ => item.to_tokens(),
827 };
828 let attr_item = attr.get_normal_item();
829 let safety = attr_item.unsafety;
830 if let AttrArgs::Eq { .. } = attr_item.args {
831 self.cx.dcx().emit_err(UnsupportedKeyValue { span });
832 }
833 let inner_tokens = attr_item.args.inner_tokens();
834 match expander.expand_with_safety(self.cx, safety, span, inner_tokens, tokens) {
835 Ok(tok_result) => {
836 let fragment = self.parse_ast_fragment(
837 tok_result,
838 fragment_kind,
839 &attr_item.path,
840 span,
841 );
842 if macro_stats {
843 update_attr_macro_stats(
844 self.cx,
845 fragment_kind,
846 span,
847 &attr_item.path,
848 &attr,
849 item,
850 &fragment,
851 );
852 }
853 fragment
854 }
855 Err(guar) => return ExpandResult::Ready(fragment_kind.dummy(span, guar)),
856 }
857 } else if let SyntaxExtensionKind::AstAttr(expander) = ext {
858 self.gate_proc_macro_attr_item(span, &item);
859 match validate_attr::parse_meta(&self.cx.sess.psess, &attr) {
863 Ok(meta) => {
864 let item_clone = macro_stats.then(|| item.clone());
865 let items = match expander.expand(self.cx, span, &meta, item, false) {
866 ExpandResult::Ready(items) => items,
867 ExpandResult::Retry(item) => {
868 return ExpandResult::Retry(Invocation {
870 kind: InvocationKind::Attr { attr, pos, item, derives },
871 ..invoc
872 });
873 }
874 };
875 if #[allow(non_exhaustive_omitted_patterns)] match fragment_kind {
AstFragmentKind::Expr | AstFragmentKind::MethodReceiverExpr => true,
_ => false,
}matches!(
876 fragment_kind,
877 AstFragmentKind::Expr | AstFragmentKind::MethodReceiverExpr
878 ) && items.is_empty()
879 {
880 let guar = self.cx.dcx().emit_err(RemoveExprNotSupported { span });
881 fragment_kind.dummy(span, guar)
882 } else {
883 let fragment = fragment_kind.expect_from_annotatables(items);
884 if macro_stats {
885 update_attr_macro_stats(
886 self.cx,
887 fragment_kind,
888 span,
889 &meta.path,
890 &attr,
891 item_clone.unwrap(),
892 &fragment,
893 );
894 }
895 fragment
896 }
897 }
898 Err(err) => {
899 err.emit();
900 fragment_kind.expect_from_annotatables(iter::once(item))
901 }
902 }
903 } else if let SyntaxExtensionKind::NonMacroAttr = ext {
904 self.cx.expanded_inert_attrs.mark(&attr);
906 item.visit_attrs(|attrs| attrs.insert(pos, attr));
907 fragment_kind.expect_from_annotatables(iter::once(item))
908 } else {
909 ::core::panicking::unreachable_default_msg();unreachable!();
910 }
911 }
912 InvocationKind::Derive { path, item, is_const } => match ext {
913 SyntaxExtensionKind::Derive(expander)
914 | SyntaxExtensionKind::AstDerive(expander) => {
915 let meta = ast::MetaItem {
918 unsafety: ast::Safety::Default,
919 kind: MetaItemKind::Word,
920 span,
921 path,
922 };
923 let items = match expander.expand(self.cx, span, &meta, item, is_const) {
924 ExpandResult::Ready(items) => items,
925 ExpandResult::Retry(item) => {
926 return ExpandResult::Retry(Invocation {
928 kind: InvocationKind::Derive { path: meta.path, item, is_const },
929 ..invoc
930 });
931 }
932 };
933 let fragment = fragment_kind.expect_from_annotatables(items);
934 if macro_stats {
935 update_derive_macro_stats(
936 self.cx,
937 fragment_kind,
938 span,
939 &meta.path,
940 &fragment,
941 );
942 }
943 fragment
944 }
945 SyntaxExtensionKind::MacroRules(expander)
946 if expander.kinds().contains(MacroKinds::DERIVE) =>
947 {
948 if is_const {
949 let guar = self
950 .cx
951 .dcx()
952 .span_err(span, "macro `derive` does not support const derives");
953 return ExpandResult::Ready(fragment_kind.dummy(span, guar));
954 }
955 let body = item.to_tokens();
956 match expander.expand_derive(self.cx, span, &body) {
957 Ok(tok_result) => {
958 let fragment =
959 self.parse_ast_fragment(tok_result, fragment_kind, &path, span);
960 if macro_stats {
961 update_derive_macro_stats(
962 self.cx,
963 fragment_kind,
964 span,
965 &path,
966 &fragment,
967 );
968 }
969 fragment
970 }
971 Err(guar) => return ExpandResult::Ready(fragment_kind.dummy(span, guar)),
972 }
973 }
974 _ => ::core::panicking::unreachable_default_msg()unreachable!(),
975 },
976 InvocationKind::GlobDelegation { item, of_trait } => {
977 let AssocItemKind::DelegationMac(deleg) = &item.kind else { ::core::panicking::unreachable_default_msg()unreachable!() };
978 let suffixes = match ext {
979 SyntaxExtensionKind::GlobDelegation(expander) => match expander.expand(self.cx)
980 {
981 ExpandResult::Ready(suffixes) => suffixes,
982 ExpandResult::Retry(()) => {
983 return ExpandResult::Retry(Invocation {
985 kind: InvocationKind::GlobDelegation { item, of_trait },
986 ..invoc
987 });
988 }
989 },
990 SyntaxExtensionKind::Bang(..) => {
991 let msg = "expanded a dummy glob delegation";
992 let guar = self.cx.dcx().span_delayed_bug(span, msg);
993 return ExpandResult::Ready(fragment_kind.dummy(span, guar));
994 }
995 _ => ::core::panicking::unreachable_default_msg()unreachable!(),
996 };
997
998 type Node = AstNodeWrapper<Box<ast::AssocItem>, ImplItemTag>;
999 let single_delegations = build_single_delegations::<Node>(
1000 self.cx,
1001 deleg,
1002 &item,
1003 &suffixes,
1004 item.span,
1005 DelegationSource::Glob,
1006 );
1007 fragment_kind.expect_from_annotatables(single_delegations.map(|item| {
1009 Annotatable::AssocItem(Box::new(item), AssocCtxt::Impl { of_trait })
1010 }))
1011 }
1012 })
1013 }
1014
1015 fn gate_proc_macro_attr_item(&self, span: Span, item: &Annotatable) {
1016 let kind = match item {
1017 Annotatable::Item(_)
1018 | Annotatable::AssocItem(..)
1019 | Annotatable::ForeignItem(_)
1020 | Annotatable::Crate(..) => return,
1021 Annotatable::Stmt(stmt) => {
1022 if stmt.is_item() {
1025 return;
1026 }
1027 "statements"
1028 }
1029 Annotatable::Expr(_) => "expressions",
1030 Annotatable::Arm(..)
1031 | Annotatable::ExprField(..)
1032 | Annotatable::PatField(..)
1033 | Annotatable::GenericParam(..)
1034 | Annotatable::Param(..)
1035 | Annotatable::FieldDef(..)
1036 | Annotatable::Variant(..)
1037 | Annotatable::WherePredicate(..) => { ::core::panicking::panic_fmt(format_args!("unexpected annotatable")); }panic!("unexpected annotatable"),
1038 };
1039 if self.cx.ecfg.features.proc_macro_hygiene() {
1040 return;
1041 }
1042 feature_err(
1043 self.cx.sess,
1044 sym::proc_macro_hygiene,
1045 span,
1046 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("macro attributes on {0} are unstable",
kind))
})format!("macro attributes on {kind} are unstable"),
1047 )
1048 .emit();
1049 }
1050
1051 fn parse_ast_fragment(
1052 &mut self,
1053 toks: TokenStream,
1054 kind: AstFragmentKind,
1055 path: &ast::Path,
1056 span: Span,
1057 ) -> AstFragment {
1058 let mut parser = self.cx.new_parser_from_tts(toks);
1059 match parse_ast_fragment(&mut parser, kind) {
1060 Ok(fragment) => {
1061 ensure_complete_parse(&parser, path, kind.name(), span);
1062 fragment
1063 }
1064 Err(mut err) => {
1065 if err.span.is_dummy() {
1066 err.span(span);
1067 }
1068 let guar = err.emit_err();
1069 self.cx.macro_error_and_trace_macros_diag();
1070 kind.dummy(span, guar)
1071 }
1072 }
1073 }
1074}
1075
1076pub fn parse_ast_fragment<'a>(
1077 this: &mut Parser<'a>,
1078 kind: AstFragmentKind,
1079) -> PResult<'a, AstFragment> {
1080 Ok(match kind {
1081 AstFragmentKind::Items => {
1082 let mut items = SmallVec::new();
1083 while let Some(item) = this.parse_item(ForceCollect::No, AllowConstBlockItems::Yes)? {
1084 items.push(item);
1085 }
1086 AstFragment::Items(items)
1087 }
1088 AstFragmentKind::TraitItems => {
1089 let mut items = SmallVec::new();
1090 while let Some(item) = this.parse_trait_item(ForceCollect::No)? {
1091 items.extend(item);
1092 }
1093 AstFragment::TraitItems(items)
1094 }
1095 AstFragmentKind::ImplItems => {
1096 let mut items = SmallVec::new();
1097 while let Some(item) = this.parse_impl_item(ForceCollect::No)? {
1098 items.extend(item);
1099 }
1100 AstFragment::ImplItems(items)
1101 }
1102 AstFragmentKind::TraitImplItems => {
1103 let mut items = SmallVec::new();
1104 while let Some(item) = this.parse_impl_item(ForceCollect::No)? {
1105 items.extend(item);
1106 }
1107 AstFragment::TraitImplItems(items)
1108 }
1109 AstFragmentKind::ForeignItems => {
1110 let mut items = SmallVec::new();
1111 while let Some(item) = this.parse_foreign_item(ForceCollect::No)? {
1112 items.extend(item);
1113 }
1114 AstFragment::ForeignItems(items)
1115 }
1116 AstFragmentKind::Stmts => {
1117 let mut stmts = SmallVec::new();
1118 while this.token != token::Eof && this.token != token::CloseBrace {
1120 stmts.push(this.parse_full_stmt(AttemptLocalParseRecovery::Yes)?);
1121 }
1122 AstFragment::Stmts(stmts)
1123 }
1124 AstFragmentKind::Expr => AstFragment::Expr(this.parse_expr()?),
1125 AstFragmentKind::MethodReceiverExpr => AstFragment::MethodReceiverExpr(this.parse_expr()?),
1126 AstFragmentKind::OptExpr => {
1127 if this.token != token::Eof {
1128 AstFragment::OptExpr(Some(this.parse_expr()?))
1129 } else {
1130 AstFragment::OptExpr(None)
1131 }
1132 }
1133 AstFragmentKind::Ty => AstFragment::Ty(this.parse_ty()?),
1134 AstFragmentKind::Pat => AstFragment::Pat(Box::new(this.parse_pat_allow_top_guard(
1135 None,
1136 RecoverComma::No,
1137 RecoverColon::Yes,
1138 CommaRecoveryMode::LikelyTuple,
1139 )?)),
1140 AstFragmentKind::Crate => AstFragment::Crate(this.parse_crate_mod()?),
1141 AstFragmentKind::Arms
1142 | AstFragmentKind::ExprFields
1143 | AstFragmentKind::PatFields
1144 | AstFragmentKind::GenericParams
1145 | AstFragmentKind::Params
1146 | AstFragmentKind::FieldDefs
1147 | AstFragmentKind::Variants
1148 | AstFragmentKind::WherePredicates => {
::core::panicking::panic_fmt(format_args!("unexpected AST fragment kind"));
}panic!("unexpected AST fragment kind"),
1149 })
1150}
1151
1152pub(crate) fn ensure_complete_parse<'a>(
1153 parser: &Parser<'a>,
1154 macro_path: &ast::Path,
1155 kind_name: &str,
1156 span: Span,
1157) {
1158 if parser.token != token::Eof {
1159 let descr = token_descr(&parser.token);
1160 let def_site_span = parser.token.span.with_ctxt(SyntaxContext::root());
1162
1163 let semi_span = parser.psess.source_map().next_point(span);
1164 let add_semicolon = match &parser.psess.source_map().span_to_snippet(semi_span) {
1165 Ok(snippet) if &snippet[..] != ";" && kind_name == "expression" => {
1166 Some(span.shrink_to_hi())
1167 }
1168 _ => None,
1169 };
1170
1171 let expands_to_match_arm = kind_name == "pattern" && parser.token == token::FatArrow;
1172
1173 parser.dcx().emit_err(IncompleteParse {
1174 span: def_site_span,
1175 descr,
1176 label_span: span,
1177 macro_path: pprust::path_to_string(macro_path),
1178 kind_name,
1179 expands_to_match_arm,
1180 add_semicolon,
1181 });
1182 }
1183}
1184
1185macro_rules! assign_id {
1208 ($self:ident, $id:expr, $closure:expr) => {{
1209 let old_id = $self.cx.current_expansion.lint_node_id;
1210 if $self.monotonic {
1211 debug_assert_eq!(*$id, ast::DUMMY_NODE_ID);
1212 let new_id = $self.cx.resolver.next_node_id();
1213 *$id = new_id;
1214 $self.cx.current_expansion.lint_node_id = new_id;
1215 }
1216 let ret = ($closure)();
1217 $self.cx.current_expansion.lint_node_id = old_id;
1218 ret
1219 }};
1220}
1221
1222enum AddSemicolon {
1223 Yes,
1224 No,
1225}
1226
1227trait InvocationCollectorNode: HasAttrs + HasNodeId + Sized + DeclaredIdents {
1230 type OutputTy = SmallVec<[Self; 1]>;
1231 type ItemKind = ItemKind;
1232 const KIND: AstFragmentKind;
1233 fn to_annotatable(self) -> Annotatable;
1234 fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy;
1235 fn walk_flat_map(self, _collector: &mut InvocationCollector<'_, '_>) -> Self::OutputTy {
1236 ::core::panicking::unreachable_default_msg()unreachable!()
1237 }
1238 fn walk(&mut self, _collector: &mut InvocationCollector<'_, '_>) {
1239 ::core::panicking::unreachable_default_msg()unreachable!()
1240 }
1241 fn is_mac_call(&self) -> bool {
1242 false
1243 }
1244 fn take_mac_call(self) -> (Box<ast::MacCall>, ast::AttrVec, AddSemicolon) {
1245 ::core::panicking::unreachable_default_msg()unreachable!()
1246 }
1247 fn delegation(&self) -> Option<(&ast::DelegationMac, &ast::Item<Self::ItemKind>)> {
1248 None
1249 }
1250 fn delegation_item_kind(_deleg: Box<ast::Delegation>) -> Self::ItemKind {
1251 ::core::panicking::unreachable_default_msg()unreachable!()
1252 }
1253 fn from_item(_item: ast::Item<Self::ItemKind>) -> Self {
1254 ::core::panicking::unreachable_default_msg()unreachable!()
1255 }
1256 fn flatten_outputs(_outputs: impl Iterator<Item = Self::OutputTy>) -> Self::OutputTy {
1257 ::core::panicking::unreachable_default_msg()unreachable!()
1258 }
1259 fn pre_flat_map_node_collect_attr(_cfg: &StripUnconfigured<'_>, _attr: &ast::Attribute) {}
1260 fn post_flat_map_node_collect_bang(_output: &mut Self::OutputTy, _add_semicolon: AddSemicolon) {
1261 }
1262 fn wrap_flat_map_node_walk_flat_map(
1263 node: Self,
1264 collector: &mut InvocationCollector<'_, '_>,
1265 walk_flat_map: impl FnOnce(Self, &mut InvocationCollector<'_, '_>) -> Self::OutputTy,
1266 ) -> Result<Self::OutputTy, Self> {
1267 Ok(walk_flat_map(node, collector))
1268 }
1269 fn expand_cfg_false(
1270 &mut self,
1271 _collector: &mut InvocationCollector<'_, '_>,
1272 _pos: usize,
1273 _span: Span,
1274 ) {
1275 {
::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
format_args!("only crate nodes support this operation")));
};unreachable!("only crate nodes support this operation");
1276 }
1277
1278 fn as_target(&self) -> Target;
1279}
1280
1281pub trait DeclaredIdents {
1282 fn declared_idents(&self) -> Vec<Ident> {
1285 ::alloc::vec::Vec::new()vec![]
1286 }
1287}
1288
1289macro_rules! declared_idents {
1290 ($($ty:ty),*) => {
1291 $(impl DeclaredIdents for $ty {})*
1292 };
1293}
1294
1295impl DeclaredIdents for AstNodeWrapper<Box<ast::AssocItem>, TraitItemTag> {}
impl DeclaredIdents for AstNodeWrapper<Box<ast::AssocItem>, ImplItemTag> {}
impl DeclaredIdents for AstNodeWrapper<Box<ast::AssocItem>, TraitImplItemTag>
{}
impl DeclaredIdents for Box<ast::ForeignItem> {}
impl DeclaredIdents for ast::Variant {}
impl DeclaredIdents for ast::WherePredicate {}
impl DeclaredIdents for ast::FieldDef {}
impl DeclaredIdents for ast::PatField {}
impl DeclaredIdents for ast::ExprField {}
impl DeclaredIdents for ast::Param {}
impl DeclaredIdents for ast::GenericParam {}
impl DeclaredIdents for ast::Arm {}
impl DeclaredIdents for ast::Stmt {}
impl DeclaredIdents for ast::Crate {}
impl DeclaredIdents for ast::Ty {}
impl DeclaredIdents for ast::Pat {}
impl DeclaredIdents for ast::Expr {}
impl DeclaredIdents for AstNodeWrapper<Box<ast::Expr>, OptExprTag> {}
impl DeclaredIdents for AstNodeWrapper<ast::Expr, MethodReceiverTag> {}declared_idents! {
1297 AstNodeWrapper<Box<ast::AssocItem>, TraitItemTag>,
1298 AstNodeWrapper<Box<ast::AssocItem>, ImplItemTag>,
1299 AstNodeWrapper<Box<ast::AssocItem>, TraitImplItemTag>,
1300 Box<ast::ForeignItem>,
1301 ast::Variant,
1302 ast::WherePredicate,
1303 ast::FieldDef,
1304 ast::PatField,
1305 ast::ExprField,
1306 ast::Param,
1307 ast::GenericParam,
1308 ast::Arm,
1309 ast::Stmt,
1310 ast::Crate,
1311 ast::Ty,
1312 ast::Pat,
1313 ast::Expr,
1314 AstNodeWrapper<Box<ast::Expr>, OptExprTag>,
1315 AstNodeWrapper<ast::Expr, MethodReceiverTag>
1316}
1317
1318impl InvocationCollectorNode for Box<ast::Item> {
1319 const KIND: AstFragmentKind = AstFragmentKind::Items;
1320 fn to_annotatable(self) -> Annotatable {
1321 Annotatable::Item(self)
1322 }
1323 fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1324 fragment.make_items()
1325 }
1326 fn walk_flat_map(self, collector: &mut InvocationCollector<'_, '_>) -> Self::OutputTy {
1327 walk_flat_map_item(collector, self)
1328 }
1329 fn is_mac_call(&self) -> bool {
1330 #[allow(non_exhaustive_omitted_patterns)] match self.kind {
ItemKind::MacCall(..) => true,
_ => false,
}matches!(self.kind, ItemKind::MacCall(..))
1331 }
1332 fn take_mac_call(self) -> (Box<ast::MacCall>, ast::AttrVec, AddSemicolon) {
1333 match self.kind {
1334 ItemKind::MacCall(mac) => (mac, self.attrs, AddSemicolon::No),
1335 _ => ::core::panicking::unreachable_default_msg()unreachable!(),
1336 }
1337 }
1338 fn delegation(&self) -> Option<(&ast::DelegationMac, &ast::Item<Self::ItemKind>)> {
1339 match &self.kind {
1340 ItemKind::DelegationMac(deleg) => Some((deleg, self)),
1341 _ => None,
1342 }
1343 }
1344 fn delegation_item_kind(deleg: Box<ast::Delegation>) -> Self::ItemKind {
1345 ItemKind::Delegation(deleg)
1346 }
1347 fn from_item(item: ast::Item<Self::ItemKind>) -> Self {
1348 Box::new(item)
1349 }
1350 fn flatten_outputs(items: impl Iterator<Item = Self::OutputTy>) -> Self::OutputTy {
1351 items.flatten().collect()
1352 }
1353 fn wrap_flat_map_node_walk_flat_map(
1354 mut node: Self,
1355 collector: &mut InvocationCollector<'_, '_>,
1356 walk_flat_map: impl FnOnce(Self, &mut InvocationCollector<'_, '_>) -> Self::OutputTy,
1357 ) -> Result<Self::OutputTy, Self> {
1358 if !#[allow(non_exhaustive_omitted_patterns)] match node.kind {
ItemKind::Mod(..) => true,
_ => false,
}matches!(node.kind, ItemKind::Mod(..)) {
1359 return Ok(walk_flat_map(node, collector));
1360 }
1361
1362 let ItemKind::Mod(_, ident, ref mut mod_kind) = node.kind else { ::core::panicking::unreachable_default_msg()unreachable!() };
1363 let ecx = &mut collector.cx;
1364 let (file_path, dir_path, dir_ownership) = match mod_kind {
1365 ModKind::Loaded(_, inline, _) => {
1366 let (dir_path, dir_ownership) = mod_dir_path(
1368 ecx.sess,
1369 ident,
1370 &node.attrs,
1371 &ecx.current_expansion.module,
1372 ecx.current_expansion.dir_ownership,
1373 *inline,
1374 );
1375 let file_path = match inline {
1378 Inline::Yes => None,
1379 Inline::No { .. } => mod_file_path_from_attr(
1380 ecx.sess,
1381 &node.attrs,
1382 &ecx.current_expansion.module.dir_path,
1383 ),
1384 };
1385 (file_path, dir_path, dir_ownership)
1386 }
1387 ModKind::Unloaded => {
1388 let old_attrs_len = node.attrs.len();
1390 let ParsedExternalMod {
1391 items,
1392 spans,
1393 file_path,
1394 dir_path,
1395 dir_ownership,
1396 had_parse_error,
1397 } = parse_external_mod(
1398 ecx.sess,
1399 ident,
1400 node.span,
1401 &ecx.current_expansion.module,
1402 ecx.current_expansion.dir_ownership,
1403 &mut node.attrs,
1404 );
1405
1406 if let Some(lint_store) = ecx.lint_store {
1407 lint_store.pre_expansion_lint(
1408 ecx.sess,
1409 ecx.ecfg.features,
1410 ecx.resolver.registered_lint_tools(),
1411 ecx.current_expansion.lint_node_id,
1412 &node.attrs,
1413 &items,
1414 ident.name,
1415 );
1416 }
1417
1418 *mod_kind = ModKind::Loaded(items, Inline::No { had_parse_error }, spans);
1419 if node.attrs.len() > old_attrs_len {
1420 return Err(node);
1424 }
1425 (Some(file_path), dir_path, dir_ownership)
1426 }
1427 };
1428
1429 let mut module = ecx.current_expansion.module.with_dir_path(dir_path);
1431 module.mod_path.push(ident);
1432 if let Some(file_path) = file_path {
1433 module.file_path_stack.push(file_path);
1434 }
1435
1436 let orig_module = mem::replace(&mut ecx.current_expansion.module, Rc::new(module));
1437 let orig_dir_ownership =
1438 mem::replace(&mut ecx.current_expansion.dir_ownership, dir_ownership);
1439
1440 let res = Ok(walk_flat_map(node, collector));
1441
1442 collector.cx.current_expansion.dir_ownership = orig_dir_ownership;
1443 collector.cx.current_expansion.module = orig_module;
1444 res
1445 }
1446
1447 fn as_target(&self) -> Target {
1448 Target::from_ast_item(self)
1449 }
1450}
1451
1452impl DeclaredIdents for Box<ast::Item> {
1453 fn declared_idents(&self) -> Vec<Ident> {
1454 if let ItemKind::Use(ut) = &self.kind {
1455 fn collect_use_tree_leaves(ut: &ast::UseTree, idents: &mut Vec<Ident>) {
1456 match &ut.kind {
1457 ast::UseTreeKind::Glob(_) => {}
1458 ast::UseTreeKind::Simple(_) => idents.push(ut.ident()),
1459 ast::UseTreeKind::Nested { items, .. } => {
1460 for tree in items {
1461 collect_use_tree_leaves(&tree.inner, idents);
1462 }
1463 }
1464 }
1465 }
1466 let mut idents = Vec::new();
1467 collect_use_tree_leaves(ut, &mut idents);
1468 idents
1469 } else {
1470 self.kind.ident().into_iter().collect()
1471 }
1472 }
1473}
1474
1475struct TraitItemTag;
1476impl InvocationCollectorNode for AstNodeWrapper<Box<ast::AssocItem>, TraitItemTag> {
1477 type OutputTy = SmallVec<[Box<ast::AssocItem>; 1]>;
1478 type ItemKind = AssocItemKind;
1479 const KIND: AstFragmentKind = AstFragmentKind::TraitItems;
1480 fn to_annotatable(self) -> Annotatable {
1481 Annotatable::AssocItem(self.wrapped, AssocCtxt::Trait)
1482 }
1483 fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1484 fragment.make_trait_items()
1485 }
1486 fn walk_flat_map(self, collector: &mut InvocationCollector<'_, '_>) -> Self::OutputTy {
1487 walk_flat_map_assoc_item(collector, self.wrapped, AssocCtxt::Trait)
1488 }
1489 fn is_mac_call(&self) -> bool {
1490 #[allow(non_exhaustive_omitted_patterns)] match self.wrapped.kind {
AssocItemKind::MacCall(..) => true,
_ => false,
}matches!(self.wrapped.kind, AssocItemKind::MacCall(..))
1491 }
1492 fn take_mac_call(self) -> (Box<ast::MacCall>, ast::AttrVec, AddSemicolon) {
1493 let item = self.wrapped;
1494 match item.kind {
1495 AssocItemKind::MacCall(mac) => (mac, item.attrs, AddSemicolon::No),
1496 _ => ::core::panicking::unreachable_default_msg()unreachable!(),
1497 }
1498 }
1499 fn delegation(&self) -> Option<(&ast::DelegationMac, &ast::Item<Self::ItemKind>)> {
1500 match &self.wrapped.kind {
1501 AssocItemKind::DelegationMac(deleg) => Some((deleg, &self.wrapped)),
1502 _ => None,
1503 }
1504 }
1505 fn delegation_item_kind(deleg: Box<ast::Delegation>) -> Self::ItemKind {
1506 AssocItemKind::Delegation(deleg)
1507 }
1508 fn from_item(item: ast::Item<Self::ItemKind>) -> Self {
1509 AstNodeWrapper::new(Box::new(item), TraitItemTag)
1510 }
1511 fn flatten_outputs(items: impl Iterator<Item = Self::OutputTy>) -> Self::OutputTy {
1512 items.flatten().collect()
1513 }
1514 fn as_target(&self) -> Target {
1515 Target::from_assoc_item_kind(&self.wrapped.kind, AssocCtxt::Trait)
1516 }
1517}
1518
1519struct ImplItemTag;
1520impl InvocationCollectorNode for AstNodeWrapper<Box<ast::AssocItem>, ImplItemTag> {
1521 type OutputTy = SmallVec<[Box<ast::AssocItem>; 1]>;
1522 type ItemKind = AssocItemKind;
1523 const KIND: AstFragmentKind = AstFragmentKind::ImplItems;
1524 fn to_annotatable(self) -> Annotatable {
1525 Annotatable::AssocItem(self.wrapped, AssocCtxt::Impl { of_trait: false })
1526 }
1527 fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1528 fragment.make_impl_items()
1529 }
1530 fn walk_flat_map(self, collector: &mut InvocationCollector<'_, '_>) -> Self::OutputTy {
1531 walk_flat_map_assoc_item(collector, self.wrapped, AssocCtxt::Impl { of_trait: false })
1532 }
1533 fn is_mac_call(&self) -> bool {
1534 #[allow(non_exhaustive_omitted_patterns)] match self.wrapped.kind {
AssocItemKind::MacCall(..) => true,
_ => false,
}matches!(self.wrapped.kind, AssocItemKind::MacCall(..))
1535 }
1536 fn take_mac_call(self) -> (Box<ast::MacCall>, ast::AttrVec, AddSemicolon) {
1537 let item = self.wrapped;
1538 match item.kind {
1539 AssocItemKind::MacCall(mac) => (mac, item.attrs, AddSemicolon::No),
1540 _ => ::core::panicking::unreachable_default_msg()unreachable!(),
1541 }
1542 }
1543 fn delegation(&self) -> Option<(&ast::DelegationMac, &ast::Item<Self::ItemKind>)> {
1544 match &self.wrapped.kind {
1545 AssocItemKind::DelegationMac(deleg) => Some((deleg, &self.wrapped)),
1546 _ => None,
1547 }
1548 }
1549 fn delegation_item_kind(deleg: Box<ast::Delegation>) -> Self::ItemKind {
1550 AssocItemKind::Delegation(deleg)
1551 }
1552 fn from_item(item: ast::Item<Self::ItemKind>) -> Self {
1553 AstNodeWrapper::new(Box::new(item), ImplItemTag)
1554 }
1555 fn flatten_outputs(items: impl Iterator<Item = Self::OutputTy>) -> Self::OutputTy {
1556 items.flatten().collect()
1557 }
1558 fn as_target(&self) -> Target {
1559 Target::from_assoc_item_kind(&self.wrapped.kind, AssocCtxt::Impl { of_trait: false })
1560 }
1561}
1562
1563struct TraitImplItemTag;
1564impl InvocationCollectorNode for AstNodeWrapper<Box<ast::AssocItem>, TraitImplItemTag> {
1565 type OutputTy = SmallVec<[Box<ast::AssocItem>; 1]>;
1566 type ItemKind = AssocItemKind;
1567 const KIND: AstFragmentKind = AstFragmentKind::TraitImplItems;
1568 fn to_annotatable(self) -> Annotatable {
1569 Annotatable::AssocItem(self.wrapped, AssocCtxt::Impl { of_trait: true })
1570 }
1571 fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1572 fragment.make_trait_impl_items()
1573 }
1574 fn walk_flat_map(self, collector: &mut InvocationCollector<'_, '_>) -> Self::OutputTy {
1575 walk_flat_map_assoc_item(collector, self.wrapped, AssocCtxt::Impl { of_trait: true })
1576 }
1577 fn is_mac_call(&self) -> bool {
1578 #[allow(non_exhaustive_omitted_patterns)] match self.wrapped.kind {
AssocItemKind::MacCall(..) => true,
_ => false,
}matches!(self.wrapped.kind, AssocItemKind::MacCall(..))
1579 }
1580 fn take_mac_call(self) -> (Box<ast::MacCall>, ast::AttrVec, AddSemicolon) {
1581 let item = self.wrapped;
1582 match item.kind {
1583 AssocItemKind::MacCall(mac) => (mac, item.attrs, AddSemicolon::No),
1584 _ => ::core::panicking::unreachable_default_msg()unreachable!(),
1585 }
1586 }
1587 fn delegation(&self) -> Option<(&ast::DelegationMac, &ast::Item<Self::ItemKind>)> {
1588 match &self.wrapped.kind {
1589 AssocItemKind::DelegationMac(deleg) => Some((deleg, &self.wrapped)),
1590 _ => None,
1591 }
1592 }
1593 fn delegation_item_kind(deleg: Box<ast::Delegation>) -> Self::ItemKind {
1594 AssocItemKind::Delegation(deleg)
1595 }
1596 fn from_item(item: ast::Item<Self::ItemKind>) -> Self {
1597 AstNodeWrapper::new(Box::new(item), TraitImplItemTag)
1598 }
1599 fn flatten_outputs(items: impl Iterator<Item = Self::OutputTy>) -> Self::OutputTy {
1600 items.flatten().collect()
1601 }
1602 fn as_target(&self) -> Target {
1603 Target::from_assoc_item_kind(&self.wrapped.kind, AssocCtxt::Impl { of_trait: true })
1604 }
1605}
1606
1607impl InvocationCollectorNode for Box<ast::ForeignItem> {
1608 const KIND: AstFragmentKind = AstFragmentKind::ForeignItems;
1609 fn to_annotatable(self) -> Annotatable {
1610 Annotatable::ForeignItem(self)
1611 }
1612 fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1613 fragment.make_foreign_items()
1614 }
1615 fn walk_flat_map(self, collector: &mut InvocationCollector<'_, '_>) -> Self::OutputTy {
1616 walk_flat_map_foreign_item(collector, self)
1617 }
1618 fn is_mac_call(&self) -> bool {
1619 #[allow(non_exhaustive_omitted_patterns)] match self.kind {
ForeignItemKind::MacCall(..) => true,
_ => false,
}matches!(self.kind, ForeignItemKind::MacCall(..))
1620 }
1621 fn take_mac_call(self) -> (Box<ast::MacCall>, ast::AttrVec, AddSemicolon) {
1622 match self.kind {
1623 ForeignItemKind::MacCall(mac) => (mac, self.attrs, AddSemicolon::No),
1624 _ => ::core::panicking::unreachable_default_msg()unreachable!(),
1625 }
1626 }
1627 fn as_target(&self) -> Target {
1628 match &self.kind {
1629 ForeignItemKind::Static(_) => Target::ForeignStatic,
1630 ForeignItemKind::Fn(_) => Target::ForeignFn,
1631 ForeignItemKind::TyAlias(_) => Target::ForeignTy,
1632 ForeignItemKind::MacCall(_) => Target::MacroCall,
1633 }
1634 }
1635}
1636
1637impl InvocationCollectorNode for ast::Variant {
1638 const KIND: AstFragmentKind = AstFragmentKind::Variants;
1639 fn to_annotatable(self) -> Annotatable {
1640 Annotatable::Variant(self)
1641 }
1642 fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1643 fragment.make_variants()
1644 }
1645 fn walk_flat_map(self, collector: &mut InvocationCollector<'_, '_>) -> Self::OutputTy {
1646 walk_flat_map_variant(collector, self)
1647 }
1648 fn as_target(&self) -> Target {
1649 Target::Variant
1650 }
1651}
1652
1653impl InvocationCollectorNode for ast::WherePredicate {
1654 const KIND: AstFragmentKind = AstFragmentKind::WherePredicates;
1655 fn to_annotatable(self) -> Annotatable {
1656 Annotatable::WherePredicate(self)
1657 }
1658 fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1659 fragment.make_where_predicates()
1660 }
1661 fn walk_flat_map(self, collector: &mut InvocationCollector<'_, '_>) -> Self::OutputTy {
1662 walk_flat_map_where_predicate(collector, self)
1663 }
1664 fn as_target(&self) -> Target {
1665 Target::WherePredicate
1666 }
1667}
1668
1669impl InvocationCollectorNode for ast::FieldDef {
1670 const KIND: AstFragmentKind = AstFragmentKind::FieldDefs;
1671 fn to_annotatable(self) -> Annotatable {
1672 Annotatable::FieldDef(self)
1673 }
1674 fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1675 fragment.make_field_defs()
1676 }
1677 fn walk_flat_map(self, collector: &mut InvocationCollector<'_, '_>) -> Self::OutputTy {
1678 walk_flat_map_field_def(collector, self)
1679 }
1680 fn as_target(&self) -> Target {
1681 Target::Field
1682 }
1683}
1684
1685impl InvocationCollectorNode for ast::PatField {
1686 const KIND: AstFragmentKind = AstFragmentKind::PatFields;
1687 fn to_annotatable(self) -> Annotatable {
1688 Annotatable::PatField(self)
1689 }
1690 fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1691 fragment.make_pat_fields()
1692 }
1693 fn walk_flat_map(self, collector: &mut InvocationCollector<'_, '_>) -> Self::OutputTy {
1694 walk_flat_map_pat_field(collector, self)
1695 }
1696 fn as_target(&self) -> Target {
1697 Target::PatField
1698 }
1699}
1700
1701impl InvocationCollectorNode for ast::ExprField {
1702 const KIND: AstFragmentKind = AstFragmentKind::ExprFields;
1703 fn to_annotatable(self) -> Annotatable {
1704 Annotatable::ExprField(self)
1705 }
1706 fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1707 fragment.make_expr_fields()
1708 }
1709 fn walk_flat_map(self, collector: &mut InvocationCollector<'_, '_>) -> Self::OutputTy {
1710 walk_flat_map_expr_field(collector, self)
1711 }
1712 fn as_target(&self) -> Target {
1713 Target::ExprField
1714 }
1715}
1716
1717impl InvocationCollectorNode for ast::Param {
1718 const KIND: AstFragmentKind = AstFragmentKind::Params;
1719 fn to_annotatable(self) -> Annotatable {
1720 Annotatable::Param(self)
1721 }
1722 fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1723 fragment.make_params()
1724 }
1725 fn walk_flat_map(self, collector: &mut InvocationCollector<'_, '_>) -> Self::OutputTy {
1726 walk_flat_map_param(collector, self)
1727 }
1728 fn as_target(&self) -> Target {
1729 Target::Param
1730 }
1731}
1732
1733impl InvocationCollectorNode for ast::GenericParam {
1734 const KIND: AstFragmentKind = AstFragmentKind::GenericParams;
1735 fn to_annotatable(self) -> Annotatable {
1736 Annotatable::GenericParam(self)
1737 }
1738 fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1739 fragment.make_generic_params()
1740 }
1741 fn walk_flat_map(self, collector: &mut InvocationCollector<'_, '_>) -> Self::OutputTy {
1742 walk_flat_map_generic_param(collector, self)
1743 }
1744 fn as_target(&self) -> Target {
1745 match self.kind {
1746 rustc_ast::GenericParamKind::Lifetime => Target::LifetimeParam,
1747 rustc_ast::GenericParamKind::Type { .. } => Target::TypeParam,
1748 rustc_ast::GenericParamKind::Const { .. } => Target::ConstParam,
1749 }
1750 }
1751}
1752
1753impl InvocationCollectorNode for ast::Arm {
1754 const KIND: AstFragmentKind = AstFragmentKind::Arms;
1755 fn to_annotatable(self) -> Annotatable {
1756 Annotatable::Arm(self)
1757 }
1758 fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1759 fragment.make_arms()
1760 }
1761 fn walk_flat_map(self, collector: &mut InvocationCollector<'_, '_>) -> Self::OutputTy {
1762 walk_flat_map_arm(collector, self)
1763 }
1764 fn as_target(&self) -> Target {
1765 Target::Arm
1766 }
1767}
1768
1769impl InvocationCollectorNode for ast::Stmt {
1770 const KIND: AstFragmentKind = AstFragmentKind::Stmts;
1771 fn to_annotatable(self) -> Annotatable {
1772 Annotatable::Stmt(self)
1773 }
1774 fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1775 fragment.make_stmts()
1776 }
1777 fn walk_flat_map(self, collector: &mut InvocationCollector<'_, '_>) -> Self::OutputTy {
1778 walk_flat_map_stmt(collector, self)
1779 }
1780 fn is_mac_call(&self) -> bool {
1781 match &self.kind {
1782 StmtKind::MacCall(..) => true,
1783 StmtKind::Item(item) => #[allow(non_exhaustive_omitted_patterns)] match item.kind {
ItemKind::MacCall(..) => true,
_ => false,
}matches!(item.kind, ItemKind::MacCall(..)),
1784 StmtKind::Semi(expr) => #[allow(non_exhaustive_omitted_patterns)] match expr.kind {
ExprKind::MacCall(..) => true,
_ => false,
}matches!(expr.kind, ExprKind::MacCall(..)),
1785 StmtKind::Expr(..) => ::core::panicking::unreachable_default_msg()unreachable!(),
1786 StmtKind::Let(..) | StmtKind::Empty => false,
1787 }
1788 }
1789 fn take_mac_call(self) -> (Box<ast::MacCall>, ast::AttrVec, AddSemicolon) {
1790 let (add_semicolon, mac, attrs) = match self.kind {
1793 StmtKind::MacCall(mac) => {
1794 let ast::MacCallStmt { mac, style, attrs, .. } = *mac;
1795 (style == MacStmtStyle::Semicolon, mac, attrs)
1796 }
1797 StmtKind::Item(item) => match *item {
1798 ast::Item { kind: ItemKind::MacCall(mac), attrs, .. } => {
1799 (mac.args.need_semicolon(), mac, attrs)
1800 }
1801 _ => ::core::panicking::unreachable_default_msg()unreachable!(),
1802 },
1803 StmtKind::Semi(expr) => match *expr {
1804 ast::Expr { kind: ExprKind::MacCall(mac), attrs, .. } => {
1805 (mac.args.need_semicolon(), mac, attrs)
1806 }
1807 _ => ::core::panicking::unreachable_default_msg()unreachable!(),
1808 },
1809 _ => ::core::panicking::unreachable_default_msg()unreachable!(),
1810 };
1811 (mac, attrs, if add_semicolon { AddSemicolon::Yes } else { AddSemicolon::No })
1812 }
1813 fn delegation(&self) -> Option<(&ast::DelegationMac, &ast::Item<Self::ItemKind>)> {
1814 match &self.kind {
1815 StmtKind::Item(item) => match &item.kind {
1816 ItemKind::DelegationMac(deleg) => Some((deleg, item)),
1817 _ => None,
1818 },
1819 _ => None,
1820 }
1821 }
1822 fn delegation_item_kind(deleg: Box<ast::Delegation>) -> Self::ItemKind {
1823 ItemKind::Delegation(deleg)
1824 }
1825 fn from_item(item: ast::Item<Self::ItemKind>) -> Self {
1826 ast::Stmt { id: ast::DUMMY_NODE_ID, span: item.span, kind: StmtKind::Item(Box::new(item)) }
1827 }
1828 fn flatten_outputs(items: impl Iterator<Item = Self::OutputTy>) -> Self::OutputTy {
1829 items.flatten().collect()
1830 }
1831 fn post_flat_map_node_collect_bang(stmts: &mut Self::OutputTy, add_semicolon: AddSemicolon) {
1832 if #[allow(non_exhaustive_omitted_patterns)] match add_semicolon {
AddSemicolon::Yes => true,
_ => false,
}matches!(add_semicolon, AddSemicolon::Yes) {
1835 if let Some(stmt) = stmts.pop() {
1836 stmts.push(stmt.add_trailing_semicolon());
1837 }
1838 }
1839 }
1840 fn as_target(&self) -> Target {
1841 Target::Statement
1842 }
1843}
1844
1845impl InvocationCollectorNode for ast::Crate {
1846 type OutputTy = ast::Crate;
1847 const KIND: AstFragmentKind = AstFragmentKind::Crate;
1848 fn to_annotatable(self) -> Annotatable {
1849 Annotatable::Crate(self)
1850 }
1851 fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1852 fragment.make_crate()
1853 }
1854 fn walk(&mut self, collector: &mut InvocationCollector<'_, '_>) {
1855 walk_crate(collector, self)
1856 }
1857 fn expand_cfg_false(
1858 &mut self,
1859 collector: &mut InvocationCollector<'_, '_>,
1860 pos: usize,
1861 _span: Span,
1862 ) {
1863 self.attrs.truncate(pos);
1866 self.items.truncate(collector.cx.num_standard_library_imports);
1868 }
1869 fn as_target(&self) -> Target {
1870 Target::Crate
1871 }
1872}
1873
1874impl InvocationCollectorNode for ast::Ty {
1875 type OutputTy = Box<ast::Ty>;
1876 const KIND: AstFragmentKind = AstFragmentKind::Ty;
1877 fn to_annotatable(self) -> Annotatable {
1878 ::core::panicking::unreachable_default_msg()unreachable!()
1879 }
1880 fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1881 fragment.make_ty()
1882 }
1883 fn walk(&mut self, collector: &mut InvocationCollector<'_, '_>) {
1884 if let ast::TyKind::ImplTrait(..) = self.kind {
1887 let name = Symbol::intern(&pprust::ty_to_string(self).replace('\n', " "));
1892 collector.cx.resolver.insert_impl_trait_name(self.id, name);
1893 }
1894 walk_ty(collector, self)
1895 }
1896 fn is_mac_call(&self) -> bool {
1897 #[allow(non_exhaustive_omitted_patterns)] match self.kind {
ast::TyKind::MacCall(..) => true,
_ => false,
}matches!(self.kind, ast::TyKind::MacCall(..))
1898 }
1899 fn take_mac_call(self) -> (Box<ast::MacCall>, ast::AttrVec, AddSemicolon) {
1900 match self.kind {
1901 TyKind::MacCall(mac) => (mac, AttrVec::new(), AddSemicolon::No),
1902 _ => ::core::panicking::unreachable_default_msg()unreachable!(),
1903 }
1904 }
1905 fn as_target(&self) -> Target {
1906 ::core::panicking::unreachable_default_msg()unreachable!()
1908 }
1909}
1910
1911impl InvocationCollectorNode for ast::Pat {
1912 type OutputTy = Box<ast::Pat>;
1913 const KIND: AstFragmentKind = AstFragmentKind::Pat;
1914 fn to_annotatable(self) -> Annotatable {
1915 ::core::panicking::unreachable_default_msg()unreachable!()
1916 }
1917 fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1918 fragment.make_pat()
1919 }
1920 fn walk(&mut self, collector: &mut InvocationCollector<'_, '_>) {
1921 walk_pat(collector, self)
1922 }
1923 fn is_mac_call(&self) -> bool {
1924 #[allow(non_exhaustive_omitted_patterns)] match self.kind {
PatKind::MacCall(..) => true,
_ => false,
}matches!(self.kind, PatKind::MacCall(..))
1925 }
1926 fn take_mac_call(self) -> (Box<ast::MacCall>, ast::AttrVec, AddSemicolon) {
1927 match self.kind {
1928 PatKind::MacCall(mac) => (mac, AttrVec::new(), AddSemicolon::No),
1929 _ => ::core::panicking::unreachable_default_msg()unreachable!(),
1930 }
1931 }
1932 fn as_target(&self) -> Target {
1933 ::core::panicking::unimplemented_default_msg();unimplemented!();
1934 }
1935}
1936
1937impl InvocationCollectorNode for ast::Expr {
1938 type OutputTy = Box<ast::Expr>;
1939 const KIND: AstFragmentKind = AstFragmentKind::Expr;
1940 fn to_annotatable(self) -> Annotatable {
1941 Annotatable::Expr(Box::new(self))
1942 }
1943 fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1944 fragment.make_expr()
1945 }
1946 fn walk(&mut self, collector: &mut InvocationCollector<'_, '_>) {
1947 walk_expr(collector, self)
1948 }
1949 fn is_mac_call(&self) -> bool {
1950 #[allow(non_exhaustive_omitted_patterns)] match self.kind {
ExprKind::MacCall(..) => true,
_ => false,
}matches!(self.kind, ExprKind::MacCall(..))
1951 }
1952 fn take_mac_call(self) -> (Box<ast::MacCall>, ast::AttrVec, AddSemicolon) {
1953 match self.kind {
1954 ExprKind::MacCall(mac) => (mac, self.attrs, AddSemicolon::No),
1955 _ => ::core::panicking::unreachable_default_msg()unreachable!(),
1956 }
1957 }
1958 fn as_target(&self) -> Target {
1959 Target::Expression
1960 }
1961}
1962
1963struct OptExprTag;
1964impl InvocationCollectorNode for AstNodeWrapper<Box<ast::Expr>, OptExprTag> {
1965 type OutputTy = Option<Box<ast::Expr>>;
1966 const KIND: AstFragmentKind = AstFragmentKind::OptExpr;
1967 fn to_annotatable(self) -> Annotatable {
1968 Annotatable::Expr(self.wrapped)
1969 }
1970 fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1971 fragment.make_opt_expr()
1972 }
1973 fn walk_flat_map(mut self, collector: &mut InvocationCollector<'_, '_>) -> Self::OutputTy {
1974 walk_expr(collector, &mut self.wrapped);
1975 Some(self.wrapped)
1976 }
1977 fn is_mac_call(&self) -> bool {
1978 #[allow(non_exhaustive_omitted_patterns)] match self.wrapped.kind {
ast::ExprKind::MacCall(..) => true,
_ => false,
}matches!(self.wrapped.kind, ast::ExprKind::MacCall(..))
1979 }
1980 fn take_mac_call(self) -> (Box<ast::MacCall>, ast::AttrVec, AddSemicolon) {
1981 let node = self.wrapped;
1982 match node.kind {
1983 ExprKind::MacCall(mac) => (mac, node.attrs, AddSemicolon::No),
1984 _ => ::core::panicking::unreachable_default_msg()unreachable!(),
1985 }
1986 }
1987 fn pre_flat_map_node_collect_attr(cfg: &StripUnconfigured<'_>, attr: &ast::Attribute) {
1988 cfg.maybe_emit_expr_attr_err(attr);
1989 }
1990 fn as_target(&self) -> Target {
1991 Target::Expression
1992 }
1993}
1994
1995struct MethodReceiverTag;
1998
1999impl InvocationCollectorNode for AstNodeWrapper<ast::Expr, MethodReceiverTag> {
2000 type OutputTy = AstNodeWrapper<Box<ast::Expr>, MethodReceiverTag>;
2001 const KIND: AstFragmentKind = AstFragmentKind::MethodReceiverExpr;
2002 fn to_annotatable(self) -> Annotatable {
2003 Annotatable::Expr(Box::new(self.wrapped))
2004 }
2005 fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
2006 AstNodeWrapper::new(fragment.make_method_receiver_expr(), MethodReceiverTag)
2007 }
2008 fn walk(&mut self, collector: &mut InvocationCollector<'_, '_>) {
2009 walk_expr(collector, &mut self.wrapped)
2010 }
2011 fn is_mac_call(&self) -> bool {
2012 #[allow(non_exhaustive_omitted_patterns)] match self.wrapped.kind {
ast::ExprKind::MacCall(..) => true,
_ => false,
}matches!(self.wrapped.kind, ast::ExprKind::MacCall(..))
2013 }
2014 fn take_mac_call(self) -> (Box<ast::MacCall>, ast::AttrVec, AddSemicolon) {
2015 let node = self.wrapped;
2016 match node.kind {
2017 ExprKind::MacCall(mac) => (mac, node.attrs, AddSemicolon::No),
2018 _ => ::core::panicking::unreachable_default_msg()unreachable!(),
2019 }
2020 }
2021 fn as_target(&self) -> Target {
2022 Target::Expression
2023 }
2024}
2025
2026fn build_single_delegations<'a, Node: InvocationCollectorNode>(
2027 ecx: &ExtCtxt<'_>,
2028 deleg: &'a ast::DelegationMac,
2029 item: &'a ast::Item<Node::ItemKind>,
2030 suffixes: &'a [(Ident, Option<Ident>)],
2031 item_span: Span,
2032 source: DelegationSource,
2033) -> impl Iterator<Item = ast::Item<Node::ItemKind>> + 'a {
2034 if true {
{
match (&source, &DelegationSource::Single) {
(left_val, right_val) => {
if *left_val == *right_val {
let kind = ::core::panicking::AssertKind::Ne;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};
};debug_assert_ne!(source, DelegationSource::Single);
2035
2036 let from_glob = source == DelegationSource::Glob;
2037
2038 if suffixes.is_empty() {
2039 let kind = String::from(if from_glob { "glob" } else { "list" });
2042 ecx.dcx().emit_err(EmptyDelegationMac { span: item.span, kind });
2043 }
2044
2045 suffixes.iter().map(move |&(ident, rename)| {
2046 let mut path = deleg.prefix.clone();
2047 path.segments.push(ast::PathSegment { ident, id: ast::DUMMY_NODE_ID, args: None });
2048
2049 ast::Item {
2050 attrs: item.attrs.clone(),
2051 id: ast::DUMMY_NODE_ID,
2052 span: if from_glob { item_span } else { ident.span },
2053 vis: item.vis.clone(),
2054 kind: Node::delegation_item_kind(Box::new(ast::Delegation {
2055 id: ast::DUMMY_NODE_ID,
2056 qself: deleg.qself.clone(),
2057 path,
2058 ident: rename.unwrap_or(ident),
2059 rename,
2060 body: deleg.body.clone(),
2061 source,
2062 })),
2063 tokens: None,
2064 }
2065 })
2066}
2067
2068trait DummyAstNode {
2070 fn dummy() -> Self;
2071}
2072
2073impl DummyAstNode for ast::Crate {
2074 fn dummy() -> Self {
2075 ast::Crate {
2076 attrs: Default::default(),
2077 items: Default::default(),
2078 spans: Default::default(),
2079 id: DUMMY_NODE_ID,
2080 is_placeholder: Default::default(),
2081 }
2082 }
2083}
2084
2085impl DummyAstNode for ast::Ty {
2086 fn dummy() -> Self {
2087 ast::Ty { id: DUMMY_NODE_ID, kind: TyKind::Dummy, span: Default::default() }
2088 }
2089}
2090
2091impl DummyAstNode for ast::Pat {
2092 fn dummy() -> Self {
2093 ast::Pat { id: DUMMY_NODE_ID, kind: PatKind::Wild, span: Default::default() }
2094 }
2095}
2096
2097impl DummyAstNode for ast::Expr {
2098 fn dummy() -> Self {
2099 ast::Expr::dummy()
2100 }
2101}
2102
2103impl DummyAstNode for AstNodeWrapper<ast::Expr, MethodReceiverTag> {
2104 fn dummy() -> Self {
2105 AstNodeWrapper::new(ast::Expr::dummy(), MethodReceiverTag)
2106 }
2107}
2108
2109struct InvocationCollector<'a, 'b> {
2110 cx: &'a mut ExtCtxt<'b>,
2111 invocations: Vec<(Invocation, Option<Arc<SyntaxExtension>>)>,
2112 monotonic: bool,
2113}
2114
2115impl<'a, 'b> InvocationCollector<'a, 'b> {
2116 fn cfg(&self) -> StripUnconfigured<'_> {
2117 StripUnconfigured {
2118 sess: self.cx.sess,
2119 features: Some(self.cx.ecfg.features),
2120 config_tokens: false,
2121 lint_node_id: self.cx.current_expansion.lint_node_id,
2122 }
2123 }
2124
2125 fn collect(&mut self, fragment_kind: AstFragmentKind, kind: InvocationKind) -> AstFragment {
2126 let expn_id = LocalExpnId::fresh_empty();
2127 if #[allow(non_exhaustive_omitted_patterns)] match kind {
InvocationKind::GlobDelegation { .. } => true,
_ => false,
}matches!(kind, InvocationKind::GlobDelegation { .. }) {
2128 self.cx.resolver.register_glob_delegation(expn_id);
2131 }
2132 let vis = kind.placeholder_visibility();
2133 self.invocations.push((
2134 Invocation {
2135 kind,
2136 fragment_kind,
2137 expansion_data: ExpansionData {
2138 id: expn_id,
2139 depth: self.cx.current_expansion.depth + 1,
2140 ..self.cx.current_expansion.clone()
2141 },
2142 },
2143 None,
2144 ));
2145 placeholder(fragment_kind, NodeId::placeholder_from_expn_id(expn_id), vis)
2146 }
2147
2148 fn collect_bang(&mut self, mac: Box<ast::MacCall>, kind: AstFragmentKind) -> AstFragment {
2149 let span = mac.span();
2152 self.collect(kind, InvocationKind::Bang { mac, span })
2153 }
2154
2155 fn collect_attr(
2156 &mut self,
2157 (attr, pos, derives): (ast::Attribute, usize, Vec<ast::Path>),
2158 item: Annotatable,
2159 kind: AstFragmentKind,
2160 ) -> AstFragment {
2161 self.collect(kind, InvocationKind::Attr { attr, pos, item, derives })
2162 }
2163
2164 fn collect_glob_delegation(
2165 &mut self,
2166 item: Box<ast::AssocItem>,
2167 of_trait: bool,
2168 kind: AstFragmentKind,
2169 ) -> AstFragment {
2170 self.collect(kind, InvocationKind::GlobDelegation { item, of_trait })
2171 }
2172
2173 fn take_first_attr(
2177 &self,
2178 item: &mut impl HasAttrs,
2179 ) -> Option<(ast::Attribute, usize, Vec<ast::Path>)> {
2180 let mut attr = None;
2181
2182 let mut cfg_pos = None;
2183 let mut attr_pos = None;
2184 for (pos, attr) in item.attrs().iter().enumerate() {
2185 if let AttrKind::Normal(..) = attr.kind
2186 && !self.cx.expanded_inert_attrs.is_marked(attr)
2187 {
2188 let name = attr.name();
2189 if name == Some(sym::cfg) || name == Some(sym::cfg_attr) {
2190 cfg_pos = Some(pos); break;
2192 } else if attr_pos.is_none()
2193 && !name.is_some_and(rustc_feature::is_builtin_attr_name)
2194 {
2195 attr_pos = Some(pos); }
2197 }
2198 }
2199
2200 item.visit_attrs(|attrs| {
2201 attr = Some(match (cfg_pos, attr_pos) {
2202 (Some(pos), _) => (attrs.remove(pos), pos, Vec::new()),
2203 (_, Some(pos)) => {
2204 let attr = attrs.remove(pos);
2205 let following_derives = attrs[pos..]
2206 .iter()
2207 .filter(|a| a.has_name(sym::derive))
2208 .flat_map(|a| a.meta_item_list().unwrap_or_default())
2209 .filter_map(|meta_item_inner| match meta_item_inner {
2210 MetaItemInner::MetaItem(ast::MetaItem {
2211 kind: MetaItemKind::Word,
2212 path,
2213 ..
2214 }) => Some(path),
2215 _ => None,
2216 })
2217 .collect();
2218
2219 (attr, pos, following_derives)
2220 }
2221 _ => return,
2222 });
2223 });
2224
2225 attr
2226 }
2227
2228 fn check_attributes(&self, attrs: &[ast::Attribute], call: &ast::MacCall) {
2231 let parse = |group| {
2232 AttributeParser::parse_limited_all(
2233 self.cx.sess,
2234 group,
2235 None,
2236 AstTarget::MacroCall,
2237 call.span(),
2238 self.cx.current_expansion.lint_node_id,
2239 Some(self.cx.ecfg.features),
2240 ShouldEmit::ErrorsAndLints { recovery: Recovery::Allowed },
2241 Some(self.cx.resolver.registered_attr_tools()),
2242 Some(self.cx.resolver.registered_lint_tools()),
2243 )
2244 };
2245
2246 let mut doc_attrs = ::alloc::vec::Vec::new()vec![];
2247 for attr in attrs {
2248 if #[allow(non_exhaustive_omitted_patterns)] match attr.kind {
AttrKind::DocComment(..) => true,
_ => false,
}matches!(attr.kind, AttrKind::DocComment(..)) {
2249 doc_attrs.push(attr.clone());
2250 continue;
2251 }
2252 parse(slice::from_ref(attr));
2253 }
2254
2255 if !doc_attrs.is_empty() {
2258 parse(doc_attrs.as_slice());
2259 }
2260 }
2261
2262 fn expand_cfg_true(
2263 &mut self,
2264 node: &mut impl InvocationCollectorNode,
2265 attr: ast::Attribute,
2266 pos: usize,
2267 ) -> EvalConfigResult {
2268 let Some(cfg) = AttributeParser::parse_single(
2269 self.cfg().sess,
2270 &attr,
2271 attr.span,
2272 self.cfg().lint_node_id,
2273 AstTarget::None(node.as_target()),
2274 self.cfg().features,
2275 ShouldEmit::ErrorsAndLints { recovery: Recovery::Allowed },
2276 parse_cfg,
2277 &CFG_TEMPLATE,
2278 AllowExprMetavar::Yes,
2279 AttributeSafety::Normal,
2280 ) else {
2281 return EvalConfigResult::True;
2283 };
2284
2285 let res = eval_config_entry(self.cfg().sess, &cfg);
2286 if res.as_bool() {
2287 let trace_attr = attr.convert_normal_to_synthetic(SyntheticAttr::CfgTrace(cfg));
2290 node.visit_attrs(|attrs| attrs.insert(pos, trace_attr));
2291 }
2292
2293 res
2294 }
2295
2296 fn expand_cfg_attr(&self, node: &mut impl HasAttrs, attr: &ast::Attribute, pos: usize) {
2297 node.visit_attrs(|attrs| {
2298 for cfg in self.cfg().expand_cfg_attr(attr, false).into_iter().rev() {
2301 attrs.insert(pos, cfg)
2302 }
2303 });
2304 }
2305
2306 fn flat_map_node<Node: InvocationCollectorNode<OutputTy: Default>>(
2307 &mut self,
2308 mut node: Node,
2309 ) -> Node::OutputTy {
2310 loop {
2311 return match self.take_first_attr(&mut node) {
2312 Some((attr, pos, derives)) => match attr.name() {
2313 Some(sym::cfg) => {
2314 let res = self.expand_cfg_true(&mut node, attr, pos);
2315 match res {
2316 EvalConfigResult::True => continue,
2317 EvalConfigResult::False { reason } => {
2318 for ident in node.declared_idents() {
2319 self.cx.resolver.append_stripped_cfg_item(
2320 self.cx.current_expansion.lint_node_id,
2321 ident,
2322 reason.clone(),
2323 reason.span(),
2324 )
2325 }
2326 }
2327 }
2328
2329 Default::default()
2330 }
2331 Some(sym::cfg_attr) => {
2332 self.expand_cfg_attr(&mut node, &attr, pos);
2333 continue;
2334 }
2335 _ => {
2336 Node::pre_flat_map_node_collect_attr(&self.cfg(), &attr);
2337 self.collect_attr((attr, pos, derives), node.to_annotatable(), Node::KIND)
2338 .make_ast::<Node>()
2339 }
2340 },
2341 None if node.is_mac_call() => {
2342 let (mac, attrs, add_semicolon) = node.take_mac_call();
2343 self.check_attributes(&attrs, &mac);
2344 let mut res = self.collect_bang(mac, Node::KIND).make_ast::<Node>();
2345 Node::post_flat_map_node_collect_bang(&mut res, add_semicolon);
2346 res
2347 }
2348 None if let Some((deleg, item)) = node.delegation() => {
2349 let DelegationSuffixes::List(suffixes) = &deleg.suffixes else {
2350 let traitless_qself =
2351 #[allow(non_exhaustive_omitted_patterns)] match &deleg.qself {
Some(qself) if qself.position == 0 => true,
_ => false,
}matches!(&deleg.qself, Some(qself) if qself.position == 0);
2352 let (item, of_trait) = match node.to_annotatable() {
2353 Annotatable::AssocItem(item, AssocCtxt::Impl { of_trait }) => {
2354 (item, of_trait)
2355 }
2356 ann @ (Annotatable::Item(_)
2357 | Annotatable::AssocItem(..)
2358 | Annotatable::Stmt(_)) => {
2359 let span = ann.span();
2360 self.cx.dcx().emit_err(GlobDelegationOutsideImpls { span });
2361 return Default::default();
2362 }
2363 _ => ::core::panicking::unreachable_default_msg()unreachable!(),
2364 };
2365 if traitless_qself {
2366 let span = item.span;
2367 self.cx.dcx().emit_err(GlobDelegationTraitlessQpath { span });
2368 return Default::default();
2369 }
2370 return self
2371 .collect_glob_delegation(item, of_trait, Node::KIND)
2372 .make_ast::<Node>();
2373 };
2374
2375 let single_delegations = build_single_delegations::<Node>(
2376 self.cx,
2377 deleg,
2378 item,
2379 suffixes,
2380 item.span,
2381 DelegationSource::List(LocalExpnId::fresh_empty()),
2382 );
2383 Node::flatten_outputs(single_delegations.map(|item| {
2384 let mut item = Node::from_item(item);
2385 {
let old_id = self.cx.current_expansion.lint_node_id;
if self.monotonic {
if true {
{
match (&*item.node_id_mut(), &ast::DUMMY_NODE_ID) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};
};
let new_id = self.cx.resolver.next_node_id();
*item.node_id_mut() = new_id;
self.cx.current_expansion.lint_node_id = new_id;
}
let ret = (|| item.walk_flat_map(self))();
self.cx.current_expansion.lint_node_id = old_id;
ret
}assign_id!(self, item.node_id_mut(), || item.walk_flat_map(self))
2386 }))
2387 }
2388 None => {
2389 match Node::wrap_flat_map_node_walk_flat_map(node, self, |mut node, this| {
2390 {
let old_id = this.cx.current_expansion.lint_node_id;
if this.monotonic {
if true {
{
match (&*node.node_id_mut(), &ast::DUMMY_NODE_ID) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};
};
let new_id = this.cx.resolver.next_node_id();
*node.node_id_mut() = new_id;
this.cx.current_expansion.lint_node_id = new_id;
}
let ret = (|| node.walk_flat_map(this))();
this.cx.current_expansion.lint_node_id = old_id;
ret
}assign_id!(this, node.node_id_mut(), || node.walk_flat_map(this))
2391 }) {
2392 Ok(output) => output,
2393 Err(returned_node) => {
2394 node = returned_node;
2395 continue;
2396 }
2397 }
2398 }
2399 };
2400 }
2401 }
2402
2403 fn visit_node<Node: InvocationCollectorNode<OutputTy: Into<Node>> + DummyAstNode>(
2404 &mut self,
2405 node: &mut Node,
2406 ) {
2407 loop {
2408 return match self.take_first_attr(node) {
2409 Some((attr, pos, derives)) => match attr.name() {
2410 Some(sym::cfg) => {
2411 let span = attr.span;
2412
2413 match Node::KIND {
2414 AstFragmentKind::Expr | AstFragmentKind::MethodReceiverExpr => {
2415 self.cx.dcx().emit_err(CfgNotSupportedInPosition { span });
2416 }
2417 AstFragmentKind::Crate => {
2418 if !self.expand_cfg_true(node, attr, pos).as_bool() {
2419 node.expand_cfg_false(self, pos, span);
2420 }
2421 }
2422 _ => ::core::panicking::unreachable_default_msg()unreachable!(),
2423 }
2424 continue;
2425 }
2426 Some(sym::cfg_attr) => {
2427 self.expand_cfg_attr(node, &attr, pos);
2428 continue;
2429 }
2430 _ => {
2431 let n = mem::replace(node, Node::dummy());
2432 *node = self
2433 .collect_attr((attr, pos, derives), n.to_annotatable(), Node::KIND)
2434 .make_ast::<Node>()
2435 .into()
2436 }
2437 },
2438 None if node.is_mac_call() => {
2439 let n = mem::replace(node, Node::dummy());
2440 let (mac, attrs, _) = n.take_mac_call();
2441 self.check_attributes(&attrs, &mac);
2442
2443 *node = self.collect_bang(mac, Node::KIND).make_ast::<Node>().into()
2444 }
2445 None if node.delegation().is_some() => ::core::panicking::unreachable_default_msg()unreachable!(),
2446 None => {
2447 {
let old_id = self.cx.current_expansion.lint_node_id;
if self.monotonic {
if true {
{
match (&*node.node_id_mut(), &ast::DUMMY_NODE_ID) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};
};
let new_id = self.cx.resolver.next_node_id();
*node.node_id_mut() = new_id;
self.cx.current_expansion.lint_node_id = new_id;
}
let ret = (|| node.walk(self))();
self.cx.current_expansion.lint_node_id = old_id;
ret
}assign_id!(self, node.node_id_mut(), || node.walk(self))
2448 }
2449 };
2450 }
2451 }
2452}
2453
2454impl<'a, 'b> MutVisitor for InvocationCollector<'a, 'b> {
2455 fn flat_map_item(&mut self, node: Box<ast::Item>) -> SmallVec<[Box<ast::Item>; 1]> {
2456 self.flat_map_node(node)
2457 }
2458
2459 fn flat_map_assoc_item(
2460 &mut self,
2461 node: Box<ast::AssocItem>,
2462 ctxt: AssocCtxt,
2463 ) -> SmallVec<[Box<ast::AssocItem>; 1]> {
2464 match ctxt {
2465 AssocCtxt::Trait => self.flat_map_node(AstNodeWrapper::new(node, TraitItemTag)),
2466 AssocCtxt::Impl { of_trait: false, .. } => {
2467 self.flat_map_node(AstNodeWrapper::new(node, ImplItemTag))
2468 }
2469 AssocCtxt::Impl { of_trait: true, .. } => {
2470 self.flat_map_node(AstNodeWrapper::new(node, TraitImplItemTag))
2471 }
2472 }
2473 }
2474
2475 fn flat_map_foreign_item(
2476 &mut self,
2477 node: Box<ast::ForeignItem>,
2478 ) -> SmallVec<[Box<ast::ForeignItem>; 1]> {
2479 self.flat_map_node(node)
2480 }
2481
2482 fn flat_map_variant(&mut self, node: ast::Variant) -> SmallVec<[ast::Variant; 1]> {
2483 self.flat_map_node(node)
2484 }
2485
2486 fn flat_map_where_predicate(
2487 &mut self,
2488 node: ast::WherePredicate,
2489 ) -> SmallVec<[ast::WherePredicate; 1]> {
2490 self.flat_map_node(node)
2491 }
2492
2493 fn flat_map_field_def(&mut self, node: ast::FieldDef) -> SmallVec<[ast::FieldDef; 1]> {
2494 self.flat_map_node(node)
2495 }
2496
2497 fn flat_map_pat_field(&mut self, node: ast::PatField) -> SmallVec<[ast::PatField; 1]> {
2498 self.flat_map_node(node)
2499 }
2500
2501 fn flat_map_expr_field(&mut self, node: ast::ExprField) -> SmallVec<[ast::ExprField; 1]> {
2502 self.flat_map_node(node)
2503 }
2504
2505 fn flat_map_param(&mut self, node: ast::Param) -> SmallVec<[ast::Param; 1]> {
2506 self.flat_map_node(node)
2507 }
2508
2509 fn flat_map_generic_param(
2510 &mut self,
2511 node: ast::GenericParam,
2512 ) -> SmallVec<[ast::GenericParam; 1]> {
2513 self.flat_map_node(node)
2514 }
2515
2516 fn flat_map_arm(&mut self, node: ast::Arm) -> SmallVec<[ast::Arm; 1]> {
2517 self.flat_map_node(node)
2518 }
2519
2520 fn flat_map_stmt(&mut self, node: ast::Stmt) -> SmallVec<[ast::Stmt; 1]> {
2521 if node.is_expr() {
2524 return match &node.kind {
2532 StmtKind::Expr(expr)
2533 if #[allow(non_exhaustive_omitted_patterns)] match **expr {
ast::Expr { kind: ExprKind::MacCall(..), .. } => true,
_ => false,
}matches!(**expr, ast::Expr { kind: ExprKind::MacCall(..), .. }) =>
2534 {
2535 self.cx.current_expansion.is_trailing_mac = true;
2536 let res = walk_flat_map_stmt(self, node);
2539 self.cx.current_expansion.is_trailing_mac = false;
2540 res
2541 }
2542 _ => walk_flat_map_stmt(self, node),
2543 };
2544 }
2545
2546 self.flat_map_node(node)
2547 }
2548
2549 fn visit_crate(&mut self, node: &mut ast::Crate) {
2550 self.visit_node(node)
2551 }
2552
2553 fn visit_ty(&mut self, node: &mut ast::Ty) {
2554 self.visit_node(node)
2555 }
2556
2557 fn visit_pat(&mut self, node: &mut ast::Pat) {
2558 self.visit_node(node)
2559 }
2560
2561 fn visit_expr(&mut self, node: &mut ast::Expr) {
2562 if let Some(attr) = node.attrs.first() {
2564 self.cfg().maybe_emit_expr_attr_err(attr);
2565 }
2566 self.visit_node(node)
2567 }
2568
2569 fn visit_method_receiver_expr(&mut self, node: &mut ast::Expr) {
2570 self.visit_node(AstNodeWrapper::from_mut(node, MethodReceiverTag))
2571 }
2572
2573 fn filter_map_expr(&mut self, node: Box<ast::Expr>) -> Option<Box<ast::Expr>> {
2574 self.flat_map_node(AstNodeWrapper::new(node, OptExprTag))
2575 }
2576
2577 fn visit_block(&mut self, node: &mut ast::Block) {
2578 let orig_dir_ownership = mem::replace(
2579 &mut self.cx.current_expansion.dir_ownership,
2580 DirOwnership::UnownedViaBlock,
2581 );
2582 walk_block(self, node);
2583 self.cx.current_expansion.dir_ownership = orig_dir_ownership;
2584 }
2585
2586 fn visit_id(&mut self, id: &mut NodeId) {
2587 if self.monotonic && *id == ast::DUMMY_NODE_ID {
2590 *id = self.cx.resolver.next_node_id();
2591 }
2592 }
2593}
2594
2595pub struct ExpansionConfig<'feat> {
2596 pub crate_name: Symbol,
2597 pub features: &'feat Features,
2598 pub recursion_limit: Limit,
2599 pub trace_mac: bool,
2600 pub should_test: bool,
2602 pub span_debug: bool,
2604 pub proc_macro_backtrace: bool,
2606}
2607
2608impl ExpansionConfig<'_> {
2609 pub fn default(crate_name: Symbol, features: &Features) -> ExpansionConfig<'_> {
2610 ExpansionConfig {
2611 crate_name,
2612 features,
2613 recursion_limit: Limit::new(1024),
2615 trace_mac: false,
2616 should_test: false,
2617 span_debug: false,
2618 proc_macro_backtrace: false,
2619 }
2620 }
2621}