]> git.lizzy.rs Git - rust.git/blob - src/librustc/lint/builtin.rs
Implement new orphan rule that requires that impls of remote traits meet the followin...
[rust.git] / src / librustc / lint / builtin.rs
1 // Copyright 2012-2014 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 built in to rustc.
12 //!
13 //! This is a sibling of `lint::context` in order to ensure that
14 //! lints implemented here use the same public API as lint plugins.
15 //!
16 //! To add a new lint to rustc, declare it here using `declare_lint!()`.
17 //! Then add code to emit the new lint in the appropriate circumstances.
18 //! You can do that in an existing `LintPass` if it makes sense, or in
19 //! a new `LintPass`, or using `Session::add_lint` elsewhere in the
20 //! compiler. Only do the latter if the check can't be written cleanly
21 //! as a `LintPass`.
22 //!
23 //! If you define a new `LintPass`, you will also need to add it to the
24 //! `add_builtin!` or `add_builtin_with_new!` invocation in `context.rs`.
25 //! Use the former for unit-like structs and the latter for structs with
26 //! a `pub fn new()`.
27 use self::MethodContext::*;
28
29 use metadata::csearch;
30 use middle::def::*;
31 use middle::subst::Substs;
32 use middle::ty::{self, Ty};
33 use middle::{def, pat_util, stability};
34 use middle::const_eval::{eval_const_expr_partial, const_int, const_uint};
35 use util::ppaux::{ty_to_string};
36 use util::nodemap::{FnvHashMap, NodeSet};
37 use lint::{Context, LintPass, LintArray};
38
39 use std::collections::hash_map::Entry::{Occupied, Vacant};
40 use std::num::SignedInt;
41 use std::{cmp, slice};
42 use std::{i8, i16, i32, i64, u8, u16, u32, u64, f32, f64};
43
44 use syntax::{abi, ast, ast_map};
45 use syntax::ast_util::is_shift_binop;
46 use syntax::attr::{self, AttrMetaMethods};
47 use syntax::codemap::{Span, DUMMY_SP};
48 use syntax::parse::token;
49 use syntax::ast::{TyI, TyU, TyI8, TyU8, TyI16, TyU16, TyI32, TyU32, TyI64, TyU64};
50 use syntax::ast_util;
51 use syntax::ptr::P;
52 use syntax::visit::{self, Visitor};
53
54 declare_lint! {
55     WHILE_TRUE,
56     Warn,
57     "suggest using `loop { }` instead of `while true { }`"
58 }
59
60 #[derive(Copy)]
61 pub struct WhileTrue;
62
63 impl LintPass for WhileTrue {
64     fn get_lints(&self) -> LintArray {
65         lint_array!(WHILE_TRUE)
66     }
67
68     fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
69         if let ast::ExprWhile(ref cond, _, _) = e.node {
70             if let ast::ExprLit(ref lit) = cond.node {
71                 if let ast::LitBool(true) = lit.node {
72                     cx.span_lint(WHILE_TRUE, e.span,
73                                  "denote infinite loops with loop { ... }");
74                 }
75             }
76         }
77     }
78 }
79
80 declare_lint! {
81     UNUSED_TYPECASTS,
82     Allow,
83     "detects unnecessary type casts that can be removed"
84 }
85
86 #[derive(Copy)]
87 pub struct UnusedCasts;
88
89 impl LintPass for UnusedCasts {
90     fn get_lints(&self) -> LintArray {
91         lint_array!(UNUSED_TYPECASTS)
92     }
93
94     fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
95         if let ast::ExprCast(ref expr, ref ty) = e.node {
96             let t_t = ty::expr_ty(cx.tcx, e);
97             if ty::expr_ty(cx.tcx, &**expr) == t_t {
98                 cx.span_lint(UNUSED_TYPECASTS, ty.span, "unnecessary type cast");
99             }
100         }
101     }
102 }
103
104 declare_lint! {
105     UNSIGNED_NEGATION,
106     Warn,
107     "using an unary minus operator on unsigned type"
108 }
109
110 declare_lint! {
111     UNUSED_COMPARISONS,
112     Warn,
113     "comparisons made useless by limits of the types involved"
114 }
115
116 declare_lint! {
117     OVERFLOWING_LITERALS,
118     Warn,
119     "literal out of range for its type"
120 }
121
122 declare_lint! {
123     EXCEEDING_BITSHIFTS,
124     Deny,
125     "shift exceeds the type's number of bits"
126 }
127
128 #[derive(Copy)]
129 pub struct TypeLimits {
130     /// Id of the last visited negated expression
131     negated_expr_id: ast::NodeId,
132 }
133
134 impl TypeLimits {
135     pub fn new() -> TypeLimits {
136         TypeLimits {
137             negated_expr_id: -1,
138         }
139     }
140 }
141
142 impl LintPass for TypeLimits {
143     fn get_lints(&self) -> LintArray {
144         lint_array!(UNSIGNED_NEGATION, UNUSED_COMPARISONS, OVERFLOWING_LITERALS,
145                     EXCEEDING_BITSHIFTS)
146     }
147
148     fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
149         match e.node {
150             ast::ExprUnary(ast::UnNeg, ref expr) => {
151                 match expr.node  {
152                     ast::ExprLit(ref lit) => {
153                         match lit.node {
154                             ast::LitInt(_, ast::UnsignedIntLit(_)) => {
155                                 cx.span_lint(UNSIGNED_NEGATION, e.span,
156                                              "negation of unsigned int literal may \
157                                              be unintentional");
158                             },
159                             _ => ()
160                         }
161                     },
162                     _ => {
163                         let t = ty::expr_ty(cx.tcx, &**expr);
164                         match t.sty {
165                             ty::ty_uint(_) => {
166                                 cx.span_lint(UNSIGNED_NEGATION, e.span,
167                                              "negation of unsigned int variable may \
168                                              be unintentional");
169                             },
170                             _ => ()
171                         }
172                     }
173                 };
174                 // propagate negation, if the negation itself isn't negated
175                 if self.negated_expr_id != e.id {
176                     self.negated_expr_id = expr.id;
177                 }
178             },
179             ast::ExprParen(ref expr) if self.negated_expr_id == e.id => {
180                 self.negated_expr_id = expr.id;
181             },
182             ast::ExprBinary(binop, ref l, ref r) => {
183                 if is_comparison(binop) && !check_limits(cx.tcx, binop, &**l, &**r) {
184                     cx.span_lint(UNUSED_COMPARISONS, e.span,
185                                  "comparison is useless due to type limits");
186                 }
187
188                 if is_shift_binop(binop) {
189                     let opt_ty_bits = match ty::expr_ty(cx.tcx, &**l).sty {
190                         ty::ty_int(t) => Some(int_ty_bits(t, cx.sess().target.int_type)),
191                         ty::ty_uint(t) => Some(uint_ty_bits(t, cx.sess().target.uint_type)),
192                         _ => None
193                     };
194
195                     if let Some(bits) = opt_ty_bits {
196                         let exceeding = if let ast::ExprLit(ref lit) = r.node {
197                             if let ast::LitInt(shift, _) = lit.node { shift >= bits }
198                             else { false }
199                         } else {
200                             match eval_const_expr_partial(cx.tcx, &**r) {
201                                 Ok(const_int(shift)) => { shift as u64 >= bits },
202                                 Ok(const_uint(shift)) => { shift >= bits },
203                                 _ => { false }
204                             }
205                         };
206                         if exceeding {
207                             cx.span_lint(EXCEEDING_BITSHIFTS, e.span,
208                                          "bitshift exceeds the type's number of bits");
209                         }
210                     };
211                 }
212             },
213             ast::ExprLit(ref lit) => {
214                 match ty::expr_ty(cx.tcx, e).sty {
215                     ty::ty_int(t) => {
216                         match lit.node {
217                             ast::LitInt(v, ast::SignedIntLit(_, ast::Plus)) |
218                             ast::LitInt(v, ast::UnsuffixedIntLit(ast::Plus)) => {
219                                 let int_type = if t == ast::TyI {
220                                     cx.sess().target.int_type
221                                 } else { t };
222                                 let (min, max) = int_ty_range(int_type);
223                                 let negative = self.negated_expr_id == e.id;
224
225                                 if (negative && v > (min.abs() as u64)) ||
226                                    (!negative && v > (max.abs() as u64)) {
227                                     cx.span_lint(OVERFLOWING_LITERALS, e.span,
228                                                  "literal out of range for its type");
229                                     return;
230                                 }
231                             }
232                             _ => panic!()
233                         };
234                     },
235                     ty::ty_uint(t) => {
236                         let uint_type = if t == ast::TyU {
237                             cx.sess().target.uint_type
238                         } else { t };
239                         let (min, max) = uint_ty_range(uint_type);
240                         let lit_val: u64 = match lit.node {
241                             ast::LitByte(_v) => return,  // _v is u8, within range by definition
242                             ast::LitInt(v, _) => v,
243                             _ => panic!()
244                         };
245                         if  lit_val < min || lit_val > max {
246                             cx.span_lint(OVERFLOWING_LITERALS, e.span,
247                                          "literal out of range for its type");
248                         }
249                     },
250                     ty::ty_float(t) => {
251                         let (min, max) = float_ty_range(t);
252                         let lit_val: f64 = match lit.node {
253                             ast::LitFloat(ref v, _) |
254                             ast::LitFloatUnsuffixed(ref v) => {
255                                 match v.parse() {
256                                     Some(f) => f,
257                                     None => return
258                                 }
259                             }
260                             _ => panic!()
261                         };
262                         if lit_val < min || lit_val > max {
263                             cx.span_lint(OVERFLOWING_LITERALS, e.span,
264                                          "literal out of range for its type");
265                         }
266                     },
267                     _ => ()
268                 };
269             },
270             _ => ()
271         };
272
273         fn is_valid<T:cmp::PartialOrd>(binop: ast::BinOp, v: T,
274                                 min: T, max: T) -> bool {
275             match binop {
276                 ast::BiLt => v >  min && v <= max,
277                 ast::BiLe => v >= min && v <  max,
278                 ast::BiGt => v >= min && v <  max,
279                 ast::BiGe => v >  min && v <= max,
280                 ast::BiEq | ast::BiNe => v >= min && v <= max,
281                 _ => panic!()
282             }
283         }
284
285         fn rev_binop(binop: ast::BinOp) -> ast::BinOp {
286             match binop {
287                 ast::BiLt => ast::BiGt,
288                 ast::BiLe => ast::BiGe,
289                 ast::BiGt => ast::BiLt,
290                 ast::BiGe => ast::BiLe,
291                 _ => binop
292             }
293         }
294
295         // for int & uint, be conservative with the warnings, so that the
296         // warnings are consistent between 32- and 64-bit platforms
297         fn int_ty_range(int_ty: ast::IntTy) -> (i64, i64) {
298             match int_ty {
299                 ast::TyI =>    (i64::MIN,        i64::MAX),
300                 ast::TyI8 =>   (i8::MIN  as i64, i8::MAX  as i64),
301                 ast::TyI16 =>  (i16::MIN as i64, i16::MAX as i64),
302                 ast::TyI32 =>  (i32::MIN as i64, i32::MAX as i64),
303                 ast::TyI64 =>  (i64::MIN,        i64::MAX)
304             }
305         }
306
307         fn uint_ty_range(uint_ty: ast::UintTy) -> (u64, u64) {
308             match uint_ty {
309                 ast::TyU =>   (u64::MIN,         u64::MAX),
310                 ast::TyU8 =>  (u8::MIN   as u64, u8::MAX   as u64),
311                 ast::TyU16 => (u16::MIN  as u64, u16::MAX  as u64),
312                 ast::TyU32 => (u32::MIN  as u64, u32::MAX  as u64),
313                 ast::TyU64 => (u64::MIN,         u64::MAX)
314             }
315         }
316
317         fn float_ty_range(float_ty: ast::FloatTy) -> (f64, f64) {
318             match float_ty {
319                 ast::TyF32  => (f32::MIN_VALUE as f64, f32::MAX_VALUE as f64),
320                 ast::TyF64  => (f64::MIN_VALUE,        f64::MAX_VALUE)
321             }
322         }
323
324         fn int_ty_bits(int_ty: ast::IntTy, target_int_ty: ast::IntTy) -> u64 {
325             match int_ty {
326                 ast::TyI =>    int_ty_bits(target_int_ty, target_int_ty),
327                 ast::TyI8 =>   i8::BITS  as u64,
328                 ast::TyI16 =>  i16::BITS as u64,
329                 ast::TyI32 =>  i32::BITS as u64,
330                 ast::TyI64 =>  i64::BITS as u64
331             }
332         }
333
334         fn uint_ty_bits(uint_ty: ast::UintTy, target_uint_ty: ast::UintTy) -> u64 {
335             match uint_ty {
336                 ast::TyU =>    uint_ty_bits(target_uint_ty, target_uint_ty),
337                 ast::TyU8 =>   u8::BITS  as u64,
338                 ast::TyU16 =>  u16::BITS as u64,
339                 ast::TyU32 =>  u32::BITS as u64,
340                 ast::TyU64 =>  u64::BITS as u64
341             }
342         }
343
344         fn check_limits(tcx: &ty::ctxt, binop: ast::BinOp,
345                         l: &ast::Expr, r: &ast::Expr) -> bool {
346             let (lit, expr, swap) = match (&l.node, &r.node) {
347                 (&ast::ExprLit(_), _) => (l, r, true),
348                 (_, &ast::ExprLit(_)) => (r, l, false),
349                 _ => return true
350             };
351             // Normalize the binop so that the literal is always on the RHS in
352             // the comparison
353             let norm_binop = if swap { rev_binop(binop) } else { binop };
354             match ty::expr_ty(tcx, expr).sty {
355                 ty::ty_int(int_ty) => {
356                     let (min, max) = int_ty_range(int_ty);
357                     let lit_val: i64 = match lit.node {
358                         ast::ExprLit(ref li) => match li.node {
359                             ast::LitInt(v, ast::SignedIntLit(_, ast::Plus)) |
360                             ast::LitInt(v, ast::UnsuffixedIntLit(ast::Plus)) => v as i64,
361                             ast::LitInt(v, ast::SignedIntLit(_, ast::Minus)) |
362                             ast::LitInt(v, ast::UnsuffixedIntLit(ast::Minus)) => -(v as i64),
363                             _ => return true
364                         },
365                         _ => panic!()
366                     };
367                     is_valid(norm_binop, lit_val, min, max)
368                 }
369                 ty::ty_uint(uint_ty) => {
370                     let (min, max): (u64, u64) = uint_ty_range(uint_ty);
371                     let lit_val: u64 = match lit.node {
372                         ast::ExprLit(ref li) => match li.node {
373                             ast::LitInt(v, _) => v,
374                             _ => return true
375                         },
376                         _ => panic!()
377                     };
378                     is_valid(norm_binop, lit_val, min, max)
379                 }
380                 _ => true
381             }
382         }
383
384         fn is_comparison(binop: ast::BinOp) -> bool {
385             match binop {
386                 ast::BiEq | ast::BiLt | ast::BiLe |
387                 ast::BiNe | ast::BiGe | ast::BiGt => true,
388                 _ => false
389             }
390         }
391     }
392 }
393
394 declare_lint! {
395     IMPROPER_CTYPES,
396     Warn,
397     "proper use of libc types in foreign modules"
398 }
399
400 struct ImproperCTypesVisitor<'a, 'tcx: 'a> {
401     cx: &'a Context<'a, 'tcx>
402 }
403
404 impl<'a, 'tcx> ImproperCTypesVisitor<'a, 'tcx> {
405     fn check_def(&mut self, sp: Span, ty_id: ast::NodeId, path_id: ast::NodeId) {
406         match self.cx.tcx.def_map.borrow()[path_id].clone() {
407             def::DefPrimTy(ast::TyInt(ast::TyI)) => {
408                 self.cx.span_lint(IMPROPER_CTYPES, sp,
409                                   "found rust type `int` in foreign module, while \
410                                    libc::c_int or libc::c_long should be used");
411             }
412             def::DefPrimTy(ast::TyUint(ast::TyU)) => {
413                 self.cx.span_lint(IMPROPER_CTYPES, sp,
414                                   "found rust type `uint` in foreign module, while \
415                                    libc::c_uint or libc::c_ulong should be used");
416             }
417             def::DefTy(..) => {
418                 let tty = match self.cx.tcx.ast_ty_to_ty_cache.borrow().get(&ty_id) {
419                     Some(&ty::atttce_resolved(t)) => t,
420                     _ => panic!("ast_ty_to_ty_cache was incomplete after typeck!")
421                 };
422
423                 if !ty::is_ffi_safe(self.cx.tcx, tty) {
424                     self.cx.span_lint(IMPROPER_CTYPES, sp,
425                                       "found type without foreign-function-safe
426                                       representation annotation in foreign module, consider \
427                                       adding a #[repr(...)] attribute to the type");
428                 }
429             }
430             _ => ()
431         }
432     }
433 }
434
435 impl<'a, 'tcx, 'v> Visitor<'v> for ImproperCTypesVisitor<'a, 'tcx> {
436     fn visit_ty(&mut self, ty: &ast::Ty) {
437         match ty.node {
438             ast::TyPath(_, id) => self.check_def(ty.span, ty.id, id),
439             _ => (),
440         }
441         visit::walk_ty(self, ty);
442     }
443 }
444
445 #[derive(Copy)]
446 pub struct ImproperCTypes;
447
448 impl LintPass for ImproperCTypes {
449     fn get_lints(&self) -> LintArray {
450         lint_array!(IMPROPER_CTYPES)
451     }
452
453     fn check_item(&mut self, cx: &Context, it: &ast::Item) {
454         fn check_ty(cx: &Context, ty: &ast::Ty) {
455             let mut vis = ImproperCTypesVisitor { cx: cx };
456             vis.visit_ty(ty);
457         }
458
459         fn check_foreign_fn(cx: &Context, decl: &ast::FnDecl) {
460             for input in decl.inputs.iter() {
461                 check_ty(cx, &*input.ty);
462             }
463             if let ast::Return(ref ret_ty) = decl.output {
464                 check_ty(cx, &**ret_ty);
465             }
466         }
467
468         match it.node {
469             ast::ItemForeignMod(ref nmod) if nmod.abi != abi::RustIntrinsic => {
470                 for ni in nmod.items.iter() {
471                     match ni.node {
472                         ast::ForeignItemFn(ref decl, _) => check_foreign_fn(cx, &**decl),
473                         ast::ForeignItemStatic(ref t, _) => check_ty(cx, &**t)
474                     }
475                 }
476             }
477             _ => (),
478         }
479     }
480 }
481
482 declare_lint! {
483     BOX_POINTERS,
484     Allow,
485     "use of owned (Box type) heap memory"
486 }
487
488 #[derive(Copy)]
489 pub struct BoxPointers;
490
491 impl BoxPointers {
492     fn check_heap_type<'a, 'tcx>(&self, cx: &Context<'a, 'tcx>,
493                                  span: Span, ty: Ty<'tcx>) {
494         let mut n_uniq = 0i;
495         ty::fold_ty(cx.tcx, ty, |t| {
496             match t.sty {
497                 ty::ty_uniq(_) |
498                 ty::ty_closure(box ty::ClosureTy {
499                     store: ty::UniqTraitStore,
500                     ..
501                 }) => {
502                     n_uniq += 1;
503                 }
504
505                 _ => ()
506             };
507             t
508         });
509
510         if n_uniq > 0 {
511             let s = ty_to_string(cx.tcx, ty);
512             let m = format!("type uses owned (Box type) pointers: {}", s);
513             cx.span_lint(BOX_POINTERS, span, m[]);
514         }
515     }
516 }
517
518 impl LintPass for BoxPointers {
519     fn get_lints(&self) -> LintArray {
520         lint_array!(BOX_POINTERS)
521     }
522
523     fn check_item(&mut self, cx: &Context, it: &ast::Item) {
524         match it.node {
525             ast::ItemFn(..) |
526             ast::ItemTy(..) |
527             ast::ItemEnum(..) |
528             ast::ItemStruct(..) =>
529                 self.check_heap_type(cx, it.span,
530                                      ty::node_id_to_type(cx.tcx, it.id)),
531             _ => ()
532         }
533
534         // If it's a struct, we also have to check the fields' types
535         match it.node {
536             ast::ItemStruct(ref struct_def, _) => {
537                 for struct_field in struct_def.fields.iter() {
538                     self.check_heap_type(cx, struct_field.span,
539                                          ty::node_id_to_type(cx.tcx, struct_field.node.id));
540                 }
541             }
542             _ => ()
543         }
544     }
545
546     fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
547         let ty = ty::expr_ty(cx.tcx, e);
548         self.check_heap_type(cx, e.span, ty);
549     }
550 }
551
552 declare_lint! {
553     RAW_POINTER_DERIVING,
554     Warn,
555     "uses of #[derive] with raw pointers are rarely correct"
556 }
557
558 struct RawPtrDerivingVisitor<'a, 'tcx: 'a> {
559     cx: &'a Context<'a, 'tcx>
560 }
561
562 impl<'a, 'tcx, 'v> Visitor<'v> for RawPtrDerivingVisitor<'a, 'tcx> {
563     fn visit_ty(&mut self, ty: &ast::Ty) {
564         static MSG: &'static str = "use of `#[derive]` with a raw pointer";
565         if let ast::TyPtr(..) = ty.node {
566             self.cx.span_lint(RAW_POINTER_DERIVING, ty.span, MSG);
567         }
568         visit::walk_ty(self, ty);
569     }
570     // explicit override to a no-op to reduce code bloat
571     fn visit_expr(&mut self, _: &ast::Expr) {}
572     fn visit_block(&mut self, _: &ast::Block) {}
573 }
574
575 pub struct RawPointerDeriving {
576     checked_raw_pointers: NodeSet,
577 }
578
579 impl RawPointerDeriving {
580     pub fn new() -> RawPointerDeriving {
581         RawPointerDeriving {
582             checked_raw_pointers: NodeSet::new(),
583         }
584     }
585 }
586
587 impl LintPass for RawPointerDeriving {
588     fn get_lints(&self) -> LintArray {
589         lint_array!(RAW_POINTER_DERIVING)
590     }
591
592     fn check_item(&mut self, cx: &Context, item: &ast::Item) {
593         if !attr::contains_name(item.attrs[], "automatically_derived") {
594             return
595         }
596         let did = match item.node {
597             ast::ItemImpl(..) => {
598                 match ty::node_id_to_type(cx.tcx, item.id).sty {
599                     ty::ty_enum(did, _) => did,
600                     ty::ty_struct(did, _) => did,
601                     _ => return,
602                 }
603             }
604             _ => return,
605         };
606         if !ast_util::is_local(did) { return }
607         let item = match cx.tcx.map.find(did.node) {
608             Some(ast_map::NodeItem(item)) => item,
609             _ => return,
610         };
611         if !self.checked_raw_pointers.insert(item.id) { return }
612         match item.node {
613             ast::ItemStruct(..) | ast::ItemEnum(..) => {
614                 let mut visitor = RawPtrDerivingVisitor { cx: cx };
615                 visit::walk_item(&mut visitor, &*item);
616             }
617             _ => {}
618         }
619     }
620 }
621
622 declare_lint! {
623     UNUSED_ATTRIBUTES,
624     Warn,
625     "detects attributes that were not used by the compiler"
626 }
627
628 #[derive(Copy)]
629 pub struct UnusedAttributes;
630
631 impl LintPass for UnusedAttributes {
632     fn get_lints(&self) -> LintArray {
633         lint_array!(UNUSED_ATTRIBUTES)
634     }
635
636     fn check_attribute(&mut self, cx: &Context, attr: &ast::Attribute) {
637         static ATTRIBUTE_WHITELIST: &'static [&'static str] = &[
638             // FIXME: #14408 whitelist docs since rustdoc looks at them
639             "doc",
640
641             // FIXME: #14406 these are processed in trans, which happens after the
642             // lint pass
643             "cold",
644             "export_name",
645             "inline",
646             "link",
647             "link_name",
648             "link_section",
649             "linkage",
650             "no_builtins",
651             "no_mangle",
652             "no_split_stack",
653             "no_stack_check",
654             "packed",
655             "static_assert",
656             "thread_local",
657             "no_debug",
658             "omit_gdb_pretty_printer_section",
659             "unsafe_no_drop_flag",
660
661             // used in resolve
662             "prelude_import",
663
664             // FIXME: #14407 these are only looked at on-demand so we can't
665             // guarantee they'll have already been checked
666             "deprecated",
667             "experimental",
668             "frozen",
669             "locked",
670             "must_use",
671             "stable",
672             "unstable",
673
674             // FIXME: #19470 this shouldn't be needed forever
675             "old_orphan_check",
676         ];
677
678         static CRATE_ATTRS: &'static [&'static str] = &[
679             "crate_name",
680             "crate_type",
681             "feature",
682             "no_start",
683             "no_main",
684             "no_std",
685             "no_builtins",
686         ];
687
688         for &name in ATTRIBUTE_WHITELIST.iter() {
689             if attr.check_name(name) {
690                 break;
691             }
692         }
693
694         if !attr::is_used(attr) {
695             cx.span_lint(UNUSED_ATTRIBUTES, attr.span, "unused attribute");
696             if CRATE_ATTRS.contains(&attr.name().get()) {
697                 let msg = match attr.node.style {
698                     ast::AttrOuter => "crate-level attribute should be an inner \
699                                        attribute: add an exclamation mark: #![foo]",
700                     ast::AttrInner => "crate-level attribute should be in the \
701                                        root module",
702                 };
703                 cx.span_lint(UNUSED_ATTRIBUTES, attr.span, msg);
704             }
705         }
706     }
707 }
708
709 declare_lint! {
710     pub PATH_STATEMENTS,
711     Warn,
712     "path statements with no effect"
713 }
714
715 #[derive(Copy)]
716 pub struct PathStatements;
717
718 impl LintPass for PathStatements {
719     fn get_lints(&self) -> LintArray {
720         lint_array!(PATH_STATEMENTS)
721     }
722
723     fn check_stmt(&mut self, cx: &Context, s: &ast::Stmt) {
724         match s.node {
725             ast::StmtSemi(ref expr, _) => {
726                 match expr.node {
727                     ast::ExprPath(_) => cx.span_lint(PATH_STATEMENTS, s.span,
728                                                      "path statement with no effect"),
729                     _ => ()
730                 }
731             }
732             _ => ()
733         }
734     }
735 }
736
737 declare_lint! {
738     pub UNUSED_MUST_USE,
739     Warn,
740     "unused result of a type flagged as #[must_use]"
741 }
742
743 declare_lint! {
744     pub UNUSED_RESULTS,
745     Allow,
746     "unused result of an expression in a statement"
747 }
748
749 #[derive(Copy)]
750 pub struct UnusedResults;
751
752 impl LintPass for UnusedResults {
753     fn get_lints(&self) -> LintArray {
754         lint_array!(UNUSED_MUST_USE, UNUSED_RESULTS)
755     }
756
757     fn check_stmt(&mut self, cx: &Context, s: &ast::Stmt) {
758         let expr = match s.node {
759             ast::StmtSemi(ref expr, _) => &**expr,
760             _ => return
761         };
762
763         if let ast::ExprRet(..) = expr.node {
764             return;
765         }
766
767         let t = ty::expr_ty(cx.tcx, expr);
768         let mut warned = false;
769         match t.sty {
770             ty::ty_tup(ref tys) if tys.is_empty() => return,
771             ty::ty_bool => return,
772             ty::ty_struct(did, _) |
773             ty::ty_enum(did, _) => {
774                 if ast_util::is_local(did) {
775                     if let ast_map::NodeItem(it) = cx.tcx.map.get(did.node) {
776                         warned |= check_must_use(cx, it.attrs[], s.span);
777                     }
778                 } else {
779                     csearch::get_item_attrs(&cx.sess().cstore, did, |attrs| {
780                         warned |= check_must_use(cx, attrs[], s.span);
781                     });
782                 }
783             }
784             _ => {}
785         }
786         if !warned {
787             cx.span_lint(UNUSED_RESULTS, s.span, "unused result");
788         }
789
790         fn check_must_use(cx: &Context, attrs: &[ast::Attribute], sp: Span) -> bool {
791             for attr in attrs.iter() {
792                 if attr.check_name("must_use") {
793                     let mut msg = "unused result which must be used".to_string();
794                     // check for #[must_use="..."]
795                     match attr.value_str() {
796                         None => {}
797                         Some(s) => {
798                             msg.push_str(": ");
799                             msg.push_str(s.get());
800                         }
801                     }
802                     cx.span_lint(UNUSED_MUST_USE, sp, msg[]);
803                     return true;
804                 }
805             }
806             false
807         }
808     }
809 }
810
811 declare_lint! {
812     pub NON_CAMEL_CASE_TYPES,
813     Warn,
814     "types, variants, traits and type parameters should have camel case names"
815 }
816
817 #[derive(Copy)]
818 pub struct NonCamelCaseTypes;
819
820 impl NonCamelCaseTypes {
821     fn check_case(&self, cx: &Context, sort: &str, ident: ast::Ident, span: Span) {
822         fn is_camel_case(ident: ast::Ident) -> bool {
823             let ident = token::get_ident(ident);
824             if ident.get().is_empty() { return true; }
825             let ident = ident.get().trim_matches('_');
826
827             // start with a non-lowercase letter rather than non-uppercase
828             // ones (some scripts don't have a concept of upper/lowercase)
829             ident.len() > 0 && !ident.char_at(0).is_lowercase() && !ident.contains_char('_')
830         }
831
832         fn to_camel_case(s: &str) -> String {
833             s.split('_').flat_map(|word| word.chars().enumerate().map(|(i, c)|
834                 if i == 0 { c.to_uppercase() }
835                 else { c }
836             )).collect()
837         }
838
839         let s = token::get_ident(ident);
840
841         if !is_camel_case(ident) {
842             let c = to_camel_case(s.get());
843             let m = if c.is_empty() {
844                 format!("{} `{}` should have a camel case name such as `CamelCase`", sort, s)
845             } else {
846                 format!("{} `{}` should have a camel case name such as `{}`", sort, s, c)
847             };
848             cx.span_lint(NON_CAMEL_CASE_TYPES, span, m[]);
849         }
850     }
851 }
852
853 impl LintPass for NonCamelCaseTypes {
854     fn get_lints(&self) -> LintArray {
855         lint_array!(NON_CAMEL_CASE_TYPES)
856     }
857
858     fn check_item(&mut self, cx: &Context, it: &ast::Item) {
859         let has_extern_repr = it.attrs.iter().map(|attr| {
860             attr::find_repr_attrs(cx.tcx.sess.diagnostic(), attr).iter()
861                 .any(|r| r == &attr::ReprExtern)
862         }).any(|x| x);
863         if has_extern_repr { return }
864
865         match it.node {
866             ast::ItemTy(..) | ast::ItemStruct(..) => {
867                 self.check_case(cx, "type", it.ident, it.span)
868             }
869             ast::ItemTrait(..) => {
870                 self.check_case(cx, "trait", it.ident, it.span)
871             }
872             ast::ItemEnum(ref enum_definition, _) => {
873                 if has_extern_repr { return }
874                 self.check_case(cx, "type", it.ident, it.span);
875                 for variant in enum_definition.variants.iter() {
876                     self.check_case(cx, "variant", variant.node.name, variant.span);
877                 }
878             }
879             _ => ()
880         }
881     }
882
883     fn check_generics(&mut self, cx: &Context, it: &ast::Generics) {
884         for gen in it.ty_params.iter() {
885             self.check_case(cx, "type parameter", gen.ident, gen.span);
886         }
887     }
888 }
889
890 #[derive(PartialEq)]
891 enum MethodContext {
892     TraitDefaultImpl,
893     TraitImpl,
894     PlainImpl
895 }
896
897 fn method_context(cx: &Context, m: &ast::Method) -> MethodContext {
898     let did = ast::DefId {
899         krate: ast::LOCAL_CRATE,
900         node: m.id
901     };
902
903     match cx.tcx.impl_or_trait_items.borrow().get(&did).cloned() {
904         None => cx.sess().span_bug(m.span, "missing method descriptor?!"),
905         Some(md) => {
906             match md {
907                 ty::MethodTraitItem(md) => {
908                     match md.container {
909                         ty::TraitContainer(..) => TraitDefaultImpl,
910                         ty::ImplContainer(cid) => {
911                             match ty::impl_trait_ref(cx.tcx, cid) {
912                                 Some(..) => TraitImpl,
913                                 None => PlainImpl
914                             }
915                         }
916                     }
917                 }
918                 ty::TypeTraitItem(typedef) => {
919                     match typedef.container {
920                         ty::TraitContainer(..) => TraitDefaultImpl,
921                         ty::ImplContainer(cid) => {
922                             match ty::impl_trait_ref(cx.tcx, cid) {
923                                 Some(..) => TraitImpl,
924                                 None => PlainImpl
925                             }
926                         }
927                     }
928                 }
929             }
930         }
931     }
932 }
933
934 declare_lint! {
935     pub NON_SNAKE_CASE,
936     Warn,
937     "methods, functions, lifetime parameters and modules should have snake case names"
938 }
939
940 #[derive(Copy)]
941 pub struct NonSnakeCase;
942
943 impl NonSnakeCase {
944     fn check_snake_case(&self, cx: &Context, sort: &str, ident: ast::Ident, span: Span) {
945         fn is_snake_case(ident: ast::Ident) -> bool {
946             let ident = token::get_ident(ident);
947             if ident.get().is_empty() { return true; }
948             let ident = ident.get().trim_left_matches('\'');
949             let ident = ident.trim_matches('_');
950
951             let mut allow_underscore = true;
952             ident.chars().all(|c| {
953                 allow_underscore = match c {
954                     c if c.is_lowercase() || c.is_numeric() => true,
955                     '_' if allow_underscore => false,
956                     _ => return false,
957                 };
958                 true
959             })
960         }
961
962         fn to_snake_case(str: &str) -> String {
963             let mut words = vec![];
964             for s in str.split('_') {
965                 let mut last_upper = false;
966                 let mut buf = String::new();
967                 if s.is_empty() { continue; }
968                 for ch in s.chars() {
969                     if !buf.is_empty() && buf != "'"
970                                        && ch.is_uppercase()
971                                        && !last_upper {
972                         words.push(buf);
973                         buf = String::new();
974                     }
975                     last_upper = ch.is_uppercase();
976                     buf.push(ch.to_lowercase());
977                 }
978                 words.push(buf);
979             }
980             words.connect("_")
981         }
982
983         let s = token::get_ident(ident);
984
985         if !is_snake_case(ident) {
986             cx.span_lint(NON_SNAKE_CASE, span,
987                 format!("{} `{}` should have a snake case name such as `{}`",
988                         sort, s, to_snake_case(s.get()))[]);
989         }
990     }
991 }
992
993 impl LintPass for NonSnakeCase {
994     fn get_lints(&self) -> LintArray {
995         lint_array!(NON_SNAKE_CASE)
996     }
997
998     fn check_fn(&mut self, cx: &Context,
999                 fk: visit::FnKind, _: &ast::FnDecl,
1000                 _: &ast::Block, span: Span, _: ast::NodeId) {
1001         match fk {
1002             visit::FkMethod(ident, _, m) => match method_context(cx, m) {
1003                 PlainImpl
1004                     => self.check_snake_case(cx, "method", ident, span),
1005                 TraitDefaultImpl
1006                     => self.check_snake_case(cx, "trait method", ident, span),
1007                 _ => (),
1008             },
1009             visit::FkItemFn(ident, _, _, _)
1010                 => self.check_snake_case(cx, "function", ident, span),
1011             _ => (),
1012         }
1013     }
1014
1015     fn check_item(&mut self, cx: &Context, it: &ast::Item) {
1016         if let ast::ItemMod(_) = it.node {
1017             self.check_snake_case(cx, "module", it.ident, it.span);
1018         }
1019     }
1020
1021     fn check_ty_method(&mut self, cx: &Context, t: &ast::TypeMethod) {
1022         self.check_snake_case(cx, "trait method", t.ident, t.span);
1023     }
1024
1025     fn check_lifetime_def(&mut self, cx: &Context, t: &ast::LifetimeDef) {
1026         self.check_snake_case(cx, "lifetime", t.lifetime.name.ident(), t.lifetime.span);
1027     }
1028
1029     fn check_pat(&mut self, cx: &Context, p: &ast::Pat) {
1030         if let &ast::PatIdent(_, ref path1, _) = &p.node {
1031             if let Some(&def::DefLocal(_)) = cx.tcx.def_map.borrow().get(&p.id) {
1032                 self.check_snake_case(cx, "variable", path1.node, p.span);
1033             }
1034         }
1035     }
1036
1037     fn check_struct_def(&mut self, cx: &Context, s: &ast::StructDef,
1038             _: ast::Ident, _: &ast::Generics, _: ast::NodeId) {
1039         for sf in s.fields.iter() {
1040             if let ast::StructField_ { kind: ast::NamedField(ident, _), .. } = sf.node {
1041                 self.check_snake_case(cx, "structure field", ident, sf.span);
1042             }
1043         }
1044     }
1045 }
1046
1047 declare_lint! {
1048     pub NON_UPPER_CASE_GLOBALS,
1049     Warn,
1050     "static constants should have uppercase identifiers"
1051 }
1052
1053 #[derive(Copy)]
1054 pub struct NonUpperCaseGlobals;
1055
1056 impl LintPass for NonUpperCaseGlobals {
1057     fn get_lints(&self) -> LintArray {
1058         lint_array!(NON_UPPER_CASE_GLOBALS)
1059     }
1060
1061     fn check_item(&mut self, cx: &Context, it: &ast::Item) {
1062         match it.node {
1063             // only check static constants
1064             ast::ItemStatic(_, ast::MutImmutable, _) |
1065             ast::ItemConst(..) => {
1066                 let s = token::get_ident(it.ident);
1067                 // check for lowercase letters rather than non-uppercase
1068                 // ones (some scripts don't have a concept of
1069                 // upper/lowercase)
1070                 if s.get().chars().any(|c| c.is_lowercase()) {
1071                     cx.span_lint(NON_UPPER_CASE_GLOBALS, it.span,
1072                         format!("static constant `{}` should have an uppercase name \
1073                                  such as `{}`",
1074                                 s.get(), s.get().chars().map(|c| c.to_uppercase())
1075                                 .collect::<String>()[])[]);
1076                 }
1077             }
1078             _ => {}
1079         }
1080     }
1081
1082     fn check_pat(&mut self, cx: &Context, p: &ast::Pat) {
1083         // Lint for constants that look like binding identifiers (#7526)
1084         match (&p.node, cx.tcx.def_map.borrow().get(&p.id)) {
1085             (&ast::PatIdent(_, ref path1, _), Some(&def::DefConst(..))) => {
1086                 let s = token::get_ident(path1.node);
1087                 if s.get().chars().any(|c| c.is_lowercase()) {
1088                     cx.span_lint(NON_UPPER_CASE_GLOBALS, path1.span,
1089                         format!("static constant in pattern `{}` should have an uppercase \
1090                                  name such as `{}`",
1091                                 s.get(), s.get().chars().map(|c| c.to_uppercase())
1092                                     .collect::<String>()[])[]);
1093                 }
1094             }
1095             _ => {}
1096         }
1097     }
1098 }
1099
1100 declare_lint! {
1101     UNUSED_PARENS,
1102     Warn,
1103     "`if`, `match`, `while` and `return` do not need parentheses"
1104 }
1105
1106 #[derive(Copy)]
1107 pub struct UnusedParens;
1108
1109 impl UnusedParens {
1110     fn check_unused_parens_core(&self, cx: &Context, value: &ast::Expr, msg: &str,
1111                                      struct_lit_needs_parens: bool) {
1112         if let ast::ExprParen(ref inner) = value.node {
1113             let necessary = struct_lit_needs_parens && contains_exterior_struct_lit(&**inner);
1114             if !necessary {
1115                 cx.span_lint(UNUSED_PARENS, value.span,
1116                              format!("unnecessary parentheses around {}",
1117                                      msg)[])
1118             }
1119         }
1120
1121         /// Expressions that syntactically contain an "exterior" struct
1122         /// literal i.e. not surrounded by any parens or other
1123         /// delimiters, e.g. `X { y: 1 }`, `X { y: 1 }.method()`, `foo
1124         /// == X { y: 1 }` and `X { y: 1 } == foo` all do, but `(X {
1125         /// y: 1 }) == foo` does not.
1126         fn contains_exterior_struct_lit(value: &ast::Expr) -> bool {
1127             match value.node {
1128                 ast::ExprStruct(..) => true,
1129
1130                 ast::ExprAssign(ref lhs, ref rhs) |
1131                 ast::ExprAssignOp(_, ref lhs, ref rhs) |
1132                 ast::ExprBinary(_, ref lhs, ref rhs) => {
1133                     // X { y: 1 } + X { y: 2 }
1134                     contains_exterior_struct_lit(&**lhs) ||
1135                         contains_exterior_struct_lit(&**rhs)
1136                 }
1137                 ast::ExprUnary(_, ref x) |
1138                 ast::ExprCast(ref x, _) |
1139                 ast::ExprField(ref x, _) |
1140                 ast::ExprTupField(ref x, _) |
1141                 ast::ExprIndex(ref x, _) => {
1142                     // &X { y: 1 }, X { y: 1 }.y
1143                     contains_exterior_struct_lit(&**x)
1144                 }
1145
1146                 ast::ExprMethodCall(_, _, ref exprs) => {
1147                     // X { y: 1 }.bar(...)
1148                     contains_exterior_struct_lit(&*exprs[0])
1149                 }
1150
1151                 _ => false
1152             }
1153         }
1154     }
1155 }
1156
1157 impl LintPass for UnusedParens {
1158     fn get_lints(&self) -> LintArray {
1159         lint_array!(UNUSED_PARENS)
1160     }
1161
1162     fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
1163         let (value, msg, struct_lit_needs_parens) = match e.node {
1164             ast::ExprIf(ref cond, _, _) => (cond, "`if` condition", true),
1165             ast::ExprWhile(ref cond, _, _) => (cond, "`while` condition", true),
1166             ast::ExprMatch(ref head, _, source) => match source {
1167                 ast::MatchSource::Normal => (head, "`match` head expression", true),
1168                 ast::MatchSource::IfLetDesugar { .. } => (head, "`if let` head expression", true),
1169                 ast::MatchSource::WhileLetDesugar => (head, "`while let` head expression", true),
1170             },
1171             ast::ExprRet(Some(ref value)) => (value, "`return` value", false),
1172             ast::ExprAssign(_, ref value) => (value, "assigned value", false),
1173             ast::ExprAssignOp(_, _, ref value) => (value, "assigned value", false),
1174             _ => return
1175         };
1176         self.check_unused_parens_core(cx, &**value, msg, struct_lit_needs_parens);
1177     }
1178
1179     fn check_stmt(&mut self, cx: &Context, s: &ast::Stmt) {
1180         let (value, msg) = match s.node {
1181             ast::StmtDecl(ref decl, _) => match decl.node {
1182                 ast::DeclLocal(ref local) => match local.init {
1183                     Some(ref value) => (value, "assigned value"),
1184                     None => return
1185                 },
1186                 _ => return
1187             },
1188             _ => return
1189         };
1190         self.check_unused_parens_core(cx, &**value, msg, false);
1191     }
1192 }
1193
1194 declare_lint! {
1195     UNUSED_IMPORT_BRACES,
1196     Allow,
1197     "unnecessary braces around an imported item"
1198 }
1199
1200 #[derive(Copy)]
1201 pub struct UnusedImportBraces;
1202
1203 impl LintPass for UnusedImportBraces {
1204     fn get_lints(&self) -> LintArray {
1205         lint_array!(UNUSED_IMPORT_BRACES)
1206     }
1207
1208     fn check_view_item(&mut self, cx: &Context, view_item: &ast::ViewItem) {
1209         match view_item.node {
1210             ast::ViewItemUse(ref view_path) => {
1211                 match view_path.node {
1212                     ast::ViewPathList(_, ref items, _) => {
1213                         if items.len() == 1 {
1214                             match items[0].node {
1215                                 ast::PathListIdent {ref name, ..} => {
1216                                     let m = format!("braces around {} is unnecessary",
1217                                                     token::get_ident(*name).get());
1218                                     cx.span_lint(UNUSED_IMPORT_BRACES, view_item.span,
1219                                                  m[]);
1220                                 },
1221                                 _ => ()
1222                             }
1223                         }
1224                     }
1225                     _ => ()
1226                 }
1227             },
1228             _ => ()
1229         }
1230     }
1231 }
1232
1233 declare_lint! {
1234     NON_SHORTHAND_FIELD_PATTERNS,
1235     Warn,
1236     "using `Struct { x: x }` instead of `Struct { x }`"
1237 }
1238
1239 #[derive(Copy)]
1240 pub struct NonShorthandFieldPatterns;
1241
1242 impl LintPass for NonShorthandFieldPatterns {
1243     fn get_lints(&self) -> LintArray {
1244         lint_array!(NON_SHORTHAND_FIELD_PATTERNS)
1245     }
1246
1247     fn check_pat(&mut self, cx: &Context, pat: &ast::Pat) {
1248         let def_map = cx.tcx.def_map.borrow();
1249         if let ast::PatStruct(_, ref v, _) = pat.node {
1250             for fieldpat in v.iter()
1251                              .filter(|fieldpat| !fieldpat.node.is_shorthand)
1252                              .filter(|fieldpat| def_map.get(&fieldpat.node.pat.id)
1253                                                 == Some(&def::DefLocal(fieldpat.node.pat.id))) {
1254                 if let ast::PatIdent(_, ident, None) = fieldpat.node.pat.node {
1255                     if ident.node.as_str() == fieldpat.node.ident.as_str() {
1256                         cx.span_lint(NON_SHORTHAND_FIELD_PATTERNS, fieldpat.span,
1257                                      format!("the `{}:` in this pattern is redundant and can \
1258                                               be removed", ident.node.as_str())[])
1259                     }
1260                 }
1261             }
1262         }
1263     }
1264 }
1265
1266 declare_lint! {
1267     pub UNUSED_UNSAFE,
1268     Warn,
1269     "unnecessary use of an `unsafe` block"
1270 }
1271
1272 #[derive(Copy)]
1273 pub struct UnusedUnsafe;
1274
1275 impl LintPass for UnusedUnsafe {
1276     fn get_lints(&self) -> LintArray {
1277         lint_array!(UNUSED_UNSAFE)
1278     }
1279
1280     fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
1281         if let ast::ExprBlock(ref blk) = e.node {
1282             // Don't warn about generated blocks, that'll just pollute the output.
1283             if blk.rules == ast::UnsafeBlock(ast::UserProvided) &&
1284                 !cx.tcx.used_unsafe.borrow().contains(&blk.id) {
1285                     cx.span_lint(UNUSED_UNSAFE, blk.span, "unnecessary `unsafe` block");
1286             }
1287         }
1288     }
1289 }
1290
1291 declare_lint! {
1292     UNSAFE_BLOCKS,
1293     Allow,
1294     "usage of an `unsafe` block"
1295 }
1296
1297 #[derive(Copy)]
1298 pub struct UnsafeBlocks;
1299
1300 impl LintPass for UnsafeBlocks {
1301     fn get_lints(&self) -> LintArray {
1302         lint_array!(UNSAFE_BLOCKS)
1303     }
1304
1305     fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
1306         if let ast::ExprBlock(ref blk) = e.node {
1307             // Don't warn about generated blocks, that'll just pollute the output.
1308             if blk.rules == ast::UnsafeBlock(ast::UserProvided) {
1309                 cx.span_lint(UNSAFE_BLOCKS, blk.span, "usage of an `unsafe` block");
1310             }
1311         }
1312     }
1313 }
1314
1315 declare_lint! {
1316     pub UNUSED_MUT,
1317     Warn,
1318     "detect mut variables which don't need to be mutable"
1319 }
1320
1321 #[derive(Copy)]
1322 pub struct UnusedMut;
1323
1324 impl UnusedMut {
1325     fn check_unused_mut_pat(&self, cx: &Context, pats: &[P<ast::Pat>]) {
1326         // collect all mutable pattern and group their NodeIDs by their Identifier to
1327         // avoid false warnings in match arms with multiple patterns
1328
1329         let mut mutables = FnvHashMap::new();
1330         for p in pats.iter() {
1331             pat_util::pat_bindings(&cx.tcx.def_map, &**p, |mode, id, _, path1| {
1332                 let ident = path1.node;
1333                 if let ast::BindByValue(ast::MutMutable) = mode {
1334                     if !token::get_ident(ident).get().starts_with("_") {
1335                         match mutables.entry(ident.name.uint()) {
1336                             Vacant(entry) => { entry.set(vec![id]); },
1337                             Occupied(mut entry) => { entry.get_mut().push(id); },
1338                         }
1339                     }
1340                 }
1341             });
1342         }
1343
1344         let used_mutables = cx.tcx.used_mut_nodes.borrow();
1345         for (_, v) in mutables.iter() {
1346             if !v.iter().any(|e| used_mutables.contains(e)) {
1347                 cx.span_lint(UNUSED_MUT, cx.tcx.map.span(v[0]),
1348                              "variable does not need to be mutable");
1349             }
1350         }
1351     }
1352 }
1353
1354 impl LintPass for UnusedMut {
1355     fn get_lints(&self) -> LintArray {
1356         lint_array!(UNUSED_MUT)
1357     }
1358
1359     fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
1360         if let ast::ExprMatch(_, ref arms, _) = e.node {
1361             for a in arms.iter() {
1362                 self.check_unused_mut_pat(cx, a.pats[])
1363             }
1364         }
1365     }
1366
1367     fn check_stmt(&mut self, cx: &Context, s: &ast::Stmt) {
1368         if let ast::StmtDecl(ref d, _) = s.node {
1369             if let ast::DeclLocal(ref l) = d.node {
1370                 self.check_unused_mut_pat(cx, slice::ref_slice(&l.pat));
1371             }
1372         }
1373     }
1374
1375     fn check_fn(&mut self, cx: &Context,
1376                 _: visit::FnKind, decl: &ast::FnDecl,
1377                 _: &ast::Block, _: Span, _: ast::NodeId) {
1378         for a in decl.inputs.iter() {
1379             self.check_unused_mut_pat(cx, slice::ref_slice(&a.pat));
1380         }
1381     }
1382 }
1383
1384 declare_lint! {
1385     UNUSED_ALLOCATION,
1386     Warn,
1387     "detects unnecessary allocations that can be eliminated"
1388 }
1389
1390 #[derive(Copy)]
1391 pub struct UnusedAllocation;
1392
1393 impl LintPass for UnusedAllocation {
1394     fn get_lints(&self) -> LintArray {
1395         lint_array!(UNUSED_ALLOCATION)
1396     }
1397
1398     fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
1399         match e.node {
1400             ast::ExprUnary(ast::UnUniq, _) => (),
1401             _ => return
1402         }
1403
1404         if let Some(adjustment) = cx.tcx.adjustments.borrow().get(&e.id) {
1405             if let ty::AdjustDerefRef(ty::AutoDerefRef { ref autoref, .. }) = *adjustment {
1406                 match autoref {
1407                     &Some(ty::AutoPtr(_, ast::MutImmutable, None)) => {
1408                         cx.span_lint(UNUSED_ALLOCATION, e.span,
1409                                      "unnecessary allocation, use & instead");
1410                     }
1411                     &Some(ty::AutoPtr(_, ast::MutMutable, None)) => {
1412                         cx.span_lint(UNUSED_ALLOCATION, e.span,
1413                                      "unnecessary allocation, use &mut instead");
1414                     }
1415                     _ => ()
1416                 }
1417             }
1418         }
1419     }
1420 }
1421
1422 declare_lint! {
1423     MISSING_DOCS,
1424     Allow,
1425     "detects missing documentation for public members"
1426 }
1427
1428 pub struct MissingDoc {
1429     /// Stack of IDs of struct definitions.
1430     struct_def_stack: Vec<ast::NodeId>,
1431
1432     /// True if inside variant definition
1433     in_variant: bool,
1434
1435     /// Stack of whether #[doc(hidden)] is set
1436     /// at each level which has lint attributes.
1437     doc_hidden_stack: Vec<bool>,
1438 }
1439
1440 impl MissingDoc {
1441     pub fn new() -> MissingDoc {
1442         MissingDoc {
1443             struct_def_stack: vec!(),
1444             in_variant: false,
1445             doc_hidden_stack: vec!(false),
1446         }
1447     }
1448
1449     fn doc_hidden(&self) -> bool {
1450         *self.doc_hidden_stack.last().expect("empty doc_hidden_stack")
1451     }
1452
1453     fn check_missing_docs_attrs(&self,
1454                                cx: &Context,
1455                                id: Option<ast::NodeId>,
1456                                attrs: &[ast::Attribute],
1457                                sp: Span,
1458                                desc: &'static str) {
1459         // If we're building a test harness, then warning about
1460         // documentation is probably not really relevant right now.
1461         if cx.sess().opts.test { return }
1462
1463         // `#[doc(hidden)]` disables missing_docs check.
1464         if self.doc_hidden() { return }
1465
1466         // Only check publicly-visible items, using the result from the privacy pass.
1467         // It's an option so the crate root can also use this function (it doesn't
1468         // have a NodeId).
1469         if let Some(ref id) = id {
1470             if !cx.exported_items.contains(id) {
1471                 return;
1472             }
1473         }
1474
1475         let has_doc = attrs.iter().any(|a| {
1476             match a.node.value.node {
1477                 ast::MetaNameValue(ref name, _) if *name == "doc" => true,
1478                 _ => false
1479             }
1480         });
1481         if !has_doc {
1482             cx.span_lint(MISSING_DOCS, sp,
1483                 format!("missing documentation for {}", desc)[]);
1484         }
1485     }
1486 }
1487
1488 impl LintPass for MissingDoc {
1489     fn get_lints(&self) -> LintArray {
1490         lint_array!(MISSING_DOCS)
1491     }
1492
1493     fn enter_lint_attrs(&mut self, _: &Context, attrs: &[ast::Attribute]) {
1494         let doc_hidden = self.doc_hidden() || attrs.iter().any(|attr| {
1495             attr.check_name("doc") && match attr.meta_item_list() {
1496                 None => false,
1497                 Some(l) => attr::contains_name(l[], "hidden"),
1498             }
1499         });
1500         self.doc_hidden_stack.push(doc_hidden);
1501     }
1502
1503     fn exit_lint_attrs(&mut self, _: &Context, _: &[ast::Attribute]) {
1504         self.doc_hidden_stack.pop().expect("empty doc_hidden_stack");
1505     }
1506
1507     fn check_struct_def(&mut self, _: &Context,
1508         _: &ast::StructDef, _: ast::Ident, _: &ast::Generics, id: ast::NodeId) {
1509         self.struct_def_stack.push(id);
1510     }
1511
1512     fn check_struct_def_post(&mut self, _: &Context,
1513         _: &ast::StructDef, _: ast::Ident, _: &ast::Generics, id: ast::NodeId) {
1514         let popped = self.struct_def_stack.pop().expect("empty struct_def_stack");
1515         assert!(popped == id);
1516     }
1517
1518     fn check_crate(&mut self, cx: &Context, krate: &ast::Crate) {
1519         self.check_missing_docs_attrs(cx, None, krate.attrs[],
1520                                      krate.span, "crate");
1521     }
1522
1523     fn check_item(&mut self, cx: &Context, it: &ast::Item) {
1524         let desc = match it.node {
1525             ast::ItemFn(..) => "a function",
1526             ast::ItemMod(..) => "a module",
1527             ast::ItemEnum(..) => "an enum",
1528             ast::ItemStruct(..) => "a struct",
1529             ast::ItemTrait(..) => "a trait",
1530             ast::ItemTy(..) => "a type alias",
1531             _ => return
1532         };
1533         self.check_missing_docs_attrs(cx, Some(it.id), it.attrs[],
1534                                      it.span, desc);
1535     }
1536
1537     fn check_fn(&mut self, cx: &Context,
1538             fk: visit::FnKind, _: &ast::FnDecl,
1539             _: &ast::Block, _: Span, _: ast::NodeId) {
1540         if let visit::FkMethod(_, _, m) = fk {
1541             // If the method is an impl for a trait, don't doc.
1542             if method_context(cx, m) == TraitImpl { return; }
1543
1544             // Otherwise, doc according to privacy. This will also check
1545             // doc for default methods defined on traits.
1546             self.check_missing_docs_attrs(cx, Some(m.id), m.attrs[],
1547                                           m.span, "a method");
1548         }
1549     }
1550
1551     fn check_ty_method(&mut self, cx: &Context, tm: &ast::TypeMethod) {
1552         self.check_missing_docs_attrs(cx, Some(tm.id), tm.attrs[],
1553                                      tm.span, "a type method");
1554     }
1555
1556     fn check_struct_field(&mut self, cx: &Context, sf: &ast::StructField) {
1557         if let ast::NamedField(_, vis) = sf.node.kind {
1558             if vis == ast::Public || self.in_variant {
1559                 let cur_struct_def = *self.struct_def_stack.last()
1560                     .expect("empty struct_def_stack");
1561                 self.check_missing_docs_attrs(cx, Some(cur_struct_def),
1562                                               sf.node.attrs[], sf.span,
1563                                               "a struct field")
1564             }
1565         }
1566     }
1567
1568     fn check_variant(&mut self, cx: &Context, v: &ast::Variant, _: &ast::Generics) {
1569         self.check_missing_docs_attrs(cx, Some(v.node.id), v.node.attrs[],
1570                                      v.span, "a variant");
1571         assert!(!self.in_variant);
1572         self.in_variant = true;
1573     }
1574
1575     fn check_variant_post(&mut self, _: &Context, _: &ast::Variant, _: &ast::Generics) {
1576         assert!(self.in_variant);
1577         self.in_variant = false;
1578     }
1579 }
1580
1581 #[derive(Copy)]
1582 pub struct MissingCopyImplementations;
1583
1584 impl LintPass for MissingCopyImplementations {
1585     fn get_lints(&self) -> LintArray {
1586         lint_array!(MISSING_COPY_IMPLEMENTATIONS)
1587     }
1588
1589     fn check_item(&mut self, cx: &Context, item: &ast::Item) {
1590         if !cx.exported_items.contains(&item.id) {
1591             return
1592         }
1593         if cx.tcx
1594              .destructor_for_type
1595              .borrow()
1596              .contains_key(&ast_util::local_def(item.id)) {
1597             return
1598         }
1599         let ty = match item.node {
1600             ast::ItemStruct(_, ref ast_generics) => {
1601                 if ast_generics.is_parameterized() {
1602                     return
1603                 }
1604                 ty::mk_struct(cx.tcx,
1605                               ast_util::local_def(item.id),
1606                               cx.tcx.mk_substs(Substs::empty()))
1607             }
1608             ast::ItemEnum(_, ref ast_generics) => {
1609                 if ast_generics.is_parameterized() {
1610                     return
1611                 }
1612                 ty::mk_enum(cx.tcx,
1613                             ast_util::local_def(item.id),
1614                             cx.tcx.mk_substs(Substs::empty()))
1615             }
1616             _ => return,
1617         };
1618         let parameter_environment = ty::empty_parameter_environment(cx.tcx);
1619         if !ty::type_moves_by_default(&parameter_environment, item.span, ty) {
1620             return
1621         }
1622         if ty::can_type_implement_copy(&parameter_environment, item.span, ty).is_ok() {
1623             cx.span_lint(MISSING_COPY_IMPLEMENTATIONS,
1624                          item.span,
1625                          "type could implement `Copy`; consider adding `impl \
1626                           Copy`")
1627         }
1628     }
1629 }
1630
1631 declare_lint! {
1632     DEPRECATED,
1633     Warn,
1634     "detects use of #[deprecated] items"
1635 }
1636
1637 // FIXME #6875: Change to Warn after std library stabilization is complete
1638 declare_lint! {
1639     EXPERIMENTAL,
1640     Allow,
1641     "detects use of #[experimental] items"
1642 }
1643
1644 declare_lint! {
1645     UNSTABLE,
1646     Allow,
1647     "detects use of #[unstable] items (incl. items with no stability attribute)"
1648 }
1649
1650 /// Checks for use of items with `#[deprecated]`, `#[experimental]` and
1651 /// `#[unstable]` attributes, or no stability attribute.
1652 #[derive(Copy)]
1653 pub struct Stability;
1654
1655 impl Stability {
1656     fn lint(&self, cx: &Context, id: ast::DefId, span: Span) {
1657         let stability = stability::lookup(cx.tcx, id);
1658         let cross_crate = !ast_util::is_local(id);
1659
1660         // stability attributes are promises made across crates; only
1661         // check DEPRECATED for crate-local usage.
1662         let (lint, label) = match stability {
1663             // no stability attributes == Unstable
1664             None if cross_crate => (UNSTABLE, "unmarked"),
1665             Some(attr::Stability { level: attr::Unstable, .. }) if cross_crate =>
1666                 (UNSTABLE, "unstable"),
1667             Some(attr::Stability { level: attr::Experimental, .. }) if cross_crate =>
1668                 (EXPERIMENTAL, "experimental"),
1669             Some(attr::Stability { level: attr::Deprecated, .. }) =>
1670                 (DEPRECATED, "deprecated"),
1671             _ => return
1672         };
1673
1674         let msg = match stability {
1675             Some(attr::Stability { text: Some(ref s), .. }) => {
1676                 format!("use of {} item: {}", label, *s)
1677             }
1678             _ => format!("use of {} item", label)
1679         };
1680
1681         cx.span_lint(lint, span, msg[]);
1682     }
1683
1684     fn is_internal(&self, cx: &Context, span: Span) -> bool {
1685         cx.tcx.sess.codemap().span_is_internal(span)
1686     }
1687 }
1688
1689 impl LintPass for Stability {
1690     fn get_lints(&self) -> LintArray {
1691         lint_array!(DEPRECATED, EXPERIMENTAL, UNSTABLE)
1692     }
1693
1694     fn check_view_item(&mut self, cx: &Context, item: &ast::ViewItem) {
1695         // compiler-generated `extern crate` statements have a dummy span.
1696         if item.span == DUMMY_SP { return }
1697
1698         let id = match item.node {
1699             ast::ViewItemExternCrate(_, _, id) => id,
1700             ast::ViewItemUse(..) => return,
1701         };
1702         let cnum = match cx.tcx.sess.cstore.find_extern_mod_stmt_cnum(id) {
1703             Some(cnum) => cnum,
1704             None => return,
1705         };
1706         let id = ast::DefId { krate: cnum, node: ast::CRATE_NODE_ID };
1707         self.lint(cx, id, item.span);
1708     }
1709
1710     fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
1711         if self.is_internal(cx, e.span) { return; }
1712
1713         let mut span = e.span;
1714
1715         let id = match e.node {
1716             ast::ExprPath(..) | ast::ExprStruct(..) => {
1717                 match cx.tcx.def_map.borrow().get(&e.id) {
1718                     Some(&def) => def.def_id(),
1719                     None => return
1720                 }
1721             }
1722             ast::ExprMethodCall(i, _, _) => {
1723                 span = i.span;
1724                 let method_call = ty::MethodCall::expr(e.id);
1725                 match cx.tcx.method_map.borrow().get(&method_call) {
1726                     Some(method) => {
1727                         match method.origin {
1728                             ty::MethodStatic(def_id) => {
1729                                 def_id
1730                             }
1731                             ty::MethodStaticUnboxedClosure(def_id) => {
1732                                 def_id
1733                             }
1734                             ty::MethodTypeParam(ty::MethodParam {
1735                                 ref trait_ref,
1736                                 method_num: index,
1737                                 ..
1738                             }) |
1739                             ty::MethodTraitObject(ty::MethodObject {
1740                                 ref trait_ref,
1741                                 method_num: index,
1742                                 ..
1743                             }) => {
1744                                 ty::trait_item(cx.tcx, trait_ref.def_id, index).def_id()
1745                             }
1746                         }
1747                     }
1748                     None => return
1749                 }
1750             }
1751             _ => return
1752         };
1753         self.lint(cx, id, span);
1754     }
1755
1756     fn check_item(&mut self, cx: &Context, item: &ast::Item) {
1757         if self.is_internal(cx, item.span) { return }
1758
1759         match item.node {
1760             ast::ItemTrait(_, _, ref supertraits, _) => {
1761                 for t in supertraits.iter() {
1762                     if let ast::TraitTyParamBound(ref t, _) = *t {
1763                         let id = ty::trait_ref_to_def_id(cx.tcx, &t.trait_ref);
1764                         self.lint(cx, id, t.trait_ref.path.span);
1765                     }
1766                 }
1767             }
1768             ast::ItemImpl(_, _, Some(ref t), _, _) => {
1769                 let id = ty::trait_ref_to_def_id(cx.tcx, t);
1770                 self.lint(cx, id, t.path.span);
1771             }
1772             _ => (/* pass */)
1773         }
1774     }
1775 }
1776
1777 declare_lint! {
1778     pub UNUSED_IMPORTS,
1779     Warn,
1780     "imports that are never used"
1781 }
1782
1783 declare_lint! {
1784     pub UNUSED_EXTERN_CRATES,
1785     Allow,
1786     "extern crates that are never used"
1787 }
1788
1789 declare_lint! {
1790     pub UNUSED_QUALIFICATIONS,
1791     Allow,
1792     "detects unnecessarily qualified names"
1793 }
1794
1795 declare_lint! {
1796     pub UNKNOWN_LINTS,
1797     Warn,
1798     "unrecognized lint attribute"
1799 }
1800
1801 declare_lint! {
1802     pub UNUSED_VARIABLES,
1803     Warn,
1804     "detect variables which are not used in any way"
1805 }
1806
1807 declare_lint! {
1808     pub UNUSED_ASSIGNMENTS,
1809     Warn,
1810     "detect assignments that will never be read"
1811 }
1812
1813 declare_lint! {
1814     pub DEAD_CODE,
1815     Warn,
1816     "detect unused, unexported items"
1817 }
1818
1819 declare_lint! {
1820     pub UNREACHABLE_CODE,
1821     Warn,
1822     "detects unreachable code paths"
1823 }
1824
1825 declare_lint! {
1826     pub WARNINGS,
1827     Warn,
1828     "mass-change the level for lints which produce warnings"
1829 }
1830
1831 declare_lint! {
1832     pub UNKNOWN_FEATURES,
1833     Deny,
1834     "unknown features found in crate-level #[feature] directives"
1835 }
1836
1837 declare_lint! {
1838     pub UNKNOWN_CRATE_TYPES,
1839     Deny,
1840     "unknown crate type found in #[crate_type] directive"
1841 }
1842
1843 declare_lint! {
1844     pub VARIANT_SIZE_DIFFERENCES,
1845     Allow,
1846     "detects enums with widely varying variant sizes"
1847 }
1848
1849 declare_lint! {
1850     pub FAT_PTR_TRANSMUTES,
1851     Allow,
1852     "detects transmutes of fat pointers"
1853 }
1854
1855 declare_lint!{
1856     pub MISSING_COPY_IMPLEMENTATIONS,
1857     Warn,
1858     "detects potentially-forgotten implementations of `Copy`"
1859 }
1860
1861 /// Does nothing as a lint pass, but registers some `Lint`s
1862 /// which are used by other parts of the compiler.
1863 #[derive(Copy)]
1864 pub struct HardwiredLints;
1865
1866 impl LintPass for HardwiredLints {
1867     fn get_lints(&self) -> LintArray {
1868         lint_array!(
1869             UNUSED_IMPORTS,
1870             UNUSED_EXTERN_CRATES,
1871             UNUSED_QUALIFICATIONS,
1872             UNKNOWN_LINTS,
1873             UNUSED_VARIABLES,
1874             UNUSED_ASSIGNMENTS,
1875             DEAD_CODE,
1876             UNREACHABLE_CODE,
1877             WARNINGS,
1878             UNKNOWN_FEATURES,
1879             UNKNOWN_CRATE_TYPES,
1880             VARIANT_SIZE_DIFFERENCES,
1881             FAT_PTR_TRANSMUTES
1882         )
1883     }
1884 }