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 #![allow(non_snake_case)]
13 use rustc::hir::def_id::DefId;
14 use rustc::ty::subst::Substs;
15 use rustc::ty::{self, Ty, TyCtxt};
16 use rustc::ty::layout::{Layout, Primitive};
17 use rustc::traits::ProjectionMode;
18 use middle::const_val::ConstVal;
19 use rustc_const_eval::eval_const_expr_partial;
20 use rustc_const_eval::EvalHint::ExprTypeChecked;
21 use util::common::slice_pat;
22 use util::nodemap::{FnvHashSet};
23 use lint::{LateContext, LintContext, LintArray};
24 use lint::{LintPass, LateLintPass};
27 use std::{i8, i16, i32, i64, u8, u16, u32, u64, f32, f64};
37 register_long_diagnostics! {
39 It is not allowed to negate an unsigned integer.
40 You can negate a signed integer and cast it to an
41 unsigned integer or use the `!` operator.
44 let x: usize = -1isize as usize;
49 Alternatively you can use the `Wrapping` newtype
50 or the `wrapping_neg` operation that all
51 integral types support:
54 use std::num::Wrapping;
55 let x: Wrapping<usize> = -Wrapping(1);
57 let y: usize = 1.wrapping_neg();
67 "comparisons made useless by limits of the types involved"
73 "literal out of range for its type"
79 "shift exceeds the type's number of bits"
83 VARIANT_SIZE_DIFFERENCES,
85 "detects enums with widely varying variant sizes"
88 #[derive(Copy, Clone)]
89 pub struct TypeLimits {
90 /// Id of the last visited negated expression
91 negated_expr_id: ast::NodeId,
95 pub fn new() -> TypeLimits {
102 impl LintPass for TypeLimits {
103 fn get_lints(&self) -> LintArray {
104 lint_array!(UNUSED_COMPARISONS, OVERFLOWING_LITERALS, EXCEEDING_BITSHIFTS)
108 impl LateLintPass for TypeLimits {
109 fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) {
111 hir::ExprUnary(hir::UnNeg, ref expr) => {
112 if let hir::ExprLit(ref lit) = expr.node {
114 ast::LitKind::Int(_, ast::LitIntType::Unsigned(_)) => {
115 forbid_unsigned_negation(cx, e.span);
117 ast::LitKind::Int(_, ast::LitIntType::Unsuffixed) => {
118 if let ty::TyUint(_) = cx.tcx.node_id_to_type(e.id).sty {
119 forbid_unsigned_negation(cx, e.span);
125 let t = cx.tcx.node_id_to_type(expr.id);
126 if let ty::TyUint(_) = t.sty {
127 forbid_unsigned_negation(cx, e.span);
130 // propagate negation, if the negation itself isn't negated
131 if self.negated_expr_id != e.id {
132 self.negated_expr_id = expr.id;
135 hir::ExprBinary(binop, ref l, ref r) => {
136 if is_comparison(binop) && !check_limits(cx.tcx, binop, &l, &r) {
137 cx.span_lint(UNUSED_COMPARISONS, e.span,
138 "comparison is useless due to type limits");
141 if binop.node.is_shift() {
142 let opt_ty_bits = match cx.tcx.node_id_to_type(l.id).sty {
143 ty::TyInt(t) => Some(int_ty_bits(t, cx.sess().target.int_type)),
144 ty::TyUint(t) => Some(uint_ty_bits(t, cx.sess().target.uint_type)),
148 if let Some(bits) = opt_ty_bits {
149 let exceeding = if let hir::ExprLit(ref lit) = r.node {
150 if let ast::LitKind::Int(shift, _) = lit.node { shift >= bits }
153 match eval_const_expr_partial(cx.tcx, &r, ExprTypeChecked, None) {
154 Ok(ConstVal::Integral(i)) => {
155 i.is_negative() || i.to_u64()
163 cx.span_lint(EXCEEDING_BITSHIFTS, e.span,
164 "bitshift exceeds the type's number of bits");
169 hir::ExprLit(ref lit) => {
170 match cx.tcx.node_id_to_type(e.id).sty {
173 ast::LitKind::Int(v, ast::LitIntType::Signed(_)) |
174 ast::LitKind::Int(v, ast::LitIntType::Unsuffixed) => {
175 let int_type = if let ast::IntTy::Is = t {
176 cx.sess().target.int_type
180 let (_, max) = int_ty_range(int_type);
181 let negative = self.negated_expr_id == e.id;
183 // Detect literal value out of range [min, max] inclusive
184 // avoiding use of -min to prevent overflow/panic
185 if (negative && v > max as u64 + 1) ||
186 (!negative && v > max as u64) {
187 cx.span_lint(OVERFLOWING_LITERALS, e.span,
188 &format!("literal out of range for {:?}", t));
196 let uint_type = if let ast::UintTy::Us = t {
197 cx.sess().target.uint_type
201 let (min, max) = uint_ty_range(uint_type);
202 let lit_val: u64 = match lit.node {
203 // _v is u8, within range by definition
204 ast::LitKind::Byte(_v) => return,
205 ast::LitKind::Int(v, _) => v,
208 if lit_val < min || lit_val > max {
209 cx.span_lint(OVERFLOWING_LITERALS, e.span,
210 &format!("literal out of range for {:?}", t));
214 let (min, max) = float_ty_range(t);
215 let lit_val: f64 = match lit.node {
216 ast::LitKind::Float(ref v, _) |
217 ast::LitKind::FloatUnsuffixed(ref v) => {
225 if lit_val < min || lit_val > max {
226 cx.span_lint(OVERFLOWING_LITERALS, e.span,
227 &format!("literal out of range for {:?}", t));
236 fn is_valid<T:cmp::PartialOrd>(binop: hir::BinOp, v: T,
237 min: T, max: T) -> bool {
239 hir::BiLt => v > min && v <= max,
240 hir::BiLe => v >= min && v < max,
241 hir::BiGt => v >= min && v < max,
242 hir::BiGe => v > min && v <= max,
243 hir::BiEq | hir::BiNe => v >= min && v <= max,
248 fn rev_binop(binop: hir::BinOp) -> hir::BinOp {
249 codemap::respan(binop.span, match binop.node {
250 hir::BiLt => hir::BiGt,
251 hir::BiLe => hir::BiGe,
252 hir::BiGt => hir::BiLt,
253 hir::BiGe => hir::BiLe,
258 // for isize & usize, be conservative with the warnings, so that the
259 // warnings are consistent between 32- and 64-bit platforms
260 fn int_ty_range(int_ty: ast::IntTy) -> (i64, i64) {
262 ast::IntTy::Is => (i64::MIN, i64::MAX),
263 ast::IntTy::I8 => (i8::MIN as i64, i8::MAX as i64),
264 ast::IntTy::I16 => (i16::MIN as i64, i16::MAX as i64),
265 ast::IntTy::I32 => (i32::MIN as i64, i32::MAX as i64),
266 ast::IntTy::I64 => (i64::MIN, i64::MAX)
270 fn uint_ty_range(uint_ty: ast::UintTy) -> (u64, u64) {
272 ast::UintTy::Us => (u64::MIN, u64::MAX),
273 ast::UintTy::U8 => (u8::MIN as u64, u8::MAX as u64),
274 ast::UintTy::U16 => (u16::MIN as u64, u16::MAX as u64),
275 ast::UintTy::U32 => (u32::MIN as u64, u32::MAX as u64),
276 ast::UintTy::U64 => (u64::MIN, u64::MAX)
280 fn float_ty_range(float_ty: ast::FloatTy) -> (f64, f64) {
282 ast::FloatTy::F32 => (f32::MIN as f64, f32::MAX as f64),
283 ast::FloatTy::F64 => (f64::MIN, f64::MAX)
287 fn int_ty_bits(int_ty: ast::IntTy, target_int_ty: ast::IntTy) -> u64 {
289 ast::IntTy::Is => int_ty_bits(target_int_ty, target_int_ty),
291 ast::IntTy::I16 => 16 as u64,
292 ast::IntTy::I32 => 32,
293 ast::IntTy::I64 => 64,
297 fn uint_ty_bits(uint_ty: ast::UintTy, target_uint_ty: ast::UintTy) -> u64 {
299 ast::UintTy::Us => uint_ty_bits(target_uint_ty, target_uint_ty),
300 ast::UintTy::U8 => 8,
301 ast::UintTy::U16 => 16,
302 ast::UintTy::U32 => 32,
303 ast::UintTy::U64 => 64,
307 fn check_limits<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
310 r: &hir::Expr) -> bool {
311 let (lit, expr, swap) = match (&l.node, &r.node) {
312 (&hir::ExprLit(_), _) => (l, r, true),
313 (_, &hir::ExprLit(_)) => (r, l, false),
316 // Normalize the binop so that the literal is always on the RHS in
318 let norm_binop = if swap {
323 match tcx.node_id_to_type(expr.id).sty {
324 ty::TyInt(int_ty) => {
325 let (min, max) = int_ty_range(int_ty);
326 let lit_val: i64 = match lit.node {
327 hir::ExprLit(ref li) => match li.node {
328 ast::LitKind::Int(v, ast::LitIntType::Signed(_)) |
329 ast::LitKind::Int(v, ast::LitIntType::Unsuffixed) => v as i64,
334 is_valid(norm_binop, lit_val, min, max)
336 ty::TyUint(uint_ty) => {
337 let (min, max): (u64, u64) = uint_ty_range(uint_ty);
338 let lit_val: u64 = match lit.node {
339 hir::ExprLit(ref li) => match li.node {
340 ast::LitKind::Int(v, _) => v,
345 is_valid(norm_binop, lit_val, min, max)
351 fn is_comparison(binop: hir::BinOp) -> bool {
353 hir::BiEq | hir::BiLt | hir::BiLe |
354 hir::BiNe | hir::BiGe | hir::BiGt => true,
359 fn forbid_unsigned_negation(cx: &LateContext, span: Span) {
361 .struct_span_err_with_code(span, "unary negation of unsigned integer", "E0519")
362 .span_help(span, "use a cast or the `!` operator")
371 "proper use of libc types in foreign modules"
374 struct ImproperCTypesVisitor<'a, 'tcx: 'a> {
375 cx: &'a LateContext<'a, 'tcx>
380 FfiUnsafe(&'static str),
381 FfiBadStruct(DefId, &'static str),
382 FfiBadEnum(DefId, &'static str)
385 /// Check if this enum can be safely exported based on the
386 /// "nullable pointer optimization". Currently restricted
387 /// to function pointers and references, but could be
388 /// expanded to cover NonZero raw pointers and newtypes.
389 /// FIXME: This duplicates code in trans.
390 fn is_repr_nullable_ptr<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
391 def: ty::AdtDef<'tcx>,
392 substs: &Substs<'tcx>)
394 if def.variants.len() == 2 {
397 if def.variants[0].fields.is_empty() {
399 } else if def.variants[1].fields.is_empty() {
405 if def.variants[data_idx].fields.len() == 1 {
406 match def.variants[data_idx].fields[0].ty(tcx, substs).sty {
407 ty::TyFnPtr(_) => { return true; }
408 ty::TyRef(..) => { return true; }
416 impl<'a, 'tcx> ImproperCTypesVisitor<'a, 'tcx> {
417 /// Check if the given type is "ffi-safe" (has a stable, well-defined
418 /// representation which can be exported to C code).
419 fn check_type_for_ffi(&self,
420 cache: &mut FnvHashSet<Ty<'tcx>>,
423 use self::FfiResult::*;
424 let cx = self.cx.tcx;
426 // Protect against infinite recursion, for example
427 // `struct S(*mut S);`.
428 // FIXME: A recursion limit is necessary as well, for irregular
430 if !cache.insert(ty) {
435 ty::TyStruct(def, substs) => {
436 if !cx.lookup_repr_hints(def.did).contains(&attr::ReprExtern) {
438 "found struct without foreign-function-safe \
439 representation annotation in foreign module, \
440 consider adding a #[repr(C)] attribute to \
444 // We can't completely trust repr(C) markings; make sure the
445 // fields are actually safe.
446 if def.struct_variant().fields.is_empty() {
448 "found zero-size struct in foreign module, consider \
449 adding a member to this struct");
452 for field in &def.struct_variant().fields {
453 let field_ty = cx.normalize_associated_type(&field.ty(cx, substs));
454 let r = self.check_type_for_ffi(cache, field_ty);
457 FfiBadStruct(..) | FfiBadEnum(..) => { return r; }
458 FfiUnsafe(s) => { return FfiBadStruct(def.did, s); }
463 ty::TyEnum(def, substs) => {
464 if def.variants.is_empty() {
465 // Empty enums are okay... although sort of useless.
469 // Check for a repr() attribute to specify the size of the
471 let repr_hints = cx.lookup_repr_hints(def.did);
472 match slice_pat(&&**repr_hints) {
474 // Special-case types like `Option<extern fn()>`.
475 if !is_repr_nullable_ptr(cx, def, substs) {
477 "found enum without foreign-function-safe \
478 representation annotation in foreign module, \
479 consider adding a #[repr(...)] attribute to \
484 if !hint.is_ffi_safe() {
485 // FIXME: This shouldn't be reachable: we should check
488 "enum has unexpected #[repr(...)] attribute")
491 // Enum with an explicitly sized discriminant; either
492 // a C-style enum or a discriminated union.
494 // The layout of enum variants is implicitly repr(C).
495 // FIXME: Is that correct?
498 // FIXME: This shouldn't be reachable: we should check
501 "enum has too many #[repr(...)] attributes");
505 // Check the contained variants.
506 for variant in &def.variants {
507 for field in &variant.fields {
508 let arg = cx.normalize_associated_type(&field.ty(cx, substs));
509 let r = self.check_type_for_ffi(cache, arg);
512 FfiBadStruct(..) | FfiBadEnum(..) => { return r; }
513 FfiUnsafe(s) => { return FfiBadEnum(def.did, s); }
521 FfiUnsafe("found Rust type `char` in foreign module, while \
522 `u32` or `libc::wchar_t` should be used")
525 // Primitive types with a stable representation.
526 ty::TyBool | ty::TyInt(..) | ty::TyUint(..) |
527 ty::TyFloat(..) => FfiSafe,
530 FfiUnsafe("found Rust type Box<_> in foreign module, \
531 consider using a raw pointer instead")
535 FfiUnsafe("found Rust slice type in foreign module, \
536 consider using a raw pointer instead")
540 FfiUnsafe("found Rust trait type in foreign module, \
541 consider using a raw pointer instead")
545 FfiUnsafe("found Rust type `str` in foreign module; \
546 consider using a `*const libc::c_char`")
550 FfiUnsafe("found Rust tuple type in foreign module; \
551 consider using a struct instead`")
554 ty::TyRawPtr(ref m) | ty::TyRef(_, ref m) => {
555 self.check_type_for_ffi(cache, m.ty)
558 ty::TyArray(ty, _) => {
559 self.check_type_for_ffi(cache, ty)
562 ty::TyFnPtr(bare_fn) => {
566 Abi::PlatformIntrinsic |
569 "found function pointer with Rust calling \
570 convention in foreign module; consider using an \
571 `extern` function pointer")
576 let sig = cx.erase_late_bound_regions(&bare_fn.sig);
578 ty::FnDiverging => {}
579 ty::FnConverging(output) => {
580 if !output.is_nil() {
581 let r = self.check_type_for_ffi(cache, output);
589 for arg in sig.inputs {
590 let r = self.check_type_for_ffi(cache, arg);
599 ty::TyParam(..) | ty::TyInfer(..) | ty::TyError |
600 ty::TyClosure(..) | ty::TyProjection(..) |
602 bug!("Unexpected type in foreign function")
607 fn check_type_for_ffi_and_report_errors(&mut self, sp: Span, ty: Ty<'tcx>) {
608 // it is only OK to use this function because extern fns cannot have
609 // any generic types right now:
610 let ty = self.cx.tcx.normalize_associated_type(&ty);
612 match self.check_type_for_ffi(&mut FnvHashSet(), ty) {
613 FfiResult::FfiSafe => {}
614 FfiResult::FfiUnsafe(s) => {
615 self.cx.span_lint(IMPROPER_CTYPES, sp, s);
617 FfiResult::FfiBadStruct(_, s) => {
618 // FIXME: This diagnostic is difficult to read, and doesn't
619 // point at the relevant field.
620 self.cx.span_lint(IMPROPER_CTYPES, sp,
621 &format!("found non-foreign-function-safe member in \
622 struct marked #[repr(C)]: {}", s));
624 FfiResult::FfiBadEnum(_, s) => {
625 // FIXME: This diagnostic is difficult to read, and doesn't
626 // point at the relevant variant.
627 self.cx.span_lint(IMPROPER_CTYPES, sp,
628 &format!("found non-foreign-function-safe member in \
634 fn check_foreign_fn(&mut self, id: ast::NodeId, decl: &hir::FnDecl) {
635 let def_id = self.cx.tcx.map.local_def_id(id);
636 let scheme = self.cx.tcx.lookup_item_type(def_id);
637 let sig = scheme.ty.fn_sig();
638 let sig = self.cx.tcx.erase_late_bound_regions(&sig);
640 for (&input_ty, input_hir) in sig.inputs.iter().zip(&decl.inputs) {
641 self.check_type_for_ffi_and_report_errors(input_hir.ty.span, &input_ty);
644 if let hir::Return(ref ret_hir) = decl.output {
645 let ret_ty = sig.output.unwrap();
646 if !ret_ty.is_nil() {
647 self.check_type_for_ffi_and_report_errors(ret_hir.span, ret_ty);
652 fn check_foreign_static(&mut self, id: ast::NodeId, span: Span) {
653 let def_id = self.cx.tcx.map.local_def_id(id);
654 let scheme = self.cx.tcx.lookup_item_type(def_id);
655 self.check_type_for_ffi_and_report_errors(span, scheme.ty);
659 #[derive(Copy, Clone)]
660 pub struct ImproperCTypes;
662 impl LintPass for ImproperCTypes {
663 fn get_lints(&self) -> LintArray {
664 lint_array!(IMPROPER_CTYPES)
668 impl LateLintPass for ImproperCTypes {
669 fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
670 let mut vis = ImproperCTypesVisitor { cx: cx };
671 if let hir::ItemForeignMod(ref nmod) = it.node {
672 if nmod.abi != Abi::RustIntrinsic && nmod.abi != Abi::PlatformIntrinsic {
673 for ni in &nmod.items {
675 hir::ForeignItemFn(ref decl, _) => {
676 vis.check_foreign_fn(ni.id, decl);
678 hir::ForeignItemStatic(ref ty, _) => {
679 vis.check_foreign_static(ni.id, ty.span);
688 pub struct VariantSizeDifferences;
690 impl LintPass for VariantSizeDifferences {
691 fn get_lints(&self) -> LintArray {
692 lint_array!(VARIANT_SIZE_DIFFERENCES)
696 impl LateLintPass for VariantSizeDifferences {
697 fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
698 if let hir::ItemEnum(ref enum_definition, ref gens) = it.node {
699 if gens.ty_params.is_empty() { // sizes only make sense for non-generic types
700 let mut sizes = vec![];
701 let t = cx.tcx.node_id_to_type(it.id);
702 let layout = cx.tcx.normalizing_infer_ctxt(ProjectionMode::Any).enter(|infcx| {
703 t.layout(&infcx).unwrap_or_else(|e| {
704 bug!("failed to get layout for `{}`: {}", t, e)
708 if let Layout::General { ref variants, ref size, discr, .. } = *layout {
709 let discr_size = Primitive::Int(discr).size(&cx.tcx.data_layout).bytes();
711 debug!("enum `{}` is {} bytes large", t, size.bytes());
713 for (variant, variant_layout) in enum_definition.variants.iter().zip(variants) {
714 // Subtract the size of the enum discriminant
715 let bytes = variant_layout.min_size().bytes().saturating_sub(discr_size);
718 debug!("- variant `{}` is {} bytes large", variant.node.name, bytes);
721 let (largest, slargest, largest_index) = sizes.iter()
724 |(l, s, li), (idx, &size)|
734 // we only warn if the largest variant is at least thrice as large as
735 // the second-largest.
736 if largest > slargest * 3 && slargest > 0 {
737 cx.span_lint(VARIANT_SIZE_DIFFERENCES,
738 enum_definition.variants[largest_index].span,
739 &format!("enum variant is more than three times larger \
740 ({} bytes) than the next largest", largest));