]> git.lizzy.rs Git - rust.git/blob - src/librustc/lint/builtin.rs
b562d48f49d32ce7eb93b9a3ce010f962b8c3a0d
[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
28 use metadata::csearch;
29 use middle::def::*;
30 use middle::trans::adt; // for `adt::is_ffi_safe`
31 use middle::typeck::astconv::ast_ty_to_ty;
32 use middle::typeck::infer;
33 use middle::{typeck, ty, def, pat_util};
34 use util::ppaux::{ty_to_str};
35 use util::nodemap::NodeSet;
36 use lint::{Context, LintPass, LintArray};
37
38 use std::cmp;
39 use std::collections::HashMap;
40 use std::i16;
41 use std::i32;
42 use std::i64;
43 use std::i8;
44 use std::u16;
45 use std::u32;
46 use std::u64;
47 use std::u8;
48 use std::gc::Gc;
49 use syntax::abi;
50 use syntax::ast_map;
51 use syntax::attr::AttrMetaMethods;
52 use syntax::attr;
53 use syntax::codemap::Span;
54 use syntax::parse::token;
55 use syntax::{ast, ast_util, visit};
56
57 declare_lint!(WHILE_TRUE, Warn,
58               "suggest using `loop { }` instead of `while true { }`")
59
60 pub struct WhileTrue;
61
62 impl LintPass for WhileTrue {
63     fn get_lints(&self) -> LintArray {
64         lint_array!(WHILE_TRUE)
65     }
66
67     fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
68         match e.node {
69             ast::ExprWhile(cond, _) => {
70                 match cond.node {
71                     ast::ExprLit(lit) => {
72                         match lit.node {
73                             ast::LitBool(true) => {
74                                 cx.span_lint(WHILE_TRUE, e.span,
75                                              "denote infinite loops with loop \
76                                               { ... }");
77                             }
78                             _ => {}
79                         }
80                     }
81                     _ => ()
82                 }
83             }
84             _ => ()
85         }
86     }
87 }
88
89 declare_lint!(UNNECESSARY_TYPECAST, Allow,
90               "detects unnecessary type casts, that can be removed")
91
92 pub struct UnusedCasts;
93
94 impl LintPass for UnusedCasts {
95     fn get_lints(&self) -> LintArray {
96         lint_array!(UNNECESSARY_TYPECAST)
97     }
98
99     fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
100         match e.node {
101             ast::ExprCast(expr, ty) => {
102                 let t_t = ast_ty_to_ty(cx, &infer::new_infer_ctxt(cx.tcx), &*ty);
103                 if ty::get(ty::expr_ty(cx.tcx, &*expr)).sty == ty::get(t_t).sty {
104                     cx.span_lint(UNNECESSARY_TYPECAST, ty.span, "unnecessary type cast");
105                 }
106             }
107             _ => ()
108         }
109     }
110 }
111
112 declare_lint!(UNSIGNED_NEGATE, Warn,
113               "using an unary minus operator on unsigned type")
114
115 declare_lint!(TYPE_LIMITS, Warn,
116               "comparisons made useless by limits of the types involved")
117
118 declare_lint!(TYPE_OVERFLOW, Warn,
119               "literal out of range for its type")
120
121 pub struct TypeLimits {
122     /// Id of the last visited negated expression
123     negated_expr_id: ast::NodeId,
124 }
125
126 impl TypeLimits {
127     pub fn new() -> TypeLimits {
128         TypeLimits {
129             negated_expr_id: -1,
130         }
131     }
132 }
133
134 impl LintPass for TypeLimits {
135     fn get_lints(&self) -> LintArray {
136         lint_array!(UNSIGNED_NEGATE, TYPE_LIMITS, TYPE_OVERFLOW)
137     }
138
139     fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
140         match e.node {
141             ast::ExprUnary(ast::UnNeg, expr) => {
142                 match expr.node  {
143                     ast::ExprLit(lit) => {
144                         match lit.node {
145                             ast::LitUint(..) => {
146                                 cx.span_lint(UNSIGNED_NEGATE, e.span,
147                                              "negation of unsigned int literal may \
148                                              be unintentional");
149                             },
150                             _ => ()
151                         }
152                     },
153                     _ => {
154                         let t = ty::expr_ty(cx.tcx, &*expr);
155                         match ty::get(t).sty {
156                             ty::ty_uint(_) => {
157                                 cx.span_lint(UNSIGNED_NEGATE, e.span,
158                                              "negation of unsigned int variable may \
159                                              be unintentional");
160                             },
161                             _ => ()
162                         }
163                     }
164                 };
165                 // propagate negation, if the negation itself isn't negated
166                 if self.negated_expr_id != e.id {
167                     self.negated_expr_id = expr.id;
168                 }
169             },
170             ast::ExprParen(expr) if self.negated_expr_id == e.id => {
171                 self.negated_expr_id = expr.id;
172             },
173             ast::ExprBinary(binop, l, r) => {
174                 if is_comparison(binop) && !check_limits(cx.tcx, binop, &*l, &*r) {
175                     cx.span_lint(TYPE_LIMITS, e.span,
176                                  "comparison is useless due to type limits");
177                 }
178             },
179             ast::ExprLit(lit) => {
180                 match ty::get(ty::expr_ty(cx.tcx, e)).sty {
181                     ty::ty_int(t) => {
182                         let int_type = if t == ast::TyI {
183                             cx.sess().targ_cfg.int_type
184                         } else { t };
185                         let (min, max) = int_ty_range(int_type);
186                         let mut lit_val: i64 = match lit.node {
187                             ast::LitInt(v, _) => v,
188                             ast::LitUint(v, _) => v as i64,
189                             ast::LitIntUnsuffixed(v) => v,
190                             _ => fail!()
191                         };
192                         if self.negated_expr_id == e.id {
193                             lit_val *= -1;
194                         }
195                         if  lit_val < min || lit_val > max {
196                             cx.span_lint(TYPE_OVERFLOW, e.span,
197                                          "literal out of range for its type");
198                         }
199                     },
200                     ty::ty_uint(t) => {
201                         let uint_type = if t == ast::TyU {
202                             cx.sess().targ_cfg.uint_type
203                         } else { t };
204                         let (min, max) = uint_ty_range(uint_type);
205                         let lit_val: u64 = match lit.node {
206                             ast::LitByte(_v) => return,  // _v is u8, within range by definition
207                             ast::LitInt(v, _) => v as u64,
208                             ast::LitUint(v, _) => v,
209                             ast::LitIntUnsuffixed(v) => v as u64,
210                             _ => fail!()
211                         };
212                         if  lit_val < min || lit_val > max {
213                             cx.span_lint(TYPE_OVERFLOW, e.span,
214                                          "literal out of range for its type");
215                         }
216                     },
217
218                     _ => ()
219                 };
220             },
221             _ => ()
222         };
223
224         fn is_valid<T:cmp::PartialOrd>(binop: ast::BinOp, v: T,
225                                 min: T, max: T) -> bool {
226             match binop {
227                 ast::BiLt => v >  min && v <= max,
228                 ast::BiLe => v >= min && v <  max,
229                 ast::BiGt => v >= min && v <  max,
230                 ast::BiGe => v >  min && v <= max,
231                 ast::BiEq | ast::BiNe => v >= min && v <= max,
232                 _ => fail!()
233             }
234         }
235
236         fn rev_binop(binop: ast::BinOp) -> ast::BinOp {
237             match binop {
238                 ast::BiLt => ast::BiGt,
239                 ast::BiLe => ast::BiGe,
240                 ast::BiGt => ast::BiLt,
241                 ast::BiGe => ast::BiLe,
242                 _ => binop
243             }
244         }
245
246         // for int & uint, be conservative with the warnings, so that the
247         // warnings are consistent between 32- and 64-bit platforms
248         fn int_ty_range(int_ty: ast::IntTy) -> (i64, i64) {
249             match int_ty {
250                 ast::TyI =>    (i64::MIN,        i64::MAX),
251                 ast::TyI8 =>   (i8::MIN  as i64, i8::MAX  as i64),
252                 ast::TyI16 =>  (i16::MIN as i64, i16::MAX as i64),
253                 ast::TyI32 =>  (i32::MIN as i64, i32::MAX as i64),
254                 ast::TyI64 =>  (i64::MIN,        i64::MAX)
255             }
256         }
257
258         fn uint_ty_range(uint_ty: ast::UintTy) -> (u64, u64) {
259             match uint_ty {
260                 ast::TyU =>   (u64::MIN,         u64::MAX),
261                 ast::TyU8 =>  (u8::MIN   as u64, u8::MAX   as u64),
262                 ast::TyU16 => (u16::MIN  as u64, u16::MAX  as u64),
263                 ast::TyU32 => (u32::MIN  as u64, u32::MAX  as u64),
264                 ast::TyU64 => (u64::MIN,         u64::MAX)
265             }
266         }
267
268         fn check_limits(tcx: &ty::ctxt, binop: ast::BinOp,
269                         l: &ast::Expr, r: &ast::Expr) -> bool {
270             let (lit, expr, swap) = match (&l.node, &r.node) {
271                 (&ast::ExprLit(_), _) => (l, r, true),
272                 (_, &ast::ExprLit(_)) => (r, l, false),
273                 _ => return true
274             };
275             // Normalize the binop so that the literal is always on the RHS in
276             // the comparison
277             let norm_binop = if swap { rev_binop(binop) } else { binop };
278             match ty::get(ty::expr_ty(tcx, expr)).sty {
279                 ty::ty_int(int_ty) => {
280                     let (min, max) = int_ty_range(int_ty);
281                     let lit_val: i64 = match lit.node {
282                         ast::ExprLit(li) => match li.node {
283                             ast::LitInt(v, _) => v,
284                             ast::LitUint(v, _) => v as i64,
285                             ast::LitIntUnsuffixed(v) => v,
286                             _ => return true
287                         },
288                         _ => fail!()
289                     };
290                     is_valid(norm_binop, lit_val, min, max)
291                 }
292                 ty::ty_uint(uint_ty) => {
293                     let (min, max): (u64, u64) = uint_ty_range(uint_ty);
294                     let lit_val: u64 = match lit.node {
295                         ast::ExprLit(li) => match li.node {
296                             ast::LitInt(v, _) => v as u64,
297                             ast::LitUint(v, _) => v,
298                             ast::LitIntUnsuffixed(v) => v as u64,
299                             _ => return true
300                         },
301                         _ => fail!()
302                     };
303                     is_valid(norm_binop, lit_val, min, max)
304                 }
305                 _ => true
306             }
307         }
308
309         fn is_comparison(binop: ast::BinOp) -> bool {
310             match binop {
311                 ast::BiEq | ast::BiLt | ast::BiLe |
312                 ast::BiNe | ast::BiGe | ast::BiGt => true,
313                 _ => false
314             }
315         }
316     }
317 }
318
319 declare_lint!(CTYPES, Warn,
320               "proper use of libc types in foreign modules")
321
322 pub struct CTypes;
323
324 impl LintPass for CTypes {
325     fn get_lints(&self) -> LintArray {
326         lint_array!(CTYPES)
327     }
328
329     fn check_item(&mut self, cx: &Context, it: &ast::Item) {
330         fn check_ty(cx: &Context, ty: &ast::Ty) {
331             match ty.node {
332                 ast::TyPath(_, _, id) => {
333                     match cx.tcx.def_map.borrow().get_copy(&id) {
334                         def::DefPrimTy(ast::TyInt(ast::TyI)) => {
335                             cx.span_lint(CTYPES, ty.span,
336                                          "found rust type `int` in foreign module, while \
337                                           libc::c_int or libc::c_long should be used");
338                         }
339                         def::DefPrimTy(ast::TyUint(ast::TyU)) => {
340                             cx.span_lint(CTYPES, ty.span,
341                                          "found rust type `uint` in foreign module, while \
342                                           libc::c_uint or libc::c_ulong should be used");
343                         }
344                         def::DefTy(def_id) => {
345                             if !adt::is_ffi_safe(cx.tcx, def_id) {
346                                 cx.span_lint(CTYPES, ty.span,
347                                              "found enum type without foreign-function-safe \
348                                               representation annotation in foreign module");
349                                 // hmm... this message could be more helpful
350                             }
351                         }
352                         _ => ()
353                     }
354                 }
355                 ast::TyPtr(ref mt) => { check_ty(cx, &*mt.ty) }
356                 _ => {}
357             }
358         }
359
360         fn check_foreign_fn(cx: &Context, decl: &ast::FnDecl) {
361             for input in decl.inputs.iter() {
362                 check_ty(cx, &*input.ty);
363             }
364             check_ty(cx, &*decl.output)
365         }
366
367         match it.node {
368           ast::ItemForeignMod(ref nmod) if nmod.abi != abi::RustIntrinsic => {
369             for ni in nmod.items.iter() {
370                 match ni.node {
371                     ast::ForeignItemFn(decl, _) => check_foreign_fn(cx, &*decl),
372                     ast::ForeignItemStatic(t, _) => check_ty(cx, &*t)
373                 }
374             }
375           }
376           _ => {/* nothing to do */ }
377         }
378     }
379 }
380
381 declare_lint!(MANAGED_HEAP_MEMORY, Allow,
382               "use of managed (@ type) heap memory")
383
384 declare_lint!(OWNED_HEAP_MEMORY, Allow,
385               "use of owned (Box type) heap memory")
386
387 declare_lint!(HEAP_MEMORY, Allow,
388               "use of any (Box type or @ type) heap memory")
389
390 pub struct HeapMemory;
391
392 impl HeapMemory {
393     fn check_heap_type(&self, cx: &Context, span: Span, ty: ty::t) {
394         let mut n_box = 0i;
395         let mut n_uniq = 0i;
396         ty::fold_ty(cx.tcx, ty, |t| {
397             match ty::get(t).sty {
398                 ty::ty_box(_) => {
399                     n_box += 1;
400                 }
401                 ty::ty_uniq(_) |
402                 ty::ty_closure(box ty::ClosureTy {
403                     store: ty::UniqTraitStore,
404                     ..
405                 }) => {
406                     n_uniq += 1;
407                 }
408
409                 _ => ()
410             };
411             t
412         });
413
414         if n_uniq > 0 {
415             let s = ty_to_str(cx.tcx, ty);
416             let m = format!("type uses owned (Box type) pointers: {}", s);
417             cx.span_lint(OWNED_HEAP_MEMORY, span, m.as_slice());
418             cx.span_lint(HEAP_MEMORY, span, m.as_slice());
419         }
420
421         if n_box > 0 {
422             let s = ty_to_str(cx.tcx, ty);
423             let m = format!("type uses managed (@ type) pointers: {}", s);
424             cx.span_lint(MANAGED_HEAP_MEMORY, span, m.as_slice());
425             cx.span_lint(HEAP_MEMORY, span, m.as_slice());
426         }
427     }
428 }
429
430 impl LintPass for HeapMemory {
431     fn get_lints(&self) -> LintArray {
432         lint_array!(MANAGED_HEAP_MEMORY, OWNED_HEAP_MEMORY, HEAP_MEMORY)
433     }
434
435     fn check_item(&mut self, cx: &Context, it: &ast::Item) {
436         match it.node {
437             ast::ItemFn(..) |
438             ast::ItemTy(..) |
439             ast::ItemEnum(..) |
440             ast::ItemStruct(..) =>
441                 self.check_heap_type(cx, it.span,
442                                      ty::node_id_to_type(cx.tcx, it.id)),
443             _ => ()
444         }
445
446         // If it's a struct, we also have to check the fields' types
447         match it.node {
448             ast::ItemStruct(struct_def, _) => {
449                 for struct_field in struct_def.fields.iter() {
450                     self.check_heap_type(cx, struct_field.span,
451                                          ty::node_id_to_type(cx.tcx, struct_field.node.id));
452                 }
453             }
454             _ => ()
455         }
456     }
457
458     fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
459         let ty = ty::expr_ty(cx.tcx, e);
460         self.check_heap_type(cx, e.span, ty);
461     }
462 }
463
464 declare_lint!(RAW_POINTER_DERIVING, Warn,
465               "uses of #[deriving] with raw pointers are rarely correct")
466
467 struct RawPtrDerivingVisitor<'a> {
468     cx: &'a Context<'a>
469 }
470
471 impl<'a> visit::Visitor<()> for RawPtrDerivingVisitor<'a> {
472     fn visit_ty(&mut self, ty: &ast::Ty, _: ()) {
473         static MSG: &'static str = "use of `#[deriving]` with a raw pointer";
474         match ty.node {
475             ast::TyPtr(..) => self.cx.span_lint(RAW_POINTER_DERIVING, ty.span, MSG),
476             _ => {}
477         }
478         visit::walk_ty(self, ty, ());
479     }
480     // explicit override to a no-op to reduce code bloat
481     fn visit_expr(&mut self, _: &ast::Expr, _: ()) {}
482     fn visit_block(&mut self, _: &ast::Block, _: ()) {}
483 }
484
485 pub struct RawPointerDeriving {
486     checked_raw_pointers: NodeSet,
487 }
488
489 impl RawPointerDeriving {
490     pub fn new() -> RawPointerDeriving {
491         RawPointerDeriving {
492             checked_raw_pointers: NodeSet::new(),
493         }
494     }
495 }
496
497 impl LintPass for RawPointerDeriving {
498     fn get_lints(&self) -> LintArray {
499         lint_array!(RAW_POINTER_DERIVING)
500     }
501
502     fn check_item(&mut self, cx: &Context, item: &ast::Item) {
503         if !attr::contains_name(item.attrs.as_slice(), "automatically_derived") {
504             return
505         }
506         let did = match item.node {
507             ast::ItemImpl(..) => {
508                 match ty::get(ty::node_id_to_type(cx.tcx, item.id)).sty {
509                     ty::ty_enum(did, _) => did,
510                     ty::ty_struct(did, _) => did,
511                     _ => return,
512                 }
513             }
514             _ => return,
515         };
516         if !ast_util::is_local(did) { return }
517         let item = match cx.tcx.map.find(did.node) {
518             Some(ast_map::NodeItem(item)) => item,
519             _ => return,
520         };
521         if !self.checked_raw_pointers.insert(item.id) { return }
522         match item.node {
523             ast::ItemStruct(..) | ast::ItemEnum(..) => {
524                 let mut visitor = RawPtrDerivingVisitor { cx: cx };
525                 visit::walk_item(&mut visitor, &*item, ());
526             }
527             _ => {}
528         }
529     }
530 }
531
532 declare_lint!(UNUSED_ATTRIBUTE, Warn,
533               "detects attributes that were not used by the compiler")
534
535 pub struct UnusedAttribute;
536
537 impl LintPass for UnusedAttribute {
538     fn get_lints(&self) -> LintArray {
539         lint_array!(UNUSED_ATTRIBUTE)
540     }
541
542     fn check_attribute(&mut self, cx: &Context, attr: &ast::Attribute) {
543         static ATTRIBUTE_WHITELIST: &'static [&'static str] = &'static [
544             // FIXME: #14408 whitelist docs since rustdoc looks at them
545             "doc",
546
547             // FIXME: #14406 these are processed in trans, which happens after the
548             // lint pass
549             "cold",
550             "inline",
551             "link",
552             "link_name",
553             "link_section",
554             "no_builtins",
555             "no_mangle",
556             "no_split_stack",
557             "packed",
558             "static_assert",
559             "thread_local",
560
561             // not used anywhere (!?) but apparently we want to keep them around
562             "comment",
563             "desc",
564             "license",
565
566             // FIXME: #14407 these are only looked at on-demand so we can't
567             // guarantee they'll have already been checked
568             "deprecated",
569             "experimental",
570             "frozen",
571             "locked",
572             "must_use",
573             "stable",
574             "unstable",
575         ];
576
577         static CRATE_ATTRS: &'static [&'static str] = &'static [
578             "crate_type",
579             "feature",
580             "no_start",
581             "no_main",
582             "no_std",
583             "crate_id",
584             "desc",
585             "comment",
586             "license",
587             "copyright",
588             "no_builtins",
589         ];
590
591         for &name in ATTRIBUTE_WHITELIST.iter() {
592             if attr.check_name(name) {
593                 break;
594             }
595         }
596
597         if !attr::is_used(attr) {
598             cx.span_lint(UNUSED_ATTRIBUTE, attr.span, "unused attribute");
599             if CRATE_ATTRS.contains(&attr.name().get()) {
600                 let msg = match attr.node.style {
601                     ast::AttrOuter => "crate-level attribute should be an inner \
602                                        attribute: add an exclamation mark: #![foo]",
603                     ast::AttrInner => "crate-level attribute should be in the \
604                                        root module",
605                 };
606                 cx.span_lint(UNUSED_ATTRIBUTE, attr.span, msg);
607             }
608         }
609     }
610 }
611
612 declare_lint!(PATH_STATEMENT, Warn,
613               "path statements with no effect")
614
615 pub struct PathStatement;
616
617 impl LintPass for PathStatement {
618     fn get_lints(&self) -> LintArray {
619         lint_array!(PATH_STATEMENT)
620     }
621
622     fn check_stmt(&mut self, cx: &Context, s: &ast::Stmt) {
623         match s.node {
624             ast::StmtSemi(expr, _) => {
625                 match expr.node {
626                     ast::ExprPath(_) => cx.span_lint(PATH_STATEMENT, s.span,
627                                                      "path statement with no effect"),
628                     _ => ()
629                 }
630             }
631             _ => ()
632         }
633     }
634 }
635
636 declare_lint!(UNUSED_MUST_USE, Warn,
637               "unused result of a type flagged as #[must_use]")
638
639 declare_lint!(UNUSED_RESULT, Allow,
640               "unused result of an expression in a statement")
641
642 pub struct UnusedResult;
643
644 impl LintPass for UnusedResult {
645     fn get_lints(&self) -> LintArray {
646         lint_array!(UNUSED_MUST_USE, UNUSED_RESULT)
647     }
648
649     fn check_stmt(&mut self, cx: &Context, s: &ast::Stmt) {
650         let expr = match s.node {
651             ast::StmtSemi(expr, _) => expr,
652             _ => return
653         };
654         let t = ty::expr_ty(cx.tcx, &*expr);
655         match ty::get(t).sty {
656             ty::ty_nil | ty::ty_bot | ty::ty_bool => return,
657             _ => {}
658         }
659         match expr.node {
660             ast::ExprRet(..) => return,
661             _ => {}
662         }
663
664         let t = ty::expr_ty(cx.tcx, &*expr);
665         let mut warned = false;
666         match ty::get(t).sty {
667             ty::ty_struct(did, _) |
668             ty::ty_enum(did, _) => {
669                 if ast_util::is_local(did) {
670                     match cx.tcx.map.get(did.node) {
671                         ast_map::NodeItem(it) => {
672                             if attr::contains_name(it.attrs.as_slice(),
673                                                    "must_use") {
674                                 cx.span_lint(UNUSED_MUST_USE, s.span,
675                                              "unused result which must be used");
676                                 warned = true;
677                             }
678                         }
679                         _ => {}
680                     }
681                 } else {
682                     csearch::get_item_attrs(&cx.sess().cstore, did, |attrs| {
683                         if attr::contains_name(attrs.as_slice(), "must_use") {
684                             cx.span_lint(UNUSED_MUST_USE, s.span,
685                                          "unused result which must be used");
686                             warned = true;
687                         }
688                     });
689                 }
690             }
691             _ => {}
692         }
693         if !warned {
694             cx.span_lint(UNUSED_RESULT, s.span, "unused result");
695         }
696     }
697 }
698
699 declare_lint!(NON_CAMEL_CASE_TYPES, Warn,
700               "types, variants and traits should have camel case names")
701
702 pub struct NonCamelCaseTypes;
703
704 impl LintPass for NonCamelCaseTypes {
705     fn get_lints(&self) -> LintArray {
706         lint_array!(NON_CAMEL_CASE_TYPES)
707     }
708
709     fn check_item(&mut self, cx: &Context, it: &ast::Item) {
710         fn is_camel_case(ident: ast::Ident) -> bool {
711             let ident = token::get_ident(ident);
712             assert!(!ident.get().is_empty());
713             let ident = ident.get().trim_chars('_');
714
715             // start with a non-lowercase letter rather than non-uppercase
716             // ones (some scripts don't have a concept of upper/lowercase)
717             !ident.char_at(0).is_lowercase() && !ident.contains_char('_')
718         }
719
720         fn to_camel_case(s: &str) -> String {
721             s.split('_').flat_map(|word| word.chars().enumerate().map(|(i, c)|
722                 if i == 0 { c.to_uppercase() }
723                 else { c }
724             )).collect()
725         }
726
727         fn check_case(cx: &Context, sort: &str, ident: ast::Ident, span: Span) {
728             let s = token::get_ident(ident);
729
730             if !is_camel_case(ident) {
731                 cx.span_lint(NON_CAMEL_CASE_TYPES, span,
732                     format!("{} `{}` should have a camel case name such as `{}`",
733                             sort, s, to_camel_case(s.get())).as_slice());
734             }
735         }
736
737         match it.node {
738             ast::ItemTy(..) | ast::ItemStruct(..) => {
739                 check_case(cx, "type", it.ident, it.span)
740             }
741             ast::ItemTrait(..) => {
742                 check_case(cx, "trait", it.ident, it.span)
743             }
744             ast::ItemEnum(ref enum_definition, _) => {
745                 check_case(cx, "type", it.ident, it.span);
746                 for variant in enum_definition.variants.iter() {
747                     check_case(cx, "variant", variant.node.name, variant.span);
748                 }
749             }
750             _ => ()
751         }
752     }
753 }
754
755 #[deriving(PartialEq)]
756 enum MethodContext {
757     TraitDefaultImpl,
758     TraitImpl,
759     PlainImpl
760 }
761
762 fn method_context(cx: &Context, m: &ast::Method) -> MethodContext {
763     let did = ast::DefId {
764         krate: ast::LOCAL_CRATE,
765         node: m.id
766     };
767
768     match cx.tcx.methods.borrow().find_copy(&did) {
769         None => cx.sess().span_bug(m.span, "missing method descriptor?!"),
770         Some(md) => {
771             match md.container {
772                 ty::TraitContainer(..) => TraitDefaultImpl,
773                 ty::ImplContainer(cid) => {
774                     match ty::impl_trait_ref(cx.tcx, cid) {
775                         Some(..) => TraitImpl,
776                         None => PlainImpl
777                     }
778                 }
779             }
780         }
781     }
782 }
783
784 declare_lint!(NON_SNAKE_CASE_FUNCTIONS, Warn,
785               "methods and functions should have snake case names")
786
787 pub struct NonSnakeCaseFunctions;
788
789 impl NonSnakeCaseFunctions {
790     fn check_snake_case(&self, cx: &Context, sort: &str, ident: ast::Ident, span: Span) {
791         fn is_snake_case(ident: ast::Ident) -> bool {
792             let ident = token::get_ident(ident);
793             assert!(!ident.get().is_empty());
794             let ident = ident.get().trim_chars('_');
795
796             let mut allow_underscore = true;
797             ident.chars().all(|c| {
798                 allow_underscore = match c {
799                     c if c.is_lowercase() || c.is_digit() => true,
800                     '_' if allow_underscore => false,
801                     _ => return false,
802                 };
803                 true
804             })
805         }
806
807         fn to_snake_case(str: &str) -> String {
808             let mut words = vec![];
809             for s in str.split('_') {
810                 let mut buf = String::new();
811                 if s.is_empty() { continue; }
812                 for ch in s.chars() {
813                     if !buf.is_empty() && ch.is_uppercase() {
814                         words.push(buf);
815                         buf = String::new();
816                     }
817                     buf.push_char(ch.to_lowercase());
818                 }
819                 words.push(buf);
820             }
821             words.connect("_")
822         }
823
824         let s = token::get_ident(ident);
825
826         if !is_snake_case(ident) {
827             cx.span_lint(NON_SNAKE_CASE_FUNCTIONS, span,
828                 format!("{} `{}` should have a snake case name such as `{}`",
829                         sort, s, to_snake_case(s.get())).as_slice());
830         }
831     }
832 }
833
834 impl LintPass for NonSnakeCaseFunctions {
835     fn get_lints(&self) -> LintArray {
836         lint_array!(NON_SNAKE_CASE_FUNCTIONS)
837     }
838
839     fn check_fn(&mut self, cx: &Context,
840                 fk: &visit::FnKind, _: &ast::FnDecl,
841                 _: &ast::Block, span: Span, _: ast::NodeId) {
842         match *fk {
843             visit::FkMethod(ident, _, m) => match method_context(cx, m) {
844                 PlainImpl
845                     => self.check_snake_case(cx, "method", ident, span),
846                 TraitDefaultImpl
847                     => self.check_snake_case(cx, "trait method", ident, span),
848                 _ => (),
849             },
850             visit::FkItemFn(ident, _, _, _)
851                 => self.check_snake_case(cx, "function", ident, span),
852             _ => (),
853         }
854     }
855
856     fn check_ty_method(&mut self, cx: &Context, t: &ast::TypeMethod) {
857         self.check_snake_case(cx, "trait method", t.ident, t.span);
858     }
859 }
860
861 declare_lint!(NON_UPPERCASE_STATICS, Allow,
862               "static constants should have uppercase identifiers")
863
864 pub struct NonUppercaseStatics;
865
866 impl LintPass for NonUppercaseStatics {
867     fn get_lints(&self) -> LintArray {
868         lint_array!(NON_UPPERCASE_STATICS)
869     }
870
871     fn check_item(&mut self, cx: &Context, it: &ast::Item) {
872         match it.node {
873             // only check static constants
874             ast::ItemStatic(_, ast::MutImmutable, _) => {
875                 let s = token::get_ident(it.ident);
876                 // check for lowercase letters rather than non-uppercase
877                 // ones (some scripts don't have a concept of
878                 // upper/lowercase)
879                 if s.get().chars().any(|c| c.is_lowercase()) {
880                     cx.span_lint(NON_UPPERCASE_STATICS, it.span,
881                         format!("static constant `{}` should have an uppercase name \
882                                  such as `{}`",
883                                 s.get(), s.get().chars().map(|c| c.to_uppercase())
884                                 .collect::<String>().as_slice()).as_slice());
885                 }
886             }
887             _ => {}
888         }
889     }
890 }
891
892 declare_lint!(NON_UPPERCASE_PATTERN_STATICS, Warn,
893               "static constants in match patterns should be all caps")
894
895 pub struct NonUppercasePatternStatics;
896
897 impl LintPass for NonUppercasePatternStatics {
898     fn get_lints(&self) -> LintArray {
899         lint_array!(NON_UPPERCASE_PATTERN_STATICS)
900     }
901
902     fn check_pat(&mut self, cx: &Context, p: &ast::Pat) {
903         // Lint for constants that look like binding identifiers (#7526)
904         match (&p.node, cx.tcx.def_map.borrow().find(&p.id)) {
905             (&ast::PatIdent(_, ref path, _), Some(&def::DefStatic(_, false))) => {
906                 // last identifier alone is right choice for this lint.
907                 let ident = path.segments.last().unwrap().identifier;
908                 let s = token::get_ident(ident);
909                 if s.get().chars().any(|c| c.is_lowercase()) {
910                     cx.span_lint(NON_UPPERCASE_PATTERN_STATICS, path.span,
911                         format!("static constant in pattern `{}` should have an uppercase \
912                                  name such as `{}`",
913                                 s.get(), s.get().chars().map(|c| c.to_uppercase())
914                                     .collect::<String>().as_slice()).as_slice());
915                 }
916             }
917             _ => {}
918         }
919     }
920 }
921
922 declare_lint!(UPPERCASE_VARIABLES, Warn,
923               "variable and structure field names should start with a lowercase character")
924
925 pub struct UppercaseVariables;
926
927 impl LintPass for UppercaseVariables {
928     fn get_lints(&self) -> LintArray {
929         lint_array!(UPPERCASE_VARIABLES)
930     }
931
932     fn check_pat(&mut self, cx: &Context, p: &ast::Pat) {
933         match &p.node {
934             &ast::PatIdent(_, ref path, _) => {
935                 match cx.tcx.def_map.borrow().find(&p.id) {
936                     Some(&def::DefLocal(_, _)) | Some(&def::DefBinding(_, _)) |
937                             Some(&def::DefArg(_, _)) => {
938                         // last identifier alone is right choice for this lint.
939                         let ident = path.segments.last().unwrap().identifier;
940                         let s = token::get_ident(ident);
941                         if s.get().len() > 0 && s.get().char_at(0).is_uppercase() {
942                             cx.span_lint(UPPERCASE_VARIABLES, path.span,
943                                          "variable names should start with \
944                                           a lowercase character");
945                         }
946                     }
947                     _ => {}
948                 }
949             }
950             _ => {}
951         }
952     }
953
954     fn check_struct_def(&mut self, cx: &Context, s: &ast::StructDef,
955             _: ast::Ident, _: &ast::Generics, _: ast::NodeId) {
956         for sf in s.fields.iter() {
957             match sf.node {
958                 ast::StructField_ { kind: ast::NamedField(ident, _), .. } => {
959                     let s = token::get_ident(ident);
960                     if s.get().char_at(0).is_uppercase() {
961                         cx.span_lint(UPPERCASE_VARIABLES, sf.span,
962                                      "structure field names should start with \
963                                       a lowercase character");
964                     }
965                 }
966                 _ => {}
967             }
968         }
969     }
970 }
971
972 declare_lint!(UNNECESSARY_PARENS, Warn,
973               "`if`, `match`, `while` and `return` do not need parentheses")
974
975 pub struct UnnecessaryParens;
976
977 impl UnnecessaryParens {
978     fn check_unnecessary_parens_core(&self, cx: &Context, value: &ast::Expr, msg: &str,
979                                      struct_lit_needs_parens: bool) {
980         match value.node {
981             ast::ExprParen(ref inner) => {
982                 let necessary = struct_lit_needs_parens && contains_exterior_struct_lit(&**inner);
983                 if !necessary {
984                     cx.span_lint(UNNECESSARY_PARENS, value.span,
985                                  format!("unnecessary parentheses around {}",
986                                          msg).as_slice())
987                 }
988             }
989             _ => {}
990         }
991
992         /// Expressions that syntatically contain an "exterior" struct
993         /// literal i.e. not surrounded by any parens or other
994         /// delimiters, e.g. `X { y: 1 }`, `X { y: 1 }.method()`, `foo
995         /// == X { y: 1 }` and `X { y: 1 } == foo` all do, but `(X {
996         /// y: 1 }) == foo` does not.
997         fn contains_exterior_struct_lit(value: &ast::Expr) -> bool {
998             match value.node {
999                 ast::ExprStruct(..) => true,
1000
1001                 ast::ExprAssign(ref lhs, ref rhs) |
1002                 ast::ExprAssignOp(_, ref lhs, ref rhs) |
1003                 ast::ExprBinary(_, ref lhs, ref rhs) => {
1004                     // X { y: 1 } + X { y: 2 }
1005                     contains_exterior_struct_lit(&**lhs) ||
1006                         contains_exterior_struct_lit(&**rhs)
1007                 }
1008                 ast::ExprUnary(_, ref x) |
1009                 ast::ExprCast(ref x, _) |
1010                 ast::ExprField(ref x, _, _) |
1011                 ast::ExprIndex(ref x, _) => {
1012                     // &X { y: 1 }, X { y: 1 }.y
1013                     contains_exterior_struct_lit(&**x)
1014                 }
1015
1016                 ast::ExprMethodCall(_, _, ref exprs) => {
1017                     // X { y: 1 }.bar(...)
1018                     contains_exterior_struct_lit(&**exprs.get(0))
1019                 }
1020
1021                 _ => false
1022             }
1023         }
1024     }
1025 }
1026
1027 impl LintPass for UnnecessaryParens {
1028     fn get_lints(&self) -> LintArray {
1029         lint_array!(UNNECESSARY_PARENS)
1030     }
1031
1032     fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
1033         let (value, msg, struct_lit_needs_parens) = match e.node {
1034             ast::ExprIf(cond, _, _) => (cond, "`if` condition", true),
1035             ast::ExprWhile(cond, _) => (cond, "`while` condition", true),
1036             ast::ExprMatch(head, _) => (head, "`match` head expression", true),
1037             ast::ExprRet(Some(value)) => (value, "`return` value", false),
1038             ast::ExprAssign(_, value) => (value, "assigned value", false),
1039             ast::ExprAssignOp(_, _, value) => (value, "assigned value", false),
1040             _ => return
1041         };
1042         self.check_unnecessary_parens_core(cx, &*value, msg, struct_lit_needs_parens);
1043     }
1044
1045     fn check_stmt(&mut self, cx: &Context, s: &ast::Stmt) {
1046         let (value, msg) = match s.node {
1047             ast::StmtDecl(decl, _) => match decl.node {
1048                 ast::DeclLocal(local) => match local.init {
1049                     Some(value) => (value, "assigned value"),
1050                     None => return
1051                 },
1052                 _ => return
1053             },
1054             _ => return
1055         };
1056         self.check_unnecessary_parens_core(cx, &*value, msg, false);
1057     }
1058 }
1059
1060 declare_lint!(UNUSED_UNSAFE, Warn,
1061               "unnecessary use of an `unsafe` block")
1062
1063 pub struct UnusedUnsafe;
1064
1065 impl LintPass for UnusedUnsafe {
1066     fn get_lints(&self) -> LintArray {
1067         lint_array!(UNUSED_UNSAFE)
1068     }
1069
1070     fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
1071         match e.node {
1072             // Don't warn about generated blocks, that'll just pollute the output.
1073             ast::ExprBlock(ref blk) => {
1074                 if blk.rules == ast::UnsafeBlock(ast::UserProvided) &&
1075                     !cx.tcx.used_unsafe.borrow().contains(&blk.id) {
1076                     cx.span_lint(UNUSED_UNSAFE, blk.span, "unnecessary `unsafe` block");
1077                 }
1078             }
1079             _ => ()
1080         }
1081     }
1082 }
1083
1084 declare_lint!(UNSAFE_BLOCK, Allow,
1085               "usage of an `unsafe` block")
1086
1087 pub struct UnsafeBlock;
1088
1089 impl LintPass for UnsafeBlock {
1090     fn get_lints(&self) -> LintArray {
1091         lint_array!(UNSAFE_BLOCK)
1092     }
1093
1094     fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
1095         match e.node {
1096             // Don't warn about generated blocks, that'll just pollute the output.
1097             ast::ExprBlock(ref blk) if blk.rules == ast::UnsafeBlock(ast::UserProvided) => {
1098                 cx.span_lint(UNSAFE_BLOCK, blk.span, "usage of an `unsafe` block");
1099             }
1100             _ => ()
1101         }
1102     }
1103 }
1104
1105 declare_lint!(UNUSED_MUT, Warn,
1106               "detect mut variables which don't need to be mutable")
1107
1108 pub struct UnusedMut;
1109
1110 impl UnusedMut {
1111     fn check_unused_mut_pat(&self, cx: &Context, pats: &[Gc<ast::Pat>]) {
1112         // collect all mutable pattern and group their NodeIDs by their Identifier to
1113         // avoid false warnings in match arms with multiple patterns
1114         let mut mutables = HashMap::new();
1115         for &p in pats.iter() {
1116             pat_util::pat_bindings(&cx.tcx.def_map, &*p, |mode, id, _, path| {
1117                 match mode {
1118                     ast::BindByValue(ast::MutMutable) => {
1119                         if path.segments.len() != 1 {
1120                             cx.sess().span_bug(p.span,
1121                                                "mutable binding that doesn't consist \
1122                                                 of exactly one segment");
1123                         }
1124                         let ident = path.segments.get(0).identifier;
1125                         if !token::get_ident(ident).get().starts_with("_") {
1126                             mutables.insert_or_update_with(ident.name as uint,
1127                                 vec!(id), |_, old| { old.push(id); });
1128                         }
1129                     }
1130                     _ => {
1131                     }
1132                 }
1133             });
1134         }
1135
1136         let used_mutables = cx.tcx.used_mut_nodes.borrow();
1137         for (_, v) in mutables.iter() {
1138             if !v.iter().any(|e| used_mutables.contains(e)) {
1139                 cx.span_lint(UNUSED_MUT, cx.tcx.map.span(*v.get(0)),
1140                              "variable does not need to be mutable");
1141             }
1142         }
1143     }
1144 }
1145
1146 impl LintPass for UnusedMut {
1147     fn get_lints(&self) -> LintArray {
1148         lint_array!(UNUSED_MUT)
1149     }
1150
1151     fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
1152         match e.node {
1153             ast::ExprMatch(_, ref arms) => {
1154                 for a in arms.iter() {
1155                     self.check_unused_mut_pat(cx, a.pats.as_slice())
1156                 }
1157             }
1158             _ => {}
1159         }
1160     }
1161
1162     fn check_stmt(&mut self, cx: &Context, s: &ast::Stmt) {
1163         match s.node {
1164             ast::StmtDecl(d, _) => {
1165                 match d.node {
1166                     ast::DeclLocal(l) => {
1167                         self.check_unused_mut_pat(cx, &[l.pat]);
1168                     },
1169                     _ => {}
1170                 }
1171             },
1172             _ => {}
1173         }
1174     }
1175
1176     fn check_fn(&mut self, cx: &Context,
1177                 _: &visit::FnKind, decl: &ast::FnDecl,
1178                 _: &ast::Block, _: Span, _: ast::NodeId) {
1179         for a in decl.inputs.iter() {
1180             self.check_unused_mut_pat(cx, &[a.pat]);
1181         }
1182     }
1183 }
1184
1185 enum Allocation {
1186     VectorAllocation,
1187     BoxAllocation
1188 }
1189
1190 declare_lint!(UNNECESSARY_ALLOCATION, Warn,
1191               "detects unnecessary allocations that can be eliminated")
1192
1193 pub struct UnnecessaryAllocation;
1194
1195 impl LintPass for UnnecessaryAllocation {
1196     fn get_lints(&self) -> LintArray {
1197         lint_array!(UNNECESSARY_ALLOCATION)
1198     }
1199
1200     fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
1201         // Warn if string and vector literals with sigils, or boxing expressions,
1202         // are immediately borrowed.
1203         let allocation = match e.node {
1204             ast::ExprVstore(e2, ast::ExprVstoreUniq) => {
1205                 match e2.node {
1206                     ast::ExprLit(lit) if ast_util::lit_is_str(lit) => {
1207                         VectorAllocation
1208                     }
1209                     ast::ExprVec(..) => VectorAllocation,
1210                     _ => return
1211                 }
1212             }
1213             ast::ExprUnary(ast::UnUniq, _) |
1214             ast::ExprUnary(ast::UnBox, _) => BoxAllocation,
1215
1216             _ => return
1217         };
1218
1219         match cx.tcx.adjustments.borrow().find(&e.id) {
1220             Some(adjustment) => {
1221                 match *adjustment {
1222                     ty::AutoDerefRef(ty::AutoDerefRef { autoref, .. }) => {
1223                         match (allocation, autoref) {
1224                             (VectorAllocation, Some(ty::AutoBorrowVec(..))) => {
1225                                 cx.span_lint(UNNECESSARY_ALLOCATION, e.span,
1226                                              "unnecessary allocation, the sigil can be removed");
1227                             }
1228                             (BoxAllocation,
1229                              Some(ty::AutoPtr(_, ast::MutImmutable))) => {
1230                                 cx.span_lint(UNNECESSARY_ALLOCATION, e.span,
1231                                              "unnecessary allocation, use & instead");
1232                             }
1233                             (BoxAllocation,
1234                              Some(ty::AutoPtr(_, ast::MutMutable))) => {
1235                                 cx.span_lint(UNNECESSARY_ALLOCATION, e.span,
1236                                              "unnecessary allocation, use &mut instead");
1237                             }
1238                             _ => ()
1239                         }
1240                     }
1241                     _ => {}
1242                 }
1243             }
1244             _ => ()
1245         }
1246     }
1247 }
1248
1249 declare_lint!(MISSING_DOC, Allow,
1250               "detects missing documentation for public members")
1251
1252 pub struct MissingDoc {
1253     /// Stack of IDs of struct definitions.
1254     struct_def_stack: Vec<ast::NodeId>,
1255
1256     /// Stack of whether #[doc(hidden)] is set
1257     /// at each level which has lint attributes.
1258     doc_hidden_stack: Vec<bool>,
1259 }
1260
1261 impl MissingDoc {
1262     pub fn new() -> MissingDoc {
1263         MissingDoc {
1264             struct_def_stack: vec!(),
1265             doc_hidden_stack: vec!(false),
1266         }
1267     }
1268
1269     fn doc_hidden(&self) -> bool {
1270         *self.doc_hidden_stack.last().expect("empty doc_hidden_stack")
1271     }
1272
1273     fn check_missing_doc_attrs(&self,
1274                                cx: &Context,
1275                                id: Option<ast::NodeId>,
1276                                attrs: &[ast::Attribute],
1277                                sp: Span,
1278                                desc: &'static str) {
1279         // If we're building a test harness, then warning about
1280         // documentation is probably not really relevant right now.
1281         if cx.sess().opts.test { return }
1282
1283         // `#[doc(hidden)]` disables missing_doc check.
1284         if self.doc_hidden() { return }
1285
1286         // Only check publicly-visible items, using the result from the privacy pass.
1287         // It's an option so the crate root can also use this function (it doesn't
1288         // have a NodeId).
1289         match id {
1290             Some(ref id) if !cx.exported_items.contains(id) => return,
1291             _ => ()
1292         }
1293
1294         let has_doc = attrs.iter().any(|a| {
1295             match a.node.value.node {
1296                 ast::MetaNameValue(ref name, _) if name.equiv(&("doc")) => true,
1297                 _ => false
1298             }
1299         });
1300         if !has_doc {
1301             cx.span_lint(MISSING_DOC, sp,
1302                 format!("missing documentation for {}", desc).as_slice());
1303         }
1304     }
1305 }
1306
1307 impl LintPass for MissingDoc {
1308     fn get_lints(&self) -> LintArray {
1309         lint_array!(MISSING_DOC)
1310     }
1311
1312     fn enter_lint_attrs(&mut self, _: &Context, attrs: &[ast::Attribute]) {
1313         let doc_hidden = self.doc_hidden() || attrs.iter().any(|attr| {
1314             attr.check_name("doc") && match attr.meta_item_list() {
1315                 None => false,
1316                 Some(l) => attr::contains_name(l.as_slice(), "hidden"),
1317             }
1318         });
1319         self.doc_hidden_stack.push(doc_hidden);
1320     }
1321
1322     fn exit_lint_attrs(&mut self, _: &Context, _: &[ast::Attribute]) {
1323         self.doc_hidden_stack.pop().expect("empty doc_hidden_stack");
1324     }
1325
1326     fn check_struct_def(&mut self, _: &Context,
1327         _: &ast::StructDef, _: ast::Ident, _: &ast::Generics, id: ast::NodeId) {
1328         self.struct_def_stack.push(id);
1329     }
1330
1331     fn check_struct_def_post(&mut self, _: &Context,
1332         _: &ast::StructDef, _: ast::Ident, _: &ast::Generics, id: ast::NodeId) {
1333         let popped = self.struct_def_stack.pop().expect("empty struct_def_stack");
1334         assert!(popped == id);
1335     }
1336
1337     fn check_crate(&mut self, cx: &Context, krate: &ast::Crate) {
1338         self.check_missing_doc_attrs(cx, None, krate.attrs.as_slice(),
1339                                      krate.span, "crate");
1340     }
1341
1342     fn check_item(&mut self, cx: &Context, it: &ast::Item) {
1343         let desc = match it.node {
1344             ast::ItemFn(..) => "a function",
1345             ast::ItemMod(..) => "a module",
1346             ast::ItemEnum(..) => "an enum",
1347             ast::ItemStruct(..) => "a struct",
1348             ast::ItemTrait(..) => "a trait",
1349             _ => return
1350         };
1351         self.check_missing_doc_attrs(cx, Some(it.id), it.attrs.as_slice(),
1352                                      it.span, desc);
1353     }
1354
1355     fn check_fn(&mut self, cx: &Context,
1356             fk: &visit::FnKind, _: &ast::FnDecl,
1357             _: &ast::Block, _: Span, _: ast::NodeId) {
1358         match *fk {
1359             visit::FkMethod(_, _, m) => {
1360                 // If the method is an impl for a trait, don't doc.
1361                 if method_context(cx, m) == TraitImpl { return; }
1362
1363                 // Otherwise, doc according to privacy. This will also check
1364                 // doc for default methods defined on traits.
1365                 self.check_missing_doc_attrs(cx, Some(m.id), m.attrs.as_slice(),
1366                                              m.span, "a method");
1367             }
1368             _ => {}
1369         }
1370     }
1371
1372     fn check_ty_method(&mut self, cx: &Context, tm: &ast::TypeMethod) {
1373         self.check_missing_doc_attrs(cx, Some(tm.id), tm.attrs.as_slice(),
1374                                      tm.span, "a type method");
1375     }
1376
1377     fn check_struct_field(&mut self, cx: &Context, sf: &ast::StructField) {
1378         match sf.node.kind {
1379             ast::NamedField(_, vis) if vis == ast::Public => {
1380                 let cur_struct_def = *self.struct_def_stack.last()
1381                     .expect("empty struct_def_stack");
1382                 self.check_missing_doc_attrs(cx, Some(cur_struct_def),
1383                                              sf.node.attrs.as_slice(), sf.span,
1384                                              "a struct field")
1385             }
1386             _ => {}
1387         }
1388     }
1389
1390     fn check_variant(&mut self, cx: &Context, v: &ast::Variant, _: &ast::Generics) {
1391         self.check_missing_doc_attrs(cx, Some(v.node.id), v.node.attrs.as_slice(),
1392                                      v.span, "a variant");
1393     }
1394 }
1395
1396 declare_lint!(DEPRECATED, Warn,
1397               "detects use of #[deprecated] items")
1398
1399 // FIXME #6875: Change to Warn after std library stabilization is complete
1400 declare_lint!(EXPERIMENTAL, Allow,
1401               "detects use of #[experimental] items")
1402
1403 declare_lint!(UNSTABLE, Allow,
1404               "detects use of #[unstable] items (incl. items with no stability attribute)")
1405
1406 /// Checks for use of items with `#[deprecated]`, `#[experimental]` and
1407 /// `#[unstable]` attributes, or no stability attribute.
1408 pub struct Stability;
1409
1410 impl LintPass for Stability {
1411     fn get_lints(&self) -> LintArray {
1412         lint_array!(DEPRECATED, EXPERIMENTAL, UNSTABLE)
1413     }
1414
1415     fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
1416         let id = match e.node {
1417             ast::ExprPath(..) | ast::ExprStruct(..) => {
1418                 match cx.tcx.def_map.borrow().find(&e.id) {
1419                     Some(&def) => def.def_id(),
1420                     None => return
1421                 }
1422             }
1423             ast::ExprMethodCall(..) => {
1424                 let method_call = typeck::MethodCall::expr(e.id);
1425                 match cx.tcx.method_map.borrow().find(&method_call) {
1426                     Some(method) => {
1427                         match method.origin {
1428                             typeck::MethodStatic(def_id) => {
1429                                 // If this implements a trait method, get def_id
1430                                 // of the method inside trait definition.
1431                                 // Otherwise, use the current def_id (which refers
1432                                 // to the method inside impl).
1433                                 ty::trait_method_of_method(cx.tcx, def_id).unwrap_or(def_id)
1434                             }
1435                             typeck::MethodParam(typeck::MethodParam {
1436                                 trait_id: trait_id,
1437                                 method_num: index,
1438                                 ..
1439                             })
1440                             | typeck::MethodObject(typeck::MethodObject {
1441                                 trait_id: trait_id,
1442                                 method_num: index,
1443                                 ..
1444                             }) => ty::trait_method(cx.tcx, trait_id, index).def_id
1445                         }
1446                     }
1447                     None => return
1448                 }
1449             }
1450             _ => return
1451         };
1452
1453         // stability attributes are promises made across crates; do not
1454         // check anything for crate-local usage.
1455         if ast_util::is_local(id) { return }
1456
1457         let stability = cx.tcx.stability.borrow_mut().lookup(&cx.tcx.sess.cstore, id);
1458
1459         let (lint, label) = match stability {
1460             // no stability attributes == Unstable
1461             None => (UNSTABLE, "unmarked"),
1462             Some(attr::Stability { level: attr::Unstable, .. }) =>
1463                     (UNSTABLE, "unstable"),
1464             Some(attr::Stability { level: attr::Experimental, .. }) =>
1465                     (EXPERIMENTAL, "experimental"),
1466             Some(attr::Stability { level: attr::Deprecated, .. }) =>
1467                     (DEPRECATED, "deprecated"),
1468             _ => return
1469         };
1470
1471         let msg = match stability {
1472             Some(attr::Stability { text: Some(ref s), .. }) => {
1473                 format!("use of {} item: {}", label, *s)
1474             }
1475             _ => format!("use of {} item", label)
1476         };
1477
1478         cx.span_lint(lint, e.span, msg.as_slice());
1479     }
1480 }
1481
1482 declare_lint!(pub UNUSED_IMPORTS, Warn,
1483               "imports that are never used")
1484
1485 declare_lint!(pub UNNECESSARY_QUALIFICATION, Allow,
1486               "detects unnecessarily qualified names")
1487
1488 declare_lint!(pub UNRECOGNIZED_LINT, Warn,
1489               "unrecognized lint attribute")
1490
1491 declare_lint!(pub UNUSED_VARIABLE, Warn,
1492               "detect variables which are not used in any way")
1493
1494 declare_lint!(pub DEAD_ASSIGNMENT, Warn,
1495               "detect assignments that will never be read")
1496
1497 declare_lint!(pub DEAD_CODE, Warn,
1498               "detect piece of code that will never be used")
1499
1500 declare_lint!(pub VISIBLE_PRIVATE_TYPES, Warn,
1501               "detect use of private types in exported type signatures")
1502
1503 declare_lint!(pub UNREACHABLE_CODE, Warn,
1504               "detects unreachable code")
1505
1506 declare_lint!(pub WARNINGS, Warn,
1507               "mass-change the level for lints which produce warnings")
1508
1509 declare_lint!(pub UNKNOWN_FEATURES, Deny,
1510               "unknown features found in crate-level #[feature] directives")
1511
1512 declare_lint!(pub UNKNOWN_CRATE_TYPE, Deny,
1513               "unknown crate type found in #[crate_type] directive")
1514
1515 declare_lint!(pub VARIANT_SIZE_DIFFERENCE, Allow,
1516               "detects enums with widely varying variant sizes")
1517
1518 /// Does nothing as a lint pass, but registers some `Lint`s
1519 /// which are used by other parts of the compiler.
1520 pub struct HardwiredLints;
1521
1522 impl LintPass for HardwiredLints {
1523     fn get_lints(&self) -> LintArray {
1524         lint_array!(
1525             UNUSED_IMPORTS,
1526             UNNECESSARY_QUALIFICATION,
1527             UNRECOGNIZED_LINT,
1528             UNUSED_VARIABLE,
1529             DEAD_ASSIGNMENT,
1530             DEAD_CODE,
1531             VISIBLE_PRIVATE_TYPES,
1532             UNREACHABLE_CODE,
1533             WARNINGS,
1534             UNKNOWN_FEATURES,
1535             UNKNOWN_CRATE_TYPE,
1536             VARIANT_SIZE_DIFFERENCE
1537         )
1538     }
1539 }