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