Commit graph

1090 commits

Author SHA1 Message Date
bors
8bf5a8d12f Auto merge of #132833 - est31:stabilize_let_chains, r=fee1-dead
Stabilize let chains in the 2024 edition

# Stabilization report

This proposes the stabilization of `let_chains` ([tracking issue], [RFC 2497]) in the [2024 edition] of Rust.

[tracking issue]: https://github.com/rust-lang/rust/issues/53667
[RFC 2497]: https://github.com/rust-lang/rfcs/pull/2497
[2024 edition]: https://doc.rust-lang.org/nightly/edition-guide/rust-2024/index.html

## What is being stabilized

The ability to `&&`-chain `let` statements inside `if` and `while` is being stabilized, allowing intermixture with boolean expressions. The patterns inside the `let` sub-expressions can be irrefutable or refutable.

```Rust
struct FnCall<'a> {
    fn_name: &'a str,
    args: Vec<i32>,
}

fn is_legal_ident(s: &str) -> bool {
    s.chars()
        .all(|c| ('a'..='z').contains(&c) || ('A'..='Z').contains(&c))
}

impl<'a> FnCall<'a> {
    fn parse(s: &'a str) -> Option<Self> {
        if let Some((fn_name, after_name)) = s.split_once("(")
            && !fn_name.is_empty()
            && is_legal_ident(fn_name)
            && let Some((args_str, "")) = after_name.rsplit_once(")")
        {
            let args = args_str
                .split(',')
                .map(|arg| arg.parse())
                .collect::<Result<Vec<_>, _>>();
            args.ok().map(|args| FnCall { fn_name, args })
        } else {
            None
        }
    }
    fn exec(&self) -> Option<i32> {
        let iter = self.args.iter().copied();
        match self.fn_name {
            "sum" => Some(iter.sum()),
            "max" => iter.max(),
            "min" => iter.min(),
            _ => None,
        }
    }
}

fn main() {
    println!("{:?}", FnCall::parse("sum(1,2,3)").unwrap().exec());
    println!("{:?}", FnCall::parse("max(4,5)").unwrap().exec());
}
```

The feature will only be stabilized for the 2024 edition and future editions. Users of past editions will get an error with a hint to update the edition.

closes #53667

## Why 2024 edition?

Rust generally tries to ship new features to all editions. So even the oldest editions receive the newest features. However, sometimes a feature requires a breaking change so much that offering the feature without the breaking change makes no sense. This occurs rarely, but has happened in the 2018 edition already with `async` and `await` syntax. It required an edition boundary in order for `async`/`await` to become keywords, and the entire feature foots on those keywords.

In the instance of let chains, the issue is the drop order of `if let` chains. If we want `if let` chains to be compatible with `if let`, drop order makes it hard for us to [generate correct MIR]. It would be strange to have different behaviour for `if let ... {}` and `if true && let ... {}`. So it's better to [stay consistent with `if let`].

In edition 2024, [drop order changes] have been introduced to make `if let` temporaries be lived more shortly. These changes also affected `if let` chains. These changes make sense even if you don't take the `if let` chains MIR generation problem into account. But if we want to use them as the solution to the MIR generation problem, we need to restrict let chains to edition 2024 and beyond: for let chains, it's not just a change towards more sensible behaviour, but one required for correct function.

[generate correct MIR]: https://github.com/rust-lang/rust/issues/104843
[stay consistent with `if let`]: https://github.com/rust-lang/rust/pull/103293#issuecomment-1293408574
[drop order changes]: https://github.com/rust-lang/rust/issues/124085

## Introduction considerations

As edition 2024 is very new, this stabilization PR only makes it possible to use let chains on 2024 without that feature gate, it doesn't mark that feature gate as stable/removed. I would propose to continue offering the `let_chains` feature (behind a feature gate) for a limited time (maybe 3 months after stabilization?) on older editions to allow nightly users to adopt edition 2024 at their own pace. After that, the feature gate shall be marked as *stabilized*, not removed, and replaced by an error on editions 2021 and below.

## Implementation history

