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