]> git.lizzy.rs Git - rust.git/blob - src/librustc_lint/types.rs
494f0b66760521841addad4ab77c09aa6d023a40
[rust.git] / src / librustc_lint / types.rs
1 #![allow(non_snake_case)]
2
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};
14
15 use std::cmp;
16 use std::{i8, i16, i32, i64, u8, u16, u32, u64, f32, f64};
17
18 use syntax::{ast, attr, source_map};
19 use syntax::errors::Applicability;
20 use syntax::symbol::sym;
21 use rustc_target::spec::abi::Abi;
22 use syntax_pos::Span;
23
24 use rustc::hir;
25
26 use rustc::mir::interpret::{sign_extend, truncate};
27
28 use log::debug;
29
30 declare_lint! {
31     UNUSED_COMPARISONS,
32     Warn,
33     "comparisons made useless by limits of the types involved"
34 }
35
36 declare_lint! {
37     OVERFLOWING_LITERALS,
38     Deny,
39     "literal out of range for its type"
40 }
41
42 declare_lint! {
43     VARIANT_SIZE_DIFFERENCES,
44     Allow,
45     "detects enums with widely varying variant sizes"
46 }
47
48 #[derive(Copy, Clone)]
49 pub struct TypeLimits {
50     /// Id of the last visited negated expression
51     negated_expr_id: hir::HirId,
52 }
53
54 impl_lint_pass!(TypeLimits => [UNUSED_COMPARISONS, OVERFLOWING_LITERALS]);
55
56 impl TypeLimits {
57     pub fn new() -> TypeLimits {
58         TypeLimits { negated_expr_id: hir::DUMMY_HIR_ID }
59     }
60 }
61
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>,
66     lit: &hir::Lit,
67     lit_val: u128,
68     max: u128,
69     expr: &'tcx hir::Expr,
70     parent_expr: &'tcx hir::Expr,
71     ty: impl std::fmt::Debug,
72 ) -> bool {
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(
82                 OVERFLOWING_LITERALS,
83                 parent_expr.span,
84                 &format!("range endpoint is out of range for `{:?}`", ty),
85             );
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(),
94                     _ => bug!(),
95                 };
96                 let suggestion = format!("{}..={}{}", start, lit_val - 1, suffix);
97                 err.span_suggestion(
98                     parent_expr.span,
99                     &"use an inclusive range instead",
100                     suggestion,
101                     Applicability::MachineApplicable,
102                 );
103                 err.emit();
104                 return true;
105             }
106         }
107     }
108
109     false
110 }
111
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) {
115     match int_ty {
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()),
122     }
123 }
124
125 fn uint_ty_range(uint_ty: ast::UintTy) -> (u128, u128) {
126     match uint_ty {
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()),
133     }
134 }
135
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()?;
139
140     if firstch == '0' {
141         match src.chars().nth(1) {
142             Some('x') | Some('b') => return Some(src),
143             _ => return None,
144         }
145     }
146
147     None
148 }
149
150 fn report_bin_hex_error(
151     cx: &LateContext<'_, '_>,
152     expr: &hir::Expr,
153     ty: attr::IntType,
154     repr_str: String,
155     val: u128,
156     negative: bool,
157 ) {
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())
163         }
164         attr::IntType::UnsignedInt(t) => {
165             let actually = truncate(val, size);
166             (format!("{:?}", t), actually.to_string())
167         }
168     };
169     let mut err = cx.struct_span_lint(
170         OVERFLOWING_LITERALS,
171         expr.span,
172         &format!("literal out of range for {}", t),
173     );
174     err.note(&format!(
175         "the literal `{}` (decimal `{}`) does not fit into \
176             an `{}` and will become `{}{}`",
177         repr_str, val, t, actually, t
178     ));
179     if let Some(sugg_ty) =
180         get_type_suggestion(&cx.tables.node_type(expr.hir_id), val, negative)
181     {
182         if let Some(pos) = repr_str.chars().position(|c| c == 'i' || c == 'u') {
183             let (sans_suffix, _) = repr_str.split_at(pos);
184             err.span_suggestion(
185                 expr.span,
186                 &format!("consider using `{}` instead", sugg_ty),
187                 format!("{}{}", sans_suffix, sugg_ty),
188                 Applicability::MachineApplicable
189             );
190         } else {
191             err.help(&format!("consider using `{}` instead", sugg_ty));
192         }
193     }
194
195     err.emit();
196 }
197
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`
201 //  - `-iX` => `iY`
202 //  - `uX` => `uY`
203 //
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),*]),+) => {
211             {
212                 let _neg = if negative { 1 } else { 0 };
213                 match $ty {
214                     $($type => {
215                         $(if !negative && val <= uint_ty_range($utypes).1 {
216                             return Some(format!("{:?}", $utypes))
217                         })*
218                         $(if val <= int_ty_range($itypes).1 as u128 + _neg {
219                             return Some(format!("{:?}", $itypes))
220                         })*
221                         None
222                     },)*
223                     _ => None
224                 }
225             }
226         }
227     }
228     match t.sty {
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] => []),
241         _ => None,
242     }
243 }
244
245 fn lint_int_literal<'a, 'tcx>(
246     cx: &LateContext<'a, 'tcx>,
247     type_limits: &TypeLimits,
248     e: &'tcx hir::Expr,
249     lit: &hir::Lit,
250     t: ast::IntTy,
251     v: u128,
252 ) {
253     let int_type = if let ast::IntTy::Isize = t {
254         cx.sess().target.isize_ty
255     } else {
256         t
257     };
258
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;
262
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(
268                 cx,
269                 e,
270                 attr::IntType::SignedInt(t),
271                 repr_str,
272                 v,
273                 negative,
274             );
275             return;
276         }
277
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)
283                 {
284                     // The overflowing literal lint was overridden.
285                     return;
286                 }
287             }
288         }
289
290         cx.span_lint(
291             OVERFLOWING_LITERALS,
292             e.span,
293             &format!("literal out of range for `{:?}`", t),
294         );
295     }
296 }
297
298 fn lint_uint_literal<'a, 'tcx>(
299     cx: &LateContext<'a, 'tcx>,
300     e: &'tcx hir::Expr,
301     lit: &hir::Lit,
302     t: ast::UintTy,
303 ) {
304     let uint_type = if let ast::UintTy::Usize = t {
305         cx.sess().target.usize_ty
306     } else {
307         t
308     };
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,
314         _ => bug!(),
315     };
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) {
319             match par_e.node {
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,
324                             par_e.span,
325                             "only `u8` can be cast into `char`",
326                         );
327                         err.span_suggestion(
328                             par_e.span,
329                             &"use a `char` literal instead",
330                             format!("'\\u{{{:X}}}'", lit_val),
331                             Applicability::MachineApplicable,
332                         );
333                         err.emit();
334                         return;
335                     }
336                 }
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.
341                             return;
342                         }
343                     }
344                 _ => {}
345             }
346         }
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);
349             return;
350         }
351         cx.span_lint(
352             OVERFLOWING_LITERALS,
353             e.span,
354             &format!("literal out of range for `{:?}`", t),
355         );
356     }
357 }
358
359 fn lint_literal<'a, 'tcx>(
360     cx: &LateContext<'a, 'tcx>,
361     type_limits: &TypeLimits,
362     e: &'tcx hir::Expr,
363     lit: &hir::Lit,
364 ) {
365     match cx.tables.node_type(e.hir_id).sty {
366         ty::Int(t) => {
367             match lit.node {
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)
371                 }
372                 _ => bug!(),
373             };
374         }
375         ty::Uint(t) => {
376             lint_uint_literal(cx, e, lit, t)
377         }
378         ty::Float(t) => {
379             let is_infinite = match lit.node {
380                 ast::LitKind::Float(v, _) |
381                 ast::LitKind::FloatUnsuffixed(v) => {
382                     match t {
383                         ast::FloatTy::F32 => v.as_str().parse().map(f32::is_infinite),
384                         ast::FloatTy::F64 => v.as_str().parse().map(f64::is_infinite),
385                     }
386                 }
387                 _ => bug!(),
388             };
389             if is_infinite == Ok(true) {
390                 cx.span_lint(OVERFLOWING_LITERALS,
391                              e.span,
392                              &format!("literal out of range for `{:?}`", t));
393             }
394         }
395         _ => {}
396     }
397 }
398
399 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TypeLimits {
400     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx hir::Expr) {
401         match e.node {
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;
406                 }
407             }
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,
411                                  e.span,
412                                  "comparison is useless due to type limits");
413                 }
414             }
415             hir::ExprKind::Lit(ref lit) => lint_literal(cx, self, e, lit),
416             _ => {}
417         };
418
419         fn is_valid<T: cmp::PartialOrd>(binop: hir::BinOp, v: T, min: T, max: T) -> bool {
420             match binop.node {
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,
426                 _ => bug!(),
427             }
428         }
429
430         fn rev_binop(binop: hir::BinOp) -> hir::BinOp {
431             source_map::respan(binop.span,
432                             match binop.node {
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,
437                                 _ => return binop,
438                             })
439         }
440
441         fn check_limits(cx: &LateContext<'_, '_>,
442                         binop: hir::BinOp,
443                         l: &hir::Expr,
444                         r: &hir::Expr)
445                         -> bool {
446             let (lit, expr, swap) = match (&l.node, &r.node) {
447                 (&hir::ExprKind::Lit(_), _) => (l, r, true),
448                 (_, &hir::ExprKind::Lit(_)) => (r, l, false),
449                 _ => return true,
450             };
451             // Normalize the binop so that the literal is always on the RHS in
452             // the comparison
453             let norm_binop = if swap { rev_binop(binop) } else { binop };
454             match cx.tables.node_type(expr.hir_id).sty {
455                 ty::Int(int_ty) => {
456                     let (min, max) = int_ty_range(int_ty);
457                     let lit_val: i128 = match lit.node {
458                         hir::ExprKind::Lit(ref li) => {
459                             match li.node {
460                                 ast::LitKind::Int(v, ast::LitIntType::Signed(_)) |
461                                 ast::LitKind::Int(v, ast::LitIntType::Unsuffixed) => v as i128,
462                                 _ => return true
463                             }
464                         },
465                         _ => bug!()
466                     };
467                     is_valid(norm_binop, lit_val, min, max)
468                 }
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) => {
473                             match li.node {
474                                 ast::LitKind::Int(v, _) => v,
475                                 _ => return true
476                             }
477                         },
478                         _ => bug!()
479                     };
480                     is_valid(norm_binop, lit_val, min, max)
481                 }
482                 _ => true,
483             }
484         }
485
486         fn is_comparison(binop: hir::BinOp) -> bool {
487             match binop.node {
488                 hir::BinOpKind::Eq |
489                 hir::BinOpKind::Lt |
490                 hir::BinOpKind::Le |
491                 hir::BinOpKind::Ne |
492                 hir::BinOpKind::Ge |
493                 hir::BinOpKind::Gt => true,
494                 _ => false,
495             }
496         }
497     }
498 }
499
500 declare_lint! {
501     IMPROPER_CTYPES,
502     Warn,
503     "proper use of libc types in foreign modules"
504 }
505
506 declare_lint_pass!(ImproperCTypes => [IMPROPER_CTYPES]);
507
508 struct ImproperCTypesVisitor<'a, 'tcx: 'a> {
509     cx: &'a LateContext<'a, 'tcx>,
510 }
511
512 enum FfiResult<'tcx> {
513     FfiSafe,
514     FfiPhantom(Ty<'tcx>),
515     FfiUnsafe {
516         ty: Ty<'tcx>,
517         reason: &'static str,
518         help: Option<&'static str>,
519     },
520 }
521
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)
524 }
525
526 fn ty_is_known_nonnull<'tcx>(tcx: TyCtxt<'tcx, 'tcx>, ty: Ty<'tcx>) -> bool {
527     match ty.sty {
528         ty::FnPtr(_) => true,
529         ty::Ref(..) => 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),
535                 );
536                 if is_zst(tcx, field.did, field_ty) {
537                     continue;
538                 }
539
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) {
543                     return true;
544                 }
545             }
546
547             false
548         }
549         _ => false,
550     }
551 }
552
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>,
559                                   ty: Ty<'tcx>,
560                                   ty_def: &'tcx ty::AdtDef,
561                                   substs: SubstsRef<'tcx>)
562                                   -> bool {
563     if ty_def.variants.len() != 2 {
564         return false;
565     }
566
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() {
570         &variant_fields[1]
571     } else if variant_fields[1].is_empty() {
572         &variant_fields[0]
573     } else {
574         return false;
575     };
576
577     if fields.len() != 1 {
578         return false;
579     }
580
581     let field_ty = fields[0].ty(tcx, substs);
582     if !ty_is_known_nonnull(tcx, field_ty) {
583         return false;
584     }
585
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?");
592     }
593
594     true
595 }
596
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> {
603         use FfiResult::*;
604
605         let cx = self.cx.tcx;
606
607         // Protect against infinite recursion, for example
608         // `struct S(*mut S);`.
609         // FIXME: A recursion limit is necessary as well, for irregular
610         // recursive types.
611         if !cache.insert(ty) {
612             return FfiSafe;
613         }
614
615         match ty.sty {
616             ty::Adt(def, substs) => {
617                 if def.is_phantom_data() {
618                     return FfiPhantom(ty);
619                 }
620                 match def.adt_kind() {
621                     AdtKind::Struct => {
622                         if !def.repr.c() && !def.repr.transparent() {
623                             return FfiUnsafe {
624                                 ty: ty,
625                                 reason: "this struct has unspecified layout",
626                                 help: Some("consider adding a `#[repr(C)]` or \
627                                             `#[repr(transparent)]` attribute to this struct"),
628                             };
629                         }
630
631                         if def.non_enum_variant().fields.is_empty() {
632                             return FfiUnsafe {
633                                 ty: ty,
634                                 reason: "this struct has no fields",
635                                 help: Some("consider adding a member to this struct"),
636                             };
637                         }
638
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),
646                             );
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) {
650                                 continue;
651                             }
652                             let r = self.check_type_for_ffi(cache, field_ty);
653                             match r {
654                                 FfiSafe => {
655                                     all_phantom = false;
656                                 }
657                                 FfiPhantom(..) => {}
658                                 FfiUnsafe { .. } => {
659                                     return r;
660                                 }
661                             }
662                         }
663
664                         if all_phantom { FfiPhantom(ty) } else { FfiSafe }
665                     }
666                     AdtKind::Union => {
667                         if !def.repr.c() && !def.repr.transparent() {
668                             return FfiUnsafe {
669                                 ty: ty,
670                                 reason: "this union has unspecified layout",
671                                 help: Some("consider adding a `#[repr(C)]` or \
672                                             `#[repr(transparent)]` attribute to this union"),
673                             };
674                         }
675
676                         if def.non_enum_variant().fields.is_empty() {
677                             return FfiUnsafe {
678                                 ty: ty,
679                                 reason: "this union has no fields",
680                                 help: Some("consider adding a field to this union"),
681                             };
682                         }
683
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),
689                             );
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) {
693                                 continue;
694                             }
695                             let r = self.check_type_for_ffi(cache, field_ty);
696                             match r {
697                                 FfiSafe => {
698                                     all_phantom = false;
699                                 }
700                                 FfiPhantom(..) => {}
701                                 FfiUnsafe { .. } => {
702                                     return r;
703                                 }
704                             }
705                         }
706
707                         if all_phantom { FfiPhantom(ty) } else { FfiSafe }
708                     }
709                     AdtKind::Enum => {
710                         if def.variants.is_empty() {
711                             // Empty enums are okay... although sort of useless.
712                             return FfiSafe;
713                         }
714
715                         // Check for a repr() attribute to specify the size of the
716                         // discriminant.
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) {
720                                 return FfiUnsafe {
721                                     ty: ty,
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"),
726                                 };
727                             }
728                         }
729
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),
736                                 );
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) {
740                                     continue;
741                                 }
742                                 let r = self.check_type_for_ffi(cache, field_ty);
743                                 match r {
744                                     FfiSafe => {}
745                                     FfiUnsafe { .. } => {
746                                         return r;
747                                     }
748                                     FfiPhantom(..) => {
749                                         return FfiUnsafe {
750                                             ty: ty,
751                                             reason: "this enum contains a PhantomData field",
752                                             help: None,
753                                         };
754                                     }
755                                 }
756                             }
757                         }
758                         FfiSafe
759                     }
760                 }
761             }
762
763             ty::Char => FfiUnsafe {
764                 ty: ty,
765                 reason: "the `char` type has no C equivalent",
766                 help: Some("consider using `u32` or `libc::wchar_t` instead"),
767             },
768
769             ty::Int(ast::IntTy::I128) | ty::Uint(ast::UintTy::U128) => FfiUnsafe {
770                 ty: ty,
771                 reason: "128-bit integers don't currently have a known stable ABI",
772                 help: None,
773             },
774
775             // Primitive types with a stable representation.
776             ty::Bool | ty::Int(..) | ty::Uint(..) | ty::Float(..) | ty::Never => FfiSafe,
777
778             ty::Slice(_) => FfiUnsafe {
779                 ty: ty,
780                 reason: "slices have no C equivalent",
781                 help: Some("consider using a raw pointer instead"),
782             },
783
784             ty::Dynamic(..) => FfiUnsafe {
785                 ty: ty,
786                 reason: "trait objects have no C equivalent",
787                 help: None,
788             },
789
790             ty::Str => FfiUnsafe {
791                 ty: ty,
792                 reason: "string slices have no C equivalent",
793                 help: Some("consider using `*const u8` and a length instead"),
794             },
795
796             ty::Tuple(..) => FfiUnsafe {
797                 ty: ty,
798                 reason: "tuples have unspecified layout",
799                 help: Some("consider using a struct instead"),
800             },
801
802             ty::RawPtr(ty::TypeAndMut { ty, .. }) |
803             ty::Ref(_, ty, _) => self.check_type_for_ffi(cache, ty),
804
805             ty::Array(ty, _) => self.check_type_for_ffi(cache, ty),
806
807             ty::FnPtr(sig) => {
808                 match sig.abi() {
809                     Abi::Rust | Abi::RustIntrinsic | Abi::PlatformIntrinsic | Abi::RustCall => {
810                         return FfiUnsafe {
811                             ty: ty,
812                             reason: "this function pointer has Rust-specific calling convention",
813                             help: Some("consider using an `extern fn(...) -> ...` \
814                                         function pointer instead"),
815                         }
816                     }
817                     _ => {}
818                 }
819
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());
823                     match r {
824                         FfiSafe => {}
825                         _ => {
826                             return r;
827                         }
828                     }
829                 }
830                 for arg in sig.inputs() {
831                     let r = self.check_type_for_ffi(cache, arg);
832                     match r {
833                         FfiSafe => {}
834                         _ => {
835                             return r;
836                         }
837                     }
838                 }
839                 FfiSafe
840             }
841
842             ty::Foreign(..) => FfiSafe,
843
844             ty::Param(..) |
845             ty::Infer(..) |
846             ty::Bound(..) |
847             ty::Error |
848             ty::Closure(..) |
849             ty::Generator(..) |
850             ty::GeneratorWitness(..) |
851             ty::Placeholder(..) |
852             ty::UnnormalizedProjection(..) |
853             ty::Projection(..) |
854             ty::Opaque(..) |
855             ty::FnDef(..) => bug!("Unexpected type in foreign function"),
856         }
857     }
858
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);
863
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,
868                                   sp,
869                                   &format!("`extern` block uses type `{}` which is not FFI-safe: \
870                                             composed only of PhantomData", ty));
871             }
872             FfiResult::FfiUnsafe { ty: unsafe_ty, reason, help } => {
873                 let msg = format!("`extern` block uses type `{}` which is not FFI-safe: {}",
874                                   unsafe_ty, reason);
875                 let mut diag = self.cx.struct_span_lint(IMPROPER_CTYPES, sp, &msg);
876                 if let Some(s) = help {
877                     diag.help(s);
878                 }
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");
882                     }
883                 }
884                 diag.emit();
885             }
886         }
887     }
888
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
895             // of inputs.
896             &sig.inputs()[..sig.inputs().len() - 1]
897         } else {
898             &sig.inputs()[..]
899         };
900
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);
903         }
904
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);
909             }
910         }
911     }
912
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);
917     }
918 }
919
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 {
925             match it.node {
926                 hir::ForeignItemKind::Fn(ref decl, _, _) => {
927                     vis.check_foreign_fn(it.hir_id, decl);
928                 }
929                 hir::ForeignItemKind::Static(ref ty, _) => {
930                     vis.check_foreign_static(it.hir_id, ty.span);
931                 }
932                 hir::ForeignItemKind::Type => ()
933             }
934         }
935     }
936 }
937
938 declare_lint_pass!(VariantSizeDifferences => [VARIANT_SIZE_DIFFERENCES]);
939
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);
951                 }
952             };
953             let (variants, tag) = match layout.variants {
954                 layout::Variants::Multiple {
955                     discr_kind: layout::DiscriminantKind::Tag,
956                     ref discr,
957                     ref variants,
958                     ..
959                 } => (variants, discr),
960                 _ => return,
961             };
962
963             let discr_size = tag.value.size(&cx.tcx).bytes();
964
965             debug!("enum `{}` is {} bytes large with layout:\n{:#?}",
966                    t, layout.size.bytes(), layout);
967
968             let (largest, slargest, largest_index) = enum_definition.variants
969                 .iter()
970                 .zip(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);
974
975                     debug!("- variant `{}` is {} bytes large",
976                            variant.node.ident,
977                            bytes);
978                     bytes
979                 })
980                 .enumerate()
981                 .fold((0, 0, 0), |(l, s, li), (idx, size)| if size > l {
982                     (size, l, idx)
983                 } else if size > s {
984                     (l, size, li)
985                 } else {
986                     (l, s, li)
987                 });
988
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",
996                                          largest));
997             }
998         }
999     }
1000 }