]> git.lizzy.rs Git - rust.git/blob - src/librustc/lint/builtin.rs
Add a few more derivings to AST types
[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         let has_extern_repr = it.attrs.iter().fold(attr::ReprAny, |acc, attr| {
762             attr::find_repr_attr(cx.tcx.sess.diagnostic(), attr, acc)
763         }) == attr::ReprExtern;
764         if has_extern_repr { return }
765
766         match it.node {
767             ast::ItemTy(..) | ast::ItemStruct(..) => {
768                 check_case(cx, "type", it.ident, it.span)
769             }
770             ast::ItemTrait(..) => {
771                 check_case(cx, "trait", it.ident, it.span)
772             }
773             ast::ItemEnum(ref enum_definition, _) => {
774                 check_case(cx, "type", it.ident, it.span);
775                 for variant in enum_definition.variants.iter() {
776                     check_case(cx, "variant", variant.node.name, variant.span);
777                 }
778             }
779             _ => ()
780         }
781     }
782 }
783
784 #[deriving(PartialEq)]
785 enum MethodContext {
786     TraitDefaultImpl,
787     TraitImpl,
788     PlainImpl
789 }
790
791 fn method_context(cx: &Context, m: &ast::Method) -> MethodContext {
792     let did = ast::DefId {
793         krate: ast::LOCAL_CRATE,
794         node: m.id
795     };
796
797     match cx.tcx.methods.borrow().find_copy(&did) {
798         None => cx.sess().span_bug(m.span, "missing method descriptor?!"),
799         Some(md) => {
800             match md.container {
801                 ty::TraitContainer(..) => TraitDefaultImpl,
802                 ty::ImplContainer(cid) => {
803                     match ty::impl_trait_ref(cx.tcx, cid) {
804                         Some(..) => TraitImpl,
805                         None => PlainImpl
806                     }
807                 }
808             }
809         }
810     }
811 }
812
813 declare_lint!(NON_SNAKE_CASE_FUNCTIONS, Warn,
814               "methods and functions should have snake case names")
815
816 pub struct NonSnakeCaseFunctions;
817
818 impl NonSnakeCaseFunctions {
819     fn check_snake_case(&self, cx: &Context, sort: &str, ident: ast::Ident, span: Span) {
820         fn is_snake_case(ident: ast::Ident) -> bool {
821             let ident = token::get_ident(ident);
822             assert!(!ident.get().is_empty());
823             let ident = ident.get().trim_chars('_');
824
825             let mut allow_underscore = true;
826             ident.chars().all(|c| {
827                 allow_underscore = match c {
828                     c if c.is_lowercase() || c.is_digit() => true,
829                     '_' if allow_underscore => false,
830                     _ => return false,
831                 };
832                 true
833             })
834         }
835
836         fn to_snake_case(str: &str) -> String {
837             let mut words = vec![];
838             for s in str.split('_') {
839                 let mut buf = String::new();
840                 if s.is_empty() { continue; }
841                 for ch in s.chars() {
842                     if !buf.is_empty() && ch.is_uppercase() {
843                         words.push(buf);
844                         buf = String::new();
845                     }
846                     buf.push_char(ch.to_lowercase());
847                 }
848                 words.push(buf);
849             }
850             words.connect("_")
851         }
852
853         let s = token::get_ident(ident);
854
855         if !is_snake_case(ident) {
856             cx.span_lint(NON_SNAKE_CASE_FUNCTIONS, span,
857                 format!("{} `{}` should have a snake case name such as `{}`",
858                         sort, s, to_snake_case(s.get())).as_slice());
859         }
860     }
861 }
862
863 impl LintPass for NonSnakeCaseFunctions {
864     fn get_lints(&self) -> LintArray {
865         lint_array!(NON_SNAKE_CASE_FUNCTIONS)
866     }
867
868     fn check_fn(&mut self, cx: &Context,
869                 fk: &visit::FnKind, _: &ast::FnDecl,
870                 _: &ast::Block, span: Span, _: ast::NodeId) {
871         match *fk {
872             visit::FkMethod(ident, _, m) => match method_context(cx, m) {
873                 PlainImpl
874                     => self.check_snake_case(cx, "method", ident, span),
875                 TraitDefaultImpl
876                     => self.check_snake_case(cx, "trait method", ident, span),
877                 _ => (),
878             },
879             visit::FkItemFn(ident, _, _, _)
880                 => self.check_snake_case(cx, "function", ident, span),
881             _ => (),
882         }
883     }
884
885     fn check_ty_method(&mut self, cx: &Context, t: &ast::TypeMethod) {
886         self.check_snake_case(cx, "trait method", t.ident, t.span);
887     }
888 }
889
890 declare_lint!(NON_UPPERCASE_STATICS, Allow,
891               "static constants should have uppercase identifiers")
892
893 pub struct NonUppercaseStatics;
894
895 impl LintPass for NonUppercaseStatics {
896     fn get_lints(&self) -> LintArray {
897         lint_array!(NON_UPPERCASE_STATICS)
898     }
899
900     fn check_item(&mut self, cx: &Context, it: &ast::Item) {
901         match it.node {
902             // only check static constants
903             ast::ItemStatic(_, ast::MutImmutable, _) => {
904                 let s = token::get_ident(it.ident);
905                 // check for lowercase letters rather than non-uppercase
906                 // ones (some scripts don't have a concept of
907                 // upper/lowercase)
908                 if s.get().chars().any(|c| c.is_lowercase()) {
909                     cx.span_lint(NON_UPPERCASE_STATICS, it.span,
910                         format!("static constant `{}` should have an uppercase name \
911                                  such as `{}`",
912                                 s.get(), s.get().chars().map(|c| c.to_uppercase())
913                                 .collect::<String>().as_slice()).as_slice());
914                 }
915             }
916             _ => {}
917         }
918     }
919 }
920
921 declare_lint!(NON_UPPERCASE_PATTERN_STATICS, Warn,
922               "static constants in match patterns should be all caps")
923
924 pub struct NonUppercasePatternStatics;
925
926 impl LintPass for NonUppercasePatternStatics {
927     fn get_lints(&self) -> LintArray {
928         lint_array!(NON_UPPERCASE_PATTERN_STATICS)
929     }
930
931     fn check_pat(&mut self, cx: &Context, p: &ast::Pat) {
932         // Lint for constants that look like binding identifiers (#7526)
933         match (&p.node, cx.tcx.def_map.borrow().find(&p.id)) {
934             (&ast::PatIdent(_, ref path1, _), Some(&def::DefStatic(_, false))) => {
935                 let s = token::get_ident(path1.node);
936                 if s.get().chars().any(|c| c.is_lowercase()) {
937                     cx.span_lint(NON_UPPERCASE_PATTERN_STATICS, path1.span,
938                         format!("static constant in pattern `{}` should have an uppercase \
939                                  name such as `{}`",
940                                 s.get(), s.get().chars().map(|c| c.to_uppercase())
941                                     .collect::<String>().as_slice()).as_slice());
942                 }
943             }
944             _ => {}
945         }
946     }
947 }
948
949 declare_lint!(UPPERCASE_VARIABLES, Warn,
950               "variable and structure field names should start with a lowercase character")
951
952 pub struct UppercaseVariables;
953
954 impl LintPass for UppercaseVariables {
955     fn get_lints(&self) -> LintArray {
956         lint_array!(UPPERCASE_VARIABLES)
957     }
958
959     fn check_pat(&mut self, cx: &Context, p: &ast::Pat) {
960         match &p.node {
961             &ast::PatIdent(_, ref path1, _) => {
962                 match cx.tcx.def_map.borrow().find(&p.id) {
963                     Some(&def::DefLocal(_, _)) | Some(&def::DefBinding(_, _)) |
964                             Some(&def::DefArg(_, _)) => {
965                         let s = token::get_ident(path1.node);
966                         if s.get().len() > 0 && s.get().char_at(0).is_uppercase() {
967                             cx.span_lint(UPPERCASE_VARIABLES, path1.span,
968                                          "variable names should start with \
969                                           a lowercase character");
970                         }
971                     }
972                     _ => {}
973                 }
974             }
975             _ => {}
976         }
977     }
978
979     fn check_struct_def(&mut self, cx: &Context, s: &ast::StructDef,
980             _: ast::Ident, _: &ast::Generics, _: ast::NodeId) {
981         for sf in s.fields.iter() {
982             match sf.node {
983                 ast::StructField_ { kind: ast::NamedField(ident, _), .. } => {
984                     let s = token::get_ident(ident);
985                     if s.get().char_at(0).is_uppercase() {
986                         cx.span_lint(UPPERCASE_VARIABLES, sf.span,
987                                      "structure field names should start with \
988                                       a lowercase character");
989                     }
990                 }
991                 _ => {}
992             }
993         }
994     }
995 }
996
997 declare_lint!(UNNECESSARY_PARENS, Warn,
998               "`if`, `match`, `while` and `return` do not need parentheses")
999
1000 pub struct UnnecessaryParens;
1001
1002 impl UnnecessaryParens {
1003     fn check_unnecessary_parens_core(&self, cx: &Context, value: &ast::Expr, msg: &str,
1004                                      struct_lit_needs_parens: bool) {
1005         match value.node {
1006             ast::ExprParen(ref inner) => {
1007                 let necessary = struct_lit_needs_parens && contains_exterior_struct_lit(&**inner);
1008                 if !necessary {
1009                     cx.span_lint(UNNECESSARY_PARENS, value.span,
1010                                  format!("unnecessary parentheses around {}",
1011                                          msg).as_slice())
1012                 }
1013             }
1014             _ => {}
1015         }
1016
1017         /// Expressions that syntactically contain an "exterior" struct
1018         /// literal i.e. not surrounded by any parens or other
1019         /// delimiters, e.g. `X { y: 1 }`, `X { y: 1 }.method()`, `foo
1020         /// == X { y: 1 }` and `X { y: 1 } == foo` all do, but `(X {
1021         /// y: 1 }) == foo` does not.
1022         fn contains_exterior_struct_lit(value: &ast::Expr) -> bool {
1023             match value.node {
1024                 ast::ExprStruct(..) => true,
1025
1026                 ast::ExprAssign(ref lhs, ref rhs) |
1027                 ast::ExprAssignOp(_, ref lhs, ref rhs) |
1028                 ast::ExprBinary(_, ref lhs, ref rhs) => {
1029                     // X { y: 1 } + X { y: 2 }
1030                     contains_exterior_struct_lit(&**lhs) ||
1031                         contains_exterior_struct_lit(&**rhs)
1032                 }
1033                 ast::ExprUnary(_, ref x) |
1034                 ast::ExprCast(ref x, _) |
1035                 ast::ExprField(ref x, _, _) |
1036                 ast::ExprIndex(ref x, _) => {
1037                     // &X { y: 1 }, X { y: 1 }.y
1038                     contains_exterior_struct_lit(&**x)
1039                 }
1040
1041                 ast::ExprMethodCall(_, _, ref exprs) => {
1042                     // X { y: 1 }.bar(...)
1043                     contains_exterior_struct_lit(&**exprs.get(0))
1044                 }
1045
1046                 _ => false
1047             }
1048         }
1049     }
1050 }
1051
1052 impl LintPass for UnnecessaryParens {
1053     fn get_lints(&self) -> LintArray {
1054         lint_array!(UNNECESSARY_PARENS)
1055     }
1056
1057     fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
1058         let (value, msg, struct_lit_needs_parens) = match e.node {
1059             ast::ExprIf(cond, _, _) => (cond, "`if` condition", true),
1060             ast::ExprWhile(cond, _) => (cond, "`while` condition", true),
1061             ast::ExprMatch(head, _) => (head, "`match` head expression", true),
1062             ast::ExprRet(Some(value)) => (value, "`return` value", false),
1063             ast::ExprAssign(_, value) => (value, "assigned value", false),
1064             ast::ExprAssignOp(_, _, value) => (value, "assigned value", false),
1065             _ => return
1066         };
1067         self.check_unnecessary_parens_core(cx, &*value, msg, struct_lit_needs_parens);
1068     }
1069
1070     fn check_stmt(&mut self, cx: &Context, s: &ast::Stmt) {
1071         let (value, msg) = match s.node {
1072             ast::StmtDecl(decl, _) => match decl.node {
1073                 ast::DeclLocal(local) => match local.init {
1074                     Some(value) => (value, "assigned value"),
1075                     None => return
1076                 },
1077                 _ => return
1078             },
1079             _ => return
1080         };
1081         self.check_unnecessary_parens_core(cx, &*value, msg, false);
1082     }
1083 }
1084
1085 declare_lint!(UNUSED_UNSAFE, Warn,
1086               "unnecessary use of an `unsafe` block")
1087
1088 pub struct UnusedUnsafe;
1089
1090 impl LintPass for UnusedUnsafe {
1091     fn get_lints(&self) -> LintArray {
1092         lint_array!(UNUSED_UNSAFE)
1093     }
1094
1095     fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
1096         match e.node {
1097             // Don't warn about generated blocks, that'll just pollute the output.
1098             ast::ExprBlock(ref blk) => {
1099                 if blk.rules == ast::UnsafeBlock(ast::UserProvided) &&
1100                     !cx.tcx.used_unsafe.borrow().contains(&blk.id) {
1101                     cx.span_lint(UNUSED_UNSAFE, blk.span, "unnecessary `unsafe` block");
1102                 }
1103             }
1104             _ => ()
1105         }
1106     }
1107 }
1108
1109 declare_lint!(UNSAFE_BLOCK, Allow,
1110               "usage of an `unsafe` block")
1111
1112 pub struct UnsafeBlock;
1113
1114 impl LintPass for UnsafeBlock {
1115     fn get_lints(&self) -> LintArray {
1116         lint_array!(UNSAFE_BLOCK)
1117     }
1118
1119     fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
1120         match e.node {
1121             // Don't warn about generated blocks, that'll just pollute the output.
1122             ast::ExprBlock(ref blk) if blk.rules == ast::UnsafeBlock(ast::UserProvided) => {
1123                 cx.span_lint(UNSAFE_BLOCK, blk.span, "usage of an `unsafe` block");
1124             }
1125             _ => ()
1126         }
1127     }
1128 }
1129
1130 declare_lint!(UNUSED_MUT, Warn,
1131               "detect mut variables which don't need to be mutable")
1132
1133 pub struct UnusedMut;
1134
1135 impl UnusedMut {
1136     fn check_unused_mut_pat(&self, cx: &Context, pats: &[Gc<ast::Pat>]) {
1137         // collect all mutable pattern and group their NodeIDs by their Identifier to
1138         // avoid false warnings in match arms with multiple patterns
1139         let mut mutables = HashMap::new();
1140         for &p in pats.iter() {
1141             pat_util::pat_bindings(&cx.tcx.def_map, &*p, |mode, id, _, path1| {
1142                 let ident = path1.node;
1143                 match mode {
1144                     ast::BindByValue(ast::MutMutable) => {
1145                         if !token::get_ident(ident).get().starts_with("_") {
1146                             mutables.insert_or_update_with(ident.name.uint(),
1147                                 vec!(id), |_, old| { old.push(id); });
1148                         }
1149                     }
1150                     _ => {
1151                     }
1152                 }
1153             });
1154         }
1155
1156         let used_mutables = cx.tcx.used_mut_nodes.borrow();
1157         for (_, v) in mutables.iter() {
1158             if !v.iter().any(|e| used_mutables.contains(e)) {
1159                 cx.span_lint(UNUSED_MUT, cx.tcx.map.span(*v.get(0)),
1160                              "variable does not need to be mutable");
1161             }
1162         }
1163     }
1164 }
1165
1166 impl LintPass for UnusedMut {
1167     fn get_lints(&self) -> LintArray {
1168         lint_array!(UNUSED_MUT)
1169     }
1170
1171     fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
1172         match e.node {
1173             ast::ExprMatch(_, ref arms) => {
1174                 for a in arms.iter() {
1175                     self.check_unused_mut_pat(cx, a.pats.as_slice())
1176                 }
1177             }
1178             _ => {}
1179         }
1180     }
1181
1182     fn check_stmt(&mut self, cx: &Context, s: &ast::Stmt) {
1183         match s.node {
1184             ast::StmtDecl(d, _) => {
1185                 match d.node {
1186                     ast::DeclLocal(l) => {
1187                         self.check_unused_mut_pat(cx, &[l.pat]);
1188                     },
1189                     _ => {}
1190                 }
1191             },
1192             _ => {}
1193         }
1194     }
1195
1196     fn check_fn(&mut self, cx: &Context,
1197                 _: &visit::FnKind, decl: &ast::FnDecl,
1198                 _: &ast::Block, _: Span, _: ast::NodeId) {
1199         for a in decl.inputs.iter() {
1200             self.check_unused_mut_pat(cx, &[a.pat]);
1201         }
1202     }
1203 }
1204
1205 enum Allocation {
1206     VectorAllocation,
1207     BoxAllocation
1208 }
1209
1210 declare_lint!(UNNECESSARY_ALLOCATION, Warn,
1211               "detects unnecessary allocations that can be eliminated")
1212
1213 pub struct UnnecessaryAllocation;
1214
1215 impl LintPass for UnnecessaryAllocation {
1216     fn get_lints(&self) -> LintArray {
1217         lint_array!(UNNECESSARY_ALLOCATION)
1218     }
1219
1220     fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
1221         // Warn if string and vector literals with sigils, or boxing expressions,
1222         // are immediately borrowed.
1223         let allocation = match e.node {
1224             ast::ExprVstore(e2, ast::ExprVstoreUniq) => {
1225                 match e2.node {
1226                     ast::ExprLit(lit) if ast_util::lit_is_str(lit) => {
1227                         VectorAllocation
1228                     }
1229                     ast::ExprVec(..) => VectorAllocation,
1230                     _ => return
1231                 }
1232             }
1233             ast::ExprUnary(ast::UnUniq, _) |
1234             ast::ExprUnary(ast::UnBox, _) => BoxAllocation,
1235
1236             _ => return
1237         };
1238
1239         match cx.tcx.adjustments.borrow().find(&e.id) {
1240             Some(adjustment) => {
1241                 match *adjustment {
1242                     ty::AutoDerefRef(ty::AutoDerefRef { autoref, .. }) => {
1243                         match (allocation, autoref) {
1244                             (VectorAllocation, Some(ty::AutoBorrowVec(..))) => {
1245                                 cx.span_lint(UNNECESSARY_ALLOCATION, e.span,
1246                                              "unnecessary allocation, the sigil can be removed");
1247                             }
1248                             (BoxAllocation,
1249                              Some(ty::AutoPtr(_, ast::MutImmutable))) => {
1250                                 cx.span_lint(UNNECESSARY_ALLOCATION, e.span,
1251                                              "unnecessary allocation, use & instead");
1252                             }
1253                             (BoxAllocation,
1254                              Some(ty::AutoPtr(_, ast::MutMutable))) => {
1255                                 cx.span_lint(UNNECESSARY_ALLOCATION, e.span,
1256                                              "unnecessary allocation, use &mut instead");
1257                             }
1258                             _ => ()
1259                         }
1260                     }
1261                     _ => {}
1262                 }
1263             }
1264             _ => ()
1265         }
1266     }
1267 }
1268
1269 declare_lint!(MISSING_DOC, Allow,
1270               "detects missing documentation for public members")
1271
1272 pub struct MissingDoc {
1273     /// Stack of IDs of struct definitions.
1274     struct_def_stack: Vec<ast::NodeId>,
1275
1276     /// Stack of whether #[doc(hidden)] is set
1277     /// at each level which has lint attributes.
1278     doc_hidden_stack: Vec<bool>,
1279 }
1280
1281 impl MissingDoc {
1282     pub fn new() -> MissingDoc {
1283         MissingDoc {
1284             struct_def_stack: vec!(),
1285             doc_hidden_stack: vec!(false),
1286         }
1287     }
1288
1289     fn doc_hidden(&self) -> bool {
1290         *self.doc_hidden_stack.last().expect("empty doc_hidden_stack")
1291     }
1292
1293     fn check_missing_doc_attrs(&self,
1294                                cx: &Context,
1295                                id: Option<ast::NodeId>,
1296                                attrs: &[ast::Attribute],
1297                                sp: Span,
1298                                desc: &'static str) {
1299         // If we're building a test harness, then warning about
1300         // documentation is probably not really relevant right now.
1301         if cx.sess().opts.test { return }
1302
1303         // `#[doc(hidden)]` disables missing_doc check.
1304         if self.doc_hidden() { return }
1305
1306         // Only check publicly-visible items, using the result from the privacy pass.
1307         // It's an option so the crate root can also use this function (it doesn't
1308         // have a NodeId).
1309         match id {
1310             Some(ref id) if !cx.exported_items.contains(id) => return,
1311             _ => ()
1312         }
1313
1314         let has_doc = attrs.iter().any(|a| {
1315             match a.node.value.node {
1316                 ast::MetaNameValue(ref name, _) if name.equiv(&("doc")) => true,
1317                 _ => false
1318             }
1319         });
1320         if !has_doc {
1321             cx.span_lint(MISSING_DOC, sp,
1322                 format!("missing documentation for {}", desc).as_slice());
1323         }
1324     }
1325 }
1326
1327 impl LintPass for MissingDoc {
1328     fn get_lints(&self) -> LintArray {
1329         lint_array!(MISSING_DOC)
1330     }
1331
1332     fn enter_lint_attrs(&mut self, _: &Context, attrs: &[ast::Attribute]) {
1333         let doc_hidden = self.doc_hidden() || attrs.iter().any(|attr| {
1334             attr.check_name("doc") && match attr.meta_item_list() {
1335                 None => false,
1336                 Some(l) => attr::contains_name(l.as_slice(), "hidden"),
1337             }
1338         });
1339         self.doc_hidden_stack.push(doc_hidden);
1340     }
1341
1342     fn exit_lint_attrs(&mut self, _: &Context, _: &[ast::Attribute]) {
1343         self.doc_hidden_stack.pop().expect("empty doc_hidden_stack");
1344     }
1345
1346     fn check_struct_def(&mut self, _: &Context,
1347         _: &ast::StructDef, _: ast::Ident, _: &ast::Generics, id: ast::NodeId) {
1348         self.struct_def_stack.push(id);
1349     }
1350
1351     fn check_struct_def_post(&mut self, _: &Context,
1352         _: &ast::StructDef, _: ast::Ident, _: &ast::Generics, id: ast::NodeId) {
1353         let popped = self.struct_def_stack.pop().expect("empty struct_def_stack");
1354         assert!(popped == id);
1355     }
1356
1357     fn check_crate(&mut self, cx: &Context, krate: &ast::Crate) {
1358         self.check_missing_doc_attrs(cx, None, krate.attrs.as_slice(),
1359                                      krate.span, "crate");
1360     }
1361
1362     fn check_item(&mut self, cx: &Context, it: &ast::Item) {
1363         let desc = match it.node {
1364             ast::ItemFn(..) => "a function",
1365             ast::ItemMod(..) => "a module",
1366             ast::ItemEnum(..) => "an enum",
1367             ast::ItemStruct(..) => "a struct",
1368             ast::ItemTrait(..) => "a trait",
1369             _ => return
1370         };
1371         self.check_missing_doc_attrs(cx, Some(it.id), it.attrs.as_slice(),
1372                                      it.span, desc);
1373     }
1374
1375     fn check_fn(&mut self, cx: &Context,
1376             fk: &visit::FnKind, _: &ast::FnDecl,
1377             _: &ast::Block, _: Span, _: ast::NodeId) {
1378         match *fk {
1379             visit::FkMethod(_, _, m) => {
1380                 // If the method is an impl for a trait, don't doc.
1381                 if method_context(cx, m) == TraitImpl { return; }
1382
1383                 // Otherwise, doc according to privacy. This will also check
1384                 // doc for default methods defined on traits.
1385                 self.check_missing_doc_attrs(cx, Some(m.id), m.attrs.as_slice(),
1386                                              m.span, "a method");
1387             }
1388             _ => {}
1389         }
1390     }
1391
1392     fn check_ty_method(&mut self, cx: &Context, tm: &ast::TypeMethod) {
1393         self.check_missing_doc_attrs(cx, Some(tm.id), tm.attrs.as_slice(),
1394                                      tm.span, "a type method");
1395     }
1396
1397     fn check_struct_field(&mut self, cx: &Context, sf: &ast::StructField) {
1398         match sf.node.kind {
1399             ast::NamedField(_, vis) if vis == ast::Public => {
1400                 let cur_struct_def = *self.struct_def_stack.last()
1401                     .expect("empty struct_def_stack");
1402                 self.check_missing_doc_attrs(cx, Some(cur_struct_def),
1403                                              sf.node.attrs.as_slice(), sf.span,
1404                                              "a struct field")
1405             }
1406             _ => {}
1407         }
1408     }
1409
1410     fn check_variant(&mut self, cx: &Context, v: &ast::Variant, _: &ast::Generics) {
1411         self.check_missing_doc_attrs(cx, Some(v.node.id), v.node.attrs.as_slice(),
1412                                      v.span, "a variant");
1413     }
1414 }
1415
1416 declare_lint!(DEPRECATED, Warn,
1417               "detects use of #[deprecated] items")
1418
1419 // FIXME #6875: Change to Warn after std library stabilization is complete
1420 declare_lint!(EXPERIMENTAL, Allow,
1421               "detects use of #[experimental] items")
1422
1423 declare_lint!(UNSTABLE, Allow,
1424               "detects use of #[unstable] items (incl. items with no stability attribute)")
1425
1426 /// Checks for use of items with `#[deprecated]`, `#[experimental]` and
1427 /// `#[unstable]` attributes, or no stability attribute.
1428 pub struct Stability;
1429
1430 impl LintPass for Stability {
1431     fn get_lints(&self) -> LintArray {
1432         lint_array!(DEPRECATED, EXPERIMENTAL, UNSTABLE)
1433     }
1434
1435     fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
1436         // if the expression was produced by a macro expansion,
1437         if e.span.expn_info.is_some() { return }
1438
1439         let id = match e.node {
1440             ast::ExprPath(..) | ast::ExprStruct(..) => {
1441                 match cx.tcx.def_map.borrow().find(&e.id) {
1442                     Some(&def) => def.def_id(),
1443                     None => return
1444                 }
1445             }
1446             ast::ExprMethodCall(..) => {
1447                 let method_call = typeck::MethodCall::expr(e.id);
1448                 match cx.tcx.method_map.borrow().find(&method_call) {
1449                     Some(method) => {
1450                         match method.origin {
1451                             typeck::MethodStatic(def_id) => {
1452                                 def_id
1453                             }
1454                             typeck::MethodStaticUnboxedClosure(def_id) => {
1455                                 def_id
1456                             }
1457                             typeck::MethodParam(typeck::MethodParam {
1458                                 trait_id: trait_id,
1459                                 method_num: index,
1460                                 ..
1461                             })
1462                             | typeck::MethodObject(typeck::MethodObject {
1463                                 trait_id: trait_id,
1464                                 method_num: index,
1465                                 ..
1466                             }) => ty::trait_method(cx.tcx, trait_id, index).def_id
1467                         }
1468                     }
1469                     None => return
1470                 }
1471             }
1472             _ => return
1473         };
1474
1475         // stability attributes are promises made across crates; do not
1476         // check anything for crate-local usage.
1477         if ast_util::is_local(id) { return }
1478
1479         let stability = stability::lookup(cx.tcx, id);
1480         let (lint, label) = match stability {
1481             // no stability attributes == Unstable
1482             None => (UNSTABLE, "unmarked"),
1483             Some(attr::Stability { level: attr::Unstable, .. }) =>
1484                     (UNSTABLE, "unstable"),
1485             Some(attr::Stability { level: attr::Experimental, .. }) =>
1486                     (EXPERIMENTAL, "experimental"),
1487             Some(attr::Stability { level: attr::Deprecated, .. }) =>
1488                     (DEPRECATED, "deprecated"),
1489             _ => return
1490         };
1491
1492         let msg = match stability {
1493             Some(attr::Stability { text: Some(ref s), .. }) => {
1494                 format!("use of {} item: {}", label, *s)
1495             }
1496             _ => format!("use of {} item", label)
1497         };
1498
1499         cx.span_lint(lint, e.span, msg.as_slice());
1500     }
1501 }
1502
1503 declare_lint!(pub UNUSED_IMPORTS, Warn,
1504               "imports that are never used")
1505
1506 declare_lint!(pub UNNECESSARY_QUALIFICATION, Allow,
1507               "detects unnecessarily qualified names")
1508
1509 declare_lint!(pub UNRECOGNIZED_LINT, Warn,
1510               "unrecognized lint attribute")
1511
1512 declare_lint!(pub UNUSED_VARIABLE, Warn,
1513               "detect variables which are not used in any way")
1514
1515 declare_lint!(pub DEAD_ASSIGNMENT, Warn,
1516               "detect assignments that will never be read")
1517
1518 declare_lint!(pub DEAD_CODE, Warn,
1519               "detect piece of code that will never be used")
1520
1521 declare_lint!(pub VISIBLE_PRIVATE_TYPES, Warn,
1522               "detect use of private types in exported type signatures")
1523
1524 declare_lint!(pub UNREACHABLE_CODE, Warn,
1525               "detects unreachable code")
1526
1527 declare_lint!(pub WARNINGS, Warn,
1528               "mass-change the level for lints which produce warnings")
1529
1530 declare_lint!(pub UNKNOWN_FEATURES, Deny,
1531               "unknown features found in crate-level #[feature] directives")
1532
1533 declare_lint!(pub UNKNOWN_CRATE_TYPE, Deny,
1534               "unknown crate type found in #[crate_type] directive")
1535
1536 declare_lint!(pub VARIANT_SIZE_DIFFERENCE, Allow,
1537               "detects enums with widely varying variant sizes")
1538
1539 /// Does nothing as a lint pass, but registers some `Lint`s
1540 /// which are used by other parts of the compiler.
1541 pub struct HardwiredLints;
1542
1543 impl LintPass for HardwiredLints {
1544     fn get_lints(&self) -> LintArray {
1545         lint_array!(
1546             UNUSED_IMPORTS,
1547             UNNECESSARY_QUALIFICATION,
1548             UNRECOGNIZED_LINT,
1549             UNUSED_VARIABLE,
1550             DEAD_ASSIGNMENT,
1551             DEAD_CODE,
1552             VISIBLE_PRIVATE_TYPES,
1553             UNREACHABLE_CODE,
1554             WARNINGS,
1555             UNKNOWN_FEATURES,
1556             UNKNOWN_CRATE_TYPE,
1557             VARIANT_SIZE_DIFFERENCE
1558         )
1559     }
1560 }