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