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