Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 9 additions & 9 deletions compiler/rustc_lint/src/diagnostics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2375,7 +2375,7 @@ pub(crate) struct AmbiguousWidePointerComparisonsExpectSuggestion<'a> {
}

#[derive(Diagnostic)]
pub(crate) enum UnpredictableFunctionPointerComparisons<'a, 'tcx> {
pub(crate) enum UnpredictableFunctionPointerComparisons<'tcx> {
#[diag(
"function pointer comparisons do not produce meaningful results since their addresses are not guaranteed to be unique"
)]
Expand All @@ -2388,7 +2388,7 @@ pub(crate) enum UnpredictableFunctionPointerComparisons<'a, 'tcx> {
)]
Suggestion {
#[subdiagnostic]
sugg: UnpredictableFunctionPointerComparisonsSuggestion<'a, 'tcx>,
sugg: UnpredictableFunctionPointerComparisonsSuggestion<'tcx>,
},
#[diag(
"function pointer comparisons do not produce meaningful results since their addresses are not guaranteed to be unique"
Expand All @@ -2404,17 +2404,17 @@ pub(crate) enum UnpredictableFunctionPointerComparisons<'a, 'tcx> {
}

#[derive(Subdiagnostic)]
pub(crate) enum UnpredictableFunctionPointerComparisonsSuggestion<'a, 'tcx> {
pub(crate) enum UnpredictableFunctionPointerComparisonsSuggestion<'tcx> {
#[multipart_suggestion(
"refactor your code, or use `{$krate}::ptr::fn_addr_eq` to suppress the lint",
style = "verbose",
applicability = "maybe-incorrect"
)]
FnAddrEq {
krate: &'static str,
ne: &'a str,
deref_left: &'a str,
deref_right: &'a str,
ne: &'static str,
deref_left: String,
deref_right: String,
#[suggestion_part(code = "{ne}{krate}::ptr::fn_addr_eq({deref_left}")]
left: Span,
#[suggestion_part(code = ", {deref_right}")]
Expand All @@ -2429,9 +2429,9 @@ pub(crate) enum UnpredictableFunctionPointerComparisonsSuggestion<'a, 'tcx> {
)]
FnAddrEqWithCast {
krate: &'static str,
ne: &'a str,
deref_left: &'a str,
deref_right: &'a str,
ne: &'static str,
deref_left: String,
deref_right: String,
fn_sig: rustc_middle::ty::PolyFnSig<'tcx>,
#[suggestion_part(code = "{ne}{krate}::ptr::fn_addr_eq({deref_left}")]
left: Span,
Expand Down
107 changes: 44 additions & 63 deletions compiler/rustc_lint/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -392,7 +392,8 @@ fn lint_wide_pointer<'tcx>(
_ => return None,
};

(!ty.is_sized(cx.tcx, cx.typing_env()))
// NB: pointers to `Code` are handled by `lint_fn_pointer`.
(!ty.is_sized(cx.tcx, cx.typing_env()) && !ty.is_lang_item(cx.tcx, LangItem::Code))
.then(|| (refs, modifiers, matches!(ty.kind(), ty::Dynamic(_, _))))
};

Expand Down Expand Up @@ -520,6 +521,19 @@ fn lint_fn_pointer<'tcx>(
(ty, refs)
};

// *const/mut Code, NonNull<code>
let is_code_ptr = |ty: Ty<'tcx>| match ty.kind() {
ty::RawPtr(t, _) => t.is_lang_item(cx.tcx, LangItem::Code),
ty::Adt(def, args) if cx.tcx.is_lang_item(def.did(), LangItem::NonNull) => {
args.type_at(0).is_lang_item(cx.tcx, LangItem::Code)
}
_ => false,
};

let is_like_fn_ptr = |ty: Ty<'tcx>| ty.is_fn() || is_code_ptr(ty);

let is_option_of_like_fn_ptr = |ty: Ty<'tcx>| matches!(ty.kind(), ty::Adt(def, args) if cx.tcx.is_lang_item(def.did(), LangItem::Option) && is_like_fn_ptr(args.type_at(0)));

