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