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