]> git.proxmox.com Git - rustc.git/blame - src/librustc_lint/types.rs
New upstream version 1.47.0+dfsg1
[rustc.git] / src / librustc_lint / types.rs
CommitLineData
9cc50fc6
SL
1#![allow(non_snake_case)]
2
dfeec247 3use crate::{LateContext, LateLintPass, LintContext};
3dfed10e 4use rustc_ast as ast;
74b04a01 5use rustc_attr as attr;
dfeec247
XL
6use rustc_data_structures::fx::FxHashSet;
7use rustc_errors::Applicability;
8use rustc_hir as hir;
dfeec247 9use rustc_hir::{is_range_literal, ExprKind, Node};
e74abb32 10use rustc_index::vec::Idx;
ba9703b0
XL
11use rustc_middle::mir::interpret::{sign_extend, truncate};
12use rustc_middle::ty::layout::{IntegerExt, SizeSkeleton};
13use rustc_middle::ty::subst::SubstsRef;
f035d41b 14use rustc_middle::ty::{self, AdtKind, Ty, TypeFoldable};
dfeec247
XL
15use rustc_span::source_map;
16use rustc_span::symbol::sym;
f035d41b 17use rustc_span::{Span, DUMMY_SP};
3dfed10e 18use rustc_target::abi::Abi;
f035d41b 19use rustc_target::abi::{Integer, LayoutOf, TagEncoding, VariantIdx, Variants};
3dfed10e 20use rustc_target::spec::abi::Abi as SpecAbi;
9fa01778 21
dfeec247 22use std::cmp;
3dfed10e 23use tracing::debug;
9fa01778 24
b039eaaf
SL
25declare_lint! {
26 UNUSED_COMPARISONS,
27 Warn,
28 "comparisons made useless by limits of the types involved"
29}
30
31declare_lint! {
32 OVERFLOWING_LITERALS,
9fa01778
XL
33 Deny,
34 "literal out of range for its type"
b039eaaf
SL
35}
36
5bcae85e
SL
37declare_lint! {
38 VARIANT_SIZE_DIFFERENCES,
39 Allow,
40 "detects enums with widely varying variant sizes"
41}
42
b039eaaf
SL
43#[derive(Copy, Clone)]
44pub struct TypeLimits {
45 /// Id of the last visited negated expression
ba9703b0 46 negated_expr_id: Option<hir::HirId>,
b039eaaf
SL
47}
48
532ac7d7
XL
49impl_lint_pass!(TypeLimits => [UNUSED_COMPARISONS, OVERFLOWING_LITERALS]);
50
b039eaaf
SL
51impl TypeLimits {
52 pub fn new() -> TypeLimits {
ba9703b0 53 TypeLimits { negated_expr_id: None }
b039eaaf
SL
54 }
55}
56
48663c56
XL
57/// Attempts to special-case the overflowing literal lint when it occurs as a range endpoint.
58/// Returns `true` iff the lint was overridden.
f035d41b
XL
59fn lint_overflowing_range_endpoint<'tcx>(
60 cx: &LateContext<'tcx>,
48663c56
XL
61 lit: &hir::Lit,
62 lit_val: u128,
63 max: u128,
dfeec247
XL
64 expr: &'tcx hir::Expr<'tcx>,
65 parent_expr: &'tcx hir::Expr<'tcx>,
60c5eb7d 66 ty: &str,
48663c56
XL
67) -> bool {
68 // We only want to handle exclusive (`..`) ranges,
69 // which are represented as `ExprKind::Struct`.
74b04a01 70 let mut overwritten = false;
e74abb32 71 if let ExprKind::Struct(_, eps, _) = &parent_expr.kind {
416331ca
XL
72 if eps.len() != 2 {
73 return false;
74 }
48663c56
XL
75 // We can suggest using an inclusive range
76 // (`..=`) instead only if it is the `end` that is
77 // overflowing and only by 1.
78 if eps[1].expr.hir_id == expr.hir_id && lit_val - 1 == max {
74b04a01
XL
79 cx.struct_span_lint(OVERFLOWING_LITERALS, parent_expr.span, |lint| {
80 let mut err = lint.build(&format!("range endpoint is out of range for `{}`", ty));
81 if let Ok(start) = cx.sess().source_map().span_to_snippet(eps[0].span) {
82 use ast::{LitIntType, LitKind};
83 // We need to preserve the literal's suffix,
84 // as it may determine typing information.
85 let suffix = match lit.node {
86 LitKind::Int(_, LitIntType::Signed(s)) => s.name_str().to_string(),
87 LitKind::Int(_, LitIntType::Unsigned(s)) => s.name_str().to_string(),
88 LitKind::Int(_, LitIntType::Unsuffixed) => "".to_string(),
89 _ => bug!(),
90 };
91 let suggestion = format!("{}..={}{}", start, lit_val - 1, suffix);
92 err.span_suggestion(
93 parent_expr.span,
94 &"use an inclusive range instead",
95 suggestion,
96 Applicability::MachineApplicable,
97 );
98 err.emit();
99 overwritten = true;
100 }
101 });
48663c56
XL
102 }
103 }
74b04a01 104 overwritten
48663c56
XL
105}
106
107// For `isize` & `usize`, be conservative with the warnings, so that the
108// warnings are consistent between 32- and 64-bit platforms.
109fn int_ty_range(int_ty: ast::IntTy) -> (i128, i128) {
110 match int_ty {
f035d41b
XL
111 ast::IntTy::Isize => (i64::MIN as i128, i64::MAX as i128),
112 ast::IntTy::I8 => (i8::MIN as i64 as i128, i8::MAX as i128),
113 ast::IntTy::I16 => (i16::MIN as i64 as i128, i16::MAX as i128),
114 ast::IntTy::I32 => (i32::MIN as i64 as i128, i32::MAX as i128),
115 ast::IntTy::I64 => (i64::MIN as i128, i64::MAX as i128),
116 ast::IntTy::I128 => (i128::MIN as i128, i128::MAX),
48663c56
XL
117 }
118}
119
120fn uint_ty_range(uint_ty: ast::UintTy) -> (u128, u128) {
121 match uint_ty {
f035d41b
XL
122 ast::UintTy::Usize => (u64::MIN as u128, u64::MAX as u128),
123 ast::UintTy::U8 => (u8::MIN as u128, u8::MAX as u128),
124 ast::UintTy::U16 => (u16::MIN as u128, u16::MAX as u128),
125 ast::UintTy::U32 => (u32::MIN as u128, u32::MAX as u128),
126 ast::UintTy::U64 => (u64::MIN as u128, u64::MAX as u128),
127 ast::UintTy::U128 => (u128::MIN, u128::MAX),
48663c56
XL
128 }
129}
130
f035d41b 131fn get_bin_hex_repr(cx: &LateContext<'_>, lit: &hir::Lit) -> Option<String> {
48663c56
XL
132 let src = cx.sess().source_map().span_to_snippet(lit.span).ok()?;
133 let firstch = src.chars().next()?;
134
135 if firstch == '0' {
136 match src.chars().nth(1) {
ba9703b0 137 Some('x' | 'b') => return Some(src),
48663c56
XL
138 _ => return None,
139 }
140 }
141
142 None
143}
144
145fn report_bin_hex_error(
f035d41b 146 cx: &LateContext<'_>,
dfeec247 147 expr: &hir::Expr<'_>,
48663c56
XL
148 ty: attr::IntType,
149 repr_str: String,
150 val: u128,
151 negative: bool,
152) {
ba9703b0 153 let size = Integer::from_attr(&cx.tcx, ty).size();
74b04a01
XL
154 cx.struct_span_lint(OVERFLOWING_LITERALS, expr.span, |lint| {
155 let (t, actually) = match ty {
156 attr::IntType::SignedInt(t) => {
157 let actually = sign_extend(val, size) as i128;
158 (t.name_str(), actually.to_string())
159 }
160 attr::IntType::UnsignedInt(t) => {
161 let actually = truncate(val, size);
162 (t.name_str(), actually.to_string())
163 }
164 };
165 let mut err = lint.build(&format!("literal out of range for {}", t));
166 err.note(&format!(
167 "the literal `{}` (decimal `{}`) does not fit into \
ba9703b0 168 the type `{}` and will become `{}{}`",
74b04a01
XL
169 repr_str, val, t, actually, t
170 ));
f035d41b 171 if let Some(sugg_ty) =
3dfed10e 172 get_type_suggestion(&cx.typeck_results().node_type(expr.hir_id), val, negative)
74b04a01
XL
173 {
174 if let Some(pos) = repr_str.chars().position(|c| c == 'i' || c == 'u') {
175 let (sans_suffix, _) = repr_str.split_at(pos);
176 err.span_suggestion(
177 expr.span,
178 &format!("consider using `{}` instead", sugg_ty),
179 format!("{}{}", sans_suffix, sugg_ty),
180 Applicability::MachineApplicable,
181 );
182 } else {
183 err.help(&format!("consider using `{}` instead", sugg_ty));
184 }
48663c56 185 }
74b04a01
XL
186 err.emit();
187 });
48663c56
XL
188}
189
190// This function finds the next fitting type and generates a suggestion string.
191// It searches for fitting types in the following way (`X < Y`):
192// - `iX`: if literal fits in `uX` => `uX`, else => `iY`
193// - `-iX` => `iY`
194// - `uX` => `uY`
195//
196// No suggestion for: `isize`, `usize`.
60c5eb7d 197fn get_type_suggestion(t: Ty<'_>, val: u128, negative: bool) -> Option<&'static str> {
3dfed10e
XL
198 use rustc_ast::IntTy::*;
199 use rustc_ast::UintTy::*;
48663c56
XL
200 macro_rules! find_fit {
201 ($ty:expr, $val:expr, $negative:expr,
202 $($type:ident => [$($utypes:expr),*] => [$($itypes:expr),*]),+) => {
203 {
204 let _neg = if negative { 1 } else { 0 };
205 match $ty {
206 $($type => {
207 $(if !negative && val <= uint_ty_range($utypes).1 {
60c5eb7d 208 return Some($utypes.name_str())
48663c56
XL
209 })*
210 $(if val <= int_ty_range($itypes).1 as u128 + _neg {
60c5eb7d 211 return Some($itypes.name_str())
48663c56
XL
212 })*
213 None
dc9dc135 214 },)+
48663c56
XL
215 _ => None
216 }
217 }
218 }
219 }
e74abb32 220 match t.kind {
48663c56
XL
221 ty::Int(i) => find_fit!(i, val, negative,
222 I8 => [U8] => [I16, I32, I64, I128],
223 I16 => [U16] => [I32, I64, I128],
224 I32 => [U32] => [I64, I128],
225 I64 => [U64] => [I128],
226 I128 => [U128] => []),
227 ty::Uint(u) => find_fit!(u, val, negative,
228 U8 => [U8, U16, U32, U64, U128] => [],
229 U16 => [U16, U32, U64, U128] => [],
230 U32 => [U32, U64, U128] => [],
231 U64 => [U64, U128] => [],
232 U128 => [U128] => []),
233 _ => None,
234 }
235}
236
f035d41b
XL
237fn lint_int_literal<'tcx>(
238 cx: &LateContext<'tcx>,
48663c56 239 type_limits: &TypeLimits,
dfeec247 240 e: &'tcx hir::Expr<'tcx>,
48663c56
XL
241 lit: &hir::Lit,
242 t: ast::IntTy,
243 v: u128,
244) {
60c5eb7d 245 let int_type = t.normalize(cx.sess().target.ptr_width);
ba9703b0 246 let (min, max) = int_ty_range(int_type);
48663c56 247 let max = max as u128;
ba9703b0 248 let negative = type_limits.negated_expr_id == Some(e.hir_id);
48663c56
XL
249
250 // Detect literal value out of range [min, max] inclusive
251 // avoiding use of -min to prevent overflow/panic
252 if (negative && v > max + 1) || (!negative && v > max) {
253 if let Some(repr_str) = get_bin_hex_repr(cx, lit) {
dfeec247 254 report_bin_hex_error(cx, e, attr::IntType::SignedInt(t), repr_str, v, negative);
48663c56
XL
255 return;
256 }
257
dc9dc135
XL
258 let par_id = cx.tcx.hir().get_parent_node(e.hir_id);
259 if let Node::Expr(par_e) = cx.tcx.hir().get(par_id) {
e74abb32 260 if let hir::ExprKind::Struct(..) = par_e.kind {
3dfed10e 261 if is_range_literal(par_e)
60c5eb7d 262 && lint_overflowing_range_endpoint(cx, lit, v, max, e, par_e, t.name_str())
48663c56
XL
263 {
264 // The overflowing literal lint was overridden.
265 return;
266 }
267 }
268 }
269
74b04a01 270 cx.struct_span_lint(OVERFLOWING_LITERALS, e.span, |lint| {
ba9703b0
XL
271 lint.build(&format!("literal out of range for `{}`", t.name_str()))
272 .note(&format!(
273 "the literal `{}` does not fit into the type `{}` whose range is `{}..={}`",
274 cx.sess()
275 .source_map()
276 .span_to_snippet(lit.span)
277 .expect("must get snippet from literal"),
278 t.name_str(),
279 min,
280 max,
281 ))
282 .emit();
74b04a01 283 });
48663c56
XL
284 }
285}
286
f035d41b
XL
287fn lint_uint_literal<'tcx>(
288 cx: &LateContext<'tcx>,
dfeec247 289 e: &'tcx hir::Expr<'tcx>,
48663c56
XL
290 lit: &hir::Lit,
291 t: ast::UintTy,
292) {
60c5eb7d 293 let uint_type = t.normalize(cx.sess().target.ptr_width);
48663c56
XL
294 let (min, max) = uint_ty_range(uint_type);
295 let lit_val: u128 = match lit.node {
296 // _v is u8, within range by definition
297 ast::LitKind::Byte(_v) => return,
298 ast::LitKind::Int(v, _) => v,
299 _ => bug!(),
300 };
301 if lit_val < min || lit_val > max {
dc9dc135
XL
302 let parent_id = cx.tcx.hir().get_parent_node(e.hir_id);
303 if let Node::Expr(par_e) = cx.tcx.hir().get(parent_id) {
e74abb32 304 match par_e.kind {
48663c56 305 hir::ExprKind::Cast(..) => {
3dfed10e 306 if let ty::Char = cx.typeck_results().expr_ty(par_e).kind {
74b04a01
XL
307 cx.struct_span_lint(OVERFLOWING_LITERALS, par_e.span, |lint| {
308 lint.build("only `u8` can be cast into `char`")
309 .span_suggestion(
310 par_e.span,
311 &"use a `char` literal instead",
312 format!("'\\u{{{:X}}}'", lit_val),
313 Applicability::MachineApplicable,
314 )
315 .emit();
316 });
48663c56
XL
317 return;
318 }
319 }
3dfed10e 320 hir::ExprKind::Struct(..) if is_range_literal(par_e) => {
dfeec247
XL
321 let t = t.name_str();
322 if lint_overflowing_range_endpoint(cx, lit, lit_val, max, e, par_e, t) {
323 // The overflowing literal lint was overridden.
324 return;
48663c56 325 }
dfeec247 326 }
48663c56
XL
327 _ => {}
328 }
329 }
330 if let Some(repr_str) = get_bin_hex_repr(cx, lit) {
331 report_bin_hex_error(cx, e, attr::IntType::UnsignedInt(t), repr_str, lit_val, false);
332 return;
333 }
74b04a01 334 cx.struct_span_lint(OVERFLOWING_LITERALS, e.span, |lint| {
ba9703b0
XL
335 lint.build(&format!("literal out of range for `{}`", t.name_str()))
336 .note(&format!(
337 "the literal `{}` does not fit into the type `{}` whose range is `{}..={}`",
338 cx.sess()
339 .source_map()
340 .span_to_snippet(lit.span)
341 .expect("must get snippet from literal"),
342 t.name_str(),
343 min,
344 max,
345 ))
346 .emit()
74b04a01 347 });
48663c56
XL
348 }
349}
350
f035d41b
XL
351fn lint_literal<'tcx>(
352 cx: &LateContext<'tcx>,
48663c56 353 type_limits: &TypeLimits,
dfeec247 354 e: &'tcx hir::Expr<'tcx>,
48663c56
XL
355 lit: &hir::Lit,
356) {
3dfed10e 357 match cx.typeck_results().node_type(e.hir_id).kind {
48663c56
XL
358 ty::Int(t) => {
359 match lit.node {
ba9703b0 360 ast::LitKind::Int(v, ast::LitIntType::Signed(_) | ast::LitIntType::Unsuffixed) => {
48663c56
XL
361 lint_int_literal(cx, type_limits, e, lit, t, v)
362 }
363 _ => bug!(),
364 };
365 }
dfeec247 366 ty::Uint(t) => lint_uint_literal(cx, e, lit, t),
48663c56
XL
367 ty::Float(t) => {
368 let is_infinite = match lit.node {
dfeec247
XL
369 ast::LitKind::Float(v, _) => match t {
370 ast::FloatTy::F32 => v.as_str().parse().map(f32::is_infinite),
371 ast::FloatTy::F64 => v.as_str().parse().map(f64::is_infinite),
372 },
48663c56
XL
373 _ => bug!(),
374 };
375 if is_infinite == Ok(true) {
74b04a01 376 cx.struct_span_lint(OVERFLOWING_LITERALS, e.span, |lint| {
ba9703b0
XL
377 lint.build(&format!("literal out of range for `{}`", t.name_str()))
378 .note(&format!(
379 "the literal `{}` does not fit into the type `{}` and will be converted to `std::{}::INFINITY`",
380 cx.sess()
381 .source_map()
382 .span_to_snippet(lit.span)
383 .expect("must get snippet from literal"),
384 t.name_str(),
385 t.name_str(),
386 ))
387 .emit();
74b04a01 388 });
48663c56
XL
389 }
390 }
391 _ => {}
392 }
393}
394
f035d41b
XL
395impl<'tcx> LateLintPass<'tcx> for TypeLimits {
396 fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx hir::Expr<'tcx>) {
e74abb32 397 match e.kind {
dfeec247 398 hir::ExprKind::Unary(hir::UnOp::UnNeg, ref expr) => {
b039eaaf 399 // propagate negation, if the negation itself isn't negated
ba9703b0
XL
400 if self.negated_expr_id != Some(e.hir_id) {
401 self.negated_expr_id = Some(expr.hir_id);
b039eaaf 402 }
c30ab7b3 403 }
8faf50e0 404 hir::ExprKind::Binary(binop, ref l, ref r) => {
32a655c1 405 if is_comparison(binop) && !check_limits(cx, binop, &l, &r) {
74b04a01
XL
406 cx.struct_span_lint(UNUSED_COMPARISONS, e.span, |lint| {
407 lint.build("comparison is useless due to type limits").emit()
408 });
b039eaaf 409 }
c30ab7b3 410 }
48663c56
XL
411 hir::ExprKind::Lit(ref lit) => lint_literal(cx, self, e, lit),
412 _ => {}
b039eaaf
SL
413 };
414
c30ab7b3 415 fn is_valid<T: cmp::PartialOrd>(binop: hir::BinOp, v: T, min: T, max: T) -> bool {
b039eaaf 416 match binop.node {
8faf50e0
XL
417 hir::BinOpKind::Lt => v > min && v <= max,
418 hir::BinOpKind::Le => v >= min && v < max,
419 hir::BinOpKind::Gt => v >= min && v < max,
420 hir::BinOpKind::Ge => v > min && v <= max,
421 hir::BinOpKind::Eq | hir::BinOpKind::Ne => v >= min && v <= max,
c30ab7b3 422 _ => bug!(),
b039eaaf
SL
423 }
424 }
425
426 fn rev_binop(binop: hir::BinOp) -> hir::BinOp {
dfeec247
XL
427 source_map::respan(
428 binop.span,
429 match binop.node {
430 hir::BinOpKind::Lt => hir::BinOpKind::Gt,
431 hir::BinOpKind::Le => hir::BinOpKind::Ge,
432 hir::BinOpKind::Gt => hir::BinOpKind::Lt,
433 hir::BinOpKind::Ge => hir::BinOpKind::Le,
434 _ => return binop,
435 },
436 )
b039eaaf
SL
437 }
438
dfeec247 439 fn check_limits(
f035d41b 440 cx: &LateContext<'_>,
dfeec247
XL
441 binop: hir::BinOp,
442 l: &hir::Expr<'_>,
443 r: &hir::Expr<'_>,
444 ) -> bool {
e74abb32 445 let (lit, expr, swap) = match (&l.kind, &r.kind) {
8faf50e0
XL
446 (&hir::ExprKind::Lit(_), _) => (l, r, true),
447 (_, &hir::ExprKind::Lit(_)) => (r, l, false),
c30ab7b3 448 _ => return true,
b039eaaf
SL
449 };
450 // Normalize the binop so that the literal is always on the RHS in
451 // the comparison
c30ab7b3 452 let norm_binop = if swap { rev_binop(binop) } else { binop };
3dfed10e 453 match cx.typeck_results().node_type(expr.hir_id).kind {
b7449926 454 ty::Int(int_ty) => {
b039eaaf 455 let (min, max) = int_ty_range(int_ty);
e74abb32 456 let lit_val: i128 = match lit.kind {
dfeec247 457 hir::ExprKind::Lit(ref li) => match li.node {
ba9703b0
XL
458 ast::LitKind::Int(
459 v,
460 ast::LitIntType::Signed(_) | ast::LitIntType::Unsuffixed,
461 ) => v as i128,
dfeec247 462 _ => return true,
32a655c1 463 },
dfeec247 464 _ => bug!(),
b039eaaf
SL
465 };
466 is_valid(norm_binop, lit_val, min, max)
467 }
b7449926 468 ty::Uint(uint_ty) => {
dfeec247 469 let (min, max): (u128, u128) = uint_ty_range(uint_ty);
e74abb32 470 let lit_val: u128 = match lit.kind {
dfeec247
XL
471 hir::ExprKind::Lit(ref li) => match li.node {
472 ast::LitKind::Int(v, _) => v,
473 _ => return true,
32a655c1 474 },
dfeec247 475 _ => bug!(),
b039eaaf
SL
476 };
477 is_valid(norm_binop, lit_val, min, max)
478 }
c30ab7b3 479 _ => true,
b039eaaf
SL
480 }
481 }
482
483 fn is_comparison(binop: hir::BinOp) -> bool {
484 match binop.node {
dfeec247
XL
485 hir::BinOpKind::Eq
486 | hir::BinOpKind::Lt
487 | hir::BinOpKind::Le
488 | hir::BinOpKind::Ne
489 | hir::BinOpKind::Ge
490 | hir::BinOpKind::Gt => true,
c30ab7b3 491 _ => false,
b039eaaf
SL
492 }
493 }
b039eaaf
SL
494 }
495}
496
497declare_lint! {
498 IMPROPER_CTYPES,
499 Warn,
500 "proper use of libc types in foreign modules"
501}
502
f035d41b
XL
503declare_lint_pass!(ImproperCTypesDeclarations => [IMPROPER_CTYPES]);
504
505declare_lint! {
506 IMPROPER_CTYPES_DEFINITIONS,
507 Warn,
508 "proper use of libc types in foreign item definitions"
509}
510
511declare_lint_pass!(ImproperCTypesDefinitions => [IMPROPER_CTYPES_DEFINITIONS]);
512
3dfed10e
XL
513#[derive(Clone, Copy)]
514crate enum CItemKind {
515 Declaration,
516 Definition,
f035d41b 517}
532ac7d7 518
dc9dc135 519struct ImproperCTypesVisitor<'a, 'tcx> {
f035d41b 520 cx: &'a LateContext<'tcx>,
3dfed10e 521 mode: CItemKind,
b039eaaf
SL
522}
523
0531ce1d 524enum FfiResult<'tcx> {
b039eaaf 525 FfiSafe,
0531ce1d 526 FfiPhantom(Ty<'tcx>),
f035d41b 527 FfiUnsafe { ty: Ty<'tcx>, reason: String, help: Option<String> },
b039eaaf
SL
528}
529
3dfed10e
XL
530/// Is type known to be non-null?
531fn ty_is_known_nonnull<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>, mode: CItemKind) -> bool {
532 let tcx = cx.tcx;
533 match ty.kind {
534 ty::FnPtr(_) => true,
535 ty::Ref(..) => true,
536 ty::Adt(def, _) if def.is_box() && matches!(mode, CItemKind::Definition) => true,
537 ty::Adt(def, substs) if def.repr.transparent() && !def.is_union() => {
538 let guaranteed_nonnull_optimization = tcx
539 .get_attrs(def.did)
540 .iter()
541 .any(|a| tcx.sess.check_name(a, sym::rustc_nonnull_optimization_guaranteed));
542
543 if guaranteed_nonnull_optimization {
544 return true;
f9652781 545 }
3dfed10e
XL
546 for variant in &def.variants {
547 if let Some(field) = variant.transparent_newtype_field(tcx) {
548 if ty_is_known_nonnull(cx, field.ty(tcx, substs), mode) {
549 return true;
f035d41b 550 }
c30ab7b3 551 }
b039eaaf 552 }
3dfed10e
XL
553
554 false
b039eaaf 555 }
3dfed10e 556 _ => false,
b039eaaf 557 }
3dfed10e 558}
dc9dc135 559
3dfed10e
XL
560/// Given a non-null scalar (or transparent) type `ty`, return the nullable version of that type.
561/// If the type passed in was not scalar, returns None.
562fn get_nullable_type<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> Option<Ty<'tcx>> {
563 let tcx = cx.tcx;
564 Some(match ty.kind {
565 ty::Adt(field_def, field_substs) => {
566 let inner_field_ty = {
567 let first_non_zst_ty =
568 field_def.variants.iter().filter_map(|v| v.transparent_newtype_field(tcx));
569 debug_assert_eq!(
570 first_non_zst_ty.clone().count(),
571 1,
572 "Wrong number of fields for transparent type"
573 );
574 first_non_zst_ty
575 .last()
576 .expect("No non-zst fields in transparent type.")
577 .ty(tcx, field_substs)
578 };
579 return get_nullable_type(cx, inner_field_ty);
580 }
581 ty::Int(ty) => tcx.mk_mach_int(ty),
582 ty::Uint(ty) => tcx.mk_mach_uint(ty),
583 ty::RawPtr(ty_mut) => tcx.mk_ptr(ty_mut),
584 // As these types are always non-null, the nullable equivalent of
585 // Option<T> of these types are their raw pointer counterparts.
586 ty::Ref(_region, ty, mutbl) => tcx.mk_ptr(ty::TypeAndMut { ty, mutbl }),
587 ty::FnPtr(..) => {
588 // There is no nullable equivalent for Rust's function pointers -- you
589 // must use an Option<fn(..) -> _> to represent it.
590 ty
591 }
592
593 // We should only ever reach this case if ty_is_known_nonnull is extended
594 // to other types.
595 ref unhandled => {
596 debug!(
597 "get_nullable_type: Unhandled scalar kind: {:?} while checking {:?}",
598 unhandled, ty
599 );
600 return None;
601 }
602 })
603}
604
605/// Check if this enum can be safely exported based on the "nullable pointer optimization". If it
606/// can, return the the type that `ty` can be safely converted to, otherwise return `None`.
607/// Currently restricted to function pointers, boxes, references, `core::num::NonZero*`,
608/// `core::ptr::NonNull`, and `#[repr(transparent)]` newtypes.
609/// FIXME: This duplicates code in codegen.
610crate fn repr_nullable_ptr<'tcx>(
611 cx: &LateContext<'tcx>,
612 ty: Ty<'tcx>,
613 ckind: CItemKind,
614) -> Option<Ty<'tcx>> {
615 debug!("is_repr_nullable_ptr(cx, ty = {:?})", ty);
616 if let ty::Adt(ty_def, substs) = ty.kind {
f035d41b 617 if ty_def.variants.len() != 2 {
3dfed10e 618 return None;
f035d41b 619 }
dc9dc135 620
f035d41b
XL
621 let get_variant_fields = |index| &ty_def.variants[VariantIdx::new(index)].fields;
622 let variant_fields = [get_variant_fields(0), get_variant_fields(1)];
623 let fields = if variant_fields[0].is_empty() {
624 &variant_fields[1]
625 } else if variant_fields[1].is_empty() {
626 &variant_fields[0]
627 } else {
3dfed10e 628 return None;
f035d41b 629 };
dc9dc135 630
f035d41b 631 if fields.len() != 1 {
3dfed10e 632 return None;
f035d41b 633 }
dc9dc135 634
3dfed10e
XL
635 let field_ty = fields[0].ty(cx.tcx, substs);
636 if !ty_is_known_nonnull(cx, field_ty, ckind) {
637 return None;
f035d41b 638 }
dc9dc135 639
3dfed10e
XL
640 // At this point, the field's type is known to be nonnull and the parent enum is Option-like.
641 // If the computed size for the field and the enum are different, the nonnull optimization isn't
642 // being applied (and we've got a problem somewhere).
643 let compute_size_skeleton = |t| SizeSkeleton::compute(t, cx.tcx, cx.param_env).unwrap();
f035d41b
XL
644 if !compute_size_skeleton(ty).same_size(compute_size_skeleton(field_ty)) {
645 bug!("improper_ctypes: Option nonnull optimization not applied?");
646 }
dc9dc135 647
3dfed10e
XL
648 // Return the nullable type this Option-like enum can be safely represented with.
649 let field_ty_abi = &cx.layout_of(field_ty).unwrap().abi;
650 if let Abi::Scalar(field_ty_scalar) = field_ty_abi {
651 match (field_ty_scalar.valid_range.start(), field_ty_scalar.valid_range.end()) {
652 (0, _) => unreachable!("Non-null optimisation extended to a non-zero value."),
653 (1, _) => {
654 return Some(get_nullable_type(cx, field_ty).unwrap());
655 }
656 (start, end) => unreachable!("Unhandled start and end range: ({}, {})", start, end),
657 };
658 }
f035d41b 659 }
3dfed10e
XL
660 None
661}
b039eaaf 662
3dfed10e 663impl<'a, 'tcx> ImproperCTypesVisitor<'a, 'tcx> {
60c5eb7d
XL
664 /// Check if the type is array and emit an unsafe type lint.
665 fn check_for_array_ty(&mut self, sp: Span, ty: Ty<'tcx>) -> bool {
666 if let ty::Array(..) = ty.kind {
667 self.emit_ffi_unsafe_type_lint(
668 ty,
669 sp,
670 "passing raw arrays by value is not FFI-safe",
671 Some("consider passing a pointer to the array"),
672 );
673 true
674 } else {
675 false
676 }
677 }
678
f035d41b
XL
679 /// Checks if the given field's type is "ffi-safe".
680 fn check_field_type_for_ffi(
681 &self,
682 cache: &mut FxHashSet<Ty<'tcx>>,
683 field: &ty::FieldDef,
684 substs: SubstsRef<'tcx>,
685 ) -> FfiResult<'tcx> {
686 let field_ty = field.ty(self.cx.tcx, substs);
687 if field_ty.has_opaque_types() {
688 self.check_type_for_ffi(cache, field_ty)
689 } else {
690 let field_ty = self.cx.tcx.normalize_erasing_regions(self.cx.param_env, field_ty);
691 self.check_type_for_ffi(cache, field_ty)
692 }
693 }
694
695 /// Checks if the given `VariantDef`'s field types are "ffi-safe".
696 fn check_variant_for_ffi(
697 &self,
698 cache: &mut FxHashSet<Ty<'tcx>>,
699 ty: Ty<'tcx>,
700 def: &ty::AdtDef,
701 variant: &ty::VariantDef,
702 substs: SubstsRef<'tcx>,
703 ) -> FfiResult<'tcx> {
704 use FfiResult::*;
705
706 if def.repr.transparent() {
707 // Can assume that only one field is not a ZST, so only check
708 // that field's type for FFI-safety.
709 if let Some(field) = variant.transparent_newtype_field(self.cx.tcx) {
710 self.check_field_type_for_ffi(cache, field, substs)
711 } else {
712 bug!("malformed transparent type");
713 }
714 } else {
715 // We can't completely trust repr(C) markings; make sure the fields are
716 // actually safe.
717 let mut all_phantom = !variant.fields.is_empty();
718 for field in &variant.fields {
719 match self.check_field_type_for_ffi(cache, &field, substs) {
720 FfiSafe => {
721 all_phantom = false;
722 }
723 FfiPhantom(..) if def.is_enum() => {
724 return FfiUnsafe {
725 ty,
726 reason: "this enum contains a PhantomData field".into(),
727 help: None,
728 };
729 }
730 FfiPhantom(..) => {}
731 r => return r,
732 }
733 }
734
735 if all_phantom { FfiPhantom(ty) } else { FfiSafe }
736 }
737 }
738
9fa01778 739 /// Checks if the given type is "ffi-safe" (has a stable, well-defined
b039eaaf 740 /// representation which can be exported to C code).
dfeec247 741 fn check_type_for_ffi(&self, cache: &mut FxHashSet<Ty<'tcx>>, ty: Ty<'tcx>) -> FfiResult<'tcx> {
9fa01778 742 use FfiResult::*;
8bb4bdeb 743
3dfed10e 744 let tcx = self.cx.tcx;
b039eaaf
SL
745
746 // Protect against infinite recursion, for example
747 // `struct S(*mut S);`.
748 // FIXME: A recursion limit is necessary as well, for irregular
b7449926 749 // recursive types.
b039eaaf
SL
750 if !cache.insert(ty) {
751 return FfiSafe;
752 }
753
e74abb32 754 match ty.kind {
3dfed10e 755 ty::Adt(def, _) if def.is_box() && matches!(self.mode, CItemKind::Definition) => {
f9652781
XL
756 FfiSafe
757 }
758
b7449926 759 ty::Adt(def, substs) => {
8bb4bdeb 760 if def.is_phantom_data() {
0531ce1d 761 return FfiPhantom(ty);
8bb4bdeb 762 }
c30ab7b3 763 match def.adt_kind() {
f035d41b
XL
764 AdtKind::Struct | AdtKind::Union => {
765 let kind = if def.is_struct() { "struct" } else { "union" };
766
2c00a5a8 767 if !def.repr.c() && !def.repr.transparent() {
0531ce1d 768 return FfiUnsafe {
e1599b0c 769 ty,
f035d41b
XL
770 reason: format!("this {} has unspecified layout", kind),
771 help: Some(format!(
dfeec247 772 "consider adding a `#[repr(C)]` or \
f035d41b
XL
773 `#[repr(transparent)]` attribute to this {}",
774 kind
775 )),
0531ce1d 776 };
c30ab7b3 777 }
b039eaaf 778
e74abb32
XL
779 let is_non_exhaustive =
780 def.non_enum_variant().is_field_list_non_exhaustive();
781 if is_non_exhaustive && !def.did.is_local() {
782 return FfiUnsafe {
783 ty,
f035d41b 784 reason: format!("this {} is non-exhaustive", kind),
e74abb32
XL
785 help: None,
786 };
787 }
788
2c00a5a8 789 if def.non_enum_variant().fields.is_empty() {
0531ce1d 790 return FfiUnsafe {
e1599b0c 791 ty,
f035d41b
XL
792 reason: format!("this {} has no fields", kind),
793 help: Some(format!("consider adding a member to this {}", kind)),
0531ce1d 794 };
8bb4bdeb
XL
795 }
796
f035d41b 797 self.check_variant_for_ffi(cache, ty, def, def.non_enum_variant(), substs)
b039eaaf 798 }
c30ab7b3
SL
799 AdtKind::Enum => {
800 if def.variants.is_empty() {
801 // Empty enums are okay... although sort of useless.
802 return FfiSafe;
803 }
9e0c209e 804
c30ab7b3
SL
805 // Check for a repr() attribute to specify the size of the
806 // discriminant.
dc9dc135 807 if !def.repr.c() && !def.repr.transparent() && def.repr.int.is_none() {
8bb4bdeb 808 // Special-case types like `Option<extern fn()>`.
3dfed10e 809 if repr_nullable_ptr(self.cx, ty, self.mode).is_none() {
0531ce1d 810 return FfiUnsafe {
e1599b0c 811 ty,
f035d41b 812 reason: "enum has no representation hint".into(),
dfeec247
XL
813 help: Some(
814 "consider adding a `#[repr(C)]`, \
dc9dc135 815 `#[repr(transparent)]`, or integer `#[repr(...)]` \
f035d41b
XL
816 attribute to this enum"
817 .into(),
dfeec247 818 ),
0531ce1d 819 };
9e0c209e 820 }
8bb4bdeb 821 }
c30ab7b3 822
e74abb32
XL
823 if def.is_variant_list_non_exhaustive() && !def.did.is_local() {
824 return FfiUnsafe {
825 ty,
f035d41b 826 reason: "this enum is non-exhaustive".into(),
e74abb32
XL
827 help: None,
828 };
829 }
830
c30ab7b3
SL
831 // Check the contained variants.
832 for variant in &def.variants {
e74abb32
XL
833 let is_non_exhaustive = variant.is_field_list_non_exhaustive();
834 if is_non_exhaustive && !variant.def_id.is_local() {
835 return FfiUnsafe {
836 ty,
f035d41b 837 reason: "this enum has non-exhaustive variants".into(),
e74abb32
XL
838 help: None,
839 };
840 }
841
f035d41b
XL
842 match self.check_variant_for_ffi(cache, ty, def, variant, substs) {
843 FfiSafe => (),
844 r => return r,
9e0c209e 845 }
b039eaaf 846 }
f035d41b 847
c30ab7b3 848 FfiSafe
b039eaaf
SL
849 }
850 }
c30ab7b3 851 }
b039eaaf 852
b7449926 853 ty::Char => FfiUnsafe {
e1599b0c 854 ty,
f035d41b
XL
855 reason: "the `char` type has no C equivalent".into(),
856 help: Some("consider using `u32` or `libc::wchar_t` instead".into()),
0531ce1d 857 },
b039eaaf 858
b7449926 859 ty::Int(ast::IntTy::I128) | ty::Uint(ast::UintTy::U128) => FfiUnsafe {
e1599b0c 860 ty,
f035d41b 861 reason: "128-bit integers don't currently have a known stable ABI".into(),
0531ce1d
XL
862 help: None,
863 },
ea8adc8c 864
b039eaaf 865 // Primitive types with a stable representation.
b7449926 866 ty::Bool | ty::Int(..) | ty::Uint(..) | ty::Float(..) | ty::Never => FfiSafe,
b039eaaf 867
b7449926 868 ty::Slice(_) => FfiUnsafe {
e1599b0c 869 ty,
f035d41b
XL
870 reason: "slices have no C equivalent".into(),
871 help: Some("consider using a raw pointer instead".into()),
0531ce1d
XL
872 },
873
dfeec247 874 ty::Dynamic(..) => {
f035d41b 875 FfiUnsafe { ty, reason: "trait objects have no C equivalent".into(), help: None }
dfeec247 876 }
0531ce1d 877
b7449926 878 ty::Str => FfiUnsafe {
e1599b0c 879 ty,
f035d41b
XL
880 reason: "string slices have no C equivalent".into(),
881 help: Some("consider using `*const u8` and a length instead".into()),
0531ce1d
XL
882 },
883
b7449926 884 ty::Tuple(..) => FfiUnsafe {
e1599b0c 885 ty,
f035d41b
XL
886 reason: "tuples have unspecified layout".into(),
887 help: Some("consider using a struct instead".into()),
0531ce1d 888 },
b039eaaf 889
f035d41b
XL
890 ty::RawPtr(ty::TypeAndMut { ty, .. }) | ty::Ref(_, ty, _)
891 if {
3dfed10e 892 matches!(self.mode, CItemKind::Definition)
f035d41b
XL
893 && ty.is_sized(self.cx.tcx.at(DUMMY_SP), self.cx.param_env)
894 } =>
895 {
896 FfiSafe
897 }
898
dfeec247
XL
899 ty::RawPtr(ty::TypeAndMut { ty, .. }) | ty::Ref(_, ty, _) => {
900 self.check_type_for_ffi(cache, ty)
901 }
b039eaaf 902
60c5eb7d 903 ty::Array(inner_ty, _) => self.check_type_for_ffi(cache, inner_ty),
b039eaaf 904
b7449926 905 ty::FnPtr(sig) => {
f035d41b
XL
906 if self.is_internal_abi(sig.abi()) {
907 return FfiUnsafe {
908 ty,
909 reason: "this function pointer has Rust-specific calling convention".into(),
910 help: Some(
911 "consider using an `extern fn(...) -> ...` \
912 function pointer instead"
913 .into(),
914 ),
915 };
b039eaaf
SL
916 }
917
3dfed10e 918 let sig = tcx.erase_late_bound_regions(&sig);
b7449926 919 if !sig.output().is_unit() {
476ff2be 920 let r = self.check_type_for_ffi(cache, sig.output());
5bcae85e
SL
921 match r {
922 FfiSafe => {}
c30ab7b3
SL
923 _ => {
924 return r;
925 }
b039eaaf
SL
926 }
927 }
476ff2be 928 for arg in sig.inputs() {
b039eaaf
SL
929 let r = self.check_type_for_ffi(cache, arg);
930 match r {
931 FfiSafe => {}
c30ab7b3
SL
932 _ => {
933 return r;
934 }
b039eaaf
SL
935 }
936 }
937 FfiSafe
938 }
939
b7449926
XL
940 ty::Foreign(..) => FfiSafe,
941
f035d41b
XL
942 // While opaque types are checked for earlier, if a projection in a struct field
943 // normalizes to an opaque type, then it will reach this branch.
944 ty::Opaque(..) => {
945 FfiUnsafe { ty, reason: "opaque types have no C equivalent".into(), help: None }
946 }
947
948 // `extern "C" fn` functions can have type parameters, which may or may not be FFI-safe,
949 // so they are currently ignored for the purposes of this lint.
3dfed10e 950 ty::Param(..) | ty::Projection(..) if matches!(self.mode, CItemKind::Definition) => {
f035d41b
XL
951 FfiSafe
952 }
953
dfeec247 954 ty::Param(..)
f035d41b 955 | ty::Projection(..)
dfeec247
XL
956 | ty::Infer(..)
957 | ty::Bound(..)
f035d41b 958 | ty::Error(_)
dfeec247
XL
959 | ty::Closure(..)
960 | ty::Generator(..)
961 | ty::GeneratorWitness(..)
962 | ty::Placeholder(..)
dfeec247 963 | ty::FnDef(..) => bug!("unexpected type in foreign function: {:?}", ty),
e1599b0c
XL
964 }
965 }
966
967 fn emit_ffi_unsafe_type_lint(
968 &mut self,
969 ty: Ty<'tcx>,
970 sp: Span,
971 note: &str,
972 help: Option<&str>,
973 ) {
f035d41b 974 let lint = match self.mode {
3dfed10e
XL
975 CItemKind::Declaration => IMPROPER_CTYPES,
976 CItemKind::Definition => IMPROPER_CTYPES_DEFINITIONS,
f035d41b
XL
977 };
978
979 self.cx.struct_span_lint(lint, sp, |lint| {
980 let item_description = match self.mode {
3dfed10e
XL
981 CItemKind::Declaration => "block",
982 CItemKind::Definition => "fn",
f035d41b
XL
983 };
984 let mut diag = lint.build(&format!(
985 "`extern` {} uses type `{}`, which is not FFI-safe",
986 item_description, ty
987 ));
74b04a01
XL
988 diag.span_label(sp, "not FFI-safe");
989 if let Some(help) = help {
990 diag.help(help);
e1599b0c 991 }
74b04a01
XL
992 diag.note(note);
993 if let ty::Adt(def, _) = ty.kind {
994 if let Some(sp) = self.cx.tcx.hir().span_if_local(def.did) {
995 diag.span_note(sp, "the type is defined here");
996 }
997 }
998 diag.emit();
999 });
e1599b0c
XL
1000 }
1001
1002 fn check_for_opaque_ty(&mut self, sp: Span, ty: Ty<'tcx>) -> bool {
f035d41b
XL
1003 struct ProhibitOpaqueTypes<'a, 'tcx> {
1004 cx: &'a LateContext<'tcx>,
e1599b0c
XL
1005 ty: Option<Ty<'tcx>>,
1006 };
1007
f035d41b 1008 impl<'a, 'tcx> ty::fold::TypeVisitor<'tcx> for ProhibitOpaqueTypes<'a, 'tcx> {
e1599b0c 1009 fn visit_ty(&mut self, ty: Ty<'tcx>) -> bool {
f035d41b
XL
1010 match ty.kind {
1011 ty::Opaque(..) => {
1012 self.ty = Some(ty);
1013 true
1014 }
1015 // Consider opaque types within projections FFI-safe if they do not normalize
1016 // to more opaque types.
1017 ty::Projection(..) => {
1018 let ty = self.cx.tcx.normalize_erasing_regions(self.cx.param_env, ty);
1019
1020 // If `ty` is a opaque type directly then `super_visit_with` won't invoke
1021 // this function again.
1022 if ty.has_opaque_types() { self.visit_ty(ty) } else { false }
1023 }
1024 _ => ty.super_visit_with(self),
e1599b0c
XL
1025 }
1026 }
1027 }
1028
f035d41b 1029 let mut visitor = ProhibitOpaqueTypes { cx: self.cx, ty: None };
e1599b0c
XL
1030 ty.visit_with(&mut visitor);
1031 if let Some(ty) = visitor.ty {
dfeec247 1032 self.emit_ffi_unsafe_type_lint(ty, sp, "opaque types have no C equivalent", None);
e1599b0c
XL
1033 true
1034 } else {
1035 false
b039eaaf
SL
1036 }
1037 }
1038
f035d41b
XL
1039 fn check_type_for_ffi_and_report_errors(
1040 &mut self,
1041 sp: Span,
1042 ty: Ty<'tcx>,
1043 is_static: bool,
1044 is_return_type: bool,
1045 ) {
e1599b0c
XL
1046 // We have to check for opaque types before `normalize_erasing_regions`,
1047 // which will replace opaque types with their underlying concrete type.
1048 if self.check_for_opaque_ty(sp, ty) {
1049 // We've already emitted an error due to an opaque type.
1050 return;
1051 }
1052
54a0048b
SL
1053 // it is only OK to use this function because extern fns cannot have
1054 // any generic types right now:
f035d41b
XL
1055 let ty = self.cx.tcx.normalize_erasing_regions(self.cx.param_env, ty);
1056
1057 // C doesn't really support passing arrays by value - the only way to pass an array by value
1058 // is through a struct. So, first test that the top level isn't an array, and then
1059 // recursively check the types inside.
60c5eb7d
XL
1060 if !is_static && self.check_for_array_ty(sp, ty) {
1061 return;
1062 }
b039eaaf 1063
f035d41b
XL
1064 // Don't report FFI errors for unit return types. This check exists here, and not in
1065 // `check_foreign_fn` (where it would make more sense) so that normalization has definitely
1066 // happened.
1067 if is_return_type && ty.is_unit() {
1068 return;
1069 }
1070
0bf4aa26 1071 match self.check_type_for_ffi(&mut FxHashSet::default(), ty) {
b039eaaf 1072 FfiResult::FfiSafe => {}
0531ce1d 1073 FfiResult::FfiPhantom(ty) => {
e1599b0c 1074 self.emit_ffi_unsafe_type_lint(ty, sp, "composed only of `PhantomData`", None);
9e0c209e 1075 }
f035d41b
XL
1076 // If `ty` is a `repr(transparent)` newtype, and the non-zero-sized type is a generic
1077 // argument, which after substitution, is `()`, then this branch can be hit.
3dfed10e 1078 FfiResult::FfiUnsafe { ty, .. } if is_return_type && ty.is_unit() => {}
e1599b0c 1079 FfiResult::FfiUnsafe { ty, reason, help } => {
f035d41b 1080 self.emit_ffi_unsafe_type_lint(ty, sp, &reason, help.as_deref());
b039eaaf
SL
1081 }
1082 }
1083 }
b039eaaf 1084
dfeec247 1085 fn check_foreign_fn(&mut self, id: hir::HirId, decl: &hir::FnDecl<'_>) {
416331ca 1086 let def_id = self.cx.tcx.hir().local_def_id(id);
041b39d2 1087 let sig = self.cx.tcx.fn_sig(def_id);
54a0048b
SL
1088 let sig = self.cx.tcx.erase_late_bound_regions(&sig);
1089
dfeec247 1090 for (input_ty, input_hir) in sig.inputs().iter().zip(decl.inputs) {
f035d41b 1091 self.check_type_for_ffi_and_report_errors(input_hir.span, input_ty, false, false);
54a0048b
SL
1092 }
1093
74b04a01 1094 if let hir::FnRetTy::Return(ref ret_hir) = decl.output {
476ff2be 1095 let ret_ty = sig.output();
f035d41b 1096 self.check_type_for_ffi_and_report_errors(ret_hir.span, ret_ty, false, true);
b039eaaf
SL
1097 }
1098 }
54a0048b 1099
532ac7d7 1100 fn check_foreign_static(&mut self, id: hir::HirId, span: Span) {
416331ca 1101 let def_id = self.cx.tcx.hir().local_def_id(id);
7cac9316 1102 let ty = self.cx.tcx.type_of(def_id);
f035d41b 1103 self.check_type_for_ffi_and_report_errors(span, ty, true, false);
54a0048b 1104 }
b039eaaf 1105
3dfed10e
XL
1106 fn is_internal_abi(&self, abi: SpecAbi) -> bool {
1107 if let SpecAbi::Rust
1108 | SpecAbi::RustCall
1109 | SpecAbi::RustIntrinsic
1110 | SpecAbi::PlatformIntrinsic = abi
1111 {
f035d41b 1112 true
e1599b0c 1113 } else {
f035d41b
XL
1114 false
1115 }
1116 }
1117}
1118
1119impl<'tcx> LateLintPass<'tcx> for ImproperCTypesDeclarations {
1120 fn check_foreign_item(&mut self, cx: &LateContext<'_>, it: &hir::ForeignItem<'_>) {
3dfed10e 1121 let mut vis = ImproperCTypesVisitor { cx, mode: CItemKind::Declaration };
f035d41b
XL
1122 let abi = cx.tcx.hir().get_foreign_abi(it.hir_id);
1123
1124 if !vis.is_internal_abi(abi) {
e74abb32 1125 match it.kind {
b7449926 1126 hir::ForeignItemKind::Fn(ref decl, _, _) => {
532ac7d7 1127 vis.check_foreign_fn(it.hir_id, decl);
b7449926
XL
1128 }
1129 hir::ForeignItemKind::Static(ref ty, _) => {
532ac7d7 1130 vis.check_foreign_static(it.hir_id, ty.span);
b039eaaf 1131 }
dfeec247 1132 hir::ForeignItemKind::Type => (),
b039eaaf 1133 }
b039eaaf
SL
1134 }
1135 }
1136}
5bcae85e 1137
f035d41b
XL
1138impl<'tcx> LateLintPass<'tcx> for ImproperCTypesDefinitions {
1139 fn check_fn(
1140 &mut self,
1141 cx: &LateContext<'tcx>,
1142 kind: hir::intravisit::FnKind<'tcx>,
1143 decl: &'tcx hir::FnDecl<'_>,
1144 _: &'tcx hir::Body<'_>,
1145 _: Span,
1146 hir_id: hir::HirId,
1147 ) {
1148 use hir::intravisit::FnKind;
1149
1150 let abi = match kind {
1151 FnKind::ItemFn(_, _, header, ..) => header.abi,
1152 FnKind::Method(_, sig, ..) => sig.header.abi,
1153 _ => return,
1154 };
1155
3dfed10e 1156 let mut vis = ImproperCTypesVisitor { cx, mode: CItemKind::Definition };
f035d41b
XL
1157 if !vis.is_internal_abi(abi) {
1158 vis.check_foreign_fn(hir_id, decl);
1159 }
1160 }
1161}
1162
532ac7d7 1163declare_lint_pass!(VariantSizeDifferences => [VARIANT_SIZE_DIFFERENCES]);
5bcae85e 1164
f035d41b
XL
1165impl<'tcx> LateLintPass<'tcx> for VariantSizeDifferences {
1166 fn check_item(&mut self, cx: &LateContext<'_>, it: &hir::Item<'_>) {
e74abb32 1167 if let hir::ItemKind::Enum(ref enum_definition, _) = it.kind {
416331ca 1168 let item_def_id = cx.tcx.hir().local_def_id(it.hir_id);
8faf50e0
XL
1169 let t = cx.tcx.type_of(item_def_id);
1170 let ty = cx.tcx.erase_regions(&t);
532ac7d7
XL
1171 let layout = match cx.layout_of(ty) {
1172 Ok(layout) => layout,
ba9703b0
XL
1173 Err(
1174 ty::layout::LayoutError::Unknown(_) | ty::layout::LayoutError::SizeOverflow(_),
1175 ) => return,
532ac7d7
XL
1176 };
1177 let (variants, tag) = match layout.variants {
ba9703b0 1178 Variants::Multiple {
f035d41b
XL
1179 tag_encoding: TagEncoding::Direct,
1180 ref tag,
532ac7d7 1181 ref variants,
48663c56 1182 ..
f035d41b 1183 } => (variants, tag),
532ac7d7
XL
1184 _ => return,
1185 };
1186
f035d41b 1187 let tag_size = tag.value.size(&cx.tcx).bytes();
532ac7d7 1188
dfeec247
XL
1189 debug!(
1190 "enum `{}` is {} bytes large with layout:\n{:#?}",
1191 t,
1192 layout.size.bytes(),
1193 layout
1194 );
532ac7d7 1195
dfeec247
XL
1196 let (largest, slargest, largest_index) = enum_definition
1197 .variants
532ac7d7
XL
1198 .iter()
1199 .zip(variants)
1200 .map(|(variant, variant_layout)| {
f035d41b
XL
1201 // Subtract the size of the enum tag.
1202 let bytes = variant_layout.size.bytes().saturating_sub(tag_size);
532ac7d7 1203
dfeec247 1204 debug!("- variant `{}` is {} bytes large", variant.ident, bytes);
532ac7d7
XL
1205 bytes
1206 })
1207 .enumerate()
dfeec247
XL
1208 .fold((0, 0, 0), |(l, s, li), (idx, size)| {
1209 if size > l {
1210 (size, l, idx)
1211 } else if size > s {
1212 (l, size, li)
1213 } else {
1214 (l, s, li)
1215 }
532ac7d7
XL
1216 });
1217
1218 // We only warn if the largest variant is at least thrice as large as
1219 // the second-largest.
1220 if largest > slargest * 3 && slargest > 0 {
74b04a01 1221 cx.struct_span_lint(
dfeec247
XL
1222 VARIANT_SIZE_DIFFERENCES,
1223 enum_definition.variants[largest_index].span,
74b04a01
XL
1224 |lint| {
1225 lint.build(&format!(
1226 "enum variant is more than three times \
532ac7d7 1227 larger ({} bytes) than the next largest",
74b04a01
XL
1228 largest
1229 ))
1230 .emit()
1231 },
dfeec247 1232 );
5bcae85e
SL
1233 }
1234 }
1235 }
1236}