rustc_resolve/
def_collector.rs

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