Skip to content

Add new UNSTABLE_INTRINSICS_WITH_STABLE_WRAPPER lint #12226

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5701,6 +5701,7 @@ Released 2018-09-13
[`unsound_collection_transmute`]: https://rust-lang.github.io/rust-clippy/master/index.html#unsound_collection_transmute
[`unstable_as_mut_slice`]: https://rust-lang.github.io/rust-clippy/master/index.html#unstable_as_mut_slice
[`unstable_as_slice`]: https://rust-lang.github.io/rust-clippy/master/index.html#unstable_as_slice
[`unstable_intrinsics_with_stable_wrapper`]: https://rust-lang.github.io/rust-clippy/master/index.html#unstable_intrinsics_with_stable_wrapper
[`unused_async`]: https://rust-lang.github.io/rust-clippy/master/index.html#unused_async
[`unused_collect`]: https://rust-lang.github.io/rust-clippy/master/index.html#unused_collect
[`unused_enumerate_index`]: https://rust-lang.github.io/rust-clippy/master/index.html#unused_enumerate_index
Expand Down
1 change: 1 addition & 0 deletions clippy_lints/src/declared_lints.rs
Original file line number Diff line number Diff line change
Expand Up @@ -712,6 +712,7 @@ pub(crate) static LINTS: &[&crate::LintInfo] = &[
crate::unnecessary_wraps::UNNECESSARY_WRAPS_INFO,
crate::unnested_or_patterns::UNNESTED_OR_PATTERNS_INFO,
crate::unsafe_removed_from_name::UNSAFE_REMOVED_FROM_NAME_INFO,
crate::unstable_intrinsics_with_stable_wrapper::UNSTABLE_INTRINSICS_WITH_STABLE_WRAPPER_INFO,
crate::unused_async::UNUSED_ASYNC_INFO,
crate::unused_io_amount::UNUSED_IO_AMOUNT_INFO,
crate::unused_peekable::UNUSED_PEEKABLE_INFO,
Expand Down
3 changes: 3 additions & 0 deletions clippy_lints/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -349,6 +349,7 @@ mod unnecessary_struct_initialization;
mod unnecessary_wraps;
mod unnested_or_patterns;
mod unsafe_removed_from_name;
mod unstable_intrinsics_with_stable_wrapper;
mod unused_async;
mod unused_io_amount;
mod unused_peekable;
Expand Down Expand Up @@ -1111,6 +1112,8 @@ pub fn register_lints(store: &mut rustc_lint::LintStore, conf: &'static Conf) {
});
store.register_late_pass(move |_| Box::new(incompatible_msrv::IncompatibleMsrv::new(msrv())));
store.register_late_pass(|_| Box::new(to_string_trait_impl::ToStringTraitImpl));
store
.register_late_pass(|_| Box::new(unstable_intrinsics_with_stable_wrapper::UnstableIntrinsicsWithStableWrapper));
// add lints here, do not remove this comment, it's used in `new_lint`
}

Expand Down
126 changes: 126 additions & 0 deletions clippy_lints/src/unstable_intrinsics_with_stable_wrapper.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
use rustc_hir::def::{DefKind, Res};
use rustc_hir::{Expr, ExprKind, Item, ItemKind, PathSegment, QPath};
use rustc_lint::{LateContext, LateLintPass};
use rustc_middle::ty::TyCtxt;
use rustc_resolve::rustdoc::{add_doc_fragment, attrs_to_doc_fragments};
use rustc_session::declare_lint_pass;
use rustc_span::def_id::DefId;
use rustc_span::{sym, Span};

use clippy_utils::diagnostics::span_lint;
use clippy_utils::{any_parent_has_attr, def_path_def_ids, match_any_def_paths};

use std::sync::OnceLock;

declare_clippy_lint! {
/// ### What it does
/// Detects usage of unstable intrinsics with safe wrappers.
///
/// ### Why is this bad?
/// It allows to have the same features without requiring to use the `core_intrinsics`
/// feature.
///
/// ### Example
/// ```no_run
/// # #![feature(core_intrinsics)]
/// use std::intrinsics::add_with_overflow;
///
/// add_with_overflow(12u32, 14);
/// ```
/// Use instead:
/// ```no_run
/// 12u32.overflowing_add(14);
/// ```
#[clippy::version = "1.77.0"]
pub UNSTABLE_INTRINSICS_WITH_STABLE_WRAPPER,
suspicious,
"Detects usage of unstable intrinsics with safe wrappers"
}

