Commit Graph

1371 Commits

Author SHA1 Message Date
bors
4a2fe4491e Auto merge of #120361 - compiler-errors:async-closures, r=oli-obk
Rework support for async closures; allow them to return futures that borrow from the closure's captures

This PR implements a new lowering for async closures via `TyKind::CoroutineClosure` which handles the curious relationship between the closure and the coroutine that it returns.

I wrote up a bunch in [this hackmd](https://hackmd.io/`@compiler-errors/S1HvqQxca)` which will be copied to the dev guide after this PR lands, and hopefully left sufficient comments in the source code explaining why this change is as large as it is.

This also necessitates that they begin implementing the `AsyncFn`-family of traits, rather than the `Fn`-family of traits -- if you need `Fn` implementations, you should probably use the non-sugar `|| async {}` syntax instead.

Notably this PR does not yet implement `async Fn()` syntax sugar for bounds, but I expect to add those soon (**edit:** #120392). For now, users must use `AsyncFn()` traits directly, which necessitates adding the `async_fn_traits` feature gate as well. I will add this as a follow-up very soon.

r? oli-obk

This is based on top of #120322, but that PR is minimal.
2024-02-06 15:04:01 +00:00
Michael Goulet
881b6b5149 Bless tests, add comments 2024-02-06 02:22:58 +00:00
Michael Goulet
a82bae2172 Teach typeck/borrowck/solvers how to deal with async closures 2024-02-06 02:22:58 +00:00
Michael Goulet
0eb2adb7e8 Add async bound modifier to enable async Fn bounds 2024-01-31 16:59:19 +00:00
Guillaume Gomez
d10f33a8d1
Rollup merge of #120434 - fmease:revert-speeder, r=petrochenkov
Revert outdated version of "Add the wasm32-wasi-preview2 target"

An outdated version of #119616 was merged in rollup #120309.
This reverts those changes to enable #119616 to “retain the intended diff” after a rebase.
```@rylev``` has agreed that this would be the cleanest approach with respect to the history.
Unblocks #119616.

r? ```@petrochenkov``` or compiler or libs
2024-01-30 16:57:49 +01:00
Dylan DPC
15e8b903b2
Rollup merge of #120453 - mattheww:2024-01_normalize_newlines, r=oli-obk
Fix incorrect comment in normalize_newlines

The incorrect comment seems to be left over from sometime before this function was first merged.
2024-01-29 12:56:54 +00:00
Matthew Woodcraft
67558055e3 normalize_newlines(): fix incorrect comment 2024-01-28 19:30:41 +00:00
León Orell Valerian Liehr
9199742339
Revert "Add the wasm32-wasi-preview2 target"
This reverts commit 31ecf34125.

Co-authored-by: Ryan Levick <me@ryanlevick.com>
2024-01-28 02:02:50 +01:00
Markus Reiter
554b0f70c3
Add NonZero symbol. 2024-01-27 16:38:57 +01:00
Matthias Krüger
a37fa37281
Rollup merge of #118803 - Nadrieril:min-exhaustive-patterns, r=compiler-errors
Add the `min_exhaustive_patterns` feature gate

## Motivation

Pattern-matching on empty types is tricky around unsafe code. For that reason, current stable rust conservatively requires arms for empty types in all but the simplest case. It has long been the intention to allow omitting empty arms when it's safe to do so. The [`exhaustive_patterns`](https://github.com/rust-lang/rust/issues/51085) feature allows the omission of all empty arms, but hasn't been stabilized because that was deemed dangerous around unsafe code.

## Proposal

This feature aims to stabilize an uncontroversial subset of exhaustive_patterns. Namely: when `min_exhaustive_patterns` is enabled and the data we're matching on is guaranteed to be valid by rust's operational semantics, then we allow empty arms to be omitted. E.g.:

```rust
let x: Result<T, !> = foo();
match x { // ok
    Ok(y) => ...,
}
let Ok(y) = x; // ok
```

If the place is not guaranteed to hold valid data (namely ptr dereferences, ref dereferences (conservatively) and union field accesses), then we keep stable behavior i.e. we (usually) require arms for the empty cases.

```rust
unsafe {
    let ptr: *const Result<u32, !> = ...;
    match *ptr {
        Ok(x) => { ... }
        Err(_) => { ... } // still required
    }
}
let foo: Result<u32, &!> = ...;
match foo {
    Ok(x) => { ... }
    Err(&_) => { ... } // still required because of the dereference
}
unsafe {
    let ptr: *const ! = ...;
    match *ptr {} // already allowed on stable
}
```

Note that we conservatively consider that a valid reference can point to invalid data, hence we don't allow arms of type `&!` and similar cases to be omitted. This could eventually change depending on [opsem decisions](https://github.com/rust-lang/unsafe-code-guidelines/issues/413). Whenever opsem is undecided on a case, we conservatively keep today's stable behavior.

I proposed this behavior in the [`never_patterns`](https://github.com/rust-lang/rust/issues/118155) feature gate but it makes sense on its own and could be stabilized more quickly. The two proposals nicely complement each other.

## Unresolved Questions

Part of the question is whether this requires an RFC. I'd argue this doesn't need one since there is no design question beyond the intent to omit unreachable patterns, but I'm aware the problem can be framed in ways that require design (I'm thinking of the [original never patterns proposal](https://smallcultfollowing.com/babysteps/blog/2018/08/13/never-patterns-exhaustive-matching-and-uninhabited-types-oh-my/), which would frame this behavior as "auto-nevering" happening).

EDIT: I initially proposed a future-compatibility lint as part of this feature, I don't anymore.
2024-01-26 06:36:36 +01:00
bors
dd2559e08e Auto merge of #116167 - RalfJung:structural-eq, r=lcnr
remove StructuralEq trait

The documentation given for the trait is outdated: *all* function pointers implement `PartialEq` and `Eq` these days. So the `StructuralEq` trait doesn't really seem to have any reason to exist any more.

One side-effect of this PR is that we allow matching on some consts that do not implement `Eq`. However, we already allowed matching on floats and consts containing floats, so this is not new, it is just allowed in more cases now. IMO it makes no sense at all to allow float matching but also sometimes require an `Eq` instance. If we want to require `Eq` we should adjust https://github.com/rust-lang/rust/pull/115893 to check for `Eq`, and rule out float matching for good.

Fixes https://github.com/rust-lang/rust/issues/115881
2024-01-26 00:17:00 +00:00
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
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
Nadrieril
886108b9fe Add feature gate 2024-01-24 23:52:03 +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
Ralf Jung
0df7810734 remove StructuralEq trait 2024-01-24 07:56:23 +01:00
León Orell Valerian Liehr
6cca9b33ec
Rollup merge of #120171 - cjgillot:jump-threading-assume-assert, r=tmiasko
Fix assume and assert in jump threading

r? ``@tmiasko``
2024-01-23 21:53:57 +01:00
Ryan Levick
31ecf34125 Add the wasm32-wasi-preview2 target
Signed-off-by: Ryan Levick <me@ryanlevick.com>
2024-01-23 13:26:16 +01:00
Camille GILLOT
161c674ef0 Add Assume custom MIR. 2024-01-22 23:55:10 +00:00
Matthias Krüger
221115cbd6
Rollup merge of #120143 - compiler-errors:consolidate-instance-resolve-for-coroutines, r=oli-obk
Consolidate logic around resolving built-in coroutine trait impls

Deduplicates a lot of code. Requires defining a new lang item for `Coroutine::resume` for consistency, but it seems not harmful at worst, and potentially later useful at best.

r? oli-obk
2024-01-22 22:12:08 +01:00
Michael Goulet
f2ef88ba06 Consolidate logic around resolving built-in coroutine trait impls 2024-01-19 21:28:37 +00:00
George Bateman
615946db4f
Stabilize simple offset_of 2024-01-19 20:38:51 +00:00
Catherine Flores
5a4561749a Add new intrinsic is_constant and optimize pow
Fix overflow check

Make MIRI choose the path randomly and rename the intrinsic

Add back test

Add miri test and make it operate on `ptr`

Define `llvm.is.constant` for primitives

Update MIRI comment and fix test in stage2

Add const eval test

Clarify that both branches must have the same side effects

guaranteed non guarantee

use immediate type instead

Co-Authored-By: Ralf Jung <post@ralfj.de>
2024-01-19 13:46:27 -05:00
bors
92d727796b Auto merge of #120112 - matthiaskrgr:rollup-48o3919, r=matthiaskrgr
Rollup of 9 pull requests

Successful merges:

 - #119582 (bootstrap: handle vendored sources when remapping crate paths)
 - #119730 (docs: fix typos)
 - #119828 (Improved collapse_debuginfo attribute, added command-line flag)
 - #119869 (replace `track_errors` usages with bubbling up `ErrorGuaranteed`)
 - #120037 (Remove `next_root_ty_var`)
 - #120094 (tests/ui/asm/inline-syntax: adapt for LLVM 18)
 - #120096 (Set RUSTC_BOOTSTRAP=1 consistently)
 - #120101 (change `.unwrap()` to `?` on write where `fmt::Result` is returned)
 - #120102 (Fix typo in munmap_partial.rs)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-01-19 08:42:17 +00:00
Matthias Krüger
c0da80f418
Rollup merge of #119828 - azhogin:azhogin/collapse_debuginfo_improved_attr, r=petrochenkov
Improved collapse_debuginfo attribute, added command-line flag

Improved attribute collapse_debuginfo with variants: `#[collapse_debuginfo=(no|external|yes)]`.
Added command-line flag for default behaviour.
Work-in-progress: will add more tests.

cc https://github.com/rust-lang/rust/issues/100758
2024-01-18 20:56:19 +01:00
Mark Rousskov
510fcd318b Use UnhashMap for a few more maps
This avoids hashing data that's already hashed.
2024-01-17 17:09:55 -05:00
Andrew Zhogin
8507f5105b Improved collapse_debuginfo attribute, added command-line flag (no|external|yes) 2024-01-17 23:18:14 +07:00
Martin Nordholts
16ba56c242 compiler: Lower fn call arg spans down to MIR
To enable improved accuracy of diagnostics in upcoming commits.
2024-01-15 19:07:11 +01:00
bors
89110dafe7 Auto merge of #118947 - Bryanskiy:delegStep1, r=petrochenkov,lcnr
Delegation implementation: step 1

See https://github.com/rust-lang/rust/issues/118212 for more details.

r? `@petrochenkov`
2024-01-13 04:19:17 +00:00
Guillaume Gomez
737452a824
Rollup merge of #119819 - chenyukang:yukang-fix-118183-lint, r=davidtwco
Check rust lints when an unknown lint is detected

Fixes #118183
2024-01-12 15:16:56 +01:00
Bryanskiy
d69cd6473c Delegation implementation: step 1 2024-01-12 14:11:16 +03:00
yukang
ca421fe1d3 check rust lints when an unknown lint is detected 2024-01-12 18:50:36 +08:00
Mark Rousskov
1d2005be71 Remove more needless leb128 coding for enum variants
This removes emit_enum_variant and the emit_usize calls that resulted
in. In libcore this eliminates 17% of leb128, taking us from 8964488 to
7383842 leb128's serialized.
2024-01-09 20:08:44 -05:00
Matthias Krüger
ee7d4c1561
Rollup merge of #118903 - azhogin:azhogin/skip_second_stmt_debuginfo.rs, r=petrochenkov
Improved support of collapse_debuginfo attribute for macros.

Added walk_chain_collapsed function to consider collapse_debuginfo attribute in parent macros in call chain.
Fixed collapse_debuginfo attribute processing for cranelift (there was if/else branches error swap).

cc https://github.com/rust-lang/rust/issues/100758
2024-01-09 00:19:32 +01:00
Andrew Zhogin
f2dbebafad Improved support of collapse_debuginfo attribute for macros. 2024-01-08 17:47:18 +07:00
Vadim Petrochenkov
edec91d624 macro_rules: Add an expansion-local cache to span marker 2024-01-08 03:06:37 +03:00
bors
b6a8c762ee Auto merge of #119662 - matthiaskrgr:rollup-ehofh5n, r=matthiaskrgr
Rollup of 9 pull requests

Successful merges:

 - #118194 (rustdoc: search for tuples and unit by type with `()`)
 - #118781 (merge core_panic feature into panic_internals)
 - #119486 (pass allow-{dirty,staged} to clippy)
 - #119591 (rustc_mir_transform: Make DestinationPropagation stable for queries)
 - #119595 (Fixed ambiguity in hint.rs)
 - #119624 (rustc_span: More consistent span combination operations)
 - #119653 (compiler: update Fuchsia sanitizer support.)
 - #119655 (Remove ignore-stage1 that was added when changing error count msg)
 - #119661 (Strip lld-wrapper binaries)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-01-06 15:50:44 +00:00
Matthias Krüger
1d6ab69ab1
Rollup merge of #119624 - petrochenkov:dialoc4, r=compiler-errors
rustc_span: More consistent span combination operations

Also add more tests for using `tt` in addition to `ident`, and some other minor tweaks, see individual commits.

This is a part of https://github.com/rust-lang/rust/pull/119412 that doesn't yet add side tables for metavariable spans.
2024-01-06 16:07:48 +01:00
bors
9212108a9b Auto merge of #119531 - petrochenkov:cmpctxt, r=cjgillot
rustc_span: Optimize syntax context comparisons

Including comparisons with root context.

- `eq_ctxt` doesn't require retrieving full `SpanData`, or taking the span interner lock twice.
- Checking `SyntaxContext` for "rootness" is cheaper than extracting a full outer `ExpnData` for it and checking *it* for rootness.

The internal lint for `eq_ctxt` is also tweaked to detect `a.ctxt() != b.ctxt()` in addition to `a.ctxt() == b.ctxt()`.
2024-01-06 13:51:01 +00:00
bors
e21f4cd98f Auto merge of #119478 - bjorn3:no_serialize_specialization, r=wesleywiser
Avoid specialization in the metadata serialization code

With the exception of a perf-only specialization for byte slices and byte vectors.

This uses the same trick of introducing a new trait and having the Encodable and Decodable derives add a bound to it as used for TyEncoder/TyDecoder. The new code is clearer about which encoder/decoder uses which impl and it reduces the dependency of rustc on specialization, making it easier to remove support for specialization entirely or turn it into a construct that is only allowed for perf optimizations if we decide to do this.
2024-01-06 09:56:00 +00:00
Vadim Petrochenkov
90d11d6448 rustc_span: Optimize syntax context comparisons
Including comparisons with root context
2024-01-06 01:25:20 +03:00
bors
b8c207435c Auto merge of #119192 - michaelwoerister:mcp533-push, r=cjgillot
Replace a number of FxHashMaps/Sets with stable-iteration-order alternatives

This PR replaces almost all of the remaining `FxHashMap`s in query results with either `FxIndexMap` or `UnordMap`. The only case that is missing is the `EffectiveVisibilities` struct which turned out to not be straightforward to transform. Once that is done too, we can remove the `HashStable` implementation from `HashMap`.

The first commit adds the `StableCompare` trait which is a companion trait to `StableOrd`. Some types like `Symbol` can be compared in a cross-session stable way, but their `Ord` implementation is not stable. In such cases, a `StableCompare` implementation can be provided to offer a lightweight way for stable sorting. The more heavyweight option is to sort via `ToStableHashKey`, but then sorting needs to have access to a stable hashing context and `ToStableHashKey` can also be expensive as in the case of `Symbol` where it has to allocate a `String`.

The rest of the commits are rather mechanical and don't overlap, so they are best reviewed individually.

Part of [MCP 533](https://github.com/rust-lang/compiler-team/issues/533).
2024-01-05 19:38:27 +00:00
Vadim Petrochenkov
508d1ff7d8 rustc_span: More consistent span combination operations 2024-01-05 19:41:46 +03:00
Vadim Petrochenkov
205fb75cfa rustc_span: Remove fn fresh_expansion
In the past it did create a fresh expansion, but now, after surviving a number of refactorings, it does not.
Now it's just a thin wrapper around `apply_mark`.
2024-01-05 19:13:52 +03:00
Matthias Krüger
a919d97aaa
Rollup merge of #119325 - RalfJung:custom-mir, r=compiler-errors
custom mir: make it clear what the return block is

Custom MIR recently got support for specifying the "unwind action", so now there's two things coming after the actual call part of `Call` terminators. That's not very self-explaining so I propose we change the syntax to imitate keyword arguments:
```
Call(popped = Vec::pop(v), ReturnTo(drop), UnwindContinue())
```

Also fix some outdated docs and add some docs to `Call` and `Drop`.
2024-01-04 15:33:58 +01:00
Michael Woerister
36dd3d4524 Make iteration order of region_scope_tree query stable 2024-01-04 13:48:54 +01:00
Michael Woerister
739e5ef49e Split StableCompare trait out of StableOrd trait.
StableCompare is a companion trait to `StableOrd`. Some types like `Symbol` can be compared in a cross-session stable way, but their `Ord` implementation is not stable. In such cases, a `StableOrd` implementation can be provided to offer a lightweight way for stable sorting. (The more heavyweight option is to sort via `ToStableHashKey`, but then sorting needs to have access to a stable hashing context and `ToStableHashKey` can also be expensive as in the case of `Symbol` where it has to allocate a `String`.)
2024-01-04 13:32:42 +01:00
bjorn3
8fb8e6eefb Add comments sugested by reviewer 2024-01-01 19:11:50 +00:00
bjorn3
47936b4813 Avoid specialization for AttrId deserialization 2023-12-31 20:48:15 +00:00
bjorn3
8d598b0d58 Remove almost all uses of specialization from the metadata encoding code 2023-12-31 20:42:17 +00:00