Currently, `CStr::from_ptr` contains its own implementation of `strlen`
that uses `const_eval_select` to either call libc's `strlen` or use a
naive Rust implementation. Refactor that into its own function so we can
use it elsewhere in the module.
Fix implementation of `Duration::checked_div`
I ran across this while running some sanity checks on `time`. Quickcheck immediately found a bug, and as I'd modified the code from `std` I knew there was a bug here as well.
tl;dr this code fails ([playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=1189a3efcdfc192c27d6d87815359353))
```rust
use std::time::Duration;
fn main() {
assert_eq!(
Duration::new(1, 1).checked_div(7),
Some(Duration::new(0, 142_857_143)),
);
}
```
The existing code determines that 1/7 = 0 (seconds), 1/7 = 0 (nanoseconds), 1 billion / 7 = 142,857,142 (extra nanoseconds). The billion comes from multiplying the remainder of the seconds (1) by the number of nanoseconds in a second. However, **this wrongly ignores any remaining nanoseconds**. This PR takes that into consideration, adds a test, and also changes the roundabout way of calculating the remainder into directly computing it.
Note: This is _not_ a rounding error. This result divides evenly.
`@rustbot` label +A-time +C-bug +S-waiting-on-reviewer +T-libs
Go into more detail about panicking in drop.
This patch was sitting around in my drafts. I don't recall the motivation, but I think it was someone expressing confusion over “will likely abort” (since, in fact, a panicking drop _not_ caused by dropping while panicking will predictably _not_ abort).
I hope that the new text will leave people well-informed about why not to panic and when it is reasonable to panic.
Make `rustc_on_unimplemented` std-agnostic for `alloc::rc`
See https://github.com/rust-lang/rust/issues/112923
Just a few lines related to `alloc:rc` for `Send` and `Sync`.
That seems to be all of the `... = "std::..."` issues found, but there a few notes with `std::` inside them still.
r? `@WaffleLapkin`
Add `suggestion` for some `#[deprecated]` items
Consider code:
```rust
fn main() {
let _ = ["a", "b"].connect(" ");
}
```
Currently it shows deprecated warning:
```rust
warning: use of deprecated method `std::slice::<impl [T]>::connect`: renamed to join
--> src/main.rs:2:24
|
2 | let _ = ["a", "b"].connect(" ");
| ^^^^^^^
|
= note: `#[warn(deprecated)]` on by default
```
This PR adds `suggestion` for `connect` and some other deprecated items, so the warning will be changed to this:
```rust
warning: use of deprecated method `std::slice::<impl [T]>::connect`: renamed to join
--> src/main.rs:2:24
|
2 | let _ = ["a", "b"].connect(" ");
| ^^^^^^^
|
= note: `#[warn(deprecated)]` on by default
help: replace the use of the deprecated method
|
2 | let _ = ["a", "b"].join(" ");
| ^^^^
```
custom_mir: change Call() terminator syntax to something more readable
I find our current syntax very hard to read -- I cannot even remember the order of arguments, and having the "next block" *before* the actual function call is very counter-intuitive IMO. So I suggest we use `Call(ret_val = function(v), next_block)` instead.
r? `@JakobDegen`
rustdoc: Add lint `redundant_explicit_links`
Closes#87799.
- Lint warns by default
- Reworks link parser to cache original link's display text
r? `@jyn514`
Inline strlen_rt in CStr::from_ptr
This enables LLVM to optimize this function as if it was strlen (LLVM knows what it does, and can avoid calling it in certain situations) without having to enable std-aware LTO. This is essentially doing what https://github.com/rust-lang/rust/pull/90007 did, except updated for this function being `const`.
Pretty sure it's safe to roll-up, considering last time I did make this change it didn't affect performance (`CStr::from_ptr` isn't really used all that often in Rust code that is checked by rust-perf).
When I was learning Rust I looked for “a modulo function” and couldn’t
find one, so thought I had to write my own; it wasn't at all obvious
that a function with “rem” in the name was the function I wanted.
Hopefully this will save the next learner from that.
However, it does have the disadvantage that the top results in rustdoc
for “mod” are now these aliases instead of the Rust keyword, which
probably isn't ideal.
Optimizing the rest of bool's Ord implementation
After coming across issue #66780, I realized that the other functions provided by Ord (`min`, `max`, and `clamp`) were similarly inefficient for bool. This change provides implementations for them in terms of boolean operators, resulting in much simpler assembly and faster code.
Fixes issue #114653
[Comparison on Godbolt](https://rust.godbolt.org/z/5nb5P8e8j)
`max` assembly before:
```assembly
example::max:
mov eax, edi
mov ecx, eax
neg cl
mov edx, esi
not dl
cmp dl, cl
cmove eax, esi
ret
```
`max` assembly after:
```assembly
example::max:
mov eax, edi
or eax, esi
ret
```
`clamp` assembly before:
```assembly
example:🗜️
mov eax, esi
sub al, dl
inc al
cmp al, 2
jae .LBB1_1
mov eax, edi
sub al, sil
movzx ecx, dil
sub dil, dl
cmp dil, 1
movzx edx, dl
cmovne edx, ecx
cmp al, -1
movzx eax, sil
cmovne eax, edx
ret
.LBB1_1:
; identical assert! code
```
`clamp` assembly after:
```assembly
example:🗜️
test edx, edx
jne .LBB1_2
test sil, sil
jne .LBB1_3
.LBB1_2:
or dil, sil
and dil, dl
mov eax, edi
ret
.LBB1_3:
; identical assert! code
```
Cleaner assert_eq! & assert_ne! panic messages
This PR finishes refactoring of the assert messages per #94005. The panic message format change #112849 used to be part of this PR, but has been factored out and just merged. It might be better to keep both changes in the same release once FCP vote completes.
Modify panic message for `assert_eq!`, `assert_ne!`, the currently unstable `assert_matches!`, as well as the corresponding `debug_assert_*` macros.
```rust
assert_eq!(1 + 1, 3);
assert_eq!(1 + 1, 3, "my custom message value={}!", 42);
```
#### Old messages
```plain
thread 'main' panicked at $DIR/main.rs:6:5:
assertion failed: `(left == right)`
left: `2`,
right: `3`
```
```plain
thread 'main' panicked at $DIR/main.rs:6:5:
assertion failed: `(left == right)`
left: `2`,
right: `3`: my custom message value=42!
```
#### New messages
```plain
thread 'main' panicked at $DIR/main.rs:6:5:
assertion `left == right` failed
left: 2
right: 3
```
```plain
thread 'main' panicked at $DIR/main.rs:6:5:
assertion `left == right` failed: my custom message value=42!
left: 2
right: 3
```
History of fixing #94005
* #94016 was a lengthy PR that was abandoned
* #111030 was similar, but it stringified left and right arguments, and thus caused compile time performance issues, thus closed
* #112849 factored out the two-line formatting of all panic messages
Fixes#94005
r? `@m-ou-se`
Modify panic message for `assert_eq!`, `assert_ne!`, the currently unstable `assert_matches!`, as well as the corresponding `debug_assert_*` macros.
```rust
assert_eq!(1 + 1, 3);
assert_eq!(1 + 1, 3, "my custom message value={}!", 42);
```
```plain
thread 'main' panicked at $DIR/main.rs:6:5:
assertion failed: `(left == right)`
left: `2`,
right: `3`
```
```plain
thread 'main' panicked at $DIR/main.rs:6:5:
assertion failed: `(left == right)`
left: `2`,
right: `3`: my custom message value=42!
```
```plain
thread 'main' panicked at $DIR/main.rs:6:5:
assertion `left == right` failed
left: 2
right: 3
```
```plain
thread 'main' panicked at $DIR/main.rs:6:5:
assertion `left == right` failed: my custom message value=42!
left: 2
right: 3
```
This PR is a simpler subset of the #111030, but it does NOT stringify the original left and right source code assert expressions, thus should be faster to compile.
Rollup of 10 pull requests
Successful merges:
- #114711 (Infer `Lld::No` linker hint when the linker stem is a generic compiler driver)
- #114772 (Add `{Local}ModDefId` to more strongly type DefIds`)
- #114800 (std: add some missing repr(transparent))
- #114820 (Add test for unknown_lints from another file.)
- #114825 (Upgrade std to gimli 0.28.0)
- #114827 (Only consider object candidates for object-safe dyn types in new solver)
- #114828 (Probe when assembling upcast candidates so they don't step on eachother's toes in new solver)
- #114829 (Separate `consider_unsize_to_dyn_candidate` from other unsize candidates)
- #114830 (Clean up some bad UI testing annotations)
- #114831 (Check projection args before substitution in new solver)
r? `@ghost`
`@rustbot` modify labels: rollup
Don't panic in ceil_char_boundary
Implementing the alternative mentioned in this comment: https://github.com/rust-lang/rust/issues/93743#issuecomment-1579935853
Since `floor_char_boundary` will always work (rounding down to the length of the string is possible), it feels best for `ceil_char_boundary` to not panic either. However, the semantics of "rounding up" past the length of the string aren't very great, which is why the method originally panicked in these cases.
Taking into account how people are using this method, it feels best to simply return the end of the string in these cases, so that the result is still a valid char boundary.
std: add some missing repr(transparent)
For some types we don't want to stably guarantee this, so hide the `repr` from rustdoc. This nice approach was suggested by `@thomcc.`
add a csky-unknown-linux-gnuabiv2 target
This is the rustc side changes to support csky based Linux target(`csky-unknown-linux-gnuabiv2`).
Tier 3 policy:
> A tier 3 target must have a designated developer or developers (the "target maintainers") on record to be CCed when issues arise regarding the target. (The mechanism to track and CC such developers may evolve over time.)
I pledge to do my best maintaining it.
> Targets must use naming consistent with any existing targets; for instance, a target for the same CPU or OS as an existing Rust target should use the same name for that CPU or OS. Targets should normally use the same names and naming conventions as used elsewhere in the broader ecosystem beyond Rust (such as in other toolchains), unless they have a very good reason to diverge. Changing the name of a target can be highly disruptive, especially once the target reaches a higher tier, so getting the name right is important even for a tier 3 target.
This `csky` section is the arch name and the `unknown-linux` section is the same as other linux target, and `gnuabiv2` is from the cross-compile toolchain of `gcc`
> Target names should not introduce undue confusion or ambiguity unless absolutely necessary to maintain ecosystem compatibility. For example, if the name of the target makes people extremely likely to form incorrect beliefs about what it targets, the name should be changed or augmented to disambiguate it.
I think the explanation in platform support doc is enough to make this aspect clear.
> Tier 3 targets may have unusual requirements to build or use, but must not create legal issues or impose onerous legal terms for the Rust project or for Rust developers or users.
It's using open source tools only.
> The target must not introduce license incompatibilities.
No new license
> Anything added to the Rust repository must be under the standard Rust license (MIT OR Apache-2.0).
Understood.
> The target must not cause the Rust tools or libraries built for any other host (even when supporting cross-compilation to the target) to depend on any new dependency less permissive than the Rust licensing policy. This applies whether the dependency is a Rust crate that would require adding new license exceptions (as specified by the tidy tool in the rust-lang/rust repository), or whether the dependency is a native library or binary. In other words, the introduction of the target must not cause a user installing or running a version of Rust or the Rust tools to be subject to any new license requirements.
There are no new dependencies/features required.
> Compiling, linking, and emitting functional binaries, libraries, or other code for the target (whether hosted on the target itself or cross-compiling from another target) must not depend on proprietary (non-FOSS) libraries. Host tools built for the target itself may depend on the ordinary runtime libraries supplied by the platform and commonly used by other applications built for the target, but those libraries must not be required for code generation for the target; cross-compilation to the target must not require such libraries at all. For instance, rustc built for the target may depend on a common proprietary C runtime library or console output library, but must not depend on a proprietary code generation library or code optimization library. Rust's license permits such combinations, but the Rust project has no interest in maintaining such combinations within the scope of Rust itself, even at tier 3.
As previously said it's using open source tools only.
> "onerous" here is an intentionally subjective term. At a minimum, "onerous" legal/licensing terms include but are not limited to: non-disclosure requirements, non-compete requirements, contributor license agreements (CLAs) or equivalent, "non-commercial"/"research-only"/etc terms, requirements conditional on the employer or employment of any particular Rust developers, revocable terms, any requirements that create liability for the Rust project or its developers or users, or any requirements that adversely affect the livelihood or prospects of the Rust project or its developers or users.
There are no such terms present/
> Neither this policy nor any decisions made regarding targets shall create any binding agreement or estoppel by any party. If any member of an approving Rust team serves as one of the maintainers of a target, or has any legal or employment requirement (explicit or implicit) that might affect their decisions regarding a target, they must recuse themselves from any approval decisions regarding the target's tier status, though they may otherwise participate in discussions.
I'm not the reviewer here.
> This requirement does not prevent part or all of this policy from being cited in an explicit contract or work agreement (e.g. to implement or maintain support for a target). This requirement exists to ensure that a developer or team responsible for reviewing and approving a target does not face any legal threats or obligations that would prevent them from freely exercising their judgment in such approval, even if such judgment involves subjective matters or goes beyond the letter of these requirements.
I'm not the reviewer here.
> Tier 3 targets should attempt to implement as much of the standard libraries as possible and appropriate (core for most targets, alloc for targets that can support dynamic memory allocation, std for targets with an operating system or equivalent layer of system-provided functionality), but may leave some code unimplemented (either unavailable or stubbed out as appropriate), whether because the target makes it impossible to implement or challenging to implement. The authors of pull requests are not obligated to avoid calling any portions of the standard library on the basis of a tier 3 target not implementing those portions.
It supports for std
> The target must provide documentation for the Rust community explaining how to build for the target, using cross-compilation if possible. If the target supports running binaries, or running tests (even if they do not pass), the documentation must explain how to run such binaries or tests for the target, using emulation if possible or dedicated hardware if necessary.
I have added the documentation, and I think it's clear.
> Tier 3 targets must not impose burden on the authors of pull requests, or other developers in the community, to maintain the target. In particular, do not post comments (automated or manual) on a PR that derail or suggest a block on the PR based on a tier 3 target. Do not send automated messages or notifications (via any medium, including via `@)` to a PR author or others involved with a PR regarding a tier 3 target, unless they have opted into such messages.
Understood.
> Backlinks such as those generated by the issue/PR tracker when linking to an issue or PR are not considered a violation of this policy, within reason. However, such messages (even on a separate repository) must not generate notifications to anyone involved with a PR who has not requested such notifications.
Understood.
> Patches adding or updating tier 3 targets must not break any existing tier 2 or tier 1 target, and must not knowingly break another tier 3 target without approval of either the compiler team or the maintainers of the other tier 3 target.
I believe I didn't break any other target.
> In particular, this may come up when working on closely related targets, such as variations of the same architecture with different features. Avoid introducing unconditional uses of features that another variation of the target may not have; use conditional compilation or runtime detection, as appropriate, to let each target run code supported by that target.
I think there are no such problems in this PR.
core/any: remove Provider trait, rename Demand to Request
This touches on two WIP features:
* `error_generic_member_access`
* tracking issue: https://github.com/rust-lang/rust/issues/99301
* RFC (WIP): https://github.com/rust-lang/rfcs/pull/2895
* `provide_any`
* tracking issue: https://github.com/rust-lang/rust/issues/96024
* RFC: https://github.com/rust-lang/rfcs/pull/3192
The changes in this PR are intended to address libs meeting feedback summarized by `@Amanieu` in https://github.com/rust-lang/rust/issues/96024#issuecomment-1554773172
The specific items this PR addresses so far are:
> We feel that the names "demand" and "request" are somewhat synonymous and would like only one of those to be used for better consistency.
I went with `Request` here since it sounds nicer, but I'm mildly concerned that at first glance it could be confused with the use of the word in networking context.
> The Provider trait should be deleted and its functionality should be merged into Error. We are happy to only provide an API that is only usable with Error. If there is demand for other uses then this can be provided through an external crate.
The net impact this PR has is that examples which previously looked like
```
core::any::request_ref::<String>(&err).unwramp()
```
now look like
```
(&err as &dyn core::error::Error).request_value::<String>().unwrap()
```
These are methods that based on the type hint when called return an `Option<T>` of that type. I'll admit I don't fully understand how that's done, but it involves `core::any::tags::Type` and `core::any::TaggedOption`, neither of which are exposed in the public API, to construct a `Request` which is then passed to the `Error.provide` method.
Something that I'm curious about is whether or not they are essential to the use of `Request` types (prior to this PR referred to as `Demand`) and if so does the fact that they are kept private imply that `Request`s are only meant to be constructed privately within the standard library? That's what it looks like to me.
These methods ultimately call into code that looks like:
```
/// Request a specific value by tag from the `Error`.
fn request_by_type_tag<'a, I>(err: &'a (impl Error + ?Sized)) -> Option<I::Reified>
where
I: tags::Type<'a>,
{
let mut tagged = core::any::TaggedOption::<'a, I>(None);
err.provide(tagged.as_request());
tagged.0
}
```
As far as the `Request` API is concerned, one suggestion I would like to make is that the previous example should look more like this:
```
/// Request a specific value by tag from the `Error`.
fn request_by_type_tag<'a, I>(err: &'a (impl Error + ?Sized)) -> Option<I::Reified>
where
I: tags::Type<'a>,
{
let tagged_request = core::any::Request<I>::new_tagged();
err.provide(tagged_request);
tagged.0
}
```
This makes it possible for anyone to construct a `Request` for use in their own projects without exposing an implementation detail like `TaggedOption` in the API surface.
Otherwise noteworthy is that I had to add `pub(crate)` on both `core::any::TaggedOption` and `core::any::tags` since `Request`s now need to be constructed in the `core::error` module. I considered moving `TaggedOption` into the `core::error` module but again I figured it's an implementation detail of `Request` and belongs closer to that.
At the time I am opening this PR, I have not yet looked into the following bit of feedback:
> We took a look at the generated code and found that LLVM is unable to optimize multiple .provide_* calls into a switch table because each call fetches the type id from Erased::type_id separately each time and the compiler doesn't know that these calls all return the same value. This should be fixed.
This is what I'll focus on next while waiting for feedback on the progress so far. I suspect that learning more about the type IDs will help me understand the need for `TaggedOption` a little better.
* remove `impl Provider for Error`
* rename `Demand` to `Request`
* update docstrings to focus on the conceptual API provided by `Request`
* move `core::any::{request_ref, request_value}` functions into `core::error`
* move `core::any::tag`, `core::any::Request`, an `core::any::TaggedOption` into `core::error`
* replace `provide_any` feature name w/ `error_generic_member_access`
* move `core::error::request_{ref,value} tests into core::tests::error module
* update unit and doc tests
Add `Iterator::map_windows`
Tracking issue: #87155.
This is inherited from the old PR #82413.
Unlike #82413, this PR implements the `MapWindows` to be lazy: only when pulling from the outer iterator, `.next()` of the inner iterator will be called.
## Implementaion Steps
- [x] Implement `MapWindows` to keep the iterators' [*Laziness*](https://doc.rust-lang.org/std/iter/index.html#laziness) contract.
- [x] Fix the known bug of memory access error.
- [ ] Full specialization of iterator-related traits for `MapWindows`.
- [x] `Iterator::size_hint`,
- [x] ~`Iterator::count`~,
- [x] `ExactSizeIterator` (when `I: ExactSizeIterator`),
- [x] ~`TrustedLen` (when `I: TrustedLen`)~,
- [x] `FusedIterator`,
- [x] ~`Iterator::advance_by`~,
- [x] ~`Iterator::nth`~,
- [ ] ...
- [ ] More tests and docs.
## Unresolved Questions:
- [ ] Is there any more iterator-related traits should be specialized?
- [ ] Is the double-space buffer worth?
- [ ] Should there be `rmap_windows` or something else?
- [ ] Taking GAT for consideration, should the mapper function be `FnMut(&[I::Item; N]) -> R` or something like `FnMut(ArrayView<'_, I::Item, N>) -> R`? Where `ArrayView` is mentioned in https://github.com/rust-lang/generic-associated-types-initiative/issues/2.
- It can save memory, only the same size as the array window is needed,
- It is more efficient, which requires less data copies,
- It is possibly compatible with the GATified version of `LendingIterator::windows`.
- But it prevents the array pattern matching like `iter.map_windows(|_arr: [_; N]| ())`, unless we extend the array pattern to allow matching the `ArrayView`.
Tell LLVM that the negation in `<*const T>::sub` cannot overflow
Today it's just `sub` <https://rust.godbolt.org/z/8EzEPnMr5>; with this PR it's `sub nsw`.
This is inherited from the old PR.
This method returns an iterator over mapped windows of the starting
iterator. Adding the more straight-forward `Iterator::windows` is not
easily possible right now as the items are stored in the iterator type,
meaning the `next` call would return references to `self`. This is not
allowed by the current `Iterator` trait design. This might change once
GATs have landed.
The idea has been brought up by @m-ou-se here:
https://rust-lang.zulipchat.com/#narrow/stream/219381-t-libs/topic/Iterator.3A.3A.7Bpairwise.2C.20windows.7D/near/224587771
Co-authored-by: Lukas Kalbertodt <lukas.kalbertodt@gmail.com>
The `debug_assert_matches` macro was marked with the `#[macro_export]` attribute,
despite being a declarative macro/macro 2.0, for which the exporting rules are similar
to items. In fact, `#[macro_export]` on a decl macro has no effect on its visibility.
Add a new `compare_bytes` intrinsic instead of calling `memcmp` directly
As discussed in #113435, this lets the backends be the place that can have the "don't call the function if n == 0" logic, if it's needed for the target. (I didn't actually *add* those checks, though, since as I understood it we didn't actually need them on known targets?)
Doing this also let me make it `const` (unstable), which I don't think `extern "C" fn memcmp` can be.
cc `@RalfJung` `@Amanieu`
Optimize `Iterator` implementation for `&mut impl Iterator + Sized`
This adds a specialization trait to forward `fold`, `try_fold`,... to the inner iterator where possible
Add `internal_features` lint
Implements https://github.com/rust-lang/compiler-team/issues/596
Also requires some more test blessing for codegen tests etc
`@jyn514` had the idea of just `allow`ing the lint by default in the test suite. I'm not sure whether this is a good idea, but it's definitely one worth considering. Additional input encouraged.
Expand, rename and improve `incorrect_fn_null_checks` lint
This PR,
- firstly, expand the lint by now linting on references
- secondly, it renames the lint `incorrect_fn_null_checks` -> `useless_ptr_null_checks`
- and thirdly it improves the lint by catching `ptr::from_mut`, `ptr::from_ref`, as well as `<*mut _>::cast` and `<*const _>::cast_mut`
Fixes https://github.com/rust-lang/rust/issues/113601
cc ```@est31```
It lints against features that are inteded to be internal to the
compiler and standard library. Implements MCP #596.
We allow `internal_features` in the standard library and compiler as those
use many features and this _is_ the standard library from the "internal to the compiler and
standard library" after all.
Marking some features as internal wasn't exactly the most scientific approach, I just marked some
mostly obvious features. While there is a categorization in the macro,
it's not very well upheld (should probably be fixed in another PR).
We always pass `-Ainternal_features` in the testsuite
About 400 UI tests and several other tests use internal features.
Instead of throwing the attribute on each one, just always allow them.
There's nothing wrong with testing internal features^^
Clarify documentation for `CStr`
* Better differentiate summaries for `from_bytes_until_nul` and `from_bytes_with_nul`
* Add some links where they may be helpful
Improve `invalid_reference_casting` lint
This PR is a follow-up to https://github.com/rust-lang/rust/pull/111567 and https://github.com/rust-lang/rust/pull/113422.
This PR does multiple things:
- First it adds support for deferred de-reference, the goal is to support code like this, where the casting and de-reference are not done on the same expression
```rust
let myself = self as *const Self as *mut Self;
*myself = Self::Ready(value);
```
- Second it does not lint anymore on SB/TB UB code by only checking assignments (`=`, `+=`, ...) and creation of mutable references `&mut *`
- Thirdly it greatly improves the diagnostics in particular for cast from `&mut` to `&mut` or assignments
- ~~And lastly it renames the lint from `cast_ref_to_mut` to `invalid_reference_casting` which is more consistent with the ["rules"](https://github.com/rust-lang/rust-clippy/issues/2845) and also more consistent with what the lint checks~~ *https://github.com/rust-lang/rust/pull/113422*
This PR is best reviewed commit by commit.
r? compiler
Change default panic handler message format.
This changes the default panic hook's message format from:
```
thread '{thread}' panicked at '{message}', {location}
```
to
```
thread '{thread}' panicked at {location}:
{message}
```
This puts the message on its own line without surrounding quotes, making it easiser to read. For example:
Before:
```
thread 'main' panicked at 'env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`', src/main.rs:4:6
```
After:
```
thread 'main' panicked at src/main.rs:4:6:
env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`
```
---
See this PR by `@nyurik,` which does that for only multi-line messages (specifically because of `assert_eq`): https://github.com/rust-lang/rust/pull/111071
This is the change that does that for *all* panic messages.
Make `Debug` representations of `[Lazy, Once]*[Cell, Lock]` consistent with `Mutex` and `RwLock`
`Mutex` prints `<locked>` as a field value when its inner value cannot be accessed, but the lazy types print a fixed string like "`OnceCell(Uninit)`". This could cause confusion if the inner type is a unit type named `Uninit` and does not respect the pretty-printing flag. With this change, the format message is now "`OnceCell(<uninit>)`", consistent with `Mutex`.
`const`-stablilize `NonNull::as_ref`
A bunch of pointer to reference methods have been made unstably const some time ago in #91823 under the feature gate `const_ptr_as_ref`.
Out of these, `NonNull::as_ref` can be implemented as a `const fn` in stable rust today, so i hereby propose to const stabilize this function only.
Tracking issue: #91822
``@rustbot`` label +T-libs-api -T-libs
Updated lines doc to include trailing carriage return note
Updated `str::lines` doc to include explicit info about (trailing) carriage returns.
Reference: #100311
fix(resolve): update the ambiguity glob binding as warning recursively
Fixes#47525Fixes#56593, but `issue-56593-2.rs` is not fixed to ensure backward compatibility.
Fixes#98467Fixes#105235Fixes#112713
This PR had added a field called `warn_ambiguous` in `NameBinding` which is only for back compatibly reason and used for lint.
More details: https://github.com/rust-lang/rust/pull/112743
r? `@petrochenkov`
Rollup of 7 pull requests
Successful merges:
- #113773 (Don't attempt to compute layout of type referencing error)
- #114107 (Prevent people from assigning me as a PR reviewer)
- #114124 (tests/ui/proc-macro/*: Migrate FIXMEs to check-pass)
- #114171 (Fix switch-stdout test for none unix/windows platforms)
- #114172 (Fix issue_15149 test for the SGX target)
- #114173 (btree/map.rs: remove "Basic usage" text)
- #114174 (doc: replace wrong punctuation mark)
r? `@ghost`
`@rustbot` modify labels: rollup
docs: fmt::Debug*: Fix comments for finish method.
In the code sample for the `finish` method on `DebugList`, `DebugMap`, and `DebugSet`, refer to finishing the list, map, or set, rather than struct as it did.
Optimize `AtomicBool` for target that don't support byte-sized atomics
`AtomicBool` is defined to have the same layout as `bool`, which means that we guarantee that it has a size of 1 byte. However on certain architectures such as RISC-V, LLVM will emulate byte atomics using a masked CAS loop on an aligned word.
We can take advantage of the fact that `bool` only ever has a value of 0 or 1 to replace `swap` operations with `and`/`or` operations that LLVM can lower to word-sized atomic `and`/`or` operations. This takes advantage of the fact that the incoming value to a `swap` or `compare_exchange` for `AtomicBool` is often a compile-time constant.
### Example
```rust
pub fn swap_true(atomic: &AtomicBool) -> bool {
atomic.swap(true, Ordering::Relaxed)
}
```
### Old
```asm
andi a1, a0, -4
slli a0, a0, 3
li a2, 255
sllw a2, a2, a0
li a3, 1
sllw a3, a3, a0
slli a3, a3, 32
srli a3, a3, 32
.LBB1_1:
lr.w a4, (a1)
mv a5, a3
xor a5, a5, a4
and a5, a5, a2
xor a5, a5, a4
sc.w a5, a5, (a1)
bnez a5, .LBB1_1
srlw a0, a4, a0
andi a0, a0, 255
snez a0, a0
ret
```
### New
```asm
andi a1, a0, -4
slli a0, a0, 3
li a2, 1
sllw a2, a2, a0
amoor.w a1, a2, (a1)
srlw a0, a1, a0
andi a0, a0, 255
snez a0, a0
ret
```
In the code sample for the `finish` method on `DebugList`,
`DebugMap`, and `DebugSet`, refer to finishing the list, map, or
set, rather than struct as it did.
`AtomicBool` is defined to have the same layout as `bool`, which means
that we guarantee that it has a size of 1 byte. However on certain
architectures such as RISC-V, LLVM will emulate byte atomics using a
masked CAS loop on an aligned word.
We can take advantage of the fact that `bool` only ever has a value of 0
or 1 to replace `swap` operations with `and`/`or` operations that LLVM
can lower to word-sized atomic `and`/`or` operations. This takes
advantage of the fact that the incoming value to a `swap` or
`compare_exchange` for `AtomicBool` is often a compile-time constant.
delete [allow(unused_unsafe)] from issue #74838
While looking into issue #111288 I noticed the following `#[allow(...)]` with a `FIXME` asking for it to be removed. Deleting the `#[allow(...)]` does not seem to break anything, it seems like the lint has been updated for unsafe blocks in macros?
Fix size_hint for EncodeUtf16
More realistic upper and lower bounds, and handle the case where the iterator is located within a surrogate pair.
Resolves#113897
Update the tracking issue for `const_cstr_from_ptr`
Tracking issue #101719 was for `const_cstr_methods`, #113219 is a new issue specific for `const_cstr_from_ptr`.
(I believe #101719 could also be closed)
```@rustbot``` label +T-libs-api +A-docs
remove the unstable `core::sync::atomic::ATOMIC_*_INIT` constants
Tracking issue: #99069
It would be weird to ever stabilise these as they are already deprecated.
Enable coinduction support for Safe Transmute
This patch adds the `#[rustc_coinductive]` annotation to `BikeshedIntrinsicFrom`, so that it's possible to compute transmutability for recursive types.
## Motivation
Safe Transmute currently already supports references (#110662). However, if a type is implemented recursively, it leads to an infinite loop when we try to check if transmutation is safe.
A couple simple examples that one might want to write, that are currently not possible to check transmutability for:
```rs
#[repr(C)] struct A(&'static B);
#[repr(C)] struct B(&'static A);
```
```rs
#[repr(C)]
enum IList<'a> { Nil, Cons(isize, &'a IList<'a>) }
#[repr(C)]
enum UList<'a> { Nil, Cons(usize, &'a UList<'a>) }
```
Previously, `@jswrenn` was considering writing a co-inductive solver from scratch, just for the `rustc_tranmsute` crate. Later on as I started working on Safe Transmute myself, I came across the `#[rustc_coinductive]` annotation, which is currently only being used for the `Sized` trait. Leveraging this trait actually solved the problem entirely, and it saves a lot of duplicate work that would have had to happen in `rustc_transmute`.
Uplift `clippy::fn_null_check` lint
This PR aims at uplifting the `clippy::fn_null_check` lint into rustc.
## `incorrect_fn_null_checks`
(warn-by-default)
The `incorrect_fn_null_checks` lint checks for expression that checks if a function pointer is null.
### Example
```rust
let fn_ptr: fn() = /* somehow obtained nullable function pointer */
if (fn_ptr as *const ()).is_null() { /* ... */ }
```
### Explanation
Function pointers are assumed to be non-null, checking for their nullity is incorrect.
-----
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
enable test_join test in Miri
Miri for quite a while now has a hack to support self-referential generators: non-`Unique` mutable references are exempt from aliasing conditions. So we can run this test now. (It passes.)
Also extend a comment in a Vec test, while I am at it.
Mark wrapped intrinsics as inline(always)
This should mitigate having the inliner decide not to inline when the architecture is lacking an implementation of
TargetTransformInfo::areInlineCompatible aware of the target features (e.g. PowerPC as today).
See https://github.com/rust-lang/stdarch/pull/1443#issuecomment-1613788080
This should mitigate having the inliner decide not to inline when
the architecture is lacking an implementation of
TargetTransformInfo::areInlineCompatible aware of the target
features (e.g. PowerPC as today).
Stabilize `const_cstr_methods`
This PR seeks to stabilize `const_cstr_methods`. Fixes most of #101719
## New const stable API
```rust
impl CStr {
// depends: memchr
pub const fn from_bytes_with_nul(bytes: &[u8]) -> Result<&Self, FromBytesWithNulError> {...}
// depends: const_slice_index
pub const fn to_bytes(&self) -> &[u8] {}
// depends: pointer casts
pub const fn to_bytes_with_nul(&self) -> &[u8] {}
// depends: str::from_utf8
pub const fn to_str(&self) -> Result<&str, str::Utf8Error> {}
}
```
I don't think any of these methods will have any issue when `CStr` becomes a thin pointer as long as `memchr` is const (which also allows for const `strlen`) .
## Notes
- `from_bytes_until_nul` relies on `const_slice_index`, which relies on `const_trait_impls`, and generally this should be avoided. After talking with Oli, it should be OK in this case because we could replace the ranges with pointer tricks if needed (worst case being those feature gates disappear). https://github.com/rust-lang/rust/pull/107624#discussion_r1101468480
- Making `from_ptr` const is deferred because it depends on `const_eval_select`. I have moved this under the new flag `const_cstr_from_ptr` https://github.com/rust-lang/rust/pull/107624#discussion_r1101555239
cc ``@oli-obk`` I think you're the const expert
``@rustbot`` modify labels: +T-libs-api +needs-fcp
This patch adds the `#[rustc_coinductive]` annotation to
`BikeshedIntrinsicFrom`, so that it's possible to compute transmutability for
recursive types.
Specialize `StepBy<Range<{integer}>>`
OLD
iter::bench_range_step_by_fold_u16 700.00ns/iter +/- 10.00ns
iter::bench_range_step_by_fold_usize 519.00ns/iter +/- 6.00ns
iter::bench_range_step_by_loop_u32 555.00ns/iter +/- 7.00ns
iter::bench_range_step_by_sum_reducible 37.00ns/iter +/- 0.00ns
NEW
iter::bench_range_step_by_fold_u16 49.00ns/iter +/- 0.00ns
iter::bench_range_step_by_fold_usize 194.00ns/iter +/- 1.00ns
iter::bench_range_step_by_loop_u32 98.00ns/iter +/- 0.00ns
iter::bench_range_step_by_sum_reducible 1.00ns/iter +/- 0.00ns
NEW + `-Ctarget-cpu=x86-64-v3`
iter::bench_range_step_by_fold_u16 22.00ns/iter +/- 0.00ns
iter::bench_range_step_by_fold_usize 80.00ns/iter +/- 1.00ns
iter::bench_range_step_by_loop_u32 41.00ns/iter +/- 0.00ns
iter::bench_range_step_by_sum_reducible 1.00ns/iter +/- 0.00ns
I have only optimized for walltime of those methods, I haven't tested whether it eliminates bounds checks when indexing into slices via things like `(0..slice.len()).step_by(16)`.
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.
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`
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.
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`
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.
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
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`
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.
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