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};
35 use util::ppaux::{ty_to_string};
36 use util::nodemap::{FnvHashMap, NodeSet};
37 use lint::{Context, LintPass, LintArray};
39 use std::collections::hash_map::Entry::{Occupied, Vacant};
40 use std::num::SignedInt;
41 use std::{cmp, slice};
42 use std::{i8, i16, i32, i64, u8, u16, u32, u64, f32, f64};
44 use syntax::{abi, ast, ast_map};
45 use syntax::ast_util::is_shift_binop;
46 use syntax::attr::{self, AttrMetaMethods};
47 use syntax::codemap::{Span, DUMMY_SP};
48 use syntax::parse::token;
49 use syntax::ast::{TyI, TyU, TyI8, TyU8, TyI16, TyU16, TyI32, TyU32, TyI64, TyU64};
52 use syntax::visit::{self, Visitor};
57 "suggest using `loop { }` instead of `while true { }`"
63 impl LintPass for WhileTrue {
64 fn get_lints(&self) -> LintArray {
65 lint_array!(WHILE_TRUE)
68 fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
69 if let ast::ExprWhile(ref cond, _, _) = e.node {
70 if let ast::ExprLit(ref lit) = cond.node {
71 if let ast::LitBool(true) = lit.node {
72 cx.span_lint(WHILE_TRUE, e.span,
73 "denote infinite loops with loop { ... }");
83 "detects unnecessary type casts that can be removed"
87 pub struct UnusedCasts;
89 impl LintPass for UnusedCasts {
90 fn get_lints(&self) -> LintArray {
91 lint_array!(UNUSED_TYPECASTS)
94 fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
95 if let ast::ExprCast(ref expr, ref ty) = e.node {
96 let t_t = ty::expr_ty(cx.tcx, e);
97 if ty::expr_ty(cx.tcx, &**expr) == t_t {
98 cx.span_lint(UNUSED_TYPECASTS, ty.span, "unnecessary type cast");
107 "using an unary minus operator on unsigned type"
113 "comparisons made useless by limits of the types involved"
117 OVERFLOWING_LITERALS,
119 "literal out of range for its type"
125 "shift exceeds the type's number of bits"
129 pub struct TypeLimits {
130 /// Id of the last visited negated expression
131 negated_expr_id: ast::NodeId,
135 pub fn new() -> TypeLimits {
142 impl LintPass for TypeLimits {
143 fn get_lints(&self) -> LintArray {
144 lint_array!(UNSIGNED_NEGATION, UNUSED_COMPARISONS, OVERFLOWING_LITERALS,
148 fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
150 ast::ExprUnary(ast::UnNeg, ref expr) => {
152 ast::ExprLit(ref lit) => {
154 ast::LitInt(_, ast::UnsignedIntLit(_)) => {
155 cx.span_lint(UNSIGNED_NEGATION, e.span,
156 "negation of unsigned int literal may \
163 let t = ty::expr_ty(cx.tcx, &**expr);
166 cx.span_lint(UNSIGNED_NEGATION, e.span,
167 "negation of unsigned int variable may \
174 // propagate negation, if the negation itself isn't negated
175 if self.negated_expr_id != e.id {
176 self.negated_expr_id = expr.id;
179 ast::ExprParen(ref expr) if self.negated_expr_id == e.id => {
180 self.negated_expr_id = expr.id;
182 ast::ExprBinary(binop, ref l, ref r) => {
183 if is_comparison(binop) && !check_limits(cx.tcx, binop, &**l, &**r) {
184 cx.span_lint(UNUSED_COMPARISONS, e.span,
185 "comparison is useless due to type limits");
188 if is_shift_binop(binop) {
189 let opt_ty_bits = match ty::expr_ty(cx.tcx, &**l).sty {
190 ty::ty_int(t) => Some(int_ty_bits(t, cx.sess().target.int_type)),
191 ty::ty_uint(t) => Some(uint_ty_bits(t, cx.sess().target.uint_type)),
195 if let Some(bits) = opt_ty_bits {
196 let exceeding = if let ast::ExprLit(ref lit) = r.node {
197 if let ast::LitInt(shift, _) = lit.node { shift >= bits }
200 match eval_const_expr_partial(cx.tcx, &**r) {
201 Ok(const_int(shift)) => { shift as u64 >= bits },
202 Ok(const_uint(shift)) => { shift >= bits },
207 cx.span_lint(EXCEEDING_BITSHIFTS, e.span,
208 "bitshift exceeds the type's number of bits");
213 ast::ExprLit(ref lit) => {
214 match ty::expr_ty(cx.tcx, e).sty {
217 ast::LitInt(v, ast::SignedIntLit(_, ast::Plus)) |
218 ast::LitInt(v, ast::UnsuffixedIntLit(ast::Plus)) => {
219 let int_type = if t == ast::TyI {
220 cx.sess().target.int_type
222 let (min, max) = int_ty_range(int_type);
223 let negative = self.negated_expr_id == e.id;
225 if (negative && v > (min.abs() as u64)) ||
226 (!negative && v > (max.abs() as u64)) {
227 cx.span_lint(OVERFLOWING_LITERALS, e.span,
228 "literal out of range for its type");
236 let uint_type = if t == ast::TyU {
237 cx.sess().target.uint_type
239 let (min, max) = uint_ty_range(uint_type);
240 let lit_val: u64 = match lit.node {
241 ast::LitByte(_v) => return, // _v is u8, within range by definition
242 ast::LitInt(v, _) => v,
245 if lit_val < min || lit_val > max {
246 cx.span_lint(OVERFLOWING_LITERALS, e.span,
247 "literal out of range for its type");
251 let (min, max) = float_ty_range(t);
252 let lit_val: f64 = match lit.node {
253 ast::LitFloat(ref v, _) |
254 ast::LitFloatUnsuffixed(ref v) => {
262 if lit_val < min || lit_val > max {
263 cx.span_lint(OVERFLOWING_LITERALS, e.span,
264 "literal out of range for its type");
273 fn is_valid<T:cmp::PartialOrd>(binop: ast::BinOp, v: T,
274 min: T, max: T) -> bool {
276 ast::BiLt => v > min && v <= max,
277 ast::BiLe => v >= min && v < max,
278 ast::BiGt => v >= min && v < max,
279 ast::BiGe => v > min && v <= max,
280 ast::BiEq | ast::BiNe => v >= min && v <= max,
285 fn rev_binop(binop: ast::BinOp) -> ast::BinOp {
287 ast::BiLt => ast::BiGt,
288 ast::BiLe => ast::BiGe,
289 ast::BiGt => ast::BiLt,
290 ast::BiGe => ast::BiLe,
295 // for int & uint, be conservative with the warnings, so that the
296 // warnings are consistent between 32- and 64-bit platforms
297 fn int_ty_range(int_ty: ast::IntTy) -> (i64, i64) {
299 ast::TyI => (i64::MIN, i64::MAX),
300 ast::TyI8 => (i8::MIN as i64, i8::MAX as i64),
301 ast::TyI16 => (i16::MIN as i64, i16::MAX as i64),
302 ast::TyI32 => (i32::MIN as i64, i32::MAX as i64),
303 ast::TyI64 => (i64::MIN, i64::MAX)
307 fn uint_ty_range(uint_ty: ast::UintTy) -> (u64, u64) {
309 ast::TyU => (u64::MIN, u64::MAX),
310 ast::TyU8 => (u8::MIN as u64, u8::MAX as u64),
311 ast::TyU16 => (u16::MIN as u64, u16::MAX as u64),
312 ast::TyU32 => (u32::MIN as u64, u32::MAX as u64),
313 ast::TyU64 => (u64::MIN, u64::MAX)
317 fn float_ty_range(float_ty: ast::FloatTy) -> (f64, f64) {
319 ast::TyF32 => (f32::MIN_VALUE as f64, f32::MAX_VALUE as f64),
320 ast::TyF64 => (f64::MIN_VALUE, f64::MAX_VALUE)
324 fn int_ty_bits(int_ty: ast::IntTy, target_int_ty: ast::IntTy) -> u64 {
326 ast::TyI => int_ty_bits(target_int_ty, target_int_ty),
327 ast::TyI8 => i8::BITS as u64,
328 ast::TyI16 => i16::BITS as u64,
329 ast::TyI32 => i32::BITS as u64,
330 ast::TyI64 => i64::BITS as u64
334 fn uint_ty_bits(uint_ty: ast::UintTy, target_uint_ty: ast::UintTy) -> u64 {
336 ast::TyU => uint_ty_bits(target_uint_ty, target_uint_ty),
337 ast::TyU8 => u8::BITS as u64,
338 ast::TyU16 => u16::BITS as u64,
339 ast::TyU32 => u32::BITS as u64,
340 ast::TyU64 => u64::BITS as u64
344 fn check_limits(tcx: &ty::ctxt, binop: ast::BinOp,
345 l: &ast::Expr, r: &ast::Expr) -> bool {
346 let (lit, expr, swap) = match (&l.node, &r.node) {
347 (&ast::ExprLit(_), _) => (l, r, true),
348 (_, &ast::ExprLit(_)) => (r, l, false),
351 // Normalize the binop so that the literal is always on the RHS in
353 let norm_binop = if swap { rev_binop(binop) } else { binop };
354 match ty::expr_ty(tcx, expr).sty {
355 ty::ty_int(int_ty) => {
356 let (min, max) = int_ty_range(int_ty);
357 let lit_val: i64 = match lit.node {
358 ast::ExprLit(ref li) => match li.node {
359 ast::LitInt(v, ast::SignedIntLit(_, ast::Plus)) |
360 ast::LitInt(v, ast::UnsuffixedIntLit(ast::Plus)) => v as i64,
361 ast::LitInt(v, ast::SignedIntLit(_, ast::Minus)) |
362 ast::LitInt(v, ast::UnsuffixedIntLit(ast::Minus)) => -(v as i64),
367 is_valid(norm_binop, lit_val, min, max)
369 ty::ty_uint(uint_ty) => {
370 let (min, max): (u64, u64) = uint_ty_range(uint_ty);
371 let lit_val: u64 = match lit.node {
372 ast::ExprLit(ref li) => match li.node {
373 ast::LitInt(v, _) => v,
378 is_valid(norm_binop, lit_val, min, max)
384 fn is_comparison(binop: ast::BinOp) -> bool {
386 ast::BiEq | ast::BiLt | ast::BiLe |
387 ast::BiNe | ast::BiGe | ast::BiGt => true,
397 "proper use of libc types in foreign modules"
400 struct ImproperCTypesVisitor<'a, 'tcx: 'a> {
401 cx: &'a Context<'a, 'tcx>
404 impl<'a, 'tcx> ImproperCTypesVisitor<'a, 'tcx> {
405 fn check_def(&mut self, sp: Span, ty_id: ast::NodeId, path_id: ast::NodeId) {
406 match self.cx.tcx.def_map.borrow()[path_id].clone() {
407 def::DefPrimTy(ast::TyInt(ast::TyI)) => {
408 self.cx.span_lint(IMPROPER_CTYPES, sp,
409 "found rust type `int` in foreign module, while \
410 libc::c_int or libc::c_long should be used");
412 def::DefPrimTy(ast::TyUint(ast::TyU)) => {
413 self.cx.span_lint(IMPROPER_CTYPES, sp,
414 "found rust type `uint` in foreign module, while \
415 libc::c_uint or libc::c_ulong should be used");
418 let tty = match self.cx.tcx.ast_ty_to_ty_cache.borrow().get(&ty_id) {
419 Some(&ty::atttce_resolved(t)) => t,
420 _ => panic!("ast_ty_to_ty_cache was incomplete after typeck!")
423 if !ty::is_ffi_safe(self.cx.tcx, tty) {
424 self.cx.span_lint(IMPROPER_CTYPES, sp,
425 "found type without foreign-function-safe
426 representation annotation in foreign module, consider \
427 adding a #[repr(...)] attribute to the type");
435 impl<'a, 'tcx, 'v> Visitor<'v> for ImproperCTypesVisitor<'a, 'tcx> {
436 fn visit_ty(&mut self, ty: &ast::Ty) {
438 ast::TyPath(_, id) => self.check_def(ty.span, ty.id, id),
441 visit::walk_ty(self, ty);
446 pub struct ImproperCTypes;
448 impl LintPass for ImproperCTypes {
449 fn get_lints(&self) -> LintArray {
450 lint_array!(IMPROPER_CTYPES)
453 fn check_item(&mut self, cx: &Context, it: &ast::Item) {
454 fn check_ty(cx: &Context, ty: &ast::Ty) {
455 let mut vis = ImproperCTypesVisitor { cx: cx };
459 fn check_foreign_fn(cx: &Context, decl: &ast::FnDecl) {
460 for input in decl.inputs.iter() {
461 check_ty(cx, &*input.ty);
463 if let ast::Return(ref ret_ty) = decl.output {
464 check_ty(cx, &**ret_ty);
469 ast::ItemForeignMod(ref nmod) if nmod.abi != abi::RustIntrinsic => {
470 for ni in nmod.items.iter() {
472 ast::ForeignItemFn(ref decl, _) => check_foreign_fn(cx, &**decl),
473 ast::ForeignItemStatic(ref t, _) => check_ty(cx, &**t)
485 "use of owned (Box type) heap memory"
489 pub struct BoxPointers;
492 fn check_heap_type<'a, 'tcx>(&self, cx: &Context<'a, 'tcx>,
493 span: Span, ty: Ty<'tcx>) {
495 ty::fold_ty(cx.tcx, ty, |t| {
498 ty::ty_closure(box ty::ClosureTy {
499 store: ty::UniqTraitStore,
511 let s = ty_to_string(cx.tcx, ty);
512 let m = format!("type uses owned (Box type) pointers: {}", s);
513 cx.span_lint(BOX_POINTERS, span, m[]);
518 impl LintPass for BoxPointers {
519 fn get_lints(&self) -> LintArray {
520 lint_array!(BOX_POINTERS)
523 fn check_item(&mut self, cx: &Context, it: &ast::Item) {
528 ast::ItemStruct(..) =>
529 self.check_heap_type(cx, it.span,
530 ty::node_id_to_type(cx.tcx, it.id)),
534 // If it's a struct, we also have to check the fields' types
536 ast::ItemStruct(ref struct_def, _) => {
537 for struct_field in struct_def.fields.iter() {
538 self.check_heap_type(cx, struct_field.span,
539 ty::node_id_to_type(cx.tcx, struct_field.node.id));
546 fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
547 let ty = ty::expr_ty(cx.tcx, e);
548 self.check_heap_type(cx, e.span, ty);
553 RAW_POINTER_DERIVING,
555 "uses of #[derive] with raw pointers are rarely correct"
558 struct RawPtrDerivingVisitor<'a, 'tcx: 'a> {
559 cx: &'a Context<'a, 'tcx>
562 impl<'a, 'tcx, 'v> Visitor<'v> for RawPtrDerivingVisitor<'a, 'tcx> {
563 fn visit_ty(&mut self, ty: &ast::Ty) {
564 static MSG: &'static str = "use of `#[derive]` with a raw pointer";
565 if let ast::TyPtr(..) = ty.node {
566 self.cx.span_lint(RAW_POINTER_DERIVING, ty.span, MSG);
568 visit::walk_ty(self, ty);
570 // explicit override to a no-op to reduce code bloat
571 fn visit_expr(&mut self, _: &ast::Expr) {}
572 fn visit_block(&mut self, _: &ast::Block) {}
575 pub struct RawPointerDeriving {
576 checked_raw_pointers: NodeSet,
579 impl RawPointerDeriving {
580 pub fn new() -> RawPointerDeriving {
582 checked_raw_pointers: NodeSet::new(),
587 impl LintPass for RawPointerDeriving {
588 fn get_lints(&self) -> LintArray {
589 lint_array!(RAW_POINTER_DERIVING)
592 fn check_item(&mut self, cx: &Context, item: &ast::Item) {
593 if !attr::contains_name(item.attrs[], "automatically_derived") {
596 let did = match item.node {
597 ast::ItemImpl(..) => {
598 match ty::node_id_to_type(cx.tcx, item.id).sty {
599 ty::ty_enum(did, _) => did,
600 ty::ty_struct(did, _) => did,
606 if !ast_util::is_local(did) { return }
607 let item = match cx.tcx.map.find(did.node) {
608 Some(ast_map::NodeItem(item)) => item,
611 if !self.checked_raw_pointers.insert(item.id) { return }
613 ast::ItemStruct(..) | ast::ItemEnum(..) => {
614 let mut visitor = RawPtrDerivingVisitor { cx: cx };
615 visit::walk_item(&mut visitor, &*item);
625 "detects attributes that were not used by the compiler"
629 pub struct UnusedAttributes;
631 impl LintPass for UnusedAttributes {
632 fn get_lints(&self) -> LintArray {
633 lint_array!(UNUSED_ATTRIBUTES)
636 fn check_attribute(&mut self, cx: &Context, attr: &ast::Attribute) {
637 static ATTRIBUTE_WHITELIST: &'static [&'static str] = &[
638 // FIXME: #14408 whitelist docs since rustdoc looks at them
641 // FIXME: #14406 these are processed in trans, which happens after the
658 "omit_gdb_pretty_printer_section",
659 "unsafe_no_drop_flag",
664 // FIXME: #14407 these are only looked at on-demand so we can't
665 // guarantee they'll have already been checked
674 // FIXME: #19470 this shouldn't be needed forever
678 static CRATE_ATTRS: &'static [&'static str] = &[
688 for &name in ATTRIBUTE_WHITELIST.iter() {
689 if attr.check_name(name) {
694 if !attr::is_used(attr) {
695 cx.span_lint(UNUSED_ATTRIBUTES, attr.span, "unused attribute");
696 if CRATE_ATTRS.contains(&attr.name().get()) {
697 let msg = match attr.node.style {
698 ast::AttrOuter => "crate-level attribute should be an inner \
699 attribute: add an exclamation mark: #![foo]",
700 ast::AttrInner => "crate-level attribute should be in the \
703 cx.span_lint(UNUSED_ATTRIBUTES, attr.span, msg);
712 "path statements with no effect"
716 pub struct PathStatements;
718 impl LintPass for PathStatements {
719 fn get_lints(&self) -> LintArray {
720 lint_array!(PATH_STATEMENTS)
723 fn check_stmt(&mut self, cx: &Context, s: &ast::Stmt) {
725 ast::StmtSemi(ref expr, _) => {
727 ast::ExprPath(_) => cx.span_lint(PATH_STATEMENTS, s.span,
728 "path statement with no effect"),
740 "unused result of a type flagged as #[must_use]"
746 "unused result of an expression in a statement"
750 pub struct UnusedResults;
752 impl LintPass for UnusedResults {
753 fn get_lints(&self) -> LintArray {
754 lint_array!(UNUSED_MUST_USE, UNUSED_RESULTS)
757 fn check_stmt(&mut self, cx: &Context, s: &ast::Stmt) {
758 let expr = match s.node {
759 ast::StmtSemi(ref expr, _) => &**expr,
763 if let ast::ExprRet(..) = expr.node {
767 let t = ty::expr_ty(cx.tcx, expr);
768 let mut warned = false;
770 ty::ty_tup(ref tys) if tys.is_empty() => return,
771 ty::ty_bool => return,
772 ty::ty_struct(did, _) |
773 ty::ty_enum(did, _) => {
774 if ast_util::is_local(did) {
775 if let ast_map::NodeItem(it) = cx.tcx.map.get(did.node) {
776 warned |= check_must_use(cx, it.attrs[], s.span);
779 csearch::get_item_attrs(&cx.sess().cstore, did, |attrs| {
780 warned |= check_must_use(cx, attrs[], s.span);
787 cx.span_lint(UNUSED_RESULTS, s.span, "unused result");
790 fn check_must_use(cx: &Context, attrs: &[ast::Attribute], sp: Span) -> bool {
791 for attr in attrs.iter() {
792 if attr.check_name("must_use") {
793 let mut msg = "unused result which must be used".to_string();
794 // check for #[must_use="..."]
795 match attr.value_str() {
799 msg.push_str(s.get());
802 cx.span_lint(UNUSED_MUST_USE, sp, msg[]);
812 pub NON_CAMEL_CASE_TYPES,
814 "types, variants, traits and type parameters should have camel case names"
818 pub struct NonCamelCaseTypes;
820 impl NonCamelCaseTypes {
821 fn check_case(&self, cx: &Context, sort: &str, ident: ast::Ident, span: Span) {
822 fn is_camel_case(ident: ast::Ident) -> bool {
823 let ident = token::get_ident(ident);
824 if ident.get().is_empty() { return true; }
825 let ident = ident.get().trim_matches('_');
827 // start with a non-lowercase letter rather than non-uppercase
828 // ones (some scripts don't have a concept of upper/lowercase)
829 ident.len() > 0 && !ident.char_at(0).is_lowercase() && !ident.contains_char('_')
832 fn to_camel_case(s: &str) -> String {
833 s.split('_').flat_map(|word| word.chars().enumerate().map(|(i, c)|
834 if i == 0 { c.to_uppercase() }
839 let s = token::get_ident(ident);
841 if !is_camel_case(ident) {
842 let c = to_camel_case(s.get());
843 let m = if c.is_empty() {
844 format!("{} `{}` should have a camel case name such as `CamelCase`", sort, s)
846 format!("{} `{}` should have a camel case name such as `{}`", sort, s, c)
848 cx.span_lint(NON_CAMEL_CASE_TYPES, span, m[]);
853 impl LintPass for NonCamelCaseTypes {
854 fn get_lints(&self) -> LintArray {
855 lint_array!(NON_CAMEL_CASE_TYPES)
858 fn check_item(&mut self, cx: &Context, it: &ast::Item) {
859 let has_extern_repr = it.attrs.iter().map(|attr| {
860 attr::find_repr_attrs(cx.tcx.sess.diagnostic(), attr).iter()
861 .any(|r| r == &attr::ReprExtern)
863 if has_extern_repr { return }
866 ast::ItemTy(..) | ast::ItemStruct(..) => {
867 self.check_case(cx, "type", it.ident, it.span)
869 ast::ItemTrait(..) => {
870 self.check_case(cx, "trait", it.ident, it.span)
872 ast::ItemEnum(ref enum_definition, _) => {
873 if has_extern_repr { return }
874 self.check_case(cx, "type", it.ident, it.span);
875 for variant in enum_definition.variants.iter() {
876 self.check_case(cx, "variant", variant.node.name, variant.span);
883 fn check_generics(&mut self, cx: &Context, it: &ast::Generics) {
884 for gen in it.ty_params.iter() {
885 self.check_case(cx, "type parameter", gen.ident, gen.span);
897 fn method_context(cx: &Context, m: &ast::Method) -> MethodContext {
898 let did = ast::DefId {
899 krate: ast::LOCAL_CRATE,
903 match cx.tcx.impl_or_trait_items.borrow().get(&did).cloned() {
904 None => cx.sess().span_bug(m.span, "missing method descriptor?!"),
907 ty::MethodTraitItem(md) => {
909 ty::TraitContainer(..) => TraitDefaultImpl,
910 ty::ImplContainer(cid) => {
911 match ty::impl_trait_ref(cx.tcx, cid) {
912 Some(..) => TraitImpl,
918 ty::TypeTraitItem(typedef) => {
919 match typedef.container {
920 ty::TraitContainer(..) => TraitDefaultImpl,
921 ty::ImplContainer(cid) => {
922 match ty::impl_trait_ref(cx.tcx, cid) {
923 Some(..) => TraitImpl,
937 "methods, functions, lifetime parameters and modules should have snake case names"
941 pub struct NonSnakeCase;
944 fn check_snake_case(&self, cx: &Context, sort: &str, ident: ast::Ident, span: Span) {
945 fn is_snake_case(ident: ast::Ident) -> bool {
946 let ident = token::get_ident(ident);
947 if ident.get().is_empty() { return true; }
948 let ident = ident.get().trim_left_matches('\'');
949 let ident = ident.trim_matches('_');
951 let mut allow_underscore = true;
952 ident.chars().all(|c| {
953 allow_underscore = match c {
954 c if c.is_lowercase() || c.is_numeric() => true,
955 '_' if allow_underscore => false,
962 fn to_snake_case(str: &str) -> String {
963 let mut words = vec![];
964 for s in str.split('_') {
965 let mut last_upper = false;
966 let mut buf = String::new();
967 if s.is_empty() { continue; }
968 for ch in s.chars() {
969 if !buf.is_empty() && buf != "'"
975 last_upper = ch.is_uppercase();
976 buf.push(ch.to_lowercase());
983 let s = token::get_ident(ident);
985 if !is_snake_case(ident) {
986 cx.span_lint(NON_SNAKE_CASE, span,
987 format!("{} `{}` should have a snake case name such as `{}`",
988 sort, s, to_snake_case(s.get()))[]);
993 impl LintPass for NonSnakeCase {
994 fn get_lints(&self) -> LintArray {
995 lint_array!(NON_SNAKE_CASE)
998 fn check_fn(&mut self, cx: &Context,
999 fk: visit::FnKind, _: &ast::FnDecl,
1000 _: &ast::Block, span: Span, _: ast::NodeId) {
1002 visit::FkMethod(ident, _, m) => match method_context(cx, m) {
1004 => self.check_snake_case(cx, "method", ident, span),
1006 => self.check_snake_case(cx, "trait method", ident, span),
1009 visit::FkItemFn(ident, _, _, _)
1010 => self.check_snake_case(cx, "function", ident, span),
1015 fn check_item(&mut self, cx: &Context, it: &ast::Item) {
1016 if let ast::ItemMod(_) = it.node {
1017 self.check_snake_case(cx, "module", it.ident, it.span);
1021 fn check_ty_method(&mut self, cx: &Context, t: &ast::TypeMethod) {
1022 self.check_snake_case(cx, "trait method", t.ident, t.span);
1025 fn check_lifetime_def(&mut self, cx: &Context, t: &ast::LifetimeDef) {
1026 self.check_snake_case(cx, "lifetime", t.lifetime.name.ident(), t.lifetime.span);
1029 fn check_pat(&mut self, cx: &Context, p: &ast::Pat) {
1030 if let &ast::PatIdent(_, ref path1, _) = &p.node {
1031 if let Some(&def::DefLocal(_)) = cx.tcx.def_map.borrow().get(&p.id) {
1032 self.check_snake_case(cx, "variable", path1.node, p.span);
1037 fn check_struct_def(&mut self, cx: &Context, s: &ast::StructDef,
1038 _: ast::Ident, _: &ast::Generics, _: ast::NodeId) {
1039 for sf in s.fields.iter() {
1040 if let ast::StructField_ { kind: ast::NamedField(ident, _), .. } = sf.node {
1041 self.check_snake_case(cx, "structure field", ident, sf.span);
1048 pub NON_UPPER_CASE_GLOBALS,
1050 "static constants should have uppercase identifiers"
1054 pub struct NonUpperCaseGlobals;
1056 impl LintPass for NonUpperCaseGlobals {
1057 fn get_lints(&self) -> LintArray {
1058 lint_array!(NON_UPPER_CASE_GLOBALS)
1061 fn check_item(&mut self, cx: &Context, it: &ast::Item) {
1063 // only check static constants
1064 ast::ItemStatic(_, ast::MutImmutable, _) |
1065 ast::ItemConst(..) => {
1066 let s = token::get_ident(it.ident);
1067 // check for lowercase letters rather than non-uppercase
1068 // ones (some scripts don't have a concept of
1070 if s.get().chars().any(|c| c.is_lowercase()) {
1071 cx.span_lint(NON_UPPER_CASE_GLOBALS, it.span,
1072 format!("static constant `{}` should have an uppercase name \
1074 s.get(), s.get().chars().map(|c| c.to_uppercase())
1075 .collect::<String>()[])[]);
1082 fn check_pat(&mut self, cx: &Context, p: &ast::Pat) {
1083 // Lint for constants that look like binding identifiers (#7526)
1084 match (&p.node, cx.tcx.def_map.borrow().get(&p.id)) {
1085 (&ast::PatIdent(_, ref path1, _), Some(&def::DefConst(..))) => {
1086 let s = token::get_ident(path1.node);
1087 if s.get().chars().any(|c| c.is_lowercase()) {
1088 cx.span_lint(NON_UPPER_CASE_GLOBALS, path1.span,
1089 format!("static constant in pattern `{}` should have an uppercase \
1091 s.get(), s.get().chars().map(|c| c.to_uppercase())
1092 .collect::<String>()[])[]);
1103 "`if`, `match`, `while` and `return` do not need parentheses"
1107 pub struct UnusedParens;
1110 fn check_unused_parens_core(&self, cx: &Context, value: &ast::Expr, msg: &str,
1111 struct_lit_needs_parens: bool) {
1112 if let ast::ExprParen(ref inner) = value.node {
1113 let necessary = struct_lit_needs_parens && contains_exterior_struct_lit(&**inner);
1115 cx.span_lint(UNUSED_PARENS, value.span,
1116 format!("unnecessary parentheses around {}",
1121 /// Expressions that syntactically contain an "exterior" struct
1122 /// literal i.e. not surrounded by any parens or other
1123 /// delimiters, e.g. `X { y: 1 }`, `X { y: 1 }.method()`, `foo
1124 /// == X { y: 1 }` and `X { y: 1 } == foo` all do, but `(X {
1125 /// y: 1 }) == foo` does not.
1126 fn contains_exterior_struct_lit(value: &ast::Expr) -> bool {
1128 ast::ExprStruct(..) => true,
1130 ast::ExprAssign(ref lhs, ref rhs) |
1131 ast::ExprAssignOp(_, ref lhs, ref rhs) |
1132 ast::ExprBinary(_, ref lhs, ref rhs) => {
1133 // X { y: 1 } + X { y: 2 }
1134 contains_exterior_struct_lit(&**lhs) ||
1135 contains_exterior_struct_lit(&**rhs)
1137 ast::ExprUnary(_, ref x) |
1138 ast::ExprCast(ref x, _) |
1139 ast::ExprField(ref x, _) |
1140 ast::ExprTupField(ref x, _) |
1141 ast::ExprIndex(ref x, _) => {
1142 // &X { y: 1 }, X { y: 1 }.y
1143 contains_exterior_struct_lit(&**x)
1146 ast::ExprMethodCall(_, _, ref exprs) => {
1147 // X { y: 1 }.bar(...)
1148 contains_exterior_struct_lit(&*exprs[0])
1157 impl LintPass for UnusedParens {
1158 fn get_lints(&self) -> LintArray {
1159 lint_array!(UNUSED_PARENS)
1162 fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
1163 let (value, msg, struct_lit_needs_parens) = match e.node {
1164 ast::ExprIf(ref cond, _, _) => (cond, "`if` condition", true),
1165 ast::ExprWhile(ref cond, _, _) => (cond, "`while` condition", true),
1166 ast::ExprMatch(ref head, _, source) => match source {
1167 ast::MatchSource::Normal => (head, "`match` head expression", true),
1168 ast::MatchSource::IfLetDesugar { .. } => (head, "`if let` head expression", true),
1169 ast::MatchSource::WhileLetDesugar => (head, "`while let` head expression", true),
1171 ast::ExprRet(Some(ref value)) => (value, "`return` value", false),
1172 ast::ExprAssign(_, ref value) => (value, "assigned value", false),
1173 ast::ExprAssignOp(_, _, ref value) => (value, "assigned value", false),
1176 self.check_unused_parens_core(cx, &**value, msg, struct_lit_needs_parens);
1179 fn check_stmt(&mut self, cx: &Context, s: &ast::Stmt) {
1180 let (value, msg) = match s.node {
1181 ast::StmtDecl(ref decl, _) => match decl.node {
1182 ast::DeclLocal(ref local) => match local.init {
1183 Some(ref value) => (value, "assigned value"),
1190 self.check_unused_parens_core(cx, &**value, msg, false);
1195 UNUSED_IMPORT_BRACES,
1197 "unnecessary braces around an imported item"
1201 pub struct UnusedImportBraces;
1203 impl LintPass for UnusedImportBraces {
1204 fn get_lints(&self) -> LintArray {
1205 lint_array!(UNUSED_IMPORT_BRACES)
1208 fn check_view_item(&mut self, cx: &Context, view_item: &ast::ViewItem) {
1209 match view_item.node {
1210 ast::ViewItemUse(ref view_path) => {
1211 match view_path.node {
1212 ast::ViewPathList(_, ref items, _) => {
1213 if items.len() == 1 {
1214 match items[0].node {
1215 ast::PathListIdent {ref name, ..} => {
1216 let m = format!("braces around {} is unnecessary",
1217 token::get_ident(*name).get());
1218 cx.span_lint(UNUSED_IMPORT_BRACES, view_item.span,
1234 NON_SHORTHAND_FIELD_PATTERNS,
1236 "using `Struct { x: x }` instead of `Struct { x }`"
1240 pub struct NonShorthandFieldPatterns;
1242 impl LintPass for NonShorthandFieldPatterns {
1243 fn get_lints(&self) -> LintArray {
1244 lint_array!(NON_SHORTHAND_FIELD_PATTERNS)
1247 fn check_pat(&mut self, cx: &Context, pat: &ast::Pat) {
1248 let def_map = cx.tcx.def_map.borrow();
1249 if let ast::PatStruct(_, ref v, _) = pat.node {
1250 for fieldpat in v.iter()
1251 .filter(|fieldpat| !fieldpat.node.is_shorthand)
1252 .filter(|fieldpat| def_map.get(&fieldpat.node.pat.id)
1253 == Some(&def::DefLocal(fieldpat.node.pat.id))) {
1254 if let ast::PatIdent(_, ident, None) = fieldpat.node.pat.node {
1255 if ident.node.as_str() == fieldpat.node.ident.as_str() {
1256 cx.span_lint(NON_SHORTHAND_FIELD_PATTERNS, fieldpat.span,
1257 format!("the `{}:` in this pattern is redundant and can \
1258 be removed", ident.node.as_str())[])
1269 "unnecessary use of an `unsafe` block"
1273 pub struct UnusedUnsafe;
1275 impl LintPass for UnusedUnsafe {
1276 fn get_lints(&self) -> LintArray {
1277 lint_array!(UNUSED_UNSAFE)
1280 fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
1281 if let ast::ExprBlock(ref blk) = e.node {
1282 // Don't warn about generated blocks, that'll just pollute the output.
1283 if blk.rules == ast::UnsafeBlock(ast::UserProvided) &&
1284 !cx.tcx.used_unsafe.borrow().contains(&blk.id) {
1285 cx.span_lint(UNUSED_UNSAFE, blk.span, "unnecessary `unsafe` block");
1294 "usage of an `unsafe` block"
1298 pub struct UnsafeBlocks;
1300 impl LintPass for UnsafeBlocks {
1301 fn get_lints(&self) -> LintArray {
1302 lint_array!(UNSAFE_BLOCKS)
1305 fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
1306 if let ast::ExprBlock(ref blk) = e.node {
1307 // Don't warn about generated blocks, that'll just pollute the output.
1308 if blk.rules == ast::UnsafeBlock(ast::UserProvided) {
1309 cx.span_lint(UNSAFE_BLOCKS, blk.span, "usage of an `unsafe` block");
1318 "detect mut variables which don't need to be mutable"
1322 pub struct UnusedMut;
1325 fn check_unused_mut_pat(&self, cx: &Context, pats: &[P<ast::Pat>]) {
1326 // collect all mutable pattern and group their NodeIDs by their Identifier to
1327 // avoid false warnings in match arms with multiple patterns
1329 let mut mutables = FnvHashMap::new();
1330 for p in pats.iter() {
1331 pat_util::pat_bindings(&cx.tcx.def_map, &**p, |mode, id, _, path1| {
1332 let ident = path1.node;
1333 if let ast::BindByValue(ast::MutMutable) = mode {
1334 if !token::get_ident(ident).get().starts_with("_") {
1335 match mutables.entry(ident.name.uint()) {
1336 Vacant(entry) => { entry.set(vec![id]); },
1337 Occupied(mut entry) => { entry.get_mut().push(id); },
1344 let used_mutables = cx.tcx.used_mut_nodes.borrow();
1345 for (_, v) in mutables.iter() {
1346 if !v.iter().any(|e| used_mutables.contains(e)) {
1347 cx.span_lint(UNUSED_MUT, cx.tcx.map.span(v[0]),
1348 "variable does not need to be mutable");
1354 impl LintPass for UnusedMut {
1355 fn get_lints(&self) -> LintArray {
1356 lint_array!(UNUSED_MUT)
1359 fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
1360 if let ast::ExprMatch(_, ref arms, _) = e.node {
1361 for a in arms.iter() {
1362 self.check_unused_mut_pat(cx, a.pats[])
1367 fn check_stmt(&mut self, cx: &Context, s: &ast::Stmt) {
1368 if let ast::StmtDecl(ref d, _) = s.node {
1369 if let ast::DeclLocal(ref l) = d.node {
1370 self.check_unused_mut_pat(cx, slice::ref_slice(&l.pat));
1375 fn check_fn(&mut self, cx: &Context,
1376 _: visit::FnKind, decl: &ast::FnDecl,
1377 _: &ast::Block, _: Span, _: ast::NodeId) {
1378 for a in decl.inputs.iter() {
1379 self.check_unused_mut_pat(cx, slice::ref_slice(&a.pat));
1387 "detects unnecessary allocations that can be eliminated"
1391 pub struct UnusedAllocation;
1393 impl LintPass for UnusedAllocation {
1394 fn get_lints(&self) -> LintArray {
1395 lint_array!(UNUSED_ALLOCATION)
1398 fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
1400 ast::ExprUnary(ast::UnUniq, _) => (),
1404 if let Some(adjustment) = cx.tcx.adjustments.borrow().get(&e.id) {
1405 if let ty::AdjustDerefRef(ty::AutoDerefRef { ref autoref, .. }) = *adjustment {
1407 &Some(ty::AutoPtr(_, ast::MutImmutable, None)) => {
1408 cx.span_lint(UNUSED_ALLOCATION, e.span,
1409 "unnecessary allocation, use & instead");
1411 &Some(ty::AutoPtr(_, ast::MutMutable, None)) => {
1412 cx.span_lint(UNUSED_ALLOCATION, e.span,
1413 "unnecessary allocation, use &mut instead");
1425 "detects missing documentation for public members"
1428 pub struct MissingDoc {
1429 /// Stack of IDs of struct definitions.
1430 struct_def_stack: Vec<ast::NodeId>,
1432 /// True if inside variant definition
1435 /// Stack of whether #[doc(hidden)] is set
1436 /// at each level which has lint attributes.
1437 doc_hidden_stack: Vec<bool>,
1441 pub fn new() -> MissingDoc {
1443 struct_def_stack: vec!(),
1445 doc_hidden_stack: vec!(false),
1449 fn doc_hidden(&self) -> bool {
1450 *self.doc_hidden_stack.last().expect("empty doc_hidden_stack")
1453 fn check_missing_docs_attrs(&self,
1455 id: Option<ast::NodeId>,
1456 attrs: &[ast::Attribute],
1458 desc: &'static str) {
1459 // If we're building a test harness, then warning about
1460 // documentation is probably not really relevant right now.
1461 if cx.sess().opts.test { return }
1463 // `#[doc(hidden)]` disables missing_docs check.
1464 if self.doc_hidden() { return }
1466 // Only check publicly-visible items, using the result from the privacy pass.
1467 // It's an option so the crate root can also use this function (it doesn't
1469 if let Some(ref id) = id {
1470 if !cx.exported_items.contains(id) {
1475 let has_doc = attrs.iter().any(|a| {
1476 match a.node.value.node {
1477 ast::MetaNameValue(ref name, _) if *name == "doc" => true,
1482 cx.span_lint(MISSING_DOCS, sp,
1483 format!("missing documentation for {}", desc)[]);
1488 impl LintPass for MissingDoc {
1489 fn get_lints(&self) -> LintArray {
1490 lint_array!(MISSING_DOCS)
1493 fn enter_lint_attrs(&mut self, _: &Context, attrs: &[ast::Attribute]) {
1494 let doc_hidden = self.doc_hidden() || attrs.iter().any(|attr| {
1495 attr.check_name("doc") && match attr.meta_item_list() {
1497 Some(l) => attr::contains_name(l[], "hidden"),
1500 self.doc_hidden_stack.push(doc_hidden);
1503 fn exit_lint_attrs(&mut self, _: &Context, _: &[ast::Attribute]) {
1504 self.doc_hidden_stack.pop().expect("empty doc_hidden_stack");
1507 fn check_struct_def(&mut self, _: &Context,
1508 _: &ast::StructDef, _: ast::Ident, _: &ast::Generics, id: ast::NodeId) {
1509 self.struct_def_stack.push(id);
1512 fn check_struct_def_post(&mut self, _: &Context,
1513 _: &ast::StructDef, _: ast::Ident, _: &ast::Generics, id: ast::NodeId) {
1514 let popped = self.struct_def_stack.pop().expect("empty struct_def_stack");
1515 assert!(popped == id);
1518 fn check_crate(&mut self, cx: &Context, krate: &ast::Crate) {
1519 self.check_missing_docs_attrs(cx, None, krate.attrs[],
1520 krate.span, "crate");
1523 fn check_item(&mut self, cx: &Context, it: &ast::Item) {
1524 let desc = match it.node {
1525 ast::ItemFn(..) => "a function",
1526 ast::ItemMod(..) => "a module",
1527 ast::ItemEnum(..) => "an enum",
1528 ast::ItemStruct(..) => "a struct",
1529 ast::ItemTrait(..) => "a trait",
1530 ast::ItemTy(..) => "a type alias",
1533 self.check_missing_docs_attrs(cx, Some(it.id), it.attrs[],
1537 fn check_fn(&mut self, cx: &Context,
1538 fk: visit::FnKind, _: &ast::FnDecl,
1539 _: &ast::Block, _: Span, _: ast::NodeId) {
1540 if let visit::FkMethod(_, _, m) = fk {
1541 // If the method is an impl for a trait, don't doc.
1542 if method_context(cx, m) == TraitImpl { return; }
1544 // Otherwise, doc according to privacy. This will also check
1545 // doc for default methods defined on traits.
1546 self.check_missing_docs_attrs(cx, Some(m.id), m.attrs[],
1547 m.span, "a method");
1551 fn check_ty_method(&mut self, cx: &Context, tm: &ast::TypeMethod) {
1552 self.check_missing_docs_attrs(cx, Some(tm.id), tm.attrs[],
1553 tm.span, "a type method");
1556 fn check_struct_field(&mut self, cx: &Context, sf: &ast::StructField) {
1557 if let ast::NamedField(_, vis) = sf.node.kind {
1558 if vis == ast::Public || self.in_variant {
1559 let cur_struct_def = *self.struct_def_stack.last()
1560 .expect("empty struct_def_stack");
1561 self.check_missing_docs_attrs(cx, Some(cur_struct_def),
1562 sf.node.attrs[], sf.span,
1568 fn check_variant(&mut self, cx: &Context, v: &ast::Variant, _: &ast::Generics) {
1569 self.check_missing_docs_attrs(cx, Some(v.node.id), v.node.attrs[],
1570 v.span, "a variant");
1571 assert!(!self.in_variant);
1572 self.in_variant = true;
1575 fn check_variant_post(&mut self, _: &Context, _: &ast::Variant, _: &ast::Generics) {
1576 assert!(self.in_variant);
1577 self.in_variant = false;
1582 pub struct MissingCopyImplementations;
1584 impl LintPass for MissingCopyImplementations {
1585 fn get_lints(&self) -> LintArray {
1586 lint_array!(MISSING_COPY_IMPLEMENTATIONS)
1589 fn check_item(&mut self, cx: &Context, item: &ast::Item) {
1590 if !cx.exported_items.contains(&item.id) {
1594 .destructor_for_type
1596 .contains_key(&ast_util::local_def(item.id)) {
1599 let ty = match item.node {
1600 ast::ItemStruct(_, ref ast_generics) => {
1601 if ast_generics.is_parameterized() {
1604 ty::mk_struct(cx.tcx,
1605 ast_util::local_def(item.id),
1606 cx.tcx.mk_substs(Substs::empty()))
1608 ast::ItemEnum(_, ref ast_generics) => {
1609 if ast_generics.is_parameterized() {
1613 ast_util::local_def(item.id),
1614 cx.tcx.mk_substs(Substs::empty()))
1618 let parameter_environment = ty::empty_parameter_environment(cx.tcx);
1619 if !ty::type_moves_by_default(¶meter_environment, item.span, ty) {
1622 if ty::can_type_implement_copy(¶meter_environment, item.span, ty).is_ok() {
1623 cx.span_lint(MISSING_COPY_IMPLEMENTATIONS,
1625 "type could implement `Copy`; consider adding `impl \
1634 "detects use of #[deprecated] items"
1637 // FIXME #6875: Change to Warn after std library stabilization is complete
1641 "detects use of #[experimental] items"
1647 "detects use of #[unstable] items (incl. items with no stability attribute)"
1650 /// Checks for use of items with `#[deprecated]`, `#[experimental]` and
1651 /// `#[unstable]` attributes, or no stability attribute.
1653 pub struct Stability;
1656 fn lint(&self, cx: &Context, id: ast::DefId, span: Span) {
1657 let stability = stability::lookup(cx.tcx, id);
1658 let cross_crate = !ast_util::is_local(id);
1660 // stability attributes are promises made across crates; only
1661 // check DEPRECATED for crate-local usage.
1662 let (lint, label) = match stability {
1663 // no stability attributes == Unstable
1664 None if cross_crate => (UNSTABLE, "unmarked"),
1665 Some(attr::Stability { level: attr::Unstable, .. }) if cross_crate =>
1666 (UNSTABLE, "unstable"),
1667 Some(attr::Stability { level: attr::Experimental, .. }) if cross_crate =>
1668 (EXPERIMENTAL, "experimental"),
1669 Some(attr::Stability { level: attr::Deprecated, .. }) =>
1670 (DEPRECATED, "deprecated"),
1674 let msg = match stability {
1675 Some(attr::Stability { text: Some(ref s), .. }) => {
1676 format!("use of {} item: {}", label, *s)
1678 _ => format!("use of {} item", label)
1681 cx.span_lint(lint, span, msg[]);
1684 fn is_internal(&self, cx: &Context, span: Span) -> bool {
1685 cx.tcx.sess.codemap().span_is_internal(span)
1689 impl LintPass for Stability {
1690 fn get_lints(&self) -> LintArray {
1691 lint_array!(DEPRECATED, EXPERIMENTAL, UNSTABLE)
1694 fn check_view_item(&mut self, cx: &Context, item: &ast::ViewItem) {
1695 // compiler-generated `extern crate` statements have a dummy span.
1696 if item.span == DUMMY_SP { return }
1698 let id = match item.node {
1699 ast::ViewItemExternCrate(_, _, id) => id,
1700 ast::ViewItemUse(..) => return,
1702 let cnum = match cx.tcx.sess.cstore.find_extern_mod_stmt_cnum(id) {
1706 let id = ast::DefId { krate: cnum, node: ast::CRATE_NODE_ID };
1707 self.lint(cx, id, item.span);
1710 fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
1711 if self.is_internal(cx, e.span) { return; }
1713 let mut span = e.span;
1715 let id = match e.node {
1716 ast::ExprPath(..) | ast::ExprStruct(..) => {
1717 match cx.tcx.def_map.borrow().get(&e.id) {
1718 Some(&def) => def.def_id(),
1722 ast::ExprMethodCall(i, _, _) => {
1724 let method_call = ty::MethodCall::expr(e.id);
1725 match cx.tcx.method_map.borrow().get(&method_call) {
1727 match method.origin {
1728 ty::MethodStatic(def_id) => {
1731 ty::MethodStaticUnboxedClosure(def_id) => {
1734 ty::MethodTypeParam(ty::MethodParam {
1739 ty::MethodTraitObject(ty::MethodObject {
1744 ty::trait_item(cx.tcx, trait_ref.def_id, index).def_id()
1753 self.lint(cx, id, span);
1756 fn check_item(&mut self, cx: &Context, item: &ast::Item) {
1757 if self.is_internal(cx, item.span) { return }
1760 ast::ItemTrait(_, _, ref supertraits, _) => {
1761 for t in supertraits.iter() {
1762 if let ast::TraitTyParamBound(ref t, _) = *t {
1763 let id = ty::trait_ref_to_def_id(cx.tcx, &t.trait_ref);
1764 self.lint(cx, id, t.trait_ref.path.span);
1768 ast::ItemImpl(_, _, Some(ref t), _, _) => {
1769 let id = ty::trait_ref_to_def_id(cx.tcx, t);
1770 self.lint(cx, id, t.path.span);
1780 "imports that are never used"
1784 pub UNUSED_EXTERN_CRATES,
1786 "extern crates that are never used"
1790 pub UNUSED_QUALIFICATIONS,
1792 "detects unnecessarily qualified names"
1798 "unrecognized lint attribute"
1802 pub UNUSED_VARIABLES,
1804 "detect variables which are not used in any way"
1808 pub UNUSED_ASSIGNMENTS,
1810 "detect assignments that will never be read"
1816 "detect unused, unexported items"
1820 pub UNREACHABLE_CODE,
1822 "detects unreachable code paths"
1828 "mass-change the level for lints which produce warnings"
1832 pub UNKNOWN_FEATURES,
1834 "unknown features found in crate-level #[feature] directives"
1838 pub UNKNOWN_CRATE_TYPES,
1840 "unknown crate type found in #[crate_type] directive"
1844 pub VARIANT_SIZE_DIFFERENCES,
1846 "detects enums with widely varying variant sizes"
1850 pub FAT_PTR_TRANSMUTES,
1852 "detects transmutes of fat pointers"
1856 pub MISSING_COPY_IMPLEMENTATIONS,
1858 "detects potentially-forgotten implementations of `Copy`"
1861 /// Does nothing as a lint pass, but registers some `Lint`s
1862 /// which are used by other parts of the compiler.
1864 pub struct HardwiredLints;
1866 impl LintPass for HardwiredLints {
1867 fn get_lints(&self) -> LintArray {
1870 UNUSED_EXTERN_CRATES,
1871 UNUSED_QUALIFICATIONS,
1879 UNKNOWN_CRATE_TYPES,
1880 VARIANT_SIZE_DIFFERENCES,