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 if attr.check_name(name) => {
899 let plugin_attributes = cx.sess().plugin_attributes.borrow_mut();
900 for &(ref name, ty) in plugin_attributes.iter() {
901 if ty == AttributeType::Whitelisted && attr.check_name(&*name) {
906 if !attr::is_used(attr) {
907 cx.span_lint(UNUSED_ATTRIBUTES, attr.span, "unused attribute");
908 // Is it a builtin attribute that must be used at the crate level?
909 let known_crate = KNOWN_ATTRIBUTES.iter().find(|&&(name, ty, _)| {
910 attr.name() == name &&
911 ty == AttributeType::CrateLevel
914 // Has a plugin registered this attribute as one which must be used at
916 let plugin_crate = plugin_attributes.iter()
917 .find(|&&(ref x, t)| {
918 &*attr.name() == &*x &&
919 AttributeType::CrateLevel == t
921 if known_crate || plugin_crate {
922 let msg = match attr.node.style {
923 ast::AttrOuter => "crate-level attribute should be an inner \
924 attribute: add an exclamation mark: #![foo]",
925 ast::AttrInner => "crate-level attribute should be in the \
928 cx.span_lint(UNUSED_ATTRIBUTES, attr.span, msg);
937 "path statements with no effect"
940 #[derive(Copy, Clone)]
941 pub struct PathStatements;
943 impl LintPass for PathStatements {
944 fn get_lints(&self) -> LintArray {
945 lint_array!(PATH_STATEMENTS)
948 fn check_stmt(&mut self, cx: &Context, s: &ast::Stmt) {
950 ast::StmtSemi(ref expr, _) => {
952 ast::ExprPath(..) => cx.span_lint(PATH_STATEMENTS, s.span,
953 "path statement with no effect"),
965 "unused result of a type flagged as #[must_use]"
971 "unused result of an expression in a statement"
974 #[derive(Copy, Clone)]
975 pub struct UnusedResults;
977 impl LintPass for UnusedResults {
978 fn get_lints(&self) -> LintArray {
979 lint_array!(UNUSED_MUST_USE, UNUSED_RESULTS)
982 fn check_stmt(&mut self, cx: &Context, s: &ast::Stmt) {
983 let expr = match s.node {
984 ast::StmtSemi(ref expr, _) => &**expr,
988 if let ast::ExprRet(..) = expr.node {
992 let t = cx.tcx.expr_ty(expr);
993 let warned = match t.sty {
994 ty::TyTuple(ref tys) if tys.is_empty() => return,
995 ty::TyBool => return,
996 ty::TyStruct(def, _) |
997 ty::TyEnum(def, _) => {
998 if def.did.is_local() {
999 if let ast_map::NodeItem(it) = cx.tcx.map.get(def.did.node) {
1000 check_must_use(cx, &it.attrs, s.span)
1005 let attrs = csearch::get_item_attrs(&cx.sess().cstore, def.did);
1006 check_must_use(cx, &attrs[..], s.span)
1012 cx.span_lint(UNUSED_RESULTS, s.span, "unused result");
1015 fn check_must_use(cx: &Context, attrs: &[ast::Attribute], sp: Span) -> bool {
1017 if attr.check_name("must_use") {
1018 let mut msg = "unused result which must be used".to_string();
1019 // check for #[must_use="..."]
1020 match attr.value_str() {
1027 cx.span_lint(UNUSED_MUST_USE, sp, &msg);
1037 pub NON_CAMEL_CASE_TYPES,
1039 "types, variants, traits and type parameters should have camel case names"
1042 #[derive(Copy, Clone)]
1043 pub struct NonCamelCaseTypes;
1045 impl NonCamelCaseTypes {
1046 fn check_case(&self, cx: &Context, sort: &str, ident: ast::Ident, span: Span) {
1047 fn is_camel_case(ident: ast::Ident) -> bool {
1048 let ident = ident.name.as_str();
1049 if ident.is_empty() {
1052 let ident = ident.trim_matches('_');
1054 // start with a non-lowercase letter rather than non-uppercase
1055 // ones (some scripts don't have a concept of upper/lowercase)
1056 !ident.is_empty() && !ident.char_at(0).is_lowercase() && !ident.contains('_')
1059 fn to_camel_case(s: &str) -> String {
1060 s.split('_').flat_map(|word| word.chars().enumerate().map(|(i, c)|
1062 c.to_uppercase().collect::<String>()
1064 c.to_lowercase().collect()
1066 )).collect::<Vec<_>>().concat()
1069 let s = ident.name.as_str();
1071 if !is_camel_case(ident) {
1072 let c = to_camel_case(&s);
1073 let m = if c.is_empty() {
1074 format!("{} `{}` should have a camel case name such as `CamelCase`", sort, s)
1076 format!("{} `{}` should have a camel case name such as `{}`", sort, s, c)
1078 cx.span_lint(NON_CAMEL_CASE_TYPES, span, &m[..]);
1083 impl LintPass for NonCamelCaseTypes {
1084 fn get_lints(&self) -> LintArray {
1085 lint_array!(NON_CAMEL_CASE_TYPES)
1088 fn check_item(&mut self, cx: &Context, it: &ast::Item) {
1089 let extern_repr_count = it.attrs.iter().filter(|attr| {
1090 attr::find_repr_attrs(cx.tcx.sess.diagnostic(), attr).iter()
1091 .any(|r| r == &attr::ReprExtern)
1093 let has_extern_repr = extern_repr_count > 0;
1095 if has_extern_repr {
1100 ast::ItemTy(..) | ast::ItemStruct(..) => {
1101 self.check_case(cx, "type", it.ident, it.span)
1103 ast::ItemTrait(..) => {
1104 self.check_case(cx, "trait", it.ident, it.span)
1106 ast::ItemEnum(ref enum_definition, _) => {
1107 if has_extern_repr {
1110 self.check_case(cx, "type", it.ident, it.span);
1111 for variant in &enum_definition.variants {
1112 self.check_case(cx, "variant", variant.node.name, variant.span);
1119 fn check_generics(&mut self, cx: &Context, it: &ast::Generics) {
1120 for gen in it.ty_params.iter() {
1121 self.check_case(cx, "type parameter", gen.ident, gen.span);
1126 #[derive(PartialEq)]
1127 enum MethodContext {
1133 fn method_context(cx: &Context, id: ast::NodeId, span: Span) -> MethodContext {
1134 match cx.tcx.impl_or_trait_items.borrow().get(&DefId::local(id)) {
1135 None => cx.sess().span_bug(span, "missing method descriptor?!"),
1136 Some(item) => match item.container() {
1137 ty::TraitContainer(..) => MethodContext::TraitDefaultImpl,
1138 ty::ImplContainer(cid) => {
1139 match cx.tcx.impl_trait_ref(cid) {
1140 Some(_) => MethodContext::TraitImpl,
1141 None => MethodContext::PlainImpl
1151 "methods, functions, lifetime parameters and modules should have snake case names"
1154 #[derive(Copy, Clone)]
1155 pub struct NonSnakeCase;
1158 fn to_snake_case(mut str: &str) -> String {
1159 let mut words = vec![];
1160 // Preserve leading underscores
1161 str = str.trim_left_matches(|c: char| {
1163 words.push(String::new());
1169 for s in str.split('_') {
1170 let mut last_upper = false;
1171 let mut buf = String::new();
1175 for ch in s.chars() {
1176 if !buf.is_empty() && buf != "'"
1177 && ch.is_uppercase()
1180 buf = String::new();
1182 last_upper = ch.is_uppercase();
1183 buf.extend(ch.to_lowercase());
1190 fn check_snake_case(&self, cx: &Context, sort: &str, name: &str, span: Option<Span>) {
1191 fn is_snake_case(ident: &str) -> bool {
1192 if ident.is_empty() {
1195 let ident = ident.trim_left_matches('\'');
1196 let ident = ident.trim_matches('_');
1198 let mut allow_underscore = true;
1199 ident.chars().all(|c| {
1200 allow_underscore = match c {
1201 '_' if !allow_underscore => return false,
1203 // It would be more obvious to use `c.is_lowercase()`,
1204 // but some characters do not have a lowercase form
1205 c if !c.is_uppercase() => true,
1212 if !is_snake_case(name) {
1213 let sc = NonSnakeCase::to_snake_case(name);
1214 let msg = if sc != name {
1215 format!("{} `{}` should have a snake case name such as `{}`",
1218 format!("{} `{}` should have a snake case name",
1222 Some(span) => cx.span_lint(NON_SNAKE_CASE, span, &msg),
1223 None => cx.lint(NON_SNAKE_CASE, &msg),
1229 impl LintPass for NonSnakeCase {
1230 fn get_lints(&self) -> LintArray {
1231 lint_array!(NON_SNAKE_CASE)
1234 fn check_crate(&mut self, cx: &Context, cr: &ast::Crate) {
1235 let attr_crate_name = cr.attrs.iter().find(|at| at.check_name("crate_name"))
1236 .and_then(|at| at.value_str().map(|s| (at, s)));
1237 if let Some(ref name) = cx.tcx.sess.opts.crate_name {
1238 self.check_snake_case(cx, "crate", name, None);
1239 } else if let Some((attr, ref name)) = attr_crate_name {
1240 self.check_snake_case(cx, "crate", name, Some(attr.span));
1244 fn check_fn(&mut self, cx: &Context,
1245 fk: visit::FnKind, _: &ast::FnDecl,
1246 _: &ast::Block, span: Span, id: ast::NodeId) {
1248 visit::FkMethod(ident, _, _) => match method_context(cx, id, span) {
1249 MethodContext::PlainImpl => {
1250 self.check_snake_case(cx, "method", &ident.name.as_str(), Some(span))
1252 MethodContext::TraitDefaultImpl => {
1253 self.check_snake_case(cx, "trait method", &ident.name.as_str(), Some(span))
1257 visit::FkItemFn(ident, _, _, _, _, _) => {
1258 self.check_snake_case(cx, "function", &ident.name.as_str(), Some(span))
1264 fn check_item(&mut self, cx: &Context, it: &ast::Item) {
1265 if let ast::ItemMod(_) = it.node {
1266 self.check_snake_case(cx, "module", &it.ident.name.as_str(), Some(it.span));
1270 fn check_trait_item(&mut self, cx: &Context, trait_item: &ast::TraitItem) {
1271 if let ast::MethodTraitItem(_, None) = trait_item.node {
1272 self.check_snake_case(cx, "trait method", &trait_item.ident.name.as_str(),
1273 Some(trait_item.span));
1277 fn check_lifetime_def(&mut self, cx: &Context, t: &ast::LifetimeDef) {
1278 self.check_snake_case(cx, "lifetime", &t.lifetime.name.as_str(),
1279 Some(t.lifetime.span));
1282 fn check_pat(&mut self, cx: &Context, p: &ast::Pat) {
1283 if let &ast::PatIdent(_, ref path1, _) = &p.node {
1284 let def = cx.tcx.def_map.borrow().get(&p.id).map(|d| d.full_def());
1285 if let Some(def::DefLocal(_)) = def {
1286 self.check_snake_case(cx, "variable", &path1.node.name.as_str(), Some(p.span));
1291 fn check_struct_def(&mut self, cx: &Context, s: &ast::StructDef,
1292 _: ast::Ident, _: &ast::Generics, _: ast::NodeId) {
1293 for sf in &s.fields {
1294 if let ast::StructField_ { kind: ast::NamedField(ident, _), .. } = sf.node {
1295 self.check_snake_case(cx, "structure field", &ident.name.as_str(),
1303 pub NON_UPPER_CASE_GLOBALS,
1305 "static constants should have uppercase identifiers"
1308 #[derive(Copy, Clone)]
1309 pub struct NonUpperCaseGlobals;
1311 impl NonUpperCaseGlobals {
1312 fn check_upper_case(cx: &Context, sort: &str, ident: ast::Ident, span: Span) {
1313 let s = ident.name.as_str();
1315 if s.chars().any(|c| c.is_lowercase()) {
1316 let uc = NonSnakeCase::to_snake_case(&s).to_uppercase();
1318 cx.span_lint(NON_UPPER_CASE_GLOBALS, span,
1319 &format!("{} `{}` should have an upper case name such as `{}`",
1322 cx.span_lint(NON_UPPER_CASE_GLOBALS, span,
1323 &format!("{} `{}` should have an upper case name",
1330 impl LintPass for NonUpperCaseGlobals {
1331 fn get_lints(&self) -> LintArray {
1332 lint_array!(NON_UPPER_CASE_GLOBALS)
1335 fn check_item(&mut self, cx: &Context, it: &ast::Item) {
1337 // only check static constants
1338 ast::ItemStatic(_, ast::MutImmutable, _) => {
1339 NonUpperCaseGlobals::check_upper_case(cx, "static constant", it.ident, it.span);
1341 ast::ItemConst(..) => {
1342 NonUpperCaseGlobals::check_upper_case(cx, "constant", it.ident, it.span);
1348 fn check_trait_item(&mut self, cx: &Context, ti: &ast::TraitItem) {
1350 ast::ConstTraitItem(..) => {
1351 NonUpperCaseGlobals::check_upper_case(cx, "associated constant",
1358 fn check_impl_item(&mut self, cx: &Context, ii: &ast::ImplItem) {
1360 ast::ConstImplItem(..) => {
1361 NonUpperCaseGlobals::check_upper_case(cx, "associated constant",
1368 fn check_pat(&mut self, cx: &Context, p: &ast::Pat) {
1369 // Lint for constants that look like binding identifiers (#7526)
1370 match (&p.node, cx.tcx.def_map.borrow().get(&p.id).map(|d| d.full_def())) {
1371 (&ast::PatIdent(_, ref path1, _), Some(def::DefConst(..))) => {
1372 NonUpperCaseGlobals::check_upper_case(cx, "constant in pattern",
1373 path1.node, p.span);
1383 "`if`, `match`, `while` and `return` do not need parentheses"
1386 #[derive(Copy, Clone)]
1387 pub struct UnusedParens;
1390 fn check_unused_parens_core(&self, cx: &Context, value: &ast::Expr, msg: &str,
1391 struct_lit_needs_parens: bool) {
1392 if let ast::ExprParen(ref inner) = value.node {
1393 let necessary = struct_lit_needs_parens && contains_exterior_struct_lit(&**inner);
1395 cx.span_lint(UNUSED_PARENS, value.span,
1396 &format!("unnecessary parentheses around {}", msg))
1400 /// Expressions that syntactically contain an "exterior" struct
1401 /// literal i.e. not surrounded by any parens or other
1402 /// delimiters, e.g. `X { y: 1 }`, `X { y: 1 }.method()`, `foo
1403 /// == X { y: 1 }` and `X { y: 1 } == foo` all do, but `(X {
1404 /// y: 1 }) == foo` does not.
1405 fn contains_exterior_struct_lit(value: &ast::Expr) -> bool {
1407 ast::ExprStruct(..) => true,
1409 ast::ExprAssign(ref lhs, ref rhs) |
1410 ast::ExprAssignOp(_, ref lhs, ref rhs) |
1411 ast::ExprBinary(_, ref lhs, ref rhs) => {
1412 // X { y: 1 } + X { y: 2 }
1413 contains_exterior_struct_lit(&**lhs) ||
1414 contains_exterior_struct_lit(&**rhs)
1416 ast::ExprUnary(_, ref x) |
1417 ast::ExprCast(ref x, _) |
1418 ast::ExprField(ref x, _) |
1419 ast::ExprTupField(ref x, _) |
1420 ast::ExprIndex(ref x, _) => {
1421 // &X { y: 1 }, X { y: 1 }.y
1422 contains_exterior_struct_lit(&**x)
1425 ast::ExprMethodCall(_, _, ref exprs) => {
1426 // X { y: 1 }.bar(...)
1427 contains_exterior_struct_lit(&*exprs[0])
1436 impl LintPass for UnusedParens {
1437 fn get_lints(&self) -> LintArray {
1438 lint_array!(UNUSED_PARENS)
1441 fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
1442 let (value, msg, struct_lit_needs_parens) = match e.node {
1443 ast::ExprIf(ref cond, _, _) => (cond, "`if` condition", true),
1444 ast::ExprWhile(ref cond, _, _) => (cond, "`while` condition", true),
1445 ast::ExprMatch(ref head, _, source) => match source {
1446 ast::MatchSource::Normal => (head, "`match` head expression", true),
1447 ast::MatchSource::IfLetDesugar { .. } => (head, "`if let` head expression", true),
1448 ast::MatchSource::WhileLetDesugar => (head, "`while let` head expression", true),
1449 ast::MatchSource::ForLoopDesugar => (head, "`for` head expression", true),
1451 ast::ExprRet(Some(ref value)) => (value, "`return` value", false),
1452 ast::ExprAssign(_, ref value) => (value, "assigned value", false),
1453 ast::ExprAssignOp(_, _, ref value) => (value, "assigned value", false),
1456 self.check_unused_parens_core(cx, &**value, msg, struct_lit_needs_parens);
1459 fn check_stmt(&mut self, cx: &Context, s: &ast::Stmt) {
1460 let (value, msg) = match s.node {
1461 ast::StmtDecl(ref decl, _) => match decl.node {
1462 ast::DeclLocal(ref local) => match local.init {
1463 Some(ref value) => (value, "assigned value"),
1470 self.check_unused_parens_core(cx, &**value, msg, false);
1475 UNUSED_IMPORT_BRACES,
1477 "unnecessary braces around an imported item"
1480 #[derive(Copy, Clone)]
1481 pub struct UnusedImportBraces;
1483 impl LintPass for UnusedImportBraces {
1484 fn get_lints(&self) -> LintArray {
1485 lint_array!(UNUSED_IMPORT_BRACES)
1488 fn check_item(&mut self, cx: &Context, item: &ast::Item) {
1489 if let ast::ItemUse(ref view_path) = item.node {
1490 if let ast::ViewPathList(_, ref items) = view_path.node {
1491 if items.len() == 1 {
1492 if let ast::PathListIdent {ref name, ..} = items[0].node {
1493 let m = format!("braces around {} is unnecessary",
1495 cx.span_lint(UNUSED_IMPORT_BRACES, item.span,
1505 NON_SHORTHAND_FIELD_PATTERNS,
1507 "using `Struct { x: x }` instead of `Struct { x }`"
1510 #[derive(Copy, Clone)]
1511 pub struct NonShorthandFieldPatterns;
1513 impl LintPass for NonShorthandFieldPatterns {
1514 fn get_lints(&self) -> LintArray {
1515 lint_array!(NON_SHORTHAND_FIELD_PATTERNS)
1518 fn check_pat(&mut self, cx: &Context, pat: &ast::Pat) {
1519 let def_map = cx.tcx.def_map.borrow();
1520 if let ast::PatStruct(_, ref v, _) = pat.node {
1521 let field_pats = v.iter().filter(|fieldpat| {
1522 if fieldpat.node.is_shorthand {
1525 let def = def_map.get(&fieldpat.node.pat.id).map(|d| d.full_def());
1526 def == Some(def::DefLocal(fieldpat.node.pat.id))
1528 for fieldpat in field_pats {
1529 if let ast::PatIdent(_, ident, None) = fieldpat.node.pat.node {
1530 if ident.node.name == fieldpat.node.ident.name {
1531 // FIXME: should this comparison really be done on the name?
1532 // doing it on the ident will fail during compilation of libcore
1533 cx.span_lint(NON_SHORTHAND_FIELD_PATTERNS, fieldpat.span,
1534 &format!("the `{}:` in this pattern is redundant and can \
1535 be removed", ident.node))
1546 "unnecessary use of an `unsafe` block"
1549 #[derive(Copy, Clone)]
1550 pub struct UnusedUnsafe;
1552 impl LintPass for UnusedUnsafe {
1553 fn get_lints(&self) -> LintArray {
1554 lint_array!(UNUSED_UNSAFE)
1557 fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
1558 if let ast::ExprBlock(ref blk) = e.node {
1559 // Don't warn about generated blocks, that'll just pollute the output.
1560 if blk.rules == ast::UnsafeBlock(ast::UserProvided) &&
1561 !cx.tcx.used_unsafe.borrow().contains(&blk.id) {
1562 cx.span_lint(UNUSED_UNSAFE, blk.span, "unnecessary `unsafe` block");
1571 "usage of `unsafe` code"
1574 #[derive(Copy, Clone)]
1575 pub struct UnsafeCode;
1577 impl LintPass for UnsafeCode {
1578 fn get_lints(&self) -> LintArray {
1579 lint_array!(UNSAFE_CODE)
1582 fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
1583 if let ast::ExprBlock(ref blk) = e.node {
1584 // Don't warn about generated blocks, that'll just pollute the output.
1585 if blk.rules == ast::UnsafeBlock(ast::UserProvided) {
1586 cx.span_lint(UNSAFE_CODE, blk.span, "usage of an `unsafe` block");
1591 fn check_item(&mut self, cx: &Context, it: &ast::Item) {
1593 ast::ItemTrait(ast::Unsafety::Unsafe, _, _, _) =>
1594 cx.span_lint(UNSAFE_CODE, it.span, "declaration of an `unsafe` trait"),
1596 ast::ItemImpl(ast::Unsafety::Unsafe, _, _, _, _, _) =>
1597 cx.span_lint(UNSAFE_CODE, it.span, "implementation of an `unsafe` trait"),
1603 fn check_fn(&mut self, cx: &Context, fk: visit::FnKind, _: &ast::FnDecl,
1604 _: &ast::Block, span: Span, _: ast::NodeId) {
1606 visit::FkItemFn(_, _, ast::Unsafety::Unsafe, _, _, _) =>
1607 cx.span_lint(UNSAFE_CODE, span, "declaration of an `unsafe` function"),
1609 visit::FkMethod(_, sig, _) => {
1610 if sig.unsafety == ast::Unsafety::Unsafe {
1611 cx.span_lint(UNSAFE_CODE, span, "implementation of an `unsafe` method")
1619 fn check_trait_item(&mut self, cx: &Context, trait_item: &ast::TraitItem) {
1620 if let ast::MethodTraitItem(ref sig, None) = trait_item.node {
1621 if sig.unsafety == ast::Unsafety::Unsafe {
1622 cx.span_lint(UNSAFE_CODE, trait_item.span,
1623 "declaration of an `unsafe` method")
1632 "detect mut variables which don't need to be mutable"
1635 #[derive(Copy, Clone)]
1636 pub struct UnusedMut;
1639 fn check_unused_mut_pat(&self, cx: &Context, pats: &[P<ast::Pat>]) {
1640 // collect all mutable pattern and group their NodeIDs by their Identifier to
1641 // avoid false warnings in match arms with multiple patterns
1643 let mut mutables = FnvHashMap();
1645 pat_util::pat_bindings(&cx.tcx.def_map, &**p, |mode, id, _, path1| {
1646 let ident = path1.node;
1647 if let ast::BindByValue(ast::MutMutable) = mode {
1648 if !ident.name.as_str().starts_with("_") {
1649 match mutables.entry(ident.name.usize()) {
1650 Vacant(entry) => { entry.insert(vec![id]); },
1651 Occupied(mut entry) => { entry.get_mut().push(id); },
1658 let used_mutables = cx.tcx.used_mut_nodes.borrow();
1659 for (_, v) in &mutables {
1660 if !v.iter().any(|e| used_mutables.contains(e)) {
1661 cx.span_lint(UNUSED_MUT, cx.tcx.map.span(v[0]),
1662 "variable does not need to be mutable");
1668 impl LintPass for UnusedMut {
1669 fn get_lints(&self) -> LintArray {
1670 lint_array!(UNUSED_MUT)
1673 fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
1674 if let ast::ExprMatch(_, ref arms, _) = e.node {
1676 self.check_unused_mut_pat(cx, &a.pats)
1681 fn check_stmt(&mut self, cx: &Context, s: &ast::Stmt) {
1682 if let ast::StmtDecl(ref d, _) = s.node {
1683 if let ast::DeclLocal(ref l) = d.node {
1684 self.check_unused_mut_pat(cx, slice::ref_slice(&l.pat));
1689 fn check_fn(&mut self, cx: &Context,
1690 _: visit::FnKind, decl: &ast::FnDecl,
1691 _: &ast::Block, _: Span, _: ast::NodeId) {
1692 for a in &decl.inputs {
1693 self.check_unused_mut_pat(cx, slice::ref_slice(&a.pat));
1701 "detects unnecessary allocations that can be eliminated"
1704 #[derive(Copy, Clone)]
1705 pub struct UnusedAllocation;
1707 impl LintPass for UnusedAllocation {
1708 fn get_lints(&self) -> LintArray {
1709 lint_array!(UNUSED_ALLOCATION)
1712 fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
1714 ast::ExprUnary(ast::UnUniq, _) => (),
1718 if let Some(adjustment) = cx.tcx.tables.borrow().adjustments.get(&e.id) {
1719 if let ty::AdjustDerefRef(ty::AutoDerefRef { ref autoref, .. }) = *adjustment {
1721 &Some(ty::AutoPtr(_, ast::MutImmutable)) => {
1722 cx.span_lint(UNUSED_ALLOCATION, e.span,
1723 "unnecessary allocation, use & instead");
1725 &Some(ty::AutoPtr(_, ast::MutMutable)) => {
1726 cx.span_lint(UNUSED_ALLOCATION, e.span,
1727 "unnecessary allocation, use &mut instead");
1739 "detects missing documentation for public members"
1742 pub struct MissingDoc {
1743 /// Stack of IDs of struct definitions.
1744 struct_def_stack: Vec<ast::NodeId>,
1746 /// True if inside variant definition
1749 /// Stack of whether #[doc(hidden)] is set
1750 /// at each level which has lint attributes.
1751 doc_hidden_stack: Vec<bool>,
1753 /// Private traits or trait items that leaked through. Don't check their methods.
1754 private_traits: HashSet<ast::NodeId>,
1758 pub fn new() -> MissingDoc {
1760 struct_def_stack: vec!(),
1762 doc_hidden_stack: vec!(false),
1763 private_traits: HashSet::new(),
1767 fn doc_hidden(&self) -> bool {
1768 *self.doc_hidden_stack.last().expect("empty doc_hidden_stack")
1771 fn check_missing_docs_attrs(&self,
1773 id: Option<ast::NodeId>,
1774 attrs: &[ast::Attribute],
1776 desc: &'static str) {
1777 // If we're building a test harness, then warning about
1778 // documentation is probably not really relevant right now.
1779 if cx.sess().opts.test {
1783 // `#[doc(hidden)]` disables missing_docs check.
1784 if self.doc_hidden() {
1788 // Only check publicly-visible items, using the result from the privacy pass.
1789 // It's an option so the crate root can also use this function (it doesn't
1791 if let Some(ref id) = id {
1792 if !cx.exported_items.contains(id) {
1797 let has_doc = attrs.iter().any(|a| {
1798 match a.node.value.node {
1799 ast::MetaNameValue(ref name, _) if *name == "doc" => true,
1804 cx.span_lint(MISSING_DOCS, sp,
1805 &format!("missing documentation for {}", desc));
1810 impl LintPass for MissingDoc {
1811 fn get_lints(&self) -> LintArray {
1812 lint_array!(MISSING_DOCS)
1815 fn enter_lint_attrs(&mut self, _: &Context, attrs: &[ast::Attribute]) {
1816 let doc_hidden = self.doc_hidden() || attrs.iter().any(|attr| {
1817 attr.check_name("doc") && match attr.meta_item_list() {
1819 Some(l) => attr::contains_name(&l[..], "hidden"),
1822 self.doc_hidden_stack.push(doc_hidden);
1825 fn exit_lint_attrs(&mut self, _: &Context, _: &[ast::Attribute]) {
1826 self.doc_hidden_stack.pop().expect("empty doc_hidden_stack");
1829 fn check_struct_def(&mut self, _: &Context, _: &ast::StructDef,
1830 _: ast::Ident, _: &ast::Generics, id: ast::NodeId) {
1831 self.struct_def_stack.push(id);
1834 fn check_struct_def_post(&mut self, _: &Context, _: &ast::StructDef,
1835 _: ast::Ident, _: &ast::Generics, id: ast::NodeId) {
1836 let popped = self.struct_def_stack.pop().expect("empty struct_def_stack");
1837 assert!(popped == id);
1840 fn check_crate(&mut self, cx: &Context, krate: &ast::Crate) {
1841 self.check_missing_docs_attrs(cx, None, &krate.attrs, krate.span, "crate");
1844 fn check_item(&mut self, cx: &Context, it: &ast::Item) {
1845 let desc = match it.node {
1846 ast::ItemFn(..) => "a function",
1847 ast::ItemMod(..) => "a module",
1848 ast::ItemEnum(..) => "an enum",
1849 ast::ItemStruct(..) => "a struct",
1850 ast::ItemTrait(_, _, _, ref items) => {
1851 // Issue #11592, traits are always considered exported, even when private.
1852 if it.vis == ast::Visibility::Inherited {
1853 self.private_traits.insert(it.id);
1855 self.private_traits.insert(itm.id);
1861 ast::ItemTy(..) => "a type alias",
1862 ast::ItemImpl(_, _, _, Some(ref trait_ref), _, ref impl_items) => {
1863 // If the trait is private, add the impl items to private_traits so they don't get
1864 // reported for missing docs.
1865 let real_trait = cx.tcx.trait_ref_to_def_id(trait_ref);
1866 match cx.tcx.map.find(real_trait.node) {
1867 Some(ast_map::NodeItem(item)) => if item.vis == ast::Visibility::Inherited {
1868 for itm in impl_items {
1869 self.private_traits.insert(itm.id);
1876 ast::ItemConst(..) => "a constant",
1877 ast::ItemStatic(..) => "a static",
1881 self.check_missing_docs_attrs(cx, Some(it.id), &it.attrs, it.span, desc);
1884 fn check_trait_item(&mut self, cx: &Context, trait_item: &ast::TraitItem) {
1885 if self.private_traits.contains(&trait_item.id) { return }
1887 let desc = match trait_item.node {
1888 ast::ConstTraitItem(..) => "an associated constant",
1889 ast::MethodTraitItem(..) => "a trait method",
1890 ast::TypeTraitItem(..) => "an associated type",
1893 self.check_missing_docs_attrs(cx, Some(trait_item.id),
1895 trait_item.span, desc);
1898 fn check_impl_item(&mut self, cx: &Context, impl_item: &ast::ImplItem) {
1899 // If the method is an impl for a trait, don't doc.
1900 if method_context(cx, impl_item.id, impl_item.span) == MethodContext::TraitImpl {
1904 let desc = match impl_item.node {
1905 ast::ConstImplItem(..) => "an associated constant",
1906 ast::MethodImplItem(..) => "a method",
1907 ast::TypeImplItem(_) => "an associated type",
1908 ast::MacImplItem(_) => "an impl item macro",
1910 self.check_missing_docs_attrs(cx, Some(impl_item.id),
1912 impl_item.span, desc);
1915 fn check_struct_field(&mut self, cx: &Context, sf: &ast::StructField) {
1916 if let ast::NamedField(_, vis) = sf.node.kind {
1917 if vis == ast::Public || self.in_variant {
1918 let cur_struct_def = *self.struct_def_stack.last()
1919 .expect("empty struct_def_stack");
1920 self.check_missing_docs_attrs(cx, Some(cur_struct_def),
1921 &sf.node.attrs, sf.span,
1927 fn check_variant(&mut self, cx: &Context, v: &ast::Variant, _: &ast::Generics) {
1928 self.check_missing_docs_attrs(cx, Some(v.node.id), &v.node.attrs, v.span, "a variant");
1929 assert!(!self.in_variant);
1930 self.in_variant = true;
1933 fn check_variant_post(&mut self, _: &Context, _: &ast::Variant, _: &ast::Generics) {
1934 assert!(self.in_variant);
1935 self.in_variant = false;
1940 pub MISSING_COPY_IMPLEMENTATIONS,
1942 "detects potentially-forgotten implementations of `Copy`"
1945 #[derive(Copy, Clone)]
1946 pub struct MissingCopyImplementations;
1948 impl LintPass for MissingCopyImplementations {
1949 fn get_lints(&self) -> LintArray {
1950 lint_array!(MISSING_COPY_IMPLEMENTATIONS)
1953 fn check_item(&mut self, cx: &Context, item: &ast::Item) {
1954 if !cx.exported_items.contains(&item.id) {
1957 let (def, ty) = match item.node {
1958 ast::ItemStruct(_, ref ast_generics) => {
1959 if ast_generics.is_parameterized() {
1962 let def = cx.tcx.lookup_adt_def(DefId::local(item.id));
1963 (def, cx.tcx.mk_struct(def,
1964 cx.tcx.mk_substs(Substs::empty())))
1966 ast::ItemEnum(_, ref ast_generics) => {
1967 if ast_generics.is_parameterized() {
1970 let def = cx.tcx.lookup_adt_def(DefId::local(item.id));
1971 (def, cx.tcx.mk_enum(def,
1972 cx.tcx.mk_substs(Substs::empty())))
1976 if def.has_dtor() { return; }
1977 let parameter_environment = cx.tcx.empty_parameter_environment();
1978 // FIXME (@jroesch) should probably inver this so that the parameter env still impls this
1980 if !ty.moves_by_default(¶meter_environment, item.span) {
1983 if parameter_environment.can_type_implement_copy(ty, item.span).is_ok() {
1984 cx.span_lint(MISSING_COPY_IMPLEMENTATIONS,
1986 "type could implement `Copy`; consider adding `impl \
1993 MISSING_DEBUG_IMPLEMENTATIONS,
1995 "detects missing implementations of fmt::Debug"
1998 pub struct MissingDebugImplementations {
1999 impling_types: Option<NodeSet>,
2002 impl MissingDebugImplementations {
2003 pub fn new() -> MissingDebugImplementations {
2004 MissingDebugImplementations {
2005 impling_types: None,
2010 impl LintPass for MissingDebugImplementations {
2011 fn get_lints(&self) -> LintArray {
2012 lint_array!(MISSING_DEBUG_IMPLEMENTATIONS)
2015 fn check_item(&mut self, cx: &Context, item: &ast::Item) {
2016 if !cx.exported_items.contains(&item.id) {
2021 ast::ItemStruct(..) | ast::ItemEnum(..) => {},
2025 let debug = match cx.tcx.lang_items.debug_trait() {
2026 Some(debug) => debug,
2030 if self.impling_types.is_none() {
2031 let debug_def = cx.tcx.lookup_trait_def(debug);
2032 let mut impls = NodeSet();
2033 debug_def.for_each_impl(cx.tcx, |d| {
2035 if let Some(ty_def) = cx.tcx.node_id_to_type(d.node).ty_to_def_id() {
2036 impls.insert(ty_def.node);
2041 self.impling_types = Some(impls);
2042 debug!("{:?}", self.impling_types);
2045 if !self.impling_types.as_ref().unwrap().contains(&item.id) {
2046 cx.span_lint(MISSING_DEBUG_IMPLEMENTATIONS,
2048 "type does not implement `fmt::Debug`; consider adding #[derive(Debug)] \
2049 or a manual implementation")
2057 "detects use of #[deprecated] items"
2060 /// Checks for use of items with `#[deprecated]` attributes
2061 #[derive(Copy, Clone)]
2062 pub struct Stability;
2065 fn lint(&self, cx: &Context, _id: DefId,
2066 span: Span, stability: &Option<&attr::Stability>) {
2067 // Deprecated attributes apply in-crate and cross-crate.
2068 let (lint, label) = match *stability {
2069 Some(&attr::Stability { deprecated_since: Some(_), .. }) =>
2070 (DEPRECATED, "deprecated"),
2074 output(cx, span, stability, lint, label);
2076 fn output(cx: &Context, span: Span, stability: &Option<&attr::Stability>,
2077 lint: &'static Lint, label: &'static str) {
2078 let msg = match *stability {
2079 Some(&attr::Stability { reason: Some(ref s), .. }) => {
2080 format!("use of {} item: {}", label, *s)
2082 _ => format!("use of {} item", label)
2085 cx.span_lint(lint, span, &msg[..]);
2090 impl LintPass for Stability {
2091 fn get_lints(&self) -> LintArray {
2092 lint_array!(DEPRECATED)
2095 fn check_item(&mut self, cx: &Context, item: &ast::Item) {
2096 stability::check_item(cx.tcx, item, false,
2097 &mut |id, sp, stab| self.lint(cx, id, sp, stab));
2100 fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
2101 stability::check_expr(cx.tcx, e,
2102 &mut |id, sp, stab| self.lint(cx, id, sp, stab));
2105 fn check_path(&mut self, cx: &Context, path: &ast::Path, id: ast::NodeId) {
2106 stability::check_path(cx.tcx, path, id,
2107 &mut |id, sp, stab| self.lint(cx, id, sp, stab));
2110 fn check_pat(&mut self, cx: &Context, pat: &ast::Pat) {
2111 stability::check_pat(cx.tcx, pat,
2112 &mut |id, sp, stab| self.lint(cx, id, sp, stab))
2117 pub UNCONDITIONAL_RECURSION,
2119 "functions that cannot return without calling themselves"
2122 #[derive(Copy, Clone)]
2123 pub struct UnconditionalRecursion;
2126 impl LintPass for UnconditionalRecursion {
2127 fn get_lints(&self) -> LintArray {
2128 lint_array![UNCONDITIONAL_RECURSION]
2131 fn check_fn(&mut self, cx: &Context, fn_kind: visit::FnKind, _: &ast::FnDecl,
2132 blk: &ast::Block, sp: Span, id: ast::NodeId) {
2133 type F = for<'tcx> fn(&ty::ctxt<'tcx>,
2134 ast::NodeId, ast::NodeId, ast::Ident, ast::NodeId) -> bool;
2136 let method = match fn_kind {
2137 visit::FkItemFn(..) => None,
2138 visit::FkMethod(..) => {
2139 cx.tcx.impl_or_trait_item(DefId::local(id)).as_opt_method()
2141 // closures can't recur, so they don't matter.
2142 visit::FkClosure => return
2145 // Walk through this function (say `f`) looking to see if
2146 // every possible path references itself, i.e. the function is
2147 // called recursively unconditionally. This is done by trying
2148 // to find a path from the entry node to the exit node that
2149 // *doesn't* call `f` by traversing from the entry while
2150 // pretending that calls of `f` are sinks (i.e. ignoring any
2151 // exit edges from them).
2153 // NB. this has an edge case with non-returning statements,
2154 // like `loop {}` or `panic!()`: control flow never reaches
2155 // the exit node through these, so one can have a function
2156 // that never actually calls itselfs but is still picked up by
2159 // fn f(cond: bool) {
2160 // if !cond { panic!() } // could come from `assert!(cond)`
2164 // In general, functions of that form may be able to call
2165 // itself a finite number of times and then diverge. The lint
2166 // considers this to be an error for two reasons, (a) it is
2167 // easier to implement, and (b) it seems rare to actually want
2168 // to have behaviour like the above, rather than
2169 // e.g. accidentally recurring after an assert.
2171 let cfg = cfg::CFG::new(cx.tcx, blk);
2173 let mut work_queue = vec![cfg.entry];
2174 let mut reached_exit_without_self_call = false;
2175 let mut self_call_spans = vec![];
2176 let mut visited = HashSet::new();
2178 while let Some(idx) = work_queue.pop() {
2179 if idx == cfg.exit {
2181 reached_exit_without_self_call = true;
2185 let cfg_id = idx.node_id();
2186 if visited.contains(&cfg_id) {
2190 visited.insert(cfg_id);
2192 let node_id = cfg.graph.node_data(idx).id();
2194 // is this a recursive call?
2195 let self_recursive = if node_id != ast::DUMMY_NODE_ID {
2197 Some(ref method) => {
2198 expr_refers_to_this_method(cx.tcx, method, node_id)
2200 None => expr_refers_to_this_fn(cx.tcx, id, node_id)
2206 self_call_spans.push(cx.tcx.map.span(node_id));
2207 // this is a self call, so we shouldn't explore past
2208 // this node in the CFG.
2211 // add the successors of this node to explore the graph further.
2212 for (_, edge) in cfg.graph.outgoing_edges(idx) {
2213 let target_idx = edge.target();
2214 let target_cfg_id = target_idx.node_id();
2215 if !visited.contains(&target_cfg_id) {
2216 work_queue.push(target_idx)
2221 // Check the number of self calls because a function that
2222 // doesn't return (e.g. calls a `-> !` function or `loop { /*
2223 // no break */ }`) shouldn't be linted unless it actually
2225 if !reached_exit_without_self_call && !self_call_spans.is_empty() {
2226 cx.span_lint(UNCONDITIONAL_RECURSION, sp,
2227 "function cannot return without recurring");
2229 // FIXME #19668: these could be span_lint_note's instead of this manual guard.
2230 if cx.current_level(UNCONDITIONAL_RECURSION) != Level::Allow {
2231 let sess = cx.sess();
2232 // offer some help to the programmer.
2233 for call in &self_call_spans {
2234 sess.span_note(*call, "recursive call site")
2236 sess.fileline_help(sp, "a `loop` may express intention \
2237 better if this is on purpose")
2244 // Functions for identifying if the given Expr NodeId `id`
2245 // represents a call to the function `fn_id`/method `method`.
2247 fn expr_refers_to_this_fn(tcx: &ty::ctxt,
2249 id: ast::NodeId) -> bool {
2250 match tcx.map.get(id) {
2251 ast_map::NodeExpr(&ast::Expr { node: ast::ExprCall(ref callee, _), .. }) => {
2252 tcx.def_map.borrow().get(&callee.id)
2253 .map_or(false, |def| def.def_id() == DefId::local(fn_id))
2259 // Check if the expression `id` performs a call to `method`.
2260 fn expr_refers_to_this_method(tcx: &ty::ctxt,
2261 method: &ty::Method,
2262 id: ast::NodeId) -> bool {
2263 let tables = tcx.tables.borrow();
2265 // Check for method calls and overloaded operators.
2266 if let Some(m) = tables.method_map.get(&ty::MethodCall::expr(id)) {
2267 if method_call_refers_to_method(tcx, method, m.def_id, m.substs, id) {
2272 // Check for overloaded autoderef method calls.
2273 if let Some(&ty::AdjustDerefRef(ref adj)) = tables.adjustments.get(&id) {
2274 for i in 0..adj.autoderefs {
2275 let method_call = ty::MethodCall::autoderef(id, i as u32);
2276 if let Some(m) = tables.method_map.get(&method_call) {
2277 if method_call_refers_to_method(tcx, method, m.def_id, m.substs, id) {
2284 // Check for calls to methods via explicit paths (e.g. `T::method()`).
2285 match tcx.map.get(id) {
2286 ast_map::NodeExpr(&ast::Expr { node: ast::ExprCall(ref callee, _), .. }) => {
2287 match tcx.def_map.borrow().get(&callee.id).map(|d| d.full_def()) {
2288 Some(def::DefMethod(def_id)) => {
2289 let no_substs = &ty::ItemSubsts::empty();
2290 let ts = tables.item_substs.get(&callee.id).unwrap_or(no_substs);
2291 method_call_refers_to_method(tcx, method, def_id, &ts.substs, id)
2300 // Check if the method call to the method with the ID `callee_id`
2301 // and instantiated with `callee_substs` refers to method `method`.
2302 fn method_call_refers_to_method<'tcx>(tcx: &ty::ctxt<'tcx>,
2303 method: &ty::Method,
2305 callee_substs: &Substs<'tcx>,
2306 expr_id: ast::NodeId) -> bool {
2307 let callee_item = tcx.impl_or_trait_item(callee_id);
2309 match callee_item.container() {
2310 // This is an inherent method, so the `def_id` refers
2311 // directly to the method definition.
2312 ty::ImplContainer(_) => {
2313 callee_id == method.def_id
2316 // A trait method, from any number of possible sources.
2317 // Attempt to select a concrete impl before checking.
2318 ty::TraitContainer(trait_def_id) => {
2319 let trait_substs = callee_substs.clone().method_to_trait();
2320 let trait_substs = tcx.mk_substs(trait_substs);
2321 let trait_ref = ty::TraitRef::new(trait_def_id, trait_substs);
2322 let trait_ref = ty::Binder(trait_ref);
2323 let span = tcx.map.span(expr_id);
2325 traits::Obligation::new(traits::ObligationCause::misc(span, expr_id),
2326 trait_ref.to_poly_trait_predicate());
2328 let param_env = ty::ParameterEnvironment::for_item(tcx, method.def_id.node);
2329 let infcx = infer::new_infer_ctxt(tcx, &tcx.tables, Some(param_env), false);
2330 let mut selcx = traits::SelectionContext::new(&infcx);
2331 match selcx.select(&obligation) {
2332 // The method comes from a `T: Trait` bound.
2333 // If `T` is `Self`, then this call is inside
2334 // a default method definition.
2335 Ok(Some(traits::VtableParam(_))) => {
2336 let self_ty = callee_substs.self_ty();
2337 let on_self = self_ty.map_or(false, |t| t.is_self());
2338 // We can only be recurring in a default
2339 // method if we're being called literally
2340 // on the `Self` type.
2341 on_self && callee_id == method.def_id
2344 // The `impl` is known, so we check that with a
2346 Ok(Some(traits::VtableImpl(vtable_impl))) => {
2347 let container = ty::ImplContainer(vtable_impl.impl_def_id);
2348 // It matches if it comes from the same impl,
2349 // and has the same method name.
2350 container == method.container
2351 && callee_item.name() == method.name
2354 // There's no way to know if this call is
2355 // recursive, so we assume it's not.
2367 "compiler plugin used as ordinary library in non-plugin crate"
2370 #[derive(Copy, Clone)]
2371 pub struct PluginAsLibrary;
2373 impl LintPass for PluginAsLibrary {
2374 fn get_lints(&self) -> LintArray {
2375 lint_array![PLUGIN_AS_LIBRARY]
2378 fn check_item(&mut self, cx: &Context, it: &ast::Item) {
2379 if cx.sess().plugin_registrar_fn.get().is_some() {
2380 // We're compiling a plugin; it's fine to link other plugins.
2385 ast::ItemExternCrate(..) => (),
2389 let md = match cx.sess().cstore.find_extern_mod_stmt_cnum(it.id) {
2390 Some(cnum) => cx.sess().cstore.get_crate_data(cnum),
2392 // Probably means we aren't linking the crate for some reason.
2394 // Not sure if / when this could happen.
2399 if decoder::get_plugin_registrar_fn(md.data()).is_some() {
2400 cx.span_lint(PLUGIN_AS_LIBRARY, it.span,
2401 "compiler plugin used as an ordinary library");
2407 PRIVATE_NO_MANGLE_FNS,
2409 "functions marked #[no_mangle] should be exported"
2413 PRIVATE_NO_MANGLE_STATICS,
2415 "statics marked #[no_mangle] should be exported"
2419 NO_MANGLE_CONST_ITEMS,
2421 "const items will not have their symbols exported"
2424 #[derive(Copy, Clone)]
2425 pub struct InvalidNoMangleItems;
2427 impl LintPass for InvalidNoMangleItems {
2428 fn get_lints(&self) -> LintArray {
2429 lint_array!(PRIVATE_NO_MANGLE_FNS,
2430 PRIVATE_NO_MANGLE_STATICS,
2431 NO_MANGLE_CONST_ITEMS)
2434 fn check_item(&mut self, cx: &Context, it: &ast::Item) {
2436 ast::ItemFn(..) => {
2437 if attr::contains_name(&it.attrs, "no_mangle") &&
2438 !cx.exported_items.contains(&it.id) {
2439 let msg = format!("function {} is marked #[no_mangle], but not exported",
2441 cx.span_lint(PRIVATE_NO_MANGLE_FNS, it.span, &msg);
2444 ast::ItemStatic(..) => {
2445 if attr::contains_name(&it.attrs, "no_mangle") &&
2446 !cx.exported_items.contains(&it.id) {
2447 let msg = format!("static {} is marked #[no_mangle], but not exported",
2449 cx.span_lint(PRIVATE_NO_MANGLE_STATICS, it.span, &msg);
2452 ast::ItemConst(..) => {
2453 if attr::contains_name(&it.attrs, "no_mangle") {
2454 // Const items do not refer to a particular location in memory, and therefore
2455 // don't have anything to attach a symbol to
2456 let msg = "const items should never be #[no_mangle], consider instead using \
2458 cx.span_lint(NO_MANGLE_CONST_ITEMS, it.span, msg);
2466 #[derive(Clone, Copy)]
2467 pub struct MutableTransmutes;
2472 "mutating transmuted &mut T from &T may cause undefined behavior"
2475 impl LintPass for MutableTransmutes {
2476 fn get_lints(&self) -> LintArray {
2477 lint_array!(MUTABLE_TRANSMUTES)
2480 fn check_expr(&mut self, cx: &Context, expr: &ast::Expr) {
2481 use syntax::abi::RustIntrinsic;
2482 let msg = "mutating transmuted &mut T from &T may cause undefined behavior,\
2483 consider instead using an UnsafeCell";
2484 match get_transmute_from_to(cx, expr) {
2485 Some((&ty::TyRef(_, from_mt), &ty::TyRef(_, to_mt))) => {
2486 if to_mt.mutbl == ast::Mutability::MutMutable
2487 && from_mt.mutbl == ast::Mutability::MutImmutable {
2488 cx.span_lint(MUTABLE_TRANSMUTES, expr.span, msg);
2494 fn get_transmute_from_to<'a, 'tcx>(cx: &Context<'a, 'tcx>, expr: &ast::Expr)
2495 -> Option<(&'tcx ty::TypeVariants<'tcx>, &'tcx ty::TypeVariants<'tcx>)> {
2497 ast::ExprPath(..) => (),
2500 if let def::DefFn(did, _) = cx.tcx.resolve_expr(expr) {
2501 if !def_id_is_transmute(cx, did) {
2504 let typ = cx.tcx.node_id_to_type(expr.id);
2506 ty::TyBareFn(_, ref bare_fn) if bare_fn.abi == RustIntrinsic => {
2507 if let ty::FnConverging(to) = bare_fn.sig.0.output {
2508 let from = bare_fn.sig.0.inputs[0];
2509 return Some((&from.sty, &to.sty));
2518 fn def_id_is_transmute(cx: &Context, def_id: DefId) -> bool {
2519 match cx.tcx.lookup_item_type(def_id).ty.sty {
2520 ty::TyBareFn(_, ref bfty) if bfty.abi == RustIntrinsic => (),
2523 cx.tcx.with_path(def_id, |path| match path.last() {
2524 Some(ref last) => last.name().as_str() == "transmute",
2531 /// Forbids using the `#[feature(...)]` attribute
2532 #[derive(Copy, Clone)]
2533 pub struct UnstableFeatures;
2538 "enabling unstable features (deprecated. do not use)"
2541 impl LintPass for UnstableFeatures {
2542 fn get_lints(&self) -> LintArray {
2543 lint_array!(UNSTABLE_FEATURES)
2545 fn check_attribute(&mut self, ctx: &Context, attr: &ast::Attribute) {
2546 if attr::contains_name(&[attr.node.value.clone()], "feature") {
2547 if let Some(items) = attr.node.value.meta_item_list() {
2549 ctx.span_lint(UNSTABLE_FEATURES, item.span, "unstable feature");
2556 /// Lints for attempts to impl Drop on types that have `#[repr(C)]`
2557 /// attribute (see issue #24585).
2558 #[derive(Copy, Clone)]
2559 pub struct DropWithReprExtern;
2562 DROP_WITH_REPR_EXTERN,
2564 "use of #[repr(C)] on a type that implements Drop"
2567 impl LintPass for DropWithReprExtern {
2568 fn get_lints(&self) -> LintArray {
2569 lint_array!(DROP_WITH_REPR_EXTERN)
2571 fn check_crate(&mut self, ctx: &Context, _: &ast::Crate) {
2572 for dtor_did in ctx.tcx.destructors.borrow().iter() {
2573 let (drop_impl_did, dtor_self_type) =
2574 if dtor_did.is_local() {
2575 let impl_did = ctx.tcx.map.get_parent_did(dtor_did.node);
2576 let ty = ctx.tcx.lookup_item_type(impl_did).ty;
2582 match dtor_self_type.sty {
2583 ty::TyEnum(self_type_def, _) |
2584 ty::TyStruct(self_type_def, _) => {
2585 let self_type_did = self_type_def.did;
2586 let hints = ctx.tcx.lookup_repr_hints(self_type_did);
2587 if hints.iter().any(|attr| *attr == attr::ReprExtern) &&
2588 self_type_def.dtor_kind().has_drop_flag() {
2589 let drop_impl_span = ctx.tcx.map.def_id_span(drop_impl_did,
2591 let self_defn_span = ctx.tcx.map.def_id_span(self_type_did,
2593 ctx.span_lint(DROP_WITH_REPR_EXTERN,
2595 "implementing Drop adds hidden state to types, \
2596 possibly conflicting with `#[repr(C)]`");
2597 // FIXME #19668: could be span_lint_note instead of manual guard.
2598 if ctx.current_level(DROP_WITH_REPR_EXTERN) != Level::Allow {
2599 ctx.sess().span_note(self_defn_span,
2600 "the `#[repr(C)]` attribute is attached here");