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, Lint};
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::{TyIs, TyUs, 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 let ast::TyIs(_) = t {
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 let ast::TyUs(_) = t {
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::TyIs(_) => (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::TyUs(_) => (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::TyIs(_) => 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::TyUs(_) => 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::TyIs(_))) => {
408 self.cx.span_lint(IMPROPER_CTYPES, sp,
409 "found rust type `isize` in foreign module, while \
410 libc::c_int or libc::c_long should be used");
412 def::DefPrimTy(ast::TyUint(ast::TyUs(_))) => {
413 self.cx.span_lint(IMPROPER_CTYPES, sp,
414 "found rust type `usize` 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| {
507 let s = ty_to_string(cx.tcx, ty);
508 let m = format!("type uses owned (Box type) pointers: {}", s);
509 cx.span_lint(BOX_POINTERS, span, &m[]);
514 impl LintPass for BoxPointers {
515 fn get_lints(&self) -> LintArray {
516 lint_array!(BOX_POINTERS)
519 fn check_item(&mut self, cx: &Context, it: &ast::Item) {
524 ast::ItemStruct(..) =>
525 self.check_heap_type(cx, it.span,
526 ty::node_id_to_type(cx.tcx, it.id)),
530 // If it's a struct, we also have to check the fields' types
532 ast::ItemStruct(ref struct_def, _) => {
533 for struct_field in struct_def.fields.iter() {
534 self.check_heap_type(cx, struct_field.span,
535 ty::node_id_to_type(cx.tcx, struct_field.node.id));
542 fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
543 let ty = ty::expr_ty(cx.tcx, e);
544 self.check_heap_type(cx, e.span, ty);
551 "uses of #[derive] with raw pointers are rarely correct"
554 struct RawPtrDeriveVisitor<'a, 'tcx: 'a> {
555 cx: &'a Context<'a, 'tcx>
558 impl<'a, 'tcx, 'v> Visitor<'v> for RawPtrDeriveVisitor<'a, 'tcx> {
559 fn visit_ty(&mut self, ty: &ast::Ty) {
560 static MSG: &'static str = "use of `#[derive]` with a raw pointer";
561 if let ast::TyPtr(..) = ty.node {
562 self.cx.span_lint(RAW_POINTER_DERIVE, ty.span, MSG);
564 visit::walk_ty(self, ty);
566 // explicit override to a no-op to reduce code bloat
567 fn visit_expr(&mut self, _: &ast::Expr) {}
568 fn visit_block(&mut self, _: &ast::Block) {}
571 pub struct RawPointerDerive {
572 checked_raw_pointers: NodeSet,
575 impl RawPointerDerive {
576 pub fn new() -> RawPointerDerive {
578 checked_raw_pointers: NodeSet(),
583 impl LintPass for RawPointerDerive {
584 fn get_lints(&self) -> LintArray {
585 lint_array!(RAW_POINTER_DERIVE)
588 fn check_item(&mut self, cx: &Context, item: &ast::Item) {
589 if !attr::contains_name(&item.attrs[], "automatically_derived") {
592 let did = match item.node {
593 ast::ItemImpl(..) => {
594 match ty::node_id_to_type(cx.tcx, item.id).sty {
595 ty::ty_enum(did, _) => did,
596 ty::ty_struct(did, _) => did,
602 if !ast_util::is_local(did) { return }
603 let item = match cx.tcx.map.find(did.node) {
604 Some(ast_map::NodeItem(item)) => item,
607 if !self.checked_raw_pointers.insert(item.id) { return }
609 ast::ItemStruct(..) | ast::ItemEnum(..) => {
610 let mut visitor = RawPtrDeriveVisitor { cx: cx };
611 visit::walk_item(&mut visitor, &*item);
621 "detects attributes that were not used by the compiler"
625 pub struct UnusedAttributes;
627 impl LintPass for UnusedAttributes {
628 fn get_lints(&self) -> LintArray {
629 lint_array!(UNUSED_ATTRIBUTES)
632 fn check_attribute(&mut self, cx: &Context, attr: &ast::Attribute) {
633 static ATTRIBUTE_WHITELIST: &'static [&'static str] = &[
634 // FIXME: #14408 whitelist docs since rustdoc looks at them
637 // FIXME: #14406 these are processed in trans, which happens after the
654 "omit_gdb_pretty_printer_section",
655 "unsafe_no_drop_flag",
660 // FIXME: #14407 these are only looked at on-demand so we can't
661 // guarantee they'll have already been checked
669 "rustc_on_unimplemented",
671 // FIXME: #19470 this shouldn't be needed forever
676 static CRATE_ATTRS: &'static [&'static str] = &[
686 for &name in ATTRIBUTE_WHITELIST.iter() {
687 if attr.check_name(name) {
692 if !attr::is_used(attr) {
693 cx.span_lint(UNUSED_ATTRIBUTES, attr.span, "unused attribute");
694 if CRATE_ATTRS.contains(&attr.name().get()) {
695 let msg = match attr.node.style {
696 ast::AttrOuter => "crate-level attribute should be an inner \
697 attribute: add an exclamation mark: #![foo]",
698 ast::AttrInner => "crate-level attribute should be in the \
701 cx.span_lint(UNUSED_ATTRIBUTES, attr.span, msg);
710 "path statements with no effect"
714 pub struct PathStatements;
716 impl LintPass for PathStatements {
717 fn get_lints(&self) -> LintArray {
718 lint_array!(PATH_STATEMENTS)
721 fn check_stmt(&mut self, cx: &Context, s: &ast::Stmt) {
723 ast::StmtSemi(ref expr, _) => {
725 ast::ExprPath(_) => cx.span_lint(PATH_STATEMENTS, s.span,
726 "path statement with no effect"),
738 "unused result of a type flagged as #[must_use]"
744 "unused result of an expression in a statement"
748 pub struct UnusedResults;
750 impl LintPass for UnusedResults {
751 fn get_lints(&self) -> LintArray {
752 lint_array!(UNUSED_MUST_USE, UNUSED_RESULTS)
755 fn check_stmt(&mut self, cx: &Context, s: &ast::Stmt) {
756 let expr = match s.node {
757 ast::StmtSemi(ref expr, _) => &**expr,
761 if let ast::ExprRet(..) = expr.node {
765 let t = ty::expr_ty(cx.tcx, expr);
766 let mut warned = false;
768 ty::ty_tup(ref tys) if tys.is_empty() => return,
769 ty::ty_bool => return,
770 ty::ty_struct(did, _) |
771 ty::ty_enum(did, _) => {
772 if ast_util::is_local(did) {
773 if let ast_map::NodeItem(it) = cx.tcx.map.get(did.node) {
774 warned |= check_must_use(cx, &it.attrs[], s.span);
777 let attrs = csearch::get_item_attrs(&cx.sess().cstore, did);
778 warned |= check_must_use(cx, &attrs[], s.span);
784 cx.span_lint(UNUSED_RESULTS, s.span, "unused result");
787 fn check_must_use(cx: &Context, attrs: &[ast::Attribute], sp: Span) -> bool {
788 for attr in attrs.iter() {
789 if attr.check_name("must_use") {
790 let mut msg = "unused result which must be used".to_string();
791 // check for #[must_use="..."]
792 match attr.value_str() {
796 msg.push_str(s.get());
799 cx.span_lint(UNUSED_MUST_USE, sp, &msg[]);
809 pub NON_CAMEL_CASE_TYPES,
811 "types, variants, traits and type parameters should have camel case names"
815 pub struct NonCamelCaseTypes;
817 impl NonCamelCaseTypes {
818 fn check_case(&self, cx: &Context, sort: &str, ident: ast::Ident, span: Span) {
819 fn is_camel_case(ident: ast::Ident) -> bool {
820 let ident = token::get_ident(ident);
821 if ident.get().is_empty() { return true; }
822 let ident = ident.get().trim_matches('_');
824 // start with a non-lowercase letter rather than non-uppercase
825 // ones (some scripts don't have a concept of upper/lowercase)
826 ident.len() > 0 && !ident.char_at(0).is_lowercase() && !ident.contains_char('_')
829 fn to_camel_case(s: &str) -> String {
830 s.split('_').flat_map(|word| word.chars().enumerate().map(|(i, c)|
831 if i == 0 { c.to_uppercase() }
836 let s = token::get_ident(ident);
838 if !is_camel_case(ident) {
839 let c = to_camel_case(s.get());
840 let m = if c.is_empty() {
841 format!("{} `{}` should have a camel case name such as `CamelCase`", sort, s)
843 format!("{} `{}` should have a camel case name such as `{}`", sort, s, c)
845 cx.span_lint(NON_CAMEL_CASE_TYPES, span, &m[]);
850 impl LintPass for NonCamelCaseTypes {
851 fn get_lints(&self) -> LintArray {
852 lint_array!(NON_CAMEL_CASE_TYPES)
855 fn check_item(&mut self, cx: &Context, it: &ast::Item) {
856 let has_extern_repr = it.attrs.iter().map(|attr| {
857 attr::find_repr_attrs(cx.tcx.sess.diagnostic(), attr).iter()
858 .any(|r| r == &attr::ReprExtern)
860 if has_extern_repr { return }
863 ast::ItemTy(..) | ast::ItemStruct(..) => {
864 self.check_case(cx, "type", it.ident, it.span)
866 ast::ItemTrait(..) => {
867 self.check_case(cx, "trait", it.ident, it.span)
869 ast::ItemEnum(ref enum_definition, _) => {
870 if has_extern_repr { return }
871 self.check_case(cx, "type", it.ident, it.span);
872 for variant in enum_definition.variants.iter() {
873 self.check_case(cx, "variant", variant.node.name, variant.span);
880 fn check_generics(&mut self, cx: &Context, it: &ast::Generics) {
881 for gen in it.ty_params.iter() {
882 self.check_case(cx, "type parameter", gen.ident, gen.span);
894 fn method_context(cx: &Context, m: &ast::Method) -> MethodContext {
895 let did = ast::DefId {
896 krate: ast::LOCAL_CRATE,
900 match cx.tcx.impl_or_trait_items.borrow().get(&did).cloned() {
901 None => cx.sess().span_bug(m.span, "missing method descriptor?!"),
904 ty::MethodTraitItem(md) => {
906 ty::TraitContainer(..) => TraitDefaultImpl,
907 ty::ImplContainer(cid) => {
908 match ty::impl_trait_ref(cx.tcx, cid) {
909 Some(..) => TraitImpl,
915 ty::TypeTraitItem(typedef) => {
916 match typedef.container {
917 ty::TraitContainer(..) => TraitDefaultImpl,
918 ty::ImplContainer(cid) => {
919 match ty::impl_trait_ref(cx.tcx, cid) {
920 Some(..) => TraitImpl,
934 "methods, functions, lifetime parameters and modules should have snake case names"
938 pub struct NonSnakeCase;
941 fn check_snake_case(&self, cx: &Context, sort: &str, ident: ast::Ident, span: Span) {
942 fn is_snake_case(ident: ast::Ident) -> bool {
943 let ident = token::get_ident(ident);
944 if ident.get().is_empty() { return true; }
945 let ident = ident.get().trim_left_matches('\'');
946 let ident = ident.trim_matches('_');
948 let mut allow_underscore = true;
949 ident.chars().all(|c| {
950 allow_underscore = match c {
951 c if c.is_lowercase() || c.is_numeric() => true,
952 '_' if allow_underscore => false,
959 fn to_snake_case(str: &str) -> String {
960 let mut words = vec![];
961 for s in str.split('_') {
962 let mut last_upper = false;
963 let mut buf = String::new();
964 if s.is_empty() { continue; }
965 for ch in s.chars() {
966 if !buf.is_empty() && buf != "'"
972 last_upper = ch.is_uppercase();
973 buf.push(ch.to_lowercase());
980 let s = token::get_ident(ident);
982 if !is_snake_case(ident) {
983 cx.span_lint(NON_SNAKE_CASE, span,
984 &format!("{} `{}` should have a snake case name such as `{}`",
985 sort, s, to_snake_case(s.get()))[]);
990 impl LintPass for NonSnakeCase {
991 fn get_lints(&self) -> LintArray {
992 lint_array!(NON_SNAKE_CASE)
995 fn check_fn(&mut self, cx: &Context,
996 fk: visit::FnKind, _: &ast::FnDecl,
997 _: &ast::Block, span: Span, _: ast::NodeId) {
999 visit::FkMethod(ident, _, m) => match method_context(cx, m) {
1001 => self.check_snake_case(cx, "method", ident, span),
1003 => self.check_snake_case(cx, "trait method", ident, span),
1006 visit::FkItemFn(ident, _, _, _)
1007 => self.check_snake_case(cx, "function", ident, span),
1012 fn check_item(&mut self, cx: &Context, it: &ast::Item) {
1013 if let ast::ItemMod(_) = it.node {
1014 self.check_snake_case(cx, "module", it.ident, it.span);
1018 fn check_ty_method(&mut self, cx: &Context, t: &ast::TypeMethod) {
1019 self.check_snake_case(cx, "trait method", t.ident, t.span);
1022 fn check_lifetime_def(&mut self, cx: &Context, t: &ast::LifetimeDef) {
1023 self.check_snake_case(cx, "lifetime", t.lifetime.name.ident(), t.lifetime.span);
1026 fn check_pat(&mut self, cx: &Context, p: &ast::Pat) {
1027 if let &ast::PatIdent(_, ref path1, _) = &p.node {
1028 if let Some(&def::DefLocal(_)) = cx.tcx.def_map.borrow().get(&p.id) {
1029 self.check_snake_case(cx, "variable", path1.node, p.span);
1034 fn check_struct_def(&mut self, cx: &Context, s: &ast::StructDef,
1035 _: ast::Ident, _: &ast::Generics, _: ast::NodeId) {
1036 for sf in s.fields.iter() {
1037 if let ast::StructField_ { kind: ast::NamedField(ident, _), .. } = sf.node {
1038 self.check_snake_case(cx, "structure field", ident, sf.span);
1045 pub NON_UPPER_CASE_GLOBALS,
1047 "static constants should have uppercase identifiers"
1051 pub struct NonUpperCaseGlobals;
1053 impl LintPass for NonUpperCaseGlobals {
1054 fn get_lints(&self) -> LintArray {
1055 lint_array!(NON_UPPER_CASE_GLOBALS)
1058 fn check_item(&mut self, cx: &Context, it: &ast::Item) {
1060 // only check static constants
1061 ast::ItemStatic(_, ast::MutImmutable, _) |
1062 ast::ItemConst(..) => {
1063 let s = token::get_ident(it.ident);
1064 // check for lowercase letters rather than non-uppercase
1065 // ones (some scripts don't have a concept of
1067 if s.get().chars().any(|c| c.is_lowercase()) {
1068 cx.span_lint(NON_UPPER_CASE_GLOBALS, it.span,
1069 &format!("static constant `{}` should have an uppercase name \
1071 s.get(), &s.get().chars().map(|c| c.to_uppercase())
1072 .collect::<String>()[])[]);
1079 fn check_pat(&mut self, cx: &Context, p: &ast::Pat) {
1080 // Lint for constants that look like binding identifiers (#7526)
1081 match (&p.node, cx.tcx.def_map.borrow().get(&p.id)) {
1082 (&ast::PatIdent(_, ref path1, _), Some(&def::DefConst(..))) => {
1083 let s = token::get_ident(path1.node);
1084 if s.get().chars().any(|c| c.is_lowercase()) {
1085 cx.span_lint(NON_UPPER_CASE_GLOBALS, path1.span,
1086 &format!("static constant in pattern `{}` should have an uppercase \
1088 s.get(), &s.get().chars().map(|c| c.to_uppercase())
1089 .collect::<String>()[])[]);
1100 "`if`, `match`, `while` and `return` do not need parentheses"
1104 pub struct UnusedParens;
1107 fn check_unused_parens_core(&self, cx: &Context, value: &ast::Expr, msg: &str,
1108 struct_lit_needs_parens: bool) {
1109 if let ast::ExprParen(ref inner) = value.node {
1110 let necessary = struct_lit_needs_parens && contains_exterior_struct_lit(&**inner);
1112 cx.span_lint(UNUSED_PARENS, value.span,
1113 &format!("unnecessary parentheses around {}",
1118 /// Expressions that syntactically contain an "exterior" struct
1119 /// literal i.e. not surrounded by any parens or other
1120 /// delimiters, e.g. `X { y: 1 }`, `X { y: 1 }.method()`, `foo
1121 /// == X { y: 1 }` and `X { y: 1 } == foo` all do, but `(X {
1122 /// y: 1 }) == foo` does not.
1123 fn contains_exterior_struct_lit(value: &ast::Expr) -> bool {
1125 ast::ExprStruct(..) => true,
1127 ast::ExprAssign(ref lhs, ref rhs) |
1128 ast::ExprAssignOp(_, ref lhs, ref rhs) |
1129 ast::ExprBinary(_, ref lhs, ref rhs) => {
1130 // X { y: 1 } + X { y: 2 }
1131 contains_exterior_struct_lit(&**lhs) ||
1132 contains_exterior_struct_lit(&**rhs)
1134 ast::ExprUnary(_, ref x) |
1135 ast::ExprCast(ref x, _) |
1136 ast::ExprField(ref x, _) |
1137 ast::ExprTupField(ref x, _) |
1138 ast::ExprIndex(ref x, _) => {
1139 // &X { y: 1 }, X { y: 1 }.y
1140 contains_exterior_struct_lit(&**x)
1143 ast::ExprMethodCall(_, _, ref exprs) => {
1144 // X { y: 1 }.bar(...)
1145 contains_exterior_struct_lit(&*exprs[0])
1154 impl LintPass for UnusedParens {
1155 fn get_lints(&self) -> LintArray {
1156 lint_array!(UNUSED_PARENS)
1159 fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
1160 let (value, msg, struct_lit_needs_parens) = match e.node {
1161 ast::ExprIf(ref cond, _, _) => (cond, "`if` condition", true),
1162 ast::ExprWhile(ref cond, _, _) => (cond, "`while` condition", true),
1163 ast::ExprMatch(ref head, _, source) => match source {
1164 ast::MatchSource::Normal => (head, "`match` head expression", true),
1165 ast::MatchSource::IfLetDesugar { .. } => (head, "`if let` head expression", true),
1166 ast::MatchSource::WhileLetDesugar => (head, "`while let` head expression", true),
1168 ast::ExprRet(Some(ref value)) => (value, "`return` value", false),
1169 ast::ExprAssign(_, ref value) => (value, "assigned value", false),
1170 ast::ExprAssignOp(_, _, ref value) => (value, "assigned value", false),
1173 self.check_unused_parens_core(cx, &**value, msg, struct_lit_needs_parens);
1176 fn check_stmt(&mut self, cx: &Context, s: &ast::Stmt) {
1177 let (value, msg) = match s.node {
1178 ast::StmtDecl(ref decl, _) => match decl.node {
1179 ast::DeclLocal(ref local) => match local.init {
1180 Some(ref value) => (value, "assigned value"),
1187 self.check_unused_parens_core(cx, &**value, msg, false);
1192 UNUSED_IMPORT_BRACES,
1194 "unnecessary braces around an imported item"
1198 pub struct UnusedImportBraces;
1200 impl LintPass for UnusedImportBraces {
1201 fn get_lints(&self) -> LintArray {
1202 lint_array!(UNUSED_IMPORT_BRACES)
1205 fn check_view_item(&mut self, cx: &Context, view_item: &ast::ViewItem) {
1206 match view_item.node {
1207 ast::ViewItemUse(ref view_path) => {
1208 match view_path.node {
1209 ast::ViewPathList(_, ref items, _) => {
1210 if items.len() == 1 {
1211 match items[0].node {
1212 ast::PathListIdent {ref name, ..} => {
1213 let m = format!("braces around {} is unnecessary",
1214 token::get_ident(*name).get());
1215 cx.span_lint(UNUSED_IMPORT_BRACES, view_item.span,
1231 NON_SHORTHAND_FIELD_PATTERNS,
1233 "using `Struct { x: x }` instead of `Struct { x }`"
1237 pub struct NonShorthandFieldPatterns;
1239 impl LintPass for NonShorthandFieldPatterns {
1240 fn get_lints(&self) -> LintArray {
1241 lint_array!(NON_SHORTHAND_FIELD_PATTERNS)
1244 fn check_pat(&mut self, cx: &Context, pat: &ast::Pat) {
1245 let def_map = cx.tcx.def_map.borrow();
1246 if let ast::PatStruct(_, ref v, _) = pat.node {
1247 for fieldpat in v.iter()
1248 .filter(|fieldpat| !fieldpat.node.is_shorthand)
1249 .filter(|fieldpat| def_map.get(&fieldpat.node.pat.id)
1250 == Some(&def::DefLocal(fieldpat.node.pat.id))) {
1251 if let ast::PatIdent(_, ident, None) = fieldpat.node.pat.node {
1252 if ident.node.as_str() == fieldpat.node.ident.as_str() {
1253 cx.span_lint(NON_SHORTHAND_FIELD_PATTERNS, fieldpat.span,
1254 &format!("the `{}:` in this pattern is redundant and can \
1255 be removed", ident.node.as_str())[])
1266 "unnecessary use of an `unsafe` block"
1270 pub struct UnusedUnsafe;
1272 impl LintPass for UnusedUnsafe {
1273 fn get_lints(&self) -> LintArray {
1274 lint_array!(UNUSED_UNSAFE)
1277 fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
1278 if let ast::ExprBlock(ref blk) = e.node {
1279 // Don't warn about generated blocks, that'll just pollute the output.
1280 if blk.rules == ast::UnsafeBlock(ast::UserProvided) &&
1281 !cx.tcx.used_unsafe.borrow().contains(&blk.id) {
1282 cx.span_lint(UNUSED_UNSAFE, blk.span, "unnecessary `unsafe` block");
1291 "usage of an `unsafe` block"
1295 pub struct UnsafeBlocks;
1297 impl LintPass for UnsafeBlocks {
1298 fn get_lints(&self) -> LintArray {
1299 lint_array!(UNSAFE_BLOCKS)
1302 fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
1303 if let ast::ExprBlock(ref blk) = e.node {
1304 // Don't warn about generated blocks, that'll just pollute the output.
1305 if blk.rules == ast::UnsafeBlock(ast::UserProvided) {
1306 cx.span_lint(UNSAFE_BLOCKS, blk.span, "usage of an `unsafe` block");
1315 "detect mut variables which don't need to be mutable"
1319 pub struct UnusedMut;
1322 fn check_unused_mut_pat(&self, cx: &Context, pats: &[P<ast::Pat>]) {
1323 // collect all mutable pattern and group their NodeIDs by their Identifier to
1324 // avoid false warnings in match arms with multiple patterns
1326 let mut mutables = FnvHashMap();
1327 for p in pats.iter() {
1328 pat_util::pat_bindings(&cx.tcx.def_map, &**p, |mode, id, _, path1| {
1329 let ident = path1.node;
1330 if let ast::BindByValue(ast::MutMutable) = mode {
1331 if !token::get_ident(ident).get().starts_with("_") {
1332 match mutables.entry(ident.name.usize()) {
1333 Vacant(entry) => { entry.insert(vec![id]); },
1334 Occupied(mut entry) => { entry.get_mut().push(id); },
1341 let used_mutables = cx.tcx.used_mut_nodes.borrow();
1342 for (_, v) in mutables.iter() {
1343 if !v.iter().any(|e| used_mutables.contains(e)) {
1344 cx.span_lint(UNUSED_MUT, cx.tcx.map.span(v[0]),
1345 "variable does not need to be mutable");
1351 impl LintPass for UnusedMut {
1352 fn get_lints(&self) -> LintArray {
1353 lint_array!(UNUSED_MUT)
1356 fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
1357 if let ast::ExprMatch(_, ref arms, _) = e.node {
1358 for a in arms.iter() {
1359 self.check_unused_mut_pat(cx, &a.pats[])
1364 fn check_stmt(&mut self, cx: &Context, s: &ast::Stmt) {
1365 if let ast::StmtDecl(ref d, _) = s.node {
1366 if let ast::DeclLocal(ref l) = d.node {
1367 self.check_unused_mut_pat(cx, slice::ref_slice(&l.pat));
1372 fn check_fn(&mut self, cx: &Context,
1373 _: visit::FnKind, decl: &ast::FnDecl,
1374 _: &ast::Block, _: Span, _: ast::NodeId) {
1375 for a in decl.inputs.iter() {
1376 self.check_unused_mut_pat(cx, slice::ref_slice(&a.pat));
1384 "detects unnecessary allocations that can be eliminated"
1388 pub struct UnusedAllocation;
1390 impl LintPass for UnusedAllocation {
1391 fn get_lints(&self) -> LintArray {
1392 lint_array!(UNUSED_ALLOCATION)
1395 fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
1397 ast::ExprUnary(ast::UnUniq, _) => (),
1401 if let Some(adjustment) = cx.tcx.adjustments.borrow().get(&e.id) {
1402 if let ty::AdjustDerefRef(ty::AutoDerefRef { ref autoref, .. }) = *adjustment {
1404 &Some(ty::AutoPtr(_, ast::MutImmutable, None)) => {
1405 cx.span_lint(UNUSED_ALLOCATION, e.span,
1406 "unnecessary allocation, use & instead");
1408 &Some(ty::AutoPtr(_, ast::MutMutable, None)) => {
1409 cx.span_lint(UNUSED_ALLOCATION, e.span,
1410 "unnecessary allocation, use &mut instead");
1422 "detects missing documentation for public members"
1425 pub struct MissingDoc {
1426 /// Stack of IDs of struct definitions.
1427 struct_def_stack: Vec<ast::NodeId>,
1429 /// True if inside variant definition
1432 /// Stack of whether #[doc(hidden)] is set
1433 /// at each level which has lint attributes.
1434 doc_hidden_stack: Vec<bool>,
1438 pub fn new() -> MissingDoc {
1440 struct_def_stack: vec!(),
1442 doc_hidden_stack: vec!(false),
1446 fn doc_hidden(&self) -> bool {
1447 *self.doc_hidden_stack.last().expect("empty doc_hidden_stack")
1450 fn check_missing_docs_attrs(&self,
1452 id: Option<ast::NodeId>,
1453 attrs: &[ast::Attribute],
1455 desc: &'static str) {
1456 // If we're building a test harness, then warning about
1457 // documentation is probably not really relevant right now.
1458 if cx.sess().opts.test { return }
1460 // `#[doc(hidden)]` disables missing_docs check.
1461 if self.doc_hidden() { return }
1463 // Only check publicly-visible items, using the result from the privacy pass.
1464 // It's an option so the crate root can also use this function (it doesn't
1466 if let Some(ref id) = id {
1467 if !cx.exported_items.contains(id) {
1472 let has_doc = attrs.iter().any(|a| {
1473 match a.node.value.node {
1474 ast::MetaNameValue(ref name, _) if *name == "doc" => true,
1479 cx.span_lint(MISSING_DOCS, sp,
1480 &format!("missing documentation for {}", desc)[]);
1485 impl LintPass for MissingDoc {
1486 fn get_lints(&self) -> LintArray {
1487 lint_array!(MISSING_DOCS)
1490 fn enter_lint_attrs(&mut self, _: &Context, attrs: &[ast::Attribute]) {
1491 let doc_hidden = self.doc_hidden() || attrs.iter().any(|attr| {
1492 attr.check_name("doc") && match attr.meta_item_list() {
1494 Some(l) => attr::contains_name(&l[], "hidden"),
1497 self.doc_hidden_stack.push(doc_hidden);
1500 fn exit_lint_attrs(&mut self, _: &Context, _: &[ast::Attribute]) {
1501 self.doc_hidden_stack.pop().expect("empty doc_hidden_stack");
1504 fn check_struct_def(&mut self, _: &Context,
1505 _: &ast::StructDef, _: ast::Ident, _: &ast::Generics, id: ast::NodeId) {
1506 self.struct_def_stack.push(id);
1509 fn check_struct_def_post(&mut self, _: &Context,
1510 _: &ast::StructDef, _: ast::Ident, _: &ast::Generics, id: ast::NodeId) {
1511 let popped = self.struct_def_stack.pop().expect("empty struct_def_stack");
1512 assert!(popped == id);
1515 fn check_crate(&mut self, cx: &Context, krate: &ast::Crate) {
1516 self.check_missing_docs_attrs(cx, None, &krate.attrs[],
1517 krate.span, "crate");
1520 fn check_item(&mut self, cx: &Context, it: &ast::Item) {
1521 let desc = match it.node {
1522 ast::ItemFn(..) => "a function",
1523 ast::ItemMod(..) => "a module",
1524 ast::ItemEnum(..) => "an enum",
1525 ast::ItemStruct(..) => "a struct",
1526 ast::ItemTrait(..) => "a trait",
1527 ast::ItemTy(..) => "a type alias",
1530 self.check_missing_docs_attrs(cx, Some(it.id), &it.attrs[],
1534 fn check_fn(&mut self, cx: &Context,
1535 fk: visit::FnKind, _: &ast::FnDecl,
1536 _: &ast::Block, _: Span, _: ast::NodeId) {
1537 if let visit::FkMethod(_, _, m) = fk {
1538 // If the method is an impl for a trait, don't doc.
1539 if method_context(cx, m) == TraitImpl { return; }
1541 // Otherwise, doc according to privacy. This will also check
1542 // doc for default methods defined on traits.
1543 self.check_missing_docs_attrs(cx, Some(m.id), &m.attrs[],
1544 m.span, "a method");
1548 fn check_ty_method(&mut self, cx: &Context, tm: &ast::TypeMethod) {
1549 self.check_missing_docs_attrs(cx, Some(tm.id), &tm.attrs[],
1550 tm.span, "a type method");
1553 fn check_struct_field(&mut self, cx: &Context, sf: &ast::StructField) {
1554 if let ast::NamedField(_, vis) = sf.node.kind {
1555 if vis == ast::Public || self.in_variant {
1556 let cur_struct_def = *self.struct_def_stack.last()
1557 .expect("empty struct_def_stack");
1558 self.check_missing_docs_attrs(cx, Some(cur_struct_def),
1559 &sf.node.attrs[], sf.span,
1565 fn check_variant(&mut self, cx: &Context, v: &ast::Variant, _: &ast::Generics) {
1566 self.check_missing_docs_attrs(cx, Some(v.node.id), &v.node.attrs[],
1567 v.span, "a variant");
1568 assert!(!self.in_variant);
1569 self.in_variant = true;
1572 fn check_variant_post(&mut self, _: &Context, _: &ast::Variant, _: &ast::Generics) {
1573 assert!(self.in_variant);
1574 self.in_variant = false;
1579 pub struct MissingCopyImplementations;
1581 impl LintPass for MissingCopyImplementations {
1582 fn get_lints(&self) -> LintArray {
1583 lint_array!(MISSING_COPY_IMPLEMENTATIONS)
1586 fn check_item(&mut self, cx: &Context, item: &ast::Item) {
1587 if !cx.exported_items.contains(&item.id) {
1591 .destructor_for_type
1593 .contains_key(&ast_util::local_def(item.id)) {
1596 let ty = match item.node {
1597 ast::ItemStruct(_, ref ast_generics) => {
1598 if ast_generics.is_parameterized() {
1601 ty::mk_struct(cx.tcx,
1602 ast_util::local_def(item.id),
1603 cx.tcx.mk_substs(Substs::empty()))
1605 ast::ItemEnum(_, ref ast_generics) => {
1606 if ast_generics.is_parameterized() {
1610 ast_util::local_def(item.id),
1611 cx.tcx.mk_substs(Substs::empty()))
1615 let parameter_environment = ty::empty_parameter_environment(cx.tcx);
1616 if !ty::type_moves_by_default(¶meter_environment, item.span, ty) {
1619 if ty::can_type_implement_copy(¶meter_environment, item.span, ty).is_ok() {
1620 cx.span_lint(MISSING_COPY_IMPLEMENTATIONS,
1622 "type could implement `Copy`; consider adding `impl \
1631 "detects use of #[deprecated] items"
1637 "detects use of #[unstable] items (incl. items with no stability attribute)"
1640 /// Checks for use of items with `#[deprecated]`, `#[unstable]` and
1641 /// `#[unstable]` attributes, or no stability attribute.
1643 pub struct Stability { this_crate_staged: bool }
1646 pub fn new() -> Stability { Stability { this_crate_staged: false } }
1648 fn lint(&self, cx: &Context, id: ast::DefId, span: Span) {
1650 let ref stability = stability::lookup(cx.tcx, id);
1651 let cross_crate = !ast_util::is_local(id);
1652 let staged = (!cross_crate && self.this_crate_staged)
1653 || (cross_crate && stability::is_staged_api(cx.tcx, id));
1655 if !staged { return }
1657 // stability attributes are promises made across crates; only
1658 // check DEPRECATED for crate-local usage.
1659 let (lint, label) = match *stability {
1660 // no stability attributes == Unstable
1661 None if cross_crate => (UNSTABLE, "unmarked"),
1662 Some(attr::Stability { level: attr::Unstable, .. }) if cross_crate =>
1663 (UNSTABLE, "unstable"),
1664 Some(attr::Stability { level: attr::Deprecated, .. }) =>
1665 (DEPRECATED, "deprecated"),
1669 output(cx, span, stability, lint, label);
1671 fn output(cx: &Context, span: Span, stability: &Option<attr::Stability>,
1672 lint: &'static Lint, label: &'static str) {
1673 let msg = match *stability {
1674 Some(attr::Stability { text: Some(ref s), .. }) => {
1675 format!("use of {} item: {}", label, *s)
1677 _ => format!("use of {} item", label)
1680 cx.span_lint(lint, span, &msg[]);
1685 fn is_internal(&self, cx: &Context, span: Span) -> bool {
1686 cx.tcx.sess.codemap().span_is_internal(span)
1691 impl LintPass for Stability {
1692 fn get_lints(&self) -> LintArray {
1693 lint_array!(DEPRECATED, UNSTABLE)
1696 fn check_crate(&mut self, _: &Context, c: &ast::Crate) {
1697 // Just mark the #[staged_api] attribute used, though nothing else is done
1698 // with it during this pass over the source.
1699 for attr in c.attrs.iter() {
1700 if attr.name().get() == "staged_api" {
1701 match attr.node.value.node {
1702 ast::MetaWord(_) => {
1703 attr::mark_used(attr);
1704 self.this_crate_staged = true;
1712 fn check_view_item(&mut self, cx: &Context, item: &ast::ViewItem) {
1713 // compiler-generated `extern crate` statements have a dummy span.
1714 if item.span == DUMMY_SP { return }
1716 let id = match item.node {
1717 ast::ViewItemExternCrate(_, _, id) => id,
1718 ast::ViewItemUse(..) => return,
1720 let cnum = match cx.tcx.sess.cstore.find_extern_mod_stmt_cnum(id) {
1724 let id = ast::DefId { krate: cnum, node: ast::CRATE_NODE_ID };
1725 self.lint(cx, id, item.span);
1728 fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
1729 if self.is_internal(cx, e.span) { return; }
1731 let mut span = e.span;
1733 let id = match e.node {
1734 ast::ExprPath(..) | ast::ExprQPath(..) | ast::ExprStruct(..) => {
1735 match cx.tcx.def_map.borrow().get(&e.id) {
1736 Some(&def) => def.def_id(),
1740 ast::ExprMethodCall(i, _, _) => {
1742 let method_call = ty::MethodCall::expr(e.id);
1743 match cx.tcx.method_map.borrow().get(&method_call) {
1745 match method.origin {
1746 ty::MethodStatic(def_id) => {
1749 ty::MethodStaticUnboxedClosure(def_id) => {
1752 ty::MethodTypeParam(ty::MethodParam {
1757 ty::MethodTraitObject(ty::MethodObject {
1762 ty::trait_item(cx.tcx, trait_ref.def_id, index).def_id()
1772 self.lint(cx, id, span);
1775 fn check_item(&mut self, cx: &Context, item: &ast::Item) {
1776 if self.is_internal(cx, item.span) { return }
1779 ast::ItemTrait(_, _, ref supertraits, _) => {
1780 for t in supertraits.iter() {
1781 if let ast::TraitTyParamBound(ref t, _) = *t {
1782 let id = ty::trait_ref_to_def_id(cx.tcx, &t.trait_ref);
1783 self.lint(cx, id, t.trait_ref.path.span);
1787 ast::ItemImpl(_, _, _, Some(ref t), _, _) => {
1788 let id = ty::trait_ref_to_def_id(cx.tcx, t);
1789 self.lint(cx, id, t.path.span);
1799 "imports that are never used"
1803 pub UNUSED_EXTERN_CRATES,
1805 "extern crates that are never used"
1809 pub UNUSED_QUALIFICATIONS,
1811 "detects unnecessarily qualified names"
1817 "unrecognized lint attribute"
1821 pub UNUSED_VARIABLES,
1823 "detect variables which are not used in any way"
1827 pub UNUSED_ASSIGNMENTS,
1829 "detect assignments that will never be read"
1835 "detect unused, unexported items"
1839 pub UNREACHABLE_CODE,
1841 "detects unreachable code paths"
1847 "mass-change the level for lints which produce warnings"
1851 pub UNKNOWN_FEATURES,
1853 "unknown features found in crate-level #[feature] directives"
1857 pub UNKNOWN_CRATE_TYPES,
1859 "unknown crate type found in #[crate_type] directive"
1863 pub VARIANT_SIZE_DIFFERENCES,
1865 "detects enums with widely varying variant sizes"
1869 pub FAT_PTR_TRANSMUTES,
1871 "detects transmutes of fat pointers"
1875 pub MISSING_COPY_IMPLEMENTATIONS,
1877 "detects potentially-forgotten implementations of `Copy`"
1880 /// Does nothing as a lint pass, but registers some `Lint`s
1881 /// which are used by other parts of the compiler.
1883 pub struct HardwiredLints;
1885 impl LintPass for HardwiredLints {
1886 fn get_lints(&self) -> LintArray {
1889 UNUSED_EXTERN_CRATES,
1890 UNUSED_QUALIFICATIONS,
1898 UNKNOWN_CRATE_TYPES,
1899 VARIANT_SIZE_DIFFERENCES,
1905 /// Forbids using the `#[feature(...)]` attribute
1907 pub struct UnstableFeatures;
1909 declare_lint!(UNSTABLE_FEATURES, Allow,
1910 "enabling unstable features");
1912 impl LintPass for UnstableFeatures {
1913 fn get_lints(&self) -> LintArray {
1914 lint_array!(UNSTABLE_FEATURES)
1916 fn check_attribute(&mut self, ctx: &Context, attr: &ast::Attribute) {
1918 if attr::contains_name(&[attr.node.value.clone()], "feature") {
1919 ctx.span_lint(UNSTABLE_FEATURES, attr.span, "unstable feature");