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};
27pub(crate) use crate::ferrocene::LintUnvalidated;
29use crate::{LateContext, LateLintPass, LintContext};
30
31mod literal;
32use literal::{int_ty_range, lint_literal, uint_ty_range};
33
34#[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! {
35 UNUSED_COMPARISONS,
53 Warn,
54 "comparisons made useless by limits of the types involved"
55}
56
57#[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! {
58 OVERFLOWING_LITERALS,
74 Deny,
75 "literal out of range for its type"
76}
77
78#[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! {
79 VARIANT_SIZE_DIFFERENCES,
111 Allow,
112 "detects enums with widely varying variant sizes"
113}
114
115#[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! {
116 INVALID_NAN_COMPARISONS,
133 Warn,
134 "detects invalid floating point NaN comparisons"
135}
136
137#[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! {
138 AMBIGUOUS_WIDE_POINTER_COMPARISONS,
164 Warn,
165 "detects ambiguous wide pointer comparisons"
166}
167
168#[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! {
169 UNPREDICTABLE_FUNCTION_POINTER_COMPARISONS,
193 Warn,
194 "detects unpredictable function pointer comparisons",
195 report_in_external_macro
196}
197
198#[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)]
199pub(crate) struct TypeLimits {
200 last_visited_negation: Option<NegationInfo>,
201}
202
203#[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)]
204struct NegationInfo {
205 negation_span: Span,
207 negated_id: hir::HirId,
209}
210
211impl ::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 => [
212 UNUSED_COMPARISONS,
213 OVERFLOWING_LITERALS,
214 INVALID_NAN_COMPARISONS,
215 AMBIGUOUS_WIDE_POINTER_COMPARISONS,
216 UNPREDICTABLE_FUNCTION_POINTER_COMPARISONS
217]);
218
219impl TypeLimits {
220 pub(crate) fn new() -> TypeLimits {
221 TypeLimits { last_visited_negation: None }
222 }
223}
224
225fn lint_nan<'tcx>(
226 cx: &LateContext<'tcx>,
227 e: &'tcx hir::Expr<'tcx>,
228 binop: hir::BinOpKind,
229 l: &'tcx hir::Expr<'tcx>,
230 r: &'tcx hir::Expr<'tcx>,
231) {
232 fn is_nan(cx: &LateContext<'_>, expr: &hir::Expr<'_>) -> bool {
233 let expr = expr.peel_blocks().peel_borrows();
234 match expr.kind {
235 ExprKind::Path(qpath) => {
236 let Some(def_id) = cx.typeck_results().qpath_res(&qpath, expr.hir_id).opt_def_id()
237 else {
238 return false;
239 };
240
241 #[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!(
242 cx.tcx.get_diagnostic_name(def_id),
243 Some(sym::f16_nan | sym::f32_nan | sym::f64_nan | sym::f128_nan)
244 )
245 }
246 _ => false,
247 }
248 }
249
250 fn eq_ne(
251 e: &hir::Expr<'_>,
252 l: &hir::Expr<'_>,
253 r: &hir::Expr<'_>,
254 f: impl FnOnce(Span, Span) -> InvalidNanComparisonsSuggestion,
255 ) -> InvalidNanComparisons {
256 let suggestion = if let Some(l_span) = l.span.find_ancestor_inside(e.span)
257 && let Some(r_span) = r.span.find_ancestor_inside(e.span)
258 {
259 f(l_span, r_span)
260 } else {
261 InvalidNanComparisonsSuggestion::Spanless
262 };
263
264 InvalidNanComparisons::EqNe { suggestion }
265 }
266
267 let lint = match binop {
268 hir::BinOpKind::Eq | hir::BinOpKind::Ne if is_nan(cx, l) => {
269 eq_ne(e, l, r, |l_span, r_span| InvalidNanComparisonsSuggestion::Spanful {
270 nan_plus_binop: l_span.until(r_span),
271 float: r_span.shrink_to_hi(),
272 neg: (binop == hir::BinOpKind::Ne).then(|| r_span.shrink_to_lo()),
273 })
274 }
275 hir::BinOpKind::Eq | hir::BinOpKind::Ne if is_nan(cx, r) => {
276 eq_ne(e, l, r, |l_span, r_span| InvalidNanComparisonsSuggestion::Spanful {
277 nan_plus_binop: l_span.shrink_to_hi().to(r_span),
278 float: l_span.shrink_to_hi(),
279 neg: (binop == hir::BinOpKind::Ne).then(|| l_span.shrink_to_lo()),
280 })
281 }
282 hir::BinOpKind::Lt | hir::BinOpKind::Le | hir::BinOpKind::Gt | hir::BinOpKind::Ge
283 if is_nan(cx, l) || is_nan(cx, r) =>
284 {
285 InvalidNanComparisons::LtLeGtGe
286 }
287 _ => return,
288 };
289
290 cx.emit_span_lint(INVALID_NAN_COMPARISONS, e.span, lint);
291}
292
293#[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)]
294enum ComparisonOp {
295 BinOp(hir::BinOpKind),
296 Other,
297}
298
299fn lint_wide_pointer<'tcx>(
300 cx: &LateContext<'tcx>,
301 e: &'tcx hir::Expr<'tcx>,
302 cmpop: ComparisonOp,
303 l: &'tcx hir::Expr<'tcx>,
304 r: &'tcx hir::Expr<'tcx>,
305) {
306 let ptr_unsized = |mut ty: Ty<'tcx>| -> Option<(
307 usize,
308 String,
309 bool,
310 )> {
311 let mut refs = 0;
312 while let ty::Ref(_, inner_ty, _) = ty.kind() {
315 ty = *inner_ty;
316 refs += 1;
317 }
318
319 let mut modifiers = String::new();
321 ty = match ty.kind() {
322 ty::RawPtr(ty, _) => *ty,
323 ty::Adt(def, args) if cx.tcx.is_diagnostic_item(sym::NonNull, def.did()) => {
324 modifiers.push_str(".as_ptr()");
325 args.type_at(0)
326 }
327 _ => return None,
328 };
329
330 (!ty.is_sized(cx.tcx, cx.typing_env()))
331 .then(|| (refs, modifiers, #[allow(non_exhaustive_omitted_patterns)] match ty.kind() {
ty::Dynamic(_, _) => true,
_ => false,
}matches!(ty.kind(), ty::Dynamic(_, _))))
332 };
333
334 let l = l.peel_borrows();
336 let r = r.peel_borrows();
337
338 let Some(l_ty) = cx.typeck_results().expr_ty_opt(l) else {
339 return;
340 };
341 let Some(r_ty) = cx.typeck_results().expr_ty_opt(r) else {
342 return;
343 };
344
345 let Some((l_ty_refs, l_modifiers, l_inner_ty_is_dyn)) = ptr_unsized(l_ty) else {
346 return;
347 };
348 let Some((r_ty_refs, r_modifiers, r_inner_ty_is_dyn)) = ptr_unsized(r_ty) else {
349 return;
350 };
351
352 let (Some(l_span), Some(r_span)) =
353 (l.span.find_ancestor_inside(e.span), r.span.find_ancestor_inside(e.span))
354 else {
355 return cx.emit_span_lint(
356 AMBIGUOUS_WIDE_POINTER_COMPARISONS,
357 e.span,
358 AmbiguousWidePointerComparisons::Spanless,
359 );
360 };
361
362 let ne = if cmpop == ComparisonOp::BinOp(hir::BinOpKind::Ne) { "!" } else { "" };
363 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));
364 let is_dyn_comparison = l_inner_ty_is_dyn && r_inner_ty_is_dyn;
365 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(..));
366
367 let left = e.span.shrink_to_lo().until(l_span.shrink_to_lo());
368 let middle = l_span.shrink_to_hi().until(r_span.shrink_to_lo());
369 let right = r_span.shrink_to_hi().until(e.span.shrink_to_hi());
370
371 let deref_left = &*"*".repeat(l_ty_refs);
372 let deref_right = &*"*".repeat(r_ty_refs);
373
374 let l_modifiers = &*l_modifiers;
375 let r_modifiers = &*r_modifiers;
376
377 cx.emit_span_lint(
378 AMBIGUOUS_WIDE_POINTER_COMPARISONS,
379 e.span,
380 if is_eq_ne {
381 AmbiguousWidePointerComparisons::SpanfulEq {
382 addr_metadata_suggestion: (!is_dyn_comparison).then(|| {
383 AmbiguousWidePointerComparisonsAddrMetadataSuggestion {
384 ne,
385 deref_left,
386 deref_right,
387 l_modifiers,
388 r_modifiers,
389 left,
390 middle,
391 right,
392 }
393 }),
394 addr_suggestion: AmbiguousWidePointerComparisonsAddrSuggestion {
395 ne,
396 deref_left,
397 deref_right,
398 l_modifiers,
399 r_modifiers,
400 left,
401 middle,
402 right,
403 },
404 }
405 } else {
406 AmbiguousWidePointerComparisons::SpanfulCmp {
407 cast_suggestion: AmbiguousWidePointerComparisonsCastSuggestion {
408 deref_left,
409 deref_right,
410 l_modifiers,
411 r_modifiers,
412 paren_left: if l_ty_refs != 0 { ")" } else { "" },
413 paren_right: if r_ty_refs != 0 { ")" } else { "" },
414 left_before: (l_ty_refs != 0).then_some(l_span.shrink_to_lo()),
415 left_after: l_span.shrink_to_hi(),
416 right_before: (r_ty_refs != 0).then_some(r_span.shrink_to_lo()),
417 right_after: r_span.shrink_to_hi(),
418 },
419 expect_suggestion: AmbiguousWidePointerComparisonsExpectSuggestion {
420 paren_left: if via_method_call { "" } else { "(" },
421 paren_right: if via_method_call { "" } else { ")" },
422 before: e.span.shrink_to_lo(),
423 after: e.span.shrink_to_hi(),
424 },
425 }
426 },
427 );
428}
429
430fn lint_fn_pointer<'tcx>(
431 cx: &LateContext<'tcx>,
432 e: &'tcx hir::Expr<'tcx>,
433 cmpop: ComparisonOp,
434 l: &'tcx hir::Expr<'tcx>,
435 r: &'tcx hir::Expr<'tcx>,
436) {
437 let peel_refs = |mut ty: Ty<'tcx>| -> (Ty<'tcx>, usize) {
438 let mut refs = 0;
439
440 while let ty::Ref(_, inner_ty, _) = ty.kind() {
441 ty = *inner_ty;
442 refs += 1;
443 }
444
445 (ty, refs)
446 };
447
448 let l = l.peel_borrows();
450 let r = r.peel_borrows();
451
452 let Some(l_ty) = cx.typeck_results().expr_ty_opt(l) else { return };
453 let Some(r_ty) = cx.typeck_results().expr_ty_opt(r) else { return };
454
455 let (l_ty, l_ty_refs) = peel_refs(l_ty);
458 let (r_ty, r_ty_refs) = peel_refs(r_ty);
459
460 if l_ty.is_fn() && r_ty.is_fn() {
461 } else if let ty::Adt(l_def, l_args) = l_ty.kind()
463 && let ty::Adt(r_def, r_args) = r_ty.kind()
464 && cx.tcx.is_lang_item(l_def.did(), LangItem::Option)
465 && cx.tcx.is_lang_item(r_def.did(), LangItem::Option)
466 && let Some(l_some_arg) = l_args.get(0)
467 && let Some(r_some_arg) = r_args.get(0)
468 && l_some_arg.expect_ty().is_fn()
469 && r_some_arg.expect_ty().is_fn()
470 {
471 return cx.emit_span_lint(
473 UNPREDICTABLE_FUNCTION_POINTER_COMPARISONS,
474 e.span,
475 UnpredictableFunctionPointerComparisons::Warn,
476 );
477 } else {
478 return;
480 }
481
482 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));
485
486 if !is_eq_ne {
487 return cx.emit_span_lint(
489 UNPREDICTABLE_FUNCTION_POINTER_COMPARISONS,
490 e.span,
491 UnpredictableFunctionPointerComparisons::Warn,
492 );
493 }
494
495 let (Some(l_span), Some(r_span)) =
496 (l.span.find_ancestor_inside(e.span), r.span.find_ancestor_inside(e.span))
497 else {
498 return cx.emit_span_lint(
500 UNPREDICTABLE_FUNCTION_POINTER_COMPARISONS,
501 e.span,
502 UnpredictableFunctionPointerComparisons::Warn,
503 );
504 };
505
506 let ne = if cmpop == ComparisonOp::BinOp(hir::BinOpKind::Ne) { "!" } else { "" };
507
508 let deref_left = &*"*".repeat(l_ty_refs);
510 let deref_right = &*"*".repeat(r_ty_refs);
511
512 let left = e.span.shrink_to_lo().until(l_span.shrink_to_lo());
513 let middle = l_span.shrink_to_hi().until(r_span.shrink_to_lo());
514 let right = r_span.shrink_to_hi().until(e.span.shrink_to_hi());
515
516 let sugg =
517 if !r_ty.is_fn_ptr() {
520 let fn_sig = r_ty.fn_sig(cx.tcx);
521
522 UnpredictableFunctionPointerComparisonsSuggestion::FnAddrEqWithCast {
523 ne,
524 fn_sig,
525 deref_left,
526 deref_right,
527 left,
528 middle,
529 right,
530 }
531 } else {
532 UnpredictableFunctionPointerComparisonsSuggestion::FnAddrEq {
533 ne,
534 deref_left,
535 deref_right,
536 left,
537 middle,
538 right,
539 }
540 };
541
542 cx.emit_span_lint(
543 UNPREDICTABLE_FUNCTION_POINTER_COMPARISONS,
544 e.span,
545 UnpredictableFunctionPointerComparisons::Suggestion { sugg },
546 );
547}
548
549impl<'tcx> LateLintPass<'tcx> for TypeLimits {
550 fn check_lit(
551 &mut self,
552 cx: &LateContext<'tcx>,
553 hir_id: HirId,
554 lit: hir::Lit,
555 is_negated_pat: bool,
556 ) {
557 let surrounding_negation = if is_negated_pat {
558 Some(lit.span)
561 } else if let Some(negation_info) = self.last_visited_negation
562 && negation_info.negated_id == hir_id
563 {
564 Some(negation_info.negation_span)
565 } else {
566 None
567 };
568 lint_literal(cx, hir_id, lit.span, &lit, surrounding_negation);
569 }
570
571 fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx hir::Expr<'tcx>) {
572 match e.kind {
573 hir::ExprKind::Unary(hir::UnOp::Neg, expr) => {
574 self.last_visited_negation =
575 Some(NegationInfo { negation_span: e.span, negated_id: expr.hir_id });
576 }
577 hir::ExprKind::Binary(binop, ref l, ref r) => {
578 if is_comparison(binop.node) {
579 if !check_limits(cx, binop.node, l, r) {
580 cx.emit_span_lint(UNUSED_COMPARISONS, e.span, UnusedComparisons);
581 } else {
582 lint_nan(cx, e, binop.node, l, r);
583 let cmpop = ComparisonOp::BinOp(binop.node);
584 lint_wide_pointer(cx, e, cmpop, l, r);
585 lint_fn_pointer(cx, e, cmpop, l, r);
586 }
587 }
588 }
589 hir::ExprKind::Call(path, [l, r])
590 if let ExprKind::Path(ref qpath) = path.kind
591 && let Some(def_id) = cx.qpath_res(qpath, path.hir_id).opt_def_id()
592 && let Some(diag_item) = cx.tcx.get_diagnostic_name(def_id)
593 && let Some(cmpop) = diag_item_cmpop(diag_item) =>
594 {
595 lint_wide_pointer(cx, e, cmpop, l, r);
596 lint_fn_pointer(cx, e, cmpop, l, r);
597 }
598 hir::ExprKind::MethodCall(_, l, [r], _)
599 if let Some(def_id) = cx.typeck_results().type_dependent_def_id(e.hir_id)
600 && let Some(diag_item) = cx.tcx.get_diagnostic_name(def_id)
601 && let Some(cmpop) = diag_item_cmpop(diag_item) =>
602 {
603 lint_wide_pointer(cx, e, cmpop, l, r);
604 lint_fn_pointer(cx, e, cmpop, l, r);
605 }
606 _ => {}
607 };
608
609 fn is_valid<T: PartialOrd>(binop: hir::BinOpKind, v: T, min: T, max: T) -> bool {
610 match binop {
611 hir::BinOpKind::Lt => v > min && v <= max,
612 hir::BinOpKind::Le => v >= min && v < max,
613 hir::BinOpKind::Gt => v >= min && v < max,
614 hir::BinOpKind::Ge => v > min && v <= max,
615 hir::BinOpKind::Eq | hir::BinOpKind::Ne => v >= min && v <= max,
616 _ => ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
617 }
618 }
619
620 fn rev_binop(binop: hir::BinOpKind) -> hir::BinOpKind {
621 match binop {
622 hir::BinOpKind::Lt => hir::BinOpKind::Gt,
623 hir::BinOpKind::Le => hir::BinOpKind::Ge,
624 hir::BinOpKind::Gt => hir::BinOpKind::Lt,
625 hir::BinOpKind::Ge => hir::BinOpKind::Le,
626 _ => binop,
627 }
628 }
629
630 fn check_limits(
631 cx: &LateContext<'_>,
632 binop: hir::BinOpKind,
633 l: &hir::Expr<'_>,
634 r: &hir::Expr<'_>,
635 ) -> bool {
636 let (lit, expr, swap) = match (&l.kind, &r.kind) {
637 (&hir::ExprKind::Lit(_), _) => (l, r, true),
638 (_, &hir::ExprKind::Lit(_)) => (r, l, false),
639 _ => return true,
640 };
641 let norm_binop = if swap { rev_binop(binop) } else { binop };
644 match *cx.typeck_results().node_type(expr.hir_id).kind() {
645 ty::Int(int_ty) => {
646 let (min, max) = int_ty_range(int_ty);
647 let lit_val: i128 = match lit.kind {
648 hir::ExprKind::Lit(li) => match li.node {
649 ast::LitKind::Int(
650 v,
651 ast::LitIntType::Signed(_) | ast::LitIntType::Unsuffixed,
652 ) => v.get() as i128,
653 _ => return true,
654 },
655 _ => ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
656 };
657 is_valid(norm_binop, lit_val, min, max)
658 }
659 ty::Uint(uint_ty) => {
660 let (min, max): (u128, u128) = uint_ty_range(uint_ty);
661 let lit_val: u128 = match lit.kind {
662 hir::ExprKind::Lit(li) => match li.node {
663 ast::LitKind::Int(v, _) => v.get(),
664 _ => return true,
665 },
666 _ => ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
667 };
668 is_valid(norm_binop, lit_val, min, max)
669 }
670 _ => true,
671 }
672 }
673
674 fn is_comparison(binop: hir::BinOpKind) -> bool {
675 #[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!(
676 binop,
677 hir::BinOpKind::Eq
678 | hir::BinOpKind::Lt
679 | hir::BinOpKind::Le
680 | hir::BinOpKind::Ne
681 | hir::BinOpKind::Ge
682 | hir::BinOpKind::Gt
683 )
684 }
685
686 fn diag_item_cmpop(diag_item: Symbol) -> Option<ComparisonOp> {
687 Some(match diag_item {
688 sym::cmp_ord_max => ComparisonOp::Other,
689 sym::cmp_ord_min => ComparisonOp::Other,
690 sym::ord_cmp_method => ComparisonOp::Other,
691 sym::cmp_partialeq_eq => ComparisonOp::BinOp(hir::BinOpKind::Eq),
692 sym::cmp_partialeq_ne => ComparisonOp::BinOp(hir::BinOpKind::Ne),
693 sym::cmp_partialord_cmp => ComparisonOp::Other,
694 sym::cmp_partialord_ge => ComparisonOp::BinOp(hir::BinOpKind::Ge),
695 sym::cmp_partialord_gt => ComparisonOp::BinOp(hir::BinOpKind::Gt),
696 sym::cmp_partialord_le => ComparisonOp::BinOp(hir::BinOpKind::Le),
697 sym::cmp_partialord_lt => ComparisonOp::BinOp(hir::BinOpKind::Lt),
698 _ => return None,
699 })
700 }
701 }
702}
703
704pub(crate) fn nonnull_optimization_guaranteed<'tcx>(
705 tcx: TyCtxt<'tcx>,
706 def: ty::AdtDef<'tcx>,
707) -> bool {
708 {
{
'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)
709}
710
711pub(crate) fn transparent_newtype_field<'a, 'tcx>(
714 tcx: TyCtxt<'tcx>,
715 variant: &'a ty::VariantDef,
716) -> Option<&'a ty::FieldDef> {
717 let typing_env = ty::TypingEnv::non_body_analysis(tcx, variant.def_id);
718 variant.fields.iter().find(|field| {
719 let field_ty = tcx.type_of(field.did).instantiate_identity().skip_norm_wip();
720 let is_1zst =
721 tcx.layout_of(typing_env.as_query_input(field_ty)).is_ok_and(|layout| layout.is_1zst());
722 !is_1zst
723 })
724}
725
726fn ty_is_known_nonnull<'tcx>(
728 tcx: TyCtxt<'tcx>,
729 typing_env: ty::TypingEnv<'tcx>,
730 ty: Ty<'tcx>,
731) -> bool {
732 let ty = tcx.try_normalize_erasing_regions(typing_env, Unnormalized::new_wip(ty)).unwrap_or(ty);
733
734 match ty.kind() {
735 ty::FnPtr(..) => true,
736 ty::Ref(..) => true,
737 ty::Adt(def, _) if def.is_box() => true,
738 ty::Adt(def, args) if def.repr().transparent() && !def.is_union() => {
739 let marked_non_null = nonnull_optimization_guaranteed(tcx, *def);
740
741 if marked_non_null {
742 return true;
743 }
744
745 if def.is_unsafe_cell() || def.is_unsafe_pinned() {
747 return false;
748 }
749
750 def.variants().iter().filter_map(|variant| transparent_newtype_field(tcx, variant)).any(
751 |field| ty_is_known_nonnull(tcx, typing_env, field.ty(tcx, args).skip_norm_wip()),
752 )
753 }
754 ty::Pat(base, pat) => {
755 ty_is_known_nonnull(tcx, typing_env, *base)
756 || pat_ty_is_known_nonnull(tcx, typing_env, *pat)
757 }
758 _ => false,
759 }
760}
761
762fn pat_ty_is_known_nonnull<'tcx>(
763 tcx: TyCtxt<'tcx>,
764 typing_env: ty::TypingEnv<'tcx>,
765 pat: ty::Pattern<'tcx>,
766) -> bool {
767 try {
768 match *pat {
769 ty::PatternKind::Range { start, end } => {
770 let start = start.try_to_value()?.try_to_bits(tcx, typing_env)?;
771 let end = end.try_to_value()?.try_to_bits(tcx, typing_env)?;
772
773 start > 0 && end >= start
776 }
777 ty::PatternKind::NotNull => true,
778 ty::PatternKind::Or(patterns) => {
779 patterns.iter().all(|pat| pat_ty_is_known_nonnull(tcx, typing_env, pat))
780 }
781 }
782 }
783 .unwrap_or_default()
784}
785
786fn get_nullable_type<'tcx>(
789 tcx: TyCtxt<'tcx>,
790 typing_env: ty::TypingEnv<'tcx>,
791 ty: Ty<'tcx>,
792) -> Option<Ty<'tcx>> {
793 let ty = tcx.try_normalize_erasing_regions(typing_env, Unnormalized::new_wip(ty)).unwrap_or(ty);
794
795 Some(match *ty.kind() {
796 ty::Adt(field_def, field_args) => {
797 let inner_field_ty = {
798 let mut first_non_zst_ty =
799 field_def.variants().iter().filter_map(|v| transparent_newtype_field(tcx, v));
800 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!(
801 first_non_zst_ty.clone().count(),
802 1,
803 "Wrong number of fields for transparent type"
804 );
805 first_non_zst_ty
806 .next_back()
807 .expect("No non-zst fields in transparent type.")
808 .ty(tcx, field_args)
809 .skip_norm_wip()
810 };
811 return get_nullable_type(tcx, typing_env, inner_field_ty);
812 }
813 ty::Pat(base, ..) => return get_nullable_type(tcx, typing_env, base),
814 ty::Int(_) | ty::Uint(_) | ty::Char | ty::RawPtr(..) => ty,
815 ty::Ref(_region, ty, mutbl) => Ty::new_ptr(tcx, ty, mutbl),
818 ty::FnPtr(..) => ty,
821 ref unhandled => {
824 {
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:824",
"rustc_lint::types", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_lint/src/types.rs"),
::tracing_core::__macro_support::Option::Some(824u32),
::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!(
825 "get_nullable_type: Unhandled scalar kind: {:?} while checking {:?}",
826 unhandled, ty
827 );
828 return None;
829 }
830 })
831}
832
833fn is_niche_optimization_candidate<'tcx>(
838 tcx: TyCtxt<'tcx>,
839 typing_env: ty::TypingEnv<'tcx>,
840 ty: Ty<'tcx>,
841) -> bool {
842 if tcx.layout_of(typing_env.as_query_input(ty)).is_ok_and(|layout| !layout.is_1zst()) {
843 return false;
844 }
845
846 match ty.kind() {
847 ty::Adt(ty_def, _) => {
848 let non_exhaustive = ty_def.is_variant_list_non_exhaustive();
849 let empty = (ty_def.is_struct() && ty_def.non_enum_variant().fields.is_empty())
850 || (ty_def.is_enum() && ty_def.variants().is_empty());
851
852 !non_exhaustive && empty
853 }
854 ty::Tuple(tys) => tys.is_empty(),
855 _ => false,
856 }
857}
858
859pub(crate) fn repr_nullable_ptr<'tcx>(
864 tcx: TyCtxt<'tcx>,
865 typing_env: ty::TypingEnv<'tcx>,
866 ty: Ty<'tcx>,
867) -> Option<Ty<'tcx>> {
868 {
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:868",
"rustc_lint::types", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_lint/src/types.rs"),
::tracing_core::__macro_support::Option::Some(868u32),
::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);
869 match ty.kind() {
870 ty::Adt(ty_def, args) => {
871 let field_ty = match &ty_def.variants().raw[..] {
872 [var_one, var_two] => match (&var_one.fields.raw[..], &var_two.fields.raw[..]) {
873 ([], [field]) | ([field], []) => field.ty(tcx, args).skip_norm_wip(),
874 ([field1], [field2]) => {
875 let ty1 = field1.ty(tcx, args).skip_norm_wip();
876 let ty2 = field2.ty(tcx, args).skip_norm_wip();
877
878 if is_niche_optimization_candidate(tcx, typing_env, ty1) {
879 ty2
880 } else if is_niche_optimization_candidate(tcx, typing_env, ty2) {
881 ty1
882 } else {
883 return None;
884 }
885 }
886 _ => return None,
887 },
888 _ => return None,
889 };
890
891 if !ty_is_known_nonnull(tcx, typing_env, field_ty) {
892 return None;
893 }
894
895 let compute_size_skeleton =
899 |t| SizeSkeleton::compute(t, tcx, typing_env, DUMMY_SP).ok();
900 if !compute_size_skeleton(ty)?.same_size(compute_size_skeleton(field_ty)?) {
901 ::rustc_middle::util::bug::bug_fmt(format_args!("improper_ctypes: Option nonnull optimization not applied?"));bug!("improper_ctypes: Option nonnull optimization not applied?");
902 }
903
904 let field_ty_layout = tcx.layout_of(typing_env.as_query_input(field_ty));
906 if field_ty_layout.is_err() && !field_ty.has_non_region_param() {
907 ::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");
908 }
909
910 let field_ty_abi = &field_ty_layout.ok()?.backend_repr;
911 if let BackendRepr::Scalar(field_ty_scalar) = field_ty_abi {
912 match field_ty_scalar.valid_range(&tcx) {
913 WrappingRange { start: 0, end }
914 if end == field_ty_scalar.size(&tcx).unsigned_int_max() - 1 =>
915 {
916 return Some(get_nullable_type(tcx, typing_env, field_ty).expect(
917 "known non-null scalar type should have a nullable representation",
918 ));
919 }
920 WrappingRange { start: 1, .. } => {
921 return Some(get_nullable_type(tcx, typing_env, field_ty).expect(
922 "known non-null scalar type should have a nullable representation",
923 ));
924 }
925 WrappingRange { start, end } => {
926 {
::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)
927 }
928 };
929 }
930 None
931 }
932 ty::Pat(base, pat) => get_nullable_type_from_pat(tcx, typing_env, *base, *pat),
933 _ => None,
934 }
935}
936
937fn get_nullable_type_from_pat<'tcx>(
938 tcx: TyCtxt<'tcx>,
939 typing_env: ty::TypingEnv<'tcx>,
940 base: Ty<'tcx>,
941 pat: ty::Pattern<'tcx>,
942) -> Option<Ty<'tcx>> {
943 match *pat {
944 ty::PatternKind::NotNull | ty::PatternKind::Range { .. } => {
945 get_nullable_type(tcx, typing_env, base)
946 }
947 ty::PatternKind::Or(patterns) => {
948 let first = get_nullable_type_from_pat(tcx, typing_env, base, patterns[0])?;
949 for &pat in &patterns[1..] {
950 {
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)?);
951 }
952 Some(first)
953 }
954 }
955}
956
957pub 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]);
958
959impl<'tcx> LateLintPass<'tcx> for VariantSizeDifferences {
960 fn check_item(&mut self, cx: &LateContext<'_>, it: &hir::Item<'_>) {
961 if let hir::ItemKind::Enum(_, _, ref enum_definition) = it.kind {
962 let t = cx.tcx.type_of(it.owner_id).instantiate_identity().skip_norm_wip();
963 let ty = cx.tcx.erase_and_anonymize_regions(t);
964 let Ok(layout) = cx.layout_of(ty) else { return };
965 let Variants::Multiple { tag_encoding: TagEncoding::Direct, tag, variants, .. } =
966 &layout.variants
967 else {
968 return;
969 };
970
971 let tag_size = tag.size(&cx.tcx).bytes();
972
973 {
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:973",
"rustc_lint::types", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_lint/src/types.rs"),
::tracing_core::__macro_support::Option::Some(973u32),
::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!(
974 "enum `{}` is {} bytes large with layout:\n{:#?}",
975 t,
976 layout.size.bytes(),
977 layout
978 );
979
980 let (largest, slargest, largest_index) = iter::zip(enum_definition.variants, variants)
981 .map(|(variant, variant_layout)| {
982 let bytes = variant_layout.size.bytes().saturating_sub(tag_size);
984
985 {
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:985",
"rustc_lint::types", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_lint/src/types.rs"),
::tracing_core::__macro_support::Option::Some(985u32),
::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);
986 bytes
987 })
988 .enumerate()
989 .fold((0, 0, 0), |(l, s, li), (idx, size)| {
990 if size > l {
991 (size, l, idx)
992 } else if size > s {
993 (l, size, li)
994 } else {
995 (l, s, li)
996 }
997 });
998
999 if largest > slargest * 3 && slargest > 0 {
1002 cx.emit_span_lint(
1003 VARIANT_SIZE_DIFFERENCES,
1004 enum_definition.variants[largest_index].span,
1005 VariantSizeDifferencesDiag { largest },
1006 );
1007 }
1008 }
1009 }
1010}
1011
1012#[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! {
1013 INVALID_ATOMIC_ORDERING,
1051 Deny,
1052 "usage of invalid atomic ordering in atomic operations and memory fences"
1053}
1054
1055pub 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]);
1056
1057impl InvalidAtomicOrdering {
1058 fn inherent_atomic_method_call<'hir>(
1059 cx: &LateContext<'_>,
1060 expr: &Expr<'hir>,
1061 recognized_names: &[Symbol], ) -> Option<(Symbol, &'hir [Expr<'hir>])> {
1063 if let ExprKind::MethodCall(method_path, _, args, _) = &expr.kind
1064 && recognized_names.contains(&method_path.ident.name)
1065 && let Some(m_def_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id)
1066 && let Some(impl_did) = cx.tcx.inherent_impl_of_assoc(m_def_id)
1068 && let Some(adt) = cx.tcx.type_of(impl_did).instantiate_identity().skip_norm_wip().ty_adt_def()
1069 && cx.tcx.is_diagnostic_item(sym::Atomic, adt.did())
1070 {
1071 return Some((method_path.ident.name, args));
1072 }
1073 None
1074 }
1075
1076 fn match_ordering(cx: &LateContext<'_>, ord_arg: &Expr<'_>) -> Option<Symbol> {
1077 let ExprKind::Path(ref ord_qpath) = ord_arg.kind else { return None };
1078 let did = cx.qpath_res(ord_qpath, ord_arg.hir_id).opt_def_id()?;
1079 let tcx = cx.tcx;
1080 let atomic_ordering = tcx.get_diagnostic_item(sym::Ordering);
1081 let name = tcx.item_name(did);
1082 let parent = tcx.parent(did);
1083 [sym::Relaxed, sym::Release, sym::Acquire, sym::AcqRel, sym::SeqCst].into_iter().find(
1084 |&ordering| {
1085 name == ordering
1086 && (Some(parent) == atomic_ordering
1087 || tcx.opt_parent(parent) == atomic_ordering)
1089 },
1090 )
1091 }
1092
1093 fn check_atomic_load_store(cx: &LateContext<'_>, expr: &Expr<'_>) {
1094 if let Some((method, args)) =
1095 Self::inherent_atomic_method_call(cx, expr, &[sym::load, sym::store])
1096 && let Some((ordering_arg, invalid_ordering)) = match method {
1097 sym::load => Some((&args[0], sym::Release)),
1098 sym::store => Some((&args[1], sym::Acquire)),
1099 _ => None,
1100 }
1101 && let Some(ordering) = Self::match_ordering(cx, ordering_arg)
1102 && (ordering == invalid_ordering || ordering == sym::AcqRel)
1103 {
1104 if method == sym::load {
1105 cx.emit_span_lint(INVALID_ATOMIC_ORDERING, ordering_arg.span, AtomicOrderingLoad);
1106 } else {
1107 cx.emit_span_lint(INVALID_ATOMIC_ORDERING, ordering_arg.span, AtomicOrderingStore);
1108 };
1109 }
1110 }
1111
1112 fn check_memory_fence(cx: &LateContext<'_>, expr: &Expr<'_>) {
1113 if let ExprKind::Call(func, args) = expr.kind
1114 && let ExprKind::Path(ref func_qpath) = func.kind
1115 && let Some(def_id) = cx.qpath_res(func_qpath, func.hir_id).opt_def_id()
1116 && #[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))
1117 && Self::match_ordering(cx, &args[0]) == Some(sym::Relaxed)
1118 {
1119 cx.emit_span_lint(INVALID_ATOMIC_ORDERING, args[0].span, AtomicOrderingFence);
1120 }
1121 }
1122
1123 fn check_atomic_compare_exchange(cx: &LateContext<'_>, expr: &Expr<'_>) {
1124 let Some((method, args)) = Self::inherent_atomic_method_call(
1125 cx,
1126 expr,
1127 &[
1128 sym::update,
1129 sym::try_update,
1130 sym::fetch_update,
1131 sym::compare_exchange,
1132 sym::compare_exchange_weak,
1133 ],
1134 ) else {
1135 return;
1136 };
1137
1138 let fail_order_arg = match method {
1139 sym::update | sym::try_update | sym::fetch_update => &args[1],
1140 sym::compare_exchange | sym::compare_exchange_weak => &args[3],
1141 _ => return,
1142 };
1143
1144 let Some(fail_ordering) = Self::match_ordering(cx, fail_order_arg) else { return };
1145
1146 if #[allow(non_exhaustive_omitted_patterns)] match fail_ordering {
sym::Release | sym::AcqRel => true,
_ => false,
}matches!(fail_ordering, sym::Release | sym::AcqRel) {
1147 cx.emit_span_lint(
1148 INVALID_ATOMIC_ORDERING,
1149 fail_order_arg.span,
1150 InvalidAtomicOrderingDiag { method, fail_order_arg_span: fail_order_arg.span },
1151 );
1152 }
1153 }
1154}
1155
1156impl<'tcx> LateLintPass<'tcx> for InvalidAtomicOrdering {
1157 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
1158 Self::check_atomic_load_store(cx, expr);
1159 Self::check_memory_fence(cx, expr);
1160 Self::check_atomic_compare_exchange(cx, expr);
1161 }
1162}