// Left and right operands can have borrows, remove them
let l = l.peel_borrows();
let r = r.peel_borrows();
Expand All @@ -532,74 +546,40 @@ fn lint_fn_pointer<'tcx>(
let (l_ty, l_ty_refs) = peel_refs(l_ty);
let (r_ty, r_ty_refs) = peel_refs(r_ty);

if l_ty.is_fn() && r_ty.is_fn() {
// both operands are function pointers, fallthrough
} else if let ty::Adt(l_def, l_args) = l_ty.kind()
&& let ty::Adt(r_def, r_args) = r_ty.kind()
&& cx.tcx.is_lang_item(l_def.did(), LangItem::Option)
&& cx.tcx.is_lang_item(r_def.did(), LangItem::Option)
&& let Some(l_some_arg) = l_args.get(0)
&& let Some(r_some_arg) = r_args.get(0)
&& l_some_arg.expect_ty().is_fn()
&& r_some_arg.expect_ty().is_fn()
if (is_like_fn_ptr(l_ty) && is_like_fn_ptr(r_ty))
|| (is_option_of_like_fn_ptr(l_ty) && is_option_of_like_fn_ptr(r_ty))
{
// both operands are `Option<{function ptr}>`
return cx.emit_span_lint(
UNPREDICTABLE_FUNCTION_POINTER_COMPARISONS,
e.span,
UnpredictableFunctionPointerComparisons::Warn,
);
// both operands are vaguely function pointer shaped, fallthrough
} else {
// types are not function pointers, nothing to do
return;
}

// Let's try to suggest `ptr::fn_addr_eq` if/when possible.

let is_eq_ne = matches!(cmpop, ComparisonOp::BinOp(hir::BinOpKind::Eq | hir::BinOpKind::Ne));

if !is_eq_ne {
// Neither `==` nor `!=`, we can't suggest `ptr::fn_addr_eq`, just show the warning.
return cx.emit_span_lint(
UNPREDICTABLE_FUNCTION_POINTER_COMPARISONS,
e.span,
UnpredictableFunctionPointerComparisons::Warn,
);
}

let (Some(l_span), Some(r_span)) =
(l.span.find_ancestor_inside(e.span), r.span.find_ancestor_inside(e.span))
else {
// No appropriate spans for the left and right operands, just show the warning.
return cx.emit_span_lint(
UNPREDICTABLE_FUNCTION_POINTER_COMPARISONS,
e.span,
UnpredictableFunctionPointerComparisons::Warn,
);
};

let ne = if cmpop == ComparisonOp::BinOp(hir::BinOpKind::Ne) { "!" } else { "" };

