Skip to content
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

Create unnecessary_send_constraint lint for &(dyn ... + Send) #110961

Open
wants to merge 21 commits into
base: master
Choose a base branch
from
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
6 changes: 6 additions & 0 deletions compiler/rustc_lint/messages.ftl
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,12 @@ lint_redundant_semicolons =
*[false] this semicolon
}

lint_unnecessary_send_constraint = constraining a reference to `Send` is meaningless
.suggestion = {$only_trait ->
[true] replace this with `std::any::Any`
Copy link
Member

Choose a reason for hiding this comment

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

Replacing by Any is a very strange suggestion. Why would type_id machinery be necessary? Can't the 'static bound cause a problem?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I wasn't sure what else to put, this is for the scenario where Send is the only trait specified (so removing it would be invalid)

*[false] remove this
}

lint_drop_trait_constraints =
bounds on `{$predicate}` are most likely incorrect, consider instead using `{$needs_drop}` to detect whether a type can be trivially dropped

Expand Down
3 changes: 3 additions & 0 deletions compiler/rustc_lint/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ mod passes;
mod redundant_semicolon;
mod traits;
mod types;
mod unnecessary_send_constraint;
mod unused;

pub use array_into_iter::ARRAY_INTO_ITER;
Expand Down Expand Up @@ -125,6 +126,7 @@ pub use passes::{EarlyLintPass, LateLintPass};
pub use rustc_session::lint::Level::{self, *};
pub use rustc_session::lint::{BufferedEarlyLint, FutureIncompatibleInfo, Lint, LintId};
pub use rustc_session::lint::{LintArray, LintPass};
use unnecessary_send_constraint::UnnecessarySendConstraint;

fluent_messages! { "../messages.ftl" }

Expand Down Expand Up @@ -242,6 +244,7 @@ late_lint_methods!(
OpaqueHiddenInferredBound: OpaqueHiddenInferredBound,
MultipleSupertraitUpcastable: MultipleSupertraitUpcastable,
MapUnitFn: MapUnitFn,
UnnecessarySendConstraint: UnnecessarySendConstraint,
]
]
);
Expand Down
9 changes: 9 additions & 0 deletions compiler/rustc_lint/src/lints.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1168,6 +1168,15 @@ pub struct RedundantSemicolonsDiag {
pub suggestion: Span,
}

// lint_unnecessary_send_constraint.rs
#[derive(LintDiagnostic)]
#[diag(lint_unnecessary_send_constraint)]
pub struct UnnecessarySendConstraintDiag {
pub only_trait: bool,
#[suggestion(code = "", applicability = "maybe-incorrect")]
pub suggestion: Span,
}

// traits.rs
pub struct DropTraitConstraintsDiag<'a> {
pub predicate: Predicate<'a>,
Expand Down
57 changes: 57 additions & 0 deletions compiler/rustc_lint/src/unnecessary_send_constraint.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
use rustc_span::sym;

use crate::hir;

use crate::{lints::UnnecessarySendConstraintDiag, LateContext, LateLintPass};

declare_lint! {
/// The `unnecessary_send_constraint` lints unnecessary constraint of references to `Send`.
///
/// ### Example
///
/// ```rust,compile_fail
/// #[deny(unnecessary_send_constraint)]
/// fn foo(_: &(dyn Any + Send)) {}
/// ```
///
/// {{produces}}
///
/// ### Explanation
///
/// Shared references cannot be sent across threads unless they have a `Sync` bound, so constraining them to `Send` without `Sync` is unnecessary.
pub UNNECESSARY_SEND_CONSTRAINT,
Warn,
"constraining a reference to `Send` without `Sync` is unnecessary, consider removing it"
Copy link
Member

@RalfJung RalfJung Jun 27, 2023

Choose a reason for hiding this comment

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

Shouldn't the recommendation be to replace Send by Sync? That seems more likely to be what the author intended.

Copy link
Member

Choose a reason for hiding this comment

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

See this comment: #110961 (comment)

In those situations, it stems from a Box<dyn Any + Send> to which a &dyn was made. It's easy to just copy Any + Send, but the Send part should be removed for shared references.

Copy link
Member

Choose a reason for hiding this comment

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

That seems like a fairly special case to me, I would not expect this to be common enough to warrant a general recommendation of dropping the Send. The more symmetric thing to do would be to have &dyn Any+Sync, to get a shared reference that can still be shared across thread boundaries. Of course then you'd need Box<dyn Any+Send+Sync> for the owned case.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

So it should recommend replacing Send with Sync instead? just confirming before making the change

}

declare_lint_pass!(UnnecessarySendConstraint => [UNNECESSARY_SEND_CONSTRAINT]);

