rustc_resolve/
def_collector.rs

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::def::{CtorKind, CtorOf, DefKind};
9use rustc_hir::def_id::LocalDefId;
10use rustc_middle::span_bug;
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(ident, 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 mut parser = AttributeParser::<'_, Early>::new(
132                    &self.resolver.tcx.sess,
133                    self.resolver.tcx.features(),
134                    Vec::new(),
135                    Early { emit_errors: ShouldEmit::Nothing },
136                );
137                let attrs = parser.parse_attribute_list(
138                    &i.attrs,
139                    i.span,
140                    i.id,
141                    OmitDoc::Skip,
142                    std::convert::identity,
143                    |_l| {
144                        // FIXME(jdonszelmann): emit lints here properly
145                        // NOTE that before new attribute parsing, they didn't happen either
146                        // but it would be nice if we could change that.
147                    },
148                );
149
150                let macro_data =
151                    self.resolver.compile_macro(def, *ident, &attrs, i.span, i.id, edition);
152                let macro_kind = macro_data.ext.macro_kind();
153                opt_macro_data = Some(macro_data);
154                DefKind::Macro(macro_kind)
155            }
156            ItemKind::GlobalAsm(..) => DefKind::GlobalAsm,
157            ItemKind::Use(use_tree) => {
158                self.create_def(i.id, None, DefKind::Use, use_tree.span);
159                return visit::walk_item(self, i);
160            }
161            ItemKind::MacCall(..) | ItemKind::DelegationMac(..) => {
162                return self.visit_macro_invoc(i.id);
163            }
164        };
165        let def_id =
166            self.create_def(i.id, i.kind.ident().map(|ident| ident.name), def_kind, i.span);
167
168        if let Some(macro_data) = opt_macro_data {
169            self.resolver.new_local_macro(def_id, macro_data);
170        }
171
172        self.with_parent(def_id, |this| {
173            this.with_impl_trait(ImplTraitContext::Existential, |this| {
174                match i.kind {
175                    ItemKind::Struct(_, _, ref struct_def)
176                    | ItemKind::Union(_, _, ref struct_def) => {
177                        // If this is a unit or tuple-like struct, register the constructor.
178                        if let Some((ctor_kind, ctor_node_id)) = CtorKind::from_ast(struct_def) {
179                            this.create_def(
180                                ctor_node_id,
181                                None,
182                                DefKind::Ctor(CtorOf::Struct, ctor_kind),
183                                i.span,
184                            );
185                        }
186                    }
187                    _ => {}
188                }
189                visit::walk_item(this, i);
190            })
191        });
192    }
193
194    fn visit_fn(&mut self, fn_kind: FnKind<'a>, span: Span, _: NodeId) {
195        match fn_kind {
196            FnKind::Fn(
197                _ctxt,
198                _vis,
199                Fn {
200                    sig: FnSig { header, decl, span: _ }, ident, generics, contract, body, ..
201                },
202            ) if let Some(coroutine_kind) = header.coroutine_kind => {
203                self.visit_ident(ident);
204                self.visit_fn_header(header);
205                self.visit_generics(generics);
206                if let Some(contract) = contract {
207                    self.visit_contract(contract);
208                }
209
210                // For async functions, we need to create their inner defs inside of a
211                // closure to match their desugared representation. Besides that,
212                // we must mirror everything that `visit::walk_fn` below does.
213                let FnDecl { inputs, output } = &**decl;
214                for param in inputs {
215                    self.visit_param(param);
216                }
217
218                let (return_id, return_span) = coroutine_kind.return_id();
219                let return_def = self.create_def(return_id, None, DefKind::OpaqueTy, return_span);
220                self.with_parent(return_def, |this| this.visit_fn_ret_ty(output));
221
222                // If this async fn has no body (i.e. it's an async fn signature in a trait)
223                // then the closure_def will never be used, and we should avoid generating a
224                // def-id for it.
225                if let Some(body) = body {
226                    let closure_def =
227                        self.create_def(coroutine_kind.closure_id(), None, DefKind::Closure, span);
228                    self.with_parent(closure_def, |this| this.visit_block(body));
229                }
230            }
231            FnKind::Closure(binder, Some(coroutine_kind), decl, body) => {
232                self.visit_closure_binder(binder);
233                visit::walk_fn_decl(self, decl);
234
235                // Async closures desugar to closures inside of closures, so
236                // we must create two defs.
237                let coroutine_def =
238                    self.create_def(coroutine_kind.closure_id(), None, DefKind::Closure, span);
239                self.with_parent(coroutine_def, |this| this.visit_expr(body));
240            }
241            _ => visit::walk_fn(self, fn_kind),
242        }
243    }
244
245    fn visit_nested_use_tree(&mut self, use_tree: &'a UseTree, id: NodeId) {
246        self.create_def(id, None, DefKind::Use, use_tree.span);
247        visit::walk_use_tree(self, use_tree);
248    }
249
250    fn visit_foreign_item(&mut self, fi: &'a ForeignItem) {
251        let (ident, def_kind) = match fi.kind {
252            ForeignItemKind::Static(box StaticItem {
253                ident,
254                ty: _,
255                mutability,
256                expr: _,
257                safety,
258                define_opaque: _,
259            }) => {
260                let safety = match safety {
261                    ast::Safety::Unsafe(_) | ast::Safety::Default => hir::Safety::Unsafe,
262                    ast::Safety::Safe(_) => hir::Safety::Safe,
263                };
264
265                (ident, DefKind::Static { safety, mutability, nested: false })
266            }
267            ForeignItemKind::Fn(box Fn { ident, .. }) => (ident, DefKind::Fn),
268            ForeignItemKind::TyAlias(box TyAlias { ident, .. }) => (ident, DefKind::ForeignTy),
269            ForeignItemKind::MacCall(_) => return self.visit_macro_invoc(fi.id),
270        };
271
272        let def = self.create_def(fi.id, Some(ident.name), def_kind, fi.span);
273
274        self.with_parent(def, |this| visit::walk_item(this, fi));
275    }
276
277    fn visit_variant(&mut self, v: &'a Variant) {
278        if v.is_placeholder {
279            return self.visit_macro_invoc(v.id);
280        }
281        let def = self.create_def(v.id, Some(v.ident.name), DefKind::Variant, v.span);
282        self.with_parent(def, |this| {
283            if let Some((ctor_kind, ctor_node_id)) = CtorKind::from_ast(&v.data) {
284                this.create_def(
285                    ctor_node_id,
286                    None,
287                    DefKind::Ctor(CtorOf::Variant, ctor_kind),
288                    v.span,
289                );
290            }
291            visit::walk_variant(this, v)
292        });
293    }
294
295    fn visit_where_predicate(&mut self, pred: &'a WherePredicate) {
296        if pred.is_placeholder {
297            self.visit_macro_invoc(pred.id)
298        } else {
299            visit::walk_where_predicate(self, pred)
300        }
301    }
302
303    fn visit_variant_data(&mut self, data: &'a VariantData) {
304        // The assumption here is that non-`cfg` macro expansion cannot change field indices.
305        // It currently holds because only inert attributes are accepted on fields,
306        // and every such attribute expands into a single field after it's resolved.
307        for (index, field) in data.fields().iter().enumerate() {
308            self.collect_field(field, Some(index));
309        }
310    }
311
312    fn visit_generic_param(&mut self, param: &'a GenericParam) {
313        if param.is_placeholder {
314            self.visit_macro_invoc(param.id);
315            return;
316        }
317        let def_kind = match param.kind {
318            GenericParamKind::Lifetime { .. } => DefKind::LifetimeParam,
319            GenericParamKind::Type { .. } => DefKind::TyParam,
320            GenericParamKind::Const { .. } => DefKind::ConstParam,
321        };
322        self.create_def(param.id, Some(param.ident.name), def_kind, param.ident.span);
323
324        // impl-Trait can happen inside generic parameters, like
325        // ```
326        // fn foo<U: Iterator<Item = impl Clone>>() {}
327        // ```
328        //
329        // In that case, the impl-trait is lowered as an additional generic parameter.
330        self.with_impl_trait(ImplTraitContext::Universal, |this| {
331            visit::walk_generic_param(this, param)
332        });
333    }
334
335    fn visit_assoc_item(&mut self, i: &'a AssocItem, ctxt: visit::AssocCtxt) {
336        let (ident, def_kind) = match &i.kind {
337            AssocItemKind::Fn(box Fn { ident, .. })
338            | AssocItemKind::Delegation(box Delegation { ident, .. }) => (*ident, DefKind::AssocFn),
339            AssocItemKind::Const(box ConstItem { ident, .. }) => (*ident, DefKind::AssocConst),
340            AssocItemKind::Type(box TyAlias { ident, .. }) => (*ident, DefKind::AssocTy),
341            AssocItemKind::MacCall(..) | AssocItemKind::DelegationMac(..) => {
342                return self.visit_macro_invoc(i.id);
343            }
344        };
345
346        let def = self.create_def(i.id, Some(ident.name), def_kind, i.span);
347        self.with_parent(def, |this| visit::walk_assoc_item(this, i, ctxt));
348    }
349
350    fn visit_pat(&mut self, pat: &'a Pat) {
351        match pat.kind {
352            PatKind::MacCall(..) => self.visit_macro_invoc(pat.id),
353            _ => visit::walk_pat(self, pat),
354        }
355    }
356
357    fn visit_anon_const(&mut self, constant: &'a AnonConst) {
358        let parent = self.create_def(constant.id, None, DefKind::AnonConst, constant.value.span);
359        self.with_parent(parent, |this| visit::walk_anon_const(this, constant));
360    }
361
362    fn visit_expr(&mut self, expr: &'a Expr) {
363        let parent_def = match expr.kind {
364            ExprKind::MacCall(..) => return self.visit_macro_invoc(expr.id),
365            ExprKind::Closure(..) | ExprKind::Gen(..) => {
366                self.create_def(expr.id, None, DefKind::Closure, expr.span)
367            }
368            ExprKind::ConstBlock(ref constant) => {
369                for attr in &expr.attrs {
370                    visit::walk_attribute(self, attr);
371                }
372                let def =
373                    self.create_def(constant.id, None, DefKind::InlineConst, constant.value.span);
374                self.with_parent(def, |this| visit::walk_anon_const(this, constant));
375                return;
376            }
377            _ => self.invocation_parent.parent_def,
378        };
379
380        self.with_parent(parent_def, |this| visit::walk_expr(this, expr))
381    }
382
383    fn visit_ty(&mut self, ty: &'a Ty) {
384        match ty.kind {
385            TyKind::MacCall(..) => self.visit_macro_invoc(ty.id),
386            TyKind::ImplTrait(opaque_id, _) => {
387                let name = *self
388                    .resolver
389                    .impl_trait_names
390                    .get(&ty.id)
391                    .unwrap_or_else(|| span_bug!(ty.span, "expected this opaque to be named"));
392                let kind = match self.invocation_parent.impl_trait_context {
393                    ImplTraitContext::Universal => DefKind::TyParam,
394                    ImplTraitContext::Existential => DefKind::OpaqueTy,
395                    ImplTraitContext::InBinding => return visit::walk_ty(self, ty),
396                };
397                let id = self.create_def(opaque_id, Some(name), kind, ty.span);
398                match self.invocation_parent.impl_trait_context {
399                    // Do not nest APIT, as we desugar them as `impl_trait: bounds`,
400                    // so the `impl_trait` node is not a parent to `bounds`.
401                    ImplTraitContext::Universal => visit::walk_ty(self, ty),
402                    ImplTraitContext::Existential => {
403                        self.with_parent(id, |this| visit::walk_ty(this, ty))
404                    }
405                    ImplTraitContext::InBinding => unreachable!(),
406                };
407            }
408            _ => visit::walk_ty(self, ty),
409        }
410    }
411
412    fn visit_stmt(&mut self, stmt: &'a Stmt) {
413        match stmt.kind {
414            StmtKind::MacCall(..) => self.visit_macro_invoc(stmt.id),
415            // FIXME(impl_trait_in_bindings): We don't really have a good way of
416            // introducing the right `ImplTraitContext` here for all the cases we
417            // care about, in case we want to introduce ITIB to other positions
418            // such as turbofishes (e.g. `foo::<impl Fn()>(|| {})`).
419            StmtKind::Let(ref local) => self.with_impl_trait(ImplTraitContext::InBinding, |this| {
420                visit::walk_local(this, local)
421            }),
422            _ => visit::walk_stmt(self, stmt),
423        }
424    }
425
426    fn visit_arm(&mut self, arm: &'a Arm) {
427        if arm.is_placeholder { self.visit_macro_invoc(arm.id) } else { visit::walk_arm(self, arm) }
428    }
429
430    fn visit_expr_field(&mut self, f: &'a ExprField) {
431        if f.is_placeholder {
432            self.visit_macro_invoc(f.id)
433        } else {
434            visit::walk_expr_field(self, f)
435        }
436    }
437
438    fn visit_pat_field(&mut self, fp: &'a PatField) {
439        if fp.is_placeholder {
440            self.visit_macro_invoc(fp.id)
441        } else {
442            visit::walk_pat_field(self, fp)
443        }
444    }
445
446    fn visit_param(&mut self, p: &'a Param) {
447        if p.is_placeholder {
448            self.visit_macro_invoc(p.id)
449        } else {
450            self.with_impl_trait(ImplTraitContext::Universal, |this| visit::walk_param(this, p))
451        }
452    }
453
454    // This method is called only when we are visiting an individual field
455    // after expanding an attribute on it.
456    fn visit_field_def(&mut self, field: &'a FieldDef) {
457        self.collect_field(field, None);
458    }
459
460    fn visit_crate(&mut self, krate: &'a Crate) {
461        if krate.is_placeholder {
462            self.visit_macro_invoc(krate.id)
463        } else {
464            visit::walk_crate(self, krate)
465        }
466    }
467
468    fn visit_attribute(&mut self, attr: &'a Attribute) -> Self::Result {
469        let orig_in_attr = mem::replace(&mut self.invocation_parent.in_attr, true);
470        visit::walk_attribute(self, attr);
471        self.invocation_parent.in_attr = orig_in_attr;
472    }
473
474    fn visit_inline_asm(&mut self, asm: &'a InlineAsm) {
475        let InlineAsm {
476            asm_macro: _,
477            template: _,
478            template_strs: _,
479            operands,
480            clobber_abis: _,
481            options: _,
482            line_spans: _,
483        } = asm;
484        for (op, _span) in operands {
485            match op {
486                InlineAsmOperand::In { expr, reg: _ }
487                | InlineAsmOperand::Out { expr: Some(expr), reg: _, late: _ }
488                | InlineAsmOperand::InOut { expr, reg: _, late: _ } => {
489                    self.visit_expr(expr);
490                }
491                InlineAsmOperand::Out { expr: None, reg: _, late: _ } => {}
492                InlineAsmOperand::SplitInOut { in_expr, out_expr, reg: _, late: _ } => {
493                    self.visit_expr(in_expr);
494                    if let Some(expr) = out_expr {
495                        self.visit_expr(expr);
496                    }
497                }
498                InlineAsmOperand::Const { anon_const } => {
499                    let def = self.create_def(
500                        anon_const.id,
501                        None,
502                        DefKind::InlineConst,
503                        anon_const.value.span,
504                    );
505                    self.with_parent(def, |this| visit::walk_anon_const(this, anon_const));
506                }
507                InlineAsmOperand::Sym { sym } => self.visit_inline_asm_sym(sym),
508                InlineAsmOperand::Label { block } => self.visit_block(block),
509            }
510        }
511    }
512}