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