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