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