Implement `Sync` for `mpsc::Sender`
`mpsc::Sender` is currently `!Sync` because the previous implementation contained an optimization where the channel started out as single-producer and was dynamically upgraded on the first clone, which relied on a unique reference to the sender. This optimization is one of the main reasons the old implementation was so complex and was removed in #93563. `mpsc::Sender` can now soundly implement `Sync`.
Note for any potential confusion, this chance does *not* add MPMC behavior. This only affects the already `Send + Clone` *sender*, not *receiver*.
It's technically possible to rely on the `!Sync` behavior in the same way as a `PhantomData<*mut T>`, but that seems very unlikely in practice. Either way, this change is insta-stable and needs an FCP.
`@rustbot` label +T-libs-api -T-libs
slice::from_raw_parts: mention no-wrap-around condition
Cc https://github.com/rust-lang/rust/issues/83996. This probably needs to be mentioned in more places, so I am not closing that issue, but this here should help at least.
Warn on unused `offset_of!()` result
The usage of `core::hint::must_use()` means that we don't get a specialized message. I figured out that since there are plenty of other methods that just have `#[must_use]` with no message it'll be fine, but it is a bit unfortunate that the error mentions `must_use` and not `offset_of!`.
Fixes#111669.
Document memory orderings of `thread::{park, unpark}`
Document `thread::park/unpark` as having acquire/release synchronization. Without that guarantee, even the example in the documentation can deadlock:
```rust
let flag = Arc::new(AtomicBool::new(false));
let t2 = thread::spawn(move || {
while !flag.load(Ordering::Acquire) {
thread::park();
}
});
flag.store(true, Ordering::Release);
t2.thread().unpark();
// t1: flag.store(true)
// t1: thread.unpark()
// t2: flag.load() == false
// t2 now parks, is immediately unblocked but never
// acquires the flag, and thus spins forever
```
Multiple calls to `unpark` should also maintain a release sequence to make sure operations released by previous `unpark`s are not lost:
```rust
let a = Arc::new(AtomicBool::new(false));
let b = Arc::new(AtomicBool::new(false));
let t2 = thread::spawn(move || {
while !a.load(Ordering::Acquire) || !b.load(Ordering::Acquire) {
thread::park();
}
});
thread::spawn(move || {
a.store(true, Ordering::Release);
t2.thread().unpark();
});
b.store(true, Ordering::Release);
t2.thread().unpark();
// t1: a.store(true)
// t1: t2.unpark()
// t3: b.store(true)
// t3: t2.unpark()
// t2 now parks, is immediately unblocked but never
// acquires the store of `a`, only the store of `b` which
// was released by the most recent unpark, and thus spins forever
```
This is of course a contrived example, but is reasonable to rely upon in real code.
Note that all implementations of park/unpark already comply with the rules, it's just undocumented.
Implement PartialOrd for `Vec`s over different allocators
It is already possible to `PartialEq` `Vec`s with different allocators, but that is not the case with `PartialOrd`.
Add `implement_via_object` to `rustc_deny_explicit_impl` to control object candidate assembly
Some built-in traits are special, since they are used to prove facts about the program that are important for later phases of compilation such as codegen and CTFE. For example, the `Unsize` trait is used to assert to the compiler that we are able to unsize a type into another type. It doesn't have any methods because it doesn't actually *instruct* the compiler how to do this unsizing, but this is later used (alongside an exhaustive match of combinations of unsizeable types) during codegen to generate unsize coercion code.
Due to this, these built-in traits are incompatible with the type erasure provided by object types. For example, the existence of `dyn Unsize<T>` does not mean that the compiler is able to unsize `Box<dyn Unsize<T>>` into `Box<T>`, since `Unsize` is a *witness* to the fact that a type can be unsized, and it doesn't actually encode that unsizing operation in its vtable as mentioned above.
The old trait solver gets around this fact by having complex control flow that never considers object bounds for certain built-in traits:
2f896da247/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs (L61-L132)
However, candidate assembly in the new solver is much more lovely, and I'd hate to add this list of opt-out cases into the new solver. Instead of maintaining this complex and hard-coded control flow, instead we can make this a property of the trait via a built-in attribute. We already have such a build attribute that's applied to every single trait that we care about: `rustc_deny_explicit_impl`. This PR adds `implement_via_object` as a meta-item to that attribute that allows us to opt a trait out of object-bound candidate assembly as well.
r? `@lcnr`
Rollup of 8 pull requests
Successful merges:
- #112232 (Better error for non const `PartialEq` call generated by `match`)
- #112499 (Fix python linting errors)
- #112596 (Suggest correct signature on missing fn returning RPITIT/AFIT)
- #112606 (Alter `Display` for `Ipv6Addr` for IPv4-compatible addresses)
- #112781 (Don't consider TAIT normalizable to hidden ty if it would result in impossible item bounds)
- #112787 (Add gha problem matcher)
- #112799 (Clean up "doc(hidden)" check)
- #112803 (Format the examples directory of cg_clif)
r? `@ghost`
`@rustbot` modify labels: rollup
Add `alloc::rc::UniqueRc`
This PR implements `UniqueRc` as described in https://github.com/rust-lang/libs-team/issues/90.
I've tried to stick to the API proposed there, incorporating the feedback from the ACP review. For now I've just implemented `UniqueRc`, but we'll want `UniqueArc` as well. I wanted to get feedback on this implementation first since the `UniqueArc` version should be mostly a copy/paste/rename job.
This is an `Rc` that is guaranteed to only have one strong reference.
Because it is uniquely owned, it can safely implement `DerefMut`, which
allows programs to have an initialization phase where structures inside
the `Rc` can be mutated.
The `UniqueRc` can then be converted to a regular `Rc`, allowing sharing
and but read-only access.
During the "initialization phase," weak references can be created, but
attempting to upgrade these will fail until the `UniqueRc` has been
converted to a regular `Rc`. This feature can be useful to create
cyclic data structures.
This API is an implementation based on the feedback provided to the ACP
at https://github.com/rust-lang/libs-team/issues/90.
Use BorrowFlag instead of explicit isize
The integer type tracking borrow count has a typedef called `BorrowFlag`. This type should be used instead of explicit `isize`.
[doc] `poll_fn`: explain how to `pin` captured state safely
Usage of `Pin::new_unchecked(&mut …)` is dangerous with `poll_fn`, even though the `!Unpin`-infectiousness has made things smoother. Nonetheless, there are easy ways to avoid the need for any `unsafe` altogether, be it through `Box::pin`ning, or the `pin!` macro. Since the latter only works within an `async` context, showing an example artificially introducing one ought to help people navigate this subtlety with safety and confidence.
## Preview
https://user-images.githubusercontent.com/9920355/230092494-da22fdcb-0b8f-4ff4-a2ac-aa7d9ead077a.mov
```@rustbot``` label +A-docs
[libs] Simplify `unchecked_{shl,shr}`
There's no need for the `const_eval_select` dance here. And while I originally wrote the `.try_into().unwrap_unchecked()` implementation here, it's kinda a mess in MIR -- this new one is substantially simpler, as shown by the old one being above the inlining threshold but the new one being below it in the `mir-opt/inline/unchecked_shifts` tests.
We don't need `u32::checked_shl` doing a dance through both `Result` *and* `Option` 🙃
Usage of `Pin::new_unchecked(&mut …)` is dangerous with `poll_fn`, even
though the `!Unpin`-infectiousness has made things smoother.
Nonetheless, there are easy ways to avoid the need for any `unsafe`
altogether, be it through `Box::pin`ning, or the `pin!` macro. Since the
latter only works within an `async` context, showing an example
artifically introducing one ought to help people navigate this subtlety
with safety and confidence.
std: only depend on dlmalloc for wasm*-unknown
It was already filtered out for emscripten, but wasi doesn't need dlmalloc
either since it reuses `unix/alloc.rs`.
io: soften ‘at most one write attempt’ requirement in io::Write::write
At the moment, documentation of std::io::Write::write indicates that
call to it ‘represents at most one attempt to write to any wrapped
object’. It seems that such wording was put there to contrast it with
pre-1.0 interface which attempted to write all the data (it has since
been changed in [RFC 517]).
However, the requirement puts unnecessary constraints and may
complicate adaptors which perform non-trivial transformations on the
data. For example, they may maintain an internal buffer which needs
to be written out before the write method accepts more data. It might
be natural to code the method such that it flushes the buffer and then
grabs another chunk of user data. With the current wording in the
documentation, the adaptor would be forced to return Ok(0).
This commit softens the wording such that implementations can choose
code structure which makes most sense for their particular use case.
While at it, elaborate on the meaning of `Ok(0)` return pointing out
that the write_all methods interprets it as an error.
[RFC 517]: https://rust-lang.github.io/rfcs/0517-io-os-reform.html
Launch a non-unwinding panic for misaligned pointer deref
This panic already never unwinds, but that's only because it always hits the unwind guard that's created by our `UnwindAction::Terminate`. Hitting the unwind guard generates a huge double-panic backtrace. Now we generate a normal-looking panic message when this check is hit.
r? `@thomcc`
fix: get the l4re target working again
This is based on work from https://github.com/rust-lang/rust/pull/103966, addressing the review comment by `@m-ou-se` at the time and "fixing" the (probably newly) missing read_buf.
Remove `box_free` lang item
This PR removes the `box_free` lang item, replacing it with `Box`'s `Drop` impl. Box dropping is still slightly magic because the contained value is still dropped by the compiler.
Rollup of 6 pull requests
Successful merges:
- #112352 (Fix documentation build on FreeBSD)
- #112644 (Correct types in method descriptions of `NonZero*` types)
- #112683 (fix ICE on specific malformed asm clobber_abi)
- #112707 ([rustdoc] Fix invalid handling of "going back in history" when "go to only search result" setting is enabled)
- #112719 (Replace fvdl with ffx, allow test without install)
- #112728 (Add `<meta charset="utf-8">` to `-Zdump-mir-spanview` output)
r? `@ghost`
`@rustbot` modify labels: rollup
Correct types in method descriptions of `NonZero*` types
- `$Int`: e.g. i32, usize
- `$Ty`: e.g. NonZeroI32, NonZeroUsize
|method|current description|after my changes|
|-|-|-|
|`saturating_add`|...Return `$Int`::MAX on overflow.|...Return `$Ty`::MAX on overflow.|
|`checked_abs`|...returns None if self == `$Int`::MIN.|...returns None if self == `$Ty`::MIN.|
|`checked_neg`|...returning None if self == i32::MIN.|...returning None if self == `$Ty`::MIN.|
|`saturating_neg`|...returning MAX if self == i32::MIN...|...returning `$Ty`::MAX if self == `$Ty`::MIN...|
|`saturating_mul`|...Return `$Int`::MAX...|...Return `$Ty`::MAX...|
|`saturating_pow`|...Return `$Int`::MIN or `$Int`::MAX...|...Return `$Ty`::MIN or `$Ty`::MAX...|
---
For example:
```rust
pub const fn saturating_neg(self) -> NonZeroI128
```
- current
- Saturating negation. Computes `-self`, returning `MAX` if `self == i32::MIN` instead of overflowing.
- after my changes
- Saturating negation. Computes `-self`, returning `NonZeroI128::MAX` if `self == NonZeroI128::MIN` instead of overflowing.
Fix documentation build on FreeBSD
After the socket ancillary data implementation was introduced, the documentation build was broken on FreeBSD hosts, add the same workaround as for the existing implementations.
Fixes the doc build after #91793