]> git.lizzy.rs Git - rust.git/blob - src/librustc_lint/builtin.rs
Rollup merge of #48570 - Amanieu:aarch64_features, r=alexcrichton
[rust.git] / src / librustc_lint / builtin.rs
1 // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Lints in the Rust compiler.
12 //!
13 //! This contains lints which can feasibly be implemented as their own
14 //! AST visitor. Also see `rustc::lint::builtin`, which contains the
15 //! definitions of lints that are emitted directly inside the main
16 //! compiler.
17 //!
18 //! To add a new lint to rustc, declare it here using `declare_lint!()`.
19 //! Then add code to emit the new lint in the appropriate circumstances.
20 //! You can do that in an existing `LintPass` if it makes sense, or in a
21 //! new `LintPass`, or using `Session::add_lint` elsewhere in the
22 //! compiler. Only do the latter if the check can't be written cleanly as a
23 //! `LintPass` (also, note that such lints will need to be defined in
24 //! `rustc::lint::builtin`, not here).
25 //!
26 //! If you define a new `LintPass`, you will also need to add it to the
27 //! `add_builtin!` or `add_builtin_with_new!` invocation in `lib.rs`.
28 //! Use the former for unit-like structs and the latter for structs with
29 //! a `pub fn new()`.
30
31 use rustc::hir::def::Def;
32 use rustc::hir::def_id::DefId;
33 use rustc::cfg;
34 use rustc::ty::subst::Substs;
35 use rustc::ty::{self, Ty};
36 use rustc::traits::{self, Reveal};
37 use rustc::hir::map as hir_map;
38 use util::nodemap::NodeSet;
39 use lint::{LateContext, LintContext, LintArray};
40 use lint::{LintPass, LateLintPass, EarlyLintPass, EarlyContext};
41
42 use std::collections::HashSet;
43
44 use syntax::ast;
45 use syntax::attr;
46 use syntax::feature_gate::{AttributeGate, AttributeType, Stability, deprecated_attributes};
47 use syntax_pos::{BytePos, Span, SyntaxContext};
48 use syntax::symbol::keywords;
49
50 use rustc::hir::{self, PatKind};
51 use rustc::hir::intravisit::FnKind;
52
53 use bad_style::{MethodLateContext, method_context};
54
55 // hardwired lints from librustc
56 pub use lint::builtin::*;
57
58 declare_lint! {
59     WHILE_TRUE,
60     Warn,
61     "suggest using `loop { }` instead of `while true { }`"
62 }
63
64 #[derive(Copy, Clone)]
65 pub struct WhileTrue;
66
67 impl LintPass for WhileTrue {
68     fn get_lints(&self) -> LintArray {
69         lint_array!(WHILE_TRUE)
70     }
71 }
72
73 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for WhileTrue {
74     fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) {
75         if let hir::ExprWhile(ref cond, ..) = e.node {
76             if let hir::ExprLit(ref lit) = cond.node {
77                 if let ast::LitKind::Bool(true) = lit.node {
78                     if lit.span.ctxt() == SyntaxContext::empty() {
79                         let msg = "denote infinite loops with `loop { ... }`";
80                         let condition_span = cx.tcx.sess.codemap().def_span(e.span);
81                         let mut err = cx.struct_span_lint(WHILE_TRUE, condition_span, msg);
82                         err.span_suggestion_short(condition_span, "use `loop`", "loop".to_owned());
83                         err.emit();
84                     }
85                 }
86             }
87         }
88     }
89 }
90
91 declare_lint! {
92     BOX_POINTERS,
93     Allow,
94     "use of owned (Box type) heap memory"
95 }
96
97 #[derive(Copy, Clone)]
98 pub struct BoxPointers;
99
100 impl BoxPointers {
101     fn check_heap_type<'a, 'tcx>(&self, cx: &LateContext, span: Span, ty: Ty) {
102         for leaf_ty in ty.walk() {
103             if leaf_ty.is_box() {
104                 let m = format!("type uses owned (Box type) pointers: {}", ty);
105                 cx.span_lint(BOX_POINTERS, span, &m);
106             }
107         }
108     }
109 }
110
111 impl LintPass for BoxPointers {
112     fn get_lints(&self) -> LintArray {
113         lint_array!(BOX_POINTERS)
114     }
115 }
116
117 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for BoxPointers {
118     fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
119         match it.node {
120             hir::ItemFn(..) |
121             hir::ItemTy(..) |
122             hir::ItemEnum(..) |
123             hir::ItemStruct(..) |
124             hir::ItemUnion(..) => {
125                 let def_id = cx.tcx.hir.local_def_id(it.id);
126                 self.check_heap_type(cx, it.span, cx.tcx.type_of(def_id))
127             }
128             _ => ()
129         }
130
131         // If it's a struct, we also have to check the fields' types
132         match it.node {
133             hir::ItemStruct(ref struct_def, _) |
134             hir::ItemUnion(ref struct_def, _) => {
135                 for struct_field in struct_def.fields() {
136                     let def_id = cx.tcx.hir.local_def_id(struct_field.id);
137                     self.check_heap_type(cx, struct_field.span,
138                                          cx.tcx.type_of(def_id));
139                 }
140             }
141             _ => (),
142         }
143     }
144
145     fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) {
146         let ty = cx.tables.node_id_to_type(e.hir_id);
147         self.check_heap_type(cx, e.span, ty);
148     }
149 }
150
151 declare_lint! {
152     NON_SHORTHAND_FIELD_PATTERNS,
153     Warn,
154     "using `Struct { x: x }` instead of `Struct { x }` in a pattern"
155 }
156
157 #[derive(Copy, Clone)]
158 pub struct NonShorthandFieldPatterns;
159
160 impl LintPass for NonShorthandFieldPatterns {
161     fn get_lints(&self) -> LintArray {
162         lint_array!(NON_SHORTHAND_FIELD_PATTERNS)
163     }
164 }
165
166 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonShorthandFieldPatterns {
167     fn check_pat(&mut self, cx: &LateContext, pat: &hir::Pat) {
168         if let PatKind::Struct(_, ref field_pats, _) = pat.node {
169             for fieldpat in field_pats {
170                 if fieldpat.node.is_shorthand {
171                     continue;
172                 }
173                 if let PatKind::Binding(_, _, ident, None) = fieldpat.node.pat.node {
174                     if ident.node == fieldpat.node.name {
175                         let mut err = cx.struct_span_lint(NON_SHORTHAND_FIELD_PATTERNS,
176                                      fieldpat.span,
177                                      &format!("the `{}:` in this pattern is redundant",
178                                               ident.node));
179                         let subspan = cx.tcx.sess.codemap().span_through_char(fieldpat.span, ':');
180                         err.span_suggestion_short(subspan,
181                                                   "remove this",
182                                                   format!("{}", ident.node));
183                         err.emit();
184                     }
185                 }
186             }
187         }
188     }
189 }
190
191 declare_lint! {
192     UNSAFE_CODE,
193     Allow,
194     "usage of `unsafe` code"
195 }
196
197 #[derive(Copy, Clone)]
198 pub struct UnsafeCode;
199
200 impl LintPass for UnsafeCode {
201     fn get_lints(&self) -> LintArray {
202         lint_array!(UNSAFE_CODE)
203     }
204 }
205
206 impl UnsafeCode {
207     fn report_unsafe(&self, cx: &LateContext, span: Span, desc: &'static str) {
208         // This comes from a macro that has #[allow_internal_unsafe].
209         if span.allows_unsafe() {
210             return;
211         }
212
213         cx.span_lint(UNSAFE_CODE, span, desc);
214     }
215 }
216
217 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnsafeCode {
218     fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) {
219         if let hir::ExprBlock(ref blk) = e.node {
220             // Don't warn about generated blocks, that'll just pollute the output.
221             if blk.rules == hir::UnsafeBlock(hir::UserProvided) {
222                 self.report_unsafe(cx, blk.span, "usage of an `unsafe` block");
223             }
224         }
225     }
226
227     fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
228         match it.node {
229             hir::ItemTrait(_, hir::Unsafety::Unsafe, ..) => {
230                 self.report_unsafe(cx, it.span, "declaration of an `unsafe` trait")
231             }
232
233             hir::ItemImpl(hir::Unsafety::Unsafe, ..) => {
234                 self.report_unsafe(cx, it.span, "implementation of an `unsafe` trait")
235             }
236
237             _ => return,
238         }
239     }
240
241     fn check_fn(&mut self,
242                 cx: &LateContext,
243                 fk: FnKind<'tcx>,
244                 _: &hir::FnDecl,
245                 _: &hir::Body,
246                 span: Span,
247                 _: ast::NodeId) {
248         match fk {
249             FnKind::ItemFn(_, _, hir::Unsafety::Unsafe, ..) => {
250                 self.report_unsafe(cx, span, "declaration of an `unsafe` function")
251             }
252
253             FnKind::Method(_, sig, ..) => {
254                 if sig.unsafety == hir::Unsafety::Unsafe {
255                     self.report_unsafe(cx, span, "implementation of an `unsafe` method")
256                 }
257             }
258
259             _ => (),
260         }
261     }
262
263     fn check_trait_item(&mut self, cx: &LateContext, item: &hir::TraitItem) {
264         if let hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Required(_)) = item.node {
265             if sig.unsafety == hir::Unsafety::Unsafe {
266                 self.report_unsafe(cx, item.span, "declaration of an `unsafe` method")
267             }
268         }
269     }
270 }
271
272 declare_lint! {
273     MISSING_DOCS,
274     Allow,
275     "detects missing documentation for public members"
276 }
277
278 pub struct MissingDoc {
279     /// Stack of whether #[doc(hidden)] is set
280     /// at each level which has lint attributes.
281     doc_hidden_stack: Vec<bool>,
282
283     /// Private traits or trait items that leaked through. Don't check their methods.
284     private_traits: HashSet<ast::NodeId>,
285 }
286
287 impl MissingDoc {
288     pub fn new() -> MissingDoc {
289         MissingDoc {
290             doc_hidden_stack: vec![false],
291             private_traits: HashSet::new(),
292         }
293     }
294
295     fn doc_hidden(&self) -> bool {
296         *self.doc_hidden_stack.last().expect("empty doc_hidden_stack")
297     }
298
299     fn check_missing_docs_attrs(&self,
300                                 cx: &LateContext,
301                                 id: Option<ast::NodeId>,
302                                 attrs: &[ast::Attribute],
303                                 sp: Span,
304                                 desc: &'static str) {
305         // If we're building a test harness, then warning about
306         // documentation is probably not really relevant right now.
307         if cx.sess().opts.test {
308             return;
309         }
310
311         // `#[doc(hidden)]` disables missing_docs check.
312         if self.doc_hidden() {
313             return;
314         }
315
316         // Only check publicly-visible items, using the result from the privacy pass.
317         // It's an option so the crate root can also use this function (it doesn't
318         // have a NodeId).
319         if let Some(id) = id {
320             if !cx.access_levels.is_exported(id) {
321                 return;
322             }
323         }
324
325         fn has_doc(attr: &ast::Attribute) -> bool {
326             if !attr.check_name("doc") {
327                 return false;
328             }
329
330             if attr.is_value_str() {
331                 return true;
332             }
333
334             if let Some(list) = attr.meta_item_list() {
335                 for meta in list {
336                     if meta.check_name("include") {
337                         return true;
338                     }
339                 }
340             }
341
342             false
343         }
344
345         let has_doc = attrs.iter().any(|a| has_doc(a));
346         if !has_doc {
347             cx.span_lint(MISSING_DOCS,
348                          cx.tcx.sess.codemap().def_span(sp),
349                          &format!("missing documentation for {}", desc));
350         }
351     }
352 }
353
354 impl LintPass for MissingDoc {
355     fn get_lints(&self) -> LintArray {
356         lint_array!(MISSING_DOCS)
357     }
358 }
359
360 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingDoc {
361     fn enter_lint_attrs(&mut self, _: &LateContext, attrs: &[ast::Attribute]) {
362         let doc_hidden = self.doc_hidden() ||
363                          attrs.iter().any(|attr| {
364             attr.check_name("doc") &&
365             match attr.meta_item_list() {
366                 None => false,
367                 Some(l) => attr::list_contains_name(&l, "hidden"),
368             }
369         });
370         self.doc_hidden_stack.push(doc_hidden);
371     }
372
373     fn exit_lint_attrs(&mut self, _: &LateContext, _attrs: &[ast::Attribute]) {
374         self.doc_hidden_stack.pop().expect("empty doc_hidden_stack");
375     }
376
377     fn check_crate(&mut self, cx: &LateContext, krate: &hir::Crate) {
378         self.check_missing_docs_attrs(cx, None, &krate.attrs, krate.span, "crate");
379     }
380
381     fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
382         let desc = match it.node {
383             hir::ItemFn(..) => "a function",
384             hir::ItemMod(..) => "a module",
385             hir::ItemEnum(..) => "an enum",
386             hir::ItemStruct(..) => "a struct",
387             hir::ItemUnion(..) => "a union",
388             hir::ItemTrait(.., ref trait_item_refs) => {
389                 // Issue #11592, traits are always considered exported, even when private.
390                 if it.vis == hir::Visibility::Inherited {
391                     self.private_traits.insert(it.id);
392                     for trait_item_ref in trait_item_refs {
393                         self.private_traits.insert(trait_item_ref.id.node_id);
394                     }
395                     return;
396                 }
397                 "a trait"
398             }
399             hir::ItemTy(..) => "a type alias",
400             hir::ItemImpl(.., Some(ref trait_ref), _, ref impl_item_refs) => {
401                 // If the trait is private, add the impl items to private_traits so they don't get
402                 // reported for missing docs.
403                 let real_trait = trait_ref.path.def.def_id();
404                 if let Some(node_id) = cx.tcx.hir.as_local_node_id(real_trait) {
405                     match cx.tcx.hir.find(node_id) {
406                         Some(hir_map::NodeItem(item)) => {
407                             if item.vis == hir::Visibility::Inherited {
408                                 for impl_item_ref in impl_item_refs {
409                                     self.private_traits.insert(impl_item_ref.id.node_id);
410                                 }
411                             }
412                         }
413                         _ => {}
414                     }
415                 }
416                 return;
417             }
418             hir::ItemConst(..) => "a constant",
419             hir::ItemStatic(..) => "a static",
420             _ => return,
421         };
422
423         self.check_missing_docs_attrs(cx, Some(it.id), &it.attrs, it.span, desc);
424     }
425
426     fn check_trait_item(&mut self, cx: &LateContext, trait_item: &hir::TraitItem) {
427         if self.private_traits.contains(&trait_item.id) {
428             return;
429         }
430
431         let desc = match trait_item.node {
432             hir::TraitItemKind::Const(..) => "an associated constant",
433             hir::TraitItemKind::Method(..) => "a trait method",
434             hir::TraitItemKind::Type(..) => "an associated type",
435         };
436
437         self.check_missing_docs_attrs(cx,
438                                       Some(trait_item.id),
439                                       &trait_item.attrs,
440                                       trait_item.span,
441                                       desc);
442     }
443
444     fn check_impl_item(&mut self, cx: &LateContext, impl_item: &hir::ImplItem) {
445         // If the method is an impl for a trait, don't doc.
446         if method_context(cx, impl_item.id) == MethodLateContext::TraitImpl {
447             return;
448         }
449
450         let desc = match impl_item.node {
451             hir::ImplItemKind::Const(..) => "an associated constant",
452             hir::ImplItemKind::Method(..) => "a method",
453             hir::ImplItemKind::Type(_) => "an associated type",
454         };
455         self.check_missing_docs_attrs(cx,
456                                       Some(impl_item.id),
457                                       &impl_item.attrs,
458                                       impl_item.span,
459                                       desc);
460     }
461
462     fn check_struct_field(&mut self, cx: &LateContext, sf: &hir::StructField) {
463         if !sf.is_positional() {
464             self.check_missing_docs_attrs(cx,
465                                           Some(sf.id),
466                                           &sf.attrs,
467                                           sf.span,
468                                           "a struct field")
469         }
470     }
471
472     fn check_variant(&mut self, cx: &LateContext, v: &hir::Variant, _: &hir::Generics) {
473         self.check_missing_docs_attrs(cx,
474                                       Some(v.node.data.id()),
475                                       &v.node.attrs,
476                                       v.span,
477                                       "a variant");
478     }
479 }
480
481 declare_lint! {
482     pub MISSING_COPY_IMPLEMENTATIONS,
483     Allow,
484     "detects potentially-forgotten implementations of `Copy`"
485 }
486
487 #[derive(Copy, Clone)]
488 pub struct MissingCopyImplementations;
489
490 impl LintPass for MissingCopyImplementations {
491     fn get_lints(&self) -> LintArray {
492         lint_array!(MISSING_COPY_IMPLEMENTATIONS)
493     }
494 }
495
496 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingCopyImplementations {
497     fn check_item(&mut self, cx: &LateContext, item: &hir::Item) {
498         if !cx.access_levels.is_reachable(item.id) {
499             return;
500         }
501         let (def, ty) = match item.node {
502             hir::ItemStruct(_, ref ast_generics) => {
503                 if !ast_generics.params.is_empty() {
504                     return;
505                 }
506                 let def = cx.tcx.adt_def(cx.tcx.hir.local_def_id(item.id));
507                 (def, cx.tcx.mk_adt(def, cx.tcx.intern_substs(&[])))
508             }
509             hir::ItemUnion(_, ref ast_generics) => {
510                 if !ast_generics.params.is_empty() {
511                     return;
512                 }
513                 let def = cx.tcx.adt_def(cx.tcx.hir.local_def_id(item.id));
514                 (def, cx.tcx.mk_adt(def, cx.tcx.intern_substs(&[])))
515             }
516             hir::ItemEnum(_, ref ast_generics) => {
517                 if !ast_generics.params.is_empty() {
518                     return;
519                 }
520                 let def = cx.tcx.adt_def(cx.tcx.hir.local_def_id(item.id));
521                 (def, cx.tcx.mk_adt(def, cx.tcx.intern_substs(&[])))
522             }
523             _ => return,
524         };
525         if def.has_dtor(cx.tcx) {
526             return;
527         }
528         let param_env = ty::ParamEnv::empty(Reveal::UserFacing);
529         if !ty.moves_by_default(cx.tcx, param_env, item.span) {
530             return;
531         }
532         if param_env.can_type_implement_copy(cx.tcx, ty, item.span).is_ok() {
533             cx.span_lint(MISSING_COPY_IMPLEMENTATIONS,
534                          item.span,
535                          "type could implement `Copy`; consider adding `impl \
536                           Copy`")
537         }
538     }
539 }
540
541 declare_lint! {
542     MISSING_DEBUG_IMPLEMENTATIONS,
543     Allow,
544     "detects missing implementations of fmt::Debug"
545 }
546
547 pub struct MissingDebugImplementations {
548     impling_types: Option<NodeSet>,
549 }
550
551 impl MissingDebugImplementations {
552     pub fn new() -> MissingDebugImplementations {
553         MissingDebugImplementations { impling_types: None }
554     }
555 }
556
557 impl LintPass for MissingDebugImplementations {
558     fn get_lints(&self) -> LintArray {
559         lint_array!(MISSING_DEBUG_IMPLEMENTATIONS)
560     }
561 }
562
563 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingDebugImplementations {
564     fn check_item(&mut self, cx: &LateContext, item: &hir::Item) {
565         if !cx.access_levels.is_reachable(item.id) {
566             return;
567         }
568
569         match item.node {
570             hir::ItemStruct(..) |
571             hir::ItemUnion(..) |
572             hir::ItemEnum(..) => {}
573             _ => return,
574         }
575
576         let debug = match cx.tcx.lang_items().debug_trait() {
577             Some(debug) => debug,
578             None => return,
579         };
580
581         if self.impling_types.is_none() {
582             let mut impls = NodeSet();
583             cx.tcx.for_each_impl(debug, |d| {
584                 if let Some(ty_def) = cx.tcx.type_of(d).ty_to_def_id() {
585                     if let Some(node_id) = cx.tcx.hir.as_local_node_id(ty_def) {
586                         impls.insert(node_id);
587                     }
588                 }
589             });
590
591             self.impling_types = Some(impls);
592             debug!("{:?}", self.impling_types);
593         }
594
595         if !self.impling_types.as_ref().unwrap().contains(&item.id) {
596             cx.span_lint(MISSING_DEBUG_IMPLEMENTATIONS,
597                          item.span,
598                          "type does not implement `fmt::Debug`; consider adding #[derive(Debug)] \
599                           or a manual implementation")
600         }
601     }
602 }
603
604 declare_lint! {
605     pub ANONYMOUS_PARAMETERS,
606     Allow,
607     "detects anonymous parameters"
608 }
609
610 /// Checks for use of anonymous parameters (RFC 1685)
611 #[derive(Clone)]
612 pub struct AnonymousParameters;
613
614 impl LintPass for AnonymousParameters {
615     fn get_lints(&self) -> LintArray {
616         lint_array!(ANONYMOUS_PARAMETERS)
617     }
618 }
619
620 impl EarlyLintPass for AnonymousParameters {
621     fn check_trait_item(&mut self, cx: &EarlyContext, it: &ast::TraitItem) {
622         match it.node {
623             ast::TraitItemKind::Method(ref sig, _) => {
624                 for arg in sig.decl.inputs.iter() {
625                     match arg.pat.node {
626                         ast::PatKind::Ident(_, ident, None) => {
627                             if ident.node.name == keywords::Invalid.name() {
628                                 cx.span_lint(ANONYMOUS_PARAMETERS,
629                                              arg.pat.span,
630                                              "use of deprecated anonymous parameter");
631                             }
632                         }
633                         _ => (),
634                     }
635                 }
636             },
637             _ => (),
638         }
639     }
640 }
641
642 /// Checks for use of attributes which have been deprecated.
643 #[derive(Clone)]
644 pub struct DeprecatedAttr {
645     // This is not free to compute, so we want to keep it around, rather than
646     // compute it for every attribute.
647     depr_attrs: Vec<&'static (&'static str, AttributeType, AttributeGate)>,
648 }
649
650 impl DeprecatedAttr {
651     pub fn new() -> DeprecatedAttr {
652         DeprecatedAttr {
653             depr_attrs: deprecated_attributes(),
654         }
655     }
656 }
657
658 impl LintPass for DeprecatedAttr {
659     fn get_lints(&self) -> LintArray {
660         lint_array!()
661     }
662 }
663
664 impl EarlyLintPass for DeprecatedAttr {
665     fn check_attribute(&mut self, cx: &EarlyContext, attr: &ast::Attribute) {
666         let name = unwrap_or!(attr.name(), return);
667         for &&(n, _, ref g) in &self.depr_attrs {
668             if name == n {
669                 if let &AttributeGate::Gated(Stability::Deprecated(link),
670                                              ref name,
671                                              ref reason,
672                                              _) = g {
673                     let msg = format!("use of deprecated attribute `{}`: {}. See {}",
674                                       name, reason, link);
675                     let mut err = cx.struct_span_lint(DEPRECATED, attr.span, &msg);
676                     err.span_suggestion_short(attr.span, "remove this attribute", "".to_owned());
677                     err.emit();
678                 }
679                 return;
680             }
681         }
682     }
683 }
684
685 declare_lint! {
686     pub ILLEGAL_FLOATING_POINT_LITERAL_PATTERN,
687     Warn,
688     "floating-point literals cannot be used in patterns"
689 }
690
691 /// Checks for floating point literals in patterns.
692 #[derive(Clone)]
693 pub struct IllegalFloatLiteralPattern;
694
695 impl LintPass for IllegalFloatLiteralPattern {
696     fn get_lints(&self) -> LintArray {
697         lint_array!(ILLEGAL_FLOATING_POINT_LITERAL_PATTERN)
698     }
699 }
700
701 fn fl_lit_check_expr(cx: &EarlyContext, expr: &ast::Expr) {
702     use self::ast::{ExprKind, LitKind};
703     match expr.node {
704         ExprKind::Lit(ref l) => {
705             match l.node {
706                 LitKind::FloatUnsuffixed(..) |
707                 LitKind::Float(..) => {
708                     cx.span_lint(ILLEGAL_FLOATING_POINT_LITERAL_PATTERN,
709                                  l.span,
710                                  "floating-point literals cannot be used in patterns");
711                     },
712                 _ => (),
713             }
714         }
715         // These may occur in patterns
716         // and can maybe contain float literals
717         ExprKind::Unary(_, ref f) => fl_lit_check_expr(cx, f),
718         // Other kinds of exprs can't occur in patterns so we don't have to check them
719         // (ast_validation will emit an error if they occur)
720         _ => (),
721     }
722 }
723
724 impl EarlyLintPass for IllegalFloatLiteralPattern {
725     fn check_pat(&mut self, cx: &EarlyContext, pat: &ast::Pat) {
726         use self::ast::PatKind;
727         pat.walk(&mut |p| {
728             match p.node {
729                 // Wildcard patterns and paths are uninteresting for the lint
730                 PatKind::Wild |
731                 PatKind::Path(..) => (),
732
733                 // The walk logic recurses inside these
734                 PatKind::Ident(..) |
735                 PatKind::Struct(..) |
736                 PatKind::Tuple(..) |
737                 PatKind::TupleStruct(..) |
738                 PatKind::Ref(..) |
739                 PatKind::Box(..) |
740                 PatKind::Paren(..) |
741                 PatKind::Slice(..) => (),
742
743                 // Extract the expressions and check them
744                 PatKind::Lit(ref e) => fl_lit_check_expr(cx, e),
745                 PatKind::Range(ref st, ref en, _) => {
746                     fl_lit_check_expr(cx, st);
747                     fl_lit_check_expr(cx, en);
748                 },
749
750                 PatKind::Mac(_) => bug!("lint must run post-expansion"),
751             }
752             true
753         });
754     }
755 }
756
757 declare_lint! {
758     pub UNUSED_DOC_COMMENT,
759     Warn,
760     "detects doc comments that aren't used by rustdoc"
761 }
762
763 #[derive(Copy, Clone)]
764 pub struct UnusedDocComment;
765
766 impl LintPass for UnusedDocComment {
767     fn get_lints(&self) -> LintArray {
768         lint_array![UNUSED_DOC_COMMENT]
769     }
770 }
771
772 impl UnusedDocComment {
773     fn warn_if_doc<'a, 'tcx,
774                    I: Iterator<Item=&'a ast::Attribute>,
775                    C: LintContext<'tcx>>(&self, mut attrs: I, cx: &C) {
776         if let Some(attr) = attrs.find(|a| a.is_value_str() && a.check_name("doc")) {
777             cx.struct_span_lint(UNUSED_DOC_COMMENT, attr.span, "doc comment not used by rustdoc")
778               .emit();
779         }
780     }
781 }
782
783 impl EarlyLintPass for UnusedDocComment {
784     fn check_local(&mut self, cx: &EarlyContext, decl: &ast::Local) {
785         self.warn_if_doc(decl.attrs.iter(), cx);
786     }
787
788     fn check_arm(&mut self, cx: &EarlyContext, arm: &ast::Arm) {
789         self.warn_if_doc(arm.attrs.iter(), cx);
790     }
791
792     fn check_expr(&mut self, cx: &EarlyContext, expr: &ast::Expr) {
793         self.warn_if_doc(expr.attrs.iter(), cx);
794     }
795 }
796
797 declare_lint! {
798     pub UNCONDITIONAL_RECURSION,
799     Warn,
800     "functions that cannot return without calling themselves"
801 }
802
803 #[derive(Copy, Clone)]
804 pub struct UnconditionalRecursion;
805
806
807 impl LintPass for UnconditionalRecursion {
808     fn get_lints(&self) -> LintArray {
809         lint_array![UNCONDITIONAL_RECURSION]
810     }
811 }
812
813 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnconditionalRecursion {
814     fn check_fn(&mut self,
815                 cx: &LateContext,
816                 fn_kind: FnKind,
817                 _: &hir::FnDecl,
818                 body: &hir::Body,
819                 sp: Span,
820                 id: ast::NodeId) {
821         let method = match fn_kind {
822             FnKind::ItemFn(..) => None,
823             FnKind::Method(..) => {
824                 Some(cx.tcx.associated_item(cx.tcx.hir.local_def_id(id)))
825             }
826             // closures can't recur, so they don't matter.
827             FnKind::Closure(_) => return,
828         };
829
830         // Walk through this function (say `f`) looking to see if
831         // every possible path references itself, i.e. the function is
832         // called recursively unconditionally. This is done by trying
833         // to find a path from the entry node to the exit node that
834         // *doesn't* call `f` by traversing from the entry while
835         // pretending that calls of `f` are sinks (i.e. ignoring any
836         // exit edges from them).
837         //
838         // NB. this has an edge case with non-returning statements,
839         // like `loop {}` or `panic!()`: control flow never reaches
840         // the exit node through these, so one can have a function
841         // that never actually calls itselfs but is still picked up by
842         // this lint:
843         //
844         //     fn f(cond: bool) {
845         //         if !cond { panic!() } // could come from `assert!(cond)`
846         //         f(false)
847         //     }
848         //
849         // In general, functions of that form may be able to call
850         // itself a finite number of times and then diverge. The lint
851         // considers this to be an error for two reasons, (a) it is
852         // easier to implement, and (b) it seems rare to actually want
853         // to have behaviour like the above, rather than
854         // e.g. accidentally recurring after an assert.
855
856         let cfg = cfg::CFG::new(cx.tcx, &body);
857
858         let mut work_queue = vec![cfg.entry];
859         let mut reached_exit_without_self_call = false;
860         let mut self_call_spans = vec![];
861         let mut visited = HashSet::new();
862
863         while let Some(idx) = work_queue.pop() {
864             if idx == cfg.exit {
865                 // found a path!
866                 reached_exit_without_self_call = true;
867                 break;
868             }
869
870             let cfg_id = idx.node_id();
871             if visited.contains(&cfg_id) {
872                 // already done
873                 continue;
874             }
875             visited.insert(cfg_id);
876
877             // is this a recursive call?
878             let local_id = cfg.graph.node_data(idx).id();
879             if local_id != hir::DUMMY_ITEM_LOCAL_ID {
880                 let node_id = cx.tcx.hir.hir_to_node_id(hir::HirId {
881                     owner: body.value.hir_id.owner,
882                     local_id
883                 });
884                 let self_recursive = match method {
885                     Some(ref method) => expr_refers_to_this_method(cx, method, node_id),
886                     None => expr_refers_to_this_fn(cx, id, node_id),
887                 };
888                 if self_recursive {
889                     self_call_spans.push(cx.tcx.hir.span(node_id));
890                     // this is a self call, so we shouldn't explore past
891                     // this node in the CFG.
892                     continue;
893                 }
894             }
895
896             // add the successors of this node to explore the graph further.
897             for (_, edge) in cfg.graph.outgoing_edges(idx) {
898                 let target_idx = edge.target();
899                 let target_cfg_id = target_idx.node_id();
900                 if !visited.contains(&target_cfg_id) {
901                     work_queue.push(target_idx)
902                 }
903             }
904         }
905
906         // Check the number of self calls because a function that
907         // doesn't return (e.g. calls a `-> !` function or `loop { /*
908         // no break */ }`) shouldn't be linted unless it actually
909         // recurs.
910         if !reached_exit_without_self_call && !self_call_spans.is_empty() {
911             let sp = cx.tcx.sess.codemap().def_span(sp);
912             let mut db = cx.struct_span_lint(UNCONDITIONAL_RECURSION,
913                                              sp,
914                                              "function cannot return without recurring");
915             db.span_label(sp, "cannot return without recurring");
916             // offer some help to the programmer.
917             for call in &self_call_spans {
918                 db.span_label(*call, "recursive call site");
919             }
920             db.help("a `loop` may express intention better if this is on purpose");
921             db.emit();
922         }
923
924         // all done
925         return;
926
927         // Functions for identifying if the given Expr NodeId `id`
928         // represents a call to the function `fn_id`/method `method`.
929
930         fn expr_refers_to_this_fn(cx: &LateContext, fn_id: ast::NodeId, id: ast::NodeId) -> bool {
931             match cx.tcx.hir.get(id) {
932                 hir_map::NodeExpr(&hir::Expr { node: hir::ExprCall(ref callee, _), .. }) => {
933                     let def = if let hir::ExprPath(ref qpath) = callee.node {
934                         cx.tables.qpath_def(qpath, callee.hir_id)
935                     } else {
936                         return false;
937                     };
938                     match def {
939                         Def::Local(..) | Def::Upvar(..) => false,
940                         _ => def.def_id() == cx.tcx.hir.local_def_id(fn_id)
941                     }
942                 }
943                 _ => false,
944             }
945         }
946
947         // Check if the expression `id` performs a call to `method`.
948         fn expr_refers_to_this_method(cx: &LateContext,
949                                       method: &ty::AssociatedItem,
950                                       id: ast::NodeId)
951                                       -> bool {
952             use rustc::ty::adjustment::*;
953
954             // Ignore non-expressions.
955             let expr = if let hir_map::NodeExpr(e) = cx.tcx.hir.get(id) {
956                 e
957             } else {
958                 return false;
959             };
960
961             // Check for overloaded autoderef method calls.
962             let mut source = cx.tables.expr_ty(expr);
963             for adjustment in cx.tables.expr_adjustments(expr) {
964                 if let Adjust::Deref(Some(deref)) = adjustment.kind {
965                     let (def_id, substs) = deref.method_call(cx.tcx, source);
966                     if method_call_refers_to_method(cx, method, def_id, substs, id) {
967                         return true;
968                     }
969                 }
970                 source = adjustment.target;
971             }
972
973             // Check for method calls and overloaded operators.
974             if cx.tables.is_method_call(expr) {
975                 let hir_id = cx.tcx.hir.definitions().node_to_hir_id(id);
976                 let def_id = cx.tables.type_dependent_defs()[hir_id].def_id();
977                 let substs = cx.tables.node_substs(hir_id);
978                 if method_call_refers_to_method(cx, method, def_id, substs, id) {
979                     return true;
980                 }
981             }
982
983             // Check for calls to methods via explicit paths (e.g. `T::method()`).
984             match expr.node {
985                 hir::ExprCall(ref callee, _) => {
986                     let def = if let hir::ExprPath(ref qpath) = callee.node {
987                         cx.tables.qpath_def(qpath, callee.hir_id)
988                     } else {
989                         return false;
990                     };
991                     match def {
992                         Def::Method(def_id) => {
993                             let substs = cx.tables.node_substs(callee.hir_id);
994                             method_call_refers_to_method(cx, method, def_id, substs, id)
995                         }
996                         _ => false,
997                     }
998                 }
999                 _ => false,
1000             }
1001         }
1002
1003         // Check if the method call to the method with the ID `callee_id`
1004         // and instantiated with `callee_substs` refers to method `method`.
1005         fn method_call_refers_to_method<'a, 'tcx>(cx: &LateContext<'a, 'tcx>,
1006                                                   method: &ty::AssociatedItem,
1007                                                   callee_id: DefId,
1008                                                   callee_substs: &Substs<'tcx>,
1009                                                   expr_id: ast::NodeId)
1010                                                   -> bool {
1011             let tcx = cx.tcx;
1012             let callee_item = tcx.associated_item(callee_id);
1013
1014             match callee_item.container {
1015                 // This is an inherent method, so the `def_id` refers
1016                 // directly to the method definition.
1017                 ty::ImplContainer(_) => callee_id == method.def_id,
1018
1019                 // A trait method, from any number of possible sources.
1020                 // Attempt to select a concrete impl before checking.
1021                 ty::TraitContainer(trait_def_id) => {
1022                     let trait_ref = ty::TraitRef::from_method(tcx, trait_def_id, callee_substs);
1023                     let trait_ref = ty::Binder(trait_ref);
1024                     let span = tcx.hir.span(expr_id);
1025                     let obligation =
1026                         traits::Obligation::new(traits::ObligationCause::misc(span, expr_id),
1027                                                 cx.param_env,
1028                                                 trait_ref.to_poly_trait_predicate());
1029
1030                     tcx.infer_ctxt().enter(|infcx| {
1031                         let mut selcx = traits::SelectionContext::new(&infcx);
1032                         match selcx.select(&obligation) {
1033                             // The method comes from a `T: Trait` bound.
1034                             // If `T` is `Self`, then this call is inside
1035                             // a default method definition.
1036                             Ok(Some(traits::VtableParam(_))) => {
1037                                 let on_self = trait_ref.self_ty().is_self();
1038                                 // We can only be recurring in a default
1039                                 // method if we're being called literally
1040                                 // on the `Self` type.
1041                                 on_self && callee_id == method.def_id
1042                             }
1043
1044                             // The `impl` is known, so we check that with a
1045                             // special case:
1046                             Ok(Some(traits::VtableImpl(vtable_impl))) => {
1047                                 let container = ty::ImplContainer(vtable_impl.impl_def_id);
1048                                 // It matches if it comes from the same impl,
1049                                 // and has the same method name.
1050                                 container == method.container && callee_item.name == method.name
1051                             }
1052
1053                             // There's no way to know if this call is
1054                             // recursive, so we assume it's not.
1055                             _ => false,
1056                         }
1057                     })
1058                 }
1059             }
1060         }
1061     }
1062 }
1063
1064 declare_lint! {
1065     PLUGIN_AS_LIBRARY,
1066     Warn,
1067     "compiler plugin used as ordinary library in non-plugin crate"
1068 }
1069
1070 #[derive(Copy, Clone)]
1071 pub struct PluginAsLibrary;
1072
1073 impl LintPass for PluginAsLibrary {
1074     fn get_lints(&self) -> LintArray {
1075         lint_array![PLUGIN_AS_LIBRARY]
1076     }
1077 }
1078
1079 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for PluginAsLibrary {
1080     fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
1081         if cx.sess().plugin_registrar_fn.get().is_some() {
1082             // We're compiling a plugin; it's fine to link other plugins.
1083             return;
1084         }
1085
1086         match it.node {
1087             hir::ItemExternCrate(..) => (),
1088             _ => return,
1089         };
1090
1091         let def_id = cx.tcx.hir.local_def_id(it.id);
1092         let prfn = match cx.tcx.extern_mod_stmt_cnum(def_id) {
1093             Some(cnum) => cx.tcx.plugin_registrar_fn(cnum),
1094             None => {
1095                 // Probably means we aren't linking the crate for some reason.
1096                 //
1097                 // Not sure if / when this could happen.
1098                 return;
1099             }
1100         };
1101
1102         if prfn.is_some() {
1103             cx.span_lint(PLUGIN_AS_LIBRARY,
1104                          it.span,
1105                          "compiler plugin used as an ordinary library");
1106         }
1107     }
1108 }
1109
1110 declare_lint! {
1111     PRIVATE_NO_MANGLE_FNS,
1112     Warn,
1113     "functions marked #[no_mangle] should be exported"
1114 }
1115
1116 declare_lint! {
1117     PRIVATE_NO_MANGLE_STATICS,
1118     Warn,
1119     "statics marked #[no_mangle] should be exported"
1120 }
1121
1122 declare_lint! {
1123     NO_MANGLE_CONST_ITEMS,
1124     Deny,
1125     "const items will not have their symbols exported"
1126 }
1127
1128 declare_lint! {
1129     NO_MANGLE_GENERIC_ITEMS,
1130     Warn,
1131     "generic items must be mangled"
1132 }
1133
1134 #[derive(Copy, Clone)]
1135 pub struct InvalidNoMangleItems;
1136
1137 impl LintPass for InvalidNoMangleItems {
1138     fn get_lints(&self) -> LintArray {
1139         lint_array!(PRIVATE_NO_MANGLE_FNS,
1140                     PRIVATE_NO_MANGLE_STATICS,
1141                     NO_MANGLE_CONST_ITEMS,
1142                     NO_MANGLE_GENERIC_ITEMS)
1143     }
1144 }
1145
1146 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for InvalidNoMangleItems {
1147     fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
1148         match it.node {
1149             hir::ItemFn(.., ref generics, _) => {
1150                 if let Some(no_mangle_attr) = attr::find_by_name(&it.attrs, "no_mangle") {
1151                     if attr::contains_name(&it.attrs, "linkage") {
1152                         return;
1153                     }
1154                     if !cx.access_levels.is_reachable(it.id) {
1155                         let msg = "function is marked #[no_mangle], but not exported";
1156                         let mut err = cx.struct_span_lint(PRIVATE_NO_MANGLE_FNS, it.span, msg);
1157                         let insertion_span = it.span.with_hi(it.span.lo());
1158                         if it.vis == hir::Visibility::Inherited {
1159                             err.span_suggestion(insertion_span,
1160                                                 "try making it public",
1161                                                 "pub ".to_owned());
1162                         }
1163                         err.emit();
1164                     }
1165                     if generics.is_type_parameterized() {
1166                         let mut err = cx.struct_span_lint(NO_MANGLE_GENERIC_ITEMS,
1167                                                           it.span,
1168                                                           "functions generic over \
1169                                                            types must be mangled");
1170                         err.span_suggestion_short(no_mangle_attr.span,
1171                                                   "remove this attribute",
1172                                                   "".to_owned());
1173                         err.emit();
1174                     }
1175                 }
1176             }
1177             hir::ItemStatic(..) => {
1178                 if attr::contains_name(&it.attrs, "no_mangle") &&
1179                    !cx.access_levels.is_reachable(it.id) {
1180                        let msg = "static is marked #[no_mangle], but not exported";
1181                        let mut err = cx.struct_span_lint(PRIVATE_NO_MANGLE_STATICS, it.span, msg);
1182                        let insertion_span = it.span.with_hi(it.span.lo());
1183                        if it.vis == hir::Visibility::Inherited {
1184                            err.span_suggestion(insertion_span,
1185                                                "try making it public",
1186                                                "pub ".to_owned());
1187                        }
1188                        err.emit();
1189                 }
1190             }
1191             hir::ItemConst(..) => {
1192                 if attr::contains_name(&it.attrs, "no_mangle") {
1193                     // Const items do not refer to a particular location in memory, and therefore
1194                     // don't have anything to attach a symbol to
1195                     let msg = "const items should never be #[no_mangle]";
1196                     let mut err = cx.struct_span_lint(NO_MANGLE_CONST_ITEMS, it.span, msg);
1197
1198                     // account for "pub const" (#45562)
1199                     let start = cx.tcx.sess.codemap().span_to_snippet(it.span)
1200                         .map(|snippet| snippet.find("const").unwrap_or(0))
1201                         .unwrap_or(0) as u32;
1202                     // `const` is 5 chars
1203                     let const_span = it.span.with_hi(BytePos(it.span.lo().0 + start + 5));
1204                     err.span_suggestion(const_span,
1205                                         "try a static value",
1206                                         "pub static".to_owned());
1207                     err.emit();
1208                 }
1209             }
1210             _ => {}
1211         }
1212     }
1213 }
1214
1215 #[derive(Clone, Copy)]
1216 pub struct MutableTransmutes;
1217
1218 declare_lint! {
1219     MUTABLE_TRANSMUTES,
1220     Deny,
1221     "mutating transmuted &mut T from &T may cause undefined behavior"
1222 }
1223
1224 impl LintPass for MutableTransmutes {
1225     fn get_lints(&self) -> LintArray {
1226         lint_array!(MUTABLE_TRANSMUTES)
1227     }
1228 }
1229
1230 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MutableTransmutes {
1231     fn check_expr(&mut self, cx: &LateContext, expr: &hir::Expr) {
1232         use syntax::abi::Abi::RustIntrinsic;
1233
1234         let msg = "mutating transmuted &mut T from &T may cause undefined behavior, \
1235                    consider instead using an UnsafeCell";
1236         match get_transmute_from_to(cx, expr) {
1237             Some((&ty::TyRef(_, from_mt), &ty::TyRef(_, to_mt))) => {
1238                 if to_mt.mutbl == hir::Mutability::MutMutable &&
1239                    from_mt.mutbl == hir::Mutability::MutImmutable {
1240                     cx.span_lint(MUTABLE_TRANSMUTES, expr.span, msg);
1241                 }
1242             }
1243             _ => (),
1244         }
1245
1246         fn get_transmute_from_to<'a, 'tcx>
1247             (cx: &LateContext<'a, 'tcx>,
1248              expr: &hir::Expr)
1249              -> Option<(&'tcx ty::TypeVariants<'tcx>, &'tcx ty::TypeVariants<'tcx>)> {
1250             let def = if let hir::ExprPath(ref qpath) = expr.node {
1251                 cx.tables.qpath_def(qpath, expr.hir_id)
1252             } else {
1253                 return None;
1254             };
1255             if let Def::Fn(did) = def {
1256                 if !def_id_is_transmute(cx, did) {
1257                     return None;
1258                 }
1259                 let sig = cx.tables.node_id_to_type(expr.hir_id).fn_sig(cx.tcx);
1260                 let from = sig.inputs().skip_binder()[0];
1261                 let to = *sig.output().skip_binder();
1262                 return Some((&from.sty, &to.sty));
1263             }
1264             None
1265         }
1266
1267         fn def_id_is_transmute(cx: &LateContext, def_id: DefId) -> bool {
1268             cx.tcx.fn_sig(def_id).abi() == RustIntrinsic &&
1269             cx.tcx.item_name(def_id) == "transmute"
1270         }
1271     }
1272 }
1273
1274 /// Forbids using the `#[feature(...)]` attribute
1275 #[derive(Copy, Clone)]
1276 pub struct UnstableFeatures;
1277
1278 declare_lint! {
1279     UNSTABLE_FEATURES,
1280     Allow,
1281     "enabling unstable features (deprecated. do not use)"
1282 }
1283
1284 impl LintPass for UnstableFeatures {
1285     fn get_lints(&self) -> LintArray {
1286         lint_array!(UNSTABLE_FEATURES)
1287     }
1288 }
1289
1290 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnstableFeatures {
1291     fn check_attribute(&mut self, ctx: &LateContext, attr: &ast::Attribute) {
1292         if attr.check_name("feature") {
1293             if let Some(items) = attr.meta_item_list() {
1294                 for item in items {
1295                     ctx.span_lint(UNSTABLE_FEATURES, item.span(), "unstable feature");
1296                 }
1297             }
1298         }
1299     }
1300 }
1301
1302 /// Lint for unions that contain fields with possibly non-trivial destructors.
1303 pub struct UnionsWithDropFields;
1304
1305 declare_lint! {
1306     UNIONS_WITH_DROP_FIELDS,
1307     Warn,
1308     "use of unions that contain fields with possibly non-trivial drop code"
1309 }
1310
1311 impl LintPass for UnionsWithDropFields {
1312     fn get_lints(&self) -> LintArray {
1313         lint_array!(UNIONS_WITH_DROP_FIELDS)
1314     }
1315 }
1316
1317 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnionsWithDropFields {
1318     fn check_item(&mut self, ctx: &LateContext, item: &hir::Item) {
1319         if let hir::ItemUnion(ref vdata, _) = item.node {
1320             for field in vdata.fields() {
1321                 let field_ty = ctx.tcx.type_of(ctx.tcx.hir.local_def_id(field.id));
1322                 if field_ty.needs_drop(ctx.tcx, ctx.param_env) {
1323                     ctx.span_lint(UNIONS_WITH_DROP_FIELDS,
1324                                   field.span,
1325                                   "union contains a field with possibly non-trivial drop code, \
1326                                    drop code of union fields is ignored when dropping the union");
1327                     return;
1328                 }
1329             }
1330         }
1331     }
1332 }
1333
1334 /// Lint for items marked `pub` that aren't reachable from other crates
1335 pub struct UnreachablePub;
1336
1337 declare_lint! {
1338     UNREACHABLE_PUB,
1339     Allow,
1340     "`pub` items not reachable from crate root"
1341 }
1342
1343 impl LintPass for UnreachablePub {
1344     fn get_lints(&self) -> LintArray {
1345         lint_array!(UNREACHABLE_PUB)
1346     }
1347 }
1348
1349 impl UnreachablePub {
1350     fn perform_lint(&self, cx: &LateContext, what: &str, id: ast::NodeId,
1351                     vis: &hir::Visibility, span: Span, exportable: bool) {
1352         if !cx.access_levels.is_reachable(id) && *vis == hir::Visibility::Public {
1353             let def_span = cx.tcx.sess.codemap().def_span(span);
1354             let mut err = cx.struct_span_lint(UNREACHABLE_PUB, def_span,
1355                                               &format!("unreachable `pub` {}", what));
1356             // visibility is token at start of declaration (can be macro
1357             // variable rather than literal `pub`)
1358             let pub_span = cx.tcx.sess.codemap().span_until_char(def_span, ' ');
1359             let replacement = if cx.tcx.sess.features.borrow().crate_visibility_modifier {
1360                 "crate"
1361             } else {
1362                 "pub(crate)"
1363             }.to_owned();
1364             err.span_suggestion(pub_span, "consider restricting its visibility", replacement);
1365             if exportable {
1366                 err.help("or consider exporting it for use by other crates");
1367             }
1368             err.emit();
1369         }
1370     }
1371 }
1372
1373 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnreachablePub {
1374     fn check_item(&mut self, cx: &LateContext, item: &hir::Item) {
1375         self.perform_lint(cx, "item", item.id, &item.vis, item.span, true);
1376     }
1377
1378     fn check_foreign_item(&mut self, cx: &LateContext, foreign_item: &hir::ForeignItem) {
1379         self.perform_lint(cx, "item", foreign_item.id, &foreign_item.vis, foreign_item.span, true);
1380     }
1381
1382     fn check_struct_field(&mut self, cx: &LateContext, field: &hir::StructField) {
1383         self.perform_lint(cx, "field", field.id, &field.vis, field.span, false);
1384     }
1385
1386     fn check_impl_item(&mut self, cx: &LateContext, impl_item: &hir::ImplItem) {
1387         self.perform_lint(cx, "item", impl_item.id, &impl_item.vis, impl_item.span, false);
1388     }
1389 }