Commit Graph

11635 Commits

Author SHA1 Message Date
yanchith
e0e355dd25 Impl allocator function for iterators 2023-06-11 22:56:16 +02:00
yanchith
d9b6181d2f Remove explicit lifetimes 2023-06-11 22:42:50 +02:00
Ralf Jung
3b9b4e5e3d reorder attributes to make miri-test-libstd work again 2023-06-11 22:15:46 +02:00
Matthias Krüger
0ff35f27b0
Rollup merge of #112497 - icecream17:patch-1, r=Mark-Simulacrum
abs_sub: fix typo 0[-:][+.]0
2023-06-11 01:57:28 +02:00
Matthias Krüger
e4f6b3d39e
Rollup merge of #112484 - bdbai:fix/uwpntdll, r=ChrisDenton
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.
2023-06-11 01:57:26 +02:00
Ibraheem Ahmed
5f56956b3c implement Sync for mpsc::Sender 2023-06-10 19:22:07 -04:00
icecream17
83d7826753
abs_sub: fix typo 0[-:][+.]0 2023-06-10 10:45:50 -05:00
bors
788c98df59 Auto merge of #111818 - Urgau:uplift_cmp_nan, r=cjgillot
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
2023-06-10 12:47:51 +00:00
bdbai
cd523f2f18 Keep uwp specific code in sync with windows-sys 2023-06-10 20:47:10 +08:00
bdbai
48e410e317 Lazy load ntdll functions on UWP 2023-06-10 16:34:20 +08:00
Urgau
3681285df7 Add diagnostic items for f32::NAN and f64::NAN 2023-06-09 17:46:33 +02:00
bors
397641f3bd Auto merge of #112465 - GuillaumeGomez:rollup-gyh5buc, r=GuillaumeGomez
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
2023-06-09 15:37:22 +00:00
bors
d7ad9d9797 Auto merge of #111530 - Urgau:uplift_undropped_manually_drops, r=compiler-errors
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
2023-06-09 12:44:23 +00:00
yanchith
4df4c0d00b Don't explicitly name Global 2023-06-09 12:19:17 +02:00
yanchith
767a7119a0 Pass tidy again 2023-06-09 12:02:25 +02:00
yanchith
208da513cc Add allocator function 2023-06-09 11:53:28 +02:00
yanchith
7a9f282528 Reallocatorize after merge 2023-06-09 11:48:11 +02:00
yanchith
cb5c011670 Merge branch 'master' into binary-heap-ta 2023-06-09 11:22:08 +02:00
Guillaume Gomez
2ce7cd906b Fix intra-doc links from pointer appearing in windows HANDLE type alias 2023-06-09 10:36:22 +02:00
Matthias Krüger
8747c0ebea
Rollup merge of #109953 - thomcc:thomcc/typeid128, r=WaffleLapkin
Use 128 bits for TypeId hash

Preliminary/Draft impl of https://github.com/rust-lang/compiler-team/issues/608

