]> git.lizzy.rs Git - rust.git/blob - src/librustc_lint/types.rs
Auto merge of #41433 - estebank:constructor, r=michaelwoerister
[rust.git] / src / librustc_lint / types.rs
1 // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 #![allow(non_snake_case)]
12
13 use rustc::hir::def_id::DefId;
14 use rustc::ty::subst::Substs;
15 use rustc::ty::{self, AdtKind, Ty, TyCtxt};
16 use rustc::ty::layout::{Layout, Primitive};
17 use rustc::traits::Reveal;
18 use middle::const_val::ConstVal;
19 use rustc_const_eval::ConstContext;
20 use util::nodemap::FxHashSet;
21 use lint::{LateContext, LintContext, LintArray};
22 use lint::{LintPass, LateLintPass};
23
24 use std::cmp;
25 use std::{i8, i16, i32, i64, u8, u16, u32, u64, f32, f64};
26
27 use syntax::ast;
28 use syntax::abi::Abi;
29 use syntax::attr;
30 use syntax_pos::Span;
31 use syntax::codemap;
32
33 use rustc::hir;
34
35 declare_lint! {
36     UNUSED_COMPARISONS,
37     Warn,
38     "comparisons made useless by limits of the types involved"
39 }
40
41 declare_lint! {
42     OVERFLOWING_LITERALS,
43     Warn,
44     "literal out of range for its type"
45 }
46
47 declare_lint! {
48     EXCEEDING_BITSHIFTS,
49     Deny,
50     "shift exceeds the type's number of bits"
51 }
52
53 declare_lint! {
54     VARIANT_SIZE_DIFFERENCES,
55     Allow,
56     "detects enums with widely varying variant sizes"
57 }
58
59 #[derive(Copy, Clone)]
60 pub struct TypeLimits {
61     /// Id of the last visited negated expression
62     negated_expr_id: ast::NodeId,
63 }
64
65 impl TypeLimits {
66     pub fn new() -> TypeLimits {
67         TypeLimits { negated_expr_id: ast::DUMMY_NODE_ID }
68     }
69 }
70
71 impl LintPass for TypeLimits {
72     fn get_lints(&self) -> LintArray {
73         lint_array!(UNUSED_COMPARISONS,
74                     OVERFLOWING_LITERALS,
75                     EXCEEDING_BITSHIFTS)
76     }
77 }
78
79 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TypeLimits {
80     fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) {
81         match e.node {
82             hir::ExprUnary(hir::UnNeg, ref expr) => {
83                 // propagate negation, if the negation itself isn't negated
84                 if self.negated_expr_id != e.id {
85                     self.negated_expr_id = expr.id;
86                 }
87             }
88             hir::ExprBinary(binop, ref l, ref r) => {
89                 if is_comparison(binop) && !check_limits(cx, binop, &l, &r) {
90                     cx.span_lint(UNUSED_COMPARISONS,
91                                  e.span,
92                                  "comparison is useless due to type limits");
93                 }
94
95                 if binop.node.is_shift() {
96                     let opt_ty_bits = match cx.tables.node_id_to_type(l.id).sty {
97                         ty::TyInt(t) => Some(int_ty_bits(t, cx.sess().target.int_type)),
98                         ty::TyUint(t) => Some(uint_ty_bits(t, cx.sess().target.uint_type)),
99                         _ => None,
100                     };
101
102                     if let Some(bits) = opt_ty_bits {
103                         let exceeding = if let hir::ExprLit(ref lit) = r.node {
104                             if let ast::LitKind::Int(shift, _) = lit.node {
105                                 shift as u64 >= bits
106                             } else {
107                                 false
108                             }
109                         } else {
110                             let const_cx = ConstContext::with_tables(cx.tcx, cx.tables);
111                             match const_cx.eval(&r) {
112                                 Ok(ConstVal::Integral(i)) => {
113                                     i.is_negative() ||
114                                     i.to_u64()
115                                         .map(|i| i >= bits)
116                                         .unwrap_or(true)
117                                 }
118                                 _ => false,
119                             }
120                         };
121                         if exceeding {
122                             cx.span_lint(EXCEEDING_BITSHIFTS,
123                                          e.span,
124                                          "bitshift exceeds the type's number of bits");
125                         }
126                     };
127                 }
128             }
129             hir::ExprLit(ref lit) => {
130                 match cx.tables.node_id_to_type(e.id).sty {
131                     ty::TyInt(t) => {
132                         match lit.node {
133                             ast::LitKind::Int(v, ast::LitIntType::Signed(_)) |
134                             ast::LitKind::Int(v, ast::LitIntType::Unsuffixed) => {
135                                 let int_type = if let ast::IntTy::Is = t {
136                                     cx.sess().target.int_type
137                                 } else {
138                                     t
139                                 };
140                                 let (_, max) = int_ty_range(int_type);
141                                 let max = max as u128;
142                                 let negative = self.negated_expr_id == e.id;
143
144                                 // Detect literal value out of range [min, max] inclusive
145                                 // avoiding use of -min to prevent overflow/panic
146                                 if (negative && v > max + 1) ||
147                                    (!negative && v > max) {
148                                     cx.span_lint(OVERFLOWING_LITERALS,
149                                                  e.span,
150                                                  &format!("literal out of range for {:?}", t));
151                                     return;
152                                 }
153                             }
154                             _ => bug!(),
155                         };
156                     }
157                     ty::TyUint(t) => {
158                         let uint_type = if let ast::UintTy::Us = t {
159                             cx.sess().target.uint_type
160                         } else {
161                             t
162                         };
163                         let (min, max) = uint_ty_range(uint_type);
164                         let lit_val: u128 = match lit.node {
165                             // _v is u8, within range by definition
166                             ast::LitKind::Byte(_v) => return,
167                             ast::LitKind::Int(v, _) => v,
168                             _ => bug!(),
169                         };
170                         if lit_val < min || lit_val > max {
171                             cx.span_lint(OVERFLOWING_LITERALS,
172                                          e.span,
173                                          &format!("literal out of range for {:?}", t));
174                         }
175                     }
176                     ty::TyFloat(t) => {
177                         let (min, max) = float_ty_range(t);
178                         let lit_val: f64 = match lit.node {
179                             ast::LitKind::Float(v, _) |
180                             ast::LitKind::FloatUnsuffixed(v) => {
181                                 match v.as_str().parse() {
182                                     Ok(f) => f,
183                                     Err(_) => return,
184                                 }
185                             }
186                             _ => bug!(),
187                         };
188                         if lit_val < min || lit_val > max {
189                             cx.span_lint(OVERFLOWING_LITERALS,
190                                          e.span,
191                                          &format!("literal out of range for {:?}", t));
192                         }
193                     }
194                     _ => (),
195                 };
196             }
197             _ => (),
198         };
199
200         fn is_valid<T: cmp::PartialOrd>(binop: hir::BinOp, v: T, min: T, max: T) -> bool {
201             match binop.node {
202                 hir::BiLt => v > min && v <= max,
203                 hir::BiLe => v >= min && v < max,
204                 hir::BiGt => v >= min && v < max,
205                 hir::BiGe => v > min && v <= max,
206                 hir::BiEq | hir::BiNe => v >= min && v <= max,
207                 _ => bug!(),
208             }
209         }
210
211         fn rev_binop(binop: hir::BinOp) -> hir::BinOp {
212             codemap::respan(binop.span,
213                             match binop.node {
214                                 hir::BiLt => hir::BiGt,
215                                 hir::BiLe => hir::BiGe,
216                                 hir::BiGt => hir::BiLt,
217                                 hir::BiGe => hir::BiLe,
218                                 _ => return binop,
219                             })
220         }
221
222         // for isize & usize, be conservative with the warnings, so that the
223         // warnings are consistent between 32- and 64-bit platforms
224         fn int_ty_range(int_ty: ast::IntTy) -> (i128, i128) {
225             match int_ty {
226                 ast::IntTy::Is => (i64::min_value() as i128, i64::max_value() as i128),
227                 ast::IntTy::I8 => (i8::min_value() as i64 as i128, i8::max_value() as i128),
228                 ast::IntTy::I16 => (i16::min_value() as i64 as i128, i16::max_value() as i128),
229                 ast::IntTy::I32 => (i32::min_value() as i64 as i128, i32::max_value() as i128),
230                 ast::IntTy::I64 => (i64::min_value() as i128, i64::max_value() as i128),
231                 ast::IntTy::I128 =>(i128::min_value() as i128, i128::max_value()),
232             }
233         }
234
235         fn uint_ty_range(uint_ty: ast::UintTy) -> (u128, u128) {
236             match uint_ty {
237                 ast::UintTy::Us => (u64::min_value() as u128, u64::max_value() as u128),
238                 ast::UintTy::U8 => (u8::min_value() as u128, u8::max_value() as u128),
239                 ast::UintTy::U16 => (u16::min_value() as u128, u16::max_value() as u128),
240                 ast::UintTy::U32 => (u32::min_value() as u128, u32::max_value() as u128),
241                 ast::UintTy::U64 => (u64::min_value() as u128, u64::max_value() as u128),
242                 ast::UintTy::U128 => (u128::min_value(), u128::max_value()),
243             }
244         }
245
246         fn float_ty_range(float_ty: ast::FloatTy) -> (f64, f64) {
247             match float_ty {
248                 ast::FloatTy::F32 => (f32::MIN as f64, f32::MAX as f64),
249                 ast::FloatTy::F64 => (f64::MIN, f64::MAX),
250             }
251         }
252
253         fn int_ty_bits(int_ty: ast::IntTy, target_int_ty: ast::IntTy) -> u64 {
254             match int_ty {
255                 ast::IntTy::Is => int_ty_bits(target_int_ty, target_int_ty),
256                 ast::IntTy::I8 => 8,
257                 ast::IntTy::I16 => 16 as u64,
258                 ast::IntTy::I32 => 32,
259                 ast::IntTy::I64 => 64,
260                 ast::IntTy::I128 => 128,
261             }
262         }
263
264         fn uint_ty_bits(uint_ty: ast::UintTy, target_uint_ty: ast::UintTy) -> u64 {
265             match uint_ty {
266                 ast::UintTy::Us => uint_ty_bits(target_uint_ty, target_uint_ty),
267                 ast::UintTy::U8 => 8,
268                 ast::UintTy::U16 => 16,
269                 ast::UintTy::U32 => 32,
270                 ast::UintTy::U64 => 64,
271                 ast::UintTy::U128 => 128,
272             }
273         }
274
275         fn check_limits(cx: &LateContext,
276                         binop: hir::BinOp,
277                         l: &hir::Expr,
278                         r: &hir::Expr)
279                         -> bool {
280             let (lit, expr, swap) = match (&l.node, &r.node) {
281                 (&hir::ExprLit(_), _) => (l, r, true),
282                 (_, &hir::ExprLit(_)) => (r, l, false),
283                 _ => return true,
284             };
285             // Normalize the binop so that the literal is always on the RHS in
286             // the comparison
287             let norm_binop = if swap { rev_binop(binop) } else { binop };
288             match cx.tables.node_id_to_type(expr.id).sty {
289                 ty::TyInt(int_ty) => {
290                     let (min, max) = int_ty_range(int_ty);
291                     let lit_val: i128 = match lit.node {
292                         hir::ExprLit(ref li) => {
293                             match li.node {
294                                 ast::LitKind::Int(v, ast::LitIntType::Signed(_)) |
295                                 ast::LitKind::Int(v, ast::LitIntType::Unsuffixed) => v as i128,
296                                 _ => return true
297                             }
298                         },
299                         _ => bug!()
300                     };
301                     is_valid(norm_binop, lit_val, min, max)
302                 }
303                 ty::TyUint(uint_ty) => {
304                     let (min, max) :(u128, u128) = uint_ty_range(uint_ty);
305                     let lit_val: u128 = match lit.node {
306                         hir::ExprLit(ref li) => {
307                             match li.node {
308                                 ast::LitKind::Int(v, _) => v,
309                                 _ => return true
310                             }
311                         },
312                         _ => bug!()
313                     };
314                     is_valid(norm_binop, lit_val, min, max)
315                 }
316                 _ => true,
317             }
318         }
319
320         fn is_comparison(binop: hir::BinOp) -> bool {
321             match binop.node {
322                 hir::BiEq | hir::BiLt | hir::BiLe | hir::BiNe | hir::BiGe | hir::BiGt => true,
323                 _ => false,
324             }
325         }
326     }
327 }
328
329 declare_lint! {
330     IMPROPER_CTYPES,
331     Warn,
332     "proper use of libc types in foreign modules"
333 }
334
335 struct ImproperCTypesVisitor<'a, 'tcx: 'a> {
336     cx: &'a LateContext<'a, 'tcx>,
337 }
338
339 enum FfiResult {
340     FfiSafe,
341     FfiPhantom,
342     FfiUnsafe(&'static str),
343     FfiBadStruct(DefId, &'static str),
344     FfiBadUnion(DefId, &'static str),
345     FfiBadEnum(DefId, &'static str),
346 }
347
348 /// Check if this enum can be safely exported based on the
349 /// "nullable pointer optimization". Currently restricted
350 /// to function pointers and references, but could be
351 /// expanded to cover NonZero raw pointers and newtypes.
352 /// FIXME: This duplicates code in trans.
353 fn is_repr_nullable_ptr<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
354                                   def: &'tcx ty::AdtDef,
355                                   substs: &Substs<'tcx>)
356                                   -> bool {
357     if def.variants.len() == 2 {
358         let data_idx;
359
360         if def.variants[0].fields.is_empty() {
361             data_idx = 1;
362         } else if def.variants[1].fields.is_empty() {
363             data_idx = 0;
364         } else {
365             return false;
366         }
367
368         if def.variants[data_idx].fields.len() == 1 {
369             match def.variants[data_idx].fields[0].ty(tcx, substs).sty {
370                 ty::TyFnPtr(_) => {
371                     return true;
372                 }
373                 ty::TyRef(..) => {
374                     return true;
375                 }
376                 _ => {}
377             }
378         }
379     }
380     false
381 }
382
383 fn is_ffi_safe(ty: attr::IntType) -> bool {
384     match ty {
385         attr::SignedInt(ast::IntTy::I8) | attr::UnsignedInt(ast::UintTy::U8) |
386         attr::SignedInt(ast::IntTy::I16) | attr::UnsignedInt(ast::UintTy::U16) |
387         attr::SignedInt(ast::IntTy::I32) | attr::UnsignedInt(ast::UintTy::U32) |
388         attr::SignedInt(ast::IntTy::I64) | attr::UnsignedInt(ast::UintTy::U64) |
389         attr::SignedInt(ast::IntTy::I128) | attr::UnsignedInt(ast::UintTy::U128) => true,
390         attr::SignedInt(ast::IntTy::Is) | attr::UnsignedInt(ast::UintTy::Us) => false
391     }
392 }
393
394 impl<'a, 'tcx> ImproperCTypesVisitor<'a, 'tcx> {
395     /// Check if the given type is "ffi-safe" (has a stable, well-defined
396     /// representation which can be exported to C code).
397     fn check_type_for_ffi(&self,
398                           cache: &mut FxHashSet<Ty<'tcx>>,
399                           ty: Ty<'tcx>) -> FfiResult {
400         use self::FfiResult::*;
401
402         let cx = self.cx.tcx;
403
404         // Protect against infinite recursion, for example
405         // `struct S(*mut S);`.
406         // FIXME: A recursion limit is necessary as well, for irregular
407         // recusive types.
408         if !cache.insert(ty) {
409             return FfiSafe;
410         }
411
412         match ty.sty {
413             ty::TyAdt(def, substs) => {
414                 if def.is_phantom_data() {
415                     return FfiPhantom;
416                 }
417                 match def.adt_kind() {
418                     AdtKind::Struct => {
419                         if !def.repr.c() {
420                             return FfiUnsafe("found struct without foreign-function-safe \
421                                               representation annotation in foreign module, \
422                                               consider adding a #[repr(C)] attribute to the type");
423                         }
424
425                         if def.struct_variant().fields.is_empty() {
426                             return FfiUnsafe("found zero-size struct in foreign module, consider \
427                                               adding a member to this struct");
428                         }
429
430                         // We can't completely trust repr(C) markings; make sure the
431                         // fields are actually safe.
432                         let mut all_phantom = true;
433                         for field in &def.struct_variant().fields {
434                             let field_ty = cx.normalize_associated_type(&field.ty(cx, substs));
435                             let r = self.check_type_for_ffi(cache, field_ty);
436                             match r {
437                                 FfiSafe => {
438                                     all_phantom = false;
439                                 }
440                                 FfiPhantom => {}
441                                 FfiBadStruct(..) | FfiBadUnion(..) | FfiBadEnum(..) => {
442                                     return r;
443                                 }
444                                 FfiUnsafe(s) => {
445                                     return FfiBadStruct(def.did, s);
446                                 }
447                             }
448                         }
449
450                         if all_phantom { FfiPhantom } else { FfiSafe }
451                     }
452                     AdtKind::Union => {
453                         if !def.repr.c() {
454                             return FfiUnsafe("found union without foreign-function-safe \
455                                               representation annotation in foreign module, \
456                                               consider adding a #[repr(C)] attribute to the type");
457                         }
458
459                         if def.struct_variant().fields.is_empty() {
460                             return FfiUnsafe("found zero-size union in foreign module, consider \
461                                               adding a member to this union");
462                         }
463
464                         let mut all_phantom = true;
465                         for field in &def.struct_variant().fields {
466                             let field_ty = cx.normalize_associated_type(&field.ty(cx, substs));
467                             let r = self.check_type_for_ffi(cache, field_ty);
468                             match r {
469                                 FfiSafe => {
470                                     all_phantom = false;
471                                 }
472                                 FfiPhantom => {}
473                                 FfiBadStruct(..) | FfiBadUnion(..) | FfiBadEnum(..) => {
474                                     return r;
475                                 }
476                                 FfiUnsafe(s) => {
477                                     return FfiBadUnion(def.did, s);
478                                 }
479                             }
480                         }
481
482                         if all_phantom { FfiPhantom } else { FfiSafe }
483                     }
484                     AdtKind::Enum => {
485                         if def.variants.is_empty() {
486                             // Empty enums are okay... although sort of useless.
487                             return FfiSafe;
488                         }
489
490                         // Check for a repr() attribute to specify the size of the
491                         // discriminant.
492                         if !def.repr.c() && def.repr.int.is_none() {
493                             // Special-case types like `Option<extern fn()>`.
494                             if !is_repr_nullable_ptr(cx, def, substs) {
495                                 return FfiUnsafe("found enum without foreign-function-safe \
496                                                   representation annotation in foreign \
497                                                   module, consider adding a #[repr(...)] \
498                                                   attribute to the type");
499                             }
500                         }
501
502                         if let Some(int_ty) = def.repr.int {
503                             if !is_ffi_safe(int_ty) {
504                                 // FIXME: This shouldn't be reachable: we should check
505                                 // this earlier.
506                                 return FfiUnsafe("enum has unexpected #[repr(...)] attribute");
507                             }
508
509                             // Enum with an explicitly sized discriminant; either
510                             // a C-style enum or a discriminated union.
511
512                             // The layout of enum variants is implicitly repr(C).
513                             // FIXME: Is that correct?
514                         }
515
516                         // Check the contained variants.
517                         for variant in &def.variants {
518                             for field in &variant.fields {
519                                 let arg = cx.normalize_associated_type(&field.ty(cx, substs));
520                                 let r = self.check_type_for_ffi(cache, arg);
521                                 match r {
522                                     FfiSafe => {}
523                                     FfiBadStruct(..) | FfiBadUnion(..) | FfiBadEnum(..) => {
524                                         return r;
525                                     }
526                                     FfiPhantom => {
527                                         return FfiBadEnum(def.did,
528                                                           "Found phantom data in enum variant");
529                                     }
530                                     FfiUnsafe(s) => {
531                                         return FfiBadEnum(def.did, s);
532                                     }
533                                 }
534                             }
535                         }
536                         FfiSafe
537                     }
538                 }
539             }
540
541             ty::TyChar => {
542                 FfiUnsafe("found Rust type `char` in foreign module, while \
543                            `u32` or `libc::wchar_t` should be used")
544             }
545
546             // Primitive types with a stable representation.
547             ty::TyBool | ty::TyInt(..) | ty::TyUint(..) | ty::TyFloat(..) | ty::TyNever => FfiSafe,
548
549             ty::TySlice(_) => {
550                 FfiUnsafe("found Rust slice type in foreign module, \
551                            consider using a raw pointer instead")
552             }
553
554             ty::TyDynamic(..) => {
555                 FfiUnsafe("found Rust trait type in foreign module, \
556                            consider using a raw pointer instead")
557             }
558
559             ty::TyStr => {
560                 FfiUnsafe("found Rust type `str` in foreign module; \
561                            consider using a `*const libc::c_char`")
562             }
563
564             ty::TyTuple(..) => {
565                 FfiUnsafe("found Rust tuple type in foreign module; \
566                            consider using a struct instead")
567             }
568
569             ty::TyRawPtr(ref m) |
570             ty::TyRef(_, ref m) => self.check_type_for_ffi(cache, m.ty),
571
572             ty::TyArray(ty, _) => self.check_type_for_ffi(cache, ty),
573
574             ty::TyFnPtr(sig) => {
575                 match sig.abi() {
576                     Abi::Rust | Abi::RustIntrinsic | Abi::PlatformIntrinsic | Abi::RustCall => {
577                         return FfiUnsafe("found function pointer with Rust calling convention in \
578                                           foreign module; consider using an `extern` function \
579                                           pointer")
580                     }
581                     _ => {}
582                 }
583
584                 let sig = cx.erase_late_bound_regions(&sig);
585                 if !sig.output().is_nil() {
586                     let r = self.check_type_for_ffi(cache, sig.output());
587                     match r {
588                         FfiSafe => {}
589                         _ => {
590                             return r;
591                         }
592                     }
593                 }
594                 for arg in sig.inputs() {
595                     let r = self.check_type_for_ffi(cache, arg);
596                     match r {
597                         FfiSafe => {}
598                         _ => {
599                             return r;
600                         }
601                     }
602                 }
603                 FfiSafe
604             }
605
606             ty::TyParam(..) |
607             ty::TyInfer(..) |
608             ty::TyError |
609             ty::TyClosure(..) |
610             ty::TyProjection(..) |
611             ty::TyAnon(..) |
612             ty::TyFnDef(..) => bug!("Unexpected type in foreign function"),
613         }
614     }
615
616     fn check_type_for_ffi_and_report_errors(&mut self, sp: Span, ty: Ty<'tcx>) {
617         // it is only OK to use this function because extern fns cannot have
618         // any generic types right now:
619         let ty = self.cx.tcx.normalize_associated_type(&ty);
620
621         match self.check_type_for_ffi(&mut FxHashSet(), ty) {
622             FfiResult::FfiSafe => {}
623             FfiResult::FfiPhantom => {
624                 self.cx.span_lint(IMPROPER_CTYPES,
625                                   sp,
626                                   &format!("found zero-sized type composed only \
627                                             of phantom-data in a foreign-function."));
628             }
629             FfiResult::FfiUnsafe(s) => {
630                 self.cx.span_lint(IMPROPER_CTYPES, sp, s);
631             }
632             FfiResult::FfiBadStruct(_, s) => {
633                 // FIXME: This diagnostic is difficult to read, and doesn't
634                 // point at the relevant field.
635                 self.cx.span_lint(IMPROPER_CTYPES,
636                                   sp,
637                                   &format!("found non-foreign-function-safe member in struct \
638                                             marked #[repr(C)]: {}",
639                                            s));
640             }
641             FfiResult::FfiBadUnion(_, s) => {
642                 // FIXME: This diagnostic is difficult to read, and doesn't
643                 // point at the relevant field.
644                 self.cx.span_lint(IMPROPER_CTYPES,
645                                   sp,
646                                   &format!("found non-foreign-function-safe member in union \
647                                             marked #[repr(C)]: {}",
648                                            s));
649             }
650             FfiResult::FfiBadEnum(_, s) => {
651                 // FIXME: This diagnostic is difficult to read, and doesn't
652                 // point at the relevant variant.
653                 self.cx.span_lint(IMPROPER_CTYPES,
654                                   sp,
655                                   &format!("found non-foreign-function-safe member in enum: {}",
656                                            s));
657             }
658         }
659     }
660
661     fn check_foreign_fn(&mut self, id: ast::NodeId, decl: &hir::FnDecl) {
662         let def_id = self.cx.tcx.hir.local_def_id(id);
663         let sig = self.cx.tcx.type_of(def_id).fn_sig();
664         let sig = self.cx.tcx.erase_late_bound_regions(&sig);
665
666         for (input_ty, input_hir) in sig.inputs().iter().zip(&decl.inputs) {
667             self.check_type_for_ffi_and_report_errors(input_hir.span, input_ty);
668         }
669
670         if let hir::Return(ref ret_hir) = decl.output {
671             let ret_ty = sig.output();
672             if !ret_ty.is_nil() {
673                 self.check_type_for_ffi_and_report_errors(ret_hir.span, ret_ty);
674             }
675         }
676     }
677
678     fn check_foreign_static(&mut self, id: ast::NodeId, span: Span) {
679         let def_id = self.cx.tcx.hir.local_def_id(id);
680         let ty = self.cx.tcx.type_of(def_id);
681         self.check_type_for_ffi_and_report_errors(span, ty);
682     }
683 }
684
685 #[derive(Copy, Clone)]
686 pub struct ImproperCTypes;
687
688 impl LintPass for ImproperCTypes {
689     fn get_lints(&self) -> LintArray {
690         lint_array!(IMPROPER_CTYPES)
691     }
692 }
693
694 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ImproperCTypes {
695     fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
696         let mut vis = ImproperCTypesVisitor { cx: cx };
697         if let hir::ItemForeignMod(ref nmod) = it.node {
698             if nmod.abi != Abi::RustIntrinsic && nmod.abi != Abi::PlatformIntrinsic {
699                 for ni in &nmod.items {
700                     match ni.node {
701                         hir::ForeignItemFn(ref decl, _, _) => {
702                             vis.check_foreign_fn(ni.id, decl);
703                         }
704                         hir::ForeignItemStatic(ref ty, _) => {
705                             vis.check_foreign_static(ni.id, ty.span);
706                         }
707                     }
708                 }
709             }
710         }
711     }
712 }
713
714 pub struct VariantSizeDifferences;
715
716 impl LintPass for VariantSizeDifferences {
717     fn get_lints(&self) -> LintArray {
718         lint_array!(VARIANT_SIZE_DIFFERENCES)
719     }
720 }
721
722 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for VariantSizeDifferences {
723     fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
724         if let hir::ItemEnum(ref enum_definition, ref gens) = it.node {
725             if gens.ty_params.is_empty() {
726                 // sizes only make sense for non-generic types
727                 let t = cx.tcx.type_of(cx.tcx.hir.local_def_id(it.id));
728                 let layout = cx.tcx.infer_ctxt((), Reveal::All).enter(|infcx| {
729                     let ty = cx.tcx.erase_regions(&t);
730                     ty.layout(&infcx).unwrap_or_else(|e| {
731                         bug!("failed to get layout for `{}`: {}", t, e)
732                     })
733                 });
734
735                 if let Layout::General { ref variants, ref size, discr, .. } = *layout {
736                     let discr_size = Primitive::Int(discr).size(cx.tcx).bytes();
737
738                     debug!("enum `{}` is {} bytes large with layout:\n{:#?}",
739                       t, size.bytes(), layout);
740
741                     let (largest, slargest, largest_index) = enum_definition.variants
742                         .iter()
743                         .zip(variants)
744                         .map(|(variant, variant_layout)| {
745                             // Subtract the size of the enum discriminant
746                             let bytes = variant_layout.min_size
747                                 .bytes()
748                                 .saturating_sub(discr_size);
749
750                             debug!("- variant `{}` is {} bytes large", variant.node.name, bytes);
751                             bytes
752                         })
753                         .enumerate()
754                         .fold((0, 0, 0), |(l, s, li), (idx, size)| if size > l {
755                             (size, l, idx)
756                         } else if size > s {
757                             (l, size, li)
758                         } else {
759                             (l, s, li)
760                         });
761
762                     // we only warn if the largest variant is at least thrice as large as
763                     // the second-largest.
764                     if largest > slargest * 3 && slargest > 0 {
765                         cx.span_lint(VARIANT_SIZE_DIFFERENCES,
766                                      enum_definition.variants[largest_index].span,
767                                      &format!("enum variant is more than three times larger \
768                                                ({} bytes) than the next largest",
769                                               largest));
770                     }
771                 }
772             }
773         }
774     }
775 }