rustc_resolve/
def_collector.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
use std::mem;

use rustc_ast::visit::FnKind;
use rustc_ast::*;
use rustc_ast_pretty::pprust;
use rustc_expand::expand::AstFragment;
use rustc_hir as hir;
use rustc_hir::def::{CtorKind, CtorOf, DefKind};
use rustc_hir::def_id::LocalDefId;
use rustc_span::Span;
use rustc_span::hygiene::LocalExpnId;
use rustc_span::symbol::{Symbol, kw, sym};
use tracing::debug;

use crate::{ImplTraitContext, InvocationParent, PendingAnonConstInfo, Resolver};

pub(crate) fn collect_definitions(
    resolver: &mut Resolver<'_, '_>,
    fragment: &AstFragment,
    expansion: LocalExpnId,
) {
    let InvocationParent { parent_def, pending_anon_const_info, impl_trait_context, in_attr } =
        resolver.invocation_parents[&expansion];
    let mut visitor = DefCollector {
        resolver,
        parent_def,
        pending_anon_const_info,
        expansion,
        impl_trait_context,
        in_attr,
    };
    fragment.visit_with(&mut visitor);
}

/// Creates `DefId`s for nodes in the AST.
struct DefCollector<'a, 'ra, 'tcx> {
    resolver: &'a mut Resolver<'ra, 'tcx>,
    parent_def: LocalDefId,
    /// If we have an anon const that consists of a macro invocation, e.g. `Foo<{ m!() }>`,
    /// we need to wait until we know what the macro expands to before we create the def for
    /// the anon const. That's because we lower some anon consts into `hir::ConstArgKind::Path`,
    /// which don't have defs.
    ///
    /// See `Self::visit_anon_const()`.
    pending_anon_const_info: Option<PendingAnonConstInfo>,
    impl_trait_context: ImplTraitContext,
    in_attr: bool,
    expansion: LocalExpnId,
}

impl<'a, 'ra, 'tcx> DefCollector<'a, 'ra, 'tcx> {
    fn create_def(
        &mut self,
        node_id: NodeId,
        name: Symbol,
        def_kind: DefKind,
        span: Span,
    ) -> LocalDefId {
        let parent_def = self.parent_def;
        debug!(
            "create_def(node_id={:?}, def_kind={:?}, parent_def={:?})",
            node_id, def_kind, parent_def
        );
        self.resolver
            .create_def(
                parent_def,
                node_id,
                name,
                def_kind,
                self.expansion.to_expn_id(),
                span.with_parent(None),
            )
            .def_id()
    }

    fn with_parent<F: FnOnce(&mut Self)>(&mut self, parent_def: LocalDefId, f: F) {
        let orig_parent_def = mem::replace(&mut self.parent_def, parent_def);
        f(self);
        self.parent_def = orig_parent_def;
    }

    fn with_impl_trait<F: FnOnce(&mut Self)>(
        &mut self,
        impl_trait_context: ImplTraitContext,
        f: F,
    ) {
        let orig_itc = mem::replace(&mut self.impl_trait_context, impl_trait_context);
        f(self);
        self.impl_trait_context = orig_itc;
    }

    fn collect_field(&mut self, field: &'a FieldDef, index: Option<usize>) {
        let index = |this: &Self| {
            index.unwrap_or_else(|| {
                let node_id = NodeId::placeholder_from_expn_id(this.expansion);
                this.resolver.placeholder_field_indices[&node_id]
            })
        };

        if field.is_placeholder {
            let old_index = self.resolver.placeholder_field_indices.insert(field.id, index(self));
            assert!(old_index.is_none(), "placeholder field index is reset for a node ID");
            self.visit_macro_invoc(field.id);
        } else {
            let name = field.ident.map_or_else(|| sym::integer(index(self)), |ident| ident.name);
            let def = self.create_def(field.id, name, DefKind::Field, field.span);
            self.with_parent(def, |this| visit::walk_field_def(this, field));
        }
    }

    fn visit_macro_invoc(&mut self, id: NodeId) {
        let id = id.placeholder_to_expn_id();
        let pending_anon_const_info = self.pending_anon_const_info.take();
        let old_parent = self.resolver.invocation_parents.insert(id, InvocationParent {
            parent_def: self.parent_def,
            pending_anon_const_info,
            impl_trait_context: self.impl_trait_context,
            in_attr: self.in_attr,
        });
        assert!(old_parent.is_none(), "parent `LocalDefId` is reset for an invocation");
    }

