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