impl<'tcx> LateLintPass<'tcx> for UnnecessarySendConstraint {
fn check_ty(&mut self, cx: &LateContext<'tcx>, ty: &'tcx hir::Ty<'tcx>) {
let hir::TyKind::Ref(
..,
hir::MutTy {
ty: hir::Ty {
kind: hir::TyKind::TraitObject(bounds, ..),
..
},
..
},
) = ty.kind else { return; };

let send = cx.tcx.get_diagnostic_item(sym::Send);

let send_bound = bounds.iter().find(|b| b.trait_ref.trait_def_id() == send);

if let Some(send_bound) = send_bound {
let only_trait = bounds.len() == 1;

cx.tcx.emit_spanned_lint(
UNNECESSARY_SEND_CONSTRAINT,
send_bound.trait_ref.hir_ref_id, // is this correct?
send_bound.span,
UnnecessarySendConstraintDiag { only_trait, suggestion: send_bound.span },
)
}
}
}
4 changes: 2 additions & 2 deletions library/core/src/any.rs
Original file line number Diff line number Diff line change
Expand Up @@ -398,7 +398,7 @@ impl dyn Any + Send {
/// ```
/// use std::any::Any;
///
/// fn is_string(s: &(dyn Any + Send)) {
/// fn is_string(s: &dyn Any) {
/// if s.is::<String>() {
/// println!("It's a string!");
/// } else {
Expand All @@ -422,7 +422,7 @@ impl dyn Any + Send {
/// ```
/// use std::any::Any;
///
/// fn print_if_string(s: &(dyn Any + Send)) {
/// fn print_if_string(s: &dyn Any) {
/// if let Some(string) = s.downcast_ref::<String>() {
/// println!("It's a string({}): '{}'", string.len(), string);
/// } else {
Expand Down
1 change: 1 addition & 0 deletions library/core/src/cell.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2246,6 +2246,7 @@ impl<T: CoerceUnsized<U>, U> CoerceUnsized<SyncUnsafeCell<U>> for SyncUnsafeCell
impl<T: DispatchFromDyn<U>, U> DispatchFromDyn<SyncUnsafeCell<U>> for SyncUnsafeCell<T> {}

#[allow(unused)]
#[cfg_attr(not(bootstrap), allow(unnecessary_send_constraint))]
fn assert_coerce_unsized(
a: UnsafeCell<&i32>,
b: SyncUnsafeCell<&i32>,
Expand Down
2 changes: 1 addition & 1 deletion library/core/src/panic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,5 +107,5 @@ pub unsafe trait BoxMeUp {
fn take_box(&mut self) -> *mut (dyn Any + Send);

/// Just borrow the contents.
fn get(&mut self) -> &(dyn Any + Send);
fn get(&mut self) -> &dyn Any;
}
6 changes: 3 additions & 3 deletions library/core/src/panic/panic_info.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ use crate::panic::Location;
#[stable(feature = "panic_hooks", since = "1.10.0")]
#[derive(Debug)]
pub struct PanicInfo<'a> {
payload: &'a (dyn Any + Send),
payload: &'a dyn Any,
message: Option<&'a fmt::Arguments<'a>>,
location: &'a Location<'a>,
can_unwind: bool,
Expand Down Expand Up @@ -54,7 +54,7 @@ impl<'a> PanicInfo<'a> {
)]
#[doc(hidden)]
#[inline]
pub fn set_payload(&mut self, info: &'a (dyn Any + Send)) {
pub fn set_payload(&mut self, info: &'a dyn Any) {
self.payload = info;
}

Expand All @@ -81,7 +81,7 @@ impl<'a> PanicInfo<'a> {
/// ```
#[must_use]
#[stable(feature = "panic_hooks", since = "1.10.0")]
pub fn payload(&self) -> &(dyn Any + Send) {
pub fn payload(&self) -> &dyn Any {
self.payload
}

Expand Down
2 changes: 1 addition & 1 deletion library/core/src/panicking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
//! ```
//!
//! This definition allows for panicking with any general message, but it does not
//! allow for failing with a `Box<Any>` value. (`PanicInfo` just contains a `&(dyn Any + Send)`,
//! allow for failing with a `Box<Any>` value. (`PanicInfo` just contains a `&dyn Any`,
//! for which we fill in a dummy value in `PanicInfo::internal_constructor`.)
//! The reason for this is that core is not allowed to allocate.
//!
Expand Down
4 changes: 2 additions & 2 deletions library/std/src/io/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -695,7 +695,7 @@ impl Error {
#[stable(feature = "io_error_inner", since = "1.3.0")]
#[must_use]
#[inline]
pub fn get_ref(&self) -> Option<&(dyn error::Error + Send + Sync + 'static)> {
pub fn get_ref(&self) -> Option<&(dyn error::Error + Sync + 'static)> {
Copy link
Member

@steffahn steffahn Jan 16, 2024

Choose a reason for hiding this comment

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

dyn Error + Send + Sync has some API that dyn Error + Sync doesn’t have. Like an is method and a downcast_ref method.

Copy link
Member

Choose a reason for hiding this comment

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

Also, in any case, changing these methods is a breaking change the impact of which I’m not sure has been tested anywhere yet.

Copy link
Contributor

Choose a reason for hiding this comment

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

that dyn Error + Sync doesn’t have. Like an is method and a downcast_ref method.

dyn Error also implements is and downcast_* with exact the same signature.

Copy link
Contributor

Choose a reason for hiding this comment

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

dyn Error also implements is and downcast_* with exact the same signature.

Oops, my bad. We cannot use dyn Error's methods on dyn Error + Sync, though it seems odd to me.

match self.repr.data() {
ErrorData::Os(..) => None,
ErrorData::Simple(..) => None,
Expand Down Expand Up @@ -769,7 +769,7 @@ impl Error {
#[stable(feature = "io_error_inner", since = "1.3.0")]
#[must_use]
#[inline]
pub fn get_mut(&mut self) -> Option<&mut (dyn error::Error + Send + Sync + 'static)> {
pub fn get_mut(&mut self) -> Option<&mut (dyn error::Error + Sync + 'static)> {
Copy link
Member

Choose a reason for hiding this comment

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

This is a mutable reference. For &mut … + Send, the Send makes sense, doesn’t it?

match self.repr.data_mut() {
ErrorData::Os(..) => None,
ErrorData::Simple(..) => None,
Expand Down
13 changes: 5 additions & 8 deletions library/std/src/panicking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -220,10 +220,7 @@ pub fn take_hook() -> Box<dyn Fn(&PanicInfo<'_>) + 'static + Sync + Send> {
#[unstable(feature = "panic_update_hook", issue = "92649")]
pub fn update_hook<F>(hook_fn: F)
where
F: Fn(&(dyn Fn(&PanicInfo<'_>) + Send + Sync + 'static), &PanicInfo<'_>)
+ Sync
+ Send
+ 'static,
F: Fn(&(dyn Fn(&PanicInfo<'_>) + Sync + 'static), &PanicInfo<'_>) + Sync + Send + 'static,
{
if thread::panicking() {
panic!("cannot modify the panic hook from a panicking thread");
Expand Down Expand Up @@ -556,7 +553,7 @@ pub fn begin_panic_handler(info: &PanicInfo<'_>) -> ! {
Box::into_raw(Box::new(contents))
}

fn get(&mut self) -> &(dyn Any + Send) {
fn get(&mut self) -> &dyn Any {
self.fill()
}
}
Expand All @@ -568,7 +565,7 @@ pub fn begin_panic_handler(info: &PanicInfo<'_>) -> ! {
Box::into_raw(Box::new(self.0))
}

fn get(&mut self) -> &(dyn Any + Send) {
fn get(&mut self) -> &dyn Any {
&self.0
}
}
Expand Down Expand Up @@ -635,7 +632,7 @@ pub const fn begin_panic<M: Any + Send>(msg: M) -> ! {
Box::into_raw(data)
}

fn get(&mut self) -> &(dyn Any + Send) {
fn get(&mut self) -> &dyn Any {
match self.inner {
Some(ref a) => a,
None => process::abort(),
Expand Down Expand Up @@ -725,7 +722,7 @@ pub fn rust_panic_without_hook(payload: Box<dyn Any + Send>) -> ! {
Box::into_raw(mem::replace(&mut self.0, Box::new(())))
}

fn get(&mut self) -> &(dyn Any + Send) {
fn get(&mut self) -> &dyn Any {
&*self.0
}
}
Expand Down
2 changes: 1 addition & 1 deletion library/test/src/test_result.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ pub enum TestResult {
/// and associated data.
pub fn calc_result<'a>(
desc: &TestDesc,
task_result: Result<(), &'a (dyn Any + 'static + Send)>,
task_result: Result<(), &'a (dyn Any + 'static)>,
time_opts: &Option<time::TestTimeOptions>,
exec_time: &Option<time::TestExecTime>,
) -> TestResult {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
#![warn(unnecessary_send_constraint)]

use std::any::Any;

fn main() {}

fn fine(_a: &dyn Any) {}

fn should_replace_with_any(_a: &(dyn Send)) {}

fn should_remove_send(_a: &(dyn Any + Send)) {}

fn should_remove_send_duplicate(_a: &(dyn Any + Send)) {}