Skip to content

Commit fda3378

Browse files
committed
introduce negative_impls feature gate and document
They used to be covered by `optin_builtin_traits` but negative impls are now applicable to all traits, not just auto traits. This also adds docs in the unstable book for the current state of auto traits.
1 parent 6507170 commit fda3378

File tree

102 files changed

+330
-111
lines changed

Some content is hidden

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

102 files changed

+330
-111
lines changed
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
# `negative_impls`
2+
3+
The tracking issue for this feature is [#13231]
4+
5+
[#13231]: https://github.com/rust-lang/rust/issues/13231
6+
7+
----
8+
9+
With the feature gate `negative_impls`, you can write negative impls as well as positive ones:
10+
11+
```rust
12+
#![feature(negative_impls)]
13+
trait DerefMut { }
14+
impl<T: ?Sized> !DerefMut for &T { }
15+
```
16+
17+
Negative impls indicate a semver guarantee that the given trait will not be implemented for the given types. Negative impls play an additional purpose for auto traits, described below.
18+
19+
Negative impls have the following characteristics:
20+
21+
* They do not have any items.
22+
* They must obey the orphan rules as if they were a positive impl.
23+
* They cannot "overlap" with any positive impls.
24+
25+
## Semver interaction
26+
27+
It is a breaking change to remove a negative impl. Negative impls are a commitment not to implement the given trait for the named types.
28+
29+
## Orphan and overlap rules
30+
31+
Negative impls must obey the same orphan rules as a positive impl. This implies you cannot add a negative impl for types defined in upstream crates and so forth.
32+
33+
Similarly, negative impls cannot overlap with positive impls, again using the same "overlap" check that we ordinarily use to determine if two impls overlap. (Note that positive impls typically cannot overlap with one another either, except as permitted by specialization.)
34+
35+
## Interaction with auto traits
36+
37+
Declaring a negative impl `impl !SomeAutoTrait for SomeType` for an
38+
auto-trait serves two purposes:
39+
40+
* as with any trait, it declares that `SomeType` will never implement `SomeAutoTrait`;
41+
* it disables the automatic `SomeType: SomeAutoTrait` impl that would otherwise have been generated.
42+
43+
Note that, at present, there is no way to indicate that a given type
44+
does not implement an auto trait *but that it may do so in the
45+
future*. For ordinary types, this is done by simply not declaring any
46+
impl at all, but that is not an option for auto traits. A workaround
47+
is that one could embed a marker type as one of the fields, where the
48+
marker type is `!AutoTrait`.
49+
50+
## Immediate uses
51+
52+
Negative impls are used to declare that `&T: !DerefMut` and `&mut T: !Clone`, as required to fix the soundness of `Pin` described in [#66544](https://github.com/rust-lang/rust/issues/66544).
53+
54+
This serves two purposes:
55+
56+
* For proving the correctness of unsafe code, we can use that impl as evidence that no `DerefMut` or `Clone` impl exists.
57+
* It prevents downstream crates from creating such impls.

src/doc/unstable-book/src/language-features/optin-builtin-traits.md

Lines changed: 63 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,8 @@ The `optin_builtin_traits` feature gate allows you to define auto traits.
1010

1111
Auto traits, like [`Send`] or [`Sync`] in the standard library, are marker traits
1212
that are automatically implemented for every type, unless the type, or a type it contains,
13-
has explicitly opted out via a negative impl.
13+
has explicitly opted out via a negative impl. (Negative impls are separately controlled
14+
by the `negative_impls` feature.)
1415

1516
[`Send`]: https://doc.rust-lang.org/std/marker/trait.Send.html
1617
[`Sync`]: https://doc.rust-lang.org/std/marker/trait.Sync.html
@@ -22,6 +23,7 @@ impl !Trait for Type
2223
Example:
2324

2425
```rust
26+
#![feature(negative_impls)]
2527
#![feature(optin_builtin_traits)]
2628

2729
auto trait Valid {}
@@ -43,3 +45,63 @@ fn main() {
4345
// must_be_valid( MaybeValid(False) );
4446
}
4547
```
48+
49+
## Automatic trait implementations
50+
51+
When a type is declared as an `auto trait`, we will automatically
52+
create impls for every struct/enum/union, unless an explicit impl is
53+
provided. These automatic impls contain a where clause for each field
54+
of the form `T: AutoTrait`, where `T` is the type of the field and
55+
`AutoTrait` is the auto trait in question. As an example, consider the
56+
struct `List` and the auto trait `Send`:
57+
58+
```rust
59+
struct List<T> {
60+
data: T,
61+
next: Option<Box<List<T>>>,
62+
}
63+
```
64+
65+
Presuming that there is no explicit impl of `Send` for `List`, the
66+
compiler will supply an automatic impl of the form:
67+
68+
```rust
69+
struct List<T> {
70+
data: T,
71+
next: Option<Box<List<T>>>,
72+
}
73+
74+
unsafe impl<T> Send for List<T>
75+
where
76+
T: Send, // from the field `data`
77+
Option<Box<List<T>>>: Send, // from the field `next`
78+
{ }
79+
```
80+
81+
Explicit impls may be either positive or negative. They take the form:
82+
83+
```rust,ignore
84+
impl<...> AutoTrait for StructName<..> { }
85+
impl<...> !AutoTrait for StructName<..> { }
86+
```
87+
88+
## Coinduction: Auto traits permit cyclic matching
89+
90+
Unlike ordinary trait matching, auto traits are **coinductive**. This
91+
means, in short, that cycles which occur in trait matching are
92+
considered ok. As an example, consider the recursive struct `List`
93+
introduced in the previous section. In attempting to determine whether
94+
`List: Send`, we would wind up in a cycle: to apply the impl, we must
95+
show that `Option<Box<List>>: Send`, which will in turn require
96+
`Box<List>: Send` and then finally `List: Send` again. Under ordinary
97+
trait matching, this cycle would be an error, but for an auto trait it
98+
is considered a successful match.
99+
100+
## Items
101+
102+
Auto traits cannot have any trait items, such as methods or associated types. This ensures that we can generate default implementations.
103+
104+
## Supertraits
105+
106+
Auto traits cannot have supertraits. This is for soundness reasons, as the interaction of coinduction with implied bounds is difficult to reconcile.
107+

src/liballoc/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,7 @@
9999
#![feature(internal_uninit_const)]
100100
#![feature(lang_items)]
101101
#![feature(libc)]
102+
#![cfg_attr(not(bootstrap), feature(negative_impls))]
102103
#![feature(nll)]
103104
#![feature(optin_builtin_traits)]
104105
#![feature(pattern)]

src/libcore/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,7 @@
9898
#![feature(is_sorted)]
9999
#![feature(lang_items)]
100100
#![feature(link_llvm_intrinsics)]
101+
#![cfg_attr(not(bootstrap), feature(negative_impls))]
101102
#![feature(never_type)]
102103
#![feature(nll)]
103104
#![feature(exhaustive_patterns)]

src/libproc_macro/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
#![feature(decl_macro)]
2525
#![feature(extern_types)]
2626
#![feature(in_band_lifetimes)]
27+
#![cfg_attr(not(bootstrap), feature(negative_impls))]
2728
#![feature(optin_builtin_traits)]
2829
#![feature(rustc_attrs)]
2930
#![cfg_attr(bootstrap, feature(specialization))]

src/librustc_ast_passes/feature_gate.rs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -286,8 +286,8 @@ impl<'a> Visitor<'a> for PostExpansionVisitor<'a> {
286286
start,
287287
i.span,
288288
"`#[start]` functions are experimental \
289-
and their signature may change \
290-
over time"
289+
and their signature may change \
290+
over time"
291291
);
292292
}
293293
if attr::contains_name(&i.attrs[..], sym::main) {
@@ -296,8 +296,8 @@ impl<'a> Visitor<'a> for PostExpansionVisitor<'a> {
296296
main,
297297
i.span,
298298
"declaration of a non-standard `#[main]` \
299-
function may change over time, for now \
300-
a top-level `fn main()` is required"
299+
function may change over time, for now \
300+
a top-level `fn main()` is required"
301301
);
302302
}
303303
}
@@ -341,7 +341,7 @@ impl<'a> Visitor<'a> for PostExpansionVisitor<'a> {
341341
if let ast::ImplPolarity::Negative(span) = polarity {
342342
gate_feature_post!(
343343
&self,
344-
optin_builtin_traits,
344+
negative_impls,
345345
span.to(of_trait.as_ref().map(|t| t.path.span).unwrap_or(span)),
346346
"negative trait bounds are not yet fully implemented; \
347347
use marker types for now"

src/librustc_errors/lib.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -802,13 +802,13 @@ impl HandlerInner {
802802
));
803803
self.failure(&format!(
804804
"For more information about an error, try \
805-
`rustc --explain {}`.",
805+
`rustc --explain {}`.",
806806
&error_codes[0]
807807
));
808808
} else {
809809
self.failure(&format!(
810810
"For more information about this error, try \
811-
`rustc --explain {}`.",
811+
`rustc --explain {}`.",
812812
&error_codes[0]
813813
));
814814
}

