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