Prior art (probably incomplete list)
- https://github.com/rust-lang/rust/pull/75923
- https://github.com/rust-lang/rust/pull/95845
2023-06-08 12:36:17 +02:00
Urgau
d9d1c76ded Allow undropped_manually_drops for some tests 2023-06-08 11:41:34 +02:00
bors
80917360d3 Auto merge of #112292 - thomcc:tls-ohno, r=m-ou-se
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.
2023-06-08 04:44:08 +00:00
Thom Chiovoloni
b512004a4a
Fix typo
Co-authored-by: bjorn3 <17426603+bjorn3@users.noreply.github.com>
2023-06-07 21:27:51 -07:00
bors
10b7e468f3 Auto merge of #96875 - SabrinaJewson:noop-waker, r=m-ou-se
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
2023-06-07 06:04:32 +00:00
bors
b3dd578767 Auto merge of #111819 - nikarh:vita-improved, r=Amanieu
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.
2023-06-07 03:20:15 +00:00
Dan McGregor
e99f7ed071 Fix documentation build on FreeBSD
After the socket ancillary data implementation was introduced, the
build was broken on FreeBSD, add the same workaround as for the
existing implementations.
2023-06-06 10:28:10 -06:00
Nikolay Arhipov
032857e7e4 Bumped libc version 2023-06-06 16:09:05 +03:00
David Carlier
25b3751fd1 std: available_parallelism using native netbsd api first
before falling back to existing code paths like FreeBSD does.
2023-06-06 06:34:27 +01:00
Nikolay Arhipov
ac48d49ff8 Simplified bool to int conversion 2023-06-05 19:26:04 +03:00
Nikolay Arhipov
50117af409 Std support improvement for ps vita target 2023-06-05 19:14:09 +03:00
Guillaume Gomez
200d03acad
Rollup merge of #112263 - GrishaVar:remove-extend-element, r=scottmcm
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`
2023-06-05 17:02:51 +02:00
Thom Chiovoloni
70e1dc9967
Avoid unwind across extern "C" in thread_local::fast_local.rs 2023-06-04 14:54:28 -07:00
Thom Chiovoloni
9e5573a0d2
Use 128 bits for TypeId hash
- 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
2023-06-04 08:34:48 -07:00
Grisha Vartanyan
dd2bd03d0a Remove ExtendWith and ExtendElement 2023-06-04 15:55:34 +02:00
Matthias Krüger
cbc3e3f641
Rollup merge of #112172 - tshepang:patch-1, r=Mark-Simulacrum
doc: improve explanation
2023-06-04 13:21:27 +02:00
Matthias Krüger
7ee2505529
Rollup merge of #109093 - Dante-Broggi:patch-2, r=joshtriplett
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`
2023-06-04 13:21:25 +02:00
Matthias Krüger
6e024ecab8
Rollup merge of #111702 - cgwalters:option-map-or-else-with-result, r=Mark-Simulacrum
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.
2023-06-03 20:38:11 +02:00
bors
1e17cef9e2 Auto merge of #109432 - flba-eb:108594_forkspawn_exponential_backoff, r=workingjubilee
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
2023-06-03 10:06:59 +00:00
Matthias Krüger
4435544c35
Rollup merge of #112206 - k0ur0x:typo, r=Nilstrieb
Fix typo in `std::cell` module docs
2023-06-02 18:12:47 +02:00
Matthias Krüger
a3b639ce43
Rollup merge of #111647 - klensy:cstr, r=oli-obk
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
2023-06-02 18:12:45 +02:00
Florian Bartels
716cc5ac93 Only determine clock res once; give up before sleeping more than 1 second 2023-06-02 17:52:14 +02:00
Florian Bartels
bdb475cf6c Retry to fork/spawn with exponential backoff 2023-06-02 16:12:21 +02:00
Kourosh
9df4572277
Fix typo in std::cell module docs 2023-06-02 15:30:40 +03:30
klensy
2f459f7f14 fix ptr cast 2023-06-02 11:26:34 +03:00
Michael Goulet
24404e6409
Rollup merge of #111670 - compiler-errors:const-param-ty, r=BoxyUwU
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`
2023-06-01 23:07:36 -07:00
Trevor Gross
5cb701f379 Stabilize 'const_cstr_methods' 2023-06-01 17:39:18 -04:00
Matthias Krüger
a66ba9b10b
Rollup merge of #112154 - ShaneEverittM:zero-len-utf16, r=thomcc
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.
2023-06-01 22:47:32 +02:00
Michael Goulet
a9fcb524ff Impl ConstParamTy for tuples, make PartialStructuralEq a supertrait too 2023-06-01 18:21:42 +00:00
Boxy
bbf41279fa Require that const param tys implement ConstParamTy 2023-06-01 18:03:59 +00:00
Tshepang Mbambo
793fa8d7c5
doc: improve explanation 2023-06-01 12:55:58 +02:00
Dylan DPC
129c559764
Rollup merge of #112141 - anna-singleton:issue-111655-fix, r=thomcc
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.
2023-06-01 11:09:45 +05:30
bors
ba1690bedd Auto merge of #111567 - Urgau:uplift_cast_ref_to_mut, r=b-naber
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
2023-06-01 01:27:32 +00:00
Shane Murphy
1293c17205 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.
2023-05-31 17:25:53 -07:00
klensy
f212ba6d6d use c literals in library 2023-05-31 19:41:51 +03:00
anna-singleton
2eeb7693c5 remove reference to Into in ? operator core/std docs, fix 111655 2023-05-31 15:51:28 +01:00
bors
ad8304a0d5 Auto merge of #111076 - notriddle:notriddle/silence-private-dep-trait-impl-suggestions, r=cjgillot
diagnostics: exclude indirect private deps from trait impl suggest

Fixes #88696
2023-05-31 13:47:36 +00:00
Urgau
a51ad131e6 Add diagnostic items for ptr::cast_mut and ptr::from_ref 2023-05-31 12:26:36 +02:00
Matthias Krüger
2054acb0a4
Rollup merge of #112103 - Mark-Simulacrum:bootstrap-update, r=clubby789
Bootstrap update to 1.71 beta

Best reviewed by-commit.
2023-05-31 11:19:09 +02:00
bors
617d3d6d72 Auto merge of #112127 - matthiaskrgr:rollup-77pt893, r=matthiaskrgr
Rollup of 7 pull requests

Successful merges:

 - #112031 (Migrate  `item_proc_macro` to Askama)
 - #112053 (Remove `-Zcgu-partitioning-strategy`.)
 - #112069 (offset_of: don't require type to be `Sized`)
 - #112084 (enhancements on  build_helper utilization and rustdoc-gui-test)
 - #112096 (Remove array_zip)
 - #112108 (Fix re-export of doc hidden item inside private item not displayed)
 - #112113 (rustdoc: simplify `clean` by removing `FnRetTy`)

r? `@ghost`
`@rustbot` modify labels: rollup
2023-05-31 05:42:26 +00:00
Matthias Krüger
88160ab94c
Rollup merge of #112096 - workingjubilee:array-unzip, r=scottmcm
Remove array_zip

`[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.

- FCP concluded in https://github.com/rust-lang/rust/issues/80094#issuecomment-1468300057
- Closes https://github.com/rust-lang/rust/issues/80094
- Closes https://github.com/rust-lang/rust/issues/103555

Could use review to make sure we aren't losing any essential codegen tests.
r? `@scottmcm`
2023-05-31 07:07:02 +02:00
bors
f51fca3af3 Auto merge of #112120 - weihanglo:update-cargo, r=ehuss
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`
2023-05-31 03:03:10 +00:00
Weihang Lo
5abff3753a
Explicit set workspace.resolver = "1"
rust-lang/cargo#10910 starts emitting warning if resolver is not set
for 2021 edition package. We want to surpress the warning for now.
2023-05-31 00:08:11 +01:00
bors
9610dfe5a9 Auto merge of #109698 - epage:wtf, r=Amanieu
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
2023-05-30 21:26:22 +00:00
Mark Rousskov
42e757192d Bump to latest beta compiler 2023-05-30 08:00:10 -04:00
Mark Rousskov
4f9b394c8a Swap out CURRENT_RUSTC_VERSION to 1.71.0 2023-05-30 07:54:29 -04:00
Nilstrieb
7a4006cc52
Rollup merge of #111543 - Urgau:uplift_invalid_utf8_in_unchecked, r=WaffleLapkin
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
2023-05-30 12:57:38 +02:00
Nilstrieb
18c9baf4fe
Rollup merge of #107916 - reez12g:issue-107040, r=Amanieu
fix comment on Allocator trait

fixes https://github.com/rust-lang/rust/issues/107040
2023-05-30 12:57:38 +02:00
Jubilee Young
472230d192 Remove array_zip
`[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.
2023-05-30 00:40:39 -07:00
reez12g
000cd9b5fb fix comment on Allocator trait 2023-05-30 13:56:57 +09:00
Scott McMurray
11fa1764ee Make TrustedStep require Copy
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`.
2023-05-29 13:19:47 -07:00
Matthias Krüger
e71b3b3cfa
Rollup merge of #112045 - Sp00ph:update_current_impl, r=Amanieu
Followup to #111973

I somehow forgot to update the comment on `select_nth_unstable_by_key` in #111973, so this PR fixes that.

r? `@Amanieu`
2023-05-29 04:03:03 +02:00
Markus Everling
448a388387 Update current impl comment for select_nth_unstable_by_key 2023-05-28 16:12:48 +00:00
Markus Everling
62ee9e1d0a Update runtime guarantee for select_nth_unstable 2023-05-28 16:09:55 +00:00
est31
3ab0d90b7e Stabilize String::leak 2023-05-28 12:26:30 +02:00
Matthias Krüger
5a4c04cc2c
Rollup merge of #111656 - finnbear:string_leak_unbounded_lifetime, r=Amanieu
Use an unbounded lifetime in `String::leak`.

Using `'a` instead of `'static` is predicted to make the process of making `String` generic over an allocator easier/less of a breaking change.

See:
- https://github.com/rust-lang/rust/pull/109814#issuecomment-1550164195
- https://github.com/rust-lang/rust/pull/109814#issuecomment-1550250163

ACP: https://github.com/rust-lang/libs-team/issues/109
2023-05-27 20:40:29 +02:00
Matthias Krüger
1d06bb9612
Rollup merge of #108630 - overlookmotel:realloc-docs-fix, r=Amanieu
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.
2023-05-27 20:40:27 +02:00
bors
f91b634643 Auto merge of #110975 - Amanieu:panic_count, r=joshtriplett
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
2023-05-27 15:12:24 +00:00
Amanieu d'Antras
ef7f0e697b Rework handling of recursive panics 2023-05-27 16:35:16 +02:00
bors
82b311b418 Auto merge of #112016 - GuillaumeGomez:rollup-fhqn4i6, r=GuillaumeGomez
Rollup of 6 pull requests

Successful merges:

 - #111936 (Include test suite metadata in the build metrics)
 - #111952 (Remove DesugaringKind::Replace.)
 - #111966 (Add #[inline] to array TryFrom impls)
 - #111983 (Perform MIR type ops locally in new solver)
 - #111997 (Fix re-export of doc hidden macro not showing up)
 - #112014 (rustdoc: get unnormalized link destination for suggestions)

r? `@ghost`
`@rustbot` modify labels: rollup
2023-05-27 12:29:07 +00:00
Guillaume Gomez
b2abb2b056
Rollup merge of #111966 - saethlin:inline-slice-tryfrom, r=thomcc
Add #[inline] to array TryFrom impls

I was looking into https://github.com/rust-lang/rust/issues/111959 and I realized we don't have these. They seem like an uncontroversial addition.

IMO this PR does not fix that issue. I think the bad codegen is being caused by some underlying deeper problem but this change might cause the MIR inliner to paper over it in this specific case.

r? `@thomcc`
2023-05-27 13:38:31 +02:00
bors
786178b2ab Auto merge of #111934 - scottmcm:stabilize-hash-one, r=Amanieu
Stabilize `BuildHasher::hash_one`

FCP completed in https://github.com/rust-lang/rust/issues/86161#issuecomment-1561125732
2023-05-27 09:47:42 +00:00
bors
a525c7ddba Auto merge of #111928 - c410-f3r:dqewdas, r=eholk
[RFC-2011] Expand more expressions

cc #44838

Expands `if`, `let`, `match` and also makes `generic_assert_internals` an allowed feature when using `assert!`. `#![feature(generic_assert)]` is still needed to activate everything.

```rust
#![feature(generic_assert)]

fn fun(a: Option<i32>, b: Option<i32>, c: Option<i32>) {
  assert!(
    if a.is_some() { 1 } else { 2 } == 3
      && if let Some(elem) = b { elem == 4 } else { false }
      && match c { Some(_) => true, None => false }
  );
}

fn main() {
  fun(Some(1), None, Some(2));
}

// Assertion failed: assert!(
//   if a.is_some() { 1 } else { 2 } == 3
//     && if let Some(elem) = b { elem == 4 } else { false }
//     && match c { Some(_) => true, None => false }
// );
//
// With captures:
//   a = Some(1)
//   b = None
//   c = Some(2)
```
2023-05-27 07:02:48 +00:00
bors
dbfc95f969 Auto merge of #111348 - ozkanonur:remove-hardcoded-rustdoc-flags, r=albertlarsan68,oli-obk
new tool `rustdoc-gui-test`

Implements new tool `rustdoc-gui-test` that allows using compiletest headers for `rustdoc-gui` tests.
2023-05-27 04:20:44 +00:00
Matthias Krüger
18398ad337
Rollup merge of #111973 - Sp00ph:update_current_impl, r=Amanieu
Update current implementation comments for `select_nth_unstable`

This more accurately reflects the actual implementation, as it hasn't been a simple quickselect since #106997. While it does say that the current implementation always runs in O(n), I don't think it should require an FCP as it doesn't guarantee linearity in general and only points out that the current implementation is in fact linear.

r? `@Amanieu`
2023-05-27 00:23:59 +02:00
Urgau
b84c190b9a Allow newly uplifted invalid_from_utf8 lint 2023-05-27 00:18:28 +02:00
Urgau
7f99c7d3e6 Add invalid_from_utf8 analogous to invalid_from_utf8_unchecked 2023-05-27 00:18:28 +02:00
Urgau
7f8846a9ef Uplift clippy::invalid_utf8_in_unchecked as invalid_from_utf8_unchecked 2023-05-27 00:16:47 +02:00
bors
1a5f8bce74 Auto merge of #103291 - ink-feather-org:typeid_no_struct_match, r=dtolnay
Remove structural match from `TypeId`

As per https://github.com/rust-lang/rust/pull/99189#issuecomment-1203720442.

> Removing the structural equality might make sense, but is a breaking change that'd require a libs-api FCP.

https://github.com/rust-lang/rust/pull/99189#issuecomment-1197545482

> Landing this PR now (well, mainly the "remove structural equality" part) would unblock `const fn` `TypeId::of`, since we only postponed that because we were guaranteeing too much.

See also #99189, #101698
2023-05-26 17:29:03 +00:00
Pietro Albini
b82eb28224
convert benches to tests in subprocess if we're not benchmarking 2023-05-26 14:59:10 +02:00
Pietro Albini
2f7fd2e5f7
add StaticBenchAsTestFn and DynBenchAsTestFn to convert benches to tests
Before this commit, both static and dynamic benches were converted to a
DynTestFn, with a boxed closure that ran the benchmarks exactly once.

While this worked, it conflicted with -Z panic-abort-tests as the flag
does not support dynamic tests. With this change, a StaticBenchFn is
converted to a StaticBenchAsTestFn, avoiding any dynamic test creation.
DynBenchFn is also converted to DynBenchAsTestFn for completeness.
2023-05-26 14:57:38 +02:00
Pietro Albini
fa451fe6db
remove nested function from run_test
The inner function is not needed anymore as it's only called once after
the previous commit's refactoring.
2023-05-26 14:56:59 +02:00
Pietro Albini
b1d60bc076
refactor executing tests to centralize actually invoking tests
Before this commit, tests were invoked in multiple places, especially
due to `-Z panic-abort-tests`, and adding a new test kind meant having
to chase down and update all these places.

This commit creates a new Runnable enum, and its children RunnableTest
and RunnableBench. The rest of the harness will now pass around the enum
rather than constructing and passing around boxed functions. The enum
has two children enums because invoking tests and invoking benchmarks
requires different parameters.
2023-05-26 14:53:43 +02:00
Matthias Krüger
2daecf7c45
Rollup merge of #111940 - zirconium-n:io-read-doc-change, r=thomcc
Clarify safety concern of `io::Read::read` is only relevant in unsafe code

We have this clarification note in other similar place like [Iterator::size_hint](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.size_hint).

The lack of clarification might lead to confusion to Rust beginners. [Relevant URLO post](https://users.rust-lang.org/t/can-read-overflow-a-buffer/94347).
2023-05-26 08:24:08 +02:00
Markus Everling
ea327915d8 Update current implementation comments for select_nth_unstable 2023-05-26 01:31:04 +00:00
Ben Kimock
e1b8fad664 Add #[inline] to array TryFrom impls 2023-05-25 18:24:27 -04:00
Michael Goulet
fb45513126
Rollup merge of #107522 - Sp00ph:introselect, r=Amanieu
Add Median of Medians fallback to introselect

Fixes #102451.

This PR is a follow up to #106997. It adds a Fast Deterministic Selection implementation as a fallback to the introselect algorithm used by `select_nth_unstable`. This allows it to guarantee O(n) worst case running time, while maintaining good performance in all cases.

This would fix #102451, which was opened because the `select_nth_unstable` docs falsely claimed that it had O(n) worst case performance, even though it was actually quadratic in the worst case. #106997 improved the worst case complexity to O(n log n) by using heapsort as a fallback, and this PR further improves it to O(n) (this would also make #106933 unnecessary).
It also improves the actual runtime if the fallback gets called: Using a pathological input of size `1 << 19` (see the playground link in #102451), calculating the median is roughly 3x faster using fast deterministic selection as a fallback than it is using heapsort.

The downside to this is less code reuse between the sorting and selection algorithms, but I don't think it's that bad. The additional algorithms are ~250 LOC with no `unsafe` blocks (I tried using unsafe to avoid bounds checks but it didn't noticeably improve the performance).
I also let it fuzz for a while against the current `select_nth_unstable` implementation to ensure correctness, and it seems to still fulfill all the necessary postconditions.

cc `@scottmcm` who reviewed #106997
2023-05-25 13:57:59 -07:00
raldone01
f2bdaf1a4d Remove structural match from TypeId. 2023-05-25 20:15:39 +02:00
bors
a2b1646c59 Auto merge of #86844 - bjorn3:global_alloc_improvements, r=pnkfelix
Support #[global_allocator] without the allocator shim

This makes it possible to use liballoc/libstd in combination with `--emit obj` if you use `#[global_allocator]`. This is what rust-for-linux uses right now and systemd may use in the future. Currently they have to depend on the exact implementation of the allocator shim to create one themself as `--emit obj` doesn't create an allocator shim.

Note that currently the allocator shim also defines the oom error handler, which is normally required too. Once `#![feature(default_alloc_error_handler)]` becomes the only option, this can be avoided. In addition when using only fallible allocator methods and either `--cfg no_global_oom_handling` for liballoc (like rust-for-linux) or `--gc-sections` no references to the oom error handler will exist.

To avoid this feature being insta-stable, you will have to define `__rust_no_alloc_shim_is_unstable` to avoid linker errors.

(Labeling this with both T-compiler and T-lang as it originally involved both an implementation detail and had an insta-stable user facing change. As noted above, the `__rust_no_alloc_shim_is_unstable` symbol requirement should prevent unintended dependence on this unstable feature.)
2023-05-25 16:59:57 +00:00
Michael Howell
5fb752bdd5 std: make fortanix-sgx-abi a public depedenceny
It's exported publicly, so it should not be linted.
2023-05-25 08:15:05 -07:00
Michael Howell
8c21920cc7 std: make internal-only items pub(crate)
This works around a weird problem that looks like a bug in the
`exported_private_dependencies` lint.
2023-05-25 08:15:05 -07:00
Michael Howell
b537c1f175 std: mark common functions in test crate pub(crate)
This is not a library, so there's no reason for them to be `pub`.
Without doing this, compiling the test crates causes private dep
lint errors:

      error: type `PathBuf` from private dependency 'std' in public interface
        --> library/std/tests/common/mod.rs:26:5
         |
      26 |     pub fn join(&self, path: &str) -> PathBuf {
         |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
         |
         = note: `-D exported-private-dependencies` implied by `-D warnings`

      error: type `Path` from private dependency 'std' in public interface
        --> library/std/tests/common/mod.rs:31:5
         |
      31 |     pub fn path(&self) -> &Path {
         |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^

      error: could not compile `std` (test "create_dir_all_bare") due to 2 previous errors

This happens because Cargo passes `--extern 'priv:std=...` when
compiling the test crate.

I'm not sure if these warnings are desirable or not. They seem correct
in a very pedantic way (the dependency on `std` is not marked public,
since it's implicit), but also pointless (the test crate is not an API,
so who cares what it does).
2023-05-25 08:15:04 -07:00
Michael Howell
64025bb168 bootstrap: enable Cargo public-dependency feature for libstd 2023-05-25 08:13:23 -07:00
Ziru Niu
dd56f930cc Clarify safety concern of io::Read::read is only relevant in unsafe code 2023-05-25 18:38:38 +08:00
Scott McMurray
ba5a3968b8 Stabilize BuildHasher::hash_one 2023-05-24 23:47:50 -07:00
Matthias Krüger
8497948c7a
Rollup merge of #95198 - clarfonthey:get_chunk, r=scottmcm
Add slice::{split_,}{first,last}_chunk{,_mut}

This adds to the existing tracking issue for `slice::array_chunks` (#74985) under a separate feature, `slice_get_chunk`.

Currently, we have the existing `first`/`last` API for slices:

```rust
impl [T] {
    pub const fn first(&self) -> Option<&T>;
    pub const fn first_mut(&mut self) -> Option<&mut T>;
    pub const fn last(&self) -> Option<&T>;
    pub const fn last_mut(&mut self) -> Option<&mut T>;
    pub const fn split_first(&self) -> Option<(&T, &[T])>;
    pub const fn split_first_mut(&mut self) -> Option<(&mut T, &mut [T])>;
    pub const fn split_last(&self) -> Option<(&T, &[T])>;
    pub const fn split_last_mut(&mut self) -> Option<(&mut T, &mut [T])>;
}
```

This augments it with a `first_chunk`/`last_chunk` API that allows retrieving multiple elements at once:

```rust
impl [T] {
    pub const fn first_chunk<const N: usize>(&self) -> Option<&[T; N]>;
    pub const fn first_chunk_mut<const N: usize>(&mut self) -> Option<&mut [T; N]>;
    pub const fn last_chunk<const N: usize>(&self) -> Option<&[T; N]>;
    pub const fn last_chunk_mut<const N: usize>(&mut self) -> Option<&mut [T; N]>;
    pub const fn split_first_chunk<const N: usize>(&self) -> Option<(&[T; N], &[T])>;
    pub const fn split_first_chunk_mut<const N: usize>(&mut self) -> Option<(&mut [T; N], &mut [T])>;
    pub const fn split_last_chunk<const N: usize>(&self) -> Option<(&[T; N], &[T])>;
    pub const fn split_last_chunk_mut<const N: usize>(&mut self) -> Option<(&mut [T; N], &mut [T])>;
}
```

The code is based off of a copy of the existing API, with the documentation and examples properly modified. Currently, the most common way to perform these kinds of lookups with the existing methods is via `slice.as_chunks::<N>().0[0]` or the worse `slice.as_chunks::<N>().0[slice.len() - N]`, which is substantially less readable than `slice.first_chunk::<N>()` or `slice.last_chunk::<N>()`.

ACP: https://github.com/rust-lang/libs-team/issues/69
2023-05-25 08:01:07 +02:00
Caio
462a96c9e9 [RFC-2011] Expand more expressions 2023-05-24 21:15:50 -03:00
Manish Goregaokar
8038606bf3
Rollup merge of #111915 - jyn514:libtest-errors, r=thomcc
libtest: Improve error when missing `-Zunstable-options`

"only accepted on the nightly compiler" is misleading when this *is* nightly.
2023-05-24 15:05:05 -07:00
Markus Everling
fd5fa012e9 Use helper functions for min/max_idx 2023-05-24 19:33:04 +00:00
jyn
9314ed0cbd libtest: Improve error when missing -Zunstable-options
"only accepted on the nightly compiler" is misleading when this *is* nightly.
2023-05-24 11:18:20 -05:00
Markus Everling
3d11b655bd Add Median of Medians fallback to introselect 2023-05-24 00:38:20 +00:00
danakj
0e89b1b5fe Roll compiler_builtins to 0.1.92
This pulls in the weak-intrinsics feature (which currently
defaults off), and a minor version update to libm for the
compiler_builtins crate to 0.2.7.
2023-05-23 11:14:50 -04:00
bors
f3d597b31c Auto merge of #111807 - erikdesjardins:noalias, r=oli-obk
[rustc_ty_utils] Treat `drop_in_place`'s *mut argument like &mut when adding LLVM attributes

This resurrects PR #103614, which has sat idle for a while.

This could probably use a new perf run, since we're on a new LLVM version now.

r? `@oli-obk`
cc `@RalfJung`

---

LLVM can make use of the `noalias` parameter attribute on the parameter to `drop_in_place` in areas like argument promotion. Because the Rust compiler fully controls the code for `drop_in_place`, it can soundly deduce parameter attributes on it.

In #103957, Miri was changed to retag `drop_in_place`'s argument as if it was `&mut`, matching this change.
2023-05-23 10:12:46 +00:00
Dylan DPC
71f78682be
Rollup merge of #111756 - Urgau:rename_drop_forget_copy_ref_lints, r=fee1-dead
Rename `{drop,forget}_{copy,ref}` lints to more consistent naming

This PR renames previous uplifted lints in https://github.com/rust-lang/rust/pull/109732 to more consistent naming.

I followed the renaming done [here](https://github.com/rust-lang/rust/issues/53224) and also advocated in this [clippy issue](https://github.com/rust-lang/rust-clippy/issues/2845):
   - `drop_copy` to `dropping_copy_types`
   - `forget_copy` to `forgetting_copy_types`
   - `drop_ref` to `dropping_references`
   - `forget_ref` to `forgetting_references`
2023-05-23 00:32:19 +05:30
Dylan DPC
df8b0dfc27
Rollup merge of #111612 - ChayimFriedman2:collect-into-slice-ref, r=petrochenkov
Give better error when collecting into `&[T]`

The detection of slice reference of `{integral}` in `rustc_on_unimplemented` is hacky, but a proper solution requires changing `FmtPrinter` to add a parameter to print integers as `{integral}` and I didn't want to change it just for `rustc_on_unimplemented`. I can do that if requested, though.

I'm open to better wording; this is the best I could come up with.
2023-05-23 00:32:18 +05:30
Dylan DPC
47fe1a3e1f
Rollup merge of #111609 - LegionMammal978:internal-unsafe, r=thomcc
Mark internal functions and traits unsafe to reflect preconditions

No semantics are changed in this PR; I only mark some functions and and a trait `unsafe` which already had implicit preconditions. Although it seems somewhat redundant for `numfmt::Part::Copy` to contain a `&[u8]` instead of a `&str`, given that all of its current consumers ultimately expect valid UTF-8. Is the type also intended to work for byte-slice formatting in the future?
2023-05-23 00:32:18 +05:30
bors
2fe47b966a Auto merge of #111634 - marc0246:arc-new-uninit-bloat, r=thomcc
Fix duplicate `arcinner_layout_for_value_layout` calls when using the uninit `Arc` constructors

What this fixes is the duplicate calls to `arcinner_layout_for_value_layout` seen here: https://godbolt.org/z/jr5Gxozhj

The issue was discovered alongside #111603 but is otherwise unrelated to the duplicate `alloca`s, which remain unsolved. Everything I tried to solve said main issue has failed.

As for the duplicate layout calculations, I also tried slapping `#[inline]` and `#[inline(always)]` on everything in sight but the only thing that worked in the end is to dedup the calls by hand.
2023-05-22 15:06:32 +00:00
bors
48ec50ae39 Auto merge of #111711 - Jules-Bertholet:document-pin-layout, r=thomcc
Document `Pin` memory layout

The fact that `Pin` is `#[repr(transparent)]` technically isn't documented anywhere currently. I don't see any reason why `Pin`'s layout would ever change, so this PR codifies it.

`@rustbot` label +T-libs-api -T-libs +A-docs +A-layout +A-pin
2023-05-22 09:35:51 +00:00
bors
2d66e5a729 Auto merge of #111835 - matthiaskrgr:rollup-qd4b2vu, r=matthiaskrgr
Rollup of 2 pull requests

Successful merges:

 - #111810 (Don't use inner macro in `marker_impls`)
 - #111826 (Render test messages from bootstrap)

r? `@ghost`
`@rustbot` modify labels: rollup
2023-05-22 06:38:20 +00:00
Matthias Krüger
b0415dbec7
Rollup merge of #111810 - compiler-errors:less-macro, r=thomcc
Don't use inner macro in `marker_impls`

Just recurse instead of having to define an inner macro to avoid the problem with expansion binders being misnumbered between the `$meta` and `$T` variables.

cc `@Veykril` this should fix rust-lang/rust-analyzer#14862 since we've gotten rid of the inner macro.
2023-05-22 06:54:16 +02:00
bors
7ca94f241f Auto merge of #111781 - the8472:filter-map-chunk, r=thomcc
optimize next_chunk impls for Filter and FilterMap

```
OLD:

benchmarks:
    iter::bench_next_chunk_filter_even                 104.00ns/iter  +/- 1.00ns
    iter::bench_next_chunk_filter_map_even             101.00ns/iter  +/- 1.00ns
    iter::bench_next_chunk_filter_map_mostly_false       1.99µs/iter +/- 10.00ns
    iter::bench_next_chunk_filter_map_predictably_true  56.00ns/iter  +/- 0.00ns
    iter::bench_next_chunk_filter_mostly_false           1.15µs/iter  +/- 6.00ns
    iter::bench_next_chunk_filter_predictably_true      65.00ns/iter  +/- 1.00ns

NEW:

benchmarks:
    iter::bench_next_chunk_filter_even                  42.00ns/iter  +/- 0.00ns
    iter::bench_next_chunk_filter_map_even              49.00ns/iter  +/- 1.00ns
    iter::bench_next_chunk_filter_map_mostly_false     501.00ns/iter  +/- 3.00ns
    iter::bench_next_chunk_filter_map_predictably_true  31.00ns/iter  +/- 0.00ns
    iter::bench_next_chunk_filter_mostly_false         534.00ns/iter +/- 13.00ns
    iter::bench_next_chunk_filter_predictably_true      28.00ns/iter  +/- 1.00ns
```
2023-05-22 03:37:20 +00:00
Erik Desjardins
340827af9b drop_in_place docs: remove pseudocode-ish implementation details 2023-05-21 11:34:01 -04:00
Urgau
1c7ab18c08 Rename drop_copy lint to dropping_copy_types 2023-05-21 13:37:32 +02:00
Michael Goulet
e9a5a9d7d5 Don't use inner macro in marker_impls 2023-05-21 04:16:24 +00:00
bors
a11235d1bf Auto merge of #111696 - lukas-code:offset-of-erase-regions-harder, r=compiler-errors
don't skip inference for type in `offset_of!`

Fixes https://github.com/rust-lang/rust/issues/111678 by no longer skipping inference on the type in `offset_of!`. Simply erasing the regions the during writeback isn't enough and can cause ICEs. A test case for this is included.

This reverts https://github.com/rust-lang/rust/pull/111661, because it becomes redundant, since inference already erases the regions.
2023-05-21 04:02:46 +00:00
Erik Desjardins
58c3999949 improve drop_in_place docs 2023-05-20 18:12:54 -04:00
Patrick Walton
b2ef9f7223 Add missing "unsafe" to fix doctest 2023-05-20 18:12:54 -04:00
Patrick Walton
2836e5541a Update documentation for drop_in_place() 2023-05-20 18:12:54 -04:00
bors
fe76e14955 Auto merge of #111646 - Voultapher:restore-branchless-code-gen-for-merge, r=cuviper
Use code with reliable branchless code-gen for slice::sort merge

The recent LLVM 16 update changes code-gen to be not branchless anymore, in the slice::sort implementation merge function. This improves performance by 30% for random patterns, restoring the performance to the state with LLVM 15.

Fixes #111559
2023-05-20 21:52:10 +00:00
Lukas Markeffsky
7cdb23b98a don't skip inference for type in offset_of! 2023-05-20 15:20:27 +02:00
ozkanonur
6a347322a9 derive Default trait for compiletest::common::Config 2023-05-20 14:40:46 +03:00
bors
6d1bf733d6 Auto merge of #111778 - Dylan-DPC:rollup-107ig9h, r=Dylan-DPC
Rollup of 10 pull requests

Successful merges:

 - #111491 (Dont check `must_use` on nested `impl Future` from fn)
 - #111606 (very minor cleanups)
 - #111619 (Add timings for MIR passes to profiling report)
 - #111652 (Better diagnostic for `use Self::..`)
 - #111665 (Add more tests for the offset_of macro)
 - #111708 (Give a more useful location for where a span_bug was delayed)
 - #111715 (Fix doc comment for `ConstParamTy` derive)
 - #111723 (style: do not overwrite obligations)
 - #111743 (Improve cgu merging debug output)
 - #111762 (fix: emit error when fragment is `MethodReceiverExpr` and items is empty)

r? `@ghost`
`@rustbot` modify labels: rollup
2023-05-20 10:30:30 +00:00
The 8472
b40896d17b optimize next_chunk impls for Filter and FilterMap 2023-05-20 11:29:34 +02:00
Dylan DPC
93c031f6e6
Rollup merge of #111715 - juntyr:const-param-ty-derive-fix, r=Nilstrieb
Fix doc comment for `ConstParamTy` derive

See https://github.com/rust-lang/rust/pull/111670#discussion_r1196453888

Thanks ````@Nilstrieb```` for the pointer :)
2023-05-20 12:21:01 +05:30
Dylan DPC
e892e32df4
Rollup merge of #111665 - est31:offset_of_tests, r=WaffleLapkin
Add more tests for the offset_of macro

Implements what I [suggested in the tracking issue](https://github.com/rust-lang/rust/issues/106655#issuecomment-1535007205), plus some further improvements:

* ensuring that offset_of!(Self, ...) works iff inside an impl block
* ensuring that the output type is usize and doesn't coerce. this can be changed in the future, but if it is done, it should be a conscious decision
* improving the privacy checking test
* ensuring that generics don't let you escape the unsized check

r? `````@WaffleLapkin`````
2023-05-20 12:21:00 +05:30
bors
e86fd62b6b Auto merge of #111524 - scottmcm:escape-using-ascii, r=cuviper
`ascii::Char`-ify the escaping code in `core`

This means that `EscapeIterInner::as_str` no longer needs unsafe code, because the type system ensures the internal buffer is only ASCII, and thus valid UTF-8.

Come to think of it, this also gives it a (non-guaranteed) niche.

cc `@BurntSushi` as potentially interested
`ascii::Char` tracking issue: #110998
2023-05-20 04:43:17 +00:00
Ed Page
e6a35c4953 docs: Add missing period 2023-05-19 19:41:41 -05:00
bors
7047d97e01 Auto merge of #111453 - scottmcm:constify-as-slice, r=Mark-Simulacrum
constify `slice_as_chunks` (unstable)

Tracking issue: #74985

Nothing complicated required; just adding `const` to the declarations.
2023-05-19 23:12:36 +00:00
ltdk
d58dd10f5a Add slice::{split_,}{first,last}_chunk{,_mut} 2023-05-19 18:20:39 -04:00
bors
521f4dae1b Auto merge of #109773 - beetrees:set-file-time-improvements, r=Amanieu
Add creation time support to `FileTimes` on apple and windows

Adds support for setting file creation times on platforms which support changing it directly (currently only Apple and Windows). Based on top of #110093 (which was split from this PR).

ACP: rust-lang/libs-team#199 (currently still in progress)

Tracking issue: #98245

`@rustbot` label +T-libs-api -T-libs
2023-05-19 19:53:14 +00:00
Ibraheem Ahmed
4fbca2e1d5 tidy 2023-05-19 12:45:41 +02:00
Ibraheem Ahmed
b997f3ca13 remove unstable Poll::ready 2023-05-19 12:42:58 +02:00
Scott McMurray
62fcebdf7a constify slice_as_chunks (unstable)
Tracking issue: 74985

Nothing complicated required; just adding `const` to the declarations.
2023-05-19 02:32:10 -07:00
bors
2d17294d18 Auto merge of #111590 - dtolnay:panictemporaries, r=bjorn3
Shorten even more panic temporary lifetimes

Followup to #104134. As pointed out by `@bjorn3` in https://github.com/rust-lang/rust/pull/104134#pullrequestreview-1425585948, there are other cases in the panic macros which would also benefit from dropping their non-Send temporaries as soon as possible, avoiding pointlessly holding them across an await point.

For the tests added in this PR, here are the failures you get today on master without the macro changes in this PR:

<details>
<summary>tests/ui/macros/panic-temporaries-2018.rs</summary>

```console
error: future cannot be sent between threads safely
  --> tests/ui/macros/panic-temporaries-2018.rs:52:18
   |
LL |     require_send(panic_display());
   |                  ^^^^^^^^^^^^^^^ future returned by `panic_display` is not `Send`
   |
   = help: within `impl Future<Output = ()>`, the trait `Send` is not implemented for `*const u8`
note: future is not `Send` as this value is used across an await
  --> tests/ui/macros/panic-temporaries-2018.rs:35:31
   |
LL |     f(panic!("{}", NOT_SEND)).await;
   |                    --------   ^^^^^- `NOT_SEND` is later dropped here
   |                    |          |
   |                    |          await occurs here, with `NOT_SEND` maybe used later
   |                    has type `NotSend` which is not `Send`
note: required by a bound in `require_send`
  --> tests/ui/macros/panic-temporaries-2018.rs:48:25
   |
LL | fn require_send(_: impl Send) {}
   |                         ^^^^ required by this bound in `require_send`

error: future cannot be sent between threads safely
  --> tests/ui/macros/panic-temporaries-2018.rs:52:18
   |
LL |     require_send(panic_display());
   |                  ^^^^^^^^^^^^^^^ future returned by `panic_display` is not `Send`
   |
   = help: within `NotSend`, the trait `Sync` is not implemented for `*const u8`
note: future is not `Send` as this value is used across an await
  --> tests/ui/macros/panic-temporaries-2018.rs:35:31
   |
LL |     f(panic!("{}", NOT_SEND)).await;
   |       ----------------------  ^^^^^- the value is later dropped here
   |       |                       |
   |       |                       await occurs here, with the value maybe used later
   |       has type `&NotSend` which is not `Send`
note: required by a bound in `require_send`
  --> tests/ui/macros/panic-temporaries-2018.rs:48:25
   |
LL | fn require_send(_: impl Send) {}
   |                         ^^^^ required by this bound in `require_send`

error: future cannot be sent between threads safely
  --> tests/ui/macros/panic-temporaries-2018.rs:53:18
   |
LL |     require_send(panic_str());
   |                  ^^^^^^^^^^^ future returned by `panic_str` is not `Send`
   |
   = help: within `impl Future<Output = ()>`, the trait `Send` is not implemented for `*const u8`
note: future is not `Send` as this value is used across an await
  --> tests/ui/macros/panic-temporaries-2018.rs:40:36
   |
LL |     f(panic!((NOT_SEND, "...").1)).await;
   |               --------             ^^^^^- `NOT_SEND` is later dropped here
   |               |                    |
   |               |                    await occurs here, with `NOT_SEND` maybe used later
   |               has type `NotSend` which is not `Send`
note: required by a bound in `require_send`
  --> tests/ui/macros/panic-temporaries-2018.rs:48:25
   |
LL | fn require_send(_: impl Send) {}
   |                         ^^^^ required by this bound in `require_send`

error: future cannot be sent between threads safely
  --> tests/ui/macros/panic-temporaries-2018.rs:54:18
   |
LL |     require_send(unreachable_display());
   |                  ^^^^^^^^^^^^^^^^^^^^^ future returned by `unreachable_display` is not `Send`
   |
   = help: within `impl Future<Output = ()>`, the trait `Send` is not implemented for `*const u8`
note: future is not `Send` as this value is used across an await
  --> tests/ui/macros/panic-temporaries-2018.rs:45:31
   |
LL |     f(unreachable!(NOT_SEND)).await;
   |                    --------   ^^^^^- `NOT_SEND` is later dropped here
   |                    |          |
   |                    |          await occurs here, with `NOT_SEND` maybe used later
   |                    has type `NotSend` which is not `Send`
note: required by a bound in `require_send`
  --> tests/ui/macros/panic-temporaries-2018.rs:48:25
   |
LL | fn require_send(_: impl Send) {}
   |                         ^^^^ required by this bound in `require_send`

error: future cannot be sent between threads safely
  --> tests/ui/macros/panic-temporaries-2018.rs:54:18
   |
LL |     require_send(unreachable_display());
   |                  ^^^^^^^^^^^^^^^^^^^^^ future returned by `unreachable_display` is not `Send`
   |
   = help: within `NotSend`, the trait `Sync` is not implemented for `*const u8`
note: future is not `Send` as this value is used across an await
  --> tests/ui/macros/panic-temporaries-2018.rs:45:31
   |
LL |     f(unreachable!(NOT_SEND)).await;
   |       ----------------------  ^^^^^- the value is later dropped here
   |       |                       |
   |       |                       await occurs here, with the value maybe used later
   |       has type `&NotSend` which is not `Send`
note: required by a bound in `require_send`
  --> tests/ui/macros/panic-temporaries-2018.rs:48:25
   |
LL | fn require_send(_: impl Send) {}
   |                         ^^^^ required by this bound in `require_send`

error: aborting due to 5 previous errors
```
</details>

<details>
<summary>tests/ui/macros/panic-temporaries.rs</summary>

```console
error: future cannot be sent between threads safely
  --> tests/ui/macros/panic-temporaries.rs:42:18
   |
LL |     require_send(panic_display());
   |                  ^^^^^^^^^^^^^^^ future returned by `panic_display` is not `Send`
   |
   = help: within `impl Future<Output = ()>`, the trait `Send` is not implemented for `*const u8`
note: future is not `Send` as this value is used across an await
  --> tests/ui/macros/panic-temporaries.rs:35:31
   |
LL |     f(panic!("{}", NOT_SEND)).await;
   |                    --------   ^^^^^- `NOT_SEND` is later dropped here
   |                    |          |
   |                    |          await occurs here, with `NOT_SEND` maybe used later
   |                    has type `NotSend` which is not `Send`
note: required by a bound in `require_send`
  --> tests/ui/macros/panic-temporaries.rs:38:25
   |
LL | fn require_send(_: impl Send) {}
   |                         ^^^^ required by this bound in `require_send`

error: future cannot be sent between threads safely
  --> tests/ui/macros/panic-temporaries.rs:42:18
   |
LL |     require_send(panic_display());
   |                  ^^^^^^^^^^^^^^^ future returned by `panic_display` is not `Send`
   |
   = help: within `NotSend`, the trait `Sync` is not implemented for `*const u8`
note: future is not `Send` as this value is used across an await
  --> tests/ui/macros/panic-temporaries.rs:35:31
   |
LL |     f(panic!("{}", NOT_SEND)).await;
   |       ----------------------  ^^^^^- the value is later dropped here
   |       |                       |
   |       |                       await occurs here, with the value maybe used later
   |       has type `&NotSend` which is not `Send`
note: required by a bound in `require_send`
  --> tests/ui/macros/panic-temporaries.rs:38:25
   |
LL | fn require_send(_: impl Send) {}
   |                         ^^^^ required by this bound in `require_send`

error: aborting due to 2 previous errors
```
</details>

r? bjorn3
2023-05-19 07:15:38 +00:00
Colin Walters
440912b74f 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.
2023-05-18 08:02:53 -04:00
est31
30c0e4e72b Add more tests for the offset_of!() macro
* ensuring that offset_of!(Self, ...) works iff inside an impl block
* ensuring that the output type is usize and doesn't coerce. this can be
  changed in the future, but if it is done, it should be a conscious descision
* improving the privacy checking test
* ensuring that generics don't let you escape the unsized check
2023-05-18 13:16:17 +02:00
Juniper Tyree
f577cc4dea
Fix doc comment for ConstParamTy derive
See https://github.com/rust-lang/rust/pull/111670#discussion_r1196453888

Thanks @Nilstrieb for the pointer :)
2023-05-18 11:54:51 +03:00
bors
9052ca9393 Auto merge of #111710 - Dylan-DPC:rollup-eutrx54, r=Dylan-DPC
Rollup of 7 pull requests

Successful merges:

 - #110884 (Support RISC-V unaligned-scalar-mem target feature)
 - #111160 (Update serde in workspace and non-synced dependencies)
 - #111168 (Specialize ToString implementation for fmt::Arguments)
 - #111527 (add examples of port 0 binding behavior)
 - #111561 (Include better context for "already exists" error in compiletest)
 - #111633 (Avoid `&format("...")` calls in error message code.)
 - #111679 (Remove libs message about ACPs from triagebot)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
2023-05-18 07:14:23 +00:00
Jules Bertholet
f16acbeef6
Document Pin memory layout 2023-05-18 01:30:12 -04:00
Dylan DPC
f9bbd23adf
Rollup merge of #111527 - knickish:bind_port_0_documentation, r=Mark-Simulacrum
add examples of port 0 binding behavior

Was trying to find the method to specify the IP address but not the port, and there wasn't information easily accessible about it in the `TcpListener` or `SocketAddr`. Adding examples to `TcpListener` and `UdpSocket` for clarity.
2023-05-18 10:52:34 +05:30
Dylan DPC
e0991b7bcd
Rollup merge of #111168 - DaniPopes:arguments-to-string, r=Mark-Simulacrum
Specialize ToString implementation for fmt::Arguments

Generates far fewer instructions by formatting into a String with `fmt::format` directly instead of going through the `fmt::Display` impl. This change is insta-stable.
2023-05-18 10:52:34 +05:30
Ed Page
5d177afe95 docs: Clarify OsStr is self-synchronizing 2023-05-17 09:34:25 -05:00
yukang
c3394b3eaa Fix #107910, Shorten backtraces in ICEs 2023-05-17 17:56:26 +08:00
Dylan DPC
71fdb95272
Rollup merge of #111654 - JoJoJet:unsafe-cell-from-mut-lib, r=joshtriplett
Add a conversion from `&mut T` to `&mut UnsafeCell<T>`

Provides a safe way of downgrading an exclusive reference into an alias-able `&UnsafeCell<T>` reference.

ACP: https://github.com/rust-lang/libs-team/issues/198.
2023-05-17 11:13:57 +05:30
Dylan DPC
bc3b94a486
Rollup merge of #111649 - Nilstrieb:derive-const-param-ty, r=BoxyUwU
Add derive for `core::marker::ConstParamTy`

This makes it easier to implement it for a type, just like `Copy`.

`@BoxyUwU` half asked me to add it
2023-05-17 11:13:57 +05:30
Dylan DPC
5b58471c4c
Rollup merge of #111043 - jmillikin:cstr-is-empty, r=dtolnay
Stabilize feature `cstr_is_empty`

Fixes #102444

ACP: https://github.com/rust-lang/libs-team/issues/106
2023-05-17 11:13:56 +05:30
Ed Page
f9aaad0939 docs: Add examples of OsStr safety violation 2023-05-16 21:03:29 -05:00
Finn Bear
f0c9c1eb19 Use an unbounded lifetime in String::leak. 2023-05-16 13:39:17 -07:00
JoJoJet
ffacb8861a add UnsafeCell::from_mut 2023-05-16 15:36:05 -04:00
Matthias Krüger
20f6aa1365
Rollup merge of #111592 - Nemo157:fix-vec-capacity-examples, r=joshtriplett
Change Vec examples to not assert exact capacity except where it is guaranteed

It was [brought up on discord](https://discord.com/channels/273534239310479360/818964227783262209/1107633959329878077) that the `Vec::into_boxed_slice` example contradicted the `Vec::with_capacity` docs in that the returned `Vec` might have _more_ capacity than requested.

So, to reduce confusion change all the `assert_eq!(vec.capacity(), _)` to `assert!(vec.capacity() >= _)`, except in 4 examples that have guaranteed capacities: `Vec::from_raw_parts`, `Vec::from_raw_parts_in`, `Vec::<()>::with_capacity`,`Vec::<(), _>::with_capacity_in`.
2023-05-16 20:12:17 +02:00
Nilstrieb
0336dd132b Add derive for core::marker::ConstParamTy
This makes it easier to implement it for a type, just like `Copy`.
2023-05-16 20:09:25 +02:00
David Tolnay
e7963a65ed
Hide repr attribute from doc of types without guaranteed repr 2023-05-16 10:00:52 -07:00
Lukas Bergdoll
42655ff03b Use code with reliable branchless code-gen for slice::sort merge
The recent LLVM 16 update changes code-gen to be not branchless anymore, in the
slice::sort implementation merge function. This improves performance by 30% for
random patterns, restoring the performance to the state with LLVM 15.
2023-05-16 18:38:32 +02:00
Nilstrieb
0db9de843d
Rollup merge of #111617 - kesleta:master, r=Dylan-DPC
Fixed typo

Fixed typo in BTree Curser.
2023-05-16 11:39:41 +02:00
marc0246
2a466466c7
Fix duplicate arcinner_layout_for_value_layout calls 2023-05-16 08:53:05 +02:00
bors
3ea9ad5324 Auto merge of #111134 - GilShoshan94:remove-send-bound-on-error, r=dtolnay
Remove unnecessary Send bound

Hi,

While working on a [PR on Tokio](https://github.com/tokio-rs/tokio/pull/5666), I took inspiration from the std channel mpsc and stumbled on a `Send` bound for a `Error` impl.

Tokio's maintainer `@Darksonn` pointed out to me that `Error` used to required the `Send` bound long time ago (here https://github.com/rust-lang/rust/pull/23541).

In the meantime, the `Send` bound `Error` got removed (see https://github.com/rust-lang/rust/pull/21312 and https://github.com/rust-lang/rust/pull/23799).

So here a PR to removed this bound for `SendError<T>`, `TrySendError<T>` and `SendTimeoutError<T>`.
2023-05-16 04:03:26 +00:00
bors
76e79ca026 Auto merge of #111044 - jmillikin:nonzero-negation, r=dtolnay
Stabilize feature `nonzero_negation_ops`

Fixes #102443

ACP: https://github.com/rust-lang/libs-team/issues/105
2023-05-16 01:07:42 +00:00
Benjamin Atelsek
9688a6cebb Fixed typo 2023-05-15 15:13:21 -04:00
LegionMammal978
77481099ca Mark internal functions and traits unsafe 2023-05-15 14:31:00 -04:00
Chayim Refael Friedman
83930ecdea Give better error when collecting into &[T] 2023-05-15 21:16:35 +03:00
Matthias Krüger
eeebb6590a
Rollup merge of #111587 - cbeuw:copy-for-deref, r=oli-obk
Custom MIR: Support `Rvalue::CopyForDeref`

r? `@oli-obk` or `@tmiasko` or `@JakobDegen`
2023-05-15 17:12:47 +02:00
Matthias Krüger
c93c2985d8
Rollup merge of #110049 - SkiFire13:localkey-with-docs-fix, r=workingjubilee
Don't claim `LocalKey::with` prevents a reference to be sent across threads

The documentation for `LocalKey` claims that `with` yields a reference that cannot be sent across threads, but this is false since you can easily do that with scoped threads. What it actually prevents is the reference from outliving the current thread.
2023-05-15 17:12:44 +02:00
Matthias Krüger
1063548a1a
Rollup merge of #108356 - gftea:master, r=workingjubilee
improve doc test for UnsafeCell::raw_get

improve docs of public API `UnsafeCell::raw_get`
2023-05-15 17:12:44 +02:00
Matthias Krüger
fc30207b16
Rollup merge of #108291 - chenyukang:yukang/fix-benchmarks, r=workingjubilee
Fix more benchmark test with black_box

Follow up fix for https://github.com/rust-lang/rust/issues/107590
2023-05-15 17:12:43 +02:00
beetrees
246dcbcbcd
Add test for FileTimes 2023-05-15 15:04:45 +01:00
beetrees
db90a0b78d
Add creation time support to FileTimes on apple and windows 2023-05-15 15:04:39 +01:00
Wim Looman
a9cb4822be
Change Vec examples to not assert exact capacity except where it is guaranteed 2023-05-15 14:25:05 +02:00
David Tolnay
2f5d993945
Shorten lifetime of even more panic temporaries 2023-05-15 03:47:37 -07:00
Andy Wang
3d938ddb39
Documentation 2023-05-15 12:08:16 +02:00
Andy Wang
c3ab4f28d3
Add CopyForDeref to custom MIR 2023-05-15 12:05:10 +02:00
Matthias Krüger
75186c0f7d
Rollup merge of #111582 - Vagelis-Prokopiou:fix/wanting, r=workingjubilee
(docs) Change "wanting" to "want"

Changing " If you’re wanting" to "If you want".

Wanting is not wrong, of course, but I think that "If you want" feels more natural to most readers.
2023-05-15 10:58:42 +02:00
Matthias Krüger
9d8c11ba75
Rollup merge of #111581 - scottmcm:fix-pattern-comment, r=workingjubilee
Fix some misleading and copy-pasted `Pattern` examples

These examples were listed twice and also were confusable with doing a substring match instead of a any-of-set match.
2023-05-15 10:58:42 +02:00
Matthias Krüger
28bc8745ad
Rollup merge of #102673 - lukas-code:infered-lifetimes, r=ehuss
Update doc for `PhantomData` to match code example

After https://github.com/rust-lang/rust/pull/106621, there is no longer a `T: 'a` annotation in the doc example, so update the text to match the code.
2023-05-15 10:58:39 +02:00
Vagelis Prokopiou
5fa8c4aced wanting => want 2023-05-15 10:13:08 +03:00
Scott McMurray
47232ade61 Fix some misleading and copy-pasted Pattern examples
These examples were listed twice and also were confusable with doing a substring match instead of a any-of-set match.
2023-05-14 23:03:50 -07:00
bors
0bcfd2d96e Auto merge of #108273 - tspiteri:const_slice_split_at_not_mut, r=dtolnay
Stabilize const slice::split_at

This stabilizes the use of the following method in const context:

```rust
impl<T> [T] {
    pub const fn split_at(&self, mid: usize) -> (&[T], &[T]);
}
```

cc tracking issue #101158
2023-05-15 03:54:33 +00:00
bors
a14d6961f9 Auto merge of #108196 - sunfishcode:sunfishcode/windows-as-socket-impls, r=dtolnay
Implement `AsHandle`/`AsSocket` for `Arc`/`Rc`/`Box` on Windows

Implement the Windows counterpart to #97437 and #107317: Implement `AsHandle` and `AsSocket` for `Arc<T>`, `Rc<T>`, and `Box<T>`.
2023-05-14 22:10:09 +00:00
bors
18bfe5d8a9 Auto merge of #92048 - Urgau:num-midpoint, r=scottmcm
Add midpoint function for all integers and floating numbers

This pull-request adds the `midpoint` function to `{u,i}{8,16,32,64,128,size}`, `NonZeroU{8,16,32,64,size}` and `f{32,64}`.

This new function is analog to the [C++ midpoint](https://en.cppreference.com/w/cpp/numeric/midpoint) function, and basically compute `(a + b) / 2` with a rounding towards ~~`a`~~ negative infinity in the case of integers. Or simply said: `midpoint(a, b)` is `(a + b) >> 1` as if it were performed in a sufficiently-large signed integral type.

Note that unlike the C++ function this pull-request does not implement this function on pointers (`*const T` or `*mut T`). This could be implemented in a future pull-request if desire.

### Implementation

For `f32` and `f64` the implementation in based on the `libcxx` [one](18ab892ff7/libcxx/include/__numeric/midpoint.h (L65-L77)). I originally tried many different approach but all of them failed or lead me with a poor version of the `libcxx`. Note that `libstdc++` has a very similar one; Microsoft STL implementation is also basically the same as `libcxx`. It unfortunately doesn't seems like a better way exist.

For unsigned integers I created the macro `midpoint_impl!`, this macro has two branches:
 - The first one take `$SelfT` and is used when there is no unsigned integer with at least the double of bits. The code simply use this formula `a + (b - a) / 2` with the arguments in the correct order and signs to have the good rounding.
 - The second branch is used when a `$WideT` (at least double of bits as `$SelfT`) is provided, using a wider number means that no overflow can occur, this greatly improve the codegen (no branch and less instructions).

For signed integers the code basically forwards the signed numbers to the unsigned version of midpoint by mapping the signed numbers to their unsigned numbers (`ex: i8 [-128; 127] to [0; 255]`) and vice versa.
I originally created a version that worked directly on the signed numbers but the code was "ugly" and not understandable. Despite this mapping "overhead" the codegen is better than my most optimized version on signed integers.

~~Note that in the case of unsigned numbers I tried to be smart and used `#[cfg(target_pointer_width = "64")]` to determine if using the wide version was better or not by looking at the assembly on godbolt. This was applied to `u32`, `u64` and `usize` and doesn't change the behavior only the assembly code generated.~~
2023-05-14 19:33:02 +00:00
Lukas Markeffsky
3d02aa850b explain that PhantomData<&'a T> infers T: 'a 2023-05-14 16:52:08 +02:00
David Tolnay
cb109a672d
Shorten lifetime of panic temporaries in panic_fmt case 2023-05-14 07:27:20 -07:00
bors
ad6ab11234 Auto merge of #111425 - Bryanskiy:privacy_ef, r=petrochenkov
Populate effective visibilities in `rustc_privacy` (take 2)

Same as https://github.com/rust-lang/rust/pull/110907 + regressions fixes.
Fixes https://github.com/rust-lang/rust/issues/111359.

r? `@petrochenkov`
2023-05-14 02:53:52 +00:00
Ed Page
7b9290384e refactor: Remove bespoke from_os_str_bytes_unchecked 2023-05-13 19:09:00 +02:00
Ed Page
7f1a6cd421 refactor: Remove redundant, private OsStr::bytes 2023-05-13 18:47:14 +02:00
kirk
e33d5169e8 add examples of port 0 binding behavior 2023-05-13 07:13:52 +00:00
bors
16d3e18281 Auto merge of #111447 - scottmcm:remove-more-assumes, r=thomcc
Remove useless `assume`s from `slice::iter(_mut)`

You were right in https://github.com/rust-lang/rust/pull/111395#discussion_r1190312704,
r? `@the8472`

LLVM already removes these assumes while optimizing, as can be seen in <https://rust.godbolt.org/z/KTfWKbdEM>.
2023-05-13 03:09:05 +00:00
Scott McMurray
28449daa22 ascii::Char-ify the escaping code
This means that `EscapeIterInner::as_str` no longer needs unsafe code, because the type system ensures the internal buffer is only ASCII, and thus valid UTF-8.
2023-05-12 19:37:02 -07:00
Scott McMurray
c50a2e1d17 Remove useless assumes from slice::iter(_mut) 2023-05-12 17:34:55 -07:00
bors
9850584a4e Auto merge of #103413 - RalfJung:phantom-dropck, r=lcnr
PhantomData: fix documentation wrt interaction with dropck

As far as I could find out, the `PhantomData`-dropck interaction *only* affects code using `may_dangle`. The documentation in the standard library has not been updated for 8 years and thus stems from a time when Rust still used "parametric dropck", before [RFC 1238](https://rust-lang.github.io/rfcs/1238-nonparametric-dropck.html). Back then what the docs said was correct, but with `may_dangle` dropck it stopped being entirely accurate and these days, with NLL, it is actively misleading.

Fixes https://github.com/rust-lang/rust/issues/102810
Fixes https://github.com/rust-lang/rust/issues/70841
Cc `@nikomatsakis` I hope what I am saying here is right.^^
2023-05-13 00:23:51 +00:00
Ralf Jung
b93fd8355a hedge for future changes
Co-authored-by: lcnr <rust@lcnr.de>
2023-05-12 15:28:51 +02:00
bors
077fc26f0a Auto merge of #109732 - Urgau:uplift_drop_forget_ref_lints, r=davidtwco
Uplift `clippy::{drop,forget}_{ref,copy}` lints

This PR aims at uplifting the `clippy::drop_ref`, `clippy::drop_copy`, `clippy::forget_ref` and `clippy::forget_copy` lints.

Those lints are/were declared in the correctness category of clippy because they lint on useless and most probably is not what the developer wanted.

## `drop_ref` and `forget_ref`

The `drop_ref` and `forget_ref` lint checks for calls to `std::mem::drop` or `std::mem::forget` with a reference instead of an owned value.

### Example

```rust
let mut lock_guard = mutex.lock();
std::mem::drop(&lock_guard) // Should have been drop(lock_guard), mutex
// still locked
operation_that_requires_mutex_to_be_unlocked();
```

### Explanation

Calling `drop` or `forget` on a reference will only drop the reference itself, which is a no-op. It will not call the `drop` or `forget` method on the underlying referenced value, which is likely what was intended.

## `drop_copy` and `forget_copy`

The `drop_copy` and `forget_copy` lint checks for calls to `std::mem::forget` or `std::mem::drop` with a value that derives the Copy trait.

### Example

```rust
let x: i32 = 42; // i32 implements Copy
std::mem::forget(x) // A copy of x is passed to the function, leaving the
                    // original unaffected
```

### Explanation

Calling `std::mem::forget` [does nothing for types that implement Copy](https://doc.rust-lang.org/std/mem/fn.drop.html) since the value will be copied and moved into the function on invocation.

-----

Followed the instructions for uplift a clippy describe here: https://github.com/rust-lang/rust/pull/99696#pullrequestreview-1134072751

cc `@m-ou-se` (as T-libs-api leader because the uplifting was discussed in a recent meeting)
2023-05-12 12:04:32 +00:00
bors
26e0c57dde Auto merge of #111475 - workingjubilee:sync-simd-2023-may-10, r=workingjubilee
Sync portable-simd to 2023 May 10

Take 2.

r? `@ghost`
2023-05-12 02:05:05 +00:00