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 {
248                ty: _,
249                mutability,
250                expr: _,
251                safety,
252                define_opaque: _,
253            }) => {
254                let safety = match safety {
255                    ast::Safety::Unsafe(_) | ast::Safety::Default => hir::Safety::Unsafe,
256                    ast::Safety::Safe(_) => hir::Safety::Safe,
257                };
258
259                DefKind::Static { safety, mutability, nested: false }
260            }
261            ForeignItemKind::Fn(_) => DefKind::Fn,
262            ForeignItemKind::TyAlias(_) => DefKind::ForeignTy,
263            ForeignItemKind::MacCall(_) => return self.visit_macro_invoc(fi.id),
264        };
265
266        let def = self.create_def(fi.id, Some(fi.ident.name), def_kind, fi.span);
267
268        self.with_parent(def, |this| visit::walk_item(this, fi));
269    }
270
271    fn visit_variant(&mut self, v: &'a Variant) {
272        if v.is_placeholder {
273            return self.visit_macro_invoc(v.id);
274        }
275        let def = self.create_def(v.id, Some(v.ident.name), DefKind::Variant, v.span);
276        self.with_parent(def, |this| {
277            if let Some((ctor_kind, ctor_node_id)) = CtorKind::from_ast(&v.data) {
278                this.create_def(
279                    ctor_node_id,
280                    None,
281                    DefKind::Ctor(CtorOf::Variant, ctor_kind),
282                    v.span,
283                );
284            }
285            visit::walk_variant(this, v)
286        });
287    }
288
289    fn visit_where_predicate(&mut self, pred: &'a WherePredicate) {
290        if pred.is_placeholder {
291            self.visit_macro_invoc(pred.id)
292        } else {
293            visit::walk_where_predicate(self, pred)
294        }
295    }
296
297    fn visit_variant_data(&mut self, data: &'a VariantData) {
298        // The assumption here is that non-`cfg` macro expansion cannot change field indices.
299        // It currently holds because only inert attributes are accepted on fields,
300        // and every such attribute expands into a single field after it's resolved.
301        for (index, field) in data.fields().iter().enumerate() {
302            self.collect_field(field, Some(index));
303        }
304    }
305
306    fn visit_generic_param(&mut self, param: &'a GenericParam) {
307        if param.is_placeholder {
308            self.visit_macro_invoc(param.id);
309            return;
310        }
311        let def_kind = match param.kind {
312            GenericParamKind::Lifetime { .. } => DefKind::LifetimeParam,
313            GenericParamKind::Type { .. } => DefKind::TyParam,
314            GenericParamKind::Const { .. } => DefKind::ConstParam,
315        };
316        self.create_def(param.id, Some(param.ident.name), def_kind, param.ident.span);
317
318        // impl-Trait can happen inside generic parameters, like
319        // ```
320        // fn foo<U: Iterator<Item = impl Clone>>() {}
321        // ```
322        //
323        // In that case, the impl-trait is lowered as an additional generic parameter.
324        self.with_impl_trait(ImplTraitContext::Universal, |this| {
325            visit::walk_generic_param(this, param)
326        });
327    }
328
329    fn visit_assoc_item(&mut self, i: &'a AssocItem, ctxt: visit::AssocCtxt) {
330        let def_kind = match &i.kind {
331            AssocItemKind::Fn(..) | AssocItemKind::Delegation(..) => DefKind::AssocFn,
332            AssocItemKind::Const(..) => DefKind::AssocConst,
333            AssocItemKind::Type(..) => DefKind::AssocTy,
334            AssocItemKind::MacCall(..) | AssocItemKind::DelegationMac(..) => {
335                return self.visit_macro_invoc(i.id);
336            }
337        };
338
339        let def = self.create_def(i.id, Some(i.ident.name), def_kind, i.span);
340        self.with_parent(def, |this| visit::walk_assoc_item(this, i, ctxt));
341    }
342
343    fn visit_pat(&mut self, pat: &'a Pat) {
344        match pat.kind {
345            PatKind::MacCall(..) => self.visit_macro_invoc(pat.id),
346            _ => visit::walk_pat(self, pat),
347        }
348    }
349
350    fn visit_anon_const(&mut self, constant: &'a AnonConst) {
351        let parent = self.create_def(constant.id, None, DefKind::AnonConst, constant.value.span);
352        self.with_parent(parent, |this| visit::walk_anon_const(this, constant));
353    }
354
355    fn visit_expr(&mut self, expr: &'a Expr) {
356        let parent_def = match expr.kind {
357            ExprKind::MacCall(..) => return self.visit_macro_invoc(expr.id),
358            ExprKind::Closure(..) | ExprKind::Gen(..) => {
359                self.create_def(expr.id, None, DefKind::Closure, expr.span)
360            }
361            ExprKind::ConstBlock(ref constant) => {
362                for attr in &expr.attrs {
363                    visit::walk_attribute(self, attr);
364                }
365                let def =
366                    self.create_def(constant.id, None, DefKind::InlineConst, constant.value.span);
367                self.with_parent(def, |this| visit::walk_anon_const(this, constant));
368                return;
369            }
370            _ => self.parent_def,
371        };
372
373        self.with_parent(parent_def, |this| visit::walk_expr(this, expr))
374    }
375
376    fn visit_ty(&mut self, ty: &'a Ty) {
377        match &ty.kind {
378            TyKind::MacCall(..) => self.visit_macro_invoc(ty.id),
379            TyKind::ImplTrait(id, _) => {
380                // HACK: pprust breaks strings with newlines when the type
381                // gets too long. We don't want these to show up in compiler
382                // output or built artifacts, so replace them here...
383                // Perhaps we should instead format APITs more robustly.
384                let name = Symbol::intern(&pprust::ty_to_string(ty).replace('\n', " "));
385                let kind = match self.impl_trait_context {
386                    ImplTraitContext::Universal => DefKind::TyParam,
387                    ImplTraitContext::Existential => DefKind::OpaqueTy,
388                    ImplTraitContext::InBinding => return visit::walk_ty(self, ty),
389                };
390                let id = self.create_def(*id, Some(name), kind, ty.span);
391                match self.impl_trait_context {
392                    // Do not nest APIT, as we desugar them as `impl_trait: bounds`,
393                    // so the `impl_trait` node is not a parent to `bounds`.
394                    ImplTraitContext::Universal => visit::walk_ty(self, ty),
395                    ImplTraitContext::Existential => {
396                        self.with_parent(id, |this| visit::walk_ty(this, ty))
397                    }
398                    ImplTraitContext::InBinding => unreachable!(),
399                };
400            }
401            _ => visit::walk_ty(self, ty),
402        }
403    }
404
405    fn visit_stmt(&mut self, stmt: &'a Stmt) {
406        match stmt.kind {
407            StmtKind::MacCall(..) => self.visit_macro_invoc(stmt.id),
408            // FIXME(impl_trait_in_bindings): We don't really have a good way of
409            // introducing the right `ImplTraitContext` here for all the cases we
410            // care about, in case we want to introduce ITIB to other positions
411            // such as turbofishes (e.g. `foo::<impl Fn()>(|| {})`).
412            StmtKind::Let(ref local) => self.with_impl_trait(ImplTraitContext::InBinding, |this| {
413                visit::walk_local(this, local)
414            }),
415            _ => visit::walk_stmt(self, stmt),
416        }
417    }
418
419    fn visit_arm(&mut self, arm: &'a Arm) {
420        if arm.is_placeholder { self.visit_macro_invoc(arm.id) } else { visit::walk_arm(self, arm) }
421    }
422
423    fn visit_expr_field(&mut self, f: &'a ExprField) {
424        if f.is_placeholder {
425            self.visit_macro_invoc(f.id)
426        } else {
427            visit::walk_expr_field(self, f)
428        }
429    }
430
431    fn visit_pat_field(&mut self, fp: &'a PatField) {
432        if fp.is_placeholder {
433            self.visit_macro_invoc(fp.id)
434        } else {
435            visit::walk_pat_field(self, fp)
436        }
437    }
438
439    fn visit_param(&mut self, p: &'a Param) {
440        if p.is_placeholder {
441            self.visit_macro_invoc(p.id)
442        } else {
443            self.with_impl_trait(ImplTraitContext::Universal, |this| visit::walk_param(this, p))
444        }
445    }
446
447    // This method is called only when we are visiting an individual field
448    // after expanding an attribute on it.
449    fn visit_field_def(&mut self, field: &'a FieldDef) {
450        self.collect_field(field, None);
451    }
452
453    fn visit_crate(&mut self, krate: &'a Crate) {
454        if krate.is_placeholder {
455            self.visit_macro_invoc(krate.id)
456        } else {
457            visit::walk_crate(self, krate)
458        }
459    }
460
461    fn visit_attribute(&mut self, attr: &'a Attribute) -> Self::Result {
462        let orig_in_attr = mem::replace(&mut self.in_attr, true);
463        visit::walk_attribute(self, attr);
464        self.in_attr = orig_in_attr;
465    }
466
467    fn visit_inline_asm(&mut self, asm: &'a InlineAsm) {
468        let InlineAsm {
469            asm_macro: _,
470            template: _,
471            template_strs: _,
472            operands,
473            clobber_abis: _,
474            options: _,
475            line_spans: _,
476        } = asm;
477        for (op, _span) in operands {
478            match op {
479                InlineAsmOperand::In { expr, reg: _ }
480                | InlineAsmOperand::Out { expr: Some(expr), reg: _, late: _ }
481                | InlineAsmOperand::InOut { expr, reg: _, late: _ } => {
482                    self.visit_expr(expr);
483                }
484                InlineAsmOperand::Out { expr: None, reg: _, late: _ } => {}
485                InlineAsmOperand::SplitInOut { in_expr, out_expr, reg: _, late: _ } => {
486                    self.visit_expr(in_expr);
487                    if let Some(expr) = out_expr {
488                        self.visit_expr(expr);
489                    }
490                }
491                InlineAsmOperand::Const { anon_const } => {
492                    let def = self.create_def(
493                        anon_const.id,
494                        None,
495                        DefKind::InlineConst,
496                        anon_const.value.span,
497                    );
498                    self.with_parent(def, |this| visit::walk_anon_const(this, anon_const));
499                }
500                InlineAsmOperand::Sym { sym } => self.visit_inline_asm_sym(sym),
501                InlineAsmOperand::Label { block } => self.visit_block(block),
502            }
503        }
504    }
505}