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)]
14 use rustc::ty::subst::Substs;
15 use rustc::ty::{self, AdtKind, ParamEnv, Ty, TyCtxt};
16 use rustc::ty::layout::{self, IntegerExt, LayoutOf};
17 use util::nodemap::FxHashSet;
18 use lint::{LateContext, LintContext, LintArray};
19 use lint::{LintPass, LateLintPass};
22 use std::{i8, i16, i32, i64, u8, u16, u32, u64, f32, f64};
24 use syntax::{ast, attr};
25 use syntax::errors::Applicability;
26 use rustc_target::spec::abi::Abi;
27 use syntax::edition::Edition;
29 use syntax::source_map;
36 "comparisons made useless by limits of the types involved"
42 "literal out of range for its type",
43 Edition::Edition2018 => Deny
47 VARIANT_SIZE_DIFFERENCES,
49 "detects enums with widely varying variant sizes"
52 #[derive(Copy, Clone)]
53 pub struct TypeLimits {
54 /// Id of the last visited negated expression
55 negated_expr_id: ast::NodeId,
59 pub fn new() -> TypeLimits {
60 TypeLimits { negated_expr_id: ast::DUMMY_NODE_ID }
64 impl LintPass for TypeLimits {
65 fn get_lints(&self) -> LintArray {
66 lint_array!(UNUSED_COMPARISONS,
71 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TypeLimits {
72 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx hir::Expr) {
74 hir::ExprKind::Unary(hir::UnNeg, ref expr) => {
75 // propagate negation, if the negation itself isn't negated
76 if self.negated_expr_id != e.id {
77 self.negated_expr_id = expr.id;
80 hir::ExprKind::Binary(binop, ref l, ref r) => {
81 if is_comparison(binop) && !check_limits(cx, binop, &l, &r) {
82 cx.span_lint(UNUSED_COMPARISONS,
84 "comparison is useless due to type limits");
87 hir::ExprKind::Lit(ref lit) => {
88 match cx.tables.node_id_to_type(e.hir_id).sty {
91 ast::LitKind::Int(v, ast::LitIntType::Signed(_)) |
92 ast::LitKind::Int(v, ast::LitIntType::Unsuffixed) => {
93 let int_type = if let ast::IntTy::Isize = t {
94 cx.sess().target.isize_ty
98 let (_, max) = int_ty_range(int_type);
99 let max = max as u128;
100 let negative = self.negated_expr_id == e.id;
102 // Detect literal value out of range [min, max] inclusive
103 // avoiding use of -min to prevent overflow/panic
104 if (negative && v > max + 1) || (!negative && v > max) {
105 if let Some(repr_str) = get_bin_hex_repr(cx, lit) {
106 report_bin_hex_error(
117 OVERFLOWING_LITERALS,
119 &format!("literal out of range for {:?}", t),
128 let uint_type = if let ast::UintTy::Usize = t {
129 cx.sess().target.usize_ty
133 let (min, max) = uint_ty_range(uint_type);
134 let lit_val: u128 = match lit.node {
135 // _v is u8, within range by definition
136 ast::LitKind::Byte(_v) => return,
137 ast::LitKind::Int(v, _) => v,
140 if lit_val < min || lit_val > max {
141 let parent_id = cx.tcx.hir.get_parent_node(e.id);
142 if let Node::Expr(parent_expr) = cx.tcx.hir.get(parent_id) {
143 if let hir::ExprKind::Cast(..) = parent_expr.node {
144 if let ty::Char = cx.tables.expr_ty(parent_expr).sty {
145 let mut err = cx.struct_span_lint(
146 OVERFLOWING_LITERALS,
148 "only u8 can be cast into char");
149 err.span_suggestion_with_applicability(
151 &"use a char literal instead",
152 format!("'\\u{{{:X}}}'", lit_val),
153 Applicability::MachineApplicable
160 if let Some(repr_str) = get_bin_hex_repr(cx, lit) {
161 report_bin_hex_error(
172 OVERFLOWING_LITERALS,
174 &format!("literal out of range for {:?}", t),
179 let is_infinite = match lit.node {
180 ast::LitKind::Float(v, _) |
181 ast::LitKind::FloatUnsuffixed(v) => {
183 ast::FloatTy::F32 => v.as_str().parse().map(f32::is_infinite),
184 ast::FloatTy::F64 => v.as_str().parse().map(f64::is_infinite),
189 if is_infinite == Ok(true) {
190 cx.span_lint(OVERFLOWING_LITERALS,
192 &format!("literal out of range for {:?}", t));
201 fn is_valid<T: cmp::PartialOrd>(binop: hir::BinOp, v: T, min: T, max: T) -> bool {
203 hir::BinOpKind::Lt => v > min && v <= max,
204 hir::BinOpKind::Le => v >= min && v < max,
205 hir::BinOpKind::Gt => v >= min && v < max,
206 hir::BinOpKind::Ge => v > min && v <= max,
207 hir::BinOpKind::Eq | hir::BinOpKind::Ne => v >= min && v <= max,
212 fn rev_binop(binop: hir::BinOp) -> hir::BinOp {
213 source_map::respan(binop.span,
215 hir::BinOpKind::Lt => hir::BinOpKind::Gt,
216 hir::BinOpKind::Le => hir::BinOpKind::Ge,
217 hir::BinOpKind::Gt => hir::BinOpKind::Lt,
218 hir::BinOpKind::Ge => hir::BinOpKind::Le,
223 // for isize & usize, be conservative with the warnings, so that the
224 // warnings are consistent between 32- and 64-bit platforms
225 fn int_ty_range(int_ty: ast::IntTy) -> (i128, i128) {
227 ast::IntTy::Isize => (i64::min_value() as i128, i64::max_value() as i128),
228 ast::IntTy::I8 => (i8::min_value() as i64 as i128, i8::max_value() as i128),
229 ast::IntTy::I16 => (i16::min_value() as i64 as i128, i16::max_value() as i128),
230 ast::IntTy::I32 => (i32::min_value() as i64 as i128, i32::max_value() as i128),
231 ast::IntTy::I64 => (i64::min_value() as i128, i64::max_value() as i128),
232 ast::IntTy::I128 =>(i128::min_value() as i128, i128::max_value()),
236 fn uint_ty_range(uint_ty: ast::UintTy) -> (u128, u128) {
238 ast::UintTy::Usize => (u64::min_value() as u128, u64::max_value() as u128),
239 ast::UintTy::U8 => (u8::min_value() as u128, u8::max_value() as u128),
240 ast::UintTy::U16 => (u16::min_value() as u128, u16::max_value() as u128),
241 ast::UintTy::U32 => (u32::min_value() as u128, u32::max_value() as u128),
242 ast::UintTy::U64 => (u64::min_value() as u128, u64::max_value() as u128),
243 ast::UintTy::U128 => (u128::min_value(), u128::max_value()),
247 fn check_limits(cx: &LateContext,
252 let (lit, expr, swap) = match (&l.node, &r.node) {
253 (&hir::ExprKind::Lit(_), _) => (l, r, true),
254 (_, &hir::ExprKind::Lit(_)) => (r, l, false),
257 // Normalize the binop so that the literal is always on the RHS in
259 let norm_binop = if swap { rev_binop(binop) } else { binop };
260 match cx.tables.node_id_to_type(expr.hir_id).sty {
262 let (min, max) = int_ty_range(int_ty);
263 let lit_val: i128 = match lit.node {
264 hir::ExprKind::Lit(ref li) => {
266 ast::LitKind::Int(v, ast::LitIntType::Signed(_)) |
267 ast::LitKind::Int(v, ast::LitIntType::Unsuffixed) => v as i128,
273 is_valid(norm_binop, lit_val, min, max)
275 ty::Uint(uint_ty) => {
276 let (min, max) :(u128, u128) = uint_ty_range(uint_ty);
277 let lit_val: u128 = match lit.node {
278 hir::ExprKind::Lit(ref li) => {
280 ast::LitKind::Int(v, _) => v,
286 is_valid(norm_binop, lit_val, min, max)
292 fn is_comparison(binop: hir::BinOp) -> bool {
299 hir::BinOpKind::Gt => true,
304 fn get_bin_hex_repr(cx: &LateContext, lit: &ast::Lit) -> Option<String> {
305 let src = cx.sess().source_map().span_to_snippet(lit.span).ok()?;
306 let firstch = src.chars().next()?;
309 match src.chars().nth(1) {
310 Some('x') | Some('b') => return Some(src),
318 // This function finds the next fitting type and generates a suggestion string.
319 // It searches for fitting types in the following way (`X < Y`):
320 // - `iX`: if literal fits in `uX` => `uX`, else => `iY`
324 // No suggestion for: `isize`, `usize`.
325 fn get_type_suggestion<'a>(
329 ) -> Option<String> {
330 use syntax::ast::IntTy::*;
331 use syntax::ast::UintTy::*;
332 macro_rules! find_fit {
333 ($ty:expr, $val:expr, $negative:expr,
334 $($type:ident => [$($utypes:expr),*] => [$($itypes:expr),*]),+) => {
336 let _neg = if negative { 1 } else { 0 };
339 $(if !negative && val <= uint_ty_range($utypes).1 {
340 return Some(format!("{:?}", $utypes))
342 $(if val <= int_ty_range($itypes).1 as u128 + _neg {
343 return Some(format!("{:?}", $itypes))
353 &ty::Int(i) => find_fit!(i, val, negative,
354 I8 => [U8] => [I16, I32, I64, I128],
355 I16 => [U16] => [I32, I64, I128],
356 I32 => [U32] => [I64, I128],
357 I64 => [U64] => [I128],
358 I128 => [U128] => []),
359 &ty::Uint(u) => find_fit!(u, val, negative,
360 U8 => [U8, U16, U32, U64, U128] => [],
361 U16 => [U16, U32, U64, U128] => [],
362 U32 => [U32, U64, U128] => [],
363 U64 => [U64, U128] => [],
364 U128 => [U128] => []),
369 fn report_bin_hex_error(
377 let (t, actually) = match ty {
379 let ity = attr::IntType::SignedInt(t);
380 let bits = layout::Integer::from_attr(cx.tcx, ity).size().bits();
381 let actually = (val << (128 - bits)) as i128 >> (128 - bits);
382 (format!("{:?}", t), actually.to_string())
385 let ity = attr::IntType::UnsignedInt(t);
386 let bits = layout::Integer::from_attr(cx.tcx, ity).size().bits();
387 let actually = (val << (128 - bits)) >> (128 - bits);
388 (format!("{:?}", t), actually.to_string())
392 let mut err = cx.struct_span_lint(
393 OVERFLOWING_LITERALS,
395 &format!("literal out of range for {}", t),
398 "the literal `{}` (decimal `{}`) does not fit into \
399 an `{}` and will become `{}{}`",
400 repr_str, val, t, actually, t
402 if let Some(sugg_ty) =
403 get_type_suggestion(&cx.tables.node_id_to_type(expr.hir_id).sty, val, negative)
405 if let Some(pos) = repr_str.chars().position(|c| c == 'i' || c == 'u') {
406 let (sans_suffix, _) = repr_str.split_at(pos);
407 err.span_suggestion_with_applicability(
409 &format!("consider using `{}` instead", sugg_ty),
410 format!("{}{}", sans_suffix, sugg_ty),
411 Applicability::MachineApplicable
414 err.help(&format!("consider using `{}` instead", sugg_ty));
426 "proper use of libc types in foreign modules"
429 struct ImproperCTypesVisitor<'a, 'tcx: 'a> {
430 cx: &'a LateContext<'a, 'tcx>,
433 enum FfiResult<'tcx> {
435 FfiPhantom(Ty<'tcx>),
438 reason: &'static str,
439 help: Option<&'static str>,
443 /// Check if this enum can be safely exported based on the
444 /// "nullable pointer optimization". Currently restricted
445 /// to function pointers and references, but could be
446 /// expanded to cover NonZero raw pointers and newtypes.
447 /// FIXME: This duplicates code in codegen.
448 fn is_repr_nullable_ptr<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
449 def: &'tcx ty::AdtDef,
450 substs: &Substs<'tcx>)
452 if def.variants.len() == 2 {
455 if def.variants[0].fields.is_empty() {
457 } else if def.variants[1].fields.is_empty() {
463 if def.variants[data_idx].fields.len() == 1 {
464 match def.variants[data_idx].fields[0].ty(tcx, substs).sty {
478 impl<'a, 'tcx> ImproperCTypesVisitor<'a, 'tcx> {
479 /// Check if the given type is "ffi-safe" (has a stable, well-defined
480 /// representation which can be exported to C code).
481 fn check_type_for_ffi(&self,
482 cache: &mut FxHashSet<Ty<'tcx>>,
483 ty: Ty<'tcx>) -> FfiResult<'tcx> {
484 use self::FfiResult::*;
486 let cx = self.cx.tcx;
488 // Protect against infinite recursion, for example
489 // `struct S(*mut S);`.
490 // FIXME: A recursion limit is necessary as well, for irregular
492 if !cache.insert(ty) {
497 ty::Adt(def, substs) => {
498 if def.is_phantom_data() {
499 return FfiPhantom(ty);
501 match def.adt_kind() {
503 if !def.repr.c() && !def.repr.transparent() {
506 reason: "this struct has unspecified layout",
507 help: Some("consider adding a #[repr(C)] or #[repr(transparent)] \
508 attribute to this struct"),
512 if def.non_enum_variant().fields.is_empty() {
515 reason: "this struct has no fields",
516 help: Some("consider adding a member to this struct"),
520 // We can't completely trust repr(C) and repr(transparent) markings;
521 // make sure the fields are actually safe.
522 let mut all_phantom = true;
523 for field in &def.non_enum_variant().fields {
524 let field_ty = cx.normalize_erasing_regions(
525 ParamEnv::reveal_all(),
526 field.ty(cx, substs),
528 // repr(transparent) types are allowed to have arbitrary ZSTs, not just
529 // PhantomData -- skip checking all ZST fields
530 if def.repr.transparent() {
532 .layout_of(cx.param_env(field.did).and(field_ty))
533 .map(|layout| layout.is_zst())
539 let r = self.check_type_for_ffi(cache, field_ty);
545 FfiUnsafe { .. } => {
551 if all_phantom { FfiPhantom(ty) } else { FfiSafe }
557 reason: "this union has unspecified layout",
558 help: Some("consider adding a #[repr(C)] attribute to this union"),
562 if def.non_enum_variant().fields.is_empty() {
565 reason: "this union has no fields",
566 help: Some("consider adding a field to this union"),
570 let mut all_phantom = true;
571 for field in &def.non_enum_variant().fields {
572 let field_ty = cx.normalize_erasing_regions(
573 ParamEnv::reveal_all(),
574 field.ty(cx, substs),
576 let r = self.check_type_for_ffi(cache, field_ty);
582 FfiUnsafe { .. } => {
588 if all_phantom { FfiPhantom(ty) } else { FfiSafe }
591 if def.variants.is_empty() {
592 // Empty enums are okay... although sort of useless.
596 // Check for a repr() attribute to specify the size of the
598 if !def.repr.c() && def.repr.int.is_none() {
599 // Special-case types like `Option<extern fn()>`.
600 if !is_repr_nullable_ptr(cx, def, substs) {
603 reason: "enum has no representation hint",
604 help: Some("consider adding a #[repr(...)] attribute \
610 // Check the contained variants.
611 for variant in &def.variants {
612 for field in &variant.fields {
613 let arg = cx.normalize_erasing_regions(
614 ParamEnv::reveal_all(),
615 field.ty(cx, substs),
617 let r = self.check_type_for_ffi(cache, arg);
620 FfiUnsafe { .. } => {
626 reason: "this enum contains a PhantomData field",
638 ty::Char => FfiUnsafe {
640 reason: "the `char` type has no C equivalent",
641 help: Some("consider using `u32` or `libc::wchar_t` instead"),
644 ty::Int(ast::IntTy::I128) | ty::Uint(ast::UintTy::U128) => FfiUnsafe {
646 reason: "128-bit integers don't currently have a known stable ABI",
650 // Primitive types with a stable representation.
651 ty::Bool | ty::Int(..) | ty::Uint(..) | ty::Float(..) | ty::Never => FfiSafe,
653 ty::Slice(_) => FfiUnsafe {
655 reason: "slices have no C equivalent",
656 help: Some("consider using a raw pointer instead"),
659 ty::Dynamic(..) => FfiUnsafe {
661 reason: "trait objects have no C equivalent",
665 ty::Str => FfiUnsafe {
667 reason: "string slices have no C equivalent",
668 help: Some("consider using `*const u8` and a length instead"),
671 ty::Tuple(..) => FfiUnsafe {
673 reason: "tuples have unspecified layout",
674 help: Some("consider using a struct instead"),
677 ty::RawPtr(ty::TypeAndMut { ty, .. }) |
678 ty::Ref(_, ty, _) => self.check_type_for_ffi(cache, ty),
680 ty::Array(ty, _) => self.check_type_for_ffi(cache, ty),
684 Abi::Rust | Abi::RustIntrinsic | Abi::PlatformIntrinsic | Abi::RustCall => {
687 reason: "this function pointer has Rust-specific calling convention",
688 help: Some("consider using an `extern fn(...) -> ...` \
689 function pointer instead"),
695 let sig = cx.erase_late_bound_regions(&sig);
696 if !sig.output().is_unit() {
697 let r = self.check_type_for_ffi(cache, sig.output());
705 for arg in sig.inputs() {
706 let r = self.check_type_for_ffi(cache, arg);
717 ty::Foreign(..) => FfiSafe,
724 ty::GeneratorWitness(..) |
725 ty::UnnormalizedProjection(..) |
728 ty::FnDef(..) => bug!("Unexpected type in foreign function"),
732 fn check_type_for_ffi_and_report_errors(&mut self, sp: Span, ty: Ty<'tcx>) {
733 // it is only OK to use this function because extern fns cannot have
734 // any generic types right now:
735 let ty = self.cx.tcx.normalize_erasing_regions(ParamEnv::reveal_all(), ty);
737 match self.check_type_for_ffi(&mut FxHashSet(), ty) {
738 FfiResult::FfiSafe => {}
739 FfiResult::FfiPhantom(ty) => {
740 self.cx.span_lint(IMPROPER_CTYPES,
742 &format!("`extern` block uses type `{}` which is not FFI-safe: \
743 composed only of PhantomData", ty));
745 FfiResult::FfiUnsafe { ty: unsafe_ty, reason, help } => {
746 let msg = format!("`extern` block uses type `{}` which is not FFI-safe: {}",
748 let mut diag = self.cx.struct_span_lint(IMPROPER_CTYPES, sp, &msg);
749 if let Some(s) = help {
752 if let ty::Adt(def, _) = unsafe_ty.sty {
753 if let Some(sp) = self.cx.tcx.hir.span_if_local(def.did) {
754 diag.span_note(sp, "type defined here");
762 fn check_foreign_fn(&mut self, id: ast::NodeId, decl: &hir::FnDecl) {
763 let def_id = self.cx.tcx.hir.local_def_id(id);
764 let sig = self.cx.tcx.fn_sig(def_id);
765 let sig = self.cx.tcx.erase_late_bound_regions(&sig);
767 for (input_ty, input_hir) in sig.inputs().iter().zip(&decl.inputs) {
768 self.check_type_for_ffi_and_report_errors(input_hir.span, input_ty);
771 if let hir::Return(ref ret_hir) = decl.output {
772 let ret_ty = sig.output();
773 if !ret_ty.is_unit() {
774 self.check_type_for_ffi_and_report_errors(ret_hir.span, ret_ty);
779 fn check_foreign_static(&mut self, id: ast::NodeId, span: Span) {
780 let def_id = self.cx.tcx.hir.local_def_id(id);
781 let ty = self.cx.tcx.type_of(def_id);
782 self.check_type_for_ffi_and_report_errors(span, ty);
786 #[derive(Copy, Clone)]
787 pub struct ImproperCTypes;
789 impl LintPass for ImproperCTypes {
790 fn get_lints(&self) -> LintArray {
791 lint_array!(IMPROPER_CTYPES)
795 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ImproperCTypes {
796 fn check_foreign_item(&mut self, cx: &LateContext, it: &hir::ForeignItem) {
797 let mut vis = ImproperCTypesVisitor { cx: cx };
798 let abi = cx.tcx.hir.get_foreign_abi(it.id);
799 if abi != Abi::RustIntrinsic && abi != Abi::PlatformIntrinsic {
801 hir::ForeignItemKind::Fn(ref decl, _, _) => {
802 vis.check_foreign_fn(it.id, decl);
804 hir::ForeignItemKind::Static(ref ty, _) => {
805 vis.check_foreign_static(it.id, ty.span);
807 hir::ForeignItemKind::Type => ()
813 pub struct VariantSizeDifferences;
815 impl LintPass for VariantSizeDifferences {
816 fn get_lints(&self) -> LintArray {
817 lint_array!(VARIANT_SIZE_DIFFERENCES)
821 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for VariantSizeDifferences {
822 fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
823 if let hir::ItemKind::Enum(ref enum_definition, _) = it.node {
824 let item_def_id = cx.tcx.hir.local_def_id(it.id);
825 let t = cx.tcx.type_of(item_def_id);
826 let ty = cx.tcx.erase_regions(&t);
827 match cx.layout_of(ty) {
829 let variants = &layout.variants;
830 if let layout::Variants::Tagged { ref variants, ref tag, .. } = variants {
831 let discr_size = tag.value.size(cx.tcx).bytes();
833 debug!("enum `{}` is {} bytes large with layout:\n{:#?}",
834 t, layout.size.bytes(), layout);
836 let (largest, slargest, largest_index) = enum_definition.variants
839 .map(|(variant, variant_layout)| {
840 // Subtract the size of the enum discriminant.
841 let bytes = variant_layout.size.bytes().saturating_sub(discr_size);
843 debug!("- variant `{}` is {} bytes large",
849 .fold((0, 0, 0), |(l, s, li), (idx, size)| if size > l {
857 // We only warn if the largest variant is at least thrice as large as
858 // the second-largest.
859 if largest > slargest * 3 && slargest > 0 {
860 cx.span_lint(VARIANT_SIZE_DIFFERENCES,
861 enum_definition.variants[largest_index].span,
862 &format!("enum variant is more than three times \
863 larger ({} bytes) than the next largest",
868 Err(ty::layout::LayoutError::Unknown(_)) => return,
869 Err(err @ ty::layout::LayoutError::SizeOverflow(_)) => {
870 bug!("failed to get layout for `{}`: {}", t, err);