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
If `&T` implements these traits, `Arc<T>` has no reason not to do so
either. This is useful for operating system handles like `File` or
`TcpStream` which don't need a mutable reference to implement these
traits.
CC #53835.
CC #94744.
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.
For ranges < usize we determine the number of items
StepBy would yield and then store that in the range.end
instead of the actual end. This significantly
simplifies calculation of the loop induction variable
especially in cases where StepBy::step (an usize)
could overflow the Range's item type
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
previously it was only able to use BufWriter. This was due to a limitation in the
BufReader generics that prevented specialization. This change works around the issue
by using `where Self: Read` instead of `where I: Read`. This limits our options, e.g.
we can't access BufRead methods, but it happens to work out if we rely on some
implementation details.
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.
`#[lang_item]` for `core::ptr::Unique`
Tree Borrows is about to introduce experimental special handling of `core::ptr::Unique` in Miri to give it a semantics.
As of now there does not seem to be a clean way (i.e. other than `&format!("{adt:?}") == "std::ptr::Unique"`) to check if an `AdtDef` represents a `Unique`.
r? `@RalfJung`
Draft: making a lang item
Fix building libstd documentation on FreeBSD.
It fixes the following error:
```
error[E0412]: cannot find type `sockcred2` in module `libc`
--> library/std/src/os/unix/net/ancillary.rs:211:29
|
211 | pub struct SocketCred(libc::sockcred2);
| ^^^^^^^^^ not found in `libc`
```
Extend `unused_must_use` to cover block exprs
Given code like
```rust
#[must_use]
fn foo() -> i32 {
42
}
fn warns() {
{
foo();
}
}
fn does_not_warn() {
{
foo()
};
}
fn main() {
warns();
does_not_warn();
}
```
### Before This PR
```
warning: unused return value of `foo` that must be used
--> test.rs:8:9
|
8 | foo();
| ^^^^^
|
= note: `#[warn(unused_must_use)]` on by default
help: use `let _ = ...` to ignore the resulting value
|
8 | let _ = foo();
| +++++++
warning: 1 warning emitted
```
### After This PR
```
warning: unused return value of `foo` that must be used
--> test.rs:8:9
|
8 | foo();
| ^^^^^
|
= note: `#[warn(unused_must_use)]` on by default
help: use `let _ = ...` to ignore the resulting value
|
8 | let _ = foo();
| +++++++
warning: unused return value of `foo` that must be used
--> test.rs:14:9
|
14 | foo()
| ^^^^^
|
help: use `let _ = ...` to ignore the resulting value
|
14 | let _ = foo();
| +++++++ +
warning: 2 warnings emitted
```
Fixes#104253.
This commit reverts a change made in #111425.
It was believed that this change was necessary for implementing type privacy lints, but #111801 showed that it was not necessary.
Quite opposite, the revert fixes some issues.
Mention `env!` in `option_env!`'s docs
`env!` mentions that there is an alternative that returns an `Option<...>` instead of emitting a compile error.
Now `option_env!` also mentions that there is an alternative that emits a compile error instead of returning an `Option<...>`.
Update runtime guarantee for `select_nth_unstable`
#106933 changed the runtime guarantee for `select_nth_unstable` from O(n) to O(n log n), since the old guarantee wasn't actually met by the implementation at the time. Now with #107522, `select_nth_unstable` should be truly linear in runtime, so we can revert its runtime guarantee to O(n). Since #106933 was considered a bug fix, this will probably need an FCP because it counts as a new API guarantee.
r? `@Amanieu`
Stabilize String::leak
Stabilizes the following API:
```Rust
impl String {
pub fn leak(self) -> &'static mut str;
}
```
closes#102929
blocked by having an FCP for stabilization.
Implement `TryFrom<&OsStr>` for `&str`
Recently when trying to work with `&OsStr` I was surprised to find this `impl` missing.
Since the `to_str` method already existed the actual implementation is fairly non-controversial, except for maybe the choice of the error type. I chose an opaque error here instead of something like `std::str::Utf8Error`, since that would already make a number of assumption about the underlying implementation of `OsStr`.
As this is a trait implementation, it is insta-stable, if I'm not mistaken?
Either way this will need an FCP.
I chose "1.64.0" as the version, since this is unlikely to land before the beta cut-off.
`@rustbot` modify labels: +T-libs-api
API Change Proposal: rust-lang/rust#99031 (accepted)
Add support for targets without unwinding in `mir-opt`, and improve `--bless` for it
The main goal of this PR is to add support for targets without unwinding support in the `mir-opt` test suite, by adding the `EMIT_MIR_FOR_EACH_PANIC_STRATEGY` comment. Similarly to 32bit vs 64bit, when that comment is present, blessed output files will have the `.panic-unwind` or `.panic-abort` suffix, and the right one will be chosen depending on the target's panic strategy.
The `EMIT_MIR_FOR_EACH_PANIC_STRATEGY` comment replaced all the `ignore-wasm32` comments in the `mir-opt` test suite, as those comments were added due to `wasm32` being a target without unwinding support. The comment was also added on other tests that were only executed on x86 but were still panic strategy dependent.
The `mir-opt` suite was then blessed, which caused a ton of churn as most of the existing output files had to be renamed and (mostly) duplicated with the abort strategy.
---
After [asking on Zulip](https://rust-lang.zulipchat.com/#narrow/stream/131828-t-compiler/topic/mir-opt.20tests.20and.20panic.3Dabort), the main concern about this change is it'd make blessing the `mir-opt` suite even harder, as you'd need to both bless it with an unwinding target and an aborting target. This exacerbated the current situation, where you'd need to bless it with a 32bit and a 64bit target already.
Because of that, this PR also makes significant enhancements to `--bless` for the `mir-opt` suite, where it will automatically bless the suite four times with different targets, while requiring minimal cross-compilation.
To handle the 32bit vs 64bit blessing, there is now an hardcoded list of target mapping between 32bit and 64bit. The goal of the list is to find a related target that will *probably* work without requiring additional cross-compilation toolchains on the system. If a mapping is found, bootstrap will bless the suite with both targets, otherwise just with the current target.
To handle the panic strategy blessing (abort vs unwind), I had to resort to what I call "synthetic targets". For each of the target we're blessing (so either the current one, or a 32bit and a 64bit depending on the previous paragraph), bootstrap will extract the JSON spec of the target and change it to include `"panic-strategy": "abort"`. It will then build the standard library with this synthetic target, and bless the `mir-opt` suite with it.
As a result of these changes, blessing the `mir-opt` suite will actually bless it two or four times with different targets, ensuring all possible variants are actually blessed.
---
This PR is best reviewed commit-by-commit.
r? `@jyn514`
cc `@saethlin` `@oli-obk`
Ignore `core`, `alloc` and `test` tests that require unwinding on `-C panic=abort`
Some of the tests for `core` and `alloc` require unwinding through their use of `catch_unwind`. These tests fail when testing using `-C panic=abort` (in my case through a target without unwinding support, and `-Z panic-abort-tests`), while they should be ignored as they don't indicate a failure.
This PR marks all of these tests with this attribute:
```rust
#[cfg_attr(not(panic = "unwind"), ignore = "test requires unwinding support")]
```
I'm not aware of a way to test this on rust-lang/rust's CI, as we don't test any target with `-C panic=abort`, but I tested this locally on a Ferrocene target and it does indeed make the test suite pass.
It fixes the following error:
error[E0412]: cannot find type `sockcred2` in module `libc`
--> library/std/src/os/unix/net/ancillary.rs:211:29
|
211 | pub struct SocketCred(libc::sockcred2);
| ^^^^^^^^^ not found in `libc`
Make BinaryHeap parametric over Allocator
Tracking issue: #32838
Related: https://github.com/rust-lang/wg-allocators/issues/7
This parametrizes `BinaryHeap` with `A`, similarly to how other collections are parametrized.
A couple things I left out:
```
BinaryHeap::append
Currently requires both structures to have the same allocator type. Could
change, but depends on Vec::append, which has the same constraints.
impl<T: Ord> Default for BinaryHeap<T>
Not parametrized, because there's nowhere to conjure the allocator from.
impl<T: Ord> FromIterator<T> for BinaryHeap<T>
Not parametrized, because there's nowhere to conjure the allocator from.
impl<T: Ord, const N: usize> From<[T; N]> for BinaryHeap<T>
Not parametrized, because there's nowhere to conjure the allocator from.
unsafe impl<I> AsVecIntoIter for IntoIter<I>
AsVecIntoIter is not allocator aware, and I didn't dare change it without guidance. Is this something important?
```
I've seen very few tests for allocator_api in general, but I'd like to at least test this on some usage code in my projects before moving forward.
EDIT: Updated the list of impls and functions that are not affected by this. `BinaryHeap` no longer has a `SpecExtend` impl, and prior work made implementing `Extend` possible.
It might happen that a synthetic target name does not match one of the
hardcoded ones in std's build script, causing std to fail to build. This
commit changes the std build script avoid including the restricted-std
feature unconditionally when a synthetic target is being built.
Fix ntdll linkage issues on Windows UWP platforms
See discussion: https://github.com/rust-lang/rust/issues/112265#issuecomment-1575479683
Static loading `ntdll` functions does not work for UWP programs, which will end up link errors complaining about missing symbols, or failure to pass the WACK tests. The breakage was introduced in #108262.
This PR basically reverts part of the changes in #108262 for UWP only, and fixes some lint suggestions.
Uplift `clippy::cmp_nan` lint
This PR aims at uplifting the `clippy::cmp_nan` lint into rustc.
## `invalid_nan_comparisons`
~~(deny-by-default)~~ (warn-by-default)
The `invalid_nan_comparisons` lint checks comparison with `f32::NAN` or `f64::NAN` as one of the operand.
### Example
```rust,compile_fail
let a = 2.3f32;
if a == f32::NAN {}
```
### Explanation
NaN does not compare meaningfully to anything – not even itself – so those comparisons are always false.
-----
Mostly followed the instructions for uplifting a clippy lint described here: https://github.com/rust-lang/rust/pull/99696#pullrequestreview-1134072751
`@rustbot` label: +I-lang-nominated
r? compiler
Rollup of 3 pull requests
Successful merges:
- #112260 (Improve document of `unsafe_code` lint)
- #112429 ([rustdoc] List matching impls on type aliases)
- #112442 (Deduplicate identical region constraints in new solver)
r? `@ghost`
`@rustbot` modify labels: rollup
Uplift `clippy::undropped_manually_drops` lint
This PR aims at uplifting the `clippy::undropped_manually_drops` lint.
## `undropped_manually_drops`
(warn-by-default)
The `undropped_manually_drops` lint check for calls to `std::mem::drop` with a value of `std::mem::ManuallyDrop` which doesn't drop.
### Example
```rust
struct S;
drop(std::mem::ManuallyDrop::new(S));
```
### Explanation
`ManuallyDrop` does not drop it's inner value so calling `std::mem::drop` will not drop the inner value of the `ManuallyDrop` either.
-----
Mostly followed the instructions for uplifting an clippy lint described here: https://github.com/rust-lang/rust/pull/99696#pullrequestreview-1134072751
`@rustbot` label: +I-lang-nominated
r? compiler
-----
For Clippy:
changelog: Moves: Uplifted `clippy::undropped_manually_drops` into rustc
Avoid unwind across `extern "C"` in `thread_local::fast_local`
This is a minimal fix for #112285, in case we want a simple patch that can be easily to backported if that's desirable.
*(Note: I have another broader cleanup which I've mostly omitted from here to avoid clutter, except for the `Cell` change, which isn't needed to fix UB, but simplifies safety comments).*
The only tier-1 target that this occurs on in a way that seems likely to cause problems in practice linux-gnu, although I believe some folks care about that platform somewhat 😉. I'm unsure how big of an issue this is. I've seen stuff like this behave quite badly, but there's a number of reasons to think this might actually be "fine in practice".
I've hedged my bets and assumed we'll backport this at least to beta but my feeling is that there's not enough evidence this is a problem worth backporting further than that.
### More details
This issue seems to have existed since `thread_local!`'s `const` init functionality was added. It occurs if you have a `const`-initialized thread local for a type that `needs_drop`, the drop panics, and you're on a target with support for static thread locals. In this case, we will end up defining an `extern "C"` function in the user crate rather than in libstd, and because the user crate will not have `#![feature(c_unwind)]` enabled, their panic will not be caught by an auto-inserted abort guard.
In practice, the actual situation where problems are likely[^ub] is somewhat narrower.
On most targets with static thread locals, we manage the TLS dtor list by hand (for reentrancy reasons among others). In these cases, while the users code may panic, we're calling it inside our own `extern "C"` (or `extern "system"`) function, which seems to (at least in practice) catch the panic and convert it to an abort.
However, on a few targets, most notably linux-gnu with recent glibc (but also fuchsia and redox), a tls dtor registration mechanism exists which we can actually use directly, [`__cxa_thread_atexit_impl`](https://github.com/rust-lang/rust/blob/master/library/std/src/sys/unix/thread_local_dtor.rs#L26-L36).
This is the case that seems most likely to be a cause for concern, as now we're passing a function to the system library and panicking out of it in a case where there are may not be Rust frames above it on the call stack (since it's running thread shutdown), and even if there were, it may not be prepared to handle such unwinding. If that's the case, it'd be bad.
Is it? Dunno. The fact that it's a `__cxa_*` function makes me think they probably have considered that the callback could throw but I have no evidence here and it doesn't seem to be written down anywhere, so it's just a guess. (I would not be surprised if someone comes into this thread to tell me how definitely-bad-news it is).
That said, as I said, all this is actually UB! If this isn't a "technically UB but fine in practice", but all bets are off if this is the kind of thing we are telling LLVM about.
[^ub]: This is UB so take that with a grain of salt -- I'm absolutely making assumptions about how the UB will behave "in practice" here, which is almost certainly a mistake.
Add `task::Waker::noop`
I have found myself reimplementing this function many times when I need a `Context` but don't have a runtime or `futures` to hand.
Prior art: [`futures::task::noop_waker`](https://docs.rs/futures/0.3/futures/task/fn.noop_waker.html) and [`futures::task::noop_waker_ref`](https://docs.rs/futures/0.3/futures/task/fn.noop_waker_ref.html)
Tracking issue: https://github.com/rust-lang/rust/issues/98286
Unresolved questions:
1. Should we also add `RawWaker::noop()`? (I don't think so, I can't think of a use case for it)
2. Should we also add `Context::noop()`? Depending on the future direction `Context` goes a "noop context" might not even make sense in future.
3. Should it be an associated constant instead? That would allow for `let cx = &mut Context::from_waker(&Waker::NOOP);` to work on one line which is pretty nice. I don't really know what the guideline is here.
r? rust-lang/libs-api `@rustbot` label +T-libs-api -T-libs
Improved std support for ps vita target
Fixed a couple of things in std support for ps vita via Vita SDK newlib oss implementation:
- Added missing hardware features to target spec
- Compile in thumb by default (newlib is also compiled in thumb)
- Fixed fs calls. Vita newlib has a not-very-posix dirent. Also vita does not expose inodes, it's stubbed as 0 in stat, and I'm stubbing it here for dirent (because vita newlibs's dirent doesn't even have that field)
- Enabled signal handlers for panic unwinding
- Dropped static link requirement from the platform support md. Also, rearranged sections to better stick with the template.
After the socket ancillary data implementation was introduced, the
build was broken on FreeBSD, add the same workaround as for the
existing implementations.
Remove ExtendElement, ExtendWith, extend_with
Related to #104624, broken up into two commits. The first removes wrapper trait ExtendWith and its only implementer struct ExtendElement. The second may have perf issues so may be reverted/removed if no alternate fix is found; it should be profiled.
r? `@scottmcm`
- Switch TypeId to 128 bits
- Hack around the fact that tracing-subscriber dislikes how TypeId is hashed
- Remove lowering of type_id128 from rustc_codegen_llvm
- Remove unnecessary `type_id128` intrinsic (just change return type of `type_id`)
- Only hash the lower 64 bits of the TypeId
- Reword comment
add `#[doc(alias="flatmap")]` to `Option::and_then`
I keep forgetting that rust calls this `and_then` and trying to search for `flatmap`. `and_then`'s docs even mention "Some languages call this operation flatmap", but it doesn't show up as a result in the search at `https://doc.rust-lang.org/std/?search=flatmap`
Option::map_or_else: Show an example of integrating with Result
Moving this from https://github.com/rust-lang/libs-team/issues/59 where an API addition was rejected. But I think it's valuable to add this example to the documentation at least.
QNX Neutrino: exponential backoff when fork/spawn needs a retry
Fixes#108594: When retrying, sleep with an exponential duration. When sleep duration is lower than minimum possible sleeping time, yield instead (this will not be often due to the exponential increase of duration).
Minimum possible sleeping time is determined using `libc::clock_getres` but only when spawn/fork failed the first time in a request. This is cached using a LazyLock.
CC `@gh-tr`
r? `@workingjubilee`
`@rustbot` label +O-neutrino
use c literals in compiler and library
Use c literals #108801 in compiler and library
currently blocked on:
* <strike>rustfmt: don't know how to format c literals</strike> nope, nightly one works.
* <strike>bootstrap</strike>
r? `@ghost`
`@rustbot` blocked
Require that const param tys implement `ConstParamTy`
1. Require that const param tys implement `ConstParamTy` instead of using `search_for_adt_const_param_violation`
2. Add `StructuralPartialEq` as a supertrait for `ConstParamTy`, since we need to make sure that we derive *both* `PartialEq` and `Eq`
3. Implement `ConstParamTy` for tuples up to 12 (or whatever the default for tuples is)
4. Add some custom diagnostics to `ConstParamTy` errors, to avoid regressions from (1.). It's still not as great as it could be -- will point out inline in comments.
r? `@BoxyUwU`
Fix bug in utf16_to_utf8 for zero length strings
This fixes the behavior of sending EOF by pressing Ctrl+Z => Enter in a windows console.
Previously, that would trip the unpaired surrogate error, whereas now we correctly detect EOF.
remove reference to Into in ? operator core/std docs, fix#111655
remove the text stating that `?` uses `Into::into` and add text stating it uses `From::from` instead. This closes#111655.
Uplift `clippy::cast_ref_to_mut` lint
This PR aims at uplifting the `clippy::cast_ref_to_mut` lint into rustc.
## `cast_ref_to_mut`
(deny-by-default)
The `cast_ref_to_mut` lint checks for casts of `&T` to `&mut T` without using interior mutability.
### Example
```rust,compile_fail
fn x(r: &i32) {
unsafe {
*(r as *const i32 as *mut i32) += 1;
}
}
```
### Explanation
Casting `&T` to `&mut T` without interior mutability is undefined behavior, as it's a violation of Rust reference aliasing requirements.
-----
Mostly followed the instructions for uplifting a clippy lint described here: https://github.com/rust-lang/rust/pull/99696#pullrequestreview-1134072751
`@rustbot` label: +I-lang-nominated
r? compiler
-----
For Clippy:
changelog: Moves: Uplifted `clippy::cast_ref_to_mut` into rustc
This fixes the behavior of sending EOF by pressing Ctrl+Z => Enter in a
windows console.
Previously, that would trip the unpaired surrogate error, whereas now we
correctly detect EOF.
Update cargo
17 commits in 64fb38c97ac4d3a327fc9032c862dd28c8833b17..f7b95e31642e09c2b6eabb18ed75007dda6677a0
2023-05-23 18:53:23 +0000 to 2023-05-30 19:25:02 +0000
- chore: detect the channel a PR wants to merge into (rust-lang/cargo#12181)
- refactor: de-depulicate `make_dep_prefix` implementation (rust-lang/cargo#12203)
- Re-enable code_generation test on Windows (rust-lang/cargo#12199)
- docs: add doc comments for git source and friends (rust-lang/cargo#12192)
- test: set retry sleep to 1ms for all tests (rust-lang/cargo#12194)
- fix(add): Reduce the chance we re-format the user's `[features]` table (rust-lang/cargo#12191)
- test(add): Remove expensive test (rust-lang/cargo#12188)
- Add a description of `Cargo.lock` conflicts in the Cargo FAQ (rust-lang/cargo#12185)
- refactor(tests): Reduce cargo-add setup load (rust-lang/cargo#12189)
- Warn when an edition 2021 crate is in a virtual workspace with default resolver (rust-lang/cargo#10910)
- refactor(tests): Reduce cargo-remove setup load (rust-lang/cargo#12184)
- chore: Lexicographically order `-Z` flags (rust-lang/cargo#12182)
- chore(ci): remove temporary fix for rustup 1.24.1 (rust-lang/cargo#12180)
- fix: AIX searches dynamic libraries in `LIBPATH`. (rust-lang/cargo#11968)
- deps: remove unused features from windows-sys (rust-lang/cargo#12176)
- Automatically inherit workspace lints when running cargo new/init (rust-lang/cargo#12174)
- Test that the new `debuginfo` options match between cargo and rustc (rust-lang/cargo#12022)
r? `@ghost`
Allow limited access to `OsStr` bytes
`OsStr` has historically kept its implementation details private out of
concern for locking us into a specific encoding on Windows.
This is an alternative to rust-lang#95290 which proposed specifying the encoding on Windows. Instead, this
only specifies that for cross-platform code, `OsStr`'s encoding is a superset of UTF-8 and defines
rules for safely interacting with it
At minimum, this can greatly simplify the `os_str_bytes` crate and every
arg parser that interacts with `OsStr` directly (which is most of those
that support invalid UTF-8).
Tracking issue: #111544
Uplift `clippy::invalid_utf8_in_unchecked` lint
This PR aims at uplifting the `clippy::invalid_utf8_in_unchecked` lint into two lints.
## `invalid_from_utf8_unchecked`
(deny-by-default)
The `invalid_from_utf8_unchecked` lint checks for calls to `std::str::from_utf8_unchecked` and `std::str::from_utf8_unchecked_mut` with an invalid UTF-8 literal.
### Example
```rust
unsafe {
std::str::from_utf8_unchecked(b"cl\x82ippy");
}
```
### Explanation
Creating such a `str` would result in undefined behavior as per documentation for `std::str::from_utf8_unchecked` and `std::str::from_utf8_unchecked_mut`.
## `invalid_from_utf8`
(warn-by-default)
The `invalid_from_utf8` lint checks for calls to `std::str::from_utf8` and `std::str::from_utf8_mut` with an invalid UTF-8 literal.
### Example
```rust
std::str::from_utf8(b"ru\x82st");
```
### Explanation
Trying to create such a `str` would always return an error as per documentation for `std::str::from_utf8` and `std::str::from_utf8_mut`.
-----
Mostly followed the instructions for uplifting a clippy lint described here: https://github.com/rust-lang/rust/pull/99696#pullrequestreview-1134072751
````@rustbot```` label: +I-lang-nominated
r? compiler
-----
For Clippy:
changelog: Moves: Uplifted `clippy::invalid_utf8_in_unchecked` into rustc
`[T; N]::zip` is "eager" but most zips are mapped.
This causes poor optimization in generated code.
This is a fundamental design issue and "zip" is
"prime real estate" in terms of function names,
so let's free it up again.
All the implementations of the trait already are `Copy`, and this seems to be enough to simplify the implementations enough to make the MIR inliner willing to inline basics like `Range::next`.
Fix docs for `alloc::realloc`
Fixes#108546.
Corrects the docs for `alloc::realloc` to bring the safety constraints into line with `Layout::from_size_align_unchecked`'s constraints.
Rework handling of recursive panics
This PR makes 2 changes to how recursive panics works (a panic while handling a panic).
1. The panic count is no longer used to determine whether to force an immediate abort. This allows code like the following to work without aborting the process immediately:
```rust
struct Double;
impl Drop for Double {
fn drop(&mut self) {
// 2 panics are active at once, but this is fine since it is caught.
std::panic::catch_unwind(|| panic!("twice"));
}
}
let _d = Double;
panic!("once");
```
Rustc already generates appropriate code so that any exceptions escaping out of a `Drop` called in the unwind path will immediately abort the process.
2. Any panics while the panic hook is executing will force an immediate abort. This is necessary to avoid potential deadlocks like #110771 where a panic happens while holding the backtrace lock. We don't even try to print the panic message in this case since the panic may have been caused by `Display` impls.
Fixes#110771