rustc_resolve/
def_collector.rs

1use std::mem;
2
3use rustc_ast::visit::FnKind;
4use rustc_ast::*;
5use rustc_ast_pretty::pprust;
6use rustc_expand::expand::AstFragment;
7use rustc_hir as hir;
8use rustc_hir::def::{CtorKind, CtorOf, DefKind};
9use rustc_hir::def_id::LocalDefId;
10use rustc_span::hygiene::LocalExpnId;
11use rustc_span::{Span, Symbol, kw, sym};
12use tracing::debug;
13
14use crate::{ImplTraitContext, InvocationParent, Resolver};
15
16pub(crate) fn collect_definitions(
17    resolver: &mut Resolver<'_, '_>,
18    fragment: &AstFragment,
19    expansion: LocalExpnId,
20) {
21    let InvocationParent { parent_def, impl_trait_context, in_attr } =
22        resolver.invocation_parents[&expansion];
23    let mut visitor = DefCollector { resolver, parent_def, expansion, impl_trait_context, in_attr };
24    fragment.visit_with(&mut visitor);
25}
26
27/// Creates `DefId`s for nodes in the AST.
28struct DefCollector<'a, 'ra, 'tcx> {
29    resolver: &'a mut Resolver<'ra, 'tcx>,
30    parent_def: LocalDefId,
31    impl_trait_context: ImplTraitContext,
32    in_attr: bool,
33    expansion: LocalExpnId,
34}
35
36impl<'a, 'ra, 'tcx> DefCollector<'a, 'ra, 'tcx> {
37    fn create_def(
38        &mut self,
39        node_id: NodeId,
40        name: Symbol,
41        def_kind: DefKind,
42        span: Span,
43    ) -> LocalDefId {
44        let parent_def = self.parent_def;
45        debug!(
46            "create_def(node_id={:?}, def_kind={:?}, parent_def={:?})",
47            node_id, def_kind, parent_def
48        );
49        self.resolver
50            .create_def(
51                parent_def,
52                node_id,
53                name,
54                def_kind,
55                self.expansion.to_expn_id(),
56                span.with_parent(None),
57            )
58            .def_id()
59    }
60
61    fn with_parent<F: FnOnce(&mut Self)>(&mut self, parent_def: LocalDefId, f: F) {
62        let orig_parent_def = mem::replace(&mut self.parent_def, parent_def);
63        f(self);
64        self.parent_def = orig_parent_def;
65    }
66
67    fn with_impl_trait<F: FnOnce(&mut Self)>(
68        &mut self,
69        impl_trait_context: ImplTraitContext,
70        f: F,
71    ) {
72        let orig_itc = mem::replace(&mut self.impl_trait_context, impl_trait_context);
73        f(self);
74        self.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, 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(
99            id,
100            InvocationParent {
101                parent_def: self.parent_def,
102                impl_trait_context: self.impl_trait_context,
103                in_attr: self.in_attr,
104            },
105        );
106        assert!(old_parent.is_none(), "parent `LocalDefId` is reset for an invocation");
107    }
108}
109
110impl<'a, 'ra, 'tcx> visit::Visitor<'a> for DefCollector<'a, 'ra, 'tcx> {
111    fn visit_item(&mut self, i: &'a Item) {
112        // Pick the def data. This need not be unique, but the more
113        // information we encapsulate into, the better
114        let mut opt_macro_data = None;
115        let def_kind = match &i.kind {
116            ItemKind::Impl(i) => DefKind::Impl { of_trait: i.of_trait.is_some() },
117            ItemKind::ForeignMod(..) => DefKind::ForeignMod,
118            ItemKind::Mod(..) => DefKind::Mod,
119            ItemKind::Trait(..) => DefKind::Trait,
120            ItemKind::TraitAlias(..) => DefKind::TraitAlias,
121            ItemKind::Enum(..) => DefKind::Enum,
122            ItemKind::Struct(..) => DefKind::Struct,
123            ItemKind::Union(..) => DefKind::Union,
124            ItemKind::ExternCrate(..) => DefKind::ExternCrate,
125            ItemKind::TyAlias(..) => DefKind::TyAlias,
126            ItemKind::Static(s) => DefKind::Static {
127                safety: hir::Safety::Safe,
128                mutability: s.mutability,
129                nested: false,
130            },
131            ItemKind::Const(..) => DefKind::Const,
132            ItemKind::Fn(..) | ItemKind::Delegation(..) => DefKind::Fn,
133            ItemKind::MacroDef(def) => {
134                let edition = i.span.edition();
135                let macro_data =
136                    self.resolver.compile_macro(def, i.ident, &i.attrs, i.span, i.id, edition);
137                let macro_kind = macro_data.ext.macro_kind();
138                opt_macro_data = Some(macro_data);
139                DefKind::Macro(macro_kind)
140            }
141            ItemKind::GlobalAsm(..) => DefKind::GlobalAsm,
142            ItemKind::Use(..) => return visit::walk_item(self, i),
143            ItemKind::MacCall(..) | ItemKind::DelegationMac(..) => {
144                return self.visit_macro_invoc(i.id);
145            }
146        };
147        let def_id = self.create_def(i.id, i.ident.name, def_kind, i.span);
148
149        if let Some(macro_data) = opt_macro_data {
150            self.resolver.macro_map.insert(def_id.to_def_id(), macro_data);
151        }
152
153        self.with_parent(def_id, |this| {
154            this.with_impl_trait(ImplTraitContext::Existential, |this| {
155                match i.kind {
156                    ItemKind::Struct(ref struct_def, _) | ItemKind::Union(ref struct_def, _) => {
157                        // If this is a unit or tuple-like struct, register the constructor.
158                        if let Some((ctor_kind, ctor_node_id)) = CtorKind::from_ast(struct_def) {
159                            this.create_def(
160                                ctor_node_id,
161                                kw::Empty,
162                                DefKind::Ctor(CtorOf::Struct, ctor_kind),
163                                i.span,
164                            );
165                        }
166                    }
167                    _ => {}
168                }
169                visit::walk_item(this, i);
170            })
171        });
172    }
173
174    fn visit_fn(&mut self, fn_kind: FnKind<'a>, span: Span, _: NodeId) {
175        match fn_kind {
176            FnKind::Fn(
177                _ctxt,
178                _ident,
179                _vis,
180                Fn { sig: FnSig { header, decl, span: _ }, generics, contract, body, .. },
181            ) if let Some(coroutine_kind) = header.coroutine_kind => {
182                self.visit_fn_header(header);
183                self.visit_generics(generics);
184                if let Some(contract) = contract {
185                    self.visit_contract(contract);
186                }
187
188                // For async functions, we need to create their inner defs inside of a
189                // closure to match their desugared representation. Besides that,
190                // we must mirror everything that `visit::walk_fn` below does.
191                let FnDecl { inputs, output } = &**decl;
192                for param in inputs {
193                    self.visit_param(param);
194                }
195
196                let (return_id, return_span) = coroutine_kind.return_id();
197                let return_def =
198                    self.create_def(return_id, kw::Empty, DefKind::OpaqueTy, return_span);
199                self.with_parent(return_def, |this| this.visit_fn_ret_ty(output));
200
201                // If this async fn has no body (i.e. it's an async fn signature in a trait)
202                // then the closure_def will never be used, and we should avoid generating a
203                // def-id for it.
204                if let Some(body) = body {
205                    let closure_def = self.create_def(
206                        coroutine_kind.closure_id(),
207                        kw::Empty,
208                        DefKind::Closure,
209                        span,
210                    );
211                    self.with_parent(closure_def, |this| this.visit_block(body));
212                }
213            }
214            FnKind::Closure(binder, Some(coroutine_kind), decl, body) => {
215                self.visit_closure_binder(binder);
216                visit::walk_fn_decl(self, decl);
217
218                // Async closures desugar to closures inside of closures, so
219                // we must create two defs.
220                let coroutine_def =
221                    self.create_def(coroutine_kind.closure_id(), kw::Empty, DefKind::Closure, span);
222                self.with_parent(coroutine_def, |this| this.visit_expr(body));
223            }
224            _ => visit::walk_fn(self, fn_kind),
225        }
226    }
227
228    fn visit_use_tree(&mut self, use_tree: &'a UseTree, id: NodeId, _nested: bool) {
229        self.create_def(id, kw::Empty, DefKind::Use, use_tree.span);
230        visit::walk_use_tree(self, use_tree, id);
231    }
232
233    fn visit_foreign_item(&mut self, fi: &'a ForeignItem) {
234        let def_kind = match fi.kind {
235            ForeignItemKind::Static(box StaticItem { ty: _, mutability, expr: _, safety }) => {
236                let safety = match safety {
237                    ast::Safety::Unsafe(_) | ast::Safety::Default => hir::Safety::Unsafe,
238                    ast::Safety::Safe(_) => hir::Safety::Safe,
239                };
240
241                DefKind::Static { safety, mutability, nested: false }
242            }
243            ForeignItemKind::Fn(_) => DefKind::Fn,
244            ForeignItemKind::TyAlias(_) => DefKind::ForeignTy,
245            ForeignItemKind::MacCall(_) => return self.visit_macro_invoc(fi.id),
246        };
247
248        let def = self.create_def(fi.id, fi.ident.name, def_kind, fi.span);
249
250        self.with_parent(def, |this| visit::walk_item(this, fi));
251    }
252
253    fn visit_variant(&mut self, v: &'a Variant) {
254        if v.is_placeholder {
255            return self.visit_macro_invoc(v.id);
256        }
257        let def = self.create_def(v.id, v.ident.name, DefKind::Variant, v.span);
258        self.with_parent(def, |this| {
259            if let Some((ctor_kind, ctor_node_id)) = CtorKind::from_ast(&v.data) {
260                this.create_def(
261                    ctor_node_id,
262                    kw::Empty,
263                    DefKind::Ctor(CtorOf::Variant, ctor_kind),
264                    v.span,
265                );
266            }
267            visit::walk_variant(this, v)
268        });
269    }
270
271    fn visit_variant_data(&mut self, data: &'a VariantData) {
272        // The assumption here is that non-`cfg` macro expansion cannot change field indices.
273        // It currently holds because only inert attributes are accepted on fields,
274        // and every such attribute expands into a single field after it's resolved.
275        for (index, field) in data.fields().iter().enumerate() {
276            self.collect_field(field, Some(index));
277        }
278    }
279
280    fn visit_generic_param(&mut self, param: &'a GenericParam) {
281        if param.is_placeholder {
282            self.visit_macro_invoc(param.id);
283            return;
284        }
285        let def_kind = match param.kind {
286            GenericParamKind::Lifetime { .. } => DefKind::LifetimeParam,
287            GenericParamKind::Type { .. } => DefKind::TyParam,
288            GenericParamKind::Const { .. } => DefKind::ConstParam,
289        };
290        self.create_def(param.id, param.ident.name, def_kind, param.ident.span);
291
292        // impl-Trait can happen inside generic parameters, like
293        // ```
294        // fn foo<U: Iterator<Item = impl Clone>>() {}
295        // ```
296        //
297        // In that case, the impl-trait is lowered as an additional generic parameter.
298        self.with_impl_trait(ImplTraitContext::Universal, |this| {
299            visit::walk_generic_param(this, param)
300        });
301    }
302
303    fn visit_assoc_item(&mut self, i: &'a AssocItem, ctxt: visit::AssocCtxt) {
304        let def_kind = match &i.kind {
305            AssocItemKind::Fn(..) | AssocItemKind::Delegation(..) => DefKind::AssocFn,
306            AssocItemKind::Const(..) => DefKind::AssocConst,
307            AssocItemKind::Type(..) => DefKind::AssocTy,
308            AssocItemKind::MacCall(..) | AssocItemKind::DelegationMac(..) => {
309                return self.visit_macro_invoc(i.id);
310            }
311        };
312
313        let def = self.create_def(i.id, i.ident.name, def_kind, i.span);
314        self.with_parent(def, |this| visit::walk_assoc_item(this, i, ctxt));
315    }
316
317    fn visit_pat(&mut self, pat: &'a Pat) {
318        match pat.kind {
319            PatKind::MacCall(..) => self.visit_macro_invoc(pat.id),
320            _ => visit::walk_pat(self, pat),
321        }
322    }
323
324    fn visit_anon_const(&mut self, constant: &'a AnonConst) {
325        let parent =
326            self.create_def(constant.id, kw::Empty, DefKind::AnonConst, constant.value.span);
327        self.with_parent(parent, |this| visit::walk_anon_const(this, constant));
328    }
329
330    fn visit_expr(&mut self, expr: &'a Expr) {
331        let parent_def = match expr.kind {
332            ExprKind::MacCall(..) => return self.visit_macro_invoc(expr.id),
333            ExprKind::Closure(..) | ExprKind::Gen(..) => {
334                self.create_def(expr.id, kw::Empty, DefKind::Closure, expr.span)
335            }
336            ExprKind::ConstBlock(ref constant) => {
337                for attr in &expr.attrs {
338                    visit::walk_attribute(self, attr);
339                }
340                let def = self.create_def(
341                    constant.id,
342                    kw::Empty,
343                    DefKind::InlineConst,
344                    constant.value.span,
345                );
346                self.with_parent(def, |this| visit::walk_anon_const(this, constant));
347                return;
348            }
349            _ => self.parent_def,
350        };
351
352        self.with_parent(parent_def, |this| visit::walk_expr(this, expr))
353    }
354
355    fn visit_ty(&mut self, ty: &'a Ty) {
356        match &ty.kind {
357            TyKind::MacCall(..) => self.visit_macro_invoc(ty.id),
358            TyKind::ImplTrait(id, _) => {
359                // HACK: pprust breaks strings with newlines when the type
360                // gets too long. We don't want these to show up in compiler
361                // output or built artifacts, so replace them here...
362                // Perhaps we should instead format APITs more robustly.
363                let name = Symbol::intern(&pprust::ty_to_string(ty).replace('\n', " "));
364                let kind = match self.impl_trait_context {
365                    ImplTraitContext::Universal => DefKind::TyParam,
366                    ImplTraitContext::Existential => DefKind::OpaqueTy,
367                    ImplTraitContext::InBinding => return visit::walk_ty(self, ty),
368                };
369                let id = self.create_def(*id, name, kind, ty.span);
370                match self.impl_trait_context {
371                    // Do not nest APIT, as we desugar them as `impl_trait: bounds`,
372                    // so the `impl_trait` node is not a parent to `bounds`.
373                    ImplTraitContext::Universal => visit::walk_ty(self, ty),
374                    ImplTraitContext::Existential => {
375                        self.with_parent(id, |this| visit::walk_ty(this, ty))
376                    }
377                    ImplTraitContext::InBinding => unreachable!(),
378                };
379            }
380            _ => visit::walk_ty(self, ty),
381        }
382    }
383
384    fn visit_stmt(&mut self, stmt: &'a Stmt) {
385        match stmt.kind {
386            StmtKind::MacCall(..) => self.visit_macro_invoc(stmt.id),
387            // FIXME(impl_trait_in_bindings): We don't really have a good way of
388            // introducing the right `ImplTraitContext` here for all the cases we
389            // care about, in case we want to introduce ITIB to other positions
390            // such as turbofishes (e.g. `foo::<impl Fn()>(|| {})`).
391            StmtKind::Let(ref local) => self.with_impl_trait(ImplTraitContext::InBinding, |this| {
392                visit::walk_local(this, local)
393            }),
394            _ => visit::walk_stmt(self, stmt),
395        }
396    }
397
398    fn visit_arm(&mut self, arm: &'a Arm) {
399        if arm.is_placeholder { self.visit_macro_invoc(arm.id) } else { visit::walk_arm(self, arm) }
400    }
401
402    fn visit_expr_field(&mut self, f: &'a ExprField) {
403        if f.is_placeholder {
404            self.visit_macro_invoc(f.id)
405        } else {
406            visit::walk_expr_field(self, f)
407        }
408    }
409
410    fn visit_pat_field(&mut self, fp: &'a PatField) {
411        if fp.is_placeholder {
412            self.visit_macro_invoc(fp.id)
413        } else {
414            visit::walk_pat_field(self, fp)
415        }
416    }
417
418    fn visit_param(&mut self, p: &'a Param) {
419        if p.is_placeholder {
420            self.visit_macro_invoc(p.id)
421        } else {
422            self.with_impl_trait(ImplTraitContext::Universal, |this| visit::walk_param(this, p))
423        }
424    }
425
426    // This method is called only when we are visiting an individual field
427    // after expanding an attribute on it.
428    fn visit_field_def(&mut self, field: &'a FieldDef) {
429        self.collect_field(field, None);
430    }
431
432    fn visit_crate(&mut self, krate: &'a Crate) {
433        if krate.is_placeholder {
434            self.visit_macro_invoc(krate.id)
435        } else {
436            visit::walk_crate(self, krate)
437        }
438    }
439
440    fn visit_attribute(&mut self, attr: &'a Attribute) -> Self::Result {
441        let orig_in_attr = mem::replace(&mut self.in_attr, true);
442        visit::walk_attribute(self, attr);
443        self.in_attr = orig_in_attr;
444    }
445}