]> git.lizzy.rs Git - rust.git/blob - src/librustc_passes/dead.rs
Rollup merge of #67887 - anp:tracked-std-panics, r=nagisa
[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::intravisit::{self, NestedVisitorMap, Visitor};
6 use rustc::lint;
7 use rustc::middle::codegen_fn_attrs::CodegenFnAttrFlags;
8 use rustc::middle::privacy;
9 use rustc::ty::{self, DefIdTree, TyCtxt};
10 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
11 use rustc_hir as hir;
12 use rustc_hir::def::{CtorOf, DefKind, Res};
13 use rustc_hir::def_id::{DefId, LOCAL_CRATE};
14 use rustc_hir::itemlikevisit::ItemLikeVisitor;
15 use rustc_hir::{Node, PatKind, TyKind};
16
17 use rustc_span;
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     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
214         NestedVisitorMap::None
215     }
216
217     fn visit_nested_body(&mut self, body: hir::BodyId) {
218         let old_tables = self.tables;
219         self.tables = self.tcx.body_tables(body);
220         let body = self.tcx.hir().body(body);
221         self.visit_body(body);
222         self.tables = old_tables;
223     }
224
225     fn visit_variant_data(
226         &mut self,
227         def: &'tcx hir::VariantData<'tcx>,
228         _: ast::Name,
229         _: &hir::Generics<'_>,
230         _: hir::HirId,
231         _: rustc_span::Span,
232     ) {
233         let has_repr_c = self.repr_has_repr_c;
234         let inherited_pub_visibility = self.inherited_pub_visibility;
235         let live_fields = def
236             .fields()
237             .iter()
238             .filter(|f| has_repr_c || inherited_pub_visibility || f.vis.node.is_pub());
239         self.live_symbols.extend(live_fields.map(|f| f.hir_id));
240
241         intravisit::walk_struct_def(self, def);
242     }
243
244     fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
245         match expr.kind {
246             hir::ExprKind::Path(ref qpath @ hir::QPath::TypeRelative(..)) => {
247                 let res = self.tables.qpath_res(qpath, expr.hir_id);
248                 self.handle_res(res);
249             }
250             hir::ExprKind::MethodCall(..) => {
251                 self.lookup_and_handle_method(expr.hir_id);
252             }
253             hir::ExprKind::Field(ref lhs, ..) => {
254                 self.handle_field_access(&lhs, expr.hir_id);
255             }
256             hir::ExprKind::Struct(_, ref fields, _) => {
257                 if let ty::Adt(ref adt, _) = self.tables.expr_ty(expr).kind {
258                     self.mark_as_used_if_union(adt, fields);
259                 }
260             }
261             _ => (),
262         }
263
264         intravisit::walk_expr(self, expr);
265     }
266
267     fn visit_arm(&mut self, arm: &'tcx hir::Arm<'tcx>) {
268         // Inside the body, ignore constructions of variants
269         // necessary for the pattern to match. Those construction sites
270         // can't be reached unless the variant is constructed elsewhere.
271         let len = self.ignore_variant_stack.len();
272         self.ignore_variant_stack.extend(arm.pat.necessary_variants());
273         intravisit::walk_arm(self, arm);
274         self.ignore_variant_stack.truncate(len);
275     }
276
277     fn visit_pat(&mut self, pat: &'tcx hir::Pat<'tcx>) {
278         match pat.kind {
279             PatKind::Struct(ref path, ref fields, _) => {
280                 let res = self.tables.qpath_res(path, pat.hir_id);
281                 self.handle_field_pattern_match(pat, res, fields);
282             }
283             PatKind::Path(ref qpath) => {
284                 let res = self.tables.qpath_res(qpath, pat.hir_id);
285                 self.handle_res(res);
286             }
287             _ => (),
288         }
289
290         self.in_pat = true;
291         intravisit::walk_pat(self, pat);
292         self.in_pat = false;
293     }
294
295     fn visit_path(&mut self, path: &'tcx hir::Path<'tcx>, _: hir::HirId) {
296         self.handle_res(path.res);
297         intravisit::walk_path(self, path);
298     }
299
300     fn visit_ty(&mut self, ty: &'tcx hir::Ty<'tcx>) {
301         match ty.kind {
302             TyKind::Def(item_id, _) => {
303                 let item = self.tcx.hir().expect_item(item_id.id);
304                 intravisit::walk_item(self, item);
305             }
306             _ => (),
307         }
308         intravisit::walk_ty(self, ty);
309     }
310
311     fn visit_anon_const(&mut self, c: &'tcx hir::AnonConst) {
312         self.live_symbols.insert(c.hir_id);
313         intravisit::walk_anon_const(self, c);
314     }
315 }
316
317 fn has_allow_dead_code_or_lang_attr(
318     tcx: TyCtxt<'_>,
319     id: hir::HirId,
320     attrs: &[ast::Attribute],
321 ) -> bool {
322     if attr::contains_name(attrs, sym::lang) {
323         return true;
324     }
325
326     // Stable attribute for #[lang = "panic_impl"]
327     if attr::contains_name(attrs, sym::panic_handler) {
328         return true;
329     }
330
331     // (To be) stable attribute for #[lang = "oom"]
332     if attr::contains_name(attrs, sym::alloc_error_handler) {
333         return true;
334     }
335
336     let def_id = tcx.hir().local_def_id(id);
337     let cg_attrs = tcx.codegen_fn_attrs(def_id);
338
339     // #[used], #[no_mangle], #[export_name], etc also keeps the item alive
340     // forcefully, e.g., for placing it in a specific section.
341     if cg_attrs.contains_extern_indicator() || cg_attrs.flags.contains(CodegenFnAttrFlags::USED) {
342         return true;
343     }
344
345     tcx.lint_level_at_node(lint::builtin::DEAD_CODE, id).0 == lint::Allow
346 }
347
348 // This visitor seeds items that
349 //   1) We want to explicitly consider as live:
350 //     * Item annotated with #[allow(dead_code)]
351 //         - This is done so that if we want to suppress warnings for a
352 //           group of dead functions, we only have to annotate the "root".
353 //           For example, if both `f` and `g` are dead and `f` calls `g`,
354 //           then annotating `f` with `#[allow(dead_code)]` will suppress
355 //           warning for both `f` and `g`.
356 //     * Item annotated with #[lang=".."]
357 //         - This is because lang items are always callable from elsewhere.
358 //   or
359 //   2) We are not sure to be live or not
360 //     * Implementation of a trait method
361 struct LifeSeeder<'k, 'tcx> {
362     worklist: Vec<hir::HirId>,
363     krate: &'k hir::Crate<'k>,
364     tcx: TyCtxt<'tcx>,
365     // see `MarkSymbolVisitor::struct_constructors`
366     struct_constructors: FxHashMap<hir::HirId, hir::HirId>,
367 }
368
369 impl<'v, 'k, 'tcx> ItemLikeVisitor<'v> for LifeSeeder<'k, 'tcx> {
370     fn visit_item(&mut self, item: &hir::Item<'_>) {
371         let allow_dead_code = has_allow_dead_code_or_lang_attr(self.tcx, item.hir_id, &item.attrs);
372         if allow_dead_code {
373             self.worklist.push(item.hir_id);
374         }
375         match item.kind {
376             hir::ItemKind::Enum(ref enum_def, _) => {
377                 if allow_dead_code {
378                     self.worklist.extend(enum_def.variants.iter().map(|variant| variant.id));
379                 }
380
381                 for variant in enum_def.variants {
382                     if let Some(ctor_hir_id) = variant.data.ctor_hir_id() {
383                         self.struct_constructors.insert(ctor_hir_id, variant.id);
384                     }
385                 }
386             }
387             hir::ItemKind::Trait(.., trait_item_refs) => {
388                 for trait_item_ref in trait_item_refs {
389                     let trait_item = self.krate.trait_item(trait_item_ref.id);
390                     match trait_item.kind {
391                         hir::TraitItemKind::Const(_, Some(_))
392                         | hir::TraitItemKind::Method(_, hir::TraitMethod::Provided(_)) => {
393                             if has_allow_dead_code_or_lang_attr(
394                                 self.tcx,
395                                 trait_item.hir_id,
396                                 &trait_item.attrs,
397                             ) {
398                                 self.worklist.push(trait_item.hir_id);
399                             }
400                         }
401                         _ => {}
402                     }
403                 }
404             }
405             hir::ItemKind::Impl(.., ref opt_trait, _, impl_item_refs) => {
406                 for impl_item_ref in impl_item_refs {
407                     let impl_item = self.krate.impl_item(impl_item_ref.id);
408                     if opt_trait.is_some()
409                         || has_allow_dead_code_or_lang_attr(
410                             self.tcx,
411                             impl_item.hir_id,
412                             &impl_item.attrs,
413                         )
414                     {
415                         self.worklist.push(impl_item_ref.id.hir_id);
416                     }
417                 }
418             }
419             hir::ItemKind::Struct(ref variant_data, _) => {
420                 if let Some(ctor_hir_id) = variant_data.ctor_hir_id() {
421                     self.struct_constructors.insert(ctor_hir_id, item.hir_id);
422                 }
423             }
424             _ => (),
425         }
426     }
427
428     fn visit_trait_item(&mut self, _item: &hir::TraitItem<'_>) {
429         // ignore: we are handling this in `visit_item` above
430     }
431
432     fn visit_impl_item(&mut self, _item: &hir::ImplItem<'_>) {
433         // ignore: we are handling this in `visit_item` above
434     }
435 }
436
437 fn create_and_seed_worklist<'tcx>(
438     tcx: TyCtxt<'tcx>,
439     access_levels: &privacy::AccessLevels,
440     krate: &hir::Crate<'_>,
441 ) -> (Vec<hir::HirId>, FxHashMap<hir::HirId, hir::HirId>) {
442     let worklist = access_levels
443         .map
444         .iter()
445         .filter_map(
446             |(&id, level)| {
447                 if level >= &privacy::AccessLevel::Reachable { Some(id) } else { None }
448             },
449         )
450         .chain(
451             // Seed entry point
452             tcx.entry_fn(LOCAL_CRATE).map(|(def_id, _)| tcx.hir().as_local_hir_id(def_id).unwrap()),
453         )
454         .collect::<Vec<_>>();
455
456     // Seed implemented trait items
457     let mut life_seeder =
458         LifeSeeder { worklist, krate, tcx, struct_constructors: Default::default() };
459     krate.visit_all_item_likes(&mut life_seeder);
460
461     (life_seeder.worklist, life_seeder.struct_constructors)
462 }
463
464 fn find_live<'tcx>(
465     tcx: TyCtxt<'tcx>,
466     access_levels: &privacy::AccessLevels,
467     krate: &hir::Crate<'_>,
468 ) -> FxHashSet<hir::HirId> {
469     let (worklist, struct_constructors) = create_and_seed_worklist(tcx, access_levels, krate);
470     let mut symbol_visitor = MarkSymbolVisitor {
471         worklist,
472         tcx,
473         tables: &ty::TypeckTables::empty(None),
474         live_symbols: Default::default(),
475         repr_has_repr_c: false,
476         in_pat: false,
477         inherited_pub_visibility: false,
478         ignore_variant_stack: vec![],
479         struct_constructors,
480     };
481     symbol_visitor.mark_live_symbols();
482     symbol_visitor.live_symbols
483 }
484
485 struct DeadVisitor<'tcx> {
486     tcx: TyCtxt<'tcx>,
487     live_symbols: FxHashSet<hir::HirId>,
488 }
489
490 impl DeadVisitor<'tcx> {
491     fn should_warn_about_item(&mut self, item: &hir::Item<'_>) -> bool {
492         let should_warn = match item.kind {
493             hir::ItemKind::Static(..)
494             | hir::ItemKind::Const(..)
495             | hir::ItemKind::Fn(..)
496             | hir::ItemKind::TyAlias(..)
497             | hir::ItemKind::Enum(..)
498             | hir::ItemKind::Struct(..)
499             | hir::ItemKind::Union(..) => true,
500             _ => false,
501         };
502         should_warn && !self.symbol_is_live(item.hir_id)
503     }
504
505     fn should_warn_about_field(&mut self, field: &hir::StructField<'_>) -> bool {
506         let field_type = self.tcx.type_of(self.tcx.hir().local_def_id(field.hir_id));
507         !field.is_positional()
508             && !self.symbol_is_live(field.hir_id)
509             && !field_type.is_phantom_data()
510             && !has_allow_dead_code_or_lang_attr(self.tcx, field.hir_id, &field.attrs)
511     }
512
513     fn should_warn_about_variant(&mut self, variant: &hir::Variant<'_>) -> bool {
514         !self.symbol_is_live(variant.id)
515             && !has_allow_dead_code_or_lang_attr(self.tcx, variant.id, &variant.attrs)
516     }
517
518     fn should_warn_about_foreign_item(&mut self, fi: &hir::ForeignItem<'_>) -> bool {
519         !self.symbol_is_live(fi.hir_id)
520             && !has_allow_dead_code_or_lang_attr(self.tcx, fi.hir_id, &fi.attrs)
521     }
522
523     // id := HIR id of an item's definition.
524     fn symbol_is_live(&mut self, id: hir::HirId) -> bool {
525         if self.live_symbols.contains(&id) {
526             return true;
527         }
528         // If it's a type whose items are live, then it's live, too.
529         // This is done to handle the case where, for example, the static
530         // method of a private type is used, but the type itself is never
531         // called directly.
532         let def_id = self.tcx.hir().local_def_id(id);
533         let inherent_impls = self.tcx.inherent_impls(def_id);
534         for &impl_did in inherent_impls.iter() {
535             for &item_did in &self.tcx.associated_item_def_ids(impl_did)[..] {
536                 if let Some(item_hir_id) = self.tcx.hir().as_local_hir_id(item_did) {
537                     if self.live_symbols.contains(&item_hir_id) {
538                         return true;
539                     }
540                 }
541             }
542         }
543         false
544     }
545
546     fn warn_dead_code(
547         &mut self,
548         id: hir::HirId,
549         span: rustc_span::Span,
550         name: ast::Name,
551         node_type: &str,
552         participle: &str,
553     ) {
554         if !name.as_str().starts_with("_") {
555             self.tcx.lint_hir(
556                 lint::builtin::DEAD_CODE,
557                 id,
558                 span,
559                 &format!("{} is never {}: `{}`", node_type, participle, name),
560             );
561         }
562     }
563 }
564
565 impl Visitor<'tcx> for DeadVisitor<'tcx> {
566     /// Walk nested items in place so that we don't report dead-code
567     /// on inner functions when the outer function is already getting
568     /// an error. We could do this also by checking the parents, but
569     /// this is how the code is setup and it seems harmless enough.
570     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
571         NestedVisitorMap::All(&self.tcx.hir())
572     }
573
574     fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
575         if self.should_warn_about_item(item) {
576             // For most items, we want to highlight its identifier
577             let span = match item.kind {
578                 hir::ItemKind::Fn(..)
579                 | hir::ItemKind::Mod(..)
580                 | hir::ItemKind::Enum(..)
581                 | hir::ItemKind::Struct(..)
582                 | hir::ItemKind::Union(..)
583                 | hir::ItemKind::Trait(..)
584                 | hir::ItemKind::Impl(..) => {
585                     // FIXME(66095): Because item.span is annotated with things
586                     // like expansion data, and ident.span isn't, we use the
587                     // def_span method if it's part of a macro invocation
588                     // (and thus has asource_callee set).
589                     // We should probably annotate ident.span with the macro
590                     // context, but that's a larger change.
591                     if item.span.source_callee().is_some() {
592                         self.tcx.sess.source_map().def_span(item.span)
593                     } else {
594                         item.ident.span
595                     }
596                 }
597                 _ => item.span,
598             };
599             let participle = match item.kind {
600                 hir::ItemKind::Struct(..) => "constructed", // Issue #52325
601                 _ => "used",
602             };
603             self.warn_dead_code(
604                 item.hir_id,
605                 span,
606                 item.ident.name,
607                 item.kind.descriptive_variant(),
608                 participle,
609             );
610         } else {
611             // Only continue if we didn't warn
612             intravisit::walk_item(self, item);
613         }
614     }
615
616     fn visit_variant(
617         &mut self,
618         variant: &'tcx hir::Variant<'tcx>,
619         g: &'tcx hir::Generics<'tcx>,
620         id: hir::HirId,
621     ) {
622         if self.should_warn_about_variant(&variant) {
623             self.warn_dead_code(
624                 variant.id,
625                 variant.span,
626                 variant.ident.name,
627                 "variant",
628                 "constructed",
629             );
630         } else {
631             intravisit::walk_variant(self, variant, g, id);
632         }
633     }
634
635     fn visit_foreign_item(&mut self, fi: &'tcx hir::ForeignItem<'tcx>) {
636         if self.should_warn_about_foreign_item(fi) {
637             self.warn_dead_code(
638                 fi.hir_id,
639                 fi.span,
640                 fi.ident.name,
641                 fi.kind.descriptive_variant(),
642                 "used",
643             );
644         }
645         intravisit::walk_foreign_item(self, fi);
646     }
647
648     fn visit_struct_field(&mut self, field: &'tcx hir::StructField<'tcx>) {
649         if self.should_warn_about_field(&field) {
650             self.warn_dead_code(field.hir_id, field.span, field.ident.name, "field", "read");
651         }
652         intravisit::walk_struct_field(self, field);
653     }
654
655     fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
656         match impl_item.kind {
657             hir::ImplItemKind::Const(_, body_id) => {
658                 if !self.symbol_is_live(impl_item.hir_id) {
659                     self.warn_dead_code(
660                         impl_item.hir_id,
661                         impl_item.span,
662                         impl_item.ident.name,
663                         "associated const",
664                         "used",
665                     );
666                 }
667                 self.visit_nested_body(body_id)
668             }
669             hir::ImplItemKind::Method(_, body_id) => {
670                 if !self.symbol_is_live(impl_item.hir_id) {
671                     let span = self.tcx.sess.source_map().def_span(impl_item.span);
672                     self.warn_dead_code(
673                         impl_item.hir_id,
674                         span,
675                         impl_item.ident.name,
676                         "method",
677                         "used",
678                     );
679                 }
680                 self.visit_nested_body(body_id)
681             }
682             hir::ImplItemKind::OpaqueTy(..) | hir::ImplItemKind::TyAlias(..) => {}
683         }
684     }
685
686     // Overwrite so that we don't warn the trait item itself.
687     fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) {
688         match trait_item.kind {
689             hir::TraitItemKind::Const(_, Some(body_id))
690             | hir::TraitItemKind::Method(_, hir::TraitMethod::Provided(body_id)) => {
691                 self.visit_nested_body(body_id)
692             }
693             hir::TraitItemKind::Const(_, None)
694             | hir::TraitItemKind::Method(_, hir::TraitMethod::Required(_))
695             | hir::TraitItemKind::Type(..) => {}
696         }
697     }
698 }
699
700 pub fn check_crate(tcx: TyCtxt<'_>) {
701     let access_levels = &tcx.privacy_access_levels(LOCAL_CRATE);
702     let krate = tcx.hir().krate();
703     let live_symbols = find_live(tcx, access_levels, krate);
704     let mut visitor = DeadVisitor { tcx, live_symbols };
705     intravisit::walk_crate(&mut visitor, krate);
706 }