Skip to content

Commit 055d0d6

Browse files
committed
Auto merge of #135634 - joboet:trivial-clone, r=Mark-Simulacrum
stop specializing on `Copy` fixes #132442 `std` specializes on `Copy` to optimize certain library functions such as `clone_from_slice`. This is unsound, however, as the `Copy` implementation may not be always applicable because of lifetime bounds, which specialization does not take into account; the result being that values are copied even though they are not `Copy`. For instance, this code: ```rust struct SometimesCopy<'a>(&'a Cell<bool>); impl<'a> Clone for SometimesCopy<'a> { fn clone(&self) -> Self { self.0.set(true); Self(self.0) } } impl Copy for SometimesCopy<'static> {} let clone_called = Cell::new(false); // As SometimesCopy<'clone_called> is not 'static, this must run `clone`, // setting the value to `true`. let _ = [SometimesCopy(&clone_called)].clone(); assert!(clone_called.get()); ``` should not panic, but does ([playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=6be7a48cad849d8bd064491616fdb43c)). To solve this, this PR introduces a new `unsafe` trait: `TrivialClone`. This trait may be implemented whenever the `Clone` implementation is equivalent to copying the value (so e.g. `fn clone(&self) -> Self { *self }`). Because of lifetime erasure, there is no way for the `Clone` implementation to observe lifetime bounds, meaning that even if the `TrivialClone` has stricter bounds than the `Clone` implementation, its invariant still holds. Therefore, it is sound to specialize on `TrivialClone`. I've changed all `Copy` specializations in the standard library to specialize on `TrivialClone` instead. Unfortunately, the unsound `#[rustc_unsafe_specialization_marker]` attribute on `Copy` cannot be removed in this PR as `hashbrown` still depends on it. I'll make a PR updating `hashbrown` once this lands. With `Copy` no longer being considered for specialization, this change alone would result in the standard library optimizations not being applied for user types unaware of `TrivialClone`. To avoid this and restore the optimizations in most cases, I have changed the expansion of `#[derive(Clone)]`: Currently, whenever both `Clone` and `Copy` are derived, the `clone` method performs a copy of the value. With this PR, the derive macro also adds a `TrivialClone` implementation to make this case observable using specialization. I anticipate that most users will use `#[derive(Clone, Copy)]` whenever both are applicable, so most users will still profit from the library optimizations. Unfortunately, Hyrum's law applies to this PR: there are some popular crates which rely on the precise specialization behaviour of `core` to implement "specialization at home", e.g. [`libAFL`](https://github.com/AFLplusplus/LibAFL/blob/89cff637025c1652c24e8d97a30a2e3d01f187a4/libafl_bolts/src/tuples.rs#L27-L49). I have no remorse for breaking such horrible code, but perhaps we should open other, better ways to satisfy their needs – for example by dropping the `'static` bound on `TypeId::of`...
2 parents a7b3715 + 16d2b55 commit 055d0d6

File tree

46 files changed

+339
-90
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

46 files changed

+339
-90
lines changed

compiler/rustc_builtin_macros/src/deriving/bounds.rs

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use rustc_ast::MetaItem;
1+
use rustc_ast::{MetaItem, Safety};
22
use rustc_expand::base::{Annotatable, ExtCtxt};
33
use rustc_span::Span;
44

@@ -24,6 +24,8 @@ pub(crate) fn expand_deriving_copy(
2424
associated_types: Vec::new(),
2525
is_const,
2626
is_staged_api_crate: cx.ecfg.features.staged_api(),
27+
safety: Safety::Default,
28+
document: true,
2729
};
2830

2931
trait_def.expand(cx, mitem, item, push);
@@ -48,6 +50,8 @@ pub(crate) fn expand_deriving_const_param_ty(
4850
associated_types: Vec::new(),
4951
is_const,
5052
is_staged_api_crate: cx.ecfg.features.staged_api(),
53+
safety: Safety::Default,
54+
document: true,
5155
};
5256

5357
trait_def.expand(cx, mitem, item, push);

compiler/rustc_builtin_macros/src/deriving/clone.rs

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
1-
use rustc_ast::{self as ast, Generics, ItemKind, MetaItem, VariantData};
1+
use rustc_ast::{self as ast, Generics, ItemKind, MetaItem, Safety, VariantData};
22
use rustc_data_structures::fx::FxHashSet;
33
use rustc_expand::base::{Annotatable, ExtCtxt};
4-
use rustc_span::{Ident, Span, kw, sym};
4+
use rustc_span::{DUMMY_SP, Ident, Span, kw, sym};
55
use thin_vec::{ThinVec, thin_vec};
66

