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