// `ptr::fn_addr_eq` only works with raw pointer, deref any references.
let deref_left = &*"*".repeat(l_ty_refs);
let deref_right = &*"*".repeat(r_ty_refs);
// If the comparison is either == or !=, both types are functions (and not NonNull<Code>, etc),
// spans for left and right operators are available, and std/core crate can be found suggest
// using `fn_addr_eq`.
//
// Otherwise just show a warning.
let lint = if matches!(cmpop, ComparisonOp::BinOp(hir::BinOpKind::Eq | hir::BinOpKind::Ne))
&& l_ty.is_fn()
&& r_ty.is_fn()
&& let Some(l_span) = l.span.find_ancestor_inside(e.span)
&& let Some(r_span) = r.span.find_ancestor_inside(e.span)
&& let Some(krate) = std_or_core(cx)
{
let ne = if cmpop == ComparisonOp::BinOp(hir::BinOpKind::Ne) { "!" } else { "" };

let left = e.span.shrink_to_lo().until(l_span.shrink_to_lo());
let middle = l_span.shrink_to_hi().until(r_span.shrink_to_lo());
let right = r_span.shrink_to_hi().until(e.span.shrink_to_hi());
// `ptr::fn_addr_eq` only works with raw pointer, deref any references.
let deref_left = "*".repeat(l_ty_refs);
let deref_right = "*".repeat(r_ty_refs);

let Some(krate) = std_or_core(cx) else {
return cx.emit_span_lint(
UNPREDICTABLE_FUNCTION_POINTER_COMPARISONS,
e.span,
UnpredictableFunctionPointerComparisons::Warn,
);
};
let left = e.span.shrink_to_lo().until(l_span.shrink_to_lo());
let middle = l_span.shrink_to_hi().until(r_span.shrink_to_lo());
let right = r_span.shrink_to_hi().until(e.span.shrink_to_hi());

let sugg =
// We only check for a right cast as `FnDef` == `FnPtr` is not possible,
// only `FnPtr == FnDef` is possible.
if !r_ty.is_fn_ptr() {
let sugg = if !r_ty.is_fn_ptr() {
let fn_sig = r_ty.fn_sig(cx.tcx);

UnpredictableFunctionPointerComparisonsSuggestion::FnAddrEqWithCast {
Expand All @@ -624,11 +604,12 @@ fn lint_fn_pointer<'tcx>(
}
};

cx.emit_span_lint(
UNPREDICTABLE_FUNCTION_POINTER_COMPARISONS,
e.span,
UnpredictableFunctionPointerComparisons::Suggestion { sugg },
);
UnpredictableFunctionPointerComparisons::Suggestion { sugg }
} else {
UnpredictableFunctionPointerComparisons::Warn
};

cx.emit_span_lint(UNPREDICTABLE_FUNCTION_POINTER_COMPARISONS, e.span, lint);
}

impl<'tcx> LateLintPass<'tcx> for TypeLimits {
Expand Down
52 changes: 52 additions & 0 deletions compiler/rustc_middle/src/ty/sty.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1661,6 +1661,58 @@ impl<'tcx> Ty<'tcx> {
}
}

/// Returns true if `self` is the provided `lang_item`.
#[inline]
pub fn is_lang_item(self, tcx: TyCtxt<'_>, lang_item: LangItem) -> bool {
let def_id = match *self.kind() {
ty::Adt(adt_def, _) => adt_def.did(),

ty::FnDef(def_id, _) | ty::Foreign(def_id) => def_id,

ty::Alias(_, alias) => match alias.kind {
ty::AliasTyKind::Projection { def_id }
| ty::AliasTyKind::Inherent { def_id }
| ty::AliasTyKind::Opaque { def_id }
| ty::AliasTyKind::Free { def_id } => def_id,
},

// Do not have a def id of their own
ty::Bool
| ty::Char
| ty::Int(_)
| ty::Uint(_)
| ty::Str
| ty::Pat(..)
| ty::Array(..)
| ty::Slice(..)
| ty::RawPtr(..)
| ty::Ref(..)
| ty::Tuple(_)
| ty::FnPtr(..)
| ty::UnsafeBinder(_)
| ty::Placeholder(..)
| ty::Param(_)
| ty::Infer(_)
| ty::Bound(..)
| ty::Error(_)
| ty::Never
| ty::Float(_)
| ty::View(..) => return false,

// could technically use the principal trait def id,
// but that feels more confusing than helpful
ty::Dynamic(..) => return false,

// have a def id, but can't be marked as a lang item
ty::Closure(_def_id, _)
| ty::CoroutineClosure(_def_id, _)
| ty::Coroutine(_def_id, _)
| ty::CoroutineWitness(_def_id, _) => return false,
};

tcx.is_lang_item(def_id, lang_item)
}

/// Returns a list of tuple type arguments.
///
/// Panics when called on anything but a tuple.
Expand Down
1 change: 1 addition & 0 deletions src/bootstrap/src/core/builder/cargo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -762,6 +762,7 @@ impl Builder<'_> {
&& allow_dirty
{
cargo.arg("--allow-dirty");
cargo.arg("--broken-code");
}

