]> git.lizzy.rs Git - rust.git/blob - src/librustc_lint/types.rs
Fix rebase fallout.
[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_index::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: &str,
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.kind {
76         if eps.len() != 2 {
77             return false;
78         }
79         // We can suggest using an inclusive range
80         // (`..=`) instead only if it is the `end` that is
81         // overflowing and only by 1.
82         if eps[1].expr.hir_id == expr.hir_id && lit_val - 1 == max {
83             let mut err = cx.struct_span_lint(
84                 OVERFLOWING_LITERALS,
85                 parent_expr.span,
86                 &format!("range endpoint is out of range for `{}`", ty),
87             );
88             if let Ok(start) = cx.sess().source_map().span_to_snippet(eps[0].span) {
89                 use ast::{LitKind, LitIntType};
90                 // We need to preserve the literal's suffix,
91                 // as it may determine typing information.
92                 let suffix = match lit.node {
93                     LitKind::Int(_, LitIntType::Signed(s)) => format!("{}", s.name_str()),
94                     LitKind::Int(_, LitIntType::Unsigned(s)) => format!("{}", s.name_str()),
95                     LitKind::Int(_, LitIntType::Unsuffixed) => "".to_owned(),
96                     _ => bug!(),
97                 };
98                 let suggestion = format!("{}..={}{}", start, lit_val - 1, suffix);
99                 err.span_suggestion(
100                     parent_expr.span,
101                     &"use an inclusive range instead",
102                     suggestion,
103                     Applicability::MachineApplicable,
104                 );
105                 err.emit();
106                 return true;
107             }
108         }
109     }
110
111     false
112 }
113
114 // For `isize` & `usize`, be conservative with the warnings, so that the
115 // warnings are consistent between 32- and 64-bit platforms.
116 fn int_ty_range(int_ty: ast::IntTy) -> (i128, i128) {
117     match int_ty {
118         ast::IntTy::Isize => (i64::min_value() as i128, i64::max_value() as i128),
119         ast::IntTy::I8 => (i8::min_value() as i64 as i128, i8::max_value() as i128),
120         ast::IntTy::I16 => (i16::min_value() as i64 as i128, i16::max_value() as i128),
121         ast::IntTy::I32 => (i32::min_value() as i64 as i128, i32::max_value() as i128),
122         ast::IntTy::I64 => (i64::min_value() as i128, i64::max_value() as i128),
123         ast::IntTy::I128 =>(i128::min_value() as i128, i128::max_value()),
124     }
125 }
126
127 fn uint_ty_range(uint_ty: ast::UintTy) -> (u128, u128) {
128     match uint_ty {
129         ast::UintTy::Usize => (u64::min_value() as u128, u64::max_value() as u128),
130         ast::UintTy::U8 => (u8::min_value() as u128, u8::max_value() as u128),
131         ast::UintTy::U16 => (u16::min_value() as u128, u16::max_value() as u128),
132         ast::UintTy::U32 => (u32::min_value() as u128, u32::max_value() as u128),
133         ast::UintTy::U64 => (u64::min_value() as u128, u64::max_value() as u128),
134         ast::UintTy::U128 => (u128::min_value(), u128::max_value()),
135     }
136 }
137
138 fn get_bin_hex_repr(cx: &LateContext<'_, '_>, lit: &hir::Lit) -> Option<String> {
139     let src = cx.sess().source_map().span_to_snippet(lit.span).ok()?;
140     let firstch = src.chars().next()?;
141
142     if firstch == '0' {
143         match src.chars().nth(1) {
144             Some('x') | Some('b') => return Some(src),
145             _ => return None,
146         }
147     }
148
149     None
150 }
151
152 fn report_bin_hex_error(
153     cx: &LateContext<'_, '_>,
154     expr: &hir::Expr,
155     ty: attr::IntType,
156     repr_str: String,
157     val: u128,
158     negative: bool,
159 ) {
160     let size = layout::Integer::from_attr(&cx.tcx, ty).size();
161     let (t, actually) = match ty {
162         attr::IntType::SignedInt(t) => {
163             let actually = sign_extend(val, size) as i128;
164             (t.name_str(), actually.to_string())
165         }
166         attr::IntType::UnsignedInt(t) => {
167             let actually = truncate(val, size);
168             (t.name_str(), actually.to_string())
169         }
170     };
171     let mut err = cx.struct_span_lint(
172         OVERFLOWING_LITERALS,
173         expr.span,
174         &format!("literal out of range for {}", t),
175     );
176     err.note(&format!(
177         "the literal `{}` (decimal `{}`) does not fit into \
178             an `{}` and will become `{}{}`",
179         repr_str, val, t, actually, t
180     ));
181     if let Some(sugg_ty) =
182         get_type_suggestion(&cx.tables.node_type(expr.hir_id), val, negative)
183     {
184         if let Some(pos) = repr_str.chars().position(|c| c == 'i' || c == 'u') {
185             let (sans_suffix, _) = repr_str.split_at(pos);
186             err.span_suggestion(
187                 expr.span,
188                 &format!("consider using `{}` instead", sugg_ty),
189                 format!("{}{}", sans_suffix, sugg_ty),
190                 Applicability::MachineApplicable
191             );
192         } else {
193             err.help(&format!("consider using `{}` instead", sugg_ty));
194         }
195     }
196
197     err.emit();
198 }
199
200 // This function finds the next fitting type and generates a suggestion string.
201 // It searches for fitting types in the following way (`X < Y`):
202 //  - `iX`: if literal fits in `uX` => `uX`, else => `iY`
203 //  - `-iX` => `iY`
204 //  - `uX` => `uY`
205 //
206 // No suggestion for: `isize`, `usize`.
207 fn get_type_suggestion(t: Ty<'_>, val: u128, negative: bool) -> Option<&'static str> {
208     use syntax::ast::IntTy::*;
209     use syntax::ast::UintTy::*;
210     macro_rules! find_fit {
211         ($ty:expr, $val:expr, $negative:expr,
212          $($type:ident => [$($utypes:expr),*] => [$($itypes:expr),*]),+) => {
213             {
214                 let _neg = if negative { 1 } else { 0 };
215                 match $ty {
216                     $($type => {
217                         $(if !negative && val <= uint_ty_range($utypes).1 {
218                             return Some($utypes.name_str())
219                         })*
220                         $(if val <= int_ty_range($itypes).1 as u128 + _neg {
221                             return Some($itypes.name_str())
222                         })*
223                         None
224                     },)+
225                     _ => None
226                 }
227             }
228         }
229     }
230     match t.kind {
231         ty::Int(i) => find_fit!(i, val, negative,
232                       I8 => [U8] => [I16, I32, I64, I128],
233                       I16 => [U16] => [I32, I64, I128],
234                       I32 => [U32] => [I64, I128],
235                       I64 => [U64] => [I128],
236                       I128 => [U128] => []),
237         ty::Uint(u) => find_fit!(u, val, negative,
238                       U8 => [U8, U16, U32, U64, U128] => [],
239                       U16 => [U16, U32, U64, U128] => [],
240                       U32 => [U32, U64, U128] => [],
241                       U64 => [U64, U128] => [],
242                       U128 => [U128] => []),
243         _ => None,
244     }
245 }
246
247 fn lint_int_literal<'a, 'tcx>(
248     cx: &LateContext<'a, 'tcx>,
249     type_limits: &TypeLimits,
250     e: &'tcx hir::Expr,
251     lit: &hir::Lit,
252     t: ast::IntTy,
253     v: u128,
254 ) {
255     let int_type = if let ast::IntTy::Isize = t {
256         cx.sess().target.isize_ty
257     } else {
258         t
259     };
260
261     let (_, max) = int_ty_range(int_type);
262     let max = max as u128;
263     let negative = type_limits.negated_expr_id == e.hir_id;
264
265     // Detect literal value out of range [min, max] inclusive
266     // avoiding use of -min to prevent overflow/panic
267     if (negative && v > max + 1) || (!negative && v > max) {
268         if let Some(repr_str) = get_bin_hex_repr(cx, lit) {
269             report_bin_hex_error(
270                 cx,
271                 e,
272                 attr::IntType::SignedInt(t),
273                 repr_str,
274                 v,
275                 negative,
276             );
277             return;
278         }
279
280         let par_id = cx.tcx.hir().get_parent_node(e.hir_id);
281         if let Node::Expr(par_e) = cx.tcx.hir().get(par_id) {
282             if let hir::ExprKind::Struct(..) = par_e.kind {
283                 if is_range_literal(cx.sess(), par_e)
284                     && lint_overflowing_range_endpoint(cx, lit, v, max, e, par_e, t.name_str())
285                 {
286                     // The overflowing literal lint was overridden.
287                     return;
288                 }
289             }
290         }
291
292         cx.span_lint(
293             OVERFLOWING_LITERALS,
294             e.span,
295             &format!("literal out of range for `{}`", t.name_str()),
296         );
297     }
298 }
299
300 fn lint_uint_literal<'a, 'tcx>(
301     cx: &LateContext<'a, 'tcx>,
302     e: &'tcx hir::Expr,
303     lit: &hir::Lit,
304     t: ast::UintTy,
305 ) {
306     let uint_type = if let ast::UintTy::Usize = t {
307         cx.sess().target.usize_ty
308     } else {
309         t
310     };
311     let (min, max) = uint_ty_range(uint_type);
312     let lit_val: u128 = match lit.node {
313         // _v is u8, within range by definition
314         ast::LitKind::Byte(_v) => return,
315         ast::LitKind::Int(v, _) => v,
316         _ => bug!(),
317     };
318     if lit_val < min || lit_val > max {
319         let parent_id = cx.tcx.hir().get_parent_node(e.hir_id);
320         if let Node::Expr(par_e) = cx.tcx.hir().get(parent_id) {
321             match par_e.kind {
322                 hir::ExprKind::Cast(..) => {
323                     if let ty::Char = cx.tables.expr_ty(par_e).kind {
324                         let mut err = cx.struct_span_lint(
325                             OVERFLOWING_LITERALS,
326                             par_e.span,
327                             "only `u8` can be cast into `char`",
328                         );
329                         err.span_suggestion(
330                             par_e.span,
331                             &"use a `char` literal instead",
332                             format!("'\\u{{{:X}}}'", lit_val),
333                             Applicability::MachineApplicable,
334                         );
335                         err.emit();
336                         return;
337                     }
338                 }
339                 hir::ExprKind::Struct(..)
340                     if is_range_literal(cx.sess(), par_e) => {
341                         let t = t.name_str();
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.name_str()),
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: &hir::Lit,
367 ) {
368     match cx.tables.node_type(e.hir_id).kind {
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                     match t {
385                         ast::FloatTy::F32 => v.as_str().parse().map(f32::is_infinite),
386                         ast::FloatTy::F64 => v.as_str().parse().map(f64::is_infinite),
387                     }
388                 }
389                 _ => bug!(),
390             };
391             if is_infinite == Ok(true) {
392                 cx.span_lint(
393                     OVERFLOWING_LITERALS,
394                     e.span,
395                     &format!("literal out of range for `{}`", t.name_str()),
396                 );
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.kind {
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.kind, &r.kind) {
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).kind {
459                 ty::Int(int_ty) => {
460                     let (min, max) = int_ty_range(int_ty);
461                     let lit_val: i128 = match lit.kind {
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.kind {
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> {
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<'tcx>(tcx: TyCtxt<'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<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> bool {
531     match ty.kind {
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<'tcx>(
563     tcx: TyCtxt<'tcx>,
564     ty: Ty<'tcx>,
565     ty_def: &'tcx ty::AdtDef,
566     substs: SubstsRef<'tcx>,
567 ) -> bool {
568     if ty_def.variants.len() != 2 {
569         return false;
570     }
571
572     let get_variant_fields = |index| &ty_def.variants[VariantIdx::new(index)].fields;
573     let variant_fields = [get_variant_fields(0), get_variant_fields(1)];
574     let fields = if variant_fields[0].is_empty() {
575         &variant_fields[1]
576     } else if variant_fields[1].is_empty() {
577         &variant_fields[0]
578     } else {
579         return false;
580     };
581
582     if fields.len() != 1 {
583         return false;
584     }
585
586     let field_ty = fields[0].ty(tcx, substs);
587     if !ty_is_known_nonnull(tcx, field_ty) {
588         return false;
589     }
590
591     // At this point, the field's type is known to be nonnull and the parent enum is Option-like.
592     // If the computed size for the field and the enum are different, the nonnull optimization isn't
593     // being applied (and we've got a problem somewhere).
594     let compute_size_skeleton = |t| SizeSkeleton::compute(t, tcx, ParamEnv::reveal_all()).unwrap();
595     if !compute_size_skeleton(ty).same_size(compute_size_skeleton(field_ty)) {
596         bug!("improper_ctypes: Option nonnull optimization not applied?");
597     }
598
599     true
600 }
601
602 impl<'a, 'tcx> ImproperCTypesVisitor<'a, 'tcx> {
603     /// Checks if the given type is "ffi-safe" (has a stable, well-defined
604     /// representation which can be exported to C code).
605     fn check_type_for_ffi(&self,
606                           cache: &mut FxHashSet<Ty<'tcx>>,
607                           ty: Ty<'tcx>) -> FfiResult<'tcx> {
608         use FfiResult::*;
609
610         let cx = self.cx.tcx;
611
612         // Protect against infinite recursion, for example
613         // `struct S(*mut S);`.
614         // FIXME: A recursion limit is necessary as well, for irregular
615         // recursive types.
616         if !cache.insert(ty) {
617             return FfiSafe;
618         }
619
620         match ty.kind {
621             ty::Adt(def, substs) => {
622                 if def.is_phantom_data() {
623                     return FfiPhantom(ty);
624                 }
625                 match def.adt_kind() {
626                     AdtKind::Struct => {
627                         if !def.repr.c() && !def.repr.transparent() {
628                             return FfiUnsafe {
629                                 ty,
630                                 reason: "this struct has unspecified layout",
631                                 help: Some("consider adding a `#[repr(C)]` or \
632                                             `#[repr(transparent)]` attribute to this struct"),
633                             };
634                         }
635
636                         let is_non_exhaustive =
637                             def.non_enum_variant().is_field_list_non_exhaustive();
638                         if is_non_exhaustive && !def.did.is_local() {
639                             return FfiUnsafe {
640                                 ty,
641                                 reason: "this struct is non-exhaustive",
642                                 help: None,
643                             };
644                         }
645
646                         if def.non_enum_variant().fields.is_empty() {
647                             return FfiUnsafe {
648                                 ty,
649                                 reason: "this struct has no fields",
650                                 help: Some("consider adding a member to this struct"),
651                             };
652                         }
653
654                         // We can't completely trust repr(C) and repr(transparent) markings;
655                         // make sure the fields are actually safe.
656                         let mut all_phantom = true;
657                         for field in &def.non_enum_variant().fields {
658                             let field_ty = cx.normalize_erasing_regions(
659                                 ParamEnv::reveal_all(),
660                                 field.ty(cx, substs),
661                             );
662                             // repr(transparent) types are allowed to have arbitrary ZSTs, not just
663                             // PhantomData -- skip checking all ZST fields
664                             if def.repr.transparent() && is_zst(cx, field.did, field_ty) {
665                                 continue;
666                             }
667                             let r = self.check_type_for_ffi(cache, field_ty);
668                             match r {
669                                 FfiSafe => {
670                                     all_phantom = false;
671                                 }
672                                 FfiPhantom(..) => {}
673                                 FfiUnsafe { .. } => {
674                                     return r;
675                                 }
676                             }
677                         }
678
679                         if all_phantom { FfiPhantom(ty) } else { FfiSafe }
680                     }
681                     AdtKind::Union => {
682                         if !def.repr.c() && !def.repr.transparent() {
683                             return FfiUnsafe {
684                                 ty,
685                                 reason: "this union has unspecified layout",
686                                 help: Some("consider adding a `#[repr(C)]` or \
687                                             `#[repr(transparent)]` attribute to this union"),
688                             };
689                         }
690
691                         if def.non_enum_variant().fields.is_empty() {
692                             return FfiUnsafe {
693                                 ty,
694                                 reason: "this union has no fields",
695                                 help: Some("consider adding a field to this union"),
696                             };
697                         }
698
699                         let mut all_phantom = true;
700                         for field in &def.non_enum_variant().fields {
701                             let field_ty = cx.normalize_erasing_regions(
702                                 ParamEnv::reveal_all(),
703                                 field.ty(cx, substs),
704                             );
705                             // repr(transparent) types are allowed to have arbitrary ZSTs, not just
706                             // PhantomData -- skip checking all ZST fields.
707                             if def.repr.transparent() && is_zst(cx, field.did, field_ty) {
708                                 continue;
709                             }
710                             let r = self.check_type_for_ffi(cache, field_ty);
711                             match r {
712                                 FfiSafe => {
713                                     all_phantom = false;
714                                 }
715                                 FfiPhantom(..) => {}
716                                 FfiUnsafe { .. } => {
717                                     return r;
718                                 }
719                             }
720                         }
721
722                         if all_phantom { FfiPhantom(ty) } else { FfiSafe }
723                     }
724                     AdtKind::Enum => {
725                         if def.variants.is_empty() {
726                             // Empty enums are okay... although sort of useless.
727                             return FfiSafe;
728                         }
729
730                         // Check for a repr() attribute to specify the size of the
731                         // discriminant.
732                         if !def.repr.c() && !def.repr.transparent() && def.repr.int.is_none() {
733                             // Special-case types like `Option<extern fn()>`.
734                             if !is_repr_nullable_ptr(cx, ty, def, substs) {
735                                 return FfiUnsafe {
736                                     ty,
737                                     reason: "enum has no representation hint",
738                                     help: Some("consider adding a `#[repr(C)]`, \
739                                                 `#[repr(transparent)]`, or integer `#[repr(...)]` \
740                                                 attribute to this enum"),
741                                 };
742                             }
743                         }
744
745                         if def.is_variant_list_non_exhaustive() && !def.did.is_local() {
746                             return FfiUnsafe {
747                                 ty,
748                                 reason: "this enum is non-exhaustive",
749                                 help: None,
750                             };
751                         }
752
753                         // Check the contained variants.
754                         for variant in &def.variants {
755                             let is_non_exhaustive = variant.is_field_list_non_exhaustive();
756                             if is_non_exhaustive && !variant.def_id.is_local() {
757                                 return FfiUnsafe {
758                                     ty,
759                                     reason: "this enum has non-exhaustive variants",
760                                     help: None,
761                                 };
762                             }
763
764                             for field in &variant.fields {
765                                 let field_ty = cx.normalize_erasing_regions(
766                                     ParamEnv::reveal_all(),
767                                     field.ty(cx, substs),
768                                 );
769                                 // repr(transparent) types are allowed to have arbitrary ZSTs, not
770                                 // just PhantomData -- skip checking all ZST fields.
771                                 if def.repr.transparent() && is_zst(cx, field.did, field_ty) {
772                                     continue;
773                                 }
774                                 let r = self.check_type_for_ffi(cache, field_ty);
775                                 match r {
776                                     FfiSafe => {}
777                                     FfiUnsafe { .. } => {
778                                         return r;
779                                     }
780                                     FfiPhantom(..) => {
781                                         return FfiUnsafe {
782                                             ty,
783                                             reason: "this enum contains a PhantomData field",
784                                             help: None,
785                                         };
786                                     }
787                                 }
788                             }
789                         }
790                         FfiSafe
791                     }
792                 }
793             }
794
795             ty::Char => FfiUnsafe {
796                 ty,
797                 reason: "the `char` type has no C equivalent",
798                 help: Some("consider using `u32` or `libc::wchar_t` instead"),
799             },
800
801             ty::Int(ast::IntTy::I128) | ty::Uint(ast::UintTy::U128) => FfiUnsafe {
802                 ty,
803                 reason: "128-bit integers don't currently have a known stable ABI",
804                 help: None,
805             },
806
807             // Primitive types with a stable representation.
808             ty::Bool | ty::Int(..) | ty::Uint(..) | ty::Float(..) | ty::Never => FfiSafe,
809
810             ty::Slice(_) => FfiUnsafe {
811                 ty,
812                 reason: "slices have no C equivalent",
813                 help: Some("consider using a raw pointer instead"),
814             },
815
816             ty::Dynamic(..) => FfiUnsafe {
817                 ty,
818                 reason: "trait objects have no C equivalent",
819                 help: None,
820             },
821
822             ty::Str => FfiUnsafe {
823                 ty,
824                 reason: "string slices have no C equivalent",
825                 help: Some("consider using `*const u8` and a length instead"),
826             },
827
828             ty::Tuple(..) => FfiUnsafe {
829                 ty,
830                 reason: "tuples have unspecified layout",
831                 help: Some("consider using a struct instead"),
832             },
833
834             ty::RawPtr(ty::TypeAndMut { ty, .. }) |
835             ty::Ref(_, ty, _) => self.check_type_for_ffi(cache, ty),
836
837             ty::Array(ty, _) => self.check_type_for_ffi(cache, ty),
838
839             ty::FnPtr(sig) => {
840                 match sig.abi() {
841                     Abi::Rust | Abi::RustIntrinsic | Abi::PlatformIntrinsic | Abi::RustCall => {
842                         return FfiUnsafe {
843                             ty,
844                             reason: "this function pointer has Rust-specific calling convention",
845                             help: Some("consider using an `extern fn(...) -> ...` \
846                                         function pointer instead"),
847                         }
848                     }
849                     _ => {}
850                 }
851
852                 let sig = cx.erase_late_bound_regions(&sig);
853                 if !sig.output().is_unit() {
854                     let r = self.check_type_for_ffi(cache, sig.output());
855                     match r {
856                         FfiSafe => {}
857                         _ => {
858                             return r;
859                         }
860                     }
861                 }
862                 for arg in sig.inputs() {
863                     let r = self.check_type_for_ffi(cache, arg);
864                     match r {
865                         FfiSafe => {}
866                         _ => {
867                             return r;
868                         }
869                     }
870                 }
871                 FfiSafe
872             }
873
874             ty::Foreign(..) => FfiSafe,
875
876             ty::Param(..) |
877             ty::Infer(..) |
878             ty::Bound(..) |
879             ty::Error |
880             ty::Closure(..) |
881             ty::Generator(..) |
882             ty::GeneratorWitness(..) |
883             ty::Placeholder(..) |
884             ty::UnnormalizedProjection(..) |
885             ty::Projection(..) |
886             ty::Opaque(..) |
887             ty::FnDef(..) => bug!("unexpected type in foreign function: {:?}", ty),
888         }
889     }
890
891     fn emit_ffi_unsafe_type_lint(
892         &mut self,
893         ty: Ty<'tcx>,
894         sp: Span,
895         note: &str,
896         help: Option<&str>,
897     ) {
898         let mut diag = self.cx.struct_span_lint(
899             IMPROPER_CTYPES,
900             sp,
901             &format!("`extern` block uses type `{}`, which is not FFI-safe", ty),
902         );
903         diag.span_label(sp, "not FFI-safe");
904         if let Some(help) = help {
905             diag.help(help);
906         }
907         diag.note(note);
908         if let ty::Adt(def, _) = ty.kind {
909             if let Some(sp) = self.cx.tcx.hir().span_if_local(def.did) {
910                 diag.span_note(sp, "type defined here");
911             }
912         }
913         diag.emit();
914     }
915
916     fn check_for_opaque_ty(&mut self, sp: Span, ty: Ty<'tcx>) -> bool {
917         use crate::rustc::ty::TypeFoldable;
918
919         struct ProhibitOpaqueTypes<'tcx> {
920             ty: Option<Ty<'tcx>>,
921         };
922
923         impl<'tcx> ty::fold::TypeVisitor<'tcx> for ProhibitOpaqueTypes<'tcx> {
924             fn visit_ty(&mut self, ty: Ty<'tcx>) -> bool {
925                 if let ty::Opaque(..) = ty.kind {
926                     self.ty = Some(ty);
927                     true
928                 } else {
929                     ty.super_visit_with(self)
930                 }
931             }
932         }
933
934         let mut visitor = ProhibitOpaqueTypes { ty: None };
935         ty.visit_with(&mut visitor);
936         if let Some(ty) = visitor.ty {
937             self.emit_ffi_unsafe_type_lint(
938                 ty,
939                 sp,
940                 "opaque types have no C equivalent",
941                 None,
942             );
943             true
944         } else {
945             false
946         }
947     }
948
949     fn check_type_for_ffi_and_report_errors(&mut self, sp: Span, ty: Ty<'tcx>) {
950         // We have to check for opaque types before `normalize_erasing_regions`,
951         // which will replace opaque types with their underlying concrete type.
952         if self.check_for_opaque_ty(sp, ty) {
953             // We've already emitted an error due to an opaque type.
954             return;
955         }
956
957         // it is only OK to use this function because extern fns cannot have
958         // any generic types right now:
959         let ty = self.cx.tcx.normalize_erasing_regions(ParamEnv::reveal_all(), ty);
960
961         match self.check_type_for_ffi(&mut FxHashSet::default(), ty) {
962             FfiResult::FfiSafe => {}
963             FfiResult::FfiPhantom(ty) => {
964                 self.emit_ffi_unsafe_type_lint(ty, sp, "composed only of `PhantomData`", None);
965             }
966             FfiResult::FfiUnsafe { ty, reason, help } => {
967                 self.emit_ffi_unsafe_type_lint(ty, sp, reason, help);
968             }
969         }
970     }
971
972     fn check_foreign_fn(&mut self, id: hir::HirId, decl: &hir::FnDecl) {
973         let def_id = self.cx.tcx.hir().local_def_id(id);
974         let sig = self.cx.tcx.fn_sig(def_id);
975         let sig = self.cx.tcx.erase_late_bound_regions(&sig);
976
977         for (input_ty, input_hir) in sig.inputs().iter().zip(&decl.inputs) {
978             self.check_type_for_ffi_and_report_errors(input_hir.span, input_ty);
979         }
980
981         if let hir::Return(ref ret_hir) = decl.output {
982             let ret_ty = sig.output();
983             if !ret_ty.is_unit() {
984                 self.check_type_for_ffi_and_report_errors(ret_hir.span, ret_ty);
985             }
986         }
987     }
988
989     fn check_foreign_static(&mut self, id: hir::HirId, span: Span) {
990         let def_id = self.cx.tcx.hir().local_def_id(id);
991         let ty = self.cx.tcx.type_of(def_id);
992         self.check_type_for_ffi_and_report_errors(span, ty);
993     }
994 }
995
996 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ImproperCTypes {
997     fn check_foreign_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::ForeignItem) {
998         let mut vis = ImproperCTypesVisitor { cx };
999         let abi = cx.tcx.hir().get_foreign_abi(it.hir_id);
1000         if let Abi::Rust | Abi::RustCall | Abi::RustIntrinsic | Abi::PlatformIntrinsic = abi {
1001             // Don't worry about types in internal ABIs.
1002         } else {
1003             match it.kind {
1004                 hir::ForeignItemKind::Fn(ref decl, _, _) => {
1005                     vis.check_foreign_fn(it.hir_id, decl);
1006                 }
1007                 hir::ForeignItemKind::Static(ref ty, _) => {
1008                     vis.check_foreign_static(it.hir_id, ty.span);
1009                 }
1010                 hir::ForeignItemKind::Type => ()
1011             }
1012         }
1013     }
1014 }
1015
1016 declare_lint_pass!(VariantSizeDifferences => [VARIANT_SIZE_DIFFERENCES]);
1017
1018 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for VariantSizeDifferences {
1019     fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item) {
1020         if let hir::ItemKind::Enum(ref enum_definition, _) = it.kind {
1021             let item_def_id = cx.tcx.hir().local_def_id(it.hir_id);
1022             let t = cx.tcx.type_of(item_def_id);
1023             let ty = cx.tcx.erase_regions(&t);
1024             let layout = match cx.layout_of(ty) {
1025                 Ok(layout) => layout,
1026                 Err(ty::layout::LayoutError::Unknown(_)) => return,
1027                 Err(err @ ty::layout::LayoutError::SizeOverflow(_)) => {
1028                     bug!("failed to get layout for `{}`: {}", t, err);
1029                 }
1030             };
1031             let (variants, tag) = match layout.variants {
1032                 layout::Variants::Multiple {
1033                     discr_kind: layout::DiscriminantKind::Tag,
1034                     ref discr,
1035                     ref variants,
1036                     ..
1037                 } => (variants, discr),
1038                 _ => return,
1039             };
1040
1041             let discr_size = tag.value.size(&cx.tcx).bytes();
1042
1043             debug!("enum `{}` is {} bytes large with layout:\n{:#?}",
1044                    t, layout.size.bytes(), layout);
1045
1046             let (largest, slargest, largest_index) = enum_definition.variants
1047                 .iter()
1048                 .zip(variants)
1049                 .map(|(variant, variant_layout)| {
1050                     // Subtract the size of the enum discriminant.
1051                     let bytes = variant_layout.size.bytes().saturating_sub(discr_size);
1052
1053                     debug!("- variant `{}` is {} bytes large",
1054                            variant.ident,
1055                            bytes);
1056                     bytes
1057                 })
1058                 .enumerate()
1059                 .fold((0, 0, 0), |(l, s, li), (idx, size)| if size > l {
1060                     (size, l, idx)
1061                 } else if size > s {
1062                     (l, size, li)
1063                 } else {
1064                     (l, s, li)
1065                 });
1066
1067             // We only warn if the largest variant is at least thrice as large as
1068             // the second-largest.
1069             if largest > slargest * 3 && slargest > 0 {
1070                 cx.span_lint(VARIANT_SIZE_DIFFERENCES,
1071                                 enum_definition.variants[largest_index].span,
1072                                 &format!("enum variant is more than three times \
1073                                           larger ({} bytes) than the next largest",
1074                                          largest));
1075             }
1076         }
1077     }
1078 }