Commit Graph

244739 Commits

Author SHA1 Message Date
Matthias Krüger 8c6cf3c934
Rollup merge of #119305 - compiler-errors:async-fn-traits, r=oli-obk
Add `AsyncFn` family of traits

I'm proposing to add a new family of `async`hronous `Fn`-like traits to the standard library for experimentation purposes.

## Why do we need new traits?

On the user side, it is useful to be able to express `AsyncFn` trait bounds natively via the parenthesized sugar syntax, i.e. `x: impl AsyncFn(&str) -> String` when experimenting with async-closure code.

This also does not preclude `AsyncFn` becoming something else like a trait alias if a more fundamental desugaring (which can take many[^1] different[^2] forms) comes around. I think we should be able to play around with `AsyncFn` well before that, though.

I'm also not proposing stabilization of these trait names any time soon (we may even want to instead express them via new syntax, like `async Fn() -> ..`), but I also don't think we need to introduce an obtuse bikeshedding name, since `AsyncFn` just makes sense.

## The lending problem: why not add a more fundamental primitive of `LendingFn`/`LendingFnMut`?

Firstly, for `async` closures to be as flexible as possible, they must be allowed to return futures which borrow from the async closure's captures. This can be done by introducing `LendingFn`/`LendingFnMut` traits, or (equivalently) by adding a new generic associated type to `FnMut` which allows the return type to capture lifetimes from the `&mut self` argument of the trait. This was proposed in one of [Niko's blog posts](https://smallcultfollowing.com/babysteps/blog/2023/05/09/giving-lending-and-async-closures/).

Upon further experimentation, for the purposes of closure type- and borrow-checking, I've come to the conclusion that it's significantly harder to teach the compiler how to handle *general* lending closures which may borrow from their captures. This is, because unlike `Fn`/`FnMut`, the `LendingFn`/`LendingFnMut` traits don't form a simple "inheritance" hierarchy whose top trait is `FnOnce`.

```mermaid
flowchart LR
    Fn
    FnMut
    FnOnce
    LendingFn
    LendingFnMut

    Fn -- isa --> FnMut
    FnMut -- isa --> FnOnce

    LendingFn -- isa --> LendingFnMut

    Fn -- isa --> LendingFn
    FnMut -- isa --> LendingFnMut
```

For example:

```
fn main() {
  let s = String::from("hello, world");
  let f = move || &s;
  let x = f(); // This borrows `f` for some lifetime `'1` and returns `&'1 String`.
```

That trait hierarchy means that in general for "lending" closures, like `f` above, there's not really a meaningful return type for `<typeof(f) as FnOnce>::Output` -- it can't return `&'static str`, for example.

### Special-casing this problem:

By splitting out these traits manually, and making sure that each trait has its own associated future type, we side-step the issue of having to answer the questions of a general `LendingFn`/`LendingFnMut` implementation, since the compiler knows how to generate built-in implementations for first-class constructs like async closures, including the required future types for the (by-move) `AsyncFnOnce` and (by-ref) `AsyncFnMut`/`AsyncFn` trait implementations.

[^1]: For example, with trait transformers, we may eventually be able to write: `trait AsyncFn = async Fn;`
[^2]: For example, via the introduction of a more fundamental "`LendingFn`" trait, plus a [special desugaring with augmented trait aliases](https://rust-lang.zulipchat.com/#narrow/stream/213817-t-lang/topic/Lending.20closures.20and.20Fn*.28.29.20-.3E.20impl.20Trait/near/408471480).
2024-01-25 08:39:41 +01:00
bors d93feccb35 Auto merge of #119955 - kamalesh0406:master, r=WaffleLapkin
Modify GenericArg and Term structs to use strict provenance rules

This is the first PR to solve issue #119217 . In this PR, I have modified the GenericArg struct to use the `NonNull` struct as the pointer instead of `NonZeroUsize`. The change were tested by running `./x test compiler/rustc_middle`.

Resolves https://github.com/rust-lang/rust/issues/119217

r? `@WaffleLapkin`
2024-01-25 07:22:58 +00:00
bors 50a067d7f8 Auto merge of #119911 - NCGThompson:is-statically-known, r=oli-obk
Replacement of #114390: Add new intrinsic `is_var_statically_known` and optimize pow for powers of two

This adds a new intrinsic `is_val_statically_known` that lowers to [``@llvm.is.constant.*`](https://llvm.org/docs/LangRef.html#llvm-is-constant-intrinsic).` It also applies the intrinsic in the int_pow methods to recognize and optimize the idiom `2isize.pow(x)`. See #114390 for more discussion.

While I have extended the scope of the power of two optimization from #114390, I haven't added any new uses for the intrinsic. That can be done in later pull requests.

Note: When testing or using the library, be sure to use `--stage 1` or higher. Otherwise, the intrinsic will be a noop and the doctests will be skipped. If you are trying out edits, you may be interested in [`--keep-stage 0`](https://rustc-dev-guide.rust-lang.org/building/suggested.html#faster-builds-with---keep-stage).

Fixes #47234
Resolves #114390
`@Centri3`
2024-01-25 05:16:53 +00:00
bors 039d887928 Auto merge of #119911 - NCGThompson:is-statically-known, r=oli-obk
Replacement of #114390: Add new intrinsic `is_var_statically_known` and optimize pow for powers of two

This adds a new intrinsic `is_val_statically_known` that lowers to [``@llvm.is.constant.*`](https://llvm.org/docs/LangRef.html#llvm-is-constant-intrinsic).` It also applies the intrinsic in the int_pow methods to recognize and optimize the idiom `2isize.pow(x)`. See #114390 for more discussion.

While I have extended the scope of the power of two optimization from #114390, I haven't added any new uses for the intrinsic. That can be done in later pull requests.

Note: When testing or using the library, be sure to use `--stage 1` or higher. Otherwise, the intrinsic will be a noop and the doctests will be skipped. If you are trying out edits, you may be interested in [`--keep-stage 0`](https://rustc-dev-guide.rust-lang.org/building/suggested.html#faster-builds-with---keep-stage).

Fixes #47234
Resolves #114390
`@Centri3`
2024-01-25 05:16:53 +00:00
Michael Goulet 07b7c77705 What even is CoroutineInfo 2024-01-25 04:44:11 +00:00
Michael Goulet 2aa746913b Don't fire OPAQUE_HIDDEN_INFERRED_BOUND on sized return of AFIT 2024-01-25 04:41:38 +00:00
Michael Goulet 3004e8c44b Remove coroutine info when building coroutine drop body 2024-01-25 03:26:29 +00:00
bors 68411c9554 Auto merge of #119627 - oli-obk:const_prop_lint_n̵o̵n̵sense, r=cjgillot
Remove all ConstPropNonsense

We track all locals and projections on them ourselves within the const propagator and only use the InterpCx to actually do some low level operations or read from constants (via `OpTy` we get for said constants).

This helps moving the const prop lint out from the normal pipeline and running it just based on borrowck information. This in turn allows us to make progress on https://github.com/rust-lang/rust/pull/108730#issuecomment-1875557745

there are various follow up cleanups that can be done after this PR (e.g. not matching on Rvalue twice and doing binop checks twice), but lets try landing this one first.

r? `@RalfJung`
2024-01-25 03:16:07 +00:00
Nicholas Nethercote 6be2e5623c Use `unescape_unicode` for raw C string literals.
They can't contain `\x` escapes, which means they can't contain high
bytes, which means we can used `unescape_unicode` instead of
`unescape_mixed` to unescape them. This avoids unnecessary used of
`MixedUnit`.
2024-01-25 12:28:11 +11:00
Nicholas Nethercote 86f371ed59 Rename the unescaping functions.
`unescape_literal` becomes `unescape_unicode`, and `unescape_c_string`
becomes `unescape_mixed`. Because rfc3349 will mean that C string
literals will no longer be the only mixed utf8 literals.
2024-01-25 12:28:11 +11:00
Nicholas Nethercote 5e5aa6d556 Rename and invert sense of `Mode` predicates.
I find it easier if they describe what's allowed, rather than what's
forbidden. Also, consistent naming makes them easier to understand.
2024-01-25 12:28:11 +11:00
Nicholas Nethercote a1c07214f0 Rework `CStrUnit`.
- Rename it as `MixedUnit`, because it will soon be used in more than
  just C string literals.
- Change the `Byte` variant to `HighByte` and use it only for
  `\x80`..`\xff` cases. This fixes the old inexactness where ASCII chars
  could be encoded with either `Byte` or `Char`.
- Add useful comments.
- Remove `is_ascii`, in favour of `u8::is_ascii`.
2024-01-25 12:28:11 +11:00
Nicholas Nethercote ef1e2228cf Use `from` instead of `into` in unescaping code.
The `T` type in these functions took me some time to understand, and I
find the explicit `T` in the use of `from` makes the code easier to
read, as does the `u8` annotation in `scan_escape`.
2024-01-25 12:26:36 +11:00
Nicholas Nethercote 4b4bdb575b Fix copy/paste error.
The `CString` handling code is erroneously identical to the `ByteString`
handling code.
2024-01-25 12:26:25 +11:00
Nicholas Nethercote 314dbc7f22 Avoid useless checking in `from_token_lit`.
The parser already does a check-only unescaping which catches all
errors. So the checking done in `from_token_lit` never hits.

But literals causing warnings can still occur in `from_token_lit`. So
the commit changes `str-escape.rs` to use byte string literals and C
string literals as well, to give better coverage and ensure the new
assertions in `from_token_lit` are correct.
2024-01-25 12:22:17 +11:00
Josh Stone 8f3af4c6e2 rustc_data_structures: use either instead of itertools 2024-01-24 15:36:57 -08:00
bors 900a5aa036 Auto merge of #12180 - y21:conf_lev_distance, r=blyxyas
Suggest existing configuration option if one is found

While working on/testing #12179, I made the mistake of using underscores instead of dashes for the field name in the clippy.toml file and ended up being confused for a few minutes until I found out what's wrong. With this change, clippy will suggest an existing field if there's one that's similar.
```
1 | allow_mixed_uninlined_format_args = true
  | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: perhaps you meant: `allow-mixed-uninlined-format-args`
```
(in hindsight, the current behavior of printing all the config options makes it obvious in most cases but I still think a suggestion like this would be nice to have)

I had to play around with the value a bit. A max distance of 5 seemed a bit too strong since it'd suggest changing `foobar` to `msrv`, which seemed odd, and 4 seemed just good enough to detect a typo of five underscores.

changelog: when an invalid field in clippy.toml is found, suggest the closest existing one if one is found
2024-01-24 23:13:11 +00:00
Nadrieril 95a14d43d7 Implement feature gate logic 2024-01-25 00:12:32 +01:00
y21 4780637cbc
suggest similar config option if one is found 2024-01-25 00:11:43 +01:00
Nadrieril 886108b9fe Add feature gate 2024-01-24 23:52:03 +01:00
Michael Goulet 8c2ae804e3 Don't manually resolve async closures in rustc_resolve 2024-01-24 20:48:07 +00:00
bors 7ffc697ce1 Auto merge of #120309 - fmease:rollup-kr7wqy6, r=fmease
Rollup of 9 pull requests

Successful merges:

 - #114764 ([style edition 2024] Combine all delimited exprs as last argument)
 - #118326 (Add `NonZero*::count_ones`)
 - #119460 (coverage: Never emit improperly-ordered coverage regions)
 - #119616 (Add a new `wasm32-wasi-preview2` target)
 - #120185 (coverage: Don't instrument `#[automatically_derived]` functions)
 - #120265 (Remove no-system-llvm)
 - #120284 (privacy: Refactor top-level visiting in `TypePrivacyVisitor`)
 - #120285 (Remove extra # from url in suggestion)
 - #120299 (Add mw to review rotation and add some owner assignments)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-01-24 20:34:41 +00:00
Nadrieril 354b45f528 Improve `Range: Debug` impl 2024-01-24 20:09:30 +01:00
Nadrieril bdab213993 Most of the `DeconstructedPat` `Debug` impl is reusable 2024-01-24 20:04:33 +01:00
Esteban Küber 796814d916 Account for expected `dyn Trait` found `impl Trait` 2024-01-24 16:57:15 +00:00
Guillaume Gomez bdc9ce0d95 Don't call `walk_` functions directly if there is an equivalent `visit_` method. 2024-01-24 17:33:33 +01:00
Esteban Küber d992d9cd56 On E0308 involving `dyn Trait`, mention trait objects
When encountering a type mismatch error involving `dyn Trait`, mention
the existence of boxed trait objects if the other type involved
implements `Trait`.

Partially addresses #102629.
2024-01-24 16:32:24 +00:00
Nadrieril e088016f9d Let `ctor_sub_tys` return any Iterator they want
Since we always clone and allocate the types somewhere else ourselves,
no need to ask for `Cx` to do the allocation.
2024-01-24 16:55:26 +01:00
León Orell Valerian Liehr 8325f3dd63
Rollup merge of #120299 - michaelwoerister:review-rotation-update, r=davidtwco
Add mw to review rotation and add some owner assignments

I've also added a `debuginfo` group and fixed the ownership assignment for the `incremental` group. I hope I got the syntax right.

r? ``@davidtwco``
2024-01-24 15:43:15 +01:00
León Orell Valerian Liehr 7403d5821a
Rollup merge of #120285 - est31:remove_extra_pound, r=fmease
Remove extra # from url in suggestion

The suggestion added in #119805 contains an unnecessary # hash sign.
2024-01-24 15:43:14 +01:00
León Orell Valerian Liehr fee8f00024
Rollup merge of #120284 - petrochenkov:typrivisit2, r=oli-obk
privacy: Refactor top-level visiting in `TypePrivacyVisitor`

Full hierarchical visiting (`nested_filter::All`) is not necessary, visiting all item-likes in isolation is enough.
Tracking current item is not necessary, just keeping the current `mod` item is enough.
`visit_generic_arg` should behave like its default version, including checking types of const arguments.
Some comments, including FIXMEs, are also added.

Noticed while reading code to review https://github.com/rust-lang/rust/pull/113671.
r? ``@oli-obk``
2024-01-24 15:43:14 +01:00
León Orell Valerian Liehr 8290589f24
Rollup merge of #120265 - nikic:no-no-system-llvm, r=nagisa
Remove no-system-llvm

We currently have a bunch of codegen tests that use no-system-llvm -- however, all of those tests also pass with system LLVM 16.

I've opted to remove `no-system-llvm` entirely, as there's basically no valid use case for it anymore:

 * The only thing this option could have legitimately been used for (testing the target feature support that requires an LLVM patch) doesn't use it, and the need for this will go away with LLVM 18 anyway.
 * In cases where the test depends on optimizations/fixes from newer LLVM versions, `min-llvm-version` should be used instead.
 * In case it depends on optimization/fixes from newer LLVM versions that have been backported into our fork, `min-system-llvm-version` (with the major version larger than the one in our fork) should be used instead.

r? `````@cuviper`````
2024-01-24 15:43:13 +01:00
León Orell Valerian Liehr 8bd126cb18
Rollup merge of #120185 - Zalathar:auto-derived, r=wesleywiser
coverage: Don't instrument `#[automatically_derived]` functions

This PR makes the coverage instrumentor detect and skip functions that have [`#[automatically_derived]`](https://doc.rust-lang.org/reference/attributes/derive.html#the-automatically_derived-attribute) on their enclosing impl block.

Most notably, this means that methods generated by built-in derives (e.g. `Clone`, `Debug`, `PartialEq`) are now ignored by coverage instrumentation, and won't appear as executed or not-executed in coverage reports.

This is a noticeable change in user-visible behaviour, but overall I think it's a net improvement. For example, we've had a few user requests for this sort of change (e.g. #105055, https://github.com/rust-lang/rust/issues/84605#issuecomment-1902069040), and I believe it's the behaviour that most users will expect/prefer by default.

It's possible to imagine situations where users would want to instrument these derived implementations, but I think it's OK to treat that as an opportunity to consider adding more fine-grained option flags to control the details of coverage instrumentation, while leaving this new behaviour as the default.

(Also note that while `-Cinstrument-coverage` is a stable feature, the exact details of coverage instrumentation are allowed to change. So we *can* make this change; the main question is whether we *should*.)

Fixes #105055.
2024-01-24 15:43:12 +01:00
León Orell Valerian Liehr e0a4f43903
Rollup merge of #119616 - rylev:wasm32-wasi-preview2, r=petrochenkov,m-ou-se
Add a new `wasm32-wasi-preview2` target

This is the initial implementation of the MCP https://github.com/rust-lang/compiler-team/issues/694 creating a new tier 3 target `wasm32-wasi-preview2`. That MCP has been seconded and will most likely be approved in a little over a week from now. For more information on the need for this target, please read the [MCP](https://github.com/rust-lang/compiler-team/issues/694).

There is one aspect of this PR that will become insta-stable once these changes reach a stable compiler:
* A new `target_family` named `wasi` is introduced. This target family incorporates all wasi targets including `wasm32-wasi` and its derivative `wasm32-wasi-preview1-threads`. The difference between `target_family = wasi` and `target_os = wasi` will become much clearer when `wasm32-wasi` is renamed to `wasm32-wasi-preview1` and the `target_os` becomes `wasm32-wasi-preview1`. You can read about this target rename in [this MCP](https://github.com/rust-lang/compiler-team/issues/695) which has also been seconded and will hopefully be officially approved soon.

Additional technical details include:
* Both `std::sys::wasi_preview2` and `std::os::wasi_preview2` have been created and mostly use `#[path]` annotations on their submodules to reach into the existing `wasi` (soon to be `wasi_preview1`) modules. Over time the differences between `wasi_preview1` and `wasi_preview2` will grow and most like all `#[path]` based module aliases will fall away.
* Building `wasi-preview2` relies on a [`wasi-sdk`](https://github.com/WebAssembly/wasi-sdk) in the same way that `wasi-preview1` does (one must include a `wasi-root` path in the `Config.toml` pointing to sysroot included in the wasi-sdk). The target should build against [wasi-sdk v21](https://github.com/WebAssembly/wasi-sdk/releases/tag/wasi-sdk-21) without modifications. However, the wasi-sdk itself is growing [preview2 support](https://github.com/WebAssembly/wasi-sdk/pull/370) so this might shift rapidly. We will be following along quickly to make sure that building the target remains possible as the wasi-sdk changes.
* This requires a [patch to libc](https://github.com/rylev/rust-libc/tree/wasm32-wasi-preview2) that we'll need to land in conjunction with this change. Until that patch lands the target won't actually build.
2024-01-24 15:43:12 +01:00
León Orell Valerian Liehr 5a38754d23
Rollup merge of #119460 - Zalathar:improper-region, r=wesleywiser
coverage: Never emit improperly-ordered coverage regions

If we emit a coverage region that is improperly ordered (end < start), `llvm-cov` will fail with `coveragemap_error::malformed`, which is inconvenient for users and also very hard to debug.

Ideally we would fix the root causes of these situations, but they tend to occur in very obscure edge-case scenarios (often involving nested macros), and we don't always have a good MCVE to work from. So it makes sense to also have a catch-all check that will prevent improperly-ordered regions from ever being emitted.

---

This is mainly aimed at resolving #119453. We don't have a specific way to reproduce it, which is why I haven't been able to add a test case in this PR. But based on the information provided in that issue, this change seems likely to avoid the error in `llvm-cov`.

`````@rustbot````` label +A-code-coverage
2024-01-24 15:43:11 +01:00
León Orell Valerian Liehr 3529d45b74
Rollup merge of #118326 - WaffleLapkin:nz_count_ones, r=scottmcm
Add `NonZero*::count_ones`

This PR adds the following APIs to the standard library:

```rust
impl NonZero* {
    pub const fn count_ones(self) -> NonZeroU32;
}
```

This is potentially interesting, given that `count_ones` can't ever return 0.

r? libs-api
2024-01-24 15:43:11 +01:00
León Orell Valerian Liehr 61e2b410ff
Rollup merge of #114764 - pitaj:style-delimited-expressions, r=joshtriplett
[style edition 2024] Combine all delimited exprs as last argument

Closes rust-lang/style-team#149

If this is merged, the rustfmt option `overflow_delimited_expr` should be enabled by default in style edition 2024.

[Rendered](https://github.com/pitaj/rust/blob/style-delimited-expressions/src/doc/style-guide/src/expressions.md#combinable-expressions)

r? joshtriplett
2024-01-24 15:43:10 +01:00
Askar Safin df0c9c37c1 Finishing clone3 clean up 2024-01-24 17:23:51 +03:00
Askar Safin 1ee773e242 This commit is part of clone3 clean up. Merge tests from tests/ui/command/command-create-pidfd.rs
to library/std/src/sys/pal/unix/process/process_unix/tests.rs to remove code
duplication
2024-01-24 17:23:42 +03:00
Askar Safin 57f9d1f01a This commit is part of clone3 clean up. As part of clean up we will
remove tests/ui/command/command-create-pidfd.rs . But it contains
very useful comment, so let's move the comment to library/std/src/sys/pal/unix/rand.rs ,
which contains another instance of the same Docker problem
2024-01-24 15:22:00 +03:00
Oli Scherer cc34dc2bc7 Correctly explain `ensure_forwards_result_if_red` 2024-01-24 11:04:13 +00:00
bors cd6d8f2a04 Auto merge of #118336 - saethlin:const-to-op-cache, r=RalfJung
Return a finite number of AllocIds per ConstAllocation in Miri

Before this, every evaluation of a const slice would produce a new AllocId. So in Miri, this program used to have unbounded memory use:
```rust
fn main() {
    loop {
        helper();
    }
}

fn helper() {
    "ouch";
}
```
Every trip around the loop creates a new AllocId which we need to keep track of a base address for. And the provenance GC can never clean up that AllocId -> u64 mapping, because the AllocId is for a const allocation which will never be deallocated.

So this PR moves the logic of producing an AllocId for a ConstAllocation to the Machine trait, and the implementation that Miri provides will only produce 16 AllocIds for each allocation. The cache is also keyed on the Instance that the const is evaluated in, so that equal consts evaluated in two functions will have disjoint base addresses.

r? RalfJung
2024-01-24 10:17:12 +00:00
Urgau 64f590a50d Assert that a single scope is passed to `for_scope` 2024-01-24 10:52:02 +01:00
Michael Woerister db4cf5d88b
Add @davidtwco to debuginfo group in triage.toml
Co-authored-by: David Wood <agile.lion3441@fuligin.ink>
2024-01-24 10:40:35 +01:00
bors 4e8ad10843 Auto merge of #3277 - RalfJung:freebsd, r=RalfJung
add __cxa_thread_atexit_impl on freebsd

Fixes https://github.com/rust-lang/miri/issues/3276
2024-01-24 09:18:10 +00:00
Ralf Jung 12dd3bfa2f a bit of refactoring for find_mir_or_eval_fn 2024-01-24 10:16:49 +01:00
Michael Woerister eabfe455ec Add mw to review rotation and add some owner assignments 2024-01-24 10:13:28 +01:00
Ralf Jung e611211f30 add __cxa_thread_atexit_impl on freebsd 2024-01-24 10:12:24 +01:00
Ralf Jung cba1fdbff3 refactor extern static handling 2024-01-24 10:12:24 +01:00
bors cf22ee0c0c Auto merge of #3275 - rust-lang:rustup-2024-01-24, r=RalfJung
Automatic Rustup
2024-01-24 08:12:24 +00:00