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