declare_lint_pass!(UnstableIntrinsicsWithStableWrapper => [UNSTABLE_INTRINSICS_WITH_STABLE_WRAPPER]);

fn get_doc(tcx: TyCtxt<'_>, fn_def_id: DefId) -> String {
let (fragments, _) =
attrs_to_doc_fragments(tcx.get_attrs_unchecked(fn_def_id).iter().map(|attr| (attr, None)), true);
let mut doc = String::new();
for fragment in &fragments {
add_doc_fragment(&mut doc, fragment);
}
doc
}

fn emit_if_is_unstable_intrinsic(
cx: &LateContext<'_>,
def_id: DefId,
expr_span: Span,
fn_name: &str,
segments: &[PathSegment<'_>],
) {
static FNS: OnceLock<Vec<DefId>> = OnceLock::new();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why not a DefIdMap?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think having a Vec will be a problem here, we don't have that many intrinsics anyway.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess. A benchmark is always handy, I just think it's cleaner at least and more greppable

let fns = FNS.get_or_init(|| {
let mod_def_id = def_path_def_ids(cx, &["core", "intrinsics"]).next().unwrap();
cx.tcx
.module_children(mod_def_id)
.iter()
.filter_map(|child| match child.res {
Res::Def(DefKind::Fn, fn_def_id) => Some(fn_def_id),
_ => None,
})
.filter(|fn_def_id| !get_doc(cx.tcx, *fn_def_id).contains("does not have a stable counterpart"))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Some intrinsics don't have this. For example is_val_statically_known or const_eval_select

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's probably best to at least check for "the stabilized version of this intrinsic is" after this too

.collect::<Vec<_>>()
});

if cx.tcx.is_intrinsic(def_id)
// This is to prevent false positives like "transmute".
&& segments.len() > 1
&& let Some(mod_def_id) = segments[segments.len() - 2].res.opt_def_id()
&& match_any_def_paths(cx, mod_def_id, &[
&["core", "intrinsics"],
&["std", "intrinsics"],
]).is_some()
{
for intrinsic in fns {
if *intrinsic == def_id {
span_lint(
cx,
UNSTABLE_INTRINSICS_WITH_STABLE_WRAPPER,
expr_span,
&format!(
"consider using the stable counterpart mentioned in the documentation \
(https://doc.rust-lang.org/stable/core/intrinsics/fn.{fn_name}.html)"
),
);
return;
}
}
}
}

impl<'tcx> LateLintPass<'tcx> for UnstableIntrinsicsWithStableWrapper {
fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'tcx>) {
if let ItemKind::Use(path, _) = item.kind {
for res in &path.res {
if let Some(use_def_id) = res.opt_def_id()
&& cx.tcx.def_kind(use_def_id) == DefKind::Fn
&& let Some(fn_name) = cx.tcx.opt_item_name(use_def_id)
{
emit_if_is_unstable_intrinsic(cx, use_def_id, path.span, fn_name.as_str(), path.segments);
}
}
}
}

fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) {
if let ExprKind::Call(call_expr, _) = expr.kind
&& let ExprKind::Path(QPath::Resolved(_, path)) = call_expr.kind
&& let Some(fn_def_id) = path.res.opt_def_id()
&& !fn_def_id.is_local()
// We get the function name instead from `path` because it could have been renamed.
&& let Some(fn_name) = cx.tcx.opt_item_name(fn_def_id)
&& let fn_name = fn_name.as_str()
&& !any_parent_has_attr(cx.tcx, expr.hir_id, sym::automatically_derived)
{
emit_if_is_unstable_intrinsic(cx, fn_def_id, expr.span, fn_name, path.segments);
}
}
}
7 changes: 6 additions & 1 deletion tests/ui/transmute.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
#![allow(dead_code, clippy::borrow_as_ptr, clippy::needless_lifetimes)]
#![allow(
dead_code,
clippy::borrow_as_ptr,
clippy::needless_lifetimes,
clippy::unstable_intrinsics_with_stable_wrapper
)]
//@no-rustfix
extern crate core;

Expand Down
Loading