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