See https://rust-lang.zulipchat.com/#narrow/stream/131828-t-compiler/topic/Attaching.20backtraces.20to.20RefCell/near/226273614
for some background discussion
This PR adds a new off-by-default feature `debug-refcell` to libcore.
When enabled, this feature stores additional debugging information in
`RefCell`. This information is included in the panic message when
`borrow()` or `borrow_mut()` panics, to make it easier to track down the
source of the issue.
Currently, we store the caller location for the earliest active borrow.
This has a number of advantages:
* There is only a constant amount of overhead per `RefCell`
* We don't need any heap memory, so it can easily be implemented in core
* Since we are storing the *earliest* active borrow, we don't need any
extra logic in the `Drop` implementation for `Ref` and `RefMut`
Limitations:
* We only store the caller location, not a full `Backtrace`. Until
we get support for `Backtrace` in libcore, this is the best tha we can
do.
* The captured location is only displayed when `borrow()` or
`borrow_mut()` panics. If a crate calls `try_borrow().unwrap()`
or `try_borrow_mut().unwrap()`, this extra information will be lost.
To make testing easier, I've enabled the `debug-refcell` feature by
default. I'm not sure how to write a test for this feature - we would
need to rebuild core from the test framework, and create a separate
sysroot.
Since this feature will be off-by-default, users will need to use
`xargo` or `cargo -Z build-std` to enable this feature. For users using
a prebuilt standard library, this feature will be disabled with zero
overhead.
I've created a simple test program:
```rust
use std::cell::RefCell;
fn main() {
let _ = std::panic::catch_unwind(|| {
let val = RefCell::new(true);
let _first = val.borrow();
let _second = val.borrow();
let _third = val.borrow_mut();
});
let _ = std::panic::catch_unwind(|| {
let val = RefCell::new(true);
let first = val.borrow_mut();
drop(first);
let _second = val.borrow_mut();
let _thid = val.borrow();
});
}
```
which produces the following output:
```
thread 'main' panicked at 'already borrowed: BorrowMutError { location: Location { file: "refcell_test.rs", line: 6, col: 26 } }', refcell_test.rs:8:26
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
thread 'main' panicked at 'already mutably borrowed: BorrowError { location: Location { file: "refcell_test.rs", line: 16, col: 27 } }', refcell_test.rs:18:25
```
Clarify non-exact length in the Iterator::take documentation
There's an example which demonstrates incomplete length case, but it'd be best to explain it right from the start.
Document panicking cases for integer division and remainder
This PR documents the cases when integer division and remainder operations panic. These operations panic in two cases: division by zero and overflow.
It's surprising that these operations always panic on overflow, unlike most other arithmetic operations, which panic on overflow only when `debug_assertions` is enabled. The panic on overflow for the remainder is also surprising because a return value of `0` would be reasonable in this case. ("Overflow" occurs only for `MIN % -1`.) Since the panics on overflow are somewhat surprising, they should be documented.
I guess it's worth asking: is panic on overflow (even when `debug_assertions` is disabled) the intended behavior? If not, what's the best way forward?
Add license metadata for std dependencies
These five crates are in the dependency tree of `std` but lack license metadata:
- `alloc`
- `core`
- `panic_abort`
- `panic_unwind`
- `unwind`
Querying the dependency tree of `std` is a useful thing to be able to do, since these crates will typically be linked into Rust binaries. Tools show the license fields missing, as seen in https://github.com/rust-lang/rust/issues/67014#issuecomment-782704534. This PR adds the license field for the five crates, based on the license of the `std` package and this repo as a whole. I also added the `repository` and `descriptions` fields, since those seem useful. For `description`, I copied text from top-level comments for the respective modules - except for `unwind` which has none.
I also note that https://github.com/rust-lang/rust/pull/73530 attempted to add license metadata for all crates in this repo, but was rejected because there was question about some of them. I hope that this smaller change, focusing only on the runtime dependencies, will be easier to review.
cc `@Mark-Simulacrum` `@Lokathor`
Fix inequality in docs for div_euclid
This commit fixes the statement of the inequality that the Euclidean remainder satisfies. (The remainder is guaranteed to be less than abs(rhs), not rhs.) It also rewords the documentation to make it a little easier to read.
(You might wonder why I've written `abs(rhs)` instead of `rhs.abs()`. Two reasons: first, the `rem_euclid` docs use `abs(rhs)` instead of `rhs.abs()`, and second, the absolute value here is the mathematical absolute value, not the the `.abs()` operation which may overflow.)
Avoid temporary allocations in `render_assoc_item`
`render_assoc_item` came up as very hot in a profile of rustdoc on
`bevy`. This avoids some temporary allocations just to calculate the
length of the header.
This should be a strict improvement, since all string formatting was
done twice before.
cc #82845
Otherwise you get a lot of instances of `item.span.span()`, which is
just plain confusing. `item.span.inner()` conveys the correct meaning of
"get the type that `clean::Span` wraps".
Download a more recent LLVM version if `src/version` is modified
When bumping the bootstrap version, the name of the generated LLVM
shared object file is changed, even though it's the same contents as
before. If bootstrap tries to use an older version, it will get linking
errors:
```
Building rustdoc for stage1 (x86_64-unknown-linux-gnu)
Compiling rustdoc-tool v0.0.0 (/home/joshua/rustc/src/tools/rustdoc)
error: linking with `cc` failed: exit code: 1
|
= note: "cc" "-Wl,--as-needed" ... lots of args ...
= note: /usr/bin/ld: cannot find -lLLVM-12-rust-1.53.0-nightly
clang: error: linker command failed with exit code 1 (use -v to see invocation)
error: could not compile `rustdoc-tool`
```
Helps with https://github.com/rust-lang/rust/issues/81930.
Move `std::sys::unix::platform` to `std::sys::unix::ext`
This moves the operating system dependent alias `platform` (`std::os::{linux, android, ...}`) from `std::sys::unix` to `std::sys::unix::ext` (a.k.a. `std::os::unix`), removing the need for compatibility code in `unix_ext` when documenting on another platform.
This is also a step in making it possible to properly move `std::sys::unix::ext` to `std::os::unix`, as ideally `std::sys` should not depend on the rest of `std`.
Fix invalid slice access in String::retain
As noted in #78499, the previous fix was technically still unsound because it accessed elements of a slice outside its bounds (even though they were still inside the same allocation). This PR addresses that concern by switching to a dropguard approach.
Implement TrustedLen and TrustedRandomAccess for Range<integer>, array::IntoIter, VecDequeue's iterators
This should make some `FromIterator` and `.zip()` specializations applicable in a few more cases.
``@rustbot`` label libs-impl
Make NonNull::as_ref (and friends) return refs with unbound lifetimes
# Rationale:
1. The documentation for all of these functions claims that this is what the functions already do, as they all come with this comment:
> You must enforce Rust's aliasing rules, *since the returned lifetime 'a is arbitrarily chosen* and does not necessarily reflect the actual lifetime of the data...
So I think it's just a bug that they weren't this way already. Note that had it not been for this part, I wouldn't be making this PR, so if we decide we won't take this change, I'll follow it up with a docs PR to fix this.
2. This is how the equivalent raw pointer functions behave.
They also take `self` and not `&self`/`&mut self`, but that can't be changed compatibly at this point. This is the next best thing.
3. Without this fix, often code that uses these methods will find it has to expand the lifetime of the result.
(I can't speak for others but even in unsafe-heavy code, needing to do this unexpectedly is a huge red flag -- if Rust thinks something should have a specific lifetime, I assume it's for a reason)
### Can this cause existing code to be unsound?
I'm confident this can't cause new unsoundness since the reference exists for at most its lifetime, but you get a borrow checker error if you do something that would require/allow the reference to exist past its lifetime.
Additionally, the aliasing rules of a reference only applies while the reference exists.
This *must* be the case, as it is required by the rules used by safe code. (That said, the documentation in this file sort of contradicts it, but I think it's just ambiguity between the lifetime `'a` in `&'a T` and lifetime of the `&'a T` reference itself...)
We are increasing the lifetime of these references, but they should already have hard bounds on that lifetime, or they'd have borrow checker errors.
(CC ``@RalfJung`` because I have gone and done the mistake where I say something definitive about aliasing in Rust which is honestly outside the group of things I should make definitive comments about).
# Caveats
1. This is insta-stable (except for on the unstable functions ofc). I don't think there's any other alternative.
2. I don't believe this is a breaking change in practice. In theory someone could be assigning `NonNull::as_ref` to a function pointer of type `fn(&NonNull<T>) -> &T`. Now they'd need to use a slightly different function pointer type which is (probably) incompatible. This seems pathological, but I guess crater could be used if there are concerns.
3. This has no tests. The old version didn't either that I saw. I could add some stuff that fails to compile without it, if that would be useful.
4. Sometimes the NLL borrow checker gives up and decides lifetimes live till the end of the scope, as opposed to the range where they're used. If this change can cause this to happen more, then my soundness rationale is wrong, and it's likely breaking.
In practice this seems super unlikely.
Anyway. That was a lot of typing.
Fixes https://github.com/rust-lang/rust/issues/80183
Use TrustedRandomAccess for in-place iterators where possible
This can speed up in-place iterators containing simple casts and transmutes from `Copy` types to any type of same size. `!Copy` types can't be optimized since `TrustedRandomAccess` isn't implemented for those iterators.
```
name on.b ns/iter o1.b ns/iter diff ns/iter diff % speedup
vec::bench_transmute 20 (40000 MB/s) 12 (66666 MB/s) -8 -40.00% x 1.67
```
Enable mutable noalias for LLVM >= 12
Enable mutable noalias by default on LLVM 12, as previously known miscompiles have been resolved. Now it's time to find the next one ;)
* The `-Z mutable-noalias` option no longer has an explicit default and accepts `-Z mutable-noalias=yes` and `-Z mutable-noalias=no` to override the LLVM version based default behavior.
* The decision on whether to apply the noalias attribute is moved into rustc_codegen_llvm. rustc_middle only provides us with the necessary information to make the decision.
* `noalias` is not emitted for types that are `!Unpin`, as a heuristic for self-referential structures (see #54878 and #63818).