let build_compiler_stage = if compiler.stage == 0 && self.local_rebuild {
Expand Down
4 changes: 2 additions & 2 deletions src/tools/clippy/clippy_lints/src/assert_is_empty.rs
Original file line number Diff line number Diff line change
Expand Up @@ -240,7 +240,7 @@ fn suggestion_for_type<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> Option<(&'
/// through `as_slice()` because they do not implement `PartialEq`. `VecDeque<T>` compares
/// against `VecDeque::new()`. Returns `None` for other receiver types.
fn suggestion_for_peeled_type<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> Option<(&'static str, String)> {
if ty.is_str() || ty.is_lang_item(cx, LangItem::String) {
if ty.is_str() || ty.is_lang_item(cx.tcx, LangItem::String) {
Some(("", "\"\"".to_string()))
} else if matches!(ty.kind(), ty::Slice(..)) {
Some(("", "[]".to_string()))
Expand All @@ -265,7 +265,7 @@ fn suggestion_for_peeled_type<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> Opt
/// print it on failure. Strings satisfy this directly; sequence-like values require printable,
/// self-comparable elements. Returns `false` when either trait bound is missing.
fn type_is_printable_and_comparable<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
if ty.is_str() || ty.is_lang_item(cx, LangItem::String) {
if ty.is_str() || ty.is_lang_item(cx.tcx, LangItem::String) {
return true;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ fn match_acceptable_type(cx: &LateContext<'_>, local: &LetStmt<'_>) -> bool {
| sym::Vec
| sym::VecDeque
)
) || ty.is_lang_item(cx, LangItem::String)
) || ty.is_lang_item(cx.tcx, LangItem::String)
}

fn has_no_read_access<'tcx, T: Visitable<'tcx>>(cx: &LateContext<'tcx>, id: HirId, block: T) -> bool {
Expand Down
2 changes: 1 addition & 1 deletion src/tools/clippy/clippy_lints/src/drop_forget_ref.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ impl<'tcx> LateLintPass<'tcx> for DropForgetRef {
sym::mem_forget if arg_ty.is_ref() => return,
sym::mem_drop if is_copy && !drop_is_single_call_in_arm => return,
sym::mem_forget if is_copy => return,
sym::mem_drop if arg_ty.is_lang_item(cx, LangItem::ManuallyDrop) => return,
sym::mem_drop if arg_ty.is_lang_item(cx.tcx, LangItem::ManuallyDrop) => return,
sym::mem_drop
if !(arg_ty.needs_drop(cx.tcx, cx.typing_env())
|| is_must_use_func_call(cx, arg)
Expand Down
2 changes: 1 addition & 1 deletion src/tools/clippy/clippy_lints/src/format_args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -533,7 +533,7 @@ impl<'tcx> FormatArgsExpr<'_, 'tcx> {
if let Some(placeholder_span) = placeholder.span
&& *options != FormatOptions::default()
&& let ty = self.cx.typeck_results().expr_ty(arg).peel_refs()
&& ty.is_lang_item(self.cx, LangItem::FormatArguments)
&& ty.is_lang_item(self.cx.tcx, LangItem::FormatArguments)
{
span_lint_and_then(
self.cx,
Expand Down
3 changes: 1 addition & 2 deletions src/tools/clippy/clippy_lints/src/format_push_string.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use clippy_utils::diagnostics::span_lint_and_then;
use clippy_utils::macros::{FormatArgsStorage, format_args_inputs_span, root_macro_call_first_node};
use clippy_utils::res::MaybeDef as _;
use clippy_utils::source::{snippet_with_applicability, snippet_with_context};
use clippy_utils::sym;
use rustc_attr_ir::lang_items::LangItem;
Expand Down Expand Up @@ -193,5 +192,5 @@ fn is_string(cx: &LateContext<'_>, e: &Expr<'_>) -> bool {
cx.typeck_results()
.expr_ty(e)
.peel_refs()
.is_lang_item(cx, LangItem::String)
.is_lang_item(cx.tcx, LangItem::String)
}
3 changes: 1 addition & 2 deletions src/tools/clippy/clippy_lints/src/from_str_radix_10.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use clippy_config::Conf;
use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::msrvs::{self, Msrv};
use clippy_utils::res::MaybeDef as _;
use clippy_utils::source::snippet_opt;
use clippy_utils::sugg::Sugg;
use clippy_utils::{is_in_const_context, is_integer_literal, sym};
Expand Down Expand Up @@ -142,5 +141,5 @@ fn get_integer_ty<'tcx>(

/// Checks if a Ty is `String` or `&str`
fn is_ty_stringish(cx: &LateContext<'_>, ty: Ty<'_>) -> bool {
ty.is_lang_item(cx, LangItem::String) || ty.peel_refs().is_str()
ty.is_lang_item(cx.tcx, LangItem::String) || ty.peel_refs().is_str()
}
3 changes: 1 addition & 2 deletions src/tools/clippy/clippy_lints/src/inherent_to_string.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
use clippy_utils::diagnostics::span_lint_and_help;
use clippy_utils::res::MaybeDef as _;
use clippy_utils::ty::implements_trait;
use clippy_utils::{return_ty, trait_ref_of_method};
use rustc_abi::ExternAbi;
Expand Down Expand Up @@ -108,7 +107,7 @@ impl<'tcx> LateLintPass<'tcx> for InherentToString {
&& impl_item.generics.params.iter().all(|p| matches!(p.kind, GenericParamKind::Lifetime { .. }))
&& !impl_item.span.from_expansion()
// Check if return type is String
&& return_ty(cx, impl_item.owner_id).is_lang_item(cx, LangItem::String)
&& return_ty(cx, impl_item.owner_id).is_lang_item(cx.tcx, LangItem::String)
// Filters instances of to_string which are required by a trait
&& trait_ref_of_method(cx, impl_item.owner_id).is_none()
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::ops::ControlFlow;

use clippy_utils::diagnostics::span_lint_hir_and_then;
use clippy_utils::res::{MaybeDef as _, MaybeResPath as _};
use clippy_utils::res::MaybeResPath as _;
use clippy_utils::visitors::for_each_expr;
use clippy_utils::{eq_expr_value, higher, sym};
use rustc_attr_ir::lang_items::LangItem;
Expand Down Expand Up @@ -82,7 +82,7 @@ fn check_index_usage<'tcx>(
return;
};

let is_string_like = |ty: Ty<'_>| ty.is_str() || ty.is_lang_item(cx, LangItem::String);
let is_string_like = |ty: Ty<'_>| ty.is_str() || ty.is_lang_item(cx.tcx, LangItem::String);
let message = match parent_expr.kind {
ExprKind::MethodCall(segment, recv, ..)
// We currently only lint `str` methods (which `String` can deref to), so a `.is_str()` check is sufficient here
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use super::EXPLICIT_ITER_LOOP;
use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::msrvs::{self, Msrv};
use clippy_utils::res::MaybeDef as _;
use clippy_utils::source::snippet_with_context;
use clippy_utils::sym;
use clippy_utils::ty::{
Expand Down Expand Up @@ -129,7 +128,7 @@ fn is_ref_iterable<'tcx>(
let self_ty = typeck.expr_ty(self_arg);
let self_is_copy = is_copy(cx, self_ty);

if self_ty.peel_refs().is_lang_item(cx, LangItem::OwnedBox) && !msrv.meets(cx, msrvs::BOX_INTO_ITER) {
if self_ty.peel_refs().is_lang_item(cx.tcx, LangItem::OwnedBox) && !msrv.meets(cx, msrvs::BOX_INTO_ITER) {
return None;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ fn needs_ref_to_cmp(cx: &LateContext<'_>, ty: Ty<'_>) -> bool {
ty.is_char()
|| *ty.kind() == ty::Uint(UintTy::U8)
|| ty.is_diag_item(cx, sym::Vec)
|| ty.is_lang_item(cx, LangItem::String)
|| ty.is_lang_item(cx.tcx, LangItem::String)
}

impl LateLintPass<'_> for ManualIgnoreCaseCmp {
Expand Down
Loading
Loading