rustc_resolve/
def_collector.rs

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