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.
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.
11 //! Lints built in to rustc.
13 use metadata::csearch;
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};
26 use std::collections::HashMap;
35 use std::default::Default;
38 use syntax::attr::AttrMetaMethods;
40 use syntax::codemap::Span;
41 use syntax::parse::token;
42 use syntax::{ast, ast_util, visit};
44 declare_lint!(while_true, Warn,
45 "suggest using `loop { }` instead of `while true { }`")
50 impl LintPass for WhileTrue {
51 fn get_lints(&self) -> LintArray {
52 lint_array!(while_true)
55 fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
57 ast::ExprWhile(cond, _) => {
59 ast::ExprLit(lit) => {
61 ast::LitBool(true) => {
62 cx.span_lint(while_true, e.span,
63 "denote infinite loops with loop \
77 declare_lint!(unnecessary_typecast, Allow,
78 "detects unnecessary type casts, that can be removed")
81 pub struct UnusedCasts;
83 impl LintPass for UnusedCasts {
84 fn get_lints(&self) -> LintArray {
85 lint_array!(unnecessary_typecast)
88 fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
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");
101 declare_lint!(unsigned_negate, Warn,
102 "using an unary minus operator on unsigned type")
104 declare_lint!(type_limits, Warn,
105 "comparisons made useless by limits of the types involved")
107 declare_lint!(type_overflow, Warn,
108 "literal out of range for its type")
110 pub struct TypeLimits {
111 /// Id of the last visited negated expression
112 negated_expr_id: ast::NodeId,
115 impl Default for TypeLimits {
116 fn default() -> TypeLimits {
123 impl LintPass for TypeLimits {
124 fn get_lints(&self) -> LintArray {
125 lint_array!(unsigned_negate, type_limits, type_overflow)
128 fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
130 ast::ExprUnary(ast::UnNeg, expr) => {
132 ast::ExprLit(lit) => {
134 ast::LitUint(..) => {
135 cx.span_lint(unsigned_negate, e.span,
136 "negation of unsigned int literal may \
143 let t = ty::expr_ty(cx.tcx, expr);
144 match ty::get(t).sty {
146 cx.span_lint(unsigned_negate, e.span,
147 "negation of unsigned int variable may \
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;
159 ast::ExprParen(expr) if self.negated_expr_id == e.id => {
160 self.negated_expr_id = expr.id;
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");
168 ast::ExprLit(lit) => {
169 match ty::get(ty::expr_ty(cx.tcx, e)).sty {
171 let int_type = if t == ast::TyI {
172 cx.tcx.sess.targ_cfg.int_type
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,
181 if self.negated_expr_id == e.id {
184 if lit_val < min || lit_val > max {
185 cx.span_lint(type_overflow, e.span,
186 "literal out of range for its type");
190 let uint_type = if t == ast::TyU {
191 cx.tcx.sess.targ_cfg.uint_type
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,
200 if lit_val < min || lit_val > max {
201 cx.span_lint(type_overflow, e.span,
202 "literal out of range for its type");
212 fn is_valid<T:cmp::PartialOrd>(binop: ast::BinOp, v: T,
213 min: T, max: T) -> bool {
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,
224 fn rev_binop(binop: ast::BinOp) -> ast::BinOp {
226 ast::BiLt => ast::BiGt,
227 ast::BiLe => ast::BiGe,
228 ast::BiGt => ast::BiLt,
229 ast::BiGe => ast::BiLe,
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) {
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)
246 fn uint_ty_range(uint_ty: ast::UintTy) -> (u64, u64) {
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)
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),
263 // Normalize the binop so that the literal is always on the RHS in
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,
278 is_valid(norm_binop, lit_val, min, max)
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,
291 is_valid(norm_binop, lit_val, min, max)
297 fn is_comparison(binop: ast::BinOp) -> bool {
299 ast::BiEq | ast::BiLt | ast::BiLe |
300 ast::BiNe | ast::BiGe | ast::BiGt => true,
307 declare_lint!(ctypes, Warn,
308 "proper use of libc types in foreign modules")
313 impl LintPass for CTypes {
314 fn get_lints(&self) -> LintArray {
318 fn check_item(&mut self, cx: &Context, it: &ast::Item) {
319 fn check_ty(cx: &Context, ty: &ast::Ty) {
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");
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");
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
344 ast::TyPtr(ref mt) => { check_ty(cx, mt.ty) }
349 fn check_foreign_fn(cx: &Context, decl: &ast::FnDecl) {
350 for input in decl.inputs.iter() {
351 check_ty(cx, input.ty);
353 check_ty(cx, decl.output)
357 ast::ItemForeignMod(ref nmod) if nmod.abi != abi::RustIntrinsic => {
358 for ni in nmod.items.iter() {
360 ast::ForeignItemFn(decl, _) => check_foreign_fn(cx, decl),
361 ast::ForeignItemStatic(t, _) => check_ty(cx, t)
365 _ => {/* nothing to do */ }
370 declare_lint!(managed_heap_memory, Allow,
371 "use of managed (@ type) heap memory")
373 declare_lint!(owned_heap_memory, Allow,
374 "use of owned (Box type) heap memory")
376 declare_lint!(heap_memory, Allow,
377 "use of any (Box type or @ type) heap memory")
380 pub struct HeapMemory;
383 fn check_heap_type(&self, cx: &Context, span: Span, ty: ty::t) {
386 ty::fold_ty(cx.tcx, ty, |t| {
387 match ty::get(t).sty {
392 ty::ty_trait(box ty::TyTrait {
393 store: ty::UniqTraitStore, ..
395 ty::ty_closure(box ty::ClosureTy {
396 store: ty::UniqTraitStore,
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());
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());
423 impl LintPass for HeapMemory {
424 fn get_lints(&self) -> LintArray {
425 lint_array!(managed_heap_memory, owned_heap_memory, heap_memory)
428 fn check_item(&mut self, cx: &Context, it: &ast::Item) {
433 ast::ItemStruct(..) => self.check_heap_type(cx, it.span,
434 ty::node_id_to_type(cx.tcx,
439 // If it's a struct, we also have to check the fields' types
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));
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);
458 declare_lint!(raw_pointer_deriving, Warn,
459 "uses of #[deriving] with raw pointers are rarely correct")
461 struct RawPtrDerivingVisitor<'a> {
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";
469 ast::TyPtr(..) => self.cx.span_lint(raw_pointer_deriving, ty.span, MSG),
472 visit::walk_ty(self, ty, ());
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, _: ()) {}
479 pub struct RawPointerDeriving {
480 checked_raw_pointers: NodeSet,
483 impl Default for RawPointerDeriving {
484 fn default() -> RawPointerDeriving {
486 checked_raw_pointers: NodeSet::new(),
491 impl LintPass for RawPointerDeriving {
492 fn get_lints(&self) -> LintArray {
493 lint_array!(raw_pointer_deriving)
496 fn check_item(&mut self, cx: &Context, item: &ast::Item) {
497 if !attr::contains_name(item.attrs.as_slice(), "automatically_derived") {
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,
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,
515 if !self.checked_raw_pointers.insert(item.id) { return }
517 ast::ItemStruct(..) | ast::ItemEnum(..) => {
518 let mut visitor = RawPtrDerivingVisitor { cx: cx };
519 visit::walk_item(&mut visitor, item, ());
526 declare_lint!(unused_attribute, Warn,
527 "detects attributes that were not used by the compiler")
530 pub struct UnusedAttribute;
532 impl LintPass for UnusedAttribute {
533 fn get_lints(&self) -> LintArray {
534 lint_array!(unused_attribute)
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
542 // FIXME: #14406 these are processed in trans, which happens after the
544 "address_insignificant",
557 // not used anywhere (!?) but apparently we want to keep them around
562 // FIXME: #14407 these are only looked at on-demand so we can't
563 // guarantee they'll have already been checked
573 static CRATE_ATTRS: &'static [&'static str] = &'static [
587 for &name in ATTRIBUTE_WHITELIST.iter() {
588 if attr.check_name(name) {
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 \
602 cx.span_lint(unused_attribute, attr.span, msg);
608 declare_lint!(path_statement, Warn,
609 "path statements with no effect")
612 pub struct PathStatement;
614 impl LintPass for PathStatement {
615 fn get_lints(&self) -> LintArray {
616 lint_array!(path_statement)
619 fn check_stmt(&mut self, cx: &Context, s: &ast::Stmt) {
621 ast::StmtSemi(expr, _) => {
623 ast::ExprPath(_) => cx.span_lint(path_statement, s.span,
624 "path statement with no effect"),
633 declare_lint!(unused_must_use, Warn,
634 "unused result of a type flagged as #[must_use]")
636 declare_lint!(unused_result, Allow,
637 "unused result of an expression in a statement")
640 pub struct UnusedResult;
642 impl LintPass for UnusedResult {
643 fn get_lints(&self) -> LintArray {
644 lint_array!(unused_must_use, unused_result)
647 fn check_stmt(&mut self, cx: &Context, s: &ast::Stmt) {
648 let expr = match s.node {
649 ast::StmtSemi(expr, _) => expr,
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,
658 ast::ExprRet(..) => return,
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(),
672 cx.span_lint(unused_must_use, s.span,
673 "unused result which must be used");
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");
692 cx.span_lint(unused_result, s.span, "unused result");
697 declare_lint!(deprecated_owned_vector, Allow,
698 "use of a `~[T]` vector")
701 pub struct DeprecatedOwnedVector;
703 impl LintPass for DeprecatedOwnedVector {
704 fn get_lints(&self) -> LintArray {
705 lint_array!(deprecated_owned_vector)
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`")
723 declare_lint!(non_camel_case_types, Warn,
724 "types, variants and traits should have camel case names")
727 pub struct NonCamelCaseTypes;
729 impl LintPass for NonCamelCaseTypes {
730 fn get_lints(&self) -> LintArray {
731 lint_array!(non_camel_case_types)
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('_');
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('_')
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() }
752 fn check_case(cx: &Context, sort: &str, ident: ast::Ident, span: Span) {
753 let s = token::get_ident(ident);
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());
763 ast::ItemTy(..) | ast::ItemStruct(..) => {
764 check_case(cx, "type", it.ident, it.span)
766 ast::ItemTrait(..) => {
767 check_case(cx, "trait", it.ident, it.span)
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);
780 #[deriving(PartialEq)]
787 fn method_context(cx: &Context, m: &ast::Method) -> MethodContext {
788 let did = ast::DefId {
789 krate: ast::LOCAL_CRATE,
793 match cx.tcx.methods.borrow().find_copy(&did) {
794 None => cx.tcx.sess.span_bug(m.span, "missing method descriptor?!"),
797 ty::TraitContainer(..) => TraitDefaultImpl,
798 ty::ImplContainer(cid) => {
799 match ty::impl_trait_ref(cx.tcx, cid) {
800 Some(..) => TraitImpl,
809 declare_lint!(non_snake_case_functions, Warn,
810 "methods and functions should have snake case names")
813 pub struct NonSnakeCaseFunctions;
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('_');
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,
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() {
843 buf.push_char(ch.to_lowercase());
850 let s = token::get_ident(ident);
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());
860 impl LintPass for NonSnakeCaseFunctions {
861 fn get_lints(&self) -> LintArray {
862 lint_array!(non_snake_case_functions)
865 fn check_fn(&mut self, cx: &Context,
866 fk: &visit::FnKind, _: &ast::FnDecl,
867 _: &ast::Block, span: Span, _: ast::NodeId) {
869 visit::FkMethod(ident, _, m) => match method_context(cx, m) {
871 => self.check_snake_case(cx, "method", ident, span),
873 => self.check_snake_case(cx, "trait method", ident, span),
876 visit::FkItemFn(ident, _, _, _)
877 => self.check_snake_case(cx, "function", ident, span),
882 fn check_ty_method(&mut self, cx: &Context, t: &ast::TypeMethod) {
883 self.check_snake_case(cx, "trait method", t.ident, t.span);
887 declare_lint!(non_uppercase_statics, Allow,
888 "static constants should have uppercase identifiers")
891 pub struct NonUppercaseStatics;
893 impl LintPass for NonUppercaseStatics {
894 fn get_lints(&self) -> LintArray {
895 lint_array!(non_uppercase_statics)
898 fn check_item(&mut self, cx: &Context, it: &ast::Item) {
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
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());
919 declare_lint!(non_uppercase_pattern_statics, Warn,
920 "static constants in match patterns should be all caps")
923 pub struct NonUppercasePatternStatics;
925 impl LintPass for NonUppercasePatternStatics {
926 fn get_lints(&self) -> LintArray {
927 lint_array!(non_uppercase_pattern_statics)
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());
950 declare_lint!(uppercase_variables, Warn,
951 "variable and structure field names should start with a lowercase character")
954 pub struct UppercaseVariables;
956 impl LintPass for UppercaseVariables {
957 fn get_lints(&self) -> LintArray {
958 lint_array!(uppercase_variables)
961 fn check_pat(&mut self, cx: &Context, p: &ast::Pat) {
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");
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() {
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");
999 declare_lint!(unnecessary_parens, Warn,
1000 "`if`, `match`, `while` and `return` do not need parentheses")
1002 #[deriving(Default)]
1003 pub struct UnnecessaryParens;
1005 impl UnnecessaryParens {
1006 fn check_unnecessary_parens_core(&self, cx: &Context, value: &ast::Expr, msg: &str) {
1008 ast::ExprParen(_) => {
1009 cx.span_lint(unnecessary_parens, value.span,
1010 format!("unnecessary parentheses around {}", msg).as_slice())
1017 impl LintPass for UnnecessaryParens {
1018 fn get_lints(&self) -> LintArray {
1019 lint_array!(unnecessary_parens)
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"),
1032 self.check_unnecessary_parens_core(cx, value, msg);
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"),
1046 self.check_unnecessary_parens_core(cx, value, msg);
1050 declare_lint!(unused_unsafe, Warn,
1051 "unnecessary use of an `unsafe` block")
1053 #[deriving(Default)]
1054 pub struct UnusedUnsafe;
1056 impl LintPass for UnusedUnsafe {
1057 fn get_lints(&self) -> LintArray {
1058 lint_array!(unused_unsafe)
1061 fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
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");
1075 declare_lint!(unsafe_block, Allow,
1076 "usage of an `unsafe` block")
1078 #[deriving(Default)]
1079 pub struct UnsafeBlock;
1081 impl LintPass for UnsafeBlock {
1082 fn get_lints(&self) -> LintArray {
1083 lint_array!(unsafe_block)
1086 fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
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");
1097 declare_lint!(unused_mut, Warn,
1098 "detect mut variables which don't need to be mutable")
1100 #[deriving(Default)]
1101 pub struct 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| {
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");
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| {
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");
1140 impl LintPass for UnusedMut {
1141 fn get_lints(&self) -> LintArray {
1142 lint_array!(unused_mut)
1145 fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
1147 ast::ExprMatch(_, ref arms) => {
1148 for a in arms.iter() {
1149 self.check_unused_mut_pat(cx, a.pats.as_slice())
1156 fn check_stmt(&mut self, cx: &Context, s: &ast::Stmt) {
1158 ast::StmtDecl(d, _) => {
1160 ast::DeclLocal(l) => {
1161 self.check_unused_mut_pat(cx, &[l.pat]);
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]);
1184 declare_lint!(unnecessary_allocation, Warn,
1185 "detects unnecessary allocations that can be eliminated")
1187 #[deriving(Default)]
1188 pub struct UnnecessaryAllocation;
1190 impl LintPass for UnnecessaryAllocation {
1191 fn get_lints(&self) -> LintArray {
1192 lint_array!(unnecessary_allocation)
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) => {
1201 ast::ExprLit(lit) if ast_util::lit_is_str(lit) => {
1204 ast::ExprVec(..) => VectorAllocation,
1208 ast::ExprUnary(ast::UnUniq, _) |
1209 ast::ExprUnary(ast::UnBox, _) => BoxAllocation,
1214 match cx.tcx.adjustments.borrow().find(&e.id) {
1215 Some(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");
1224 Some(ty::AutoPtr(_, ast::MutImmutable))) => {
1225 cx.span_lint(unnecessary_allocation, e.span,
1226 "unnecessary allocation, use & instead");
1229 Some(ty::AutoPtr(_, ast::MutMutable))) => {
1230 cx.span_lint(unnecessary_allocation, e.span,
1231 "unnecessary allocation, use &mut instead");
1244 declare_lint!(missing_doc, Allow,
1245 "detects missing documentation for public members")
1247 pub struct MissingDoc {
1248 /// Set of nodes exported from this module.
1249 exported_items: Option<ExportedItems>,
1251 /// Stack of IDs of struct definitions.
1252 struct_def_stack: Vec<ast::NodeId>,
1254 /// Stack of whether #[doc(hidden)] is set
1255 /// at each level which has lint attributes.
1256 doc_hidden_stack: Vec<bool>,
1259 impl Default for MissingDoc {
1260 fn default() -> MissingDoc {
1262 exported_items: None,
1263 struct_def_stack: vec!(),
1264 doc_hidden_stack: vec!(false),
1270 fn doc_hidden(&self) -> bool {
1271 *self.doc_hidden_stack.last().expect("empty doc_hidden_stack")
1274 fn check_missing_doc_attrs(&self,
1276 id: Option<ast::NodeId>,
1277 attrs: &[ast::Attribute],
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 }
1284 // `#[doc(hidden)]` disables missing_doc check.
1285 if self.doc_hidden() { return }
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
1290 let exported = self.exported_items.as_ref().expect("exported_items not set");
1292 Some(ref id) if !exported.contains(id) => return,
1296 let has_doc = attrs.iter().any(|a| {
1297 match a.node.value.node {
1298 ast::MetaNameValue(ref name, _) if name.equiv(&("doc")) => true,
1303 cx.span_lint(missing_doc, sp,
1304 format!("missing documentation for {}", desc).as_slice());
1309 impl LintPass for MissingDoc {
1310 fn get_lints(&self) -> LintArray {
1311 lint_array!(missing_doc)
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() {
1318 Some(l) => attr::contains_name(l.as_slice(), "hidden"),
1321 self.doc_hidden_stack.push(doc_hidden);
1324 fn exit_lint_attrs(&mut self, _: &Context, _: &[ast::Attribute]) {
1325 self.doc_hidden_stack.pop().expect("empty doc_hidden_stack");
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);
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);
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());
1343 self.check_missing_doc_attrs(cx, None, krate.attrs.as_slice(),
1344 krate.span, "crate");
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",
1356 self.check_missing_doc_attrs(cx, Some(it.id), it.attrs.as_slice(),
1360 fn check_fn(&mut self, cx: &Context,
1361 fk: &visit::FnKind, _: &ast::FnDecl, _: &ast::Block, _: Span, _: ast::NodeId) {
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; }
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");
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");
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")
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");
1398 declare_lint!(deprecated, Warn,
1399 "detects use of #[deprecated] items")
1401 declare_lint!(experimental, Warn,
1402 "detects use of #[experimental] items")
1404 declare_lint!(unstable, Allow,
1405 "detects use of #[unstable] items (incl. items with no stability attribute)")
1407 /// Checks for use of items with #[deprecated], #[experimental] and
1408 /// #[unstable] (or none of them) attributes.
1409 #[deriving(Default)]
1410 pub struct Stability;
1412 impl LintPass for Stability {
1413 fn get_lints(&self) -> LintArray {
1414 lint_array!(deprecated, experimental, unstable)
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(),
1425 ast::ExprMethodCall(..) => {
1426 let method_call = typeck::MethodCall::expr(e.id);
1427 match cx.tcx.method_map.borrow().find(&method_call) {
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)
1438 typeck::MethodParam(typeck::MethodParam {
1443 | typeck::MethodObject(typeck::MethodObject {
1447 }) => ty::trait_method(cx.tcx, trait_id, index).def_id
1456 let stability = if ast_util::is_local(id) {
1458 let s = cx.tcx.map.with_attrs(id.node, |attrs| {
1459 attrs.map(|a| attr::find_stability(a.as_slice()))
1464 // no possibility of having attributes
1465 // (e.g. it's a local variable), so just
1473 // run through all the attributes and take the first
1475 csearch::get_item_attrs(&cx.tcx.sess.cstore, id, |attrs| {
1477 s = attr::find_stability(attrs.as_slice())
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"),
1495 let msg = match stability {
1496 Some(attr::Stability { text: Some(ref s), .. }) => {
1497 format!("use of {} item: {}", label, *s)
1499 _ => format!("use of {} item", label)
1502 cx.span_lint(lint, e.span, msg.as_slice());
1506 /// Doesn't actually warn; just gathers information for use by
1507 /// checks in trans.
1508 #[deriving(Default)]
1509 pub struct GatherNodeLevels;
1511 impl LintPass for GatherNodeLevels {
1512 fn get_lints(&self) -> LintArray {
1516 fn check_item(&mut self, cx: &Context, it: &ast::Item) {
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);
1532 declare_lint!(pub unused_imports, Warn,
1533 "imports that are never used")
1535 declare_lint!(pub unnecessary_qualification, Allow,
1536 "detects unnecessarily qualified names")
1538 declare_lint!(pub unrecognized_lint, Warn,
1539 "unrecognized lint attribute")
1541 declare_lint!(pub unused_variable, Warn,
1542 "detect variables which are not used in any way")
1544 declare_lint!(pub dead_assignment, Warn,
1545 "detect assignments that will never be read")
1547 declare_lint!(pub dead_code, Warn,
1548 "detect piece of code that will never be used")
1550 declare_lint!(pub visible_private_types, Warn,
1551 "detect use of private types in exported type signatures")
1553 declare_lint!(pub unreachable_code, Warn,
1554 "detects unreachable code")
1556 declare_lint!(pub warnings, Warn,
1557 "mass-change the level for lints which produce warnings")
1559 declare_lint!(pub unknown_features, Deny,
1560 "unknown features found in crate-level #[feature] directives")
1562 declare_lint!(pub unknown_crate_type, Deny,
1563 "unknown crate type found in #[crate_type] directive")
1565 declare_lint!(pub variant_size_difference, Allow,
1566 "detects enums with widely varying variant sizes")
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;
1573 impl LintPass for HardwiredLints {
1574 fn get_lints(&self) -> LintArray {
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)