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