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::ast_util::is_shift_binop;
49 use syntax::attr::{self, AttrMetaMethods};
50 use syntax::codemap::{self, Span};
51 use syntax::feature_gate::{KNOWN_ATTRIBUTES, AttributeType};
52 use syntax::ast::{TyIs, TyUs, TyI8, TyU8, TyI16, TyU16, TyI32, TyU32, TyI64, TyU64};
54 use syntax::visit::{self, FnKind, Visitor};
56 use rustc_front::lowering::{lower_expr, lower_block, lower_item, lower_path, lower_pat,
59 use rustc_front::attr as front_attr;
60 use rustc_front::attr::AttrMetaMethods as FrontAttrMetaMethods;
61 use rustc_front::visit::Visitor as HirVisitor;
62 use rustc_front::visit as hir_visit;
64 // hardwired lints from librustc
65 pub use lint::builtin::*;
70 "suggest using `loop { }` instead of `while true { }`"
73 #[derive(Copy, Clone)]
76 impl LintPass for WhileTrue {
77 fn get_lints(&self) -> LintArray {
78 lint_array!(WHILE_TRUE)
81 fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
82 if let ast::ExprWhile(ref cond, _, _) = e.node {
83 if let ast::ExprLit(ref lit) = cond.node {
84 if let ast::LitBool(true) = lit.node {
85 cx.span_lint(WHILE_TRUE, e.span,
86 "denote infinite loops with loop { ... }");
96 "comparisons made useless by limits of the types involved"
100 OVERFLOWING_LITERALS,
102 "literal out of range for its type"
108 "shift exceeds the type's number of bits"
111 #[derive(Copy, Clone)]
112 pub struct TypeLimits {
113 /// Id of the last visited negated expression
114 negated_expr_id: ast::NodeId,
118 pub fn new() -> TypeLimits {
125 impl LintPass for TypeLimits {
126 fn get_lints(&self) -> LintArray {
127 lint_array!(UNUSED_COMPARISONS, OVERFLOWING_LITERALS, EXCEEDING_BITSHIFTS)
130 fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
132 ast::ExprUnary(ast::UnNeg, ref expr) => {
134 ast::ExprLit(ref lit) => {
136 ast::LitInt(_, ast::UnsignedIntLit(_)) => {
137 check_unsigned_negation_feature(cx, e.span);
139 ast::LitInt(_, ast::UnsuffixedIntLit(_)) => {
140 if let ty::TyUint(_) = cx.tcx.node_id_to_type(e.id).sty {
141 check_unsigned_negation_feature(cx, e.span);
148 let t = cx.tcx.node_id_to_type(expr.id);
151 check_unsigned_negation_feature(cx, e.span);
157 // propagate negation, if the negation itself isn't negated
158 if self.negated_expr_id != e.id {
159 self.negated_expr_id = expr.id;
162 ast::ExprParen(ref expr) if self.negated_expr_id == e.id => {
163 self.negated_expr_id = expr.id;
165 ast::ExprBinary(binop, ref l, ref r) => {
166 if is_comparison(binop) && !check_limits(cx.tcx, binop, &**l, &**r) {
167 cx.span_lint(UNUSED_COMPARISONS, e.span,
168 "comparison is useless due to type limits");
171 if is_shift_binop(binop.node) {
172 let opt_ty_bits = match cx.tcx.node_id_to_type(l.id).sty {
173 ty::TyInt(t) => Some(int_ty_bits(t, cx.sess().target.int_type)),
174 ty::TyUint(t) => Some(uint_ty_bits(t, cx.sess().target.uint_type)),
178 if let Some(bits) = opt_ty_bits {
179 let exceeding = if let ast::ExprLit(ref lit) = r.node {
180 if let ast::LitInt(shift, _) = lit.node { shift >= bits }
183 let r = lower_expr(r);
184 match eval_const_expr_partial(cx.tcx, &r, ExprTypeChecked) {
185 Ok(ConstVal::Int(shift)) => { shift as u64 >= bits },
186 Ok(ConstVal::Uint(shift)) => { shift >= bits },
191 cx.span_lint(EXCEEDING_BITSHIFTS, e.span,
192 "bitshift exceeds the type's number of bits");
197 ast::ExprLit(ref lit) => {
198 match cx.tcx.node_id_to_type(e.id).sty {
201 ast::LitInt(v, ast::SignedIntLit(_, ast::Plus)) |
202 ast::LitInt(v, ast::UnsuffixedIntLit(ast::Plus)) => {
203 let int_type = if let hir::TyIs = t {
204 cx.sess().target.int_type
208 let (_, max) = int_ty_range(int_type);
209 let negative = self.negated_expr_id == e.id;
211 // Detect literal value out of range [min, max] inclusive
212 // avoiding use of -min to prevent overflow/panic
213 if (negative && v > max as u64 + 1) ||
214 (!negative && v > max as u64) {
215 cx.span_lint(OVERFLOWING_LITERALS, e.span,
216 &*format!("literal out of range for {:?}", t));
224 let uint_type = if let hir::TyUs = t {
225 cx.sess().target.uint_type
229 let (min, max) = uint_ty_range(uint_type);
230 let lit_val: u64 = match lit.node {
231 ast::LitByte(_v) => return, // _v is u8, within range by definition
232 ast::LitInt(v, _) => v,
235 if lit_val < min || lit_val > max {
236 cx.span_lint(OVERFLOWING_LITERALS, e.span,
237 &*format!("literal out of range for {:?}", t));
241 let (min, max) = float_ty_range(t);
242 let lit_val: f64 = match lit.node {
243 ast::LitFloat(ref v, _) |
244 ast::LitFloatUnsuffixed(ref v) => {
252 if lit_val < min || lit_val > max {
253 cx.span_lint(OVERFLOWING_LITERALS, e.span,
254 &*format!("literal out of range for {:?}", t));
263 fn is_valid<T:cmp::PartialOrd>(binop: ast::BinOp, v: T,
264 min: T, max: T) -> bool {
266 ast::BiLt => v > min && v <= max,
267 ast::BiLe => v >= min && v < max,
268 ast::BiGt => v >= min && v < max,
269 ast::BiGe => v > min && v <= max,
270 ast::BiEq | ast::BiNe => v >= min && v <= max,
275 fn rev_binop(binop: ast::BinOp) -> ast::BinOp {
276 codemap::respan(binop.span, match binop.node {
277 ast::BiLt => ast::BiGt,
278 ast::BiLe => ast::BiGe,
279 ast::BiGt => ast::BiLt,
280 ast::BiGe => ast::BiLe,
285 // for isize & usize, be conservative with the warnings, so that the
286 // warnings are consistent between 32- and 64-bit platforms
287 fn int_ty_range(int_ty: hir::IntTy) -> (i64, i64) {
289 hir::TyIs => (i64::MIN, i64::MAX),
290 hir::TyI8 => (i8::MIN as i64, i8::MAX as i64),
291 hir::TyI16 => (i16::MIN as i64, i16::MAX as i64),
292 hir::TyI32 => (i32::MIN as i64, i32::MAX as i64),
293 hir::TyI64 => (i64::MIN, i64::MAX)
297 fn uint_ty_range(uint_ty: hir::UintTy) -> (u64, u64) {
299 hir::TyUs => (u64::MIN, u64::MAX),
300 hir::TyU8 => (u8::MIN as u64, u8::MAX as u64),
301 hir::TyU16 => (u16::MIN as u64, u16::MAX as u64),
302 hir::TyU32 => (u32::MIN as u64, u32::MAX as u64),
303 hir::TyU64 => (u64::MIN, u64::MAX)
307 fn float_ty_range(float_ty: hir::FloatTy) -> (f64, f64) {
309 hir::TyF32 => (f32::MIN as f64, f32::MAX as f64),
310 hir::TyF64 => (f64::MIN, f64::MAX)
314 fn int_ty_bits(int_ty: hir::IntTy, target_int_ty: hir::IntTy) -> u64 {
316 hir::TyIs => int_ty_bits(target_int_ty, target_int_ty),
317 hir::TyI8 => i8::BITS as u64,
318 hir::TyI16 => i16::BITS as u64,
319 hir::TyI32 => i32::BITS as u64,
320 hir::TyI64 => i64::BITS as u64
324 fn uint_ty_bits(uint_ty: hir::UintTy, target_uint_ty: hir::UintTy) -> u64 {
326 hir::TyUs => uint_ty_bits(target_uint_ty, target_uint_ty),
327 hir::TyU8 => u8::BITS as u64,
328 hir::TyU16 => u16::BITS as u64,
329 hir::TyU32 => u32::BITS as u64,
330 hir::TyU64 => u64::BITS as u64
334 fn check_limits(tcx: &ty::ctxt, binop: ast::BinOp,
335 l: &ast::Expr, r: &ast::Expr) -> bool {
336 let (lit, expr, swap) = match (&l.node, &r.node) {
337 (&ast::ExprLit(_), _) => (l, r, true),
338 (_, &ast::ExprLit(_)) => (r, l, false),
341 // Normalize the binop so that the literal is always on the RHS in
343 let norm_binop = if swap {
348 match tcx.node_id_to_type(expr.id).sty {
349 ty::TyInt(int_ty) => {
350 let (min, max) = int_ty_range(int_ty);
351 let lit_val: i64 = match lit.node {
352 ast::ExprLit(ref li) => match li.node {
353 ast::LitInt(v, ast::SignedIntLit(_, ast::Plus)) |
354 ast::LitInt(v, ast::UnsuffixedIntLit(ast::Plus)) => v as i64,
355 ast::LitInt(v, ast::SignedIntLit(_, ast::Minus)) |
356 ast::LitInt(v, ast::UnsuffixedIntLit(ast::Minus)) => -(v as i64),
361 is_valid(norm_binop, lit_val, min, max)
363 ty::TyUint(uint_ty) => {
364 let (min, max): (u64, u64) = uint_ty_range(uint_ty);
365 let lit_val: u64 = match lit.node {
366 ast::ExprLit(ref li) => match li.node {
367 ast::LitInt(v, _) => v,
372 is_valid(norm_binop, lit_val, min, max)
378 fn is_comparison(binop: ast::BinOp) -> bool {
380 ast::BiEq | ast::BiLt | ast::BiLe |
381 ast::BiNe | ast::BiGe | ast::BiGt => true,
386 fn check_unsigned_negation_feature(cx: &Context, span: Span) {
387 if !cx.sess().features.borrow().negate_unsigned {
388 // FIXME(#27141): change this to syntax::feature_gate::emit_feature_err…
389 cx.sess().span_warn(span,
390 "unary negation of unsigned integers will be feature gated in the future");
391 // …and remove following two expressions.
392 if option_env!("CFG_DISABLE_UNSTABLE_FEATURES").is_some() { return; }
393 cx.sess().fileline_help(span, "add #![feature(negate_unsigned)] to the \
394 crate attributes to enable the gate in advance");
403 "proper use of libc types in foreign modules"
406 struct ImproperCTypesVisitor<'a, 'tcx: 'a> {
407 cx: &'a Context<'a, 'tcx>
412 FfiUnsafe(&'static str),
413 FfiBadStruct(DefId, &'static str),
414 FfiBadEnum(DefId, &'static str)
417 /// Check if this enum can be safely exported based on the
418 /// "nullable pointer optimization". Currently restricted
419 /// to function pointers and references, but could be
420 /// expanded to cover NonZero raw pointers and newtypes.
421 /// FIXME: This duplicates code in trans.
422 fn is_repr_nullable_ptr<'tcx>(tcx: &ty::ctxt<'tcx>,
423 def: ty::AdtDef<'tcx>,
424 substs: &Substs<'tcx>)
426 if def.variants.len() == 2 {
429 if def.variants[0].fields.is_empty() {
431 } else if def.variants[1].fields.is_empty() {
437 if def.variants[data_idx].fields.len() == 1 {
438 match def.variants[data_idx].fields[0].ty(tcx, substs).sty {
439 ty::TyBareFn(None, _) => { return true; }
440 ty::TyRef(..) => { return true; }
448 fn ast_ty_to_normalized<'tcx>(tcx: &ty::ctxt<'tcx>,
451 let tty = match tcx.ast_ty_to_ty_cache.borrow().get(&id) {
453 None => panic!("ast_ty_to_ty_cache was incomplete after typeck!")
455 infer::normalize_associated_type(tcx, &tty)
458 impl<'a, 'tcx> ImproperCTypesVisitor<'a, 'tcx> {
459 /// Check if the given type is "ffi-safe" (has a stable, well-defined
460 /// representation which can be exported to C code).
461 fn check_type_for_ffi(&self,
462 cache: &mut FnvHashSet<Ty<'tcx>>,
465 use self::FfiResult::*;
466 let cx = &self.cx.tcx;
468 // Protect against infinite recursion, for example
469 // `struct S(*mut S);`.
470 // FIXME: A recursion limit is necessary as well, for irregular
472 if !cache.insert(ty) {
477 ty::TyStruct(def, substs) => {
478 if !cx.lookup_repr_hints(def.did).contains(&front_attr::ReprExtern) {
480 "found struct without foreign-function-safe \
481 representation annotation in foreign module, \
482 consider adding a #[repr(C)] attribute to \
486 // We can't completely trust repr(C) markings; make sure the
487 // fields are actually safe.
488 if def.struct_variant().fields.is_empty() {
490 "found zero-size struct in foreign module, consider \
491 adding a member to this struct");
494 for field in &def.struct_variant().fields {
495 let field_ty = infer::normalize_associated_type(cx, &field.ty(cx, substs));
496 let r = self.check_type_for_ffi(cache, field_ty);
499 FfiBadStruct(..) | FfiBadEnum(..) => { return r; }
500 FfiUnsafe(s) => { return FfiBadStruct(def.did, s); }
505 ty::TyEnum(def, substs) => {
506 if def.variants.is_empty() {
507 // Empty enums are okay... although sort of useless.
511 // Check for a repr() attribute to specify the size of the
513 let repr_hints = cx.lookup_repr_hints(def.did);
514 match &**repr_hints {
516 // Special-case types like `Option<extern fn()>`.
517 if !is_repr_nullable_ptr(cx, def, substs) {
519 "found enum without foreign-function-safe \
520 representation annotation in foreign module, \
521 consider adding a #[repr(...)] attribute to \
526 if !hint.is_ffi_safe() {
527 // FIXME: This shouldn't be reachable: we should check
530 "enum has unexpected #[repr(...)] attribute")
533 // Enum with an explicitly sized discriminant; either
534 // a C-style enum or a discriminated union.
536 // The layout of enum variants is implicitly repr(C).
537 // FIXME: Is that correct?
540 // FIXME: This shouldn't be reachable: we should check
543 "enum has too many #[repr(...)] attributes");
547 // Check the contained variants.
548 for variant in &def.variants {
549 for field in &variant.fields {
550 let arg = infer::normalize_associated_type(cx, &field.ty(cx, substs));
551 let r = self.check_type_for_ffi(cache, arg);
554 FfiBadStruct(..) | FfiBadEnum(..) => { return r; }
555 FfiUnsafe(s) => { return FfiBadEnum(def.did, s); }
562 ty::TyInt(hir::TyIs) => {
563 FfiUnsafe("found Rust type `isize` in foreign module, while \
564 `libc::c_int` or `libc::c_long` should be used")
566 ty::TyUint(hir::TyUs) => {
567 FfiUnsafe("found Rust type `usize` in foreign module, while \
568 `libc::c_uint` or `libc::c_ulong` should be used")
571 FfiUnsafe("found Rust type `char` in foreign module, while \
572 `u32` or `libc::wchar_t` should be used")
575 // Primitive types with a stable representation.
576 ty::TyBool | ty::TyInt(..) | ty::TyUint(..) |
577 ty::TyFloat(..) => FfiSafe,
580 FfiUnsafe("found Rust type Box<_> in foreign module, \
581 consider using a raw pointer instead")
585 FfiUnsafe("found Rust slice type in foreign module, \
586 consider using a raw pointer instead")
590 FfiUnsafe("found Rust trait type in foreign module, \
591 consider using a raw pointer instead")
595 FfiUnsafe("found Rust type `str` in foreign module; \
596 consider using a `*const libc::c_char`")
600 FfiUnsafe("found Rust tuple type in foreign module; \
601 consider using a struct instead`")
604 ty::TyRawPtr(ref m) | ty::TyRef(_, ref m) => {
605 self.check_type_for_ffi(cache, m.ty)
608 ty::TyArray(ty, _) => {
609 self.check_type_for_ffi(cache, ty)
612 ty::TyBareFn(None, bare_fn) => {
616 abi::PlatformIntrinsic |
619 "found function pointer with Rust calling \
620 convention in foreign module; consider using an \
621 `extern` function pointer")
626 let sig = cx.erase_late_bound_regions(&bare_fn.sig);
628 ty::FnDiverging => {}
629 ty::FnConverging(output) => {
630 if !output.is_nil() {
631 let r = self.check_type_for_ffi(cache, output);
639 for arg in sig.inputs {
640 let r = self.check_type_for_ffi(cache, arg);
649 ty::TyParam(..) | ty::TyInfer(..) | ty::TyError |
650 ty::TyClosure(..) | ty::TyProjection(..) |
651 ty::TyBareFn(Some(_), _) => {
652 panic!("Unexpected type in foreign function")
657 fn check_def(&mut self, sp: Span, id: ast::NodeId) {
658 let tty = ast_ty_to_normalized(self.cx.tcx, id);
660 match ImproperCTypesVisitor::check_type_for_ffi(self, &mut FnvHashSet(), tty) {
661 FfiResult::FfiSafe => {}
662 FfiResult::FfiUnsafe(s) => {
663 self.cx.span_lint(IMPROPER_CTYPES, sp, s);
665 FfiResult::FfiBadStruct(_, s) => {
666 // FIXME: This diagnostic is difficult to read, and doesn't
667 // point at the relevant field.
668 self.cx.span_lint(IMPROPER_CTYPES, sp,
669 &format!("found non-foreign-function-safe member in \
670 struct marked #[repr(C)]: {}", s));
672 FfiResult::FfiBadEnum(_, s) => {
673 // FIXME: This diagnostic is difficult to read, and doesn't
674 // point at the relevant variant.
675 self.cx.span_lint(IMPROPER_CTYPES, sp,
676 &format!("found non-foreign-function-safe member in \
683 impl<'a, 'tcx, 'v> Visitor<'v> for ImproperCTypesVisitor<'a, 'tcx> {
684 fn visit_ty(&mut self, ty: &ast::Ty) {
687 ast::TyBareFn(..) => self.check_def(ty.span, ty.id),
689 self.cx.span_lint(IMPROPER_CTYPES, ty.span,
690 "found Rust slice type in foreign module, consider \
691 using a raw pointer instead");
693 ast::TyFixedLengthVec(ref ty, _) => self.visit_ty(ty),
695 self.cx.span_lint(IMPROPER_CTYPES, ty.span,
696 "found Rust tuple type in foreign module; \
697 consider using a struct instead`")
699 _ => visit::walk_ty(self, ty)
704 #[derive(Copy, Clone)]
705 pub struct ImproperCTypes;
707 impl LintPass for ImproperCTypes {
708 fn get_lints(&self) -> LintArray {
709 lint_array!(IMPROPER_CTYPES)
712 fn check_item(&mut self, cx: &Context, it: &ast::Item) {
713 fn check_ty(cx: &Context, ty: &ast::Ty) {
714 let mut vis = ImproperCTypesVisitor { cx: cx };
718 fn check_foreign_fn(cx: &Context, decl: &ast::FnDecl) {
719 for input in &decl.inputs {
720 check_ty(cx, &*input.ty);
722 if let ast::Return(ref ret_ty) = decl.output {
723 let tty = ast_ty_to_normalized(cx.tcx, ret_ty.id);
725 check_ty(cx, &ret_ty);
731 ast::ItemForeignMod(ref nmod)
732 if nmod.abi != abi::RustIntrinsic &&
733 nmod.abi != abi::PlatformIntrinsic => {
734 for ni in &nmod.items {
736 ast::ForeignItemFn(ref decl, _) => check_foreign_fn(cx, &**decl),
737 ast::ForeignItemStatic(ref t, _) => check_ty(cx, &**t)
749 "use of owned (Box type) heap memory"
752 #[derive(Copy, Clone)]
753 pub struct BoxPointers;
756 fn check_heap_type<'a, 'tcx>(&self, cx: &Context<'a, 'tcx>,
757 span: Span, ty: Ty<'tcx>) {
758 for leaf_ty in ty.walk() {
759 if let ty::TyBox(_) = leaf_ty.sty {
760 let m = format!("type uses owned (Box type) pointers: {}", ty);
761 cx.span_lint(BOX_POINTERS, span, &m);
767 impl LintPass for BoxPointers {
768 fn get_lints(&self) -> LintArray {
769 lint_array!(BOX_POINTERS)
772 fn check_item(&mut self, cx: &Context, it: &ast::Item) {
777 ast::ItemStruct(..) =>
778 self.check_heap_type(cx, it.span,
779 cx.tcx.node_id_to_type(it.id)),
783 // If it's a struct, we also have to check the fields' types
785 ast::ItemStruct(ref struct_def, _) => {
786 for struct_field in &struct_def.fields {
787 self.check_heap_type(cx, struct_field.span,
788 cx.tcx.node_id_to_type(struct_field.node.id));
795 fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
796 let ty = cx.tcx.node_id_to_type(e.id);
797 self.check_heap_type(cx, e.span, ty);
804 "uses of #[derive] with raw pointers are rarely correct"
807 struct RawPtrDeriveVisitor<'a, 'tcx: 'a> {
808 cx: &'a Context<'a, 'tcx>
811 impl<'a, 'tcx, 'v> HirVisitor<'v> for RawPtrDeriveVisitor<'a, 'tcx> {
812 fn visit_ty(&mut self, ty: &hir::Ty) {
813 const MSG: &'static str = "use of `#[derive]` with a raw pointer";
814 if let hir::TyPtr(..) = ty.node {
815 self.cx.span_lint(RAW_POINTER_DERIVE, ty.span, MSG);
817 hir_visit::walk_ty(self, ty);
819 // explicit override to a no-op to reduce code bloat
820 fn visit_expr(&mut self, _: &hir::Expr) {}
821 fn visit_block(&mut self, _: &hir::Block) {}
824 pub struct RawPointerDerive {
825 checked_raw_pointers: NodeSet,
828 impl RawPointerDerive {
829 pub fn new() -> RawPointerDerive {
831 checked_raw_pointers: NodeSet(),
836 impl LintPass for RawPointerDerive {
837 fn get_lints(&self) -> LintArray {
838 lint_array!(RAW_POINTER_DERIVE)
841 fn check_item(&mut self, cx: &Context, item: &ast::Item) {
842 if !attr::contains_name(&item.attrs, "automatically_derived") {
845 let item = lower_item(item);
846 let did = match item.node {
847 hir::ItemImpl(_, _, _, ref t_ref_opt, _, _) => {
848 // Deriving the Copy trait does not cause a warning
849 if let &Some(ref trait_ref) = t_ref_opt {
850 let def_id = cx.tcx.trait_ref_to_def_id(trait_ref);
851 if Some(def_id) == cx.tcx.lang_items.copy_trait() {
856 match cx.tcx.node_id_to_type(item.id).sty {
857 ty::TyEnum(def, _) => def.did,
858 ty::TyStruct(def, _) => def.did,
867 let item = match cx.tcx.map.find(did.node) {
868 Some(hir_map::NodeItem(item)) => item,
871 if !self.checked_raw_pointers.insert(item.id) {
875 hir::ItemStruct(..) | hir::ItemEnum(..) => {
876 let mut visitor = RawPtrDeriveVisitor { cx: cx };
877 hir_visit::walk_item(&mut visitor, &item);
887 "detects attributes that were not used by the compiler"
890 #[derive(Copy, Clone)]
891 pub struct UnusedAttributes;
893 impl LintPass for UnusedAttributes {
894 fn get_lints(&self) -> LintArray {
895 lint_array!(UNUSED_ATTRIBUTES)
898 fn check_attribute(&mut self, cx: &Context, attr: &ast::Attribute) {
899 // Note that check_name() marks the attribute as used if it matches.
900 for &(ref name, ty, _) in KNOWN_ATTRIBUTES {
902 AttributeType::Whitelisted if attr.check_name(name) => {
909 let plugin_attributes = cx.sess().plugin_attributes.borrow_mut();
910 for &(ref name, ty) in plugin_attributes.iter() {
911 if ty == AttributeType::Whitelisted && attr.check_name(&*name) {
916 if !attr::is_used(attr) {
917 cx.span_lint(UNUSED_ATTRIBUTES, attr.span, "unused attribute");
918 // Is it a builtin attribute that must be used at the crate level?
919 let known_crate = KNOWN_ATTRIBUTES.iter().find(|&&(name, ty, _)| {
920 attr.name() == name &&
921 ty == AttributeType::CrateLevel
924 // Has a plugin registered this attribute as one which must be used at
926 let plugin_crate = plugin_attributes.iter()
927 .find(|&&(ref x, t)| {
928 &*attr.name() == &*x &&
929 AttributeType::CrateLevel == t
931 if known_crate || plugin_crate {
932 let msg = match attr.node.style {
933 ast::AttrOuter => "crate-level attribute should be an inner \
934 attribute: add an exclamation mark: #![foo]",
935 ast::AttrInner => "crate-level attribute should be in the \
938 cx.span_lint(UNUSED_ATTRIBUTES, attr.span, msg);
947 "path statements with no effect"
950 #[derive(Copy, Clone)]
951 pub struct PathStatements;
953 impl LintPass for PathStatements {
954 fn get_lints(&self) -> LintArray {
955 lint_array!(PATH_STATEMENTS)
958 fn check_stmt(&mut self, cx: &Context, s: &ast::Stmt) {
960 ast::StmtSemi(ref expr, _) => {
962 ast::ExprPath(..) => cx.span_lint(PATH_STATEMENTS, s.span,
963 "path statement with no effect"),
975 "unused result of a type flagged as #[must_use]"
981 "unused result of an expression in a statement"
984 #[derive(Copy, Clone)]
985 pub struct UnusedResults;
987 impl LintPass for UnusedResults {
988 fn get_lints(&self) -> LintArray {
989 lint_array!(UNUSED_MUST_USE, UNUSED_RESULTS)
992 fn check_stmt(&mut self, cx: &Context, s: &ast::Stmt) {
993 let expr = match s.node {
994 ast::StmtSemi(ref expr, _) => &**expr,
998 if let ast::ExprRet(..) = expr.node {
1002 let expr = lower_expr(expr);
1003 let t = cx.tcx.expr_ty(&expr);
1004 let warned = match t.sty {
1005 ty::TyTuple(ref tys) if tys.is_empty() => return,
1006 ty::TyBool => return,
1007 ty::TyStruct(def, _) |
1008 ty::TyEnum(def, _) => {
1009 if def.did.is_local() {
1010 if let hir_map::NodeItem(it) = cx.tcx.map.get(def.did.node) {
1011 check_must_use(cx, &it.attrs, s.span)
1016 let attrs = csearch::get_item_attrs(&cx.sess().cstore, def.did);
1017 check_must_use(cx, &attrs[..], s.span)
1023 cx.span_lint(UNUSED_RESULTS, s.span, "unused result");
1026 fn check_must_use(cx: &Context, attrs: &[hir::Attribute], sp: Span) -> bool {
1028 if attr.check_name("must_use") {
1029 let mut msg = "unused result which must be used".to_string();
1030 // check for #[must_use="..."]
1031 match attr.value_str() {
1038 cx.span_lint(UNUSED_MUST_USE, sp, &msg);
1048 pub NON_CAMEL_CASE_TYPES,
1050 "types, variants, traits and type parameters should have camel case names"
1053 #[derive(Copy, Clone)]
1054 pub struct NonCamelCaseTypes;
1056 impl NonCamelCaseTypes {
1057 fn check_case(&self, cx: &Context, sort: &str, ident: ast::Ident, span: Span) {
1058 fn is_camel_case(ident: ast::Ident) -> bool {
1059 let ident = ident.name.as_str();
1060 if ident.is_empty() {
1063 let ident = ident.trim_matches('_');
1065 // start with a non-lowercase letter rather than non-uppercase
1066 // ones (some scripts don't have a concept of upper/lowercase)
1067 !ident.is_empty() && !ident.char_at(0).is_lowercase() && !ident.contains('_')
1070 fn to_camel_case(s: &str) -> String {
1071 s.split('_').flat_map(|word| word.chars().enumerate().map(|(i, c)|
1073 c.to_uppercase().collect::<String>()
1075 c.to_lowercase().collect()
1077 )).collect::<Vec<_>>().concat()
1080 let s = ident.name.as_str();
1082 if !is_camel_case(ident) {
1083 let c = to_camel_case(&s);
1084 let m = if c.is_empty() {
1085 format!("{} `{}` should have a camel case name such as `CamelCase`", sort, s)
1087 format!("{} `{}` should have a camel case name such as `{}`", sort, s, c)
1089 cx.span_lint(NON_CAMEL_CASE_TYPES, span, &m[..]);
1094 impl LintPass for NonCamelCaseTypes {
1095 fn get_lints(&self) -> LintArray {
1096 lint_array!(NON_CAMEL_CASE_TYPES)
1099 fn check_item(&mut self, cx: &Context, it: &ast::Item) {
1100 let extern_repr_count = it.attrs.iter().filter(|attr| {
1101 attr::find_repr_attrs(cx.tcx.sess.diagnostic(), attr).iter()
1102 .any(|r| r == &attr::ReprExtern)
1104 let has_extern_repr = extern_repr_count > 0;
1106 if has_extern_repr {
1111 ast::ItemTy(..) | ast::ItemStruct(..) => {
1112 self.check_case(cx, "type", it.ident, it.span)
1114 ast::ItemTrait(..) => {
1115 self.check_case(cx, "trait", it.ident, it.span)
1117 ast::ItemEnum(ref enum_definition, _) => {
1118 if has_extern_repr {
1121 self.check_case(cx, "type", it.ident, it.span);
1122 for variant in &enum_definition.variants {
1123 self.check_case(cx, "variant", variant.node.name, variant.span);
1130 fn check_generics(&mut self, cx: &Context, it: &ast::Generics) {
1131 for gen in it.ty_params.iter() {
1132 self.check_case(cx, "type parameter", gen.ident, gen.span);
1137 #[derive(PartialEq)]
1138 enum MethodContext {
1144 fn method_context(cx: &Context, id: ast::NodeId, span: Span) -> MethodContext {
1145 match cx.tcx.impl_or_trait_items.borrow().get(&DefId::local(id)) {
1146 None => cx.sess().span_bug(span, "missing method descriptor?!"),
1147 Some(item) => match item.container() {
1148 ty::TraitContainer(..) => MethodContext::TraitDefaultImpl,
1149 ty::ImplContainer(cid) => {
1150 match cx.tcx.impl_trait_ref(cid) {
1151 Some(_) => MethodContext::TraitImpl,
1152 None => MethodContext::PlainImpl
1162 "methods, functions, lifetime parameters and modules should have snake case names"
1165 #[derive(Copy, Clone)]
1166 pub struct NonSnakeCase;
1169 fn to_snake_case(mut str: &str) -> String {
1170 let mut words = vec![];
1171 // Preserve leading underscores
1172 str = str.trim_left_matches(|c: char| {
1174 words.push(String::new());
1180 for s in str.split('_') {
1181 let mut last_upper = false;
1182 let mut buf = String::new();
1186 for ch in s.chars() {
1187 if !buf.is_empty() && buf != "'"
1188 && ch.is_uppercase()
1191 buf = String::new();
1193 last_upper = ch.is_uppercase();
1194 buf.extend(ch.to_lowercase());
1201 fn check_snake_case(&self, cx: &Context, sort: &str, name: &str, span: Option<Span>) {
1202 fn is_snake_case(ident: &str) -> bool {
1203 if ident.is_empty() {
1206 let ident = ident.trim_left_matches('\'');
1207 let ident = ident.trim_matches('_');
1209 let mut allow_underscore = true;
1210 ident.chars().all(|c| {
1211 allow_underscore = match c {
1212 '_' if !allow_underscore => return false,
1214 // It would be more obvious to use `c.is_lowercase()`,
1215 // but some characters do not have a lowercase form
1216 c if !c.is_uppercase() => true,
1223 if !is_snake_case(name) {
1224 let sc = NonSnakeCase::to_snake_case(name);
1225 let msg = if sc != name {
1226 format!("{} `{}` should have a snake case name such as `{}`",
1229 format!("{} `{}` should have a snake case name",
1233 Some(span) => cx.span_lint(NON_SNAKE_CASE, span, &msg),
1234 None => cx.lint(NON_SNAKE_CASE, &msg),
1240 impl LintPass for NonSnakeCase {
1241 fn get_lints(&self) -> LintArray {
1242 lint_array!(NON_SNAKE_CASE)
1245 fn check_crate(&mut self, cx: &Context, cr: &ast::Crate) {
1246 let attr_crate_name = cr.attrs.iter().find(|at| at.check_name("crate_name"))
1247 .and_then(|at| at.value_str().map(|s| (at, s)));
1248 if let Some(ref name) = cx.tcx.sess.opts.crate_name {
1249 self.check_snake_case(cx, "crate", name, None);
1250 } else if let Some((attr, ref name)) = attr_crate_name {
1251 self.check_snake_case(cx, "crate", name, Some(attr.span));
1255 fn check_fn(&mut self, cx: &Context,
1256 fk: FnKind, _: &ast::FnDecl,
1257 _: &ast::Block, span: Span, id: ast::NodeId) {
1259 FnKind::Method(ident, _, _) => match method_context(cx, id, span) {
1260 MethodContext::PlainImpl => {
1261 self.check_snake_case(cx, "method", &ident.name.as_str(), Some(span))
1263 MethodContext::TraitDefaultImpl => {
1264 self.check_snake_case(cx, "trait method", &ident.name.as_str(), Some(span))
1268 FnKind::ItemFn(ident, _, _, _, _, _) => {
1269 self.check_snake_case(cx, "function", &ident.name.as_str(), Some(span))
1275 fn check_item(&mut self, cx: &Context, it: &ast::Item) {
1276 if let ast::ItemMod(_) = it.node {
1277 self.check_snake_case(cx, "module", &it.ident.name.as_str(), Some(it.span));
1281 fn check_trait_item(&mut self, cx: &Context, trait_item: &ast::TraitItem) {
1282 if let ast::MethodTraitItem(_, None) = trait_item.node {
1283 self.check_snake_case(cx, "trait method", &trait_item.ident.name.as_str(),
1284 Some(trait_item.span));
1288 fn check_lifetime_def(&mut self, cx: &Context, t: &ast::LifetimeDef) {
1289 self.check_snake_case(cx, "lifetime", &t.lifetime.name.as_str(),
1290 Some(t.lifetime.span));
1293 fn check_pat(&mut self, cx: &Context, p: &ast::Pat) {
1294 if let &ast::PatIdent(_, ref path1, _) = &p.node {
1295 let def = cx.tcx.def_map.borrow().get(&p.id).map(|d| d.full_def());
1296 if let Some(def::DefLocal(_)) = def {
1297 self.check_snake_case(cx, "variable", &path1.node.name.as_str(), Some(p.span));
1302 fn check_struct_def(&mut self, cx: &Context, s: &ast::StructDef,
1303 _: ast::Ident, _: &ast::Generics, _: ast::NodeId) {
1304 for sf in &s.fields {
1305 if let ast::StructField_ { kind: ast::NamedField(ident, _), .. } = sf.node {
1306 self.check_snake_case(cx, "structure field", &ident.name.as_str(),
1314 pub NON_UPPER_CASE_GLOBALS,
1316 "static constants should have uppercase identifiers"
1319 #[derive(Copy, Clone)]
1320 pub struct NonUpperCaseGlobals;
1322 impl NonUpperCaseGlobals {
1323 fn check_upper_case(cx: &Context, sort: &str, ident: ast::Ident, span: Span) {
1324 let s = ident.name.as_str();
1326 if s.chars().any(|c| c.is_lowercase()) {
1327 let uc = NonSnakeCase::to_snake_case(&s).to_uppercase();
1329 cx.span_lint(NON_UPPER_CASE_GLOBALS, span,
1330 &format!("{} `{}` should have an upper case name such as `{}`",
1333 cx.span_lint(NON_UPPER_CASE_GLOBALS, span,
1334 &format!("{} `{}` should have an upper case name",
1341 impl LintPass for NonUpperCaseGlobals {
1342 fn get_lints(&self) -> LintArray {
1343 lint_array!(NON_UPPER_CASE_GLOBALS)
1346 fn check_item(&mut self, cx: &Context, it: &ast::Item) {
1348 // only check static constants
1349 ast::ItemStatic(_, ast::MutImmutable, _) => {
1350 NonUpperCaseGlobals::check_upper_case(cx, "static constant", it.ident, it.span);
1352 ast::ItemConst(..) => {
1353 NonUpperCaseGlobals::check_upper_case(cx, "constant", it.ident, it.span);
1359 fn check_trait_item(&mut self, cx: &Context, ti: &ast::TraitItem) {
1361 ast::ConstTraitItem(..) => {
1362 NonUpperCaseGlobals::check_upper_case(cx, "associated constant",
1369 fn check_impl_item(&mut self, cx: &Context, ii: &ast::ImplItem) {
1371 ast::ConstImplItem(..) => {
1372 NonUpperCaseGlobals::check_upper_case(cx, "associated constant",
1379 fn check_pat(&mut self, cx: &Context, p: &ast::Pat) {
1380 // Lint for constants that look like binding identifiers (#7526)
1381 match (&p.node, cx.tcx.def_map.borrow().get(&p.id).map(|d| d.full_def())) {
1382 (&ast::PatIdent(_, ref path1, _), Some(def::DefConst(..))) => {
1383 NonUpperCaseGlobals::check_upper_case(cx, "constant in pattern",
1384 path1.node, p.span);
1394 "`if`, `match`, `while` and `return` do not need parentheses"
1397 #[derive(Copy, Clone)]
1398 pub struct UnusedParens;
1401 fn check_unused_parens_core(&self, cx: &Context, value: &ast::Expr, msg: &str,
1402 struct_lit_needs_parens: bool) {
1403 if let ast::ExprParen(ref inner) = value.node {
1404 let necessary = struct_lit_needs_parens && contains_exterior_struct_lit(&**inner);
1406 cx.span_lint(UNUSED_PARENS, value.span,
1407 &format!("unnecessary parentheses around {}", msg))
1411 /// Expressions that syntactically contain an "exterior" struct
1412 /// literal i.e. not surrounded by any parens or other
1413 /// delimiters, e.g. `X { y: 1 }`, `X { y: 1 }.method()`, `foo
1414 /// == X { y: 1 }` and `X { y: 1 } == foo` all do, but `(X {
1415 /// y: 1 }) == foo` does not.
1416 fn contains_exterior_struct_lit(value: &ast::Expr) -> bool {
1418 ast::ExprStruct(..) => true,
1420 ast::ExprAssign(ref lhs, ref rhs) |
1421 ast::ExprAssignOp(_, ref lhs, ref rhs) |
1422 ast::ExprBinary(_, ref lhs, ref rhs) => {
1423 // X { y: 1 } + X { y: 2 }
1424 contains_exterior_struct_lit(&**lhs) ||
1425 contains_exterior_struct_lit(&**rhs)
1427 ast::ExprUnary(_, ref x) |
1428 ast::ExprCast(ref x, _) |
1429 ast::ExprField(ref x, _) |
1430 ast::ExprTupField(ref x, _) |
1431 ast::ExprIndex(ref x, _) => {
1432 // &X { y: 1 }, X { y: 1 }.y
1433 contains_exterior_struct_lit(&**x)
1436 ast::ExprMethodCall(_, _, ref exprs) => {
1437 // X { y: 1 }.bar(...)
1438 contains_exterior_struct_lit(&*exprs[0])
1447 impl LintPass for UnusedParens {
1448 fn get_lints(&self) -> LintArray {
1449 lint_array!(UNUSED_PARENS)
1452 fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
1453 let (value, msg, struct_lit_needs_parens) = match e.node {
1454 ast::ExprIf(ref cond, _, _) => (cond, "`if` condition", true),
1455 ast::ExprWhile(ref cond, _, _) => (cond, "`while` condition", true),
1456 ast::ExprMatch(ref head, _, source) => match source {
1457 ast::MatchSource::Normal => (head, "`match` head expression", true),
1458 ast::MatchSource::IfLetDesugar { .. } => (head, "`if let` head expression", true),
1459 ast::MatchSource::WhileLetDesugar => (head, "`while let` head expression", true),
1460 ast::MatchSource::ForLoopDesugar => (head, "`for` head expression", true),
1462 ast::ExprRet(Some(ref value)) => (value, "`return` value", false),
1463 ast::ExprAssign(_, ref value) => (value, "assigned value", false),
1464 ast::ExprAssignOp(_, _, ref value) => (value, "assigned value", false),
1467 self.check_unused_parens_core(cx, &**value, msg, struct_lit_needs_parens);
1470 fn check_stmt(&mut self, cx: &Context, s: &ast::Stmt) {
1471 let (value, msg) = match s.node {
1472 ast::StmtDecl(ref decl, _) => match decl.node {
1473 ast::DeclLocal(ref local) => match local.init {
1474 Some(ref value) => (value, "assigned value"),
1481 self.check_unused_parens_core(cx, &**value, msg, false);
1486 UNUSED_IMPORT_BRACES,
1488 "unnecessary braces around an imported item"
1491 #[derive(Copy, Clone)]
1492 pub struct UnusedImportBraces;
1494 impl LintPass for UnusedImportBraces {
1495 fn get_lints(&self) -> LintArray {
1496 lint_array!(UNUSED_IMPORT_BRACES)
1499 fn check_item(&mut self, cx: &Context, item: &ast::Item) {
1500 if let ast::ItemUse(ref view_path) = item.node {
1501 if let ast::ViewPathList(_, ref items) = view_path.node {
1502 if items.len() == 1 {
1503 if let ast::PathListIdent {ref name, ..} = items[0].node {
1504 let m = format!("braces around {} is unnecessary",
1506 cx.span_lint(UNUSED_IMPORT_BRACES, item.span,
1516 NON_SHORTHAND_FIELD_PATTERNS,
1518 "using `Struct { x: x }` instead of `Struct { x }`"
1521 #[derive(Copy, Clone)]
1522 pub struct NonShorthandFieldPatterns;
1524 impl LintPass for NonShorthandFieldPatterns {
1525 fn get_lints(&self) -> LintArray {
1526 lint_array!(NON_SHORTHAND_FIELD_PATTERNS)
1529 fn check_pat(&mut self, cx: &Context, pat: &ast::Pat) {
1530 let def_map = cx.tcx.def_map.borrow();
1531 if let ast::PatStruct(_, ref v, _) = pat.node {
1532 let field_pats = v.iter().filter(|fieldpat| {
1533 if fieldpat.node.is_shorthand {
1536 let def = def_map.get(&fieldpat.node.pat.id).map(|d| d.full_def());
1537 def == Some(def::DefLocal(fieldpat.node.pat.id))
1539 for fieldpat in field_pats {
1540 if let ast::PatIdent(_, ident, None) = fieldpat.node.pat.node {
1541 if ident.node.name == fieldpat.node.ident.name {
1542 // FIXME: should this comparison really be done on the name?
1543 // doing it on the ident will fail during compilation of libcore
1544 cx.span_lint(NON_SHORTHAND_FIELD_PATTERNS, fieldpat.span,
1545 &format!("the `{}:` in this pattern is redundant and can \
1546 be removed", ident.node))
1557 "unnecessary use of an `unsafe` block"
1560 #[derive(Copy, Clone)]
1561 pub struct UnusedUnsafe;
1563 impl LintPass for UnusedUnsafe {
1564 fn get_lints(&self) -> LintArray {
1565 lint_array!(UNUSED_UNSAFE)
1568 fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
1569 if let ast::ExprBlock(ref blk) = e.node {
1570 // Don't warn about generated blocks, that'll just pollute the output.
1571 if blk.rules == ast::UnsafeBlock(ast::UserProvided) &&
1572 !cx.tcx.used_unsafe.borrow().contains(&blk.id) {
1573 cx.span_lint(UNUSED_UNSAFE, blk.span, "unnecessary `unsafe` block");
1582 "usage of `unsafe` code"
1585 #[derive(Copy, Clone)]
1586 pub struct UnsafeCode;
1588 impl LintPass for UnsafeCode {
1589 fn get_lints(&self) -> LintArray {
1590 lint_array!(UNSAFE_CODE)
1593 fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
1594 if let ast::ExprBlock(ref blk) = e.node {
1595 // Don't warn about generated blocks, that'll just pollute the output.
1596 if blk.rules == ast::UnsafeBlock(ast::UserProvided) {
1597 cx.span_lint(UNSAFE_CODE, blk.span, "usage of an `unsafe` block");
1602 fn check_item(&mut self, cx: &Context, it: &ast::Item) {
1604 ast::ItemTrait(ast::Unsafety::Unsafe, _, _, _) =>
1605 cx.span_lint(UNSAFE_CODE, it.span, "declaration of an `unsafe` trait"),
1607 ast::ItemImpl(ast::Unsafety::Unsafe, _, _, _, _, _) =>
1608 cx.span_lint(UNSAFE_CODE, it.span, "implementation of an `unsafe` trait"),
1614 fn check_fn(&mut self, cx: &Context, fk: FnKind, _: &ast::FnDecl,
1615 _: &ast::Block, span: Span, _: ast::NodeId) {
1617 FnKind::ItemFn(_, _, ast::Unsafety::Unsafe, _, _, _) =>
1618 cx.span_lint(UNSAFE_CODE, span, "declaration of an `unsafe` function"),
1620 FnKind::Method(_, sig, _) => {
1621 if sig.unsafety == ast::Unsafety::Unsafe {
1622 cx.span_lint(UNSAFE_CODE, span, "implementation of an `unsafe` method")
1630 fn check_trait_item(&mut self, cx: &Context, trait_item: &ast::TraitItem) {
1631 if let ast::MethodTraitItem(ref sig, None) = trait_item.node {
1632 if sig.unsafety == ast::Unsafety::Unsafe {
1633 cx.span_lint(UNSAFE_CODE, trait_item.span,
1634 "declaration of an `unsafe` method")
1643 "detect mut variables which don't need to be mutable"
1646 #[derive(Copy, Clone)]
1647 pub struct UnusedMut;
1650 fn check_unused_mut_pat(&self, cx: &Context, pats: &[P<ast::Pat>]) {
1651 // collect all mutable pattern and group their NodeIDs by their Identifier to
1652 // avoid false warnings in match arms with multiple patterns
1654 let mut mutables = FnvHashMap();
1656 pat_util::pat_bindings(&cx.tcx.def_map, &lower_pat(p), |mode, id, _, path1| {
1657 let ident = path1.node;
1658 if let hir::BindByValue(hir::MutMutable) = mode {
1659 if !ident.name.as_str().starts_with("_") {
1660 match mutables.entry(ident.name.usize()) {
1661 Vacant(entry) => { entry.insert(vec![id]); },
1662 Occupied(mut entry) => { entry.get_mut().push(id); },
1669 let used_mutables = cx.tcx.used_mut_nodes.borrow();
1670 for (_, v) in &mutables {
1671 if !v.iter().any(|e| used_mutables.contains(e)) {
1672 cx.span_lint(UNUSED_MUT, cx.tcx.map.span(v[0]),
1673 "variable does not need to be mutable");
1679 impl LintPass for UnusedMut {
1680 fn get_lints(&self) -> LintArray {
1681 lint_array!(UNUSED_MUT)
1684 fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
1685 if let ast::ExprMatch(_, ref arms, _) = e.node {
1687 self.check_unused_mut_pat(cx, &a.pats)
1692 fn check_stmt(&mut self, cx: &Context, s: &ast::Stmt) {
1693 if let ast::StmtDecl(ref d, _) = s.node {
1694 if let ast::DeclLocal(ref l) = d.node {
1695 self.check_unused_mut_pat(cx, slice::ref_slice(&l.pat));
1700 fn check_fn(&mut self, cx: &Context,
1701 _: FnKind, decl: &ast::FnDecl,
1702 _: &ast::Block, _: Span, _: ast::NodeId) {
1703 for a in &decl.inputs {
1704 self.check_unused_mut_pat(cx, slice::ref_slice(&a.pat));
1712 "detects unnecessary allocations that can be eliminated"
1715 #[derive(Copy, Clone)]
1716 pub struct UnusedAllocation;
1718 impl LintPass for UnusedAllocation {
1719 fn get_lints(&self) -> LintArray {
1720 lint_array!(UNUSED_ALLOCATION)
1723 fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
1725 ast::ExprUnary(ast::UnUniq, _) => (),
1729 if let Some(adjustment) = cx.tcx.tables.borrow().adjustments.get(&e.id) {
1730 if let ty::AdjustDerefRef(ty::AutoDerefRef { ref autoref, .. }) = *adjustment {
1732 &Some(ty::AutoPtr(_, hir::MutImmutable)) => {
1733 cx.span_lint(UNUSED_ALLOCATION, e.span,
1734 "unnecessary allocation, use & instead");
1736 &Some(ty::AutoPtr(_, hir::MutMutable)) => {
1737 cx.span_lint(UNUSED_ALLOCATION, e.span,
1738 "unnecessary allocation, use &mut instead");
1750 "detects missing documentation for public members"
1753 pub struct MissingDoc {
1754 /// Stack of IDs of struct definitions.
1755 struct_def_stack: Vec<ast::NodeId>,
1757 /// True if inside variant definition
1760 /// Stack of whether #[doc(hidden)] is set
1761 /// at each level which has lint attributes.
1762 doc_hidden_stack: Vec<bool>,
1764 /// Private traits or trait items that leaked through. Don't check their methods.
1765 private_traits: HashSet<ast::NodeId>,
1769 pub fn new() -> MissingDoc {
1771 struct_def_stack: vec!(),
1773 doc_hidden_stack: vec!(false),
1774 private_traits: HashSet::new(),
1778 fn doc_hidden(&self) -> bool {
1779 *self.doc_hidden_stack.last().expect("empty doc_hidden_stack")
1782 fn check_missing_docs_attrs(&self,
1784 id: Option<ast::NodeId>,
1785 attrs: &[ast::Attribute],
1787 desc: &'static str) {
1788 // If we're building a test harness, then warning about
1789 // documentation is probably not really relevant right now.
1790 if cx.sess().opts.test {
1794 // `#[doc(hidden)]` disables missing_docs check.
1795 if self.doc_hidden() {
1799 // Only check publicly-visible items, using the result from the privacy pass.
1800 // It's an option so the crate root can also use this function (it doesn't
1802 if let Some(ref id) = id {
1803 if !cx.exported_items.contains(id) {
1808 let has_doc = attrs.iter().any(|a| {
1809 match a.node.value.node {
1810 ast::MetaNameValue(ref name, _) if *name == "doc" => true,
1815 cx.span_lint(MISSING_DOCS, sp,
1816 &format!("missing documentation for {}", desc));
1821 impl LintPass for MissingDoc {
1822 fn get_lints(&self) -> LintArray {
1823 lint_array!(MISSING_DOCS)
1826 fn enter_lint_attrs(&mut self, _: &Context, attrs: &[ast::Attribute]) {
1827 let doc_hidden = self.doc_hidden() || attrs.iter().any(|attr| {
1828 attr.check_name("doc") && match attr.meta_item_list() {
1830 Some(l) => attr::contains_name(&l[..], "hidden"),
1833 self.doc_hidden_stack.push(doc_hidden);
1836 fn exit_lint_attrs(&mut self, _: &Context, _: &[ast::Attribute]) {
1837 self.doc_hidden_stack.pop().expect("empty doc_hidden_stack");
1840 fn check_struct_def(&mut self, _: &Context, _: &ast::StructDef,
1841 _: ast::Ident, _: &ast::Generics, id: ast::NodeId) {
1842 self.struct_def_stack.push(id);
1845 fn check_struct_def_post(&mut self, _: &Context, _: &ast::StructDef,
1846 _: ast::Ident, _: &ast::Generics, id: ast::NodeId) {
1847 let popped = self.struct_def_stack.pop().expect("empty struct_def_stack");
1848 assert!(popped == id);
1851 fn check_crate(&mut self, cx: &Context, krate: &ast::Crate) {
1852 self.check_missing_docs_attrs(cx, None, &krate.attrs, krate.span, "crate");
1855 fn check_item(&mut self, cx: &Context, it: &ast::Item) {
1856 let desc = match it.node {
1857 ast::ItemFn(..) => "a function",
1858 ast::ItemMod(..) => "a module",
1859 ast::ItemEnum(..) => "an enum",
1860 ast::ItemStruct(..) => "a struct",
1861 ast::ItemTrait(_, _, _, ref items) => {
1862 // Issue #11592, traits are always considered exported, even when private.
1863 if it.vis == ast::Visibility::Inherited {
1864 self.private_traits.insert(it.id);
1866 self.private_traits.insert(itm.id);
1872 ast::ItemTy(..) => "a type alias",
1873 ast::ItemImpl(_, _, _, Some(ref trait_ref), _, ref impl_items) => {
1874 // If the trait is private, add the impl items to private_traits so they don't get
1875 // reported for missing docs.
1876 let real_trait = cx.tcx.trait_ref_to_def_id(&lower_trait_ref(trait_ref));
1877 match cx.tcx.map.find(real_trait.node) {
1878 Some(hir_map::NodeItem(item)) => if item.vis == hir::Visibility::Inherited {
1879 for itm in impl_items {
1880 self.private_traits.insert(itm.id);
1887 ast::ItemConst(..) => "a constant",
1888 ast::ItemStatic(..) => "a static",
1892 self.check_missing_docs_attrs(cx, Some(it.id), &it.attrs, it.span, desc);
1895 fn check_trait_item(&mut self, cx: &Context, trait_item: &ast::TraitItem) {
1896 if self.private_traits.contains(&trait_item.id) { return }
1898 let desc = match trait_item.node {
1899 ast::ConstTraitItem(..) => "an associated constant",
1900 ast::MethodTraitItem(..) => "a trait method",
1901 ast::TypeTraitItem(..) => "an associated type",
1904 self.check_missing_docs_attrs(cx, Some(trait_item.id),
1906 trait_item.span, desc);
1909 fn check_impl_item(&mut self, cx: &Context, impl_item: &ast::ImplItem) {
1910 // If the method is an impl for a trait, don't doc.
1911 if method_context(cx, impl_item.id, impl_item.span) == MethodContext::TraitImpl {
1915 let desc = match impl_item.node {
1916 ast::ConstImplItem(..) => "an associated constant",
1917 ast::MethodImplItem(..) => "a method",
1918 ast::TypeImplItem(_) => "an associated type",
1919 ast::MacImplItem(_) => "an impl item macro",
1921 self.check_missing_docs_attrs(cx, Some(impl_item.id),
1923 impl_item.span, desc);
1926 fn check_struct_field(&mut self, cx: &Context, sf: &ast::StructField) {
1927 if let ast::NamedField(_, vis) = sf.node.kind {
1928 if vis == ast::Public || self.in_variant {
1929 let cur_struct_def = *self.struct_def_stack.last()
1930 .expect("empty struct_def_stack");
1931 self.check_missing_docs_attrs(cx, Some(cur_struct_def),
1932 &sf.node.attrs, sf.span,
1938 fn check_variant(&mut self, cx: &Context, v: &ast::Variant, _: &ast::Generics) {
1939 self.check_missing_docs_attrs(cx, Some(v.node.id), &v.node.attrs, v.span, "a variant");
1940 assert!(!self.in_variant);
1941 self.in_variant = true;
1944 fn check_variant_post(&mut self, _: &Context, _: &ast::Variant, _: &ast::Generics) {
1945 assert!(self.in_variant);
1946 self.in_variant = false;
1951 pub MISSING_COPY_IMPLEMENTATIONS,
1953 "detects potentially-forgotten implementations of `Copy`"
1956 #[derive(Copy, Clone)]
1957 pub struct MissingCopyImplementations;
1959 impl LintPass for MissingCopyImplementations {
1960 fn get_lints(&self) -> LintArray {
1961 lint_array!(MISSING_COPY_IMPLEMENTATIONS)
1964 fn check_item(&mut self, cx: &Context, item: &ast::Item) {
1965 if !cx.exported_items.contains(&item.id) {
1968 let (def, ty) = match item.node {
1969 ast::ItemStruct(_, ref ast_generics) => {
1970 if ast_generics.is_parameterized() {
1973 let def = cx.tcx.lookup_adt_def(DefId::local(item.id));
1974 (def, cx.tcx.mk_struct(def,
1975 cx.tcx.mk_substs(Substs::empty())))
1977 ast::ItemEnum(_, ref ast_generics) => {
1978 if ast_generics.is_parameterized() {
1981 let def = cx.tcx.lookup_adt_def(DefId::local(item.id));
1982 (def, cx.tcx.mk_enum(def,
1983 cx.tcx.mk_substs(Substs::empty())))
1987 if def.has_dtor() { return; }
1988 let parameter_environment = cx.tcx.empty_parameter_environment();
1989 // FIXME (@jroesch) should probably inver this so that the parameter env still impls this
1991 if !ty.moves_by_default(¶meter_environment, item.span) {
1994 if parameter_environment.can_type_implement_copy(ty, item.span).is_ok() {
1995 cx.span_lint(MISSING_COPY_IMPLEMENTATIONS,
1997 "type could implement `Copy`; consider adding `impl \
2004 MISSING_DEBUG_IMPLEMENTATIONS,
2006 "detects missing implementations of fmt::Debug"
2009 pub struct MissingDebugImplementations {
2010 impling_types: Option<NodeSet>,
2013 impl MissingDebugImplementations {
2014 pub fn new() -> MissingDebugImplementations {
2015 MissingDebugImplementations {
2016 impling_types: None,
2021 impl LintPass for MissingDebugImplementations {
2022 fn get_lints(&self) -> LintArray {
2023 lint_array!(MISSING_DEBUG_IMPLEMENTATIONS)
2026 fn check_item(&mut self, cx: &Context, item: &ast::Item) {
2027 if !cx.exported_items.contains(&item.id) {
2032 ast::ItemStruct(..) | ast::ItemEnum(..) => {},
2036 let debug = match cx.tcx.lang_items.debug_trait() {
2037 Some(debug) => debug,
2041 if self.impling_types.is_none() {
2042 let debug_def = cx.tcx.lookup_trait_def(debug);
2043 let mut impls = NodeSet();
2044 debug_def.for_each_impl(cx.tcx, |d| {
2046 if let Some(ty_def) = cx.tcx.node_id_to_type(d.node).ty_to_def_id() {
2047 impls.insert(ty_def.node);
2052 self.impling_types = Some(impls);
2053 debug!("{:?}", self.impling_types);
2056 if !self.impling_types.as_ref().unwrap().contains(&item.id) {
2057 cx.span_lint(MISSING_DEBUG_IMPLEMENTATIONS,
2059 "type does not implement `fmt::Debug`; consider adding #[derive(Debug)] \
2060 or a manual implementation")
2068 "detects use of #[deprecated] items"
2071 /// Checks for use of items with `#[deprecated]` attributes
2072 #[derive(Copy, Clone)]
2073 pub struct Stability;
2076 fn lint(&self, cx: &Context, _id: DefId,
2077 span: Span, stability: &Option<&attr::Stability>) {
2078 // Deprecated attributes apply in-crate and cross-crate.
2079 let (lint, label) = match *stability {
2080 Some(&attr::Stability { deprecated_since: Some(_), .. }) =>
2081 (DEPRECATED, "deprecated"),
2085 output(cx, span, stability, lint, label);
2087 fn output(cx: &Context, span: Span, stability: &Option<&attr::Stability>,
2088 lint: &'static Lint, label: &'static str) {
2089 let msg = match *stability {
2090 Some(&attr::Stability { reason: Some(ref s), .. }) => {
2091 format!("use of {} item: {}", label, *s)
2093 _ => format!("use of {} item", label)
2096 cx.span_lint(lint, span, &msg[..]);
2101 fn hir_to_ast_stability(stab: &front_attr::Stability) -> attr::Stability {
2103 level: match stab.level {
2104 front_attr::Unstable => attr::Unstable,
2105 front_attr::Stable => attr::Stable,
2107 feature: stab.feature.clone(),
2108 since: stab.since.clone(),
2109 deprecated_since: stab.deprecated_since.clone(),
2110 reason: stab.reason.clone(),
2115 impl LintPass for Stability {
2116 fn get_lints(&self) -> LintArray {
2117 lint_array!(DEPRECATED)
2120 fn check_item(&mut self, cx: &Context, item: &ast::Item) {
2121 stability::check_item(cx.tcx, &lower_item(item), false,
2123 self.lint(cx, id, sp,
2124 &stab.map(|s| hir_to_ast_stability(s)).as_ref()));
2127 fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
2128 stability::check_expr(cx.tcx, &lower_expr(e),
2130 self.lint(cx, id, sp,
2131 &stab.map(|s| hir_to_ast_stability(s)).as_ref()));
2134 fn check_path(&mut self, cx: &Context, path: &ast::Path, id: ast::NodeId) {
2135 stability::check_path(cx.tcx, &lower_path(path), id,
2137 self.lint(cx, id, sp,
2138 &stab.map(|s| hir_to_ast_stability(s)).as_ref()));
2141 fn check_pat(&mut self, cx: &Context, pat: &ast::Pat) {
2142 stability::check_pat(cx.tcx, &lower_pat(pat),
2144 self.lint(cx, id, sp,
2145 &stab.map(|s| hir_to_ast_stability(s)).as_ref()));
2150 pub UNCONDITIONAL_RECURSION,
2152 "functions that cannot return without calling themselves"
2155 #[derive(Copy, Clone)]
2156 pub struct UnconditionalRecursion;
2159 impl LintPass for UnconditionalRecursion {
2160 fn get_lints(&self) -> LintArray {
2161 lint_array![UNCONDITIONAL_RECURSION]
2164 fn check_fn(&mut self, cx: &Context, fn_kind: FnKind, _: &ast::FnDecl,
2165 blk: &ast::Block, sp: Span, id: ast::NodeId) {
2166 type F = for<'tcx> fn(&ty::ctxt<'tcx>,
2167 ast::NodeId, ast::NodeId, ast::Ident, ast::NodeId) -> bool;
2169 let method = match fn_kind {
2170 FnKind::ItemFn(..) => None,
2171 FnKind::Method(..) => {
2172 cx.tcx.impl_or_trait_item(DefId::local(id)).as_opt_method()
2174 // closures can't recur, so they don't matter.
2175 FnKind::Closure => return
2178 // Walk through this function (say `f`) looking to see if
2179 // every possible path references itself, i.e. the function is
2180 // called recursively unconditionally. This is done by trying
2181 // to find a path from the entry node to the exit node that
2182 // *doesn't* call `f` by traversing from the entry while
2183 // pretending that calls of `f` are sinks (i.e. ignoring any
2184 // exit edges from them).
2186 // NB. this has an edge case with non-returning statements,
2187 // like `loop {}` or `panic!()`: control flow never reaches
2188 // the exit node through these, so one can have a function
2189 // that never actually calls itselfs but is still picked up by
2192 // fn f(cond: bool) {
2193 // if !cond { panic!() } // could come from `assert!(cond)`
2197 // In general, functions of that form may be able to call
2198 // itself a finite number of times and then diverge. The lint
2199 // considers this to be an error for two reasons, (a) it is
2200 // easier to implement, and (b) it seems rare to actually want
2201 // to have behaviour like the above, rather than
2202 // e.g. accidentally recurring after an assert.
2204 let cfg = cfg::CFG::new(cx.tcx, &lower_block(blk));
2206 let mut work_queue = vec![cfg.entry];
2207 let mut reached_exit_without_self_call = false;
2208 let mut self_call_spans = vec![];
2209 let mut visited = HashSet::new();
2211 while let Some(idx) = work_queue.pop() {
2212 if idx == cfg.exit {
2214 reached_exit_without_self_call = true;
2218 let cfg_id = idx.node_id();
2219 if visited.contains(&cfg_id) {
2223 visited.insert(cfg_id);
2225 let node_id = cfg.graph.node_data(idx).id();
2227 // is this a recursive call?
2228 let self_recursive = if node_id != ast::DUMMY_NODE_ID {
2230 Some(ref method) => {
2231 expr_refers_to_this_method(cx.tcx, method, node_id)
2233 None => expr_refers_to_this_fn(cx.tcx, id, node_id)
2239 self_call_spans.push(cx.tcx.map.span(node_id));
2240 // this is a self call, so we shouldn't explore past
2241 // this node in the CFG.
2244 // add the successors of this node to explore the graph further.
2245 for (_, edge) in cfg.graph.outgoing_edges(idx) {
2246 let target_idx = edge.target();
2247 let target_cfg_id = target_idx.node_id();
2248 if !visited.contains(&target_cfg_id) {
2249 work_queue.push(target_idx)
2254 // Check the number of self calls because a function that
2255 // doesn't return (e.g. calls a `-> !` function or `loop { /*
2256 // no break */ }`) shouldn't be linted unless it actually
2258 if !reached_exit_without_self_call && !self_call_spans.is_empty() {
2259 cx.span_lint(UNCONDITIONAL_RECURSION, sp,
2260 "function cannot return without recurring");
2262 // FIXME #19668: these could be span_lint_note's instead of this manual guard.
2263 if cx.current_level(UNCONDITIONAL_RECURSION) != Level::Allow {
2264 let sess = cx.sess();
2265 // offer some help to the programmer.
2266 for call in &self_call_spans {
2267 sess.span_note(*call, "recursive call site")
2269 sess.fileline_help(sp, "a `loop` may express intention \
2270 better if this is on purpose")
2277 // Functions for identifying if the given Expr NodeId `id`
2278 // represents a call to the function `fn_id`/method `method`.
2280 fn expr_refers_to_this_fn(tcx: &ty::ctxt,
2282 id: ast::NodeId) -> bool {
2283 match tcx.map.get(id) {
2284 hir_map::NodeExpr(&hir::Expr { node: hir::ExprCall(ref callee, _), .. }) => {
2285 tcx.def_map.borrow().get(&callee.id)
2286 .map_or(false, |def| def.def_id() == DefId::local(fn_id))
2292 // Check if the expression `id` performs a call to `method`.
2293 fn expr_refers_to_this_method(tcx: &ty::ctxt,
2294 method: &ty::Method,
2295 id: ast::NodeId) -> bool {
2296 let tables = tcx.tables.borrow();
2298 // Check for method calls and overloaded operators.
2299 if let Some(m) = tables.method_map.get(&ty::MethodCall::expr(id)) {
2300 if method_call_refers_to_method(tcx, method, m.def_id, m.substs, id) {
2305 // Check for overloaded autoderef method calls.
2306 if let Some(&ty::AdjustDerefRef(ref adj)) = tables.adjustments.get(&id) {
2307 for i in 0..adj.autoderefs {
2308 let method_call = ty::MethodCall::autoderef(id, i as u32);
2309 if let Some(m) = tables.method_map.get(&method_call) {
2310 if method_call_refers_to_method(tcx, method, m.def_id, m.substs, id) {
2317 // Check for calls to methods via explicit paths (e.g. `T::method()`).
2318 match tcx.map.get(id) {
2319 hir_map::NodeExpr(&hir::Expr { node: hir::ExprCall(ref callee, _), .. }) => {
2320 match tcx.def_map.borrow().get(&callee.id).map(|d| d.full_def()) {
2321 Some(def::DefMethod(def_id)) => {
2322 let no_substs = &ty::ItemSubsts::empty();
2323 let ts = tables.item_substs.get(&callee.id).unwrap_or(no_substs);
2324 method_call_refers_to_method(tcx, method, def_id, &ts.substs, id)
2333 // Check if the method call to the method with the ID `callee_id`
2334 // and instantiated with `callee_substs` refers to method `method`.
2335 fn method_call_refers_to_method<'tcx>(tcx: &ty::ctxt<'tcx>,
2336 method: &ty::Method,
2338 callee_substs: &Substs<'tcx>,
2339 expr_id: ast::NodeId) -> bool {
2340 let callee_item = tcx.impl_or_trait_item(callee_id);
2342 match callee_item.container() {
2343 // This is an inherent method, so the `def_id` refers
2344 // directly to the method definition.
2345 ty::ImplContainer(_) => {
2346 callee_id == method.def_id
2349 // A trait method, from any number of possible sources.
2350 // Attempt to select a concrete impl before checking.
2351 ty::TraitContainer(trait_def_id) => {
2352 let trait_substs = callee_substs.clone().method_to_trait();
2353 let trait_substs = tcx.mk_substs(trait_substs);
2354 let trait_ref = ty::TraitRef::new(trait_def_id, trait_substs);
2355 let trait_ref = ty::Binder(trait_ref);
2356 let span = tcx.map.span(expr_id);
2358 traits::Obligation::new(traits::ObligationCause::misc(span, expr_id),
2359 trait_ref.to_poly_trait_predicate());
2361 let param_env = ty::ParameterEnvironment::for_item(tcx, method.def_id.node);
2362 let infcx = infer::new_infer_ctxt(tcx, &tcx.tables, Some(param_env), false);
2363 let mut selcx = traits::SelectionContext::new(&infcx);
2364 match selcx.select(&obligation) {
2365 // The method comes from a `T: Trait` bound.
2366 // If `T` is `Self`, then this call is inside
2367 // a default method definition.
2368 Ok(Some(traits::VtableParam(_))) => {
2369 let self_ty = callee_substs.self_ty();
2370 let on_self = self_ty.map_or(false, |t| t.is_self());
2371 // We can only be recurring in a default
2372 // method if we're being called literally
2373 // on the `Self` type.
2374 on_self && callee_id == method.def_id
2377 // The `impl` is known, so we check that with a
2379 Ok(Some(traits::VtableImpl(vtable_impl))) => {
2380 let container = ty::ImplContainer(vtable_impl.impl_def_id);
2381 // It matches if it comes from the same impl,
2382 // and has the same method name.
2383 container == method.container
2384 && callee_item.name() == method.name
2387 // There's no way to know if this call is
2388 // recursive, so we assume it's not.
2400 "compiler plugin used as ordinary library in non-plugin crate"
2403 #[derive(Copy, Clone)]
2404 pub struct PluginAsLibrary;
2406 impl LintPass for PluginAsLibrary {
2407 fn get_lints(&self) -> LintArray {
2408 lint_array![PLUGIN_AS_LIBRARY]
2411 fn check_item(&mut self, cx: &Context, it: &ast::Item) {
2412 if cx.sess().plugin_registrar_fn.get().is_some() {
2413 // We're compiling a plugin; it's fine to link other plugins.
2418 ast::ItemExternCrate(..) => (),
2422 let md = match cx.sess().cstore.find_extern_mod_stmt_cnum(it.id) {
2423 Some(cnum) => cx.sess().cstore.get_crate_data(cnum),
2425 // Probably means we aren't linking the crate for some reason.
2427 // Not sure if / when this could happen.
2432 if decoder::get_plugin_registrar_fn(md.data()).is_some() {
2433 cx.span_lint(PLUGIN_AS_LIBRARY, it.span,
2434 "compiler plugin used as an ordinary library");
2440 PRIVATE_NO_MANGLE_FNS,
2442 "functions marked #[no_mangle] should be exported"
2446 PRIVATE_NO_MANGLE_STATICS,
2448 "statics marked #[no_mangle] should be exported"
2452 NO_MANGLE_CONST_ITEMS,
2454 "const items will not have their symbols exported"
2457 #[derive(Copy, Clone)]
2458 pub struct InvalidNoMangleItems;
2460 impl LintPass for InvalidNoMangleItems {
2461 fn get_lints(&self) -> LintArray {
2462 lint_array!(PRIVATE_NO_MANGLE_FNS,
2463 PRIVATE_NO_MANGLE_STATICS,
2464 NO_MANGLE_CONST_ITEMS)
2467 fn check_item(&mut self, cx: &Context, it: &ast::Item) {
2469 ast::ItemFn(..) => {
2470 if attr::contains_name(&it.attrs, "no_mangle") &&
2471 !cx.exported_items.contains(&it.id) {
2472 let msg = format!("function {} is marked #[no_mangle], but not exported",
2474 cx.span_lint(PRIVATE_NO_MANGLE_FNS, it.span, &msg);
2477 ast::ItemStatic(..) => {
2478 if attr::contains_name(&it.attrs, "no_mangle") &&
2479 !cx.exported_items.contains(&it.id) {
2480 let msg = format!("static {} is marked #[no_mangle], but not exported",
2482 cx.span_lint(PRIVATE_NO_MANGLE_STATICS, it.span, &msg);
2485 ast::ItemConst(..) => {
2486 if attr::contains_name(&it.attrs, "no_mangle") {
2487 // Const items do not refer to a particular location in memory, and therefore
2488 // don't have anything to attach a symbol to
2489 let msg = "const items should never be #[no_mangle], consider instead using \
2491 cx.span_lint(NO_MANGLE_CONST_ITEMS, it.span, msg);
2499 #[derive(Clone, Copy)]
2500 pub struct MutableTransmutes;
2505 "mutating transmuted &mut T from &T may cause undefined behavior"
2508 impl LintPass for MutableTransmutes {
2509 fn get_lints(&self) -> LintArray {
2510 lint_array!(MUTABLE_TRANSMUTES)
2513 fn check_expr(&mut self, cx: &Context, expr: &ast::Expr) {
2514 use syntax::abi::RustIntrinsic;
2516 let msg = "mutating transmuted &mut T from &T may cause undefined behavior,\
2517 consider instead using an UnsafeCell";
2518 match get_transmute_from_to(cx, expr) {
2519 Some((&ty::TyRef(_, from_mt), &ty::TyRef(_, to_mt))) => {
2520 if to_mt.mutbl == hir::Mutability::MutMutable
2521 && from_mt.mutbl == hir::Mutability::MutImmutable {
2522 cx.span_lint(MUTABLE_TRANSMUTES, expr.span, msg);
2528 fn get_transmute_from_to<'a, 'tcx>(cx: &Context<'a, 'tcx>, expr: &ast::Expr)
2529 -> Option<(&'tcx ty::TypeVariants<'tcx>, &'tcx ty::TypeVariants<'tcx>)> {
2531 ast::ExprPath(..) => (),
2534 if let def::DefFn(did, _) = cx.tcx.resolve_expr(&lower_expr(expr)) {
2535 if !def_id_is_transmute(cx, did) {
2538 let typ = cx.tcx.node_id_to_type(expr.id);
2540 ty::TyBareFn(_, ref bare_fn) if bare_fn.abi == RustIntrinsic => {
2541 if let ty::FnConverging(to) = bare_fn.sig.0.output {
2542 let from = bare_fn.sig.0.inputs[0];
2543 return Some((&from.sty, &to.sty));
2552 fn def_id_is_transmute(cx: &Context, def_id: DefId) -> bool {
2553 match cx.tcx.lookup_item_type(def_id).ty.sty {
2554 ty::TyBareFn(_, ref bfty) if bfty.abi == RustIntrinsic => (),
2557 cx.tcx.with_path(def_id, |path| match path.last() {
2558 Some(ref last) => last.name().as_str() == "transmute",
2565 /// Forbids using the `#[feature(...)]` attribute
2566 #[derive(Copy, Clone)]
2567 pub struct UnstableFeatures;
2572 "enabling unstable features (deprecated. do not use)"
2575 impl LintPass for UnstableFeatures {
2576 fn get_lints(&self) -> LintArray {
2577 lint_array!(UNSTABLE_FEATURES)
2579 fn check_attribute(&mut self, ctx: &Context, attr: &ast::Attribute) {
2580 if attr::contains_name(&[attr.node.value.clone()], "feature") {
2581 if let Some(items) = attr.node.value.meta_item_list() {
2583 ctx.span_lint(UNSTABLE_FEATURES, item.span, "unstable feature");
2590 /// Lints for attempts to impl Drop on types that have `#[repr(C)]`
2591 /// attribute (see issue #24585).
2592 #[derive(Copy, Clone)]
2593 pub struct DropWithReprExtern;
2596 DROP_WITH_REPR_EXTERN,
2598 "use of #[repr(C)] on a type that implements Drop"
2601 impl LintPass for DropWithReprExtern {
2602 fn get_lints(&self) -> LintArray {
2603 lint_array!(DROP_WITH_REPR_EXTERN)
2605 fn check_crate(&mut self, ctx: &Context, _: &ast::Crate) {
2606 for dtor_did in ctx.tcx.destructors.borrow().iter() {
2607 let (drop_impl_did, dtor_self_type) =
2608 if dtor_did.is_local() {
2609 let impl_did = ctx.tcx.map.get_parent_did(dtor_did.node);
2610 let ty = ctx.tcx.lookup_item_type(impl_did).ty;
2616 match dtor_self_type.sty {
2617 ty::TyEnum(self_type_def, _) |
2618 ty::TyStruct(self_type_def, _) => {
2619 let self_type_did = self_type_def.did;
2620 let hints = ctx.tcx.lookup_repr_hints(self_type_did);
2621 if hints.iter().any(|attr| *attr == front_attr::ReprExtern) &&
2622 self_type_def.dtor_kind().has_drop_flag() {
2623 let drop_impl_span = ctx.tcx.map.def_id_span(drop_impl_did,
2625 let self_defn_span = ctx.tcx.map.def_id_span(self_type_did,
2627 ctx.span_lint(DROP_WITH_REPR_EXTERN,
2629 "implementing Drop adds hidden state to types, \
2630 possibly conflicting with `#[repr(C)]`");
2631 // FIXME #19668: could be span_lint_note instead of manual guard.
2632 if ctx.current_level(DROP_WITH_REPR_EXTERN) != Level::Allow {
2633 ctx.sess().span_note(self_defn_span,
2634 "the `#[repr(C)]` attribute is attached here");