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