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::const_eval::{eval_const_expr_partial, ConstVal};
37 use middle::const_eval::EvalHint::ExprTypeChecked;
38 use rustc::front::map as hir_map;
39 use util::nodemap::{FnvHashMap, FnvHashSet, NodeSet};
40 use lint::{Level, Context, LintPass, LintArray, Lint};
42 use std::collections::HashSet;
43 use std::collections::hash_map::Entry::{Occupied, Vacant};
44 use std::{cmp, slice};
45 use std::{i8, i16, i32, i64, u8, u16, u32, u64, f32, f64};
47 use syntax::{abi, ast};
48 use syntax::attr as syntax_attr;
49 use syntax::codemap::{self, Span};
50 use syntax::feature_gate::{KNOWN_ATTRIBUTES, AttributeType};
51 use rustc_front::hir::{TyIs, TyUs, TyI8, TyU8, TyI16, TyU16, TyI32, TyU32, TyI64, TyU64};
56 use rustc_front::attr::{self, AttrMetaMethods};
57 use rustc_front::visit::{self, FnKind, Visitor};
58 use rustc_front::lowering::unlower_attribute;
60 use rustc_front::util::is_shift_binop;
62 // hardwired lints from librustc
63 pub use lint::builtin::*;
68 "suggest using `loop { }` instead of `while true { }`"
71 #[derive(Copy, Clone)]
74 impl LintPass for WhileTrue {
75 fn get_lints(&self) -> LintArray {
76 lint_array!(WHILE_TRUE)
79 fn check_expr(&mut self, cx: &Context, e: &hir::Expr) {
80 if let hir::ExprWhile(ref cond, _, _) = e.node {
81 if let hir::ExprLit(ref lit) = cond.node {
82 if let hir::LitBool(true) = lit.node {
83 cx.span_lint(WHILE_TRUE, e.span,
84 "denote infinite loops with loop { ... }");
94 "comparisons made useless by limits of the types involved"
100 "literal out of range for its type"
106 "shift exceeds the type's number of bits"
109 #[derive(Copy, Clone)]
110 pub struct TypeLimits {
111 /// Id of the last visited negated expression
112 negated_expr_id: ast::NodeId,
116 pub fn new() -> TypeLimits {
123 impl LintPass for TypeLimits {
124 fn get_lints(&self) -> LintArray {
125 lint_array!(UNUSED_COMPARISONS, OVERFLOWING_LITERALS, EXCEEDING_BITSHIFTS)
128 fn check_expr(&mut self, cx: &Context, e: &hir::Expr) {
130 hir::ExprUnary(hir::UnNeg, ref expr) => {
132 hir::ExprLit(ref lit) => {
134 hir::LitInt(_, hir::UnsignedIntLit(_)) => {
135 check_unsigned_negation_feature(cx, e.span);
137 hir::LitInt(_, hir::UnsuffixedIntLit(_)) => {
138 if let ty::TyUint(_) = cx.tcx.node_id_to_type(e.id).sty {
139 check_unsigned_negation_feature(cx, e.span);
146 let t = cx.tcx.node_id_to_type(expr.id);
149 check_unsigned_negation_feature(cx, e.span);
155 // propagate negation, if the negation itself isn't negated
156 if self.negated_expr_id != e.id {
157 self.negated_expr_id = expr.id;
160 hir::ExprParen(ref expr) if self.negated_expr_id == e.id => {
161 self.negated_expr_id = expr.id;
163 hir::ExprBinary(binop, ref l, ref r) => {
164 if is_comparison(binop) && !check_limits(cx.tcx, binop, &**l, &**r) {
165 cx.span_lint(UNUSED_COMPARISONS, e.span,
166 "comparison is useless due to type limits");
169 if is_shift_binop(binop.node) {
170 let opt_ty_bits = match cx.tcx.node_id_to_type(l.id).sty {
171 ty::TyInt(t) => Some(int_ty_bits(t, cx.sess().target.int_type)),
172 ty::TyUint(t) => Some(uint_ty_bits(t, cx.sess().target.uint_type)),
176 if let Some(bits) = opt_ty_bits {
177 let exceeding = if let hir::ExprLit(ref lit) = r.node {
178 if let hir::LitInt(shift, _) = lit.node { shift >= bits }
181 match eval_const_expr_partial(cx.tcx, &r, ExprTypeChecked) {
182 Ok(ConstVal::Int(shift)) => { shift as u64 >= bits },
183 Ok(ConstVal::Uint(shift)) => { shift >= bits },
188 cx.span_lint(EXCEEDING_BITSHIFTS, e.span,
189 "bitshift exceeds the type's number of bits");
194 hir::ExprLit(ref lit) => {
195 match cx.tcx.node_id_to_type(e.id).sty {
198 hir::LitInt(v, hir::SignedIntLit(_, hir::Plus)) |
199 hir::LitInt(v, hir::UnsuffixedIntLit(hir::Plus)) => {
200 let int_type = if let hir::TyIs = t {
201 cx.sess().target.int_type
205 let (_, max) = int_ty_range(int_type);
206 let negative = self.negated_expr_id == e.id;
208 // Detect literal value out of range [min, max] inclusive
209 // avoiding use of -min to prevent overflow/panic
210 if (negative && v > max as u64 + 1) ||
211 (!negative && v > max as u64) {
212 cx.span_lint(OVERFLOWING_LITERALS, e.span,
213 &*format!("literal out of range for {:?}", t));
221 let uint_type = if let hir::TyUs = t {
222 cx.sess().target.uint_type
226 let (min, max) = uint_ty_range(uint_type);
227 let lit_val: u64 = match lit.node {
228 hir::LitByte(_v) => return, // _v is u8, within range by definition
229 hir::LitInt(v, _) => v,
232 if lit_val < min || lit_val > max {
233 cx.span_lint(OVERFLOWING_LITERALS, e.span,
234 &*format!("literal out of range for {:?}", t));
238 let (min, max) = float_ty_range(t);
239 let lit_val: f64 = match lit.node {
240 hir::LitFloat(ref v, _) |
241 hir::LitFloatUnsuffixed(ref v) => {
249 if lit_val < min || lit_val > max {
250 cx.span_lint(OVERFLOWING_LITERALS, e.span,
251 &*format!("literal out of range for {:?}", t));
260 fn is_valid<T:cmp::PartialOrd>(binop: hir::BinOp, v: T,
261 min: T, max: T) -> bool {
263 hir::BiLt => v > min && v <= max,
264 hir::BiLe => v >= min && v < max,
265 hir::BiGt => v >= min && v < max,
266 hir::BiGe => v > min && v <= max,
267 hir::BiEq | hir::BiNe => v >= min && v <= max,
272 fn rev_binop(binop: hir::BinOp) -> hir::BinOp {
273 codemap::respan(binop.span, match binop.node {
274 hir::BiLt => hir::BiGt,
275 hir::BiLe => hir::BiGe,
276 hir::BiGt => hir::BiLt,
277 hir::BiGe => hir::BiLe,
282 // for isize & usize, be conservative with the warnings, so that the
283 // warnings are consistent between 32- and 64-bit platforms
284 fn int_ty_range(int_ty: hir::IntTy) -> (i64, i64) {
286 hir::TyIs => (i64::MIN, i64::MAX),
287 hir::TyI8 => (i8::MIN as i64, i8::MAX as i64),
288 hir::TyI16 => (i16::MIN as i64, i16::MAX as i64),
289 hir::TyI32 => (i32::MIN as i64, i32::MAX as i64),
290 hir::TyI64 => (i64::MIN, i64::MAX)
294 fn uint_ty_range(uint_ty: hir::UintTy) -> (u64, u64) {
296 hir::TyUs => (u64::MIN, u64::MAX),
297 hir::TyU8 => (u8::MIN as u64, u8::MAX as u64),
298 hir::TyU16 => (u16::MIN as u64, u16::MAX as u64),
299 hir::TyU32 => (u32::MIN as u64, u32::MAX as u64),
300 hir::TyU64 => (u64::MIN, u64::MAX)
304 fn float_ty_range(float_ty: hir::FloatTy) -> (f64, f64) {
306 hir::TyF32 => (f32::MIN as f64, f32::MAX as f64),
307 hir::TyF64 => (f64::MIN, f64::MAX)
311 fn int_ty_bits(int_ty: hir::IntTy, target_int_ty: hir::IntTy) -> u64 {
313 hir::TyIs => int_ty_bits(target_int_ty, target_int_ty),
314 hir::TyI8 => i8::BITS as u64,
315 hir::TyI16 => i16::BITS as u64,
316 hir::TyI32 => i32::BITS as u64,
317 hir::TyI64 => i64::BITS as u64
321 fn uint_ty_bits(uint_ty: hir::UintTy, target_uint_ty: hir::UintTy) -> u64 {
323 hir::TyUs => uint_ty_bits(target_uint_ty, target_uint_ty),
324 hir::TyU8 => u8::BITS as u64,
325 hir::TyU16 => u16::BITS as u64,
326 hir::TyU32 => u32::BITS as u64,
327 hir::TyU64 => u64::BITS as u64
331 fn check_limits(tcx: &ty::ctxt, binop: hir::BinOp,
332 l: &hir::Expr, r: &hir::Expr) -> bool {
333 let (lit, expr, swap) = match (&l.node, &r.node) {
334 (&hir::ExprLit(_), _) => (l, r, true),
335 (_, &hir::ExprLit(_)) => (r, l, false),
338 // Normalize the binop so that the literal is always on the RHS in
340 let norm_binop = if swap {
345 match tcx.node_id_to_type(expr.id).sty {
346 ty::TyInt(int_ty) => {
347 let (min, max) = int_ty_range(int_ty);
348 let lit_val: i64 = match lit.node {
349 hir::ExprLit(ref li) => match li.node {
350 hir::LitInt(v, hir::SignedIntLit(_, hir::Plus)) |
351 hir::LitInt(v, hir::UnsuffixedIntLit(hir::Plus)) => v as i64,
352 hir::LitInt(v, hir::SignedIntLit(_, hir::Minus)) |
353 hir::LitInt(v, hir::UnsuffixedIntLit(hir::Minus)) => -(v as i64),
358 is_valid(norm_binop, lit_val, min, max)
360 ty::TyUint(uint_ty) => {
361 let (min, max): (u64, u64) = uint_ty_range(uint_ty);
362 let lit_val: u64 = match lit.node {
363 hir::ExprLit(ref li) => match li.node {
364 hir::LitInt(v, _) => v,
369 is_valid(norm_binop, lit_val, min, max)
375 fn is_comparison(binop: hir::BinOp) -> bool {
377 hir::BiEq | hir::BiLt | hir::BiLe |
378 hir::BiNe | hir::BiGe | hir::BiGt => true,
383 fn check_unsigned_negation_feature(cx: &Context, span: Span) {
384 if !cx.sess().features.borrow().negate_unsigned {
385 // FIXME(#27141): change this to syntax::feature_gate::emit_feature_err…
386 cx.sess().span_warn(span,
387 "unary negation of unsigned integers will be feature gated in the future");
388 // …and remove following two expressions.
389 if option_env!("CFG_DISABLE_UNSTABLE_FEATURES").is_some() { return; }
390 cx.sess().fileline_help(span, "add #![feature(negate_unsigned)] to the \
391 crate attributes to enable the gate in advance");
400 "proper use of libc types in foreign modules"
403 struct ImproperCTypesVisitor<'a, 'tcx: 'a> {
404 cx: &'a Context<'a, 'tcx>
409 FfiUnsafe(&'static str),
410 FfiBadStruct(DefId, &'static str),
411 FfiBadEnum(DefId, &'static str)
414 /// Check if this enum can be safely exported based on the
415 /// "nullable pointer optimization". Currently restricted
416 /// to function pointers and references, but could be
417 /// expanded to cover NonZero raw pointers and newtypes.
418 /// FIXME: This duplicates code in trans.
419 fn is_repr_nullable_ptr<'tcx>(tcx: &ty::ctxt<'tcx>,
420 def: ty::AdtDef<'tcx>,
421 substs: &Substs<'tcx>)
423 if def.variants.len() == 2 {
426 if def.variants[0].fields.is_empty() {
428 } else if def.variants[1].fields.is_empty() {
434 if def.variants[data_idx].fields.len() == 1 {
435 match def.variants[data_idx].fields[0].ty(tcx, substs).sty {
436 ty::TyBareFn(None, _) => { return true; }
437 ty::TyRef(..) => { return true; }
445 fn ast_ty_to_normalized<'tcx>(tcx: &ty::ctxt<'tcx>,
448 let tty = match tcx.ast_ty_to_ty_cache.borrow().get(&id) {
450 None => panic!("ast_ty_to_ty_cache was incomplete after typeck!")
452 infer::normalize_associated_type(tcx, &tty)
455 impl<'a, 'tcx> ImproperCTypesVisitor<'a, 'tcx> {
456 /// Check if the given type is "ffi-safe" (has a stable, well-defined
457 /// representation which can be exported to C code).
458 fn check_type_for_ffi(&self,
459 cache: &mut FnvHashSet<Ty<'tcx>>,
462 use self::FfiResult::*;
463 let cx = &self.cx.tcx;
465 // Protect against infinite recursion, for example
466 // `struct S(*mut S);`.
467 // FIXME: A recursion limit is necessary as well, for irregular
469 if !cache.insert(ty) {
474 ty::TyStruct(def, substs) => {
475 if !cx.lookup_repr_hints(def.did).contains(&attr::ReprExtern) {
477 "found struct without foreign-function-safe \
478 representation annotation in foreign module, \
479 consider adding a #[repr(C)] attribute to \
483 // We can't completely trust repr(C) markings; make sure the
484 // fields are actually safe.
485 if def.struct_variant().fields.is_empty() {
487 "found zero-size struct in foreign module, consider \
488 adding a member to this struct");
491 for field in &def.struct_variant().fields {
492 let field_ty = infer::normalize_associated_type(cx, &field.ty(cx, substs));
493 let r = self.check_type_for_ffi(cache, field_ty);
496 FfiBadStruct(..) | FfiBadEnum(..) => { return r; }
497 FfiUnsafe(s) => { return FfiBadStruct(def.did, s); }
502 ty::TyEnum(def, substs) => {
503 if def.variants.is_empty() {
504 // Empty enums are okay... although sort of useless.
508 // Check for a repr() attribute to specify the size of the
510 let repr_hints = cx.lookup_repr_hints(def.did);
511 match &**repr_hints {
513 // Special-case types like `Option<extern fn()>`.
514 if !is_repr_nullable_ptr(cx, def, substs) {
516 "found enum without foreign-function-safe \
517 representation annotation in foreign module, \
518 consider adding a #[repr(...)] attribute to \
523 if !hint.is_ffi_safe() {
524 // FIXME: This shouldn't be reachable: we should check
527 "enum has unexpected #[repr(...)] attribute")
530 // Enum with an explicitly sized discriminant; either
531 // a C-style enum or a discriminated union.
533 // The layout of enum variants is implicitly repr(C).
534 // FIXME: Is that correct?
537 // FIXME: This shouldn't be reachable: we should check
540 "enum has too many #[repr(...)] attributes");
544 // Check the contained variants.
545 for variant in &def.variants {
546 for field in &variant.fields {
547 let arg = infer::normalize_associated_type(cx, &field.ty(cx, substs));
548 let r = self.check_type_for_ffi(cache, arg);
551 FfiBadStruct(..) | FfiBadEnum(..) => { return r; }
552 FfiUnsafe(s) => { return FfiBadEnum(def.did, s); }
559 ty::TyInt(hir::TyIs) => {
560 FfiUnsafe("found Rust type `isize` in foreign module, while \
561 `libc::c_int` or `libc::c_long` should be used")
563 ty::TyUint(hir::TyUs) => {
564 FfiUnsafe("found Rust type `usize` in foreign module, while \
565 `libc::c_uint` or `libc::c_ulong` should be used")
568 FfiUnsafe("found Rust type `char` in foreign module, while \
569 `u32` or `libc::wchar_t` should be used")
572 // Primitive types with a stable representation.
573 ty::TyBool | ty::TyInt(..) | ty::TyUint(..) |
574 ty::TyFloat(..) => FfiSafe,
577 FfiUnsafe("found Rust type Box<_> in foreign module, \
578 consider using a raw pointer instead")
582 FfiUnsafe("found Rust slice type in foreign module, \
583 consider using a raw pointer instead")
587 FfiUnsafe("found Rust trait type in foreign module, \
588 consider using a raw pointer instead")
592 FfiUnsafe("found Rust type `str` in foreign module; \
593 consider using a `*const libc::c_char`")
597 FfiUnsafe("found Rust tuple type in foreign module; \
598 consider using a struct instead`")
601 ty::TyRawPtr(ref m) | ty::TyRef(_, ref m) => {
602 self.check_type_for_ffi(cache, m.ty)
605 ty::TyArray(ty, _) => {
606 self.check_type_for_ffi(cache, ty)
609 ty::TyBareFn(None, bare_fn) => {
613 abi::PlatformIntrinsic |
616 "found function pointer with Rust calling \
617 convention in foreign module; consider using an \
618 `extern` function pointer")
623 let sig = cx.erase_late_bound_regions(&bare_fn.sig);
625 ty::FnDiverging => {}
626 ty::FnConverging(output) => {
627 if !output.is_nil() {
628 let r = self.check_type_for_ffi(cache, output);
636 for arg in sig.inputs {
637 let r = self.check_type_for_ffi(cache, arg);
646 ty::TyParam(..) | ty::TyInfer(..) | ty::TyError |
647 ty::TyClosure(..) | ty::TyProjection(..) |
648 ty::TyBareFn(Some(_), _) => {
649 panic!("Unexpected type in foreign function")
654 fn check_def(&mut self, sp: Span, id: ast::NodeId) {
655 let tty = ast_ty_to_normalized(self.cx.tcx, id);
657 match ImproperCTypesVisitor::check_type_for_ffi(self, &mut FnvHashSet(), tty) {
658 FfiResult::FfiSafe => {}
659 FfiResult::FfiUnsafe(s) => {
660 self.cx.span_lint(IMPROPER_CTYPES, sp, s);
662 FfiResult::FfiBadStruct(_, s) => {
663 // FIXME: This diagnostic is difficult to read, and doesn't
664 // point at the relevant field.
665 self.cx.span_lint(IMPROPER_CTYPES, sp,
666 &format!("found non-foreign-function-safe member in \
667 struct marked #[repr(C)]: {}", s));
669 FfiResult::FfiBadEnum(_, s) => {
670 // FIXME: This diagnostic is difficult to read, and doesn't
671 // point at the relevant variant.
672 self.cx.span_lint(IMPROPER_CTYPES, sp,
673 &format!("found non-foreign-function-safe member in \
680 impl<'a, 'tcx, 'v> Visitor<'v> for ImproperCTypesVisitor<'a, 'tcx> {
681 fn visit_ty(&mut self, ty: &hir::Ty) {
684 hir::TyBareFn(..) => self.check_def(ty.span, ty.id),
686 self.cx.span_lint(IMPROPER_CTYPES, ty.span,
687 "found Rust slice type in foreign module, consider \
688 using a raw pointer instead");
690 hir::TyFixedLengthVec(ref ty, _) => self.visit_ty(ty),
692 self.cx.span_lint(IMPROPER_CTYPES, ty.span,
693 "found Rust tuple type in foreign module; \
694 consider using a struct instead`")
696 _ => visit::walk_ty(self, ty)
701 #[derive(Copy, Clone)]
702 pub struct ImproperCTypes;
704 impl LintPass for ImproperCTypes {
705 fn get_lints(&self) -> LintArray {
706 lint_array!(IMPROPER_CTYPES)
709 fn check_item(&mut self, cx: &Context, it: &hir::Item) {
710 fn check_ty(cx: &Context, ty: &hir::Ty) {
711 let mut vis = ImproperCTypesVisitor { cx: cx };
715 fn check_foreign_fn(cx: &Context, decl: &hir::FnDecl) {
716 for input in &decl.inputs {
717 check_ty(cx, &*input.ty);
719 if let hir::Return(ref ret_ty) = decl.output {
720 let tty = ast_ty_to_normalized(cx.tcx, ret_ty.id);
722 check_ty(cx, &ret_ty);
728 hir::ItemForeignMod(ref nmod)
729 if nmod.abi != abi::RustIntrinsic &&
730 nmod.abi != abi::PlatformIntrinsic => {
731 for ni in &nmod.items {
733 hir::ForeignItemFn(ref decl, _) => check_foreign_fn(cx, &**decl),
734 hir::ForeignItemStatic(ref t, _) => check_ty(cx, &**t)
746 "use of owned (Box type) heap memory"
749 #[derive(Copy, Clone)]
750 pub struct BoxPointers;
753 fn check_heap_type<'a, 'tcx>(&self, cx: &Context<'a, 'tcx>,
754 span: Span, ty: Ty<'tcx>) {
755 for leaf_ty in ty.walk() {
756 if let ty::TyBox(_) = leaf_ty.sty {
757 let m = format!("type uses owned (Box type) pointers: {}", ty);
758 cx.span_lint(BOX_POINTERS, span, &m);
764 impl LintPass for BoxPointers {
765 fn get_lints(&self) -> LintArray {
766 lint_array!(BOX_POINTERS)
769 fn check_item(&mut self, cx: &Context, it: &hir::Item) {
774 hir::ItemStruct(..) =>
775 self.check_heap_type(cx, it.span,
776 cx.tcx.node_id_to_type(it.id)),
780 // If it's a struct, we also have to check the fields' types
782 hir::ItemStruct(ref struct_def, _) => {
783 for struct_field in &struct_def.fields {
784 self.check_heap_type(cx, struct_field.span,
785 cx.tcx.node_id_to_type(struct_field.node.id));
792 fn check_expr(&mut self, cx: &Context, e: &hir::Expr) {
793 let ty = cx.tcx.node_id_to_type(e.id);
794 self.check_heap_type(cx, e.span, ty);
801 "uses of #[derive] with raw pointers are rarely correct"
804 struct RawPtrDeriveVisitor<'a, 'tcx: 'a> {
805 cx: &'a Context<'a, 'tcx>
808 impl<'a, 'tcx, 'v> Visitor<'v> for RawPtrDeriveVisitor<'a, 'tcx> {
809 fn visit_ty(&mut self, ty: &hir::Ty) {
810 const MSG: &'static str = "use of `#[derive]` with a raw pointer";
811 if let hir::TyPtr(..) = ty.node {
812 self.cx.span_lint(RAW_POINTER_DERIVE, ty.span, MSG);
814 visit::walk_ty(self, ty);
816 // explicit override to a no-op to reduce code bloat
817 fn visit_expr(&mut self, _: &hir::Expr) {}
818 fn visit_block(&mut self, _: &hir::Block) {}
821 pub struct RawPointerDerive {
822 checked_raw_pointers: NodeSet,
825 impl RawPointerDerive {
826 pub fn new() -> RawPointerDerive {
828 checked_raw_pointers: NodeSet(),
833 impl LintPass for RawPointerDerive {
834 fn get_lints(&self) -> LintArray {
835 lint_array!(RAW_POINTER_DERIVE)
838 fn check_item(&mut self, cx: &Context, item: &hir::Item) {
839 if !attr::contains_name(&item.attrs, "automatically_derived") {
842 let did = match item.node {
843 hir::ItemImpl(_, _, _, ref t_ref_opt, _, _) => {
844 // Deriving the Copy trait does not cause a warning
845 if let &Some(ref trait_ref) = t_ref_opt {
846 let def_id = cx.tcx.trait_ref_to_def_id(trait_ref);
847 if Some(def_id) == cx.tcx.lang_items.copy_trait() {
852 match cx.tcx.node_id_to_type(item.id).sty {
853 ty::TyEnum(def, _) => def.did,
854 ty::TyStruct(def, _) => def.did,
863 let item = match cx.tcx.map.find(did.node) {
864 Some(hir_map::NodeItem(item)) => item,
867 if !self.checked_raw_pointers.insert(item.id) {
871 hir::ItemStruct(..) | hir::ItemEnum(..) => {
872 let mut visitor = RawPtrDeriveVisitor { cx: cx };
873 visit::walk_item(&mut visitor, &item);
883 "detects attributes that were not used by the compiler"
886 #[derive(Copy, Clone)]
887 pub struct UnusedAttributes;
889 impl LintPass for UnusedAttributes {
890 fn get_lints(&self) -> LintArray {
891 lint_array!(UNUSED_ATTRIBUTES)
894 fn check_attribute(&mut self, cx: &Context, attr: &hir::Attribute) {
895 // Note that check_name() marks the attribute as used if it matches.
896 for &(ref name, ty, _) in KNOWN_ATTRIBUTES {
898 AttributeType::Whitelisted if attr.check_name(name) => {
905 let plugin_attributes = cx.sess().plugin_attributes.borrow_mut();
906 for &(ref name, ty) in plugin_attributes.iter() {
907 if ty == AttributeType::Whitelisted && attr.check_name(&*name) {
912 if !syntax_attr::is_used(&unlower_attribute(attr)) {
913 cx.span_lint(UNUSED_ATTRIBUTES, attr.span, "unused attribute");
914 // Is it a builtin attribute that must be used at the crate level?
915 let known_crate = KNOWN_ATTRIBUTES.iter().find(|&&(name, ty, _)| {
916 attr.name() == name &&
917 ty == AttributeType::CrateLevel
920 // Has a plugin registered this attribute as one which must be used at
922 let plugin_crate = plugin_attributes.iter()
923 .find(|&&(ref x, t)| {
924 &*attr.name() == &*x &&
925 AttributeType::CrateLevel == t
927 if known_crate || plugin_crate {
928 let msg = match attr.node.style {
929 hir::AttrOuter => "crate-level attribute should be an inner \
930 attribute: add an exclamation mark: #![foo]",
931 hir::AttrInner => "crate-level attribute should be in the \
934 cx.span_lint(UNUSED_ATTRIBUTES, attr.span, msg);
943 "path statements with no effect"
946 #[derive(Copy, Clone)]
947 pub struct PathStatements;
949 impl LintPass for PathStatements {
950 fn get_lints(&self) -> LintArray {
951 lint_array!(PATH_STATEMENTS)
954 fn check_stmt(&mut self, cx: &Context, s: &hir::Stmt) {
956 hir::StmtSemi(ref expr, _) => {
958 hir::ExprPath(..) => cx.span_lint(PATH_STATEMENTS, s.span,
959 "path statement with no effect"),
971 "unused result of a type flagged as #[must_use]"
977 "unused result of an expression in a statement"
980 #[derive(Copy, Clone)]
981 pub struct UnusedResults;
983 impl LintPass for UnusedResults {
984 fn get_lints(&self) -> LintArray {
985 lint_array!(UNUSED_MUST_USE, UNUSED_RESULTS)
988 fn check_stmt(&mut self, cx: &Context, s: &hir::Stmt) {
989 let expr = match s.node {
990 hir::StmtSemi(ref expr, _) => &**expr,
994 if let hir::ExprRet(..) = expr.node {
998 let t = cx.tcx.expr_ty(&expr);
999 let warned = match t.sty {
1000 ty::TyTuple(ref tys) if tys.is_empty() => return,
1001 ty::TyBool => return,
1002 ty::TyStruct(def, _) |
1003 ty::TyEnum(def, _) => {
1004 if def.did.is_local() {
1005 if let hir_map::NodeItem(it) = cx.tcx.map.get(def.did.node) {
1006 check_must_use(cx, &it.attrs, s.span)
1011 let attrs = csearch::get_item_attrs(&cx.sess().cstore, def.did);
1012 check_must_use(cx, &attrs[..], s.span)
1018 cx.span_lint(UNUSED_RESULTS, s.span, "unused result");
1021 fn check_must_use(cx: &Context, attrs: &[hir::Attribute], sp: Span) -> bool {
1023 if attr.check_name("must_use") {
1024 let mut msg = "unused result which must be used".to_string();
1025 // check for #[must_use="..."]
1026 match attr.value_str() {
1033 cx.span_lint(UNUSED_MUST_USE, sp, &msg);
1043 pub NON_CAMEL_CASE_TYPES,
1045 "types, variants, traits and type parameters should have camel case names"
1048 #[derive(Copy, Clone)]
1049 pub struct NonCamelCaseTypes;
1051 impl NonCamelCaseTypes {
1052 fn check_case(&self, cx: &Context, sort: &str, ident: ast::Ident, span: Span) {
1053 fn is_camel_case(ident: ast::Ident) -> bool {
1054 let ident = ident.name.as_str();
1055 if ident.is_empty() {
1058 let ident = ident.trim_matches('_');
1060 // start with a non-lowercase letter rather than non-uppercase
1061 // ones (some scripts don't have a concept of upper/lowercase)
1062 !ident.is_empty() && !ident.char_at(0).is_lowercase() && !ident.contains('_')
1065 fn to_camel_case(s: &str) -> String {
1066 s.split('_').flat_map(|word| word.chars().enumerate().map(|(i, c)|
1068 c.to_uppercase().collect::<String>()
1070 c.to_lowercase().collect()
1072 )).collect::<Vec<_>>().concat()
1075 let s = ident.name.as_str();
1077 if !is_camel_case(ident) {
1078 let c = to_camel_case(&s);
1079 let m = if c.is_empty() {
1080 format!("{} `{}` should have a camel case name such as `CamelCase`", sort, s)
1082 format!("{} `{}` should have a camel case name such as `{}`", sort, s, c)
1084 cx.span_lint(NON_CAMEL_CASE_TYPES, span, &m[..]);
1089 impl LintPass for NonCamelCaseTypes {
1090 fn get_lints(&self) -> LintArray {
1091 lint_array!(NON_CAMEL_CASE_TYPES)
1094 fn check_item(&mut self, cx: &Context, it: &hir::Item) {
1095 let extern_repr_count = it.attrs.iter().filter(|attr| {
1096 attr::find_repr_attrs(cx.tcx.sess.diagnostic(), attr).iter()
1097 .any(|r| r == &attr::ReprExtern)
1099 let has_extern_repr = extern_repr_count > 0;
1101 if has_extern_repr {
1106 hir::ItemTy(..) | hir::ItemStruct(..) => {
1107 self.check_case(cx, "type", it.ident, it.span)
1109 hir::ItemTrait(..) => {
1110 self.check_case(cx, "trait", it.ident, it.span)
1112 hir::ItemEnum(ref enum_definition, _) => {
1113 if has_extern_repr {
1116 self.check_case(cx, "type", it.ident, it.span);
1117 for variant in &enum_definition.variants {
1118 self.check_case(cx, "variant", variant.node.name, variant.span);
1125 fn check_generics(&mut self, cx: &Context, it: &hir::Generics) {
1126 for gen in it.ty_params.iter() {
1127 self.check_case(cx, "type parameter", gen.ident, gen.span);
1132 #[derive(PartialEq)]
1133 enum MethodContext {
1139 fn method_context(cx: &Context, id: ast::NodeId, span: Span) -> MethodContext {
1140 match cx.tcx.impl_or_trait_items.borrow().get(&DefId::local(id)) {
1141 None => cx.sess().span_bug(span, "missing method descriptor?!"),
1142 Some(item) => match item.container() {
1143 ty::TraitContainer(..) => MethodContext::TraitDefaultImpl,
1144 ty::ImplContainer(cid) => {
1145 match cx.tcx.impl_trait_ref(cid) {
1146 Some(_) => MethodContext::TraitImpl,
1147 None => MethodContext::PlainImpl
1157 "methods, functions, lifetime parameters and modules should have snake case names"
1160 #[derive(Copy, Clone)]
1161 pub struct NonSnakeCase;
1164 fn to_snake_case(mut str: &str) -> String {
1165 let mut words = vec![];
1166 // Preserve leading underscores
1167 str = str.trim_left_matches(|c: char| {
1169 words.push(String::new());
1175 for s in str.split('_') {
1176 let mut last_upper = false;
1177 let mut buf = String::new();
1181 for ch in s.chars() {
1182 if !buf.is_empty() && buf != "'"
1183 && ch.is_uppercase()
1186 buf = String::new();
1188 last_upper = ch.is_uppercase();
1189 buf.extend(ch.to_lowercase());
1196 fn check_snake_case(&self, cx: &Context, sort: &str, name: &str, span: Option<Span>) {
1197 fn is_snake_case(ident: &str) -> bool {
1198 if ident.is_empty() {
1201 let ident = ident.trim_left_matches('\'');
1202 let ident = ident.trim_matches('_');
1204 let mut allow_underscore = true;
1205 ident.chars().all(|c| {
1206 allow_underscore = match c {
1207 '_' if !allow_underscore => return false,
1209 // It would be more obvious to use `c.is_lowercase()`,
1210 // but some characters do not have a lowercase form
1211 c if !c.is_uppercase() => true,
1218 if !is_snake_case(name) {
1219 let sc = NonSnakeCase::to_snake_case(name);
1220 let msg = if sc != name {
1221 format!("{} `{}` should have a snake case name such as `{}`",
1224 format!("{} `{}` should have a snake case name",
1228 Some(span) => cx.span_lint(NON_SNAKE_CASE, span, &msg),
1229 None => cx.lint(NON_SNAKE_CASE, &msg),
1235 impl LintPass for NonSnakeCase {
1236 fn get_lints(&self) -> LintArray {
1237 lint_array!(NON_SNAKE_CASE)
1240 fn check_crate(&mut self, cx: &Context, cr: &hir::Crate) {
1241 let attr_crate_name = cr.attrs.iter().find(|at| at.check_name("crate_name"))
1242 .and_then(|at| at.value_str().map(|s| (at, s)));
1243 if let Some(ref name) = cx.tcx.sess.opts.crate_name {
1244 self.check_snake_case(cx, "crate", name, None);
1245 } else if let Some((attr, ref name)) = attr_crate_name {
1246 self.check_snake_case(cx, "crate", name, Some(attr.span));
1250 fn check_fn(&mut self, cx: &Context,
1251 fk: FnKind, _: &hir::FnDecl,
1252 _: &hir::Block, span: Span, id: ast::NodeId) {
1254 FnKind::Method(ident, _, _) => match method_context(cx, id, span) {
1255 MethodContext::PlainImpl => {
1256 self.check_snake_case(cx, "method", &ident.name.as_str(), Some(span))
1258 MethodContext::TraitDefaultImpl => {
1259 self.check_snake_case(cx, "trait method", &ident.name.as_str(), Some(span))
1263 FnKind::ItemFn(ident, _, _, _, _, _) => {
1264 self.check_snake_case(cx, "function", &ident.name.as_str(), Some(span))
1270 fn check_item(&mut self, cx: &Context, it: &hir::Item) {
1271 if let hir::ItemMod(_) = it.node {
1272 self.check_snake_case(cx, "module", &it.ident.name.as_str(), Some(it.span));
1276 fn check_trait_item(&mut self, cx: &Context, trait_item: &hir::TraitItem) {
1277 if let hir::MethodTraitItem(_, None) = trait_item.node {
1278 self.check_snake_case(cx, "trait method", &trait_item.ident.name.as_str(),
1279 Some(trait_item.span));
1283 fn check_lifetime_def(&mut self, cx: &Context, t: &hir::LifetimeDef) {
1284 self.check_snake_case(cx, "lifetime", &t.lifetime.name.as_str(),
1285 Some(t.lifetime.span));
1288 fn check_pat(&mut self, cx: &Context, p: &hir::Pat) {
1289 if let &hir::PatIdent(_, ref path1, _) = &p.node {
1290 let def = cx.tcx.def_map.borrow().get(&p.id).map(|d| d.full_def());
1291 if let Some(def::DefLocal(_)) = def {
1292 self.check_snake_case(cx, "variable", &path1.node.name.as_str(), Some(p.span));
1297 fn check_struct_def(&mut self, cx: &Context, s: &hir::StructDef,
1298 _: ast::Ident, _: &hir::Generics, _: ast::NodeId) {
1299 for sf in &s.fields {
1300 if let hir::StructField_ { kind: hir::NamedField(ident, _), .. } = sf.node {
1301 self.check_snake_case(cx, "structure field", &ident.name.as_str(),
1309 pub NON_UPPER_CASE_GLOBALS,
1311 "static constants should have uppercase identifiers"
1314 #[derive(Copy, Clone)]
1315 pub struct NonUpperCaseGlobals;
1317 impl NonUpperCaseGlobals {
1318 fn check_upper_case(cx: &Context, sort: &str, ident: ast::Ident, span: Span) {
1319 let s = ident.name.as_str();
1321 if s.chars().any(|c| c.is_lowercase()) {
1322 let uc = NonSnakeCase::to_snake_case(&s).to_uppercase();
1324 cx.span_lint(NON_UPPER_CASE_GLOBALS, span,
1325 &format!("{} `{}` should have an upper case name such as `{}`",
1328 cx.span_lint(NON_UPPER_CASE_GLOBALS, span,
1329 &format!("{} `{}` should have an upper case name",
1336 impl LintPass for NonUpperCaseGlobals {
1337 fn get_lints(&self) -> LintArray {
1338 lint_array!(NON_UPPER_CASE_GLOBALS)
1341 fn check_item(&mut self, cx: &Context, it: &hir::Item) {
1343 // only check static constants
1344 hir::ItemStatic(_, hir::MutImmutable, _) => {
1345 NonUpperCaseGlobals::check_upper_case(cx, "static constant", it.ident, it.span);
1347 hir::ItemConst(..) => {
1348 NonUpperCaseGlobals::check_upper_case(cx, "constant", it.ident, it.span);
1354 fn check_trait_item(&mut self, cx: &Context, ti: &hir::TraitItem) {
1356 hir::ConstTraitItem(..) => {
1357 NonUpperCaseGlobals::check_upper_case(cx, "associated constant",
1364 fn check_impl_item(&mut self, cx: &Context, ii: &hir::ImplItem) {
1366 hir::ConstImplItem(..) => {
1367 NonUpperCaseGlobals::check_upper_case(cx, "associated constant",
1374 fn check_pat(&mut self, cx: &Context, p: &hir::Pat) {
1375 // Lint for constants that look like binding identifiers (#7526)
1376 match (&p.node, cx.tcx.def_map.borrow().get(&p.id).map(|d| d.full_def())) {
1377 (&hir::PatIdent(_, ref path1, _), Some(def::DefConst(..))) => {
1378 NonUpperCaseGlobals::check_upper_case(cx, "constant in pattern",
1379 path1.node, p.span);
1389 "`if`, `match`, `while` and `return` do not need parentheses"
1392 #[derive(Copy, Clone)]
1393 pub struct UnusedParens;
1396 fn check_unused_parens_core(&self, cx: &Context, value: &hir::Expr, msg: &str,
1397 struct_lit_needs_parens: bool) {
1398 if let hir::ExprParen(ref inner) = value.node {
1399 let necessary = struct_lit_needs_parens && contains_exterior_struct_lit(&**inner);
1401 cx.span_lint(UNUSED_PARENS, value.span,
1402 &format!("unnecessary parentheses around {}", msg))
1406 /// Expressions that syntactically contain an "exterior" struct
1407 /// literal i.e. not surrounded by any parens or other
1408 /// delimiters, e.g. `X { y: 1 }`, `X { y: 1 }.method()`, `foo
1409 /// == X { y: 1 }` and `X { y: 1 } == foo` all do, but `(X {
1410 /// y: 1 }) == foo` does not.
1411 fn contains_exterior_struct_lit(value: &hir::Expr) -> bool {
1413 hir::ExprStruct(..) => true,
1415 hir::ExprAssign(ref lhs, ref rhs) |
1416 hir::ExprAssignOp(_, ref lhs, ref rhs) |
1417 hir::ExprBinary(_, ref lhs, ref rhs) => {
1418 // X { y: 1 } + X { y: 2 }
1419 contains_exterior_struct_lit(&**lhs) ||
1420 contains_exterior_struct_lit(&**rhs)
1422 hir::ExprUnary(_, ref x) |
1423 hir::ExprCast(ref x, _) |
1424 hir::ExprField(ref x, _) |
1425 hir::ExprTupField(ref x, _) |
1426 hir::ExprIndex(ref x, _) => {
1427 // &X { y: 1 }, X { y: 1 }.y
1428 contains_exterior_struct_lit(&**x)
1431 hir::ExprMethodCall(_, _, ref exprs) => {
1432 // X { y: 1 }.bar(...)
1433 contains_exterior_struct_lit(&*exprs[0])
1442 impl LintPass for UnusedParens {
1443 fn get_lints(&self) -> LintArray {
1444 lint_array!(UNUSED_PARENS)
1447 fn check_expr(&mut self, cx: &Context, e: &hir::Expr) {
1448 let (value, msg, struct_lit_needs_parens) = match e.node {
1449 hir::ExprIf(ref cond, _, _) => (cond, "`if` condition", true),
1450 hir::ExprWhile(ref cond, _, _) => (cond, "`while` condition", true),
1451 hir::ExprMatch(ref head, _, source) => match source {
1452 hir::MatchSource::Normal => (head, "`match` head expression", true),
1453 hir::MatchSource::IfLetDesugar { .. } => (head, "`if let` head expression", true),
1454 hir::MatchSource::WhileLetDesugar => (head, "`while let` head expression", true),
1455 hir::MatchSource::ForLoopDesugar => (head, "`for` head expression", true),
1457 hir::ExprRet(Some(ref value)) => (value, "`return` value", false),
1458 hir::ExprAssign(_, ref value) => (value, "assigned value", false),
1459 hir::ExprAssignOp(_, _, ref value) => (value, "assigned value", false),
1462 self.check_unused_parens_core(cx, &**value, msg, struct_lit_needs_parens);
1465 fn check_stmt(&mut self, cx: &Context, s: &hir::Stmt) {
1466 let (value, msg) = match s.node {
1467 hir::StmtDecl(ref decl, _) => match decl.node {
1468 hir::DeclLocal(ref local) => match local.init {
1469 Some(ref value) => (value, "assigned value"),
1476 self.check_unused_parens_core(cx, &**value, msg, false);
1481 UNUSED_IMPORT_BRACES,
1483 "unnecessary braces around an imported item"
1486 #[derive(Copy, Clone)]
1487 pub struct UnusedImportBraces;
1489 impl LintPass for UnusedImportBraces {
1490 fn get_lints(&self) -> LintArray {
1491 lint_array!(UNUSED_IMPORT_BRACES)
1494 fn check_item(&mut self, cx: &Context, item: &hir::Item) {
1495 if let hir::ItemUse(ref view_path) = item.node {
1496 if let hir::ViewPathList(_, ref items) = view_path.node {
1497 if items.len() == 1 {
1498 if let hir::PathListIdent {ref name, ..} = items[0].node {
1499 let m = format!("braces around {} is unnecessary",
1501 cx.span_lint(UNUSED_IMPORT_BRACES, item.span,
1511 NON_SHORTHAND_FIELD_PATTERNS,
1513 "using `Struct { x: x }` instead of `Struct { x }`"
1516 #[derive(Copy, Clone)]
1517 pub struct NonShorthandFieldPatterns;
1519 impl LintPass for NonShorthandFieldPatterns {
1520 fn get_lints(&self) -> LintArray {
1521 lint_array!(NON_SHORTHAND_FIELD_PATTERNS)
1524 fn check_pat(&mut self, cx: &Context, pat: &hir::Pat) {
1525 let def_map = cx.tcx.def_map.borrow();
1526 if let hir::PatStruct(_, ref v, _) = pat.node {
1527 let field_pats = v.iter().filter(|fieldpat| {
1528 if fieldpat.node.is_shorthand {
1531 let def = def_map.get(&fieldpat.node.pat.id).map(|d| d.full_def());
1532 def == Some(def::DefLocal(fieldpat.node.pat.id))
1534 for fieldpat in field_pats {
1535 if let hir::PatIdent(_, ident, None) = fieldpat.node.pat.node {
1536 if ident.node.name == fieldpat.node.ident.name {
1537 // FIXME: should this comparison really be done on the name?
1538 // doing it on the ident will fail during compilation of libcore
1539 cx.span_lint(NON_SHORTHAND_FIELD_PATTERNS, fieldpat.span,
1540 &format!("the `{}:` in this pattern is redundant and can \
1541 be removed", ident.node))
1552 "unnecessary use of an `unsafe` block"
1555 #[derive(Copy, Clone)]
1556 pub struct UnusedUnsafe;
1558 impl LintPass for UnusedUnsafe {
1559 fn get_lints(&self) -> LintArray {
1560 lint_array!(UNUSED_UNSAFE)
1563 fn check_expr(&mut self, cx: &Context, e: &hir::Expr) {
1564 if let hir::ExprBlock(ref blk) = e.node {
1565 // Don't warn about generated blocks, that'll just pollute the output.
1566 if blk.rules == hir::UnsafeBlock(hir::UserProvided) &&
1567 !cx.tcx.used_unsafe.borrow().contains(&blk.id) {
1568 cx.span_lint(UNUSED_UNSAFE, blk.span, "unnecessary `unsafe` block");
1577 "usage of `unsafe` code"
1580 #[derive(Copy, Clone)]
1581 pub struct UnsafeCode;
1583 impl LintPass for UnsafeCode {
1584 fn get_lints(&self) -> LintArray {
1585 lint_array!(UNSAFE_CODE)
1588 fn check_expr(&mut self, cx: &Context, e: &hir::Expr) {
1589 if let hir::ExprBlock(ref blk) = e.node {
1590 // Don't warn about generated blocks, that'll just pollute the output.
1591 if blk.rules == hir::UnsafeBlock(hir::UserProvided) {
1592 cx.span_lint(UNSAFE_CODE, blk.span, "usage of an `unsafe` block");
1597 fn check_item(&mut self, cx: &Context, it: &hir::Item) {
1599 hir::ItemTrait(hir::Unsafety::Unsafe, _, _, _) =>
1600 cx.span_lint(UNSAFE_CODE, it.span, "declaration of an `unsafe` trait"),
1602 hir::ItemImpl(hir::Unsafety::Unsafe, _, _, _, _, _) =>
1603 cx.span_lint(UNSAFE_CODE, it.span, "implementation of an `unsafe` trait"),
1609 fn check_fn(&mut self, cx: &Context, fk: FnKind, _: &hir::FnDecl,
1610 _: &hir::Block, span: Span, _: ast::NodeId) {
1612 FnKind::ItemFn(_, _, hir::Unsafety::Unsafe, _, _, _) =>
1613 cx.span_lint(UNSAFE_CODE, span, "declaration of an `unsafe` function"),
1615 FnKind::Method(_, sig, _) => {
1616 if sig.unsafety == hir::Unsafety::Unsafe {
1617 cx.span_lint(UNSAFE_CODE, span, "implementation of an `unsafe` method")
1625 fn check_trait_item(&mut self, cx: &Context, trait_item: &hir::TraitItem) {
1626 if let hir::MethodTraitItem(ref sig, None) = trait_item.node {
1627 if sig.unsafety == hir::Unsafety::Unsafe {
1628 cx.span_lint(UNSAFE_CODE, trait_item.span,
1629 "declaration of an `unsafe` method")
1638 "detect mut variables which don't need to be mutable"
1641 #[derive(Copy, Clone)]
1642 pub struct UnusedMut;
1645 fn check_unused_mut_pat(&self, cx: &Context, pats: &[P<hir::Pat>]) {
1646 // collect all mutable pattern and group their NodeIDs by their Identifier to
1647 // avoid false warnings in match arms with multiple patterns
1649 let mut mutables = FnvHashMap();
1651 pat_util::pat_bindings(&cx.tcx.def_map, p, |mode, id, _, path1| {
1652 let ident = path1.node;
1653 if let hir::BindByValue(hir::MutMutable) = mode {
1654 if !ident.name.as_str().starts_with("_") {
1655 match mutables.entry(ident.name.usize()) {
1656 Vacant(entry) => { entry.insert(vec![id]); },
1657 Occupied(mut entry) => { entry.get_mut().push(id); },
1664 let used_mutables = cx.tcx.used_mut_nodes.borrow();
1665 for (_, v) in &mutables {
1666 if !v.iter().any(|e| used_mutables.contains(e)) {
1667 cx.span_lint(UNUSED_MUT, cx.tcx.map.span(v[0]),
1668 "variable does not need to be mutable");
1674 impl LintPass for UnusedMut {
1675 fn get_lints(&self) -> LintArray {
1676 lint_array!(UNUSED_MUT)
1679 fn check_expr(&mut self, cx: &Context, e: &hir::Expr) {
1680 if let hir::ExprMatch(_, ref arms, _) = e.node {
1682 self.check_unused_mut_pat(cx, &a.pats)
1687 fn check_stmt(&mut self, cx: &Context, s: &hir::Stmt) {
1688 if let hir::StmtDecl(ref d, _) = s.node {
1689 if let hir::DeclLocal(ref l) = d.node {
1690 self.check_unused_mut_pat(cx, slice::ref_slice(&l.pat));
1695 fn check_fn(&mut self, cx: &Context,
1696 _: FnKind, decl: &hir::FnDecl,
1697 _: &hir::Block, _: Span, _: ast::NodeId) {
1698 for a in &decl.inputs {
1699 self.check_unused_mut_pat(cx, slice::ref_slice(&a.pat));
1707 "detects unnecessary allocations that can be eliminated"
1710 #[derive(Copy, Clone)]
1711 pub struct UnusedAllocation;
1713 impl LintPass for UnusedAllocation {
1714 fn get_lints(&self) -> LintArray {
1715 lint_array!(UNUSED_ALLOCATION)
1718 fn check_expr(&mut self, cx: &Context, e: &hir::Expr) {
1720 hir::ExprUnary(hir::UnUniq, _) => (),
1724 if let Some(adjustment) = cx.tcx.tables.borrow().adjustments.get(&e.id) {
1725 if let ty::AdjustDerefRef(ty::AutoDerefRef { ref autoref, .. }) = *adjustment {
1727 &Some(ty::AutoPtr(_, hir::MutImmutable)) => {
1728 cx.span_lint(UNUSED_ALLOCATION, e.span,
1729 "unnecessary allocation, use & instead");
1731 &Some(ty::AutoPtr(_, hir::MutMutable)) => {
1732 cx.span_lint(UNUSED_ALLOCATION, e.span,
1733 "unnecessary allocation, use &mut instead");
1745 "detects missing documentation for public members"
1748 pub struct MissingDoc {
1749 /// Stack of IDs of struct definitions.
1750 struct_def_stack: Vec<ast::NodeId>,
1752 /// True if inside variant definition
1755 /// Stack of whether #[doc(hidden)] is set
1756 /// at each level which has lint attributes.
1757 doc_hidden_stack: Vec<bool>,
1759 /// Private traits or trait items that leaked through. Don't check their methods.
1760 private_traits: HashSet<ast::NodeId>,
1764 pub fn new() -> MissingDoc {
1766 struct_def_stack: vec!(),
1768 doc_hidden_stack: vec!(false),
1769 private_traits: HashSet::new(),
1773 fn doc_hidden(&self) -> bool {
1774 *self.doc_hidden_stack.last().expect("empty doc_hidden_stack")
1777 fn check_missing_docs_attrs(&self,
1779 id: Option<ast::NodeId>,
1780 attrs: &[hir::Attribute],
1782 desc: &'static str) {
1783 // If we're building a test harness, then warning about
1784 // documentation is probably not really relevant right now.
1785 if cx.sess().opts.test {
1789 // `#[doc(hidden)]` disables missing_docs check.
1790 if self.doc_hidden() {
1794 // Only check publicly-visible items, using the result from the privacy pass.
1795 // It's an option so the crate root can also use this function (it doesn't
1797 if let Some(ref id) = id {
1798 if !cx.exported_items.contains(id) {
1803 let has_doc = attrs.iter().any(|a| {
1804 match a.node.value.node {
1805 hir::MetaNameValue(ref name, _) if *name == "doc" => true,
1810 cx.span_lint(MISSING_DOCS, sp,
1811 &format!("missing documentation for {}", desc));
1816 impl LintPass for MissingDoc {
1817 fn get_lints(&self) -> LintArray {
1818 lint_array!(MISSING_DOCS)
1821 fn enter_lint_attrs(&mut self, _: &Context, attrs: &[hir::Attribute]) {
1822 let doc_hidden = self.doc_hidden() || attrs.iter().any(|attr| {
1823 attr.check_name("doc") && match attr.meta_item_list() {
1825 Some(l) => attr::contains_name(&l[..], "hidden"),
1828 self.doc_hidden_stack.push(doc_hidden);
1831 fn exit_lint_attrs(&mut self, _: &Context, _: &[hir::Attribute]) {
1832 self.doc_hidden_stack.pop().expect("empty doc_hidden_stack");
1835 fn check_struct_def(&mut self, _: &Context, _: &hir::StructDef,
1836 _: ast::Ident, _: &hir::Generics, id: ast::NodeId) {
1837 self.struct_def_stack.push(id);
1840 fn check_struct_def_post(&mut self, _: &Context, _: &hir::StructDef,
1841 _: ast::Ident, _: &hir::Generics, id: ast::NodeId) {
1842 let popped = self.struct_def_stack.pop().expect("empty struct_def_stack");
1843 assert!(popped == id);
1846 fn check_crate(&mut self, cx: &Context, krate: &hir::Crate) {
1847 self.check_missing_docs_attrs(cx, None, &krate.attrs, krate.span, "crate");
1850 fn check_item(&mut self, cx: &Context, it: &hir::Item) {
1851 let desc = match it.node {
1852 hir::ItemFn(..) => "a function",
1853 hir::ItemMod(..) => "a module",
1854 hir::ItemEnum(..) => "an enum",
1855 hir::ItemStruct(..) => "a struct",
1856 hir::ItemTrait(_, _, _, ref items) => {
1857 // Issue #11592, traits are always considered exported, even when private.
1858 if it.vis == hir::Visibility::Inherited {
1859 self.private_traits.insert(it.id);
1861 self.private_traits.insert(itm.id);
1867 hir::ItemTy(..) => "a type alias",
1868 hir::ItemImpl(_, _, _, Some(ref trait_ref), _, ref impl_items) => {
1869 // If the trait is private, add the impl items to private_traits so they don't get
1870 // reported for missing docs.
1871 let real_trait = cx.tcx.trait_ref_to_def_id(trait_ref);
1872 match cx.tcx.map.find(real_trait.node) {
1873 Some(hir_map::NodeItem(item)) => if item.vis == hir::Visibility::Inherited {
1874 for itm in impl_items {
1875 self.private_traits.insert(itm.id);
1882 hir::ItemConst(..) => "a constant",
1883 hir::ItemStatic(..) => "a static",
1887 self.check_missing_docs_attrs(cx, Some(it.id), &it.attrs, it.span, desc);
1890 fn check_trait_item(&mut self, cx: &Context, trait_item: &hir::TraitItem) {
1891 if self.private_traits.contains(&trait_item.id) { return }
1893 let desc = match trait_item.node {
1894 hir::ConstTraitItem(..) => "an associated constant",
1895 hir::MethodTraitItem(..) => "a trait method",
1896 hir::TypeTraitItem(..) => "an associated type",
1899 self.check_missing_docs_attrs(cx, Some(trait_item.id),
1901 trait_item.span, desc);
1904 fn check_impl_item(&mut self, cx: &Context, impl_item: &hir::ImplItem) {
1905 // If the method is an impl for a trait, don't doc.
1906 if method_context(cx, impl_item.id, impl_item.span) == MethodContext::TraitImpl {
1910 let desc = match impl_item.node {
1911 hir::ConstImplItem(..) => "an associated constant",
1912 hir::MethodImplItem(..) => "a method",
1913 hir::TypeImplItem(_) => "an associated type",
1915 self.check_missing_docs_attrs(cx, Some(impl_item.id),
1917 impl_item.span, desc);
1920 fn check_struct_field(&mut self, cx: &Context, sf: &hir::StructField) {
1921 if let hir::NamedField(_, vis) = sf.node.kind {
1922 if vis == hir::Public || self.in_variant {
1923 let cur_struct_def = *self.struct_def_stack.last()
1924 .expect("empty struct_def_stack");
1925 self.check_missing_docs_attrs(cx, Some(cur_struct_def),
1926 &sf.node.attrs, sf.span,
1932 fn check_variant(&mut self, cx: &Context, v: &hir::Variant, _: &hir::Generics) {
1933 self.check_missing_docs_attrs(cx, Some(v.node.id), &v.node.attrs, v.span, "a variant");
1934 assert!(!self.in_variant);
1935 self.in_variant = true;
1938 fn check_variant_post(&mut self, _: &Context, _: &hir::Variant, _: &hir::Generics) {
1939 assert!(self.in_variant);
1940 self.in_variant = false;
1945 pub MISSING_COPY_IMPLEMENTATIONS,
1947 "detects potentially-forgotten implementations of `Copy`"
1950 #[derive(Copy, Clone)]
1951 pub struct MissingCopyImplementations;
1953 impl LintPass for MissingCopyImplementations {
1954 fn get_lints(&self) -> LintArray {
1955 lint_array!(MISSING_COPY_IMPLEMENTATIONS)
1958 fn check_item(&mut self, cx: &Context, item: &hir::Item) {
1959 if !cx.exported_items.contains(&item.id) {
1962 let (def, ty) = match item.node {
1963 hir::ItemStruct(_, ref ast_generics) => {
1964 if ast_generics.is_parameterized() {
1967 let def = cx.tcx.lookup_adt_def(DefId::local(item.id));
1968 (def, cx.tcx.mk_struct(def,
1969 cx.tcx.mk_substs(Substs::empty())))
1971 hir::ItemEnum(_, ref ast_generics) => {
1972 if ast_generics.is_parameterized() {
1975 let def = cx.tcx.lookup_adt_def(DefId::local(item.id));
1976 (def, cx.tcx.mk_enum(def,
1977 cx.tcx.mk_substs(Substs::empty())))
1981 if def.has_dtor() { return; }
1982 let parameter_environment = cx.tcx.empty_parameter_environment();
1983 // FIXME (@jroesch) should probably inver this so that the parameter env still impls this
1985 if !ty.moves_by_default(¶meter_environment, item.span) {
1988 if parameter_environment.can_type_implement_copy(ty, item.span).is_ok() {
1989 cx.span_lint(MISSING_COPY_IMPLEMENTATIONS,
1991 "type could implement `Copy`; consider adding `impl \
1998 MISSING_DEBUG_IMPLEMENTATIONS,
2000 "detects missing implementations of fmt::Debug"
2003 pub struct MissingDebugImplementations {
2004 impling_types: Option<NodeSet>,
2007 impl MissingDebugImplementations {
2008 pub fn new() -> MissingDebugImplementations {
2009 MissingDebugImplementations {
2010 impling_types: None,
2015 impl LintPass for MissingDebugImplementations {
2016 fn get_lints(&self) -> LintArray {
2017 lint_array!(MISSING_DEBUG_IMPLEMENTATIONS)
2020 fn check_item(&mut self, cx: &Context, item: &hir::Item) {
2021 if !cx.exported_items.contains(&item.id) {
2026 hir::ItemStruct(..) | hir::ItemEnum(..) => {},
2030 let debug = match cx.tcx.lang_items.debug_trait() {
2031 Some(debug) => debug,
2035 if self.impling_types.is_none() {
2036 let debug_def = cx.tcx.lookup_trait_def(debug);
2037 let mut impls = NodeSet();
2038 debug_def.for_each_impl(cx.tcx, |d| {
2040 if let Some(ty_def) = cx.tcx.node_id_to_type(d.node).ty_to_def_id() {
2041 impls.insert(ty_def.node);
2046 self.impling_types = Some(impls);
2047 debug!("{:?}", self.impling_types);
2050 if !self.impling_types.as_ref().unwrap().contains(&item.id) {
2051 cx.span_lint(MISSING_DEBUG_IMPLEMENTATIONS,
2053 "type does not implement `fmt::Debug`; consider adding #[derive(Debug)] \
2054 or a manual implementation")
2062 "detects use of #[deprecated] items"
2065 /// Checks for use of items with `#[deprecated]` attributes
2066 #[derive(Copy, Clone)]
2067 pub struct Stability;
2070 fn lint(&self, cx: &Context, _id: DefId,
2071 span: Span, stability: &Option<&attr::Stability>) {
2072 // Deprecated attributes apply in-crate and cross-crate.
2073 let (lint, label) = match *stability {
2074 Some(&attr::Stability { deprecated_since: Some(_), .. }) =>
2075 (DEPRECATED, "deprecated"),
2079 output(cx, span, stability, lint, label);
2081 fn output(cx: &Context, span: Span, stability: &Option<&attr::Stability>,
2082 lint: &'static Lint, label: &'static str) {
2083 let msg = match *stability {
2084 Some(&attr::Stability { reason: Some(ref s), .. }) => {
2085 format!("use of {} item: {}", label, *s)
2087 _ => format!("use of {} item", label)
2090 cx.span_lint(lint, span, &msg[..]);
2095 fn hir_to_ast_stability(stab: &attr::Stability) -> attr::Stability {
2097 level: match stab.level {
2098 attr::Unstable => attr::Unstable,
2099 attr::Stable => attr::Stable,
2101 feature: stab.feature.clone(),
2102 since: stab.since.clone(),
2103 deprecated_since: stab.deprecated_since.clone(),
2104 reason: stab.reason.clone(),
2109 impl LintPass for Stability {
2110 fn get_lints(&self) -> LintArray {
2111 lint_array!(DEPRECATED)
2114 fn check_item(&mut self, cx: &Context, item: &hir::Item) {
2115 stability::check_item(cx.tcx, item, false,
2117 self.lint(cx, id, sp,
2118 &stab.map(|s| hir_to_ast_stability(s)).as_ref()));
2121 fn check_expr(&mut self, cx: &Context, e: &hir::Expr) {
2122 stability::check_expr(cx.tcx, e,
2124 self.lint(cx, id, sp,
2125 &stab.map(|s| hir_to_ast_stability(s)).as_ref()));
2128 fn check_path(&mut self, cx: &Context, path: &hir::Path, id: ast::NodeId) {
2129 stability::check_path(cx.tcx, path, id,
2131 self.lint(cx, id, sp,
2132 &stab.map(|s| hir_to_ast_stability(s)).as_ref()));
2135 fn check_pat(&mut self, cx: &Context, pat: &hir::Pat) {
2136 stability::check_pat(cx.tcx, pat,
2138 self.lint(cx, id, sp,
2139 &stab.map(|s| hir_to_ast_stability(s)).as_ref()));
2144 pub UNCONDITIONAL_RECURSION,
2146 "functions that cannot return without calling themselves"
2149 #[derive(Copy, Clone)]
2150 pub struct UnconditionalRecursion;
2153 impl LintPass for UnconditionalRecursion {
2154 fn get_lints(&self) -> LintArray {
2155 lint_array![UNCONDITIONAL_RECURSION]
2158 fn check_fn(&mut self, cx: &Context, fn_kind: FnKind, _: &hir::FnDecl,
2159 blk: &hir::Block, sp: Span, id: ast::NodeId) {
2160 type F = for<'tcx> fn(&ty::ctxt<'tcx>,
2161 ast::NodeId, ast::NodeId, ast::Ident, ast::NodeId) -> bool;
2163 let method = match fn_kind {
2164 FnKind::ItemFn(..) => None,
2165 FnKind::Method(..) => {
2166 cx.tcx.impl_or_trait_item(DefId::local(id)).as_opt_method()
2168 // closures can't recur, so they don't matter.
2169 FnKind::Closure => return
2172 // Walk through this function (say `f`) looking to see if
2173 // every possible path references itself, i.e. the function is
2174 // called recursively unconditionally. This is done by trying
2175 // to find a path from the entry node to the exit node that
2176 // *doesn't* call `f` by traversing from the entry while
2177 // pretending that calls of `f` are sinks (i.e. ignoring any
2178 // exit edges from them).
2180 // NB. this has an edge case with non-returning statements,
2181 // like `loop {}` or `panic!()`: control flow never reaches
2182 // the exit node through these, so one can have a function
2183 // that never actually calls itselfs but is still picked up by
2186 // fn f(cond: bool) {
2187 // if !cond { panic!() } // could come from `assert!(cond)`
2191 // In general, functions of that form may be able to call
2192 // itself a finite number of times and then diverge. The lint
2193 // considers this to be an error for two reasons, (a) it is
2194 // easier to implement, and (b) it seems rare to actually want
2195 // to have behaviour like the above, rather than
2196 // e.g. accidentally recurring after an assert.
2198 let cfg = cfg::CFG::new(cx.tcx, blk);
2200 let mut work_queue = vec![cfg.entry];
2201 let mut reached_exit_without_self_call = false;
2202 let mut self_call_spans = vec![];
2203 let mut visited = HashSet::new();
2205 while let Some(idx) = work_queue.pop() {
2206 if idx == cfg.exit {
2208 reached_exit_without_self_call = true;
2212 let cfg_id = idx.node_id();
2213 if visited.contains(&cfg_id) {
2217 visited.insert(cfg_id);
2219 let node_id = cfg.graph.node_data(idx).id();
2221 // is this a recursive call?
2222 let self_recursive = if node_id != ast::DUMMY_NODE_ID {
2224 Some(ref method) => {
2225 expr_refers_to_this_method(cx.tcx, method, node_id)
2227 None => expr_refers_to_this_fn(cx.tcx, id, node_id)
2233 self_call_spans.push(cx.tcx.map.span(node_id));
2234 // this is a self call, so we shouldn't explore past
2235 // this node in the CFG.
2238 // add the successors of this node to explore the graph further.
2239 for (_, edge) in cfg.graph.outgoing_edges(idx) {
2240 let target_idx = edge.target();
2241 let target_cfg_id = target_idx.node_id();
2242 if !visited.contains(&target_cfg_id) {
2243 work_queue.push(target_idx)
2248 // Check the number of self calls because a function that
2249 // doesn't return (e.g. calls a `-> !` function or `loop { /*
2250 // no break */ }`) shouldn't be linted unless it actually
2252 if !reached_exit_without_self_call && !self_call_spans.is_empty() {
2253 cx.span_lint(UNCONDITIONAL_RECURSION, sp,
2254 "function cannot return without recurring");
2256 // FIXME #19668: these could be span_lint_note's instead of this manual guard.
2257 if cx.current_level(UNCONDITIONAL_RECURSION) != Level::Allow {
2258 let sess = cx.sess();
2259 // offer some help to the programmer.
2260 for call in &self_call_spans {
2261 sess.span_note(*call, "recursive call site")
2263 sess.fileline_help(sp, "a `loop` may express intention \
2264 better if this is on purpose")
2271 // Functions for identifying if the given Expr NodeId `id`
2272 // represents a call to the function `fn_id`/method `method`.
2274 fn expr_refers_to_this_fn(tcx: &ty::ctxt,
2276 id: ast::NodeId) -> bool {
2277 match tcx.map.get(id) {
2278 hir_map::NodeExpr(&hir::Expr { node: hir::ExprCall(ref callee, _), .. }) => {
2279 tcx.def_map.borrow().get(&callee.id)
2280 .map_or(false, |def| def.def_id() == DefId::local(fn_id))
2286 // Check if the expression `id` performs a call to `method`.
2287 fn expr_refers_to_this_method(tcx: &ty::ctxt,
2288 method: &ty::Method,
2289 id: ast::NodeId) -> bool {
2290 let tables = tcx.tables.borrow();
2292 // Check for method calls and overloaded operators.
2293 if let Some(m) = tables.method_map.get(&ty::MethodCall::expr(id)) {
2294 if method_call_refers_to_method(tcx, method, m.def_id, m.substs, id) {
2299 // Check for overloaded autoderef method calls.
2300 if let Some(&ty::AdjustDerefRef(ref adj)) = tables.adjustments.get(&id) {
2301 for i in 0..adj.autoderefs {
2302 let method_call = ty::MethodCall::autoderef(id, i as u32);
2303 if let Some(m) = tables.method_map.get(&method_call) {
2304 if method_call_refers_to_method(tcx, method, m.def_id, m.substs, id) {
2311 // Check for calls to methods via explicit paths (e.g. `T::method()`).
2312 match tcx.map.get(id) {
2313 hir_map::NodeExpr(&hir::Expr { node: hir::ExprCall(ref callee, _), .. }) => {
2314 match tcx.def_map.borrow().get(&callee.id).map(|d| d.full_def()) {
2315 Some(def::DefMethod(def_id)) => {
2316 let no_substs = &ty::ItemSubsts::empty();
2317 let ts = tables.item_substs.get(&callee.id).unwrap_or(no_substs);
2318 method_call_refers_to_method(tcx, method, def_id, &ts.substs, id)
2327 // Check if the method call to the method with the ID `callee_id`
2328 // and instantiated with `callee_substs` refers to method `method`.
2329 fn method_call_refers_to_method<'tcx>(tcx: &ty::ctxt<'tcx>,
2330 method: &ty::Method,
2332 callee_substs: &Substs<'tcx>,
2333 expr_id: ast::NodeId) -> bool {
2334 let callee_item = tcx.impl_or_trait_item(callee_id);
2336 match callee_item.container() {
2337 // This is an inherent method, so the `def_id` refers
2338 // directly to the method definition.
2339 ty::ImplContainer(_) => {
2340 callee_id == method.def_id
2343 // A trait method, from any number of possible sources.
2344 // Attempt to select a concrete impl before checking.
2345 ty::TraitContainer(trait_def_id) => {
2346 let trait_substs = callee_substs.clone().method_to_trait();
2347 let trait_substs = tcx.mk_substs(trait_substs);
2348 let trait_ref = ty::TraitRef::new(trait_def_id, trait_substs);
2349 let trait_ref = ty::Binder(trait_ref);
2350 let span = tcx.map.span(expr_id);
2352 traits::Obligation::new(traits::ObligationCause::misc(span, expr_id),
2353 trait_ref.to_poly_trait_predicate());
2355 let param_env = ty::ParameterEnvironment::for_item(tcx, method.def_id.node);
2356 let infcx = infer::new_infer_ctxt(tcx, &tcx.tables, Some(param_env), false);
2357 let mut selcx = traits::SelectionContext::new(&infcx);
2358 match selcx.select(&obligation) {
2359 // The method comes from a `T: Trait` bound.
2360 // If `T` is `Self`, then this call is inside
2361 // a default method definition.
2362 Ok(Some(traits::VtableParam(_))) => {
2363 let self_ty = callee_substs.self_ty();
2364 let on_self = self_ty.map_or(false, |t| t.is_self());
2365 // We can only be recurring in a default
2366 // method if we're being called literally
2367 // on the `Self` type.
2368 on_self && callee_id == method.def_id
2371 // The `impl` is known, so we check that with a
2373 Ok(Some(traits::VtableImpl(vtable_impl))) => {
2374 let container = ty::ImplContainer(vtable_impl.impl_def_id);
2375 // It matches if it comes from the same impl,
2376 // and has the same method name.
2377 container == method.container
2378 && callee_item.name() == method.name
2381 // There's no way to know if this call is
2382 // recursive, so we assume it's not.
2394 "compiler plugin used as ordinary library in non-plugin crate"
2397 #[derive(Copy, Clone)]
2398 pub struct PluginAsLibrary;
2400 impl LintPass for PluginAsLibrary {
2401 fn get_lints(&self) -> LintArray {
2402 lint_array![PLUGIN_AS_LIBRARY]
2405 fn check_item(&mut self, cx: &Context, it: &hir::Item) {
2406 if cx.sess().plugin_registrar_fn.get().is_some() {
2407 // We're compiling a plugin; it's fine to link other plugins.
2412 hir::ItemExternCrate(..) => (),
2416 let md = match cx.sess().cstore.find_extern_mod_stmt_cnum(it.id) {
2417 Some(cnum) => cx.sess().cstore.get_crate_data(cnum),
2419 // Probably means we aren't linking the crate for some reason.
2421 // Not sure if / when this could happen.
2426 if decoder::get_plugin_registrar_fn(md.data()).is_some() {
2427 cx.span_lint(PLUGIN_AS_LIBRARY, it.span,
2428 "compiler plugin used as an ordinary library");
2434 PRIVATE_NO_MANGLE_FNS,
2436 "functions marked #[no_mangle] should be exported"
2440 PRIVATE_NO_MANGLE_STATICS,
2442 "statics marked #[no_mangle] should be exported"
2446 NO_MANGLE_CONST_ITEMS,
2448 "const items will not have their symbols exported"
2451 #[derive(Copy, Clone)]
2452 pub struct InvalidNoMangleItems;
2454 impl LintPass for InvalidNoMangleItems {
2455 fn get_lints(&self) -> LintArray {
2456 lint_array!(PRIVATE_NO_MANGLE_FNS,
2457 PRIVATE_NO_MANGLE_STATICS,
2458 NO_MANGLE_CONST_ITEMS)
2461 fn check_item(&mut self, cx: &Context, it: &hir::Item) {
2463 hir::ItemFn(..) => {
2464 if attr::contains_name(&it.attrs, "no_mangle") &&
2465 !cx.exported_items.contains(&it.id) {
2466 let msg = format!("function {} is marked #[no_mangle], but not exported",
2468 cx.span_lint(PRIVATE_NO_MANGLE_FNS, it.span, &msg);
2471 hir::ItemStatic(..) => {
2472 if attr::contains_name(&it.attrs, "no_mangle") &&
2473 !cx.exported_items.contains(&it.id) {
2474 let msg = format!("static {} is marked #[no_mangle], but not exported",
2476 cx.span_lint(PRIVATE_NO_MANGLE_STATICS, it.span, &msg);
2479 hir::ItemConst(..) => {
2480 if attr::contains_name(&it.attrs, "no_mangle") {
2481 // Const items do not refer to a particular location in memory, and therefore
2482 // don't have anything to attach a symbol to
2483 let msg = "const items should never be #[no_mangle], consider instead using \
2485 cx.span_lint(NO_MANGLE_CONST_ITEMS, it.span, msg);
2493 #[derive(Clone, Copy)]
2494 pub struct MutableTransmutes;
2499 "mutating transmuted &mut T from &T may cause undefined behavior"
2502 impl LintPass for MutableTransmutes {
2503 fn get_lints(&self) -> LintArray {
2504 lint_array!(MUTABLE_TRANSMUTES)
2507 fn check_expr(&mut self, cx: &Context, expr: &hir::Expr) {
2508 use syntax::abi::RustIntrinsic;
2510 let msg = "mutating transmuted &mut T from &T may cause undefined behavior,\
2511 consider instead using an UnsafeCell";
2512 match get_transmute_from_to(cx, expr) {
2513 Some((&ty::TyRef(_, from_mt), &ty::TyRef(_, to_mt))) => {
2514 if to_mt.mutbl == hir::Mutability::MutMutable
2515 && from_mt.mutbl == hir::Mutability::MutImmutable {
2516 cx.span_lint(MUTABLE_TRANSMUTES, expr.span, msg);
2522 fn get_transmute_from_to<'a, 'tcx>(cx: &Context<'a, 'tcx>, expr: &hir::Expr)
2523 -> Option<(&'tcx ty::TypeVariants<'tcx>, &'tcx ty::TypeVariants<'tcx>)> {
2525 hir::ExprPath(..) => (),
2528 if let def::DefFn(did, _) = cx.tcx.resolve_expr(expr) {
2529 if !def_id_is_transmute(cx, did) {
2532 let typ = cx.tcx.node_id_to_type(expr.id);
2534 ty::TyBareFn(_, ref bare_fn) if bare_fn.abi == RustIntrinsic => {
2535 if let ty::FnConverging(to) = bare_fn.sig.0.output {
2536 let from = bare_fn.sig.0.inputs[0];
2537 return Some((&from.sty, &to.sty));
2546 fn def_id_is_transmute(cx: &Context, def_id: DefId) -> bool {
2547 match cx.tcx.lookup_item_type(def_id).ty.sty {
2548 ty::TyBareFn(_, ref bfty) if bfty.abi == RustIntrinsic => (),
2551 cx.tcx.with_path(def_id, |path| match path.last() {
2552 Some(ref last) => last.name().as_str() == "transmute",
2559 /// Forbids using the `#[feature(...)]` attribute
2560 #[derive(Copy, Clone)]
2561 pub struct UnstableFeatures;
2566 "enabling unstable features (deprecated. do not use)"
2569 impl LintPass for UnstableFeatures {
2570 fn get_lints(&self) -> LintArray {
2571 lint_array!(UNSTABLE_FEATURES)
2573 fn check_attribute(&mut self, ctx: &Context, attr: &hir::Attribute) {
2574 if attr::contains_name(&[attr.node.value.clone()], "feature") {
2575 if let Some(items) = attr.node.value.meta_item_list() {
2577 ctx.span_lint(UNSTABLE_FEATURES, item.span, "unstable feature");
2584 /// Lints for attempts to impl Drop on types that have `#[repr(C)]`
2585 /// attribute (see issue #24585).
2586 #[derive(Copy, Clone)]
2587 pub struct DropWithReprExtern;
2590 DROP_WITH_REPR_EXTERN,
2592 "use of #[repr(C)] on a type that implements Drop"
2595 impl LintPass for DropWithReprExtern {
2596 fn get_lints(&self) -> LintArray {
2597 lint_array!(DROP_WITH_REPR_EXTERN)
2599 fn check_crate(&mut self, ctx: &Context, _: &hir::Crate) {
2600 for dtor_did in ctx.tcx.destructors.borrow().iter() {
2601 let (drop_impl_did, dtor_self_type) =
2602 if dtor_did.is_local() {
2603 let impl_did = ctx.tcx.map.get_parent_did(dtor_did.node);
2604 let ty = ctx.tcx.lookup_item_type(impl_did).ty;
2610 match dtor_self_type.sty {
2611 ty::TyEnum(self_type_def, _) |
2612 ty::TyStruct(self_type_def, _) => {
2613 let self_type_did = self_type_def.did;
2614 let hints = ctx.tcx.lookup_repr_hints(self_type_did);
2615 if hints.iter().any(|attr| *attr == attr::ReprExtern) &&
2616 self_type_def.dtor_kind().has_drop_flag() {
2617 let drop_impl_span = ctx.tcx.map.def_id_span(drop_impl_did,
2619 let self_defn_span = ctx.tcx.map.def_id_span(self_type_did,
2621 ctx.span_lint(DROP_WITH_REPR_EXTERN,
2623 "implementing Drop adds hidden state to types, \
2624 possibly conflicting with `#[repr(C)]`");
2625 // FIXME #19668: could be span_lint_note instead of manual guard.
2626 if ctx.current_level(DROP_WITH_REPR_EXTERN) != Level::Allow {
2627 ctx.sess().span_note(self_defn_span,
2628 "the `#[repr(C)]` attribute is attached here");