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<'a>(
209 ) -> Option<String> {
210 use syntax::ast::IntTy::*;
211 use syntax::ast::UintTy::*;
212 macro_rules! find_fit {
213 ($ty:expr, $val:expr, $negative:expr,
214 $($type:ident => [$($utypes:expr),*] => [$($itypes:expr),*]),+) => {
216 let _neg = if negative { 1 } else { 0 };
219 $(if !negative && val <= uint_ty_range($utypes).1 {
220 return Some(format!("{:?}", $utypes))
222 $(if val <= int_ty_range($itypes).1 as u128 + _neg {
223 return Some(format!("{:?}", $itypes))
233 ty::Int(i) => find_fit!(i, val, negative,
234 I8 => [U8] => [I16, I32, I64, I128],
235 I16 => [U16] => [I32, I64, I128],
236 I32 => [U32] => [I64, I128],
237 I64 => [U64] => [I128],
238 I128 => [U128] => []),
239 ty::Uint(u) => find_fit!(u, val, negative,
240 U8 => [U8, U16, U32, U64, U128] => [],
241 U16 => [U16, U32, U64, U128] => [],
242 U32 => [U32, U64, U128] => [],
243 U64 => [U64, U128] => [],
244 U128 => [U128] => []),
249 fn lint_int_literal<'a, 'tcx>(
250 cx: &LateContext<'a, 'tcx>,
251 type_limits: &TypeLimits,
257 let int_type = if let ast::IntTy::Isize = t {
258 cx.sess().target.isize_ty
263 let (_, max) = int_ty_range(int_type);
264 let max = max as u128;
265 let negative = type_limits.negated_expr_id == e.hir_id;
267 // Detect literal value out of range [min, max] inclusive
268 // avoiding use of -min to prevent overflow/panic
269 if (negative && v > max + 1) || (!negative && v > max) {
270 if let Some(repr_str) = get_bin_hex_repr(cx, lit) {
271 report_bin_hex_error(
274 attr::IntType::SignedInt(t),
282 let par_id = cx.tcx.hir().get_parent_node_by_hir_id(e.hir_id);
283 if let Node::Expr(par_e) = cx.tcx.hir().get_by_hir_id(par_id) {
284 if let hir::ExprKind::Struct(..) = par_e.node {
285 if is_range_literal(cx.sess(), par_e)
286 && lint_overflowing_range_endpoint(cx, lit, v, max, e, par_e, t)
288 // The overflowing literal lint was overridden.
295 OVERFLOWING_LITERALS,
297 &format!("literal out of range for `{:?}`", t),
302 fn lint_uint_literal<'a, 'tcx>(
303 cx: &LateContext<'a, 'tcx>,
308 let uint_type = if let ast::UintTy::Usize = t {
309 cx.sess().target.usize_ty
313 let (min, max) = uint_ty_range(uint_type);
314 let lit_val: u128 = match lit.node {
315 // _v is u8, within range by definition
316 ast::LitKind::Byte(_v) => return,
317 ast::LitKind::Int(v, _) => v,
320 if lit_val < min || lit_val > max {
321 let parent_id = cx.tcx.hir().get_parent_node_by_hir_id(e.hir_id);
322 if let Node::Expr(par_e) = cx.tcx.hir().get_by_hir_id(parent_id) {
324 hir::ExprKind::Cast(..) => {
325 if let ty::Char = cx.tables.expr_ty(par_e).sty {
326 let mut err = cx.struct_span_lint(
327 OVERFLOWING_LITERALS,
329 "only `u8` can be cast into `char`",
333 &"use a `char` literal instead",
334 format!("'\\u{{{:X}}}'", lit_val),
335 Applicability::MachineApplicable,
341 hir::ExprKind::Struct(..)
342 if is_range_literal(cx.sess(), par_e) => {
343 if lint_overflowing_range_endpoint(cx, lit, lit_val, max, e, par_e, t) {
344 // The overflowing literal lint was overridden.
351 if let Some(repr_str) = get_bin_hex_repr(cx, lit) {
352 report_bin_hex_error(cx, e, attr::IntType::UnsignedInt(t), repr_str, lit_val, false);
356 OVERFLOWING_LITERALS,
358 &format!("literal out of range for `{:?}`", t),
363 fn lint_literal<'a, 'tcx>(
364 cx: &LateContext<'a, 'tcx>,
365 type_limits: &TypeLimits,
369 match cx.tables.node_type(e.hir_id).sty {
372 ast::LitKind::Int(v, ast::LitIntType::Signed(_)) |
373 ast::LitKind::Int(v, ast::LitIntType::Unsuffixed) => {
374 lint_int_literal(cx, type_limits, e, lit, t, v)
380 lint_uint_literal(cx, e, lit, t)
383 let is_infinite = match lit.node {
384 ast::LitKind::Float(v, _) |
385 ast::LitKind::FloatUnsuffixed(v) => {
387 ast::FloatTy::F32 => v.as_str().parse().map(f32::is_infinite),
388 ast::FloatTy::F64 => v.as_str().parse().map(f64::is_infinite),
393 if is_infinite == Ok(true) {
394 cx.span_lint(OVERFLOWING_LITERALS,
396 &format!("literal out of range for `{:?}`", t));
403 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TypeLimits {
404 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx hir::Expr) {
406 hir::ExprKind::Unary(hir::UnNeg, ref expr) => {
407 // propagate negation, if the negation itself isn't negated
408 if self.negated_expr_id != e.hir_id {
409 self.negated_expr_id = expr.hir_id;
412 hir::ExprKind::Binary(binop, ref l, ref r) => {
413 if is_comparison(binop) && !check_limits(cx, binop, &l, &r) {
414 cx.span_lint(UNUSED_COMPARISONS,
416 "comparison is useless due to type limits");
419 hir::ExprKind::Lit(ref lit) => lint_literal(cx, self, e, lit),
423 fn is_valid<T: cmp::PartialOrd>(binop: hir::BinOp, v: T, min: T, max: T) -> bool {
425 hir::BinOpKind::Lt => v > min && v <= max,
426 hir::BinOpKind::Le => v >= min && v < max,
427 hir::BinOpKind::Gt => v >= min && v < max,
428 hir::BinOpKind::Ge => v > min && v <= max,
429 hir::BinOpKind::Eq | hir::BinOpKind::Ne => v >= min && v <= max,
434 fn rev_binop(binop: hir::BinOp) -> hir::BinOp {
435 source_map::respan(binop.span,
437 hir::BinOpKind::Lt => hir::BinOpKind::Gt,
438 hir::BinOpKind::Le => hir::BinOpKind::Ge,
439 hir::BinOpKind::Gt => hir::BinOpKind::Lt,
440 hir::BinOpKind::Ge => hir::BinOpKind::Le,
445 fn check_limits(cx: &LateContext<'_, '_>,
450 let (lit, expr, swap) = match (&l.node, &r.node) {
451 (&hir::ExprKind::Lit(_), _) => (l, r, true),
452 (_, &hir::ExprKind::Lit(_)) => (r, l, false),
455 // Normalize the binop so that the literal is always on the RHS in
457 let norm_binop = if swap { rev_binop(binop) } else { binop };
458 match cx.tables.node_type(expr.hir_id).sty {
460 let (min, max) = int_ty_range(int_ty);
461 let lit_val: i128 = match lit.node {
462 hir::ExprKind::Lit(ref li) => {
464 ast::LitKind::Int(v, ast::LitIntType::Signed(_)) |
465 ast::LitKind::Int(v, ast::LitIntType::Unsuffixed) => v as i128,
471 is_valid(norm_binop, lit_val, min, max)
473 ty::Uint(uint_ty) => {
474 let (min, max) :(u128, u128) = uint_ty_range(uint_ty);
475 let lit_val: u128 = match lit.node {
476 hir::ExprKind::Lit(ref li) => {
478 ast::LitKind::Int(v, _) => v,
484 is_valid(norm_binop, lit_val, min, max)
490 fn is_comparison(binop: hir::BinOp) -> bool {
497 hir::BinOpKind::Gt => true,
507 "proper use of libc types in foreign modules"
510 declare_lint_pass!(ImproperCTypes => [IMPROPER_CTYPES]);
512 struct ImproperCTypesVisitor<'a, 'tcx: 'a> {
513 cx: &'a LateContext<'a, 'tcx>,
516 enum FfiResult<'tcx> {
518 FfiPhantom(Ty<'tcx>),
521 reason: &'static str,
522 help: Option<&'static str>,
526 fn is_zst<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, did: DefId, ty: Ty<'tcx>) -> bool {
527 tcx.layout_of(tcx.param_env(did).and(ty)).map(|layout| layout.is_zst()).unwrap_or(false)
530 fn ty_is_known_nonnull<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, ty: Ty<'tcx>) -> bool {
532 ty::FnPtr(_) => true,
534 ty::Adt(field_def, substs) if field_def.repr.transparent() && field_def.is_struct() => {
535 for field in &field_def.non_enum_variant().fields {
536 let field_ty = tcx.normalize_erasing_regions(
537 ParamEnv::reveal_all(),
538 field.ty(tcx, substs),
540 if is_zst(tcx, field.did, field_ty) {
544 let attrs = tcx.get_attrs(field_def.did);
545 if attrs.iter().any(|a| a.check_name(sym::rustc_nonnull_optimization_guaranteed)) ||
546 ty_is_known_nonnull(tcx, field_ty) {
557 /// Check if this enum can be safely exported based on the
558 /// "nullable pointer optimization". Currently restricted
559 /// to function pointers, references, core::num::NonZero*,
560 /// core::ptr::NonNull, and #[repr(transparent)] newtypes.
561 /// FIXME: This duplicates code in codegen.
562 fn is_repr_nullable_ptr<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
564 ty_def: &'tcx ty::AdtDef,
565 substs: SubstsRef<'tcx>)
567 if ty_def.variants.len() != 2 {
571 let get_variant_fields = |index| &ty_def.variants[VariantIdx::new(index)].fields;
572 let variant_fields = [get_variant_fields(0), get_variant_fields(1)];
573 let fields = if variant_fields[0].is_empty() {
575 } else if variant_fields[1].is_empty() {
581 if fields.len() != 1 {
585 let field_ty = fields[0].ty(tcx, substs);
586 if !ty_is_known_nonnull(tcx, field_ty) {
590 // At this point, the field's type is known to be nonnull and the parent enum is Option-like.
591 // If the computed size for the field and the enum are different, the nonnull optimization isn't
592 // being applied (and we've got a problem somewhere).
593 let compute_size_skeleton = |t| SizeSkeleton::compute(t, tcx, ParamEnv::reveal_all()).unwrap();
594 if !compute_size_skeleton(ty).same_size(compute_size_skeleton(field_ty)) {
595 bug!("improper_ctypes: Option nonnull optimization not applied?");
601 impl<'a, 'tcx> ImproperCTypesVisitor<'a, 'tcx> {
602 /// Checks if the given type is "ffi-safe" (has a stable, well-defined
603 /// representation which can be exported to C code).
604 fn check_type_for_ffi(&self,
605 cache: &mut FxHashSet<Ty<'tcx>>,
606 ty: Ty<'tcx>) -> FfiResult<'tcx> {
609 let cx = self.cx.tcx;
611 // Protect against infinite recursion, for example
612 // `struct S(*mut S);`.
613 // FIXME: A recursion limit is necessary as well, for irregular
615 if !cache.insert(ty) {
620 ty::Adt(def, substs) => {
621 if def.is_phantom_data() {
622 return FfiPhantom(ty);
624 match def.adt_kind() {
626 if !def.repr.c() && !def.repr.transparent() {
629 reason: "this struct has unspecified layout",
630 help: Some("consider adding a #[repr(C)] or #[repr(transparent)] \
631 attribute to this struct"),
635 if def.non_enum_variant().fields.is_empty() {
638 reason: "this struct has no fields",
639 help: Some("consider adding a member to this struct"),
643 // We can't completely trust repr(C) and repr(transparent) markings;
644 // make sure the fields are actually safe.
645 let mut all_phantom = true;
646 for field in &def.non_enum_variant().fields {
647 let field_ty = cx.normalize_erasing_regions(
648 ParamEnv::reveal_all(),
649 field.ty(cx, substs),
651 // repr(transparent) types are allowed to have arbitrary ZSTs, not just
652 // PhantomData -- skip checking all ZST fields
653 if def.repr.transparent() && is_zst(cx, field.did, field_ty) {
656 let r = self.check_type_for_ffi(cache, field_ty);
662 FfiUnsafe { .. } => {
668 if all_phantom { FfiPhantom(ty) } else { FfiSafe }
674 reason: "this union has unspecified layout",
675 help: Some("consider adding a #[repr(C)] attribute to this union"),
679 if def.non_enum_variant().fields.is_empty() {
682 reason: "this union has no fields",
683 help: Some("consider adding a field to this union"),
687 let mut all_phantom = true;
688 for field in &def.non_enum_variant().fields {
689 let field_ty = cx.normalize_erasing_regions(
690 ParamEnv::reveal_all(),
691 field.ty(cx, substs),
693 let r = self.check_type_for_ffi(cache, field_ty);
699 FfiUnsafe { .. } => {
705 if all_phantom { FfiPhantom(ty) } else { FfiSafe }
708 if def.variants.is_empty() {
709 // Empty enums are okay... although sort of useless.
713 // Check for a repr() attribute to specify the size of the
715 if !def.repr.c() && def.repr.int.is_none() {
716 // Special-case types like `Option<extern fn()>`.
717 if !is_repr_nullable_ptr(cx, ty, def, substs) {
720 reason: "enum has no representation hint",
721 help: Some("consider adding a #[repr(...)] attribute \
727 // Check the contained variants.
728 for variant in &def.variants {
729 for field in &variant.fields {
730 let arg = cx.normalize_erasing_regions(
731 ParamEnv::reveal_all(),
732 field.ty(cx, substs),
734 let r = self.check_type_for_ffi(cache, arg);
737 FfiUnsafe { .. } => {
743 reason: "this enum contains a PhantomData field",
755 ty::Char => FfiUnsafe {
757 reason: "the `char` type has no C equivalent",
758 help: Some("consider using `u32` or `libc::wchar_t` instead"),
761 ty::Int(ast::IntTy::I128) | ty::Uint(ast::UintTy::U128) => FfiUnsafe {
763 reason: "128-bit integers don't currently have a known stable ABI",
767 // Primitive types with a stable representation.
768 ty::Bool | ty::Int(..) | ty::Uint(..) | ty::Float(..) | ty::Never => FfiSafe,
770 ty::Slice(_) => FfiUnsafe {
772 reason: "slices have no C equivalent",
773 help: Some("consider using a raw pointer instead"),
776 ty::Dynamic(..) => FfiUnsafe {
778 reason: "trait objects have no C equivalent",
782 ty::Str => FfiUnsafe {
784 reason: "string slices have no C equivalent",
785 help: Some("consider using `*const u8` and a length instead"),
788 ty::Tuple(..) => FfiUnsafe {
790 reason: "tuples have unspecified layout",
791 help: Some("consider using a struct instead"),
794 ty::RawPtr(ty::TypeAndMut { ty, .. }) |
795 ty::Ref(_, ty, _) => self.check_type_for_ffi(cache, ty),
797 ty::Array(ty, _) => self.check_type_for_ffi(cache, ty),
801 Abi::Rust | Abi::RustIntrinsic | Abi::PlatformIntrinsic | Abi::RustCall => {
804 reason: "this function pointer has Rust-specific calling convention",
805 help: Some("consider using an `extern fn(...) -> ...` \
806 function pointer instead"),
812 let sig = cx.erase_late_bound_regions(&sig);
813 if !sig.output().is_unit() {
814 let r = self.check_type_for_ffi(cache, sig.output());
822 for arg in sig.inputs() {
823 let r = self.check_type_for_ffi(cache, arg);
834 ty::Foreign(..) => FfiSafe,
842 ty::GeneratorWitness(..) |
843 ty::Placeholder(..) |
844 ty::UnnormalizedProjection(..) |
847 ty::FnDef(..) => bug!("Unexpected type in foreign function"),
851 fn check_type_for_ffi_and_report_errors(&mut self, sp: Span, ty: Ty<'tcx>) {
852 // it is only OK to use this function because extern fns cannot have
853 // any generic types right now:
854 let ty = self.cx.tcx.normalize_erasing_regions(ParamEnv::reveal_all(), ty);
856 match self.check_type_for_ffi(&mut FxHashSet::default(), ty) {
857 FfiResult::FfiSafe => {}
858 FfiResult::FfiPhantom(ty) => {
859 self.cx.span_lint(IMPROPER_CTYPES,
861 &format!("`extern` block uses type `{}` which is not FFI-safe: \
862 composed only of PhantomData", ty));
864 FfiResult::FfiUnsafe { ty: unsafe_ty, reason, help } => {
865 let msg = format!("`extern` block uses type `{}` which is not FFI-safe: {}",
867 let mut diag = self.cx.struct_span_lint(IMPROPER_CTYPES, sp, &msg);
868 if let Some(s) = help {
871 if let ty::Adt(def, _) = unsafe_ty.sty {
872 if let Some(sp) = self.cx.tcx.hir().span_if_local(def.did) {
873 diag.span_note(sp, "type defined here");
881 fn check_foreign_fn(&mut self, id: hir::HirId, decl: &hir::FnDecl) {
882 let def_id = self.cx.tcx.hir().local_def_id_from_hir_id(id);
883 let sig = self.cx.tcx.fn_sig(def_id);
884 let sig = self.cx.tcx.erase_late_bound_regions(&sig);
885 let inputs = if sig.c_variadic {
886 // Don't include the spoofed `VaList` in the functions list
888 &sig.inputs()[..sig.inputs().len() - 1]
893 for (input_ty, input_hir) in inputs.iter().zip(&decl.inputs) {
894 self.check_type_for_ffi_and_report_errors(input_hir.span, input_ty);
897 if let hir::Return(ref ret_hir) = decl.output {
898 let ret_ty = sig.output();
899 if !ret_ty.is_unit() {
900 self.check_type_for_ffi_and_report_errors(ret_hir.span, ret_ty);
905 fn check_foreign_static(&mut self, id: hir::HirId, span: Span) {
906 let def_id = self.cx.tcx.hir().local_def_id_from_hir_id(id);
907 let ty = self.cx.tcx.type_of(def_id);
908 self.check_type_for_ffi_and_report_errors(span, ty);
912 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ImproperCTypes {
913 fn check_foreign_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::ForeignItem) {
914 let mut vis = ImproperCTypesVisitor { cx };
915 let abi = cx.tcx.hir().get_foreign_abi_by_hir_id(it.hir_id);
916 if abi != Abi::RustIntrinsic && abi != Abi::PlatformIntrinsic {
918 hir::ForeignItemKind::Fn(ref decl, _, _) => {
919 vis.check_foreign_fn(it.hir_id, decl);
921 hir::ForeignItemKind::Static(ref ty, _) => {
922 vis.check_foreign_static(it.hir_id, ty.span);
924 hir::ForeignItemKind::Type => ()
930 declare_lint_pass!(VariantSizeDifferences => [VARIANT_SIZE_DIFFERENCES]);
932 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for VariantSizeDifferences {
933 fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item) {
934 if let hir::ItemKind::Enum(ref enum_definition, _) = it.node {
935 let item_def_id = cx.tcx.hir().local_def_id_from_hir_id(it.hir_id);
936 let t = cx.tcx.type_of(item_def_id);
937 let ty = cx.tcx.erase_regions(&t);
938 let layout = match cx.layout_of(ty) {
939 Ok(layout) => layout,
940 Err(ty::layout::LayoutError::Unknown(_)) => return,
941 Err(err @ ty::layout::LayoutError::SizeOverflow(_)) => {
942 bug!("failed to get layout for `{}`: {}", t, err);
945 let (variants, tag) = match layout.variants {
946 layout::Variants::Multiple {
947 discr_kind: layout::DiscriminantKind::Tag,
951 } => (variants, discr),
955 let discr_size = tag.value.size(&cx.tcx).bytes();
957 debug!("enum `{}` is {} bytes large with layout:\n{:#?}",
958 t, layout.size.bytes(), layout);
960 let (largest, slargest, largest_index) = enum_definition.variants
963 .map(|(variant, variant_layout)| {
964 // Subtract the size of the enum discriminant.
965 let bytes = variant_layout.size.bytes().saturating_sub(discr_size);
967 debug!("- variant `{}` is {} bytes large",
973 .fold((0, 0, 0), |(l, s, li), (idx, size)| if size > l {
981 // We only warn if the largest variant is at least thrice as large as
982 // the second-largest.
983 if largest > slargest * 3 && slargest > 0 {
984 cx.span_lint(VARIANT_SIZE_DIFFERENCES,
985 enum_definition.variants[largest_index].span,
986 &format!("enum variant is more than three times \
987 larger ({} bytes) than the next largest",