77
use crate::deriving::generic::ty::*;
@@ -68,6 +68,29 @@ pub(crate) fn expand_deriving_clone(
6868
_ => cx.dcx().span_bug(span, "`#[derive(Clone)]` on trait item or impl item"),
6969
}
7070

71+
// If the clone method is just copying the value, also mark the type as
72+
// `TrivialClone` to allow some library optimizations.
73+
if is_simple {
74+
let trivial_def = TraitDef {
75+
span,
76+
path: path_std!(clone::TrivialClone),
77+
skip_path_as_bound: false,
78+
needs_copy_as_bound_if_packed: true,
79+
additional_bounds: bounds.clone(),
80+
supports_unions: true,
81+
methods: Vec::new(),
82+
associated_types: Vec::new(),
83+
is_const,
84+
is_staged_api_crate: cx.ecfg.features.staged_api(),
85+
safety: Safety::Unsafe(DUMMY_SP),
86+
// `TrivialClone` is not part of an API guarantee, so it shouldn't
87+
// appear in rustdoc output.
88+
document: false,
89+
};
90+
91+
trivial_def.expand_ext(cx, mitem, item, push, true);
92+
}
93+
7194
let trait_def = TraitDef {
7295
span,
7396
path: path_std!(clone::Clone),
@@ -88,6 +111,8 @@ pub(crate) fn expand_deriving_clone(
88111
associated_types: Vec::new(),
89112
is_const,
90113
is_staged_api_crate: cx.ecfg.features.staged_api(),
114+
safety: Safety::Default,
115+
document: true,
91116
};
92117

93118
trait_def.expand_ext(cx, mitem, item, push, is_simple)

compiler/rustc_builtin_macros/src/deriving/cmp/eq.rs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use rustc_ast::{self as ast, MetaItem};
1+
use rustc_ast::{self as ast, MetaItem, Safety};
22
use rustc_data_structures::fx::FxHashSet;
33
use rustc_expand::base::{Annotatable, ExtCtxt};
44
use rustc_span::{Span, sym};
@@ -44,6 +44,8 @@ pub(crate) fn expand_deriving_eq(
4444
associated_types: Vec::new(),
4545
is_const,
4646
is_staged_api_crate: cx.ecfg.features.staged_api(),
47+
safety: Safety::Default,
48+
document: true,
4749
};
4850
trait_def.expand_ext(cx, mitem, item, push, true)
4951
}

compiler/rustc_builtin_macros/src/deriving/cmp/ord.rs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use rustc_ast::MetaItem;
1+
use rustc_ast::{MetaItem, Safety};
22
use rustc_expand::base::{Annotatable, ExtCtxt};
33
use rustc_span::{Ident, Span, sym};
44
use thin_vec::thin_vec;
@@ -35,6 +35,8 @@ pub(crate) fn expand_deriving_ord(
3535
associated_types: Vec::new(),
3636
is_const,
3737
is_staged_api_crate: cx.ecfg.features.staged_api(),
38+
safety: Safety::Default,
39+
document: true,
3840
};
3941

4042
trait_def.expand(cx, mitem, item, push)

compiler/rustc_builtin_macros/src/deriving/cmp/partial_eq.rs

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use rustc_ast::{BinOpKind, BorrowKind, Expr, ExprKind, MetaItem, Mutability};
1+
use rustc_ast::{BinOpKind, BorrowKind, Expr, ExprKind, MetaItem, Mutability, Safety};
22
use rustc_expand::base::{Annotatable, ExtCtxt};
33
use rustc_span::{Span, sym};
44
use thin_vec::thin_vec;
@@ -30,6 +30,8 @@ pub(crate) fn expand_deriving_partial_eq(
3030
associated_types: Vec::new(),
3131
is_const: false,
3232
is_staged_api_crate: cx.ecfg.features.staged_api(),
33+
safety: Safety::Default,
34+
document: true,
3335
};
3436
structural_trait_def.expand(cx, mitem, item, push);
3537

@@ -59,6 +61,8 @@ pub(crate) fn expand_deriving_partial_eq(
5961
associated_types: Vec::new(),
6062
is_const,
6163
is_staged_api_crate: cx.ecfg.features.staged_api(),
64+
safety: Safety::Default,
65+
document: true,
6266
};
6367
trait_def.expand(cx, mitem, item, push)
6468
}

