1use std::iter;
2
3use rustc_abi::{BackendRepr, TagEncoding, Variants, WrappingRange};
4use rustc_ast as ast;
5use rustc_hir as hir;
6use rustc_hir::attrs::lang_items::LangItem;
7use rustc_hir::{Expr, ExprKind, HirId, find_attr};
8use rustc_middle::bug;
9use rustc_middle::ty::layout::{LayoutOf, SizeSkeleton};
10use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitableExt, Unnormalized};
11use rustc_session::{declare_lint, declare_lint_pass, impl_lint_pass};
12use rustc_span::{DUMMY_SP, Span, Symbol, sym};
13use tracing::debug;
14
15mod improper_ctypes; pub(crate) use improper_ctypes::ImproperCTypesLint;
17
18use crate::diagnostics::{
19 AmbiguousWidePointerComparisons, AmbiguousWidePointerComparisonsAddrMetadataSuggestion,
20 AmbiguousWidePointerComparisonsAddrSuggestion, AmbiguousWidePointerComparisonsCastSuggestion,
21 AmbiguousWidePointerComparisonsExpectSuggestion, AtomicOrderingFence, AtomicOrderingLoad,
22 AtomicOrderingStore, InvalidAtomicOrderingDiag, InvalidNanComparisons,
23 InvalidNanComparisonsSuggestion, UnpredictableFunctionPointerComparisons,
24 UnpredictableFunctionPointerComparisonsSuggestion, UnusedComparisons,
25 VariantSizeDifferencesDiag,
26};
27use crate::{LateContext, LateLintPass, LintContext};
28
29mod literal;
30use literal::{int_ty_range, lint_literal, uint_ty_range};
31
32#[doc = r" The `unused_comparisons` lint detects comparisons made useless by"]
#[doc = r" limits of the types involved."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust"]
#[doc = r" fn foo(x: u8) {"]
#[doc = r" x >= 0;"]
#[doc = r" }"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc =
r" A useless comparison may indicate a mistake, and should be fixed or"]
#[doc = r" removed."]
static UNUSED_COMPARISONS: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: "UNUSED_COMPARISONS",
default_level: ::rustc_lint_defs::Warn,
desc: "comparisons made useless by limits of the types involved",
is_externally_loaded: false,
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_lint! {
33 UNUSED_COMPARISONS,
51 Warn,
52 "comparisons made useless by limits of the types involved"
53}
54
55#[doc =
r" The `overflowing_literals` lint detects literals out of range for their type."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust,compile_fail"]
#[doc = r" let x: u8 = 1000;"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc = r" It is usually a mistake to use a literal that overflows its type"]
#[doc = r" Change either the literal or its type such that the literal is"]
#[doc = r" within the range of its type."]
static OVERFLOWING_LITERALS: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: "OVERFLOWING_LITERALS",
default_level: ::rustc_lint_defs::Deny,
desc: "literal out of range for its type",
is_externally_loaded: false,
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_lint! {
56 OVERFLOWING_LITERALS,
72 Deny,
73 "literal out of range for its type"
74}
75
76#[doc =
r" The `variant_size_differences` lint detects enums with widely varying"]
#[doc = r" variant sizes."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust,compile_fail"]
#[doc = r" #![deny(variant_size_differences)]"]
#[doc = r" enum En {"]
#[doc = r" V0(u8),"]
#[doc = r" VBig([u8; 1024]),"]
#[doc = r" }"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc =
r" It can be a mistake to add a variant to an enum that is much larger"]
#[doc =
r" than the other variants, bloating the overall size required for all"]
#[doc = r" variants. This can impact performance and memory usage. This is"]
#[doc = r" triggered if one variant is more than 3 times larger than the"]
#[doc = r" second-largest variant."]
#[doc = r""]
#[doc =
r" Consider placing the large variant's contents on the heap (for example"]
#[doc = r" via [`Box`]) to keep the overall size of the enum itself down."]
#[doc = r""]
#[doc =
r#" This lint is "allow" by default because it can be noisy, and may not be"#]
#[doc = r" an actual problem. Decisions about this should be guided with"]
#[doc = r" profiling and benchmarking."]
#[doc = r""]
#[doc = r" [`Box`]: https://doc.rust-lang.org/std/boxed/index.html"]
static VARIANT_SIZE_DIFFERENCES: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: "VARIANT_SIZE_DIFFERENCES",
default_level: ::rustc_lint_defs::Allow,
desc: "detects enums with widely varying variant sizes",
is_externally_loaded: false,
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_lint! {
77 VARIANT_SIZE_DIFFERENCES,
109 Allow,
110 "detects enums with widely varying variant sizes"
111}
112
113#[doc =
r" The `invalid_nan_comparisons` lint checks comparison with `f32::NAN` or `f64::NAN`"]
#[doc = r" as one of the operand."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust"]
#[doc = r" let a = 2.3f32;"]
#[doc = r" if a == f32::NAN {}"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc = r" NaN does not compare meaningfully to anything – not"]
#[doc = r" even itself – so those comparisons are always false."]
static INVALID_NAN_COMPARISONS: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: "INVALID_NAN_COMPARISONS",
default_level: ::rustc_lint_defs::Warn,
desc: "detects invalid floating point NaN comparisons",
is_externally_loaded: false,
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_lint! {
114 INVALID_NAN_COMPARISONS,
131 Warn,
132 "detects invalid floating point NaN comparisons"
133}
134
135#[doc = r" The `ambiguous_wide_pointer_comparisons` lint checks comparison"]
#[doc = r" of `*const/*mut ?Sized` as the operands."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust"]
#[doc = r" # struct A;"]
#[doc = r" # struct B;"]
#[doc = r""]
#[doc = r" # trait T {}"]
#[doc = r" # impl T for A {}"]
#[doc = r" # impl T for B {}"]
#[doc = r""]
#[doc = r" let ab = (A, B);"]
#[doc = r" let a = &ab.0 as *const dyn T;"]
#[doc = r" let b = &ab.1 as *const dyn T;"]
#[doc = r""]
#[doc = r" let _ = a == b;"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc = r" The comparison includes metadata which may not be expected."]
static AMBIGUOUS_WIDE_POINTER_COMPARISONS: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: "AMBIGUOUS_WIDE_POINTER_COMPARISONS",
default_level: ::rustc_lint_defs::Warn,
desc: "detects ambiguous wide pointer comparisons",
is_externally_loaded: false,
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_lint! {
136 AMBIGUOUS_WIDE_POINTER_COMPARISONS,
162 Warn,
163 "detects ambiguous wide pointer comparisons"
164}
165
166#[doc =
r" The `unpredictable_function_pointer_comparisons` lint checks comparison"]
#[doc = r" of function pointer as the operands."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust"]
#[doc = r" fn a() {}"]
#[doc = r" fn b() {}"]
#[doc = r""]
#[doc = r" let f: fn() = a;"]
#[doc = r" let g: fn() = b;"]
#[doc = r""]
#[doc = r" let _ = f == g;"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc =
r" Function pointers comparisons do not produce meaningful result since"]
#[doc =
r" they are never guaranteed to be unique and could vary between different"]
#[doc =
r" code generation units. Furthermore, different functions could have the"]
#[doc = r" same address after being merged together."]
static UNPREDICTABLE_FUNCTION_POINTER_COMPARISONS: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: "UNPREDICTABLE_FUNCTION_POINTER_COMPARISONS",
default_level: ::rustc_lint_defs::Warn,
desc: "detects unpredictable function pointer comparisons",
is_externally_loaded: false,
report_in_external_macro: true,
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_lint! {
167 UNPREDICTABLE_FUNCTION_POINTER_COMPARISONS,
191 Warn,
192 "detects unpredictable function pointer comparisons",
193 report_in_external_macro
194}
195
196#[derive(#[automatically_derived]
impl ::core::marker::Copy for TypeLimits { }Copy, #[automatically_derived]
impl ::core::clone::Clone for TypeLimits {
#[inline]
fn clone(&self) -> TypeLimits {
let _: ::core::clone::AssertParamIsClone<Option<NegationInfo>>;
*self
}
}Clone, #[automatically_derived]
impl ::core::default::Default for TypeLimits {
#[inline]
fn default() -> TypeLimits {
TypeLimits {
last_visited_negation: ::core::default::Default::default(),
}
}
}Default)]
197pub(crate) struct TypeLimits {
198 last_visited_negation: Option<NegationInfo>,
199}
200
201#[derive(#[automatically_derived]
impl ::core::marker::Copy for NegationInfo { }Copy, #[automatically_derived]
impl ::core::clone::Clone for NegationInfo {
#[inline]
fn clone(&self) -> NegationInfo {
let _: ::core::clone::AssertParamIsClone<Span>;
let _: ::core::clone::AssertParamIsClone<hir::HirId>;
*self
}
}Clone)]
202struct NegationInfo {
203 negation_span: Span,
205 negated_id: hir::HirId,
207}
208
209impl ::rustc_lint_defs::LintPass for TypeLimits {
fn name(&self) -> &'static str { "TypeLimits" }
fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[UNUSED_COMPARISONS, OVERFLOWING_LITERALS,
INVALID_NAN_COMPARISONS, AMBIGUOUS_WIDE_POINTER_COMPARISONS,
UNPREDICTABLE_FUNCTION_POINTER_COMPARISONS]))
}
}
impl TypeLimits {
#[allow(unused)]
pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[UNUSED_COMPARISONS, OVERFLOWING_LITERALS,
INVALID_NAN_COMPARISONS, AMBIGUOUS_WIDE_POINTER_COMPARISONS,
UNPREDICTABLE_FUNCTION_POINTER_COMPARISONS]))
}
}impl_lint_pass!(TypeLimits => [
210 UNUSED_COMPARISONS,
211 OVERFLOWING_LITERALS,
212 INVALID_NAN_COMPARISONS,
213 AMBIGUOUS_WIDE_POINTER_COMPARISONS,
214 UNPREDICTABLE_FUNCTION_POINTER_COMPARISONS
215]);
216
217impl TypeLimits {
218 pub(crate) fn new() -> TypeLimits {
219 TypeLimits { last_visited_negation: None }
220 }
221}
222
223fn lint_nan<'tcx>(
224 cx: &LateContext<'tcx>,
225 e: &'tcx hir::Expr<'tcx>,
226 binop: hir::BinOpKind,
227 l: &'tcx hir::Expr<'tcx>,
228 r: &'tcx hir::Expr<'tcx>,
229) {
230 fn is_nan(cx: &LateContext<'_>, expr: &hir::Expr<'_>) -> bool {
231 let expr = expr.peel_blocks().peel_borrows();
232 match expr.kind {
233 ExprKind::Path(qpath) => {
234 let Some(def_id) = cx.typeck_results().qpath_res(&qpath, expr.hir_id).opt_def_id()
235 else {
236 return false;
237 };
238
239 #[allow(non_exhaustive_omitted_patterns)] match cx.tcx.get_diagnostic_name(def_id)
{
Some(sym::f16_nan | sym::f32_nan | sym::f64_nan | sym::f128_nan) => true,
_ => false,
}matches!(
240 cx.tcx.get_diagnostic_name(def_id),
241 Some(sym::f16_nan | sym::f32_nan | sym::f64_nan | sym::f128_nan)
242 )
243 }
244 _ => false,
245 }
246 }
247
248 fn eq_ne(
249 e: &hir::Expr<'_>,
250 l: &hir::Expr<'_>,
251 r: &hir::Expr<'_>,
252 f: impl FnOnce(Span, Span) -> InvalidNanComparisonsSuggestion,
253 ) -> InvalidNanComparisons {
254 let suggestion = if let Some(l_span) = l.span.find_ancestor_inside(e.span)
255 && let Some(r_span) = r.span.find_ancestor_inside(e.span)
256 {
257 f(l_span, r_span)
258 } else {
259 InvalidNanComparisonsSuggestion::Spanless
260 };
261
262 InvalidNanComparisons::EqNe { suggestion }
263 }
264
265 let lint = match binop {
266 hir::BinOpKind::Eq | hir::BinOpKind::Ne if is_nan(cx, l) => {
267 eq_ne(e, l, r, |l_span, r_span| InvalidNanComparisonsSuggestion::Spanful {
268 nan_plus_binop: l_span.until(r_span),
269 float: r_span.shrink_to_hi(),
270 neg: (binop == hir::BinOpKind::Ne).then(|| r_span.shrink_to_lo()),
271 })
272 }
273 hir::BinOpKind::Eq | hir::BinOpKind::Ne if is_nan(cx, r) => {
274 eq_ne(e, l, r, |l_span, r_span| InvalidNanComparisonsSuggestion::Spanful {
275 nan_plus_binop: l_span.shrink_to_hi().to(r_span),
276 float: l_span.shrink_to_hi(),
277 neg: (binop == hir::BinOpKind::Ne).then(|| l_span.shrink_to_lo()),
278 })
279 }
280 hir::BinOpKind::Lt | hir::BinOpKind::Le | hir::BinOpKind::Gt | hir::BinOpKind::Ge
281 if is_nan(cx, l) || is_nan(cx, r) =>
282 {
283 InvalidNanComparisons::LtLeGtGe
284 }
285 _ => return,
286 };
287
288 cx.emit_span_lint(INVALID_NAN_COMPARISONS, e.span, lint);
289}
290
291#[derive(#[automatically_derived]
impl ::core::fmt::Debug for ComparisonOp {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
ComparisonOp::BinOp(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "BinOp",
&__self_0),
ComparisonOp::Other =>
::core::fmt::Formatter::write_str(f, "Other"),
}
}
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for ComparisonOp {
#[inline]
fn eq(&self, other: &ComparisonOp) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr &&
match (self, other) {
(ComparisonOp::BinOp(__self_0), ComparisonOp::BinOp(__arg1_0))
=> __self_0 == __arg1_0,
_ => true,
}
}
}PartialEq, #[automatically_derived]
impl ::core::marker::Copy for ComparisonOp { }Copy, #[automatically_derived]
impl ::core::clone::Clone for ComparisonOp {
#[inline]
fn clone(&self) -> ComparisonOp {
let _: ::core::clone::AssertParamIsClone<hir::BinOpKind>;
*self
}
}Clone)]
292enum ComparisonOp {
293 BinOp(hir::BinOpKind),
294 Other,
295}
296
297fn lint_wide_pointer<'tcx>(
298 cx: &LateContext<'tcx>,
299 e: &'tcx hir::Expr<'tcx>,
300 cmpop: ComparisonOp,
301 l: &'tcx hir::Expr<'tcx>,
302 r: &'tcx hir::Expr<'tcx>,
303) {
304 let ptr_unsized = |mut ty: Ty<'tcx>| -> Option<(
305 usize,
306 String,
307 bool,
308 )> {
309 let mut refs = 0;
310 while let ty::Ref(_, inner_ty, _) = ty.kind() {
313 ty = *inner_ty;
314 refs += 1;
315 }
316
317 let mut modifiers = String::new();
319 ty = match ty.kind() {
320 ty::RawPtr(ty, _) => *ty,
321 ty::Adt(def, args) if cx.tcx.is_diagnostic_item(sym::NonNull, def.did()) => {
322 modifiers.push_str(".as_ptr()");
323 args.type_at(0)
324 }
325 _ => return None,
326 };
327
328 (!ty.is_sized(cx.tcx, cx.typing_env()))
329 .then(|| (refs, modifiers, #[allow(non_exhaustive_omitted_patterns)] match ty.kind() {
ty::Dynamic(_, _) => true,
_ => false,
}matches!(ty.kind(), ty::Dynamic(_, _))))
330 };
331
332 let l = l.peel_borrows();
334 let r = r.peel_borrows();
335
336 let Some(l_ty) = cx.typeck_results().expr_ty_opt(l) else {
337 return;
338 };
339 let Some(r_ty) = cx.typeck_results().expr_ty_opt(r) else {
340 return;
341 };
342
343 let Some((l_ty_refs, l_modifiers, l_inner_ty_is_dyn)) = ptr_unsized(l_ty) else {
344 return;
345 };
346 let Some((r_ty_refs, r_modifiers, r_inner_ty_is_dyn)) = ptr_unsized(r_ty) else {
347 return;
348 };
349
350 let (Some(l_span), Some(r_span)) =
351 (l.span.find_ancestor_inside(e.span), r.span.find_ancestor_inside(e.span))
352 else {
353 return cx.emit_span_lint(
354 AMBIGUOUS_WIDE_POINTER_COMPARISONS,
355 e.span,
356 AmbiguousWidePointerComparisons::Spanless,
357 );
358 };
359
360 let ne = if cmpop == ComparisonOp::BinOp(hir::BinOpKind::Ne) { "!" } else { "" };
361 let is_eq_ne = #[allow(non_exhaustive_omitted_patterns)] match cmpop {
ComparisonOp::BinOp(hir::BinOpKind::Eq | hir::BinOpKind::Ne) => true,
_ => false,
}matches!(cmpop, ComparisonOp::BinOp(hir::BinOpKind::Eq | hir::BinOpKind::Ne));
362 let is_dyn_comparison = l_inner_ty_is_dyn && r_inner_ty_is_dyn;
363 let via_method_call = #[allow(non_exhaustive_omitted_patterns)] match &e.kind {
ExprKind::MethodCall(..) | ExprKind::Call(..) => true,
_ => false,
}matches!(&e.kind, ExprKind::MethodCall(..) | ExprKind::Call(..));
364
365 let left = e.span.shrink_to_lo().until(l_span.shrink_to_lo());
366 let middle = l_span.shrink_to_hi().until(r_span.shrink_to_lo());
367 let right = r_span.shrink_to_hi().until(e.span.shrink_to_hi());
368
369 let deref_left = &*"*".repeat(l_ty_refs);
370 let deref_right = &*"*".repeat(r_ty_refs);
371
372 let l_modifiers = &*l_modifiers;
373 let r_modifiers = &*r_modifiers;
374
375 cx.emit_span_lint(
376 AMBIGUOUS_WIDE_POINTER_COMPARISONS,
377 e.span,
378 if is_eq_ne {
379 AmbiguousWidePointerComparisons::SpanfulEq {
380 addr_metadata_suggestion: (!is_dyn_comparison).then(|| {
381 AmbiguousWidePointerComparisonsAddrMetadataSuggestion {
382 ne,
383 deref_left,
384 deref_right,
385 l_modifiers,
386 r_modifiers,
387 left,
388 middle,
389 right,
390 }
391 }),
392 addr_suggestion: AmbiguousWidePointerComparisonsAddrSuggestion {
393 ne,
394 deref_left,
395 deref_right,
396 l_modifiers,
397 r_modifiers,
398 left,
399 middle,
400 right,
401 },
402 }
403 } else {
404 AmbiguousWidePointerComparisons::SpanfulCmp {
405 cast_suggestion: AmbiguousWidePointerComparisonsCastSuggestion {
406 deref_left,
407 deref_right,
408 l_modifiers,
409 r_modifiers,
410 paren_left: if l_ty_refs != 0 { ")" } else { "" },
411 paren_right: if r_ty_refs != 0 { ")" } else { "" },
412 left_before: (l_ty_refs != 0).then_some(l_span.shrink_to_lo()),
413 left_after: l_span.shrink_to_hi(),
414 right_before: (r_ty_refs != 0).then_some(r_span.shrink_to_lo()),
415 right_after: r_span.shrink_to_hi(),
416 },
417 expect_suggestion: AmbiguousWidePointerComparisonsExpectSuggestion {
418 paren_left: if via_method_call { "" } else { "(" },
419 paren_right: if via_method_call { "" } else { ")" },
420 before: e.span.shrink_to_lo(),
421 after: e.span.shrink_to_hi(),
422 },
423 }
424 },
425 );
426}
427
428fn lint_fn_pointer<'tcx>(
429 cx: &LateContext<'tcx>,
430 e: &'tcx hir::Expr<'tcx>,
431 cmpop: ComparisonOp,
432 l: &'tcx hir::Expr<'tcx>,
433 r: &'tcx hir::Expr<'tcx>,
434) {
435 let peel_refs = |mut ty: Ty<'tcx>| -> (Ty<'tcx>, usize) {
436 let mut refs = 0;
437
438 while let ty::Ref(_, inner_ty, _) = ty.kind() {
439 ty = *inner_ty;
440 refs += 1;
441 }
442
443 (ty, refs)
444 };
445
446 let l = l.peel_borrows();
448 let r = r.peel_borrows();
449
450 let Some(l_ty) = cx.typeck_results().expr_ty_opt(l) else { return };
451 let Some(r_ty) = cx.typeck_results().expr_ty_opt(r) else { return };
452
453 let (l_ty, l_ty_refs) = peel_refs(l_ty);
456 let (r_ty, r_ty_refs) = peel_refs(r_ty);
457
458 if l_ty.is_fn() && r_ty.is_fn() {
459 } else if let ty::Adt(l_def, l_args) = l_ty.kind()
461 && let ty::Adt(r_def, r_args) = r_ty.kind()
462 && cx.tcx.is_lang_item(l_def.did(), LangItem::Option)
463 && cx.tcx.is_lang_item(r_def.did(), LangItem::Option)
464 && let Some(l_some_arg) = l_args.get(0)
465 && let Some(r_some_arg) = r_args.get(0)
466 && l_some_arg.expect_ty().is_fn()
467 && r_some_arg.expect_ty().is_fn()
468 {
469 return cx.emit_span_lint(
471 UNPREDICTABLE_FUNCTION_POINTER_COMPARISONS,
472 e.span,
473 UnpredictableFunctionPointerComparisons::Warn,
474 );
475 } else {
476 return;
478 }
479
480 let is_eq_ne = #[allow(non_exhaustive_omitted_patterns)] match cmpop {
ComparisonOp::BinOp(hir::BinOpKind::Eq | hir::BinOpKind::Ne) => true,
_ => false,
}matches!(cmpop, ComparisonOp::BinOp(hir::BinOpKind::Eq | hir::BinOpKind::Ne));
483
484 if !is_eq_ne {
485 return cx.emit_span_lint(
487 UNPREDICTABLE_FUNCTION_POINTER_COMPARISONS,
488 e.span,
489 UnpredictableFunctionPointerComparisons::Warn,
490 );
491 }
492
493 let (Some(l_span), Some(r_span)) =
494 (l.span.find_ancestor_inside(e.span), r.span.find_ancestor_inside(e.span))
495 else {
496 return cx.emit_span_lint(
498 UNPREDICTABLE_FUNCTION_POINTER_COMPARISONS,
499 e.span,
500 UnpredictableFunctionPointerComparisons::Warn,
501 );
502 };
503
504 let ne = if cmpop == ComparisonOp::BinOp(hir::BinOpKind::Ne) { "!" } else { "" };
505
506 let deref_left = &*"*".repeat(l_ty_refs);
508 let deref_right = &*"*".repeat(r_ty_refs);
509
510 let left = e.span.shrink_to_lo().until(l_span.shrink_to_lo());
511 let middle = l_span.shrink_to_hi().until(r_span.shrink_to_lo());
512 let right = r_span.shrink_to_hi().until(e.span.shrink_to_hi());
513
514 let sugg =
515 if !r_ty.is_fn_ptr() {
518 let fn_sig = r_ty.fn_sig(cx.tcx);
519
520 UnpredictableFunctionPointerComparisonsSuggestion::FnAddrEqWithCast {
521 ne,
522 fn_sig,
523 deref_left,
524 deref_right,
525 left,
526 middle,
527 right,
528 }
529 } else {
530 UnpredictableFunctionPointerComparisonsSuggestion::FnAddrEq {
531 ne,
532 deref_left,
533 deref_right,
534 left,
535 middle,
536 right,
537 }
538 };
539
540 cx.emit_span_lint(
541 UNPREDICTABLE_FUNCTION_POINTER_COMPARISONS,
542 e.span,
543 UnpredictableFunctionPointerComparisons::Suggestion { sugg },
544 );
545}
546
547impl<'tcx> LateLintPass<'tcx> for TypeLimits {
548 fn check_lit(
549 &mut self,
550 cx: &LateContext<'tcx>,
551 hir_id: HirId,
552 lit: hir::Lit,
553 is_negated_pat: bool,
554 ) {
555 let surrounding_negation = if is_negated_pat {
556 Some(lit.span)
559 } else if let Some(negation_info) = self.last_visited_negation
560 && negation_info.negated_id == hir_id
561 {
562 Some(negation_info.negation_span)
563 } else {
564 None
565 };
566 lint_literal(cx, hir_id, lit.span, &lit, surrounding_negation);
567 }
568
569 fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx hir::Expr<'tcx>) {
570 match e.kind {
571 hir::ExprKind::Unary(hir::UnOp::Neg, expr) => {
572 self.last_visited_negation =
573 Some(NegationInfo { negation_span: e.span, negated_id: expr.hir_id });
574 }
575 hir::ExprKind::Binary(binop, ref l, ref r) => {
576 if is_comparison(binop.node) {
577 if !check_limits(cx, binop.node, l, r) {
578 cx.emit_span_lint(UNUSED_COMPARISONS, e.span, UnusedComparisons);
579 } else {
580 lint_nan(cx, e, binop.node, l, r);
581 let cmpop = ComparisonOp::BinOp(binop.node);
582 lint_wide_pointer(cx, e, cmpop, l, r);
583 lint_fn_pointer(cx, e, cmpop, l, r);
584 }
585 }
586 }
587 hir::ExprKind::Call(path, [l, r])
588 if let ExprKind::Path(ref qpath) = path.kind
589 && let Some(def_id) = cx.qpath_res(qpath, path.hir_id).opt_def_id()
590 && let Some(diag_item) = cx.tcx.get_diagnostic_name(def_id)
591 && let Some(cmpop) = diag_item_cmpop(diag_item) =>
592 {
593 lint_wide_pointer(cx, e, cmpop, l, r);
594 lint_fn_pointer(cx, e, cmpop, l, r);
595 }
596 hir::ExprKind::MethodCall(_, l, [r], _)
597 if let Some(def_id) = cx.typeck_results().type_dependent_def_id(e.hir_id)
598 && let Some(diag_item) = cx.tcx.get_diagnostic_name(def_id)
599 && let Some(cmpop) = diag_item_cmpop(diag_item) =>
600 {
601 lint_wide_pointer(cx, e, cmpop, l, r);
602 lint_fn_pointer(cx, e, cmpop, l, r);
603 }
604 _ => {}
605 };
606
607 fn is_valid<T: PartialOrd>(binop: hir::BinOpKind, v: T, min: T, max: T) -> bool {
608 match binop {
609 hir::BinOpKind::Lt => v > min && v <= max,
610 hir::BinOpKind::Le => v >= min && v < max,
611 hir::BinOpKind::Gt => v >= min && v < max,
612 hir::BinOpKind::Ge => v > min && v <= max,
613 hir::BinOpKind::Eq | hir::BinOpKind::Ne => v >= min && v <= max,
614 _ => ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
615 }
616 }
617
618 fn rev_binop(binop: hir::BinOpKind) -> hir::BinOpKind {
619 match binop {
620 hir::BinOpKind::Lt => hir::BinOpKind::Gt,
621 hir::BinOpKind::Le => hir::BinOpKind::Ge,
622 hir::BinOpKind::Gt => hir::BinOpKind::Lt,
623 hir::BinOpKind::Ge => hir::BinOpKind::Le,
624 _ => binop,
625 }
626 }
627
628 fn check_limits(
629 cx: &LateContext<'_>,
630 binop: hir::BinOpKind,
631 l: &hir::Expr<'_>,
632 r: &hir::Expr<'_>,
633 ) -> bool {
634 let (lit, expr, swap) = match (&l.kind, &r.kind) {
635 (&hir::ExprKind::Lit(_), _) => (l, r, true),
636 (_, &hir::ExprKind::Lit(_)) => (r, l, false),
637 _ => return true,
638 };
639 let norm_binop = if swap { rev_binop(binop) } else { binop };
642 match *cx.typeck_results().node_type(expr.hir_id).kind() {
643 ty::Int(int_ty) => {
644 let (min, max) = int_ty_range(int_ty);
645 let lit_val: i128 = match lit.kind {
646 hir::ExprKind::Lit(li) => match li.node {
647 ast::LitKind::Int(
648 v,
649 ast::LitIntType::Signed(_) | ast::LitIntType::Unsuffixed,
650 ) => v.get() as i128,
651 _ => return true,
652 },
653 _ => ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
654 };
655 is_valid(norm_binop, lit_val, min, max)
656 }
657 ty::Uint(uint_ty) => {
658 let (min, max): (u128, u128) = uint_ty_range(uint_ty);
659 let lit_val: u128 = match lit.kind {
660 hir::ExprKind::Lit(li) => match li.node {
661 ast::LitKind::Int(v, _) => v.get(),
662 _ => return true,
663 },
664 _ => ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
665 };
666 is_valid(norm_binop, lit_val, min, max)
667 }
668 _ => true,
669 }
670 }
671
672 fn is_comparison(binop: hir::BinOpKind) -> bool {
673 #[allow(non_exhaustive_omitted_patterns)] match binop {
hir::BinOpKind::Eq | hir::BinOpKind::Lt | hir::BinOpKind::Le |
hir::BinOpKind::Ne | hir::BinOpKind::Ge | hir::BinOpKind::Gt => true,
_ => false,
}matches!(
674 binop,
675 hir::BinOpKind::Eq
676 | hir::BinOpKind::Lt
677 | hir::BinOpKind::Le
678 | hir::BinOpKind::Ne
679 | hir::BinOpKind::Ge
680 | hir::BinOpKind::Gt
681 )
682 }
683
684 fn diag_item_cmpop(diag_item: Symbol) -> Option<ComparisonOp> {
685 Some(match diag_item {
686 sym::cmp_ord_max => ComparisonOp::Other,
687 sym::cmp_ord_min => ComparisonOp::Other,
688 sym::ord_cmp_method => ComparisonOp::Other,
689 sym::cmp_partialeq_eq => ComparisonOp::BinOp(hir::BinOpKind::Eq),
690 sym::cmp_partialeq_ne => ComparisonOp::BinOp(hir::BinOpKind::Ne),
691 sym::cmp_partialord_cmp => ComparisonOp::Other,
692 sym::cmp_partialord_ge => ComparisonOp::BinOp(hir::BinOpKind::Ge),
693 sym::cmp_partialord_gt => ComparisonOp::BinOp(hir::BinOpKind::Gt),
694 sym::cmp_partialord_le => ComparisonOp::BinOp(hir::BinOpKind::Le),
695 sym::cmp_partialord_lt => ComparisonOp::BinOp(hir::BinOpKind::Lt),
696 _ => return None,
697 })
698 }
699 }
700}
701
702pub(crate) fn nonnull_optimization_guaranteed<'tcx>(
703 tcx: TyCtxt<'tcx>,
704 def: ty::AdtDef<'tcx>,
705) -> bool {
706 {
{
'done:
{
for i in ::rustc_attr_ir::HasAttrs::get_attrs(def.did(), &tcx)
{
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(RustcNonnullOptimizationGuaranteed)
=> {
break 'done Some(());
}
::rustc_attr_ir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}.is_some()find_attr!(tcx, def.did(), RustcNonnullOptimizationGuaranteed)
707}
708
709pub(crate) fn transparent_newtype_field<'a, 'tcx>(
712 tcx: TyCtxt<'tcx>,
713 variant: &'a ty::VariantDef,
714) -> Option<&'a ty::FieldDef> {
715 let typing_env = ty::TypingEnv::non_body_analysis(tcx, variant.def_id);
716 variant.fields.iter().find(|field| {
717 let field_ty = tcx.type_of(field.did).instantiate_identity().skip_norm_wip();
718 let is_1zst =
719 tcx.layout_of(typing_env.as_query_input(field_ty)).is_ok_and(|layout| layout.is_1zst());
720 !is_1zst
721 })
722}
723
724fn ty_is_known_nonnull<'tcx>(
726 tcx: TyCtxt<'tcx>,
727 typing_env: ty::TypingEnv<'tcx>,
728 ty: Ty<'tcx>,
729) -> bool {
730 let ty = tcx.try_normalize_erasing_regions(typing_env, Unnormalized::new_wip(ty)).unwrap_or(ty);
731
732 match ty.kind() {
733 ty::FnPtr(..) => true,
734 ty::Ref(..) => true,
735 ty::Adt(def, _) if def.is_box() => true,
736 ty::Adt(def, args) if def.repr().transparent() && !def.is_union() => {
737 let marked_non_null = nonnull_optimization_guaranteed(tcx, *def);
738
739 if marked_non_null {
740 return true;
741 }
742
743 if def.is_unsafe_cell() || def.is_unsafe_pinned() {
745 return false;
746 }
747
748 def.variants().iter().filter_map(|variant| transparent_newtype_field(tcx, variant)).any(
749 |field| ty_is_known_nonnull(tcx, typing_env, field.ty(tcx, args).skip_norm_wip()),
750 )
751 }
752 ty::Pat(base, pat) => {
753 ty_is_known_nonnull(tcx, typing_env, *base)
754 || pat_ty_is_known_nonnull(tcx, typing_env, *pat)
755 }
756 _ => false,
757 }
758}
759
760fn pat_ty_is_known_nonnull<'tcx>(
761 tcx: TyCtxt<'tcx>,
762 typing_env: ty::TypingEnv<'tcx>,
763 pat: ty::Pattern<'tcx>,
764) -> bool {
765 try {
766 match *pat {
767 ty::PatternKind::Range { start, end } => {
768 let start = start.try_to_value()?.try_to_bits(tcx, typing_env)?;
769 let end = end.try_to_value()?.try_to_bits(tcx, typing_env)?;
770
771 start > 0 && end >= start
774 }
775 ty::PatternKind::NotNull => true,
776 ty::PatternKind::Or(patterns) => {
777 patterns.iter().all(|pat| pat_ty_is_known_nonnull(tcx, typing_env, pat))
778 }
779 }
780 }
781 .unwrap_or_default()
782}
783
784fn get_nullable_type<'tcx>(
787 tcx: TyCtxt<'tcx>,
788 typing_env: ty::TypingEnv<'tcx>,
789 ty: Ty<'tcx>,
790) -> Option<Ty<'tcx>> {
791 let ty = tcx.try_normalize_erasing_regions(typing_env, Unnormalized::new_wip(ty)).unwrap_or(ty);
792
793 Some(match *ty.kind() {
794 ty::Adt(field_def, field_args) => {
795 let inner_field_ty = {
796 let mut first_non_zst_ty =
797 field_def.variants().iter().filter_map(|v| transparent_newtype_field(tcx, v));
798 if true {
{
match (&first_non_zst_ty.clone().count(), &1) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val,
::core::option::Option::Some(format_args!("Wrong number of fields for transparent type")));
}
}
}
};
};debug_assert_eq!(
799 first_non_zst_ty.clone().count(),
800 1,
801 "Wrong number of fields for transparent type"
802 );
803 first_non_zst_ty
804 .next_back()
805 .expect("No non-zst fields in transparent type.")
806 .ty(tcx, field_args)
807 .skip_norm_wip()
808 };
809 return get_nullable_type(tcx, typing_env, inner_field_ty);
810 }
811 ty::Pat(base, ..) => return get_nullable_type(tcx, typing_env, base),
812 ty::Int(_) | ty::Uint(_) | ty::Char | ty::RawPtr(..) => ty,
813 ty::Ref(_region, ty, mutbl) => Ty::new_ptr(tcx, ty, mutbl),
816 ty::FnPtr(..) => ty,
819 ref unhandled => {
822 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_lint/src/types.rs:822",
"rustc_lint::types", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_lint/src/types.rs"),
::tracing_core::__macro_support::Option::Some(822u32),
::tracing_core::__macro_support::Option::Some("rustc_lint::types"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("get_nullable_type: Unhandled scalar kind: {0:?} while checking {1:?}",
unhandled, ty) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(
823 "get_nullable_type: Unhandled scalar kind: {:?} while checking {:?}",
824 unhandled, ty
825 );
826 return None;
827 }
828 })
829}
830
831fn is_niche_optimization_candidate<'tcx>(
836 tcx: TyCtxt<'tcx>,
837 typing_env: ty::TypingEnv<'tcx>,
838 ty: Ty<'tcx>,
839) -> bool {
840 if tcx.layout_of(typing_env.as_query_input(ty)).is_ok_and(|layout| !layout.is_1zst()) {
841 return false;
842 }
843
844 match ty.kind() {
845 ty::Adt(ty_def, _) => {
846 let non_exhaustive = ty_def.is_variant_list_non_exhaustive();
847 let empty = (ty_def.is_struct() && ty_def.non_enum_variant().fields.is_empty())
848 || (ty_def.is_enum() && ty_def.variants().is_empty());
849
850 !non_exhaustive && empty
851 }
852 ty::Tuple(tys) => tys.is_empty(),
853 _ => false,
854 }
855}
856
857pub(crate) fn repr_nullable_ptr<'tcx>(
862 tcx: TyCtxt<'tcx>,
863 typing_env: ty::TypingEnv<'tcx>,
864 ty: Ty<'tcx>,
865) -> Option<Ty<'tcx>> {
866 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_lint/src/types.rs:866",
"rustc_lint::types", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_lint/src/types.rs"),
::tracing_core::__macro_support::Option::Some(866u32),
::tracing_core::__macro_support::Option::Some("rustc_lint::types"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("is_repr_nullable_ptr(tcx, ty = {0:?})",
ty) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("is_repr_nullable_ptr(tcx, ty = {:?})", ty);
867 match ty.kind() {
868 ty::Adt(ty_def, args) => {
869 let field_ty = match &ty_def.variants().raw[..] {
870 [var_one, var_two] => match (&var_one.fields.raw[..], &var_two.fields.raw[..]) {
871 ([], [field]) | ([field], []) => field.ty(tcx, args).skip_norm_wip(),
872 ([field1], [field2]) => {
873 let ty1 = field1.ty(tcx, args).skip_norm_wip();
874 let ty2 = field2.ty(tcx, args).skip_norm_wip();
875
876 if is_niche_optimization_candidate(tcx, typing_env, ty1) {
877 ty2
878 } else if is_niche_optimization_candidate(tcx, typing_env, ty2) {
879 ty1
880 } else {
881 return None;
882 }
883 }
884 _ => return None,
885 },
886 _ => return None,
887 };
888
889 if !ty_is_known_nonnull(tcx, typing_env, field_ty) {
890 return None;
891 }
892
893 let compute_size_skeleton =
897 |t| SizeSkeleton::compute(t, tcx, typing_env, DUMMY_SP).ok();
898 if !compute_size_skeleton(ty)?.same_size(compute_size_skeleton(field_ty)?) {
899 ::rustc_middle::util::bug::bug_fmt(format_args!("improper_ctypes: Option nonnull optimization not applied?"));bug!("improper_ctypes: Option nonnull optimization not applied?");
900 }
901
902 let field_ty_layout = tcx.layout_of(typing_env.as_query_input(field_ty));
904 if field_ty_layout.is_err() && !field_ty.has_non_region_param() {
905 ::rustc_middle::util::bug::bug_fmt(format_args!("should be able to compute the layout of non-polymorphic type"));bug!("should be able to compute the layout of non-polymorphic type");
906 }
907
908 let field_ty_abi = &field_ty_layout.ok()?.backend_repr;
909 if let BackendRepr::Scalar(field_ty_scalar) = field_ty_abi {
910 match field_ty_scalar.valid_range(&tcx) {
911 WrappingRange { start: 0, end }
912 if end == field_ty_scalar.size(&tcx).unsigned_int_max() - 1 =>
913 {
914 return Some(get_nullable_type(tcx, typing_env, field_ty).expect(
915 "known non-null scalar type should have a nullable representation",
916 ));
917 }
918 WrappingRange { start: 1, .. } => {
919 return Some(get_nullable_type(tcx, typing_env, field_ty).expect(
920 "known non-null scalar type should have a nullable representation",
921 ));
922 }
923 WrappingRange { start, end } => {
924 {
::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
format_args!("Unhandled start and end range: ({0}, {1})", start,
end)));
}unreachable!("Unhandled start and end range: ({}, {})", start, end)
925 }
926 };
927 }
928 None
929 }
930 ty::Pat(base, pat) => get_nullable_type_from_pat(tcx, typing_env, *base, *pat),
931 _ => None,
932 }
933}
934
935fn get_nullable_type_from_pat<'tcx>(
936 tcx: TyCtxt<'tcx>,
937 typing_env: ty::TypingEnv<'tcx>,
938 base: Ty<'tcx>,
939 pat: ty::Pattern<'tcx>,
940) -> Option<Ty<'tcx>> {
941 match *pat {
942 ty::PatternKind::NotNull | ty::PatternKind::Range { .. } => {
943 get_nullable_type(tcx, typing_env, base)
944 }
945 ty::PatternKind::Or(patterns) => {
946 let first = get_nullable_type_from_pat(tcx, typing_env, base, patterns[0])?;
947 for &pat in &patterns[1..] {
948 {
match (&first, &get_nullable_type_from_pat(tcx, typing_env, base, pat)?) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(first, get_nullable_type_from_pat(tcx, typing_env, base, pat)?);
949 }
950 Some(first)
951 }
952 }
953}
954
955pub struct VariantSizeDifferences;
#[automatically_derived]
impl ::core::marker::Copy for VariantSizeDifferences { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for VariantSizeDifferences { }
#[automatically_derived]
impl ::core::clone::Clone for VariantSizeDifferences {
#[inline]
fn clone(&self) -> VariantSizeDifferences { *self }
}
impl ::rustc_lint_defs::LintPass for VariantSizeDifferences {
fn name(&self) -> &'static str { "VariantSizeDifferences" }
fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[VARIANT_SIZE_DIFFERENCES]))
}
}
impl VariantSizeDifferences {
#[allow(unused)]
pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[VARIANT_SIZE_DIFFERENCES]))
}
}declare_lint_pass!(VariantSizeDifferences => [VARIANT_SIZE_DIFFERENCES]);
956
957impl<'tcx> LateLintPass<'tcx> for VariantSizeDifferences {
958 fn check_item(&mut self, cx: &LateContext<'_>, it: &hir::Item<'_>) {
959 if let hir::ItemKind::Enum(_, _, ref enum_definition) = it.kind {
960 let t = cx.tcx.type_of(it.owner_id).instantiate_identity().skip_norm_wip();
961 let ty = cx.tcx.erase_and_anonymize_regions(t);
962 let Ok(layout) = cx.layout_of(ty) else { return };
963 let Variants::Multiple { tag_encoding: TagEncoding::Direct, tag, variants, .. } =
964 &layout.variants
965 else {
966 return;
967 };
968
969 let tag_size = tag.size(&cx.tcx).bytes();
970
971 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_lint/src/types.rs:971",
"rustc_lint::types", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_lint/src/types.rs"),
::tracing_core::__macro_support::Option::Some(971u32),
::tracing_core::__macro_support::Option::Some("rustc_lint::types"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("enum `{0}` is {1} bytes large with layout:\n{2:#?}",
t, layout.size.bytes(), layout) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(
972 "enum `{}` is {} bytes large with layout:\n{:#?}",
973 t,
974 layout.size.bytes(),
975 layout
976 );
977
978 let (largest, slargest, largest_index) = iter::zip(enum_definition.variants, variants)
979 .map(|(variant, variant_layout)| {
980 let bytes = variant_layout.size.bytes().saturating_sub(tag_size);
982
983 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_lint/src/types.rs:983",
"rustc_lint::types", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_lint/src/types.rs"),
::tracing_core::__macro_support::Option::Some(983u32),
::tracing_core::__macro_support::Option::Some("rustc_lint::types"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("- variant `{0}` is {1} bytes large",
variant.ident, bytes) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("- variant `{}` is {} bytes large", variant.ident, bytes);
984 bytes
985 })
986 .enumerate()
987 .fold((0, 0, 0), |(l, s, li), (idx, size)| {
988 if size > l {
989 (size, l, idx)
990 } else if size > s {
991 (l, size, li)
992 } else {
993 (l, s, li)
994 }
995 });
996
997 if largest > slargest * 3 && slargest > 0 {
1000 cx.emit_span_lint(
1001 VARIANT_SIZE_DIFFERENCES,
1002 enum_definition.variants[largest_index].span,
1003 VariantSizeDifferencesDiag { largest },
1004 );
1005 }
1006 }
1007 }
1008}
1009
1010#[doc = r" The `invalid_atomic_ordering` lint detects passing an `Ordering`"]
#[doc = r" to an atomic operation that does not support that ordering."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust,compile_fail"]
#[doc = r" # use core::sync::atomic::{AtomicU8, Ordering};"]
#[doc = r" let atom = AtomicU8::new(0);"]
#[doc = r" let value = atom.load(Ordering::Release);"]
#[doc = r" # let _ = value;"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc = r" Some atomic operations are only supported for a subset of the"]
#[doc =
r" `atomic::Ordering` variants. Passing an unsupported variant will cause"]
#[doc =
r" an unconditional panic at runtime, which is detected by this lint."]
#[doc = r""]
#[doc =
r" This lint will trigger in the following cases: (where `AtomicType` is an"]
#[doc = r" atomic type from `core::sync::atomic`, such as `AtomicBool`,"]
#[doc = r" `AtomicPtr`, `AtomicUsize`, or any of the other integer atomics)."]
#[doc = r""]
#[doc = r" - Passing `Ordering::Acquire` or `Ordering::AcqRel` to"]
#[doc = r" `AtomicType::store`."]
#[doc = r""]
#[doc = r" - Passing `Ordering::Release` or `Ordering::AcqRel` to"]
#[doc = r" `AtomicType::load`."]
#[doc = r""]
#[doc = r" - Passing `Ordering::Relaxed` to `core::sync::atomic::fence` or"]
#[doc = r" `core::sync::atomic::compiler_fence`."]
#[doc = r""]
#[doc =
r" - Passing `Ordering::Release` or `Ordering::AcqRel` as the failure"]
#[doc = r" ordering for any of `AtomicType::compare_exchange`,"]
#[doc = r" `AtomicType::compare_exchange_weak`, `AtomicType::update`, or"]
#[doc = r" `AtomicType::try_update`."]
static INVALID_ATOMIC_ORDERING: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: "INVALID_ATOMIC_ORDERING",
default_level: ::rustc_lint_defs::Deny,
desc: "usage of invalid atomic ordering in atomic operations and memory fences",
is_externally_loaded: false,
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_lint! {
1011 INVALID_ATOMIC_ORDERING,
1049 Deny,
1050 "usage of invalid atomic ordering in atomic operations and memory fences"
1051}
1052
1053pub struct InvalidAtomicOrdering;
#[automatically_derived]
impl ::core::marker::Copy for InvalidAtomicOrdering { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for InvalidAtomicOrdering { }
#[automatically_derived]
impl ::core::clone::Clone for InvalidAtomicOrdering {
#[inline]
fn clone(&self) -> InvalidAtomicOrdering { *self }
}
impl ::rustc_lint_defs::LintPass for InvalidAtomicOrdering {
fn name(&self) -> &'static str { "InvalidAtomicOrdering" }
fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[INVALID_ATOMIC_ORDERING]))
}
}
impl InvalidAtomicOrdering {
#[allow(unused)]
pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[INVALID_ATOMIC_ORDERING]))
}
}declare_lint_pass!(InvalidAtomicOrdering => [INVALID_ATOMIC_ORDERING]);
1054
1055impl InvalidAtomicOrdering {
1056 fn inherent_atomic_method_call<'hir>(
1057 cx: &LateContext<'_>,
1058 expr: &Expr<'hir>,
1059 recognized_names: &[Symbol], ) -> Option<(Symbol, &'hir [Expr<'hir>])> {
1061 if let ExprKind::MethodCall(method_path, _, args, _) = &expr.kind
1062 && recognized_names.contains(&method_path.ident.name)
1063 && let Some(m_def_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id)
1064 && let Some(impl_did) = cx.tcx.inherent_impl_of_assoc(m_def_id)
1066 && let Some(adt) = cx.tcx.type_of(impl_did).instantiate_identity().skip_norm_wip().ty_adt_def()
1067 && cx.tcx.is_diagnostic_item(sym::Atomic, adt.did())
1068 {
1069 return Some((method_path.ident.name, args));
1070 }
1071 None
1072 }
1073
1074 fn match_ordering(cx: &LateContext<'_>, ord_arg: &Expr<'_>) -> Option<Symbol> {
1075 let ExprKind::Path(ref ord_qpath) = ord_arg.kind else { return None };
1076 let did = cx.qpath_res(ord_qpath, ord_arg.hir_id).opt_def_id()?;
1077 let tcx = cx.tcx;
1078 let atomic_ordering = tcx.get_diagnostic_item(sym::Ordering);
1079 let name = tcx.item_name(did);
1080 let parent = tcx.parent(did);
1081 [sym::Relaxed, sym::Release, sym::Acquire, sym::AcqRel, sym::SeqCst].into_iter().find(
1082 |&ordering| {
1083 name == ordering
1084 && (Some(parent) == atomic_ordering
1085 || tcx.opt_parent(parent) == atomic_ordering)
1087 },
1088 )
1089 }
1090
1091 fn check_atomic_load_store(cx: &LateContext<'_>, expr: &Expr<'_>) {
1092 if let Some((method, args)) =
1093 Self::inherent_atomic_method_call(cx, expr, &[sym::load, sym::store])
1094 && let Some((ordering_arg, invalid_ordering)) = match method {
1095 sym::load => Some((&args[0], sym::Release)),
1096 sym::store => Some((&args[1], sym::Acquire)),
1097 _ => None,
1098 }
1099 && let Some(ordering) = Self::match_ordering(cx, ordering_arg)
1100 && (ordering == invalid_ordering || ordering == sym::AcqRel)
1101 {
1102 if method == sym::load {
1103 cx.emit_span_lint(INVALID_ATOMIC_ORDERING, ordering_arg.span, AtomicOrderingLoad);
1104 } else {
1105 cx.emit_span_lint(INVALID_ATOMIC_ORDERING, ordering_arg.span, AtomicOrderingStore);
1106 };
1107 }
1108 }
1109
1110 fn check_memory_fence(cx: &LateContext<'_>, expr: &Expr<'_>) {
1111 if let ExprKind::Call(func, args) = expr.kind
1112 && let ExprKind::Path(ref func_qpath) = func.kind
1113 && let Some(def_id) = cx.qpath_res(func_qpath, func.hir_id).opt_def_id()
1114 && #[allow(non_exhaustive_omitted_patterns)] match cx.tcx.get_diagnostic_name(def_id)
{
Some(sym::fence | sym::compiler_fence) => true,
_ => false,
}matches!(cx.tcx.get_diagnostic_name(def_id), Some(sym::fence | sym::compiler_fence))
1115 && Self::match_ordering(cx, &args[0]) == Some(sym::Relaxed)
1116 {
1117 cx.emit_span_lint(INVALID_ATOMIC_ORDERING, args[0].span, AtomicOrderingFence);
1118 }
1119 }
1120
1121 fn check_atomic_compare_exchange(cx: &LateContext<'_>, expr: &Expr<'_>) {
1122 let Some((method, args)) = Self::inherent_atomic_method_call(
1123 cx,
1124 expr,
1125 &[
1126 sym::update,
1127 sym::try_update,
1128 sym::fetch_update,
1129 sym::compare_exchange,
1130 sym::compare_exchange_weak,
1131 ],
1132 ) else {
1133 return;
1134 };
1135
1136 let fail_order_arg = match method {
1137 sym::update | sym::try_update | sym::fetch_update => &args[1],
1138 sym::compare_exchange | sym::compare_exchange_weak => &args[3],
1139 _ => return,
1140 };
1141
1142 let Some(fail_ordering) = Self::match_ordering(cx, fail_order_arg) else { return };
1143
1144 if #[allow(non_exhaustive_omitted_patterns)] match fail_ordering {
sym::Release | sym::AcqRel => true,
_ => false,
}matches!(fail_ordering, sym::Release | sym::AcqRel) {
1145 cx.emit_span_lint(
1146 INVALID_ATOMIC_ORDERING,
1147 fail_order_arg.span,
1148 InvalidAtomicOrderingDiag { method, fail_order_arg_span: fail_order_arg.span },
1149 );
1150 }
1151 }
1152}
1153
1154impl<'tcx> LateLintPass<'tcx> for InvalidAtomicOrdering {
1155 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
1156 Self::check_atomic_load_store(cx, expr);
1157 Self::check_memory_fence(cx, expr);
1158 Self::check_atomic_compare_exchange(cx, expr);
1159 }
1160}