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
27 use self::MethodContext::*;
29 use metadata::{csearch, decoder};
31 use middle::subst::Substs;
32 use middle::ty::{self, Ty};
33 use middle::{def, pat_util, stability};
34 use middle::const_eval::{eval_const_expr_partial, const_int, const_uint};
36 use util::ppaux::{ty_to_string};
37 use util::nodemap::{FnvHashMap, NodeSet};
38 use lint::{Level, Context, LintPass, LintArray, Lint};
40 use std::collections::BitvSet;
41 use std::collections::hash_map::Entry::{Occupied, Vacant};
42 use std::num::SignedInt;
43 use std::{cmp, slice};
44 use std::{i8, i16, i32, i64, u8, u16, u32, u64, f32, f64};
46 use syntax::{abi, ast, ast_map};
47 use syntax::ast_util::is_shift_binop;
48 use syntax::attr::{self, AttrMetaMethods};
49 use syntax::codemap::{self, Span};
50 use syntax::feature_gate::{KNOWN_ATTRIBUTES, AttributeType};
51 use syntax::parse::token;
52 use syntax::ast::{TyIs, TyUs, TyI8, TyU8, TyI16, TyU16, TyI32, TyU32, TyI64, TyU64};
55 use syntax::visit::{self, Visitor};
60 "suggest using `loop { }` instead of `while true { }`"
66 impl LintPass for WhileTrue {
67 fn get_lints(&self) -> LintArray {
68 lint_array!(WHILE_TRUE)
71 fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
72 if let ast::ExprWhile(ref cond, _, _) = e.node {
73 if let ast::ExprLit(ref lit) = cond.node {
74 if let ast::LitBool(true) = lit.node {
75 cx.span_lint(WHILE_TRUE, e.span,
76 "denote infinite loops with loop { ... }");
86 "detects unnecessary type casts that can be removed"
90 pub struct UnusedCasts;
92 impl LintPass for UnusedCasts {
93 fn get_lints(&self) -> LintArray {
94 lint_array!(UNUSED_TYPECASTS)
97 fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
98 if let ast::ExprCast(ref expr, ref ty) = e.node {
99 let t_t = ty::expr_ty(cx.tcx, e);
100 if ty::expr_ty(cx.tcx, &**expr) == t_t {
101 cx.span_lint(UNUSED_TYPECASTS, ty.span, "unnecessary type cast");
110 "using an unary minus operator on unsigned type"
116 "comparisons made useless by limits of the types involved"
120 OVERFLOWING_LITERALS,
122 "literal out of range for its type"
128 "shift exceeds the type's number of bits"
132 pub struct TypeLimits {
133 /// Id of the last visited negated expression
134 negated_expr_id: ast::NodeId,
138 pub fn new() -> TypeLimits {
145 impl LintPass for TypeLimits {
146 fn get_lints(&self) -> LintArray {
147 lint_array!(UNSIGNED_NEGATION, UNUSED_COMPARISONS, OVERFLOWING_LITERALS,
151 fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
153 ast::ExprUnary(ast::UnNeg, ref expr) => {
155 ast::ExprLit(ref lit) => {
157 ast::LitInt(_, ast::UnsignedIntLit(_)) => {
158 cx.span_lint(UNSIGNED_NEGATION, e.span,
159 "negation of unsigned int literal may \
166 let t = ty::expr_ty(cx.tcx, &**expr);
169 cx.span_lint(UNSIGNED_NEGATION, e.span,
170 "negation of unsigned int variable may \
177 // propagate negation, if the negation itself isn't negated
178 if self.negated_expr_id != e.id {
179 self.negated_expr_id = expr.id;
182 ast::ExprParen(ref expr) if self.negated_expr_id == e.id => {
183 self.negated_expr_id = expr.id;
185 ast::ExprBinary(binop, ref l, ref r) => {
186 if is_comparison(binop) && !check_limits(cx.tcx, binop, &**l, &**r) {
187 cx.span_lint(UNUSED_COMPARISONS, e.span,
188 "comparison is useless due to type limits");
191 if is_shift_binop(binop.node) {
192 let opt_ty_bits = match ty::expr_ty(cx.tcx, &**l).sty {
193 ty::ty_int(t) => Some(int_ty_bits(t, cx.sess().target.int_type)),
194 ty::ty_uint(t) => Some(uint_ty_bits(t, cx.sess().target.uint_type)),
198 if let Some(bits) = opt_ty_bits {
199 let exceeding = if let ast::ExprLit(ref lit) = r.node {
200 if let ast::LitInt(shift, _) = lit.node { shift >= bits }
203 match eval_const_expr_partial(cx.tcx, &**r, Some(cx.tcx.types.uint)) {
204 Ok(const_int(shift)) => { shift as u64 >= bits },
205 Ok(const_uint(shift)) => { shift >= bits },
210 cx.span_lint(EXCEEDING_BITSHIFTS, e.span,
211 "bitshift exceeds the type's number of bits");
216 ast::ExprLit(ref lit) => {
217 match ty::expr_ty(cx.tcx, e).sty {
220 ast::LitInt(v, ast::SignedIntLit(_, ast::Plus)) |
221 ast::LitInt(v, ast::UnsuffixedIntLit(ast::Plus)) => {
222 let int_type = if let ast::TyIs(_) = t {
223 cx.sess().target.int_type
225 let (min, max) = int_ty_range(int_type);
226 let negative = self.negated_expr_id == e.id;
228 if (negative && v > (min.abs() as u64)) ||
229 (!negative && v > (max.abs() as u64)) {
230 cx.span_lint(OVERFLOWING_LITERALS, e.span,
231 &*format!("literal out of range for {:?}", t));
239 let uint_type = if let ast::TyUs(_) = t {
240 cx.sess().target.uint_type
242 let (min, max) = uint_ty_range(uint_type);
243 let lit_val: u64 = match lit.node {
244 ast::LitByte(_v) => return, // _v is u8, within range by definition
245 ast::LitInt(v, _) => v,
248 if lit_val < min || lit_val > max {
249 cx.span_lint(OVERFLOWING_LITERALS, e.span,
250 &*format!("literal out of range for {:?}", t));
254 let (min, max) = float_ty_range(t);
255 let lit_val: f64 = match lit.node {
256 ast::LitFloat(ref v, _) |
257 ast::LitFloatUnsuffixed(ref v) => {
258 match v.parse().ok() {
265 if lit_val < min || lit_val > max {
266 cx.span_lint(OVERFLOWING_LITERALS, e.span,
267 &*format!("literal out of range for {:?}", t));
276 fn is_valid<T:cmp::PartialOrd>(binop: ast::BinOp, v: T,
277 min: T, max: T) -> bool {
279 ast::BiLt => v > min && v <= max,
280 ast::BiLe => v >= min && v < max,
281 ast::BiGt => v >= min && v < max,
282 ast::BiGe => v > min && v <= max,
283 ast::BiEq | ast::BiNe => v >= min && v <= max,
288 fn rev_binop(binop: ast::BinOp) -> ast::BinOp {
289 codemap::respan(binop.span, match binop.node {
290 ast::BiLt => ast::BiGt,
291 ast::BiLe => ast::BiGe,
292 ast::BiGt => ast::BiLt,
293 ast::BiGe => ast::BiLe,
298 // for int & uint, be conservative with the warnings, so that the
299 // warnings are consistent between 32- and 64-bit platforms
300 fn int_ty_range(int_ty: ast::IntTy) -> (i64, i64) {
302 ast::TyIs(_) => (i64::MIN, i64::MAX),
303 ast::TyI8 => (i8::MIN as i64, i8::MAX as i64),
304 ast::TyI16 => (i16::MIN as i64, i16::MAX as i64),
305 ast::TyI32 => (i32::MIN as i64, i32::MAX as i64),
306 ast::TyI64 => (i64::MIN, i64::MAX)
310 fn uint_ty_range(uint_ty: ast::UintTy) -> (u64, u64) {
312 ast::TyUs(_) => (u64::MIN, u64::MAX),
313 ast::TyU8 => (u8::MIN as u64, u8::MAX as u64),
314 ast::TyU16 => (u16::MIN as u64, u16::MAX as u64),
315 ast::TyU32 => (u32::MIN as u64, u32::MAX as u64),
316 ast::TyU64 => (u64::MIN, u64::MAX)
320 fn float_ty_range(float_ty: ast::FloatTy) -> (f64, f64) {
322 ast::TyF32 => (f32::MIN as f64, f32::MAX as f64),
323 ast::TyF64 => (f64::MIN, f64::MAX)
327 fn int_ty_bits(int_ty: ast::IntTy, target_int_ty: ast::IntTy) -> u64 {
329 ast::TyIs(_) => int_ty_bits(target_int_ty, target_int_ty),
330 ast::TyI8 => i8::BITS as u64,
331 ast::TyI16 => i16::BITS as u64,
332 ast::TyI32 => i32::BITS as u64,
333 ast::TyI64 => i64::BITS as u64
337 fn uint_ty_bits(uint_ty: ast::UintTy, target_uint_ty: ast::UintTy) -> u64 {
339 ast::TyUs(_) => uint_ty_bits(target_uint_ty, target_uint_ty),
340 ast::TyU8 => u8::BITS as u64,
341 ast::TyU16 => u16::BITS as u64,
342 ast::TyU32 => u32::BITS as u64,
343 ast::TyU64 => u64::BITS as u64
347 fn check_limits(tcx: &ty::ctxt, binop: ast::BinOp,
348 l: &ast::Expr, r: &ast::Expr) -> bool {
349 let (lit, expr, swap) = match (&l.node, &r.node) {
350 (&ast::ExprLit(_), _) => (l, r, true),
351 (_, &ast::ExprLit(_)) => (r, l, false),
354 // Normalize the binop so that the literal is always on the RHS in
356 let norm_binop = if swap { rev_binop(binop) } else { binop };
357 match ty::expr_ty(tcx, expr).sty {
358 ty::ty_int(int_ty) => {
359 let (min, max) = int_ty_range(int_ty);
360 let lit_val: i64 = match lit.node {
361 ast::ExprLit(ref li) => match li.node {
362 ast::LitInt(v, ast::SignedIntLit(_, ast::Plus)) |
363 ast::LitInt(v, ast::UnsuffixedIntLit(ast::Plus)) => v as i64,
364 ast::LitInt(v, ast::SignedIntLit(_, ast::Minus)) |
365 ast::LitInt(v, ast::UnsuffixedIntLit(ast::Minus)) => -(v as i64),
370 is_valid(norm_binop, lit_val, min, max)
372 ty::ty_uint(uint_ty) => {
373 let (min, max): (u64, u64) = uint_ty_range(uint_ty);
374 let lit_val: u64 = match lit.node {
375 ast::ExprLit(ref li) => match li.node {
376 ast::LitInt(v, _) => v,
381 is_valid(norm_binop, lit_val, min, max)
387 fn is_comparison(binop: ast::BinOp) -> bool {
389 ast::BiEq | ast::BiLt | ast::BiLe |
390 ast::BiNe | ast::BiGe | ast::BiGt => true,
400 "proper use of libc types in foreign modules"
403 struct ImproperCTypesVisitor<'a, 'tcx: 'a> {
404 cx: &'a Context<'a, 'tcx>
407 impl<'a, 'tcx> ImproperCTypesVisitor<'a, 'tcx> {
408 fn check_def(&mut self, sp: Span, ty_id: ast::NodeId, path_id: ast::NodeId) {
409 match self.cx.tcx.def_map.borrow()[path_id].clone() {
410 def::DefPrimTy(ast::TyInt(ast::TyIs(_))) => {
411 self.cx.span_lint(IMPROPER_CTYPES, sp,
412 "found rust type `isize` in foreign module, while \
413 libc::c_int or libc::c_long should be used");
415 def::DefPrimTy(ast::TyUint(ast::TyUs(_))) => {
416 self.cx.span_lint(IMPROPER_CTYPES, sp,
417 "found rust type `usize` in foreign module, while \
418 libc::c_uint or libc::c_ulong should be used");
421 let tty = match self.cx.tcx.ast_ty_to_ty_cache.borrow().get(&ty_id) {
422 Some(&ty::atttce_resolved(t)) => t,
423 _ => panic!("ast_ty_to_ty_cache was incomplete after typeck!")
426 if !ty::is_ffi_safe(self.cx.tcx, tty) {
427 self.cx.span_lint(IMPROPER_CTYPES, sp,
428 "found type without foreign-function-safe
429 representation annotation in foreign module, consider \
430 adding a #[repr(...)] attribute to the type");
438 impl<'a, 'tcx, 'v> Visitor<'v> for ImproperCTypesVisitor<'a, 'tcx> {
439 fn visit_ty(&mut self, ty: &ast::Ty) {
441 ast::TyPath(_, id) => self.check_def(ty.span, ty.id, id),
444 visit::walk_ty(self, ty);
449 pub struct ImproperCTypes;
451 impl LintPass for ImproperCTypes {
452 fn get_lints(&self) -> LintArray {
453 lint_array!(IMPROPER_CTYPES)
456 fn check_item(&mut self, cx: &Context, it: &ast::Item) {
457 fn check_ty(cx: &Context, ty: &ast::Ty) {
458 let mut vis = ImproperCTypesVisitor { cx: cx };
462 fn check_foreign_fn(cx: &Context, decl: &ast::FnDecl) {
463 for input in &decl.inputs {
464 check_ty(cx, &*input.ty);
466 if let ast::Return(ref ret_ty) = decl.output {
467 check_ty(cx, &**ret_ty);
472 ast::ItemForeignMod(ref nmod) if nmod.abi != abi::RustIntrinsic => {
473 for ni in &nmod.items {
475 ast::ForeignItemFn(ref decl, _) => check_foreign_fn(cx, &**decl),
476 ast::ForeignItemStatic(ref t, _) => check_ty(cx, &**t)
488 "use of owned (Box type) heap memory"
492 pub struct BoxPointers;
495 fn check_heap_type<'a, 'tcx>(&self, cx: &Context<'a, 'tcx>,
496 span: Span, ty: Ty<'tcx>) {
497 let mut n_uniq: usize = 0;
498 ty::fold_ty(cx.tcx, ty, |t| {
509 let s = ty_to_string(cx.tcx, ty);
510 let m = format!("type uses owned (Box type) pointers: {}", s);
511 cx.span_lint(BOX_POINTERS, span, &m[]);
516 impl LintPass for BoxPointers {
517 fn get_lints(&self) -> LintArray {
518 lint_array!(BOX_POINTERS)
521 fn check_item(&mut self, cx: &Context, it: &ast::Item) {
526 ast::ItemStruct(..) =>
527 self.check_heap_type(cx, it.span,
528 ty::node_id_to_type(cx.tcx, it.id)),
532 // If it's a struct, we also have to check the fields' types
534 ast::ItemStruct(ref struct_def, _) => {
535 for struct_field in &struct_def.fields {
536 self.check_heap_type(cx, struct_field.span,
537 ty::node_id_to_type(cx.tcx, struct_field.node.id));
544 fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
545 let ty = ty::expr_ty(cx.tcx, e);
546 self.check_heap_type(cx, e.span, ty);
553 "uses of #[derive] with raw pointers are rarely correct"
556 struct RawPtrDeriveVisitor<'a, 'tcx: 'a> {
557 cx: &'a Context<'a, 'tcx>
560 impl<'a, 'tcx, 'v> Visitor<'v> for RawPtrDeriveVisitor<'a, 'tcx> {
561 fn visit_ty(&mut self, ty: &ast::Ty) {
562 static MSG: &'static str = "use of `#[derive]` with a raw pointer";
563 if let ast::TyPtr(..) = ty.node {
564 self.cx.span_lint(RAW_POINTER_DERIVE, ty.span, MSG);
566 visit::walk_ty(self, ty);
568 // explicit override to a no-op to reduce code bloat
569 fn visit_expr(&mut self, _: &ast::Expr) {}
570 fn visit_block(&mut self, _: &ast::Block) {}
573 pub struct RawPointerDerive {
574 checked_raw_pointers: NodeSet,
577 impl RawPointerDerive {
578 pub fn new() -> RawPointerDerive {
580 checked_raw_pointers: NodeSet(),
585 impl LintPass for RawPointerDerive {
586 fn get_lints(&self) -> LintArray {
587 lint_array!(RAW_POINTER_DERIVE)
590 fn check_item(&mut self, cx: &Context, item: &ast::Item) {
591 if !attr::contains_name(&item.attrs[], "automatically_derived") {
594 let did = match item.node {
595 ast::ItemImpl(_, _, _, ref t_ref_opt, _, _) => {
596 // Deriving the Copy trait does not cause a warning
597 if let &Some(ref trait_ref) = t_ref_opt {
598 let def_id = ty::trait_ref_to_def_id(cx.tcx, trait_ref);
599 if Some(def_id) == cx.tcx.lang_items.copy_trait() {
604 match ty::node_id_to_type(cx.tcx, item.id).sty {
605 ty::ty_enum(did, _) => did,
606 ty::ty_struct(did, _) => did,
612 if !ast_util::is_local(did) { return }
613 let item = match cx.tcx.map.find(did.node) {
614 Some(ast_map::NodeItem(item)) => item,
617 if !self.checked_raw_pointers.insert(item.id) { return }
619 ast::ItemStruct(..) | ast::ItemEnum(..) => {
620 let mut visitor = RawPtrDeriveVisitor { cx: cx };
621 visit::walk_item(&mut visitor, &*item);
631 "detects attributes that were not used by the compiler"
635 pub struct UnusedAttributes;
637 impl LintPass for UnusedAttributes {
638 fn get_lints(&self) -> LintArray {
639 lint_array!(UNUSED_ATTRIBUTES)
642 fn check_attribute(&mut self, cx: &Context, attr: &ast::Attribute) {
643 for &(ref name, ty) in KNOWN_ATTRIBUTES {
645 AttributeType::Whitelisted
646 | AttributeType::Gated(_, _) if attr.check_name(name) => {
653 if !attr::is_used(attr) {
654 cx.span_lint(UNUSED_ATTRIBUTES, attr.span, "unused attribute");
655 if KNOWN_ATTRIBUTES.contains(&(&attr.name()[], AttributeType::CrateLevel)) {
656 let msg = match attr.node.style {
657 ast::AttrOuter => "crate-level attribute should be an inner \
658 attribute: add an exclamation mark: #![foo]",
659 ast::AttrInner => "crate-level attribute should be in the \
662 cx.span_lint(UNUSED_ATTRIBUTES, attr.span, msg);
671 "path statements with no effect"
675 pub struct PathStatements;
677 impl LintPass for PathStatements {
678 fn get_lints(&self) -> LintArray {
679 lint_array!(PATH_STATEMENTS)
682 fn check_stmt(&mut self, cx: &Context, s: &ast::Stmt) {
684 ast::StmtSemi(ref expr, _) => {
686 ast::ExprPath(_) => cx.span_lint(PATH_STATEMENTS, s.span,
687 "path statement with no effect"),
699 "unused result of a type flagged as #[must_use]"
705 "unused result of an expression in a statement"
709 pub struct UnusedResults;
711 impl LintPass for UnusedResults {
712 fn get_lints(&self) -> LintArray {
713 lint_array!(UNUSED_MUST_USE, UNUSED_RESULTS)
716 fn check_stmt(&mut self, cx: &Context, s: &ast::Stmt) {
717 let expr = match s.node {
718 ast::StmtSemi(ref expr, _) => &**expr,
722 if let ast::ExprRet(..) = expr.node {
726 let t = ty::expr_ty(cx.tcx, expr);
727 let mut warned = false;
729 ty::ty_tup(ref tys) if tys.is_empty() => return,
730 ty::ty_bool => return,
731 ty::ty_struct(did, _) |
732 ty::ty_enum(did, _) => {
733 if ast_util::is_local(did) {
734 if let ast_map::NodeItem(it) = cx.tcx.map.get(did.node) {
735 warned |= check_must_use(cx, &it.attrs[], s.span);
738 let attrs = csearch::get_item_attrs(&cx.sess().cstore, did);
739 warned |= check_must_use(cx, &attrs[], s.span);
745 cx.span_lint(UNUSED_RESULTS, s.span, "unused result");
748 fn check_must_use(cx: &Context, attrs: &[ast::Attribute], sp: Span) -> bool {
750 if attr.check_name("must_use") {
751 let mut msg = "unused result which must be used".to_string();
752 // check for #[must_use="..."]
753 match attr.value_str() {
760 cx.span_lint(UNUSED_MUST_USE, sp, &msg);
770 pub NON_CAMEL_CASE_TYPES,
772 "types, variants, traits and type parameters should have camel case names"
776 pub struct NonCamelCaseTypes;
778 impl NonCamelCaseTypes {
779 fn check_case(&self, cx: &Context, sort: &str, ident: ast::Ident, span: Span) {
780 fn is_camel_case(ident: ast::Ident) -> bool {
781 let ident = token::get_ident(ident);
782 if ident.is_empty() { return true; }
783 let ident = ident.trim_matches('_');
785 // start with a non-lowercase letter rather than non-uppercase
786 // ones (some scripts don't have a concept of upper/lowercase)
787 ident.len() > 0 && !ident.char_at(0).is_lowercase() && !ident.contains_char('_')
790 fn to_camel_case(s: &str) -> String {
791 s.split('_').flat_map(|word| word.chars().enumerate().map(|(i, c)|
792 if i == 0 { c.to_uppercase() }
797 let s = token::get_ident(ident);
799 if !is_camel_case(ident) {
800 let c = to_camel_case(&s);
801 let m = if c.is_empty() {
802 format!("{} `{}` should have a camel case name such as `CamelCase`", sort, s)
804 format!("{} `{}` should have a camel case name such as `{}`", sort, s, c)
806 cx.span_lint(NON_CAMEL_CASE_TYPES, span, &m[]);
811 impl LintPass for NonCamelCaseTypes {
812 fn get_lints(&self) -> LintArray {
813 lint_array!(NON_CAMEL_CASE_TYPES)
816 fn check_item(&mut self, cx: &Context, it: &ast::Item) {
817 let has_extern_repr = it.attrs.iter().map(|attr| {
818 attr::find_repr_attrs(cx.tcx.sess.diagnostic(), attr).iter()
819 .any(|r| r == &attr::ReprExtern)
821 if has_extern_repr { return }
824 ast::ItemTy(..) | ast::ItemStruct(..) => {
825 self.check_case(cx, "type", it.ident, it.span)
827 ast::ItemTrait(..) => {
828 self.check_case(cx, "trait", it.ident, it.span)
830 ast::ItemEnum(ref enum_definition, _) => {
831 if has_extern_repr { return }
832 self.check_case(cx, "type", it.ident, it.span);
833 for variant in &enum_definition.variants {
834 self.check_case(cx, "variant", variant.node.name, variant.span);
841 fn check_generics(&mut self, cx: &Context, it: &ast::Generics) {
842 for gen in &*it.ty_params {
843 self.check_case(cx, "type parameter", gen.ident, gen.span);
855 fn method_context(cx: &Context, m: &ast::Method) -> MethodContext {
856 let did = ast::DefId {
857 krate: ast::LOCAL_CRATE,
861 match cx.tcx.impl_or_trait_items.borrow().get(&did).cloned() {
862 None => cx.sess().span_bug(m.span, "missing method descriptor?!"),
865 ty::MethodTraitItem(md) => {
867 ty::TraitContainer(..) => TraitDefaultImpl,
868 ty::ImplContainer(cid) => {
869 match ty::impl_trait_ref(cx.tcx, cid) {
870 Some(..) => TraitImpl,
876 ty::TypeTraitItem(typedef) => {
877 match typedef.container {
878 ty::TraitContainer(..) => TraitDefaultImpl,
879 ty::ImplContainer(cid) => {
880 match ty::impl_trait_ref(cx.tcx, cid) {
881 Some(..) => TraitImpl,
895 "methods, functions, lifetime parameters and modules should have snake case names"
899 pub struct NonSnakeCase;
902 fn to_snake_case(mut str: &str) -> String {
903 let mut words = vec![];
904 // Preserve leading underscores
905 str = str.trim_left_matches(|c: char| {
907 words.push(String::new());
911 for s in str.split('_') {
912 let mut last_upper = false;
913 let mut buf = String::new();
914 if s.is_empty() { continue; }
915 for ch in s.chars() {
916 if !buf.is_empty() && buf != "'"
922 last_upper = ch.is_uppercase();
923 buf.push(ch.to_lowercase());
930 fn check_snake_case(&self, cx: &Context, sort: &str, ident: ast::Ident, span: Span) {
931 fn is_snake_case(ident: ast::Ident) -> bool {
932 let ident = token::get_ident(ident);
933 if ident.is_empty() { return true; }
934 let ident = ident.trim_left_matches('\'');
935 let ident = ident.trim_matches('_');
937 let mut allow_underscore = true;
938 ident.chars().all(|c| {
939 allow_underscore = match c {
940 '_' if !allow_underscore => return false,
942 c if !c.is_uppercase() => true,
949 let s = token::get_ident(ident);
951 if !is_snake_case(ident) {
952 let sc = NonSnakeCase::to_snake_case(&s);
954 cx.span_lint(NON_SNAKE_CASE, span,
955 &*format!("{} `{}` should have a snake case name such as `{}`",
958 cx.span_lint(NON_SNAKE_CASE, span,
959 &*format!("{} `{}` should have a snake case name",
966 impl LintPass for NonSnakeCase {
967 fn get_lints(&self) -> LintArray {
968 lint_array!(NON_SNAKE_CASE)
971 fn check_fn(&mut self, cx: &Context,
972 fk: visit::FnKind, _: &ast::FnDecl,
973 _: &ast::Block, span: Span, _: ast::NodeId) {
975 visit::FkMethod(ident, _, m) => match method_context(cx, m) {
977 => self.check_snake_case(cx, "method", ident, span),
979 => self.check_snake_case(cx, "trait method", ident, span),
982 visit::FkItemFn(ident, _, _, _)
983 => self.check_snake_case(cx, "function", ident, span),
988 fn check_item(&mut self, cx: &Context, it: &ast::Item) {
989 if let ast::ItemMod(_) = it.node {
990 self.check_snake_case(cx, "module", it.ident, it.span);
994 fn check_ty_method(&mut self, cx: &Context, t: &ast::TypeMethod) {
995 self.check_snake_case(cx, "trait method", t.ident, t.span);
998 fn check_lifetime_def(&mut self, cx: &Context, t: &ast::LifetimeDef) {
999 self.check_snake_case(cx, "lifetime", t.lifetime.name.ident(), t.lifetime.span);
1002 fn check_pat(&mut self, cx: &Context, p: &ast::Pat) {
1003 if let &ast::PatIdent(_, ref path1, _) = &p.node {
1004 if let Some(&def::DefLocal(_)) = cx.tcx.def_map.borrow().get(&p.id) {
1005 self.check_snake_case(cx, "variable", path1.node, p.span);
1010 fn check_struct_def(&mut self, cx: &Context, s: &ast::StructDef,
1011 _: ast::Ident, _: &ast::Generics, _: ast::NodeId) {
1012 for sf in &s.fields {
1013 if let ast::StructField_ { kind: ast::NamedField(ident, _), .. } = sf.node {
1014 self.check_snake_case(cx, "structure field", ident, sf.span);
1021 pub NON_UPPER_CASE_GLOBALS,
1023 "static constants should have uppercase identifiers"
1027 pub struct NonUpperCaseGlobals;
1029 impl NonUpperCaseGlobals {
1030 fn check_upper_case(cx: &Context, sort: &str, ident: ast::Ident, span: Span) {
1031 let s = token::get_ident(ident);
1033 if s.chars().any(|c| c.is_lowercase()) {
1034 let uc: String = NonSnakeCase::to_snake_case(&s).chars()
1035 .map(|c| c.to_uppercase()).collect();
1037 cx.span_lint(NON_UPPER_CASE_GLOBALS, span,
1038 &format!("{} `{}` should have an upper case name such as `{}`",
1041 cx.span_lint(NON_UPPER_CASE_GLOBALS, span,
1042 &format!("{} `{}` should have an upper case name",
1049 impl LintPass for NonUpperCaseGlobals {
1050 fn get_lints(&self) -> LintArray {
1051 lint_array!(NON_UPPER_CASE_GLOBALS)
1054 fn check_item(&mut self, cx: &Context, it: &ast::Item) {
1056 // only check static constants
1057 ast::ItemStatic(_, ast::MutImmutable, _) => {
1058 NonUpperCaseGlobals::check_upper_case(cx, "static constant", it.ident, it.span);
1060 ast::ItemConst(..) => {
1061 NonUpperCaseGlobals::check_upper_case(cx, "constant", it.ident, it.span);
1067 fn check_pat(&mut self, cx: &Context, p: &ast::Pat) {
1068 // Lint for constants that look like binding identifiers (#7526)
1069 match (&p.node, cx.tcx.def_map.borrow().get(&p.id)) {
1070 (&ast::PatIdent(_, ref path1, _), Some(&def::DefConst(..))) => {
1071 NonUpperCaseGlobals::check_upper_case(cx, "constant in pattern",
1072 path1.node, p.span);
1082 "`if`, `match`, `while` and `return` do not need parentheses"
1086 pub struct UnusedParens;
1089 fn check_unused_parens_core(&self, cx: &Context, value: &ast::Expr, msg: &str,
1090 struct_lit_needs_parens: bool) {
1091 if let ast::ExprParen(ref inner) = value.node {
1092 let necessary = struct_lit_needs_parens && contains_exterior_struct_lit(&**inner);
1094 cx.span_lint(UNUSED_PARENS, value.span,
1095 &format!("unnecessary parentheses around {}",
1100 /// Expressions that syntactically contain an "exterior" struct
1101 /// literal i.e. not surrounded by any parens or other
1102 /// delimiters, e.g. `X { y: 1 }`, `X { y: 1 }.method()`, `foo
1103 /// == X { y: 1 }` and `X { y: 1 } == foo` all do, but `(X {
1104 /// y: 1 }) == foo` does not.
1105 fn contains_exterior_struct_lit(value: &ast::Expr) -> bool {
1107 ast::ExprStruct(..) => true,
1109 ast::ExprAssign(ref lhs, ref rhs) |
1110 ast::ExprAssignOp(_, ref lhs, ref rhs) |
1111 ast::ExprBinary(_, ref lhs, ref rhs) => {
1112 // X { y: 1 } + X { y: 2 }
1113 contains_exterior_struct_lit(&**lhs) ||
1114 contains_exterior_struct_lit(&**rhs)
1116 ast::ExprUnary(_, ref x) |
1117 ast::ExprCast(ref x, _) |
1118 ast::ExprField(ref x, _) |
1119 ast::ExprTupField(ref x, _) |
1120 ast::ExprIndex(ref x, _) => {
1121 // &X { y: 1 }, X { y: 1 }.y
1122 contains_exterior_struct_lit(&**x)
1125 ast::ExprMethodCall(_, _, ref exprs) => {
1126 // X { y: 1 }.bar(...)
1127 contains_exterior_struct_lit(&*exprs[0])
1136 impl LintPass for UnusedParens {
1137 fn get_lints(&self) -> LintArray {
1138 lint_array!(UNUSED_PARENS)
1141 fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
1142 let (value, msg, struct_lit_needs_parens) = match e.node {
1143 ast::ExprIf(ref cond, _, _) => (cond, "`if` condition", true),
1144 ast::ExprWhile(ref cond, _, _) => (cond, "`while` condition", true),
1145 ast::ExprMatch(ref head, _, source) => match source {
1146 ast::MatchSource::Normal => (head, "`match` head expression", true),
1147 ast::MatchSource::IfLetDesugar { .. } => (head, "`if let` head expression", true),
1148 ast::MatchSource::WhileLetDesugar => (head, "`while let` head expression", true),
1149 ast::MatchSource::ForLoopDesugar => (head, "`for` head expression", true),
1151 ast::ExprRet(Some(ref value)) => (value, "`return` value", false),
1152 ast::ExprAssign(_, ref value) => (value, "assigned value", false),
1153 ast::ExprAssignOp(_, _, ref value) => (value, "assigned value", false),
1156 self.check_unused_parens_core(cx, &**value, msg, struct_lit_needs_parens);
1159 fn check_stmt(&mut self, cx: &Context, s: &ast::Stmt) {
1160 let (value, msg) = match s.node {
1161 ast::StmtDecl(ref decl, _) => match decl.node {
1162 ast::DeclLocal(ref local) => match local.init {
1163 Some(ref value) => (value, "assigned value"),
1170 self.check_unused_parens_core(cx, &**value, msg, false);
1175 UNUSED_IMPORT_BRACES,
1177 "unnecessary braces around an imported item"
1181 pub struct UnusedImportBraces;
1183 impl LintPass for UnusedImportBraces {
1184 fn get_lints(&self) -> LintArray {
1185 lint_array!(UNUSED_IMPORT_BRACES)
1188 fn check_item(&mut self, cx: &Context, item: &ast::Item) {
1190 ast::ItemUse(ref view_path) => {
1191 match view_path.node {
1192 ast::ViewPathList(_, ref items) => {
1193 if items.len() == 1 {
1194 match items[0].node {
1195 ast::PathListIdent {ref name, ..} => {
1196 let m = format!("braces around {} is unnecessary",
1197 &token::get_ident(*name));
1198 cx.span_lint(UNUSED_IMPORT_BRACES, item.span,
1214 NON_SHORTHAND_FIELD_PATTERNS,
1216 "using `Struct { x: x }` instead of `Struct { x }`"
1220 pub struct NonShorthandFieldPatterns;
1222 impl LintPass for NonShorthandFieldPatterns {
1223 fn get_lints(&self) -> LintArray {
1224 lint_array!(NON_SHORTHAND_FIELD_PATTERNS)
1227 fn check_pat(&mut self, cx: &Context, pat: &ast::Pat) {
1228 let def_map = cx.tcx.def_map.borrow();
1229 if let ast::PatStruct(_, ref v, _) = pat.node {
1230 for fieldpat in v.iter()
1231 .filter(|fieldpat| !fieldpat.node.is_shorthand)
1232 .filter(|fieldpat| def_map.get(&fieldpat.node.pat.id)
1233 == Some(&def::DefLocal(fieldpat.node.pat.id))) {
1234 if let ast::PatIdent(_, ident, None) = fieldpat.node.pat.node {
1235 if ident.node.as_str() == fieldpat.node.ident.as_str() {
1236 cx.span_lint(NON_SHORTHAND_FIELD_PATTERNS, fieldpat.span,
1237 &format!("the `{}:` in this pattern is redundant and can \
1238 be removed", ident.node.as_str())[])
1249 "unnecessary use of an `unsafe` block"
1253 pub struct UnusedUnsafe;
1255 impl LintPass for UnusedUnsafe {
1256 fn get_lints(&self) -> LintArray {
1257 lint_array!(UNUSED_UNSAFE)
1260 fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
1261 if let ast::ExprBlock(ref blk) = e.node {
1262 // Don't warn about generated blocks, that'll just pollute the output.
1263 if blk.rules == ast::UnsafeBlock(ast::UserProvided) &&
1264 !cx.tcx.used_unsafe.borrow().contains(&blk.id) {
1265 cx.span_lint(UNUSED_UNSAFE, blk.span, "unnecessary `unsafe` block");
1274 "usage of an `unsafe` block"
1278 pub struct UnsafeBlocks;
1280 impl LintPass for UnsafeBlocks {
1281 fn get_lints(&self) -> LintArray {
1282 lint_array!(UNSAFE_BLOCKS)
1285 fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
1286 if let ast::ExprBlock(ref blk) = e.node {
1287 // Don't warn about generated blocks, that'll just pollute the output.
1288 if blk.rules == ast::UnsafeBlock(ast::UserProvided) {
1289 cx.span_lint(UNSAFE_BLOCKS, blk.span, "usage of an `unsafe` block");
1298 "detect mut variables which don't need to be mutable"
1302 pub struct UnusedMut;
1305 fn check_unused_mut_pat(&self, cx: &Context, pats: &[P<ast::Pat>]) {
1306 // collect all mutable pattern and group their NodeIDs by their Identifier to
1307 // avoid false warnings in match arms with multiple patterns
1309 let mut mutables = FnvHashMap();
1311 pat_util::pat_bindings(&cx.tcx.def_map, &**p, |mode, id, _, path1| {
1312 let ident = path1.node;
1313 if let ast::BindByValue(ast::MutMutable) = mode {
1314 if !token::get_ident(ident).starts_with("_") {
1315 match mutables.entry(ident.name.usize()) {
1316 Vacant(entry) => { entry.insert(vec![id]); },
1317 Occupied(mut entry) => { entry.get_mut().push(id); },
1324 let used_mutables = cx.tcx.used_mut_nodes.borrow();
1325 for (_, v) in &mutables {
1326 if !v.iter().any(|e| used_mutables.contains(e)) {
1327 cx.span_lint(UNUSED_MUT, cx.tcx.map.span(v[0]),
1328 "variable does not need to be mutable");
1334 impl LintPass for UnusedMut {
1335 fn get_lints(&self) -> LintArray {
1336 lint_array!(UNUSED_MUT)
1339 fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
1340 if let ast::ExprMatch(_, ref arms, _) = e.node {
1342 self.check_unused_mut_pat(cx, &a.pats[])
1347 fn check_stmt(&mut self, cx: &Context, s: &ast::Stmt) {
1348 if let ast::StmtDecl(ref d, _) = s.node {
1349 if let ast::DeclLocal(ref l) = d.node {
1350 self.check_unused_mut_pat(cx, slice::ref_slice(&l.pat));
1355 fn check_fn(&mut self, cx: &Context,
1356 _: visit::FnKind, decl: &ast::FnDecl,
1357 _: &ast::Block, _: Span, _: ast::NodeId) {
1358 for a in &decl.inputs {
1359 self.check_unused_mut_pat(cx, slice::ref_slice(&a.pat));
1367 "detects unnecessary allocations that can be eliminated"
1371 pub struct UnusedAllocation;
1373 impl LintPass for UnusedAllocation {
1374 fn get_lints(&self) -> LintArray {
1375 lint_array!(UNUSED_ALLOCATION)
1378 fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
1380 ast::ExprUnary(ast::UnUniq, _) => (),
1384 if let Some(adjustment) = cx.tcx.adjustments.borrow().get(&e.id) {
1385 if let ty::AdjustDerefRef(ty::AutoDerefRef { ref autoref, .. }) = *adjustment {
1387 &Some(ty::AutoPtr(_, ast::MutImmutable, None)) => {
1388 cx.span_lint(UNUSED_ALLOCATION, e.span,
1389 "unnecessary allocation, use & instead");
1391 &Some(ty::AutoPtr(_, ast::MutMutable, None)) => {
1392 cx.span_lint(UNUSED_ALLOCATION, e.span,
1393 "unnecessary allocation, use &mut instead");
1405 "detects missing documentation for public members"
1408 pub struct MissingDoc {
1409 /// Stack of IDs of struct definitions.
1410 struct_def_stack: Vec<ast::NodeId>,
1412 /// True if inside variant definition
1415 /// Stack of whether #[doc(hidden)] is set
1416 /// at each level which has lint attributes.
1417 doc_hidden_stack: Vec<bool>,
1421 pub fn new() -> MissingDoc {
1423 struct_def_stack: vec!(),
1425 doc_hidden_stack: vec!(false),
1429 fn doc_hidden(&self) -> bool {
1430 *self.doc_hidden_stack.last().expect("empty doc_hidden_stack")
1433 fn check_missing_docs_attrs(&self,
1435 id: Option<ast::NodeId>,
1436 attrs: &[ast::Attribute],
1438 desc: &'static str) {
1439 // If we're building a test harness, then warning about
1440 // documentation is probably not really relevant right now.
1441 if cx.sess().opts.test { return }
1443 // `#[doc(hidden)]` disables missing_docs check.
1444 if self.doc_hidden() { return }
1446 // Only check publicly-visible items, using the result from the privacy pass.
1447 // It's an option so the crate root can also use this function (it doesn't
1449 if let Some(ref id) = id {
1450 if !cx.exported_items.contains(id) {
1455 let has_doc = attrs.iter().any(|a| {
1456 match a.node.value.node {
1457 ast::MetaNameValue(ref name, _) if *name == "doc" => true,
1462 cx.span_lint(MISSING_DOCS, sp,
1463 &format!("missing documentation for {}", desc)[]);
1468 impl LintPass for MissingDoc {
1469 fn get_lints(&self) -> LintArray {
1470 lint_array!(MISSING_DOCS)
1473 fn enter_lint_attrs(&mut self, _: &Context, attrs: &[ast::Attribute]) {
1474 let doc_hidden = self.doc_hidden() || attrs.iter().any(|attr| {
1475 attr.check_name("doc") && match attr.meta_item_list() {
1477 Some(l) => attr::contains_name(&l[], "hidden"),
1480 self.doc_hidden_stack.push(doc_hidden);
1483 fn exit_lint_attrs(&mut self, _: &Context, _: &[ast::Attribute]) {
1484 self.doc_hidden_stack.pop().expect("empty doc_hidden_stack");
1487 fn check_struct_def(&mut self, _: &Context,
1488 _: &ast::StructDef, _: ast::Ident, _: &ast::Generics, id: ast::NodeId) {
1489 self.struct_def_stack.push(id);
1492 fn check_struct_def_post(&mut self, _: &Context,
1493 _: &ast::StructDef, _: ast::Ident, _: &ast::Generics, id: ast::NodeId) {
1494 let popped = self.struct_def_stack.pop().expect("empty struct_def_stack");
1495 assert!(popped == id);
1498 fn check_crate(&mut self, cx: &Context, krate: &ast::Crate) {
1499 self.check_missing_docs_attrs(cx, None, &krate.attrs[],
1500 krate.span, "crate");
1503 fn check_item(&mut self, cx: &Context, it: &ast::Item) {
1504 let desc = match it.node {
1505 ast::ItemFn(..) => "a function",
1506 ast::ItemMod(..) => "a module",
1507 ast::ItemEnum(..) => "an enum",
1508 ast::ItemStruct(..) => "a struct",
1509 ast::ItemTrait(..) => "a trait",
1510 ast::ItemTy(..) => "a type alias",
1513 self.check_missing_docs_attrs(cx, Some(it.id), &it.attrs[],
1517 fn check_fn(&mut self, cx: &Context,
1518 fk: visit::FnKind, _: &ast::FnDecl,
1519 _: &ast::Block, _: Span, _: ast::NodeId) {
1520 if let visit::FkMethod(_, _, m) = fk {
1521 // If the method is an impl for a trait, don't doc.
1522 if method_context(cx, m) == TraitImpl { return; }
1524 // Otherwise, doc according to privacy. This will also check
1525 // doc for default methods defined on traits.
1526 self.check_missing_docs_attrs(cx, Some(m.id), &m.attrs[],
1527 m.span, "a method");
1531 fn check_ty_method(&mut self, cx: &Context, tm: &ast::TypeMethod) {
1532 self.check_missing_docs_attrs(cx, Some(tm.id), &tm.attrs[],
1533 tm.span, "a type method");
1536 fn check_struct_field(&mut self, cx: &Context, sf: &ast::StructField) {
1537 if let ast::NamedField(_, vis) = sf.node.kind {
1538 if vis == ast::Public || self.in_variant {
1539 let cur_struct_def = *self.struct_def_stack.last()
1540 .expect("empty struct_def_stack");
1541 self.check_missing_docs_attrs(cx, Some(cur_struct_def),
1542 &sf.node.attrs[], sf.span,
1548 fn check_variant(&mut self, cx: &Context, v: &ast::Variant, _: &ast::Generics) {
1549 self.check_missing_docs_attrs(cx, Some(v.node.id), &v.node.attrs[],
1550 v.span, "a variant");
1551 assert!(!self.in_variant);
1552 self.in_variant = true;
1555 fn check_variant_post(&mut self, _: &Context, _: &ast::Variant, _: &ast::Generics) {
1556 assert!(self.in_variant);
1557 self.in_variant = false;
1562 pub struct MissingCopyImplementations;
1564 impl LintPass for MissingCopyImplementations {
1565 fn get_lints(&self) -> LintArray {
1566 lint_array!(MISSING_COPY_IMPLEMENTATIONS)
1569 fn check_item(&mut self, cx: &Context, item: &ast::Item) {
1570 if !cx.exported_items.contains(&item.id) {
1574 .destructor_for_type
1576 .contains_key(&ast_util::local_def(item.id)) {
1579 let ty = match item.node {
1580 ast::ItemStruct(_, ref ast_generics) => {
1581 if ast_generics.is_parameterized() {
1584 ty::mk_struct(cx.tcx,
1585 ast_util::local_def(item.id),
1586 cx.tcx.mk_substs(Substs::empty()))
1588 ast::ItemEnum(_, ref ast_generics) => {
1589 if ast_generics.is_parameterized() {
1593 ast_util::local_def(item.id),
1594 cx.tcx.mk_substs(Substs::empty()))
1598 let parameter_environment = ty::empty_parameter_environment(cx.tcx);
1599 if !ty::type_moves_by_default(¶meter_environment, item.span, ty) {
1602 if ty::can_type_implement_copy(¶meter_environment, item.span, ty).is_ok() {
1603 cx.span_lint(MISSING_COPY_IMPLEMENTATIONS,
1605 "type could implement `Copy`; consider adding `impl \
1612 MISSING_DEBUG_IMPLEMENTATIONS,
1614 "detects missing implementations of fmt::Debug"
1617 pub struct MissingDebugImplementations {
1618 impling_types: Option<NodeSet>,
1621 impl MissingDebugImplementations {
1622 pub fn new() -> MissingDebugImplementations {
1623 MissingDebugImplementations {
1624 impling_types: None,
1629 impl LintPass for MissingDebugImplementations {
1630 fn get_lints(&self) -> LintArray {
1631 lint_array!(MISSING_DEBUG_IMPLEMENTATIONS)
1634 fn check_item(&mut self, cx: &Context, item: &ast::Item) {
1635 if !cx.exported_items.contains(&item.id) {
1640 ast::ItemStruct(..) | ast::ItemEnum(..) => {},
1644 let debug = match cx.tcx.lang_items.debug_trait() {
1645 Some(debug) => debug,
1649 if self.impling_types.is_none() {
1650 let impls = cx.tcx.trait_impls.borrow();
1651 let impls = match impls.get(&debug) {
1653 impls.borrow().iter()
1654 .filter(|d| d.krate == ast::LOCAL_CRATE)
1655 .filter_map(|d| ty::ty_to_def_id(ty::node_id_to_type(cx.tcx, d.node)))
1661 self.impling_types = Some(impls);
1662 debug!("{:?}", self.impling_types);
1665 if !self.impling_types.as_ref().unwrap().contains(&item.id) {
1666 cx.span_lint(MISSING_DEBUG_IMPLEMENTATIONS,
1668 "type does not implement `fmt::Debug`; consider adding #[derive(Debug)] \
1669 or a manual implementation")
1677 "detects use of #[deprecated] items"
1680 /// Checks for use of items with `#[deprecated]` attributes
1682 pub struct Stability;
1685 fn lint(&self, cx: &Context, _id: ast::DefId, span: Span, stability: &Option<attr::Stability>) {
1687 // deprecated attributes apply in-crate and cross-crate
1688 let (lint, label) = match *stability {
1689 Some(attr::Stability { deprecated_since: Some(_), .. }) =>
1690 (DEPRECATED, "deprecated"),
1694 output(cx, span, stability, lint, label);
1696 fn output(cx: &Context, span: Span, stability: &Option<attr::Stability>,
1697 lint: &'static Lint, label: &'static str) {
1698 let msg = match *stability {
1699 Some(attr::Stability { reason: Some(ref s), .. }) => {
1700 format!("use of {} item: {}", label, *s)
1702 _ => format!("use of {} item", label)
1705 cx.span_lint(lint, span, &msg[]);
1710 impl LintPass for Stability {
1711 fn get_lints(&self) -> LintArray {
1712 lint_array!(DEPRECATED)
1715 fn check_item(&mut self, cx: &Context, item: &ast::Item) {
1716 stability::check_item(cx.tcx, item, false,
1717 &mut |id, sp, stab| self.lint(cx, id, sp, stab));
1720 fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
1721 stability::check_expr(cx.tcx, e,
1722 &mut |id, sp, stab| self.lint(cx, id, sp, stab));
1725 fn check_path(&mut self, cx: &Context, path: &ast::Path, id: ast::NodeId) {
1726 stability::check_path(cx.tcx, path, id,
1727 &mut |id, sp, stab| self.lint(cx, id, sp, stab));
1732 pub UNCONDITIONAL_RECURSION,
1734 "functions that cannot return without calling themselves"
1738 pub struct UnconditionalRecursion;
1741 impl LintPass for UnconditionalRecursion {
1742 fn get_lints(&self) -> LintArray {
1743 lint_array![UNCONDITIONAL_RECURSION]
1746 fn check_fn(&mut self, cx: &Context, fn_kind: visit::FnKind, _: &ast::FnDecl,
1747 blk: &ast::Block, sp: Span, id: ast::NodeId) {
1748 type F = for<'tcx> fn(&ty::ctxt<'tcx>,
1749 ast::NodeId, ast::NodeId, ast::Ident, ast::NodeId) -> bool;
1751 let (name, checker) = match fn_kind {
1752 visit::FkItemFn(name, _, _, _) => (name, id_refers_to_this_fn as F),
1753 visit::FkMethod(name, _, _) => (name, id_refers_to_this_method as F),
1754 // closures can't recur, so they don't matter.
1755 visit::FkFnBlock => return
1758 let impl_def_id = ty::impl_of_method(cx.tcx, ast_util::local_def(id))
1759 .unwrap_or(ast_util::local_def(ast::DUMMY_NODE_ID));
1760 assert!(ast_util::is_local(impl_def_id));
1761 let impl_node_id = impl_def_id.node;
1763 // Walk through this function (say `f`) looking to see if
1764 // every possible path references itself, i.e. the function is
1765 // called recursively unconditionally. This is done by trying
1766 // to find a path from the entry node to the exit node that
1767 // *doesn't* call `f` by traversing from the entry while
1768 // pretending that calls of `f` are sinks (i.e. ignoring any
1769 // exit edges from them).
1771 // NB. this has an edge case with non-returning statements,
1772 // like `loop {}` or `panic!()`: control flow never reaches
1773 // the exit node through these, so one can have a function
1774 // that never actually calls itselfs but is still picked up by
1777 // fn f(cond: bool) {
1778 // if !cond { panic!() } // could come from `assert!(cond)`
1782 // In general, functions of that form may be able to call
1783 // itself a finite number of times and then diverge. The lint
1784 // considers this to be an error for two reasons, (a) it is
1785 // easier to implement, and (b) it seems rare to actually want
1786 // to have behaviour like the above, rather than
1787 // e.g. accidentally recurring after an assert.
1789 let cfg = cfg::CFG::new(cx.tcx, blk);
1791 let mut work_queue = vec![cfg.entry];
1792 let mut reached_exit_without_self_call = false;
1793 let mut self_call_spans = vec![];
1794 let mut visited = BitvSet::new();
1796 while let Some(idx) = work_queue.pop() {
1797 let cfg_id = idx.node_id();
1798 if idx == cfg.exit {
1800 reached_exit_without_self_call = true;
1802 } else if visited.contains(&cfg_id) {
1806 visited.insert(cfg_id);
1807 let node_id = cfg.graph.node_data(idx).id;
1809 // is this a recursive call?
1810 if node_id != ast::DUMMY_NODE_ID && checker(cx.tcx, impl_node_id, id, name, node_id) {
1812 self_call_spans.push(cx.tcx.map.span(node_id));
1813 // this is a self call, so we shouldn't explore past
1814 // this node in the CFG.
1817 // add the successors of this node to explore the graph further.
1818 cfg.graph.each_outgoing_edge(idx, |_, edge| {
1819 let target_idx = edge.target();
1820 let target_cfg_id = target_idx.node_id();
1821 if !visited.contains(&target_cfg_id) {
1822 work_queue.push(target_idx)
1828 // check the number of sell calls because a function that
1829 // doesn't return (e.g. calls a `-> !` function or `loop { /*
1830 // no break */ }`) shouldn't be linted unless it actually
1832 if !reached_exit_without_self_call && self_call_spans.len() > 0 {
1833 cx.span_lint(UNCONDITIONAL_RECURSION, sp,
1834 "function cannot return without recurring");
1836 // FIXME #19668: these could be span_lint_note's instead of this manual guard.
1837 if cx.current_level(UNCONDITIONAL_RECURSION) != Level::Allow {
1838 let sess = cx.sess();
1839 // offer some help to the programmer.
1840 for call in &self_call_spans {
1841 sess.span_note(*call, "recursive call site")
1843 sess.span_help(sp, "a `loop` may express intention better if this is on purpose")
1850 // Functions for identifying if the given NodeId `id`
1851 // represents a call to the function `fn_id`/method
1854 fn id_refers_to_this_fn<'tcx>(tcx: &ty::ctxt<'tcx>,
1858 id: ast::NodeId) -> bool {
1859 tcx.def_map.borrow().get(&id)
1860 .map_or(false, |def| {
1861 let did = def.def_id();
1862 ast_util::is_local(did) && did.node == fn_id
1866 // check if the method call `id` refers to method `method_id`
1867 // (with name `method_name` contained in impl `impl_id`).
1868 fn id_refers_to_this_method<'tcx>(tcx: &ty::ctxt<'tcx>,
1869 impl_id: ast::NodeId,
1870 method_id: ast::NodeId,
1871 method_name: ast::Ident,
1872 id: ast::NodeId) -> bool {
1873 let did = match tcx.method_map.borrow().get(&ty::MethodCall::expr(id)) {
1874 None => return false,
1875 Some(m) => match m.origin {
1876 // There's no way to know if a method call via a
1877 // vtable is recursion, so we assume it's not.
1878 ty::MethodTraitObject(_) => return false,
1880 // This `did` refers directly to the method definition.
1881 ty::MethodStatic(did) | ty::MethodStaticClosure(did) => did,
1883 // MethodTypeParam are methods from traits:
1885 // The `impl ... for ...` of this method call
1886 // isn't known, e.g. it might be a default method
1887 // in a trait, so we get the def-id of the trait
1889 ty::MethodTypeParam(
1890 ty::MethodParam { ref trait_ref, method_num, impl_def_id: None, }) => {
1891 ty::trait_item(tcx, trait_ref.def_id, method_num).def_id()
1894 // The `impl` is known, so we check that with a
1896 ty::MethodTypeParam(
1897 ty::MethodParam { impl_def_id: Some(impl_def_id), .. }) => {
1899 let name = match tcx.map.expect_expr(id).node {
1900 ast::ExprMethodCall(ref sp_ident, _, _) => sp_ident.node,
1901 _ => tcx.sess.span_bug(
1903 "non-method call expr behaving like a method call?")
1905 // it matches if it comes from the same impl,
1906 // and has the same method name.
1907 return ast_util::is_local(impl_def_id)
1908 && impl_def_id.node == impl_id
1909 && method_name.name == name.name
1914 ast_util::is_local(did) && did.node == method_id
1922 "compiler plugin used as ordinary library in non-plugin crate"
1926 pub struct PluginAsLibrary;
1928 impl LintPass for PluginAsLibrary {
1929 fn get_lints(&self) -> LintArray {
1930 lint_array![PLUGIN_AS_LIBRARY]
1933 fn check_item(&mut self, cx: &Context, it: &ast::Item) {
1934 if cx.sess().plugin_registrar_fn.get().is_some() {
1935 // We're compiling a plugin; it's fine to link other plugins.
1940 ast::ItemExternCrate(..) => (),
1944 let md = match cx.sess().cstore.find_extern_mod_stmt_cnum(it.id) {
1945 Some(cnum) => cx.sess().cstore.get_crate_data(cnum),
1947 // Probably means we aren't linking the crate for some reason.
1949 // Not sure if / when this could happen.
1954 if decoder::get_plugin_registrar_fn(md.data()).is_some() {
1955 cx.span_lint(PLUGIN_AS_LIBRARY, it.span,
1956 "compiler plugin used as an ordinary library");
1964 "imports that are never used"
1968 pub UNUSED_EXTERN_CRATES,
1970 "extern crates that are never used"
1974 pub UNUSED_QUALIFICATIONS,
1976 "detects unnecessarily qualified names"
1982 "unrecognized lint attribute"
1986 pub UNUSED_VARIABLES,
1988 "detect variables which are not used in any way"
1992 pub UNUSED_ASSIGNMENTS,
1994 "detect assignments that will never be read"
2000 "detect unused, unexported items"
2004 pub UNREACHABLE_CODE,
2006 "detects unreachable code paths"
2012 "mass-change the level for lints which produce warnings"
2016 pub UNUSED_FEATURES,
2018 "unused or unknown features found in crate-level #[feature] directives"
2022 pub STABLE_FEATURES,
2024 "stable features found in #[feature] directive"
2028 pub UNKNOWN_CRATE_TYPES,
2030 "unknown crate type found in #[crate_type] directive"
2034 pub VARIANT_SIZE_DIFFERENCES,
2036 "detects enums with widely varying variant sizes"
2040 pub FAT_PTR_TRANSMUTES,
2042 "detects transmutes of fat pointers"
2046 pub MISSING_COPY_IMPLEMENTATIONS,
2048 "detects potentially-forgotten implementations of `Copy`"
2051 /// Does nothing as a lint pass, but registers some `Lint`s
2052 /// which are used by other parts of the compiler.
2054 pub struct HardwiredLints;
2056 impl LintPass for HardwiredLints {
2057 fn get_lints(&self) -> LintArray {
2060 UNUSED_EXTERN_CRATES,
2061 UNUSED_QUALIFICATIONS,
2070 UNKNOWN_CRATE_TYPES,
2071 VARIANT_SIZE_DIFFERENCES,
2078 PRIVATE_NO_MANGLE_FNS,
2080 "functions marked #[no_mangle] should be exported"
2084 PRIVATE_NO_MANGLE_STATICS,
2086 "statics marked #[no_mangle] should be exported"
2090 NO_MANGLE_CONST_ITEMS,
2092 "const items will not have their symbols exported"
2096 pub struct InvalidNoMangleItems;
2098 impl LintPass for InvalidNoMangleItems {
2099 fn get_lints(&self) -> LintArray {
2100 lint_array!(PRIVATE_NO_MANGLE_FNS,
2101 PRIVATE_NO_MANGLE_STATICS,
2102 NO_MANGLE_CONST_ITEMS)
2105 fn check_item(&mut self, cx: &Context, it: &ast::Item) {
2107 ast::ItemFn(..) => {
2108 if attr::contains_name(&it.attrs, "no_mangle") &&
2109 !cx.exported_items.contains(&it.id) {
2110 let msg = format!("function {} is marked #[no_mangle], but not exported",
2112 cx.span_lint(PRIVATE_NO_MANGLE_FNS, it.span, &msg);
2115 ast::ItemStatic(..) => {
2116 if attr::contains_name(it.attrs.as_slice(), "no_mangle") &&
2117 !cx.exported_items.contains(&it.id) {
2118 let msg = format!("static {} is marked #[no_mangle], but not exported",
2120 cx.span_lint(PRIVATE_NO_MANGLE_STATICS, it.span, msg.as_slice());
2123 ast::ItemConst(..) => {
2124 if attr::contains_name(it.attrs.as_slice(), "no_mangle") {
2125 // Const items do not refer to a particular location in memory, and therefore
2126 // don't have anything to attach a symbol to
2127 let msg = "const items should never be #[no_mangle], consider instead using \
2129 cx.span_lint(NO_MANGLE_CONST_ITEMS, it.span, msg);
2137 /// Forbids using the `#[feature(...)]` attribute
2139 pub struct UnstableFeatures;
2141 declare_lint!(UNSTABLE_FEATURES, Allow,
2142 "enabling unstable features");
2144 impl LintPass for UnstableFeatures {
2145 fn get_lints(&self) -> LintArray {
2146 lint_array!(UNSTABLE_FEATURES)
2148 fn check_attribute(&mut self, ctx: &Context, attr: &ast::Attribute) {
2150 if attr::contains_name(&[attr.node.value.clone()], "feature") {
2151 ctx.span_lint(UNSTABLE_FEATURES, attr.span, "unstable feature");