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 //! This is a sibling of `lint::context` in order to ensure that
14 //! lints implemented here use the same public API as lint plugins.
16 //! To add a new lint to rustc, declare it here using `declare_lint!()`.
17 //! Then add code to emit the new lint in the appropriate circumstances.
18 //! You can do that in an existing `LintPass` if it makes sense, or in
19 //! a new `LintPass`, or using `Session::add_lint` elsewhere in the
20 //! compiler. Only do the latter if the check can't be written cleanly
23 //! If you define a new `LintPass`, you will also need to add it to the
24 //! `add_builtin!` or `add_builtin_with_new!` invocation in `context.rs`.
25 //! Use the former for unit-like structs and the latter for structs with
28 use metadata::csearch;
30 use middle::trans::adt; // for `adt::is_ffi_safe`
31 use middle::typeck::astconv::ast_ty_to_ty;
32 use middle::typeck::infer;
33 use middle::{typeck, ty, def, pat_util, stability};
34 use util::ppaux::{ty_to_string};
35 use util::nodemap::NodeSet;
36 use lint::{Context, LintPass, LintArray};
39 use std::collections::HashMap;
40 use std::{i8, i16, i32, i64, u8, u16, u32, u64, f32, f64};
44 use syntax::attr::AttrMetaMethods;
46 use syntax::codemap::Span;
47 use syntax::parse::token;
48 use syntax::{ast, ast_util, visit};
50 declare_lint!(WHILE_TRUE, Warn,
51 "suggest using `loop { }` instead of `while true { }`")
55 impl LintPass for WhileTrue {
56 fn get_lints(&self) -> LintArray {
57 lint_array!(WHILE_TRUE)
60 fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
62 ast::ExprWhile(cond, _) => {
64 ast::ExprLit(lit) => {
66 ast::LitBool(true) => {
67 cx.span_lint(WHILE_TRUE, e.span,
68 "denote infinite loops with loop \
82 declare_lint!(UNNECESSARY_TYPECAST, Allow,
83 "detects unnecessary type casts, that can be removed")
85 pub struct UnusedCasts;
87 impl LintPass for UnusedCasts {
88 fn get_lints(&self) -> LintArray {
89 lint_array!(UNNECESSARY_TYPECAST)
92 fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
94 ast::ExprCast(expr, ty) => {
95 let t_t = ast_ty_to_ty(cx, &infer::new_infer_ctxt(cx.tcx), &*ty);
96 if ty::get(ty::expr_ty(cx.tcx, &*expr)).sty == ty::get(t_t).sty {
97 cx.span_lint(UNNECESSARY_TYPECAST, ty.span, "unnecessary type cast");
105 declare_lint!(UNSIGNED_NEGATE, Warn,
106 "using an unary minus operator on unsigned type")
108 declare_lint!(TYPE_LIMITS, Warn,
109 "comparisons made useless by limits of the types involved")
111 declare_lint!(TYPE_OVERFLOW, Warn,
112 "literal out of range for its type")
114 pub struct TypeLimits {
115 /// Id of the last visited negated expression
116 negated_expr_id: ast::NodeId,
120 pub fn new() -> TypeLimits {
127 impl LintPass for TypeLimits {
128 fn get_lints(&self) -> LintArray {
129 lint_array!(UNSIGNED_NEGATE, TYPE_LIMITS, TYPE_OVERFLOW)
132 fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
134 ast::ExprUnary(ast::UnNeg, expr) => {
136 ast::ExprLit(lit) => {
138 ast::LitUint(..) => {
139 cx.span_lint(UNSIGNED_NEGATE, e.span,
140 "negation of unsigned int literal may \
147 let t = ty::expr_ty(cx.tcx, &*expr);
148 match ty::get(t).sty {
150 cx.span_lint(UNSIGNED_NEGATE, e.span,
151 "negation of unsigned int variable may \
158 // propagate negation, if the negation itself isn't negated
159 if self.negated_expr_id != e.id {
160 self.negated_expr_id = expr.id;
163 ast::ExprParen(expr) if self.negated_expr_id == e.id => {
164 self.negated_expr_id = expr.id;
166 ast::ExprBinary(binop, l, r) => {
167 if is_comparison(binop) && !check_limits(cx.tcx, binop, &*l, &*r) {
168 cx.span_lint(TYPE_LIMITS, e.span,
169 "comparison is useless due to type limits");
172 ast::ExprLit(lit) => {
173 match ty::get(ty::expr_ty(cx.tcx, e)).sty {
175 let int_type = if t == ast::TyI {
176 cx.sess().targ_cfg.int_type
178 let (min, max) = int_ty_range(int_type);
179 let mut lit_val: i64 = match lit.node {
180 ast::LitInt(v, _) => v,
181 ast::LitUint(v, _) => v as i64,
182 ast::LitIntUnsuffixed(v) => v,
185 if self.negated_expr_id == e.id {
188 if lit_val < min || lit_val > max {
189 cx.span_lint(TYPE_OVERFLOW, e.span,
190 "literal out of range for its type");
194 let uint_type = if t == ast::TyU {
195 cx.sess().targ_cfg.uint_type
197 let (min, max) = uint_ty_range(uint_type);
198 let lit_val: u64 = match lit.node {
199 ast::LitByte(_v) => return, // _v is u8, within range by definition
200 ast::LitInt(v, _) => v as u64,
201 ast::LitUint(v, _) => v,
202 ast::LitIntUnsuffixed(v) => v as u64,
205 if lit_val < min || lit_val > max {
206 cx.span_lint(TYPE_OVERFLOW, e.span,
207 "literal out of range for its type");
211 let (min, max) = float_ty_range(t);
212 let lit_val: f64 = match lit.node {
213 ast::LitFloat(ref v, _) |
214 ast::LitFloatUnsuffixed(ref v) => match from_str(v.get()) {
220 if lit_val < min || lit_val > max {
221 cx.span_lint(TYPE_OVERFLOW, e.span,
222 "literal out of range for its type");
231 fn is_valid<T:cmp::PartialOrd>(binop: ast::BinOp, v: T,
232 min: T, max: T) -> bool {
234 ast::BiLt => v > min && v <= max,
235 ast::BiLe => v >= min && v < max,
236 ast::BiGt => v >= min && v < max,
237 ast::BiGe => v > min && v <= max,
238 ast::BiEq | ast::BiNe => v >= min && v <= max,
243 fn rev_binop(binop: ast::BinOp) -> ast::BinOp {
245 ast::BiLt => ast::BiGt,
246 ast::BiLe => ast::BiGe,
247 ast::BiGt => ast::BiLt,
248 ast::BiGe => ast::BiLe,
253 // for int & uint, be conservative with the warnings, so that the
254 // warnings are consistent between 32- and 64-bit platforms
255 fn int_ty_range(int_ty: ast::IntTy) -> (i64, i64) {
257 ast::TyI => (i64::MIN, i64::MAX),
258 ast::TyI8 => (i8::MIN as i64, i8::MAX as i64),
259 ast::TyI16 => (i16::MIN as i64, i16::MAX as i64),
260 ast::TyI32 => (i32::MIN as i64, i32::MAX as i64),
261 ast::TyI64 => (i64::MIN, i64::MAX)
265 fn uint_ty_range(uint_ty: ast::UintTy) -> (u64, u64) {
267 ast::TyU => (u64::MIN, u64::MAX),
268 ast::TyU8 => (u8::MIN as u64, u8::MAX as u64),
269 ast::TyU16 => (u16::MIN as u64, u16::MAX as u64),
270 ast::TyU32 => (u32::MIN as u64, u32::MAX as u64),
271 ast::TyU64 => (u64::MIN, u64::MAX)
275 fn float_ty_range(float_ty: ast::FloatTy) -> (f64, f64) {
277 ast::TyF32 => (f32::MIN_VALUE as f64, f32::MAX_VALUE as f64),
278 ast::TyF64 => (f64::MIN_VALUE, f64::MAX_VALUE)
282 fn check_limits(tcx: &ty::ctxt, binop: ast::BinOp,
283 l: &ast::Expr, r: &ast::Expr) -> bool {
284 let (lit, expr, swap) = match (&l.node, &r.node) {
285 (&ast::ExprLit(_), _) => (l, r, true),
286 (_, &ast::ExprLit(_)) => (r, l, false),
289 // Normalize the binop so that the literal is always on the RHS in
291 let norm_binop = if swap { rev_binop(binop) } else { binop };
292 match ty::get(ty::expr_ty(tcx, expr)).sty {
293 ty::ty_int(int_ty) => {
294 let (min, max) = int_ty_range(int_ty);
295 let lit_val: i64 = match lit.node {
296 ast::ExprLit(li) => match li.node {
297 ast::LitInt(v, _) => v,
298 ast::LitUint(v, _) => v as i64,
299 ast::LitIntUnsuffixed(v) => v,
304 is_valid(norm_binop, lit_val, min, max)
306 ty::ty_uint(uint_ty) => {
307 let (min, max): (u64, u64) = uint_ty_range(uint_ty);
308 let lit_val: u64 = match lit.node {
309 ast::ExprLit(li) => match li.node {
310 ast::LitInt(v, _) => v as u64,
311 ast::LitUint(v, _) => v,
312 ast::LitIntUnsuffixed(v) => v as u64,
317 is_valid(norm_binop, lit_val, min, max)
323 fn is_comparison(binop: ast::BinOp) -> bool {
325 ast::BiEq | ast::BiLt | ast::BiLe |
326 ast::BiNe | ast::BiGe | ast::BiGt => true,
333 declare_lint!(CTYPES, Warn,
334 "proper use of libc types in foreign modules")
338 impl LintPass for CTypes {
339 fn get_lints(&self) -> LintArray {
343 fn check_item(&mut self, cx: &Context, it: &ast::Item) {
344 fn check_ty(cx: &Context, ty: &ast::Ty) {
346 ast::TyPath(_, _, id) => {
347 match cx.tcx.def_map.borrow().get_copy(&id) {
348 def::DefPrimTy(ast::TyInt(ast::TyI)) => {
349 cx.span_lint(CTYPES, ty.span,
350 "found rust type `int` in foreign module, while \
351 libc::c_int or libc::c_long should be used");
353 def::DefPrimTy(ast::TyUint(ast::TyU)) => {
354 cx.span_lint(CTYPES, ty.span,
355 "found rust type `uint` in foreign module, while \
356 libc::c_uint or libc::c_ulong should be used");
358 def::DefTy(def_id) => {
359 if !adt::is_ffi_safe(cx.tcx, def_id) {
360 cx.span_lint(CTYPES, ty.span,
361 "found enum type without foreign-function-safe
362 representation annotation in foreign module, consider \
363 adding a #[repr(...)] attribute to the enumeration");
369 ast::TyPtr(ref mt) => { check_ty(cx, &*mt.ty) }
374 fn check_foreign_fn(cx: &Context, decl: &ast::FnDecl) {
375 for input in decl.inputs.iter() {
376 check_ty(cx, &*input.ty);
378 check_ty(cx, &*decl.output)
382 ast::ItemForeignMod(ref nmod) if nmod.abi != abi::RustIntrinsic => {
383 for ni in nmod.items.iter() {
385 ast::ForeignItemFn(decl, _) => check_foreign_fn(cx, &*decl),
386 ast::ForeignItemStatic(t, _) => check_ty(cx, &*t)
390 _ => {/* nothing to do */ }
395 declare_lint!(MANAGED_HEAP_MEMORY, Allow,
396 "use of managed (@ type) heap memory")
398 declare_lint!(OWNED_HEAP_MEMORY, Allow,
399 "use of owned (Box type) heap memory")
401 declare_lint!(HEAP_MEMORY, Allow,
402 "use of any (Box type or @ type) heap memory")
404 pub struct HeapMemory;
407 fn check_heap_type(&self, cx: &Context, span: Span, ty: ty::t) {
410 ty::fold_ty(cx.tcx, ty, |t| {
411 match ty::get(t).sty {
416 ty::ty_closure(box ty::ClosureTy {
417 store: ty::UniqTraitStore,
429 let s = ty_to_string(cx.tcx, ty);
430 let m = format!("type uses owned (Box type) pointers: {}", s);
431 cx.span_lint(OWNED_HEAP_MEMORY, span, m.as_slice());
432 cx.span_lint(HEAP_MEMORY, span, m.as_slice());
436 let s = ty_to_string(cx.tcx, ty);
437 let m = format!("type uses managed (@ type) pointers: {}", s);
438 cx.span_lint(MANAGED_HEAP_MEMORY, span, m.as_slice());
439 cx.span_lint(HEAP_MEMORY, span, m.as_slice());
444 impl LintPass for HeapMemory {
445 fn get_lints(&self) -> LintArray {
446 lint_array!(MANAGED_HEAP_MEMORY, OWNED_HEAP_MEMORY, HEAP_MEMORY)
449 fn check_item(&mut self, cx: &Context, it: &ast::Item) {
454 ast::ItemStruct(..) =>
455 self.check_heap_type(cx, it.span,
456 ty::node_id_to_type(cx.tcx, it.id)),
460 // If it's a struct, we also have to check the fields' types
462 ast::ItemStruct(struct_def, _) => {
463 for struct_field in struct_def.fields.iter() {
464 self.check_heap_type(cx, struct_field.span,
465 ty::node_id_to_type(cx.tcx, struct_field.node.id));
472 fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
473 let ty = ty::expr_ty(cx.tcx, e);
474 self.check_heap_type(cx, e.span, ty);
478 declare_lint!(RAW_POINTER_DERIVING, Warn,
479 "uses of #[deriving] with raw pointers are rarely correct")
481 struct RawPtrDerivingVisitor<'a> {
485 impl<'a> visit::Visitor<()> for RawPtrDerivingVisitor<'a> {
486 fn visit_ty(&mut self, ty: &ast::Ty, _: ()) {
487 static MSG: &'static str = "use of `#[deriving]` with a raw pointer";
489 ast::TyPtr(..) => self.cx.span_lint(RAW_POINTER_DERIVING, ty.span, MSG),
492 visit::walk_ty(self, ty, ());
494 // explicit override to a no-op to reduce code bloat
495 fn visit_expr(&mut self, _: &ast::Expr, _: ()) {}
496 fn visit_block(&mut self, _: &ast::Block, _: ()) {}
499 pub struct RawPointerDeriving {
500 checked_raw_pointers: NodeSet,
503 impl RawPointerDeriving {
504 pub fn new() -> RawPointerDeriving {
506 checked_raw_pointers: NodeSet::new(),
511 impl LintPass for RawPointerDeriving {
512 fn get_lints(&self) -> LintArray {
513 lint_array!(RAW_POINTER_DERIVING)
516 fn check_item(&mut self, cx: &Context, item: &ast::Item) {
517 if !attr::contains_name(item.attrs.as_slice(), "automatically_derived") {
520 let did = match item.node {
521 ast::ItemImpl(..) => {
522 match ty::get(ty::node_id_to_type(cx.tcx, item.id)).sty {
523 ty::ty_enum(did, _) => did,
524 ty::ty_struct(did, _) => did,
530 if !ast_util::is_local(did) { return }
531 let item = match cx.tcx.map.find(did.node) {
532 Some(ast_map::NodeItem(item)) => item,
535 if !self.checked_raw_pointers.insert(item.id) { return }
537 ast::ItemStruct(..) | ast::ItemEnum(..) => {
538 let mut visitor = RawPtrDerivingVisitor { cx: cx };
539 visit::walk_item(&mut visitor, &*item, ());
546 declare_lint!(UNUSED_ATTRIBUTE, Warn,
547 "detects attributes that were not used by the compiler")
549 pub struct UnusedAttribute;
551 impl LintPass for UnusedAttribute {
552 fn get_lints(&self) -> LintArray {
553 lint_array!(UNUSED_ATTRIBUTE)
556 fn check_attribute(&mut self, cx: &Context, attr: &ast::Attribute) {
557 static ATTRIBUTE_WHITELIST: &'static [&'static str] = &[
558 // FIXME: #14408 whitelist docs since rustdoc looks at them
561 // FIXME: #14406 these are processed in trans, which happens after the
575 // not used anywhere (!?) but apparently we want to keep them around
580 // FIXME: #14407 these are only looked at on-demand so we can't
581 // guarantee they'll have already been checked
591 static CRATE_ATTRS: &'static [&'static str] = &[
605 for &name in ATTRIBUTE_WHITELIST.iter() {
606 if attr.check_name(name) {
611 if !attr::is_used(attr) {
612 cx.span_lint(UNUSED_ATTRIBUTE, attr.span, "unused attribute");
613 if CRATE_ATTRS.contains(&attr.name().get()) {
614 let msg = match attr.node.style {
615 ast::AttrOuter => "crate-level attribute should be an inner \
616 attribute: add an exclamation mark: #![foo]",
617 ast::AttrInner => "crate-level attribute should be in the \
620 cx.span_lint(UNUSED_ATTRIBUTE, attr.span, msg);
626 declare_lint!(PATH_STATEMENT, Warn,
627 "path statements with no effect")
629 pub struct PathStatement;
631 impl LintPass for PathStatement {
632 fn get_lints(&self) -> LintArray {
633 lint_array!(PATH_STATEMENT)
636 fn check_stmt(&mut self, cx: &Context, s: &ast::Stmt) {
638 ast::StmtSemi(expr, _) => {
640 ast::ExprPath(_) => cx.span_lint(PATH_STATEMENT, s.span,
641 "path statement with no effect"),
650 declare_lint!(UNUSED_MUST_USE, Warn,
651 "unused result of a type flagged as #[must_use]")
653 declare_lint!(UNUSED_RESULT, Allow,
654 "unused result of an expression in a statement")
656 pub struct UnusedResult;
658 impl LintPass for UnusedResult {
659 fn get_lints(&self) -> LintArray {
660 lint_array!(UNUSED_MUST_USE, UNUSED_RESULT)
663 fn check_stmt(&mut self, cx: &Context, s: &ast::Stmt) {
664 let expr = match s.node {
665 ast::StmtSemi(expr, _) => expr,
668 let t = ty::expr_ty(cx.tcx, &*expr);
669 match ty::get(t).sty {
670 ty::ty_nil | ty::ty_bot | ty::ty_bool => return,
674 ast::ExprRet(..) => return,
678 let t = ty::expr_ty(cx.tcx, &*expr);
679 let mut warned = false;
680 match ty::get(t).sty {
681 ty::ty_struct(did, _) |
682 ty::ty_enum(did, _) => {
683 if ast_util::is_local(did) {
684 match cx.tcx.map.get(did.node) {
685 ast_map::NodeItem(it) => {
686 warned |= check_must_use(cx, it.attrs.as_slice(), s.span);
691 csearch::get_item_attrs(&cx.sess().cstore, did, |attrs| {
692 warned |= check_must_use(cx, attrs.as_slice(), s.span);
699 cx.span_lint(UNUSED_RESULT, s.span, "unused result");
702 fn check_must_use(cx: &Context, attrs: &[ast::Attribute], sp: Span) -> bool {
703 for attr in attrs.iter() {
704 if attr.check_name("must_use") {
705 let mut msg = "unused result which must be used".to_string();
706 // check for #[must_use="..."]
707 match attr.value_str() {
711 msg.push_str(s.get());
714 cx.span_lint(UNUSED_MUST_USE, sp, msg.as_slice());
723 declare_lint!(NON_CAMEL_CASE_TYPES, Warn,
724 "types, variants and traits should have camel case names")
726 pub struct NonCamelCaseTypes;
728 impl LintPass for NonCamelCaseTypes {
729 fn get_lints(&self) -> LintArray {
730 lint_array!(NON_CAMEL_CASE_TYPES)
733 fn check_item(&mut self, cx: &Context, it: &ast::Item) {
734 fn is_camel_case(ident: ast::Ident) -> bool {
735 let ident = token::get_ident(ident);
736 assert!(!ident.get().is_empty());
737 let ident = ident.get().trim_chars('_');
739 // start with a non-lowercase letter rather than non-uppercase
740 // ones (some scripts don't have a concept of upper/lowercase)
741 !ident.char_at(0).is_lowercase() && !ident.contains_char('_')
744 fn to_camel_case(s: &str) -> String {
745 s.split('_').flat_map(|word| word.chars().enumerate().map(|(i, c)|
746 if i == 0 { c.to_uppercase() }
751 fn check_case(cx: &Context, sort: &str, ident: ast::Ident, span: Span) {
752 let s = token::get_ident(ident);
754 if !is_camel_case(ident) {
755 cx.span_lint(NON_CAMEL_CASE_TYPES, span,
756 format!("{} `{}` should have a camel case name such as `{}`",
757 sort, s, to_camel_case(s.get())).as_slice());
761 let has_extern_repr = it.attrs.iter().fold(attr::ReprAny, |acc, attr| {
762 attr::find_repr_attr(cx.tcx.sess.diagnostic(), attr, acc)
763 }) == attr::ReprExtern;
764 if has_extern_repr { return }
767 ast::ItemTy(..) | ast::ItemStruct(..) => {
768 check_case(cx, "type", it.ident, it.span)
770 ast::ItemTrait(..) => {
771 check_case(cx, "trait", it.ident, it.span)
773 ast::ItemEnum(ref enum_definition, _) => {
774 check_case(cx, "type", it.ident, it.span);
775 for variant in enum_definition.variants.iter() {
776 check_case(cx, "variant", variant.node.name, variant.span);
784 #[deriving(PartialEq)]
791 fn method_context(cx: &Context, m: &ast::Method) -> MethodContext {
792 let did = ast::DefId {
793 krate: ast::LOCAL_CRATE,
797 match cx.tcx.methods.borrow().find_copy(&did) {
798 None => cx.sess().span_bug(m.span, "missing method descriptor?!"),
801 ty::TraitContainer(..) => TraitDefaultImpl,
802 ty::ImplContainer(cid) => {
803 match ty::impl_trait_ref(cx.tcx, cid) {
804 Some(..) => TraitImpl,
813 declare_lint!(NON_SNAKE_CASE_FUNCTIONS, Warn,
814 "methods and functions should have snake case names")
816 pub struct NonSnakeCaseFunctions;
818 impl NonSnakeCaseFunctions {
819 fn check_snake_case(&self, cx: &Context, sort: &str, ident: ast::Ident, span: Span) {
820 fn is_snake_case(ident: ast::Ident) -> bool {
821 let ident = token::get_ident(ident);
822 assert!(!ident.get().is_empty());
823 let ident = ident.get().trim_chars('_');
825 let mut allow_underscore = true;
826 ident.chars().all(|c| {
827 allow_underscore = match c {
828 c if c.is_lowercase() || c.is_digit() => true,
829 '_' if allow_underscore => false,
836 fn to_snake_case(str: &str) -> String {
837 let mut words = vec![];
838 for s in str.split('_') {
839 let mut buf = String::new();
840 if s.is_empty() { continue; }
841 for ch in s.chars() {
842 if !buf.is_empty() && ch.is_uppercase() {
846 buf.push_char(ch.to_lowercase());
853 let s = token::get_ident(ident);
855 if !is_snake_case(ident) {
856 cx.span_lint(NON_SNAKE_CASE_FUNCTIONS, span,
857 format!("{} `{}` should have a snake case name such as `{}`",
858 sort, s, to_snake_case(s.get())).as_slice());
863 impl LintPass for NonSnakeCaseFunctions {
864 fn get_lints(&self) -> LintArray {
865 lint_array!(NON_SNAKE_CASE_FUNCTIONS)
868 fn check_fn(&mut self, cx: &Context,
869 fk: &visit::FnKind, _: &ast::FnDecl,
870 _: &ast::Block, span: Span, _: ast::NodeId) {
872 visit::FkMethod(ident, _, m) => match method_context(cx, m) {
874 => self.check_snake_case(cx, "method", ident, span),
876 => self.check_snake_case(cx, "trait method", ident, span),
879 visit::FkItemFn(ident, _, _, _)
880 => self.check_snake_case(cx, "function", ident, span),
885 fn check_ty_method(&mut self, cx: &Context, t: &ast::TypeMethod) {
886 self.check_snake_case(cx, "trait method", t.ident, t.span);
890 declare_lint!(NON_UPPERCASE_STATICS, Allow,
891 "static constants should have uppercase identifiers")
893 pub struct NonUppercaseStatics;
895 impl LintPass for NonUppercaseStatics {
896 fn get_lints(&self) -> LintArray {
897 lint_array!(NON_UPPERCASE_STATICS)
900 fn check_item(&mut self, cx: &Context, it: &ast::Item) {
902 // only check static constants
903 ast::ItemStatic(_, ast::MutImmutable, _) => {
904 let s = token::get_ident(it.ident);
905 // check for lowercase letters rather than non-uppercase
906 // ones (some scripts don't have a concept of
908 if s.get().chars().any(|c| c.is_lowercase()) {
909 cx.span_lint(NON_UPPERCASE_STATICS, it.span,
910 format!("static constant `{}` should have an uppercase name \
912 s.get(), s.get().chars().map(|c| c.to_uppercase())
913 .collect::<String>().as_slice()).as_slice());
921 declare_lint!(NON_UPPERCASE_PATTERN_STATICS, Warn,
922 "static constants in match patterns should be all caps")
924 pub struct NonUppercasePatternStatics;
926 impl LintPass for NonUppercasePatternStatics {
927 fn get_lints(&self) -> LintArray {
928 lint_array!(NON_UPPERCASE_PATTERN_STATICS)
931 fn check_pat(&mut self, cx: &Context, p: &ast::Pat) {
932 // Lint for constants that look like binding identifiers (#7526)
933 match (&p.node, cx.tcx.def_map.borrow().find(&p.id)) {
934 (&ast::PatIdent(_, ref path1, _), Some(&def::DefStatic(_, false))) => {
935 let s = token::get_ident(path1.node);
936 if s.get().chars().any(|c| c.is_lowercase()) {
937 cx.span_lint(NON_UPPERCASE_PATTERN_STATICS, path1.span,
938 format!("static constant in pattern `{}` should have an uppercase \
940 s.get(), s.get().chars().map(|c| c.to_uppercase())
941 .collect::<String>().as_slice()).as_slice());
949 declare_lint!(UPPERCASE_VARIABLES, Warn,
950 "variable and structure field names should start with a lowercase character")
952 pub struct UppercaseVariables;
954 impl LintPass for UppercaseVariables {
955 fn get_lints(&self) -> LintArray {
956 lint_array!(UPPERCASE_VARIABLES)
959 fn check_pat(&mut self, cx: &Context, p: &ast::Pat) {
961 &ast::PatIdent(_, ref path1, _) => {
962 match cx.tcx.def_map.borrow().find(&p.id) {
963 Some(&def::DefLocal(_, _)) | Some(&def::DefBinding(_, _)) |
964 Some(&def::DefArg(_, _)) => {
965 let s = token::get_ident(path1.node);
966 if s.get().len() > 0 && s.get().char_at(0).is_uppercase() {
967 cx.span_lint(UPPERCASE_VARIABLES, path1.span,
968 "variable names should start with \
969 a lowercase character");
979 fn check_struct_def(&mut self, cx: &Context, s: &ast::StructDef,
980 _: ast::Ident, _: &ast::Generics, _: ast::NodeId) {
981 for sf in s.fields.iter() {
983 ast::StructField_ { kind: ast::NamedField(ident, _), .. } => {
984 let s = token::get_ident(ident);
985 if s.get().char_at(0).is_uppercase() {
986 cx.span_lint(UPPERCASE_VARIABLES, sf.span,
987 "structure field names should start with \
988 a lowercase character");
997 declare_lint!(UNNECESSARY_PARENS, Warn,
998 "`if`, `match`, `while` and `return` do not need parentheses")
1000 pub struct UnnecessaryParens;
1002 impl UnnecessaryParens {
1003 fn check_unnecessary_parens_core(&self, cx: &Context, value: &ast::Expr, msg: &str,
1004 struct_lit_needs_parens: bool) {
1006 ast::ExprParen(ref inner) => {
1007 let necessary = struct_lit_needs_parens && contains_exterior_struct_lit(&**inner);
1009 cx.span_lint(UNNECESSARY_PARENS, value.span,
1010 format!("unnecessary parentheses around {}",
1017 /// Expressions that syntactically contain an "exterior" struct
1018 /// literal i.e. not surrounded by any parens or other
1019 /// delimiters, e.g. `X { y: 1 }`, `X { y: 1 }.method()`, `foo
1020 /// == X { y: 1 }` and `X { y: 1 } == foo` all do, but `(X {
1021 /// y: 1 }) == foo` does not.
1022 fn contains_exterior_struct_lit(value: &ast::Expr) -> bool {
1024 ast::ExprStruct(..) => true,
1026 ast::ExprAssign(ref lhs, ref rhs) |
1027 ast::ExprAssignOp(_, ref lhs, ref rhs) |
1028 ast::ExprBinary(_, ref lhs, ref rhs) => {
1029 // X { y: 1 } + X { y: 2 }
1030 contains_exterior_struct_lit(&**lhs) ||
1031 contains_exterior_struct_lit(&**rhs)
1033 ast::ExprUnary(_, ref x) |
1034 ast::ExprCast(ref x, _) |
1035 ast::ExprField(ref x, _, _) |
1036 ast::ExprIndex(ref x, _) => {
1037 // &X { y: 1 }, X { y: 1 }.y
1038 contains_exterior_struct_lit(&**x)
1041 ast::ExprMethodCall(_, _, ref exprs) => {
1042 // X { y: 1 }.bar(...)
1043 contains_exterior_struct_lit(&**exprs.get(0))
1052 impl LintPass for UnnecessaryParens {
1053 fn get_lints(&self) -> LintArray {
1054 lint_array!(UNNECESSARY_PARENS)
1057 fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
1058 let (value, msg, struct_lit_needs_parens) = match e.node {
1059 ast::ExprIf(cond, _, _) => (cond, "`if` condition", true),
1060 ast::ExprWhile(cond, _) => (cond, "`while` condition", true),
1061 ast::ExprMatch(head, _) => (head, "`match` head expression", true),
1062 ast::ExprRet(Some(value)) => (value, "`return` value", false),
1063 ast::ExprAssign(_, value) => (value, "assigned value", false),
1064 ast::ExprAssignOp(_, _, value) => (value, "assigned value", false),
1067 self.check_unnecessary_parens_core(cx, &*value, msg, struct_lit_needs_parens);
1070 fn check_stmt(&mut self, cx: &Context, s: &ast::Stmt) {
1071 let (value, msg) = match s.node {
1072 ast::StmtDecl(decl, _) => match decl.node {
1073 ast::DeclLocal(local) => match local.init {
1074 Some(value) => (value, "assigned value"),
1081 self.check_unnecessary_parens_core(cx, &*value, msg, false);
1085 declare_lint!(UNUSED_UNSAFE, Warn,
1086 "unnecessary use of an `unsafe` block")
1088 pub struct UnusedUnsafe;
1090 impl LintPass for UnusedUnsafe {
1091 fn get_lints(&self) -> LintArray {
1092 lint_array!(UNUSED_UNSAFE)
1095 fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
1097 // Don't warn about generated blocks, that'll just pollute the output.
1098 ast::ExprBlock(ref blk) => {
1099 if blk.rules == ast::UnsafeBlock(ast::UserProvided) &&
1100 !cx.tcx.used_unsafe.borrow().contains(&blk.id) {
1101 cx.span_lint(UNUSED_UNSAFE, blk.span, "unnecessary `unsafe` block");
1109 declare_lint!(UNSAFE_BLOCK, Allow,
1110 "usage of an `unsafe` block")
1112 pub struct UnsafeBlock;
1114 impl LintPass for UnsafeBlock {
1115 fn get_lints(&self) -> LintArray {
1116 lint_array!(UNSAFE_BLOCK)
1119 fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
1121 // Don't warn about generated blocks, that'll just pollute the output.
1122 ast::ExprBlock(ref blk) if blk.rules == ast::UnsafeBlock(ast::UserProvided) => {
1123 cx.span_lint(UNSAFE_BLOCK, blk.span, "usage of an `unsafe` block");
1130 declare_lint!(UNUSED_MUT, Warn,
1131 "detect mut variables which don't need to be mutable")
1133 pub struct UnusedMut;
1136 fn check_unused_mut_pat(&self, cx: &Context, pats: &[Gc<ast::Pat>]) {
1137 // collect all mutable pattern and group their NodeIDs by their Identifier to
1138 // avoid false warnings in match arms with multiple patterns
1139 let mut mutables = HashMap::new();
1140 for &p in pats.iter() {
1141 pat_util::pat_bindings(&cx.tcx.def_map, &*p, |mode, id, _, path1| {
1142 let ident = path1.node;
1144 ast::BindByValue(ast::MutMutable) => {
1145 if !token::get_ident(ident).get().starts_with("_") {
1146 mutables.insert_or_update_with(ident.name.uint(),
1147 vec!(id), |_, old| { old.push(id); });
1156 let used_mutables = cx.tcx.used_mut_nodes.borrow();
1157 for (_, v) in mutables.iter() {
1158 if !v.iter().any(|e| used_mutables.contains(e)) {
1159 cx.span_lint(UNUSED_MUT, cx.tcx.map.span(*v.get(0)),
1160 "variable does not need to be mutable");
1166 impl LintPass for UnusedMut {
1167 fn get_lints(&self) -> LintArray {
1168 lint_array!(UNUSED_MUT)
1171 fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
1173 ast::ExprMatch(_, ref arms) => {
1174 for a in arms.iter() {
1175 self.check_unused_mut_pat(cx, a.pats.as_slice())
1182 fn check_stmt(&mut self, cx: &Context, s: &ast::Stmt) {
1184 ast::StmtDecl(d, _) => {
1186 ast::DeclLocal(l) => {
1187 self.check_unused_mut_pat(cx, &[l.pat]);
1196 fn check_fn(&mut self, cx: &Context,
1197 _: &visit::FnKind, decl: &ast::FnDecl,
1198 _: &ast::Block, _: Span, _: ast::NodeId) {
1199 for a in decl.inputs.iter() {
1200 self.check_unused_mut_pat(cx, &[a.pat]);
1210 declare_lint!(UNNECESSARY_ALLOCATION, Warn,
1211 "detects unnecessary allocations that can be eliminated")
1213 pub struct UnnecessaryAllocation;
1215 impl LintPass for UnnecessaryAllocation {
1216 fn get_lints(&self) -> LintArray {
1217 lint_array!(UNNECESSARY_ALLOCATION)
1220 fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
1221 // Warn if string and vector literals with sigils, or boxing expressions,
1222 // are immediately borrowed.
1223 let allocation = match e.node {
1224 ast::ExprVstore(e2, ast::ExprVstoreUniq) => {
1226 ast::ExprLit(lit) if ast_util::lit_is_str(lit) => {
1229 ast::ExprVec(..) => VectorAllocation,
1233 ast::ExprUnary(ast::UnUniq, _) |
1234 ast::ExprUnary(ast::UnBox, _) => BoxAllocation,
1239 match cx.tcx.adjustments.borrow().find(&e.id) {
1240 Some(adjustment) => {
1242 ty::AutoDerefRef(ty::AutoDerefRef { autoref, .. }) => {
1243 match (allocation, autoref) {
1244 (VectorAllocation, Some(ty::AutoBorrowVec(..))) => {
1245 cx.span_lint(UNNECESSARY_ALLOCATION, e.span,
1246 "unnecessary allocation, the sigil can be removed");
1249 Some(ty::AutoPtr(_, ast::MutImmutable))) => {
1250 cx.span_lint(UNNECESSARY_ALLOCATION, e.span,
1251 "unnecessary allocation, use & instead");
1254 Some(ty::AutoPtr(_, ast::MutMutable))) => {
1255 cx.span_lint(UNNECESSARY_ALLOCATION, e.span,
1256 "unnecessary allocation, use &mut instead");
1269 declare_lint!(MISSING_DOC, Allow,
1270 "detects missing documentation for public members")
1272 pub struct MissingDoc {
1273 /// Stack of IDs of struct definitions.
1274 struct_def_stack: Vec<ast::NodeId>,
1276 /// Stack of whether #[doc(hidden)] is set
1277 /// at each level which has lint attributes.
1278 doc_hidden_stack: Vec<bool>,
1282 pub fn new() -> MissingDoc {
1284 struct_def_stack: vec!(),
1285 doc_hidden_stack: vec!(false),
1289 fn doc_hidden(&self) -> bool {
1290 *self.doc_hidden_stack.last().expect("empty doc_hidden_stack")
1293 fn check_missing_doc_attrs(&self,
1295 id: Option<ast::NodeId>,
1296 attrs: &[ast::Attribute],
1298 desc: &'static str) {
1299 // If we're building a test harness, then warning about
1300 // documentation is probably not really relevant right now.
1301 if cx.sess().opts.test { return }
1303 // `#[doc(hidden)]` disables missing_doc check.
1304 if self.doc_hidden() { return }
1306 // Only check publicly-visible items, using the result from the privacy pass.
1307 // It's an option so the crate root can also use this function (it doesn't
1310 Some(ref id) if !cx.exported_items.contains(id) => return,
1314 let has_doc = attrs.iter().any(|a| {
1315 match a.node.value.node {
1316 ast::MetaNameValue(ref name, _) if name.equiv(&("doc")) => true,
1321 cx.span_lint(MISSING_DOC, sp,
1322 format!("missing documentation for {}", desc).as_slice());
1327 impl LintPass for MissingDoc {
1328 fn get_lints(&self) -> LintArray {
1329 lint_array!(MISSING_DOC)
1332 fn enter_lint_attrs(&mut self, _: &Context, attrs: &[ast::Attribute]) {
1333 let doc_hidden = self.doc_hidden() || attrs.iter().any(|attr| {
1334 attr.check_name("doc") && match attr.meta_item_list() {
1336 Some(l) => attr::contains_name(l.as_slice(), "hidden"),
1339 self.doc_hidden_stack.push(doc_hidden);
1342 fn exit_lint_attrs(&mut self, _: &Context, _: &[ast::Attribute]) {
1343 self.doc_hidden_stack.pop().expect("empty doc_hidden_stack");
1346 fn check_struct_def(&mut self, _: &Context,
1347 _: &ast::StructDef, _: ast::Ident, _: &ast::Generics, id: ast::NodeId) {
1348 self.struct_def_stack.push(id);
1351 fn check_struct_def_post(&mut self, _: &Context,
1352 _: &ast::StructDef, _: ast::Ident, _: &ast::Generics, id: ast::NodeId) {
1353 let popped = self.struct_def_stack.pop().expect("empty struct_def_stack");
1354 assert!(popped == id);
1357 fn check_crate(&mut self, cx: &Context, krate: &ast::Crate) {
1358 self.check_missing_doc_attrs(cx, None, krate.attrs.as_slice(),
1359 krate.span, "crate");
1362 fn check_item(&mut self, cx: &Context, it: &ast::Item) {
1363 let desc = match it.node {
1364 ast::ItemFn(..) => "a function",
1365 ast::ItemMod(..) => "a module",
1366 ast::ItemEnum(..) => "an enum",
1367 ast::ItemStruct(..) => "a struct",
1368 ast::ItemTrait(..) => "a trait",
1371 self.check_missing_doc_attrs(cx, Some(it.id), it.attrs.as_slice(),
1375 fn check_fn(&mut self, cx: &Context,
1376 fk: &visit::FnKind, _: &ast::FnDecl,
1377 _: &ast::Block, _: Span, _: ast::NodeId) {
1379 visit::FkMethod(_, _, m) => {
1380 // If the method is an impl for a trait, don't doc.
1381 if method_context(cx, m) == TraitImpl { return; }
1383 // Otherwise, doc according to privacy. This will also check
1384 // doc for default methods defined on traits.
1385 self.check_missing_doc_attrs(cx, Some(m.id), m.attrs.as_slice(),
1386 m.span, "a method");
1392 fn check_ty_method(&mut self, cx: &Context, tm: &ast::TypeMethod) {
1393 self.check_missing_doc_attrs(cx, Some(tm.id), tm.attrs.as_slice(),
1394 tm.span, "a type method");
1397 fn check_struct_field(&mut self, cx: &Context, sf: &ast::StructField) {
1398 match sf.node.kind {
1399 ast::NamedField(_, vis) if vis == ast::Public => {
1400 let cur_struct_def = *self.struct_def_stack.last()
1401 .expect("empty struct_def_stack");
1402 self.check_missing_doc_attrs(cx, Some(cur_struct_def),
1403 sf.node.attrs.as_slice(), sf.span,
1410 fn check_variant(&mut self, cx: &Context, v: &ast::Variant, _: &ast::Generics) {
1411 self.check_missing_doc_attrs(cx, Some(v.node.id), v.node.attrs.as_slice(),
1412 v.span, "a variant");
1416 declare_lint!(DEPRECATED, Warn,
1417 "detects use of #[deprecated] items")
1419 // FIXME #6875: Change to Warn after std library stabilization is complete
1420 declare_lint!(EXPERIMENTAL, Allow,
1421 "detects use of #[experimental] items")
1423 declare_lint!(UNSTABLE, Allow,
1424 "detects use of #[unstable] items (incl. items with no stability attribute)")
1426 /// Checks for use of items with `#[deprecated]`, `#[experimental]` and
1427 /// `#[unstable]` attributes, or no stability attribute.
1428 pub struct Stability;
1430 impl LintPass for Stability {
1431 fn get_lints(&self) -> LintArray {
1432 lint_array!(DEPRECATED, EXPERIMENTAL, UNSTABLE)
1435 fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
1436 // if the expression was produced by a macro expansion,
1437 if e.span.expn_info.is_some() { return }
1439 let id = match e.node {
1440 ast::ExprPath(..) | ast::ExprStruct(..) => {
1441 match cx.tcx.def_map.borrow().find(&e.id) {
1442 Some(&def) => def.def_id(),
1446 ast::ExprMethodCall(..) => {
1447 let method_call = typeck::MethodCall::expr(e.id);
1448 match cx.tcx.method_map.borrow().find(&method_call) {
1450 match method.origin {
1451 typeck::MethodStatic(def_id) => {
1454 typeck::MethodStaticUnboxedClosure(def_id) => {
1457 typeck::MethodParam(typeck::MethodParam {
1462 | typeck::MethodObject(typeck::MethodObject {
1466 }) => ty::trait_method(cx.tcx, trait_id, index).def_id
1475 // stability attributes are promises made across crates; do not
1476 // check anything for crate-local usage.
1477 if ast_util::is_local(id) { return }
1479 let stability = stability::lookup(cx.tcx, id);
1480 let (lint, label) = match stability {
1481 // no stability attributes == Unstable
1482 None => (UNSTABLE, "unmarked"),
1483 Some(attr::Stability { level: attr::Unstable, .. }) =>
1484 (UNSTABLE, "unstable"),
1485 Some(attr::Stability { level: attr::Experimental, .. }) =>
1486 (EXPERIMENTAL, "experimental"),
1487 Some(attr::Stability { level: attr::Deprecated, .. }) =>
1488 (DEPRECATED, "deprecated"),
1492 let msg = match stability {
1493 Some(attr::Stability { text: Some(ref s), .. }) => {
1494 format!("use of {} item: {}", label, *s)
1496 _ => format!("use of {} item", label)
1499 cx.span_lint(lint, e.span, msg.as_slice());
1503 declare_lint!(pub UNUSED_IMPORTS, Warn,
1504 "imports that are never used")
1506 declare_lint!(pub UNNECESSARY_QUALIFICATION, Allow,
1507 "detects unnecessarily qualified names")
1509 declare_lint!(pub UNRECOGNIZED_LINT, Warn,
1510 "unrecognized lint attribute")
1512 declare_lint!(pub UNUSED_VARIABLE, Warn,
1513 "detect variables which are not used in any way")
1515 declare_lint!(pub DEAD_ASSIGNMENT, Warn,
1516 "detect assignments that will never be read")
1518 declare_lint!(pub DEAD_CODE, Warn,
1519 "detect piece of code that will never be used")
1521 declare_lint!(pub VISIBLE_PRIVATE_TYPES, Warn,
1522 "detect use of private types in exported type signatures")
1524 declare_lint!(pub UNREACHABLE_CODE, Warn,
1525 "detects unreachable code")
1527 declare_lint!(pub WARNINGS, Warn,
1528 "mass-change the level for lints which produce warnings")
1530 declare_lint!(pub UNKNOWN_FEATURES, Deny,
1531 "unknown features found in crate-level #[feature] directives")
1533 declare_lint!(pub UNKNOWN_CRATE_TYPE, Deny,
1534 "unknown crate type found in #[crate_type] directive")
1536 declare_lint!(pub VARIANT_SIZE_DIFFERENCE, Allow,
1537 "detects enums with widely varying variant sizes")
1539 /// Does nothing as a lint pass, but registers some `Lint`s
1540 /// which are used by other parts of the compiler.
1541 pub struct HardwiredLints;
1543 impl LintPass for HardwiredLints {
1544 fn get_lints(&self) -> LintArray {
1547 UNNECESSARY_QUALIFICATION,
1552 VISIBLE_PRIVATE_TYPES,
1557 VARIANT_SIZE_DIFFERENCE