]> git.lizzy.rs Git - rust.git/blob - src/librustc_lint/builtin.rs
Allow the linker to choose the LTO-plugin (which is useful when using LLD)
[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::VisibilityKind::Inherited {
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::VisibilityKind::Inherited {
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                 if let Some(def) = cx.tables.type_dependent_defs().get(hir_id) {
1008                     let def_id = def.def_id();
1009                     let substs = cx.tables.node_substs(hir_id);
1010                     if method_call_refers_to_method(cx, method, def_id, substs, id) {
1011                         return true;
1012                     }
1013                 } else {
1014                     cx.tcx.sess.delay_span_bug(expr.span,
1015                                                "no type-dependent def for method call");
1016                 }
1017             }
1018
1019             // Check for calls to methods via explicit paths (e.g. `T::method()`).
1020             match expr.node {
1021                 hir::ExprCall(ref callee, _) => {
1022                     let def = if let hir::ExprPath(ref qpath) = callee.node {
1023                         cx.tables.qpath_def(qpath, callee.hir_id)
1024                     } else {
1025                         return false;
1026                     };
1027                     match def {
1028                         Def::Method(def_id) => {
1029                             let substs = cx.tables.node_substs(callee.hir_id);
1030                             method_call_refers_to_method(cx, method, def_id, substs, id)
1031                         }
1032                         _ => false,
1033                     }
1034                 }
1035                 _ => false,
1036             }
1037         }
1038
1039         // Check if the method call to the method with the ID `callee_id`
1040         // and instantiated with `callee_substs` refers to method `method`.
1041         fn method_call_refers_to_method<'a, 'tcx>(cx: &LateContext<'a, 'tcx>,
1042                                                   method: &ty::AssociatedItem,
1043                                                   callee_id: DefId,
1044                                                   callee_substs: &Substs<'tcx>,
1045                                                   expr_id: ast::NodeId)
1046                                                   -> bool {
1047             let tcx = cx.tcx;
1048             let callee_item = tcx.associated_item(callee_id);
1049
1050             match callee_item.container {
1051                 // This is an inherent method, so the `def_id` refers
1052                 // directly to the method definition.
1053                 ty::ImplContainer(_) => callee_id == method.def_id,
1054
1055                 // A trait method, from any number of possible sources.
1056                 // Attempt to select a concrete impl before checking.
1057                 ty::TraitContainer(trait_def_id) => {
1058                     let trait_ref = ty::TraitRef::from_method(tcx, trait_def_id, callee_substs);
1059                     let trait_ref = ty::Binder::bind(trait_ref);
1060                     let span = tcx.hir.span(expr_id);
1061                     let obligation =
1062                         traits::Obligation::new(traits::ObligationCause::misc(span, expr_id),
1063                                                 cx.param_env,
1064                                                 trait_ref.to_poly_trait_predicate());
1065
1066                     tcx.infer_ctxt().enter(|infcx| {
1067                         let mut selcx = traits::SelectionContext::new(&infcx);
1068                         match selcx.select(&obligation) {
1069                             // The method comes from a `T: Trait` bound.
1070                             // If `T` is `Self`, then this call is inside
1071                             // a default method definition.
1072                             Ok(Some(traits::VtableParam(_))) => {
1073                                 let on_self = trait_ref.self_ty().is_self();
1074                                 // We can only be recurring in a default
1075                                 // method if we're being called literally
1076                                 // on the `Self` type.
1077                                 on_self && callee_id == method.def_id
1078                             }
1079
1080                             // The `impl` is known, so we check that with a
1081                             // special case:
1082                             Ok(Some(traits::VtableImpl(vtable_impl))) => {
1083                                 let container = ty::ImplContainer(vtable_impl.impl_def_id);
1084                                 // It matches if it comes from the same impl,
1085                                 // and has the same method name.
1086                                 container == method.container &&
1087                                 callee_item.ident.name == method.ident.name
1088                             }
1089
1090                             // There's no way to know if this call is
1091                             // recursive, so we assume it's not.
1092                             _ => false,
1093                         }
1094                     })
1095                 }
1096             }
1097         }
1098     }
1099 }
1100
1101 declare_lint! {
1102     PLUGIN_AS_LIBRARY,
1103     Warn,
1104     "compiler plugin used as ordinary library in non-plugin crate"
1105 }
1106
1107 #[derive(Copy, Clone)]
1108 pub struct PluginAsLibrary;
1109
1110 impl LintPass for PluginAsLibrary {
1111     fn get_lints(&self) -> LintArray {
1112         lint_array![PLUGIN_AS_LIBRARY]
1113     }
1114 }
1115
1116 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for PluginAsLibrary {
1117     fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
1118         if cx.sess().plugin_registrar_fn.get().is_some() {
1119             // We're compiling a plugin; it's fine to link other plugins.
1120             return;
1121         }
1122
1123         match it.node {
1124             hir::ItemExternCrate(..) => (),
1125             _ => return,
1126         };
1127
1128         let def_id = cx.tcx.hir.local_def_id(it.id);
1129         let prfn = match cx.tcx.extern_mod_stmt_cnum(def_id) {
1130             Some(cnum) => cx.tcx.plugin_registrar_fn(cnum),
1131             None => {
1132                 // Probably means we aren't linking the crate for some reason.
1133                 //
1134                 // Not sure if / when this could happen.
1135                 return;
1136             }
1137         };
1138
1139         if prfn.is_some() {
1140             cx.span_lint(PLUGIN_AS_LIBRARY,
1141                          it.span,
1142                          "compiler plugin used as an ordinary library");
1143         }
1144     }
1145 }
1146
1147 declare_lint! {
1148     PRIVATE_NO_MANGLE_FNS,
1149     Warn,
1150     "functions marked #[no_mangle] should be exported"
1151 }
1152
1153 declare_lint! {
1154     PRIVATE_NO_MANGLE_STATICS,
1155     Warn,
1156     "statics marked #[no_mangle] should be exported"
1157 }
1158
1159 declare_lint! {
1160     NO_MANGLE_CONST_ITEMS,
1161     Deny,
1162     "const items will not have their symbols exported"
1163 }
1164
1165 declare_lint! {
1166     NO_MANGLE_GENERIC_ITEMS,
1167     Warn,
1168     "generic items must be mangled"
1169 }
1170
1171 #[derive(Copy, Clone)]
1172 pub struct InvalidNoMangleItems;
1173
1174 impl LintPass for InvalidNoMangleItems {
1175     fn get_lints(&self) -> LintArray {
1176         lint_array!(PRIVATE_NO_MANGLE_FNS,
1177                     PRIVATE_NO_MANGLE_STATICS,
1178                     NO_MANGLE_CONST_ITEMS,
1179                     NO_MANGLE_GENERIC_ITEMS)
1180     }
1181 }
1182
1183 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for InvalidNoMangleItems {
1184     fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
1185         let suggest_export = |vis: &hir::Visibility, err: &mut DiagnosticBuilder| {
1186             let suggestion = match vis.node {
1187                 hir::VisibilityKind::Inherited => {
1188                     // inherited visibility is empty span at item start; need an extra space
1189                     Some("pub ".to_owned())
1190                 },
1191                 hir::VisibilityKind::Restricted { .. } |
1192                 hir::VisibilityKind::Crate(_) => {
1193                     Some("pub".to_owned())
1194                 },
1195                 hir::VisibilityKind::Public => {
1196                     err.help("try exporting the item with a `pub use` statement");
1197                     None
1198                 }
1199             };
1200             if let Some(replacement) = suggestion {
1201                 err.span_suggestion(vis.span, "try making it public", replacement);
1202             }
1203         };
1204
1205         match it.node {
1206             hir::ItemFn(.., ref generics, _) => {
1207                 if let Some(no_mangle_attr) = attr::find_by_name(&it.attrs, "no_mangle") {
1208                     if attr::contains_name(&it.attrs, "linkage") {
1209                         return;
1210                     }
1211                     if !cx.access_levels.is_reachable(it.id) {
1212                         let msg = "function is marked #[no_mangle], but not exported";
1213                         let mut err = cx.struct_span_lint(PRIVATE_NO_MANGLE_FNS, it.span, msg);
1214                         suggest_export(&it.vis, &mut err);
1215                         err.emit();
1216                     }
1217                     for param in &generics.params {
1218                         match param.kind {
1219                             GenericParamKind::Lifetime { .. } => {}
1220                             GenericParamKind::Type { .. } => {
1221                                 let mut err = cx.struct_span_lint(NO_MANGLE_GENERIC_ITEMS,
1222                                                                   it.span,
1223                                                                   "functions generic over \
1224                                                                    types must be mangled");
1225                                 err.span_suggestion_short(no_mangle_attr.span,
1226                                                           "remove this attribute",
1227                                                           "".to_owned());
1228                                 err.emit();
1229                                 break;
1230                             }
1231                         }
1232                     }
1233                 }
1234             }
1235             hir::ItemStatic(..) => {
1236                 if attr::contains_name(&it.attrs, "no_mangle") &&
1237                     !cx.access_levels.is_reachable(it.id) {
1238                         let msg = "static is marked #[no_mangle], but not exported";
1239                         let mut err = cx.struct_span_lint(PRIVATE_NO_MANGLE_STATICS, it.span, msg);
1240                         suggest_export(&it.vis, &mut err);
1241                         err.emit();
1242                     }
1243             }
1244             hir::ItemConst(..) => {
1245                 if attr::contains_name(&it.attrs, "no_mangle") {
1246                     // Const items do not refer to a particular location in memory, and therefore
1247                     // don't have anything to attach a symbol to
1248                     let msg = "const items should never be #[no_mangle]";
1249                     let mut err = cx.struct_span_lint(NO_MANGLE_CONST_ITEMS, it.span, msg);
1250
1251                     // account for "pub const" (#45562)
1252                     let start = cx.tcx.sess.codemap().span_to_snippet(it.span)
1253                         .map(|snippet| snippet.find("const").unwrap_or(0))
1254                         .unwrap_or(0) as u32;
1255                     // `const` is 5 chars
1256                     let const_span = it.span.with_hi(BytePos(it.span.lo().0 + start + 5));
1257                     err.span_suggestion(const_span,
1258                                         "try a static value",
1259                                         "pub static".to_owned());
1260                     err.emit();
1261                 }
1262             }
1263             _ => {}
1264         }
1265     }
1266 }
1267
1268 #[derive(Clone, Copy)]
1269 pub struct MutableTransmutes;
1270
1271 declare_lint! {
1272     MUTABLE_TRANSMUTES,
1273     Deny,
1274     "mutating transmuted &mut T from &T may cause undefined behavior"
1275 }
1276
1277 impl LintPass for MutableTransmutes {
1278     fn get_lints(&self) -> LintArray {
1279         lint_array!(MUTABLE_TRANSMUTES)
1280     }
1281 }
1282
1283 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MutableTransmutes {
1284     fn check_expr(&mut self, cx: &LateContext, expr: &hir::Expr) {
1285         use rustc_target::spec::abi::Abi::RustIntrinsic;
1286
1287         let msg = "mutating transmuted &mut T from &T may cause undefined behavior, \
1288                    consider instead using an UnsafeCell";
1289         match get_transmute_from_to(cx, expr) {
1290             Some((&ty::TyRef(_, _, from_mt), &ty::TyRef(_, _, to_mt))) => {
1291                 if to_mt == hir::Mutability::MutMutable &&
1292                    from_mt == hir::Mutability::MutImmutable {
1293                     cx.span_lint(MUTABLE_TRANSMUTES, expr.span, msg);
1294                 }
1295             }
1296             _ => (),
1297         }
1298
1299         fn get_transmute_from_to<'a, 'tcx>
1300             (cx: &LateContext<'a, 'tcx>,
1301              expr: &hir::Expr)
1302              -> Option<(&'tcx ty::TypeVariants<'tcx>, &'tcx ty::TypeVariants<'tcx>)> {
1303             let def = if let hir::ExprPath(ref qpath) = expr.node {
1304                 cx.tables.qpath_def(qpath, expr.hir_id)
1305             } else {
1306                 return None;
1307             };
1308             if let Def::Fn(did) = def {
1309                 if !def_id_is_transmute(cx, did) {
1310                     return None;
1311                 }
1312                 let sig = cx.tables.node_id_to_type(expr.hir_id).fn_sig(cx.tcx);
1313                 let from = sig.inputs().skip_binder()[0];
1314                 let to = *sig.output().skip_binder();
1315                 return Some((&from.sty, &to.sty));
1316             }
1317             None
1318         }
1319
1320         fn def_id_is_transmute(cx: &LateContext, def_id: DefId) -> bool {
1321             cx.tcx.fn_sig(def_id).abi() == RustIntrinsic &&
1322             cx.tcx.item_name(def_id) == "transmute"
1323         }
1324     }
1325 }
1326
1327 /// Forbids using the `#[feature(...)]` attribute
1328 #[derive(Copy, Clone)]
1329 pub struct UnstableFeatures;
1330
1331 declare_lint! {
1332     UNSTABLE_FEATURES,
1333     Allow,
1334     "enabling unstable features (deprecated. do not use)"
1335 }
1336
1337 impl LintPass for UnstableFeatures {
1338     fn get_lints(&self) -> LintArray {
1339         lint_array!(UNSTABLE_FEATURES)
1340     }
1341 }
1342
1343 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnstableFeatures {
1344     fn check_attribute(&mut self, ctx: &LateContext, attr: &ast::Attribute) {
1345         if attr.check_name("feature") {
1346             if let Some(items) = attr.meta_item_list() {
1347                 for item in items {
1348                     ctx.span_lint(UNSTABLE_FEATURES, item.span(), "unstable feature");
1349                 }
1350             }
1351         }
1352     }
1353 }
1354
1355 /// Lint for unions that contain fields with possibly non-trivial destructors.
1356 pub struct UnionsWithDropFields;
1357
1358 declare_lint! {
1359     UNIONS_WITH_DROP_FIELDS,
1360     Warn,
1361     "use of unions that contain fields with possibly non-trivial drop code"
1362 }
1363
1364 impl LintPass for UnionsWithDropFields {
1365     fn get_lints(&self) -> LintArray {
1366         lint_array!(UNIONS_WITH_DROP_FIELDS)
1367     }
1368 }
1369
1370 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnionsWithDropFields {
1371     fn check_item(&mut self, ctx: &LateContext, item: &hir::Item) {
1372         if let hir::ItemUnion(ref vdata, _) = item.node {
1373             for field in vdata.fields() {
1374                 let field_ty = ctx.tcx.type_of(ctx.tcx.hir.local_def_id(field.id));
1375                 if field_ty.needs_drop(ctx.tcx, ctx.param_env) {
1376                     ctx.span_lint(UNIONS_WITH_DROP_FIELDS,
1377                                   field.span,
1378                                   "union contains a field with possibly non-trivial drop code, \
1379                                    drop code of union fields is ignored when dropping the union");
1380                     return;
1381                 }
1382             }
1383         }
1384     }
1385 }
1386
1387 /// Lint for items marked `pub` that aren't reachable from other crates
1388 pub struct UnreachablePub;
1389
1390 declare_lint! {
1391     pub UNREACHABLE_PUB,
1392     Allow,
1393     "`pub` items not reachable from crate root"
1394 }
1395
1396 impl LintPass for UnreachablePub {
1397     fn get_lints(&self) -> LintArray {
1398         lint_array!(UNREACHABLE_PUB)
1399     }
1400 }
1401
1402 impl UnreachablePub {
1403     fn perform_lint(&self, cx: &LateContext, what: &str, id: ast::NodeId,
1404                     vis: &hir::Visibility, span: Span, exportable: bool) {
1405         let mut applicability = Applicability::MachineApplicable;
1406         match vis.node {
1407             hir::VisibilityKind::Public if !cx.access_levels.is_reachable(id) => {
1408                 if span.ctxt().outer().expn_info().is_some() {
1409                     applicability = Applicability::MaybeIncorrect;
1410                 }
1411                 let def_span = cx.tcx.sess.codemap().def_span(span);
1412                 let mut err = cx.struct_span_lint(UNREACHABLE_PUB, def_span,
1413                                                   &format!("unreachable `pub` {}", what));
1414                 let replacement = if cx.tcx.features().crate_visibility_modifier {
1415                     "crate"
1416                 } else {
1417                     "pub(crate)"
1418                 }.to_owned();
1419
1420                 err.span_suggestion_with_applicability(vis.span,
1421                                                        "consider restricting its visibility",
1422                                                        replacement,
1423                                                        applicability);
1424                 if exportable {
1425                     err.help("or consider exporting it for use by other crates");
1426                 }
1427                 err.emit();
1428             },
1429             _ => {}
1430         }
1431     }
1432 }
1433
1434
1435 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnreachablePub {
1436     fn check_item(&mut self, cx: &LateContext, item: &hir::Item) {
1437         self.perform_lint(cx, "item", item.id, &item.vis, item.span, true);
1438     }
1439
1440     fn check_foreign_item(&mut self, cx: &LateContext, foreign_item: &hir::ForeignItem) {
1441         self.perform_lint(cx, "item", foreign_item.id, &foreign_item.vis,
1442                           foreign_item.span, true);
1443     }
1444
1445     fn check_struct_field(&mut self, cx: &LateContext, field: &hir::StructField) {
1446         self.perform_lint(cx, "field", field.id, &field.vis, field.span, false);
1447     }
1448
1449     fn check_impl_item(&mut self, cx: &LateContext, impl_item: &hir::ImplItem) {
1450         self.perform_lint(cx, "item", impl_item.id, &impl_item.vis, impl_item.span, false);
1451     }
1452 }
1453
1454 /// Lint for trait and lifetime bounds in type aliases being mostly ignored:
1455 /// They are relevant when using associated types, but otherwise neither checked
1456 /// at definition site nor enforced at use site.
1457
1458 pub struct TypeAliasBounds;
1459
1460 declare_lint! {
1461     TYPE_ALIAS_BOUNDS,
1462     Warn,
1463     "bounds in type aliases are not enforced"
1464 }
1465
1466 impl LintPass for TypeAliasBounds {
1467     fn get_lints(&self) -> LintArray {
1468         lint_array!(TYPE_ALIAS_BOUNDS)
1469     }
1470 }
1471
1472 impl TypeAliasBounds {
1473     fn is_type_variable_assoc(qpath: &hir::QPath) -> bool {
1474         match *qpath {
1475             hir::QPath::TypeRelative(ref ty, _) => {
1476                 // If this is a type variable, we found a `T::Assoc`.
1477                 match ty.node {
1478                     hir::TyPath(hir::QPath::Resolved(None, ref path)) => {
1479                         match path.def {
1480                             Def::TyParam(_) => true,
1481                             _ => false
1482                         }
1483                     }
1484                     _ => false
1485                 }
1486             }
1487             hir::QPath::Resolved(..) => false,
1488         }
1489     }
1490
1491     fn suggest_changing_assoc_types(ty: &hir::Ty, err: &mut DiagnosticBuilder) {
1492         // Access to associates types should use `<T as Bound>::Assoc`, which does not need a
1493         // bound.  Let's see if this type does that.
1494
1495         // We use a HIR visitor to walk the type.
1496         use rustc::hir::intravisit::{self, Visitor};
1497         use syntax::ast::NodeId;
1498         struct WalkAssocTypes<'a, 'db> where 'db: 'a {
1499             err: &'a mut DiagnosticBuilder<'db>
1500         }
1501         impl<'a, 'db, 'v> Visitor<'v> for WalkAssocTypes<'a, 'db> {
1502             fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'v>
1503             {
1504                 intravisit::NestedVisitorMap::None
1505             }
1506
1507             fn visit_qpath(&mut self, qpath: &'v hir::QPath, id: NodeId, span: Span) {
1508                 if TypeAliasBounds::is_type_variable_assoc(qpath) {
1509                     self.err.span_help(span,
1510                         "use fully disambiguated paths (i.e., `<T as Trait>::Assoc`) to refer to \
1511                          associated types in type aliases");
1512                 }
1513                 intravisit::walk_qpath(self, qpath, id, span)
1514             }
1515         }
1516
1517         // Let's go for a walk!
1518         let mut visitor = WalkAssocTypes { err };
1519         visitor.visit_ty(ty);
1520     }
1521 }
1522
1523 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TypeAliasBounds {
1524     fn check_item(&mut self, cx: &LateContext, item: &hir::Item) {
1525         let (ty, type_alias_generics) = match item.node {
1526             hir::ItemTy(ref ty, ref generics) => (&*ty, generics),
1527             _ => return,
1528         };
1529         let mut suggested_changing_assoc_types = false;
1530         // There must not be a where clause
1531         if !type_alias_generics.where_clause.predicates.is_empty() {
1532             let spans : Vec<_> = type_alias_generics.where_clause.predicates.iter()
1533                 .map(|pred| pred.span()).collect();
1534             let mut err = cx.struct_span_lint(TYPE_ALIAS_BOUNDS, spans,
1535                 "where clauses are not enforced in type aliases");
1536             err.help("the clause will not be checked when the type alias is used, \
1537                       and should be removed");
1538             if !suggested_changing_assoc_types {
1539                 TypeAliasBounds::suggest_changing_assoc_types(ty, &mut err);
1540                 suggested_changing_assoc_types = true;
1541             }
1542             err.emit();
1543         }
1544         // The parameters must not have bounds
1545         for param in type_alias_generics.params.iter() {
1546             let spans: Vec<_> = param.bounds.iter().map(|b| b.span()).collect();
1547             if !spans.is_empty() {
1548                 let mut err = cx.struct_span_lint(
1549                     TYPE_ALIAS_BOUNDS,
1550                     spans,
1551                     "bounds on generic parameters are not enforced in type aliases",
1552                 );
1553                 err.help("the bound will not be checked when the type alias is used, \
1554                           and should be removed");
1555                 if !suggested_changing_assoc_types {
1556                     TypeAliasBounds::suggest_changing_assoc_types(ty, &mut err);
1557                     suggested_changing_assoc_types = true;
1558                 }
1559                 err.emit();
1560             }
1561         }
1562     }
1563 }
1564
1565 /// Lint constants that are erroneous.
1566 /// Without this lint, we might not get any diagnostic if the constant is
1567 /// unused within this crate, even though downstream crates can't use it
1568 /// without producing an error.
1569 pub struct UnusedBrokenConst;
1570
1571 impl LintPass for UnusedBrokenConst {
1572     fn get_lints(&self) -> LintArray {
1573         lint_array!()
1574     }
1575 }
1576
1577 fn check_const(cx: &LateContext, body_id: hir::BodyId, what: &str) {
1578     let def_id = cx.tcx.hir.body_owner_def_id(body_id);
1579     let param_env = cx.tcx.param_env(def_id);
1580     let cid = ::rustc::mir::interpret::GlobalId {
1581         instance: ty::Instance::mono(cx.tcx, def_id),
1582         promoted: None
1583     };
1584     if let Err(err) = cx.tcx.const_eval(param_env.and(cid)) {
1585         let span = cx.tcx.def_span(def_id);
1586         err.report_as_lint(
1587             cx.tcx.at(span),
1588             &format!("this {} cannot be used", what),
1589             cx.current_lint_root(),
1590         );
1591     }
1592 }
1593
1594 struct UnusedBrokenConstVisitor<'a, 'tcx: 'a>(&'a LateContext<'a, 'tcx>);
1595
1596 impl<'a, 'tcx, 'v> hir::intravisit::Visitor<'v> for UnusedBrokenConstVisitor<'a, 'tcx> {
1597     fn visit_nested_body(&mut self, id: hir::BodyId) {
1598         check_const(self.0, id, "array length");
1599     }
1600     fn nested_visit_map<'this>(&'this mut self) -> hir::intravisit::NestedVisitorMap<'this, 'v> {
1601         hir::intravisit::NestedVisitorMap::None
1602     }
1603 }
1604
1605 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedBrokenConst {
1606     fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
1607         match it.node {
1608             hir::ItemConst(_, body_id) => {
1609                 check_const(cx, body_id, "constant");
1610             },
1611             hir::ItemTy(ref ty, _) => hir::intravisit::walk_ty(
1612                 &mut UnusedBrokenConstVisitor(cx),
1613                 ty
1614             ),
1615             _ => {},
1616         }
1617     }
1618 }
1619
1620 /// Lint for trait and lifetime bounds that don't depend on type parameters
1621 /// which either do nothing, or stop the item from being used.
1622 pub struct TrivialConstraints;
1623
1624 declare_lint! {
1625     TRIVIAL_BOUNDS,
1626     Warn,
1627     "these bounds don't depend on an type parameters"
1628 }
1629
1630 impl LintPass for TrivialConstraints {
1631     fn get_lints(&self) -> LintArray {
1632         lint_array!(TRIVIAL_BOUNDS)
1633     }
1634 }
1635
1636 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TrivialConstraints {
1637     fn check_item(
1638         &mut self,
1639         cx: &LateContext<'a, 'tcx>,
1640         item: &'tcx hir::Item,
1641     ) {
1642         use rustc::ty::fold::TypeFoldable;
1643         use rustc::ty::Predicate::*;
1644
1645
1646         if cx.tcx.features().trivial_bounds {
1647             let def_id = cx.tcx.hir.local_def_id(item.id);
1648             let predicates = cx.tcx.predicates_of(def_id);
1649             for predicate in &predicates.predicates {
1650                 let predicate_kind_name = match *predicate {
1651                     Trait(..) => "Trait",
1652                     TypeOutlives(..) |
1653                     RegionOutlives(..) => "Lifetime",
1654
1655                     // Ignore projections, as they can only be global
1656                     // if the trait bound is global
1657                     Projection(..) |
1658                     // Ignore bounds that a user can't type
1659                     WellFormed(..) |
1660                     ObjectSafe(..) |
1661                     ClosureKind(..) |
1662                     Subtype(..) |
1663                     ConstEvaluatable(..) => continue,
1664                 };
1665                 if predicate.is_global() {
1666                     cx.span_lint(
1667                         TRIVIAL_BOUNDS,
1668                         item.span,
1669                         &format!("{} bound {} does not depend on any type \
1670                                 or lifetime parameters", predicate_kind_name, predicate),
1671                     );
1672                 }
1673             }
1674         }
1675     }
1676 }
1677
1678
1679 /// Does nothing as a lint pass, but registers some `Lint`s
1680 /// which are used by other parts of the compiler.
1681 #[derive(Copy, Clone)]
1682 pub struct SoftLints;
1683
1684 impl LintPass for SoftLints {
1685     fn get_lints(&self) -> LintArray {
1686         lint_array!(
1687             WHILE_TRUE,
1688             BOX_POINTERS,
1689             NON_SHORTHAND_FIELD_PATTERNS,
1690             UNSAFE_CODE,
1691             MISSING_DOCS,
1692             MISSING_COPY_IMPLEMENTATIONS,
1693             MISSING_DEBUG_IMPLEMENTATIONS,
1694             ANONYMOUS_PARAMETERS,
1695             UNUSED_DOC_COMMENTS,
1696             UNCONDITIONAL_RECURSION,
1697             PLUGIN_AS_LIBRARY,
1698             PRIVATE_NO_MANGLE_FNS,
1699             PRIVATE_NO_MANGLE_STATICS,
1700             NO_MANGLE_CONST_ITEMS,
1701             NO_MANGLE_GENERIC_ITEMS,
1702             MUTABLE_TRANSMUTES,
1703             UNSTABLE_FEATURES,
1704             UNIONS_WITH_DROP_FIELDS,
1705             UNREACHABLE_PUB,
1706             TYPE_ALIAS_BOUNDS,
1707             TRIVIAL_BOUNDS,
1708         )
1709     }
1710 }
1711
1712
1713 declare_lint! {
1714     pub ELLIPSIS_INCLUSIVE_RANGE_PATTERNS,
1715     Allow,
1716     "`...` range patterns are deprecated"
1717 }
1718
1719
1720 pub struct EllipsisInclusiveRangePatterns;
1721
1722 impl LintPass for EllipsisInclusiveRangePatterns {
1723     fn get_lints(&self) -> LintArray {
1724         lint_array!(ELLIPSIS_INCLUSIVE_RANGE_PATTERNS)
1725     }
1726 }
1727
1728 impl EarlyLintPass for EllipsisInclusiveRangePatterns {
1729     fn check_pat(&mut self, cx: &EarlyContext, pat: &ast::Pat) {
1730         use self::ast::{PatKind, RangeEnd, RangeSyntax};
1731
1732         if let PatKind::Range(
1733             _, _, Spanned { span, node: RangeEnd::Included(RangeSyntax::DotDotDot) }
1734         ) = pat.node {
1735             let msg = "`...` range patterns are deprecated";
1736             let mut err = cx.struct_span_lint(ELLIPSIS_INCLUSIVE_RANGE_PATTERNS, span, msg);
1737             err.span_suggestion_short_with_applicability(
1738                 span, "use `..=` for an inclusive range", "..=".to_owned(),
1739                 // FIXME: outstanding problem with precedence in ref patterns:
1740                 // https://github.com/rust-lang/rust/issues/51043#issuecomment-392252285
1741                 Applicability::MaybeIncorrect
1742             );
1743             err.emit()
1744         }
1745     }
1746 }