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