    /// Determines whether the const argument `AnonConst` is a simple macro call, optionally
    /// surrounded with braces.
    ///
    /// If this const argument *is* a trivial macro call then the id for the macro call is
    /// returned along with the information required to build the anon const's def if
    /// the macro call expands to a non-trivial expression.
    fn is_const_arg_trivial_macro_expansion(
        &self,
        anon_const: &'a AnonConst,
    ) -> Option<(PendingAnonConstInfo, NodeId)> {
        anon_const.value.optionally_braced_mac_call(false).map(|(block_was_stripped, id)| {
            (
                PendingAnonConstInfo {
                    id: anon_const.id,
                    span: anon_const.value.span,
                    block_was_stripped,
                },
                id,
            )
        })
    }

    /// Determines whether the expression `const_arg_sub_expr` is a simple macro call, sometimes
    /// surrounded with braces if a set of braces has not already been entered. This is required
    /// as `{ N }` is treated as equivalent to a bare parameter `N` whereas `{{ N }}` is treated as
    /// a real block expression and is lowered to an anonymous constant which is not allowed to use
    /// generic parameters.
    ///
    /// If this expression is a trivial macro call then the id for the macro call is
    /// returned along with the information required to build the anon const's def if
    /// the macro call expands to a non-trivial expression.
    fn is_const_arg_sub_expr_trivial_macro_expansion(
        &self,
        const_arg_sub_expr: &'a Expr,
    ) -> Option<(PendingAnonConstInfo, NodeId)> {
        let pending_anon = self.pending_anon_const_info.unwrap_or_else(||
            panic!("Checking expr is trivial macro call without having entered anon const: `{const_arg_sub_expr:?}`"),
        );

        const_arg_sub_expr.optionally_braced_mac_call(pending_anon.block_was_stripped).map(
            |(block_was_stripped, id)| {
                (PendingAnonConstInfo { block_was_stripped, ..pending_anon }, id)
            },
        )
    }
}

