]> git.lizzy.rs Git - rust.git/blob - src/librustc/lint/builtin.rs
Auto merge of #20373 - huonw:self-call-lint, r=luqmana
[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, DUMMY_SP};
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() {
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 = 0i;
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             "experimental",
666             "frozen",
667             "locked",
668             "must_use",
669             "stable",
670             "unstable",
671             "rustc_on_unimplemented",
672
673             // FIXME: #19470 this shouldn't be needed forever
674             "old_orphan_check",
675             "old_impl_check",
676         ];
677
678         static CRATE_ATTRS: &'static [&'static str] = &[
679             "crate_name",
680             "crate_type",
681             "feature",
682             "no_start",
683             "no_main",
684             "no_std",
685             "no_builtins",
686         ];
687
688         for &name in ATTRIBUTE_WHITELIST.iter() {
689             if attr.check_name(name) {
690                 break;
691             }
692         }
693
694         if !attr::is_used(attr) {
695             cx.span_lint(UNUSED_ATTRIBUTES, attr.span, "unused attribute");
696             if CRATE_ATTRS.contains(&attr.name().get()) {
697                 let msg = match attr.node.style {
698                     ast::AttrOuter => "crate-level attribute should be an inner \
699                                        attribute: add an exclamation mark: #![foo]",
700                     ast::AttrInner => "crate-level attribute should be in the \
701                                        root module",
702                 };
703                 cx.span_lint(UNUSED_ATTRIBUTES, attr.span, msg);
704             }
705         }
706     }
707 }
708
709 declare_lint! {
710     pub PATH_STATEMENTS,
711     Warn,
712     "path statements with no effect"
713 }
714
715 #[derive(Copy)]
716 pub struct PathStatements;
717
718 impl LintPass for PathStatements {
719     fn get_lints(&self) -> LintArray {
720         lint_array!(PATH_STATEMENTS)
721     }
722
723     fn check_stmt(&mut self, cx: &Context, s: &ast::Stmt) {
724         match s.node {
725             ast::StmtSemi(ref expr, _) => {
726                 match expr.node {
727                     ast::ExprPath(_) => cx.span_lint(PATH_STATEMENTS, s.span,
728                                                      "path statement with no effect"),
729                     _ => ()
730                 }
731             }
732             _ => ()
733         }
734     }
735 }
736
737 declare_lint! {
738     pub UNUSED_MUST_USE,
739     Warn,
740     "unused result of a type flagged as #[must_use]"
741 }
742
743 declare_lint! {
744     pub UNUSED_RESULTS,
745     Allow,
746     "unused result of an expression in a statement"
747 }
748
749 #[derive(Copy)]
750 pub struct UnusedResults;
751
752 impl LintPass for UnusedResults {
753     fn get_lints(&self) -> LintArray {
754         lint_array!(UNUSED_MUST_USE, UNUSED_RESULTS)
755     }
756
757     fn check_stmt(&mut self, cx: &Context, s: &ast::Stmt) {
758         let expr = match s.node {
759             ast::StmtSemi(ref expr, _) => &**expr,
760             _ => return
761         };
762
763         if let ast::ExprRet(..) = expr.node {
764             return;
765         }
766
767         let t = ty::expr_ty(cx.tcx, expr);
768         let mut warned = false;
769         match t.sty {
770             ty::ty_tup(ref tys) if tys.is_empty() => return,
771             ty::ty_bool => return,
772             ty::ty_struct(did, _) |
773             ty::ty_enum(did, _) => {
774                 if ast_util::is_local(did) {
775                     if let ast_map::NodeItem(it) = cx.tcx.map.get(did.node) {
776                         warned |= check_must_use(cx, &it.attrs[], s.span);
777                     }
778                 } else {
779                     let attrs = csearch::get_item_attrs(&cx.sess().cstore, did);
780                     warned |= check_must_use(cx, &attrs[], s.span);
781                 }
782             }
783             _ => {}
784         }
785         if !warned {
786             cx.span_lint(UNUSED_RESULTS, s.span, "unused result");
787         }
788
789         fn check_must_use(cx: &Context, attrs: &[ast::Attribute], sp: Span) -> bool {
790             for attr in attrs.iter() {
791                 if attr.check_name("must_use") {
792                     let mut msg = "unused result which must be used".to_string();
793                     // check for #[must_use="..."]
794                     match attr.value_str() {
795                         None => {}
796                         Some(s) => {
797                             msg.push_str(": ");
798                             msg.push_str(s.get());
799                         }
800                     }
801                     cx.span_lint(UNUSED_MUST_USE, sp, &msg[]);
802                     return true;
803                 }
804             }
805             false
806         }
807     }
808 }
809
810 declare_lint! {
811     pub NON_CAMEL_CASE_TYPES,
812     Warn,
813     "types, variants, traits and type parameters should have camel case names"
814 }
815
816 #[derive(Copy)]
817 pub struct NonCamelCaseTypes;
818
819 impl NonCamelCaseTypes {
820     fn check_case(&self, cx: &Context, sort: &str, ident: ast::Ident, span: Span) {
821         fn is_camel_case(ident: ast::Ident) -> bool {
822             let ident = token::get_ident(ident);
823             if ident.get().is_empty() { return true; }
824             let ident = ident.get().trim_matches('_');
825
826             // start with a non-lowercase letter rather than non-uppercase
827             // ones (some scripts don't have a concept of upper/lowercase)
828             ident.len() > 0 && !ident.char_at(0).is_lowercase() && !ident.contains_char('_')
829         }
830
831         fn to_camel_case(s: &str) -> String {
832             s.split('_').flat_map(|word| word.chars().enumerate().map(|(i, c)|
833                 if i == 0 { c.to_uppercase() }
834                 else { c }
835             )).collect()
836         }
837
838         let s = token::get_ident(ident);
839
840         if !is_camel_case(ident) {
841             let c = to_camel_case(s.get());
842             let m = if c.is_empty() {
843                 format!("{} `{}` should have a camel case name such as `CamelCase`", sort, s)
844             } else {
845                 format!("{} `{}` should have a camel case name such as `{}`", sort, s, c)
846             };
847             cx.span_lint(NON_CAMEL_CASE_TYPES, span, &m[]);
848         }
849     }
850 }
851
852 impl LintPass for NonCamelCaseTypes {
853     fn get_lints(&self) -> LintArray {
854         lint_array!(NON_CAMEL_CASE_TYPES)
855     }
856
857     fn check_item(&mut self, cx: &Context, it: &ast::Item) {
858         let has_extern_repr = it.attrs.iter().map(|attr| {
859             attr::find_repr_attrs(cx.tcx.sess.diagnostic(), attr).iter()
860                 .any(|r| r == &attr::ReprExtern)
861         }).any(|x| x);
862         if has_extern_repr { return }
863
864         match it.node {
865             ast::ItemTy(..) | ast::ItemStruct(..) => {
866                 self.check_case(cx, "type", it.ident, it.span)
867             }
868             ast::ItemTrait(..) => {
869                 self.check_case(cx, "trait", it.ident, it.span)
870             }
871             ast::ItemEnum(ref enum_definition, _) => {
872                 if has_extern_repr { return }
873                 self.check_case(cx, "type", it.ident, it.span);
874                 for variant in enum_definition.variants.iter() {
875                     self.check_case(cx, "variant", variant.node.name, variant.span);
876                 }
877             }
878             _ => ()
879         }
880     }
881
882     fn check_generics(&mut self, cx: &Context, it: &ast::Generics) {
883         for gen in it.ty_params.iter() {
884             self.check_case(cx, "type parameter", gen.ident, gen.span);
885         }
886     }
887 }
888
889 #[derive(PartialEq)]
890 enum MethodContext {
891     TraitDefaultImpl,
892     TraitImpl,
893     PlainImpl
894 }
895
896 fn method_context(cx: &Context, m: &ast::Method) -> MethodContext {
897     let did = ast::DefId {
898         krate: ast::LOCAL_CRATE,
899         node: m.id
900     };
901
902     match cx.tcx.impl_or_trait_items.borrow().get(&did).cloned() {
903         None => cx.sess().span_bug(m.span, "missing method descriptor?!"),
904         Some(md) => {
905             match md {
906                 ty::MethodTraitItem(md) => {
907                     match md.container {
908                         ty::TraitContainer(..) => TraitDefaultImpl,
909                         ty::ImplContainer(cid) => {
910                             match ty::impl_trait_ref(cx.tcx, cid) {
911                                 Some(..) => TraitImpl,
912                                 None => PlainImpl
913                             }
914                         }
915                     }
916                 }
917                 ty::TypeTraitItem(typedef) => {
918                     match typedef.container {
919                         ty::TraitContainer(..) => TraitDefaultImpl,
920                         ty::ImplContainer(cid) => {
921                             match ty::impl_trait_ref(cx.tcx, cid) {
922                                 Some(..) => TraitImpl,
923                                 None => PlainImpl
924                             }
925                         }
926                     }
927                 }
928             }
929         }
930     }
931 }
932
933 declare_lint! {
934     pub NON_SNAKE_CASE,
935     Warn,
936     "methods, functions, lifetime parameters and modules should have snake case names"
937 }
938
939 #[derive(Copy)]
940 pub struct NonSnakeCase;
941
942 impl NonSnakeCase {
943     fn check_snake_case(&self, cx: &Context, sort: &str, ident: ast::Ident, span: Span) {
944         fn is_snake_case(ident: ast::Ident) -> bool {
945             let ident = token::get_ident(ident);
946             if ident.get().is_empty() { return true; }
947             let ident = ident.get().trim_left_matches('\'');
948             let ident = ident.trim_matches('_');
949
950             let mut allow_underscore = true;
951             ident.chars().all(|c| {
952                 allow_underscore = match c {
953                     c if c.is_lowercase() || c.is_numeric() => true,
954                     '_' if allow_underscore => false,
955                     _ => return false,
956                 };
957                 true
958             })
959         }
960
961         fn to_snake_case(str: &str) -> String {
962             let mut words = vec![];
963             for s in str.split('_') {
964                 let mut last_upper = false;
965                 let mut buf = String::new();
966                 if s.is_empty() { continue; }
967                 for ch in s.chars() {
968                     if !buf.is_empty() && buf != "'"
969                                        && ch.is_uppercase()
970                                        && !last_upper {
971                         words.push(buf);
972                         buf = String::new();
973                     }
974                     last_upper = ch.is_uppercase();
975                     buf.push(ch.to_lowercase());
976                 }
977                 words.push(buf);
978             }
979             words.connect("_")
980         }
981
982         let s = token::get_ident(ident);
983
984         if !is_snake_case(ident) {
985             cx.span_lint(NON_SNAKE_CASE, span,
986                 &format!("{} `{}` should have a snake case name such as `{}`",
987                         sort, s, to_snake_case(s.get()))[]);
988         }
989     }
990 }
991
992 impl LintPass for NonSnakeCase {
993     fn get_lints(&self) -> LintArray {
994         lint_array!(NON_SNAKE_CASE)
995     }
996
997     fn check_fn(&mut self, cx: &Context,
998                 fk: visit::FnKind, _: &ast::FnDecl,
999                 _: &ast::Block, span: Span, _: ast::NodeId) {
1000         match fk {
1001             visit::FkMethod(ident, _, m) => match method_context(cx, m) {
1002                 PlainImpl
1003                     => self.check_snake_case(cx, "method", ident, span),
1004                 TraitDefaultImpl
1005                     => self.check_snake_case(cx, "trait method", ident, span),
1006                 _ => (),
1007             },
1008             visit::FkItemFn(ident, _, _, _)
1009                 => self.check_snake_case(cx, "function", ident, span),
1010             _ => (),
1011         }
1012     }
1013
1014     fn check_item(&mut self, cx: &Context, it: &ast::Item) {
1015         if let ast::ItemMod(_) = it.node {
1016             self.check_snake_case(cx, "module", it.ident, it.span);
1017         }
1018     }
1019
1020     fn check_ty_method(&mut self, cx: &Context, t: &ast::TypeMethod) {
1021         self.check_snake_case(cx, "trait method", t.ident, t.span);
1022     }
1023
1024     fn check_lifetime_def(&mut self, cx: &Context, t: &ast::LifetimeDef) {
1025         self.check_snake_case(cx, "lifetime", t.lifetime.name.ident(), t.lifetime.span);
1026     }
1027
1028     fn check_pat(&mut self, cx: &Context, p: &ast::Pat) {
1029         if let &ast::PatIdent(_, ref path1, _) = &p.node {
1030             if let Some(&def::DefLocal(_)) = cx.tcx.def_map.borrow().get(&p.id) {
1031                 self.check_snake_case(cx, "variable", path1.node, p.span);
1032             }
1033         }
1034     }
1035
1036     fn check_struct_def(&mut self, cx: &Context, s: &ast::StructDef,
1037             _: ast::Ident, _: &ast::Generics, _: ast::NodeId) {
1038         for sf in s.fields.iter() {
1039             if let ast::StructField_ { kind: ast::NamedField(ident, _), .. } = sf.node {
1040                 self.check_snake_case(cx, "structure field", ident, sf.span);
1041             }
1042         }
1043     }
1044 }
1045
1046 declare_lint! {
1047     pub NON_UPPER_CASE_GLOBALS,
1048     Warn,
1049     "static constants should have uppercase identifiers"
1050 }
1051
1052 #[derive(Copy)]
1053 pub struct NonUpperCaseGlobals;
1054
1055 impl LintPass for NonUpperCaseGlobals {
1056     fn get_lints(&self) -> LintArray {
1057         lint_array!(NON_UPPER_CASE_GLOBALS)
1058     }
1059
1060     fn check_item(&mut self, cx: &Context, it: &ast::Item) {
1061         match it.node {
1062             // only check static constants
1063             ast::ItemStatic(_, ast::MutImmutable, _) |
1064             ast::ItemConst(..) => {
1065                 let s = token::get_ident(it.ident);
1066                 // check for lowercase letters rather than non-uppercase
1067                 // ones (some scripts don't have a concept of
1068                 // upper/lowercase)
1069                 if s.get().chars().any(|c| c.is_lowercase()) {
1070                     cx.span_lint(NON_UPPER_CASE_GLOBALS, it.span,
1071                         &format!("static constant `{}` should have an uppercase name \
1072                                  such as `{}`",
1073                                 s.get(), &s.get().chars().map(|c| c.to_uppercase())
1074                                 .collect::<String>()[])[]);
1075                 }
1076             }
1077             _ => {}
1078         }
1079     }
1080
1081     fn check_pat(&mut self, cx: &Context, p: &ast::Pat) {
1082         // Lint for constants that look like binding identifiers (#7526)
1083         match (&p.node, cx.tcx.def_map.borrow().get(&p.id)) {
1084             (&ast::PatIdent(_, ref path1, _), Some(&def::DefConst(..))) => {
1085                 let s = token::get_ident(path1.node);
1086                 if s.get().chars().any(|c| c.is_lowercase()) {
1087                     cx.span_lint(NON_UPPER_CASE_GLOBALS, path1.span,
1088                         &format!("static constant in pattern `{}` should have an uppercase \
1089                                  name such as `{}`",
1090                                 s.get(), &s.get().chars().map(|c| c.to_uppercase())
1091                                     .collect::<String>()[])[]);
1092                 }
1093             }
1094             _ => {}
1095         }
1096     }
1097 }
1098
1099 declare_lint! {
1100     UNUSED_PARENS,
1101     Warn,
1102     "`if`, `match`, `while` and `return` do not need parentheses"
1103 }
1104
1105 #[derive(Copy)]
1106 pub struct UnusedParens;
1107
1108 impl UnusedParens {
1109     fn check_unused_parens_core(&self, cx: &Context, value: &ast::Expr, msg: &str,
1110                                      struct_lit_needs_parens: bool) {
1111         if let ast::ExprParen(ref inner) = value.node {
1112             let necessary = struct_lit_needs_parens && contains_exterior_struct_lit(&**inner);
1113             if !necessary {
1114                 cx.span_lint(UNUSED_PARENS, value.span,
1115                              &format!("unnecessary parentheses around {}",
1116                                      msg)[])
1117             }
1118         }
1119
1120         /// Expressions that syntactically contain an "exterior" struct
1121         /// literal i.e. not surrounded by any parens or other
1122         /// delimiters, e.g. `X { y: 1 }`, `X { y: 1 }.method()`, `foo
1123         /// == X { y: 1 }` and `X { y: 1 } == foo` all do, but `(X {
1124         /// y: 1 }) == foo` does not.
1125         fn contains_exterior_struct_lit(value: &ast::Expr) -> bool {
1126             match value.node {
1127                 ast::ExprStruct(..) => true,
1128
1129                 ast::ExprAssign(ref lhs, ref rhs) |
1130                 ast::ExprAssignOp(_, ref lhs, ref rhs) |
1131                 ast::ExprBinary(_, ref lhs, ref rhs) => {
1132                     // X { y: 1 } + X { y: 2 }
1133                     contains_exterior_struct_lit(&**lhs) ||
1134                         contains_exterior_struct_lit(&**rhs)
1135                 }
1136                 ast::ExprUnary(_, ref x) |
1137                 ast::ExprCast(ref x, _) |
1138                 ast::ExprField(ref x, _) |
1139                 ast::ExprTupField(ref x, _) |
1140                 ast::ExprIndex(ref x, _) => {
1141                     // &X { y: 1 }, X { y: 1 }.y
1142                     contains_exterior_struct_lit(&**x)
1143                 }
1144
1145                 ast::ExprMethodCall(_, _, ref exprs) => {
1146                     // X { y: 1 }.bar(...)
1147                     contains_exterior_struct_lit(&*exprs[0])
1148                 }
1149
1150                 _ => false
1151             }
1152         }
1153     }
1154 }
1155
1156 impl LintPass for UnusedParens {
1157     fn get_lints(&self) -> LintArray {
1158         lint_array!(UNUSED_PARENS)
1159     }
1160
1161     fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
1162         let (value, msg, struct_lit_needs_parens) = match e.node {
1163             ast::ExprIf(ref cond, _, _) => (cond, "`if` condition", true),
1164             ast::ExprWhile(ref cond, _, _) => (cond, "`while` condition", true),
1165             ast::ExprMatch(ref head, _, source) => match source {
1166                 ast::MatchSource::Normal => (head, "`match` head expression", true),
1167                 ast::MatchSource::IfLetDesugar { .. } => (head, "`if let` head expression", true),
1168                 ast::MatchSource::WhileLetDesugar => (head, "`while let` head expression", true),
1169             },
1170             ast::ExprRet(Some(ref value)) => (value, "`return` value", false),
1171             ast::ExprAssign(_, ref value) => (value, "assigned value", false),
1172             ast::ExprAssignOp(_, _, ref value) => (value, "assigned value", false),
1173             _ => return
1174         };
1175         self.check_unused_parens_core(cx, &**value, msg, struct_lit_needs_parens);
1176     }
1177
1178     fn check_stmt(&mut self, cx: &Context, s: &ast::Stmt) {
1179         let (value, msg) = match s.node {
1180             ast::StmtDecl(ref decl, _) => match decl.node {
1181                 ast::DeclLocal(ref local) => match local.init {
1182                     Some(ref value) => (value, "assigned value"),
1183                     None => return
1184                 },
1185                 _ => return
1186             },
1187             _ => return
1188         };
1189         self.check_unused_parens_core(cx, &**value, msg, false);
1190     }
1191 }
1192
1193 declare_lint! {
1194     UNUSED_IMPORT_BRACES,
1195     Allow,
1196     "unnecessary braces around an imported item"
1197 }
1198
1199 #[derive(Copy)]
1200 pub struct UnusedImportBraces;
1201
1202 impl LintPass for UnusedImportBraces {
1203     fn get_lints(&self) -> LintArray {
1204         lint_array!(UNUSED_IMPORT_BRACES)
1205     }
1206
1207     fn check_item(&mut self, cx: &Context, item: &ast::Item) {
1208         match item.node {
1209             ast::ItemUse(ref view_path) => {
1210                 match view_path.node {
1211                     ast::ViewPathList(_, ref items) => {
1212                         if items.len() == 1 {
1213                             match items[0].node {
1214                                 ast::PathListIdent {ref name, ..} => {
1215                                     let m = format!("braces around {} is unnecessary",
1216                                                     token::get_ident(*name).get());
1217                                     cx.span_lint(UNUSED_IMPORT_BRACES, item.span,
1218                                                  &m[]);
1219                                 },
1220                                 _ => ()
1221                             }
1222                         }
1223                     }
1224                     _ => ()
1225                 }
1226             },
1227             _ => ()
1228         }
1229     }
1230 }
1231
1232 declare_lint! {
1233     NON_SHORTHAND_FIELD_PATTERNS,
1234     Warn,
1235     "using `Struct { x: x }` instead of `Struct { x }`"
1236 }
1237
1238 #[derive(Copy)]
1239 pub struct NonShorthandFieldPatterns;
1240
1241 impl LintPass for NonShorthandFieldPatterns {
1242     fn get_lints(&self) -> LintArray {
1243         lint_array!(NON_SHORTHAND_FIELD_PATTERNS)
1244     }
1245
1246     fn check_pat(&mut self, cx: &Context, pat: &ast::Pat) {
1247         let def_map = cx.tcx.def_map.borrow();
1248         if let ast::PatStruct(_, ref v, _) = pat.node {
1249             for fieldpat in v.iter()
1250                              .filter(|fieldpat| !fieldpat.node.is_shorthand)
1251                              .filter(|fieldpat| def_map.get(&fieldpat.node.pat.id)
1252                                                 == Some(&def::DefLocal(fieldpat.node.pat.id))) {
1253                 if let ast::PatIdent(_, ident, None) = fieldpat.node.pat.node {
1254                     if ident.node.as_str() == fieldpat.node.ident.as_str() {
1255                         cx.span_lint(NON_SHORTHAND_FIELD_PATTERNS, fieldpat.span,
1256                                      &format!("the `{}:` in this pattern is redundant and can \
1257                                               be removed", ident.node.as_str())[])
1258                     }
1259                 }
1260             }
1261         }
1262     }
1263 }
1264
1265 declare_lint! {
1266     pub UNUSED_UNSAFE,
1267     Warn,
1268     "unnecessary use of an `unsafe` block"
1269 }
1270
1271 #[derive(Copy)]
1272 pub struct UnusedUnsafe;
1273
1274 impl LintPass for UnusedUnsafe {
1275     fn get_lints(&self) -> LintArray {
1276         lint_array!(UNUSED_UNSAFE)
1277     }
1278
1279     fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
1280         if let ast::ExprBlock(ref blk) = e.node {
1281             // Don't warn about generated blocks, that'll just pollute the output.
1282             if blk.rules == ast::UnsafeBlock(ast::UserProvided) &&
1283                 !cx.tcx.used_unsafe.borrow().contains(&blk.id) {
1284                     cx.span_lint(UNUSED_UNSAFE, blk.span, "unnecessary `unsafe` block");
1285             }
1286         }
1287     }
1288 }
1289
1290 declare_lint! {
1291     UNSAFE_BLOCKS,
1292     Allow,
1293     "usage of an `unsafe` block"
1294 }
1295
1296 #[derive(Copy)]
1297 pub struct UnsafeBlocks;
1298
1299 impl LintPass for UnsafeBlocks {
1300     fn get_lints(&self) -> LintArray {
1301         lint_array!(UNSAFE_BLOCKS)
1302     }
1303
1304     fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
1305         if let ast::ExprBlock(ref blk) = e.node {
1306             // Don't warn about generated blocks, that'll just pollute the output.
1307             if blk.rules == ast::UnsafeBlock(ast::UserProvided) {
1308                 cx.span_lint(UNSAFE_BLOCKS, blk.span, "usage of an `unsafe` block");
1309             }
1310         }
1311     }
1312 }
1313
1314 declare_lint! {
1315     pub UNUSED_MUT,
1316     Warn,
1317     "detect mut variables which don't need to be mutable"
1318 }
1319
1320 #[derive(Copy)]
1321 pub struct UnusedMut;
1322
1323 impl UnusedMut {
1324     fn check_unused_mut_pat(&self, cx: &Context, pats: &[P<ast::Pat>]) {
1325         // collect all mutable pattern and group their NodeIDs by their Identifier to
1326         // avoid false warnings in match arms with multiple patterns
1327
1328         let mut mutables = FnvHashMap();
1329         for p in pats.iter() {
1330             pat_util::pat_bindings(&cx.tcx.def_map, &**p, |mode, id, _, path1| {
1331                 let ident = path1.node;
1332                 if let ast::BindByValue(ast::MutMutable) = mode {
1333                     if !token::get_ident(ident).get().starts_with("_") {
1334                         match mutables.entry(ident.name.usize()) {
1335                             Vacant(entry) => { entry.insert(vec![id]); },
1336                             Occupied(mut entry) => { entry.get_mut().push(id); },
1337                         }
1338                     }
1339                 }
1340             });
1341         }
1342
1343         let used_mutables = cx.tcx.used_mut_nodes.borrow();
1344         for (_, v) in mutables.iter() {
1345             if !v.iter().any(|e| used_mutables.contains(e)) {
1346                 cx.span_lint(UNUSED_MUT, cx.tcx.map.span(v[0]),
1347                              "variable does not need to be mutable");
1348             }
1349         }
1350     }
1351 }
1352
1353 impl LintPass for UnusedMut {
1354     fn get_lints(&self) -> LintArray {
1355         lint_array!(UNUSED_MUT)
1356     }
1357
1358     fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
1359         if let ast::ExprMatch(_, ref arms, _) = e.node {
1360             for a in arms.iter() {
1361                 self.check_unused_mut_pat(cx, &a.pats[])
1362             }
1363         }
1364     }
1365
1366     fn check_stmt(&mut self, cx: &Context, s: &ast::Stmt) {
1367         if let ast::StmtDecl(ref d, _) = s.node {
1368             if let ast::DeclLocal(ref l) = d.node {
1369                 self.check_unused_mut_pat(cx, slice::ref_slice(&l.pat));
1370             }
1371         }
1372     }
1373
1374     fn check_fn(&mut self, cx: &Context,
1375                 _: visit::FnKind, decl: &ast::FnDecl,
1376                 _: &ast::Block, _: Span, _: ast::NodeId) {
1377         for a in decl.inputs.iter() {
1378             self.check_unused_mut_pat(cx, slice::ref_slice(&a.pat));
1379         }
1380     }
1381 }
1382
1383 declare_lint! {
1384     UNUSED_ALLOCATION,
1385     Warn,
1386     "detects unnecessary allocations that can be eliminated"
1387 }
1388
1389 #[derive(Copy)]
1390 pub struct UnusedAllocation;
1391
1392 impl LintPass for UnusedAllocation {
1393     fn get_lints(&self) -> LintArray {
1394         lint_array!(UNUSED_ALLOCATION)
1395     }
1396
1397     fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
1398         match e.node {
1399             ast::ExprUnary(ast::UnUniq, _) => (),
1400             _ => return
1401         }
1402
1403         if let Some(adjustment) = cx.tcx.adjustments.borrow().get(&e.id) {
1404             if let ty::AdjustDerefRef(ty::AutoDerefRef { ref autoref, .. }) = *adjustment {
1405                 match autoref {
1406                     &Some(ty::AutoPtr(_, ast::MutImmutable, None)) => {
1407                         cx.span_lint(UNUSED_ALLOCATION, e.span,
1408                                      "unnecessary allocation, use & instead");
1409                     }
1410                     &Some(ty::AutoPtr(_, ast::MutMutable, None)) => {
1411                         cx.span_lint(UNUSED_ALLOCATION, e.span,
1412                                      "unnecessary allocation, use &mut instead");
1413                     }
1414                     _ => ()
1415                 }
1416             }
1417         }
1418     }
1419 }
1420
1421 declare_lint! {
1422     MISSING_DOCS,
1423     Allow,
1424     "detects missing documentation for public members"
1425 }
1426
1427 pub struct MissingDoc {
1428     /// Stack of IDs of struct definitions.
1429     struct_def_stack: Vec<ast::NodeId>,
1430
1431     /// True if inside variant definition
1432     in_variant: bool,
1433
1434     /// Stack of whether #[doc(hidden)] is set
1435     /// at each level which has lint attributes.
1436     doc_hidden_stack: Vec<bool>,
1437 }
1438
1439 impl MissingDoc {
1440     pub fn new() -> MissingDoc {
1441         MissingDoc {
1442             struct_def_stack: vec!(),
1443             in_variant: false,
1444             doc_hidden_stack: vec!(false),
1445         }
1446     }
1447
1448     fn doc_hidden(&self) -> bool {
1449         *self.doc_hidden_stack.last().expect("empty doc_hidden_stack")
1450     }
1451
1452     fn check_missing_docs_attrs(&self,
1453                                cx: &Context,
1454                                id: Option<ast::NodeId>,
1455                                attrs: &[ast::Attribute],
1456                                sp: Span,
1457                                desc: &'static str) {
1458         // If we're building a test harness, then warning about
1459         // documentation is probably not really relevant right now.
1460         if cx.sess().opts.test { return }
1461
1462         // `#[doc(hidden)]` disables missing_docs check.
1463         if self.doc_hidden() { return }
1464
1465         // Only check publicly-visible items, using the result from the privacy pass.
1466         // It's an option so the crate root can also use this function (it doesn't
1467         // have a NodeId).
1468         if let Some(ref id) = id {
1469             if !cx.exported_items.contains(id) {
1470                 return;
1471             }
1472         }
1473
1474         let has_doc = attrs.iter().any(|a| {
1475             match a.node.value.node {
1476                 ast::MetaNameValue(ref name, _) if *name == "doc" => true,
1477                 _ => false
1478             }
1479         });
1480         if !has_doc {
1481             cx.span_lint(MISSING_DOCS, sp,
1482                 &format!("missing documentation for {}", desc)[]);
1483         }
1484     }
1485 }
1486
1487 impl LintPass for MissingDoc {
1488     fn get_lints(&self) -> LintArray {
1489         lint_array!(MISSING_DOCS)
1490     }
1491
1492     fn enter_lint_attrs(&mut self, _: &Context, attrs: &[ast::Attribute]) {
1493         let doc_hidden = self.doc_hidden() || attrs.iter().any(|attr| {
1494             attr.check_name("doc") && match attr.meta_item_list() {
1495                 None => false,
1496                 Some(l) => attr::contains_name(&l[], "hidden"),
1497             }
1498         });
1499         self.doc_hidden_stack.push(doc_hidden);
1500     }
1501
1502     fn exit_lint_attrs(&mut self, _: &Context, _: &[ast::Attribute]) {
1503         self.doc_hidden_stack.pop().expect("empty doc_hidden_stack");
1504     }
1505
1506     fn check_struct_def(&mut self, _: &Context,
1507         _: &ast::StructDef, _: ast::Ident, _: &ast::Generics, id: ast::NodeId) {
1508         self.struct_def_stack.push(id);
1509     }
1510
1511     fn check_struct_def_post(&mut self, _: &Context,
1512         _: &ast::StructDef, _: ast::Ident, _: &ast::Generics, id: ast::NodeId) {
1513         let popped = self.struct_def_stack.pop().expect("empty struct_def_stack");
1514         assert!(popped == id);
1515     }
1516
1517     fn check_crate(&mut self, cx: &Context, krate: &ast::Crate) {
1518         self.check_missing_docs_attrs(cx, None, &krate.attrs[],
1519                                      krate.span, "crate");
1520     }
1521
1522     fn check_item(&mut self, cx: &Context, it: &ast::Item) {
1523         let desc = match it.node {
1524             ast::ItemFn(..) => "a function",
1525             ast::ItemMod(..) => "a module",
1526             ast::ItemEnum(..) => "an enum",
1527             ast::ItemStruct(..) => "a struct",
1528             ast::ItemTrait(..) => "a trait",
1529             ast::ItemTy(..) => "a type alias",
1530             _ => return
1531         };
1532         self.check_missing_docs_attrs(cx, Some(it.id), &it.attrs[],
1533                                      it.span, desc);
1534     }
1535
1536     fn check_fn(&mut self, cx: &Context,
1537             fk: visit::FnKind, _: &ast::FnDecl,
1538             _: &ast::Block, _: Span, _: ast::NodeId) {
1539         if let visit::FkMethod(_, _, m) = fk {
1540             // If the method is an impl for a trait, don't doc.
1541             if method_context(cx, m) == TraitImpl { return; }
1542
1543             // Otherwise, doc according to privacy. This will also check
1544             // doc for default methods defined on traits.
1545             self.check_missing_docs_attrs(cx, Some(m.id), &m.attrs[],
1546                                           m.span, "a method");
1547         }
1548     }
1549
1550     fn check_ty_method(&mut self, cx: &Context, tm: &ast::TypeMethod) {
1551         self.check_missing_docs_attrs(cx, Some(tm.id), &tm.attrs[],
1552                                      tm.span, "a type method");
1553     }
1554
1555     fn check_struct_field(&mut self, cx: &Context, sf: &ast::StructField) {
1556         if let ast::NamedField(_, vis) = sf.node.kind {
1557             if vis == ast::Public || self.in_variant {
1558                 let cur_struct_def = *self.struct_def_stack.last()
1559                     .expect("empty struct_def_stack");
1560                 self.check_missing_docs_attrs(cx, Some(cur_struct_def),
1561                                               &sf.node.attrs[], sf.span,
1562                                               "a struct field")
1563             }
1564         }
1565     }
1566
1567     fn check_variant(&mut self, cx: &Context, v: &ast::Variant, _: &ast::Generics) {
1568         self.check_missing_docs_attrs(cx, Some(v.node.id), &v.node.attrs[],
1569                                      v.span, "a variant");
1570         assert!(!self.in_variant);
1571         self.in_variant = true;
1572     }
1573
1574     fn check_variant_post(&mut self, _: &Context, _: &ast::Variant, _: &ast::Generics) {
1575         assert!(self.in_variant);
1576         self.in_variant = false;
1577     }
1578 }
1579
1580 #[derive(Copy)]
1581 pub struct MissingCopyImplementations;
1582
1583 impl LintPass for MissingCopyImplementations {
1584     fn get_lints(&self) -> LintArray {
1585         lint_array!(MISSING_COPY_IMPLEMENTATIONS)
1586     }
1587
1588     fn check_item(&mut self, cx: &Context, item: &ast::Item) {
1589         if !cx.exported_items.contains(&item.id) {
1590             return
1591         }
1592         if cx.tcx
1593              .destructor_for_type
1594              .borrow()
1595              .contains_key(&ast_util::local_def(item.id)) {
1596             return
1597         }
1598         let ty = match item.node {
1599             ast::ItemStruct(_, ref ast_generics) => {
1600                 if ast_generics.is_parameterized() {
1601                     return
1602                 }
1603                 ty::mk_struct(cx.tcx,
1604                               ast_util::local_def(item.id),
1605                               cx.tcx.mk_substs(Substs::empty()))
1606             }
1607             ast::ItemEnum(_, ref ast_generics) => {
1608                 if ast_generics.is_parameterized() {
1609                     return
1610                 }
1611                 ty::mk_enum(cx.tcx,
1612                             ast_util::local_def(item.id),
1613                             cx.tcx.mk_substs(Substs::empty()))
1614             }
1615             _ => return,
1616         };
1617         let parameter_environment = ty::empty_parameter_environment(cx.tcx);
1618         if !ty::type_moves_by_default(&parameter_environment, item.span, ty) {
1619             return
1620         }
1621         if ty::can_type_implement_copy(&parameter_environment, item.span, ty).is_ok() {
1622             cx.span_lint(MISSING_COPY_IMPLEMENTATIONS,
1623                          item.span,
1624                          "type could implement `Copy`; consider adding `impl \
1625                           Copy`")
1626         }
1627     }
1628 }
1629
1630 declare_lint! {
1631     DEPRECATED,
1632     Warn,
1633     "detects use of #[deprecated] items"
1634 }
1635
1636 declare_lint! {
1637     UNSTABLE,
1638     Warn,
1639     "detects use of #[unstable] items (incl. items with no stability attribute)"
1640 }
1641
1642 /// Checks for use of items with `#[deprecated]`, `#[unstable]` and
1643 /// `#[unstable]` attributes, or no stability attribute.
1644 #[derive(Copy)]
1645 pub struct Stability { this_crate_staged: bool }
1646
1647 impl Stability {
1648     pub fn new() -> Stability { Stability { this_crate_staged: false } }
1649
1650     fn lint(&self, cx: &Context, id: ast::DefId, span: Span) {
1651
1652         let ref stability = stability::lookup(cx.tcx, id);
1653         let cross_crate = !ast_util::is_local(id);
1654         let staged = (!cross_crate && self.this_crate_staged)
1655             || (cross_crate && stability::is_staged_api(cx.tcx, id));
1656
1657         if !staged { return }
1658
1659         // stability attributes are promises made across crates; only
1660         // check DEPRECATED for crate-local usage.
1661         let (lint, label) = match *stability {
1662             // no stability attributes == Unstable
1663             None if cross_crate => (UNSTABLE, "unmarked"),
1664             Some(attr::Stability { level: attr::Unstable, .. }) if cross_crate =>
1665                 (UNSTABLE, "unstable"),
1666             Some(attr::Stability { level: attr::Deprecated, .. }) =>
1667                 (DEPRECATED, "deprecated"),
1668             _ => return
1669         };
1670
1671         output(cx, span, stability, lint, label);
1672
1673         fn output(cx: &Context, span: Span, stability: &Option<attr::Stability>,
1674                   lint: &'static Lint, label: &'static str) {
1675             let msg = match *stability {
1676                 Some(attr::Stability { text: Some(ref s), .. }) => {
1677                     format!("use of {} item: {}", label, *s)
1678                 }
1679                 _ => format!("use of {} item", label)
1680             };
1681
1682             cx.span_lint(lint, span, &msg[]);
1683         }
1684     }
1685
1686
1687     fn is_internal(&self, cx: &Context, span: Span) -> bool {
1688         cx.tcx.sess.codemap().span_is_internal(span)
1689     }
1690
1691 }
1692
1693 impl LintPass for Stability {
1694     fn get_lints(&self) -> LintArray {
1695         lint_array!(DEPRECATED, UNSTABLE)
1696     }
1697
1698     fn check_crate(&mut self, _: &Context, c: &ast::Crate) {
1699         // Just mark the #[staged_api] attribute used, though nothing else is done
1700         // with it during this pass over the source.
1701         for attr in c.attrs.iter() {
1702             if attr.name().get() == "staged_api" {
1703                 match attr.node.value.node {
1704                     ast::MetaWord(_) => {
1705                         attr::mark_used(attr);
1706                         self.this_crate_staged = true;
1707                     }
1708                     _ => (/*pass*/)
1709                 }
1710             }
1711         }
1712     }
1713
1714     fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
1715         if self.is_internal(cx, e.span) { return; }
1716
1717         let mut span = e.span;
1718
1719         let id = match e.node {
1720             ast::ExprPath(..) | ast::ExprQPath(..) | ast::ExprStruct(..) => {
1721                 match cx.tcx.def_map.borrow().get(&e.id) {
1722                     Some(&def) => def.def_id(),
1723                     None => return
1724                 }
1725             }
1726             ast::ExprMethodCall(i, _, _) => {
1727                 span = i.span;
1728                 let method_call = ty::MethodCall::expr(e.id);
1729                 match cx.tcx.method_map.borrow().get(&method_call) {
1730                     Some(method) => {
1731                         match method.origin {
1732                             ty::MethodStatic(def_id) => {
1733                                 def_id
1734                             }
1735                             ty::MethodStaticUnboxedClosure(def_id) => {
1736                                 def_id
1737                             }
1738                             ty::MethodTypeParam(ty::MethodParam {
1739                                 ref trait_ref,
1740                                 method_num: index,
1741                                 ..
1742                             }) |
1743                             ty::MethodTraitObject(ty::MethodObject {
1744                                 ref trait_ref,
1745                                 method_num: index,
1746                                 ..
1747                             }) => {
1748                                 ty::trait_item(cx.tcx, trait_ref.def_id, index).def_id()
1749                             }
1750                         }
1751                     }
1752                     None => return
1753                 }
1754             }
1755             _ => return
1756         };
1757
1758         self.lint(cx, id, span);
1759     }
1760
1761     fn check_item(&mut self, cx: &Context, item: &ast::Item) {
1762         if self.is_internal(cx, item.span) { return }
1763
1764         match item.node {
1765             ast::ItemExternCrate(_) => {
1766                 // compiler-generated `extern crate` items have a dummy span.
1767                 if item.span == DUMMY_SP { return }
1768
1769                 let cnum = match cx.tcx.sess.cstore.find_extern_mod_stmt_cnum(item.id) {
1770                     Some(cnum) => cnum,
1771                     None => return,
1772                 };
1773                 let id = ast::DefId { krate: cnum, node: ast::CRATE_NODE_ID };
1774                 self.lint(cx, id, item.span);
1775             }
1776             ast::ItemTrait(_, _, ref supertraits, _) => {
1777                 for t in supertraits.iter() {
1778                     if let ast::TraitTyParamBound(ref t, _) = *t {
1779                         let id = ty::trait_ref_to_def_id(cx.tcx, &t.trait_ref);
1780                         self.lint(cx, id, t.trait_ref.path.span);
1781                     }
1782                 }
1783             }
1784             ast::ItemImpl(_, _, _, Some(ref t), _, _) => {
1785                 let id = ty::trait_ref_to_def_id(cx.tcx, t);
1786                 self.lint(cx, id, t.path.span);
1787             }
1788             _ => (/* pass */)
1789         }
1790     }
1791 }
1792
1793 declare_lint! {
1794     pub UNCONDITIONAL_RECURSION,
1795     Warn,
1796     "functions that cannot return without calling themselves"
1797 }
1798
1799 #[derive(Copy)]
1800 pub struct UnconditionalRecursion;
1801
1802
1803 impl LintPass for UnconditionalRecursion {
1804     fn get_lints(&self) -> LintArray {
1805         lint_array![UNCONDITIONAL_RECURSION]
1806     }
1807
1808     fn check_fn(&mut self, cx: &Context, fn_kind: visit::FnKind, _: &ast::FnDecl,
1809                 blk: &ast::Block, sp: Span, id: ast::NodeId) {
1810         type F = for<'tcx> fn(&ty::ctxt<'tcx>,
1811                               ast::NodeId, ast::NodeId, ast::Ident, ast::NodeId) -> bool;
1812
1813         let (name, checker) = match fn_kind {
1814             visit::FkItemFn(name, _, _, _) => (name, id_refers_to_this_fn as F),
1815             visit::FkMethod(name, _, _) => (name, id_refers_to_this_method as F),
1816             // closures can't recur, so they don't matter.
1817             visit::FkFnBlock => return
1818         };
1819
1820         let impl_def_id = ty::impl_of_method(cx.tcx, ast_util::local_def(id))
1821             .unwrap_or(ast_util::local_def(ast::DUMMY_NODE_ID));
1822         assert!(ast_util::is_local(impl_def_id));
1823         let impl_node_id = impl_def_id.node;
1824
1825         // Walk through this function (say `f`) looking to see if
1826         // every possible path references itself, i.e. the function is
1827         // called recursively unconditionally. This is done by trying
1828         // to find a path from the entry node to the exit node that
1829         // *doesn't* call `f` by traversing from the entry while
1830         // pretending that calls of `f` are sinks (i.e. ignoring any
1831         // exit edges from them).
1832         //
1833         // NB. this has an edge case with non-returning statements,
1834         // like `loop {}` or `panic!()`: control flow never reaches
1835         // the exit node through these, so one can have a function
1836         // that never actually calls itselfs but is still picked up by
1837         // this lint:
1838         //
1839         //     fn f(cond: bool) {
1840         //         if !cond { panic!() } // could come from `assert!(cond)`
1841         //         f(false)
1842         //     }
1843         //
1844         // In general, functions of that form may be able to call
1845         // itself a finite number of times and then diverge. The lint
1846         // considers this to be an error for two reasons, (a) it is
1847         // easier to implement, and (b) it seems rare to actually want
1848         // to have behaviour like the above, rather than
1849         // e.g. accidentally recurring after an assert.
1850
1851         let cfg = cfg::CFG::new(cx.tcx, blk);
1852
1853         let mut work_queue = vec![cfg.entry];
1854         let mut reached_exit_without_self_call = false;
1855         let mut self_call_spans = vec![];
1856         let mut visited = BitvSet::new();
1857
1858         while let Some(idx) = work_queue.pop() {
1859             let cfg_id = idx.node_id();
1860             if idx == cfg.exit {
1861                 // found a path!
1862                 reached_exit_without_self_call = true;
1863                 break
1864             } else if visited.contains(&cfg_id) {
1865                 // already done
1866                 continue
1867             }
1868             visited.insert(cfg_id);
1869             let node_id = cfg.graph.node_data(idx).id;
1870
1871             // is this a recursive call?
1872             if node_id != ast::DUMMY_NODE_ID && checker(cx.tcx, impl_node_id, id, name, node_id) {
1873
1874                 self_call_spans.push(cx.tcx.map.span(node_id));
1875                 // this is a self call, so we shouldn't explore past
1876                 // this node in the CFG.
1877                 continue
1878             }
1879             // add the successors of this node to explore the graph further.
1880             cfg.graph.each_outgoing_edge(idx, |_, edge| {
1881                 let target_idx = edge.target();
1882                 let target_cfg_id = target_idx.node_id();
1883                 if !visited.contains(&target_cfg_id) {
1884                     work_queue.push(target_idx)
1885                 }
1886                 true
1887             });
1888         }
1889
1890         // check the number of sell calls because a function that
1891         // doesn't return (e.g. calls a `-> !` function or `loop { /*
1892         // no break */ }`) shouldn't be linted unless it actually
1893         // recurs.
1894         if !reached_exit_without_self_call && self_call_spans.len() > 0 {
1895             cx.span_lint(UNCONDITIONAL_RECURSION, sp,
1896                          "function cannot return without recurring");
1897
1898             // FIXME #19668: these could be span_lint_note's instead of this manual guard.
1899             if cx.current_level(UNCONDITIONAL_RECURSION) != Level::Allow {
1900                 let sess = cx.sess();
1901                 // offer some help to the programmer.
1902                 for call in self_call_spans.iter() {
1903                     sess.span_note(*call, "recursive call site")
1904                 }
1905                 sess.span_help(sp, "a `loop` may express intention better if this is on purpose")
1906             }
1907         }
1908
1909         // all done
1910         return;
1911
1912         // Functions for identifying if the given NodeId `id`
1913         // represents a call to the function `fn_id`/method
1914         // `method_id`.
1915
1916         fn id_refers_to_this_fn<'tcx>(tcx: &ty::ctxt<'tcx>,
1917                                       _: ast::NodeId,
1918                                       fn_id: ast::NodeId,
1919                                       _: ast::Ident,
1920                                       id: ast::NodeId) -> bool {
1921             tcx.def_map.borrow().get(&id)
1922                 .map_or(false, |def| {
1923                     let did = def.def_id();
1924                     ast_util::is_local(did) && did.node == fn_id
1925                 })
1926         }
1927
1928         // check if the method call `id` refers to method `method_id`
1929         // (with name `method_name` contained in impl `impl_id`).
1930         fn id_refers_to_this_method<'tcx>(tcx: &ty::ctxt<'tcx>,
1931                                           impl_id: ast::NodeId,
1932                                           method_id: ast::NodeId,
1933                                           method_name: ast::Ident,
1934                                           id: ast::NodeId) -> bool {
1935             let did = match tcx.method_map.borrow().get(&ty::MethodCall::expr(id)) {
1936                 None => return false,
1937                 Some(m) => match m.origin {
1938                     // There's no way to know if a method call via a
1939                     // vtable is recursion, so we assume it's not.
1940                     ty::MethodTraitObject(_) => return false,
1941
1942                     // This `did` refers directly to the method definition.
1943                     ty::MethodStatic(did) | ty::MethodStaticUnboxedClosure(did) => did,
1944
1945                     // MethodTypeParam are methods from traits:
1946
1947                     // The `impl ... for ...` of this method call
1948                     // isn't known, e.g. it might be a default method
1949                     // in a trait, so we get the def-id of the trait
1950                     // method instead.
1951                     ty::MethodTypeParam(
1952                         ty::MethodParam { ref trait_ref, method_num, impl_def_id: None, }) => {
1953                         ty::trait_item(tcx, trait_ref.def_id, method_num).def_id()
1954                     }
1955
1956                     // The `impl` is known, so we check that with a
1957                     // special case:
1958                     ty::MethodTypeParam(
1959                         ty::MethodParam { impl_def_id: Some(impl_def_id), .. }) => {
1960
1961                         let name = match tcx.map.expect_expr(id).node {
1962                             ast::ExprMethodCall(ref sp_ident, _, _) => sp_ident.node,
1963                             _ => tcx.sess.span_bug(
1964                                 tcx.map.span(id),
1965                                 "non-method call expr behaving like a method call?")
1966                         };
1967                         // it matches if it comes from the same impl,
1968                         // and has the same method name.
1969                         return ast_util::is_local(impl_def_id)
1970                             && impl_def_id.node == impl_id
1971                             && method_name.name == name.name
1972                     }
1973                 }
1974             };
1975
1976             ast_util::is_local(did) && did.node == method_id
1977         }
1978     }
1979 }
1980
1981 declare_lint! {
1982     pub UNUSED_IMPORTS,
1983     Warn,
1984     "imports that are never used"
1985 }
1986
1987 declare_lint! {
1988     pub UNUSED_EXTERN_CRATES,
1989     Allow,
1990     "extern crates that are never used"
1991 }
1992
1993 declare_lint! {
1994     pub UNUSED_QUALIFICATIONS,
1995     Allow,
1996     "detects unnecessarily qualified names"
1997 }
1998
1999 declare_lint! {
2000     pub UNKNOWN_LINTS,
2001     Warn,
2002     "unrecognized lint attribute"
2003 }
2004
2005 declare_lint! {
2006     pub UNUSED_VARIABLES,
2007     Warn,
2008     "detect variables which are not used in any way"
2009 }
2010
2011 declare_lint! {
2012     pub UNUSED_ASSIGNMENTS,
2013     Warn,
2014     "detect assignments that will never be read"
2015 }
2016
2017 declare_lint! {
2018     pub DEAD_CODE,
2019     Warn,
2020     "detect unused, unexported items"
2021 }
2022
2023 declare_lint! {
2024     pub UNREACHABLE_CODE,
2025     Warn,
2026     "detects unreachable code paths"
2027 }
2028
2029 declare_lint! {
2030     pub WARNINGS,
2031     Warn,
2032     "mass-change the level for lints which produce warnings"
2033 }
2034
2035 declare_lint! {
2036     pub UNKNOWN_FEATURES,
2037     Deny,
2038     "unknown features found in crate-level #[feature] directives"
2039 }
2040
2041 declare_lint! {
2042     pub UNKNOWN_CRATE_TYPES,
2043     Deny,
2044     "unknown crate type found in #[crate_type] directive"
2045 }
2046
2047 declare_lint! {
2048     pub VARIANT_SIZE_DIFFERENCES,
2049     Allow,
2050     "detects enums with widely varying variant sizes"
2051 }
2052
2053 declare_lint! {
2054     pub FAT_PTR_TRANSMUTES,
2055     Allow,
2056     "detects transmutes of fat pointers"
2057 }
2058
2059 declare_lint! {
2060     pub MISSING_COPY_IMPLEMENTATIONS,
2061     Warn,
2062     "detects potentially-forgotten implementations of `Copy`"
2063 }
2064
2065 /// Does nothing as a lint pass, but registers some `Lint`s
2066 /// which are used by other parts of the compiler.
2067 #[derive(Copy)]
2068 pub struct HardwiredLints;
2069
2070 impl LintPass for HardwiredLints {
2071     fn get_lints(&self) -> LintArray {
2072         lint_array!(
2073             UNUSED_IMPORTS,
2074             UNUSED_EXTERN_CRATES,
2075             UNUSED_QUALIFICATIONS,
2076             UNKNOWN_LINTS,
2077             UNUSED_VARIABLES,
2078             UNUSED_ASSIGNMENTS,
2079             DEAD_CODE,
2080             UNREACHABLE_CODE,
2081             WARNINGS,
2082             UNKNOWN_FEATURES,
2083             UNKNOWN_CRATE_TYPES,
2084             VARIANT_SIZE_DIFFERENCES,
2085             FAT_PTR_TRANSMUTES
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 }