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;
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, Visitor};
56 // hardwired lints from librustc
57 pub use lint::builtin::*;
62 "suggest using `loop { }` instead of `while true { }`"
65 #[derive(Copy, Clone)]
68 impl LintPass for WhileTrue {
69 fn get_lints(&self) -> LintArray {
70 lint_array!(WHILE_TRUE)
73 fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
74 if let ast::ExprWhile(ref cond, _, _) = e.node {
75 if let ast::ExprLit(ref lit) = cond.node {
76 if let ast::LitBool(true) = lit.node {
77 cx.span_lint(WHILE_TRUE, e.span,
78 "denote infinite loops with loop { ... }");
88 "comparisons made useless by limits of the types involved"
94 "literal out of range for its type"
100 "shift exceeds the type's number of bits"
103 #[derive(Copy, Clone)]
104 pub struct TypeLimits {
105 /// Id of the last visited negated expression
106 negated_expr_id: ast::NodeId,
110 pub fn new() -> TypeLimits {
117 impl LintPass for TypeLimits {
118 fn get_lints(&self) -> LintArray {
119 lint_array!(UNUSED_COMPARISONS, OVERFLOWING_LITERALS, EXCEEDING_BITSHIFTS)
122 fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
124 ast::ExprUnary(ast::UnNeg, ref expr) => {
126 ast::ExprLit(ref lit) => {
128 ast::LitInt(_, ast::UnsignedIntLit(_)) => {
129 check_unsigned_negation_feature(cx, e.span);
131 ast::LitInt(_, ast::UnsuffixedIntLit(_)) => {
132 if let ty::TyUint(_) = cx.tcx.expr_ty(e).sty {
133 check_unsigned_negation_feature(cx, e.span);
140 let t = cx.tcx.expr_ty(&**expr);
143 check_unsigned_negation_feature(cx, e.span);
149 // propagate negation, if the negation itself isn't negated
150 if self.negated_expr_id != e.id {
151 self.negated_expr_id = expr.id;
154 ast::ExprParen(ref expr) if self.negated_expr_id == e.id => {
155 self.negated_expr_id = expr.id;
157 ast::ExprBinary(binop, ref l, ref r) => {
158 if is_comparison(binop) && !check_limits(cx.tcx, binop, &**l, &**r) {
159 cx.span_lint(UNUSED_COMPARISONS, e.span,
160 "comparison is useless due to type limits");
163 if is_shift_binop(binop.node) {
164 let opt_ty_bits = match cx.tcx.expr_ty(&**l).sty {
165 ty::TyInt(t) => Some(int_ty_bits(t, cx.sess().target.int_type)),
166 ty::TyUint(t) => Some(uint_ty_bits(t, cx.sess().target.uint_type)),
170 if let Some(bits) = opt_ty_bits {
171 let exceeding = if let ast::ExprLit(ref lit) = r.node {
172 if let ast::LitInt(shift, _) = lit.node { shift >= bits }
175 match eval_const_expr_partial(cx.tcx, &**r, ExprTypeChecked) {
176 Ok(ConstVal::Int(shift)) => { shift as u64 >= bits },
177 Ok(ConstVal::Uint(shift)) => { shift >= bits },
182 cx.span_lint(EXCEEDING_BITSHIFTS, e.span,
183 "bitshift exceeds the type's number of bits");
188 ast::ExprLit(ref lit) => {
189 match cx.tcx.expr_ty(e).sty {
192 ast::LitInt(v, ast::SignedIntLit(_, ast::Plus)) |
193 ast::LitInt(v, ast::UnsuffixedIntLit(ast::Plus)) => {
194 let int_type = if let ast::TyIs = t {
195 cx.sess().target.int_type
199 let (_, max) = int_ty_range(int_type);
200 let negative = self.negated_expr_id == e.id;
202 // Detect literal value out of range [min, max] inclusive
203 // avoiding use of -min to prevent overflow/panic
204 if (negative && v > max as u64 + 1) ||
205 (!negative && v > max as u64) {
206 cx.span_lint(OVERFLOWING_LITERALS, e.span,
207 &*format!("literal out of range for {:?}", t));
215 let uint_type = if let ast::TyUs = t {
216 cx.sess().target.uint_type
220 let (min, max) = uint_ty_range(uint_type);
221 let lit_val: u64 = match lit.node {
222 ast::LitByte(_v) => return, // _v is u8, within range by definition
223 ast::LitInt(v, _) => v,
226 if lit_val < min || lit_val > max {
227 cx.span_lint(OVERFLOWING_LITERALS, e.span,
228 &*format!("literal out of range for {:?}", t));
232 let (min, max) = float_ty_range(t);
233 let lit_val: f64 = match lit.node {
234 ast::LitFloat(ref v, _) |
235 ast::LitFloatUnsuffixed(ref v) => {
243 if lit_val < min || lit_val > max {
244 cx.span_lint(OVERFLOWING_LITERALS, e.span,
245 &*format!("literal out of range for {:?}", t));
254 fn is_valid<T:cmp::PartialOrd>(binop: ast::BinOp, v: T,
255 min: T, max: T) -> bool {
257 ast::BiLt => v > min && v <= max,
258 ast::BiLe => v >= min && v < max,
259 ast::BiGt => v >= min && v < max,
260 ast::BiGe => v > min && v <= max,
261 ast::BiEq | ast::BiNe => v >= min && v <= max,
266 fn rev_binop(binop: ast::BinOp) -> ast::BinOp {
267 codemap::respan(binop.span, match binop.node {
268 ast::BiLt => ast::BiGt,
269 ast::BiLe => ast::BiGe,
270 ast::BiGt => ast::BiLt,
271 ast::BiGe => ast::BiLe,
276 // for isize & usize, be conservative with the warnings, so that the
277 // warnings are consistent between 32- and 64-bit platforms
278 fn int_ty_range(int_ty: ast::IntTy) -> (i64, i64) {
280 ast::TyIs => (i64::MIN, i64::MAX),
281 ast::TyI8 => (i8::MIN as i64, i8::MAX as i64),
282 ast::TyI16 => (i16::MIN as i64, i16::MAX as i64),
283 ast::TyI32 => (i32::MIN as i64, i32::MAX as i64),
284 ast::TyI64 => (i64::MIN, i64::MAX)
288 fn uint_ty_range(uint_ty: ast::UintTy) -> (u64, u64) {
290 ast::TyUs => (u64::MIN, u64::MAX),
291 ast::TyU8 => (u8::MIN as u64, u8::MAX as u64),
292 ast::TyU16 => (u16::MIN as u64, u16::MAX as u64),
293 ast::TyU32 => (u32::MIN as u64, u32::MAX as u64),
294 ast::TyU64 => (u64::MIN, u64::MAX)
298 fn float_ty_range(float_ty: ast::FloatTy) -> (f64, f64) {
300 ast::TyF32 => (f32::MIN as f64, f32::MAX as f64),
301 ast::TyF64 => (f64::MIN, f64::MAX)
305 fn int_ty_bits(int_ty: ast::IntTy, target_int_ty: ast::IntTy) -> u64 {
307 ast::TyIs => int_ty_bits(target_int_ty, target_int_ty),
308 ast::TyI8 => i8::BITS as u64,
309 ast::TyI16 => i16::BITS as u64,
310 ast::TyI32 => i32::BITS as u64,
311 ast::TyI64 => i64::BITS as u64
315 fn uint_ty_bits(uint_ty: ast::UintTy, target_uint_ty: ast::UintTy) -> u64 {
317 ast::TyUs => uint_ty_bits(target_uint_ty, target_uint_ty),
318 ast::TyU8 => u8::BITS as u64,
319 ast::TyU16 => u16::BITS as u64,
320 ast::TyU32 => u32::BITS as u64,
321 ast::TyU64 => u64::BITS as u64
325 fn check_limits(tcx: &ty::ctxt, binop: ast::BinOp,
326 l: &ast::Expr, r: &ast::Expr) -> bool {
327 let (lit, expr, swap) = match (&l.node, &r.node) {
328 (&ast::ExprLit(_), _) => (l, r, true),
329 (_, &ast::ExprLit(_)) => (r, l, false),
332 // Normalize the binop so that the literal is always on the RHS in
334 let norm_binop = if swap {
339 match tcx.expr_ty(expr).sty {
340 ty::TyInt(int_ty) => {
341 let (min, max) = int_ty_range(int_ty);
342 let lit_val: i64 = match lit.node {
343 ast::ExprLit(ref li) => match li.node {
344 ast::LitInt(v, ast::SignedIntLit(_, ast::Plus)) |
345 ast::LitInt(v, ast::UnsuffixedIntLit(ast::Plus)) => v as i64,
346 ast::LitInt(v, ast::SignedIntLit(_, ast::Minus)) |
347 ast::LitInt(v, ast::UnsuffixedIntLit(ast::Minus)) => -(v as i64),
352 is_valid(norm_binop, lit_val, min, max)
354 ty::TyUint(uint_ty) => {
355 let (min, max): (u64, u64) = uint_ty_range(uint_ty);
356 let lit_val: u64 = match lit.node {
357 ast::ExprLit(ref li) => match li.node {
358 ast::LitInt(v, _) => v,
363 is_valid(norm_binop, lit_val, min, max)
369 fn is_comparison(binop: ast::BinOp) -> bool {
371 ast::BiEq | ast::BiLt | ast::BiLe |
372 ast::BiNe | ast::BiGe | ast::BiGt => true,
377 fn check_unsigned_negation_feature(cx: &Context, span: Span) {
378 if !cx.sess().features.borrow().negate_unsigned {
379 // FIXME(#27141): change this to syntax::feature_gate::emit_feature_err…
380 cx.sess().span_warn(span,
381 "unary negation of unsigned integers will be feature gated in the future");
382 // …and remove following two expressions.
383 if option_env!("CFG_DISABLE_UNSTABLE_FEATURES").is_some() { return; }
384 cx.sess().fileline_help(span, "add #![feature(negate_unsigned)] to the \
385 crate attributes to enable the gate in advance");
394 "proper use of libc types in foreign modules"
397 struct ImproperCTypesVisitor<'a, 'tcx: 'a> {
398 cx: &'a Context<'a, 'tcx>
403 FfiUnsafe(&'static str),
404 FfiBadStruct(DefId, &'static str),
405 FfiBadEnum(DefId, &'static str)
408 /// Check if this enum can be safely exported based on the
409 /// "nullable pointer optimization". Currently restricted
410 /// to function pointers and references, but could be
411 /// expanded to cover NonZero raw pointers and newtypes.
412 /// FIXME: This duplicates code in trans.
413 fn is_repr_nullable_ptr<'tcx>(tcx: &ty::ctxt<'tcx>,
414 def: ty::AdtDef<'tcx>,
415 substs: &Substs<'tcx>)
417 if def.variants.len() == 2 {
420 if def.variants[0].fields.is_empty() {
422 } else if def.variants[1].fields.is_empty() {
428 if def.variants[data_idx].fields.len() == 1 {
429 match def.variants[data_idx].fields[0].ty(tcx, substs).sty {
430 ty::TyBareFn(None, _) => { return true; }
431 ty::TyRef(..) => { return true; }
439 fn ast_ty_to_normalized<'tcx>(tcx: &ty::ctxt<'tcx>,
442 let tty = match tcx.ast_ty_to_ty_cache.borrow().get(&id) {
444 None => panic!("ast_ty_to_ty_cache was incomplete after typeck!")
446 infer::normalize_associated_type(tcx, &tty)
449 impl<'a, 'tcx> ImproperCTypesVisitor<'a, 'tcx> {
450 /// Check if the given type is "ffi-safe" (has a stable, well-defined
451 /// representation which can be exported to C code).
452 fn check_type_for_ffi(&self,
453 cache: &mut FnvHashSet<Ty<'tcx>>,
456 use self::FfiResult::*;
457 let cx = &self.cx.tcx;
459 // Protect against infinite recursion, for example
460 // `struct S(*mut S);`.
461 // FIXME: A recursion limit is necessary as well, for irregular
463 if !cache.insert(ty) {
468 ty::TyStruct(def, substs) => {
469 if !cx.lookup_repr_hints(def.did).contains(&attr::ReprExtern) {
471 "found struct without foreign-function-safe \
472 representation annotation in foreign module, \
473 consider adding a #[repr(C)] attribute to \
477 // We can't completely trust repr(C) markings; make sure the
478 // fields are actually safe.
479 if def.struct_variant().fields.is_empty() {
481 "found zero-size struct in foreign module, consider \
482 adding a member to this struct");
485 for field in &def.struct_variant().fields {
486 let field_ty = infer::normalize_associated_type(cx, &field.ty(cx, substs));
487 let r = self.check_type_for_ffi(cache, field_ty);
490 FfiBadStruct(..) | FfiBadEnum(..) => { return r; }
491 FfiUnsafe(s) => { return FfiBadStruct(def.did, s); }
496 ty::TyEnum(def, substs) => {
497 if def.variants.is_empty() {
498 // Empty enums are okay... although sort of useless.
502 // Check for a repr() attribute to specify the size of the
504 let repr_hints = cx.lookup_repr_hints(def.did);
505 match &**repr_hints {
507 // Special-case types like `Option<extern fn()>`.
508 if !is_repr_nullable_ptr(cx, def, substs) {
510 "found enum without foreign-function-safe \
511 representation annotation in foreign module, \
512 consider adding a #[repr(...)] attribute to \
517 if !hint.is_ffi_safe() {
518 // FIXME: This shouldn't be reachable: we should check
521 "enum has unexpected #[repr(...)] attribute")
524 // Enum with an explicitly sized discriminant; either
525 // a C-style enum or a discriminated union.
527 // The layout of enum variants is implicitly repr(C).
528 // FIXME: Is that correct?
531 // FIXME: This shouldn't be reachable: we should check
534 "enum has too many #[repr(...)] attributes");
538 // Check the contained variants.
539 for variant in &def.variants {
540 for field in &variant.fields {
541 let arg = infer::normalize_associated_type(cx, &field.ty(cx, substs));
542 let r = self.check_type_for_ffi(cache, arg);
545 FfiBadStruct(..) | FfiBadEnum(..) => { return r; }
546 FfiUnsafe(s) => { return FfiBadEnum(def.did, s); }
553 ty::TyInt(ast::TyIs) => {
554 FfiUnsafe("found Rust type `isize` in foreign module, while \
555 `libc::c_int` or `libc::c_long` should be used")
557 ty::TyUint(ast::TyUs) => {
558 FfiUnsafe("found Rust type `usize` in foreign module, while \
559 `libc::c_uint` or `libc::c_ulong` should be used")
562 FfiUnsafe("found Rust type `char` in foreign module, while \
563 `u32` or `libc::wchar_t` should be used")
566 // Primitive types with a stable representation.
567 ty::TyBool | ty::TyInt(..) | ty::TyUint(..) |
568 ty::TyFloat(..) => FfiSafe,
571 FfiUnsafe("found Rust type Box<_> in foreign module, \
572 consider using a raw pointer instead")
576 FfiUnsafe("found Rust slice type in foreign module, \
577 consider using a raw pointer instead")
581 FfiUnsafe("found Rust trait type in foreign module, \
582 consider using a raw pointer instead")
586 FfiUnsafe("found Rust type `str` in foreign module; \
587 consider using a `*const libc::c_char`")
591 FfiUnsafe("found Rust tuple type in foreign module; \
592 consider using a struct instead`")
595 ty::TyRawPtr(ref m) | ty::TyRef(_, ref m) => {
596 self.check_type_for_ffi(cache, m.ty)
599 ty::TyArray(ty, _) => {
600 self.check_type_for_ffi(cache, ty)
603 ty::TyBareFn(None, bare_fn) => {
607 abi::PlatformIntrinsic |
610 "found function pointer with Rust calling \
611 convention in foreign module; consider using an \
612 `extern` function pointer")
617 let sig = cx.erase_late_bound_regions(&bare_fn.sig);
619 ty::FnDiverging => {}
620 ty::FnConverging(output) => {
621 if !output.is_nil() {
622 let r = self.check_type_for_ffi(cache, output);
630 for arg in sig.inputs {
631 let r = self.check_type_for_ffi(cache, arg);
640 ty::TyParam(..) | ty::TyInfer(..) | ty::TyError |
641 ty::TyClosure(..) | ty::TyProjection(..) |
642 ty::TyBareFn(Some(_), _) => {
643 panic!("Unexpected type in foreign function")
648 fn check_def(&mut self, sp: Span, id: ast::NodeId) {
649 let tty = ast_ty_to_normalized(self.cx.tcx, id);
651 match ImproperCTypesVisitor::check_type_for_ffi(self, &mut FnvHashSet(), tty) {
652 FfiResult::FfiSafe => {}
653 FfiResult::FfiUnsafe(s) => {
654 self.cx.span_lint(IMPROPER_CTYPES, sp, s);
656 FfiResult::FfiBadStruct(_, s) => {
657 // FIXME: This diagnostic is difficult to read, and doesn't
658 // point at the relevant field.
659 self.cx.span_lint(IMPROPER_CTYPES, sp,
660 &format!("found non-foreign-function-safe member in \
661 struct marked #[repr(C)]: {}", s));
663 FfiResult::FfiBadEnum(_, s) => {
664 // FIXME: This diagnostic is difficult to read, and doesn't
665 // point at the relevant variant.
666 self.cx.span_lint(IMPROPER_CTYPES, sp,
667 &format!("found non-foreign-function-safe member in \
674 impl<'a, 'tcx, 'v> Visitor<'v> for ImproperCTypesVisitor<'a, 'tcx> {
675 fn visit_ty(&mut self, ty: &ast::Ty) {
678 ast::TyBareFn(..) => self.check_def(ty.span, ty.id),
680 self.cx.span_lint(IMPROPER_CTYPES, ty.span,
681 "found Rust slice type in foreign module, consider \
682 using a raw pointer instead");
684 ast::TyFixedLengthVec(ref ty, _) => self.visit_ty(ty),
686 self.cx.span_lint(IMPROPER_CTYPES, ty.span,
687 "found Rust tuple type in foreign module; \
688 consider using a struct instead`")
690 _ => visit::walk_ty(self, ty)
695 #[derive(Copy, Clone)]
696 pub struct ImproperCTypes;
698 impl LintPass for ImproperCTypes {
699 fn get_lints(&self) -> LintArray {
700 lint_array!(IMPROPER_CTYPES)
703 fn check_item(&mut self, cx: &Context, it: &ast::Item) {
704 fn check_ty(cx: &Context, ty: &ast::Ty) {
705 let mut vis = ImproperCTypesVisitor { cx: cx };
709 fn check_foreign_fn(cx: &Context, decl: &ast::FnDecl) {
710 for input in &decl.inputs {
711 check_ty(cx, &*input.ty);
713 if let ast::Return(ref ret_ty) = decl.output {
714 let tty = ast_ty_to_normalized(cx.tcx, ret_ty.id);
716 check_ty(cx, &ret_ty);
722 ast::ItemForeignMod(ref nmod)
723 if nmod.abi != abi::RustIntrinsic &&
724 nmod.abi != abi::PlatformIntrinsic => {
725 for ni in &nmod.items {
727 ast::ForeignItemFn(ref decl, _) => check_foreign_fn(cx, &**decl),
728 ast::ForeignItemStatic(ref t, _) => check_ty(cx, &**t)
740 "use of owned (Box type) heap memory"
743 #[derive(Copy, Clone)]
744 pub struct BoxPointers;
747 fn check_heap_type<'a, 'tcx>(&self, cx: &Context<'a, 'tcx>,
748 span: Span, ty: Ty<'tcx>) {
749 for leaf_ty in ty.walk() {
750 if let ty::TyBox(_) = leaf_ty.sty {
751 let m = format!("type uses owned (Box type) pointers: {}", ty);
752 cx.span_lint(BOX_POINTERS, span, &m);
758 impl LintPass for BoxPointers {
759 fn get_lints(&self) -> LintArray {
760 lint_array!(BOX_POINTERS)
763 fn check_item(&mut self, cx: &Context, it: &ast::Item) {
768 ast::ItemStruct(..) =>
769 self.check_heap_type(cx, it.span,
770 cx.tcx.node_id_to_type(it.id)),
774 // If it's a struct, we also have to check the fields' types
776 ast::ItemStruct(ref struct_def, _) => {
777 for struct_field in &struct_def.fields {
778 self.check_heap_type(cx, struct_field.span,
779 cx.tcx.node_id_to_type(struct_field.node.id));
786 fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
787 let ty = cx.tcx.expr_ty(e);
788 self.check_heap_type(cx, e.span, ty);
795 "uses of #[derive] with raw pointers are rarely correct"
798 struct RawPtrDeriveVisitor<'a, 'tcx: 'a> {
799 cx: &'a Context<'a, 'tcx>
802 impl<'a, 'tcx, 'v> Visitor<'v> for RawPtrDeriveVisitor<'a, 'tcx> {
803 fn visit_ty(&mut self, ty: &ast::Ty) {
804 const MSG: &'static str = "use of `#[derive]` with a raw pointer";
805 if let ast::TyPtr(..) = ty.node {
806 self.cx.span_lint(RAW_POINTER_DERIVE, ty.span, MSG);
808 visit::walk_ty(self, ty);
810 // explicit override to a no-op to reduce code bloat
811 fn visit_expr(&mut self, _: &ast::Expr) {}
812 fn visit_block(&mut self, _: &ast::Block) {}
815 pub struct RawPointerDerive {
816 checked_raw_pointers: NodeSet,
819 impl RawPointerDerive {
820 pub fn new() -> RawPointerDerive {
822 checked_raw_pointers: NodeSet(),
827 impl LintPass for RawPointerDerive {
828 fn get_lints(&self) -> LintArray {
829 lint_array!(RAW_POINTER_DERIVE)
832 fn check_item(&mut self, cx: &Context, item: &ast::Item) {
833 if !attr::contains_name(&item.attrs, "automatically_derived") {
836 let did = match item.node {
837 ast::ItemImpl(_, _, _, ref t_ref_opt, _, _) => {
838 // Deriving the Copy trait does not cause a warning
839 if let &Some(ref trait_ref) = t_ref_opt {
840 let def_id = cx.tcx.trait_ref_to_def_id(trait_ref);
841 if Some(def_id) == cx.tcx.lang_items.copy_trait() {
846 match cx.tcx.node_id_to_type(item.id).sty {
847 ty::TyEnum(def, _) => def.did,
848 ty::TyStruct(def, _) => def.did,
857 let item = match cx.tcx.map.find(did.node) {
858 Some(ast_map::NodeItem(item)) => item,
861 if !self.checked_raw_pointers.insert(item.id) {
865 ast::ItemStruct(..) | ast::ItemEnum(..) => {
866 let mut visitor = RawPtrDeriveVisitor { cx: cx };
867 visit::walk_item(&mut visitor, &*item);
877 "detects attributes that were not used by the compiler"
880 #[derive(Copy, Clone)]
881 pub struct UnusedAttributes;
883 impl LintPass for UnusedAttributes {
884 fn get_lints(&self) -> LintArray {
885 lint_array!(UNUSED_ATTRIBUTES)
888 fn check_attribute(&mut self, cx: &Context, attr: &ast::Attribute) {
889 // Note that check_name() marks the attribute as used if it matches.
890 for &(ref name, ty) in KNOWN_ATTRIBUTES {
892 AttributeType::Whitelisted
893 | AttributeType::Gated(_, _) if attr.check_name(name) => {
900 let plugin_attributes = cx.sess().plugin_attributes.borrow_mut();
901 for &(ref name, ty) in plugin_attributes.iter() {
902 if ty == AttributeType::Whitelisted && attr.check_name(&*name) {
907 if !attr::is_used(attr) {
908 cx.span_lint(UNUSED_ATTRIBUTES, attr.span, "unused attribute");
909 // Is it a builtin attribute that must be used at the crate level?
910 let known_crate = KNOWN_ATTRIBUTES.contains(&(&attr.name(),
911 AttributeType::CrateLevel));
912 // Has a plugin registered this attribute as one which must be used at
914 let plugin_crate = plugin_attributes.iter()
915 .find(|&&(ref x, t)| {
916 &*attr.name() == &*x &&
917 AttributeType::CrateLevel == t
919 if known_crate || plugin_crate {
920 let msg = match attr.node.style {
921 ast::AttrOuter => "crate-level attribute should be an inner \
922 attribute: add an exclamation mark: #![foo]",
923 ast::AttrInner => "crate-level attribute should be in the \
926 cx.span_lint(UNUSED_ATTRIBUTES, attr.span, msg);
935 "path statements with no effect"
938 #[derive(Copy, Clone)]
939 pub struct PathStatements;
941 impl LintPass for PathStatements {
942 fn get_lints(&self) -> LintArray {
943 lint_array!(PATH_STATEMENTS)
946 fn check_stmt(&mut self, cx: &Context, s: &ast::Stmt) {
948 ast::StmtSemi(ref expr, _) => {
950 ast::ExprPath(..) => cx.span_lint(PATH_STATEMENTS, s.span,
951 "path statement with no effect"),
963 "unused result of a type flagged as #[must_use]"
969 "unused result of an expression in a statement"
972 #[derive(Copy, Clone)]
973 pub struct UnusedResults;
975 impl LintPass for UnusedResults {
976 fn get_lints(&self) -> LintArray {
977 lint_array!(UNUSED_MUST_USE, UNUSED_RESULTS)
980 fn check_stmt(&mut self, cx: &Context, s: &ast::Stmt) {
981 let expr = match s.node {
982 ast::StmtSemi(ref expr, _) => &**expr,
986 if let ast::ExprRet(..) = expr.node {
990 let t = cx.tcx.expr_ty(expr);
991 let warned = match t.sty {
992 ty::TyTuple(ref tys) if tys.is_empty() => return,
993 ty::TyBool => return,
994 ty::TyStruct(def, _) |
995 ty::TyEnum(def, _) => {
996 if def.did.is_local() {
997 if let ast_map::NodeItem(it) = cx.tcx.map.get(def.did.node) {
998 check_must_use(cx, &it.attrs, s.span)
1003 let attrs = csearch::get_item_attrs(&cx.sess().cstore, def.did);
1004 check_must_use(cx, &attrs[..], s.span)
1010 cx.span_lint(UNUSED_RESULTS, s.span, "unused result");
1013 fn check_must_use(cx: &Context, attrs: &[ast::Attribute], sp: Span) -> bool {
1015 if attr.check_name("must_use") {
1016 let mut msg = "unused result which must be used".to_string();
1017 // check for #[must_use="..."]
1018 match attr.value_str() {
1025 cx.span_lint(UNUSED_MUST_USE, sp, &msg);
1035 pub NON_CAMEL_CASE_TYPES,
1037 "types, variants, traits and type parameters should have camel case names"
1040 #[derive(Copy, Clone)]
1041 pub struct NonCamelCaseTypes;
1043 impl NonCamelCaseTypes {
1044 fn check_case(&self, cx: &Context, sort: &str, ident: ast::Ident, span: Span) {
1045 fn is_camel_case(ident: ast::Ident) -> bool {
1046 let ident = ident.name.as_str();
1047 if ident.is_empty() {
1050 let ident = ident.trim_matches('_');
1052 // start with a non-lowercase letter rather than non-uppercase
1053 // ones (some scripts don't have a concept of upper/lowercase)
1054 !ident.is_empty() && !ident.char_at(0).is_lowercase() && !ident.contains('_')
1057 fn to_camel_case(s: &str) -> String {
1058 s.split('_').flat_map(|word| word.chars().enumerate().map(|(i, c)|
1060 c.to_uppercase().collect::<String>()
1062 c.to_lowercase().collect()
1064 )).collect::<Vec<_>>().concat()
1067 let s = ident.name.as_str();
1069 if !is_camel_case(ident) {
1070 let c = to_camel_case(&s);
1071 let m = if c.is_empty() {
1072 format!("{} `{}` should have a camel case name such as `CamelCase`", sort, s)
1074 format!("{} `{}` should have a camel case name such as `{}`", sort, s, c)
1076 cx.span_lint(NON_CAMEL_CASE_TYPES, span, &m[..]);
1081 impl LintPass for NonCamelCaseTypes {
1082 fn get_lints(&self) -> LintArray {
1083 lint_array!(NON_CAMEL_CASE_TYPES)
1086 fn check_item(&mut self, cx: &Context, it: &ast::Item) {
1087 let extern_repr_count = it.attrs.iter().filter(|attr| {
1088 attr::find_repr_attrs(cx.tcx.sess.diagnostic(), attr).iter()
1089 .any(|r| r == &attr::ReprExtern)
1091 let has_extern_repr = extern_repr_count > 0;
1093 if has_extern_repr {
1098 ast::ItemTy(..) | ast::ItemStruct(..) => {
1099 self.check_case(cx, "type", it.ident, it.span)
1101 ast::ItemTrait(..) => {
1102 self.check_case(cx, "trait", it.ident, it.span)
1104 ast::ItemEnum(ref enum_definition, _) => {
1105 if has_extern_repr {
1108 self.check_case(cx, "type", it.ident, it.span);
1109 for variant in &enum_definition.variants {
1110 self.check_case(cx, "variant", variant.node.name, variant.span);
1117 fn check_generics(&mut self, cx: &Context, it: &ast::Generics) {
1118 for gen in it.ty_params.iter() {
1119 self.check_case(cx, "type parameter", gen.ident, gen.span);
1124 #[derive(PartialEq)]
1125 enum MethodContext {
1131 fn method_context(cx: &Context, id: ast::NodeId, span: Span) -> MethodContext {
1132 match cx.tcx.impl_or_trait_items.borrow().get(&DefId::local(id)) {
1133 None => cx.sess().span_bug(span, "missing method descriptor?!"),
1134 Some(item) => match item.container() {
1135 ty::TraitContainer(..) => MethodContext::TraitDefaultImpl,
1136 ty::ImplContainer(cid) => {
1137 match cx.tcx.impl_trait_ref(cid) {
1138 Some(_) => MethodContext::TraitImpl,
1139 None => MethodContext::PlainImpl
1149 "methods, functions, lifetime parameters and modules should have snake case names"
1152 #[derive(Copy, Clone)]
1153 pub struct NonSnakeCase;
1156 fn to_snake_case(mut str: &str) -> String {
1157 let mut words = vec![];
1158 // Preserve leading underscores
1159 str = str.trim_left_matches(|c: char| {
1161 words.push(String::new());
1167 for s in str.split('_') {
1168 let mut last_upper = false;
1169 let mut buf = String::new();
1173 for ch in s.chars() {
1174 if !buf.is_empty() && buf != "'"
1175 && ch.is_uppercase()
1178 buf = String::new();
1180 last_upper = ch.is_uppercase();
1181 buf.extend(ch.to_lowercase());
1188 fn check_snake_case(&self, cx: &Context, sort: &str, name: &str, span: Option<Span>) {
1189 fn is_snake_case(ident: &str) -> bool {
1190 if ident.is_empty() {
1193 let ident = ident.trim_left_matches('\'');
1194 let ident = ident.trim_matches('_');
1196 let mut allow_underscore = true;
1197 ident.chars().all(|c| {
1198 allow_underscore = match c {
1199 '_' if !allow_underscore => return false,
1201 // It would be more obvious to use `c.is_lowercase()`,
1202 // but some characters do not have a lowercase form
1203 c if !c.is_uppercase() => true,
1210 if !is_snake_case(name) {
1211 let sc = NonSnakeCase::to_snake_case(name);
1212 let msg = if sc != name {
1213 format!("{} `{}` should have a snake case name such as `{}`",
1216 format!("{} `{}` should have a snake case name",
1220 Some(span) => cx.span_lint(NON_SNAKE_CASE, span, &msg),
1221 None => cx.lint(NON_SNAKE_CASE, &msg),
1227 impl LintPass for NonSnakeCase {
1228 fn get_lints(&self) -> LintArray {
1229 lint_array!(NON_SNAKE_CASE)
1232 fn check_crate(&mut self, cx: &Context, cr: &ast::Crate) {
1233 let attr_crate_name = cr.attrs.iter().find(|at| at.check_name("crate_name"))
1234 .and_then(|at| at.value_str().map(|s| (at, s)));
1235 if let Some(ref name) = cx.tcx.sess.opts.crate_name {
1236 self.check_snake_case(cx, "crate", name, None);
1237 } else if let Some((attr, ref name)) = attr_crate_name {
1238 self.check_snake_case(cx, "crate", name, Some(attr.span));
1242 fn check_fn(&mut self, cx: &Context,
1243 fk: visit::FnKind, _: &ast::FnDecl,
1244 _: &ast::Block, span: Span, id: ast::NodeId) {
1246 visit::FkMethod(ident, _, _) => match method_context(cx, id, span) {
1247 MethodContext::PlainImpl => {
1248 self.check_snake_case(cx, "method", &ident.name.as_str(), Some(span))
1250 MethodContext::TraitDefaultImpl => {
1251 self.check_snake_case(cx, "trait method", &ident.name.as_str(), Some(span))
1255 visit::FkItemFn(ident, _, _, _, _, _) => {
1256 self.check_snake_case(cx, "function", &ident.name.as_str(), Some(span))
1262 fn check_item(&mut self, cx: &Context, it: &ast::Item) {
1263 if let ast::ItemMod(_) = it.node {
1264 self.check_snake_case(cx, "module", &it.ident.name.as_str(), Some(it.span));
1268 fn check_trait_item(&mut self, cx: &Context, trait_item: &ast::TraitItem) {
1269 if let ast::MethodTraitItem(_, None) = trait_item.node {
1270 self.check_snake_case(cx, "trait method", &trait_item.ident.name.as_str(),
1271 Some(trait_item.span));
1275 fn check_lifetime_def(&mut self, cx: &Context, t: &ast::LifetimeDef) {
1276 self.check_snake_case(cx, "lifetime", &t.lifetime.name.as_str(),
1277 Some(t.lifetime.span));
1280 fn check_pat(&mut self, cx: &Context, p: &ast::Pat) {
1281 if let &ast::PatIdent(_, ref path1, _) = &p.node {
1282 let def = cx.tcx.def_map.borrow().get(&p.id).map(|d| d.full_def());
1283 if let Some(def::DefLocal(_)) = def {
1284 self.check_snake_case(cx, "variable", &path1.node.name.as_str(), Some(p.span));
1289 fn check_struct_def(&mut self, cx: &Context, s: &ast::StructDef,
1290 _: ast::Ident, _: &ast::Generics, _: ast::NodeId) {
1291 for sf in &s.fields {
1292 if let ast::StructField_ { kind: ast::NamedField(ident, _), .. } = sf.node {
1293 self.check_snake_case(cx, "structure field", &ident.name.as_str(),
1301 pub NON_UPPER_CASE_GLOBALS,
1303 "static constants should have uppercase identifiers"
1306 #[derive(Copy, Clone)]
1307 pub struct NonUpperCaseGlobals;
1309 impl NonUpperCaseGlobals {
1310 fn check_upper_case(cx: &Context, sort: &str, ident: ast::Ident, span: Span) {
1311 let s = ident.name.as_str();
1313 if s.chars().any(|c| c.is_lowercase()) {
1314 let uc = NonSnakeCase::to_snake_case(&s).to_uppercase();
1316 cx.span_lint(NON_UPPER_CASE_GLOBALS, span,
1317 &format!("{} `{}` should have an upper case name such as `{}`",
1320 cx.span_lint(NON_UPPER_CASE_GLOBALS, span,
1321 &format!("{} `{}` should have an upper case name",
1328 impl LintPass for NonUpperCaseGlobals {
1329 fn get_lints(&self) -> LintArray {
1330 lint_array!(NON_UPPER_CASE_GLOBALS)
1333 fn check_item(&mut self, cx: &Context, it: &ast::Item) {
1335 // only check static constants
1336 ast::ItemStatic(_, ast::MutImmutable, _) => {
1337 NonUpperCaseGlobals::check_upper_case(cx, "static constant", it.ident, it.span);
1339 ast::ItemConst(..) => {
1340 NonUpperCaseGlobals::check_upper_case(cx, "constant", it.ident, it.span);
1346 fn check_trait_item(&mut self, cx: &Context, ti: &ast::TraitItem) {
1348 ast::ConstTraitItem(..) => {
1349 NonUpperCaseGlobals::check_upper_case(cx, "associated constant",
1356 fn check_impl_item(&mut self, cx: &Context, ii: &ast::ImplItem) {
1358 ast::ConstImplItem(..) => {
1359 NonUpperCaseGlobals::check_upper_case(cx, "associated constant",
1366 fn check_pat(&mut self, cx: &Context, p: &ast::Pat) {
1367 // Lint for constants that look like binding identifiers (#7526)
1368 match (&p.node, cx.tcx.def_map.borrow().get(&p.id).map(|d| d.full_def())) {
1369 (&ast::PatIdent(_, ref path1, _), Some(def::DefConst(..))) => {
1370 NonUpperCaseGlobals::check_upper_case(cx, "constant in pattern",
1371 path1.node, p.span);
1381 "`if`, `match`, `while` and `return` do not need parentheses"
1384 #[derive(Copy, Clone)]
1385 pub struct UnusedParens;
1388 fn check_unused_parens_core(&self, cx: &Context, value: &ast::Expr, msg: &str,
1389 struct_lit_needs_parens: bool) {
1390 if let ast::ExprParen(ref inner) = value.node {
1391 let necessary = struct_lit_needs_parens && contains_exterior_struct_lit(&**inner);
1393 cx.span_lint(UNUSED_PARENS, value.span,
1394 &format!("unnecessary parentheses around {}", msg))
1398 /// Expressions that syntactically contain an "exterior" struct
1399 /// literal i.e. not surrounded by any parens or other
1400 /// delimiters, e.g. `X { y: 1 }`, `X { y: 1 }.method()`, `foo
1401 /// == X { y: 1 }` and `X { y: 1 } == foo` all do, but `(X {
1402 /// y: 1 }) == foo` does not.
1403 fn contains_exterior_struct_lit(value: &ast::Expr) -> bool {
1405 ast::ExprStruct(..) => true,
1407 ast::ExprAssign(ref lhs, ref rhs) |
1408 ast::ExprAssignOp(_, ref lhs, ref rhs) |
1409 ast::ExprBinary(_, ref lhs, ref rhs) => {
1410 // X { y: 1 } + X { y: 2 }
1411 contains_exterior_struct_lit(&**lhs) ||
1412 contains_exterior_struct_lit(&**rhs)
1414 ast::ExprUnary(_, ref x) |
1415 ast::ExprCast(ref x, _) |
1416 ast::ExprField(ref x, _) |
1417 ast::ExprTupField(ref x, _) |
1418 ast::ExprIndex(ref x, _) => {
1419 // &X { y: 1 }, X { y: 1 }.y
1420 contains_exterior_struct_lit(&**x)
1423 ast::ExprMethodCall(_, _, ref exprs) => {
1424 // X { y: 1 }.bar(...)
1425 contains_exterior_struct_lit(&*exprs[0])
1434 impl LintPass for UnusedParens {
1435 fn get_lints(&self) -> LintArray {
1436 lint_array!(UNUSED_PARENS)
1439 fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
1440 let (value, msg, struct_lit_needs_parens) = match e.node {
1441 ast::ExprIf(ref cond, _, _) => (cond, "`if` condition", true),
1442 ast::ExprWhile(ref cond, _, _) => (cond, "`while` condition", true),
1443 ast::ExprMatch(ref head, _, source) => match source {
1444 ast::MatchSource::Normal => (head, "`match` head expression", true),
1445 ast::MatchSource::IfLetDesugar { .. } => (head, "`if let` head expression", true),
1446 ast::MatchSource::WhileLetDesugar => (head, "`while let` head expression", true),
1447 ast::MatchSource::ForLoopDesugar => (head, "`for` head expression", true),
1449 ast::ExprRet(Some(ref value)) => (value, "`return` value", false),
1450 ast::ExprAssign(_, ref value) => (value, "assigned value", false),
1451 ast::ExprAssignOp(_, _, ref value) => (value, "assigned value", false),
1454 self.check_unused_parens_core(cx, &**value, msg, struct_lit_needs_parens);
1457 fn check_stmt(&mut self, cx: &Context, s: &ast::Stmt) {
1458 let (value, msg) = match s.node {
1459 ast::StmtDecl(ref decl, _) => match decl.node {
1460 ast::DeclLocal(ref local) => match local.init {
1461 Some(ref value) => (value, "assigned value"),
1468 self.check_unused_parens_core(cx, &**value, msg, false);
1473 UNUSED_IMPORT_BRACES,
1475 "unnecessary braces around an imported item"
1478 #[derive(Copy, Clone)]
1479 pub struct UnusedImportBraces;
1481 impl LintPass for UnusedImportBraces {
1482 fn get_lints(&self) -> LintArray {
1483 lint_array!(UNUSED_IMPORT_BRACES)
1486 fn check_item(&mut self, cx: &Context, item: &ast::Item) {
1487 if let ast::ItemUse(ref view_path) = item.node {
1488 if let ast::ViewPathList(_, ref items) = view_path.node {
1489 if items.len() == 1 {
1490 if let ast::PathListIdent {ref name, ..} = items[0].node {
1491 let m = format!("braces around {} is unnecessary",
1493 cx.span_lint(UNUSED_IMPORT_BRACES, item.span,
1503 NON_SHORTHAND_FIELD_PATTERNS,
1505 "using `Struct { x: x }` instead of `Struct { x }`"
1508 #[derive(Copy, Clone)]
1509 pub struct NonShorthandFieldPatterns;
1511 impl LintPass for NonShorthandFieldPatterns {
1512 fn get_lints(&self) -> LintArray {
1513 lint_array!(NON_SHORTHAND_FIELD_PATTERNS)
1516 fn check_pat(&mut self, cx: &Context, pat: &ast::Pat) {
1517 let def_map = cx.tcx.def_map.borrow();
1518 if let ast::PatStruct(_, ref v, _) = pat.node {
1519 let field_pats = v.iter().filter(|fieldpat| {
1520 if fieldpat.node.is_shorthand {
1523 let def = def_map.get(&fieldpat.node.pat.id).map(|d| d.full_def());
1524 def == Some(def::DefLocal(fieldpat.node.pat.id))
1526 for fieldpat in field_pats {
1527 if let ast::PatIdent(_, ident, None) = fieldpat.node.pat.node {
1528 if ident.node.name == fieldpat.node.ident.name {
1529 // FIXME: should this comparison really be done on the name?
1530 // doing it on the ident will fail during compilation of libcore
1531 cx.span_lint(NON_SHORTHAND_FIELD_PATTERNS, fieldpat.span,
1532 &format!("the `{}:` in this pattern is redundant and can \
1533 be removed", ident.node))
1544 "unnecessary use of an `unsafe` block"
1547 #[derive(Copy, Clone)]
1548 pub struct UnusedUnsafe;
1550 impl LintPass for UnusedUnsafe {
1551 fn get_lints(&self) -> LintArray {
1552 lint_array!(UNUSED_UNSAFE)
1555 fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
1556 if let ast::ExprBlock(ref blk) = e.node {
1557 // Don't warn about generated blocks, that'll just pollute the output.
1558 if blk.rules == ast::UnsafeBlock(ast::UserProvided) &&
1559 !cx.tcx.used_unsafe.borrow().contains(&blk.id) {
1560 cx.span_lint(UNUSED_UNSAFE, blk.span, "unnecessary `unsafe` block");
1569 "usage of `unsafe` code"
1572 #[derive(Copy, Clone)]
1573 pub struct UnsafeCode;
1575 impl LintPass for UnsafeCode {
1576 fn get_lints(&self) -> LintArray {
1577 lint_array!(UNSAFE_CODE)
1580 fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
1581 if let ast::ExprBlock(ref blk) = e.node {
1582 // Don't warn about generated blocks, that'll just pollute the output.
1583 if blk.rules == ast::UnsafeBlock(ast::UserProvided) {
1584 cx.span_lint(UNSAFE_CODE, blk.span, "usage of an `unsafe` block");
1589 fn check_item(&mut self, cx: &Context, it: &ast::Item) {
1591 ast::ItemTrait(ast::Unsafety::Unsafe, _, _, _) =>
1592 cx.span_lint(UNSAFE_CODE, it.span, "declaration of an `unsafe` trait"),
1594 ast::ItemImpl(ast::Unsafety::Unsafe, _, _, _, _, _) =>
1595 cx.span_lint(UNSAFE_CODE, it.span, "implementation of an `unsafe` trait"),
1601 fn check_fn(&mut self, cx: &Context, fk: visit::FnKind, _: &ast::FnDecl,
1602 _: &ast::Block, span: Span, _: ast::NodeId) {
1604 visit::FkItemFn(_, _, ast::Unsafety::Unsafe, _, _, _) =>
1605 cx.span_lint(UNSAFE_CODE, span, "declaration of an `unsafe` function"),
1607 visit::FkMethod(_, sig, _) => {
1608 if sig.unsafety == ast::Unsafety::Unsafe {
1609 cx.span_lint(UNSAFE_CODE, span, "implementation of an `unsafe` method")
1617 fn check_trait_item(&mut self, cx: &Context, trait_item: &ast::TraitItem) {
1618 if let ast::MethodTraitItem(ref sig, None) = trait_item.node {
1619 if sig.unsafety == ast::Unsafety::Unsafe {
1620 cx.span_lint(UNSAFE_CODE, trait_item.span,
1621 "declaration of an `unsafe` method")
1630 "detect mut variables which don't need to be mutable"
1633 #[derive(Copy, Clone)]
1634 pub struct UnusedMut;
1637 fn check_unused_mut_pat(&self, cx: &Context, pats: &[P<ast::Pat>]) {
1638 // collect all mutable pattern and group their NodeIDs by their Identifier to
1639 // avoid false warnings in match arms with multiple patterns
1641 let mut mutables = FnvHashMap();
1643 pat_util::pat_bindings(&cx.tcx.def_map, &**p, |mode, id, _, path1| {
1644 let ident = path1.node;
1645 if let ast::BindByValue(ast::MutMutable) = mode {
1646 if !ident.name.as_str().starts_with("_") {
1647 match mutables.entry(ident.name.usize()) {
1648 Vacant(entry) => { entry.insert(vec![id]); },
1649 Occupied(mut entry) => { entry.get_mut().push(id); },
1656 let used_mutables = cx.tcx.used_mut_nodes.borrow();
1657 for (_, v) in &mutables {
1658 if !v.iter().any(|e| used_mutables.contains(e)) {
1659 cx.span_lint(UNUSED_MUT, cx.tcx.map.span(v[0]),
1660 "variable does not need to be mutable");
1666 impl LintPass for UnusedMut {
1667 fn get_lints(&self) -> LintArray {
1668 lint_array!(UNUSED_MUT)
1671 fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
1672 if let ast::ExprMatch(_, ref arms, _) = e.node {
1674 self.check_unused_mut_pat(cx, &a.pats)
1679 fn check_stmt(&mut self, cx: &Context, s: &ast::Stmt) {
1680 if let ast::StmtDecl(ref d, _) = s.node {
1681 if let ast::DeclLocal(ref l) = d.node {
1682 self.check_unused_mut_pat(cx, slice::ref_slice(&l.pat));
1687 fn check_fn(&mut self, cx: &Context,
1688 _: visit::FnKind, decl: &ast::FnDecl,
1689 _: &ast::Block, _: Span, _: ast::NodeId) {
1690 for a in &decl.inputs {
1691 self.check_unused_mut_pat(cx, slice::ref_slice(&a.pat));
1699 "detects unnecessary allocations that can be eliminated"
1702 #[derive(Copy, Clone)]
1703 pub struct UnusedAllocation;
1705 impl LintPass for UnusedAllocation {
1706 fn get_lints(&self) -> LintArray {
1707 lint_array!(UNUSED_ALLOCATION)
1710 fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
1712 ast::ExprUnary(ast::UnUniq, _) => (),
1716 if let Some(adjustment) = cx.tcx.tables.borrow().adjustments.get(&e.id) {
1717 if let ty::AdjustDerefRef(ty::AutoDerefRef { ref autoref, .. }) = *adjustment {
1719 &Some(ty::AutoPtr(_, ast::MutImmutable)) => {
1720 cx.span_lint(UNUSED_ALLOCATION, e.span,
1721 "unnecessary allocation, use & instead");
1723 &Some(ty::AutoPtr(_, ast::MutMutable)) => {
1724 cx.span_lint(UNUSED_ALLOCATION, e.span,
1725 "unnecessary allocation, use &mut instead");
1737 "detects missing documentation for public members"
1740 pub struct MissingDoc {
1741 /// Stack of IDs of struct definitions.
1742 struct_def_stack: Vec<ast::NodeId>,
1744 /// True if inside variant definition
1747 /// Stack of whether #[doc(hidden)] is set
1748 /// at each level which has lint attributes.
1749 doc_hidden_stack: Vec<bool>,
1751 /// Private traits or trait items that leaked through. Don't check their methods.
1752 private_traits: HashSet<ast::NodeId>,
1756 pub fn new() -> MissingDoc {
1758 struct_def_stack: vec!(),
1760 doc_hidden_stack: vec!(false),
1761 private_traits: HashSet::new(),
1765 fn doc_hidden(&self) -> bool {
1766 *self.doc_hidden_stack.last().expect("empty doc_hidden_stack")
1769 fn check_missing_docs_attrs(&self,
1771 id: Option<ast::NodeId>,
1772 attrs: &[ast::Attribute],
1774 desc: &'static str) {
1775 // If we're building a test harness, then warning about
1776 // documentation is probably not really relevant right now.
1777 if cx.sess().opts.test {
1781 // `#[doc(hidden)]` disables missing_docs check.
1782 if self.doc_hidden() {
1786 // Only check publicly-visible items, using the result from the privacy pass.
1787 // It's an option so the crate root can also use this function (it doesn't
1789 if let Some(ref id) = id {
1790 if !cx.exported_items.contains(id) {
1795 let has_doc = attrs.iter().any(|a| {
1796 match a.node.value.node {
1797 ast::MetaNameValue(ref name, _) if *name == "doc" => true,
1802 cx.span_lint(MISSING_DOCS, sp,
1803 &format!("missing documentation for {}", desc));
1808 impl LintPass for MissingDoc {
1809 fn get_lints(&self) -> LintArray {
1810 lint_array!(MISSING_DOCS)
1813 fn enter_lint_attrs(&mut self, _: &Context, attrs: &[ast::Attribute]) {
1814 let doc_hidden = self.doc_hidden() || attrs.iter().any(|attr| {
1815 attr.check_name("doc") && match attr.meta_item_list() {
1817 Some(l) => attr::contains_name(&l[..], "hidden"),
1820 self.doc_hidden_stack.push(doc_hidden);
1823 fn exit_lint_attrs(&mut self, _: &Context, _: &[ast::Attribute]) {
1824 self.doc_hidden_stack.pop().expect("empty doc_hidden_stack");
1827 fn check_struct_def(&mut self, _: &Context, _: &ast::StructDef,
1828 _: ast::Ident, _: &ast::Generics, id: ast::NodeId) {
1829 self.struct_def_stack.push(id);
1832 fn check_struct_def_post(&mut self, _: &Context, _: &ast::StructDef,
1833 _: ast::Ident, _: &ast::Generics, id: ast::NodeId) {
1834 let popped = self.struct_def_stack.pop().expect("empty struct_def_stack");
1835 assert!(popped == id);
1838 fn check_crate(&mut self, cx: &Context, krate: &ast::Crate) {
1839 self.check_missing_docs_attrs(cx, None, &krate.attrs, krate.span, "crate");
1842 fn check_item(&mut self, cx: &Context, it: &ast::Item) {
1843 let desc = match it.node {
1844 ast::ItemFn(..) => "a function",
1845 ast::ItemMod(..) => "a module",
1846 ast::ItemEnum(..) => "an enum",
1847 ast::ItemStruct(..) => "a struct",
1848 ast::ItemTrait(_, _, _, ref items) => {
1849 // Issue #11592, traits are always considered exported, even when private.
1850 if it.vis == ast::Visibility::Inherited {
1851 self.private_traits.insert(it.id);
1853 self.private_traits.insert(itm.id);
1859 ast::ItemTy(..) => "a type alias",
1860 ast::ItemImpl(_, _, _, Some(ref trait_ref), _, ref impl_items) => {
1861 // If the trait is private, add the impl items to private_traits so they don't get
1862 // reported for missing docs.
1863 let real_trait = cx.tcx.trait_ref_to_def_id(trait_ref);
1864 match cx.tcx.map.find(real_trait.node) {
1865 Some(ast_map::NodeItem(item)) => if item.vis == ast::Visibility::Inherited {
1866 for itm in impl_items {
1867 self.private_traits.insert(itm.id);
1874 ast::ItemConst(..) => "a constant",
1875 ast::ItemStatic(..) => "a static",
1879 self.check_missing_docs_attrs(cx, Some(it.id), &it.attrs, it.span, desc);
1882 fn check_trait_item(&mut self, cx: &Context, trait_item: &ast::TraitItem) {
1883 if self.private_traits.contains(&trait_item.id) { return }
1885 let desc = match trait_item.node {
1886 ast::ConstTraitItem(..) => "an associated constant",
1887 ast::MethodTraitItem(..) => "a trait method",
1888 ast::TypeTraitItem(..) => "an associated type",
1891 self.check_missing_docs_attrs(cx, Some(trait_item.id),
1893 trait_item.span, desc);
1896 fn check_impl_item(&mut self, cx: &Context, impl_item: &ast::ImplItem) {
1897 // If the method is an impl for a trait, don't doc.
1898 if method_context(cx, impl_item.id, impl_item.span) == MethodContext::TraitImpl {
1902 let desc = match impl_item.node {
1903 ast::ConstImplItem(..) => "an associated constant",
1904 ast::MethodImplItem(..) => "a method",
1905 ast::TypeImplItem(_) => "an associated type",
1906 ast::MacImplItem(_) => "an impl item macro",
1908 self.check_missing_docs_attrs(cx, Some(impl_item.id),
1910 impl_item.span, desc);
1913 fn check_struct_field(&mut self, cx: &Context, sf: &ast::StructField) {
1914 if let ast::NamedField(_, vis) = sf.node.kind {
1915 if vis == ast::Public || self.in_variant {
1916 let cur_struct_def = *self.struct_def_stack.last()
1917 .expect("empty struct_def_stack");
1918 self.check_missing_docs_attrs(cx, Some(cur_struct_def),
1919 &sf.node.attrs, sf.span,
1925 fn check_variant(&mut self, cx: &Context, v: &ast::Variant, _: &ast::Generics) {
1926 self.check_missing_docs_attrs(cx, Some(v.node.id), &v.node.attrs, v.span, "a variant");
1927 assert!(!self.in_variant);
1928 self.in_variant = true;
1931 fn check_variant_post(&mut self, _: &Context, _: &ast::Variant, _: &ast::Generics) {
1932 assert!(self.in_variant);
1933 self.in_variant = false;
1938 pub MISSING_COPY_IMPLEMENTATIONS,
1940 "detects potentially-forgotten implementations of `Copy`"
1943 #[derive(Copy, Clone)]
1944 pub struct MissingCopyImplementations;
1946 impl LintPass for MissingCopyImplementations {
1947 fn get_lints(&self) -> LintArray {
1948 lint_array!(MISSING_COPY_IMPLEMENTATIONS)
1951 fn check_item(&mut self, cx: &Context, item: &ast::Item) {
1952 if !cx.exported_items.contains(&item.id) {
1955 if cx.tcx.destructor_for_type.borrow().contains_key(&DefId::local(item.id)) {
1958 let ty = match item.node {
1959 ast::ItemStruct(_, ref ast_generics) => {
1960 if ast_generics.is_parameterized() {
1963 cx.tcx.mk_struct(cx.tcx.lookup_adt_def(DefId::local(item.id)),
1964 cx.tcx.mk_substs(Substs::empty()))
1966 ast::ItemEnum(_, ref ast_generics) => {
1967 if ast_generics.is_parameterized() {
1970 cx.tcx.mk_enum(cx.tcx.lookup_adt_def(DefId::local(item.id)),
1971 cx.tcx.mk_substs(Substs::empty()))
1975 let parameter_environment = cx.tcx.empty_parameter_environment();
1976 // FIXME (@jroesch) should probably inver this so that the parameter env still impls this
1978 if !ty.moves_by_default(¶meter_environment, item.span) {
1981 if parameter_environment.can_type_implement_copy(ty, item.span).is_ok() {
1982 cx.span_lint(MISSING_COPY_IMPLEMENTATIONS,
1984 "type could implement `Copy`; consider adding `impl \
1991 MISSING_DEBUG_IMPLEMENTATIONS,
1993 "detects missing implementations of fmt::Debug"
1996 pub struct MissingDebugImplementations {
1997 impling_types: Option<NodeSet>,
2000 impl MissingDebugImplementations {
2001 pub fn new() -> MissingDebugImplementations {
2002 MissingDebugImplementations {
2003 impling_types: None,
2008 impl LintPass for MissingDebugImplementations {
2009 fn get_lints(&self) -> LintArray {
2010 lint_array!(MISSING_DEBUG_IMPLEMENTATIONS)
2013 fn check_item(&mut self, cx: &Context, item: &ast::Item) {
2014 if !cx.exported_items.contains(&item.id) {
2019 ast::ItemStruct(..) | ast::ItemEnum(..) => {},
2023 let debug = match cx.tcx.lang_items.debug_trait() {
2024 Some(debug) => debug,
2028 if self.impling_types.is_none() {
2029 let debug_def = cx.tcx.lookup_trait_def(debug);
2030 let mut impls = NodeSet();
2031 debug_def.for_each_impl(cx.tcx, |d| {
2033 if let Some(ty_def) = cx.tcx.node_id_to_type(d.node).ty_to_def_id() {
2034 impls.insert(ty_def.node);
2039 self.impling_types = Some(impls);
2040 debug!("{:?}", self.impling_types);
2043 if !self.impling_types.as_ref().unwrap().contains(&item.id) {
2044 cx.span_lint(MISSING_DEBUG_IMPLEMENTATIONS,
2046 "type does not implement `fmt::Debug`; consider adding #[derive(Debug)] \
2047 or a manual implementation")
2055 "detects use of #[deprecated] items"
2058 /// Checks for use of items with `#[deprecated]` attributes
2059 #[derive(Copy, Clone)]
2060 pub struct Stability;
2063 fn lint(&self, cx: &Context, _id: DefId,
2064 span: Span, stability: &Option<&attr::Stability>) {
2065 // Deprecated attributes apply in-crate and cross-crate.
2066 let (lint, label) = match *stability {
2067 Some(&attr::Stability { deprecated_since: Some(_), .. }) =>
2068 (DEPRECATED, "deprecated"),
2072 output(cx, span, stability, lint, label);
2074 fn output(cx: &Context, span: Span, stability: &Option<&attr::Stability>,
2075 lint: &'static Lint, label: &'static str) {
2076 let msg = match *stability {
2077 Some(&attr::Stability { reason: Some(ref s), .. }) => {
2078 format!("use of {} item: {}", label, *s)
2080 _ => format!("use of {} item", label)
2083 cx.span_lint(lint, span, &msg[..]);
2088 impl LintPass for Stability {
2089 fn get_lints(&self) -> LintArray {
2090 lint_array!(DEPRECATED)
2093 fn check_item(&mut self, cx: &Context, item: &ast::Item) {
2094 stability::check_item(cx.tcx, item, false,
2095 &mut |id, sp, stab| self.lint(cx, id, sp, stab));
2098 fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
2099 stability::check_expr(cx.tcx, e,
2100 &mut |id, sp, stab| self.lint(cx, id, sp, stab));
2103 fn check_path(&mut self, cx: &Context, path: &ast::Path, id: ast::NodeId) {
2104 stability::check_path(cx.tcx, path, id,
2105 &mut |id, sp, stab| self.lint(cx, id, sp, stab));
2108 fn check_pat(&mut self, cx: &Context, pat: &ast::Pat) {
2109 stability::check_pat(cx.tcx, pat,
2110 &mut |id, sp, stab| self.lint(cx, id, sp, stab))
2115 pub UNCONDITIONAL_RECURSION,
2117 "functions that cannot return without calling themselves"
2120 #[derive(Copy, Clone)]
2121 pub struct UnconditionalRecursion;
2124 impl LintPass for UnconditionalRecursion {
2125 fn get_lints(&self) -> LintArray {
2126 lint_array![UNCONDITIONAL_RECURSION]
2129 fn check_fn(&mut self, cx: &Context, fn_kind: visit::FnKind, _: &ast::FnDecl,
2130 blk: &ast::Block, sp: Span, id: ast::NodeId) {
2131 type F = for<'tcx> fn(&ty::ctxt<'tcx>,
2132 ast::NodeId, ast::NodeId, ast::Ident, ast::NodeId) -> bool;
2134 let method = match fn_kind {
2135 visit::FkItemFn(..) => None,
2136 visit::FkMethod(..) => {
2137 cx.tcx.impl_or_trait_item(DefId::local(id)).as_opt_method()
2139 // closures can't recur, so they don't matter.
2140 visit::FkFnBlock => return
2143 // Walk through this function (say `f`) looking to see if
2144 // every possible path references itself, i.e. the function is
2145 // called recursively unconditionally. This is done by trying
2146 // to find a path from the entry node to the exit node that
2147 // *doesn't* call `f` by traversing from the entry while
2148 // pretending that calls of `f` are sinks (i.e. ignoring any
2149 // exit edges from them).
2151 // NB. this has an edge case with non-returning statements,
2152 // like `loop {}` or `panic!()`: control flow never reaches
2153 // the exit node through these, so one can have a function
2154 // that never actually calls itselfs but is still picked up by
2157 // fn f(cond: bool) {
2158 // if !cond { panic!() } // could come from `assert!(cond)`
2162 // In general, functions of that form may be able to call
2163 // itself a finite number of times and then diverge. The lint
2164 // considers this to be an error for two reasons, (a) it is
2165 // easier to implement, and (b) it seems rare to actually want
2166 // to have behaviour like the above, rather than
2167 // e.g. accidentally recurring after an assert.
2169 let cfg = cfg::CFG::new(cx.tcx, blk);
2171 let mut work_queue = vec![cfg.entry];
2172 let mut reached_exit_without_self_call = false;
2173 let mut self_call_spans = vec![];
2174 let mut visited = HashSet::new();
2176 while let Some(idx) = work_queue.pop() {
2177 if idx == cfg.exit {
2179 reached_exit_without_self_call = true;
2183 let cfg_id = idx.node_id();
2184 if visited.contains(&cfg_id) {
2188 visited.insert(cfg_id);
2190 let node_id = cfg.graph.node_data(idx).id();
2192 // is this a recursive call?
2193 let self_recursive = if node_id != ast::DUMMY_NODE_ID {
2195 Some(ref method) => {
2196 expr_refers_to_this_method(cx.tcx, method, node_id)
2198 None => expr_refers_to_this_fn(cx.tcx, id, node_id)
2204 self_call_spans.push(cx.tcx.map.span(node_id));
2205 // this is a self call, so we shouldn't explore past
2206 // this node in the CFG.
2209 // add the successors of this node to explore the graph further.
2210 for (_, edge) in cfg.graph.outgoing_edges(idx) {
2211 let target_idx = edge.target();
2212 let target_cfg_id = target_idx.node_id();
2213 if !visited.contains(&target_cfg_id) {
2214 work_queue.push(target_idx)
2219 // Check the number of self calls because a function that
2220 // doesn't return (e.g. calls a `-> !` function or `loop { /*
2221 // no break */ }`) shouldn't be linted unless it actually
2223 if !reached_exit_without_self_call && !self_call_spans.is_empty() {
2224 cx.span_lint(UNCONDITIONAL_RECURSION, sp,
2225 "function cannot return without recurring");
2227 // FIXME #19668: these could be span_lint_note's instead of this manual guard.
2228 if cx.current_level(UNCONDITIONAL_RECURSION) != Level::Allow {
2229 let sess = cx.sess();
2230 // offer some help to the programmer.
2231 for call in &self_call_spans {
2232 sess.span_note(*call, "recursive call site")
2234 sess.fileline_help(sp, "a `loop` may express intention \
2235 better if this is on purpose")
2242 // Functions for identifying if the given Expr NodeId `id`
2243 // represents a call to the function `fn_id`/method `method`.
2245 fn expr_refers_to_this_fn(tcx: &ty::ctxt,
2247 id: ast::NodeId) -> bool {
2248 match tcx.map.get(id) {
2249 ast_map::NodeExpr(&ast::Expr { node: ast::ExprCall(ref callee, _), .. }) => {
2250 tcx.def_map.borrow().get(&callee.id)
2251 .map_or(false, |def| def.def_id() == DefId::local(fn_id))
2257 // Check if the expression `id` performs a call to `method`.
2258 fn expr_refers_to_this_method(tcx: &ty::ctxt,
2259 method: &ty::Method,
2260 id: ast::NodeId) -> bool {
2261 let tables = tcx.tables.borrow();
2263 // Check for method calls and overloaded operators.
2264 if let Some(m) = tables.method_map.get(&ty::MethodCall::expr(id)) {
2265 if method_call_refers_to_method(tcx, method, m.def_id, m.substs, id) {
2270 // Check for overloaded autoderef method calls.
2271 if let Some(&ty::AdjustDerefRef(ref adj)) = tables.adjustments.get(&id) {
2272 for i in 0..adj.autoderefs {
2273 let method_call = ty::MethodCall::autoderef(id, i as u32);
2274 if let Some(m) = tables.method_map.get(&method_call) {
2275 if method_call_refers_to_method(tcx, method, m.def_id, m.substs, id) {
2282 // Check for calls to methods via explicit paths (e.g. `T::method()`).
2283 match tcx.map.get(id) {
2284 ast_map::NodeExpr(&ast::Expr { node: ast::ExprCall(ref callee, _), .. }) => {
2285 match tcx.def_map.borrow().get(&callee.id).map(|d| d.full_def()) {
2286 Some(def::DefMethod(def_id)) => {
2287 let no_substs = &ty::ItemSubsts::empty();
2288 let ts = tables.item_substs.get(&callee.id).unwrap_or(no_substs);
2289 method_call_refers_to_method(tcx, method, def_id, &ts.substs, id)
2298 // Check if the method call to the method with the ID `callee_id`
2299 // and instantiated with `callee_substs` refers to method `method`.
2300 fn method_call_refers_to_method<'tcx>(tcx: &ty::ctxt<'tcx>,
2301 method: &ty::Method,
2303 callee_substs: &Substs<'tcx>,
2304 expr_id: ast::NodeId) -> bool {
2305 let callee_item = tcx.impl_or_trait_item(callee_id);
2307 match callee_item.container() {
2308 // This is an inherent method, so the `def_id` refers
2309 // directly to the method definition.
2310 ty::ImplContainer(_) => {
2311 callee_id == method.def_id
2314 // A trait method, from any number of possible sources.
2315 // Attempt to select a concrete impl before checking.
2316 ty::TraitContainer(trait_def_id) => {
2317 let trait_substs = callee_substs.clone().method_to_trait();
2318 let trait_substs = tcx.mk_substs(trait_substs);
2319 let trait_ref = ty::TraitRef::new(trait_def_id, trait_substs);
2320 let trait_ref = ty::Binder(trait_ref);
2321 let span = tcx.map.span(expr_id);
2323 traits::Obligation::new(traits::ObligationCause::misc(span, expr_id),
2324 trait_ref.to_poly_trait_predicate());
2326 let param_env = ty::ParameterEnvironment::for_item(tcx, method.def_id.node);
2327 let infcx = infer::new_infer_ctxt(tcx, &tcx.tables, Some(param_env), false);
2328 let mut selcx = traits::SelectionContext::new(&infcx);
2329 match selcx.select(&obligation) {
2330 // The method comes from a `T: Trait` bound.
2331 // If `T` is `Self`, then this call is inside
2332 // a default method definition.
2333 Ok(Some(traits::VtableParam(_))) => {
2334 let self_ty = callee_substs.self_ty();
2335 let on_self = self_ty.map_or(false, |t| t.is_self());
2336 // We can only be recurring in a default
2337 // method if we're being called literally
2338 // on the `Self` type.
2339 on_self && callee_id == method.def_id
2342 // The `impl` is known, so we check that with a
2344 Ok(Some(traits::VtableImpl(vtable_impl))) => {
2345 let container = ty::ImplContainer(vtable_impl.impl_def_id);
2346 // It matches if it comes from the same impl,
2347 // and has the same method name.
2348 container == method.container
2349 && callee_item.name() == method.name
2352 // There's no way to know if this call is
2353 // recursive, so we assume it's not.
2365 "compiler plugin used as ordinary library in non-plugin crate"
2368 #[derive(Copy, Clone)]
2369 pub struct PluginAsLibrary;
2371 impl LintPass for PluginAsLibrary {
2372 fn get_lints(&self) -> LintArray {
2373 lint_array![PLUGIN_AS_LIBRARY]
2376 fn check_item(&mut self, cx: &Context, it: &ast::Item) {
2377 if cx.sess().plugin_registrar_fn.get().is_some() {
2378 // We're compiling a plugin; it's fine to link other plugins.
2383 ast::ItemExternCrate(..) => (),
2387 let md = match cx.sess().cstore.find_extern_mod_stmt_cnum(it.id) {
2388 Some(cnum) => cx.sess().cstore.get_crate_data(cnum),
2390 // Probably means we aren't linking the crate for some reason.
2392 // Not sure if / when this could happen.
2397 if decoder::get_plugin_registrar_fn(md.data()).is_some() {
2398 cx.span_lint(PLUGIN_AS_LIBRARY, it.span,
2399 "compiler plugin used as an ordinary library");
2405 PRIVATE_NO_MANGLE_FNS,
2407 "functions marked #[no_mangle] should be exported"
2411 PRIVATE_NO_MANGLE_STATICS,
2413 "statics marked #[no_mangle] should be exported"
2417 NO_MANGLE_CONST_ITEMS,
2419 "const items will not have their symbols exported"
2422 #[derive(Copy, Clone)]
2423 pub struct InvalidNoMangleItems;
2425 impl LintPass for InvalidNoMangleItems {
2426 fn get_lints(&self) -> LintArray {
2427 lint_array!(PRIVATE_NO_MANGLE_FNS,
2428 PRIVATE_NO_MANGLE_STATICS,
2429 NO_MANGLE_CONST_ITEMS)
2432 fn check_item(&mut self, cx: &Context, it: &ast::Item) {
2434 ast::ItemFn(..) => {
2435 if attr::contains_name(&it.attrs, "no_mangle") &&
2436 !cx.exported_items.contains(&it.id) {
2437 let msg = format!("function {} is marked #[no_mangle], but not exported",
2439 cx.span_lint(PRIVATE_NO_MANGLE_FNS, it.span, &msg);
2442 ast::ItemStatic(..) => {
2443 if attr::contains_name(&it.attrs, "no_mangle") &&
2444 !cx.exported_items.contains(&it.id) {
2445 let msg = format!("static {} is marked #[no_mangle], but not exported",
2447 cx.span_lint(PRIVATE_NO_MANGLE_STATICS, it.span, &msg);
2450 ast::ItemConst(..) => {
2451 if attr::contains_name(&it.attrs, "no_mangle") {
2452 // Const items do not refer to a particular location in memory, and therefore
2453 // don't have anything to attach a symbol to
2454 let msg = "const items should never be #[no_mangle], consider instead using \
2456 cx.span_lint(NO_MANGLE_CONST_ITEMS, it.span, msg);
2464 #[derive(Clone, Copy)]
2465 pub struct MutableTransmutes;
2470 "mutating transmuted &mut T from &T may cause undefined behavior"
2473 impl LintPass for MutableTransmutes {
2474 fn get_lints(&self) -> LintArray {
2475 lint_array!(MUTABLE_TRANSMUTES)
2478 fn check_expr(&mut self, cx: &Context, expr: &ast::Expr) {
2479 use syntax::abi::RustIntrinsic;
2480 let msg = "mutating transmuted &mut T from &T may cause undefined behavior,\
2481 consider instead using an UnsafeCell";
2482 match get_transmute_from_to(cx, expr) {
2483 Some((&ty::TyRef(_, from_mt), &ty::TyRef(_, to_mt))) => {
2484 if to_mt.mutbl == ast::Mutability::MutMutable
2485 && from_mt.mutbl == ast::Mutability::MutImmutable {
2486 cx.span_lint(MUTABLE_TRANSMUTES, expr.span, msg);
2492 fn get_transmute_from_to<'a, 'tcx>(cx: &Context<'a, 'tcx>, expr: &ast::Expr)
2493 -> Option<(&'tcx ty::TypeVariants<'tcx>, &'tcx ty::TypeVariants<'tcx>)> {
2495 ast::ExprPath(..) => (),
2498 if let def::DefFn(did, _) = cx.tcx.resolve_expr(expr) {
2499 if !def_id_is_transmute(cx, did) {
2502 let typ = cx.tcx.node_id_to_type(expr.id);
2504 ty::TyBareFn(_, ref bare_fn) if bare_fn.abi == RustIntrinsic => {
2505 if let ty::FnConverging(to) = bare_fn.sig.0.output {
2506 let from = bare_fn.sig.0.inputs[0];
2507 return Some((&from.sty, &to.sty));
2516 fn def_id_is_transmute(cx: &Context, def_id: DefId) -> bool {
2517 match cx.tcx.lookup_item_type(def_id).ty.sty {
2518 ty::TyBareFn(_, ref bfty) if bfty.abi == RustIntrinsic => (),
2521 cx.tcx.with_path(def_id, |path| match path.last() {
2522 Some(ref last) => last.name().as_str() == "transmute",
2529 /// Forbids using the `#[feature(...)]` attribute
2530 #[derive(Copy, Clone)]
2531 pub struct UnstableFeatures;
2536 "enabling unstable features (deprecated. do not use)"
2539 impl LintPass for UnstableFeatures {
2540 fn get_lints(&self) -> LintArray {
2541 lint_array!(UNSTABLE_FEATURES)
2543 fn check_attribute(&mut self, ctx: &Context, attr: &ast::Attribute) {
2544 if attr::contains_name(&[attr.node.value.clone()], "feature") {
2545 if let Some(items) = attr.node.value.meta_item_list() {
2547 ctx.span_lint(UNSTABLE_FEATURES, item.span, "unstable feature");
2554 /// Lints for attempts to impl Drop on types that have `#[repr(C)]`
2555 /// attribute (see issue #24585).
2556 #[derive(Copy, Clone)]
2557 pub struct DropWithReprExtern;
2560 DROP_WITH_REPR_EXTERN,
2562 "use of #[repr(C)] on a type that implements Drop"
2565 impl LintPass for DropWithReprExtern {
2566 fn get_lints(&self) -> LintArray {
2567 lint_array!(DROP_WITH_REPR_EXTERN)
2569 fn check_crate(&mut self, ctx: &Context, _: &ast::Crate) {
2570 for dtor_did in ctx.tcx.destructors.borrow().iter() {
2571 let (drop_impl_did, dtor_self_type) =
2572 if dtor_did.is_local() {
2573 let impl_did = ctx.tcx.map.get_parent_did(dtor_did.node);
2574 let ty = ctx.tcx.lookup_item_type(impl_did).ty;
2580 match dtor_self_type.sty {
2581 ty::TyEnum(self_type_def, _) |
2582 ty::TyStruct(self_type_def, _) => {
2583 let self_type_did = self_type_def.did;
2584 let hints = ctx.tcx.lookup_repr_hints(self_type_did);
2585 if hints.iter().any(|attr| *attr == attr::ReprExtern) &&
2586 ctx.tcx.ty_dtor(self_type_did).has_drop_flag() {
2587 let drop_impl_span = ctx.tcx.map.def_id_span(drop_impl_did,
2589 let self_defn_span = ctx.tcx.map.def_id_span(self_type_did,
2591 ctx.span_lint(DROP_WITH_REPR_EXTERN,
2593 "implementing Drop adds hidden state to types, \
2594 possibly conflicting with `#[repr(C)]`");
2595 // FIXME #19668: could be span_lint_note instead of manual guard.
2596 if ctx.current_level(DROP_WITH_REPR_EXTERN) != Level::Allow {
2597 ctx.sess().span_note(self_defn_span,
2598 "the `#[repr(C)]` attribute is attached here");