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