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 as syntax_attr;
50 use syntax::codemap::{self, Span};
51 use syntax::feature_gate::{KNOWN_ATTRIBUTES, AttributeType};
52 use rustc_front::hir::{TyIs, TyUs, TyI8, TyU8, TyI16, TyU16, TyI32, TyU32, TyI64, TyU64};
57 use rustc_front::attr::{self, AttrMetaMethods};
58 use rustc_front::visit::{self, FnKind, Visitor};
59 use rustc_front::lowering::unlower_attribute;
61 use rustc_front::util::is_shift_binop;
63 // hardwired lints from librustc
64 pub use lint::builtin::*;
69 "suggest using `loop { }` instead of `while true { }`"
72 #[derive(Copy, Clone)]
75 impl LintPass for WhileTrue {
76 fn get_lints(&self) -> LintArray {
77 lint_array!(WHILE_TRUE)
80 fn check_expr(&mut self, cx: &Context, e: &hir::Expr) {
81 if let hir::ExprWhile(ref cond, _, _) = e.node {
82 if let hir::ExprLit(ref lit) = cond.node {
83 if let hir::LitBool(true) = lit.node {
84 cx.span_lint(WHILE_TRUE, e.span,
85 "denote infinite loops with loop { ... }");
95 "comparisons made useless by limits of the types involved"
101 "literal out of range for its type"
107 "shift exceeds the type's number of bits"
110 #[derive(Copy, Clone)]
111 pub struct TypeLimits {
112 /// Id of the last visited negated expression
113 negated_expr_id: ast::NodeId,
117 pub fn new() -> TypeLimits {
124 impl LintPass for TypeLimits {
125 fn get_lints(&self) -> LintArray {
126 lint_array!(UNUSED_COMPARISONS, OVERFLOWING_LITERALS, EXCEEDING_BITSHIFTS)
129 fn check_expr(&mut self, cx: &Context, e: &hir::Expr) {
131 hir::ExprUnary(hir::UnNeg, ref expr) => {
133 hir::ExprLit(ref lit) => {
135 hir::LitInt(_, hir::UnsignedIntLit(_)) => {
136 check_unsigned_negation_feature(cx, e.span);
138 hir::LitInt(_, hir::UnsuffixedIntLit(_)) => {
139 if let ty::TyUint(_) = cx.tcx.node_id_to_type(e.id).sty {
140 check_unsigned_negation_feature(cx, e.span);
147 let t = cx.tcx.node_id_to_type(expr.id);
150 check_unsigned_negation_feature(cx, e.span);
156 // propagate negation, if the negation itself isn't negated
157 if self.negated_expr_id != e.id {
158 self.negated_expr_id = expr.id;
161 hir::ExprParen(ref expr) if self.negated_expr_id == e.id => {
162 self.negated_expr_id = expr.id;
164 hir::ExprBinary(binop, ref l, ref r) => {
165 if is_comparison(binop) && !check_limits(cx.tcx, binop, &**l, &**r) {
166 cx.span_lint(UNUSED_COMPARISONS, e.span,
167 "comparison is useless due to type limits");
170 if is_shift_binop(binop.node) {
171 let opt_ty_bits = match cx.tcx.node_id_to_type(l.id).sty {
172 ty::TyInt(t) => Some(int_ty_bits(t, cx.sess().target.int_type)),
173 ty::TyUint(t) => Some(uint_ty_bits(t, cx.sess().target.uint_type)),
177 if let Some(bits) = opt_ty_bits {
178 let exceeding = if let hir::ExprLit(ref lit) = r.node {
179 if let hir::LitInt(shift, _) = lit.node { shift >= bits }
182 match eval_const_expr_partial(cx.tcx, &r, ExprTypeChecked) {
183 Ok(ConstVal::Int(shift)) => { shift as u64 >= bits },
184 Ok(ConstVal::Uint(shift)) => { shift >= bits },
189 cx.span_lint(EXCEEDING_BITSHIFTS, e.span,
190 "bitshift exceeds the type's number of bits");
195 hir::ExprLit(ref lit) => {
196 match cx.tcx.node_id_to_type(e.id).sty {
199 hir::LitInt(v, hir::SignedIntLit(_, hir::Plus)) |
200 hir::LitInt(v, hir::UnsuffixedIntLit(hir::Plus)) => {
201 let int_type = if let hir::TyIs = t {
202 cx.sess().target.int_type
206 let (_, max) = int_ty_range(int_type);
207 let negative = self.negated_expr_id == e.id;
209 // Detect literal value out of range [min, max] inclusive
210 // avoiding use of -min to prevent overflow/panic
211 if (negative && v > max as u64 + 1) ||
212 (!negative && v > max as u64) {
213 cx.span_lint(OVERFLOWING_LITERALS, e.span,
214 &*format!("literal out of range for {:?}", t));
222 let uint_type = if let hir::TyUs = t {
223 cx.sess().target.uint_type
227 let (min, max) = uint_ty_range(uint_type);
228 let lit_val: u64 = match lit.node {
229 hir::LitByte(_v) => return, // _v is u8, within range by definition
230 hir::LitInt(v, _) => v,
233 if lit_val < min || lit_val > max {
234 cx.span_lint(OVERFLOWING_LITERALS, e.span,
235 &*format!("literal out of range for {:?}", t));
239 let (min, max) = float_ty_range(t);
240 let lit_val: f64 = match lit.node {
241 hir::LitFloat(ref v, _) |
242 hir::LitFloatUnsuffixed(ref v) => {
250 if lit_val < min || lit_val > max {
251 cx.span_lint(OVERFLOWING_LITERALS, e.span,
252 &*format!("literal out of range for {:?}", t));
261 fn is_valid<T:cmp::PartialOrd>(binop: hir::BinOp, v: T,
262 min: T, max: T) -> bool {
264 hir::BiLt => v > min && v <= max,
265 hir::BiLe => v >= min && v < max,
266 hir::BiGt => v >= min && v < max,
267 hir::BiGe => v > min && v <= max,
268 hir::BiEq | hir::BiNe => v >= min && v <= max,
273 fn rev_binop(binop: hir::BinOp) -> hir::BinOp {
274 codemap::respan(binop.span, match binop.node {
275 hir::BiLt => hir::BiGt,
276 hir::BiLe => hir::BiGe,
277 hir::BiGt => hir::BiLt,
278 hir::BiGe => hir::BiLe,
283 // for isize & usize, be conservative with the warnings, so that the
284 // warnings are consistent between 32- and 64-bit platforms
285 fn int_ty_range(int_ty: hir::IntTy) -> (i64, i64) {
287 hir::TyIs => (i64::MIN, i64::MAX),
288 hir::TyI8 => (i8::MIN as i64, i8::MAX as i64),
289 hir::TyI16 => (i16::MIN as i64, i16::MAX as i64),
290 hir::TyI32 => (i32::MIN as i64, i32::MAX as i64),
291 hir::TyI64 => (i64::MIN, i64::MAX)
295 fn uint_ty_range(uint_ty: hir::UintTy) -> (u64, u64) {
297 hir::TyUs => (u64::MIN, u64::MAX),
298 hir::TyU8 => (u8::MIN as u64, u8::MAX as u64),
299 hir::TyU16 => (u16::MIN as u64, u16::MAX as u64),
300 hir::TyU32 => (u32::MIN as u64, u32::MAX as u64),
301 hir::TyU64 => (u64::MIN, u64::MAX)
305 fn float_ty_range(float_ty: hir::FloatTy) -> (f64, f64) {
307 hir::TyF32 => (f32::MIN as f64, f32::MAX as f64),
308 hir::TyF64 => (f64::MIN, f64::MAX)
312 fn int_ty_bits(int_ty: hir::IntTy, target_int_ty: hir::IntTy) -> u64 {
314 hir::TyIs => int_ty_bits(target_int_ty, target_int_ty),
315 hir::TyI8 => i8::BITS as u64,
316 hir::TyI16 => i16::BITS as u64,
317 hir::TyI32 => i32::BITS as u64,
318 hir::TyI64 => i64::BITS as u64
322 fn uint_ty_bits(uint_ty: hir::UintTy, target_uint_ty: hir::UintTy) -> u64 {
324 hir::TyUs => uint_ty_bits(target_uint_ty, target_uint_ty),
325 hir::TyU8 => u8::BITS as u64,
326 hir::TyU16 => u16::BITS as u64,
327 hir::TyU32 => u32::BITS as u64,
328 hir::TyU64 => u64::BITS as u64
332 fn check_limits(tcx: &ty::ctxt, binop: hir::BinOp,
333 l: &hir::Expr, r: &hir::Expr) -> bool {
334 let (lit, expr, swap) = match (&l.node, &r.node) {
335 (&hir::ExprLit(_), _) => (l, r, true),
336 (_, &hir::ExprLit(_)) => (r, l, false),
339 // Normalize the binop so that the literal is always on the RHS in
341 let norm_binop = if swap {
346 match tcx.node_id_to_type(expr.id).sty {
347 ty::TyInt(int_ty) => {
348 let (min, max) = int_ty_range(int_ty);
349 let lit_val: i64 = match lit.node {
350 hir::ExprLit(ref li) => match li.node {
351 hir::LitInt(v, hir::SignedIntLit(_, hir::Plus)) |
352 hir::LitInt(v, hir::UnsuffixedIntLit(hir::Plus)) => v as i64,
353 hir::LitInt(v, hir::SignedIntLit(_, hir::Minus)) |
354 hir::LitInt(v, hir::UnsuffixedIntLit(hir::Minus)) => -(v as i64),
359 is_valid(norm_binop, lit_val, min, max)
361 ty::TyUint(uint_ty) => {
362 let (min, max): (u64, u64) = uint_ty_range(uint_ty);
363 let lit_val: u64 = match lit.node {
364 hir::ExprLit(ref li) => match li.node {
365 hir::LitInt(v, _) => v,
370 is_valid(norm_binop, lit_val, min, max)
376 fn is_comparison(binop: hir::BinOp) -> bool {
378 hir::BiEq | hir::BiLt | hir::BiLe |
379 hir::BiNe | hir::BiGe | hir::BiGt => true,
384 fn check_unsigned_negation_feature(cx: &Context, span: Span) {
385 if !cx.sess().features.borrow().negate_unsigned {
386 // FIXME(#27141): change this to syntax::feature_gate::emit_feature_err…
387 cx.sess().span_warn(span,
388 "unary negation of unsigned integers will be feature gated in the future");
389 // …and remove following two expressions.
390 if option_env!("CFG_DISABLE_UNSTABLE_FEATURES").is_some() { return; }
391 cx.sess().fileline_help(span, "add #![feature(negate_unsigned)] to the \
392 crate attributes to enable the gate in advance");
401 "proper use of libc types in foreign modules"
404 struct ImproperCTypesVisitor<'a, 'tcx: 'a> {
405 cx: &'a Context<'a, 'tcx>
410 FfiUnsafe(&'static str),
411 FfiBadStruct(DefId, &'static str),
412 FfiBadEnum(DefId, &'static str)
415 /// Check if this enum can be safely exported based on the
416 /// "nullable pointer optimization". Currently restricted
417 /// to function pointers and references, but could be
418 /// expanded to cover NonZero raw pointers and newtypes.
419 /// FIXME: This duplicates code in trans.
420 fn is_repr_nullable_ptr<'tcx>(tcx: &ty::ctxt<'tcx>,
421 def: ty::AdtDef<'tcx>,
422 substs: &Substs<'tcx>)
424 if def.variants.len() == 2 {
427 if def.variants[0].fields.is_empty() {
429 } else if def.variants[1].fields.is_empty() {
435 if def.variants[data_idx].fields.len() == 1 {
436 match def.variants[data_idx].fields[0].ty(tcx, substs).sty {
437 ty::TyBareFn(None, _) => { return true; }
438 ty::TyRef(..) => { return true; }
446 fn ast_ty_to_normalized<'tcx>(tcx: &ty::ctxt<'tcx>,
449 let tty = match tcx.ast_ty_to_ty_cache.borrow().get(&id) {
451 None => panic!("ast_ty_to_ty_cache was incomplete after typeck!")
453 infer::normalize_associated_type(tcx, &tty)
456 impl<'a, 'tcx> ImproperCTypesVisitor<'a, 'tcx> {
457 /// Check if the given type is "ffi-safe" (has a stable, well-defined
458 /// representation which can be exported to C code).
459 fn check_type_for_ffi(&self,
460 cache: &mut FnvHashSet<Ty<'tcx>>,
463 use self::FfiResult::*;
464 let cx = &self.cx.tcx;
466 // Protect against infinite recursion, for example
467 // `struct S(*mut S);`.
468 // FIXME: A recursion limit is necessary as well, for irregular
470 if !cache.insert(ty) {
475 ty::TyStruct(def, substs) => {
476 if !cx.lookup_repr_hints(def.did).contains(&attr::ReprExtern) {
478 "found struct without foreign-function-safe \
479 representation annotation in foreign module, \
480 consider adding a #[repr(C)] attribute to \
484 // We can't completely trust repr(C) markings; make sure the
485 // fields are actually safe.
486 if def.struct_variant().fields.is_empty() {
488 "found zero-size struct in foreign module, consider \
489 adding a member to this struct");
492 for field in &def.struct_variant().fields {
493 let field_ty = infer::normalize_associated_type(cx, &field.ty(cx, substs));
494 let r = self.check_type_for_ffi(cache, field_ty);
497 FfiBadStruct(..) | FfiBadEnum(..) => { return r; }
498 FfiUnsafe(s) => { return FfiBadStruct(def.did, s); }
503 ty::TyEnum(def, substs) => {
504 if def.variants.is_empty() {
505 // Empty enums are okay... although sort of useless.
509 // Check for a repr() attribute to specify the size of the
511 let repr_hints = cx.lookup_repr_hints(def.did);
512 match &**repr_hints {
514 // Special-case types like `Option<extern fn()>`.
515 if !is_repr_nullable_ptr(cx, def, substs) {
517 "found enum without foreign-function-safe \
518 representation annotation in foreign module, \
519 consider adding a #[repr(...)] attribute to \
524 if !hint.is_ffi_safe() {
525 // FIXME: This shouldn't be reachable: we should check
528 "enum has unexpected #[repr(...)] attribute")
531 // Enum with an explicitly sized discriminant; either
532 // a C-style enum or a discriminated union.
534 // The layout of enum variants is implicitly repr(C).
535 // FIXME: Is that correct?
538 // FIXME: This shouldn't be reachable: we should check
541 "enum has too many #[repr(...)] attributes");
545 // Check the contained variants.
546 for variant in &def.variants {
547 for field in &variant.fields {
548 let arg = infer::normalize_associated_type(cx, &field.ty(cx, substs));
549 let r = self.check_type_for_ffi(cache, arg);
552 FfiBadStruct(..) | FfiBadEnum(..) => { return r; }
553 FfiUnsafe(s) => { return FfiBadEnum(def.did, s); }
560 ty::TyInt(hir::TyIs) => {
561 FfiUnsafe("found Rust type `isize` in foreign module, while \
562 `libc::c_int` or `libc::c_long` should be used")
564 ty::TyUint(hir::TyUs) => {
565 FfiUnsafe("found Rust type `usize` in foreign module, while \
566 `libc::c_uint` or `libc::c_ulong` should be used")
569 FfiUnsafe("found Rust type `char` in foreign module, while \
570 `u32` or `libc::wchar_t` should be used")
573 // Primitive types with a stable representation.
574 ty::TyBool | ty::TyInt(..) | ty::TyUint(..) |
575 ty::TyFloat(..) => FfiSafe,
578 FfiUnsafe("found Rust type Box<_> in foreign module, \
579 consider using a raw pointer instead")
583 FfiUnsafe("found Rust slice type in foreign module, \
584 consider using a raw pointer instead")
588 FfiUnsafe("found Rust trait type in foreign module, \
589 consider using a raw pointer instead")
593 FfiUnsafe("found Rust type `str` in foreign module; \
594 consider using a `*const libc::c_char`")
598 FfiUnsafe("found Rust tuple type in foreign module; \
599 consider using a struct instead`")
602 ty::TyRawPtr(ref m) | ty::TyRef(_, ref m) => {
603 self.check_type_for_ffi(cache, m.ty)
606 ty::TyArray(ty, _) => {
607 self.check_type_for_ffi(cache, ty)
610 ty::TyBareFn(None, bare_fn) => {
614 abi::PlatformIntrinsic |
617 "found function pointer with Rust calling \
618 convention in foreign module; consider using an \
619 `extern` function pointer")
624 let sig = cx.erase_late_bound_regions(&bare_fn.sig);
626 ty::FnDiverging => {}
627 ty::FnConverging(output) => {
628 if !output.is_nil() {
629 let r = self.check_type_for_ffi(cache, output);
637 for arg in sig.inputs {
638 let r = self.check_type_for_ffi(cache, arg);
647 ty::TyParam(..) | ty::TyInfer(..) | ty::TyError |
648 ty::TyClosure(..) | ty::TyProjection(..) |
649 ty::TyBareFn(Some(_), _) => {
650 panic!("Unexpected type in foreign function")
655 fn check_def(&mut self, sp: Span, id: ast::NodeId) {
656 let tty = ast_ty_to_normalized(self.cx.tcx, id);
658 match ImproperCTypesVisitor::check_type_for_ffi(self, &mut FnvHashSet(), tty) {
659 FfiResult::FfiSafe => {}
660 FfiResult::FfiUnsafe(s) => {
661 self.cx.span_lint(IMPROPER_CTYPES, sp, s);
663 FfiResult::FfiBadStruct(_, s) => {
664 // FIXME: This diagnostic is difficult to read, and doesn't
665 // point at the relevant field.
666 self.cx.span_lint(IMPROPER_CTYPES, sp,
667 &format!("found non-foreign-function-safe member in \
668 struct marked #[repr(C)]: {}", s));
670 FfiResult::FfiBadEnum(_, s) => {
671 // FIXME: This diagnostic is difficult to read, and doesn't
672 // point at the relevant variant.
673 self.cx.span_lint(IMPROPER_CTYPES, sp,
674 &format!("found non-foreign-function-safe member in \
681 impl<'a, 'tcx, 'v> Visitor<'v> for ImproperCTypesVisitor<'a, 'tcx> {
682 fn visit_ty(&mut self, ty: &hir::Ty) {
685 hir::TyBareFn(..) => self.check_def(ty.span, ty.id),
687 self.cx.span_lint(IMPROPER_CTYPES, ty.span,
688 "found Rust slice type in foreign module, consider \
689 using a raw pointer instead");
691 hir::TyFixedLengthVec(ref ty, _) => self.visit_ty(ty),
693 self.cx.span_lint(IMPROPER_CTYPES, ty.span,
694 "found Rust tuple type in foreign module; \
695 consider using a struct instead`")
697 _ => visit::walk_ty(self, ty)
702 #[derive(Copy, Clone)]
703 pub struct ImproperCTypes;
705 impl LintPass for ImproperCTypes {
706 fn get_lints(&self) -> LintArray {
707 lint_array!(IMPROPER_CTYPES)
710 fn check_item(&mut self, cx: &Context, it: &hir::Item) {
711 fn check_ty(cx: &Context, ty: &hir::Ty) {
712 let mut vis = ImproperCTypesVisitor { cx: cx };
716 fn check_foreign_fn(cx: &Context, decl: &hir::FnDecl) {
717 for input in &decl.inputs {
718 check_ty(cx, &*input.ty);
720 if let hir::Return(ref ret_ty) = decl.output {
721 let tty = ast_ty_to_normalized(cx.tcx, ret_ty.id);
723 check_ty(cx, &ret_ty);
729 hir::ItemForeignMod(ref nmod)
730 if nmod.abi != abi::RustIntrinsic &&
731 nmod.abi != abi::PlatformIntrinsic => {
732 for ni in &nmod.items {
734 hir::ForeignItemFn(ref decl, _) => check_foreign_fn(cx, &**decl),
735 hir::ForeignItemStatic(ref t, _) => check_ty(cx, &**t)
747 "use of owned (Box type) heap memory"
750 #[derive(Copy, Clone)]
751 pub struct BoxPointers;
754 fn check_heap_type<'a, 'tcx>(&self, cx: &Context<'a, 'tcx>,
755 span: Span, ty: Ty<'tcx>) {
756 for leaf_ty in ty.walk() {
757 if let ty::TyBox(_) = leaf_ty.sty {
758 let m = format!("type uses owned (Box type) pointers: {}", ty);
759 cx.span_lint(BOX_POINTERS, span, &m);
765 impl LintPass for BoxPointers {
766 fn get_lints(&self) -> LintArray {
767 lint_array!(BOX_POINTERS)
770 fn check_item(&mut self, cx: &Context, it: &hir::Item) {
775 hir::ItemStruct(..) =>
776 self.check_heap_type(cx, it.span,
777 cx.tcx.node_id_to_type(it.id)),
781 // If it's a struct, we also have to check the fields' types
783 hir::ItemStruct(ref struct_def, _) => {
784 for struct_field in &struct_def.fields {
785 self.check_heap_type(cx, struct_field.span,
786 cx.tcx.node_id_to_type(struct_field.node.id));
793 fn check_expr(&mut self, cx: &Context, e: &hir::Expr) {
794 let ty = cx.tcx.node_id_to_type(e.id);
795 self.check_heap_type(cx, e.span, ty);
802 "uses of #[derive] with raw pointers are rarely correct"
805 struct RawPtrDeriveVisitor<'a, 'tcx: 'a> {
806 cx: &'a Context<'a, 'tcx>
809 impl<'a, 'tcx, 'v> Visitor<'v> for RawPtrDeriveVisitor<'a, 'tcx> {
810 fn visit_ty(&mut self, ty: &hir::Ty) {
811 const MSG: &'static str = "use of `#[derive]` with a raw pointer";
812 if let hir::TyPtr(..) = ty.node {
813 self.cx.span_lint(RAW_POINTER_DERIVE, ty.span, MSG);
815 visit::walk_ty(self, ty);
817 // explicit override to a no-op to reduce code bloat
818 fn visit_expr(&mut self, _: &hir::Expr) {}
819 fn visit_block(&mut self, _: &hir::Block) {}
822 pub struct RawPointerDerive {
823 checked_raw_pointers: NodeSet,
826 impl RawPointerDerive {
827 pub fn new() -> RawPointerDerive {
829 checked_raw_pointers: NodeSet(),
834 impl LintPass for RawPointerDerive {
835 fn get_lints(&self) -> LintArray {
836 lint_array!(RAW_POINTER_DERIVE)
839 fn check_item(&mut self, cx: &Context, item: &hir::Item) {
840 if !attr::contains_name(&item.attrs, "automatically_derived") {
843 let did = match item.node {
844 hir::ItemImpl(_, _, _, ref t_ref_opt, _, _) => {
845 // Deriving the Copy trait does not cause a warning
846 if let &Some(ref trait_ref) = t_ref_opt {
847 let def_id = cx.tcx.trait_ref_to_def_id(trait_ref);
848 if Some(def_id) == cx.tcx.lang_items.copy_trait() {
853 match cx.tcx.node_id_to_type(item.id).sty {
854 ty::TyEnum(def, _) => def.did,
855 ty::TyStruct(def, _) => def.did,
864 let item = match cx.tcx.map.find(did.node) {
865 Some(hir_map::NodeItem(item)) => item,
868 if !self.checked_raw_pointers.insert(item.id) {
872 hir::ItemStruct(..) | hir::ItemEnum(..) => {
873 let mut visitor = RawPtrDeriveVisitor { cx: cx };
874 visit::walk_item(&mut visitor, &item);
884 "detects attributes that were not used by the compiler"
887 #[derive(Copy, Clone)]
888 pub struct UnusedAttributes;
890 impl LintPass for UnusedAttributes {
891 fn get_lints(&self) -> LintArray {
892 lint_array!(UNUSED_ATTRIBUTES)
895 fn check_attribute(&mut self, cx: &Context, attr: &hir::Attribute) {
896 // Note that check_name() marks the attribute as used if it matches.
897 for &(ref name, ty, _) in KNOWN_ATTRIBUTES {
899 AttributeType::Whitelisted if attr.check_name(name) => {
906 let plugin_attributes = cx.sess().plugin_attributes.borrow_mut();
907 for &(ref name, ty) in plugin_attributes.iter() {
908 if ty == AttributeType::Whitelisted && attr.check_name(&*name) {
913 if !syntax_attr::is_used(&unlower_attribute(attr)) {
914 cx.span_lint(UNUSED_ATTRIBUTES, attr.span, "unused attribute");
915 // Is it a builtin attribute that must be used at the crate level?
916 let known_crate = KNOWN_ATTRIBUTES.iter().find(|&&(name, ty, _)| {
917 attr.name() == name &&
918 ty == AttributeType::CrateLevel
921 // Has a plugin registered this attribute as one which must be used at
923 let plugin_crate = plugin_attributes.iter()
924 .find(|&&(ref x, t)| {
925 &*attr.name() == &*x &&
926 AttributeType::CrateLevel == t
928 if known_crate || plugin_crate {
929 let msg = match attr.node.style {
930 hir::AttrOuter => "crate-level attribute should be an inner \
931 attribute: add an exclamation mark: #![foo]",
932 hir::AttrInner => "crate-level attribute should be in the \
935 cx.span_lint(UNUSED_ATTRIBUTES, attr.span, msg);
944 "path statements with no effect"
947 #[derive(Copy, Clone)]
948 pub struct PathStatements;
950 impl LintPass for PathStatements {
951 fn get_lints(&self) -> LintArray {
952 lint_array!(PATH_STATEMENTS)
955 fn check_stmt(&mut self, cx: &Context, s: &hir::Stmt) {
957 hir::StmtSemi(ref expr, _) => {
959 hir::ExprPath(..) => cx.span_lint(PATH_STATEMENTS, s.span,
960 "path statement with no effect"),
972 "unused result of a type flagged as #[must_use]"
978 "unused result of an expression in a statement"
981 #[derive(Copy, Clone)]
982 pub struct UnusedResults;
984 impl LintPass for UnusedResults {
985 fn get_lints(&self) -> LintArray {
986 lint_array!(UNUSED_MUST_USE, UNUSED_RESULTS)
989 fn check_stmt(&mut self, cx: &Context, s: &hir::Stmt) {
990 let expr = match s.node {
991 hir::StmtSemi(ref expr, _) => &**expr,
995 if let hir::ExprRet(..) = expr.node {
999 let t = cx.tcx.expr_ty(&expr);
1000 let warned = match t.sty {
1001 ty::TyTuple(ref tys) if tys.is_empty() => return,
1002 ty::TyBool => return,
1003 ty::TyStruct(def, _) |
1004 ty::TyEnum(def, _) => {
1005 if def.did.is_local() {
1006 if let hir_map::NodeItem(it) = cx.tcx.map.get(def.did.node) {
1007 check_must_use(cx, &it.attrs, s.span)
1012 let attrs = csearch::get_item_attrs(&cx.sess().cstore, def.did);
1013 check_must_use(cx, &attrs[..], s.span)
1019 cx.span_lint(UNUSED_RESULTS, s.span, "unused result");
1022 fn check_must_use(cx: &Context, attrs: &[hir::Attribute], sp: Span) -> bool {
1024 if attr.check_name("must_use") {
1025 let mut msg = "unused result which must be used".to_string();
1026 // check for #[must_use="..."]
1027 match attr.value_str() {
1034 cx.span_lint(UNUSED_MUST_USE, sp, &msg);
1044 pub NON_CAMEL_CASE_TYPES,
1046 "types, variants, traits and type parameters should have camel case names"
1049 #[derive(Copy, Clone)]
1050 pub struct NonCamelCaseTypes;
1052 impl NonCamelCaseTypes {
1053 fn check_case(&self, cx: &Context, sort: &str, ident: ast::Ident, span: Span) {
1054 fn is_camel_case(ident: ast::Ident) -> bool {
1055 let ident = ident.name.as_str();
1056 if ident.is_empty() {
1059 let ident = ident.trim_matches('_');
1061 // start with a non-lowercase letter rather than non-uppercase
1062 // ones (some scripts don't have a concept of upper/lowercase)
1063 !ident.is_empty() && !ident.char_at(0).is_lowercase() && !ident.contains('_')
1066 fn to_camel_case(s: &str) -> String {
1067 s.split('_').flat_map(|word| word.chars().enumerate().map(|(i, c)|
1069 c.to_uppercase().collect::<String>()
1071 c.to_lowercase().collect()
1073 )).collect::<Vec<_>>().concat()
1076 let s = ident.name.as_str();
1078 if !is_camel_case(ident) {
1079 let c = to_camel_case(&s);
1080 let m = if c.is_empty() {
1081 format!("{} `{}` should have a camel case name such as `CamelCase`", sort, s)
1083 format!("{} `{}` should have a camel case name such as `{}`", sort, s, c)
1085 cx.span_lint(NON_CAMEL_CASE_TYPES, span, &m[..]);
1090 impl LintPass for NonCamelCaseTypes {
1091 fn get_lints(&self) -> LintArray {
1092 lint_array!(NON_CAMEL_CASE_TYPES)
1095 fn check_item(&mut self, cx: &Context, it: &hir::Item) {
1096 let extern_repr_count = it.attrs.iter().filter(|attr| {
1097 attr::find_repr_attrs(cx.tcx.sess.diagnostic(), attr).iter()
1098 .any(|r| r == &attr::ReprExtern)
1100 let has_extern_repr = extern_repr_count > 0;
1102 if has_extern_repr {
1107 hir::ItemTy(..) | hir::ItemStruct(..) => {
1108 self.check_case(cx, "type", it.ident, it.span)
1110 hir::ItemTrait(..) => {
1111 self.check_case(cx, "trait", it.ident, it.span)
1113 hir::ItemEnum(ref enum_definition, _) => {
1114 if has_extern_repr {
1117 self.check_case(cx, "type", it.ident, it.span);
1118 for variant in &enum_definition.variants {
1119 self.check_case(cx, "variant", variant.node.name, variant.span);
1126 fn check_generics(&mut self, cx: &Context, it: &hir::Generics) {
1127 for gen in it.ty_params.iter() {
1128 self.check_case(cx, "type parameter", gen.ident, gen.span);
1133 #[derive(PartialEq)]
1134 enum MethodContext {
1140 fn method_context(cx: &Context, id: ast::NodeId, span: Span) -> MethodContext {
1141 match cx.tcx.impl_or_trait_items.borrow().get(&DefId::local(id)) {
1142 None => cx.sess().span_bug(span, "missing method descriptor?!"),
1143 Some(item) => match item.container() {
1144 ty::TraitContainer(..) => MethodContext::TraitDefaultImpl,
1145 ty::ImplContainer(cid) => {
1146 match cx.tcx.impl_trait_ref(cid) {
1147 Some(_) => MethodContext::TraitImpl,
1148 None => MethodContext::PlainImpl
1158 "methods, functions, lifetime parameters and modules should have snake case names"
1161 #[derive(Copy, Clone)]
1162 pub struct NonSnakeCase;
1165 fn to_snake_case(mut str: &str) -> String {
1166 let mut words = vec![];
1167 // Preserve leading underscores
1168 str = str.trim_left_matches(|c: char| {
1170 words.push(String::new());
1176 for s in str.split('_') {
1177 let mut last_upper = false;
1178 let mut buf = String::new();
1182 for ch in s.chars() {
1183 if !buf.is_empty() && buf != "'"
1184 && ch.is_uppercase()
1187 buf = String::new();
1189 last_upper = ch.is_uppercase();
1190 buf.extend(ch.to_lowercase());
1197 fn check_snake_case(&self, cx: &Context, sort: &str, name: &str, span: Option<Span>) {
1198 fn is_snake_case(ident: &str) -> bool {
1199 if ident.is_empty() {
1202 let ident = ident.trim_left_matches('\'');
1203 let ident = ident.trim_matches('_');
1205 let mut allow_underscore = true;
1206 ident.chars().all(|c| {
1207 allow_underscore = match c {
1208 '_' if !allow_underscore => return false,
1210 // It would be more obvious to use `c.is_lowercase()`,
1211 // but some characters do not have a lowercase form
1212 c if !c.is_uppercase() => true,
1219 if !is_snake_case(name) {
1220 let sc = NonSnakeCase::to_snake_case(name);
1221 let msg = if sc != name {
1222 format!("{} `{}` should have a snake case name such as `{}`",
1225 format!("{} `{}` should have a snake case name",
1229 Some(span) => cx.span_lint(NON_SNAKE_CASE, span, &msg),
1230 None => cx.lint(NON_SNAKE_CASE, &msg),
1236 impl LintPass for NonSnakeCase {
1237 fn get_lints(&self) -> LintArray {
1238 lint_array!(NON_SNAKE_CASE)
1241 fn check_crate(&mut self, cx: &Context, cr: &hir::Crate) {
1242 let attr_crate_name = cr.attrs.iter().find(|at| at.check_name("crate_name"))
1243 .and_then(|at| at.value_str().map(|s| (at, s)));
1244 if let Some(ref name) = cx.tcx.sess.opts.crate_name {
1245 self.check_snake_case(cx, "crate", name, None);
1246 } else if let Some((attr, ref name)) = attr_crate_name {
1247 self.check_snake_case(cx, "crate", name, Some(attr.span));
1251 fn check_fn(&mut self, cx: &Context,
1252 fk: FnKind, _: &hir::FnDecl,
1253 _: &hir::Block, span: Span, id: ast::NodeId) {
1255 FnKind::Method(ident, _, _) => match method_context(cx, id, span) {
1256 MethodContext::PlainImpl => {
1257 self.check_snake_case(cx, "method", &ident.name.as_str(), Some(span))
1259 MethodContext::TraitDefaultImpl => {
1260 self.check_snake_case(cx, "trait method", &ident.name.as_str(), Some(span))
1264 FnKind::ItemFn(ident, _, _, _, _, _) => {
1265 self.check_snake_case(cx, "function", &ident.name.as_str(), Some(span))
1271 fn check_item(&mut self, cx: &Context, it: &hir::Item) {
1272 if let hir::ItemMod(_) = it.node {
1273 self.check_snake_case(cx, "module", &it.ident.name.as_str(), Some(it.span));
1277 fn check_trait_item(&mut self, cx: &Context, trait_item: &hir::TraitItem) {
1278 if let hir::MethodTraitItem(_, None) = trait_item.node {
1279 self.check_snake_case(cx, "trait method", &trait_item.ident.name.as_str(),
1280 Some(trait_item.span));
1284 fn check_lifetime_def(&mut self, cx: &Context, t: &hir::LifetimeDef) {
1285 self.check_snake_case(cx, "lifetime", &t.lifetime.name.as_str(),
1286 Some(t.lifetime.span));
1289 fn check_pat(&mut self, cx: &Context, p: &hir::Pat) {
1290 if let &hir::PatIdent(_, ref path1, _) = &p.node {
1291 let def = cx.tcx.def_map.borrow().get(&p.id).map(|d| d.full_def());
1292 if let Some(def::DefLocal(_)) = def {
1293 self.check_snake_case(cx, "variable", &path1.node.name.as_str(), Some(p.span));
1298 fn check_struct_def(&mut self, cx: &Context, s: &hir::StructDef,
1299 _: ast::Ident, _: &hir::Generics, _: ast::NodeId) {
1300 for sf in &s.fields {
1301 if let hir::StructField_ { kind: hir::NamedField(ident, _), .. } = sf.node {
1302 self.check_snake_case(cx, "structure field", &ident.name.as_str(),
1310 pub NON_UPPER_CASE_GLOBALS,
1312 "static constants should have uppercase identifiers"
1315 #[derive(Copy, Clone)]
1316 pub struct NonUpperCaseGlobals;
1318 impl NonUpperCaseGlobals {
1319 fn check_upper_case(cx: &Context, sort: &str, ident: ast::Ident, span: Span) {
1320 let s = ident.name.as_str();
1322 if s.chars().any(|c| c.is_lowercase()) {
1323 let uc = NonSnakeCase::to_snake_case(&s).to_uppercase();
1325 cx.span_lint(NON_UPPER_CASE_GLOBALS, span,
1326 &format!("{} `{}` should have an upper case name such as `{}`",
1329 cx.span_lint(NON_UPPER_CASE_GLOBALS, span,
1330 &format!("{} `{}` should have an upper case name",
1337 impl LintPass for NonUpperCaseGlobals {
1338 fn get_lints(&self) -> LintArray {
1339 lint_array!(NON_UPPER_CASE_GLOBALS)
1342 fn check_item(&mut self, cx: &Context, it: &hir::Item) {
1344 // only check static constants
1345 hir::ItemStatic(_, hir::MutImmutable, _) => {
1346 NonUpperCaseGlobals::check_upper_case(cx, "static constant", it.ident, it.span);
1348 hir::ItemConst(..) => {
1349 NonUpperCaseGlobals::check_upper_case(cx, "constant", it.ident, it.span);
1355 fn check_trait_item(&mut self, cx: &Context, ti: &hir::TraitItem) {
1357 hir::ConstTraitItem(..) => {
1358 NonUpperCaseGlobals::check_upper_case(cx, "associated constant",
1365 fn check_impl_item(&mut self, cx: &Context, ii: &hir::ImplItem) {
1367 hir::ConstImplItem(..) => {
1368 NonUpperCaseGlobals::check_upper_case(cx, "associated constant",
1375 fn check_pat(&mut self, cx: &Context, p: &hir::Pat) {
1376 // Lint for constants that look like binding identifiers (#7526)
1377 match (&p.node, cx.tcx.def_map.borrow().get(&p.id).map(|d| d.full_def())) {
1378 (&hir::PatIdent(_, ref path1, _), Some(def::DefConst(..))) => {
1379 NonUpperCaseGlobals::check_upper_case(cx, "constant in pattern",
1380 path1.node, p.span);
1390 "`if`, `match`, `while` and `return` do not need parentheses"
1393 #[derive(Copy, Clone)]
1394 pub struct UnusedParens;
1397 fn check_unused_parens_core(&self, cx: &Context, value: &hir::Expr, msg: &str,
1398 struct_lit_needs_parens: bool) {
1399 if let hir::ExprParen(ref inner) = value.node {
1400 let necessary = struct_lit_needs_parens && contains_exterior_struct_lit(&**inner);
1402 cx.span_lint(UNUSED_PARENS, value.span,
1403 &format!("unnecessary parentheses around {}", msg))
1407 /// Expressions that syntactically contain an "exterior" struct
1408 /// literal i.e. not surrounded by any parens or other
1409 /// delimiters, e.g. `X { y: 1 }`, `X { y: 1 }.method()`, `foo
1410 /// == X { y: 1 }` and `X { y: 1 } == foo` all do, but `(X {
1411 /// y: 1 }) == foo` does not.
1412 fn contains_exterior_struct_lit(value: &hir::Expr) -> bool {
1414 hir::ExprStruct(..) => true,
1416 hir::ExprAssign(ref lhs, ref rhs) |
1417 hir::ExprAssignOp(_, ref lhs, ref rhs) |
1418 hir::ExprBinary(_, ref lhs, ref rhs) => {
1419 // X { y: 1 } + X { y: 2 }
1420 contains_exterior_struct_lit(&**lhs) ||
1421 contains_exterior_struct_lit(&**rhs)
1423 hir::ExprUnary(_, ref x) |
1424 hir::ExprCast(ref x, _) |
1425 hir::ExprField(ref x, _) |
1426 hir::ExprTupField(ref x, _) |
1427 hir::ExprIndex(ref x, _) => {
1428 // &X { y: 1 }, X { y: 1 }.y
1429 contains_exterior_struct_lit(&**x)
1432 hir::ExprMethodCall(_, _, ref exprs) => {
1433 // X { y: 1 }.bar(...)
1434 contains_exterior_struct_lit(&*exprs[0])
1443 impl LintPass for UnusedParens {
1444 fn get_lints(&self) -> LintArray {
1445 lint_array!(UNUSED_PARENS)
1448 fn check_expr(&mut self, cx: &Context, e: &hir::Expr) {
1449 let (value, msg, struct_lit_needs_parens) = match e.node {
1450 hir::ExprIf(ref cond, _, _) => (cond, "`if` condition", true),
1451 hir::ExprWhile(ref cond, _, _) => (cond, "`while` condition", true),
1452 hir::ExprMatch(ref head, _, source) => match source {
1453 hir::MatchSource::Normal => (head, "`match` head expression", true),
1454 hir::MatchSource::IfLetDesugar { .. } => (head, "`if let` head expression", true),
1455 hir::MatchSource::WhileLetDesugar => (head, "`while let` head expression", true),
1456 hir::MatchSource::ForLoopDesugar => (head, "`for` head expression", true),
1458 hir::ExprRet(Some(ref value)) => (value, "`return` value", false),
1459 hir::ExprAssign(_, ref value) => (value, "assigned value", false),
1460 hir::ExprAssignOp(_, _, ref value) => (value, "assigned value", false),
1463 self.check_unused_parens_core(cx, &**value, msg, struct_lit_needs_parens);
1466 fn check_stmt(&mut self, cx: &Context, s: &hir::Stmt) {
1467 let (value, msg) = match s.node {
1468 hir::StmtDecl(ref decl, _) => match decl.node {
1469 hir::DeclLocal(ref local) => match local.init {
1470 Some(ref value) => (value, "assigned value"),
1477 self.check_unused_parens_core(cx, &**value, msg, false);
1482 UNUSED_IMPORT_BRACES,
1484 "unnecessary braces around an imported item"
1487 #[derive(Copy, Clone)]
1488 pub struct UnusedImportBraces;
1490 impl LintPass for UnusedImportBraces {
1491 fn get_lints(&self) -> LintArray {
1492 lint_array!(UNUSED_IMPORT_BRACES)
1495 fn check_item(&mut self, cx: &Context, item: &hir::Item) {
1496 if let hir::ItemUse(ref view_path) = item.node {
1497 if let hir::ViewPathList(_, ref items) = view_path.node {
1498 if items.len() == 1 {
1499 if let hir::PathListIdent {ref name, ..} = items[0].node {
1500 let m = format!("braces around {} is unnecessary",
1502 cx.span_lint(UNUSED_IMPORT_BRACES, item.span,
1512 NON_SHORTHAND_FIELD_PATTERNS,
1514 "using `Struct { x: x }` instead of `Struct { x }`"
1517 #[derive(Copy, Clone)]
1518 pub struct NonShorthandFieldPatterns;
1520 impl LintPass for NonShorthandFieldPatterns {
1521 fn get_lints(&self) -> LintArray {
1522 lint_array!(NON_SHORTHAND_FIELD_PATTERNS)
1525 fn check_pat(&mut self, cx: &Context, pat: &hir::Pat) {
1526 let def_map = cx.tcx.def_map.borrow();
1527 if let hir::PatStruct(_, ref v, _) = pat.node {
1528 let field_pats = v.iter().filter(|fieldpat| {
1529 if fieldpat.node.is_shorthand {
1532 let def = def_map.get(&fieldpat.node.pat.id).map(|d| d.full_def());
1533 def == Some(def::DefLocal(fieldpat.node.pat.id))
1535 for fieldpat in field_pats {
1536 if let hir::PatIdent(_, ident, None) = fieldpat.node.pat.node {
1537 if ident.node.name == fieldpat.node.ident.name {
1538 // FIXME: should this comparison really be done on the name?
1539 // doing it on the ident will fail during compilation of libcore
1540 cx.span_lint(NON_SHORTHAND_FIELD_PATTERNS, fieldpat.span,
1541 &format!("the `{}:` in this pattern is redundant and can \
1542 be removed", ident.node))
1553 "unnecessary use of an `unsafe` block"
1556 #[derive(Copy, Clone)]
1557 pub struct UnusedUnsafe;
1559 impl LintPass for UnusedUnsafe {
1560 fn get_lints(&self) -> LintArray {
1561 lint_array!(UNUSED_UNSAFE)
1564 fn check_expr(&mut self, cx: &Context, e: &hir::Expr) {
1565 if let hir::ExprBlock(ref blk) = e.node {
1566 // Don't warn about generated blocks, that'll just pollute the output.
1567 if blk.rules == hir::UnsafeBlock(hir::UserProvided) &&
1568 !cx.tcx.used_unsafe.borrow().contains(&blk.id) {
1569 cx.span_lint(UNUSED_UNSAFE, blk.span, "unnecessary `unsafe` block");
1578 "usage of `unsafe` code"
1581 #[derive(Copy, Clone)]
1582 pub struct UnsafeCode;
1584 impl LintPass for UnsafeCode {
1585 fn get_lints(&self) -> LintArray {
1586 lint_array!(UNSAFE_CODE)
1589 fn check_expr(&mut self, cx: &Context, e: &hir::Expr) {
1590 if let hir::ExprBlock(ref blk) = e.node {
1591 // Don't warn about generated blocks, that'll just pollute the output.
1592 if blk.rules == hir::UnsafeBlock(hir::UserProvided) {
1593 cx.span_lint(UNSAFE_CODE, blk.span, "usage of an `unsafe` block");
1598 fn check_item(&mut self, cx: &Context, it: &hir::Item) {
1600 hir::ItemTrait(hir::Unsafety::Unsafe, _, _, _) =>
1601 cx.span_lint(UNSAFE_CODE, it.span, "declaration of an `unsafe` trait"),
1603 hir::ItemImpl(hir::Unsafety::Unsafe, _, _, _, _, _) =>
1604 cx.span_lint(UNSAFE_CODE, it.span, "implementation of an `unsafe` trait"),
1610 fn check_fn(&mut self, cx: &Context, fk: FnKind, _: &hir::FnDecl,
1611 _: &hir::Block, span: Span, _: ast::NodeId) {
1613 FnKind::ItemFn(_, _, hir::Unsafety::Unsafe, _, _, _) =>
1614 cx.span_lint(UNSAFE_CODE, span, "declaration of an `unsafe` function"),
1616 FnKind::Method(_, sig, _) => {
1617 if sig.unsafety == hir::Unsafety::Unsafe {
1618 cx.span_lint(UNSAFE_CODE, span, "implementation of an `unsafe` method")
1626 fn check_trait_item(&mut self, cx: &Context, trait_item: &hir::TraitItem) {
1627 if let hir::MethodTraitItem(ref sig, None) = trait_item.node {
1628 if sig.unsafety == hir::Unsafety::Unsafe {
1629 cx.span_lint(UNSAFE_CODE, trait_item.span,
1630 "declaration of an `unsafe` method")
1639 "detect mut variables which don't need to be mutable"
1642 #[derive(Copy, Clone)]
1643 pub struct UnusedMut;
1646 fn check_unused_mut_pat(&self, cx: &Context, pats: &[P<hir::Pat>]) {
1647 // collect all mutable pattern and group their NodeIDs by their Identifier to
1648 // avoid false warnings in match arms with multiple patterns
1650 let mut mutables = FnvHashMap();
1652 pat_util::pat_bindings(&cx.tcx.def_map, p, |mode, id, _, path1| {
1653 let ident = path1.node;
1654 if let hir::BindByValue(hir::MutMutable) = mode {
1655 if !ident.name.as_str().starts_with("_") {
1656 match mutables.entry(ident.name.usize()) {
1657 Vacant(entry) => { entry.insert(vec![id]); },
1658 Occupied(mut entry) => { entry.get_mut().push(id); },
1665 let used_mutables = cx.tcx.used_mut_nodes.borrow();
1666 for (_, v) in &mutables {
1667 if !v.iter().any(|e| used_mutables.contains(e)) {
1668 cx.span_lint(UNUSED_MUT, cx.tcx.map.span(v[0]),
1669 "variable does not need to be mutable");
1675 impl LintPass for UnusedMut {
1676 fn get_lints(&self) -> LintArray {
1677 lint_array!(UNUSED_MUT)
1680 fn check_expr(&mut self, cx: &Context, e: &hir::Expr) {
1681 if let hir::ExprMatch(_, ref arms, _) = e.node {
1683 self.check_unused_mut_pat(cx, &a.pats)
1688 fn check_stmt(&mut self, cx: &Context, s: &hir::Stmt) {
1689 if let hir::StmtDecl(ref d, _) = s.node {
1690 if let hir::DeclLocal(ref l) = d.node {
1691 self.check_unused_mut_pat(cx, slice::ref_slice(&l.pat));
1696 fn check_fn(&mut self, cx: &Context,
1697 _: FnKind, decl: &hir::FnDecl,
1698 _: &hir::Block, _: Span, _: ast::NodeId) {
1699 for a in &decl.inputs {
1700 self.check_unused_mut_pat(cx, slice::ref_slice(&a.pat));
1708 "detects unnecessary allocations that can be eliminated"
1711 #[derive(Copy, Clone)]
1712 pub struct UnusedAllocation;
1714 impl LintPass for UnusedAllocation {
1715 fn get_lints(&self) -> LintArray {
1716 lint_array!(UNUSED_ALLOCATION)
1719 fn check_expr(&mut self, cx: &Context, e: &hir::Expr) {
1721 hir::ExprUnary(hir::UnUniq, _) => (),
1725 if let Some(adjustment) = cx.tcx.tables.borrow().adjustments.get(&e.id) {
1726 if let adjustment::AdjustDerefRef(adjustment::AutoDerefRef {
1730 &Some(adjustment::AutoPtr(_, hir::MutImmutable)) => {
1731 cx.span_lint(UNUSED_ALLOCATION, e.span,
1732 "unnecessary allocation, use & instead");
1734 &Some(adjustment::AutoPtr(_, hir::MutMutable)) => {
1735 cx.span_lint(UNUSED_ALLOCATION, e.span,
1736 "unnecessary allocation, use &mut instead");
1748 "detects missing documentation for public members"
1751 pub struct MissingDoc {
1752 /// Stack of IDs of struct definitions.
1753 struct_def_stack: Vec<ast::NodeId>,
1755 /// True if inside variant definition
1758 /// Stack of whether #[doc(hidden)] is set
1759 /// at each level which has lint attributes.
1760 doc_hidden_stack: Vec<bool>,
1762 /// Private traits or trait items that leaked through. Don't check their methods.
1763 private_traits: HashSet<ast::NodeId>,
1767 pub fn new() -> MissingDoc {
1769 struct_def_stack: vec!(),
1771 doc_hidden_stack: vec!(false),
1772 private_traits: HashSet::new(),
1776 fn doc_hidden(&self) -> bool {
1777 *self.doc_hidden_stack.last().expect("empty doc_hidden_stack")
1780 fn check_missing_docs_attrs(&self,
1782 id: Option<ast::NodeId>,
1783 attrs: &[hir::Attribute],
1785 desc: &'static str) {
1786 // If we're building a test harness, then warning about
1787 // documentation is probably not really relevant right now.
1788 if cx.sess().opts.test {
1792 // `#[doc(hidden)]` disables missing_docs check.
1793 if self.doc_hidden() {
1797 // Only check publicly-visible items, using the result from the privacy pass.
1798 // It's an option so the crate root can also use this function (it doesn't
1800 if let Some(ref id) = id {
1801 if !cx.exported_items.contains(id) {
1806 let has_doc = attrs.iter().any(|a| {
1807 match a.node.value.node {
1808 hir::MetaNameValue(ref name, _) if *name == "doc" => true,
1813 cx.span_lint(MISSING_DOCS, sp,
1814 &format!("missing documentation for {}", desc));
1819 impl LintPass for MissingDoc {
1820 fn get_lints(&self) -> LintArray {
1821 lint_array!(MISSING_DOCS)
1824 fn enter_lint_attrs(&mut self, _: &Context, attrs: &[hir::Attribute]) {
1825 let doc_hidden = self.doc_hidden() || attrs.iter().any(|attr| {
1826 attr.check_name("doc") && match attr.meta_item_list() {
1828 Some(l) => attr::contains_name(&l[..], "hidden"),
1831 self.doc_hidden_stack.push(doc_hidden);
1834 fn exit_lint_attrs(&mut self, _: &Context, _: &[hir::Attribute]) {
1835 self.doc_hidden_stack.pop().expect("empty doc_hidden_stack");
1838 fn check_struct_def(&mut self, _: &Context, _: &hir::StructDef,
1839 _: ast::Ident, _: &hir::Generics, id: ast::NodeId) {
1840 self.struct_def_stack.push(id);
1843 fn check_struct_def_post(&mut self, _: &Context, _: &hir::StructDef,
1844 _: ast::Ident, _: &hir::Generics, id: ast::NodeId) {
1845 let popped = self.struct_def_stack.pop().expect("empty struct_def_stack");
1846 assert!(popped == id);
1849 fn check_crate(&mut self, cx: &Context, krate: &hir::Crate) {
1850 self.check_missing_docs_attrs(cx, None, &krate.attrs, krate.span, "crate");
1853 fn check_item(&mut self, cx: &Context, it: &hir::Item) {
1854 let desc = match it.node {
1855 hir::ItemFn(..) => "a function",
1856 hir::ItemMod(..) => "a module",
1857 hir::ItemEnum(..) => "an enum",
1858 hir::ItemStruct(..) => "a struct",
1859 hir::ItemTrait(_, _, _, ref items) => {
1860 // Issue #11592, traits are always considered exported, even when private.
1861 if it.vis == hir::Visibility::Inherited {
1862 self.private_traits.insert(it.id);
1864 self.private_traits.insert(itm.id);
1870 hir::ItemTy(..) => "a type alias",
1871 hir::ItemImpl(_, _, _, Some(ref trait_ref), _, ref impl_items) => {
1872 // If the trait is private, add the impl items to private_traits so they don't get
1873 // reported for missing docs.
1874 let real_trait = cx.tcx.trait_ref_to_def_id(trait_ref);
1875 match cx.tcx.map.find(real_trait.node) {
1876 Some(hir_map::NodeItem(item)) => if item.vis == hir::Visibility::Inherited {
1877 for itm in impl_items {
1878 self.private_traits.insert(itm.id);
1885 hir::ItemConst(..) => "a constant",
1886 hir::ItemStatic(..) => "a static",
1890 self.check_missing_docs_attrs(cx, Some(it.id), &it.attrs, it.span, desc);
1893 fn check_trait_item(&mut self, cx: &Context, trait_item: &hir::TraitItem) {
1894 if self.private_traits.contains(&trait_item.id) { return }
1896 let desc = match trait_item.node {
1897 hir::ConstTraitItem(..) => "an associated constant",
1898 hir::MethodTraitItem(..) => "a trait method",
1899 hir::TypeTraitItem(..) => "an associated type",
1902 self.check_missing_docs_attrs(cx, Some(trait_item.id),
1904 trait_item.span, desc);
1907 fn check_impl_item(&mut self, cx: &Context, impl_item: &hir::ImplItem) {
1908 // If the method is an impl for a trait, don't doc.
1909 if method_context(cx, impl_item.id, impl_item.span) == MethodContext::TraitImpl {
1913 let desc = match impl_item.node {
1914 hir::ConstImplItem(..) => "an associated constant",
1915 hir::MethodImplItem(..) => "a method",
1916 hir::TypeImplItem(_) => "an associated type",
1918 self.check_missing_docs_attrs(cx, Some(impl_item.id),
1920 impl_item.span, desc);
1923 fn check_struct_field(&mut self, cx: &Context, sf: &hir::StructField) {
1924 if let hir::NamedField(_, vis) = sf.node.kind {
1925 if vis == hir::Public || self.in_variant {
1926 let cur_struct_def = *self.struct_def_stack.last()
1927 .expect("empty struct_def_stack");
1928 self.check_missing_docs_attrs(cx, Some(cur_struct_def),
1929 &sf.node.attrs, sf.span,
1935 fn check_variant(&mut self, cx: &Context, v: &hir::Variant, _: &hir::Generics) {
1936 self.check_missing_docs_attrs(cx, Some(v.node.id), &v.node.attrs, v.span, "a variant");
1937 assert!(!self.in_variant);
1938 self.in_variant = true;
1941 fn check_variant_post(&mut self, _: &Context, _: &hir::Variant, _: &hir::Generics) {
1942 assert!(self.in_variant);
1943 self.in_variant = false;
1948 pub MISSING_COPY_IMPLEMENTATIONS,
1950 "detects potentially-forgotten implementations of `Copy`"
1953 #[derive(Copy, Clone)]
1954 pub struct MissingCopyImplementations;
1956 impl LintPass for MissingCopyImplementations {
1957 fn get_lints(&self) -> LintArray {
1958 lint_array!(MISSING_COPY_IMPLEMENTATIONS)
1961 fn check_item(&mut self, cx: &Context, item: &hir::Item) {
1962 if !cx.exported_items.contains(&item.id) {
1965 let (def, ty) = match item.node {
1966 hir::ItemStruct(_, ref ast_generics) => {
1967 if ast_generics.is_parameterized() {
1970 let def = cx.tcx.lookup_adt_def(DefId::local(item.id));
1971 (def, cx.tcx.mk_struct(def,
1972 cx.tcx.mk_substs(Substs::empty())))
1974 hir::ItemEnum(_, ref ast_generics) => {
1975 if ast_generics.is_parameterized() {
1978 let def = cx.tcx.lookup_adt_def(DefId::local(item.id));
1979 (def, cx.tcx.mk_enum(def,
1980 cx.tcx.mk_substs(Substs::empty())))
1984 if def.has_dtor() { return; }
1985 let parameter_environment = cx.tcx.empty_parameter_environment();
1986 // FIXME (@jroesch) should probably inver this so that the parameter env still impls this
1988 if !ty.moves_by_default(¶meter_environment, item.span) {
1991 if parameter_environment.can_type_implement_copy(ty, item.span).is_ok() {
1992 cx.span_lint(MISSING_COPY_IMPLEMENTATIONS,
1994 "type could implement `Copy`; consider adding `impl \
2001 MISSING_DEBUG_IMPLEMENTATIONS,
2003 "detects missing implementations of fmt::Debug"
2006 pub struct MissingDebugImplementations {
2007 impling_types: Option<NodeSet>,
2010 impl MissingDebugImplementations {
2011 pub fn new() -> MissingDebugImplementations {
2012 MissingDebugImplementations {
2013 impling_types: None,
2018 impl LintPass for MissingDebugImplementations {
2019 fn get_lints(&self) -> LintArray {
2020 lint_array!(MISSING_DEBUG_IMPLEMENTATIONS)
2023 fn check_item(&mut self, cx: &Context, item: &hir::Item) {
2024 if !cx.exported_items.contains(&item.id) {
2029 hir::ItemStruct(..) | hir::ItemEnum(..) => {},
2033 let debug = match cx.tcx.lang_items.debug_trait() {
2034 Some(debug) => debug,
2038 if self.impling_types.is_none() {
2039 let debug_def = cx.tcx.lookup_trait_def(debug);
2040 let mut impls = NodeSet();
2041 debug_def.for_each_impl(cx.tcx, |d| {
2043 if let Some(ty_def) = cx.tcx.node_id_to_type(d.node).ty_to_def_id() {
2044 impls.insert(ty_def.node);
2049 self.impling_types = Some(impls);
2050 debug!("{:?}", self.impling_types);
2053 if !self.impling_types.as_ref().unwrap().contains(&item.id) {
2054 cx.span_lint(MISSING_DEBUG_IMPLEMENTATIONS,
2056 "type does not implement `fmt::Debug`; consider adding #[derive(Debug)] \
2057 or a manual implementation")
2065 "detects use of #[deprecated] items"
2068 /// Checks for use of items with `#[deprecated]` attributes
2069 #[derive(Copy, Clone)]
2070 pub struct Stability;
2073 fn lint(&self, cx: &Context, _id: DefId,
2074 span: Span, stability: &Option<&attr::Stability>) {
2075 // Deprecated attributes apply in-crate and cross-crate.
2076 let (lint, label) = match *stability {
2077 Some(&attr::Stability { deprecated_since: Some(_), .. }) =>
2078 (DEPRECATED, "deprecated"),
2082 output(cx, span, stability, lint, label);
2084 fn output(cx: &Context, span: Span, stability: &Option<&attr::Stability>,
2085 lint: &'static Lint, label: &'static str) {
2086 let msg = match *stability {
2087 Some(&attr::Stability { reason: Some(ref s), .. }) => {
2088 format!("use of {} item: {}", label, *s)
2090 _ => format!("use of {} item", label)
2093 cx.span_lint(lint, span, &msg[..]);
2098 fn hir_to_ast_stability(stab: &attr::Stability) -> attr::Stability {
2100 level: match stab.level {
2101 attr::Unstable => attr::Unstable,
2102 attr::Stable => attr::Stable,
2104 feature: stab.feature.clone(),
2105 since: stab.since.clone(),
2106 deprecated_since: stab.deprecated_since.clone(),
2107 reason: stab.reason.clone(),
2112 impl LintPass for Stability {
2113 fn get_lints(&self) -> LintArray {
2114 lint_array!(DEPRECATED)
2117 fn check_item(&mut self, cx: &Context, item: &hir::Item) {
2118 stability::check_item(cx.tcx, item, false,
2120 self.lint(cx, id, sp,
2121 &stab.map(|s| hir_to_ast_stability(s)).as_ref()));
2124 fn check_expr(&mut self, cx: &Context, e: &hir::Expr) {
2125 stability::check_expr(cx.tcx, e,
2127 self.lint(cx, id, sp,
2128 &stab.map(|s| hir_to_ast_stability(s)).as_ref()));
2131 fn check_path(&mut self, cx: &Context, path: &hir::Path, id: ast::NodeId) {
2132 stability::check_path(cx.tcx, path, id,
2134 self.lint(cx, id, sp,
2135 &stab.map(|s| hir_to_ast_stability(s)).as_ref()));
2138 fn check_pat(&mut self, cx: &Context, pat: &hir::Pat) {
2139 stability::check_pat(cx.tcx, pat,
2141 self.lint(cx, id, sp,
2142 &stab.map(|s| hir_to_ast_stability(s)).as_ref()));
2147 pub UNCONDITIONAL_RECURSION,
2149 "functions that cannot return without calling themselves"
2152 #[derive(Copy, Clone)]
2153 pub struct UnconditionalRecursion;
2156 impl LintPass for UnconditionalRecursion {
2157 fn get_lints(&self) -> LintArray {
2158 lint_array![UNCONDITIONAL_RECURSION]
2161 fn check_fn(&mut self, cx: &Context, fn_kind: FnKind, _: &hir::FnDecl,
2162 blk: &hir::Block, sp: Span, id: ast::NodeId) {
2163 type F = for<'tcx> fn(&ty::ctxt<'tcx>,
2164 ast::NodeId, ast::NodeId, ast::Ident, ast::NodeId) -> bool;
2166 let method = match fn_kind {
2167 FnKind::ItemFn(..) => None,
2168 FnKind::Method(..) => {
2169 cx.tcx.impl_or_trait_item(DefId::local(id)).as_opt_method()
2171 // closures can't recur, so they don't matter.
2172 FnKind::Closure => return
2175 // Walk through this function (say `f`) looking to see if
2176 // every possible path references itself, i.e. the function is
2177 // called recursively unconditionally. This is done by trying
2178 // to find a path from the entry node to the exit node that
2179 // *doesn't* call `f` by traversing from the entry while
2180 // pretending that calls of `f` are sinks (i.e. ignoring any
2181 // exit edges from them).
2183 // NB. this has an edge case with non-returning statements,
2184 // like `loop {}` or `panic!()`: control flow never reaches
2185 // the exit node through these, so one can have a function
2186 // that never actually calls itselfs but is still picked up by
2189 // fn f(cond: bool) {
2190 // if !cond { panic!() } // could come from `assert!(cond)`
2194 // In general, functions of that form may be able to call
2195 // itself a finite number of times and then diverge. The lint
2196 // considers this to be an error for two reasons, (a) it is
2197 // easier to implement, and (b) it seems rare to actually want
2198 // to have behaviour like the above, rather than
2199 // e.g. accidentally recurring after an assert.
2201 let cfg = cfg::CFG::new(cx.tcx, blk);
2203 let mut work_queue = vec![cfg.entry];
2204 let mut reached_exit_without_self_call = false;
2205 let mut self_call_spans = vec![];
2206 let mut visited = HashSet::new();
2208 while let Some(idx) = work_queue.pop() {
2209 if idx == cfg.exit {
2211 reached_exit_without_self_call = true;
2215 let cfg_id = idx.node_id();
2216 if visited.contains(&cfg_id) {
2220 visited.insert(cfg_id);
2222 let node_id = cfg.graph.node_data(idx).id();
2224 // is this a recursive call?
2225 let self_recursive = if node_id != ast::DUMMY_NODE_ID {
2227 Some(ref method) => {
2228 expr_refers_to_this_method(cx.tcx, method, node_id)
2230 None => expr_refers_to_this_fn(cx.tcx, id, node_id)
2236 self_call_spans.push(cx.tcx.map.span(node_id));
2237 // this is a self call, so we shouldn't explore past
2238 // this node in the CFG.
2241 // add the successors of this node to explore the graph further.
2242 for (_, edge) in cfg.graph.outgoing_edges(idx) {
2243 let target_idx = edge.target();
2244 let target_cfg_id = target_idx.node_id();
2245 if !visited.contains(&target_cfg_id) {
2246 work_queue.push(target_idx)
2251 // Check the number of self calls because a function that
2252 // doesn't return (e.g. calls a `-> !` function or `loop { /*
2253 // no break */ }`) shouldn't be linted unless it actually
2255 if !reached_exit_without_self_call && !self_call_spans.is_empty() {
2256 cx.span_lint(UNCONDITIONAL_RECURSION, sp,
2257 "function cannot return without recurring");
2259 // FIXME #19668: these could be span_lint_note's instead of this manual guard.
2260 if cx.current_level(UNCONDITIONAL_RECURSION) != Level::Allow {
2261 let sess = cx.sess();
2262 // offer some help to the programmer.
2263 for call in &self_call_spans {
2264 sess.span_note(*call, "recursive call site")
2266 sess.fileline_help(sp, "a `loop` may express intention \
2267 better if this is on purpose")
2274 // Functions for identifying if the given Expr NodeId `id`
2275 // represents a call to the function `fn_id`/method `method`.
2277 fn expr_refers_to_this_fn(tcx: &ty::ctxt,
2279 id: ast::NodeId) -> bool {
2280 match tcx.map.get(id) {
2281 hir_map::NodeExpr(&hir::Expr { node: hir::ExprCall(ref callee, _), .. }) => {
2282 tcx.def_map.borrow().get(&callee.id)
2283 .map_or(false, |def| def.def_id() == DefId::local(fn_id))
2289 // Check if the expression `id` performs a call to `method`.
2290 fn expr_refers_to_this_method(tcx: &ty::ctxt,
2291 method: &ty::Method,
2292 id: ast::NodeId) -> bool {
2293 let tables = tcx.tables.borrow();
2295 // Check for method calls and overloaded operators.
2296 if let Some(m) = tables.method_map.get(&ty::MethodCall::expr(id)) {
2297 if method_call_refers_to_method(tcx, method, m.def_id, m.substs, id) {
2302 // Check for overloaded autoderef method calls.
2303 if let Some(&adjustment::AdjustDerefRef(ref adj)) = tables.adjustments.get(&id) {
2304 for i in 0..adj.autoderefs {
2305 let method_call = ty::MethodCall::autoderef(id, i as u32);
2306 if let Some(m) = tables.method_map.get(&method_call) {
2307 if method_call_refers_to_method(tcx, method, m.def_id, m.substs, id) {
2314 // Check for calls to methods via explicit paths (e.g. `T::method()`).
2315 match tcx.map.get(id) {
2316 hir_map::NodeExpr(&hir::Expr { node: hir::ExprCall(ref callee, _), .. }) => {
2317 match tcx.def_map.borrow().get(&callee.id).map(|d| d.full_def()) {
2318 Some(def::DefMethod(def_id)) => {
2319 let no_substs = &ty::ItemSubsts::empty();
2320 let ts = tables.item_substs.get(&callee.id).unwrap_or(no_substs);
2321 method_call_refers_to_method(tcx, method, def_id, &ts.substs, id)
2330 // Check if the method call to the method with the ID `callee_id`
2331 // and instantiated with `callee_substs` refers to method `method`.
2332 fn method_call_refers_to_method<'tcx>(tcx: &ty::ctxt<'tcx>,
2333 method: &ty::Method,
2335 callee_substs: &Substs<'tcx>,
2336 expr_id: ast::NodeId) -> bool {
2337 let callee_item = tcx.impl_or_trait_item(callee_id);
2339 match callee_item.container() {
2340 // This is an inherent method, so the `def_id` refers
2341 // directly to the method definition.
2342 ty::ImplContainer(_) => {
2343 callee_id == method.def_id
2346 // A trait method, from any number of possible sources.
2347 // Attempt to select a concrete impl before checking.
2348 ty::TraitContainer(trait_def_id) => {
2349 let trait_substs = callee_substs.clone().method_to_trait();
2350 let trait_substs = tcx.mk_substs(trait_substs);
2351 let trait_ref = ty::TraitRef::new(trait_def_id, trait_substs);
2352 let trait_ref = ty::Binder(trait_ref);
2353 let span = tcx.map.span(expr_id);
2355 traits::Obligation::new(traits::ObligationCause::misc(span, expr_id),
2356 trait_ref.to_poly_trait_predicate());
2358 let param_env = ty::ParameterEnvironment::for_item(tcx, method.def_id.node);
2359 let infcx = infer::new_infer_ctxt(tcx, &tcx.tables, Some(param_env), false);
2360 let mut selcx = traits::SelectionContext::new(&infcx);
2361 match selcx.select(&obligation) {
2362 // The method comes from a `T: Trait` bound.
2363 // If `T` is `Self`, then this call is inside
2364 // a default method definition.
2365 Ok(Some(traits::VtableParam(_))) => {
2366 let self_ty = callee_substs.self_ty();
2367 let on_self = self_ty.map_or(false, |t| t.is_self());
2368 // We can only be recurring in a default
2369 // method if we're being called literally
2370 // on the `Self` type.
2371 on_self && callee_id == method.def_id
2374 // The `impl` is known, so we check that with a
2376 Ok(Some(traits::VtableImpl(vtable_impl))) => {
2377 let container = ty::ImplContainer(vtable_impl.impl_def_id);
2378 // It matches if it comes from the same impl,
2379 // and has the same method name.
2380 container == method.container
2381 && callee_item.name() == method.name
2384 // There's no way to know if this call is
2385 // recursive, so we assume it's not.
2397 "compiler plugin used as ordinary library in non-plugin crate"
2400 #[derive(Copy, Clone)]
2401 pub struct PluginAsLibrary;
2403 impl LintPass for PluginAsLibrary {
2404 fn get_lints(&self) -> LintArray {
2405 lint_array![PLUGIN_AS_LIBRARY]
2408 fn check_item(&mut self, cx: &Context, it: &hir::Item) {
2409 if cx.sess().plugin_registrar_fn.get().is_some() {
2410 // We're compiling a plugin; it's fine to link other plugins.
2415 hir::ItemExternCrate(..) => (),
2419 let md = match cx.sess().cstore.find_extern_mod_stmt_cnum(it.id) {
2420 Some(cnum) => cx.sess().cstore.get_crate_data(cnum),
2422 // Probably means we aren't linking the crate for some reason.
2424 // Not sure if / when this could happen.
2429 if decoder::get_plugin_registrar_fn(md.data()).is_some() {
2430 cx.span_lint(PLUGIN_AS_LIBRARY, it.span,
2431 "compiler plugin used as an ordinary library");
2437 PRIVATE_NO_MANGLE_FNS,
2439 "functions marked #[no_mangle] should be exported"
2443 PRIVATE_NO_MANGLE_STATICS,
2445 "statics marked #[no_mangle] should be exported"
2449 NO_MANGLE_CONST_ITEMS,
2451 "const items will not have their symbols exported"
2454 #[derive(Copy, Clone)]
2455 pub struct InvalidNoMangleItems;
2457 impl LintPass for InvalidNoMangleItems {
2458 fn get_lints(&self) -> LintArray {
2459 lint_array!(PRIVATE_NO_MANGLE_FNS,
2460 PRIVATE_NO_MANGLE_STATICS,
2461 NO_MANGLE_CONST_ITEMS)
2464 fn check_item(&mut self, cx: &Context, it: &hir::Item) {
2466 hir::ItemFn(..) => {
2467 if attr::contains_name(&it.attrs, "no_mangle") &&
2468 !cx.exported_items.contains(&it.id) {
2469 let msg = format!("function {} is marked #[no_mangle], but not exported",
2471 cx.span_lint(PRIVATE_NO_MANGLE_FNS, it.span, &msg);
2474 hir::ItemStatic(..) => {
2475 if attr::contains_name(&it.attrs, "no_mangle") &&
2476 !cx.exported_items.contains(&it.id) {
2477 let msg = format!("static {} is marked #[no_mangle], but not exported",
2479 cx.span_lint(PRIVATE_NO_MANGLE_STATICS, it.span, &msg);
2482 hir::ItemConst(..) => {
2483 if attr::contains_name(&it.attrs, "no_mangle") {
2484 // Const items do not refer to a particular location in memory, and therefore
2485 // don't have anything to attach a symbol to
2486 let msg = "const items should never be #[no_mangle], consider instead using \
2488 cx.span_lint(NO_MANGLE_CONST_ITEMS, it.span, msg);
2496 #[derive(Clone, Copy)]
2497 pub struct MutableTransmutes;
2502 "mutating transmuted &mut T from &T may cause undefined behavior"
2505 impl LintPass for MutableTransmutes {
2506 fn get_lints(&self) -> LintArray {
2507 lint_array!(MUTABLE_TRANSMUTES)
2510 fn check_expr(&mut self, cx: &Context, expr: &hir::Expr) {
2511 use syntax::abi::RustIntrinsic;
2513 let msg = "mutating transmuted &mut T from &T may cause undefined behavior,\
2514 consider instead using an UnsafeCell";
2515 match get_transmute_from_to(cx, expr) {
2516 Some((&ty::TyRef(_, from_mt), &ty::TyRef(_, to_mt))) => {
2517 if to_mt.mutbl == hir::Mutability::MutMutable
2518 && from_mt.mutbl == hir::Mutability::MutImmutable {
2519 cx.span_lint(MUTABLE_TRANSMUTES, expr.span, msg);
2525 fn get_transmute_from_to<'a, 'tcx>(cx: &Context<'a, 'tcx>, expr: &hir::Expr)
2526 -> Option<(&'tcx ty::TypeVariants<'tcx>, &'tcx ty::TypeVariants<'tcx>)> {
2528 hir::ExprPath(..) => (),
2531 if let def::DefFn(did, _) = cx.tcx.resolve_expr(expr) {
2532 if !def_id_is_transmute(cx, did) {
2535 let typ = cx.tcx.node_id_to_type(expr.id);
2537 ty::TyBareFn(_, ref bare_fn) if bare_fn.abi == RustIntrinsic => {
2538 if let ty::FnConverging(to) = bare_fn.sig.0.output {
2539 let from = bare_fn.sig.0.inputs[0];
2540 return Some((&from.sty, &to.sty));
2549 fn def_id_is_transmute(cx: &Context, def_id: DefId) -> bool {
2550 match cx.tcx.lookup_item_type(def_id).ty.sty {
2551 ty::TyBareFn(_, ref bfty) if bfty.abi == RustIntrinsic => (),
2554 cx.tcx.with_path(def_id, |path| match path.last() {
2555 Some(ref last) => last.name().as_str() == "transmute",
2562 /// Forbids using the `#[feature(...)]` attribute
2563 #[derive(Copy, Clone)]
2564 pub struct UnstableFeatures;
2569 "enabling unstable features (deprecated. do not use)"
2572 impl LintPass for UnstableFeatures {
2573 fn get_lints(&self) -> LintArray {
2574 lint_array!(UNSTABLE_FEATURES)
2576 fn check_attribute(&mut self, ctx: &Context, attr: &hir::Attribute) {
2577 if attr::contains_name(&[attr.node.value.clone()], "feature") {
2578 if let Some(items) = attr.node.value.meta_item_list() {
2580 ctx.span_lint(UNSTABLE_FEATURES, item.span, "unstable feature");
2587 /// Lints for attempts to impl Drop on types that have `#[repr(C)]`
2588 /// attribute (see issue #24585).
2589 #[derive(Copy, Clone)]
2590 pub struct DropWithReprExtern;
2593 DROP_WITH_REPR_EXTERN,
2595 "use of #[repr(C)] on a type that implements Drop"
2598 impl LintPass for DropWithReprExtern {
2599 fn get_lints(&self) -> LintArray {
2600 lint_array!(DROP_WITH_REPR_EXTERN)
2602 fn check_crate(&mut self, ctx: &Context, _: &hir::Crate) {
2603 for dtor_did in ctx.tcx.destructors.borrow().iter() {
2604 let (drop_impl_did, dtor_self_type) =
2605 if dtor_did.is_local() {
2606 let impl_did = ctx.tcx.map.get_parent_did(dtor_did.node);
2607 let ty = ctx.tcx.lookup_item_type(impl_did).ty;
2613 match dtor_self_type.sty {
2614 ty::TyEnum(self_type_def, _) |
2615 ty::TyStruct(self_type_def, _) => {
2616 let self_type_did = self_type_def.did;
2617 let hints = ctx.tcx.lookup_repr_hints(self_type_did);
2618 if hints.iter().any(|attr| *attr == attr::ReprExtern) &&
2619 self_type_def.dtor_kind().has_drop_flag() {
2620 let drop_impl_span = ctx.tcx.map.def_id_span(drop_impl_did,
2622 let self_defn_span = ctx.tcx.map.def_id_span(self_type_did,
2624 ctx.span_lint(DROP_WITH_REPR_EXTERN,
2626 "implementing Drop adds hidden state to types, \
2627 possibly conflicting with `#[repr(C)]`");
2628 // FIXME #19668: could be span_lint_note instead of manual guard.
2629 if ctx.current_level(DROP_WITH_REPR_EXTERN) != Level::Allow {
2630 ctx.sess().span_note(self_defn_span,
2631 "the `#[repr(C)]` attribute is attached here");