]> git.lizzy.rs Git - rust.git/blob - src/librustc_lint/types.rs
5cafd3d676f3faa6c10da25f0c9b79edf192971a
[rust.git] / src / librustc_lint / types.rs
1 #![allow(non_snake_case)]
2
3 use rustc::hir::{ExprKind, Node};
4 use rustc::hir::lowering::is_range_literal;
5 use rustc::ty::subst::SubstsRef;
6 use rustc::ty::{self, AdtKind, ParamEnv, Ty, TyCtxt};
7 use rustc::ty::layout::{self, IntegerExt, LayoutOf, VariantIdx};
8 use rustc::{lint, util};
9 use rustc_data_structures::indexed_vec::Idx;
10 use util::nodemap::FxHashSet;
11 use lint::{LateContext, LintContext, LintArray};
12 use lint::{LintPass, LateLintPass};
13
14 use std::cmp;
15 use std::{i8, i16, i32, i64, u8, u16, u32, u64, f32, f64};
16
17 use syntax::{ast, attr};
18 use syntax::errors::Applicability;
19 use rustc_target::spec::abi::Abi;
20 use syntax_pos::Span;
21 use syntax::source_map;
22
23 use rustc::hir;
24
25 use rustc::mir::interpret::{sign_extend, truncate};
26
27 use log::debug;
28
29 declare_lint! {
30     UNUSED_COMPARISONS,
31     Warn,
32     "comparisons made useless by limits of the types involved"
33 }
34
35 declare_lint! {
36     OVERFLOWING_LITERALS,
37     Deny,
38     "literal out of range for its type"
39 }
40
41 declare_lint! {
42     VARIANT_SIZE_DIFFERENCES,
43     Allow,
44     "detects enums with widely varying variant sizes"
45 }
46
47 #[derive(Copy, Clone)]
48 pub struct TypeLimits {
49     /// Id of the last visited negated expression
50     negated_expr_id: hir::HirId,
51 }
52
53 impl_lint_pass!(TypeLimits => [UNUSED_COMPARISONS, OVERFLOWING_LITERALS]);
54
55 impl TypeLimits {
56     pub fn new() -> TypeLimits {
57         TypeLimits { negated_expr_id: hir::DUMMY_HIR_ID }
58     }
59 }
60
61 /// Attempts to special-case the overflowing literal lint when it occurs as a range endpoint.
62 /// Returns `true` iff the lint was overridden.
63 fn lint_overflowing_range_endpoint<'a, 'tcx>(
64     cx: &LateContext<'a, 'tcx>,
65     lit: &ast::Lit,
66     lit_val: u128,
67     max: u128,
68     expr: &'tcx hir::Expr,
69     parent_expr: &'tcx hir::Expr,
70     ty: impl std::fmt::Debug,
71 ) -> bool {
72     // We only want to handle exclusive (`..`) ranges,
73     // which are represented as `ExprKind::Struct`.
74     if let ExprKind::Struct(_, eps, _) = &parent_expr.node {
75         debug_assert_eq!(eps.len(), 2);
76         // We can suggest using an inclusive range
77         // (`..=`) instead only if it is the `end` that is
78         // overflowing and only by 1.
79         if eps[1].expr.hir_id == expr.hir_id && lit_val - 1 == max {
80             let mut err = cx.struct_span_lint(
81                 OVERFLOWING_LITERALS,
82                 parent_expr.span,
83                 &format!("range endpoint is out of range for `{:?}`", ty),
84             );
85             if let Ok(start) = cx.sess().source_map().span_to_snippet(eps[0].span) {
86                 use ast::{LitKind, LitIntType};
87                 // We need to preserve the literal's suffix,
88                 // as it may determine typing information.
89                 let suffix = match lit.node {
90                     LitKind::Int(_, LitIntType::Signed(s)) => format!("{}", s),
91                     LitKind::Int(_, LitIntType::Unsigned(s)) => format!("{}", s),
92                     LitKind::Int(_, LitIntType::Unsuffixed) => "".to_owned(),
93                     _ => bug!(),
94                 };
95                 let suggestion = format!("{}..={}{}", start, lit_val - 1, suffix);
96                 err.span_suggestion(
97                     parent_expr.span,
98                     &"use an inclusive range instead",
99                     suggestion,
100                     Applicability::MachineApplicable,
101                 );
102                 err.emit();
103                 return true;
104             }
105         }
106     }
107
108     false
109 }
110
111 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TypeLimits {
112     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx hir::Expr) {
113         match e.node {
114             hir::ExprKind::Unary(hir::UnNeg, ref expr) => {
115                 // propagate negation, if the negation itself isn't negated
116                 if self.negated_expr_id != e.hir_id {
117                     self.negated_expr_id = expr.hir_id;
118                 }
119             }
120             hir::ExprKind::Binary(binop, ref l, ref r) => {
121                 if is_comparison(binop) && !check_limits(cx, binop, &l, &r) {
122                     cx.span_lint(UNUSED_COMPARISONS,
123                                  e.span,
124                                  "comparison is useless due to type limits");
125                 }
126             }
127             hir::ExprKind::Lit(ref lit) => {
128                 match cx.tables.node_type(e.hir_id).sty {
129                     ty::Int(t) => {
130                         match lit.node {
131                             ast::LitKind::Int(v, ast::LitIntType::Signed(_)) |
132                             ast::LitKind::Int(v, ast::LitIntType::Unsuffixed) => {
133                                 let int_type = if let ast::IntTy::Isize = t {
134                                     cx.sess().target.isize_ty
135                                 } else {
136                                     t
137                                 };
138                                 let (_, max) = int_ty_range(int_type);
139                                 let max = max as u128;
140                                 let negative = self.negated_expr_id == e.hir_id;
141
142                                 // Detect literal value out of range [min, max] inclusive
143                                 // avoiding use of -min to prevent overflow/panic
144                                 if (negative && v > max + 1) || (!negative && v > max) {
145                                     if let Some(repr_str) = get_bin_hex_repr(cx, lit) {
146                                         report_bin_hex_error(
147                                             cx,
148                                             e,
149                                             attr::IntType::SignedInt(t),
150                                             repr_str,
151                                             v,
152                                             negative,
153                                         );
154                                         return;
155                                     }
156
157                                     let par_id = cx.tcx.hir().get_parent_node_by_hir_id(e.hir_id);
158                                     if let Node::Expr(par_e) = cx.tcx.hir().get_by_hir_id(par_id) {
159                                         if let hir::ExprKind::Struct(..) = par_e.node {
160                                             if is_range_literal(cx.sess(), par_e)
161                                                 && lint_overflowing_range_endpoint(
162                                                     cx,
163                                                     lit,
164                                                     v,
165                                                     max,
166                                                     e,
167                                                     par_e,
168                                                     t,
169                                                 )
170                                             {
171                                                     // The overflowing literal lint was overridden.
172                                                     return;
173                                             }
174                                         }
175                                     }
176
177                                     cx.span_lint(
178                                         OVERFLOWING_LITERALS,
179                                         e.span,
180                                         &format!("literal out of range for `{:?}`", t),
181                                     );
182                                     return;
183                                 }
184                             }
185                             _ => bug!(),
186                         };
187                     }
188                     ty::Uint(t) => {
189                         let uint_type = if let ast::UintTy::Usize = t {
190                             cx.sess().target.usize_ty
191                         } else {
192                             t
193                         };
194                         let (min, max) = uint_ty_range(uint_type);
195                         let lit_val: u128 = match lit.node {
196                             // _v is u8, within range by definition
197                             ast::LitKind::Byte(_v) => return,
198                             ast::LitKind::Int(v, _) => v,
199                             _ => bug!(),
200                         };
201                         if lit_val < min || lit_val > max {
202                             let parent_id = cx.tcx.hir().get_parent_node_by_hir_id(e.hir_id);
203                             if let Node::Expr(parent_expr) = cx.tcx.hir().get_by_hir_id(parent_id) {
204                                 match parent_expr.node {
205                                     hir::ExprKind::Cast(..) => {
206                                         if let ty::Char = cx.tables.expr_ty(parent_expr).sty {
207                                             let mut err = cx.struct_span_lint(
208                                                 OVERFLOWING_LITERALS,
209                                                 parent_expr.span,
210                                                 "only `u8` can be cast into `char`",
211                                             );
212                                             err.span_suggestion(
213                                                 parent_expr.span,
214                                                 &"use a `char` literal instead",
215                                                 format!("'\\u{{{:X}}}'", lit_val),
216                                                 Applicability::MachineApplicable,
217                                             );
218                                             err.emit();
219                                             return;
220                                         }
221                                     }
222                                     hir::ExprKind::Struct(..)
223                                         if is_range_literal(cx.sess(), parent_expr) => {
224                                             if lint_overflowing_range_endpoint(
225                                                 cx,
226                                                 lit,
227                                                 lit_val,
228                                                 max,
229                                                 e,
230                                                 parent_expr,
231                                                 t,
232                                             ) {
233                                                 // The overflowing literal lint was overridden.
234                                                 return;
235                                             }
236                                         }
237                                     _ => {}
238                                 }
239                             }
240                             if let Some(repr_str) = get_bin_hex_repr(cx, lit) {
241                                 report_bin_hex_error(
242                                     cx,
243                                     e,
244                                     attr::IntType::UnsignedInt(t),
245                                     repr_str,
246                                     lit_val,
247                                     false,
248                                 );
249                                 return;
250                             }
251                             cx.span_lint(
252                                 OVERFLOWING_LITERALS,
253                                 e.span,
254                                 &format!("literal out of range for `{:?}`", t),
255                             );
256                         }
257                     }
258                     ty::Float(t) => {
259                         let is_infinite = match lit.node {
260                             ast::LitKind::Float(v, _) |
261                             ast::LitKind::FloatUnsuffixed(v) => {
262                                 match t {
263                                     ast::FloatTy::F32 => v.as_str().parse().map(f32::is_infinite),
264                                     ast::FloatTy::F64 => v.as_str().parse().map(f64::is_infinite),
265                                 }
266                             }
267                             _ => bug!(),
268                         };
269                         if is_infinite == Ok(true) {
270                             cx.span_lint(OVERFLOWING_LITERALS,
271                                          e.span,
272                                          &format!("literal out of range for `{:?}`", t));
273                         }
274                     }
275                     _ => (),
276                 };
277             }
278             _ => (),
279         };
280
281         fn is_valid<T: cmp::PartialOrd>(binop: hir::BinOp, v: T, min: T, max: T) -> bool {
282             match binop.node {
283                 hir::BinOpKind::Lt => v > min && v <= max,
284                 hir::BinOpKind::Le => v >= min && v < max,
285                 hir::BinOpKind::Gt => v >= min && v < max,
286                 hir::BinOpKind::Ge => v > min && v <= max,
287                 hir::BinOpKind::Eq | hir::BinOpKind::Ne => v >= min && v <= max,
288                 _ => bug!(),
289             }
290         }
291
292         fn rev_binop(binop: hir::BinOp) -> hir::BinOp {
293             source_map::respan(binop.span,
294                             match binop.node {
295                                 hir::BinOpKind::Lt => hir::BinOpKind::Gt,
296                                 hir::BinOpKind::Le => hir::BinOpKind::Ge,
297                                 hir::BinOpKind::Gt => hir::BinOpKind::Lt,
298                                 hir::BinOpKind::Ge => hir::BinOpKind::Le,
299                                 _ => return binop,
300                             })
301         }
302
303         // for isize & usize, be conservative with the warnings, so that the
304         // warnings are consistent between 32- and 64-bit platforms
305         fn int_ty_range(int_ty: ast::IntTy) -> (i128, i128) {
306             match int_ty {
307                 ast::IntTy::Isize => (i64::min_value() as i128, i64::max_value() as i128),
308                 ast::IntTy::I8 => (i8::min_value() as i64 as i128, i8::max_value() as i128),
309                 ast::IntTy::I16 => (i16::min_value() as i64 as i128, i16::max_value() as i128),
310                 ast::IntTy::I32 => (i32::min_value() as i64 as i128, i32::max_value() as i128),
311                 ast::IntTy::I64 => (i64::min_value() as i128, i64::max_value() as i128),
312                 ast::IntTy::I128 =>(i128::min_value() as i128, i128::max_value()),
313             }
314         }
315
316         fn uint_ty_range(uint_ty: ast::UintTy) -> (u128, u128) {
317             match uint_ty {
318                 ast::UintTy::Usize => (u64::min_value() as u128, u64::max_value() as u128),
319                 ast::UintTy::U8 => (u8::min_value() as u128, u8::max_value() as u128),
320                 ast::UintTy::U16 => (u16::min_value() as u128, u16::max_value() as u128),
321                 ast::UintTy::U32 => (u32::min_value() as u128, u32::max_value() as u128),
322                 ast::UintTy::U64 => (u64::min_value() as u128, u64::max_value() as u128),
323                 ast::UintTy::U128 => (u128::min_value(), u128::max_value()),
324             }
325         }
326
327         fn check_limits(cx: &LateContext<'_, '_>,
328                         binop: hir::BinOp,
329                         l: &hir::Expr,
330                         r: &hir::Expr)
331                         -> bool {
332             let (lit, expr, swap) = match (&l.node, &r.node) {
333                 (&hir::ExprKind::Lit(_), _) => (l, r, true),
334                 (_, &hir::ExprKind::Lit(_)) => (r, l, false),
335                 _ => return true,
336             };
337             // Normalize the binop so that the literal is always on the RHS in
338             // the comparison
339             let norm_binop = if swap { rev_binop(binop) } else { binop };
340             match cx.tables.node_type(expr.hir_id).sty {
341                 ty::Int(int_ty) => {
342                     let (min, max) = int_ty_range(int_ty);
343                     let lit_val: i128 = match lit.node {
344                         hir::ExprKind::Lit(ref li) => {
345                             match li.node {
346                                 ast::LitKind::Int(v, ast::LitIntType::Signed(_)) |
347                                 ast::LitKind::Int(v, ast::LitIntType::Unsuffixed) => v as i128,
348                                 _ => return true
349                             }
350                         },
351                         _ => bug!()
352                     };
353                     is_valid(norm_binop, lit_val, min, max)
354                 }
355                 ty::Uint(uint_ty) => {
356                     let (min, max) :(u128, u128) = uint_ty_range(uint_ty);
357                     let lit_val: u128 = match lit.node {
358                         hir::ExprKind::Lit(ref li) => {
359                             match li.node {
360                                 ast::LitKind::Int(v, _) => v,
361                                 _ => return true
362                             }
363                         },
364                         _ => bug!()
365                     };
366                     is_valid(norm_binop, lit_val, min, max)
367                 }
368                 _ => true,
369             }
370         }
371
372         fn is_comparison(binop: hir::BinOp) -> bool {
373             match binop.node {
374                 hir::BinOpKind::Eq |
375                 hir::BinOpKind::Lt |
376                 hir::BinOpKind::Le |
377                 hir::BinOpKind::Ne |
378                 hir::BinOpKind::Ge |
379                 hir::BinOpKind::Gt => true,
380                 _ => false,
381             }
382         }
383
384         fn get_bin_hex_repr(cx: &LateContext<'_, '_>, lit: &ast::Lit) -> Option<String> {
385             let src = cx.sess().source_map().span_to_snippet(lit.span).ok()?;
386             let firstch = src.chars().next()?;
387
388             if firstch == '0' {
389                 match src.chars().nth(1) {
390                     Some('x') | Some('b') => return Some(src),
391                     _ => return None,
392                 }
393             }
394
395             None
396         }
397
398         // This function finds the next fitting type and generates a suggestion string.
399         // It searches for fitting types in the following way (`X < Y`):
400         //  - `iX`: if literal fits in `uX` => `uX`, else => `iY`
401         //  - `-iX` => `iY`
402         //  - `uX` => `uY`
403         //
404         // No suggestion for: `isize`, `usize`.
405         fn get_type_suggestion<'a>(
406             t: Ty<'_>,
407             val: u128,
408             negative: bool,
409         ) -> Option<String> {
410             use syntax::ast::IntTy::*;
411             use syntax::ast::UintTy::*;
412             macro_rules! find_fit {
413                 ($ty:expr, $val:expr, $negative:expr,
414                  $($type:ident => [$($utypes:expr),*] => [$($itypes:expr),*]),+) => {
415                     {
416                         let _neg = if negative { 1 } else { 0 };
417                         match $ty {
418                             $($type => {
419                                 $(if !negative && val <= uint_ty_range($utypes).1 {
420                                     return Some(format!("{:?}", $utypes))
421                                 })*
422                                 $(if val <= int_ty_range($itypes).1 as u128 + _neg {
423                                     return Some(format!("{:?}", $itypes))
424                                 })*
425                                 None
426                             },)*
427                             _ => None
428                         }
429                     }
430                 }
431             }
432             match t.sty {
433                 ty::Int(i) => find_fit!(i, val, negative,
434                               I8 => [U8] => [I16, I32, I64, I128],
435                               I16 => [U16] => [I32, I64, I128],
436                               I32 => [U32] => [I64, I128],
437                               I64 => [U64] => [I128],
438                               I128 => [U128] => []),
439                 ty::Uint(u) => find_fit!(u, val, negative,
440                               U8 => [U8, U16, U32, U64, U128] => [],
441                               U16 => [U16, U32, U64, U128] => [],
442                               U32 => [U32, U64, U128] => [],
443                               U64 => [U64, U128] => [],
444                               U128 => [U128] => []),
445                 _ => None,
446             }
447         }
448
449         fn report_bin_hex_error(
450             cx: &LateContext<'_, '_>,
451             expr: &hir::Expr,
452             ty: attr::IntType,
453             repr_str: String,
454             val: u128,
455             negative: bool,
456         ) {
457             let size = layout::Integer::from_attr(&cx.tcx, ty).size();
458             let (t, actually) = match ty {
459                 attr::IntType::SignedInt(t) => {
460                     let actually = sign_extend(val, size) as i128;
461                     (format!("{:?}", t), actually.to_string())
462                 }
463                 attr::IntType::UnsignedInt(t) => {
464                     let actually = truncate(val, size);
465                     (format!("{:?}", t), actually.to_string())
466                 }
467             };
468             let mut err = cx.struct_span_lint(
469                 OVERFLOWING_LITERALS,
470                 expr.span,
471                 &format!("literal out of range for {}", t),
472             );
473             err.note(&format!(
474                 "the literal `{}` (decimal `{}`) does not fit into \
475                  an `{}` and will become `{}{}`",
476                 repr_str, val, t, actually, t
477             ));
478             if let Some(sugg_ty) =
479                 get_type_suggestion(&cx.tables.node_type(expr.hir_id), val, negative)
480             {
481                 if let Some(pos) = repr_str.chars().position(|c| c == 'i' || c == 'u') {
482                     let (sans_suffix, _) = repr_str.split_at(pos);
483                     err.span_suggestion(
484                         expr.span,
485                         &format!("consider using `{}` instead", sugg_ty),
486                         format!("{}{}", sans_suffix, sugg_ty),
487                         Applicability::MachineApplicable
488                     );
489                 } else {
490                     err.help(&format!("consider using `{}` instead", sugg_ty));
491                 }
492             }
493
494             err.emit();
495         }
496     }
497 }
498
499 declare_lint! {
500     IMPROPER_CTYPES,
501     Warn,
502     "proper use of libc types in foreign modules"
503 }
504
505 declare_lint_pass!(ImproperCTypes => [IMPROPER_CTYPES]);
506
507 struct ImproperCTypesVisitor<'a, 'tcx: 'a> {
508     cx: &'a LateContext<'a, 'tcx>,
509 }
510
511 enum FfiResult<'tcx> {
512     FfiSafe,
513     FfiPhantom(Ty<'tcx>),
514     FfiUnsafe {
515         ty: Ty<'tcx>,
516         reason: &'static str,
517         help: Option<&'static str>,
518     },
519 }
520
521 /// Check if this enum can be safely exported based on the
522 /// "nullable pointer optimization". Currently restricted
523 /// to function pointers and references, but could be
524 /// expanded to cover NonZero raw pointers and newtypes.
525 /// FIXME: This duplicates code in codegen.
526 fn is_repr_nullable_ptr<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
527                                   def: &'tcx ty::AdtDef,
528                                   substs: SubstsRef<'tcx>)
529                                   -> bool {
530     if def.variants.len() == 2 {
531         let data_idx;
532
533         let zero = VariantIdx::new(0);
534         let one = VariantIdx::new(1);
535
536         if def.variants[zero].fields.is_empty() {
537             data_idx = one;
538         } else if def.variants[one].fields.is_empty() {
539             data_idx = zero;
540         } else {
541             return false;
542         }
543
544         if def.variants[data_idx].fields.len() == 1 {
545             match def.variants[data_idx].fields[0].ty(tcx, substs).sty {
546                 ty::FnPtr(_) => {
547                     return true;
548                 }
549                 ty::Ref(..) => {
550                     return true;
551                 }
552                 _ => {}
553             }
554         }
555     }
556     false
557 }
558
559 impl<'a, 'tcx> ImproperCTypesVisitor<'a, 'tcx> {
560     /// Checks if the given type is "ffi-safe" (has a stable, well-defined
561     /// representation which can be exported to C code).
562     fn check_type_for_ffi(&self,
563                           cache: &mut FxHashSet<Ty<'tcx>>,
564                           ty: Ty<'tcx>) -> FfiResult<'tcx> {
565         use FfiResult::*;
566
567         let cx = self.cx.tcx;
568
569         // Protect against infinite recursion, for example
570         // `struct S(*mut S);`.
571         // FIXME: A recursion limit is necessary as well, for irregular
572         // recursive types.
573         if !cache.insert(ty) {
574             return FfiSafe;
575         }
576
577         match ty.sty {
578             ty::Adt(def, substs) => {
579                 if def.is_phantom_data() {
580                     return FfiPhantom(ty);
581                 }
582                 match def.adt_kind() {
583                     AdtKind::Struct => {
584                         if !def.repr.c() && !def.repr.transparent() {
585                             return FfiUnsafe {
586                                 ty: ty,
587                                 reason: "this struct has unspecified layout",
588                                 help: Some("consider adding a #[repr(C)] or #[repr(transparent)] \
589                                             attribute to this struct"),
590                             };
591                         }
592
593                         if def.non_enum_variant().fields.is_empty() {
594                             return FfiUnsafe {
595                                 ty: ty,
596                                 reason: "this struct has no fields",
597                                 help: Some("consider adding a member to this struct"),
598                             };
599                         }
600
601                         // We can't completely trust repr(C) and repr(transparent) markings;
602                         // make sure the fields are actually safe.
603                         let mut all_phantom = true;
604                         for field in &def.non_enum_variant().fields {
605                             let field_ty = cx.normalize_erasing_regions(
606                                 ParamEnv::reveal_all(),
607                                 field.ty(cx, substs),
608                             );
609                             // repr(transparent) types are allowed to have arbitrary ZSTs, not just
610                             // PhantomData -- skip checking all ZST fields
611                             if def.repr.transparent() {
612                                 let is_zst = cx
613                                     .layout_of(cx.param_env(field.did).and(field_ty))
614                                     .map(|layout| layout.is_zst())
615                                     .unwrap_or(false);
616                                 if is_zst {
617                                     continue;
618                                 }
619                             }
620                             let r = self.check_type_for_ffi(cache, field_ty);
621                             match r {
622                                 FfiSafe => {
623                                     all_phantom = false;
624                                 }
625                                 FfiPhantom(..) => {}
626                                 FfiUnsafe { .. } => {
627                                     return r;
628                                 }
629                             }
630                         }
631
632                         if all_phantom { FfiPhantom(ty) } else { FfiSafe }
633                     }
634                     AdtKind::Union => {
635                         if !def.repr.c() {
636                             return FfiUnsafe {
637                                 ty: ty,
638                                 reason: "this union has unspecified layout",
639                                 help: Some("consider adding a #[repr(C)] attribute to this union"),
640                             };
641                         }
642
643                         if def.non_enum_variant().fields.is_empty() {
644                             return FfiUnsafe {
645                                 ty: ty,
646                                 reason: "this union has no fields",
647                                 help: Some("consider adding a field to this union"),
648                             };
649                         }
650
651                         let mut all_phantom = true;
652                         for field in &def.non_enum_variant().fields {
653                             let field_ty = cx.normalize_erasing_regions(
654                                 ParamEnv::reveal_all(),
655                                 field.ty(cx, substs),
656                             );
657                             let r = self.check_type_for_ffi(cache, field_ty);
658                             match r {
659                                 FfiSafe => {
660                                     all_phantom = false;
661                                 }
662                                 FfiPhantom(..) => {}
663                                 FfiUnsafe { .. } => {
664                                     return r;
665                                 }
666                             }
667                         }
668
669                         if all_phantom { FfiPhantom(ty) } else { FfiSafe }
670                     }
671                     AdtKind::Enum => {
672                         if def.variants.is_empty() {
673                             // Empty enums are okay... although sort of useless.
674                             return FfiSafe;
675                         }
676
677                         // Check for a repr() attribute to specify the size of the
678                         // discriminant.
679                         if !def.repr.c() && def.repr.int.is_none() {
680                             // Special-case types like `Option<extern fn()>`.
681                             if !is_repr_nullable_ptr(cx, def, substs) {
682                                 return FfiUnsafe {
683                                     ty: ty,
684                                     reason: "enum has no representation hint",
685                                     help: Some("consider adding a #[repr(...)] attribute \
686                                                 to this enum"),
687                                 };
688                             }
689                         }
690
691                         // Check the contained variants.
692                         for variant in &def.variants {
693                             for field in &variant.fields {
694                                 let arg = cx.normalize_erasing_regions(
695                                     ParamEnv::reveal_all(),
696                                     field.ty(cx, substs),
697                                 );
698                                 let r = self.check_type_for_ffi(cache, arg);
699                                 match r {
700                                     FfiSafe => {}
701                                     FfiUnsafe { .. } => {
702                                         return r;
703                                     }
704                                     FfiPhantom(..) => {
705                                         return FfiUnsafe {
706                                             ty: ty,
707                                             reason: "this enum contains a PhantomData field",
708                                             help: None,
709                                         };
710                                     }
711                                 }
712                             }
713                         }
714                         FfiSafe
715                     }
716                 }
717             }
718
719             ty::Char => FfiUnsafe {
720                 ty: ty,
721                 reason: "the `char` type has no C equivalent",
722                 help: Some("consider using `u32` or `libc::wchar_t` instead"),
723             },
724
725             ty::Int(ast::IntTy::I128) | ty::Uint(ast::UintTy::U128) => FfiUnsafe {
726                 ty: ty,
727                 reason: "128-bit integers don't currently have a known stable ABI",
728                 help: None,
729             },
730
731             // Primitive types with a stable representation.
732             ty::Bool | ty::Int(..) | ty::Uint(..) | ty::Float(..) | ty::Never => FfiSafe,
733
734             ty::Slice(_) => FfiUnsafe {
735                 ty: ty,
736                 reason: "slices have no C equivalent",
737                 help: Some("consider using a raw pointer instead"),
738             },
739
740             ty::Dynamic(..) => FfiUnsafe {
741                 ty: ty,
742                 reason: "trait objects have no C equivalent",
743                 help: None,
744             },
745
746             ty::Str => FfiUnsafe {
747                 ty: ty,
748                 reason: "string slices have no C equivalent",
749                 help: Some("consider using `*const u8` and a length instead"),
750             },
751
752             ty::Tuple(..) => FfiUnsafe {
753                 ty: ty,
754                 reason: "tuples have unspecified layout",
755                 help: Some("consider using a struct instead"),
756             },
757
758             ty::RawPtr(ty::TypeAndMut { ty, .. }) |
759             ty::Ref(_, ty, _) => self.check_type_for_ffi(cache, ty),
760
761             ty::Array(ty, _) => self.check_type_for_ffi(cache, ty),
762
763             ty::FnPtr(sig) => {
764                 match sig.abi() {
765                     Abi::Rust | Abi::RustIntrinsic | Abi::PlatformIntrinsic | Abi::RustCall => {
766                         return FfiUnsafe {
767                             ty: ty,
768                             reason: "this function pointer has Rust-specific calling convention",
769                             help: Some("consider using an `extern fn(...) -> ...` \
770                                         function pointer instead"),
771                         }
772                     }
773                     _ => {}
774                 }
775
776                 let sig = cx.erase_late_bound_regions(&sig);
777                 if !sig.output().is_unit() {
778                     let r = self.check_type_for_ffi(cache, sig.output());
779                     match r {
780                         FfiSafe => {}
781                         _ => {
782                             return r;
783                         }
784                     }
785                 }
786                 for arg in sig.inputs() {
787                     let r = self.check_type_for_ffi(cache, arg);
788                     match r {
789                         FfiSafe => {}
790                         _ => {
791                             return r;
792                         }
793                     }
794                 }
795                 FfiSafe
796             }
797
798             ty::Foreign(..) => FfiSafe,
799
800             ty::Param(..) |
801             ty::Infer(..) |
802             ty::Bound(..) |
803             ty::Error |
804             ty::Closure(..) |
805             ty::Generator(..) |
806             ty::GeneratorWitness(..) |
807             ty::Placeholder(..) |
808             ty::UnnormalizedProjection(..) |
809             ty::Projection(..) |
810             ty::Opaque(..) |
811             ty::FnDef(..) => bug!("Unexpected type in foreign function"),
812         }
813     }
814
815     fn check_type_for_ffi_and_report_errors(&mut self, sp: Span, ty: Ty<'tcx>) {
816         // it is only OK to use this function because extern fns cannot have
817         // any generic types right now:
818         let ty = self.cx.tcx.normalize_erasing_regions(ParamEnv::reveal_all(), ty);
819
820         match self.check_type_for_ffi(&mut FxHashSet::default(), ty) {
821             FfiResult::FfiSafe => {}
822             FfiResult::FfiPhantom(ty) => {
823                 self.cx.span_lint(IMPROPER_CTYPES,
824                                   sp,
825                                   &format!("`extern` block uses type `{}` which is not FFI-safe: \
826                                             composed only of PhantomData", ty));
827             }
828             FfiResult::FfiUnsafe { ty: unsafe_ty, reason, help } => {
829                 let msg = format!("`extern` block uses type `{}` which is not FFI-safe: {}",
830                                   unsafe_ty, reason);
831                 let mut diag = self.cx.struct_span_lint(IMPROPER_CTYPES, sp, &msg);
832                 if let Some(s) = help {
833                     diag.help(s);
834                 }
835                 if let ty::Adt(def, _) = unsafe_ty.sty {
836                     if let Some(sp) = self.cx.tcx.hir().span_if_local(def.did) {
837                         diag.span_note(sp, "type defined here");
838                     }
839                 }
840                 diag.emit();
841             }
842         }
843     }
844
845     fn check_foreign_fn(&mut self, id: hir::HirId, decl: &hir::FnDecl) {
846         let def_id = self.cx.tcx.hir().local_def_id_from_hir_id(id);
847         let sig = self.cx.tcx.fn_sig(def_id);
848         let sig = self.cx.tcx.erase_late_bound_regions(&sig);
849         let inputs = if sig.c_variadic {
850             // Don't include the spoofed `VaList` in the functions list
851             // of inputs.
852             &sig.inputs()[..sig.inputs().len() - 1]
853         } else {
854             &sig.inputs()[..]
855         };
856
857         for (input_ty, input_hir) in inputs.iter().zip(&decl.inputs) {
858             self.check_type_for_ffi_and_report_errors(input_hir.span, input_ty);
859         }
860
861         if let hir::Return(ref ret_hir) = decl.output {
862             let ret_ty = sig.output();
863             if !ret_ty.is_unit() {
864                 self.check_type_for_ffi_and_report_errors(ret_hir.span, ret_ty);
865             }
866         }
867     }
868
869     fn check_foreign_static(&mut self, id: hir::HirId, span: Span) {
870         let def_id = self.cx.tcx.hir().local_def_id_from_hir_id(id);
871         let ty = self.cx.tcx.type_of(def_id);
872         self.check_type_for_ffi_and_report_errors(span, ty);
873     }
874 }
875
876 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ImproperCTypes {
877     fn check_foreign_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::ForeignItem) {
878         let mut vis = ImproperCTypesVisitor { cx };
879         let abi = cx.tcx.hir().get_foreign_abi_by_hir_id(it.hir_id);
880         if abi != Abi::RustIntrinsic && abi != Abi::PlatformIntrinsic {
881             match it.node {
882                 hir::ForeignItemKind::Fn(ref decl, _, _) => {
883                     vis.check_foreign_fn(it.hir_id, decl);
884                 }
885                 hir::ForeignItemKind::Static(ref ty, _) => {
886                     vis.check_foreign_static(it.hir_id, ty.span);
887                 }
888                 hir::ForeignItemKind::Type => ()
889             }
890         }
891     }
892 }
893
894 declare_lint_pass!(VariantSizeDifferences => [VARIANT_SIZE_DIFFERENCES]);
895
896 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for VariantSizeDifferences {
897     fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item) {
898         if let hir::ItemKind::Enum(ref enum_definition, _) = it.node {
899             let item_def_id = cx.tcx.hir().local_def_id_from_hir_id(it.hir_id);
900             let t = cx.tcx.type_of(item_def_id);
901             let ty = cx.tcx.erase_regions(&t);
902             let layout = match cx.layout_of(ty) {
903                 Ok(layout) => layout,
904                 Err(ty::layout::LayoutError::Unknown(_)) => return,
905                 Err(err @ ty::layout::LayoutError::SizeOverflow(_)) => {
906                     bug!("failed to get layout for `{}`: {}", t, err);
907                 }
908             };
909             let (variants, tag) = match layout.variants {
910                 layout::Variants::Multiple {
911                     discr_kind: layout::DiscriminantKind::Tag,
912                     ref discr,
913                     ref variants,
914                     ..
915                 } => (variants, discr),
916                 _ => return,
917             };
918
919             let discr_size = tag.value.size(&cx.tcx).bytes();
920
921             debug!("enum `{}` is {} bytes large with layout:\n{:#?}",
922                    t, layout.size.bytes(), layout);
923
924             let (largest, slargest, largest_index) = enum_definition.variants
925                 .iter()
926                 .zip(variants)
927                 .map(|(variant, variant_layout)| {
928                     // Subtract the size of the enum discriminant.
929                     let bytes = variant_layout.size.bytes().saturating_sub(discr_size);
930
931                     debug!("- variant `{}` is {} bytes large",
932                            variant.node.ident,
933                            bytes);
934                     bytes
935                 })
936                 .enumerate()
937                 .fold((0, 0, 0), |(l, s, li), (idx, size)| if size > l {
938                     (size, l, idx)
939                 } else if size > s {
940                     (l, size, li)
941                 } else {
942                     (l, s, li)
943                 });
944
945             // We only warn if the largest variant is at least thrice as large as
946             // the second-largest.
947             if largest > slargest * 3 && slargest > 0 {
948                 cx.span_lint(VARIANT_SIZE_DIFFERENCES,
949                                 enum_definition.variants[largest_index].span,
950                                 &format!("enum variant is more than three times \
951                                           larger ({} bytes) than the next largest",
952                                          largest));
953             }
954         }
955     }
956 }