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