1 #![allow(non_snake_case)]
3 use rustc::hir::{ExprKind, Node};
4 use crate::hir::def_id::DefId;
5 use rustc::hir::lowering::is_range_literal;
6 use rustc::ty::subst::SubstsRef;
7 use rustc::ty::{self, AdtKind, ParamEnv, Ty, TyCtxt};
8 use rustc::ty::layout::{self, IntegerExt, LayoutOf, VariantIdx, SizeSkeleton};
9 use rustc::{lint, util};
10 use rustc_data_structures::indexed_vec::Idx;
11 use util::nodemap::FxHashSet;
12 use lint::{LateContext, LintContext, LintArray};
13 use lint::{LintPass, LateLintPass};
16 use std::{i8, i16, i32, i64, u8, u16, u32, u64, f32, f64};
18 use syntax::{ast, attr, source_map};
19 use syntax::errors::Applicability;
20 use syntax::symbol::sym;
21 use rustc_target::spec::abi::Abi;
26 use rustc::mir::interpret::{sign_extend, truncate};
33 "comparisons made useless by limits of the types involved"
39 "literal out of range for its type"
43 VARIANT_SIZE_DIFFERENCES,
45 "detects enums with widely varying variant sizes"
48 #[derive(Copy, Clone)]
49 pub struct TypeLimits {
50 /// Id of the last visited negated expression
51 negated_expr_id: hir::HirId,
54 impl_lint_pass!(TypeLimits => [UNUSED_COMPARISONS, OVERFLOWING_LITERALS]);
57 pub fn new() -> TypeLimits {
58 TypeLimits { negated_expr_id: hir::DUMMY_HIR_ID }
62 /// Attempts to special-case the overflowing literal lint when it occurs as a range endpoint.
63 /// Returns `true` iff the lint was overridden.
64 fn lint_overflowing_range_endpoint<'a, 'tcx>(
65 cx: &LateContext<'a, 'tcx>,
69 expr: &'tcx hir::Expr,
70 parent_expr: &'tcx hir::Expr,
71 ty: impl std::fmt::Debug,
73 // We only want to handle exclusive (`..`) ranges,
74 // which are represented as `ExprKind::Struct`.
75 if let ExprKind::Struct(_, eps, _) = &parent_expr.node {
76 debug_assert_eq!(eps.len(), 2);
77 // We can suggest using an inclusive range
78 // (`..=`) instead only if it is the `end` that is
79 // overflowing and only by 1.
80 if eps[1].expr.hir_id == expr.hir_id && lit_val - 1 == max {
81 let mut err = cx.struct_span_lint(
84 &format!("range endpoint is out of range for `{:?}`", ty),
86 if let Ok(start) = cx.sess().source_map().span_to_snippet(eps[0].span) {
87 use ast::{LitKind, LitIntType};
88 // We need to preserve the literal's suffix,
89 // as it may determine typing information.
90 let suffix = match lit.node {
91 LitKind::Int(_, LitIntType::Signed(s)) => format!("{}", s),
92 LitKind::Int(_, LitIntType::Unsigned(s)) => format!("{}", s),
93 LitKind::Int(_, LitIntType::Unsuffixed) => "".to_owned(),
96 let suggestion = format!("{}..={}{}", start, lit_val - 1, suffix);
99 &"use an inclusive range instead",
101 Applicability::MachineApplicable,
112 // For `isize` & `usize`, be conservative with the warnings, so that the
113 // warnings are consistent between 32- and 64-bit platforms.
114 fn int_ty_range(int_ty: ast::IntTy) -> (i128, i128) {
116 ast::IntTy::Isize => (i64::min_value() as i128, i64::max_value() as i128),
117 ast::IntTy::I8 => (i8::min_value() as i64 as i128, i8::max_value() as i128),
118 ast::IntTy::I16 => (i16::min_value() as i64 as i128, i16::max_value() as i128),
119 ast::IntTy::I32 => (i32::min_value() as i64 as i128, i32::max_value() as i128),
120 ast::IntTy::I64 => (i64::min_value() as i128, i64::max_value() as i128),
121 ast::IntTy::I128 =>(i128::min_value() as i128, i128::max_value()),
125 fn uint_ty_range(uint_ty: ast::UintTy) -> (u128, u128) {
127 ast::UintTy::Usize => (u64::min_value() as u128, u64::max_value() as u128),
128 ast::UintTy::U8 => (u8::min_value() as u128, u8::max_value() as u128),
129 ast::UintTy::U16 => (u16::min_value() as u128, u16::max_value() as u128),
130 ast::UintTy::U32 => (u32::min_value() as u128, u32::max_value() as u128),
131 ast::UintTy::U64 => (u64::min_value() as u128, u64::max_value() as u128),
132 ast::UintTy::U128 => (u128::min_value(), u128::max_value()),
136 fn get_bin_hex_repr(cx: &LateContext<'_, '_>, lit: &hir::Lit) -> Option<String> {
137 let src = cx.sess().source_map().span_to_snippet(lit.span).ok()?;
138 let firstch = src.chars().next()?;
141 match src.chars().nth(1) {
142 Some('x') | Some('b') => return Some(src),
150 fn report_bin_hex_error(
151 cx: &LateContext<'_, '_>,
158 let size = layout::Integer::from_attr(&cx.tcx, ty).size();
159 let (t, actually) = match ty {
160 attr::IntType::SignedInt(t) => {
161 let actually = sign_extend(val, size) as i128;
162 (format!("{:?}", t), actually.to_string())
164 attr::IntType::UnsignedInt(t) => {
165 let actually = truncate(val, size);
166 (format!("{:?}", t), actually.to_string())
169 let mut err = cx.struct_span_lint(
170 OVERFLOWING_LITERALS,
172 &format!("literal out of range for {}", t),
175 "the literal `{}` (decimal `{}`) does not fit into \
176 an `{}` and will become `{}{}`",
177 repr_str, val, t, actually, t
179 if let Some(sugg_ty) =
180 get_type_suggestion(&cx.tables.node_type(expr.hir_id), val, negative)
182 if let Some(pos) = repr_str.chars().position(|c| c == 'i' || c == 'u') {
183 let (sans_suffix, _) = repr_str.split_at(pos);
186 &format!("consider using `{}` instead", sugg_ty),
187 format!("{}{}", sans_suffix, sugg_ty),
188 Applicability::MachineApplicable
191 err.help(&format!("consider using `{}` instead", sugg_ty));
198 // This function finds the next fitting type and generates a suggestion string.
199 // It searches for fitting types in the following way (`X < Y`):
200 // - `iX`: if literal fits in `uX` => `uX`, else => `iY`
204 // No suggestion for: `isize`, `usize`.
205 fn get_type_suggestion(t: Ty<'_>, val: u128, negative: bool) -> Option<String> {
206 use syntax::ast::IntTy::*;
207 use syntax::ast::UintTy::*;
208 macro_rules! find_fit {
209 ($ty:expr, $val:expr, $negative:expr,
210 $($type:ident => [$($utypes:expr),*] => [$($itypes:expr),*]),+) => {
212 let _neg = if negative { 1 } else { 0 };
215 $(if !negative && val <= uint_ty_range($utypes).1 {
216 return Some(format!("{:?}", $utypes))
218 $(if val <= int_ty_range($itypes).1 as u128 + _neg {
219 return Some(format!("{:?}", $itypes))
229 ty::Int(i) => find_fit!(i, val, negative,
230 I8 => [U8] => [I16, I32, I64, I128],
231 I16 => [U16] => [I32, I64, I128],
232 I32 => [U32] => [I64, I128],
233 I64 => [U64] => [I128],
234 I128 => [U128] => []),
235 ty::Uint(u) => find_fit!(u, val, negative,
236 U8 => [U8, U16, U32, U64, U128] => [],
237 U16 => [U16, U32, U64, U128] => [],
238 U32 => [U32, U64, U128] => [],
239 U64 => [U64, U128] => [],
240 U128 => [U128] => []),
245 fn lint_int_literal<'a, 'tcx>(
246 cx: &LateContext<'a, 'tcx>,
247 type_limits: &TypeLimits,
253 let int_type = if let ast::IntTy::Isize = t {
254 cx.sess().target.isize_ty
259 let (_, max) = int_ty_range(int_type);
260 let max = max as u128;
261 let negative = type_limits.negated_expr_id == e.hir_id;
263 // Detect literal value out of range [min, max] inclusive
264 // avoiding use of -min to prevent overflow/panic
265 if (negative && v > max + 1) || (!negative && v > max) {
266 if let Some(repr_str) = get_bin_hex_repr(cx, lit) {
267 report_bin_hex_error(
270 attr::IntType::SignedInt(t),
278 let par_id = cx.tcx.hir().get_parent_node_by_hir_id(e.hir_id);
279 if let Node::Expr(par_e) = cx.tcx.hir().get_by_hir_id(par_id) {
280 if let hir::ExprKind::Struct(..) = par_e.node {
281 if is_range_literal(cx.sess(), par_e)
282 && lint_overflowing_range_endpoint(cx, lit, v, max, e, par_e, t)
284 // The overflowing literal lint was overridden.
291 OVERFLOWING_LITERALS,
293 &format!("literal out of range for `{:?}`", t),
298 fn lint_uint_literal<'a, 'tcx>(
299 cx: &LateContext<'a, 'tcx>,
304 let uint_type = if let ast::UintTy::Usize = t {
305 cx.sess().target.usize_ty
309 let (min, max) = uint_ty_range(uint_type);
310 let lit_val: u128 = match lit.node {
311 // _v is u8, within range by definition
312 ast::LitKind::Byte(_v) => return,
313 ast::LitKind::Int(v, _) => v,
316 if lit_val < min || lit_val > max {
317 let parent_id = cx.tcx.hir().get_parent_node_by_hir_id(e.hir_id);
318 if let Node::Expr(par_e) = cx.tcx.hir().get_by_hir_id(parent_id) {
320 hir::ExprKind::Cast(..) => {
321 if let ty::Char = cx.tables.expr_ty(par_e).sty {
322 let mut err = cx.struct_span_lint(
323 OVERFLOWING_LITERALS,
325 "only `u8` can be cast into `char`",
329 &"use a `char` literal instead",
330 format!("'\\u{{{:X}}}'", lit_val),
331 Applicability::MachineApplicable,
337 hir::ExprKind::Struct(..)
338 if is_range_literal(cx.sess(), par_e) => {
339 if lint_overflowing_range_endpoint(cx, lit, lit_val, max, e, par_e, t) {
340 // The overflowing literal lint was overridden.
347 if let Some(repr_str) = get_bin_hex_repr(cx, lit) {
348 report_bin_hex_error(cx, e, attr::IntType::UnsignedInt(t), repr_str, lit_val, false);
352 OVERFLOWING_LITERALS,
354 &format!("literal out of range for `{:?}`", t),
359 fn lint_literal<'a, 'tcx>(
360 cx: &LateContext<'a, 'tcx>,
361 type_limits: &TypeLimits,
365 match cx.tables.node_type(e.hir_id).sty {
368 ast::LitKind::Int(v, ast::LitIntType::Signed(_)) |
369 ast::LitKind::Int(v, ast::LitIntType::Unsuffixed) => {
370 lint_int_literal(cx, type_limits, e, lit, t, v)
376 lint_uint_literal(cx, e, lit, t)
379 let is_infinite = match lit.node {
380 ast::LitKind::Float(v, _) |
381 ast::LitKind::FloatUnsuffixed(v) => {
383 ast::FloatTy::F32 => v.as_str().parse().map(f32::is_infinite),
384 ast::FloatTy::F64 => v.as_str().parse().map(f64::is_infinite),
389 if is_infinite == Ok(true) {
390 cx.span_lint(OVERFLOWING_LITERALS,
392 &format!("literal out of range for `{:?}`", t));
399 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TypeLimits {
400 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx hir::Expr) {
402 hir::ExprKind::Unary(hir::UnNeg, ref expr) => {
403 // propagate negation, if the negation itself isn't negated
404 if self.negated_expr_id != e.hir_id {
405 self.negated_expr_id = expr.hir_id;
408 hir::ExprKind::Binary(binop, ref l, ref r) => {
409 if is_comparison(binop) && !check_limits(cx, binop, &l, &r) {
410 cx.span_lint(UNUSED_COMPARISONS,
412 "comparison is useless due to type limits");
415 hir::ExprKind::Lit(ref lit) => lint_literal(cx, self, e, lit),
419 fn is_valid<T: cmp::PartialOrd>(binop: hir::BinOp, v: T, min: T, max: T) -> bool {
421 hir::BinOpKind::Lt => v > min && v <= max,
422 hir::BinOpKind::Le => v >= min && v < max,
423 hir::BinOpKind::Gt => v >= min && v < max,
424 hir::BinOpKind::Ge => v > min && v <= max,
425 hir::BinOpKind::Eq | hir::BinOpKind::Ne => v >= min && v <= max,
430 fn rev_binop(binop: hir::BinOp) -> hir::BinOp {
431 source_map::respan(binop.span,
433 hir::BinOpKind::Lt => hir::BinOpKind::Gt,
434 hir::BinOpKind::Le => hir::BinOpKind::Ge,
435 hir::BinOpKind::Gt => hir::BinOpKind::Lt,
436 hir::BinOpKind::Ge => hir::BinOpKind::Le,
441 fn check_limits(cx: &LateContext<'_, '_>,
446 let (lit, expr, swap) = match (&l.node, &r.node) {
447 (&hir::ExprKind::Lit(_), _) => (l, r, true),
448 (_, &hir::ExprKind::Lit(_)) => (r, l, false),
451 // Normalize the binop so that the literal is always on the RHS in
453 let norm_binop = if swap { rev_binop(binop) } else { binop };
454 match cx.tables.node_type(expr.hir_id).sty {
456 let (min, max) = int_ty_range(int_ty);
457 let lit_val: i128 = match lit.node {
458 hir::ExprKind::Lit(ref li) => {
460 ast::LitKind::Int(v, ast::LitIntType::Signed(_)) |
461 ast::LitKind::Int(v, ast::LitIntType::Unsuffixed) => v as i128,
467 is_valid(norm_binop, lit_val, min, max)
469 ty::Uint(uint_ty) => {
470 let (min, max) :(u128, u128) = uint_ty_range(uint_ty);
471 let lit_val: u128 = match lit.node {
472 hir::ExprKind::Lit(ref li) => {
474 ast::LitKind::Int(v, _) => v,
480 is_valid(norm_binop, lit_val, min, max)
486 fn is_comparison(binop: hir::BinOp) -> bool {
493 hir::BinOpKind::Gt => true,
503 "proper use of libc types in foreign modules"
506 declare_lint_pass!(ImproperCTypes => [IMPROPER_CTYPES]);
508 struct ImproperCTypesVisitor<'a, 'tcx: 'a> {
509 cx: &'a LateContext<'a, 'tcx>,
512 enum FfiResult<'tcx> {
514 FfiPhantom(Ty<'tcx>),
517 reason: &'static str,
518 help: Option<&'static str>,
522 fn is_zst<'tcx>(tcx: TyCtxt<'tcx, 'tcx>, did: DefId, ty: Ty<'tcx>) -> bool {
523 tcx.layout_of(tcx.param_env(did).and(ty)).map(|layout| layout.is_zst()).unwrap_or(false)
526 fn ty_is_known_nonnull<'tcx>(tcx: TyCtxt<'tcx, 'tcx>, ty: Ty<'tcx>) -> bool {
528 ty::FnPtr(_) => true,
530 ty::Adt(field_def, substs) if field_def.repr.transparent() && !field_def.is_union() => {
531 for field in field_def.all_fields() {
532 let field_ty = tcx.normalize_erasing_regions(
533 ParamEnv::reveal_all(),
534 field.ty(tcx, substs),
536 if is_zst(tcx, field.did, field_ty) {
540 let attrs = tcx.get_attrs(field_def.did);
541 if attrs.iter().any(|a| a.check_name(sym::rustc_nonnull_optimization_guaranteed)) ||
542 ty_is_known_nonnull(tcx, field_ty) {
553 /// Check if this enum can be safely exported based on the
554 /// "nullable pointer optimization". Currently restricted
555 /// to function pointers, references, core::num::NonZero*,
556 /// core::ptr::NonNull, and #[repr(transparent)] newtypes.
557 /// FIXME: This duplicates code in codegen.
558 fn is_repr_nullable_ptr<'tcx>(tcx: TyCtxt<'tcx, 'tcx>,
560 ty_def: &'tcx ty::AdtDef,
561 substs: SubstsRef<'tcx>)
563 if ty_def.variants.len() != 2 {
567 let get_variant_fields = |index| &ty_def.variants[VariantIdx::new(index)].fields;
568 let variant_fields = [get_variant_fields(0), get_variant_fields(1)];
569 let fields = if variant_fields[0].is_empty() {
571 } else if variant_fields[1].is_empty() {
577 if fields.len() != 1 {
581 let field_ty = fields[0].ty(tcx, substs);
582 if !ty_is_known_nonnull(tcx, field_ty) {
586 // At this point, the field's type is known to be nonnull and the parent enum is Option-like.
587 // If the computed size for the field and the enum are different, the nonnull optimization isn't
588 // being applied (and we've got a problem somewhere).
589 let compute_size_skeleton = |t| SizeSkeleton::compute(t, tcx, ParamEnv::reveal_all()).unwrap();
590 if !compute_size_skeleton(ty).same_size(compute_size_skeleton(field_ty)) {
591 bug!("improper_ctypes: Option nonnull optimization not applied?");
597 impl<'a, 'tcx> ImproperCTypesVisitor<'a, 'tcx> {
598 /// Checks if the given type is "ffi-safe" (has a stable, well-defined
599 /// representation which can be exported to C code).
600 fn check_type_for_ffi(&self,
601 cache: &mut FxHashSet<Ty<'tcx>>,
602 ty: Ty<'tcx>) -> FfiResult<'tcx> {
605 let cx = self.cx.tcx;
607 // Protect against infinite recursion, for example
608 // `struct S(*mut S);`.
609 // FIXME: A recursion limit is necessary as well, for irregular
611 if !cache.insert(ty) {
616 ty::Adt(def, substs) => {
617 if def.is_phantom_data() {
618 return FfiPhantom(ty);
620 match def.adt_kind() {
622 if !def.repr.c() && !def.repr.transparent() {
625 reason: "this struct has unspecified layout",
626 help: Some("consider adding a `#[repr(C)]` or \
627 `#[repr(transparent)]` attribute to this struct"),
631 if def.non_enum_variant().fields.is_empty() {
634 reason: "this struct has no fields",
635 help: Some("consider adding a member to this struct"),
639 // We can't completely trust repr(C) and repr(transparent) markings;
640 // make sure the fields are actually safe.
641 let mut all_phantom = true;
642 for field in &def.non_enum_variant().fields {
643 let field_ty = cx.normalize_erasing_regions(
644 ParamEnv::reveal_all(),
645 field.ty(cx, substs),
647 // repr(transparent) types are allowed to have arbitrary ZSTs, not just
648 // PhantomData -- skip checking all ZST fields
649 if def.repr.transparent() && is_zst(cx, field.did, field_ty) {
652 let r = self.check_type_for_ffi(cache, field_ty);
658 FfiUnsafe { .. } => {
664 if all_phantom { FfiPhantom(ty) } else { FfiSafe }
667 if !def.repr.c() && !def.repr.transparent() {
670 reason: "this union has unspecified layout",
671 help: Some("consider adding a `#[repr(C)]` or \
672 `#[repr(transparent)]` attribute to this union"),
676 if def.non_enum_variant().fields.is_empty() {
679 reason: "this union has no fields",
680 help: Some("consider adding a field to this union"),
684 let mut all_phantom = true;
685 for field in &def.non_enum_variant().fields {
686 let field_ty = cx.normalize_erasing_regions(
687 ParamEnv::reveal_all(),
688 field.ty(cx, substs),
690 // repr(transparent) types are allowed to have arbitrary ZSTs, not just
691 // PhantomData -- skip checking all ZST fields.
692 if def.repr.transparent() && is_zst(cx, field.did, field_ty) {
695 let r = self.check_type_for_ffi(cache, field_ty);
701 FfiUnsafe { .. } => {
707 if all_phantom { FfiPhantom(ty) } else { FfiSafe }
710 if def.variants.is_empty() {
711 // Empty enums are okay... although sort of useless.
715 // Check for a repr() attribute to specify the size of the
717 if !def.repr.c() && !def.repr.transparent() && def.repr.int.is_none() {
718 // Special-case types like `Option<extern fn()>`.
719 if !is_repr_nullable_ptr(cx, ty, def, substs) {
722 reason: "enum has no representation hint",
723 help: Some("consider adding a `#[repr(C)]`, \
724 `#[repr(transparent)]`, or integer `#[repr(...)]` \
725 attribute to this enum"),
730 // Check the contained variants.
731 for variant in &def.variants {
732 for field in &variant.fields {
733 let field_ty = cx.normalize_erasing_regions(
734 ParamEnv::reveal_all(),
735 field.ty(cx, substs),
737 // repr(transparent) types are allowed to have arbitrary ZSTs, not
738 // just PhantomData -- skip checking all ZST fields.
739 if def.repr.transparent() && is_zst(cx, field.did, field_ty) {
742 let r = self.check_type_for_ffi(cache, field_ty);
745 FfiUnsafe { .. } => {
751 reason: "this enum contains a PhantomData field",
763 ty::Char => FfiUnsafe {
765 reason: "the `char` type has no C equivalent",
766 help: Some("consider using `u32` or `libc::wchar_t` instead"),
769 ty::Int(ast::IntTy::I128) | ty::Uint(ast::UintTy::U128) => FfiUnsafe {
771 reason: "128-bit integers don't currently have a known stable ABI",
775 // Primitive types with a stable representation.
776 ty::Bool | ty::Int(..) | ty::Uint(..) | ty::Float(..) | ty::Never => FfiSafe,
778 ty::Slice(_) => FfiUnsafe {
780 reason: "slices have no C equivalent",
781 help: Some("consider using a raw pointer instead"),
784 ty::Dynamic(..) => FfiUnsafe {
786 reason: "trait objects have no C equivalent",
790 ty::Str => FfiUnsafe {
792 reason: "string slices have no C equivalent",
793 help: Some("consider using `*const u8` and a length instead"),
796 ty::Tuple(..) => FfiUnsafe {
798 reason: "tuples have unspecified layout",
799 help: Some("consider using a struct instead"),
802 ty::RawPtr(ty::TypeAndMut { ty, .. }) |
803 ty::Ref(_, ty, _) => self.check_type_for_ffi(cache, ty),
805 ty::Array(ty, _) => self.check_type_for_ffi(cache, ty),
809 Abi::Rust | Abi::RustIntrinsic | Abi::PlatformIntrinsic | Abi::RustCall => {
812 reason: "this function pointer has Rust-specific calling convention",
813 help: Some("consider using an `extern fn(...) -> ...` \
814 function pointer instead"),
820 let sig = cx.erase_late_bound_regions(&sig);
821 if !sig.output().is_unit() {
822 let r = self.check_type_for_ffi(cache, sig.output());
830 for arg in sig.inputs() {
831 let r = self.check_type_for_ffi(cache, arg);
842 ty::Foreign(..) => FfiSafe,
850 ty::GeneratorWitness(..) |
851 ty::Placeholder(..) |
852 ty::UnnormalizedProjection(..) |
855 ty::FnDef(..) => bug!("Unexpected type in foreign function"),
859 fn check_type_for_ffi_and_report_errors(&mut self, sp: Span, ty: Ty<'tcx>) {
860 // it is only OK to use this function because extern fns cannot have
861 // any generic types right now:
862 let ty = self.cx.tcx.normalize_erasing_regions(ParamEnv::reveal_all(), ty);
864 match self.check_type_for_ffi(&mut FxHashSet::default(), ty) {
865 FfiResult::FfiSafe => {}
866 FfiResult::FfiPhantom(ty) => {
867 self.cx.span_lint(IMPROPER_CTYPES,
869 &format!("`extern` block uses type `{}` which is not FFI-safe: \
870 composed only of PhantomData", ty));
872 FfiResult::FfiUnsafe { ty: unsafe_ty, reason, help } => {
873 let msg = format!("`extern` block uses type `{}` which is not FFI-safe: {}",
875 let mut diag = self.cx.struct_span_lint(IMPROPER_CTYPES, sp, &msg);
876 if let Some(s) = help {
879 if let ty::Adt(def, _) = unsafe_ty.sty {
880 if let Some(sp) = self.cx.tcx.hir().span_if_local(def.did) {
881 diag.span_note(sp, "type defined here");
889 fn check_foreign_fn(&mut self, id: hir::HirId, decl: &hir::FnDecl) {
890 let def_id = self.cx.tcx.hir().local_def_id_from_hir_id(id);
891 let sig = self.cx.tcx.fn_sig(def_id);
892 let sig = self.cx.tcx.erase_late_bound_regions(&sig);
893 let inputs = if sig.c_variadic {
894 // Don't include the spoofed `VaList` in the functions list
896 &sig.inputs()[..sig.inputs().len() - 1]
901 for (input_ty, input_hir) in inputs.iter().zip(&decl.inputs) {
902 self.check_type_for_ffi_and_report_errors(input_hir.span, input_ty);
905 if let hir::Return(ref ret_hir) = decl.output {
906 let ret_ty = sig.output();
907 if !ret_ty.is_unit() {
908 self.check_type_for_ffi_and_report_errors(ret_hir.span, ret_ty);
913 fn check_foreign_static(&mut self, id: hir::HirId, span: Span) {
914 let def_id = self.cx.tcx.hir().local_def_id_from_hir_id(id);
915 let ty = self.cx.tcx.type_of(def_id);
916 self.check_type_for_ffi_and_report_errors(span, ty);
920 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ImproperCTypes {
921 fn check_foreign_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::ForeignItem) {
922 let mut vis = ImproperCTypesVisitor { cx };
923 let abi = cx.tcx.hir().get_foreign_abi_by_hir_id(it.hir_id);
924 if abi != Abi::RustIntrinsic && abi != Abi::PlatformIntrinsic {
926 hir::ForeignItemKind::Fn(ref decl, _, _) => {
927 vis.check_foreign_fn(it.hir_id, decl);
929 hir::ForeignItemKind::Static(ref ty, _) => {
930 vis.check_foreign_static(it.hir_id, ty.span);
932 hir::ForeignItemKind::Type => ()
938 declare_lint_pass!(VariantSizeDifferences => [VARIANT_SIZE_DIFFERENCES]);
940 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for VariantSizeDifferences {
941 fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item) {
942 if let hir::ItemKind::Enum(ref enum_definition, _) = it.node {
943 let item_def_id = cx.tcx.hir().local_def_id_from_hir_id(it.hir_id);
944 let t = cx.tcx.type_of(item_def_id);
945 let ty = cx.tcx.erase_regions(&t);
946 let layout = match cx.layout_of(ty) {
947 Ok(layout) => layout,
948 Err(ty::layout::LayoutError::Unknown(_)) => return,
949 Err(err @ ty::layout::LayoutError::SizeOverflow(_)) => {
950 bug!("failed to get layout for `{}`: {}", t, err);
953 let (variants, tag) = match layout.variants {
954 layout::Variants::Multiple {
955 discr_kind: layout::DiscriminantKind::Tag,
959 } => (variants, discr),
963 let discr_size = tag.value.size(&cx.tcx).bytes();
965 debug!("enum `{}` is {} bytes large with layout:\n{:#?}",
966 t, layout.size.bytes(), layout);
968 let (largest, slargest, largest_index) = enum_definition.variants
971 .map(|(variant, variant_layout)| {
972 // Subtract the size of the enum discriminant.
973 let bytes = variant_layout.size.bytes().saturating_sub(discr_size);
975 debug!("- variant `{}` is {} bytes large",
981 .fold((0, 0, 0), |(l, s, li), (idx, size)| if size > l {
989 // We only warn if the largest variant is at least thrice as large as
990 // the second-largest.
991 if largest > slargest * 3 && slargest > 0 {
992 cx.span_lint(VARIANT_SIZE_DIFFERENCES,
993 enum_definition.variants[largest_index].span,
994 &format!("enum variant is more than three times \
995 larger ({} bytes) than the next largest",