1 // Copyright 2012-2015 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 in the Rust compiler.
13 //! This contains lints which can feasibly be implemented as their own
14 //! AST visitor. Also see `rustc::lint::builtin`, which contains the
15 //! definitions of lints that are emitted directly inside the main
18 //! To add a new lint to rustc, declare it here using `declare_lint!()`.
19 //! Then add code to emit the new lint in the appropriate circumstances.
20 //! You can do that in an existing `LintPass` if it makes sense, or in a
21 //! new `LintPass`, or using `Session::add_lint` elsewhere in the
22 //! compiler. Only do the latter if the check can't be written cleanly as a
23 //! `LintPass` (also, note that such lints will need to be defined in
24 //! `rustc::lint::builtin`, not here).
26 //! If you define a new `LintPass`, you will also need to add it to the
27 //! `add_builtin!` or `add_builtin_with_new!` invocation in `lib.rs`.
28 //! Use the former for unit-like structs and the latter for structs with
31 use metadata::{csearch, decoder};
32 use middle::{cfg, def, infer, pat_util, stability, traits};
33 use middle::def_id::DefId;
34 use middle::subst::Substs;
35 use middle::ty::{self, Ty};
36 use middle::ty::adjustment;
37 use middle::const_eval::{eval_const_expr_partial, ConstVal};
38 use middle::const_eval::EvalHint::ExprTypeChecked;
39 use rustc::front::map as hir_map;
40 use util::nodemap::{FnvHashMap, FnvHashSet, NodeSet};
41 use lint::{Level, Context, LintPass, LintArray, Lint};
43 use std::collections::HashSet;
44 use std::collections::hash_map::Entry::{Occupied, Vacant};
45 use std::{cmp, slice};
46 use std::{i8, i16, i32, i64, u8, u16, u32, u64, f32, f64};
48 use syntax::{abi, ast};
49 use syntax::attr::{self, AttrMetaMethods};
50 use syntax::codemap::{self, Span};
51 use syntax::feature_gate::{KNOWN_ATTRIBUTES, AttributeType};
52 use syntax::ast::{TyIs, TyUs, TyI8, TyU8, TyI16, TyU16, TyI32, TyU32, TyI64, TyU64};
56 use rustc_front::visit::{self, FnKind, Visitor};
57 use rustc_front::util::is_shift_binop;
59 // hardwired lints from librustc
60 pub use lint::builtin::*;
65 "suggest using `loop { }` instead of `while true { }`"
68 #[derive(Copy, Clone)]
71 impl LintPass for WhileTrue {
72 fn get_lints(&self) -> LintArray {
73 lint_array!(WHILE_TRUE)
76 fn check_expr(&mut self, cx: &Context, e: &hir::Expr) {
77 if let hir::ExprWhile(ref cond, _, _) = e.node {
78 if let hir::ExprLit(ref lit) = cond.node {
79 if let ast::LitBool(true) = lit.node {
80 cx.span_lint(WHILE_TRUE, e.span,
81 "denote infinite loops with loop { ... }");
91 "comparisons made useless by limits of the types involved"
97 "literal out of range for its type"
103 "shift exceeds the type's number of bits"
106 #[derive(Copy, Clone)]
107 pub struct TypeLimits {
108 /// Id of the last visited negated expression
109 negated_expr_id: ast::NodeId,
113 pub fn new() -> TypeLimits {
120 impl LintPass for TypeLimits {
121 fn get_lints(&self) -> LintArray {
122 lint_array!(UNUSED_COMPARISONS, OVERFLOWING_LITERALS, EXCEEDING_BITSHIFTS)
125 fn check_expr(&mut self, cx: &Context, e: &hir::Expr) {
127 hir::ExprUnary(hir::UnNeg, ref expr) => {
129 hir::ExprLit(ref lit) => {
131 ast::LitInt(_, ast::UnsignedIntLit(_)) => {
132 check_unsigned_negation_feature(cx, e.span);
134 ast::LitInt(_, ast::UnsuffixedIntLit(_)) => {
135 if let ty::TyUint(_) = cx.tcx.node_id_to_type(e.id).sty {
136 check_unsigned_negation_feature(cx, e.span);
143 let t = cx.tcx.node_id_to_type(expr.id);
146 check_unsigned_negation_feature(cx, e.span);
152 // propagate negation, if the negation itself isn't negated
153 if self.negated_expr_id != e.id {
154 self.negated_expr_id = expr.id;
157 hir::ExprParen(ref expr) if self.negated_expr_id == e.id => {
158 self.negated_expr_id = expr.id;
160 hir::ExprBinary(binop, ref l, ref r) => {
161 if is_comparison(binop) && !check_limits(cx.tcx, binop, &**l, &**r) {
162 cx.span_lint(UNUSED_COMPARISONS, e.span,
163 "comparison is useless due to type limits");
166 if is_shift_binop(binop.node) {
167 let opt_ty_bits = match cx.tcx.node_id_to_type(l.id).sty {
168 ty::TyInt(t) => Some(int_ty_bits(t, cx.sess().target.int_type)),
169 ty::TyUint(t) => Some(uint_ty_bits(t, cx.sess().target.uint_type)),
173 if let Some(bits) = opt_ty_bits {
174 let exceeding = if let hir::ExprLit(ref lit) = r.node {
175 if let ast::LitInt(shift, _) = lit.node { shift >= bits }
178 match eval_const_expr_partial(cx.tcx, &r, ExprTypeChecked) {
179 Ok(ConstVal::Int(shift)) => { shift as u64 >= bits },
180 Ok(ConstVal::Uint(shift)) => { shift >= bits },
185 cx.span_lint(EXCEEDING_BITSHIFTS, e.span,
186 "bitshift exceeds the type's number of bits");
191 hir::ExprLit(ref lit) => {
192 match cx.tcx.node_id_to_type(e.id).sty {
195 ast::LitInt(v, ast::SignedIntLit(_, ast::Plus)) |
196 ast::LitInt(v, ast::UnsuffixedIntLit(ast::Plus)) => {
197 let int_type = if let ast::TyIs = t {
198 cx.sess().target.int_type
202 let (_, max) = int_ty_range(int_type);
203 let negative = self.negated_expr_id == e.id;
205 // Detect literal value out of range [min, max] inclusive
206 // avoiding use of -min to prevent overflow/panic
207 if (negative && v > max as u64 + 1) ||
208 (!negative && v > max as u64) {
209 cx.span_lint(OVERFLOWING_LITERALS, e.span,
210 &*format!("literal out of range for {:?}", t));
218 let uint_type = if let ast::TyUs = t {
219 cx.sess().target.uint_type
223 let (min, max) = uint_ty_range(uint_type);
224 let lit_val: u64 = match lit.node {
225 ast::LitByte(_v) => return, // _v is u8, within range by definition
226 ast::LitInt(v, _) => v,
229 if lit_val < min || lit_val > max {
230 cx.span_lint(OVERFLOWING_LITERALS, e.span,
231 &*format!("literal out of range for {:?}", t));
235 let (min, max) = float_ty_range(t);
236 let lit_val: f64 = match lit.node {
237 ast::LitFloat(ref v, _) |
238 ast::LitFloatUnsuffixed(ref v) => {
246 if lit_val < min || lit_val > max {
247 cx.span_lint(OVERFLOWING_LITERALS, e.span,
248 &*format!("literal out of range for {:?}", t));
257 fn is_valid<T:cmp::PartialOrd>(binop: hir::BinOp, v: T,
258 min: T, max: T) -> bool {
260 hir::BiLt => v > min && v <= max,
261 hir::BiLe => v >= min && v < max,
262 hir::BiGt => v >= min && v < max,
263 hir::BiGe => v > min && v <= max,
264 hir::BiEq | hir::BiNe => v >= min && v <= max,
269 fn rev_binop(binop: hir::BinOp) -> hir::BinOp {
270 codemap::respan(binop.span, match binop.node {
271 hir::BiLt => hir::BiGt,
272 hir::BiLe => hir::BiGe,
273 hir::BiGt => hir::BiLt,
274 hir::BiGe => hir::BiLe,
279 // for isize & usize, be conservative with the warnings, so that the
280 // warnings are consistent between 32- and 64-bit platforms
281 fn int_ty_range(int_ty: ast::IntTy) -> (i64, i64) {
283 ast::TyIs => (i64::MIN, i64::MAX),
284 ast::TyI8 => (i8::MIN as i64, i8::MAX as i64),
285 ast::TyI16 => (i16::MIN as i64, i16::MAX as i64),
286 ast::TyI32 => (i32::MIN as i64, i32::MAX as i64),
287 ast::TyI64 => (i64::MIN, i64::MAX)
291 fn uint_ty_range(uint_ty: ast::UintTy) -> (u64, u64) {
293 ast::TyUs => (u64::MIN, u64::MAX),
294 ast::TyU8 => (u8::MIN as u64, u8::MAX as u64),
295 ast::TyU16 => (u16::MIN as u64, u16::MAX as u64),
296 ast::TyU32 => (u32::MIN as u64, u32::MAX as u64),
297 ast::TyU64 => (u64::MIN, u64::MAX)
301 fn float_ty_range(float_ty: ast::FloatTy) -> (f64, f64) {
303 ast::TyF32 => (f32::MIN as f64, f32::MAX as f64),
304 ast::TyF64 => (f64::MIN, f64::MAX)
308 fn int_ty_bits(int_ty: ast::IntTy, target_int_ty: ast::IntTy) -> u64 {
310 ast::TyIs => int_ty_bits(target_int_ty, target_int_ty),
311 ast::TyI8 => i8::BITS as u64,
312 ast::TyI16 => i16::BITS as u64,
313 ast::TyI32 => i32::BITS as u64,
314 ast::TyI64 => i64::BITS as u64
318 fn uint_ty_bits(uint_ty: ast::UintTy, target_uint_ty: ast::UintTy) -> u64 {
320 ast::TyUs => uint_ty_bits(target_uint_ty, target_uint_ty),
321 ast::TyU8 => u8::BITS as u64,
322 ast::TyU16 => u16::BITS as u64,
323 ast::TyU32 => u32::BITS as u64,
324 ast::TyU64 => u64::BITS as u64
328 fn check_limits(tcx: &ty::ctxt, binop: hir::BinOp,
329 l: &hir::Expr, r: &hir::Expr) -> bool {
330 let (lit, expr, swap) = match (&l.node, &r.node) {
331 (&hir::ExprLit(_), _) => (l, r, true),
332 (_, &hir::ExprLit(_)) => (r, l, false),
335 // Normalize the binop so that the literal is always on the RHS in
337 let norm_binop = if swap {
342 match tcx.node_id_to_type(expr.id).sty {
343 ty::TyInt(int_ty) => {
344 let (min, max) = int_ty_range(int_ty);
345 let lit_val: i64 = match lit.node {
346 hir::ExprLit(ref li) => match li.node {
347 ast::LitInt(v, ast::SignedIntLit(_, ast::Plus)) |
348 ast::LitInt(v, ast::UnsuffixedIntLit(ast::Plus)) => v as i64,
349 ast::LitInt(v, ast::SignedIntLit(_, ast::Minus)) |
350 ast::LitInt(v, ast::UnsuffixedIntLit(ast::Minus)) => -(v as i64),
355 is_valid(norm_binop, lit_val, min, max)
357 ty::TyUint(uint_ty) => {
358 let (min, max): (u64, u64) = uint_ty_range(uint_ty);
359 let lit_val: u64 = match lit.node {
360 hir::ExprLit(ref li) => match li.node {
361 ast::LitInt(v, _) => v,
366 is_valid(norm_binop, lit_val, min, max)
372 fn is_comparison(binop: hir::BinOp) -> bool {
374 hir::BiEq | hir::BiLt | hir::BiLe |
375 hir::BiNe | hir::BiGe | hir::BiGt => true,
380 fn check_unsigned_negation_feature(cx: &Context, span: Span) {
381 if !cx.sess().features.borrow().negate_unsigned {
382 // FIXME(#27141): change this to syntax::feature_gate::emit_feature_err…
383 cx.sess().span_warn(span,
384 "unary negation of unsigned integers will be feature gated in the future");
385 // …and remove following two expressions.
386 if option_env!("CFG_DISABLE_UNSTABLE_FEATURES").is_some() { return; }
387 cx.sess().fileline_help(span, "add #![feature(negate_unsigned)] to the \
388 crate attributes to enable the gate in advance");
397 "proper use of libc types in foreign modules"
400 struct ImproperCTypesVisitor<'a, 'tcx: 'a> {
401 cx: &'a Context<'a, 'tcx>
406 FfiUnsafe(&'static str),
407 FfiBadStruct(DefId, &'static str),
408 FfiBadEnum(DefId, &'static str)
411 /// Check if this enum can be safely exported based on the
412 /// "nullable pointer optimization". Currently restricted
413 /// to function pointers and references, but could be
414 /// expanded to cover NonZero raw pointers and newtypes.
415 /// FIXME: This duplicates code in trans.
416 fn is_repr_nullable_ptr<'tcx>(tcx: &ty::ctxt<'tcx>,
417 def: ty::AdtDef<'tcx>,
418 substs: &Substs<'tcx>)
420 if def.variants.len() == 2 {
423 if def.variants[0].fields.is_empty() {
425 } else if def.variants[1].fields.is_empty() {
431 if def.variants[data_idx].fields.len() == 1 {
432 match def.variants[data_idx].fields[0].ty(tcx, substs).sty {
433 ty::TyBareFn(None, _) => { return true; }
434 ty::TyRef(..) => { return true; }
442 fn ast_ty_to_normalized<'tcx>(tcx: &ty::ctxt<'tcx>,
445 let tty = match tcx.ast_ty_to_ty_cache.borrow().get(&id) {
447 None => panic!("ast_ty_to_ty_cache was incomplete after typeck!")
449 infer::normalize_associated_type(tcx, &tty)
452 impl<'a, 'tcx> ImproperCTypesVisitor<'a, 'tcx> {
453 /// Check if the given type is "ffi-safe" (has a stable, well-defined
454 /// representation which can be exported to C code).
455 fn check_type_for_ffi(&self,
456 cache: &mut FnvHashSet<Ty<'tcx>>,
459 use self::FfiResult::*;
460 let cx = &self.cx.tcx;
462 // Protect against infinite recursion, for example
463 // `struct S(*mut S);`.
464 // FIXME: A recursion limit is necessary as well, for irregular
466 if !cache.insert(ty) {
471 ty::TyStruct(def, substs) => {
472 if !cx.lookup_repr_hints(def.did).contains(&attr::ReprExtern) {
474 "found struct without foreign-function-safe \
475 representation annotation in foreign module, \
476 consider adding a #[repr(C)] attribute to \
480 // We can't completely trust repr(C) markings; make sure the
481 // fields are actually safe.
482 if def.struct_variant().fields.is_empty() {
484 "found zero-size struct in foreign module, consider \
485 adding a member to this struct");
488 for field in &def.struct_variant().fields {
489 let field_ty = infer::normalize_associated_type(cx, &field.ty(cx, substs));
490 let r = self.check_type_for_ffi(cache, field_ty);
493 FfiBadStruct(..) | FfiBadEnum(..) => { return r; }
494 FfiUnsafe(s) => { return FfiBadStruct(def.did, s); }
499 ty::TyEnum(def, substs) => {
500 if def.variants.is_empty() {
501 // Empty enums are okay... although sort of useless.
505 // Check for a repr() attribute to specify the size of the
507 let repr_hints = cx.lookup_repr_hints(def.did);
508 match &**repr_hints {
510 // Special-case types like `Option<extern fn()>`.
511 if !is_repr_nullable_ptr(cx, def, substs) {
513 "found enum without foreign-function-safe \
514 representation annotation in foreign module, \
515 consider adding a #[repr(...)] attribute to \
520 if !hint.is_ffi_safe() {
521 // FIXME: This shouldn't be reachable: we should check
524 "enum has unexpected #[repr(...)] attribute")
527 // Enum with an explicitly sized discriminant; either
528 // a C-style enum or a discriminated union.
530 // The layout of enum variants is implicitly repr(C).
531 // FIXME: Is that correct?
534 // FIXME: This shouldn't be reachable: we should check
537 "enum has too many #[repr(...)] attributes");
541 // Check the contained variants.
542 for variant in &def.variants {
543 for field in &variant.fields {
544 let arg = infer::normalize_associated_type(cx, &field.ty(cx, substs));
545 let r = self.check_type_for_ffi(cache, arg);
548 FfiBadStruct(..) | FfiBadEnum(..) => { return r; }
549 FfiUnsafe(s) => { return FfiBadEnum(def.did, s); }
556 ty::TyInt(ast::TyIs) => {
557 FfiUnsafe("found Rust type `isize` in foreign module, while \
558 `libc::c_int` or `libc::c_long` should be used")
560 ty::TyUint(ast::TyUs) => {
561 FfiUnsafe("found Rust type `usize` in foreign module, while \
562 `libc::c_uint` or `libc::c_ulong` should be used")
565 FfiUnsafe("found Rust type `char` in foreign module, while \
566 `u32` or `libc::wchar_t` should be used")
569 // Primitive types with a stable representation.
570 ty::TyBool | ty::TyInt(..) | ty::TyUint(..) |
571 ty::TyFloat(..) => FfiSafe,
574 FfiUnsafe("found Rust type Box<_> in foreign module, \
575 consider using a raw pointer instead")
579 FfiUnsafe("found Rust slice type in foreign module, \
580 consider using a raw pointer instead")
584 FfiUnsafe("found Rust trait type in foreign module, \
585 consider using a raw pointer instead")
589 FfiUnsafe("found Rust type `str` in foreign module; \
590 consider using a `*const libc::c_char`")
594 FfiUnsafe("found Rust tuple type in foreign module; \
595 consider using a struct instead`")
598 ty::TyRawPtr(ref m) | ty::TyRef(_, ref m) => {
599 self.check_type_for_ffi(cache, m.ty)
602 ty::TyArray(ty, _) => {
603 self.check_type_for_ffi(cache, ty)
606 ty::TyBareFn(None, bare_fn) => {
610 abi::PlatformIntrinsic |
613 "found function pointer with Rust calling \
614 convention in foreign module; consider using an \
615 `extern` function pointer")
620 let sig = cx.erase_late_bound_regions(&bare_fn.sig);
622 ty::FnDiverging => {}
623 ty::FnConverging(output) => {
624 if !output.is_nil() {
625 let r = self.check_type_for_ffi(cache, output);
633 for arg in sig.inputs {
634 let r = self.check_type_for_ffi(cache, arg);
643 ty::TyParam(..) | ty::TyInfer(..) | ty::TyError |
644 ty::TyClosure(..) | ty::TyProjection(..) |
645 ty::TyBareFn(Some(_), _) => {
646 panic!("Unexpected type in foreign function")
651 fn check_def(&mut self, sp: Span, id: ast::NodeId) {
652 let tty = ast_ty_to_normalized(self.cx.tcx, id);
654 match ImproperCTypesVisitor::check_type_for_ffi(self, &mut FnvHashSet(), tty) {
655 FfiResult::FfiSafe => {}
656 FfiResult::FfiUnsafe(s) => {
657 self.cx.span_lint(IMPROPER_CTYPES, sp, s);
659 FfiResult::FfiBadStruct(_, s) => {
660 // FIXME: This diagnostic is difficult to read, and doesn't
661 // point at the relevant field.
662 self.cx.span_lint(IMPROPER_CTYPES, sp,
663 &format!("found non-foreign-function-safe member in \
664 struct marked #[repr(C)]: {}", s));
666 FfiResult::FfiBadEnum(_, s) => {
667 // FIXME: This diagnostic is difficult to read, and doesn't
668 // point at the relevant variant.
669 self.cx.span_lint(IMPROPER_CTYPES, sp,
670 &format!("found non-foreign-function-safe member in \
677 impl<'a, 'tcx, 'v> Visitor<'v> for ImproperCTypesVisitor<'a, 'tcx> {
678 fn visit_ty(&mut self, ty: &hir::Ty) {
681 hir::TyBareFn(..) => self.check_def(ty.span, ty.id),
683 self.cx.span_lint(IMPROPER_CTYPES, ty.span,
684 "found Rust slice type in foreign module, consider \
685 using a raw pointer instead");
687 hir::TyFixedLengthVec(ref ty, _) => self.visit_ty(ty),
689 self.cx.span_lint(IMPROPER_CTYPES, ty.span,
690 "found Rust tuple type in foreign module; \
691 consider using a struct instead`")
693 _ => visit::walk_ty(self, ty)
698 #[derive(Copy, Clone)]
699 pub struct ImproperCTypes;
701 impl LintPass for ImproperCTypes {
702 fn get_lints(&self) -> LintArray {
703 lint_array!(IMPROPER_CTYPES)
706 fn check_item(&mut self, cx: &Context, it: &hir::Item) {
707 fn check_ty(cx: &Context, ty: &hir::Ty) {
708 let mut vis = ImproperCTypesVisitor { cx: cx };
712 fn check_foreign_fn(cx: &Context, decl: &hir::FnDecl) {
713 for input in &decl.inputs {
714 check_ty(cx, &*input.ty);
716 if let hir::Return(ref ret_ty) = decl.output {
717 let tty = ast_ty_to_normalized(cx.tcx, ret_ty.id);
719 check_ty(cx, &ret_ty);
725 hir::ItemForeignMod(ref nmod)
726 if nmod.abi != abi::RustIntrinsic &&
727 nmod.abi != abi::PlatformIntrinsic => {
728 for ni in &nmod.items {
730 hir::ForeignItemFn(ref decl, _) => check_foreign_fn(cx, &**decl),
731 hir::ForeignItemStatic(ref t, _) => check_ty(cx, &**t)
743 "use of owned (Box type) heap memory"
746 #[derive(Copy, Clone)]
747 pub struct BoxPointers;
750 fn check_heap_type<'a, 'tcx>(&self, cx: &Context<'a, 'tcx>,
751 span: Span, ty: Ty<'tcx>) {
752 for leaf_ty in ty.walk() {
753 if let ty::TyBox(_) = leaf_ty.sty {
754 let m = format!("type uses owned (Box type) pointers: {}", ty);
755 cx.span_lint(BOX_POINTERS, span, &m);
761 impl LintPass for BoxPointers {
762 fn get_lints(&self) -> LintArray {
763 lint_array!(BOX_POINTERS)
766 fn check_item(&mut self, cx: &Context, it: &hir::Item) {
771 hir::ItemStruct(..) =>
772 self.check_heap_type(cx, it.span,
773 cx.tcx.node_id_to_type(it.id)),
777 // If it's a struct, we also have to check the fields' types
779 hir::ItemStruct(ref struct_def, _) => {
780 for struct_field in &struct_def.fields {
781 self.check_heap_type(cx, struct_field.span,
782 cx.tcx.node_id_to_type(struct_field.node.id));
789 fn check_expr(&mut self, cx: &Context, e: &hir::Expr) {
790 let ty = cx.tcx.node_id_to_type(e.id);
791 self.check_heap_type(cx, e.span, ty);
798 "uses of #[derive] with raw pointers are rarely correct"
801 struct RawPtrDeriveVisitor<'a, 'tcx: 'a> {
802 cx: &'a Context<'a, 'tcx>
805 impl<'a, 'tcx, 'v> Visitor<'v> for RawPtrDeriveVisitor<'a, 'tcx> {
806 fn visit_ty(&mut self, ty: &hir::Ty) {
807 const MSG: &'static str = "use of `#[derive]` with a raw pointer";
808 if let hir::TyPtr(..) = ty.node {
809 self.cx.span_lint(RAW_POINTER_DERIVE, ty.span, MSG);
811 visit::walk_ty(self, ty);
813 // explicit override to a no-op to reduce code bloat
814 fn visit_expr(&mut self, _: &hir::Expr) {}
815 fn visit_block(&mut self, _: &hir::Block) {}
818 pub struct RawPointerDerive {
819 checked_raw_pointers: NodeSet,
822 impl RawPointerDerive {
823 pub fn new() -> RawPointerDerive {
825 checked_raw_pointers: NodeSet(),
830 impl LintPass for RawPointerDerive {
831 fn get_lints(&self) -> LintArray {
832 lint_array!(RAW_POINTER_DERIVE)
835 fn check_item(&mut self, cx: &Context, item: &hir::Item) {
836 if !attr::contains_name(&item.attrs, "automatically_derived") {
839 let did = match item.node {
840 hir::ItemImpl(_, _, _, ref t_ref_opt, _, _) => {
841 // Deriving the Copy trait does not cause a warning
842 if let &Some(ref trait_ref) = t_ref_opt {
843 let def_id = cx.tcx.trait_ref_to_def_id(trait_ref);
844 if Some(def_id) == cx.tcx.lang_items.copy_trait() {
849 match cx.tcx.node_id_to_type(item.id).sty {
850 ty::TyEnum(def, _) => def.did,
851 ty::TyStruct(def, _) => def.did,
860 let item = match cx.tcx.map.find(did.node) {
861 Some(hir_map::NodeItem(item)) => item,
864 if !self.checked_raw_pointers.insert(item.id) {
868 hir::ItemStruct(..) | hir::ItemEnum(..) => {
869 let mut visitor = RawPtrDeriveVisitor { cx: cx };
870 visit::walk_item(&mut visitor, &item);
880 "detects attributes that were not used by the compiler"
883 #[derive(Copy, Clone)]
884 pub struct UnusedAttributes;
886 impl LintPass for UnusedAttributes {
887 fn get_lints(&self) -> LintArray {
888 lint_array!(UNUSED_ATTRIBUTES)
891 fn check_attribute(&mut self, cx: &Context, attr: &ast::Attribute) {
892 // Note that check_name() marks the attribute as used if it matches.
893 for &(ref name, ty, _) in KNOWN_ATTRIBUTES {
895 AttributeType::Whitelisted if attr.check_name(name) => {
902 let plugin_attributes = cx.sess().plugin_attributes.borrow_mut();
903 for &(ref name, ty) in plugin_attributes.iter() {
904 if ty == AttributeType::Whitelisted && attr.check_name(&*name) {
909 if !attr::is_used(attr) {
910 cx.span_lint(UNUSED_ATTRIBUTES, attr.span, "unused attribute");
911 // Is it a builtin attribute that must be used at the crate level?
912 let known_crate = KNOWN_ATTRIBUTES.iter().find(|&&(name, ty, _)| {
913 attr.name() == name &&
914 ty == AttributeType::CrateLevel
917 // Has a plugin registered this attribute as one which must be used at
919 let plugin_crate = plugin_attributes.iter()
920 .find(|&&(ref x, t)| {
921 &*attr.name() == &*x &&
922 AttributeType::CrateLevel == t
924 if known_crate || plugin_crate {
925 let msg = match attr.node.style {
926 ast::AttrOuter => "crate-level attribute should be an inner \
927 attribute: add an exclamation mark: #![foo]",
928 ast::AttrInner => "crate-level attribute should be in the \
931 cx.span_lint(UNUSED_ATTRIBUTES, attr.span, msg);
940 "path statements with no effect"
943 #[derive(Copy, Clone)]
944 pub struct PathStatements;
946 impl LintPass for PathStatements {
947 fn get_lints(&self) -> LintArray {
948 lint_array!(PATH_STATEMENTS)
951 fn check_stmt(&mut self, cx: &Context, s: &hir::Stmt) {
953 hir::StmtSemi(ref expr, _) => {
955 hir::ExprPath(..) => cx.span_lint(PATH_STATEMENTS, s.span,
956 "path statement with no effect"),
968 "unused result of a type flagged as #[must_use]"
974 "unused result of an expression in a statement"
977 #[derive(Copy, Clone)]
978 pub struct UnusedResults;
980 impl LintPass for UnusedResults {
981 fn get_lints(&self) -> LintArray {
982 lint_array!(UNUSED_MUST_USE, UNUSED_RESULTS)
985 fn check_stmt(&mut self, cx: &Context, s: &hir::Stmt) {
986 let expr = match s.node {
987 hir::StmtSemi(ref expr, _) => &**expr,
991 if let hir::ExprRet(..) = expr.node {
995 let t = cx.tcx.expr_ty(&expr);
996 let warned = match t.sty {
997 ty::TyTuple(ref tys) if tys.is_empty() => return,
998 ty::TyBool => return,
999 ty::TyStruct(def, _) |
1000 ty::TyEnum(def, _) => {
1001 if def.did.is_local() {
1002 if let hir_map::NodeItem(it) = cx.tcx.map.get(def.did.node) {
1003 check_must_use(cx, &it.attrs, s.span)
1008 let attrs = csearch::get_item_attrs(&cx.sess().cstore, def.did);
1009 check_must_use(cx, &attrs[..], s.span)
1015 cx.span_lint(UNUSED_RESULTS, s.span, "unused result");
1018 fn check_must_use(cx: &Context, attrs: &[ast::Attribute], sp: Span) -> bool {
1020 if attr.check_name("must_use") {
1021 let mut msg = "unused result which must be used".to_string();
1022 // check for #[must_use="..."]
1023 match attr.value_str() {
1030 cx.span_lint(UNUSED_MUST_USE, sp, &msg);
1040 pub NON_CAMEL_CASE_TYPES,
1042 "types, variants, traits and type parameters should have camel case names"
1045 #[derive(Copy, Clone)]
1046 pub struct NonCamelCaseTypes;
1048 impl NonCamelCaseTypes {
1049 fn check_case(&self, cx: &Context, sort: &str, ident: ast::Ident, span: Span) {
1050 fn is_camel_case(ident: ast::Ident) -> bool {
1051 let ident = ident.name.as_str();
1052 if ident.is_empty() {
1055 let ident = ident.trim_matches('_');
1057 // start with a non-lowercase letter rather than non-uppercase
1058 // ones (some scripts don't have a concept of upper/lowercase)
1059 !ident.is_empty() && !ident.char_at(0).is_lowercase() && !ident.contains('_')
1062 fn to_camel_case(s: &str) -> String {
1063 s.split('_').flat_map(|word| word.chars().enumerate().map(|(i, c)|
1065 c.to_uppercase().collect::<String>()
1067 c.to_lowercase().collect()
1069 )).collect::<Vec<_>>().concat()
1072 let s = ident.name.as_str();
1074 if !is_camel_case(ident) {
1075 let c = to_camel_case(&s);
1076 let m = if c.is_empty() {
1077 format!("{} `{}` should have a camel case name such as `CamelCase`", sort, s)
1079 format!("{} `{}` should have a camel case name such as `{}`", sort, s, c)
1081 cx.span_lint(NON_CAMEL_CASE_TYPES, span, &m[..]);
1086 impl LintPass for NonCamelCaseTypes {
1087 fn get_lints(&self) -> LintArray {
1088 lint_array!(NON_CAMEL_CASE_TYPES)
1091 fn check_item(&mut self, cx: &Context, it: &hir::Item) {
1092 let extern_repr_count = it.attrs.iter().filter(|attr| {
1093 attr::find_repr_attrs(cx.tcx.sess.diagnostic(), attr).iter()
1094 .any(|r| r == &attr::ReprExtern)
1096 let has_extern_repr = extern_repr_count > 0;
1098 if has_extern_repr {
1103 hir::ItemTy(..) | hir::ItemStruct(..) => {
1104 self.check_case(cx, "type", it.ident, it.span)
1106 hir::ItemTrait(..) => {
1107 self.check_case(cx, "trait", it.ident, it.span)
1109 hir::ItemEnum(ref enum_definition, _) => {
1110 if has_extern_repr {
1113 self.check_case(cx, "type", it.ident, it.span);
1114 for variant in &enum_definition.variants {
1115 self.check_case(cx, "variant", variant.node.name, variant.span);
1122 fn check_generics(&mut self, cx: &Context, it: &hir::Generics) {
1123 for gen in it.ty_params.iter() {
1124 self.check_case(cx, "type parameter", gen.ident, gen.span);
1129 #[derive(PartialEq)]
1130 enum MethodContext {
1136 fn method_context(cx: &Context, id: ast::NodeId, span: Span) -> MethodContext {
1137 match cx.tcx.impl_or_trait_items.borrow().get(&DefId::local(id)) {
1138 None => cx.sess().span_bug(span, "missing method descriptor?!"),
1139 Some(item) => match item.container() {
1140 ty::TraitContainer(..) => MethodContext::TraitDefaultImpl,
1141 ty::ImplContainer(cid) => {
1142 match cx.tcx.impl_trait_ref(cid) {
1143 Some(_) => MethodContext::TraitImpl,
1144 None => MethodContext::PlainImpl
1154 "methods, functions, lifetime parameters and modules should have snake case names"
1157 #[derive(Copy, Clone)]
1158 pub struct NonSnakeCase;
1161 fn to_snake_case(mut str: &str) -> String {
1162 let mut words = vec![];
1163 // Preserve leading underscores
1164 str = str.trim_left_matches(|c: char| {
1166 words.push(String::new());
1172 for s in str.split('_') {
1173 let mut last_upper = false;
1174 let mut buf = String::new();
1178 for ch in s.chars() {
1179 if !buf.is_empty() && buf != "'"
1180 && ch.is_uppercase()
1183 buf = String::new();
1185 last_upper = ch.is_uppercase();
1186 buf.extend(ch.to_lowercase());
1193 fn check_snake_case(&self, cx: &Context, sort: &str, name: &str, span: Option<Span>) {
1194 fn is_snake_case(ident: &str) -> bool {
1195 if ident.is_empty() {
1198 let ident = ident.trim_left_matches('\'');
1199 let ident = ident.trim_matches('_');
1201 let mut allow_underscore = true;
1202 ident.chars().all(|c| {
1203 allow_underscore = match c {
1204 '_' if !allow_underscore => return false,
1206 // It would be more obvious to use `c.is_lowercase()`,
1207 // but some characters do not have a lowercase form
1208 c if !c.is_uppercase() => true,
1215 if !is_snake_case(name) {
1216 let sc = NonSnakeCase::to_snake_case(name);
1217 let msg = if sc != name {
1218 format!("{} `{}` should have a snake case name such as `{}`",
1221 format!("{} `{}` should have a snake case name",
1225 Some(span) => cx.span_lint(NON_SNAKE_CASE, span, &msg),
1226 None => cx.lint(NON_SNAKE_CASE, &msg),
1232 impl LintPass for NonSnakeCase {
1233 fn get_lints(&self) -> LintArray {
1234 lint_array!(NON_SNAKE_CASE)
1237 fn check_crate(&mut self, cx: &Context, cr: &hir::Crate) {
1238 let attr_crate_name = cr.attrs.iter().find(|at| at.check_name("crate_name"))
1239 .and_then(|at| at.value_str().map(|s| (at, s)));
1240 if let Some(ref name) = cx.tcx.sess.opts.crate_name {
1241 self.check_snake_case(cx, "crate", name, None);
1242 } else if let Some((attr, ref name)) = attr_crate_name {
1243 self.check_snake_case(cx, "crate", name, Some(attr.span));
1247 fn check_fn(&mut self, cx: &Context,
1248 fk: FnKind, _: &hir::FnDecl,
1249 _: &hir::Block, span: Span, id: ast::NodeId) {
1251 FnKind::Method(ident, _, _) => match method_context(cx, id, span) {
1252 MethodContext::PlainImpl => {
1253 self.check_snake_case(cx, "method", &ident.name.as_str(), Some(span))
1255 MethodContext::TraitDefaultImpl => {
1256 self.check_snake_case(cx, "trait method", &ident.name.as_str(), Some(span))
1260 FnKind::ItemFn(ident, _, _, _, _, _) => {
1261 self.check_snake_case(cx, "function", &ident.name.as_str(), Some(span))
1267 fn check_item(&mut self, cx: &Context, it: &hir::Item) {
1268 if let hir::ItemMod(_) = it.node {
1269 self.check_snake_case(cx, "module", &it.ident.name.as_str(), Some(it.span));
1273 fn check_trait_item(&mut self, cx: &Context, trait_item: &hir::TraitItem) {
1274 if let hir::MethodTraitItem(_, None) = trait_item.node {
1275 self.check_snake_case(cx, "trait method", &trait_item.ident.name.as_str(),
1276 Some(trait_item.span));
1280 fn check_lifetime_def(&mut self, cx: &Context, t: &hir::LifetimeDef) {
1281 self.check_snake_case(cx, "lifetime", &t.lifetime.name.as_str(),
1282 Some(t.lifetime.span));
1285 fn check_pat(&mut self, cx: &Context, p: &hir::Pat) {
1286 if let &hir::PatIdent(_, ref path1, _) = &p.node {
1287 let def = cx.tcx.def_map.borrow().get(&p.id).map(|d| d.full_def());
1288 if let Some(def::DefLocal(_)) = def {
1289 self.check_snake_case(cx, "variable", &path1.node.name.as_str(), Some(p.span));
1294 fn check_struct_def(&mut self, cx: &Context, s: &hir::StructDef,
1295 _: ast::Ident, _: &hir::Generics, _: ast::NodeId) {
1296 for sf in &s.fields {
1297 if let hir::StructField_ { kind: hir::NamedField(ident, _), .. } = sf.node {
1298 self.check_snake_case(cx, "structure field", &ident.name.as_str(),
1306 pub NON_UPPER_CASE_GLOBALS,
1308 "static constants should have uppercase identifiers"
1311 #[derive(Copy, Clone)]
1312 pub struct NonUpperCaseGlobals;
1314 impl NonUpperCaseGlobals {
1315 fn check_upper_case(cx: &Context, sort: &str, ident: ast::Ident, span: Span) {
1316 let s = ident.name.as_str();
1318 if s.chars().any(|c| c.is_lowercase()) {
1319 let uc = NonSnakeCase::to_snake_case(&s).to_uppercase();
1321 cx.span_lint(NON_UPPER_CASE_GLOBALS, span,
1322 &format!("{} `{}` should have an upper case name such as `{}`",
1325 cx.span_lint(NON_UPPER_CASE_GLOBALS, span,
1326 &format!("{} `{}` should have an upper case name",
1333 impl LintPass for NonUpperCaseGlobals {
1334 fn get_lints(&self) -> LintArray {
1335 lint_array!(NON_UPPER_CASE_GLOBALS)
1338 fn check_item(&mut self, cx: &Context, it: &hir::Item) {
1340 // only check static constants
1341 hir::ItemStatic(_, hir::MutImmutable, _) => {
1342 NonUpperCaseGlobals::check_upper_case(cx, "static constant", it.ident, it.span);
1344 hir::ItemConst(..) => {
1345 NonUpperCaseGlobals::check_upper_case(cx, "constant", it.ident, it.span);
1351 fn check_trait_item(&mut self, cx: &Context, ti: &hir::TraitItem) {
1353 hir::ConstTraitItem(..) => {
1354 NonUpperCaseGlobals::check_upper_case(cx, "associated constant",
1361 fn check_impl_item(&mut self, cx: &Context, ii: &hir::ImplItem) {
1363 hir::ConstImplItem(..) => {
1364 NonUpperCaseGlobals::check_upper_case(cx, "associated constant",
1371 fn check_pat(&mut self, cx: &Context, p: &hir::Pat) {
1372 // Lint for constants that look like binding identifiers (#7526)
1373 match (&p.node, cx.tcx.def_map.borrow().get(&p.id).map(|d| d.full_def())) {
1374 (&hir::PatIdent(_, ref path1, _), Some(def::DefConst(..))) => {
1375 NonUpperCaseGlobals::check_upper_case(cx, "constant in pattern",
1376 path1.node, p.span);
1386 "`if`, `match`, `while` and `return` do not need parentheses"
1389 #[derive(Copy, Clone)]
1390 pub struct UnusedParens;
1393 fn check_unused_parens_core(&self, cx: &Context, value: &hir::Expr, msg: &str,
1394 struct_lit_needs_parens: bool) {
1395 if let hir::ExprParen(ref inner) = value.node {
1396 let necessary = struct_lit_needs_parens && contains_exterior_struct_lit(&**inner);
1398 cx.span_lint(UNUSED_PARENS, value.span,
1399 &format!("unnecessary parentheses around {}", msg))
1403 /// Expressions that syntactically contain an "exterior" struct
1404 /// literal i.e. not surrounded by any parens or other
1405 /// delimiters, e.g. `X { y: 1 }`, `X { y: 1 }.method()`, `foo
1406 /// == X { y: 1 }` and `X { y: 1 } == foo` all do, but `(X {
1407 /// y: 1 }) == foo` does not.
1408 fn contains_exterior_struct_lit(value: &hir::Expr) -> bool {
1410 hir::ExprStruct(..) => true,
1412 hir::ExprAssign(ref lhs, ref rhs) |
1413 hir::ExprAssignOp(_, ref lhs, ref rhs) |
1414 hir::ExprBinary(_, ref lhs, ref rhs) => {
1415 // X { y: 1 } + X { y: 2 }
1416 contains_exterior_struct_lit(&**lhs) ||
1417 contains_exterior_struct_lit(&**rhs)
1419 hir::ExprUnary(_, ref x) |
1420 hir::ExprCast(ref x, _) |
1421 hir::ExprField(ref x, _) |
1422 hir::ExprTupField(ref x, _) |
1423 hir::ExprIndex(ref x, _) => {
1424 // &X { y: 1 }, X { y: 1 }.y
1425 contains_exterior_struct_lit(&**x)
1428 hir::ExprMethodCall(_, _, ref exprs) => {
1429 // X { y: 1 }.bar(...)
1430 contains_exterior_struct_lit(&*exprs[0])
1439 impl LintPass for UnusedParens {
1440 fn get_lints(&self) -> LintArray {
1441 lint_array!(UNUSED_PARENS)
1444 fn check_expr(&mut self, cx: &Context, e: &hir::Expr) {
1445 let (value, msg, struct_lit_needs_parens) = match e.node {
1446 hir::ExprIf(ref cond, _, _) => (cond, "`if` condition", true),
1447 hir::ExprWhile(ref cond, _, _) => (cond, "`while` condition", true),
1448 hir::ExprMatch(ref head, _, source) => match source {
1449 hir::MatchSource::Normal => (head, "`match` head expression", true),
1450 hir::MatchSource::IfLetDesugar { .. } => (head, "`if let` head expression", true),
1451 hir::MatchSource::WhileLetDesugar => (head, "`while let` head expression", true),
1452 hir::MatchSource::ForLoopDesugar => (head, "`for` head expression", true),
1454 hir::ExprRet(Some(ref value)) => (value, "`return` value", false),
1455 hir::ExprAssign(_, ref value) => (value, "assigned value", false),
1456 hir::ExprAssignOp(_, _, ref value) => (value, "assigned value", false),
1459 self.check_unused_parens_core(cx, &**value, msg, struct_lit_needs_parens);
1462 fn check_stmt(&mut self, cx: &Context, s: &hir::Stmt) {
1463 let (value, msg) = match s.node {
1464 hir::StmtDecl(ref decl, _) => match decl.node {
1465 hir::DeclLocal(ref local) => match local.init {
1466 Some(ref value) => (value, "assigned value"),
1473 self.check_unused_parens_core(cx, &**value, msg, false);
1478 UNUSED_IMPORT_BRACES,
1480 "unnecessary braces around an imported item"
1483 #[derive(Copy, Clone)]
1484 pub struct UnusedImportBraces;
1486 impl LintPass for UnusedImportBraces {
1487 fn get_lints(&self) -> LintArray {
1488 lint_array!(UNUSED_IMPORT_BRACES)
1491 fn check_item(&mut self, cx: &Context, item: &hir::Item) {
1492 if let hir::ItemUse(ref view_path) = item.node {
1493 if let hir::ViewPathList(_, ref items) = view_path.node {
1494 if items.len() == 1 {
1495 if let hir::PathListIdent {ref name, ..} = items[0].node {
1496 let m = format!("braces around {} is unnecessary",
1498 cx.span_lint(UNUSED_IMPORT_BRACES, item.span,
1508 NON_SHORTHAND_FIELD_PATTERNS,
1510 "using `Struct { x: x }` instead of `Struct { x }`"
1513 #[derive(Copy, Clone)]
1514 pub struct NonShorthandFieldPatterns;
1516 impl LintPass for NonShorthandFieldPatterns {
1517 fn get_lints(&self) -> LintArray {
1518 lint_array!(NON_SHORTHAND_FIELD_PATTERNS)
1521 fn check_pat(&mut self, cx: &Context, pat: &hir::Pat) {
1522 let def_map = cx.tcx.def_map.borrow();
1523 if let hir::PatStruct(_, ref v, _) = pat.node {
1524 let field_pats = v.iter().filter(|fieldpat| {
1525 if fieldpat.node.is_shorthand {
1528 let def = def_map.get(&fieldpat.node.pat.id).map(|d| d.full_def());
1529 def == Some(def::DefLocal(fieldpat.node.pat.id))
1531 for fieldpat in field_pats {
1532 if let hir::PatIdent(_, ident, None) = fieldpat.node.pat.node {
1533 if ident.node.name == fieldpat.node.ident.name {
1534 // FIXME: should this comparison really be done on the name?
1535 // doing it on the ident will fail during compilation of libcore
1536 cx.span_lint(NON_SHORTHAND_FIELD_PATTERNS, fieldpat.span,
1537 &format!("the `{}:` in this pattern is redundant and can \
1538 be removed", ident.node))
1549 "unnecessary use of an `unsafe` block"
1552 #[derive(Copy, Clone)]
1553 pub struct UnusedUnsafe;
1555 impl LintPass for UnusedUnsafe {
1556 fn get_lints(&self) -> LintArray {
1557 lint_array!(UNUSED_UNSAFE)
1560 fn check_expr(&mut self, cx: &Context, e: &hir::Expr) {
1561 if let hir::ExprBlock(ref blk) = e.node {
1562 // Don't warn about generated blocks, that'll just pollute the output.
1563 if blk.rules == hir::UnsafeBlock(hir::UserProvided) &&
1564 !cx.tcx.used_unsafe.borrow().contains(&blk.id) {
1565 cx.span_lint(UNUSED_UNSAFE, blk.span, "unnecessary `unsafe` block");
1574 "usage of `unsafe` code"
1577 #[derive(Copy, Clone)]
1578 pub struct UnsafeCode;
1580 impl LintPass for UnsafeCode {
1581 fn get_lints(&self) -> LintArray {
1582 lint_array!(UNSAFE_CODE)
1585 fn check_expr(&mut self, cx: &Context, e: &hir::Expr) {
1586 if let hir::ExprBlock(ref blk) = e.node {
1587 // Don't warn about generated blocks, that'll just pollute the output.
1588 if blk.rules == hir::UnsafeBlock(hir::UserProvided) {
1589 cx.span_lint(UNSAFE_CODE, blk.span, "usage of an `unsafe` block");
1594 fn check_item(&mut self, cx: &Context, it: &hir::Item) {
1596 hir::ItemTrait(hir::Unsafety::Unsafe, _, _, _) =>
1597 cx.span_lint(UNSAFE_CODE, it.span, "declaration of an `unsafe` trait"),
1599 hir::ItemImpl(hir::Unsafety::Unsafe, _, _, _, _, _) =>
1600 cx.span_lint(UNSAFE_CODE, it.span, "implementation of an `unsafe` trait"),
1606 fn check_fn(&mut self, cx: &Context, fk: FnKind, _: &hir::FnDecl,
1607 _: &hir::Block, span: Span, _: ast::NodeId) {
1609 FnKind::ItemFn(_, _, hir::Unsafety::Unsafe, _, _, _) =>
1610 cx.span_lint(UNSAFE_CODE, span, "declaration of an `unsafe` function"),
1612 FnKind::Method(_, sig, _) => {
1613 if sig.unsafety == hir::Unsafety::Unsafe {
1614 cx.span_lint(UNSAFE_CODE, span, "implementation of an `unsafe` method")
1622 fn check_trait_item(&mut self, cx: &Context, trait_item: &hir::TraitItem) {
1623 if let hir::MethodTraitItem(ref sig, None) = trait_item.node {
1624 if sig.unsafety == hir::Unsafety::Unsafe {
1625 cx.span_lint(UNSAFE_CODE, trait_item.span,
1626 "declaration of an `unsafe` method")
1635 "detect mut variables which don't need to be mutable"
1638 #[derive(Copy, Clone)]
1639 pub struct UnusedMut;
1642 fn check_unused_mut_pat(&self, cx: &Context, pats: &[P<hir::Pat>]) {
1643 // collect all mutable pattern and group their NodeIDs by their Identifier to
1644 // avoid false warnings in match arms with multiple patterns
1646 let mut mutables = FnvHashMap();
1648 pat_util::pat_bindings(&cx.tcx.def_map, p, |mode, id, _, path1| {
1649 let ident = path1.node;
1650 if let hir::BindByValue(hir::MutMutable) = mode {
1651 if !ident.name.as_str().starts_with("_") {
1652 match mutables.entry(ident.name.usize()) {
1653 Vacant(entry) => { entry.insert(vec![id]); },
1654 Occupied(mut entry) => { entry.get_mut().push(id); },
1661 let used_mutables = cx.tcx.used_mut_nodes.borrow();
1662 for (_, v) in &mutables {
1663 if !v.iter().any(|e| used_mutables.contains(e)) {
1664 cx.span_lint(UNUSED_MUT, cx.tcx.map.span(v[0]),
1665 "variable does not need to be mutable");
1671 impl LintPass for UnusedMut {
1672 fn get_lints(&self) -> LintArray {
1673 lint_array!(UNUSED_MUT)
1676 fn check_expr(&mut self, cx: &Context, e: &hir::Expr) {
1677 if let hir::ExprMatch(_, ref arms, _) = e.node {
1679 self.check_unused_mut_pat(cx, &a.pats)
1684 fn check_stmt(&mut self, cx: &Context, s: &hir::Stmt) {
1685 if let hir::StmtDecl(ref d, _) = s.node {
1686 if let hir::DeclLocal(ref l) = d.node {
1687 self.check_unused_mut_pat(cx, slice::ref_slice(&l.pat));
1692 fn check_fn(&mut self, cx: &Context,
1693 _: FnKind, decl: &hir::FnDecl,
1694 _: &hir::Block, _: Span, _: ast::NodeId) {
1695 for a in &decl.inputs {
1696 self.check_unused_mut_pat(cx, slice::ref_slice(&a.pat));
1704 "detects unnecessary allocations that can be eliminated"
1707 #[derive(Copy, Clone)]
1708 pub struct UnusedAllocation;
1710 impl LintPass for UnusedAllocation {
1711 fn get_lints(&self) -> LintArray {
1712 lint_array!(UNUSED_ALLOCATION)
1715 fn check_expr(&mut self, cx: &Context, e: &hir::Expr) {
1717 hir::ExprUnary(hir::UnUniq, _) => (),
1721 if let Some(adjustment) = cx.tcx.tables.borrow().adjustments.get(&e.id) {
1722 if let adjustment::AdjustDerefRef(adjustment::AutoDerefRef {
1726 &Some(adjustment::AutoPtr(_, hir::MutImmutable)) => {
1727 cx.span_lint(UNUSED_ALLOCATION, e.span,
1728 "unnecessary allocation, use & instead");
1730 &Some(adjustment::AutoPtr(_, hir::MutMutable)) => {
1731 cx.span_lint(UNUSED_ALLOCATION, e.span,
1732 "unnecessary allocation, use &mut instead");
1744 "detects missing documentation for public members"
1747 pub struct MissingDoc {
1748 /// Stack of IDs of struct definitions.
1749 struct_def_stack: Vec<ast::NodeId>,
1751 /// True if inside variant definition
1754 /// Stack of whether #[doc(hidden)] is set
1755 /// at each level which has lint attributes.
1756 doc_hidden_stack: Vec<bool>,
1758 /// Private traits or trait items that leaked through. Don't check their methods.
1759 private_traits: HashSet<ast::NodeId>,
1763 pub fn new() -> MissingDoc {
1765 struct_def_stack: vec!(),
1767 doc_hidden_stack: vec!(false),
1768 private_traits: HashSet::new(),
1772 fn doc_hidden(&self) -> bool {
1773 *self.doc_hidden_stack.last().expect("empty doc_hidden_stack")
1776 fn check_missing_docs_attrs(&self,
1778 id: Option<ast::NodeId>,
1779 attrs: &[ast::Attribute],
1781 desc: &'static str) {
1782 // If we're building a test harness, then warning about
1783 // documentation is probably not really relevant right now.
1784 if cx.sess().opts.test {
1788 // `#[doc(hidden)]` disables missing_docs check.
1789 if self.doc_hidden() {
1793 // Only check publicly-visible items, using the result from the privacy pass.
1794 // It's an option so the crate root can also use this function (it doesn't
1796 if let Some(ref id) = id {
1797 if !cx.exported_items.contains(id) {
1802 let has_doc = attrs.iter().any(|a| {
1803 match a.node.value.node {
1804 ast::MetaNameValue(ref name, _) if *name == "doc" => true,
1809 cx.span_lint(MISSING_DOCS, sp,
1810 &format!("missing documentation for {}", desc));
1815 impl LintPass for MissingDoc {
1816 fn get_lints(&self) -> LintArray {
1817 lint_array!(MISSING_DOCS)
1820 fn enter_lint_attrs(&mut self, _: &Context, attrs: &[ast::Attribute]) {
1821 let doc_hidden = self.doc_hidden() || attrs.iter().any(|attr| {
1822 attr.check_name("doc") && match attr.meta_item_list() {
1824 Some(l) => attr::contains_name(&l[..], "hidden"),
1827 self.doc_hidden_stack.push(doc_hidden);
1830 fn exit_lint_attrs(&mut self, _: &Context, _: &[ast::Attribute]) {
1831 self.doc_hidden_stack.pop().expect("empty doc_hidden_stack");
1834 fn check_struct_def(&mut self, _: &Context, _: &hir::StructDef,
1835 _: ast::Ident, _: &hir::Generics, id: ast::NodeId) {
1836 self.struct_def_stack.push(id);
1839 fn check_struct_def_post(&mut self, _: &Context, _: &hir::StructDef,
1840 _: ast::Ident, _: &hir::Generics, id: ast::NodeId) {
1841 let popped = self.struct_def_stack.pop().expect("empty struct_def_stack");
1842 assert!(popped == id);
1845 fn check_crate(&mut self, cx: &Context, krate: &hir::Crate) {
1846 self.check_missing_docs_attrs(cx, None, &krate.attrs, krate.span, "crate");
1849 fn check_item(&mut self, cx: &Context, it: &hir::Item) {
1850 let desc = match it.node {
1851 hir::ItemFn(..) => "a function",
1852 hir::ItemMod(..) => "a module",
1853 hir::ItemEnum(..) => "an enum",
1854 hir::ItemStruct(..) => "a struct",
1855 hir::ItemTrait(_, _, _, ref items) => {
1856 // Issue #11592, traits are always considered exported, even when private.
1857 if it.vis == hir::Visibility::Inherited {
1858 self.private_traits.insert(it.id);
1860 self.private_traits.insert(itm.id);
1866 hir::ItemTy(..) => "a type alias",
1867 hir::ItemImpl(_, _, _, Some(ref trait_ref), _, ref impl_items) => {
1868 // If the trait is private, add the impl items to private_traits so they don't get
1869 // reported for missing docs.
1870 let real_trait = cx.tcx.trait_ref_to_def_id(trait_ref);
1871 match cx.tcx.map.find(real_trait.node) {
1872 Some(hir_map::NodeItem(item)) => if item.vis == hir::Visibility::Inherited {
1873 for itm in impl_items {
1874 self.private_traits.insert(itm.id);
1881 hir::ItemConst(..) => "a constant",
1882 hir::ItemStatic(..) => "a static",
1886 self.check_missing_docs_attrs(cx, Some(it.id), &it.attrs, it.span, desc);
1889 fn check_trait_item(&mut self, cx: &Context, trait_item: &hir::TraitItem) {
1890 if self.private_traits.contains(&trait_item.id) { return }
1892 let desc = match trait_item.node {
1893 hir::ConstTraitItem(..) => "an associated constant",
1894 hir::MethodTraitItem(..) => "a trait method",
1895 hir::TypeTraitItem(..) => "an associated type",
1898 self.check_missing_docs_attrs(cx, Some(trait_item.id),
1900 trait_item.span, desc);
1903 fn check_impl_item(&mut self, cx: &Context, impl_item: &hir::ImplItem) {
1904 // If the method is an impl for a trait, don't doc.
1905 if method_context(cx, impl_item.id, impl_item.span) == MethodContext::TraitImpl {
1909 let desc = match impl_item.node {
1910 hir::ConstImplItem(..) => "an associated constant",
1911 hir::MethodImplItem(..) => "a method",
1912 hir::TypeImplItem(_) => "an associated type",
1914 self.check_missing_docs_attrs(cx, Some(impl_item.id),
1916 impl_item.span, desc);
1919 fn check_struct_field(&mut self, cx: &Context, sf: &hir::StructField) {
1920 if let hir::NamedField(_, vis) = sf.node.kind {
1921 if vis == hir::Public || self.in_variant {
1922 let cur_struct_def = *self.struct_def_stack.last()
1923 .expect("empty struct_def_stack");
1924 self.check_missing_docs_attrs(cx, Some(cur_struct_def),
1925 &sf.node.attrs, sf.span,
1931 fn check_variant(&mut self, cx: &Context, v: &hir::Variant, _: &hir::Generics) {
1932 self.check_missing_docs_attrs(cx, Some(v.node.id), &v.node.attrs, v.span, "a variant");
1933 assert!(!self.in_variant);
1934 self.in_variant = true;
1937 fn check_variant_post(&mut self, _: &Context, _: &hir::Variant, _: &hir::Generics) {
1938 assert!(self.in_variant);
1939 self.in_variant = false;
1944 pub MISSING_COPY_IMPLEMENTATIONS,
1946 "detects potentially-forgotten implementations of `Copy`"
1949 #[derive(Copy, Clone)]
1950 pub struct MissingCopyImplementations;
1952 impl LintPass for MissingCopyImplementations {
1953 fn get_lints(&self) -> LintArray {
1954 lint_array!(MISSING_COPY_IMPLEMENTATIONS)
1957 fn check_item(&mut self, cx: &Context, item: &hir::Item) {
1958 if !cx.exported_items.contains(&item.id) {
1961 let (def, ty) = match item.node {
1962 hir::ItemStruct(_, ref ast_generics) => {
1963 if ast_generics.is_parameterized() {
1966 let def = cx.tcx.lookup_adt_def(DefId::local(item.id));
1967 (def, cx.tcx.mk_struct(def,
1968 cx.tcx.mk_substs(Substs::empty())))
1970 hir::ItemEnum(_, ref ast_generics) => {
1971 if ast_generics.is_parameterized() {
1974 let def = cx.tcx.lookup_adt_def(DefId::local(item.id));
1975 (def, cx.tcx.mk_enum(def,
1976 cx.tcx.mk_substs(Substs::empty())))
1980 if def.has_dtor() { return; }
1981 let parameter_environment = cx.tcx.empty_parameter_environment();
1982 // FIXME (@jroesch) should probably inver this so that the parameter env still impls this
1984 if !ty.moves_by_default(¶meter_environment, item.span) {
1987 if parameter_environment.can_type_implement_copy(ty, item.span).is_ok() {
1988 cx.span_lint(MISSING_COPY_IMPLEMENTATIONS,
1990 "type could implement `Copy`; consider adding `impl \
1997 MISSING_DEBUG_IMPLEMENTATIONS,
1999 "detects missing implementations of fmt::Debug"
2002 pub struct MissingDebugImplementations {
2003 impling_types: Option<NodeSet>,
2006 impl MissingDebugImplementations {
2007 pub fn new() -> MissingDebugImplementations {
2008 MissingDebugImplementations {
2009 impling_types: None,
2014 impl LintPass for MissingDebugImplementations {
2015 fn get_lints(&self) -> LintArray {
2016 lint_array!(MISSING_DEBUG_IMPLEMENTATIONS)
2019 fn check_item(&mut self, cx: &Context, item: &hir::Item) {
2020 if !cx.exported_items.contains(&item.id) {
2025 hir::ItemStruct(..) | hir::ItemEnum(..) => {},
2029 let debug = match cx.tcx.lang_items.debug_trait() {
2030 Some(debug) => debug,
2034 if self.impling_types.is_none() {
2035 let debug_def = cx.tcx.lookup_trait_def(debug);
2036 let mut impls = NodeSet();
2037 debug_def.for_each_impl(cx.tcx, |d| {
2039 if let Some(ty_def) = cx.tcx.node_id_to_type(d.node).ty_to_def_id() {
2040 impls.insert(ty_def.node);
2045 self.impling_types = Some(impls);
2046 debug!("{:?}", self.impling_types);
2049 if !self.impling_types.as_ref().unwrap().contains(&item.id) {
2050 cx.span_lint(MISSING_DEBUG_IMPLEMENTATIONS,
2052 "type does not implement `fmt::Debug`; consider adding #[derive(Debug)] \
2053 or a manual implementation")
2061 "detects use of #[deprecated] items"
2064 /// Checks for use of items with `#[deprecated]` attributes
2065 #[derive(Copy, Clone)]
2066 pub struct Stability;
2069 fn lint(&self, cx: &Context, _id: DefId,
2070 span: Span, stability: &Option<&attr::Stability>) {
2071 // Deprecated attributes apply in-crate and cross-crate.
2072 let (lint, label) = match *stability {
2073 Some(&attr::Stability { deprecated_since: Some(_), .. }) =>
2074 (DEPRECATED, "deprecated"),
2078 output(cx, span, stability, lint, label);
2080 fn output(cx: &Context, span: Span, stability: &Option<&attr::Stability>,
2081 lint: &'static Lint, label: &'static str) {
2082 let msg = match *stability {
2083 Some(&attr::Stability { reason: Some(ref s), .. }) => {
2084 format!("use of {} item: {}", label, *s)
2086 _ => format!("use of {} item", label)
2089 cx.span_lint(lint, span, &msg[..]);
2094 fn hir_to_ast_stability(stab: &attr::Stability) -> attr::Stability {
2096 level: match stab.level {
2097 attr::Unstable => attr::Unstable,
2098 attr::Stable => attr::Stable,
2100 feature: stab.feature.clone(),
2101 since: stab.since.clone(),
2102 deprecated_since: stab.deprecated_since.clone(),
2103 reason: stab.reason.clone(),
2108 impl LintPass for Stability {
2109 fn get_lints(&self) -> LintArray {
2110 lint_array!(DEPRECATED)
2113 fn check_item(&mut self, cx: &Context, item: &hir::Item) {
2114 stability::check_item(cx.tcx, item, false,
2116 self.lint(cx, id, sp,
2117 &stab.map(|s| hir_to_ast_stability(s)).as_ref()));
2120 fn check_expr(&mut self, cx: &Context, e: &hir::Expr) {
2121 stability::check_expr(cx.tcx, e,
2123 self.lint(cx, id, sp,
2124 &stab.map(|s| hir_to_ast_stability(s)).as_ref()));
2127 fn check_path(&mut self, cx: &Context, path: &hir::Path, id: ast::NodeId) {
2128 stability::check_path(cx.tcx, path, id,
2130 self.lint(cx, id, sp,
2131 &stab.map(|s| hir_to_ast_stability(s)).as_ref()));
2134 fn check_pat(&mut self, cx: &Context, pat: &hir::Pat) {
2135 stability::check_pat(cx.tcx, pat,
2137 self.lint(cx, id, sp,
2138 &stab.map(|s| hir_to_ast_stability(s)).as_ref()));
2143 pub UNCONDITIONAL_RECURSION,
2145 "functions that cannot return without calling themselves"
2148 #[derive(Copy, Clone)]
2149 pub struct UnconditionalRecursion;
2152 impl LintPass for UnconditionalRecursion {
2153 fn get_lints(&self) -> LintArray {
2154 lint_array![UNCONDITIONAL_RECURSION]
2157 fn check_fn(&mut self, cx: &Context, fn_kind: FnKind, _: &hir::FnDecl,
2158 blk: &hir::Block, sp: Span, id: ast::NodeId) {
2159 type F = for<'tcx> fn(&ty::ctxt<'tcx>,
2160 ast::NodeId, ast::NodeId, ast::Ident, ast::NodeId) -> bool;
2162 let method = match fn_kind {
2163 FnKind::ItemFn(..) => None,
2164 FnKind::Method(..) => {
2165 cx.tcx.impl_or_trait_item(DefId::local(id)).as_opt_method()
2167 // closures can't recur, so they don't matter.
2168 FnKind::Closure => return
2171 // Walk through this function (say `f`) looking to see if
2172 // every possible path references itself, i.e. the function is
2173 // called recursively unconditionally. This is done by trying
2174 // to find a path from the entry node to the exit node that
2175 // *doesn't* call `f` by traversing from the entry while
2176 // pretending that calls of `f` are sinks (i.e. ignoring any
2177 // exit edges from them).
2179 // NB. this has an edge case with non-returning statements,
2180 // like `loop {}` or `panic!()`: control flow never reaches
2181 // the exit node through these, so one can have a function
2182 // that never actually calls itselfs but is still picked up by
2185 // fn f(cond: bool) {
2186 // if !cond { panic!() } // could come from `assert!(cond)`
2190 // In general, functions of that form may be able to call
2191 // itself a finite number of times and then diverge. The lint
2192 // considers this to be an error for two reasons, (a) it is
2193 // easier to implement, and (b) it seems rare to actually want
2194 // to have behaviour like the above, rather than
2195 // e.g. accidentally recurring after an assert.
2197 let cfg = cfg::CFG::new(cx.tcx, blk);
2199 let mut work_queue = vec![cfg.entry];
2200 let mut reached_exit_without_self_call = false;
2201 let mut self_call_spans = vec![];
2202 let mut visited = HashSet::new();
2204 while let Some(idx) = work_queue.pop() {
2205 if idx == cfg.exit {
2207 reached_exit_without_self_call = true;
2211 let cfg_id = idx.node_id();
2212 if visited.contains(&cfg_id) {
2216 visited.insert(cfg_id);
2218 let node_id = cfg.graph.node_data(idx).id();
2220 // is this a recursive call?
2221 let self_recursive = if node_id != ast::DUMMY_NODE_ID {
2223 Some(ref method) => {
2224 expr_refers_to_this_method(cx.tcx, method, node_id)
2226 None => expr_refers_to_this_fn(cx.tcx, id, node_id)
2232 self_call_spans.push(cx.tcx.map.span(node_id));
2233 // this is a self call, so we shouldn't explore past
2234 // this node in the CFG.
2237 // add the successors of this node to explore the graph further.
2238 for (_, edge) in cfg.graph.outgoing_edges(idx) {
2239 let target_idx = edge.target();
2240 let target_cfg_id = target_idx.node_id();
2241 if !visited.contains(&target_cfg_id) {
2242 work_queue.push(target_idx)
2247 // Check the number of self calls because a function that
2248 // doesn't return (e.g. calls a `-> !` function or `loop { /*
2249 // no break */ }`) shouldn't be linted unless it actually
2251 if !reached_exit_without_self_call && !self_call_spans.is_empty() {
2252 cx.span_lint(UNCONDITIONAL_RECURSION, sp,
2253 "function cannot return without recurring");
2255 // FIXME #19668: these could be span_lint_note's instead of this manual guard.
2256 if cx.current_level(UNCONDITIONAL_RECURSION) != Level::Allow {
2257 let sess = cx.sess();
2258 // offer some help to the programmer.
2259 for call in &self_call_spans {
2260 sess.span_note(*call, "recursive call site")
2262 sess.fileline_help(sp, "a `loop` may express intention \
2263 better if this is on purpose")
2270 // Functions for identifying if the given Expr NodeId `id`
2271 // represents a call to the function `fn_id`/method `method`.
2273 fn expr_refers_to_this_fn(tcx: &ty::ctxt,
2275 id: ast::NodeId) -> bool {
2276 match tcx.map.get(id) {
2277 hir_map::NodeExpr(&hir::Expr { node: hir::ExprCall(ref callee, _), .. }) => {
2278 tcx.def_map.borrow().get(&callee.id)
2279 .map_or(false, |def| def.def_id() == DefId::local(fn_id))
2285 // Check if the expression `id` performs a call to `method`.
2286 fn expr_refers_to_this_method(tcx: &ty::ctxt,
2287 method: &ty::Method,
2288 id: ast::NodeId) -> bool {
2289 let tables = tcx.tables.borrow();
2291 // Check for method calls and overloaded operators.
2292 if let Some(m) = tables.method_map.get(&ty::MethodCall::expr(id)) {
2293 if method_call_refers_to_method(tcx, method, m.def_id, m.substs, id) {
2298 // Check for overloaded autoderef method calls.
2299 if let Some(&adjustment::AdjustDerefRef(ref adj)) = tables.adjustments.get(&id) {
2300 for i in 0..adj.autoderefs {
2301 let method_call = ty::MethodCall::autoderef(id, i as u32);
2302 if let Some(m) = tables.method_map.get(&method_call) {
2303 if method_call_refers_to_method(tcx, method, m.def_id, m.substs, id) {
2310 // Check for calls to methods via explicit paths (e.g. `T::method()`).
2311 match tcx.map.get(id) {
2312 hir_map::NodeExpr(&hir::Expr { node: hir::ExprCall(ref callee, _), .. }) => {
2313 match tcx.def_map.borrow().get(&callee.id).map(|d| d.full_def()) {
2314 Some(def::DefMethod(def_id)) => {
2315 let no_substs = &ty::ItemSubsts::empty();
2316 let ts = tables.item_substs.get(&callee.id).unwrap_or(no_substs);
2317 method_call_refers_to_method(tcx, method, def_id, &ts.substs, id)
2326 // Check if the method call to the method with the ID `callee_id`
2327 // and instantiated with `callee_substs` refers to method `method`.
2328 fn method_call_refers_to_method<'tcx>(tcx: &ty::ctxt<'tcx>,
2329 method: &ty::Method,
2331 callee_substs: &Substs<'tcx>,
2332 expr_id: ast::NodeId) -> bool {
2333 let callee_item = tcx.impl_or_trait_item(callee_id);
2335 match callee_item.container() {
2336 // This is an inherent method, so the `def_id` refers
2337 // directly to the method definition.
2338 ty::ImplContainer(_) => {
2339 callee_id == method.def_id
2342 // A trait method, from any number of possible sources.
2343 // Attempt to select a concrete impl before checking.
2344 ty::TraitContainer(trait_def_id) => {
2345 let trait_substs = callee_substs.clone().method_to_trait();
2346 let trait_substs = tcx.mk_substs(trait_substs);
2347 let trait_ref = ty::TraitRef::new(trait_def_id, trait_substs);
2348 let trait_ref = ty::Binder(trait_ref);
2349 let span = tcx.map.span(expr_id);
2351 traits::Obligation::new(traits::ObligationCause::misc(span, expr_id),
2352 trait_ref.to_poly_trait_predicate());
2354 let param_env = ty::ParameterEnvironment::for_item(tcx, method.def_id.node);
2355 let infcx = infer::new_infer_ctxt(tcx, &tcx.tables, Some(param_env), false);
2356 let mut selcx = traits::SelectionContext::new(&infcx);
2357 match selcx.select(&obligation) {
2358 // The method comes from a `T: Trait` bound.
2359 // If `T` is `Self`, then this call is inside
2360 // a default method definition.
2361 Ok(Some(traits::VtableParam(_))) => {
2362 let self_ty = callee_substs.self_ty();
2363 let on_self = self_ty.map_or(false, |t| t.is_self());
2364 // We can only be recurring in a default
2365 // method if we're being called literally
2366 // on the `Self` type.
2367 on_self && callee_id == method.def_id
2370 // The `impl` is known, so we check that with a
2372 Ok(Some(traits::VtableImpl(vtable_impl))) => {
2373 let container = ty::ImplContainer(vtable_impl.impl_def_id);
2374 // It matches if it comes from the same impl,
2375 // and has the same method name.
2376 container == method.container
2377 && callee_item.name() == method.name
2380 // There's no way to know if this call is
2381 // recursive, so we assume it's not.
2393 "compiler plugin used as ordinary library in non-plugin crate"
2396 #[derive(Copy, Clone)]
2397 pub struct PluginAsLibrary;
2399 impl LintPass for PluginAsLibrary {
2400 fn get_lints(&self) -> LintArray {
2401 lint_array![PLUGIN_AS_LIBRARY]
2404 fn check_item(&mut self, cx: &Context, it: &hir::Item) {
2405 if cx.sess().plugin_registrar_fn.get().is_some() {
2406 // We're compiling a plugin; it's fine to link other plugins.
2411 hir::ItemExternCrate(..) => (),
2415 let md = match cx.sess().cstore.find_extern_mod_stmt_cnum(it.id) {
2416 Some(cnum) => cx.sess().cstore.get_crate_data(cnum),
2418 // Probably means we aren't linking the crate for some reason.
2420 // Not sure if / when this could happen.
2425 if decoder::get_plugin_registrar_fn(md.data()).is_some() {
2426 cx.span_lint(PLUGIN_AS_LIBRARY, it.span,
2427 "compiler plugin used as an ordinary library");
2433 PRIVATE_NO_MANGLE_FNS,
2435 "functions marked #[no_mangle] should be exported"
2439 PRIVATE_NO_MANGLE_STATICS,
2441 "statics marked #[no_mangle] should be exported"
2445 NO_MANGLE_CONST_ITEMS,
2447 "const items will not have their symbols exported"
2450 #[derive(Copy, Clone)]
2451 pub struct InvalidNoMangleItems;
2453 impl LintPass for InvalidNoMangleItems {
2454 fn get_lints(&self) -> LintArray {
2455 lint_array!(PRIVATE_NO_MANGLE_FNS,
2456 PRIVATE_NO_MANGLE_STATICS,
2457 NO_MANGLE_CONST_ITEMS)
2460 fn check_item(&mut self, cx: &Context, it: &hir::Item) {
2462 hir::ItemFn(..) => {
2463 if attr::contains_name(&it.attrs, "no_mangle") &&
2464 !cx.exported_items.contains(&it.id) {
2465 let msg = format!("function {} is marked #[no_mangle], but not exported",
2467 cx.span_lint(PRIVATE_NO_MANGLE_FNS, it.span, &msg);
2470 hir::ItemStatic(..) => {
2471 if attr::contains_name(&it.attrs, "no_mangle") &&
2472 !cx.exported_items.contains(&it.id) {
2473 let msg = format!("static {} is marked #[no_mangle], but not exported",
2475 cx.span_lint(PRIVATE_NO_MANGLE_STATICS, it.span, &msg);
2478 hir::ItemConst(..) => {
2479 if attr::contains_name(&it.attrs, "no_mangle") {
2480 // Const items do not refer to a particular location in memory, and therefore
2481 // don't have anything to attach a symbol to
2482 let msg = "const items should never be #[no_mangle], consider instead using \
2484 cx.span_lint(NO_MANGLE_CONST_ITEMS, it.span, msg);
2492 #[derive(Clone, Copy)]
2493 pub struct MutableTransmutes;
2498 "mutating transmuted &mut T from &T may cause undefined behavior"
2501 impl LintPass for MutableTransmutes {
2502 fn get_lints(&self) -> LintArray {
2503 lint_array!(MUTABLE_TRANSMUTES)
2506 fn check_expr(&mut self, cx: &Context, expr: &hir::Expr) {
2507 use syntax::abi::RustIntrinsic;
2509 let msg = "mutating transmuted &mut T from &T may cause undefined behavior,\
2510 consider instead using an UnsafeCell";
2511 match get_transmute_from_to(cx, expr) {
2512 Some((&ty::TyRef(_, from_mt), &ty::TyRef(_, to_mt))) => {
2513 if to_mt.mutbl == hir::Mutability::MutMutable
2514 && from_mt.mutbl == hir::Mutability::MutImmutable {
2515 cx.span_lint(MUTABLE_TRANSMUTES, expr.span, msg);
2521 fn get_transmute_from_to<'a, 'tcx>(cx: &Context<'a, 'tcx>, expr: &hir::Expr)
2522 -> Option<(&'tcx ty::TypeVariants<'tcx>, &'tcx ty::TypeVariants<'tcx>)> {
2524 hir::ExprPath(..) => (),
2527 if let def::DefFn(did, _) = cx.tcx.resolve_expr(expr) {
2528 if !def_id_is_transmute(cx, did) {
2531 let typ = cx.tcx.node_id_to_type(expr.id);
2533 ty::TyBareFn(_, ref bare_fn) if bare_fn.abi == RustIntrinsic => {
2534 if let ty::FnConverging(to) = bare_fn.sig.0.output {
2535 let from = bare_fn.sig.0.inputs[0];
2536 return Some((&from.sty, &to.sty));
2545 fn def_id_is_transmute(cx: &Context, def_id: DefId) -> bool {
2546 match cx.tcx.lookup_item_type(def_id).ty.sty {
2547 ty::TyBareFn(_, ref bfty) if bfty.abi == RustIntrinsic => (),
2550 cx.tcx.with_path(def_id, |path| match path.last() {
2551 Some(ref last) => last.name().as_str() == "transmute",
2558 /// Forbids using the `#[feature(...)]` attribute
2559 #[derive(Copy, Clone)]
2560 pub struct UnstableFeatures;
2565 "enabling unstable features (deprecated. do not use)"
2568 impl LintPass for UnstableFeatures {
2569 fn get_lints(&self) -> LintArray {
2570 lint_array!(UNSTABLE_FEATURES)
2572 fn check_attribute(&mut self, ctx: &Context, attr: &ast::Attribute) {
2573 if attr::contains_name(&[attr.node.value.clone()], "feature") {
2574 if let Some(items) = attr.node.value.meta_item_list() {
2576 ctx.span_lint(UNSTABLE_FEATURES, item.span, "unstable feature");
2583 /// Lints for attempts to impl Drop on types that have `#[repr(C)]`
2584 /// attribute (see issue #24585).
2585 #[derive(Copy, Clone)]
2586 pub struct DropWithReprExtern;
2589 DROP_WITH_REPR_EXTERN,
2591 "use of #[repr(C)] on a type that implements Drop"
2594 impl LintPass for DropWithReprExtern {
2595 fn get_lints(&self) -> LintArray {
2596 lint_array!(DROP_WITH_REPR_EXTERN)
2598 fn check_crate(&mut self, ctx: &Context, _: &hir::Crate) {
2599 for dtor_did in ctx.tcx.destructors.borrow().iter() {
2600 let (drop_impl_did, dtor_self_type) =
2601 if dtor_did.is_local() {
2602 let impl_did = ctx.tcx.map.get_parent_did(dtor_did.node);
2603 let ty = ctx.tcx.lookup_item_type(impl_did).ty;
2609 match dtor_self_type.sty {
2610 ty::TyEnum(self_type_def, _) |
2611 ty::TyStruct(self_type_def, _) => {
2612 let self_type_did = self_type_def.did;
2613 let hints = ctx.tcx.lookup_repr_hints(self_type_did);
2614 if hints.iter().any(|attr| *attr == attr::ReprExtern) &&
2615 self_type_def.dtor_kind().has_drop_flag() {
2616 let drop_impl_span = ctx.tcx.map.def_id_span(drop_impl_did,
2618 let self_defn_span = ctx.tcx.map.def_id_span(self_type_did,
2620 ctx.span_lint(DROP_WITH_REPR_EXTERN,
2622 "implementing Drop adds hidden state to types, \
2623 possibly conflicting with `#[repr(C)]`");
2624 // FIXME #19668: could be span_lint_note instead of manual guard.
2625 if ctx.current_level(DROP_WITH_REPR_EXTERN) != Level::Allow {
2626 ctx.sess().span_note(self_defn_span,
2627 "the `#[repr(C)]` attribute is attached here");