* History from before March 14, 2022 can be found in the [original stabilization PR] that was reverted.
* https://github.com/rust-lang/rust/pull/94927
* https://github.com/rust-lang/rust/pull/94951
* https://github.com/rust-lang/rust/pull/94974
* https://github.com/rust-lang/rust/pull/95008
* https://github.com/rust-lang/rust/pull/97295
* https://github.com/rust-lang/rust/pull/98633
* https://github.com/rust-lang/rust/pull/99731
* https://github.com/rust-lang/rust/pull/102394
* https://github.com/rust-lang/rust/pull/100526
* https://github.com/rust-lang/rust/pull/100538
* https://github.com/rust-lang/rust/pull/102998
* https://github.com/rust-lang/rust/pull/103405
* https://github.com/rust-lang/rust/pull/103293
* https://github.com/rust-lang/rust/pull/107251
* https://github.com/rust-lang/rust/pull/110568
* https://github.com/rust-lang/rust/pull/115677
* https://github.com/rust-lang/rust/pull/117743
* https://github.com/rust-lang/rust/pull/117770
* https://github.com/rust-lang/rust/pull/118191
* https://github.com/rust-lang/rust/pull/119554
* https://github.com/rust-lang/rust/pull/129394
* https://github.com/rust-lang/rust/pull/132828
* https://github.com/rust-lang/reference/pull/1179
* https://github.com/rust-lang/reference/pull/1251
* https://github.com/rust-lang/rustfmt/pull/5910

[original stabilization PR]: https://github.com/rust-lang/rust/pull/94927

## Adoption history

### In the compiler

* History before March 14, 2022 can be found in the [original stabilization PR].
* https://github.com/rust-lang/rust/pull/115983
* https://github.com/rust-lang/rust/pull/116549
* https://github.com/rust-lang/rust/pull/116688

### Outside of the compiler