compiler/rustc_builtin_macros/src/deriving/cmp/partial_ord.rs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use rustc_ast::{ExprKind, ItemKind, MetaItem, PatKind};
1+
use rustc_ast::{ExprKind, ItemKind, MetaItem, PatKind, Safety};
22
use rustc_expand::base::{Annotatable, ExtCtxt};
33
use rustc_span::{Ident, Span, sym};
44
use thin_vec::thin_vec;
@@ -65,6 +65,8 @@ pub(crate) fn expand_deriving_partial_ord(
6565
associated_types: Vec::new(),
6666
is_const,
6767
is_staged_api_crate: cx.ecfg.features.staged_api(),
68+
safety: Safety::Default,
69+
document: true,
6870
};
6971
trait_def.expand(cx, mitem, item, push)
7072
}

compiler/rustc_builtin_macros/src/deriving/debug.rs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use rustc_ast::{self as ast, EnumDef, MetaItem};
1+
use rustc_ast::{self as ast, EnumDef, MetaItem, Safety};
22
use rustc_expand::base::{Annotatable, ExtCtxt};
33
use rustc_session::config::FmtDebug;
44
use rustc_span::{Ident, Span, Symbol, sym};
@@ -42,6 +42,8 @@ pub(crate) fn expand_deriving_debug(
4242
associated_types: Vec::new(),
4343
is_const,
4444
is_staged_api_crate: cx.ecfg.features.staged_api(),
45+
safety: Safety::Default,
46+
document: true,
4547
};
4648
trait_def.expand(cx, mitem, item, push)
4749
}

compiler/rustc_builtin_macros/src/deriving/default.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,7 @@
11
use core::ops::ControlFlow;
22

3-
use rustc_ast as ast;
43
use rustc_ast::visit::visit_opt;
5-
use rustc_ast::{EnumDef, VariantData, attr};
4+
use rustc_ast::{self as ast, EnumDef, Safety, VariantData, attr};
65
use rustc_expand::base::{Annotatable, DummyResult, ExtCtxt};
76
use rustc_span::{ErrorGuaranteed, Ident, Span, kw, sym};
87
use smallvec::SmallVec;
@@ -52,6 +51,8 @@ pub(crate) fn expand_deriving_default(
5251
associated_types: Vec::new(),
5352
is_const,
5453
is_staged_api_crate: cx.ecfg.features.staged_api(),
54+
safety: Safety::Default,
55+
document: true,
5556
};
5657
trait_def.expand(cx, mitem, item, push)
5758
}

compiler/rustc_builtin_macros/src/deriving/from.rs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
use rustc_ast as ast;
2-
use rustc_ast::{ItemKind, VariantData};
2+
use rustc_ast::{ItemKind, Safety, VariantData};
33
use rustc_errors::MultiSpan;
44
use rustc_expand::base::{Annotatable, DummyResult, ExtCtxt};
55
use rustc_span::{Ident, Span, kw, sym};
@@ -127,6 +127,8 @@ pub(crate) fn expand_deriving_from(
127127
associated_types: Vec::new(),
128128
is_const,
129129
is_staged_api_crate: cx.ecfg.features.staged_api(),
130+
safety: Safety::Default,
131+
document: true,
130132
};
131133

132134
from_trait_def.expand(cx, mitem, annotatable, push);

compiler/rustc_builtin_macros/src/deriving/generic/mod.rs

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -225,6 +225,12 @@ pub(crate) struct TraitDef<'a> {
225225
pub is_const: bool,
226226

227227
pub is_staged_api_crate: bool,
228+
229+
/// The safety of the `impl`.
230+
pub safety: Safety,
231+
232+
/// Whether the added `impl` should appear in rustdoc output.
233+
pub document: bool,
228234
}
229235

230236
pub(crate) struct MethodDef<'a> {
@@ -826,13 +832,17 @@ impl<'a> TraitDef<'a> {
826832
)
827833
}
828834

835+
if !self.document {
836+
attrs.push(cx.attr_nested_word(sym::doc, sym::hidden, self.span));
837+
}
838+
829839
cx.item(
830840
self.span,
831841
attrs,
832842
ast::ItemKind::Impl(ast::Impl {
833843
generics: trait_generics,
834844
of_trait: Some(Box::new(ast::TraitImplHeader {
835-
safety: ast::Safety::Default,
845+
safety: self.safety,
836846
polarity: ast::ImplPolarity::Positive,
837847
defaultness: ast::Defaultness::Final,
838848
constness: if self.is_const {

0 commit comments

Comments
 (0)