src/librustc_feature/active.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -152,6 +152,9 @@ declare_features! (
152152
/// Allows features specific to OIBIT (auto traits).
153153
(active, optin_builtin_traits, "1.0.0", Some(13231), None),
154154

155+
/// Allow negative trait implementations.
156+
(active, negative_impls, "1.0.0", Some(13231), None),
157+
155158
/// Allows using `box` in patterns (RFC 469).
156159
(active, box_patterns, "1.0.0", Some(29641), None),
157160

src/librustc_span/lib.rs

Lines changed: 36 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
#![feature(const_if_match)]
1010
#![feature(const_fn)]
1111
#![feature(const_panic)]
12+
#![cfg_attr(not(bootstrap), feature(negative_impls))]
1213
#![feature(nll)]
1314
#![feature(optin_builtin_traits)]
1415
#![feature(specialization)]
@@ -305,7 +306,11 @@ impl Span {
305306

306307
/// Returns `self` if `self` is not the dummy span, and `other` otherwise.
307308
pub fn substitute_dummy(self, other: Span) -> Span {
308-
if self.is_dummy() { other } else { self }
309+
if self.is_dummy() {
310+
other
311+
} else {
312+
self
313+
}
309314
}
310315

311316
/// Returns `true` if `self` fully encloses `other`.
@@ -336,21 +341,33 @@ impl Span {
336341
pub fn trim_start(self, other: Span) -> Option<Span> {
337342
let span = self.data();
338343
let other = other.data();
339-
if span.hi > other.hi { Some(span.with_lo(cmp::max(span.lo, other.hi))) } else { None }
344+
if span.hi > other.hi {
345+
Some(span.with_lo(cmp::max(span.lo, other.hi)))
346+
} else {
347+
None
348+
}
340349
}
341350

342351
/// Returns the source span -- this is either the supplied span, or the span for
343352
/// the macro callsite that expanded to it.
344353
pub fn source_callsite(self) -> Span {
345354
let expn_data = self.ctxt().outer_expn_data();
346-
if !expn_data.is_root() { expn_data.call_site.source_callsite() } else { self }
355+
if !expn_data.is_root() {
356+
expn_data.call_site.source_callsite()
357+
} else {
358+
self
359+
}
347360
}
348361

349362
/// The `Span` for the tokens in the previous macro expansion from which `self` was generated,
350363
/// if any.
351364
pub fn parent(self) -> Option<Span> {
352365
let expn_data = self.ctxt().outer_expn_data();
353-
if !expn_data.is_root() { Some(expn_data.call_site) } else { None }
366+
if !expn_data.is_root() {
367+
Some(expn_data.call_site)
368+
} else {
369+
None
370+
}
354371
}
355372

356373
/// Edition of the crate from which this span came.
@@ -376,10 +393,18 @@ impl Span {
376393
pub fn source_callee(self) -> Option<ExpnData> {
377394
fn source_callee(expn_data: ExpnData) -> ExpnData {
378395
let next_expn_data = expn_data.call_site.ctxt().outer_expn_data();
379-
if !next_expn_data.is_root() { source_callee(next_expn_data) } else { expn_data }
396+
if !next_expn_data.is_root() {
397+
source_callee(next_expn_data)
398+
} else {
399+
expn_data
400+
}
380401
}
381402
let expn_data = self.ctxt().outer_expn_data();
382-
if !expn_data.is_root() { Some(source_callee(expn_data)) } else { None }
403+
if !expn_data.is_root() {
404+
Some(source_callee(expn_data))
405+
} else {
406+
None
407+
}
383408
}
384409

385410
/// Checks if a span is "internal" to a macro in which `#[unstable]`
@@ -1199,7 +1224,11 @@ impl SourceFile {
11991224

12001225
let line_index = lookup_line(&self.lines[..], pos);
12011226
assert!(line_index < self.lines.len() as isize);
1202-
if line_index >= 0 { Some(line_index as usize) } else { None }
1227+
if line_index >= 0 {
1228+
Some(line_index as usize)
1229+
} else {
1230+
None
1231+
}
12031232
}
12041233

12051234
pub fn line_bounds(&self, line_index: usize) -> (BytePos, BytePos) {

src/librustc_span/symbol.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -473,6 +473,7 @@ symbols! {
473473
needs_drop,
474474
needs_panic_runtime,
475475
negate_unsigned,
476+
negative_impls,
476477
never,
477478
never_type,
478479
never_type_fallback,

0 commit comments

Comments
 (0)