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;
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::parse::token;
51 use syntax::ast::{TyIs, TyUs, TyI8, TyU8, TyI16, TyU16, TyI32, TyU32, TyI64, TyU64};
54 use syntax::visit::{self, Visitor};
59 "suggest using `loop { }` instead of `while true { }`"
65 impl LintPass for WhileTrue {
66 fn get_lints(&self) -> LintArray {
67 lint_array!(WHILE_TRUE)
70 fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
71 if let ast::ExprWhile(ref cond, _, _) = e.node {
72 if let ast::ExprLit(ref lit) = cond.node {
73 if let ast::LitBool(true) = lit.node {
74 cx.span_lint(WHILE_TRUE, e.span,
75 "denote infinite loops with loop { ... }");
85 "detects unnecessary type casts that can be removed"
89 pub struct UnusedCasts;
91 impl LintPass for UnusedCasts {
92 fn get_lints(&self) -> LintArray {
93 lint_array!(UNUSED_TYPECASTS)
96 fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
97 if let ast::ExprCast(ref expr, ref ty) = e.node {
98 let t_t = ty::expr_ty(cx.tcx, e);
99 if ty::expr_ty(cx.tcx, &**expr) == t_t {
100 cx.span_lint(UNUSED_TYPECASTS, ty.span, "unnecessary type cast");
109 "using an unary minus operator on unsigned type"
115 "comparisons made useless by limits of the types involved"
119 OVERFLOWING_LITERALS,
121 "literal out of range for its type"
127 "shift exceeds the type's number of bits"
131 pub struct TypeLimits {
132 /// Id of the last visited negated expression
133 negated_expr_id: ast::NodeId,
137 pub fn new() -> TypeLimits {
144 impl LintPass for TypeLimits {
145 fn get_lints(&self) -> LintArray {
146 lint_array!(UNSIGNED_NEGATION, UNUSED_COMPARISONS, OVERFLOWING_LITERALS,
150 fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
152 ast::ExprUnary(ast::UnNeg, ref expr) => {
154 ast::ExprLit(ref lit) => {
156 ast::LitInt(_, ast::UnsignedIntLit(_)) => {
157 cx.span_lint(UNSIGNED_NEGATION, e.span,
158 "negation of unsigned int literal may \
165 let t = ty::expr_ty(cx.tcx, &**expr);
168 cx.span_lint(UNSIGNED_NEGATION, e.span,
169 "negation of unsigned int variable may \
176 // propagate negation, if the negation itself isn't negated
177 if self.negated_expr_id != e.id {
178 self.negated_expr_id = expr.id;
181 ast::ExprParen(ref expr) if self.negated_expr_id == e.id => {
182 self.negated_expr_id = expr.id;
184 ast::ExprBinary(binop, ref l, ref r) => {
185 if is_comparison(binop) && !check_limits(cx.tcx, binop, &**l, &**r) {
186 cx.span_lint(UNUSED_COMPARISONS, e.span,
187 "comparison is useless due to type limits");
190 if is_shift_binop(binop.node) {
191 let opt_ty_bits = match ty::expr_ty(cx.tcx, &**l).sty {
192 ty::ty_int(t) => Some(int_ty_bits(t, cx.sess().target.int_type)),
193 ty::ty_uint(t) => Some(uint_ty_bits(t, cx.sess().target.uint_type)),
197 if let Some(bits) = opt_ty_bits {
198 let exceeding = if let ast::ExprLit(ref lit) = r.node {
199 if let ast::LitInt(shift, _) = lit.node { shift >= bits }
202 match eval_const_expr_partial(cx.tcx, &**r) {
203 Ok(const_int(shift)) => { shift as u64 >= bits },
204 Ok(const_uint(shift)) => { shift >= bits },
209 cx.span_lint(EXCEEDING_BITSHIFTS, e.span,
210 "bitshift exceeds the type's number of bits");
215 ast::ExprLit(ref lit) => {
216 match ty::expr_ty(cx.tcx, e).sty {
219 ast::LitInt(v, ast::SignedIntLit(_, ast::Plus)) |
220 ast::LitInt(v, ast::UnsuffixedIntLit(ast::Plus)) => {
221 let int_type = if let ast::TyIs(_) = t {
222 cx.sess().target.int_type
224 let (min, max) = int_ty_range(int_type);
225 let negative = self.negated_expr_id == e.id;
227 if (negative && v > (min.abs() as u64)) ||
228 (!negative && v > (max.abs() as u64)) {
229 cx.span_lint(OVERFLOWING_LITERALS, e.span,
230 "literal out of range for its type");
238 let uint_type = if let ast::TyUs(_) = t {
239 cx.sess().target.uint_type
241 let (min, max) = uint_ty_range(uint_type);
242 let lit_val: u64 = match lit.node {
243 ast::LitByte(_v) => return, // _v is u8, within range by definition
244 ast::LitInt(v, _) => v,
247 if lit_val < min || lit_val > max {
248 cx.span_lint(OVERFLOWING_LITERALS, e.span,
249 "literal out of range for its type");
253 let (min, max) = float_ty_range(t);
254 let lit_val: f64 = match lit.node {
255 ast::LitFloat(ref v, _) |
256 ast::LitFloatUnsuffixed(ref v) => {
257 match v.parse().ok() {
264 if lit_val < min || lit_val > max {
265 cx.span_lint(OVERFLOWING_LITERALS, e.span,
266 "literal out of range for its type");
275 fn is_valid<T:cmp::PartialOrd>(binop: ast::BinOp, v: T,
276 min: T, max: T) -> bool {
278 ast::BiLt => v > min && v <= max,
279 ast::BiLe => v >= min && v < max,
280 ast::BiGt => v >= min && v < max,
281 ast::BiGe => v > min && v <= max,
282 ast::BiEq | ast::BiNe => v >= min && v <= max,
287 fn rev_binop(binop: ast::BinOp) -> ast::BinOp {
288 codemap::respan(binop.span, match binop.node {
289 ast::BiLt => ast::BiGt,
290 ast::BiLe => ast::BiGe,
291 ast::BiGt => ast::BiLt,
292 ast::BiGe => ast::BiLe,
297 // for int & uint, be conservative with the warnings, so that the
298 // warnings are consistent between 32- and 64-bit platforms
299 fn int_ty_range(int_ty: ast::IntTy) -> (i64, i64) {
301 ast::TyIs(_) => (i64::MIN, i64::MAX),
302 ast::TyI8 => (i8::MIN as i64, i8::MAX as i64),
303 ast::TyI16 => (i16::MIN as i64, i16::MAX as i64),
304 ast::TyI32 => (i32::MIN as i64, i32::MAX as i64),
305 ast::TyI64 => (i64::MIN, i64::MAX)
309 fn uint_ty_range(uint_ty: ast::UintTy) -> (u64, u64) {
311 ast::TyUs(_) => (u64::MIN, u64::MAX),
312 ast::TyU8 => (u8::MIN as u64, u8::MAX as u64),
313 ast::TyU16 => (u16::MIN as u64, u16::MAX as u64),
314 ast::TyU32 => (u32::MIN as u64, u32::MAX as u64),
315 ast::TyU64 => (u64::MIN, u64::MAX)
319 fn float_ty_range(float_ty: ast::FloatTy) -> (f64, f64) {
321 ast::TyF32 => (f32::MIN_VALUE as f64, f32::MAX_VALUE as f64),
322 ast::TyF64 => (f64::MIN_VALUE, f64::MAX_VALUE)
326 fn int_ty_bits(int_ty: ast::IntTy, target_int_ty: ast::IntTy) -> u64 {
328 ast::TyIs(_) => int_ty_bits(target_int_ty, target_int_ty),
329 ast::TyI8 => i8::BITS as u64,
330 ast::TyI16 => i16::BITS as u64,
331 ast::TyI32 => i32::BITS as u64,
332 ast::TyI64 => i64::BITS as u64
336 fn uint_ty_bits(uint_ty: ast::UintTy, target_uint_ty: ast::UintTy) -> u64 {
338 ast::TyUs(_) => uint_ty_bits(target_uint_ty, target_uint_ty),
339 ast::TyU8 => u8::BITS as u64,
340 ast::TyU16 => u16::BITS as u64,
341 ast::TyU32 => u32::BITS as u64,
342 ast::TyU64 => u64::BITS as u64
346 fn check_limits(tcx: &ty::ctxt, binop: ast::BinOp,
347 l: &ast::Expr, r: &ast::Expr) -> bool {
348 let (lit, expr, swap) = match (&l.node, &r.node) {
349 (&ast::ExprLit(_), _) => (l, r, true),
350 (_, &ast::ExprLit(_)) => (r, l, false),
353 // Normalize the binop so that the literal is always on the RHS in
355 let norm_binop = if swap { rev_binop(binop) } else { binop };
356 match ty::expr_ty(tcx, expr).sty {
357 ty::ty_int(int_ty) => {
358 let (min, max) = int_ty_range(int_ty);
359 let lit_val: i64 = match lit.node {
360 ast::ExprLit(ref li) => match li.node {
361 ast::LitInt(v, ast::SignedIntLit(_, ast::Plus)) |
362 ast::LitInt(v, ast::UnsuffixedIntLit(ast::Plus)) => v as i64,
363 ast::LitInt(v, ast::SignedIntLit(_, ast::Minus)) |
364 ast::LitInt(v, ast::UnsuffixedIntLit(ast::Minus)) => -(v as i64),
369 is_valid(norm_binop, lit_val, min, max)
371 ty::ty_uint(uint_ty) => {
372 let (min, max): (u64, u64) = uint_ty_range(uint_ty);
373 let lit_val: u64 = match lit.node {
374 ast::ExprLit(ref li) => match li.node {
375 ast::LitInt(v, _) => v,
380 is_valid(norm_binop, lit_val, min, max)
386 fn is_comparison(binop: ast::BinOp) -> bool {
388 ast::BiEq | ast::BiLt | ast::BiLe |
389 ast::BiNe | ast::BiGe | ast::BiGt => true,
399 "proper use of libc types in foreign modules"
402 struct ImproperCTypesVisitor<'a, 'tcx: 'a> {
403 cx: &'a Context<'a, 'tcx>
406 impl<'a, 'tcx> ImproperCTypesVisitor<'a, 'tcx> {
407 fn check_def(&mut self, sp: Span, ty_id: ast::NodeId, path_id: ast::NodeId) {
408 match self.cx.tcx.def_map.borrow()[path_id].clone() {
409 def::DefPrimTy(ast::TyInt(ast::TyIs(_))) => {
410 self.cx.span_lint(IMPROPER_CTYPES, sp,
411 "found rust type `isize` in foreign module, while \
412 libc::c_int or libc::c_long should be used");
414 def::DefPrimTy(ast::TyUint(ast::TyUs(_))) => {
415 self.cx.span_lint(IMPROPER_CTYPES, sp,
416 "found rust type `usize` in foreign module, while \
417 libc::c_uint or libc::c_ulong should be used");
420 let tty = match self.cx.tcx.ast_ty_to_ty_cache.borrow().get(&ty_id) {
421 Some(&ty::atttce_resolved(t)) => t,
422 _ => panic!("ast_ty_to_ty_cache was incomplete after typeck!")
425 if !ty::is_ffi_safe(self.cx.tcx, tty) {
426 self.cx.span_lint(IMPROPER_CTYPES, sp,
427 "found type without foreign-function-safe
428 representation annotation in foreign module, consider \
429 adding a #[repr(...)] attribute to the type");
437 impl<'a, 'tcx, 'v> Visitor<'v> for ImproperCTypesVisitor<'a, 'tcx> {
438 fn visit_ty(&mut self, ty: &ast::Ty) {
440 ast::TyPath(_, id) => self.check_def(ty.span, ty.id, id),
443 visit::walk_ty(self, ty);
448 pub struct ImproperCTypes;
450 impl LintPass for ImproperCTypes {
451 fn get_lints(&self) -> LintArray {
452 lint_array!(IMPROPER_CTYPES)
455 fn check_item(&mut self, cx: &Context, it: &ast::Item) {
456 fn check_ty(cx: &Context, ty: &ast::Ty) {
457 let mut vis = ImproperCTypesVisitor { cx: cx };
461 fn check_foreign_fn(cx: &Context, decl: &ast::FnDecl) {
462 for input in decl.inputs.iter() {
463 check_ty(cx, &*input.ty);
465 if let ast::Return(ref ret_ty) = decl.output {
466 check_ty(cx, &**ret_ty);
471 ast::ItemForeignMod(ref nmod) if nmod.abi != abi::RustIntrinsic => {
472 for ni in nmod.items.iter() {
474 ast::ForeignItemFn(ref decl, _) => check_foreign_fn(cx, &**decl),
475 ast::ForeignItemStatic(ref t, _) => check_ty(cx, &**t)
487 "use of owned (Box type) heap memory"
491 pub struct BoxPointers;
494 fn check_heap_type<'a, 'tcx>(&self, cx: &Context<'a, 'tcx>,
495 span: Span, ty: Ty<'tcx>) {
497 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.iter() {
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 static ATTRIBUTE_WHITELIST: &'static [&'static str] = &[
644 // FIXME: #14408 whitelist docs since rustdoc looks at them
647 // FIXME: #14406 these are processed in trans, which happens after the
664 "omit_gdb_pretty_printer_section",
665 "unsafe_no_drop_flag",
670 // FIXME: #14407 these are only looked at on-demand so we can't
671 // guarantee they'll have already been checked
676 "rustc_on_unimplemented",
678 // FIXME: #19470 this shouldn't be needed forever
681 "rustc_paren_sugar", // FIXME: #18101 temporary unboxed closure hack
684 static CRATE_ATTRS: &'static [&'static str] = &[
694 for &name in ATTRIBUTE_WHITELIST.iter() {
695 if attr.check_name(name) {
700 if !attr::is_used(attr) {
701 cx.span_lint(UNUSED_ATTRIBUTES, attr.span, "unused attribute");
702 if CRATE_ATTRS.contains(&attr.name().get()) {
703 let msg = match attr.node.style {
704 ast::AttrOuter => "crate-level attribute should be an inner \
705 attribute: add an exclamation mark: #![foo]",
706 ast::AttrInner => "crate-level attribute should be in the \
709 cx.span_lint(UNUSED_ATTRIBUTES, attr.span, msg);
718 "path statements with no effect"
722 pub struct PathStatements;
724 impl LintPass for PathStatements {
725 fn get_lints(&self) -> LintArray {
726 lint_array!(PATH_STATEMENTS)
729 fn check_stmt(&mut self, cx: &Context, s: &ast::Stmt) {
731 ast::StmtSemi(ref expr, _) => {
733 ast::ExprPath(_) => cx.span_lint(PATH_STATEMENTS, s.span,
734 "path statement with no effect"),
746 "unused result of a type flagged as #[must_use]"
752 "unused result of an expression in a statement"
756 pub struct UnusedResults;
758 impl LintPass for UnusedResults {
759 fn get_lints(&self) -> LintArray {
760 lint_array!(UNUSED_MUST_USE, UNUSED_RESULTS)
763 fn check_stmt(&mut self, cx: &Context, s: &ast::Stmt) {
764 let expr = match s.node {
765 ast::StmtSemi(ref expr, _) => &**expr,
769 if let ast::ExprRet(..) = expr.node {
773 let t = ty::expr_ty(cx.tcx, expr);
774 let mut warned = false;
776 ty::ty_tup(ref tys) if tys.is_empty() => return,
777 ty::ty_bool => return,
778 ty::ty_struct(did, _) |
779 ty::ty_enum(did, _) => {
780 if ast_util::is_local(did) {
781 if let ast_map::NodeItem(it) = cx.tcx.map.get(did.node) {
782 warned |= check_must_use(cx, &it.attrs[], s.span);
785 let attrs = csearch::get_item_attrs(&cx.sess().cstore, did);
786 warned |= check_must_use(cx, &attrs[], s.span);
792 cx.span_lint(UNUSED_RESULTS, s.span, "unused result");
795 fn check_must_use(cx: &Context, attrs: &[ast::Attribute], sp: Span) -> bool {
796 for attr in attrs.iter() {
797 if attr.check_name("must_use") {
798 let mut msg = "unused result which must be used".to_string();
799 // check for #[must_use="..."]
800 match attr.value_str() {
804 msg.push_str(s.get());
807 cx.span_lint(UNUSED_MUST_USE, sp, &msg[]);
817 pub NON_CAMEL_CASE_TYPES,
819 "types, variants, traits and type parameters should have camel case names"
823 pub struct NonCamelCaseTypes;
825 impl NonCamelCaseTypes {
826 fn check_case(&self, cx: &Context, sort: &str, ident: ast::Ident, span: Span) {
827 fn is_camel_case(ident: ast::Ident) -> bool {
828 let ident = token::get_ident(ident);
829 if ident.get().is_empty() { return true; }
830 let ident = ident.get().trim_matches('_');
832 // start with a non-lowercase letter rather than non-uppercase
833 // ones (some scripts don't have a concept of upper/lowercase)
834 ident.len() > 0 && !ident.char_at(0).is_lowercase() && !ident.contains_char('_')
837 fn to_camel_case(s: &str) -> String {
838 s.split('_').flat_map(|word| word.chars().enumerate().map(|(i, c)|
839 if i == 0 { c.to_uppercase() }
844 let s = token::get_ident(ident);
846 if !is_camel_case(ident) {
847 let c = to_camel_case(s.get());
848 let m = if c.is_empty() {
849 format!("{} `{}` should have a camel case name such as `CamelCase`", sort, s)
851 format!("{} `{}` should have a camel case name such as `{}`", sort, s, c)
853 cx.span_lint(NON_CAMEL_CASE_TYPES, span, &m[]);
858 impl LintPass for NonCamelCaseTypes {
859 fn get_lints(&self) -> LintArray {
860 lint_array!(NON_CAMEL_CASE_TYPES)
863 fn check_item(&mut self, cx: &Context, it: &ast::Item) {
864 let has_extern_repr = it.attrs.iter().map(|attr| {
865 attr::find_repr_attrs(cx.tcx.sess.diagnostic(), attr).iter()
866 .any(|r| r == &attr::ReprExtern)
868 if has_extern_repr { return }
871 ast::ItemTy(..) | ast::ItemStruct(..) => {
872 self.check_case(cx, "type", it.ident, it.span)
874 ast::ItemTrait(..) => {
875 self.check_case(cx, "trait", it.ident, it.span)
877 ast::ItemEnum(ref enum_definition, _) => {
878 if has_extern_repr { return }
879 self.check_case(cx, "type", it.ident, it.span);
880 for variant in enum_definition.variants.iter() {
881 self.check_case(cx, "variant", variant.node.name, variant.span);
888 fn check_generics(&mut self, cx: &Context, it: &ast::Generics) {
889 for gen in it.ty_params.iter() {
890 self.check_case(cx, "type parameter", gen.ident, gen.span);
902 fn method_context(cx: &Context, m: &ast::Method) -> MethodContext {
903 let did = ast::DefId {
904 krate: ast::LOCAL_CRATE,
908 match cx.tcx.impl_or_trait_items.borrow().get(&did).cloned() {
909 None => cx.sess().span_bug(m.span, "missing method descriptor?!"),
912 ty::MethodTraitItem(md) => {
914 ty::TraitContainer(..) => TraitDefaultImpl,
915 ty::ImplContainer(cid) => {
916 match ty::impl_trait_ref(cx.tcx, cid) {
917 Some(..) => TraitImpl,
923 ty::TypeTraitItem(typedef) => {
924 match typedef.container {
925 ty::TraitContainer(..) => TraitDefaultImpl,
926 ty::ImplContainer(cid) => {
927 match ty::impl_trait_ref(cx.tcx, cid) {
928 Some(..) => TraitImpl,
942 "methods, functions, lifetime parameters and modules should have snake case names"
946 pub struct NonSnakeCase;
949 fn to_snake_case(mut str: &str) -> String {
950 let mut words = vec![];
951 // Preserve leading underscores
952 str = str.trim_left_matches(|&mut: c: char| {
954 words.push(String::new());
958 for s in str.split('_') {
959 let mut last_upper = false;
960 let mut buf = String::new();
961 if s.is_empty() { continue; }
962 for ch in s.chars() {
963 if !buf.is_empty() && buf != "'"
969 last_upper = ch.is_uppercase();
970 buf.push(ch.to_lowercase());
977 fn check_snake_case(&self, cx: &Context, sort: &str, ident: ast::Ident, span: Span) {
978 fn is_snake_case(ident: ast::Ident) -> bool {
979 let ident = token::get_ident(ident);
980 if ident.get().is_empty() { return true; }
981 let ident = ident.get().trim_left_matches('\'');
982 let ident = ident.trim_matches('_');
984 let mut allow_underscore = true;
985 ident.chars().all(|c| {
986 allow_underscore = match c {
987 '_' if !allow_underscore => return false,
989 c if !c.is_uppercase() => true,
996 let s = token::get_ident(ident);
998 if !is_snake_case(ident) {
999 let sc = NonSnakeCase::to_snake_case(s.get());
1001 cx.span_lint(NON_SNAKE_CASE, span,
1002 &*format!("{} `{}` should have a snake case name such as `{}`",
1005 cx.span_lint(NON_SNAKE_CASE, span,
1006 &*format!("{} `{}` should have a snake case name",
1013 impl LintPass for NonSnakeCase {
1014 fn get_lints(&self) -> LintArray {
1015 lint_array!(NON_SNAKE_CASE)
1018 fn check_fn(&mut self, cx: &Context,
1019 fk: visit::FnKind, _: &ast::FnDecl,
1020 _: &ast::Block, span: Span, _: ast::NodeId) {
1022 visit::FkMethod(ident, _, m) => match method_context(cx, m) {
1024 => self.check_snake_case(cx, "method", ident, span),
1026 => self.check_snake_case(cx, "trait method", ident, span),
1029 visit::FkItemFn(ident, _, _, _)
1030 => self.check_snake_case(cx, "function", ident, span),
1035 fn check_item(&mut self, cx: &Context, it: &ast::Item) {
1036 if let ast::ItemMod(_) = it.node {
1037 self.check_snake_case(cx, "module", it.ident, it.span);
1041 fn check_ty_method(&mut self, cx: &Context, t: &ast::TypeMethod) {
1042 self.check_snake_case(cx, "trait method", t.ident, t.span);
1045 fn check_lifetime_def(&mut self, cx: &Context, t: &ast::LifetimeDef) {
1046 self.check_snake_case(cx, "lifetime", t.lifetime.name.ident(), t.lifetime.span);
1049 fn check_pat(&mut self, cx: &Context, p: &ast::Pat) {
1050 if let &ast::PatIdent(_, ref path1, _) = &p.node {
1051 if let Some(&def::DefLocal(_)) = cx.tcx.def_map.borrow().get(&p.id) {
1052 self.check_snake_case(cx, "variable", path1.node, p.span);
1057 fn check_struct_def(&mut self, cx: &Context, s: &ast::StructDef,
1058 _: ast::Ident, _: &ast::Generics, _: ast::NodeId) {
1059 for sf in s.fields.iter() {
1060 if let ast::StructField_ { kind: ast::NamedField(ident, _), .. } = sf.node {
1061 self.check_snake_case(cx, "structure field", ident, sf.span);
1068 pub NON_UPPER_CASE_GLOBALS,
1070 "static constants should have uppercase identifiers"
1074 pub struct NonUpperCaseGlobals;
1076 impl NonUpperCaseGlobals {
1077 fn check_upper_case(cx: &Context, sort: &str, ident: ast::Ident, span: Span) {
1078 let s = token::get_ident(ident);
1080 if s.get().chars().any(|c| c.is_lowercase()) {
1081 let uc: String = NonSnakeCase::to_snake_case(s.get()).chars()
1082 .map(|c| c.to_uppercase()).collect();
1084 cx.span_lint(NON_UPPER_CASE_GLOBALS, span,
1085 format!("{} `{}` should have an upper case name such as `{}`",
1086 sort, s, uc).as_slice());
1088 cx.span_lint(NON_UPPER_CASE_GLOBALS, span,
1089 format!("{} `{}` should have an upper case name",
1090 sort, s).as_slice());
1096 impl LintPass for NonUpperCaseGlobals {
1097 fn get_lints(&self) -> LintArray {
1098 lint_array!(NON_UPPER_CASE_GLOBALS)
1101 fn check_item(&mut self, cx: &Context, it: &ast::Item) {
1103 // only check static constants
1104 ast::ItemStatic(_, ast::MutImmutable, _) => {
1105 NonUpperCaseGlobals::check_upper_case(cx, "static constant", it.ident, it.span);
1107 ast::ItemConst(..) => {
1108 NonUpperCaseGlobals::check_upper_case(cx, "constant", it.ident, it.span);
1114 fn check_pat(&mut self, cx: &Context, p: &ast::Pat) {
1115 // Lint for constants that look like binding identifiers (#7526)
1116 match (&p.node, cx.tcx.def_map.borrow().get(&p.id)) {
1117 (&ast::PatIdent(_, ref path1, _), Some(&def::DefConst(..))) => {
1118 NonUpperCaseGlobals::check_upper_case(cx, "constant in pattern",
1119 path1.node, p.span);
1129 "`if`, `match`, `while` and `return` do not need parentheses"
1133 pub struct UnusedParens;
1136 fn check_unused_parens_core(&self, cx: &Context, value: &ast::Expr, msg: &str,
1137 struct_lit_needs_parens: bool) {
1138 if let ast::ExprParen(ref inner) = value.node {
1139 let necessary = struct_lit_needs_parens && contains_exterior_struct_lit(&**inner);
1141 cx.span_lint(UNUSED_PARENS, value.span,
1142 &format!("unnecessary parentheses around {}",
1147 /// Expressions that syntactically contain an "exterior" struct
1148 /// literal i.e. not surrounded by any parens or other
1149 /// delimiters, e.g. `X { y: 1 }`, `X { y: 1 }.method()`, `foo
1150 /// == X { y: 1 }` and `X { y: 1 } == foo` all do, but `(X {
1151 /// y: 1 }) == foo` does not.
1152 fn contains_exterior_struct_lit(value: &ast::Expr) -> bool {
1154 ast::ExprStruct(..) => true,
1156 ast::ExprAssign(ref lhs, ref rhs) |
1157 ast::ExprAssignOp(_, ref lhs, ref rhs) |
1158 ast::ExprBinary(_, ref lhs, ref rhs) => {
1159 // X { y: 1 } + X { y: 2 }
1160 contains_exterior_struct_lit(&**lhs) ||
1161 contains_exterior_struct_lit(&**rhs)
1163 ast::ExprUnary(_, ref x) |
1164 ast::ExprCast(ref x, _) |
1165 ast::ExprField(ref x, _) |
1166 ast::ExprTupField(ref x, _) |
1167 ast::ExprIndex(ref x, _) => {
1168 // &X { y: 1 }, X { y: 1 }.y
1169 contains_exterior_struct_lit(&**x)
1172 ast::ExprMethodCall(_, _, ref exprs) => {
1173 // X { y: 1 }.bar(...)
1174 contains_exterior_struct_lit(&*exprs[0])
1183 impl LintPass for UnusedParens {
1184 fn get_lints(&self) -> LintArray {
1185 lint_array!(UNUSED_PARENS)
1188 fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
1189 let (value, msg, struct_lit_needs_parens) = match e.node {
1190 ast::ExprIf(ref cond, _, _) => (cond, "`if` condition", true),
1191 ast::ExprWhile(ref cond, _, _) => (cond, "`while` condition", true),
1192 ast::ExprMatch(ref head, _, source) => match source {
1193 ast::MatchSource::Normal => (head, "`match` head expression", true),
1194 ast::MatchSource::IfLetDesugar { .. } => (head, "`if let` head expression", true),
1195 ast::MatchSource::WhileLetDesugar => (head, "`while let` head expression", true),
1196 ast::MatchSource::ForLoopDesugar => (head, "`for` head expression", true),
1198 ast::ExprRet(Some(ref value)) => (value, "`return` value", false),
1199 ast::ExprAssign(_, ref value) => (value, "assigned value", false),
1200 ast::ExprAssignOp(_, _, ref value) => (value, "assigned value", false),
1203 self.check_unused_parens_core(cx, &**value, msg, struct_lit_needs_parens);
1206 fn check_stmt(&mut self, cx: &Context, s: &ast::Stmt) {
1207 let (value, msg) = match s.node {
1208 ast::StmtDecl(ref decl, _) => match decl.node {
1209 ast::DeclLocal(ref local) => match local.init {
1210 Some(ref value) => (value, "assigned value"),
1217 self.check_unused_parens_core(cx, &**value, msg, false);
1222 UNUSED_IMPORT_BRACES,
1224 "unnecessary braces around an imported item"
1228 pub struct UnusedImportBraces;
1230 impl LintPass for UnusedImportBraces {
1231 fn get_lints(&self) -> LintArray {
1232 lint_array!(UNUSED_IMPORT_BRACES)
1235 fn check_item(&mut self, cx: &Context, item: &ast::Item) {
1237 ast::ItemUse(ref view_path) => {
1238 match view_path.node {
1239 ast::ViewPathList(_, ref items) => {
1240 if items.len() == 1 {
1241 match items[0].node {
1242 ast::PathListIdent {ref name, ..} => {
1243 let m = format!("braces around {} is unnecessary",
1244 token::get_ident(*name).get());
1245 cx.span_lint(UNUSED_IMPORT_BRACES, item.span,
1261 NON_SHORTHAND_FIELD_PATTERNS,
1263 "using `Struct { x: x }` instead of `Struct { x }`"
1267 pub struct NonShorthandFieldPatterns;
1269 impl LintPass for NonShorthandFieldPatterns {
1270 fn get_lints(&self) -> LintArray {
1271 lint_array!(NON_SHORTHAND_FIELD_PATTERNS)
1274 fn check_pat(&mut self, cx: &Context, pat: &ast::Pat) {
1275 let def_map = cx.tcx.def_map.borrow();
1276 if let ast::PatStruct(_, ref v, _) = pat.node {
1277 for fieldpat in v.iter()
1278 .filter(|fieldpat| !fieldpat.node.is_shorthand)
1279 .filter(|fieldpat| def_map.get(&fieldpat.node.pat.id)
1280 == Some(&def::DefLocal(fieldpat.node.pat.id))) {
1281 if let ast::PatIdent(_, ident, None) = fieldpat.node.pat.node {
1282 if ident.node.as_str() == fieldpat.node.ident.as_str() {
1283 cx.span_lint(NON_SHORTHAND_FIELD_PATTERNS, fieldpat.span,
1284 &format!("the `{}:` in this pattern is redundant and can \
1285 be removed", ident.node.as_str())[])
1296 "unnecessary use of an `unsafe` block"
1300 pub struct UnusedUnsafe;
1302 impl LintPass for UnusedUnsafe {
1303 fn get_lints(&self) -> LintArray {
1304 lint_array!(UNUSED_UNSAFE)
1307 fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
1308 if let ast::ExprBlock(ref blk) = e.node {
1309 // Don't warn about generated blocks, that'll just pollute the output.
1310 if blk.rules == ast::UnsafeBlock(ast::UserProvided) &&
1311 !cx.tcx.used_unsafe.borrow().contains(&blk.id) {
1312 cx.span_lint(UNUSED_UNSAFE, blk.span, "unnecessary `unsafe` block");
1321 "usage of an `unsafe` block"
1325 pub struct UnsafeBlocks;
1327 impl LintPass for UnsafeBlocks {
1328 fn get_lints(&self) -> LintArray {
1329 lint_array!(UNSAFE_BLOCKS)
1332 fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
1333 if let ast::ExprBlock(ref blk) = e.node {
1334 // Don't warn about generated blocks, that'll just pollute the output.
1335 if blk.rules == ast::UnsafeBlock(ast::UserProvided) {
1336 cx.span_lint(UNSAFE_BLOCKS, blk.span, "usage of an `unsafe` block");
1345 "detect mut variables which don't need to be mutable"
1349 pub struct UnusedMut;
1352 fn check_unused_mut_pat(&self, cx: &Context, pats: &[P<ast::Pat>]) {
1353 // collect all mutable pattern and group their NodeIDs by their Identifier to
1354 // avoid false warnings in match arms with multiple patterns
1356 let mut mutables = FnvHashMap();
1357 for p in pats.iter() {
1358 pat_util::pat_bindings(&cx.tcx.def_map, &**p, |mode, id, _, path1| {
1359 let ident = path1.node;
1360 if let ast::BindByValue(ast::MutMutable) = mode {
1361 if !token::get_ident(ident).get().starts_with("_") {
1362 match mutables.entry(ident.name.usize()) {
1363 Vacant(entry) => { entry.insert(vec![id]); },
1364 Occupied(mut entry) => { entry.get_mut().push(id); },
1371 let used_mutables = cx.tcx.used_mut_nodes.borrow();
1372 for (_, v) in mutables.iter() {
1373 if !v.iter().any(|e| used_mutables.contains(e)) {
1374 cx.span_lint(UNUSED_MUT, cx.tcx.map.span(v[0]),
1375 "variable does not need to be mutable");
1381 impl LintPass for UnusedMut {
1382 fn get_lints(&self) -> LintArray {
1383 lint_array!(UNUSED_MUT)
1386 fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
1387 if let ast::ExprMatch(_, ref arms, _) = e.node {
1388 for a in arms.iter() {
1389 self.check_unused_mut_pat(cx, &a.pats[])
1394 fn check_stmt(&mut self, cx: &Context, s: &ast::Stmt) {
1395 if let ast::StmtDecl(ref d, _) = s.node {
1396 if let ast::DeclLocal(ref l) = d.node {
1397 self.check_unused_mut_pat(cx, slice::ref_slice(&l.pat));
1402 fn check_fn(&mut self, cx: &Context,
1403 _: visit::FnKind, decl: &ast::FnDecl,
1404 _: &ast::Block, _: Span, _: ast::NodeId) {
1405 for a in decl.inputs.iter() {
1406 self.check_unused_mut_pat(cx, slice::ref_slice(&a.pat));
1414 "detects unnecessary allocations that can be eliminated"
1418 pub struct UnusedAllocation;
1420 impl LintPass for UnusedAllocation {
1421 fn get_lints(&self) -> LintArray {
1422 lint_array!(UNUSED_ALLOCATION)
1425 fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
1427 ast::ExprUnary(ast::UnUniq, _) => (),
1431 if let Some(adjustment) = cx.tcx.adjustments.borrow().get(&e.id) {
1432 if let ty::AdjustDerefRef(ty::AutoDerefRef { ref autoref, .. }) = *adjustment {
1434 &Some(ty::AutoPtr(_, ast::MutImmutable, None)) => {
1435 cx.span_lint(UNUSED_ALLOCATION, e.span,
1436 "unnecessary allocation, use & instead");
1438 &Some(ty::AutoPtr(_, ast::MutMutable, None)) => {
1439 cx.span_lint(UNUSED_ALLOCATION, e.span,
1440 "unnecessary allocation, use &mut instead");
1452 "detects missing documentation for public members"
1455 pub struct MissingDoc {
1456 /// Stack of IDs of struct definitions.
1457 struct_def_stack: Vec<ast::NodeId>,
1459 /// True if inside variant definition
1462 /// Stack of whether #[doc(hidden)] is set
1463 /// at each level which has lint attributes.
1464 doc_hidden_stack: Vec<bool>,
1468 pub fn new() -> MissingDoc {
1470 struct_def_stack: vec!(),
1472 doc_hidden_stack: vec!(false),
1476 fn doc_hidden(&self) -> bool {
1477 *self.doc_hidden_stack.last().expect("empty doc_hidden_stack")
1480 fn check_missing_docs_attrs(&self,
1482 id: Option<ast::NodeId>,
1483 attrs: &[ast::Attribute],
1485 desc: &'static str) {
1486 // If we're building a test harness, then warning about
1487 // documentation is probably not really relevant right now.
1488 if cx.sess().opts.test { return }
1490 // `#[doc(hidden)]` disables missing_docs check.
1491 if self.doc_hidden() { return }
1493 // Only check publicly-visible items, using the result from the privacy pass.
1494 // It's an option so the crate root can also use this function (it doesn't
1496 if let Some(ref id) = id {
1497 if !cx.exported_items.contains(id) {
1502 let has_doc = attrs.iter().any(|a| {
1503 match a.node.value.node {
1504 ast::MetaNameValue(ref name, _) if *name == "doc" => true,
1509 cx.span_lint(MISSING_DOCS, sp,
1510 &format!("missing documentation for {}", desc)[]);
1515 impl LintPass for MissingDoc {
1516 fn get_lints(&self) -> LintArray {
1517 lint_array!(MISSING_DOCS)
1520 fn enter_lint_attrs(&mut self, _: &Context, attrs: &[ast::Attribute]) {
1521 let doc_hidden = self.doc_hidden() || attrs.iter().any(|attr| {
1522 attr.check_name("doc") && match attr.meta_item_list() {
1524 Some(l) => attr::contains_name(&l[], "hidden"),
1527 self.doc_hidden_stack.push(doc_hidden);
1530 fn exit_lint_attrs(&mut self, _: &Context, _: &[ast::Attribute]) {
1531 self.doc_hidden_stack.pop().expect("empty doc_hidden_stack");
1534 fn check_struct_def(&mut self, _: &Context,
1535 _: &ast::StructDef, _: ast::Ident, _: &ast::Generics, id: ast::NodeId) {
1536 self.struct_def_stack.push(id);
1539 fn check_struct_def_post(&mut self, _: &Context,
1540 _: &ast::StructDef, _: ast::Ident, _: &ast::Generics, id: ast::NodeId) {
1541 let popped = self.struct_def_stack.pop().expect("empty struct_def_stack");
1542 assert!(popped == id);
1545 fn check_crate(&mut self, cx: &Context, krate: &ast::Crate) {
1546 self.check_missing_docs_attrs(cx, None, &krate.attrs[],
1547 krate.span, "crate");
1550 fn check_item(&mut self, cx: &Context, it: &ast::Item) {
1551 let desc = match it.node {
1552 ast::ItemFn(..) => "a function",
1553 ast::ItemMod(..) => "a module",
1554 ast::ItemEnum(..) => "an enum",
1555 ast::ItemStruct(..) => "a struct",
1556 ast::ItemTrait(..) => "a trait",
1557 ast::ItemTy(..) => "a type alias",
1560 self.check_missing_docs_attrs(cx, Some(it.id), &it.attrs[],
1564 fn check_fn(&mut self, cx: &Context,
1565 fk: visit::FnKind, _: &ast::FnDecl,
1566 _: &ast::Block, _: Span, _: ast::NodeId) {
1567 if let visit::FkMethod(_, _, m) = fk {
1568 // If the method is an impl for a trait, don't doc.
1569 if method_context(cx, m) == TraitImpl { return; }
1571 // Otherwise, doc according to privacy. This will also check
1572 // doc for default methods defined on traits.
1573 self.check_missing_docs_attrs(cx, Some(m.id), &m.attrs[],
1574 m.span, "a method");
1578 fn check_ty_method(&mut self, cx: &Context, tm: &ast::TypeMethod) {
1579 self.check_missing_docs_attrs(cx, Some(tm.id), &tm.attrs[],
1580 tm.span, "a type method");
1583 fn check_struct_field(&mut self, cx: &Context, sf: &ast::StructField) {
1584 if let ast::NamedField(_, vis) = sf.node.kind {
1585 if vis == ast::Public || self.in_variant {
1586 let cur_struct_def = *self.struct_def_stack.last()
1587 .expect("empty struct_def_stack");
1588 self.check_missing_docs_attrs(cx, Some(cur_struct_def),
1589 &sf.node.attrs[], sf.span,
1595 fn check_variant(&mut self, cx: &Context, v: &ast::Variant, _: &ast::Generics) {
1596 self.check_missing_docs_attrs(cx, Some(v.node.id), &v.node.attrs[],
1597 v.span, "a variant");
1598 assert!(!self.in_variant);
1599 self.in_variant = true;
1602 fn check_variant_post(&mut self, _: &Context, _: &ast::Variant, _: &ast::Generics) {
1603 assert!(self.in_variant);
1604 self.in_variant = false;
1609 pub struct MissingCopyImplementations;
1611 impl LintPass for MissingCopyImplementations {
1612 fn get_lints(&self) -> LintArray {
1613 lint_array!(MISSING_COPY_IMPLEMENTATIONS)
1616 fn check_item(&mut self, cx: &Context, item: &ast::Item) {
1617 if !cx.exported_items.contains(&item.id) {
1621 .destructor_for_type
1623 .contains_key(&ast_util::local_def(item.id)) {
1626 let ty = match item.node {
1627 ast::ItemStruct(_, ref ast_generics) => {
1628 if ast_generics.is_parameterized() {
1631 ty::mk_struct(cx.tcx,
1632 ast_util::local_def(item.id),
1633 cx.tcx.mk_substs(Substs::empty()))
1635 ast::ItemEnum(_, ref ast_generics) => {
1636 if ast_generics.is_parameterized() {
1640 ast_util::local_def(item.id),
1641 cx.tcx.mk_substs(Substs::empty()))
1645 let parameter_environment = ty::empty_parameter_environment(cx.tcx);
1646 if !ty::type_moves_by_default(¶meter_environment, item.span, ty) {
1649 if ty::can_type_implement_copy(¶meter_environment, item.span, ty).is_ok() {
1650 cx.span_lint(MISSING_COPY_IMPLEMENTATIONS,
1652 "type could implement `Copy`; consider adding `impl \
1659 MISSING_DEBUG_IMPLEMENTATIONS,
1661 "detects missing implementations of fmt::Debug"
1664 pub struct MissingDebugImplementations {
1665 impling_types: Option<NodeSet>,
1668 impl MissingDebugImplementations {
1669 pub fn new() -> MissingDebugImplementations {
1670 MissingDebugImplementations {
1671 impling_types: None,
1676 impl LintPass for MissingDebugImplementations {
1677 fn get_lints(&self) -> LintArray {
1678 lint_array!(MISSING_DEBUG_IMPLEMENTATIONS)
1681 fn check_item(&mut self, cx: &Context, item: &ast::Item) {
1682 if !cx.exported_items.contains(&item.id) {
1687 ast::ItemStruct(..) | ast::ItemEnum(..) => {},
1691 let debug = match cx.tcx.lang_items.debug_trait() {
1692 Some(debug) => debug,
1696 if self.impling_types.is_none() {
1697 let impls = cx.tcx.trait_impls.borrow();
1698 let impls = match impls.get(&debug) {
1700 impls.borrow().iter()
1701 .filter(|d| d.krate == ast::LOCAL_CRATE)
1702 .filter_map(|d| ty::ty_to_def_id(ty::node_id_to_type(cx.tcx, d.node)))
1708 self.impling_types = Some(impls);
1709 debug!("{:?}", self.impling_types);
1712 if !self.impling_types.as_ref().unwrap().contains(&item.id) {
1713 cx.span_lint(MISSING_DEBUG_IMPLEMENTATIONS,
1715 "type does not implement `fmt::Debug`; consider adding #[derive(Debug)] \
1716 or a manual implementation")
1724 "detects use of #[deprecated] items"
1727 /// Checks for use of items with `#[deprecated]` attributes
1729 pub struct Stability;
1732 fn lint(&self, cx: &Context, _id: ast::DefId, span: Span, stability: &Option<attr::Stability>) {
1734 // deprecated attributes apply in-crate and cross-crate
1735 let (lint, label) = match *stability {
1736 Some(attr::Stability { deprecated_since: Some(_), .. }) =>
1737 (DEPRECATED, "deprecated"),
1741 output(cx, span, stability, lint, label);
1743 fn output(cx: &Context, span: Span, stability: &Option<attr::Stability>,
1744 lint: &'static Lint, label: &'static str) {
1745 let msg = match *stability {
1746 Some(attr::Stability { reason: Some(ref s), .. }) => {
1747 format!("use of {} item: {}", label, *s)
1749 _ => format!("use of {} item", label)
1752 cx.span_lint(lint, span, &msg[]);
1757 impl LintPass for Stability {
1758 fn get_lints(&self) -> LintArray {
1759 lint_array!(DEPRECATED)
1762 fn check_item(&mut self, cx: &Context, item: &ast::Item) {
1763 stability::check_item(cx.tcx, item,
1764 &mut |id, sp, stab| self.lint(cx, id, sp, stab));
1767 fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
1768 stability::check_expr(cx.tcx, e,
1769 &mut |id, sp, stab| self.lint(cx, id, sp, stab));
1774 pub UNCONDITIONAL_RECURSION,
1776 "functions that cannot return without calling themselves"
1780 pub struct UnconditionalRecursion;
1783 impl LintPass for UnconditionalRecursion {
1784 fn get_lints(&self) -> LintArray {
1785 lint_array![UNCONDITIONAL_RECURSION]
1788 fn check_fn(&mut self, cx: &Context, fn_kind: visit::FnKind, _: &ast::FnDecl,
1789 blk: &ast::Block, sp: Span, id: ast::NodeId) {
1790 type F = for<'tcx> fn(&ty::ctxt<'tcx>,
1791 ast::NodeId, ast::NodeId, ast::Ident, ast::NodeId) -> bool;
1793 let (name, checker) = match fn_kind {
1794 visit::FkItemFn(name, _, _, _) => (name, id_refers_to_this_fn as F),
1795 visit::FkMethod(name, _, _) => (name, id_refers_to_this_method as F),
1796 // closures can't recur, so they don't matter.
1797 visit::FkFnBlock => return
1800 let impl_def_id = ty::impl_of_method(cx.tcx, ast_util::local_def(id))
1801 .unwrap_or(ast_util::local_def(ast::DUMMY_NODE_ID));
1802 assert!(ast_util::is_local(impl_def_id));
1803 let impl_node_id = impl_def_id.node;
1805 // Walk through this function (say `f`) looking to see if
1806 // every possible path references itself, i.e. the function is
1807 // called recursively unconditionally. This is done by trying
1808 // to find a path from the entry node to the exit node that
1809 // *doesn't* call `f` by traversing from the entry while
1810 // pretending that calls of `f` are sinks (i.e. ignoring any
1811 // exit edges from them).
1813 // NB. this has an edge case with non-returning statements,
1814 // like `loop {}` or `panic!()`: control flow never reaches
1815 // the exit node through these, so one can have a function
1816 // that never actually calls itselfs but is still picked up by
1819 // fn f(cond: bool) {
1820 // if !cond { panic!() } // could come from `assert!(cond)`
1824 // In general, functions of that form may be able to call
1825 // itself a finite number of times and then diverge. The lint
1826 // considers this to be an error for two reasons, (a) it is
1827 // easier to implement, and (b) it seems rare to actually want
1828 // to have behaviour like the above, rather than
1829 // e.g. accidentally recurring after an assert.
1831 let cfg = cfg::CFG::new(cx.tcx, blk);
1833 let mut work_queue = vec![cfg.entry];
1834 let mut reached_exit_without_self_call = false;
1835 let mut self_call_spans = vec![];
1836 let mut visited = BitvSet::new();
1838 while let Some(idx) = work_queue.pop() {
1839 let cfg_id = idx.node_id();
1840 if idx == cfg.exit {
1842 reached_exit_without_self_call = true;
1844 } else if visited.contains(&cfg_id) {
1848 visited.insert(cfg_id);
1849 let node_id = cfg.graph.node_data(idx).id;
1851 // is this a recursive call?
1852 if node_id != ast::DUMMY_NODE_ID && checker(cx.tcx, impl_node_id, id, name, node_id) {
1854 self_call_spans.push(cx.tcx.map.span(node_id));
1855 // this is a self call, so we shouldn't explore past
1856 // this node in the CFG.
1859 // add the successors of this node to explore the graph further.
1860 cfg.graph.each_outgoing_edge(idx, |_, edge| {
1861 let target_idx = edge.target();
1862 let target_cfg_id = target_idx.node_id();
1863 if !visited.contains(&target_cfg_id) {
1864 work_queue.push(target_idx)
1870 // check the number of sell calls because a function that
1871 // doesn't return (e.g. calls a `-> !` function or `loop { /*
1872 // no break */ }`) shouldn't be linted unless it actually
1874 if !reached_exit_without_self_call && self_call_spans.len() > 0 {
1875 cx.span_lint(UNCONDITIONAL_RECURSION, sp,
1876 "function cannot return without recurring");
1878 // FIXME #19668: these could be span_lint_note's instead of this manual guard.
1879 if cx.current_level(UNCONDITIONAL_RECURSION) != Level::Allow {
1880 let sess = cx.sess();
1881 // offer some help to the programmer.
1882 for call in self_call_spans.iter() {
1883 sess.span_note(*call, "recursive call site")
1885 sess.span_help(sp, "a `loop` may express intention better if this is on purpose")
1892 // Functions for identifying if the given NodeId `id`
1893 // represents a call to the function `fn_id`/method
1896 fn id_refers_to_this_fn<'tcx>(tcx: &ty::ctxt<'tcx>,
1900 id: ast::NodeId) -> bool {
1901 tcx.def_map.borrow().get(&id)
1902 .map_or(false, |def| {
1903 let did = def.def_id();
1904 ast_util::is_local(did) && did.node == fn_id
1908 // check if the method call `id` refers to method `method_id`
1909 // (with name `method_name` contained in impl `impl_id`).
1910 fn id_refers_to_this_method<'tcx>(tcx: &ty::ctxt<'tcx>,
1911 impl_id: ast::NodeId,
1912 method_id: ast::NodeId,
1913 method_name: ast::Ident,
1914 id: ast::NodeId) -> bool {
1915 let did = match tcx.method_map.borrow().get(&ty::MethodCall::expr(id)) {
1916 None => return false,
1917 Some(m) => match m.origin {
1918 // There's no way to know if a method call via a
1919 // vtable is recursion, so we assume it's not.
1920 ty::MethodTraitObject(_) => return false,
1922 // This `did` refers directly to the method definition.
1923 ty::MethodStatic(did) | ty::MethodStaticClosure(did) => did,
1925 // MethodTypeParam are methods from traits:
1927 // The `impl ... for ...` of this method call
1928 // isn't known, e.g. it might be a default method
1929 // in a trait, so we get the def-id of the trait
1931 ty::MethodTypeParam(
1932 ty::MethodParam { ref trait_ref, method_num, impl_def_id: None, }) => {
1933 ty::trait_item(tcx, trait_ref.def_id, method_num).def_id()
1936 // The `impl` is known, so we check that with a
1938 ty::MethodTypeParam(
1939 ty::MethodParam { impl_def_id: Some(impl_def_id), .. }) => {
1941 let name = match tcx.map.expect_expr(id).node {
1942 ast::ExprMethodCall(ref sp_ident, _, _) => sp_ident.node,
1943 _ => tcx.sess.span_bug(
1945 "non-method call expr behaving like a method call?")
1947 // it matches if it comes from the same impl,
1948 // and has the same method name.
1949 return ast_util::is_local(impl_def_id)
1950 && impl_def_id.node == impl_id
1951 && method_name.name == name.name
1956 ast_util::is_local(did) && did.node == method_id
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 UNKNOWN_CRATE_TYPES,
2024 "unknown crate type found in #[crate_type] directive"
2028 pub VARIANT_SIZE_DIFFERENCES,
2030 "detects enums with widely varying variant sizes"
2034 pub FAT_PTR_TRANSMUTES,
2036 "detects transmutes of fat pointers"
2040 pub MISSING_COPY_IMPLEMENTATIONS,
2042 "detects potentially-forgotten implementations of `Copy`"
2045 /// Does nothing as a lint pass, but registers some `Lint`s
2046 /// which are used by other parts of the compiler.
2048 pub struct HardwiredLints;
2050 impl LintPass for HardwiredLints {
2051 fn get_lints(&self) -> LintArray {
2054 UNUSED_EXTERN_CRATES,
2055 UNUSED_QUALIFICATIONS,
2063 UNKNOWN_CRATE_TYPES,
2064 VARIANT_SIZE_DIFFERENCES,
2071 PRIVATE_NO_MANGLE_FNS,
2073 "functions marked #[no_mangle] should be exported"
2077 pub struct PrivateNoMangleFns;
2079 impl LintPass for PrivateNoMangleFns {
2080 fn get_lints(&self) -> LintArray {
2081 lint_array!(PRIVATE_NO_MANGLE_FNS)
2084 fn check_item(&mut self, cx: &Context, it: &ast::Item) {
2086 ast::ItemFn(..) => {
2087 if attr::contains_name(it.attrs.as_slice(), "no_mangle") &&
2088 !cx.exported_items.contains(&it.id) {
2089 let msg = format!("function {} is marked #[no_mangle], but not exported",
2091 cx.span_lint(PRIVATE_NO_MANGLE_FNS, it.span, msg.as_slice());
2099 /// Forbids using the `#[feature(...)]` attribute
2101 pub struct UnstableFeatures;
2103 declare_lint!(UNSTABLE_FEATURES, Allow,
2104 "enabling unstable features");
2106 impl LintPass for UnstableFeatures {
2107 fn get_lints(&self) -> LintArray {
2108 lint_array!(UNSTABLE_FEATURES)
2110 fn check_attribute(&mut self, ctx: &Context, attr: &ast::Attribute) {
2112 if attr::contains_name(&[attr.node.value.clone()], "feature") {
2113 ctx.span_lint(UNSTABLE_FEATURES, attr.span, "unstable feature");