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