]> git.lizzy.rs Git - rust.git/blob - src/librustc_passes/dead.rs
Rollup merge of #70950 - nikomatsakis:leak-check-nll-2, r=matthewjasper
[rust.git] / src / librustc_passes / dead.rs
1 // This implements the dead-code warning pass. It follows middle::reachable
2 // closely. The idea is that all reachable symbols are live, codes called
3 // from live codes are live, and everything else is dead.
4
5 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
6 use rustc_hir as hir;
7 use rustc_hir::def::{CtorOf, DefKind, Res};
8 use rustc_hir::def_id::{DefId, LOCAL_CRATE};
9 use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
10 use rustc_hir::itemlikevisit::ItemLikeVisitor;
11 use rustc_hir::{Node, PatKind, TyKind};
12 use rustc_middle::hir::map::Map;
13 use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
14 use rustc_middle::middle::privacy;
15 use rustc_middle::ty::{self, DefIdTree, TyCtxt};
16 use rustc_session::lint;
17
18 use rustc_ast::{ast, attr};
19 use rustc_span::symbol::sym;
20
21 // Any local node that may call something in its body block should be
22 // explored. For example, if it's a live Node::Item that is a
23 // function, then we should explore its block to check for codes that
24 // may need to be marked as live.
25 fn should_explore(tcx: TyCtxt<'_>, hir_id: hir::HirId) -> bool {
26     match tcx.hir().find(hir_id) {
27         Some(
28             Node::Item(..)
29             | Node::ImplItem(..)
30             | Node::ForeignItem(..)
31             | Node::TraitItem(..)
32             | Node::Variant(..)
33             | Node::AnonConst(..)
34             | Node::Pat(..),
35         ) => true,
36         _ => false,
37     }
38 }
39
40 struct MarkSymbolVisitor<'a, 'tcx> {
41     worklist: Vec<hir::HirId>,
42     tcx: TyCtxt<'tcx>,
43     tables: &'a ty::TypeckTables<'tcx>,
44     live_symbols: FxHashSet<hir::HirId>,
45     repr_has_repr_c: bool,
46     in_pat: bool,
47     inherited_pub_visibility: bool,
48     ignore_variant_stack: Vec<DefId>,
49     // maps from tuple struct constructors to tuple struct items
50     struct_constructors: FxHashMap<hir::HirId, hir::HirId>,
51 }
52
53 impl<'a, 'tcx> MarkSymbolVisitor<'a, 'tcx> {
54     fn check_def_id(&mut self, def_id: DefId) {
55         if let Some(def_id) = def_id.as_local() {
56             let hir_id = self.tcx.hir().as_local_hir_id(def_id);
57             if should_explore(self.tcx, hir_id) || self.struct_constructors.contains_key(&hir_id) {
58                 self.worklist.push(hir_id);
59             }
60             self.live_symbols.insert(hir_id);
61         }
62     }
63
64     fn insert_def_id(&mut self, def_id: DefId) {
65         if let Some(def_id) = def_id.as_local() {
66             let hir_id = self.tcx.hir().as_local_hir_id(def_id);
67             debug_assert!(!should_explore(self.tcx, hir_id));
68             self.live_symbols.insert(hir_id);
69         }
70     }
71
72     fn handle_res(&mut self, res: Res) {
73         match res {
74             Res::Def(DefKind::Const | DefKind::AssocConst | DefKind::TyAlias, _) => {
75                 self.check_def_id(res.def_id());
76             }
77             _ if self.in_pat => {}
78             Res::PrimTy(..) | Res::SelfCtor(..) | Res::Local(..) => {}
79             Res::Def(DefKind::Ctor(CtorOf::Variant, ..), ctor_def_id) => {
80                 let variant_id = self.tcx.parent(ctor_def_id).unwrap();
81                 let enum_id = self.tcx.parent(variant_id).unwrap();
82                 self.check_def_id(enum_id);
83                 if !self.ignore_variant_stack.contains(&ctor_def_id) {
84                     self.check_def_id(variant_id);
85                 }
86             }
87             Res::Def(DefKind::Variant, variant_id) => {
88                 let enum_id = self.tcx.parent(variant_id).unwrap();
89                 self.check_def_id(enum_id);
90                 if !self.ignore_variant_stack.contains(&variant_id) {
91                     self.check_def_id(variant_id);
92                 }
93             }
94             Res::SelfTy(t, i) => {
95                 if let Some(t) = t {
96                     self.check_def_id(t);
97                 }
98                 if let Some(i) = i {
99                     self.check_def_id(i);
100                 }
101             }
102             Res::ToolMod | Res::NonMacroAttr(..) | Res::Err => {}
103             _ => {
104                 self.check_def_id(res.def_id());
105             }
106         }
107     }
108
109     fn lookup_and_handle_method(&mut self, id: hir::HirId) {
110         if let Some(def_id) = self.tables.type_dependent_def_id(id) {
111             self.check_def_id(def_id);
112         } else {
113             bug!("no type-dependent def for method");
114         }
115     }
116
117     fn handle_field_access(&mut self, lhs: &hir::Expr<'_>, hir_id: hir::HirId) {
118         match self.tables.expr_ty_adjusted(lhs).kind {
119             ty::Adt(def, _) => {
120                 let index = self.tcx.field_index(hir_id, self.tables);
121                 self.insert_def_id(def.non_enum_variant().fields[index].did);
122             }
123             ty::Tuple(..) => {}
124             _ => span_bug!(lhs.span, "named field access on non-ADT"),
125         }
126     }
127
128     fn handle_field_pattern_match(
129         &mut self,
130         lhs: &hir::Pat<'_>,
131         res: Res,
132         pats: &[hir::FieldPat<'_>],
133     ) {
134         let variant = match self.tables.node_type(lhs.hir_id).kind {
135             ty::Adt(adt, _) => adt.variant_of_res(res),
136             _ => span_bug!(lhs.span, "non-ADT in struct pattern"),
137         };
138         for pat in pats {
139             if let PatKind::Wild = pat.pat.kind {
140                 continue;
141             }
142             let index = self.tcx.field_index(pat.hir_id, self.tables);
143             self.insert_def_id(variant.fields[index].did);
144         }
145     }
146
147     fn mark_live_symbols(&mut self) {
148         let mut scanned = FxHashSet::default();
149         while let Some(id) = self.worklist.pop() {
150             if !scanned.insert(id) {
151                 continue;
152             }
153
154             // in the case of tuple struct constructors we want to check the item, not the generated
155             // tuple struct constructor function
156             let id = self.struct_constructors.get(&id).cloned().unwrap_or(id);
157
158             if let Some(node) = self.tcx.hir().find(id) {
159                 self.live_symbols.insert(id);
160                 self.visit_node(node);
161             }
162         }
163     }
164
165     fn visit_node(&mut self, node: Node<'tcx>) {
166         let had_repr_c = self.repr_has_repr_c;
167         self.repr_has_repr_c = false;
168         let had_inherited_pub_visibility = self.inherited_pub_visibility;
169         self.inherited_pub_visibility = false;
170         match node {
171             Node::Item(item) => match item.kind {
172                 hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) => {
173                     let def_id = self.tcx.hir().local_def_id(item.hir_id);
174                     let def = self.tcx.adt_def(def_id);
175                     self.repr_has_repr_c = def.repr.c();
176
177                     intravisit::walk_item(self, &item);
178                 }
179                 hir::ItemKind::Enum(..) => {
180                     self.inherited_pub_visibility = item.vis.node.is_pub();
181
182                     intravisit::walk_item(self, &item);
183                 }
184                 hir::ItemKind::ForeignMod(..) => {}
185                 _ => {
186                     intravisit::walk_item(self, &item);
187                 }
188             },
189             Node::TraitItem(trait_item) => {
190                 intravisit::walk_trait_item(self, trait_item);
191             }
192             Node::ImplItem(impl_item) => {
193                 intravisit::walk_impl_item(self, impl_item);
194             }
195             Node::ForeignItem(foreign_item) => {
196                 intravisit::walk_foreign_item(self, &foreign_item);
197             }
198             _ => {}
199         }
200         self.repr_has_repr_c = had_repr_c;
201         self.inherited_pub_visibility = had_inherited_pub_visibility;
202     }
203
204     fn mark_as_used_if_union(&mut self, adt: &ty::AdtDef, fields: &[hir::Field<'_>]) {
205         if adt.is_union() && adt.non_enum_variant().fields.len() > 1 && adt.did.is_local() {
206             for field in fields {
207                 let index = self.tcx.field_index(field.hir_id, self.tables);
208                 self.insert_def_id(adt.non_enum_variant().fields[index].did);
209             }
210         }
211     }
212 }
213
214 impl<'a, 'tcx> Visitor<'tcx> for MarkSymbolVisitor<'a, 'tcx> {
215     type Map = intravisit::ErasedMap<'tcx>;
216
217     fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
218         NestedVisitorMap::None
219     }
220
221     fn visit_nested_body(&mut self, body: hir::BodyId) {
222         let old_tables = self.tables;
223         self.tables = self.tcx.body_tables(body);
224         let body = self.tcx.hir().body(body);
225         self.visit_body(body);
226         self.tables = old_tables;
227     }
228
229     fn visit_variant_data(
230         &mut self,
231         def: &'tcx hir::VariantData<'tcx>,
232         _: ast::Name,
233         _: &hir::Generics<'_>,
234         _: hir::HirId,
235         _: rustc_span::Span,
236     ) {
237         let has_repr_c = self.repr_has_repr_c;
238         let inherited_pub_visibility = self.inherited_pub_visibility;
239         let live_fields = def
240             .fields()
241             .iter()
242             .filter(|f| has_repr_c || inherited_pub_visibility || f.vis.node.is_pub());
243         self.live_symbols.extend(live_fields.map(|f| f.hir_id));
244
245         intravisit::walk_struct_def(self, def);
246     }
247
248     fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
249         match expr.kind {
250             hir::ExprKind::Path(ref qpath @ hir::QPath::TypeRelative(..)) => {
251                 let res = self.tables.qpath_res(qpath, expr.hir_id);
252                 self.handle_res(res);
253             }
254             hir::ExprKind::MethodCall(..) => {
255                 self.lookup_and_handle_method(expr.hir_id);
256             }
257             hir::ExprKind::Field(ref lhs, ..) => {
258                 self.handle_field_access(&lhs, expr.hir_id);
259             }
260             hir::ExprKind::Struct(ref qpath, ref fields, _) => {
261                 let res = self.tables.qpath_res(qpath, expr.hir_id);
262                 self.handle_res(res);
263                 if let ty::Adt(ref adt, _) = self.tables.expr_ty(expr).kind {
264                     self.mark_as_used_if_union(adt, fields);
265                 }
266             }
267             _ => (),
268         }
269
270         intravisit::walk_expr(self, expr);
271     }
272
273     fn visit_arm(&mut self, arm: &'tcx hir::Arm<'tcx>) {
274         // Inside the body, ignore constructions of variants
275         // necessary for the pattern to match. Those construction sites
276         // can't be reached unless the variant is constructed elsewhere.
277         let len = self.ignore_variant_stack.len();
278         self.ignore_variant_stack.extend(arm.pat.necessary_variants());
279         intravisit::walk_arm(self, arm);
280         self.ignore_variant_stack.truncate(len);
281     }
282
283     fn visit_pat(&mut self, pat: &'tcx hir::Pat<'tcx>) {
284         match pat.kind {
285             PatKind::Struct(ref path, ref fields, _) => {
286                 let res = self.tables.qpath_res(path, pat.hir_id);
287                 self.handle_field_pattern_match(pat, res, fields);
288             }
289             PatKind::Path(ref qpath) => {
290                 let res = self.tables.qpath_res(qpath, pat.hir_id);
291                 self.handle_res(res);
292             }
293             _ => (),
294         }
295
296         self.in_pat = true;
297         intravisit::walk_pat(self, pat);
298         self.in_pat = false;
299     }
300
301     fn visit_path(&mut self, path: &'tcx hir::Path<'tcx>, _: hir::HirId) {
302         self.handle_res(path.res);
303         intravisit::walk_path(self, path);
304     }
305
306     fn visit_ty(&mut self, ty: &'tcx hir::Ty<'tcx>) {
307         if let TyKind::Def(item_id, _) = ty.kind {
308             let item = self.tcx.hir().expect_item(item_id.id);
309             intravisit::walk_item(self, item);
310         }
311         intravisit::walk_ty(self, ty);
312     }
313
314     fn visit_anon_const(&mut self, c: &'tcx hir::AnonConst) {
315         self.live_symbols.insert(c.hir_id);
316         intravisit::walk_anon_const(self, c);
317     }
318 }
319
320 fn has_allow_dead_code_or_lang_attr(
321     tcx: TyCtxt<'_>,
322     id: hir::HirId,
323     attrs: &[ast::Attribute],
324 ) -> bool {
325     if attr::contains_name(attrs, sym::lang) {
326         return true;
327     }
328
329     // Stable attribute for #[lang = "panic_impl"]
330     if attr::contains_name(attrs, sym::panic_handler) {
331         return true;
332     }
333
334     // (To be) stable attribute for #[lang = "oom"]
335     if attr::contains_name(attrs, sym::alloc_error_handler) {
336         return true;
337     }
338
339     let def_id = tcx.hir().local_def_id(id);
340     let cg_attrs = tcx.codegen_fn_attrs(def_id);
341
342     // #[used], #[no_mangle], #[export_name], etc also keeps the item alive
343     // forcefully, e.g., for placing it in a specific section.
344     if cg_attrs.contains_extern_indicator() || cg_attrs.flags.contains(CodegenFnAttrFlags::USED) {
345         return true;
346     }
347
348     tcx.lint_level_at_node(lint::builtin::DEAD_CODE, id).0 == lint::Allow
349 }
350
351 // This visitor seeds items that
352 //   1) We want to explicitly consider as live:
353 //     * Item annotated with #[allow(dead_code)]
354 //         - This is done so that if we want to suppress warnings for a
355 //           group of dead functions, we only have to annotate the "root".
356 //           For example, if both `f` and `g` are dead and `f` calls `g`,
357 //           then annotating `f` with `#[allow(dead_code)]` will suppress
358 //           warning for both `f` and `g`.
359 //     * Item annotated with #[lang=".."]
360 //         - This is because lang items are always callable from elsewhere.
361 //   or
362 //   2) We are not sure to be live or not
363 //     * Implementation of a trait method
364 struct LifeSeeder<'k, 'tcx> {
365     worklist: Vec<hir::HirId>,
366     krate: &'k hir::Crate<'k>,
367     tcx: TyCtxt<'tcx>,
368     // see `MarkSymbolVisitor::struct_constructors`
369     struct_constructors: FxHashMap<hir::HirId, hir::HirId>,
370 }
371
372 impl<'v, 'k, 'tcx> ItemLikeVisitor<'v> for LifeSeeder<'k, 'tcx> {
373     fn visit_item(&mut self, item: &hir::Item<'_>) {
374         let allow_dead_code = has_allow_dead_code_or_lang_attr(self.tcx, item.hir_id, &item.attrs);
375         if allow_dead_code {
376             self.worklist.push(item.hir_id);
377         }
378         match item.kind {
379             hir::ItemKind::Enum(ref enum_def, _) => {
380                 if allow_dead_code {
381                     self.worklist.extend(enum_def.variants.iter().map(|variant| variant.id));
382                 }
383
384                 for variant in enum_def.variants {
385                     if let Some(ctor_hir_id) = variant.data.ctor_hir_id() {
386                         self.struct_constructors.insert(ctor_hir_id, variant.id);
387                     }
388                 }
389             }
390             hir::ItemKind::Trait(.., trait_item_refs) => {
391                 for trait_item_ref in trait_item_refs {
392                     let trait_item = self.krate.trait_item(trait_item_ref.id);
393                     match trait_item.kind {
394                         hir::TraitItemKind::Const(_, Some(_))
395                         | hir::TraitItemKind::Fn(_, hir::TraitFn::Provided(_)) => {
396                             if has_allow_dead_code_or_lang_attr(
397                                 self.tcx,
398                                 trait_item.hir_id,
399                                 &trait_item.attrs,
400                             ) {
401                                 self.worklist.push(trait_item.hir_id);
402                             }
403                         }
404                         _ => {}
405                     }
406                 }
407             }
408             hir::ItemKind::Impl { ref of_trait, items, .. } => {
409                 for impl_item_ref in items {
410                     let impl_item = self.krate.impl_item(impl_item_ref.id);
411                     if of_trait.is_some()
412                         || has_allow_dead_code_or_lang_attr(
413                             self.tcx,
414                             impl_item.hir_id,
415                             &impl_item.attrs,
416                         )
417                     {
418                         self.worklist.push(impl_item_ref.id.hir_id);
419                     }
420                 }
421             }
422             hir::ItemKind::Struct(ref variant_data, _) => {
423                 if let Some(ctor_hir_id) = variant_data.ctor_hir_id() {
424                     self.struct_constructors.insert(ctor_hir_id, item.hir_id);
425                 }
426             }
427             _ => (),
428         }
429     }
430
431     fn visit_trait_item(&mut self, _item: &hir::TraitItem<'_>) {
432         // ignore: we are handling this in `visit_item` above
433     }
434
435     fn visit_impl_item(&mut self, _item: &hir::ImplItem<'_>) {
436         // ignore: we are handling this in `visit_item` above
437     }
438 }
439
440 fn create_and_seed_worklist<'tcx>(
441     tcx: TyCtxt<'tcx>,
442     access_levels: &privacy::AccessLevels,
443     krate: &hir::Crate<'_>,
444 ) -> (Vec<hir::HirId>, FxHashMap<hir::HirId, hir::HirId>) {
445     let worklist = access_levels
446         .map
447         .iter()
448         .filter_map(
449             |(&id, level)| {
450                 if level >= &privacy::AccessLevel::Reachable { Some(id) } else { None }
451             },
452         )
453         .chain(
454             // Seed entry point
455             tcx.entry_fn(LOCAL_CRATE).map(|(def_id, _)| tcx.hir().as_local_hir_id(def_id)),
456         )
457         .collect::<Vec<_>>();
458
459     // Seed implemented trait items
460     let mut life_seeder =
461         LifeSeeder { worklist, krate, tcx, struct_constructors: Default::default() };
462     krate.visit_all_item_likes(&mut life_seeder);
463
464     (life_seeder.worklist, life_seeder.struct_constructors)
465 }
466
467 fn find_live<'tcx>(
468     tcx: TyCtxt<'tcx>,
469     access_levels: &privacy::AccessLevels,
470     krate: &hir::Crate<'_>,
471 ) -> FxHashSet<hir::HirId> {
472     let (worklist, struct_constructors) = create_and_seed_worklist(tcx, access_levels, krate);
473     let mut symbol_visitor = MarkSymbolVisitor {
474         worklist,
475         tcx,
476         tables: &ty::TypeckTables::empty(None),
477         live_symbols: Default::default(),
478         repr_has_repr_c: false,
479         in_pat: false,
480         inherited_pub_visibility: false,
481         ignore_variant_stack: vec![],
482         struct_constructors,
483     };
484     symbol_visitor.mark_live_symbols();
485     symbol_visitor.live_symbols
486 }
487
488 struct DeadVisitor<'tcx> {
489     tcx: TyCtxt<'tcx>,
490     live_symbols: FxHashSet<hir::HirId>,
491 }
492
493 impl DeadVisitor<'tcx> {
494     fn should_warn_about_item(&mut self, item: &hir::Item<'_>) -> bool {
495         let should_warn = match item.kind {
496             hir::ItemKind::Static(..)
497             | hir::ItemKind::Const(..)
498             | hir::ItemKind::Fn(..)
499             | hir::ItemKind::TyAlias(..)
500             | hir::ItemKind::Enum(..)
501             | hir::ItemKind::Struct(..)
502             | hir::ItemKind::Union(..) => true,
503             _ => false,
504         };
505         should_warn && !self.symbol_is_live(item.hir_id)
506     }
507
508     fn should_warn_about_field(&mut self, field: &hir::StructField<'_>) -> bool {
509         let field_type = self.tcx.type_of(self.tcx.hir().local_def_id(field.hir_id));
510         !field.is_positional()
511             && !self.symbol_is_live(field.hir_id)
512             && !field_type.is_phantom_data()
513             && !has_allow_dead_code_or_lang_attr(self.tcx, field.hir_id, &field.attrs)
514     }
515
516     fn should_warn_about_variant(&mut self, variant: &hir::Variant<'_>) -> bool {
517         !self.symbol_is_live(variant.id)
518             && !has_allow_dead_code_or_lang_attr(self.tcx, variant.id, &variant.attrs)
519     }
520
521     fn should_warn_about_foreign_item(&mut self, fi: &hir::ForeignItem<'_>) -> bool {
522         !self.symbol_is_live(fi.hir_id)
523             && !has_allow_dead_code_or_lang_attr(self.tcx, fi.hir_id, &fi.attrs)
524     }
525
526     // id := HIR id of an item's definition.
527     fn symbol_is_live(&mut self, id: hir::HirId) -> bool {
528         if self.live_symbols.contains(&id) {
529             return true;
530         }
531         // If it's a type whose items are live, then it's live, too.
532         // This is done to handle the case where, for example, the static
533         // method of a private type is used, but the type itself is never
534         // called directly.
535         let def_id = self.tcx.hir().local_def_id(id);
536         let inherent_impls = self.tcx.inherent_impls(def_id);
537         for &impl_did in inherent_impls.iter() {
538             for &item_did in &self.tcx.associated_item_def_ids(impl_did)[..] {
539                 if let Some(did) = item_did.as_local() {
540                     let item_hir_id = self.tcx.hir().as_local_hir_id(did);
541                     if self.live_symbols.contains(&item_hir_id) {
542                         return true;
543                     }
544                 }
545             }
546         }
547         false
548     }
549
550     fn warn_dead_code(
551         &mut self,
552         id: hir::HirId,
553         span: rustc_span::Span,
554         name: ast::Name,
555         participle: &str,
556     ) {
557         if !name.as_str().starts_with('_') {
558             self.tcx.struct_span_lint_hir(lint::builtin::DEAD_CODE, id, span, |lint| {
559                 let def_id = self.tcx.hir().local_def_id(id);
560                 let descr = self.tcx.def_kind(def_id).descr(def_id.to_def_id());
561                 lint.build(&format!("{} is never {}: `{}`", descr, participle, name)).emit()
562             });
563         }
564     }
565 }
566
567 impl Visitor<'tcx> for DeadVisitor<'tcx> {
568     type Map = Map<'tcx>;
569
570     /// Walk nested items in place so that we don't report dead-code
571     /// on inner functions when the outer function is already getting
572     /// an error. We could do this also by checking the parents, but
573     /// this is how the code is setup and it seems harmless enough.
574     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
575         NestedVisitorMap::All(self.tcx.hir())
576     }
577
578     fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
579         if self.should_warn_about_item(item) {
580             // For most items, we want to highlight its identifier
581             let span = match item.kind {
582                 hir::ItemKind::Fn(..)
583                 | hir::ItemKind::Mod(..)
584                 | hir::ItemKind::Enum(..)
585                 | hir::ItemKind::Struct(..)
586                 | hir::ItemKind::Union(..)
587                 | hir::ItemKind::Trait(..)
588                 | hir::ItemKind::Impl { .. } => {
589                     // FIXME(66095): Because item.span is annotated with things
590                     // like expansion data, and ident.span isn't, we use the
591                     // def_span method if it's part of a macro invocation
592                     // (and thus has asource_callee set).
593                     // We should probably annotate ident.span with the macro
594                     // context, but that's a larger change.
595                     if item.span.source_callee().is_some() {
596                         self.tcx.sess.source_map().guess_head_span(item.span)
597                     } else {
598                         item.ident.span
599                     }
600                 }
601                 _ => item.span,
602             };
603             let participle = match item.kind {
604                 hir::ItemKind::Struct(..) => "constructed", // Issue #52325
605                 _ => "used",
606             };
607             self.warn_dead_code(item.hir_id, span, item.ident.name, participle);
608         } else {
609             // Only continue if we didn't warn
610             intravisit::walk_item(self, item);
611         }
612     }
613
614     fn visit_variant(
615         &mut self,
616         variant: &'tcx hir::Variant<'tcx>,
617         g: &'tcx hir::Generics<'tcx>,
618         id: hir::HirId,
619     ) {
620         if self.should_warn_about_variant(&variant) {
621             self.warn_dead_code(variant.id, variant.span, variant.ident.name, "constructed");
622         } else {
623             intravisit::walk_variant(self, variant, g, id);
624         }
625     }
626
627     fn visit_foreign_item(&mut self, fi: &'tcx hir::ForeignItem<'tcx>) {
628         if self.should_warn_about_foreign_item(fi) {
629             self.warn_dead_code(fi.hir_id, fi.span, fi.ident.name, "used");
630         }
631         intravisit::walk_foreign_item(self, fi);
632     }
633
634     fn visit_struct_field(&mut self, field: &'tcx hir::StructField<'tcx>) {
635         if self.should_warn_about_field(&field) {
636             self.warn_dead_code(field.hir_id, field.span, field.ident.name, "read");
637         }
638         intravisit::walk_struct_field(self, field);
639     }
640
641     fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
642         match impl_item.kind {
643             hir::ImplItemKind::Const(_, body_id) => {
644                 if !self.symbol_is_live(impl_item.hir_id) {
645                     self.warn_dead_code(
646                         impl_item.hir_id,
647                         impl_item.span,
648                         impl_item.ident.name,
649                         "used",
650                     );
651                 }
652                 self.visit_nested_body(body_id)
653             }
654             hir::ImplItemKind::Fn(_, body_id) => {
655                 if !self.symbol_is_live(impl_item.hir_id) {
656                     let span = self.tcx.sess.source_map().guess_head_span(impl_item.span);
657                     self.warn_dead_code(impl_item.hir_id, span, impl_item.ident.name, "used");
658                 }
659                 self.visit_nested_body(body_id)
660             }
661             hir::ImplItemKind::OpaqueTy(..) | hir::ImplItemKind::TyAlias(..) => {}
662         }
663     }
664
665     // Overwrite so that we don't warn the trait item itself.
666     fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) {
667         match trait_item.kind {
668             hir::TraitItemKind::Const(_, Some(body_id))
669             | hir::TraitItemKind::Fn(_, hir::TraitFn::Provided(body_id)) => {
670                 self.visit_nested_body(body_id)
671             }
672             hir::TraitItemKind::Const(_, None)
673             | hir::TraitItemKind::Fn(_, hir::TraitFn::Required(_))
674             | hir::TraitItemKind::Type(..) => {}
675         }
676     }
677 }
678
679 pub fn check_crate(tcx: TyCtxt<'_>) {
680     let access_levels = &tcx.privacy_access_levels(LOCAL_CRATE);
681     let krate = tcx.hir().krate();
682     let live_symbols = find_live(tcx, access_levels, krate);
683     let mut visitor = DeadVisitor { tcx, live_symbols };
684     intravisit::walk_crate(&mut visitor, krate);
685 }