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