impl<'a, 'ra, 'tcx> visit::Visitor<'a> for DefCollector<'a, 'ra, 'tcx> {
    fn visit_item(&mut self, i: &'a Item) {
        // Pick the def data. This need not be unique, but the more
        // information we encapsulate into, the better
        let mut opt_macro_data = None;
        let def_kind = match &i.kind {
            ItemKind::Impl(i) => DefKind::Impl { of_trait: i.of_trait.is_some() },
            ItemKind::ForeignMod(..) => DefKind::ForeignMod,
            ItemKind::Mod(..) => DefKind::Mod,
            ItemKind::Trait(..) => DefKind::Trait,
            ItemKind::TraitAlias(..) => DefKind::TraitAlias,
            ItemKind::Enum(..) => DefKind::Enum,
            ItemKind::Struct(..) => DefKind::Struct,
            ItemKind::Union(..) => DefKind::Union,
            ItemKind::ExternCrate(..) => DefKind::ExternCrate,
            ItemKind::TyAlias(..) => DefKind::TyAlias,
            ItemKind::Static(s) => DefKind::Static {
                safety: hir::Safety::Safe,
                mutability: s.mutability,
                nested: false,
            },
            ItemKind::Const(..) => DefKind::Const,
            ItemKind::Fn(..) | ItemKind::Delegation(..) => DefKind::Fn,
            ItemKind::MacroDef(def) => {
                let edition = self.resolver.tcx.sess.edition();
                let macro_data =
                    self.resolver.compile_macro(def, i.ident, &i.attrs, i.span, i.id, edition);
                let macro_kind = macro_data.ext.macro_kind();
                opt_macro_data = Some(macro_data);
                DefKind::Macro(macro_kind)
            }
            ItemKind::GlobalAsm(..) => DefKind::GlobalAsm,
            ItemKind::Use(..) => return visit::walk_item(self, i),
            ItemKind::MacCall(..) | ItemKind::DelegationMac(..) => {
                return self.visit_macro_invoc(i.id);
            }
        };
        let def_id = self.create_def(i.id, i.ident.name, def_kind, i.span);

        if let Some(macro_data) = opt_macro_data {
            self.resolver.macro_map.insert(def_id.to_def_id(), macro_data);
        }

        self.with_parent(def_id, |this| {
            this.with_impl_trait(ImplTraitContext::Existential, |this| {
                match i.kind {
                    ItemKind::Struct(ref struct_def, _) | ItemKind::Union(ref struct_def, _) => {
                        // If this is a unit or tuple-like struct, register the constructor.
                        if let Some((ctor_kind, ctor_node_id)) = CtorKind::from_ast(struct_def) {
                            this.create_def(
                                ctor_node_id,
                                kw::Empty,
                                DefKind::Ctor(CtorOf::Struct, ctor_kind),
                                i.span,
                            );
                        }
                    }
                    _ => {}
                }
                visit::walk_item(this, i);
            })
        });
    }

    fn visit_fn(&mut self, fn_kind: FnKind<'a>, span: Span, _: NodeId) {
        match fn_kind {
            FnKind::Fn(_ctxt, _ident, FnSig { header, decl, span: _ }, _vis, generics, body)
                if let Some(coroutine_kind) = header.coroutine_kind =>
            {
                self.visit_fn_header(header);
                self.visit_generics(generics);

                // For async functions, we need to create their inner defs inside of a
                // closure to match their desugared representation. Besides that,
                // we must mirror everything that `visit::walk_fn` below does.
                let FnDecl { inputs, output } = &**decl;
                for param in inputs {
                    self.visit_param(param);
                }

                let (return_id, return_span) = coroutine_kind.return_id();
                let return_def =
                    self.create_def(return_id, kw::Empty, DefKind::OpaqueTy, return_span);
                self.with_parent(return_def, |this| this.visit_fn_ret_ty(output));

                // If this async fn has no body (i.e. it's an async fn signature in a trait)
                // then the closure_def will never be used, and we should avoid generating a
                // def-id for it.
                if let Some(body) = body {
                    let closure_def = self.create_def(
                        coroutine_kind.closure_id(),
                        kw::Empty,
                        DefKind::Closure,
                        span,
                    );
                    self.with_parent(closure_def, |this| this.visit_block(body));
                }
            }
            FnKind::Closure(binder, Some(coroutine_kind), decl, body) => {
                self.visit_closure_binder(binder);
                visit::walk_fn_decl(self, decl);

                // Async closures desugar to closures inside of closures, so
                // we must create two defs.
                let coroutine_def =
                    self.create_def(coroutine_kind.closure_id(), kw::Empty, DefKind::Closure, span);
                self.with_parent(coroutine_def, |this| this.visit_expr(body));
            }
            _ => visit::walk_fn(self, fn_kind),
        }
    }

    fn visit_use_tree(&mut self, use_tree: &'a UseTree, id: NodeId, _nested: bool) {
        self.create_def(id, kw::Empty, DefKind::Use, use_tree.span);
        visit::walk_use_tree(self, use_tree, id);
    }

    fn visit_foreign_item(&mut self, fi: &'a ForeignItem) {
        let def_kind = match fi.kind {
            ForeignItemKind::Static(box StaticItem { ty: _, mutability, expr: _, safety }) => {
                let safety = match safety {
                    ast::Safety::Unsafe(_) | ast::Safety::Default => hir::Safety::Unsafe,
                    ast::Safety::Safe(_) => hir::Safety::Safe,
                };

                DefKind::Static { safety, mutability, nested: false }
            }
            ForeignItemKind::Fn(_) => DefKind::Fn,
            ForeignItemKind::TyAlias(_) => DefKind::ForeignTy,
            ForeignItemKind::MacCall(_) => return self.visit_macro_invoc(fi.id),
        };

        let def = self.create_def(fi.id, fi.ident.name, def_kind, fi.span);

        self.with_parent(def, |this| visit::walk_item(this, fi));
    }

    fn visit_variant(&mut self, v: &'a Variant) {
        if v.is_placeholder {
            return self.visit_macro_invoc(v.id);
        }
        let def = self.create_def(v.id, v.ident.name, DefKind::Variant, v.span);
        self.with_parent(def, |this| {
            if let Some((ctor_kind, ctor_node_id)) = CtorKind::from_ast(&v.data) {
                this.create_def(
                    ctor_node_id,
                    kw::Empty,
                    DefKind::Ctor(CtorOf::Variant, ctor_kind),
                    v.span,
                );
            }
            visit::walk_variant(this, v)
        });
    }

    fn visit_variant_data(&mut self, data: &'a VariantData) {
        // The assumption here is that non-`cfg` macro expansion cannot change field indices.
        // It currently holds because only inert attributes are accepted on fields,
        // and every such attribute expands into a single field after it's resolved.
        for (index, field) in data.fields().iter().enumerate() {
            self.collect_field(field, Some(index));
        }
    }

    fn visit_generic_param(&mut self, param: &'a GenericParam) {
        if param.is_placeholder {
            self.visit_macro_invoc(param.id);
            return;
        }
        let def_kind = match param.kind {
            GenericParamKind::Lifetime { .. } => DefKind::LifetimeParam,
            GenericParamKind::Type { .. } => DefKind::TyParam,
            GenericParamKind::Const { .. } => DefKind::ConstParam,
        };
        self.create_def(param.id, param.ident.name, def_kind, param.ident.span);

        // impl-Trait can happen inside generic parameters, like
        // ```
        // fn foo<U: Iterator<Item = impl Clone>>() {}
        // ```
        //
        // In that case, the impl-trait is lowered as an additional generic parameter.
        self.with_impl_trait(ImplTraitContext::Universal, |this| {
            visit::walk_generic_param(this, param)
        });
    }

    fn visit_assoc_item(&mut self, i: &'a AssocItem, ctxt: visit::AssocCtxt) {
        let def_kind = match &i.kind {
            AssocItemKind::Fn(..) | AssocItemKind::Delegation(..) => DefKind::AssocFn,
            AssocItemKind::Const(..) => DefKind::AssocConst,
            AssocItemKind::Type(..) => DefKind::AssocTy,
            AssocItemKind::MacCall(..) | AssocItemKind::DelegationMac(..) => {
                return self.visit_macro_invoc(i.id);
            }
        };

        let def = self.create_def(i.id, i.ident.name, def_kind, i.span);
        self.with_parent(def, |this| visit::walk_assoc_item(this, i, ctxt));
    }

    fn visit_pat(&mut self, pat: &'a Pat) {
        match pat.kind {
            PatKind::MacCall(..) => self.visit_macro_invoc(pat.id),
            _ => visit::walk_pat(self, pat),
        }
    }

    fn visit_anon_const(&mut self, constant: &'a AnonConst) {
        // HACK(min_generic_const_args): don't create defs for anon consts if we think they will
        // later be turned into ConstArgKind::Path's. because this is before resolve is done, we
        // may accidentally identify a construction of a unit struct as a param and not create a
        // def. we'll then create a def later in ast lowering in this case. the parent of nested
        // items will be messed up, but that's ok because there can't be any if we're just looking
        // for bare idents.

        if let Some((pending_anon, macro_invoc)) =
            self.is_const_arg_trivial_macro_expansion(constant)
        {
            self.pending_anon_const_info = Some(pending_anon);
            return self.visit_macro_invoc(macro_invoc);
        } else if constant.value.is_potential_trivial_const_arg(true) {
            return visit::walk_anon_const(self, constant);
        }

        let def = self.create_def(constant.id, kw::Empty, DefKind::AnonConst, constant.value.span);
        self.with_parent(def, |this| visit::walk_anon_const(this, constant));
    }

    fn visit_expr(&mut self, expr: &'a Expr) {
        // If we're visiting the expression of a const argument that was a macro call then
        // check if it is *still* unknown whether it is a trivial const arg or not. If so
        // recurse into the macro call and delay creating the anon const def until expansion.
        if self.pending_anon_const_info.is_some()
            && let Some((pending_anon, macro_invoc)) =
                self.is_const_arg_sub_expr_trivial_macro_expansion(expr)
        {
            self.pending_anon_const_info = Some(pending_anon);
            return self.visit_macro_invoc(macro_invoc);
        }

        // See self.pending_anon_const_info for explanation
        let parent_def = self
            .pending_anon_const_info
            .take()
            // If we already stripped away a set of braces then do not do it again when determining
            // if the macro expanded to a trivial const arg. This arises in cases such as:
            // `Foo<{ bar!() }>` where `bar!()` expands to `{ N }`. This should not be considered a
            // trivial const argument even though `{ N }` by itself *is*.
            .filter(|pending_anon| {
                !expr.is_potential_trivial_const_arg(!pending_anon.block_was_stripped)
            })
            .map(|pending_anon| {
                self.create_def(pending_anon.id, kw::Empty, DefKind::AnonConst, pending_anon.span)
            })
            .unwrap_or(self.parent_def);

        self.with_parent(parent_def, |this| {
            let parent_def = match expr.kind {
                ExprKind::MacCall(..) => return this.visit_macro_invoc(expr.id),
                ExprKind::Closure(..) | ExprKind::Gen(..) => {
                    this.create_def(expr.id, kw::Empty, DefKind::Closure, expr.span)
                }
                ExprKind::ConstBlock(ref constant) => {
                    for attr in &expr.attrs {
                        visit::walk_attribute(this, attr);
                    }
                    let def = this.create_def(
                        constant.id,
                        kw::Empty,
                        DefKind::InlineConst,
                        constant.value.span,
                    );
                    this.with_parent(def, |this| visit::walk_anon_const(this, constant));
                    return;
                }
                _ => this.parent_def,
            };

            this.with_parent(parent_def, |this| visit::walk_expr(this, expr))
        })
    }

    fn visit_ty(&mut self, ty: &'a Ty) {
        match &ty.kind {
            TyKind::MacCall(..) => self.visit_macro_invoc(ty.id),
            TyKind::ImplTrait(id, _) => {
                // HACK: pprust breaks strings with newlines when the type
                // gets too long. We don't want these to show up in compiler
                // output or built artifacts, so replace them here...
                // Perhaps we should instead format APITs more robustly.
                let name = Symbol::intern(&pprust::ty_to_string(ty).replace('\n', " "));
                let kind = match self.impl_trait_context {
                    ImplTraitContext::Universal => DefKind::TyParam,
                    ImplTraitContext::Existential => DefKind::OpaqueTy,
                };
                let id = self.create_def(*id, name, kind, ty.span);
                match self.impl_trait_context {
                    // Do not nest APIT, as we desugar them as `impl_trait: bounds`,
                    // so the `impl_trait` node is not a parent to `bounds`.
                    ImplTraitContext::Universal => visit::walk_ty(self, ty),
                    ImplTraitContext::Existential => {
                        self.with_parent(id, |this| visit::walk_ty(this, ty))
                    }
                };
            }
            _ => visit::walk_ty(self, ty),
        }
    }

    fn visit_stmt(&mut self, stmt: &'a Stmt) {
        match stmt.kind {
            StmtKind::MacCall(..) => self.visit_macro_invoc(stmt.id),
            _ => visit::walk_stmt(self, stmt),
        }
    }

    fn visit_arm(&mut self, arm: &'a Arm) {
        if arm.is_placeholder { self.visit_macro_invoc(arm.id) } else { visit::walk_arm(self, arm) }
    }

    fn visit_expr_field(&mut self, f: &'a ExprField) {
        if f.is_placeholder {
            self.visit_macro_invoc(f.id)
        } else {
            visit::walk_expr_field(self, f)
        }
    }

    fn visit_pat_field(&mut self, fp: &'a PatField) {
        if fp.is_placeholder {
            self.visit_macro_invoc(fp.id)
        } else {
            visit::walk_pat_field(self, fp)
        }
    }

    fn visit_param(&mut self, p: &'a Param) {
        if p.is_placeholder {
            self.visit_macro_invoc(p.id)
        } else {
            self.with_impl_trait(ImplTraitContext::Universal, |this| visit::walk_param(this, p))
        }
    }

    // This method is called only when we are visiting an individual field
    // after expanding an attribute on it.
    fn visit_field_def(&mut self, field: &'a FieldDef) {
        self.collect_field(field, None);
    }

    fn visit_crate(&mut self, krate: &'a Crate) {
        if krate.is_placeholder {
            self.visit_macro_invoc(krate.id)
        } else {
            visit::walk_crate(self, krate)
        }
    }

    fn visit_attribute(&mut self, attr: &'a Attribute) -> Self::Result {
        let orig_in_attr = mem::replace(&mut self.in_attr, true);
        visit::walk_attribute(self, attr);
        self.in_attr = orig_in_attr;
    }
}