* https://github.com/rust-lang/rust-clippy/pull/11750
* [rspack](https://github.com/web-infra-dev/rspack)
* [risingwave](https://github.com/risingwavelabs/risingwave)
* [dylint](https://github.com/trailofbits/dylint)
* [convex-backend](https://github.com/get-convex/convex-backend)
* [tikv](https://github.com/tikv/tikv)
* [Daft](https://github.com/Eventual-Inc/Daft)
* [greptimedb](https://github.com/GreptimeTeam/greptimedb)

## Tests

<details>

### Intentional restrictions

[`partially-macro-expanded.rs`](4adafcf40a/tests/ui/rfcs/rfc-2294-if-let-guard/partially-macro-expanded.rs), [`macro-expanded.rs`](4adafcf40a/tests/ui/rfcs/rfc-2294-if-let-guard/macro-expanded.rs): it is possible to use macros to expand to both the pattern and the expression inside a let chain, but not to the entire `let pat = expr` operand.
[`parens.rs`](4adafcf40a/tests/ui/rfcs/rfc-2294-if-let-guard/parens.rs): `if (let pat = expr)` is not allowed in chains
[`ensure-that-let-else-does-not-interact-with-let-chains.rs`](4adafcf40a/tests/ui/rfcs/rfc-2497-if-let-chains/ensure-that-let-else-does-not-interact-with-let-chains.rs): `let...else` doesn't support chaining.

### Overlap with match guards

[`move-guard-if-let-chain.rs`](4adafcf40a/tests/ui/rfcs/rfc-2294-if-let-guard/move-guard-if-let-chain.rs): test for the `use moved value` error working well in match guards. could maybe be extended with let chains that have more than one `let`
[`shadowing.rs`](4adafcf40a/tests/ui/rfcs/rfc-2294-if-let-guard/shadowing.rs): shadowing in if let guards works as expected
[`ast-validate-guards.rs`](4adafcf40a/tests/ui/rfcs/rfc-2497-if-let-chains/ast-validate-guards.rs): let chains in match guards require the match guards feature gate

### Simple cases from the early days

PR #88642 has added some tests with very simple usages of `let else`, mostly as regression tests to early bugs.

[`then-else-blocks.rs`](4adafcf40a/tests/ui/rfcs/rfc-2497-if-let-chains/then-else-blocks.rs)
[`ast-lowering-does-not-wrap-let-chains.rs`](4adafcf40a/tests/ui/rfcs/rfc-2497-if-let-chains/ast-lowering-does-not-wrap-let-chains.rs)
[`issue-90722.rs`](4adafcf40a/tests/ui/rfcs/rfc-2497-if-let-chains/issue-90722.rs)
[`issue-92145.rs`](4adafcf40a/tests/ui/rfcs/rfc-2497-if-let-chains/issue-92145.rs)

### Drop order/MIR scoping tests

[`issue-100276.rs`](4adafcf40a/tests/ui/drop/issue-100276.rs): let expressions on RHS aren't terminating scopes
[`drop_order.rs`](4adafcf40a/tests/ui/drop/drop_order.rs): exhaustive temporary drop order test for various Rust constructs, including let chains
[`scope.rs`](4adafcf40a/tests/ui/rfcs/rfc-2294-if-let-guard/scope.rs): match guard scoping test
[`drop-scope.rs`](4adafcf40a/tests/ui/rfcs/rfc-2294-if-let-guard/drop-scope.rs): another match guard scoping test, ensuring that temporaries in if-let guards live for the arm
[`drop_order_if_let_rescope.rs`](4adafcf40a/tests/ui/drop/drop_order_if_let_rescope.rs): if let rescoping on edition 2024, including chains
[`mir_let_chains_drop_order.rs`](4adafcf40a/tests/ui/mir/mir_let_chains_drop_order.rs): comprehensive drop order test for let chains, distinguishes editions 2021 and 2024.
[`issue-99938.rs`](4adafcf40a/tests/ui/rfcs/rfc-2497-if-let-chains/issue-99938.rs), [`issue-99852.rs`](4adafcf40a/tests/ui/mir/issue-99852.rs) both bad MIR ICEs fixed by #102394

### Linting

[`irrefutable-lets.rs`](4adafcf40a/tests/ui/rfcs/rfc-2497-if-let-chains/irrefutable-lets.rs): trailing and leading irrefutable let patterns get linted for, others don't. The lint is turned off for `else if`.
[`issue-121070-let-range.rs`](4adafcf40a/tests/ui/lint/issue-121070-let-range.rs): regression test for false positive of the unused parens lint, precedence requires the `()`s here

### Parser: intentional restrictions

[`disallowed-positions.rs`](2128d8df0e/tests/ui/rfcs/rfc-2497-if-let-chains/disallowed-positions.rs): `let` in expression context is rejected everywhere except at the top level
[`invalid-let-in-a-valid-let-context.rs`](4adafcf40a/tests/ui/rfcs/rfc-2497-if-let-chains/invalid-let-in-a-valid-let-context.rs): nested `let` is not allowed (let's are no legal expressions just because they are allowed in `if` and `while`).

### Parser: recovery

[`issue-103381.rs`](4adafcf40a/tests/ui/parser/issues/issue-103381.rs): Graceful recovery of incorrect chaining of `if` and `if let`
[`semi-in-let-chain.rs`](4adafcf40a/tests/ui/parser/semi-in-let-chain.rs): Ensure that stray `;`s in let chains give nice errors (`if_chain!` users might be accustomed to `;`s)
[`deli-ident-issue-1.rs`](4adafcf40a/tests/ui/parser/deli-ident-issue-1.rs), [`brace-in-let-chain.rs`](4adafcf40a/tests/ui/parser/brace-in-let-chain.rs): Ensure that stray unclosed `{`s in let chains give nice errors and hints

### Misc

[`conflicting_bindings.rs`](4adafcf40a/tests/ui/pattern/usefulness/conflicting_bindings.rs): the conflicting bindings check also works in let chains. Personally, I'd extend it to chains with multiple let's as well.
[`let-chains-attr.rs`](4adafcf40a/tests/ui/expr/if/attrs/let-chains-attr.rs): attributes work on let chains

### Tangential tests with `#![feature(let_chains)]`

[`if-let.rs`](4adafcf40a/tests/coverage/branch/if-let.rs): MC/DC coverage tests for let chains
[`logical_or_in_conditional.rs`](4adafcf40a/tests/mir-opt/building/logical_or_in_conditional.rs): not really about let chains, more about dropping/scoping behaviour of `||`
[`stringify.rs`](4adafcf40a/tests/ui/macros/stringify.rs): exhaustive test of the `stringify` macro
[`expanded-interpolation.rs`](4adafcf40a/tests/ui/unpretty/expanded-interpolation.rs), [`expanded-exhaustive.rs`](4adafcf40a/tests/ui/unpretty/expanded-exhaustive.rs): Exhaustive test of `-Zunpretty`
[`diverges-not.rs`](4adafcf40a/tests/ui/rfcs/rfc-0000-never_patterns/diverges-not.rs): Never type, mostly tangential to let chains

</details>

## Possible future work

* There is proposals to allow `if let Pat(bindings) = expr {}` to be written as `if expr is Pat(bindings) {}` ([RFC 3573]). `if let` chains are a natural extension of the already existing `if let` syntax, and I'd argue orthogonal towards `is` syntax.
  * https://github.com/rust-lang/lang-team/issues/297
* One could have similar chaining inside `let ... else` statements. There is no proposed RFC for this however, nor is it implemented on nightly.
* Match guards have the `if` keyword as well, but on stable Rust, they don't support `let`. The functionality is available via an unstable feature ([`if_let_guard` tracking issue]). Stabilization of let chains affects this feature in so far as match guards containing let chains now only need the `if_let_guard` feature gate be present instead of also the `let_chains` feature (NOTE: this PR doesn't implement this simplification, it's left for future work).

[RFC 3573]: https://github.com/rust-lang/rfcs/pull/3573
[`if_let_guard` tracking issue]: https://github.com/rust-lang/rust/issues/51114

## Open questions / blockers

- [ ] bad recovery if you don't put a `let` (I don't think this is a blocker): [#117977](https://github.com/rust-lang/rust/issues/117977)
- [x] An instance where a temporary lives shorter than with nested ifs, breaking compilation: [#103476](https://github.com/rust-lang/rust/issues/103476). Personally I don't think this is a blocker either, as it's an edge case. Edit: turns out to not reproduce in edition 2025 any more, due to let rescoping. regression test added in #133093
- [x] One should probably extend the tests for `move-guard-if-let-chain.rs` and `conflicting_bindings.rs` to have chains with multiple let's: done in 133093
- [x] Parsing rejection tests: addressed by https://github.com/rust-lang/rust/pull/132828
- [x] [Style](https://rust-lang.zulipchat.com/#narrow/channel/346005-t-style/topic/let.20chains.20stabilization.20and.20formatting): https://github.com/rust-lang/rust/pull/139456
- [x] https://github.com/rust-lang/rust/issues/86730 explicitly mentions `let_else`. I think we can live with `let pat = expr` not evaluating as `expr` for macro_rules macros, especially given that `let pat = expr` is not a legal expression anywhere except inside `if` and `while`.
- [x] Documentation in the reference: https://github.com/rust-lang/reference/pull/1740
- [x] Add chapter to the Rust 2024 [edition guide]: https://github.com/rust-lang/edition-guide/pull/337
- [x] Resolve open questions on desired drop order.

[original reference PR]: https://github.com/rust-lang/reference/pull/1179
[edition guide]: https://github.com/rust-lang/edition-guide
2025-04-22 07:54:10 +00:00
Chris Denton
5d2375f789
Rollup merge of #139042 - compiler-errors:do-not-optimize-switchint, r=saethlin
Do not remove trivial `SwitchInt` in analysis MIR

This PR ensures that we don't prematurely remove trivial `SwitchInt` terminators which affects both the borrow-checking and runtime semantics (i.e. UB) of the code. Previously the `SimplifyCfg` optimization was removing `SwitchInt` terminators when they was "trivial", i.e. when all arms branched to the same basic block, even if that `SwitchInt` terminator had the side-effect of reading an operand which (for example) may not be initialized or may point to an invalid place in memory.

This behavior is unlike all other optimizations, which are only applied after "analysis" (i.e. borrow-checking) is finished, and which Miri disables to make sure the compiler doesn't silently remove UB.

Fixing this code "breaks" (i.e. unmasks) code that used to borrow-check but no longer does, like:

```rust
fn foo() {
    let x;
    let (0 | _) = x;
}
```

This match expression should perform a read because `_` does not shadow the `0` literal pattern, and the compiler should have to read the match scrutinee to compare it to 0. I've checked that this behavior does not actually manifest in practice via a crater run which came back clean: https://github.com/rust-lang/rust/pull/139042#issuecomment-2767436367

As a side-note, it may be tempting to suggest that this is actually a good thing or that we should preserve this behavior. If we wanted to make this work (i.e. trivially optimize out reads from matches that are redundant like `0 | _`), then we should be enabling this behavior *after* fixing this. However, I think it's kinda unprincipled, and for example other variations of the code don't even work today, e.g.:

```rust
fn foo() {
    let x;
    let (0.. | _) = x;
}
```
2025-04-19 19:30:46 +00:00
est31
162daaa2fa Remove let_chains feature gate from even more tests 2025-04-18 15:57:29 +02:00
Mara Bos
1ca9300989 Update tests. 2025-04-15 11:14:23 +02:00
Matthias Krüger
143f5d7696
Rollup merge of #139767 - compiler-errors:www, r=oli-obk
Visit place in `BackwardIncompatibleDropHint` statement

Remove a weird hack from the `LocalUpdater` where we were manually visiting the place stored in a `StatementKind::BackwardIncompatibleDropHint` because the MIR visitor impls weren't doing so.

Also, clean up `BackwardIncompatibleDropHint`s in `CleanupPostBorrowck`, since they're not needed for runtime MIR.
2025-04-14 18:15:32 +02:00
Michael Goulet
2f96e784e2 Visit place in BackwardIncompatibleDropHint statement 2025-04-13 22:01:54 +00:00
clubby789
9f35fe47c7 JumpThreading: Re-enable and fix Not ops on non-booleans 2025-04-13 20:29:49 +00:00
Jacob Pratt
a6608294a9
Rollup merge of #137835 - scottmcm:signum, r=compiler-errors
Use `BinOp::Cmp` for `iNN::signum`

This way it can use the nice new LLVM intrinsic in LLVM20.
2025-04-11 21:20:59 +02:00
bors
7d7de5bf3c Auto merge of #139088 - spastorino:ergonomic-ref-counting-2, r=nikomatsakis
Ergonomic ref counting: optimize away clones when possible

This PR build on top of https://github.com/rust-lang/rust/pull/134797. It optimizes codegen of ergonomic ref-counting when the type being `use`d is only known to be copy after monomorphization. We avoid codening a clone and generate bitwise copy instead.

RFC: https://github.com/rust-lang/rfcs/pull/3680
Tracking issue: https://github.com/rust-lang/rust/issues/132290
Project goal: https://github.com/rust-lang/rust-project-goals/issues/107

r? `@nikomatsakis`

This PR could better sit on top of https://github.com/rust-lang/rust/pull/131650 but as it did not land yet I've decided to just do minimal changes. It may be the case that doing what I'm doing regress the performance and we may need to go the full route of https://github.com/rust-lang/rust/pull/131650.
cc `@saethlin` in this regard.
2025-04-10 09:08:23 +00:00
bors
f06e5c1e35 Auto merge of #139327 - cjgillot:gvn-place, r=oli-obk
Allow GVN to produce places and not just locals.

That may be too big of a hammer, as we may introduce new deref projections (possible UB footgun + probably not good for perf).

The second commit opts out of introducing projections that don't have a stable offset, which is probably what we want. Hence no new Deref and no new Index projections.

Fixes https://github.com/rust-lang/rust/issues/138936
cc `@scottmcm` `@dianqk`
2025-04-09 08:50:33 +00:00
Michael Goulet
3ee62a906e Do not optimize out SwitchInt before borrowck, or if Zmir-preserve-ub 2025-04-08 21:05:20 +00:00
Santiago Pastorino
a0856eaff6
Add mir opt tests to be sure we generate copy, clones and moves when corresponds 2025-04-07 16:53:11 -03:00
Bennet Bleßmann
7dd57f085c
update/bless tests 2025-04-06 21:41:47 +02:00
Camille GILLOT
d9caf840e1 Only introduce stable projections. 2025-04-04 10:55:42 +00:00
Camille GILLOT
109edab245 Allow GVN to produce places and not just locals. 2025-04-04 10:55:36 +00:00
bors
00095b3da4 Auto merge of #132527 - DianQK:gvn-stmt-iter, r=oli-obk
gvn: Invalid dereferences for all non-local mutations

Fixes #132353.

This PR removes the computation value by traversing SSA locals through `for_each_assignment_mut`.

Because the `for_each_assignment_mut` traversal skips statements which have side effects, such as dereference assignments, the computation may be unsound. Instead of `for_each_assignment_mut`, we compute values by traversing in reverse postorder.

Because we compute and use the symbolic representation of values on the fly, I invalidate all old values when encountering a dereference assignment. The current approach does not prevent the optimization of a clone to a copy.

In the future, we may add an alias model, or dominance information for dereference assignments, or SSA form to help GVN.

r? cjgillot

cc `@jieyouxu` #132356
cc `@RalfJung` #133474
2025-04-03 19:17:33 +00:00
dianqk
7d44887374
Invalid dereferences for all non-local mutations 2025-04-03 21:59:49 +08:00
dianqk
ac7dd7a1b3
Remove unsound-mir-opts for simplify_aggregate_to_copy 2025-04-03 21:59:43 +08:00
bors
e0883a2a6c Auto merge of #137738 - Daniel-Aaron-Bloom:const_slice_make_iter, r=dtolnay
Make slice iterator constructors unstably const

See [tracking issue](https://github.com/rust-lang/rust/issues/137737) for justification.

try-job: aarch64-apple
try-job: x86_64-gnu
2025-04-03 08:57:46 +00:00
Daniel Bloom
20417a9522 Make slice iterator constructors unstably const 2025-04-02 10:39:14 -07:00
dianqk
1787789fe5
Bless tests 2025-04-02 19:59:26 +08:00
dianqk
7e0463fe93
Revert "comment out the old tests instead of adjusting them"
This reverts commit 906f66fb4c.
2025-04-02 19:59:26 +08:00
dianqk
7830406df1
Invalidate all dereferences for non-local assignments 2025-04-02 19:58:35 +08:00
dianqk
9d999bb035
Do not use for_each_assignment_mut to iterate over assignment statements
`for_each_assignment_mut` can skip assignment statements with side effects,
which can result in some assignment statements retrieving outdated value.
For example, it may skip a dereference assignment statement.
2025-04-02 19:27:17 +08:00
Stuart Cook
82f04468e9
Rollup merge of #139214 - bjorn3:edition_2024_rustfmt, r=compiler-errors
Tell rustfmt to use the 2024 edition in ./x.py fmt

Most crates in this repo have been moved to the 2024 edition already. This also allows removing a rustfmt exclusion for a cg_clif test.
2025-04-02 13:10:42 +11:00
bjorn3
f922e74f71 Make coroutine_drop_cleanup 2024 edition compatible 2025-04-01 14:49:15 +00:00
Zalathar
577272eede coverage: Shrink call spans to just the function name
This is a way to shrink call spans that doesn't involve mixing different spans,
and avoids overlap with argument spans.

This patch also removes some low-value comments that were causing rustfmt to
ignore the match arms.
2025-04-01 13:07:33 +11:00
Michael Goulet
897acc3e5d Encode synthetic by-move coroutine body with a different DefPathData 2025-03-30 22:53:21 +00:00
Jacob Pratt
1ba9b7873a
Rollup merge of #138135 - scottmcm:chaining-ord, r=Mark-Simulacrum
Simplify `PartialOrd` on tuples containing primitives

We noticed in https://github.com/rust-lang/rust/pull/133984#issuecomment-2704011800 that currently the tuple comparison code, while it [does optimize down](https://github.com/rust-lang/rust/blob/master/tests/codegen/comparison-operators-2-tuple.rs) today, is kinda huge: <https://rust.godbolt.org/z/xqMoeYbhE>

This PR changes the tuple code to go through an overridable "chaining" version of the comparison functions, so that for simple things like `(i16, u16)` and `(f32, f32)` (as seen in the new MIR pre-codegen test) we just directly get the
```rust
if lhs.0 == rhs.0 { lhs.0 OP rhs.0 }
else { lhs.1 OP rhs.1 }
```
version in MIR, rather than emitting a mess for LLVM to have to clean up.

Test added in the first commit, so you can see the MIR diff in the second one.
2025-03-23 20:44:09 -04:00
Scott McMurray
7781346243 Stop using specialization for this
Uses `__`-named `doc(hidden)` methods instead.
2025-03-23 15:27:31 -07:00
Michael Goulet
e31d3e3bde
Rollup merge of #138545 - scottmcm:more-option-tests, r=Mark-Simulacrum
Add MIR pre-codegen tests to track #138544

I don't know how best to fix the problem yet, but wanted to check in some tests to demonstrate it and make sure that they get updated to keep it fixed if anyone does fix it 🙂

No code changes; just the tests for #138544.
2025-03-23 14:59:32 -04:00
bors
0ce1369bde Auto merge of #136974 - m-ou-se:fmt-options-64-bit, r=scottmcm
Reduce FormattingOptions to 64 bits

This is part of https://github.com/rust-lang/rust/issues/99012

This reduces FormattingOptions from 6-7 machine words (384 bits on 64-bit platforms, 224 bits on 32-bit platforms) to just 64 bits (a single register on 64-bit platforms).

Before:

```rust
pub struct FormattingOptions {
    flags: u32, // only 6 bits used
    fill: char,
    align: Option<Alignment>,
    width: Option<usize>,
    precision: Option<usize>,
}
```

After:

```rust
pub struct FormattingOptions {
    /// Bits:
    ///  - 0-20: fill character (21 bits, a full `char`)
    ///  - 21: `+` flag
    ///  - 22: `-` flag
    ///  - 23: `#` flag
    ///  - 24: `0` flag
    ///  - 25: `x?` flag
    ///  - 26: `X?` flag
    ///  - 27: Width flag (if set, the width field below is used)
    ///  - 28: Precision flag (if set, the precision field below is used)
    ///  - 29-30: Alignment (0: Left, 1: Right, 2: Center, 3: Unknown)
    ///  - 31: Always set to 1
    flags: u32,
    /// Width if width flag above is set. Otherwise, always 0.
    width: u16,
    /// Precision if precision flag above is set. Otherwise, always 0.
    precision: u16,
}
```
2025-03-22 10:56:14 +00:00
Scott McMurray
35248c6830 Add chaining versions of lt/le/gt/ge and use them in tuple PartialOrd 2025-03-19 09:27:02 -07:00
Scott McMurray
b54ca0e433 Add a MIR pre-codegen test for tuple comparisons
We have codegen ones, but it looks like we could make those less flakey by just doing something better in the first place...
2025-03-19 09:13:41 -07:00
Zalathar
cc8336b6c1 coverage: Don't store a body span in FunctionCoverageInfo 2025-03-18 23:18:24 +11:00
Matthias Krüger
fd4ad33242
Rollup merge of #137465 - Zalathar:visit-primary, r=oli-obk
mir_build: Avoid some useless work when visiting "primary" bindings

While looking over `visit_primary_bindings`, I noticed that it does a bunch of extra work to build up a collection of “user-type projections”, even though 2/3 of its call sites don't even use them. Those callers can get the same result via `thir::Pat::walk_always`.

(And it turns out that doing so also avoids creating some redundant user-type entries in MIR for some binding constructs.)

I also noticed that even when the user-type projections *are* used, the process of building them ends up eagerly cloning some nested vectors at every recursion step, even in cases where they won't be used because the current subpattern has no bindings. To avoid this, the visit method now assembles a linked list on the stack containing the information that *would* be needed to create projections, and only creates the concrete projections as needed when a primary binding is encountered.

Some relevant prior PRs:
- #55274
- 0bfe184b1a in #55937

---

There should be no user-visible change in compiler output.
2025-03-17 16:34:48 +01:00
Zalathar
7805b465fd Split visit_primary_bindings into two variants
The existing method does some non-obvious extra work to collect user types and
build user-type projections, which is specifically needed by `declare_bindings`
and not by the other two callers.
2025-03-16 12:10:35 +11:00
Zalathar
bca5f567d2 Add a mir-opt test that demonstrates user type annotations 2025-03-16 12:10:35 +11:00
Scott McMurray
1cdddd67a3 Add MIR pre-codegen tests to track 138544 2025-03-15 14:13:37 -07:00
Michael Goulet
13134dd096 Don't drop Rvalue::WrapUnsafeBinder during GVN 2025-03-15 18:10:55 +00:00
Matthias Krüger
81ba55746d
Rollup merge of #138514 - compiler-errors:fake-borrow-ref-to-value, r=oli-obk
Remove fake borrows of refs that are converted into non-refs in `MakeByMoveBody`

Remove fake borrows of closure captures if that capture has been replaced with a by-move version of that capture.

For example, given an async closure that looks like:

```
let f: Foo;
let c = async move || {
    match f { ... }
};
```

... in this pair of coroutine-closure + coroutine, we capture `Foo` in the parent and `&Foo` in the child. We will emit two fake borrows like:

```
_2 = &fake shallow (*(_1.0: &Foo));
_3 = &fake shallow (_1.0: &Foo);
```

However, since the by-move-body transform is responsible for replacing `_1.0: &Foo` with `_1.0: Foo` (since the `AsyncFnOnce` coroutine will own `Foo` by value), that makes the second fake borrow obsolete since we never have an upvar of type `&Foo`, and we should replace it with a `nop`.

As a side-note, we don't actually even care about fake borrows here at all since they're fully a MIR borrowck artifact, and we don't need to borrowck by-move MIR bodies. But it's best to preserve as much as we can between these two bodies :)

Fixes #138501

r? oli-obk
2025-03-15 11:29:27 +01:00
Michael Goulet
e54bde6d47 Remove fake borrows of refs that are converted into non-refs in MakeByMoveBody 2025-03-14 19:38:29 +00:00
bors
523c507d26 Auto merge of #138157 - scottmcm:inline-more-tiny-things, r=oli-obk
Allow more top-down inlining for single-BB callees

This means that things like `<usize as Step>::forward_unchecked` and `<PartialOrd for f32>::le` will inline even if
we've already done a bunch of inlining to find the calls to them.

Fixes #138136

~~Draft as it's built atop #138135, which adds a mir-opt test that's a nice demonstration of this.  To see just this change, look at <48f63e3be5>~~ Rebased to be just the inlining change, as the other existing tests show it great.
2025-03-14 03:51:19 +00:00
Matthias Krüger
448aa30b5a
Rollup merge of #138162 - ehuss:library-2024, r=cuviper
Update the standard library to Rust 2024

This updates the standard library to Rust 2024. This includes the following notable changes:

- Macros are updated to use new expression fragment specifiers. This PR includes a test to illustrate the changes, primarily allowing `const {...}` expressions now.
- Some tests show a change in MIR drop order. We do not believe this will be an observable change ([see zulip discussion](500972873)).

Fixes https://github.com/rust-lang/rust/issues/133081
2025-03-13 10:58:21 +01:00
Scott McMurray
91af4aa2e2 Allow more top-down inlining for single-BB callees
This means that things like `<usize as Step>::forward_unchecked` and `<PartialOrd for f32>::le` will inline even if we've already done a bunch of inlining to find the calls to them.
2025-03-12 22:39:43 -07:00
Manish Goregaokar
f5eb296c5a
Rollup merge of #138280 - folkertdev:mir-dump-asm-const, r=compiler-errors
fix ICE in pretty-printing `global_asm!`

fixes https://github.com/rust-lang/rust/issues/138260

since https://github.com/rust-lang/rust/pull/137180, `global_asm!` gets a fake body, that the pretty printing logic did not know what to do with.

based on [#t-compiler/help > tests for MIR pretty printing](https://rust-lang.zulipchat.com/#narrow/channel/182449-t-compiler.2Fhelp/topic/tests.20for.20MIR.20pretty.20printing) I created `tests/ui/unpretty/mir` which seemed as good a place as any for a test. If there is a better place, let me know.

try-job: test-various
try-job: x86_64-apple-2
2025-03-12 10:19:28 -07:00
Mara Bos
ba2809e085 Update tests. 2025-03-12 16:32:11 +01:00
Eric Huss
0e071c2c6a Migrate core to Rust 2024 2025-03-11 09:46:34 -07:00
Folkert de Vries
9213cb80c2
fix ICE in pretty-printing global_asm! 2025-03-10 14:46:01 +01:00
Mara Bos
4374d5461e Update tests. 2025-03-10 12:20:05 +01:00