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

46 files changed

Lines changed: 339 additions & 90 deletions

File tree

Some content is hidden

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

‎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::{selfas ast,Generics,ItemKind,MetaItem,VariantData};
1+
use rustc_ast::{selfas 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
usecrate::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::{selfas ast,MetaItem};
1+
use rustc_ast::{selfas 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::{selfas ast,EnumDef,MetaItem};
1+
use rustc_ast::{selfas 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::{selfas 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
pubis_const:bool,
226226

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

230236
pub(crate)structMethodDef<'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:ifself.is_const{

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Auto merge of #135634 - joboet:trivial-clone, r=Mark-Simulacrum · rust-lang/rust@055d0d6 · GitHub
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

46 files changed

Lines changed: 339 additions & 90 deletions

File tree

Some content is hidden

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

‎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::{selfas ast,Generics,ItemKind,MetaItem,VariantData};
1+
use rustc_ast::{selfas 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
usecrate::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::{selfas ast,MetaItem};
1+
use rustc_ast::{selfas 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::{selfas ast,EnumDef,MetaItem};
1+
use rustc_ast::{selfas 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::{selfas 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
pubis_const:bool,
226226

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

230236
pub(crate)structMethodDef<'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:ifself.is_const{

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' Auto merge of #135634 - joboet:trivial-clone, r=Mark-Simulacrum · rust-lang/rust@055d0d6 · GitHub
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

46 files changed

Lines changed: 339 additions & 90 deletions

File tree

Some content is hidden

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

‎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::{selfas ast,Generics,ItemKind,MetaItem,VariantData};
1+
use rustc_ast::{selfas 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
usecrate::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::{selfas ast,MetaItem};
1+
use rustc_ast::{selfas 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::{selfas ast,EnumDef,MetaItem};
1+
use rustc_ast::{selfas 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::{selfas 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
pubis_const:bool,
226226

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

230236
pub(crate)structMethodDef<'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:ifself.is_const{

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' Auto merge of #135634 - joboet:trivial-clone, r=Mark-Simulacrum · rust-lang/rust@055d0d6 · GitHub
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

46 files changed

Lines changed: 339 additions & 90 deletions

File tree

Some content is hidden

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

‎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::{selfas ast,Generics,ItemKind,MetaItem,VariantData};
1+
use rustc_ast::{selfas 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
usecrate::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::{selfas ast,MetaItem};
1+
use rustc_ast::{selfas 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::{selfas ast,EnumDef,MetaItem};
1+
use rustc_ast::{selfas 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::{selfas 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
pubis_const:bool,
226226

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

230236
pub(crate)structMethodDef<'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:ifself.is_const{

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ' Auto merge of #135634 - joboet:trivial-clone, r=Mark-Simulacrum · rust-lang/rust@055d0d6 · GitHub
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

46 files changed

Lines changed: 339 additions & 90 deletions

File tree

Some content is hidden

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

‎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::{selfas ast,Generics,ItemKind,MetaItem,VariantData};
1+
use rustc_ast::{selfas 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
usecrate::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::{selfas ast,MetaItem};
1+
use rustc_ast::{selfas 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::{selfas ast,EnumDef,MetaItem};
1+
use rustc_ast::{selfas 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::{selfas 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
pubis_const:bool,
226226

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

230236
pub(crate)structMethodDef<'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:ifself.is_const{

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' Auto merge of #135634 - joboet:trivial-clone, r=Mark-Simulacrum · rust-lang/rust@055d0d6 · GitHub
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

46 files changed

Lines changed: 339 additions & 90 deletions

File tree

Some content is hidden

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

‎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::{selfas ast,Generics,ItemKind,MetaItem,VariantData};
1+
use rustc_ast::{selfas 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
usecrate::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::{selfas ast,MetaItem};
1+
use rustc_ast::{selfas 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::{selfas ast,EnumDef,MetaItem};
1+
use rustc_ast::{selfas 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::{selfas 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
pubis_const:bool,
226226

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

230236
pub(crate)structMethodDef<'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:ifself.is_const{

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' Auto merge of #135634 - joboet:trivial-clone, r=Mark-Simulacrum · rust-lang/rust@055d0d6 · GitHub
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

46 files changed

Lines changed: 339 additions & 90 deletions

File tree

Some content is hidden

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

‎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::{selfas ast,Generics,ItemKind,MetaItem,VariantData};
1+
use rustc_ast::{selfas 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
usecrate::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::{selfas ast,MetaItem};
1+
use rustc_ast::{selfas 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::{selfas ast,EnumDef,MetaItem};
1+
use rustc_ast::{selfas 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::{selfas 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
pubis_const:bool,
226226

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

230236
pub(crate)structMethodDef<'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:ifself.is_const{

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })(); Auto merge of #135634 - joboet:trivial-clone, r=Mark-Simulacrum · rust-lang/rust@055d0d6 · GitHub
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

46 files changed

Lines changed: 339 additions & 90 deletions

File tree

Some content is hidden

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

‎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::{selfas ast,Generics,ItemKind,MetaItem,VariantData};
1+
use rustc_ast::{selfas 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
usecrate::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::{selfas ast,MetaItem};
1+
use rustc_ast::{selfas 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::{selfas ast,EnumDef,MetaItem};
1+
use rustc_ast::{selfas 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::{selfas 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
pubis_const:bool,
226226

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

230236
pub(crate)structMethodDef<'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:ifself.is_const{

0 commit comments

Comments
 (0)