1 #![allow(non_snake_case)]
4 use rustc::ty::subst::Substs;
5 use rustc::ty::{self, AdtKind, ParamEnv, Ty, TyCtxt};
6 use rustc::ty::layout::{self, IntegerExt, LayoutOf, VariantIdx};
7 use rustc_data_structures::indexed_vec::Idx;
8 use util::nodemap::FxHashSet;
9 use lint::{LateContext, LintContext, LintArray};
10 use lint::{LintPass, LateLintPass};
13 use std::{i8, i16, i32, i64, u8, u16, u32, u64, f32, f64};
15 use syntax::{ast, attr};
16 use syntax::errors::Applicability;
17 use rustc_target::spec::abi::Abi;
18 use syntax::edition::Edition;
20 use syntax::source_map;
27 "comparisons made useless by limits of the types involved"
33 "literal out of range for its type",
34 Edition::Edition2018 => Deny
38 VARIANT_SIZE_DIFFERENCES,
40 "detects enums with widely varying variant sizes"
43 #[derive(Copy, Clone)]
44 pub struct TypeLimits {
45 /// Id of the last visited negated expression
46 negated_expr_id: ast::NodeId,
50 pub fn new() -> TypeLimits {
51 TypeLimits { negated_expr_id: ast::DUMMY_NODE_ID }
55 impl LintPass for TypeLimits {
56 fn get_lints(&self) -> LintArray {
57 lint_array!(UNUSED_COMPARISONS,
62 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TypeLimits {
63 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx hir::Expr) {
65 hir::ExprKind::Unary(hir::UnNeg, ref expr) => {
66 // propagate negation, if the negation itself isn't negated
67 if self.negated_expr_id != e.id {
68 self.negated_expr_id = expr.id;
71 hir::ExprKind::Binary(binop, ref l, ref r) => {
72 if is_comparison(binop) && !check_limits(cx, binop, &l, &r) {
73 cx.span_lint(UNUSED_COMPARISONS,
75 "comparison is useless due to type limits");
78 hir::ExprKind::Lit(ref lit) => {
79 match cx.tables.node_id_to_type(e.hir_id).sty {
82 ast::LitKind::Int(v, ast::LitIntType::Signed(_)) |
83 ast::LitKind::Int(v, ast::LitIntType::Unsuffixed) => {
84 let int_type = if let ast::IntTy::Isize = t {
85 cx.sess().target.isize_ty
89 let (_, max) = int_ty_range(int_type);
90 let max = max as u128;
91 let negative = self.negated_expr_id == e.id;
93 // Detect literal value out of range [min, max] inclusive
94 // avoiding use of -min to prevent overflow/panic
95 if (negative && v > max + 1) || (!negative && v > max) {
96 if let Some(repr_str) = get_bin_hex_repr(cx, lit) {
108 OVERFLOWING_LITERALS,
110 &format!("literal out of range for {:?}", t),
119 let uint_type = if let ast::UintTy::Usize = t {
120 cx.sess().target.usize_ty
124 let (min, max) = uint_ty_range(uint_type);
125 let lit_val: u128 = match lit.node {
126 // _v is u8, within range by definition
127 ast::LitKind::Byte(_v) => return,
128 ast::LitKind::Int(v, _) => v,
131 if lit_val < min || lit_val > max {
132 let parent_id = cx.tcx.hir().get_parent_node(e.id);
133 if let Node::Expr(parent_expr) = cx.tcx.hir().get(parent_id) {
134 if let hir::ExprKind::Cast(..) = parent_expr.node {
135 if let ty::Char = cx.tables.expr_ty(parent_expr).sty {
136 let mut err = cx.struct_span_lint(
137 OVERFLOWING_LITERALS,
139 "only u8 can be cast into char");
140 err.span_suggestion_with_applicability(
142 &"use a char literal instead",
143 format!("'\\u{{{:X}}}'", lit_val),
144 Applicability::MachineApplicable
151 if let Some(repr_str) = get_bin_hex_repr(cx, lit) {
152 report_bin_hex_error(
163 OVERFLOWING_LITERALS,
165 &format!("literal out of range for {:?}", t),
170 let is_infinite = match lit.node {
171 ast::LitKind::Float(v, _) |
172 ast::LitKind::FloatUnsuffixed(v) => {
174 ast::FloatTy::F32 => v.as_str().parse().map(f32::is_infinite),
175 ast::FloatTy::F64 => v.as_str().parse().map(f64::is_infinite),
180 if is_infinite == Ok(true) {
181 cx.span_lint(OVERFLOWING_LITERALS,
183 &format!("literal out of range for {:?}", t));
192 fn is_valid<T: cmp::PartialOrd>(binop: hir::BinOp, v: T, min: T, max: T) -> bool {
194 hir::BinOpKind::Lt => v > min && v <= max,
195 hir::BinOpKind::Le => v >= min && v < max,
196 hir::BinOpKind::Gt => v >= min && v < max,
197 hir::BinOpKind::Ge => v > min && v <= max,
198 hir::BinOpKind::Eq | hir::BinOpKind::Ne => v >= min && v <= max,
203 fn rev_binop(binop: hir::BinOp) -> hir::BinOp {
204 source_map::respan(binop.span,
206 hir::BinOpKind::Lt => hir::BinOpKind::Gt,
207 hir::BinOpKind::Le => hir::BinOpKind::Ge,
208 hir::BinOpKind::Gt => hir::BinOpKind::Lt,
209 hir::BinOpKind::Ge => hir::BinOpKind::Le,
214 // for isize & usize, be conservative with the warnings, so that the
215 // warnings are consistent between 32- and 64-bit platforms
216 fn int_ty_range(int_ty: ast::IntTy) -> (i128, i128) {
218 ast::IntTy::Isize => (i64::min_value() as i128, i64::max_value() as i128),
219 ast::IntTy::I8 => (i8::min_value() as i64 as i128, i8::max_value() as i128),
220 ast::IntTy::I16 => (i16::min_value() as i64 as i128, i16::max_value() as i128),
221 ast::IntTy::I32 => (i32::min_value() as i64 as i128, i32::max_value() as i128),
222 ast::IntTy::I64 => (i64::min_value() as i128, i64::max_value() as i128),
223 ast::IntTy::I128 =>(i128::min_value() as i128, i128::max_value()),
227 fn uint_ty_range(uint_ty: ast::UintTy) -> (u128, u128) {
229 ast::UintTy::Usize => (u64::min_value() as u128, u64::max_value() as u128),
230 ast::UintTy::U8 => (u8::min_value() as u128, u8::max_value() as u128),
231 ast::UintTy::U16 => (u16::min_value() as u128, u16::max_value() as u128),
232 ast::UintTy::U32 => (u32::min_value() as u128, u32::max_value() as u128),
233 ast::UintTy::U64 => (u64::min_value() as u128, u64::max_value() as u128),
234 ast::UintTy::U128 => (u128::min_value(), u128::max_value()),
238 fn check_limits(cx: &LateContext,
243 let (lit, expr, swap) = match (&l.node, &r.node) {
244 (&hir::ExprKind::Lit(_), _) => (l, r, true),
245 (_, &hir::ExprKind::Lit(_)) => (r, l, false),
248 // Normalize the binop so that the literal is always on the RHS in
250 let norm_binop = if swap { rev_binop(binop) } else { binop };
251 match cx.tables.node_id_to_type(expr.hir_id).sty {
253 let (min, max) = int_ty_range(int_ty);
254 let lit_val: i128 = match lit.node {
255 hir::ExprKind::Lit(ref li) => {
257 ast::LitKind::Int(v, ast::LitIntType::Signed(_)) |
258 ast::LitKind::Int(v, ast::LitIntType::Unsuffixed) => v as i128,
264 is_valid(norm_binop, lit_val, min, max)
266 ty::Uint(uint_ty) => {
267 let (min, max) :(u128, u128) = uint_ty_range(uint_ty);
268 let lit_val: u128 = match lit.node {
269 hir::ExprKind::Lit(ref li) => {
271 ast::LitKind::Int(v, _) => v,
277 is_valid(norm_binop, lit_val, min, max)
283 fn is_comparison(binop: hir::BinOp) -> bool {
290 hir::BinOpKind::Gt => true,
295 fn get_bin_hex_repr(cx: &LateContext, lit: &ast::Lit) -> Option<String> {
296 let src = cx.sess().source_map().span_to_snippet(lit.span).ok()?;
297 let firstch = src.chars().next()?;
300 match src.chars().nth(1) {
301 Some('x') | Some('b') => return Some(src),
309 // This function finds the next fitting type and generates a suggestion string.
310 // It searches for fitting types in the following way (`X < Y`):
311 // - `iX`: if literal fits in `uX` => `uX`, else => `iY`
315 // No suggestion for: `isize`, `usize`.
316 fn get_type_suggestion<'a>(
320 ) -> Option<String> {
321 use syntax::ast::IntTy::*;
322 use syntax::ast::UintTy::*;
323 macro_rules! find_fit {
324 ($ty:expr, $val:expr, $negative:expr,
325 $($type:ident => [$($utypes:expr),*] => [$($itypes:expr),*]),+) => {
327 let _neg = if negative { 1 } else { 0 };
330 $(if !negative && val <= uint_ty_range($utypes).1 {
331 return Some(format!("{:?}", $utypes))
333 $(if val <= int_ty_range($itypes).1 as u128 + _neg {
334 return Some(format!("{:?}", $itypes))
344 &ty::Int(i) => find_fit!(i, val, negative,
345 I8 => [U8] => [I16, I32, I64, I128],
346 I16 => [U16] => [I32, I64, I128],
347 I32 => [U32] => [I64, I128],
348 I64 => [U64] => [I128],
349 I128 => [U128] => []),
350 &ty::Uint(u) => find_fit!(u, val, negative,
351 U8 => [U8, U16, U32, U64, U128] => [],
352 U16 => [U16, U32, U64, U128] => [],
353 U32 => [U32, U64, U128] => [],
354 U64 => [U64, U128] => [],
355 U128 => [U128] => []),
360 fn report_bin_hex_error(
368 let (t, actually) = match ty {
370 let ity = attr::IntType::SignedInt(t);
371 let bits = layout::Integer::from_attr(&cx.tcx, ity).size().bits();
372 let actually = (val << (128 - bits)) as i128 >> (128 - bits);
373 (format!("{:?}", t), actually.to_string())
376 let ity = attr::IntType::UnsignedInt(t);
377 let bits = layout::Integer::from_attr(&cx.tcx, ity).size().bits();
378 let actually = (val << (128 - bits)) >> (128 - bits);
379 (format!("{:?}", t), actually.to_string())
383 let mut err = cx.struct_span_lint(
384 OVERFLOWING_LITERALS,
386 &format!("literal out of range for {}", t),
389 "the literal `{}` (decimal `{}`) does not fit into \
390 an `{}` and will become `{}{}`",
391 repr_str, val, t, actually, t
393 if let Some(sugg_ty) =
394 get_type_suggestion(&cx.tables.node_id_to_type(expr.hir_id).sty, val, negative)
396 if let Some(pos) = repr_str.chars().position(|c| c == 'i' || c == 'u') {
397 let (sans_suffix, _) = repr_str.split_at(pos);
398 err.span_suggestion_with_applicability(
400 &format!("consider using `{}` instead", sugg_ty),
401 format!("{}{}", sans_suffix, sugg_ty),
402 Applicability::MachineApplicable
405 err.help(&format!("consider using `{}` instead", sugg_ty));
417 "proper use of libc types in foreign modules"
420 struct ImproperCTypesVisitor<'a, 'tcx: 'a> {
421 cx: &'a LateContext<'a, 'tcx>,
424 enum FfiResult<'tcx> {
426 FfiPhantom(Ty<'tcx>),
429 reason: &'static str,
430 help: Option<&'static str>,
434 /// Check if this enum can be safely exported based on the
435 /// "nullable pointer optimization". Currently restricted
436 /// to function pointers and references, but could be
437 /// expanded to cover NonZero raw pointers and newtypes.
438 /// FIXME: This duplicates code in codegen.
439 fn is_repr_nullable_ptr<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
440 def: &'tcx ty::AdtDef,
441 substs: &Substs<'tcx>)
443 if def.variants.len() == 2 {
446 let zero = VariantIdx::new(0);
447 let one = VariantIdx::new(1);
449 if def.variants[zero].fields.is_empty() {
451 } else if def.variants[one].fields.is_empty() {
457 if def.variants[data_idx].fields.len() == 1 {
458 match def.variants[data_idx].fields[0].ty(tcx, substs).sty {
472 impl<'a, 'tcx> ImproperCTypesVisitor<'a, 'tcx> {
473 /// Check if the given type is "ffi-safe" (has a stable, well-defined
474 /// representation which can be exported to C code).
475 fn check_type_for_ffi(&self,
476 cache: &mut FxHashSet<Ty<'tcx>>,
477 ty: Ty<'tcx>) -> FfiResult<'tcx> {
478 use self::FfiResult::*;
480 let cx = self.cx.tcx;
482 // Protect against infinite recursion, for example
483 // `struct S(*mut S);`.
484 // FIXME: A recursion limit is necessary as well, for irregular
486 if !cache.insert(ty) {
491 ty::Adt(def, substs) => {
492 if def.is_phantom_data() {
493 return FfiPhantom(ty);
495 match def.adt_kind() {
497 if !def.repr.c() && !def.repr.transparent() {
500 reason: "this struct has unspecified layout",
501 help: Some("consider adding a #[repr(C)] or #[repr(transparent)] \
502 attribute to this struct"),
506 if def.non_enum_variant().fields.is_empty() {
509 reason: "this struct has no fields",
510 help: Some("consider adding a member to this struct"),
514 // We can't completely trust repr(C) and repr(transparent) markings;
515 // make sure the fields are actually safe.
516 let mut all_phantom = true;
517 for field in &def.non_enum_variant().fields {
518 let field_ty = cx.normalize_erasing_regions(
519 ParamEnv::reveal_all(),
520 field.ty(cx, substs),
522 // repr(transparent) types are allowed to have arbitrary ZSTs, not just
523 // PhantomData -- skip checking all ZST fields
524 if def.repr.transparent() {
526 .layout_of(cx.param_env(field.did).and(field_ty))
527 .map(|layout| layout.is_zst())
533 let r = self.check_type_for_ffi(cache, field_ty);
539 FfiUnsafe { .. } => {
545 if all_phantom { FfiPhantom(ty) } else { FfiSafe }
551 reason: "this union has unspecified layout",
552 help: Some("consider adding a #[repr(C)] attribute to this union"),
556 if def.non_enum_variant().fields.is_empty() {
559 reason: "this union has no fields",
560 help: Some("consider adding a field to this union"),
564 let mut all_phantom = true;
565 for field in &def.non_enum_variant().fields {
566 let field_ty = cx.normalize_erasing_regions(
567 ParamEnv::reveal_all(),
568 field.ty(cx, substs),
570 let r = self.check_type_for_ffi(cache, field_ty);
576 FfiUnsafe { .. } => {
582 if all_phantom { FfiPhantom(ty) } else { FfiSafe }
585 if def.variants.is_empty() {
586 // Empty enums are okay... although sort of useless.
590 // Check for a repr() attribute to specify the size of the
592 if !def.repr.c() && def.repr.int.is_none() {
593 // Special-case types like `Option<extern fn()>`.
594 if !is_repr_nullable_ptr(cx, def, substs) {
597 reason: "enum has no representation hint",
598 help: Some("consider adding a #[repr(...)] attribute \
604 // Check the contained variants.
605 for variant in &def.variants {
606 for field in &variant.fields {
607 let arg = cx.normalize_erasing_regions(
608 ParamEnv::reveal_all(),
609 field.ty(cx, substs),
611 let r = self.check_type_for_ffi(cache, arg);
614 FfiUnsafe { .. } => {
620 reason: "this enum contains a PhantomData field",
632 ty::Char => FfiUnsafe {
634 reason: "the `char` type has no C equivalent",
635 help: Some("consider using `u32` or `libc::wchar_t` instead"),
638 ty::Int(ast::IntTy::I128) | ty::Uint(ast::UintTy::U128) => FfiUnsafe {
640 reason: "128-bit integers don't currently have a known stable ABI",
644 // Primitive types with a stable representation.
645 ty::Bool | ty::Int(..) | ty::Uint(..) | ty::Float(..) | ty::Never => FfiSafe,
647 ty::Slice(_) => FfiUnsafe {
649 reason: "slices have no C equivalent",
650 help: Some("consider using a raw pointer instead"),
653 ty::Dynamic(..) => FfiUnsafe {
655 reason: "trait objects have no C equivalent",
659 ty::Str => FfiUnsafe {
661 reason: "string slices have no C equivalent",
662 help: Some("consider using `*const u8` and a length instead"),
665 ty::Tuple(..) => FfiUnsafe {
667 reason: "tuples have unspecified layout",
668 help: Some("consider using a struct instead"),
671 ty::RawPtr(ty::TypeAndMut { ty, .. }) |
672 ty::Ref(_, ty, _) => self.check_type_for_ffi(cache, ty),
674 ty::Array(ty, _) => self.check_type_for_ffi(cache, ty),
678 Abi::Rust | Abi::RustIntrinsic | Abi::PlatformIntrinsic | Abi::RustCall => {
681 reason: "this function pointer has Rust-specific calling convention",
682 help: Some("consider using an `extern fn(...) -> ...` \
683 function pointer instead"),
689 let sig = cx.erase_late_bound_regions(&sig);
690 if !sig.output().is_unit() {
691 let r = self.check_type_for_ffi(cache, sig.output());
699 for arg in sig.inputs() {
700 let r = self.check_type_for_ffi(cache, arg);
711 ty::Foreign(..) => FfiSafe,
719 ty::GeneratorWitness(..) |
720 ty::Placeholder(..) |
721 ty::UnnormalizedProjection(..) |
724 ty::FnDef(..) => bug!("Unexpected type in foreign function"),
728 fn check_type_for_ffi_and_report_errors(&mut self, sp: Span, ty: Ty<'tcx>) {
729 // it is only OK to use this function because extern fns cannot have
730 // any generic types right now:
731 let ty = self.cx.tcx.normalize_erasing_regions(ParamEnv::reveal_all(), ty);
733 match self.check_type_for_ffi(&mut FxHashSet::default(), ty) {
734 FfiResult::FfiSafe => {}
735 FfiResult::FfiPhantom(ty) => {
736 self.cx.span_lint(IMPROPER_CTYPES,
738 &format!("`extern` block uses type `{}` which is not FFI-safe: \
739 composed only of PhantomData", ty));
741 FfiResult::FfiUnsafe { ty: unsafe_ty, reason, help } => {
742 let msg = format!("`extern` block uses type `{}` which is not FFI-safe: {}",
744 let mut diag = self.cx.struct_span_lint(IMPROPER_CTYPES, sp, &msg);
745 if let Some(s) = help {
748 if let ty::Adt(def, _) = unsafe_ty.sty {
749 if let Some(sp) = self.cx.tcx.hir().span_if_local(def.did) {
750 diag.span_note(sp, "type defined here");
758 fn check_foreign_fn(&mut self, id: ast::NodeId, decl: &hir::FnDecl) {
759 let def_id = self.cx.tcx.hir().local_def_id(id);
760 let sig = self.cx.tcx.fn_sig(def_id);
761 let sig = self.cx.tcx.erase_late_bound_regions(&sig);
763 for (input_ty, input_hir) in sig.inputs().iter().zip(&decl.inputs) {
764 self.check_type_for_ffi_and_report_errors(input_hir.span, input_ty);
767 if let hir::Return(ref ret_hir) = decl.output {
768 let ret_ty = sig.output();
769 if !ret_ty.is_unit() {
770 self.check_type_for_ffi_and_report_errors(ret_hir.span, ret_ty);
775 fn check_foreign_static(&mut self, id: ast::NodeId, span: Span) {
776 let def_id = self.cx.tcx.hir().local_def_id(id);
777 let ty = self.cx.tcx.type_of(def_id);
778 self.check_type_for_ffi_and_report_errors(span, ty);
782 #[derive(Copy, Clone)]
783 pub struct ImproperCTypes;
785 impl LintPass for ImproperCTypes {
786 fn get_lints(&self) -> LintArray {
787 lint_array!(IMPROPER_CTYPES)
791 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ImproperCTypes {
792 fn check_foreign_item(&mut self, cx: &LateContext, it: &hir::ForeignItem) {
793 let mut vis = ImproperCTypesVisitor { cx };
794 let abi = cx.tcx.hir().get_foreign_abi(it.id);
795 if abi != Abi::RustIntrinsic && abi != Abi::PlatformIntrinsic {
797 hir::ForeignItemKind::Fn(ref decl, _, _) => {
798 vis.check_foreign_fn(it.id, decl);
800 hir::ForeignItemKind::Static(ref ty, _) => {
801 vis.check_foreign_static(it.id, ty.span);
803 hir::ForeignItemKind::Type => ()
809 pub struct VariantSizeDifferences;
811 impl LintPass for VariantSizeDifferences {
812 fn get_lints(&self) -> LintArray {
813 lint_array!(VARIANT_SIZE_DIFFERENCES)
817 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for VariantSizeDifferences {
818 fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
819 if let hir::ItemKind::Enum(ref enum_definition, _) = it.node {
820 let item_def_id = cx.tcx.hir().local_def_id(it.id);
821 let t = cx.tcx.type_of(item_def_id);
822 let ty = cx.tcx.erase_regions(&t);
823 match cx.layout_of(ty) {
825 let variants = &layout.variants;
826 if let layout::Variants::Tagged { ref variants, ref tag, .. } = variants {
827 let discr_size = tag.value.size(&cx.tcx).bytes();
829 debug!("enum `{}` is {} bytes large with layout:\n{:#?}",
830 t, layout.size.bytes(), layout);
832 let (largest, slargest, largest_index) = enum_definition.variants
835 .map(|(variant, variant_layout)| {
836 // Subtract the size of the enum discriminant.
837 let bytes = variant_layout.size.bytes().saturating_sub(discr_size);
839 debug!("- variant `{}` is {} bytes large",
845 .fold((0, 0, 0), |(l, s, li), (idx, size)| if size > l {
853 // We only warn if the largest variant is at least thrice as large as
854 // the second-largest.
855 if largest > slargest * 3 && slargest > 0 {
856 cx.span_lint(VARIANT_SIZE_DIFFERENCES,
857 enum_definition.variants[largest_index].span,
858 &format!("enum variant is more than three times \
859 larger ({} bytes) than the next largest",
864 Err(ty::layout::LayoutError::Unknown(_)) => return,
865 Err(err @ ty::layout::LayoutError::SizeOverflow(_)) => {
866 bug!("failed to get layout for `{}`: {}", t, err);