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
12 changes: 12 additions & 0 deletions compiler/rustc_hir_analysis/messages.ftl
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,11 @@ hir_analysis_coercion_between_struct_same_note = expected coercion between the s

hir_analysis_coercion_between_struct_single_note = expected a single field to be coerced, none found

hir_analysis_conflict_impl_drop_and_pin_drop = conflicting implementations of `Drop::drop` and `Drop::pin_drop`
.drop_label = `drop(&mut self)` implemented here
.pin_drop_label = `pin_drop(&pin mut self)` implemented here
.suggestion = remove this implementation

hir_analysis_const_bound_for_non_const_trait = `{$modifier}` can only be applied to `const` traits
.label = can't be applied to `{$trait_name}`
.note = `{$trait_name}` can't be used with `{$modifier}` because it isn't `const`
Expand Down Expand Up @@ -441,6 +446,13 @@ hir_analysis_paren_sugar_attribute = the `#[rustc_paren_sugar]` attribute is a t
hir_analysis_parenthesized_fn_trait_expansion =
parenthesized trait syntax expands to `{$expanded_type}`

hir_analysis_pin_v2_without_pin_drop =
`{$adt_name}` must implement `pin_drop`
.note = `{$adt_name}` is marked `#[pin_v2]` here
.help = structurally pinned types must keep `Pin`'s safety contract
.pin_drop_sugg = implement `pin_drop` instead
.remove_pin_v2_sugg = remove the `#[pin_v2]` attribute if it is not intended for structurally pinning

hir_analysis_placeholder_not_allowed_item_signatures = the placeholder `_` is not allowed within types on item signatures for {$kind}
.label = not allowed in type signatures

Expand Down
72 changes: 71 additions & 1 deletion compiler/rustc_hir_analysis/src/check/always_applicable.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ use rustc_infer::traits::{ObligationCause, ObligationCauseCode};
use rustc_middle::span_bug;
use rustc_middle::ty::util::CheckRegions;
use rustc_middle::ty::{self, GenericArgsRef, Ty, TyCtxt, TypingMode};
use rustc_span::sym;
use rustc_trait_selection::regions::InferCtxtRegionExt;
use rustc_trait_selection::traits::{self, ObligationCtxt};

Expand Down Expand Up @@ -70,7 +71,11 @@ pub(crate) fn check_drop_impl(
drop_impl_did,
adt_def.did(),
adt_to_impl_args,
)
)?;

check_drop_xor_pin_drop(tcx, adt_def.did(), drop_impl_did)?;

Ok(())
}
_ => {
span_bug!(tcx.def_span(drop_impl_did), "incoherent impl of Drop");
Expand Down Expand Up @@ -291,3 +296,68 @@ fn ensure_impl_predicates_are_implied_by_item_defn<'tcx>(

Ok(())
}

