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