]> git.lizzy.rs Git - rust.git/blob - src/librustc/lint/builtin.rs
rollup merge of #21151: brson/beta
[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, Lint};
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::{TyIs, TyUs, 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 let ast::TyIs(_) = t {
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 let ast::TyUs(_) = t {
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::TyIs(_) =>    (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::TyUs(_) =>   (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::TyIs(_) =>    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::TyUs(_) =>    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::TyIs(_))) => {
408                 self.cx.span_lint(IMPROPER_CTYPES, sp,
409                                   "found rust type `isize` in foreign module, while \
410                                    libc::c_int or libc::c_long should be used");
411             }
412             def::DefPrimTy(ast::TyUint(ast::TyUs(_))) => {
413                 self.cx.span_lint(IMPROPER_CTYPES, sp,
414                                   "found rust type `usize` 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                     n_uniq += 1;
499                 }
500
501                 _ => ()
502             };
503             t
504         });
505
506         if n_uniq > 0 {
507             let s = ty_to_string(cx.tcx, ty);
508             let m = format!("type uses owned (Box type) pointers: {}", s);
509             cx.span_lint(BOX_POINTERS, span, &m[]);
510         }
511     }
512 }
513
514 impl LintPass for BoxPointers {
515     fn get_lints(&self) -> LintArray {
516         lint_array!(BOX_POINTERS)
517     }
518
519     fn check_item(&mut self, cx: &Context, it: &ast::Item) {
520         match it.node {
521             ast::ItemFn(..) |
522             ast::ItemTy(..) |
523             ast::ItemEnum(..) |
524             ast::ItemStruct(..) =>
525                 self.check_heap_type(cx, it.span,
526                                      ty::node_id_to_type(cx.tcx, it.id)),
527             _ => ()
528         }
529
530         // If it's a struct, we also have to check the fields' types
531         match it.node {
532             ast::ItemStruct(ref struct_def, _) => {
533                 for struct_field in struct_def.fields.iter() {
534                     self.check_heap_type(cx, struct_field.span,
535                                          ty::node_id_to_type(cx.tcx, struct_field.node.id));
536                 }
537             }
538             _ => ()
539         }
540     }
541
542     fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
543         let ty = ty::expr_ty(cx.tcx, e);
544         self.check_heap_type(cx, e.span, ty);
545     }
546 }
547
548 declare_lint! {
549     RAW_POINTER_DERIVE,
550     Warn,
551     "uses of #[derive] with raw pointers are rarely correct"
552 }
553
554 struct RawPtrDeriveVisitor<'a, 'tcx: 'a> {
555     cx: &'a Context<'a, 'tcx>
556 }
557
558 impl<'a, 'tcx, 'v> Visitor<'v> for RawPtrDeriveVisitor<'a, 'tcx> {
559     fn visit_ty(&mut self, ty: &ast::Ty) {
560         static MSG: &'static str = "use of `#[derive]` with a raw pointer";
561         if let ast::TyPtr(..) = ty.node {
562             self.cx.span_lint(RAW_POINTER_DERIVE, ty.span, MSG);
563         }
564         visit::walk_ty(self, ty);
565     }
566     // explicit override to a no-op to reduce code bloat
567     fn visit_expr(&mut self, _: &ast::Expr) {}
568     fn visit_block(&mut self, _: &ast::Block) {}
569 }
570
571 pub struct RawPointerDerive {
572     checked_raw_pointers: NodeSet,
573 }
574
575 impl RawPointerDerive {
576     pub fn new() -> RawPointerDerive {
577         RawPointerDerive {
578             checked_raw_pointers: NodeSet::new(),
579         }
580     }
581 }
582
583 impl LintPass for RawPointerDerive {
584     fn get_lints(&self) -> LintArray {
585         lint_array!(RAW_POINTER_DERIVE)
586     }
587
588     fn check_item(&mut self, cx: &Context, item: &ast::Item) {
589         if !attr::contains_name(&item.attrs[], "automatically_derived") {
590             return
591         }
592         let did = match item.node {
593             ast::ItemImpl(..) => {
594                 match ty::node_id_to_type(cx.tcx, item.id).sty {
595                     ty::ty_enum(did, _) => did,
596                     ty::ty_struct(did, _) => did,
597                     _ => return,
598                 }
599             }
600             _ => return,
601         };
602         if !ast_util::is_local(did) { return }
603         let item = match cx.tcx.map.find(did.node) {
604             Some(ast_map::NodeItem(item)) => item,
605             _ => return,
606         };
607         if !self.checked_raw_pointers.insert(item.id) { return }
608         match item.node {
609             ast::ItemStruct(..) | ast::ItemEnum(..) => {
610                 let mut visitor = RawPtrDeriveVisitor { cx: cx };
611                 visit::walk_item(&mut visitor, &*item);
612             }
613             _ => {}
614         }
615     }
616 }
617
618 declare_lint! {
619     UNUSED_ATTRIBUTES,
620     Warn,
621     "detects attributes that were not used by the compiler"
622 }
623
624 #[derive(Copy)]
625 pub struct UnusedAttributes;
626
627 impl LintPass for UnusedAttributes {
628     fn get_lints(&self) -> LintArray {
629         lint_array!(UNUSED_ATTRIBUTES)
630     }
631
632     fn check_attribute(&mut self, cx: &Context, attr: &ast::Attribute) {
633         static ATTRIBUTE_WHITELIST: &'static [&'static str] = &[
634             // FIXME: #14408 whitelist docs since rustdoc looks at them
635             "doc",
636
637             // FIXME: #14406 these are processed in trans, which happens after the
638             // lint pass
639             "cold",
640             "export_name",
641             "inline",
642             "link",
643             "link_name",
644             "link_section",
645             "linkage",
646             "no_builtins",
647             "no_mangle",
648             "no_split_stack",
649             "no_stack_check",
650             "packed",
651             "static_assert",
652             "thread_local",
653             "no_debug",
654             "omit_gdb_pretty_printer_section",
655             "unsafe_no_drop_flag",
656
657             // used in resolve
658             "prelude_import",
659
660             // FIXME: #14407 these are only looked at on-demand so we can't
661             // guarantee they'll have already been checked
662             "deprecated",
663             "experimental",
664             "frozen",
665             "locked",
666             "must_use",
667             "stable",
668             "unstable",
669             "rustc_on_unimplemented",
670
671             // FIXME: #19470 this shouldn't be needed forever
672             "old_orphan_check",
673             "old_impl_check",
674         ];
675
676         static CRATE_ATTRS: &'static [&'static str] = &[
677             "crate_name",
678             "crate_type",
679             "feature",
680             "no_start",
681             "no_main",
682             "no_std",
683             "no_builtins",
684         ];
685
686         for &name in ATTRIBUTE_WHITELIST.iter() {
687             if attr.check_name(name) {
688                 break;
689             }
690         }
691
692         if !attr::is_used(attr) {
693             cx.span_lint(UNUSED_ATTRIBUTES, attr.span, "unused attribute");
694             if CRATE_ATTRS.contains(&attr.name().get()) {
695                 let msg = match attr.node.style {
696                     ast::AttrOuter => "crate-level attribute should be an inner \
697                                        attribute: add an exclamation mark: #![foo]",
698                     ast::AttrInner => "crate-level attribute should be in the \
699                                        root module",
700                 };
701                 cx.span_lint(UNUSED_ATTRIBUTES, attr.span, msg);
702             }
703         }
704     }
705 }
706
707 declare_lint! {
708     pub PATH_STATEMENTS,
709     Warn,
710     "path statements with no effect"
711 }
712
713 #[derive(Copy)]
714 pub struct PathStatements;
715
716 impl LintPass for PathStatements {
717     fn get_lints(&self) -> LintArray {
718         lint_array!(PATH_STATEMENTS)
719     }
720
721     fn check_stmt(&mut self, cx: &Context, s: &ast::Stmt) {
722         match s.node {
723             ast::StmtSemi(ref expr, _) => {
724                 match expr.node {
725                     ast::ExprPath(_) => cx.span_lint(PATH_STATEMENTS, s.span,
726                                                      "path statement with no effect"),
727                     _ => ()
728                 }
729             }
730             _ => ()
731         }
732     }
733 }
734
735 declare_lint! {
736     pub UNUSED_MUST_USE,
737     Warn,
738     "unused result of a type flagged as #[must_use]"
739 }
740
741 declare_lint! {
742     pub UNUSED_RESULTS,
743     Allow,
744     "unused result of an expression in a statement"
745 }
746
747 #[derive(Copy)]
748 pub struct UnusedResults;
749
750 impl LintPass for UnusedResults {
751     fn get_lints(&self) -> LintArray {
752         lint_array!(UNUSED_MUST_USE, UNUSED_RESULTS)
753     }
754
755     fn check_stmt(&mut self, cx: &Context, s: &ast::Stmt) {
756         let expr = match s.node {
757             ast::StmtSemi(ref expr, _) => &**expr,
758             _ => return
759         };
760
761         if let ast::ExprRet(..) = expr.node {
762             return;
763         }
764
765         let t = ty::expr_ty(cx.tcx, expr);
766         let mut warned = false;
767         match t.sty {
768             ty::ty_tup(ref tys) if tys.is_empty() => return,
769             ty::ty_bool => return,
770             ty::ty_struct(did, _) |
771             ty::ty_enum(did, _) => {
772                 if ast_util::is_local(did) {
773                     if let ast_map::NodeItem(it) = cx.tcx.map.get(did.node) {
774                         warned |= check_must_use(cx, &it.attrs[], s.span);
775                     }
776                 } else {
777                     let attrs = csearch::get_item_attrs(&cx.sess().cstore, did);
778                     warned |= check_must_use(cx, &attrs[], s.span);
779                 }
780             }
781             _ => {}
782         }
783         if !warned {
784             cx.span_lint(UNUSED_RESULTS, s.span, "unused result");
785         }
786
787         fn check_must_use(cx: &Context, attrs: &[ast::Attribute], sp: Span) -> bool {
788             for attr in attrs.iter() {
789                 if attr.check_name("must_use") {
790                     let mut msg = "unused result which must be used".to_string();
791                     // check for #[must_use="..."]
792                     match attr.value_str() {
793                         None => {}
794                         Some(s) => {
795                             msg.push_str(": ");
796                             msg.push_str(s.get());
797                         }
798                     }
799                     cx.span_lint(UNUSED_MUST_USE, sp, &msg[]);
800                     return true;
801                 }
802             }
803             false
804         }
805     }
806 }
807
808 declare_lint! {
809     pub NON_CAMEL_CASE_TYPES,
810     Warn,
811     "types, variants, traits and type parameters should have camel case names"
812 }
813
814 #[derive(Copy)]
815 pub struct NonCamelCaseTypes;
816
817 impl NonCamelCaseTypes {
818     fn check_case(&self, cx: &Context, sort: &str, ident: ast::Ident, span: Span) {
819         fn is_camel_case(ident: ast::Ident) -> bool {
820             let ident = token::get_ident(ident);
821             if ident.get().is_empty() { return true; }
822             let ident = ident.get().trim_matches('_');
823
824             // start with a non-lowercase letter rather than non-uppercase
825             // ones (some scripts don't have a concept of upper/lowercase)
826             ident.len() > 0 && !ident.char_at(0).is_lowercase() && !ident.contains_char('_')
827         }
828
829         fn to_camel_case(s: &str) -> String {
830             s.split('_').flat_map(|word| word.chars().enumerate().map(|(i, c)|
831                 if i == 0 { c.to_uppercase() }
832                 else { c }
833             )).collect()
834         }
835
836         let s = token::get_ident(ident);
837
838         if !is_camel_case(ident) {
839             let c = to_camel_case(s.get());
840             let m = if c.is_empty() {
841                 format!("{} `{}` should have a camel case name such as `CamelCase`", sort, s)
842             } else {
843                 format!("{} `{}` should have a camel case name such as `{}`", sort, s, c)
844             };
845             cx.span_lint(NON_CAMEL_CASE_TYPES, span, &m[]);
846         }
847     }
848 }
849
850 impl LintPass for NonCamelCaseTypes {
851     fn get_lints(&self) -> LintArray {
852         lint_array!(NON_CAMEL_CASE_TYPES)
853     }
854
855     fn check_item(&mut self, cx: &Context, it: &ast::Item) {
856         let has_extern_repr = it.attrs.iter().map(|attr| {
857             attr::find_repr_attrs(cx.tcx.sess.diagnostic(), attr).iter()
858                 .any(|r| r == &attr::ReprExtern)
859         }).any(|x| x);
860         if has_extern_repr { return }
861
862         match it.node {
863             ast::ItemTy(..) | ast::ItemStruct(..) => {
864                 self.check_case(cx, "type", it.ident, it.span)
865             }
866             ast::ItemTrait(..) => {
867                 self.check_case(cx, "trait", it.ident, it.span)
868             }
869             ast::ItemEnum(ref enum_definition, _) => {
870                 if has_extern_repr { return }
871                 self.check_case(cx, "type", it.ident, it.span);
872                 for variant in enum_definition.variants.iter() {
873                     self.check_case(cx, "variant", variant.node.name, variant.span);
874                 }
875             }
876             _ => ()
877         }
878     }
879
880     fn check_generics(&mut self, cx: &Context, it: &ast::Generics) {
881         for gen in it.ty_params.iter() {
882             self.check_case(cx, "type parameter", gen.ident, gen.span);
883         }
884     }
885 }
886
887 #[derive(PartialEq)]
888 enum MethodContext {
889     TraitDefaultImpl,
890     TraitImpl,
891     PlainImpl
892 }
893
894 fn method_context(cx: &Context, m: &ast::Method) -> MethodContext {
895     let did = ast::DefId {
896         krate: ast::LOCAL_CRATE,
897         node: m.id
898     };
899
900     match cx.tcx.impl_or_trait_items.borrow().get(&did).cloned() {
901         None => cx.sess().span_bug(m.span, "missing method descriptor?!"),
902         Some(md) => {
903             match md {
904                 ty::MethodTraitItem(md) => {
905                     match md.container {
906                         ty::TraitContainer(..) => TraitDefaultImpl,
907                         ty::ImplContainer(cid) => {
908                             match ty::impl_trait_ref(cx.tcx, cid) {
909                                 Some(..) => TraitImpl,
910                                 None => PlainImpl
911                             }
912                         }
913                     }
914                 }
915                 ty::TypeTraitItem(typedef) => {
916                     match typedef.container {
917                         ty::TraitContainer(..) => TraitDefaultImpl,
918                         ty::ImplContainer(cid) => {
919                             match ty::impl_trait_ref(cx.tcx, cid) {
920                                 Some(..) => TraitImpl,
921                                 None => PlainImpl
922                             }
923                         }
924                     }
925                 }
926             }
927         }
928     }
929 }
930
931 declare_lint! {
932     pub NON_SNAKE_CASE,
933     Warn,
934     "methods, functions, lifetime parameters and modules should have snake case names"
935 }
936
937 #[derive(Copy)]
938 pub struct NonSnakeCase;
939
940 impl NonSnakeCase {
941     fn check_snake_case(&self, cx: &Context, sort: &str, ident: ast::Ident, span: Span) {
942         fn is_snake_case(ident: ast::Ident) -> bool {
943             let ident = token::get_ident(ident);
944             if ident.get().is_empty() { return true; }
945             let ident = ident.get().trim_left_matches('\'');
946             let ident = ident.trim_matches('_');
947
948             let mut allow_underscore = true;
949             ident.chars().all(|c| {
950                 allow_underscore = match c {
951                     c if c.is_lowercase() || c.is_numeric() => true,
952                     '_' if allow_underscore => false,
953                     _ => return false,
954                 };
955                 true
956             })
957         }
958
959         fn to_snake_case(str: &str) -> String {
960             let mut words = vec![];
961             for s in str.split('_') {
962                 let mut last_upper = false;
963                 let mut buf = String::new();
964                 if s.is_empty() { continue; }
965                 for ch in s.chars() {
966                     if !buf.is_empty() && buf != "'"
967                                        && ch.is_uppercase()
968                                        && !last_upper {
969                         words.push(buf);
970                         buf = String::new();
971                     }
972                     last_upper = ch.is_uppercase();
973                     buf.push(ch.to_lowercase());
974                 }
975                 words.push(buf);
976             }
977             words.connect("_")
978         }
979
980         let s = token::get_ident(ident);
981
982         if !is_snake_case(ident) {
983             cx.span_lint(NON_SNAKE_CASE, span,
984                 &format!("{} `{}` should have a snake case name such as `{}`",
985                         sort, s, to_snake_case(s.get()))[]);
986         }
987     }
988 }
989
990 impl LintPass for NonSnakeCase {
991     fn get_lints(&self) -> LintArray {
992         lint_array!(NON_SNAKE_CASE)
993     }
994
995     fn check_fn(&mut self, cx: &Context,
996                 fk: visit::FnKind, _: &ast::FnDecl,
997                 _: &ast::Block, span: Span, _: ast::NodeId) {
998         match fk {
999             visit::FkMethod(ident, _, m) => match method_context(cx, m) {
1000                 PlainImpl
1001                     => self.check_snake_case(cx, "method", ident, span),
1002                 TraitDefaultImpl
1003                     => self.check_snake_case(cx, "trait method", ident, span),
1004                 _ => (),
1005             },
1006             visit::FkItemFn(ident, _, _, _)
1007                 => self.check_snake_case(cx, "function", ident, span),
1008             _ => (),
1009         }
1010     }
1011
1012     fn check_item(&mut self, cx: &Context, it: &ast::Item) {
1013         if let ast::ItemMod(_) = it.node {
1014             self.check_snake_case(cx, "module", it.ident, it.span);
1015         }
1016     }
1017
1018     fn check_ty_method(&mut self, cx: &Context, t: &ast::TypeMethod) {
1019         self.check_snake_case(cx, "trait method", t.ident, t.span);
1020     }
1021
1022     fn check_lifetime_def(&mut self, cx: &Context, t: &ast::LifetimeDef) {
1023         self.check_snake_case(cx, "lifetime", t.lifetime.name.ident(), t.lifetime.span);
1024     }
1025
1026     fn check_pat(&mut self, cx: &Context, p: &ast::Pat) {
1027         if let &ast::PatIdent(_, ref path1, _) = &p.node {
1028             if let Some(&def::DefLocal(_)) = cx.tcx.def_map.borrow().get(&p.id) {
1029                 self.check_snake_case(cx, "variable", path1.node, p.span);
1030             }
1031         }
1032     }
1033
1034     fn check_struct_def(&mut self, cx: &Context, s: &ast::StructDef,
1035             _: ast::Ident, _: &ast::Generics, _: ast::NodeId) {
1036         for sf in s.fields.iter() {
1037             if let ast::StructField_ { kind: ast::NamedField(ident, _), .. } = sf.node {
1038                 self.check_snake_case(cx, "structure field", ident, sf.span);
1039             }
1040         }
1041     }
1042 }
1043
1044 declare_lint! {
1045     pub NON_UPPER_CASE_GLOBALS,
1046     Warn,
1047     "static constants should have uppercase identifiers"
1048 }
1049
1050 #[derive(Copy)]
1051 pub struct NonUpperCaseGlobals;
1052
1053 impl LintPass for NonUpperCaseGlobals {
1054     fn get_lints(&self) -> LintArray {
1055         lint_array!(NON_UPPER_CASE_GLOBALS)
1056     }
1057
1058     fn check_item(&mut self, cx: &Context, it: &ast::Item) {
1059         match it.node {
1060             // only check static constants
1061             ast::ItemStatic(_, ast::MutImmutable, _) |
1062             ast::ItemConst(..) => {
1063                 let s = token::get_ident(it.ident);
1064                 // check for lowercase letters rather than non-uppercase
1065                 // ones (some scripts don't have a concept of
1066                 // upper/lowercase)
1067                 if s.get().chars().any(|c| c.is_lowercase()) {
1068                     cx.span_lint(NON_UPPER_CASE_GLOBALS, it.span,
1069                         &format!("static constant `{}` should have an uppercase name \
1070                                  such as `{}`",
1071                                 s.get(), &s.get().chars().map(|c| c.to_uppercase())
1072                                 .collect::<String>()[])[]);
1073                 }
1074             }
1075             _ => {}
1076         }
1077     }
1078
1079     fn check_pat(&mut self, cx: &Context, p: &ast::Pat) {
1080         // Lint for constants that look like binding identifiers (#7526)
1081         match (&p.node, cx.tcx.def_map.borrow().get(&p.id)) {
1082             (&ast::PatIdent(_, ref path1, _), Some(&def::DefConst(..))) => {
1083                 let s = token::get_ident(path1.node);
1084                 if s.get().chars().any(|c| c.is_lowercase()) {
1085                     cx.span_lint(NON_UPPER_CASE_GLOBALS, path1.span,
1086                         &format!("static constant in pattern `{}` should have an uppercase \
1087                                  name such as `{}`",
1088                                 s.get(), &s.get().chars().map(|c| c.to_uppercase())
1089                                     .collect::<String>()[])[]);
1090                 }
1091             }
1092             _ => {}
1093         }
1094     }
1095 }
1096
1097 declare_lint! {
1098     UNUSED_PARENS,
1099     Warn,
1100     "`if`, `match`, `while` and `return` do not need parentheses"
1101 }
1102
1103 #[derive(Copy)]
1104 pub struct UnusedParens;
1105
1106 impl UnusedParens {
1107     fn check_unused_parens_core(&self, cx: &Context, value: &ast::Expr, msg: &str,
1108                                      struct_lit_needs_parens: bool) {
1109         if let ast::ExprParen(ref inner) = value.node {
1110             let necessary = struct_lit_needs_parens && contains_exterior_struct_lit(&**inner);
1111             if !necessary {
1112                 cx.span_lint(UNUSED_PARENS, value.span,
1113                              &format!("unnecessary parentheses around {}",
1114                                      msg)[])
1115             }
1116         }
1117
1118         /// Expressions that syntactically contain an "exterior" struct
1119         /// literal i.e. not surrounded by any parens or other
1120         /// delimiters, e.g. `X { y: 1 }`, `X { y: 1 }.method()`, `foo
1121         /// == X { y: 1 }` and `X { y: 1 } == foo` all do, but `(X {
1122         /// y: 1 }) == foo` does not.
1123         fn contains_exterior_struct_lit(value: &ast::Expr) -> bool {
1124             match value.node {
1125                 ast::ExprStruct(..) => true,
1126
1127                 ast::ExprAssign(ref lhs, ref rhs) |
1128                 ast::ExprAssignOp(_, ref lhs, ref rhs) |
1129                 ast::ExprBinary(_, ref lhs, ref rhs) => {
1130                     // X { y: 1 } + X { y: 2 }
1131                     contains_exterior_struct_lit(&**lhs) ||
1132                         contains_exterior_struct_lit(&**rhs)
1133                 }
1134                 ast::ExprUnary(_, ref x) |
1135                 ast::ExprCast(ref x, _) |
1136                 ast::ExprField(ref x, _) |
1137                 ast::ExprTupField(ref x, _) |
1138                 ast::ExprIndex(ref x, _) => {
1139                     // &X { y: 1 }, X { y: 1 }.y
1140                     contains_exterior_struct_lit(&**x)
1141                 }
1142
1143                 ast::ExprMethodCall(_, _, ref exprs) => {
1144                     // X { y: 1 }.bar(...)
1145                     contains_exterior_struct_lit(&*exprs[0])
1146                 }
1147
1148                 _ => false
1149             }
1150         }
1151     }
1152 }
1153
1154 impl LintPass for UnusedParens {
1155     fn get_lints(&self) -> LintArray {
1156         lint_array!(UNUSED_PARENS)
1157     }
1158
1159     fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
1160         let (value, msg, struct_lit_needs_parens) = match e.node {
1161             ast::ExprIf(ref cond, _, _) => (cond, "`if` condition", true),
1162             ast::ExprWhile(ref cond, _, _) => (cond, "`while` condition", true),
1163             ast::ExprMatch(ref head, _, source) => match source {
1164                 ast::MatchSource::Normal => (head, "`match` head expression", true),
1165                 ast::MatchSource::IfLetDesugar { .. } => (head, "`if let` head expression", true),
1166                 ast::MatchSource::WhileLetDesugar => (head, "`while let` head expression", true),
1167             },
1168             ast::ExprRet(Some(ref value)) => (value, "`return` value", false),
1169             ast::ExprAssign(_, ref value) => (value, "assigned value", false),
1170             ast::ExprAssignOp(_, _, ref value) => (value, "assigned value", false),
1171             _ => return
1172         };
1173         self.check_unused_parens_core(cx, &**value, msg, struct_lit_needs_parens);
1174     }
1175
1176     fn check_stmt(&mut self, cx: &Context, s: &ast::Stmt) {
1177         let (value, msg) = match s.node {
1178             ast::StmtDecl(ref decl, _) => match decl.node {
1179                 ast::DeclLocal(ref local) => match local.init {
1180                     Some(ref value) => (value, "assigned value"),
1181                     None => return
1182                 },
1183                 _ => return
1184             },
1185             _ => return
1186         };
1187         self.check_unused_parens_core(cx, &**value, msg, false);
1188     }
1189 }
1190
1191 declare_lint! {
1192     UNUSED_IMPORT_BRACES,
1193     Allow,
1194     "unnecessary braces around an imported item"
1195 }
1196
1197 #[derive(Copy)]
1198 pub struct UnusedImportBraces;
1199
1200 impl LintPass for UnusedImportBraces {
1201     fn get_lints(&self) -> LintArray {
1202         lint_array!(UNUSED_IMPORT_BRACES)
1203     }
1204
1205     fn check_view_item(&mut self, cx: &Context, view_item: &ast::ViewItem) {
1206         match view_item.node {
1207             ast::ViewItemUse(ref view_path) => {
1208                 match view_path.node {
1209                     ast::ViewPathList(_, ref items, _) => {
1210                         if items.len() == 1 {
1211                             match items[0].node {
1212                                 ast::PathListIdent {ref name, ..} => {
1213                                     let m = format!("braces around {} is unnecessary",
1214                                                     token::get_ident(*name).get());
1215                                     cx.span_lint(UNUSED_IMPORT_BRACES, view_item.span,
1216                                                  &m[]);
1217                                 },
1218                                 _ => ()
1219                             }
1220                         }
1221                     }
1222                     _ => ()
1223                 }
1224             },
1225             _ => ()
1226         }
1227     }
1228 }
1229
1230 declare_lint! {
1231     NON_SHORTHAND_FIELD_PATTERNS,
1232     Warn,
1233     "using `Struct { x: x }` instead of `Struct { x }`"
1234 }
1235
1236 #[derive(Copy)]
1237 pub struct NonShorthandFieldPatterns;
1238
1239 impl LintPass for NonShorthandFieldPatterns {
1240     fn get_lints(&self) -> LintArray {
1241         lint_array!(NON_SHORTHAND_FIELD_PATTERNS)
1242     }
1243
1244     fn check_pat(&mut self, cx: &Context, pat: &ast::Pat) {
1245         let def_map = cx.tcx.def_map.borrow();
1246         if let ast::PatStruct(_, ref v, _) = pat.node {
1247             for fieldpat in v.iter()
1248                              .filter(|fieldpat| !fieldpat.node.is_shorthand)
1249                              .filter(|fieldpat| def_map.get(&fieldpat.node.pat.id)
1250                                                 == Some(&def::DefLocal(fieldpat.node.pat.id))) {
1251                 if let ast::PatIdent(_, ident, None) = fieldpat.node.pat.node {
1252                     if ident.node.as_str() == fieldpat.node.ident.as_str() {
1253                         cx.span_lint(NON_SHORTHAND_FIELD_PATTERNS, fieldpat.span,
1254                                      &format!("the `{}:` in this pattern is redundant and can \
1255                                               be removed", ident.node.as_str())[])
1256                     }
1257                 }
1258             }
1259         }
1260     }
1261 }
1262
1263 declare_lint! {
1264     pub UNUSED_UNSAFE,
1265     Warn,
1266     "unnecessary use of an `unsafe` block"
1267 }
1268
1269 #[derive(Copy)]
1270 pub struct UnusedUnsafe;
1271
1272 impl LintPass for UnusedUnsafe {
1273     fn get_lints(&self) -> LintArray {
1274         lint_array!(UNUSED_UNSAFE)
1275     }
1276
1277     fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
1278         if let ast::ExprBlock(ref blk) = e.node {
1279             // Don't warn about generated blocks, that'll just pollute the output.
1280             if blk.rules == ast::UnsafeBlock(ast::UserProvided) &&
1281                 !cx.tcx.used_unsafe.borrow().contains(&blk.id) {
1282                     cx.span_lint(UNUSED_UNSAFE, blk.span, "unnecessary `unsafe` block");
1283             }
1284         }
1285     }
1286 }
1287
1288 declare_lint! {
1289     UNSAFE_BLOCKS,
1290     Allow,
1291     "usage of an `unsafe` block"
1292 }
1293
1294 #[derive(Copy)]
1295 pub struct UnsafeBlocks;
1296
1297 impl LintPass for UnsafeBlocks {
1298     fn get_lints(&self) -> LintArray {
1299         lint_array!(UNSAFE_BLOCKS)
1300     }
1301
1302     fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
1303         if let ast::ExprBlock(ref blk) = e.node {
1304             // Don't warn about generated blocks, that'll just pollute the output.
1305             if blk.rules == ast::UnsafeBlock(ast::UserProvided) {
1306                 cx.span_lint(UNSAFE_BLOCKS, blk.span, "usage of an `unsafe` block");
1307             }
1308         }
1309     }
1310 }
1311
1312 declare_lint! {
1313     pub UNUSED_MUT,
1314     Warn,
1315     "detect mut variables which don't need to be mutable"
1316 }
1317
1318 #[derive(Copy)]
1319 pub struct UnusedMut;
1320
1321 impl UnusedMut {
1322     fn check_unused_mut_pat(&self, cx: &Context, pats: &[P<ast::Pat>]) {
1323         // collect all mutable pattern and group their NodeIDs by their Identifier to
1324         // avoid false warnings in match arms with multiple patterns
1325
1326         let mut mutables = FnvHashMap::new();
1327         for p in pats.iter() {
1328             pat_util::pat_bindings(&cx.tcx.def_map, &**p, |mode, id, _, path1| {
1329                 let ident = path1.node;
1330                 if let ast::BindByValue(ast::MutMutable) = mode {
1331                     if !token::get_ident(ident).get().starts_with("_") {
1332                         match mutables.entry(ident.name.uint()) {
1333                             Vacant(entry) => { entry.insert(vec![id]); },
1334                             Occupied(mut entry) => { entry.get_mut().push(id); },
1335                         }
1336                     }
1337                 }
1338             });
1339         }
1340
1341         let used_mutables = cx.tcx.used_mut_nodes.borrow();
1342         for (_, v) in mutables.iter() {
1343             if !v.iter().any(|e| used_mutables.contains(e)) {
1344                 cx.span_lint(UNUSED_MUT, cx.tcx.map.span(v[0]),
1345                              "variable does not need to be mutable");
1346             }
1347         }
1348     }
1349 }
1350
1351 impl LintPass for UnusedMut {
1352     fn get_lints(&self) -> LintArray {
1353         lint_array!(UNUSED_MUT)
1354     }
1355
1356     fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
1357         if let ast::ExprMatch(_, ref arms, _) = e.node {
1358             for a in arms.iter() {
1359                 self.check_unused_mut_pat(cx, &a.pats[])
1360             }
1361         }
1362     }
1363
1364     fn check_stmt(&mut self, cx: &Context, s: &ast::Stmt) {
1365         if let ast::StmtDecl(ref d, _) = s.node {
1366             if let ast::DeclLocal(ref l) = d.node {
1367                 self.check_unused_mut_pat(cx, slice::ref_slice(&l.pat));
1368             }
1369         }
1370     }
1371
1372     fn check_fn(&mut self, cx: &Context,
1373                 _: visit::FnKind, decl: &ast::FnDecl,
1374                 _: &ast::Block, _: Span, _: ast::NodeId) {
1375         for a in decl.inputs.iter() {
1376             self.check_unused_mut_pat(cx, slice::ref_slice(&a.pat));
1377         }
1378     }
1379 }
1380
1381 declare_lint! {
1382     UNUSED_ALLOCATION,
1383     Warn,
1384     "detects unnecessary allocations that can be eliminated"
1385 }
1386
1387 #[derive(Copy)]
1388 pub struct UnusedAllocation;
1389
1390 impl LintPass for UnusedAllocation {
1391     fn get_lints(&self) -> LintArray {
1392         lint_array!(UNUSED_ALLOCATION)
1393     }
1394
1395     fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
1396         match e.node {
1397             ast::ExprUnary(ast::UnUniq, _) => (),
1398             _ => return
1399         }
1400
1401         if let Some(adjustment) = cx.tcx.adjustments.borrow().get(&e.id) {
1402             if let ty::AdjustDerefRef(ty::AutoDerefRef { ref autoref, .. }) = *adjustment {
1403                 match autoref {
1404                     &Some(ty::AutoPtr(_, ast::MutImmutable, None)) => {
1405                         cx.span_lint(UNUSED_ALLOCATION, e.span,
1406                                      "unnecessary allocation, use & instead");
1407                     }
1408                     &Some(ty::AutoPtr(_, ast::MutMutable, None)) => {
1409                         cx.span_lint(UNUSED_ALLOCATION, e.span,
1410                                      "unnecessary allocation, use &mut instead");
1411                     }
1412                     _ => ()
1413                 }
1414             }
1415         }
1416     }
1417 }
1418
1419 declare_lint! {
1420     MISSING_DOCS,
1421     Allow,
1422     "detects missing documentation for public members"
1423 }
1424
1425 pub struct MissingDoc {
1426     /// Stack of IDs of struct definitions.
1427     struct_def_stack: Vec<ast::NodeId>,
1428
1429     /// True if inside variant definition
1430     in_variant: bool,
1431
1432     /// Stack of whether #[doc(hidden)] is set
1433     /// at each level which has lint attributes.
1434     doc_hidden_stack: Vec<bool>,
1435 }
1436
1437 impl MissingDoc {
1438     pub fn new() -> MissingDoc {
1439         MissingDoc {
1440             struct_def_stack: vec!(),
1441             in_variant: false,
1442             doc_hidden_stack: vec!(false),
1443         }
1444     }
1445
1446     fn doc_hidden(&self) -> bool {
1447         *self.doc_hidden_stack.last().expect("empty doc_hidden_stack")
1448     }
1449
1450     fn check_missing_docs_attrs(&self,
1451                                cx: &Context,
1452                                id: Option<ast::NodeId>,
1453                                attrs: &[ast::Attribute],
1454                                sp: Span,
1455                                desc: &'static str) {
1456         // If we're building a test harness, then warning about
1457         // documentation is probably not really relevant right now.
1458         if cx.sess().opts.test { return }
1459
1460         // `#[doc(hidden)]` disables missing_docs check.
1461         if self.doc_hidden() { return }
1462
1463         // Only check publicly-visible items, using the result from the privacy pass.
1464         // It's an option so the crate root can also use this function (it doesn't
1465         // have a NodeId).
1466         if let Some(ref id) = id {
1467             if !cx.exported_items.contains(id) {
1468                 return;
1469             }
1470         }
1471
1472         let has_doc = attrs.iter().any(|a| {
1473             match a.node.value.node {
1474                 ast::MetaNameValue(ref name, _) if *name == "doc" => true,
1475                 _ => false
1476             }
1477         });
1478         if !has_doc {
1479             cx.span_lint(MISSING_DOCS, sp,
1480                 &format!("missing documentation for {}", desc)[]);
1481         }
1482     }
1483 }
1484
1485 impl LintPass for MissingDoc {
1486     fn get_lints(&self) -> LintArray {
1487         lint_array!(MISSING_DOCS)
1488     }
1489
1490     fn enter_lint_attrs(&mut self, _: &Context, attrs: &[ast::Attribute]) {
1491         let doc_hidden = self.doc_hidden() || attrs.iter().any(|attr| {
1492             attr.check_name("doc") && match attr.meta_item_list() {
1493                 None => false,
1494                 Some(l) => attr::contains_name(&l[], "hidden"),
1495             }
1496         });
1497         self.doc_hidden_stack.push(doc_hidden);
1498     }
1499
1500     fn exit_lint_attrs(&mut self, _: &Context, _: &[ast::Attribute]) {
1501         self.doc_hidden_stack.pop().expect("empty doc_hidden_stack");
1502     }
1503
1504     fn check_struct_def(&mut self, _: &Context,
1505         _: &ast::StructDef, _: ast::Ident, _: &ast::Generics, id: ast::NodeId) {
1506         self.struct_def_stack.push(id);
1507     }
1508
1509     fn check_struct_def_post(&mut self, _: &Context,
1510         _: &ast::StructDef, _: ast::Ident, _: &ast::Generics, id: ast::NodeId) {
1511         let popped = self.struct_def_stack.pop().expect("empty struct_def_stack");
1512         assert!(popped == id);
1513     }
1514
1515     fn check_crate(&mut self, cx: &Context, krate: &ast::Crate) {
1516         self.check_missing_docs_attrs(cx, None, &krate.attrs[],
1517                                      krate.span, "crate");
1518     }
1519
1520     fn check_item(&mut self, cx: &Context, it: &ast::Item) {
1521         let desc = match it.node {
1522             ast::ItemFn(..) => "a function",
1523             ast::ItemMod(..) => "a module",
1524             ast::ItemEnum(..) => "an enum",
1525             ast::ItemStruct(..) => "a struct",
1526             ast::ItemTrait(..) => "a trait",
1527             ast::ItemTy(..) => "a type alias",
1528             _ => return
1529         };
1530         self.check_missing_docs_attrs(cx, Some(it.id), &it.attrs[],
1531                                      it.span, desc);
1532     }
1533
1534     fn check_fn(&mut self, cx: &Context,
1535             fk: visit::FnKind, _: &ast::FnDecl,
1536             _: &ast::Block, _: Span, _: ast::NodeId) {
1537         if let visit::FkMethod(_, _, m) = fk {
1538             // If the method is an impl for a trait, don't doc.
1539             if method_context(cx, m) == TraitImpl { return; }
1540
1541             // Otherwise, doc according to privacy. This will also check
1542             // doc for default methods defined on traits.
1543             self.check_missing_docs_attrs(cx, Some(m.id), &m.attrs[],
1544                                           m.span, "a method");
1545         }
1546     }
1547
1548     fn check_ty_method(&mut self, cx: &Context, tm: &ast::TypeMethod) {
1549         self.check_missing_docs_attrs(cx, Some(tm.id), &tm.attrs[],
1550                                      tm.span, "a type method");
1551     }
1552
1553     fn check_struct_field(&mut self, cx: &Context, sf: &ast::StructField) {
1554         if let ast::NamedField(_, vis) = sf.node.kind {
1555             if vis == ast::Public || self.in_variant {
1556                 let cur_struct_def = *self.struct_def_stack.last()
1557                     .expect("empty struct_def_stack");
1558                 self.check_missing_docs_attrs(cx, Some(cur_struct_def),
1559                                               &sf.node.attrs[], sf.span,
1560                                               "a struct field")
1561             }
1562         }
1563     }
1564
1565     fn check_variant(&mut self, cx: &Context, v: &ast::Variant, _: &ast::Generics) {
1566         self.check_missing_docs_attrs(cx, Some(v.node.id), &v.node.attrs[],
1567                                      v.span, "a variant");
1568         assert!(!self.in_variant);
1569         self.in_variant = true;
1570     }
1571
1572     fn check_variant_post(&mut self, _: &Context, _: &ast::Variant, _: &ast::Generics) {
1573         assert!(self.in_variant);
1574         self.in_variant = false;
1575     }
1576 }
1577
1578 #[derive(Copy)]
1579 pub struct MissingCopyImplementations;
1580
1581 impl LintPass for MissingCopyImplementations {
1582     fn get_lints(&self) -> LintArray {
1583         lint_array!(MISSING_COPY_IMPLEMENTATIONS)
1584     }
1585
1586     fn check_item(&mut self, cx: &Context, item: &ast::Item) {
1587         if !cx.exported_items.contains(&item.id) {
1588             return
1589         }
1590         if cx.tcx
1591              .destructor_for_type
1592              .borrow()
1593              .contains_key(&ast_util::local_def(item.id)) {
1594             return
1595         }
1596         let ty = match item.node {
1597             ast::ItemStruct(_, ref ast_generics) => {
1598                 if ast_generics.is_parameterized() {
1599                     return
1600                 }
1601                 ty::mk_struct(cx.tcx,
1602                               ast_util::local_def(item.id),
1603                               cx.tcx.mk_substs(Substs::empty()))
1604             }
1605             ast::ItemEnum(_, ref ast_generics) => {
1606                 if ast_generics.is_parameterized() {
1607                     return
1608                 }
1609                 ty::mk_enum(cx.tcx,
1610                             ast_util::local_def(item.id),
1611                             cx.tcx.mk_substs(Substs::empty()))
1612             }
1613             _ => return,
1614         };
1615         let parameter_environment = ty::empty_parameter_environment(cx.tcx);
1616         if !ty::type_moves_by_default(&parameter_environment, item.span, ty) {
1617             return
1618         }
1619         if ty::can_type_implement_copy(&parameter_environment, item.span, ty).is_ok() {
1620             cx.span_lint(MISSING_COPY_IMPLEMENTATIONS,
1621                          item.span,
1622                          "type could implement `Copy`; consider adding `impl \
1623                           Copy`")
1624         }
1625     }
1626 }
1627
1628 declare_lint! {
1629     DEPRECATED,
1630     Warn,
1631     "detects use of #[deprecated] items"
1632 }
1633
1634 declare_lint! {
1635     UNSTABLE,
1636     Warn,
1637     "detects use of #[unstable] items (incl. items with no stability attribute)"
1638 }
1639
1640 /// Checks for use of items with `#[deprecated]`, `#[unstable]` and
1641 /// `#[unstable]` attributes, or no stability attribute.
1642 #[derive(Copy)]
1643 pub struct Stability { this_crate_staged: bool }
1644
1645 impl Stability {
1646     pub fn new() -> Stability { Stability { this_crate_staged: false } }
1647
1648     fn lint(&self, cx: &Context, id: ast::DefId, span: Span) {
1649
1650         let ref stability = stability::lookup(cx.tcx, id);
1651         let cross_crate = !ast_util::is_local(id);
1652         let staged = (!cross_crate && self.this_crate_staged)
1653             || (cross_crate && stability::is_staged_api(cx.tcx, id));
1654
1655         if !staged { return }
1656
1657         // stability attributes are promises made across crates; only
1658         // check DEPRECATED for crate-local usage.
1659         let (lint, label) = match *stability {
1660             // no stability attributes == Unstable
1661             None if cross_crate => (UNSTABLE, "unmarked"),
1662             Some(attr::Stability { level: attr::Unstable, .. }) if cross_crate =>
1663                 (UNSTABLE, "unstable"),
1664             Some(attr::Stability { level: attr::Deprecated, .. }) =>
1665                 (DEPRECATED, "deprecated"),
1666             _ => return
1667         };
1668
1669         output(cx, span, stability, lint, label);
1670
1671         fn output(cx: &Context, span: Span, stability: &Option<attr::Stability>,
1672                   lint: &'static Lint, label: &'static str) {
1673             let msg = match *stability {
1674                 Some(attr::Stability { text: Some(ref s), .. }) => {
1675                     format!("use of {} item: {}", label, *s)
1676                 }
1677                 _ => format!("use of {} item", label)
1678             };
1679
1680             cx.span_lint(lint, span, &msg[]);
1681         }
1682     }
1683
1684
1685     fn is_internal(&self, cx: &Context, span: Span) -> bool {
1686         cx.tcx.sess.codemap().span_is_internal(span)
1687     }
1688
1689 }
1690
1691 impl LintPass for Stability {
1692     fn get_lints(&self) -> LintArray {
1693         lint_array!(DEPRECATED, UNSTABLE)
1694     }
1695
1696     fn check_crate(&mut self, _: &Context, c: &ast::Crate) {
1697         // Just mark the #[staged_api] attribute used, though nothing else is done
1698         // with it during this pass over the source.
1699         for attr in c.attrs.iter() {
1700             if attr.name().get() == "staged_api" {
1701                 match attr.node.value.node {
1702                     ast::MetaWord(_) => {
1703                         attr::mark_used(attr);
1704                         self.this_crate_staged = true;
1705                     }
1706                     _ => (/*pass*/)
1707                 }
1708             }
1709         }
1710     }
1711
1712     fn check_view_item(&mut self, cx: &Context, item: &ast::ViewItem) {
1713         // compiler-generated `extern crate` statements have a dummy span.
1714         if item.span == DUMMY_SP { return }
1715
1716         let id = match item.node {
1717             ast::ViewItemExternCrate(_, _, id) => id,
1718             ast::ViewItemUse(..) => return,
1719         };
1720         let cnum = match cx.tcx.sess.cstore.find_extern_mod_stmt_cnum(id) {
1721             Some(cnum) => cnum,
1722             None => return,
1723         };
1724         let id = ast::DefId { krate: cnum, node: ast::CRATE_NODE_ID };
1725         self.lint(cx, id, item.span);
1726     }
1727
1728     fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
1729         if self.is_internal(cx, e.span) { return; }
1730
1731         let mut span = e.span;
1732
1733         let id = match e.node {
1734             ast::ExprPath(..) | ast::ExprQPath(..) | ast::ExprStruct(..) => {
1735                 match cx.tcx.def_map.borrow().get(&e.id) {
1736                     Some(&def) => def.def_id(),
1737                     None => return
1738                 }
1739             }
1740             ast::ExprMethodCall(i, _, _) => {
1741                 span = i.span;
1742                 let method_call = ty::MethodCall::expr(e.id);
1743                 match cx.tcx.method_map.borrow().get(&method_call) {
1744                     Some(method) => {
1745                         match method.origin {
1746                             ty::MethodStatic(def_id) => {
1747                                 def_id
1748                             }
1749                             ty::MethodStaticUnboxedClosure(def_id) => {
1750                                 def_id
1751                             }
1752                             ty::MethodTypeParam(ty::MethodParam {
1753                                 ref trait_ref,
1754                                 method_num: index,
1755                                 ..
1756                             }) |
1757                             ty::MethodTraitObject(ty::MethodObject {
1758                                 ref trait_ref,
1759                                 method_num: index,
1760                                 ..
1761                             }) => {
1762                                 ty::trait_item(cx.tcx, trait_ref.def_id, index).def_id()
1763                             }
1764                         }
1765                     }
1766                     None => return
1767                 }
1768             }
1769             _ => return
1770         };
1771
1772         self.lint(cx, id, span);
1773     }
1774
1775     fn check_item(&mut self, cx: &Context, item: &ast::Item) {
1776         if self.is_internal(cx, item.span) { return }
1777
1778         match item.node {
1779             ast::ItemTrait(_, _, ref supertraits, _) => {
1780                 for t in supertraits.iter() {
1781                     if let ast::TraitTyParamBound(ref t, _) = *t {
1782                         let id = ty::trait_ref_to_def_id(cx.tcx, &t.trait_ref);
1783                         self.lint(cx, id, t.trait_ref.path.span);
1784                     }
1785                 }
1786             }
1787             ast::ItemImpl(_, _, _, Some(ref t), _, _) => {
1788                 let id = ty::trait_ref_to_def_id(cx.tcx, t);
1789                 self.lint(cx, id, t.path.span);
1790             }
1791             _ => (/* pass */)
1792         }
1793     }
1794 }
1795
1796 declare_lint! {
1797     pub UNUSED_IMPORTS,
1798     Warn,
1799     "imports that are never used"
1800 }
1801
1802 declare_lint! {
1803     pub UNUSED_EXTERN_CRATES,
1804     Allow,
1805     "extern crates that are never used"
1806 }
1807
1808 declare_lint! {
1809     pub UNUSED_QUALIFICATIONS,
1810     Allow,
1811     "detects unnecessarily qualified names"
1812 }
1813
1814 declare_lint! {
1815     pub UNKNOWN_LINTS,
1816     Warn,
1817     "unrecognized lint attribute"
1818 }
1819
1820 declare_lint! {
1821     pub UNUSED_VARIABLES,
1822     Warn,
1823     "detect variables which are not used in any way"
1824 }
1825
1826 declare_lint! {
1827     pub UNUSED_ASSIGNMENTS,
1828     Warn,
1829     "detect assignments that will never be read"
1830 }
1831
1832 declare_lint! {
1833     pub DEAD_CODE,
1834     Warn,
1835     "detect unused, unexported items"
1836 }
1837
1838 declare_lint! {
1839     pub UNREACHABLE_CODE,
1840     Warn,
1841     "detects unreachable code paths"
1842 }
1843
1844 declare_lint! {
1845     pub WARNINGS,
1846     Warn,
1847     "mass-change the level for lints which produce warnings"
1848 }
1849
1850 declare_lint! {
1851     pub UNKNOWN_FEATURES,
1852     Deny,
1853     "unknown features found in crate-level #[feature] directives"
1854 }
1855
1856 declare_lint! {
1857     pub UNKNOWN_CRATE_TYPES,
1858     Deny,
1859     "unknown crate type found in #[crate_type] directive"
1860 }
1861
1862 declare_lint! {
1863     pub VARIANT_SIZE_DIFFERENCES,
1864     Allow,
1865     "detects enums with widely varying variant sizes"
1866 }
1867
1868 declare_lint! {
1869     pub FAT_PTR_TRANSMUTES,
1870     Allow,
1871     "detects transmutes of fat pointers"
1872 }
1873
1874 declare_lint! {
1875     pub MISSING_COPY_IMPLEMENTATIONS,
1876     Warn,
1877     "detects potentially-forgotten implementations of `Copy`"
1878 }
1879
1880 /// Does nothing as a lint pass, but registers some `Lint`s
1881 /// which are used by other parts of the compiler.
1882 #[derive(Copy)]
1883 pub struct HardwiredLints;
1884
1885 impl LintPass for HardwiredLints {
1886     fn get_lints(&self) -> LintArray {
1887         lint_array!(
1888             UNUSED_IMPORTS,
1889             UNUSED_EXTERN_CRATES,
1890             UNUSED_QUALIFICATIONS,
1891             UNKNOWN_LINTS,
1892             UNUSED_VARIABLES,
1893             UNUSED_ASSIGNMENTS,
1894             DEAD_CODE,
1895             UNREACHABLE_CODE,
1896             WARNINGS,
1897             UNKNOWN_FEATURES,
1898             UNKNOWN_CRATE_TYPES,
1899             VARIANT_SIZE_DIFFERENCES,
1900             FAT_PTR_TRANSMUTES
1901         )
1902     }
1903 }
1904
1905 /// Forbids using the `#[feature(...)]` attribute
1906 #[derive(Copy)]
1907 pub struct UnstableFeatures;
1908
1909 declare_lint!(UNSTABLE_FEATURES, Allow,
1910               "enabling unstable features");
1911
1912 impl LintPass for UnstableFeatures {
1913     fn get_lints(&self) -> LintArray {
1914         lint_array!(UNSTABLE_FEATURES)
1915     }
1916     fn check_attribute(&mut self, ctx: &Context, attr: &ast::Attribute) {
1917         use syntax::attr;
1918         if attr::contains_name(&[attr.node.value.clone()], "feature") {
1919             ctx.span_lint(UNSTABLE_FEATURES, attr.span, "unstable feature");
1920         }
1921     }
1922 }