/// This function checks at least and at most one of `Drop::drop` and `Drop::pin_drop` is implemented.
/// It also checks that `Drop::pin_drop` must be implemented if `#[pin_v2]` is present on the type.
fn check_drop_xor_pin_drop<'tcx>(
tcx: TyCtxt<'tcx>,
adt_def_id: DefId,
drop_impl_did: LocalDefId,
) -> Result<(), ErrorGuaranteed> {
let mut drop_span = None;
let mut pin_drop_span = None;
for item in tcx.associated_items(drop_impl_did).in_definition_order() {
match item.kind {
ty::AssocKind::Fn { name: sym::drop, .. } => {
drop_span = Some(tcx.def_span(item.def_id))
}
ty::AssocKind::Fn { name: sym::pin_drop, .. } => {
pin_drop_span = Some(tcx.def_span(item.def_id))
}
_ => {}
}
}

match (drop_span, pin_drop_span) {
(None, None) => {
if tcx.features().pin_ergonomics() {
return Err(tcx.dcx().emit_err(crate::errors::MissingOneOfTraitItem {
span: tcx.def_span(drop_impl_did),
note: None,
missing_items_msg: "drop`, `pin_drop".to_string(),
}));
} else {
return Err(tcx
.dcx()
.span_delayed_bug(tcx.def_span(drop_impl_did), "missing `Drop::drop`"));
}
}
(Some(span), None) => {
if tcx.adt_def(adt_def_id).is_pin_project() {
let pin_v2_span = tcx.get_attr(adt_def_id, sym::pin_v2).map(|attr| attr.span());
let adt_name = tcx.item_name(adt_def_id);
return Err(tcx.dcx().emit_err(crate::errors::PinV2WithoutPinDrop {
span,
pin_v2_span,
adt_name,
}));
}
}
(None, Some(span)) => {
if !tcx.features().pin_ergonomics() {
return Err(tcx.dcx().span_delayed_bug(
span,
"`Drop::pin_drop` should be guarded by the library feature gate",
));
}
}
(Some(drop_span), Some(pin_drop_span)) => {
return Err(tcx.dcx().emit_err(crate::errors::ConflictImplDropAndPinDrop {
span: tcx.def_span(drop_impl_did),
drop_span,
pin_drop_span,
}));
}
}
Ok(())
}
10 changes: 10 additions & 0 deletions compiler/rustc_hir_analysis/src/check/check.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ use rustc_middle::ty::{
TypeVisitable, TypeVisitableExt, fold_regions,
};
use rustc_session::lint::builtin::UNINHABITED_STATIC;
use rustc_span::sym;
use rustc_target::spec::{AbiMap, AbiMapping};
use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
use rustc_trait_selection::error_reporting::traits::on_unimplemented::OnUnimplementedDirective;
Expand Down Expand Up @@ -1278,6 +1279,15 @@ fn check_impl_items_against_trait<'tcx>(
if !is_implemented_here {
let full_impl_span = tcx.hir_span_with_body(tcx.local_def_id_to_hir_id(impl_id));
match tcx.eval_default_body_stability(trait_item_id, full_impl_span) {
// When the feature `pin_ergonomics` is disabled, we report `Drop::drop` is missing,
// instead of `Drop::drop` is unstable that might be confusing.
EvalResult::Deny { .. }
if !tcx.features().pin_ergonomics()
&& tcx.is_lang_item(trait_ref.def_id, hir::LangItem::Drop)
&& tcx.item_name(trait_item_id) == sym::drop =>
{
missing_items.push(tcx.associated_item(trait_item_id));
}
EvalResult::Deny { feature, reason, issue, .. } => default_body_is_unstable(
tcx,
full_impl_span,
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_hir_analysis/src/check/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ use rustc_middle::ty::{
use rustc_middle::{bug, span_bug};
use rustc_session::parse::feature_err;
use rustc_span::def_id::CRATE_DEF_ID;
use rustc_span::{BytePos, DUMMY_SP, Ident, Span, Symbol, kw, sym};
use rustc_span::{BytePos, DUMMY_SP, Ident, Span, Symbol, kw};
use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
use rustc_trait_selection::error_reporting::infer::ObligationCauseExt as _;
use rustc_trait_selection::error_reporting::traits::suggestions::ReturnsVisitor;
Expand Down
28 changes: 28 additions & 0 deletions compiler/rustc_hir_analysis/src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1708,3 +1708,31 @@ pub(crate) struct AsyncDropWithoutSyncDrop {
#[primary_span]
pub span: Span,
}

#[derive(Diagnostic)]
#[diag(hir_analysis_conflict_impl_drop_and_pin_drop)]
pub(crate) struct ConflictImplDropAndPinDrop {
#[primary_span]
pub span: Span,
#[label(hir_analysis_drop_label)]
pub drop_span: Span,
#[label(hir_analysis_pin_drop_label)]
pub pin_drop_span: Span,
}

#[derive(Diagnostic)]
#[diag(hir_analysis_pin_v2_without_pin_drop)]
#[help]
pub(crate) struct PinV2WithoutPinDrop {
#[primary_span]
#[suggestion(
hir_analysis_pin_drop_sugg,
code = "fn pin_drop(&pin mut self)",
applicability = "maybe-incorrect"
)]
pub span: Span,
#[note]
#[suggestion(hir_analysis_remove_pin_v2_sugg, code = "", applicability = "maybe-incorrect")]
pub pin_v2_span: Option<Span>,
pub adt_name: Symbol,
}
7 changes: 5 additions & 2 deletions compiler/rustc_hir_typeck/src/callee.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,12 @@ pub(crate) fn check_legal_trait_for_method_call(
receiver: Option<Span>,
expr_span: Span,
trait_id: DefId,
_body_id: DefId,
body_id: DefId,
) -> Result<(), ErrorGuaranteed> {
if tcx.is_lang_item(trait_id, LangItem::Drop) {
if tcx.is_lang_item(trait_id, LangItem::Drop)
// Allow calling `Drop::pin_drop` in `Drop::drop`
&& !tcx.is_lang_item(tcx.parent(body_id), LangItem::Drop)
{
let sugg = if let Some(receiver) = receiver.filter(|s| !s.is_empty()) {
errors::ExplicitDestructorCallSugg::Snippet {
lo: expr_span.shrink_to_lo(),
Expand Down
3 changes: 3 additions & 0 deletions compiler/rustc_mir_build/messages.ftl
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@ mir_build_borrow_of_moved_value = borrow of moved value
.value_borrowed_label = value borrowed here after move
.suggestion = borrow this binding in the pattern to avoid moving the value

mir_build_call_drop_explicitly_requires_unsafe =
call `{$function}` explicitly is unsafe and requires unsafe block

mir_build_call_to_deprecated_safe_fn_requires_unsafe =
call to deprecated safe function `{$function}` is unsafe and requires unsafe block
.note = consult the function's documentation for information on how to avoid undefined behavior
Expand Down
17 changes: 17 additions & 0 deletions compiler/rustc_mir_build/src/check_unsafety.rs
Original file line number Diff line number Diff line change
Expand Up @@ -542,6 +542,11 @@ impl<'a, 'tcx> Visitor<'a, 'tcx> for UnsafetyVisitor<'a, 'tcx> {
CallToFunctionWith { function: func_did, missing, build_enabled },
);
}
if let Some(trait_did) = self.tcx.trait_of_assoc(func_did)
&& self.tcx.is_lang_item(trait_did, hir::LangItem::Drop)
{
self.requires_unsafe(expr.span, CallDropExplicitly(func_did));
}
}
}
ExprKind::RawBorrow { arg, .. } => {
Expand Down Expand Up @@ -770,6 +775,8 @@ enum UnsafeOpKind {
build_enabled: Vec<Symbol>,
},
UnsafeBinderCast,
/// Calling `Drop::drop` or `Drop::pin_drop` explicitly.
CallDropExplicitly(DefId),
}

use UnsafeOpKind::*;
Expand Down Expand Up @@ -947,6 +954,9 @@ impl UnsafeOpKind {
unsafe_not_inherited_note,
},
),
CallDropExplicitly(_) => {
span_bug!(span, "`Drop::drop` or `Drop::pin_drop` should not be called explicitly")
}
}
}

Expand Down Expand Up @@ -1164,6 +1174,13 @@ impl UnsafeOpKind {
UnsafeBinderCast => {
dcx.emit_err(UnsafeBinderCastRequiresUnsafe { span, unsafe_not_inherited_note });
}
CallDropExplicitly(did) => {
dcx.emit_err(CallDropExplicitlyRequiresUnsafe {
span,
unsafe_not_inherited_note,
function: tcx.def_path_str(*did),
});
}
}
}
}
Expand Down
10 changes: 10 additions & 0 deletions compiler/rustc_mir_build/src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -532,6 +532,16 @@ pub(crate) struct UnsafeBinderCastRequiresUnsafeUnsafeOpInUnsafeFnAllowed {
pub(crate) unsafe_not_inherited_note: Option<UnsafeNotInheritedNote>,
}

