1use std::mem;
2
3use rustc_ast::visit::FnKind;
4use rustc_ast::*;
5use rustc_attr_parsing::{AttributeParser, Early, OmitDoc, ShouldEmit};
6use rustc_expand::expand::AstFragment;
7use rustc_hir as hir;
8use rustc_hir::Target;
9use rustc_hir::def::{CtorKind, CtorOf, DefKind};
10use rustc_hir::def_id::LocalDefId;
11use rustc_middle::span_bug;
12use rustc_span::hygiene::LocalExpnId;
13use rustc_span::{Span, Symbol, sym};
14use tracing::debug;
15
16use crate::{ImplTraitContext, InvocationParent, Resolver};
17
18pub(crate) fn collect_definitions(
19 resolver: &mut Resolver<'_, '_>,
20 fragment: &AstFragment,
21 expansion: LocalExpnId,
22) {
23 let invocation_parent = resolver.invocation_parents[&expansion];
24 let mut visitor = DefCollector { resolver, expansion, invocation_parent };
25 fragment.visit_with(&mut visitor);
26}
27
28struct DefCollector<'a, 'ra, 'tcx> {
30 resolver: &'a mut Resolver<'ra, 'tcx>,
31 invocation_parent: InvocationParent,
32 expansion: LocalExpnId,
33}
34
35impl<'a, 'ra, 'tcx> DefCollector<'a, 'ra, 'tcx> {
36 fn create_def(
37 &mut self,
38 node_id: NodeId,
39 name: Option<Symbol>,
40 def_kind: DefKind,
41 span: Span,
42 ) -> LocalDefId {
43 let parent_def = self.invocation_parent.parent_def;
44 debug!(
45 "create_def(node_id={:?}, def_kind={:?}, parent_def={:?})",
46 node_id, def_kind, parent_def
47 );
48 self.resolver
49 .create_def(
50 parent_def,
51 node_id,
52 name,
53 def_kind,
54 self.expansion.to_expn_id(),
55 span.with_parent(None),
56 )
57 .def_id()
58 }
59
60 fn with_parent<F: FnOnce(&mut Self)>(&mut self, parent_def: LocalDefId, f: F) {
61 let orig_parent_def = mem::replace(&mut self.invocation_parent.parent_def, parent_def);
62 f(self);
63 self.invocation_parent.parent_def = orig_parent_def;
64 }
65
66 fn with_impl_trait<F: FnOnce(&mut Self)>(
67 &mut self,
68 impl_trait_context: ImplTraitContext,
69 f: F,
70 ) {
71 let orig_itc =
72 mem::replace(&mut self.invocation_parent.impl_trait_context, impl_trait_context);
73 f(self);
74 self.invocation_parent.impl_trait_context = orig_itc;
75 }
76
77 fn collect_field(&mut self, field: &'a FieldDef, index: Option<usize>) {
78 let index = |this: &Self| {
79 index.unwrap_or_else(|| {
80 let node_id = NodeId::placeholder_from_expn_id(this.expansion);
81 this.resolver.placeholder_field_indices[&node_id]
82 })
83 };
84
85 if field.is_placeholder {
86 let old_index = self.resolver.placeholder_field_indices.insert(field.id, index(self));
87 assert!(old_index.is_none(), "placeholder field index is reset for a node ID");
88 self.visit_macro_invoc(field.id);
89 } else {
90 let name = field.ident.map_or_else(|| sym::integer(index(self)), |ident| ident.name);
91 let def = self.create_def(field.id, Some(name), DefKind::Field, field.span);
92 self.with_parent(def, |this| visit::walk_field_def(this, field));
93 }
94 }
95
96 fn visit_macro_invoc(&mut self, id: NodeId) {
97 let id = id.placeholder_to_expn_id();
98 let old_parent = self.resolver.invocation_parents.insert(id, self.invocation_parent);
99 assert!(old_parent.is_none(), "parent `LocalDefId` is reset for an invocation");
100 }
101}
102
103impl<'a, 'ra, 'tcx> visit::Visitor<'a> for DefCollector<'a, 'ra, 'tcx> {
104 fn visit_item(&mut self, i: &'a Item) {
105 let mut opt_macro_data = None;
108 let def_kind = match &i.kind {
109 ItemKind::Impl(i) => DefKind::Impl { of_trait: i.of_trait.is_some() },
110 ItemKind::ForeignMod(..) => DefKind::ForeignMod,
111 ItemKind::Mod(..) => DefKind::Mod,
112 ItemKind::Trait(..) => DefKind::Trait,
113 ItemKind::TraitAlias(..) => DefKind::TraitAlias,
114 ItemKind::Enum(..) => DefKind::Enum,
115 ItemKind::Struct(..) => DefKind::Struct,
116 ItemKind::Union(..) => DefKind::Union,
117 ItemKind::ExternCrate(..) => DefKind::ExternCrate,
118 ItemKind::TyAlias(..) => DefKind::TyAlias,
119 ItemKind::Static(s) => DefKind::Static {
120 safety: hir::Safety::Safe,
121 mutability: s.mutability,
122 nested: false,
123 },
124 ItemKind::Const(..) => DefKind::Const,
125 ItemKind::Fn(..) | ItemKind::Delegation(..) => DefKind::Fn,
126 ItemKind::MacroDef(ident, def) => {
127 let edition = i.span.edition();
128
129 let mut parser = AttributeParser::<'_, Early>::new(
133 &self.resolver.tcx.sess,
134 self.resolver.tcx.features(),
135 Vec::new(),
136 Early { emit_errors: ShouldEmit::Nothing },
137 );
138 let attrs = parser.parse_attribute_list(
139 &i.attrs,
140 i.span,
141 i.id,
142 Target::MacroDef,
143 OmitDoc::Skip,
144 std::convert::identity,
145 |_l| {
146 },
150 );
151
152 let macro_data =
153 self.resolver.compile_macro(def, *ident, &attrs, i.span, i.id, edition);
154 let macro_kinds = macro_data.ext.macro_kinds();
155 opt_macro_data = Some(macro_data);
156 DefKind::Macro(macro_kinds)
157 }
158 ItemKind::GlobalAsm(..) => DefKind::GlobalAsm,
159 ItemKind::Use(use_tree) => {
160 self.create_def(i.id, None, DefKind::Use, use_tree.span);
161 return visit::walk_item(self, i);
162 }
163 ItemKind::MacCall(..) | ItemKind::DelegationMac(..) => {
164 return self.visit_macro_invoc(i.id);
165 }
166 };
167 let def_id =
168 self.create_def(i.id, i.kind.ident().map(|ident| ident.name), def_kind, i.span);
169
170 if let Some(macro_data) = opt_macro_data {
171 self.resolver.new_local_macro(def_id, macro_data);
172 }
173
174 self.with_parent(def_id, |this| {
175 this.with_impl_trait(ImplTraitContext::Existential, |this| {
176 match i.kind {
177 ItemKind::Struct(_, _, ref struct_def)
178 | ItemKind::Union(_, _, ref struct_def) => {
179 if let Some((ctor_kind, ctor_node_id)) = CtorKind::from_ast(struct_def) {
181 this.create_def(
182 ctor_node_id,
183 None,
184 DefKind::Ctor(CtorOf::Struct, ctor_kind),
185 i.span,
186 );
187 }
188 }
189 _ => {}
190 }
191 visit::walk_item(this, i);
192 })
193 });
194 }
195
196 fn visit_fn(&mut self, fn_kind: FnKind<'a>, _: &AttrVec, span: Span, _: NodeId) {
197 match fn_kind {
198 FnKind::Fn(
199 _ctxt,
200 _vis,
201 Fn {
202 sig: FnSig { header, decl, span: _ }, ident, generics, contract, body, ..
203 },
204 ) if let Some(coroutine_kind) = header.coroutine_kind => {
205 self.visit_ident(ident);
206 self.visit_fn_header(header);
207 self.visit_generics(generics);
208 if let Some(contract) = contract {
209 self.visit_contract(contract);
210 }
211
212 let FnDecl { inputs, output } = &**decl;
216 for param in inputs {
217 self.visit_param(param);
218 }
219
220 let (return_id, return_span) = coroutine_kind.return_id();
221 let return_def = self.create_def(return_id, None, DefKind::OpaqueTy, return_span);
222 self.with_parent(return_def, |this| this.visit_fn_ret_ty(output));
223
224 if let Some(body) = body {
228 let closure_def =
229 self.create_def(coroutine_kind.closure_id(), None, DefKind::Closure, span);
230 self.with_parent(closure_def, |this| this.visit_block(body));
231 }
232 }
233 FnKind::Closure(binder, Some(coroutine_kind), decl, body) => {
234 self.visit_closure_binder(binder);
235 visit::walk_fn_decl(self, decl);
236
237 let coroutine_def =
240 self.create_def(coroutine_kind.closure_id(), None, DefKind::Closure, span);
241 self.with_parent(coroutine_def, |this| this.visit_expr(body));
242 }
243 _ => visit::walk_fn(self, fn_kind),
244 }
245 }
246
247 fn visit_nested_use_tree(&mut self, use_tree: &'a UseTree, id: NodeId) {
248 self.create_def(id, None, DefKind::Use, use_tree.span);
249 visit::walk_use_tree(self, use_tree);
250 }
251
252 fn visit_foreign_item(&mut self, fi: &'a ForeignItem) {
253 let (ident, def_kind) = match fi.kind {
254 ForeignItemKind::Static(box StaticItem {
255 ident,
256 ty: _,
257 mutability,
258 expr: _,
259 safety,
260 define_opaque: _,
261 }) => {
262 let safety = match safety {
263 ast::Safety::Unsafe(_) | ast::Safety::Default => hir::Safety::Unsafe,
264 ast::Safety::Safe(_) => hir::Safety::Safe,
265 };
266
267 (ident, DefKind::Static { safety, mutability, nested: false })
268 }
269 ForeignItemKind::Fn(box Fn { ident, .. }) => (ident, DefKind::Fn),
270 ForeignItemKind::TyAlias(box TyAlias { ident, .. }) => (ident, DefKind::ForeignTy),
271 ForeignItemKind::MacCall(_) => return self.visit_macro_invoc(fi.id),
272 };
273
274 let def = self.create_def(fi.id, Some(ident.name), def_kind, fi.span);
275
276 self.with_parent(def, |this| visit::walk_item(this, fi));
277 }
278
279 fn visit_variant(&mut self, v: &'a Variant) {
280 if v.is_placeholder {
281 return self.visit_macro_invoc(v.id);
282 }
283 let def = self.create_def(v.id, Some(v.ident.name), DefKind::Variant, v.span);
284 self.with_parent(def, |this| {
285 if let Some((ctor_kind, ctor_node_id)) = CtorKind::from_ast(&v.data) {
286 this.create_def(
287 ctor_node_id,
288 None,
289 DefKind::Ctor(CtorOf::Variant, ctor_kind),
290 v.span,
291 );
292 }
293 visit::walk_variant(this, v)
294 });
295 }
296
297 fn visit_where_predicate(&mut self, pred: &'a WherePredicate) {
298 if pred.is_placeholder {
299 self.visit_macro_invoc(pred.id)
300 } else {
301 visit::walk_where_predicate(self, pred)
302 }
303 }
304
305 fn visit_variant_data(&mut self, data: &'a VariantData) {
306 for (index, field) in data.fields().iter().enumerate() {
310 self.collect_field(field, Some(index));
311 }
312 }
313
314 fn visit_generic_param(&mut self, param: &'a GenericParam) {
315 if param.is_placeholder {
316 self.visit_macro_invoc(param.id);
317 return;
318 }
319 let def_kind = match param.kind {
320 GenericParamKind::Lifetime { .. } => DefKind::LifetimeParam,
321 GenericParamKind::Type { .. } => DefKind::TyParam,
322 GenericParamKind::Const { .. } => DefKind::ConstParam,
323 };
324 self.create_def(param.id, Some(param.ident.name), def_kind, param.ident.span);
325
326 self.with_impl_trait(ImplTraitContext::Universal, |this| {
333 visit::walk_generic_param(this, param)
334 });
335 }
336
337 fn visit_assoc_item(&mut self, i: &'a AssocItem, ctxt: visit::AssocCtxt) {
338 let (ident, def_kind) = match &i.kind {
339 AssocItemKind::Fn(box Fn { ident, .. })
340 | AssocItemKind::Delegation(box Delegation { ident, .. }) => (*ident, DefKind::AssocFn),
341 AssocItemKind::Const(box ConstItem { ident, .. }) => (*ident, DefKind::AssocConst),
342 AssocItemKind::Type(box TyAlias { ident, .. }) => (*ident, DefKind::AssocTy),
343 AssocItemKind::MacCall(..) | AssocItemKind::DelegationMac(..) => {
344 return self.visit_macro_invoc(i.id);
345 }
346 };
347
348 let def = self.create_def(i.id, Some(ident.name), def_kind, i.span);
349 self.with_parent(def, |this| visit::walk_assoc_item(this, i, ctxt));
350 }
351
352 fn visit_pat(&mut self, pat: &'a Pat) {
353 match pat.kind {
354 PatKind::MacCall(..) => self.visit_macro_invoc(pat.id),
355 _ => visit::walk_pat(self, pat),
356 }
357 }
358
359 fn visit_anon_const(&mut self, constant: &'a AnonConst) {
360 if let MgcaDisambiguation::Direct = constant.mgca_disambiguation
364 && self.resolver.tcx.features().min_generic_const_args()
365 {
366 visit::walk_anon_const(self, constant);
367 return;
368 }
369
370 let parent = self.create_def(constant.id, None, DefKind::AnonConst, constant.value.span);
371 self.with_parent(parent, |this| visit::walk_anon_const(this, constant));
372 }
373
374 fn visit_expr(&mut self, expr: &'a Expr) {
375 let parent_def = match expr.kind {
376 ExprKind::MacCall(..) => return self.visit_macro_invoc(expr.id),
377 ExprKind::Closure(..) | ExprKind::Gen(..) => {
378 self.create_def(expr.id, None, DefKind::Closure, expr.span)
379 }
380 ExprKind::ConstBlock(ref constant) => {
381 for attr in &expr.attrs {
382 visit::walk_attribute(self, attr);
383 }
384 let def =
385 self.create_def(constant.id, None, DefKind::InlineConst, constant.value.span);
386 self.with_parent(def, |this| visit::walk_anon_const(this, constant));
387 return;
388 }
389 _ => self.invocation_parent.parent_def,
390 };
391
392 self.with_parent(parent_def, |this| visit::walk_expr(this, expr))
393 }
394
395 fn visit_ty(&mut self, ty: &'a Ty) {
396 match ty.kind {
397 TyKind::MacCall(..) => self.visit_macro_invoc(ty.id),
398 TyKind::ImplTrait(opaque_id, _) => {
399 let name = *self
400 .resolver
401 .impl_trait_names
402 .get(&ty.id)
403 .unwrap_or_else(|| span_bug!(ty.span, "expected this opaque to be named"));
404 let kind = match self.invocation_parent.impl_trait_context {
405 ImplTraitContext::Universal => DefKind::TyParam,
406 ImplTraitContext::Existential => DefKind::OpaqueTy,
407 ImplTraitContext::InBinding => return visit::walk_ty(self, ty),
408 };
409 let id = self.create_def(opaque_id, Some(name), kind, ty.span);
410 match self.invocation_parent.impl_trait_context {
411 ImplTraitContext::Universal => visit::walk_ty(self, ty),
414 ImplTraitContext::Existential => {
415 self.with_parent(id, |this| visit::walk_ty(this, ty))
416 }
417 ImplTraitContext::InBinding => unreachable!(),
418 };
419 }
420 _ => visit::walk_ty(self, ty),
421 }
422 }
423
424 fn visit_stmt(&mut self, stmt: &'a Stmt) {
425 match stmt.kind {
426 StmtKind::MacCall(..) => self.visit_macro_invoc(stmt.id),
427 StmtKind::Let(ref local) => self.with_impl_trait(ImplTraitContext::InBinding, |this| {
432 visit::walk_local(this, local)
433 }),
434 _ => visit::walk_stmt(self, stmt),
435 }
436 }
437
438 fn visit_arm(&mut self, arm: &'a Arm) {
439 if arm.is_placeholder { self.visit_macro_invoc(arm.id) } else { visit::walk_arm(self, arm) }
440 }
441
442 fn visit_expr_field(&mut self, f: &'a ExprField) {
443 if f.is_placeholder {
444 self.visit_macro_invoc(f.id)
445 } else {
446 visit::walk_expr_field(self, f)
447 }
448 }
449
450 fn visit_pat_field(&mut self, fp: &'a PatField) {
451 if fp.is_placeholder {
452 self.visit_macro_invoc(fp.id)
453 } else {
454 visit::walk_pat_field(self, fp)
455 }
456 }
457
458 fn visit_param(&mut self, p: &'a Param) {
459 if p.is_placeholder {
460 self.visit_macro_invoc(p.id)
461 } else {
462 self.with_impl_trait(ImplTraitContext::Universal, |this| visit::walk_param(this, p))
463 }
464 }
465
466 fn visit_field_def(&mut self, field: &'a FieldDef) {
469 self.collect_field(field, None);
470 }
471
472 fn visit_crate(&mut self, krate: &'a Crate) {
473 if krate.is_placeholder {
474 self.visit_macro_invoc(krate.id)
475 } else {
476 visit::walk_crate(self, krate)
477 }
478 }
479
480 fn visit_attribute(&mut self, attr: &'a Attribute) -> Self::Result {
481 let orig_in_attr = mem::replace(&mut self.invocation_parent.in_attr, true);
482 visit::walk_attribute(self, attr);
483 self.invocation_parent.in_attr = orig_in_attr;
484 }
485
486 fn visit_inline_asm(&mut self, asm: &'a InlineAsm) {
487 let InlineAsm {
488 asm_macro: _,
489 template: _,
490 template_strs: _,
491 operands,
492 clobber_abis: _,
493 options: _,
494 line_spans: _,
495 } = asm;
496 for (op, _span) in operands {
497 match op {
498 InlineAsmOperand::In { expr, reg: _ }
499 | InlineAsmOperand::Out { expr: Some(expr), reg: _, late: _ }
500 | InlineAsmOperand::InOut { expr, reg: _, late: _ } => {
501 self.visit_expr(expr);
502 }
503 InlineAsmOperand::Out { expr: None, reg: _, late: _ } => {}
504 InlineAsmOperand::SplitInOut { in_expr, out_expr, reg: _, late: _ } => {
505 self.visit_expr(in_expr);
506 if let Some(expr) = out_expr {
507 self.visit_expr(expr);
508 }
509 }
510 InlineAsmOperand::Const { anon_const } => {
511 let def = self.create_def(
512 anon_const.id,
513 None,
514 DefKind::InlineConst,
515 anon_const.value.span,
516 );
517 self.with_parent(def, |this| visit::walk_anon_const(this, anon_const));
518 }
519 InlineAsmOperand::Sym { sym } => self.visit_inline_asm_sym(sym),
520 InlineAsmOperand::Label { block } => self.visit_block(block),
521 }
522 }
523 }
524}