#[derive(Diagnostic)]
#[diag(mir_build_call_drop_explicitly_requires_unsafe, code = E0133)]
pub(crate) struct CallDropExplicitlyRequiresUnsafe {
#[primary_span]
pub(crate) span: Span,
pub(crate) function: String,
#[subdiagnostic]
pub(crate) unsafe_not_inherited_note: Option<UnsafeNotInheritedNote>,
}

#[derive(Subdiagnostic)]
#[label(mir_build_unsafe_not_inherited)]
pub(crate) struct UnsafeNotInheritedNote {
Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_span/src/symbol.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1688,6 +1688,7 @@ symbols! {
pic,
pie,
pin,
pin_drop,
pin_ergonomics,
pin_macro,
pin_v2,
Expand Down
29 changes: 28 additions & 1 deletion library/core/src/ops/drop.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use crate::pin::Pin;

/// Custom code within the destructor.
///
/// When a value is no longer needed, Rust will run a "destructor" on that value.
Expand Down Expand Up @@ -237,5 +239,30 @@ pub const trait Drop {
/// [`mem::drop`]: drop
/// [`ptr::drop_in_place`]: crate::ptr::drop_in_place
#[stable(feature = "rust1", since = "1.0.0")]
fn drop(&mut self);
#[rustc_default_body_unstable(feature = "pin_ergonomics", issue = "130494")]
fn drop(&mut self) {
// SAFETY: `self` is pinned till after dropped.
unsafe { Drop::pin_drop(Pin::new_unchecked(self)) }
}

/// Execute the destructor for this type, but different to [`Drop::drop`], it requires `self`
/// to be pinned.
///
/// By implementing this method instead of [`Drop::drop`], the receiver type [`Pin<&mut Self>`]
/// makes sure that the value is pinned until it is deallocated (See [`std::pin` module docs] for
/// more details), which enables us to support field projections of `Self` type safely.
///
/// For types that support pin-projection (i.e., marked with `#[pin_v2]`), this method must be used.
///
/// For any type, at least and at most one of [`Drop::drop`] and [`Drop::pin_drop`] should be
/// implemented.
///
/// See also [`Drop::drop`] for more details.
///
/// [`Drop::drop`]: crate::ops::Drop::drop
/// [`Drop::pin_drop`]: crate::ops::Drop::pin_drop
/// [`Pin<&mut Self>`]: crate::pin::Pin
/// [`std::pin` module docs]: crate::pin
#[unstable(feature = "pin_ergonomics", issue = "130494")]
fn pin_drop(self: Pin<&mut Self>) {}
}
4 changes: 4 additions & 0 deletions tests/codegen-units/item-collection/drop-glue-eager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ struct StructWithDrop {

impl Drop for StructWithDrop {
//~ MONO_ITEM fn <StructWithDrop as std::ops::Drop>::drop
//~ MONO_ITEM fn <StructWithDrop as std::ops::Drop>::pin_drop
fn drop(&mut self) {}
}

Expand All @@ -24,6 +25,7 @@ enum EnumWithDrop {

impl Drop for EnumWithDrop {
//~ MONO_ITEM fn <EnumWithDrop as std::ops::Drop>::drop
//~ MONO_ITEM fn <EnumWithDrop as std::ops::Drop>::pin_drop
fn drop(&mut self) {}
}

Expand All @@ -34,6 +36,7 @@ enum EnumNoDrop {
// We should be able to monomorphize drops for struct with lifetimes.
impl<'a> Drop for StructWithDropAndLt<'a> {
//~ MONO_ITEM fn <StructWithDropAndLt<'_> as std::ops::Drop>::drop
//~ MONO_ITEM fn <StructWithDropAndLt<'_> as std::ops::Drop>::pin_drop
fn drop(&mut self) {}
}

Expand All @@ -52,5 +55,6 @@ struct StructWithLtAndPredicate<'a: 'a> {
// We should be able to monomorphize drops for struct with lifetimes.
impl<'a> Drop for StructWithLtAndPredicate<'a> {
//~ MONO_ITEM fn <StructWithLtAndPredicate<'_> as std::ops::Drop>::drop
//~ MONO_ITEM fn <StructWithLtAndPredicate<'_> as std::ops::Drop>::pin_drop
fn drop(&mut self) {}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ struct StructWithDtor(u32);

impl Drop for StructWithDtor {
//~ MONO_ITEM fn <StructWithDtor as std::ops::Drop>::drop
//~ MONO_ITEM fn <StructWithDtor as std::ops::Drop>::pin_drop
fn drop(&mut self) {}
}

Expand Down
1 change: 1 addition & 0 deletions tests/codegen-units/item-collection/generic-drop-glue.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ struct NonGenericWithDrop(#[allow(dead_code)] i32);

impl Drop for NonGenericWithDrop {
//~ MONO_ITEM fn <NonGenericWithDrop as std::ops::Drop>::drop
//~ MONO_ITEM fn <NonGenericWithDrop as std::ops::Drop>::pin_drop
fn drop(&mut self) {}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,5 +74,6 @@ struct PresentDrop;

impl Drop for PresentDrop {
//~ MONO_ITEM fn <PresentDrop as std::ops::Drop>::drop @@ non_generic_closures-cgu.0[External]
//~ MONO_ITEM fn <PresentDrop as std::ops::Drop>::pin_drop @@ non_generic_closures-cgu.0[External]
fn drop(&mut self) {}
}
2 changes: 2 additions & 0 deletions tests/codegen-units/item-collection/non-generic-drop-glue.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ struct StructWithDrop {

impl Drop for StructWithDrop {
//~ MONO_ITEM fn <StructWithDrop as std::ops::Drop>::drop
//~ MONO_ITEM fn <StructWithDrop as std::ops::Drop>::pin_drop
fn drop(&mut self) {}
}

Expand All @@ -25,6 +26,7 @@ enum EnumWithDrop {

impl Drop for EnumWithDrop {
//~ MONO_ITEM fn <EnumWithDrop as std::ops::Drop>::drop
//~ MONO_ITEM fn <EnumWithDrop as std::ops::Drop>::pin_drop
fn drop(&mut self) {}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ struct Leaf;

impl Drop for Leaf {
//~ MONO_ITEM fn <Leaf as std::ops::Drop>::drop
//~ MONO_ITEM fn <Leaf as std::ops::Drop>::pin_drop
fn drop(&mut self) {}
}

Expand Down
Loading
Loading