Commit Graph

1988 Commits

Author SHA1 Message Date
Nadrieril
57e8aebb6c Lower never patterns to Unreachable in mir 2024-05-04 16:30:01 +02:00
bors
09cd00fea4 Auto merge of #124401 - oli-obk:some_hir_cleanups, r=cjgillot
Some hir cleanups

It seemed odd to not put `AnonConst` in the arena, compared with the other types that we did put into an arena. This way we can also give it a `Span` without growing a lot of other HIR data structures because of the extra field.

r? compiler
2024-05-04 00:32:27 +00:00
Ralf Jung
cbd682beeb turn pointer_structural_match into a hard error 2024-05-03 15:56:59 +02:00
Ralf Jung
179a6a08b1 remove IndirectStructuralMatch lint, emit the usual hard error instead 2024-05-03 15:56:59 +02:00
Matthias Krüger
d6940fb43d
Rollup merge of #124624 - WaffleLapkin:old_unit, r=fmease
Use `tcx.types.unit` instead of `Ty::new_unit(tcx)`

I don't think there is any need for the function, given that we can just access the `.types`, similarly to all other primitives?
2024-05-02 19:42:50 +02:00
Waffle Lapkin
698d7a031e Inline & delete Ty::new_unit, since it's just a field access 2024-05-02 17:49:23 +02:00
Mark Rousskov
a64f941611 Step bootstrap cfgs 2024-05-01 22:19:11 -04:00
León Orell Valerian Liehr
2a1d748254
Replace item names containing an error code with something more meaningful
or inline such functions if useless.
2024-04-30 22:27:19 +02:00
Zalathar
7c87ad0430 coverage: Add branch coverage support for if-let and let-chains 2024-04-30 22:35:55 +10:00
Zalathar
c9dd07dd5e coverage: Add branch coverage support for let-else 2024-04-30 22:35:54 +10:00
zhuyunxing
6c8b492f02 coverage. Split mcdc builder to a sub module of coverageinfo 2024-04-30 12:17:35 +08:00
zhuyunxing
e198c51f16 coverage. Add MCDCInfoBuilder to isolate all mcdc stuff from BranchInfoBuilder 2024-04-30 12:17:25 +08:00
zhuyunxing
a76e250abd coverage. Add BlockMarkerGen to avoid ownership gymnastics 2024-04-30 11:19:23 +08:00
许杰友 Jieyou Xu (Joe)
0797adb327
Rollup merge of #124508 - Zalathar:op, r=jieyouxu
coverage: Avoid hard-coded values when visiting logical ops

This is a tiny little thing that I noticed during the final review of #123409, and I didn't want to hold up the whole PR just for this.

Instead of separately hard-coding the operation being visited, we can get it from the match arm pattern by using an as-pattern.

`@rustbot` label +A-code-coverage
2024-04-29 18:03:25 +01:00
bors
7a58674259 Auto merge of #124255 - RenjiSann:renji/mcdc-nested-expressions, r=Zalathar
MCDC coverage: support nested decision coverage

#123409 provided the initial MCDC coverage implementation.

As referenced in #124144, it does not currently support "nested" decisions, like the following example :

```rust
fn nested_if_in_condition(a: bool, b: bool, c: bool) {
    if a && if b || c { true } else { false } {
        say("yes");
    } else {
        say("no");
    }
}
```

Note that there is an if-expression (`if b || c ...`) embedded inside a boolean expression in the decision of an outer if-expression.

This PR proposes a workaround for this cases, by introducing a Decision context stack, and by handing several `temporary condition bitmaps` instead of just one.
When instrumenting boolean expressions, if the current node is a leaf condition (i.e. not a `||`/`&&` logical operator nor a `!` not operator), we insert a new decision context, such that if there are more boolean expressions inside the condition, they are handled as separate expressions.

On the codegen LLVM side, we allocate as many `temp_cond_bitmap`s as necessary to handle the maximum encountered decision depth.
2024-04-29 11:54:49 +00:00
Oli Scherer
fea1fe7f01 Avoid some def_span query calls 2024-04-29 09:48:19 +00:00
Dorian Péron
60ca9b6e29 mcdc-coverage: Get decision_depth from THIR lowering
Use decision context stack to handle nested decisions:
- Introduce MCDCDecisionCtx
- Use a stack of MCDCDecisionCtx to handle nested decisions
2024-04-29 09:13:40 +00:00
Dorian Péron
ae8c023983 mcdc-coverage: Add decision_depth field in structs
Add decision_depth field to TVBitmapUpdate/CondBitmapUpdate statements
Add decision_depth field to BcbMappingKinds MCDCBranch and MCDCDecision
Add decision_depth field to MCDCBranchSpan and MCDCDecisionSpan
2024-04-29 09:13:40 +00:00
Zalathar
a25a11ad73 coverage: Avoid hard-coded values when visiting logical ops
Instead of separately hard-coding the operation being visited, we can get it
from the match arm pattern by using an as-pattern.
2024-04-29 16:41:10 +10:00
León Orell Valerian Liehr
6e423e1651
Rollup merge of #124218 - Xiretza:subsubdiagnostics, r=davidtwco
Allow nesting subdiagnostics in #[derive(Subdiagnostic)]
2024-04-23 17:25:17 +02:00
León Orell Valerian Liehr
332cac2c6d
Rollup merge of #122598 - Nadrieril:full-derefpats, r=matthewjasper
deref patterns: lower deref patterns to MIR

This lowers deref patterns to MIR. This is a bit tricky because this is the first kind of pattern that requires storing a value in a temporary. Thanks to https://github.com/rust-lang/rust/pull/123324 false edges are no longer a problem.

The thing I'm not confident about is the handling of fake borrows. This PR ignores any fake borrows inside a deref pattern. We are guaranteed to at least fake borrow the place of the first pointer value, which could be enough, but I'm not certain.
2024-04-23 17:25:15 +02:00
Zalathar
b5a22be6a3 coverage: Move some helper code into BranchInfoBuilder 2024-04-22 21:55:33 +10:00
Zalathar
97bf553682 coverage: Detach MC/DC branch spans from regular branch spans
MC/DC's reliance on the existing branch coverage types is making it much harder
to improve branch coverage.
2024-04-22 21:55:33 +10:00
Xiretza
5646b65cf5 Pass translation closure to add_to_diag_with() as reference 2024-04-21 07:45:03 +00:00
Nadrieril
436c61266c Use deep fake borrows for deref patterns 2024-04-20 16:04:05 +02:00
Nadrieril
50531806ee Add a non-shallow fake borrow 2024-04-20 16:01:35 +02:00
Nadrieril
511bd78863 Rework fake borrow calculation 2024-04-20 16:01:35 +02:00
Nadrieril
377e095371 Allow mutable bindings inside deref patterns 2024-04-20 15:59:54 +02:00
Nadrieril
5c4909b8e1 Track mutability of deref patterns 2024-04-20 15:59:54 +02:00
Nadrieril
1dabacd059 Don't fake borrow inside a deref pattern 2024-04-20 15:59:54 +02:00
Nadrieril
c623319a30 Lower deref patterns to MIR
This handles using deref patterns to choose the correct match arm. This
does not handle bindings or guards.

Co-authored-by: Deadbeef <ent3rm4n@gmail.com>
2024-04-20 15:59:54 +02:00
Matthias Krüger
efb264fa78
Rollup merge of #123409 - ZhuUx:master, r=oli-obk
Implement Modified Condition/Decision  Coverage

This is an implementation based on llvm backend support (>= 18) by `@evodius96` and branch coverage support by `@Zalathar.`

### Major changes:

* Add -Zcoverage-options=mcdc as switch. Now coverage options accept either `no-branch`, `branch`, or `mcdc`. `mcdc` also enables `branch` because it is essential to work.
* Add coverage mapping for MCDCBranch and MCDCDecision. Note that MCDCParameter evolves from  llvm 18 to llvm 19. The mapping in rust side mainly references to 19 and is casted to 18 types in llvm wrapper.
* Add wrapper for mcdc instrinc functions from llvm. And inject associated statements to mir.
* Add BcbMappingKind::Decision, I'm not sure is it proper but can't find a better way temporarily.
* Let coverage-dump support parsing MCDCBranch and MCDCDecision from llvm ir.
* Add simple tests to check whether mcdc works.
* Same as clang, currently rustc does not generate instrument for decision with more than 6 condtions or only 1 condition due to considerations of resource.

### Implementation Details

1. To get information about conditions and decisions, `MCDCState` in `BranchInfoBuilder` is used during hir lowering to mir. For expressions with logical op we call `Builder::visit_coverage_branch_operation` to record its sub conditions, generate condition ids for them and save their spans (to construct the span of whole decision). This process mainly references to the implementation in clang and is described in comments over `MCDCState::record_conditions`. Also true marks and false marks introduced by branch coverage are used to detect where the decision evaluation ends: the next id  of the condition == 0.
2. Once the `MCDCState::decision_stack` popped all recorded conditions, we can ensure that the decision is checked over and push it into `decision_spans`. We do not manually insert decision span to avoid complexity from then_else_break in nested if scopes.
3. When constructing CoverageSpans, add condition info to BcbMappingKind::Branch and decision info to BcbMappingKind::Decision. If the branch mapping has non-zero condition id it will be transformed to MCDCBranch mapping and insert `CondBitmapUpdate` statements to its evaluated blocks. While decision bcb mapping will insert `TestVectorBitmapUpdate` in all its end blocks.

### Usage
```bash
 echo "[build]\nprofiler=true" >> config.toml
./x build --stage 1
./x test tests/coverage/mcdc_if.rs
```
to build the compiler and run tests.

```shell
export PATH=path/to/llvm-build:$PATH
rustup toolchain link mcdc build/host/stage1
cargo +mcdc rustc --bin foo -- -Cinstrument-coverage -Zcoverage-options=mcdc
cd target/debug
LLVM_PROFILE_FILE="foo.profraw" ./foo
llvm-profdata merge -sparse foo.profraw -o foo.profdata
llvm-cov show ./foo -instr-profile=foo.profdata --show-mcdc
```
to check "foo" code.

### Problems to solve

For now decision mapping will insert statements to its all end blocks, which may be optimized by inserting a final block of the decision. To do this we must also trace the evaluated value at each end of the decision and join them separately.

This implementation is not heavily tested so there should be some unrevealed issues. We are going to check our rust products in the next.  Please let me know if you had any suggestions or comments.
2024-04-20 11:10:31 +02:00
zhuyunxing
cf6b6cb2b4 coverage. Generate Mappings of decisions and conditions for MC/DC 2024-04-19 17:09:26 +08:00
Jubilee
f36ca7a75f
Rollup merge of #124110 - beetrees:neg-f16-f128, r=compiler-errors
Fix negating `f16` and `f128` constants

Make `f16` and `f128` constants respect `neg` in `parse_float_into_scalar`.

Tracking issue: #116909

```@rustbot``` label +F-f16_and_f128
2024-04-18 21:38:57 -07:00
zhuyunxing
68f86381ee coverage. Add coverage-options=mcdc as gate for MC/DC instrument 2024-04-19 10:43:53 +08:00
Matthias Krüger
2c7ef79065
Rollup merge of #124064 - Zalathar:otherwise-block, r=Nadrieril
Move confusing comment about otherwise blocks in `lower_match_tree`

This comment was historically inside a block guarded by `if let Some(otherwise_block) = otherwise`.

When #120978 made the “otherwise block” non-optional, it also flattened that region of code. Doing so left this comment awkwardly stranded above an unrelated line of code, without its original context.

We can restore that context by moving it above the declaration of `otherwise`.

r? ``@Nadrieril``
2024-04-18 08:37:49 +02:00
beetrees
cc12a1b511
Fix negating f16 and f128 constants 2024-04-18 06:43:44 +01:00
Jules Bertholet
2a4624ddd1
Rename BindingAnnotation to BindingMode 2024-04-17 09:34:39 -04:00
Zalathar
d3c3051995 Move confusing comment about otherwise blocks in lower_match_tree
This comment was historically inside a block guarded by
`if let Some(otherwise_block) = otherwise`.

When #120978 made the otherwise block non-optional, it also flattened that
region of code. Doing so left this comment awkwardly stranded above an
unrelated line of code, without its original context.

We can restore that context by moving it above the declaration of `otherwise`.
2024-04-17 19:59:39 +10:00
Matthias Krüger
45940fe6d8
Rollup merge of #122813 - nnethercote:nicer-quals, r=compiler-errors
Qualifier tweaking

Adding and removing qualifiers in some cases that make things nicer. Details in individual commits.

r? `@compiler-errors`
2024-04-17 05:44:52 +02:00
Guillaume Gomez
239b3728d5
Rollup merge of #123512 - Jules-Bertholet:ref-pat-eat-one-layer-2024, r=Nadrieril
Match ergonomics 2024: Implement eat-one-layer

r? `@Nadrieril`

cc #123076

`@rustbot` label A-edition-2024 A-patterns
2024-04-16 21:41:24 +02:00
Guillaume Gomez
6629fe6c6d
Rollup merge of #123995 - compiler-errors:thir-hooks, r=oli-obk
Make `thir_tree` and `thir_flat` into hooks

No need for them to be queries, since they are only called with `-Zunpretty`
2024-04-16 15:19:15 +02:00
Nicholas Nethercote
4b27cc8b7a Avoid lots of hir::HirId{,Map,Set} qualifiers.
Because they're a bit redundant.
2024-04-16 16:29:15 +10:00
Jules Bertholet
e3945bd3a8
Ensure inherited reference is never set to &mut behind an & 2024-04-15 23:34:50 -04:00
Michael Goulet
81bf9ae263 Make thir_tree and thir_flat into hooks 2024-04-15 20:08:21 -04:00
Michael Goulet
34bce07e8e Remove TypeVariableOriginKind 2024-04-15 16:51:50 -04:00
Alan Egerton
ddcfb94b84
Suppress erroneous suggestion
The suggestion to use `let else` with an uninitialized refutable `let`
statement was erroneous: `let else` cannot be used with deferred
initialization.
2024-04-12 17:45:15 +01:00
Oli Scherer
84acfe86de Actually create ranged int types in the type system. 2024-04-08 12:02:19 +00:00
Guillaume Gomez
f2f8d8b722
Rollup merge of #123311 - Jules-Bertholet:andpat-everywhere, r=Nadrieril
Match ergonomics: implement "`&`pat everywhere"

Implements the eat-two-layers (feature gate `and_pat_everywhere`, all editions) ~and the eat-one-layer (feature gate `and_eat_one_layer_2024`, edition 2024 only, takes priority on that edition when both feature gates are active)~ (EDIT: will be done in later PR) semantics.

cc #123076

r? ``@Nadrieril``

``@rustbot`` label A-patterns A-edition-2024
2024-04-05 16:38:50 +02:00
Matthias Krüger
504a78e2f2
Rollup merge of #123324 - Nadrieril:false-edges2, r=matthewjasper
match lowering: make false edges more precise

When lowering match expressions, we add false edges to hide details of the lowering from borrowck. Morally we pretend we're testing the patterns (and guards) one after the other in order. See the tests for examples. Problem is, the way we implement this today is too coarse for deref patterns.

In deref patterns, a pattern like `deref [1, x]` matches on a `Vec` by creating a temporary to store the output of the call to `deref()` and then uses that to continue matching. Here the pattern has a binding, which we set up after the pre-binding block. Problem is, currently the false edges tell borrowck that the pre-binding block can be reached from a previous arm as well, so the `deref()` temporary may not be initialized. This triggers an error when we try to use the binding `x`.

We could call `deref()` a second time, but this opens the door to soundness issues if the deref impl is weird. Instead in this PR I rework false edges a little bit.

What we need from false edges is a (fake) path from each candidate to the next, specifically from candidate C's pre-binding block to next candidate D's pre-binding block. Today, we link the pre-binding blocks directly. In this PR, I link them indirectly by choosing an earlier node on D's success path. Specifically, I choose the earliest block on D's success path that doesn't make a loop (if I chose e.g. the start block of the whole match (which is on the success path of all candidates), that would make a loop). This turns out to be rather straightforward to implement.

r? `@matthewjasper` if you have the bandwidth, otherwise let me know
2024-04-04 14:51:16 +02:00
Matthias Krüger
25b0e84170
Rollup merge of #123419 - petrochenkov:zeroindex, r=compiler-errors
rustc_index: Add a `ZERO` constant to index types

It is commonly used.
2024-04-03 22:11:02 +02:00
Nadrieril
8021192d34 More precise false edges 2024-04-03 21:02:47 +02:00
Nadrieril
8f80259f10 Explain false edges in more detail 2024-04-03 21:02:47 +02:00
Vadim Petrochenkov
b40ea03f8a rustc_index: Add a ZERO constant to index types
It is commonly used.
2024-04-03 19:06:22 +03:00
Matthias Krüger
deb48aa0f5
Rollup merge of #123394 - compiler-errors:postfix-match-fixes, r=estebank
Postfix match fixes

1. Don't ice on `expr as Ty.match {}`
2. Fix the suggestion span for non-exhaustive matches to add `_ => todo!(),`

Fixes #123383
2024-04-03 17:15:50 +02:00
Matthew Jasper
a277c901d9 Remove MIR unsafe check
This also remove safety information from MIR.
2024-04-03 08:50:12 +00:00
Michael Goulet
bed8b70d67 Fix suggestions for match non-exhaustiveness 2024-04-02 19:06:28 -04:00
Jules Bertholet
9d200f2d88
Address review comments 2024-04-02 10:57:54 -05:00
bors
6bb6b816bf Auto merge of #122046 - Nadrieril:integrate-or-pats2, r=matthewjasper
match lowering: handle or-patterns one layer at a time

`create_or_subcandidates` and `merge_trivial_subcandidates` both call themselves recursively to handle nested or-patterns, which is hard to follow. In this PR I avoid the need for that; we now process a single "layer" of or-patterns at a time.

By calling back into `match_candidates`, we only need to expand one layer at a time. Conversely, since we always try to simplify a layer that we just expanded (thanks to https://github.com/rust-lang/rust/pull/123067), we only have to merge one layer at a time.

r? `@matthewjasper`
2024-04-01 12:31:27 +00:00
Jules Bertholet
f37a4d55ee
Implement "&<pat> everywhere"
The original proposal allows reference patterns
with "compatible" mutability, however it's not clear
what that means so for now we require an exact match.

I don't know the type system code well, so if something
seems to not make sense it's probably because I made a
mistake
2024-03-30 12:57:54 -05:00
Nadrieril
75d2e67ed2 Sort Eq candidates in the failure case too 2024-03-30 17:37:15 +01:00
Matthias Krüger
8d820c0c47
Rollup merge of #123188 - klensy:clippy-me2, r=Nilstrieb
compiler: fix few unused_peekable and needless_pass_by_ref_mut clippy lints

This fixes few instances of `unused_peekable` and `needless_pass_by_ref_mut`. While i expected to fix more warnings, `needless_pass_by_ref_mut` produced too much for one PR, so i stopped here.

Better reviewed commit by commit, as fixes splitted by chunks.
2024-03-29 15:17:11 +01:00
klensy
8245718503 and more
warning: this argument is a mutable reference, but not used mutably
    --> compiler\rustc_mir_transform\src\coroutine.rs:1229:11
     |
1229 |     body: &mut Body<'tcx>,
     |           ^^^^^^^^^^^^^^^ help: consider changing to: `&Body<'tcx>`
     |
     = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_pass_by_ref_mut

warning: this argument is a mutable reference, but not used mutably
   --> compiler\rustc_mir_transform\src\nrvo.rs:123:11
    |
123 |     body: &mut mir::Body<'_>,
    |           ^^^^^^^^^^^^^^^^^^ help: consider changing to: `&mir::Body<'_>`
    |
    = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_pass_by_ref_mut

warning: this argument is a mutable reference, but not used mutably
  --> compiler\rustc_mir_transform\src\nrvo.rs:87:34
   |
87 | fn local_eligible_for_nrvo(body: &mut mir::Body<'_>) -> Option<Local> {
   |                                  ^^^^^^^^^^^^^^^^^^ help: consider changing to: `&mir::Body<'_>`
   |
   = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_pass_by_ref_mut
2024-03-28 17:19:15 +03:00
Nadrieril
7410f78e9a Use create_or_subcandidates for all or-pattern expansions 2024-03-27 20:53:29 +01:00
Nadrieril
23c9f698c0 Avoid recursion in creating and merging or-patterns
By calling back into `match_candidates`, we only need to expand one
layer at a time. Conversely, since we always try to simplify a layer
that we just expanded, we only have to merge one layer at a time.
2024-03-27 17:58:35 +01:00
Jules Bertholet
e0da13f25f
Implement mut ref/mut ref mut 2024-03-27 09:53:23 -04:00
Matthias Krüger
a2122dc1e3
Rollup merge of #122439 - Nadrieril:store-built-place, r=compiler-errors
match lowering: build the `Place` instead of keeping a `PlaceBuilder` around

Outside of `MatchPair::new` we don't construct new places, so we don't need to keep a `PlaceBuilder` around.

A bit annoyingly we have to store an `Option<Place>` even though it's never `None` after simplification, but the alternative would be to re-entangle `MatchPair` construction and simplification and I'd rather not do that.
2024-03-27 05:21:15 +01:00
Nadrieril
14f186c756 Store Place instead of PlaceBuilder in MatchPair 2024-03-26 19:26:16 +01:00
Nadrieril
3878b3716d Rename 2024-03-26 19:26:16 +01:00
Nadrieril
d1d9aa3108 Consistently merge simplifiable or-patterns 2024-03-25 23:52:17 +01:00
Nadrieril
08d7379961 Use the correct span for simplifying or-patterns
We have to make sure we set it everywhere that we set `subcandidates`.
2024-03-25 23:46:18 +01:00
bors
13dac8fb73 Auto merge of #122721 - oli-obk:merge_queries, r=davidtwco
Replace `mir_built` query with a hook and use mir_const everywhere instead

A small perf improvement due to less dep graph handling.

Mostly just a cleanup to get rid of one of our many mir queries
2024-03-25 01:33:46 +00:00
Zalathar
ab92699f4a Unbox and unwrap the contents of StatementKind::Coverage
The payload of coverage statements was historically a structure with several
fields, so it was boxed to avoid bloating `StatementKind`.

Now that the payload is a single relatively-small enum, we can replace
`Box<Coverage>` with just `CoverageKind`.

This patch also adds a size assertion for `StatementKind`, to avoid
accidentally bloating it in the future.
2024-03-23 22:05:11 +11:00
Michael Goulet
f0f224a37f Ty::new_ref and Ty::new_ptr stop using TypeAndMut 2024-03-22 11:13:27 -04:00
Matthias Krüger
783778c631
Rollup merge of #121619 - RossSmyth:pfix_match, r=petrochenkov
Experimental feature postfix match

This has a basic experimental implementation for the RFC postfix match (rust-lang/rfcs#3295, #121618). [Liaison is](https://rust-lang.zulipchat.com/#narrow/stream/213817-t-lang/topic/Postfix.20Match.20Liaison/near/423301844) ```@scottmcm``` with the lang team's [experimental feature gate process](https://github.com/rust-lang/lang-team/blob/master/src/how_to/experiment.md).

This feature has had an RFC for a while, and there has been discussion on it for a while. It would probably be valuable to see it out in the field rather than continue discussing it. This feature also allows to see how popular postfix expressions like this are for the postfix macros RFC, as those will take more time to implement.

It is entirely implemented in the parser, so it should be relatively easy to remove if needed.

This PR is split in to 5 commits to ease review.

1. The implementation of the feature & gating.
2. Add a MatchKind field, fix uses, fix pretty.
3. Basic rustfmt impl, as rustfmt crashes upon seeing this syntax without a fix.
4. Add new MatchSource to HIR for Clippy & other HIR consumers
2024-03-22 11:36:58 +01:00
Michael Goulet
2d633317f3 Implement macro-based deref!() syntax for deref patterns
Stop using `box PAT` syntax for deref patterns, as it's misleading and
also causes their semantics being tangled up.
2024-03-21 11:42:49 -04:00
Matthias Krüger
0867025cc8
Rollup merge of #122222 - Nadrieril:deref-pat-feature-gate, r=compiler-errors
deref patterns: bare-bones feature gate and typechecking

I am restarting the deref patterns experimentation. This introduces a feature gate under the lang-team [experimental feature](https://github.com/rust-lang/lang-team/blob/master/src/how_to/experiment.md) process, with [````@cramertj```` as lang-team liaison](https://github.com/rust-lang/lang-team/issues/88) (it's been a while though, you still ok with this ````@cramertj?).```` Tracking issue: https://github.com/rust-lang/rust/issues/87121.

This is the barest-bones implementation I could think of:
- explicit syntax, reusing `box <pat>` because that saves me a ton of work;
- use `Deref` as a marker trait (instead of a yet-to-design `DerefPure`);
- no support for mutable patterns with `DerefMut` for now;
- MIR lowering will come in the next PR. It's the trickiest part.

My goal is to let us figure out the MIR lowering part, which might take some work. And hopefully get something working for std types soon.

This is in large part salvaged from ````@fee1-dead's```` https://github.com/rust-lang/rust/pull/119467.

r? ````@compiler-errors````
2024-03-21 12:05:05 +01:00
bors
df8ac8f1d7 Auto merge of #122568 - RalfJung:mentioned-items, r=oli-obk
recursively evaluate the constants in everything that is 'mentioned'

This is another attempt at fixing https://github.com/rust-lang/rust/issues/107503. The previous attempt at https://github.com/rust-lang/rust/pull/112879 seems stuck in figuring out where the [perf regression](https://perf.rust-lang.org/compare.html?start=c55d1ee8d4e3162187214692229a63c2cc5e0f31&end=ec8de1ebe0d698b109beeaaac83e60f4ef8bb7d1&stat=instructions:u) comes from. In  https://github.com/rust-lang/rust/pull/122258 I learned some things, which informed the approach this PR is taking.

Quoting from the new collector docs, which explain the high-level idea:
```rust
//! One important role of collection is to evaluate all constants that are used by all the items
//! which are being collected. Codegen can then rely on only encountering constants that evaluate
//! successfully, and if a constant fails to evaluate, the collector has much better context to be
//! able to show where this constant comes up.
//!
//! However, the exact set of "used" items (collected as described above), and therefore the exact
//! set of used constants, can depend on optimizations. Optimizing away dead code may optimize away
//! a function call that uses a failing constant, so an unoptimized build may fail where an
//! optimized build succeeds. This is undesirable.
//!
//! To fix this, the collector has the concept of "mentioned" items. Some time during the MIR
//! pipeline, before any optimization-level-dependent optimizations, we compute a list of all items
//! that syntactically appear in the code. These are considered "mentioned", and even if they are in
//! dead code and get optimized away (which makes them no longer "used"), they are still
//! "mentioned". For every used item, the collector ensures that all mentioned items, recursively,
//! do not use a failing constant. This is reflected via the [`CollectionMode`], which determines
//! whether we are visiting a used item or merely a mentioned item.
//!
//! The collector and "mentioned items" gathering (which lives in `rustc_mir_transform::mentioned_items`)
//! need to stay in sync in the following sense:
//!
//! - For every item that the collector gather that could eventually lead to build failure (most
//!   likely due to containing a constant that fails to evaluate), a corresponding mentioned item
//!   must be added. This should use the exact same strategy as the ecollector to make sure they are
//!   in sync. However, while the collector works on monomorphized types, mentioned items are
//!   collected on generic MIR -- so any time the collector checks for a particular type (such as
//!   `ty::FnDef`), we have to just onconditionally add this as a mentioned item.
//! - In `visit_mentioned_item`, we then do with that mentioned item exactly what the collector
//!   would have done during regular MIR visiting. Basically you can think of the collector having
//!   two stages, a pre-monomorphization stage and a post-monomorphization stage (usually quite
//!   literally separated by a call to `self.monomorphize`); the pre-monomorphizationn stage is
//!   duplicated in mentioned items gathering and the post-monomorphization stage is duplicated in
//!   `visit_mentioned_item`.
//! - Finally, as a performance optimization, the collector should fill `used_mentioned_item` during
//!   its MIR traversal with exactly what mentioned item gathering would have added in the same
//!   situation. This detects mentioned items that have *not* been optimized away and hence don't
//!   need a dedicated traversal.

enum CollectionMode {
    /// Collect items that are used, i.e., actually needed for codegen.
    ///
    /// Which items are used can depend on optimization levels, as MIR optimizations can remove
    /// uses.
    UsedItems,
    /// Collect items that are mentioned. The goal of this mode is that it is independent of
    /// optimizations: the set of "mentioned" items is computed before optimizations are run.
    ///
    /// The exact contents of this set are *not* a stable guarantee. (For instance, it is currently
    /// computed after drop-elaboration. If we ever do some optimizations even in debug builds, we
    /// might decide to run them before computing mentioned items.) The key property of this set is
    /// that it is optimization-independent.
    MentionedItems,
}
```
And the `mentioned_items` MIR body field docs:
```rust
    /// Further items that were mentioned in this function and hence *may* become monomorphized,
    /// depending on optimizations. We use this to avoid optimization-dependent compile errors: the
    /// collector recursively traverses all "mentioned" items and evaluates all their
    /// `required_consts`.
    ///
    /// This is *not* soundness-critical and the contents of this list are *not* a stable guarantee.
    /// All that's relevant is that this set is optimization-level-independent, and that it includes
    /// everything that the collector would consider "used". (For example, we currently compute this
    /// set after drop elaboration, so some drop calls that can never be reached are not considered
    /// "mentioned".) See the documentation of `CollectionMode` in
    /// `compiler/rustc_monomorphize/src/collector.rs` for more context.
    pub mentioned_items: Vec<Spanned<MentionedItem<'tcx>>>,
```

Fixes #107503
2024-03-21 09:01:18 +00:00
Nadrieril
120d3570aa Add barest-bones deref patterns
Co-authored-by: Deadbeef <ent3rm4n@gmail.com>
2024-03-20 22:30:27 +01:00
bors
a128516cf9 Auto merge of #122754 - Mark-Simulacrum:bootstrap-bump, r=albertlarsan68
Bump to 1.78 bootstrap compiler

https://forge.rust-lang.org/release/process.html#master-bootstrap-update-t-2-day-tuesday
2024-03-20 13:43:41 +00:00
Mark Rousskov
02f1930595 step cfgs 2024-03-20 08:49:13 -04:00
Ralf Jung
712fe36611 collector: recursively traverse 'mentioned' items to evaluate their constants 2024-03-20 11:07:12 +01:00
Oli Scherer
afdcae2860 Rename mir_const query to mir_built 2024-03-20 09:05:22 +00:00
Oli Scherer
36728f1cdd Replace mir_built query with a hook and use mir_const everywhere instead 2024-03-20 09:05:09 +00:00
Matthias Krüger
4f3050b85a
Rollup merge of #121543 - onur-ozkan:clippy-args, r=oli-obk
various clippy fixes

We need to keep the order of the given clippy lint rules before passing them.
Since clap doesn't offer any useful interface for this purpose out of the box,
we have to handle it manually.

Additionally, this PR makes `-D` rules work as expected. Previously, lint rules were limited to `-W`. By enabling `-D`, clippy began to complain numerous lines in the tree, all of which have been resolved in this PR as well.

Fixes #121481
cc `@matthiaskrgr`
2024-03-20 05:51:22 +01:00
onur-ozkan
81d7d7aabd resolve clippy errors
Signed-off-by: onur-ozkan <work@onurozkan.dev>
2024-03-20 00:12:00 +03:00
Oli Scherer
a8f71cf289 Remove all checks of IntrinsicDef::must_be_overridden except for the actual overrides in codegen 2024-03-19 09:19:58 +00:00
bors
21d94a3d2c Auto merge of #122055 - compiler-errors:stabilize-atb, r=oli-obk
Stabilize associated type bounds (RFC 2289)

This PR stabilizes associated type bounds, which were laid out in [RFC 2289]. This gives us a shorthand to express nested type bounds that would otherwise need to be expressed with nested `impl Trait` or broken into several `where` clauses.

### What are we stabilizing?

We're stabilizing the associated item bounds syntax, which allows us to put bounds in associated type position within other bounds, i.e. `T: Trait<Assoc: Bounds...>`. See [RFC 2289] for motivation.

In all position, the associated type bound syntax expands into a set of two (or more) bounds, and never anything else (see "How does this differ[...]" section for more info).

Associated type bounds are stabilized in four positions:
* **`where` clauses (and APIT)** - This is equivalent to breaking up the bound into two (or more) `where` clauses. For example, `where T: Trait<Assoc: Bound>` is equivalent to `where T: Trait, <T as Trait>::Assoc: Bound`.
* **Supertraits** - Similar to above, `trait CopyIterator: Iterator<Item: Copy> {}`. This is almost equivalent to breaking up the bound into two (or more) `where` clauses; however, the bound on the associated item is implied whenever the trait is used. See #112573/#112629.
* **Associated type item bounds** - This allows constraining the *nested* rigid projections that are associated with a trait's associated types. e.g. `trait Trait { type Assoc: Trait2<Assoc2: Copy>; }`.
* **opaque item bounds (RPIT, TAIT)** - This allows constraining associated types that are associated with the opaque without having to *name* the opaque. For example, `impl Iterator<Item: Copy>` defines an iterator whose item is `Copy` without having to actually name that item bound.

The latter three are not expressible in surface Rust (though for associated type item bounds, this will change in #120752, which I don't believe should block this PR), so this does represent a slight expansion of what can be expressed in trait bounds.

### How does this differ from the RFC?

Compared to the RFC, the current implementation *always* desugars associated type bounds to sets of `ty::Clause`s internally. Specifically, it does *not* introduce a position-dependent desugaring as laid out in [RFC 2289], and in particular:
* It does *not* desugar to anonymous associated items in associated type item bounds.
* It does *not* desugar to nested RPITs in RPIT bounds, nor nested TAITs in TAIT bounds.

This position-dependent desugaring laid out in the RFC existed simply to side-step limitations of the trait solver, which have mostly been fixed in #120584. The desugaring laid out in the RFC also added unnecessary complication to the design of the feature, and introduces its own limitations to, for example:
* Conditionally lowering to nested `impl Trait` in certain positions such as RPIT and TAIT means that we inherit the limitations of RPIT/TAIT, namely lack of support for higher-ranked opaque inference. See this code example: https://github.com/rust-lang/rust/pull/120752#issuecomment-1979412531.
* Introducing anonymous associated types makes traits no longer object safe, since anonymous associated types are not nameable, and all associated types must be named in `dyn` types.

This last point motivates why this PR is *not* stabilizing support for associated type bounds in `dyn` types, e.g, `dyn Assoc<Item: Bound>`. Why? Because `dyn` types need to have *concrete* types for all associated items, this would necessitate a distinct lowering for associated type bounds, which seems both complicated and unnecessary compared to just requiring the user to write `impl Trait` themselves. See #120719.

### Implementation history:

Limited to the significant behavioral changes and fixes and relevant PRs, ping me if I left something out--
* #57428
* #108063
* #110512
* #112629
* #120719
* #120584

Closes #52662

[RFC 2289]: https://rust-lang.github.io/rfcs/2289-associated-type-bounds.html
2024-03-19 00:04:09 +00:00
Matthias Krüger
2d3dcfaade
Rollup merge of #121823 - Nadrieril:never-witnesses, r=compiler-errors
never patterns: suggest `!` patterns on non-exhaustive matches

When a match is non-exhaustive we now suggest never patterns whenever it makes sense.

r? ``@compiler-errors``
2024-03-18 22:24:36 +01:00
Oli Scherer
adda9da604 Avoid various uses of Option<Span> in favor of using DUMMY_SP in the few cases that used None 2024-03-18 09:34:08 +00:00
omahs
758f642c29
fix typo 2024-03-17 14:25:24 +01:00
bors
c03ea3dfd9 Auto merge of #121926 - tgross35:f16-f128-step3-feature-gate, r=compiler-errors,petrochenkov
`f16` and `f128` step 3: compiler support & feature gate

Continuation of https://github.com/rust-lang/rust/pull/121841, another portion of https://github.com/rust-lang/rust/pull/114607

This PR exposes the new types to the world and adds a feature gate. Marking this as a draft because I need some feedback on where I did the feature gate check. It also does not yet catch type via suffixed literals (so the feature gate test will fail, probably some others too because I haven't belssed).

If there is a better place to check all types after resolution, I can do that. If not, I figure maybe I can add a second gate location in AST when it checks numeric suffixes.

Unfortunately I still don't think there is much testing to be done for correctness (codegen tests or parsed value checks) until we have basic library support. I think that will be the next step.

Tracking issue: https://github.com/rust-lang/rust/issues/116909

r? `@compiler-errors`
cc `@Nilstrieb`
`@rustbot` label +F-f16_and_f128
2024-03-16 02:02:00 +00:00
Matthias Krüger
9e153ccd45
Rollup merge of #122254 - estebank:issue-48677, r=oli-obk
Detect calls to .clone() on T: !Clone types on borrowck errors

When encountering a lifetime error on a type that *holds* a type that doesn't implement `Clone`, explore the item's body for potential calls to `.clone()` that are only cloning the reference `&T` instead of `T` because `T: !Clone`. If we find this, suggest `T: Clone`.

```
error[E0502]: cannot borrow `*list` as mutable because it is also borrowed as immutable
  --> $DIR/clone-on-ref.rs:7:5
   |
LL |     for v in list.iter() {
   |              ---- immutable borrow occurs here
LL |         cloned_items.push(v.clone())
   |                             ------- this call doesn't do anything, the result is still `&T` because `T` doesn't implement `Clone`
LL |     }
LL |     list.push(T::default());
   |     ^^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here
LL |
LL |     drop(cloned_items);
   |          ------------ immutable borrow later used here
   |
help: consider further restricting this bound
   |
LL | fn foo<T: Default + Clone>(list: &mut Vec<T>) {
   |                   +++++++
```
```
error[E0505]: cannot move out of `x` because it is borrowed
  --> $DIR/clone-on-ref.rs:23:10
   |
LL | fn qux(x: A) {
   |        - binding `x` declared here
LL |     let a = &x;
   |             -- borrow of `x` occurs here
LL |     let b = a.clone();
   |               ------- this call doesn't do anything, the result is still `&A` because `A` doesn't implement `Clone`
LL |     drop(x);
   |          ^ move out of `x` occurs here
LL |
LL |     println!("{b:?}");
   |               ----- borrow later used here
   |
help: consider annotating `A` with `#[derive(Clone)]`
   |
LL + #[derive(Clone)]
LL | struct A;
   |
```

Fix #48677.
2024-03-15 21:51:56 +01:00
Matthias Krüger
1f4aff7d2b
Rollup merge of #122487 - GuillaumeGomez:rename-stmtkind-local, r=oli-obk
Rename `StmtKind::Local` variant into `StmtKind::Let`

It comes from this [discussion](https://rust-lang.zulipchat.com/#narrow/stream/131828-t-compiler/topic/Improve.20naming.20of.20.60ExprKind.3A.3ALet.60.3F).

Starting point was:

> I often end up looking at [ExprKind::Let](https://doc.rust-lang.org/nightly/nightly-rustc/rustc_hir/enum.ExprKind.html#variant.Let) instead of Local because of the name. I think renaming it (both the `ExprKind` variant and the Let struct) to `LetPattern` or LetPat could improve the situation as I'm not sure I'm not the only one encountering this issue.

And then it evolved into:

> It's already `Expr::Let` instead of `StmtKind::Local`. Counterproposal: rename `StmtKind::Local` to `StmtKind::Let`.

The goal here is to clear this confusion.

r? `@oli-obk`
2024-03-14 20:00:21 +01:00
Matthias Krüger
54a5a49af0
Rollup merge of #122322 - Zalathar:branch, r=oli-obk
coverage: Initial support for branch coverage instrumentation

(This is a review-ready version of the changes that were drafted in #118305.)

This PR adds support for branch coverage instrumentation, gated behind the unstable flag value `-Zcoverage-options=branch`. (Coverage instrumentation must also be enabled with `-Cinstrument-coverage`.)

During THIR-to-MIR lowering (MIR building), if branch coverage is enabled, we collect additional information about branch conditions and their corresponding then/else blocks. We inject special marker statements into those blocks, so that the `InstrumentCoverage` MIR pass can reliably identify them even after the initially-built MIR has been simplified and renumbered.

The rest of the changes are mostly just plumbing needed to gather up the information that was collected during MIR building, and include it in the coverage metadata that we embed in the final binary.

Note that `llvm-cov show` doesn't print branch coverage information in its source views by default; that needs to be explicitly enabled with `--show-branches=count` or similar.

---

The current implementation doesn't have any support for instrumenting `if let` or let-chains. I think it's still useful without that, and adding it would be non-trivial, so I'm happy to leave that for future work.
2024-03-14 20:00:19 +01:00
Guillaume Gomez
a4e0e50a3f Rename hir::StmtKind::Local into hir::StmtKind::Let 2024-03-14 12:42:04 +01:00
Trevor Gross
80bb15ed91 Add compiler support for parsing f16 and f128 2024-03-14 00:40:22 -05:00
Zalathar
c1bec0ce6b coverage: Record branch information during MIR building 2024-03-14 16:31:44 +11:00
Zalathar
f9cdaeb6fd coverage: Data structures for recording branch info during MIR building 2024-03-14 16:27:42 +11:00
Esteban Küber
b367c25367 Tweak wording 2024-03-13 23:05:17 +00:00
Nadrieril
f27540697e Rename RustcMatchCheckCtxt -> RustcPatCtxt 2024-03-13 14:07:44 +01:00
Matthias Krüger
e6ba504029
Rollup merge of #121908 - Nadrieril:dynamic-variant-collection, r=matthewjasper
match lowering: don't collect test alternatives ahead of time

I'm very happy with this one. Before this, when sorting candidates into the possible test branches, we manually computed `usize` indices to determine in which branch each candidate goes. To make this work we had a first pass that collected the possible alternatives we'd have to deal with, and a second pass that actually sorts the candidates.

In this PR, I replace `usize` indices with a dedicated enum. This makes `sort_candidates` easier to follow, and we don't need the first pass anymore.

r? ``@matthewjasper``
2024-03-13 06:41:21 +01:00
Matthias Krüger
1b198ba9fe
Rollup merge of #121820 - Nadrieril:idxpat2, r=compiler-errors
pattern analysis: Store field indices in `DeconstructedPat` to avoid virtual wildcards

For a pattern like `Struct { field3: true, .. }`, in pattern analysis we represent it as `Struct { field1: _, field2: _, field3: true, field4: _ }`. This PR makes it so we store `Struct { field3: true, .. }` instead. This means we never have to create fake `_` patterns during lowering.

r? ``@compiler-errors``
2024-03-13 06:41:20 +01:00
Nadrieril
1b31e14a31 Centralize the decision to suggest patterns vs _ 2024-03-12 21:49:43 +01:00
Nadrieril
b878ab6a27 Don't suggest an arm when suggesting a never pattern 2024-03-12 21:38:31 +01:00
Oli Scherer
9816915954 Change DefKind::Static to a struct variant 2024-03-12 05:53:46 +00:00
Jubilee
e3f9b2f27c
Rollup merge of #122080 - Zalathar:drop-tree, r=oli-obk
Clarity improvements to `DropTree`

These changes are based on some points of confusion I had when initially trying to understand this code.

The only “functional” change is an additional assertion in `<ExitScopes as DropTreeBuilder>::link_entry_point`, checking that the dummy terminator is `TerminatorKind::UnwindResume` as expected.
2024-03-11 09:29:35 -07:00
Nadrieril
d339bdaa07 DeconstructedPat.data is always present now 2024-03-11 04:38:57 +01:00
Nadrieril
6ae9fa31f0 Store field indices in DeconstructedPat to avoid virtual wildcards 2024-03-11 04:37:21 +01:00
Nicholas Nethercote
541d7cc65c Rename AddToDiagnostic as Subdiagnostic.
To match `derive(Subdiagnostic)`.

Also rename `add_to_diagnostic{,_with}` as `add_to_diag{,_with}`.
2024-03-11 10:04:49 +11:00
Nicholas Nethercote
7a294e998b Rename IntoDiagnostic as Diagnostic.
To match `derive(Diagnostic)`.

Also rename `into_diagnostic` as `into_diag`.
2024-03-11 09:15:09 +11:00
Matthias Krüger
163573a368
Rollup merge of #122221 - Nadrieril:patextradata, r=oli-obk
match lowering: define a convenient struct

Small refactor PR: `bindings` and `ascriptions` always come together so I made a struct for them. I'll have one or two fields to add to it in a later PR as well.
2024-03-10 10:58:18 +01:00
Guillaume Boisseau
bc3bc2ba6b
Rollup merge of #121584 - klensy:itertools-up, r=Mark-Simulacrum
bump itertools to 0.12

still depend on 0.11 (temporary dupes version):
* <del>clippy</del>, https://github.com/rust-lang/rust-clippy/pull/12346
* rustfmt, sigh, https://github.com/rust-lang/rustfmt/pull/6093

https://github.com/rust-itertools/itertools/blob/v0.12.1/CHANGELOG.md

removed unused `derive_more` dep from `rustc_middle`
2024-03-09 21:40:08 +01:00
Nadrieril
594cf1de61 review 2024-03-09 15:28:26 +01:00
Nadrieril
7843e46f17 Factor out non-branch-related pattern data 2024-03-09 03:51:30 +01:00
Michael Goulet
c63f3feb0f Stabilize associated type bounds 2024-03-08 20:56:25 +00:00
klensy
52501c2a75 bump itertools to 0.12
still depend on 0.11:
* clippy
* rustfmt, sigh
2024-03-08 12:34:05 +03:00
Matthias Krüger
d774fbea7c
Rollup merge of #119365 - nbdd0121:asm-goto, r=Amanieu
Add asm goto support to `asm!`

Tracking issue: #119364

This PR implements asm-goto support, using the syntax described in "future possibilities" section of [RFC2873](https://rust-lang.github.io/rfcs/2873-inline-asm.html#asm-goto).

Currently I have only implemented the `label` part, not the `fallthrough` part (i.e. fallthrough is implicit). This doesn't reduce the expressive though, since you can use label-break to get arbitrary control flow or simply set a value and rely on jump threading optimisation to get the desired control flow. I can add that later if deemed necessary.

r? ``@Amanieu``
cc ``@ojeda``
2024-03-08 08:19:17 +01:00
Zalathar
570376c496 Don't pass a break scope to Builder::break_for_else
This method would previously take a target scope, and then verify that it
was equal to the scope on top of the if-then scope stack.

In practice, this means that callers have to go out of their way to pass around
redundant scope information that's already on the if-then stack.

So it's easier to just retrieve the correct scope directly from the if-then
stack, and simplify the other code that was passing it around.
2024-03-07 23:11:18 +11:00
Zalathar
5ba70bd3ec Replace tuples in DropTree with named structs
This allows us to use real field names instead of tuple element numbers.

Renaming `previous_drops` to `existing_drops_map` clarifies that "previous" was
unrelated to drop order.
2024-03-06 23:09:04 +11:00
Zalathar
fbdac30427 Rename DropTree::add_entry to add_entry_point
This clarifies that we're adding an "entry point", not just adding an "entry"
of some kind.
2024-03-06 23:02:38 +11:00
Zalathar
3bd8df96e1 Assert that link_entry_point sees the expected dummy terminator 2024-03-06 22:32:01 +11:00
Zalathar
30fa6a8b50 Rename DropTreeBuilder::add_entry to link_entry_point 2024-03-06 22:32:01 +11:00
Zalathar
250e697834 Additional comments for lowering if 2024-03-06 17:08:28 +11:00
Zalathar
3402f39bcb Clarify lowering the else arm into the else block 2024-03-06 17:08:28 +11:00
Ross Smyth
567c98b30f Add postfix match MatchSource to HIR 2024-03-06 00:51:48 -05:00
Zalathar
7396fd1fa0 Clarify how lowering if produces then/else blocks
This makes it easier to see that the call to `in_scope` returns both the then
block and the else block. The rather confusing `unpack!` step is confined to
its own separate line.

(This patch reindents several lines, so using "ignore whitespace" is
recommended in order to focus on the actual changes.)
2024-03-06 14:57:00 +11:00
Nicholas Nethercote
573267cf3c Rename SubdiagnosticMessageOp as SubdiagMessageOp. 2024-03-05 12:14:49 +11:00
Matthias Krüger
58a0f64c8b
Rollup merge of #121928 - Zalathar:then-else-args, r=Nadrieril
Extract an arguments struct for `Builder::then_else_break`

Most of this method's arguments are usually or always forwarded as-is to recursive invocations.

Wrapping them in a dedicated struct allows us to document each struct field, and lets us use struct-update syntax to indicate which arguments are being modified when making a recursive call.

---

While trying to understand the lowering of `if` expressions, I found it difficult to keep track of the half-dozen arguments passed through to every call to `then_else_break`. I tried switching over to an arguments struct, and I found that it really helps to make sense of what each argument does, and how each call is modifying the arguments.

I have some further ideas for how to streamline these recursive calls, but I've kept those out of this PR so that it's a pure refactoring with no behavioural changes.
2024-03-04 22:16:32 +01:00
Zalathar
4146136d6d Extract an arguments struct for Builder::then_else_break
Most of this method's arguments are usually or always forwarded as-is to
recursive invocations.

Wrapping them in a dedicated struct allows us to document each struct field,
and lets us use struct-update syntax to indicate which arguments are being
modified when making a recursive call.
2024-03-04 18:42:12 +11:00
Guillaume Gomez
7d8f74f8b2
Rollup merge of #121917 - GuillaumeGomez:pattern-complexity_limit.rs, r=Nadrieril
Add new `pattern_complexity` attribute to add possibility to limit and check recursion in pattern matching

Needed for https://github.com/rust-lang/rust-analyzer/issues/9528.

This PR adds a new attribute only available when running rust testsuite called `pattern_complexity` which allows to set the maximum recursion for the pattern matching. It is quite useful to ensure the complexity doesn't grow, like in `tests/ui/pattern/usefulness/issue-118437-exponential-time-on-diagonal-match.rs`.

r? `@Nadrieril`
2024-03-03 14:07:43 +01:00
Guillaume Gomez
be31b6b6cd Add new pattern_complexity attribute to add possibility to limit and check recursion in pattern matching 2024-03-03 13:10:15 +01:00
bors
0decdac390 Auto merge of #121914 - Nadrieril:rollup-ol98ncg, r=Nadrieril
Rollup of 5 pull requests

Successful merges:

 - #120761 (Add initial support for DataFlowSanitizer)
 - #121622 (Preserve same vtable pointer when cloning raw waker, to fix Waker::will_wake)
 - #121716 (match lowering: Lower bindings in a predictable order)
 - #121731 (Now that inlining, mir validation and const eval all use reveal-all, we won't be constraining hidden types here anymore)
 - #121841 (`f16` and `f128` step 2: intrinsics)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-03-02 22:59:19 +00:00
Guillaume Boisseau
30976fbe2b
Rollup merge of #121716 - Nadrieril:simple-binding-order, r=matthewjasper
match lowering: Lower bindings in a predictable order

After the recent refactorings, we can now lower bindings in a truly predictable order. The order in https://github.com/rust-lang/rust/pull/120214 was an improvement but not very clear. With this PR, we lower bindings from left to right, with the special case that `x @ pat` is traversed as `pat @ x` (i.e. `x` is lowered after any bindings in `pat`).

This description only applies in the absence of or-patterns. Or-patterns make everything complicated, because the binding place depends on the subpattern. Until I have a better idea I leave them to be handled in whatever weird order arises from today's code.

r? `@matthewjasper`
2024-03-02 20:13:23 +01:00
Nadrieril
d46ff6415c Fix a subtle regression
Before, the SwitchInt cases were computed in two passes: if the first
pass accepted e.g. 0..=5 and then 1, the second pass would not accept
0..=5 anymore because 1 would be listed in the SwitchInt options.

Now there's a single pass, so if we sort 0..=5 we must take care to not
sort a subsequent 1.
2024-03-02 18:38:37 +01:00
Nadrieril
edea739292 No need to collect test variants ahead of time 2024-03-02 18:35:53 +01:00
Nadrieril
8c3688cbb5 Allocate candidate vectors as we sort them 2024-03-02 18:33:19 +01:00
Nadrieril
3d3b321c60 Use an enum instead of manually tracking indices for target_blocks 2024-03-02 18:33:17 +01:00
Nadrieril
832b23ffcf Tiny missed simplification 2024-03-02 18:06:12 +01:00
Matthias Krüger
7bacfced95
Rollup merge of #121892 - Zalathar:expr-kind-let, r=Nadrieril
The ordinary lowering of `thir::ExprKind::Let` is unreachable

After desugaring, `let` expressions should only appear inside `if` expressions or `match` guards, possibly nested within a let-chain. In both cases they are specifically handled by the lowerings of those expressions, so this case is currently unreachable.

---

Context: https://rust-lang.zulipchat.com/#narrow/stream/182449-t-compiler.2Fhelp/topic/Lowering.20of.20.60thir.3A.3AExprKind.3A.3ALet.60.20is.20unreachable

My conclusions are partly based on the observation that stubbing out this match arm doesn't cause any test failures. So either this really is unreachable, or it can be reached in some obscure circumstances that our test suite doesn't cover.

If we end up needing this code (or something like it) for an implementation of https://github.com/rust-lang/rfcs/pull/3573, it should be easy enough to pull it back out of version control history.

I looked into having the `if`/`match` lowerings call back into `expr_into_dest`, but from what I can tell that won't work well, because there are extra scoping considerations that require some awareness of the enclosing if/match.

r? ```@Nadrieril```
2024-03-02 16:53:16 +01:00
Zalathar
972d8daf47 The ordinary lowering of thir::ExprKind::Let is unreachable
After desugaring, `let` expressions should only appear inside `if` expressions
or `match` guards, possibly nested within a let-chain. In both cases they are
specifically handled by the lowerings of those expressions, so this case is
currently unreachable.
2024-03-02 20:49:29 +11:00
Matthias Krüger
b2c933a1b9
Rollup merge of #121715 - Nadrieril:testcase-or, r=matthewjasper
match lowering: pre-simplify or-patterns too

This is the final part of my work to simplify match pairs early: now we do it for or-patterns too. This makes it possible to collect fake borrows separately from the main match lowering algorithm. That'll enable more simplifications of or-pattern handling.

Note: I was tempted to have `Candidate` contain a `FlatPat`, but there are so many places that use `candidate.match_pairs` etc directly that I chose not to.

r? `@matthewjasper`
2024-03-02 10:09:35 +01:00
Matthias Krüger
0d2205f9a6
Rollup merge of #121750 - Nadrieril:switchkind-if, r=matthewjasper
match lowering: Separate the `bool` case from other integers in `TestKind`

`TestKind::SwitchInt` had a special case for `bool` essentially everywhere it's used, so I made `TestKind::If` to handle the bool case on its own.

r? `@matthewjasper`
2024-03-01 22:38:49 +01:00
Matthias Krüger
1fbc53af48
Rollup merge of #121706 - Nadrieril:simplify-sort-candidate, r=matthewjasper
match lowering: Remove hacky branch in sort_candidate

Reusing `self.test()` there wasn't actually pulling a lot of weight. In particular the `TestKind::Len` cases were all already correctly handled.

r? `@matthewjasper`
2024-03-01 22:38:48 +01:00
Matthias Krüger
1a4c93e3ed
Rollup merge of #121784 - Zalathar:if-or-converge, r=Nadrieril
Make the success arms of `if lhs || rhs` meet up in a separate block

Extracted from #118305, where this is necessary to avoid introducing a bug when injecting marker statements into the then/else arms.

---

In the previous code (#111752), the success block of `lhs` would jump directly to the success block of `rhs`. However, `rhs_success_block` could already contain statements that are specific to the RHS, and the direct goto causes them to be executed in the LHS success path as well.

This patch therefore creates a fresh block that the LHS and RHS success blocks can both jump to.

---

I think the reason we currently get away with this is that `rhs_success_block` usually doesn't contain anything other than StorageDead statements for locals used by the RHS, and those statements don't seem to cause problems in the LHS success path (which never makes those locals live).

But if we start adding meaningful statements for branch coverage (or MC/DC coverage), it's important to keep the LHS and RHS blocks separate.
2024-03-01 17:51:30 +01:00
bors
6cbf0926d5 Auto merge of #121728 - tgross35:f16-f128-step1-ty-updates, r=compiler-errors
Add stubs in IR and ABI for `f16` and `f128`

This is the very first step toward the changes in https://github.com/rust-lang/rust/pull/114607 and the [`f16` and `f128` RFC](https://rust-lang.github.io/rfcs/3453-f16-and-f128.html). It adds the types to `rustc_type_ir::FloatTy` and `rustc_abi::Primitive`, and just propagates those out as `unimplemented!` stubs where necessary.

These types do not parse yet so there is no feature gate, and it should be okay to use `unimplemented!`.

The next steps will probably be AST support with parsing and the feature gate.

r? `@compiler-errors`
cc `@Nilstrieb` suggested breaking the PR up in https://github.com/rust-lang/rust/pull/120645#issuecomment-1925900572
2024-03-01 03:36:11 +00:00
Guillaume Gomez
2e0a26a32a
Rollup merge of #121376 - Nadrieril:mir-half-ranges, r=pnkfelix
Skip unnecessary comparison with half-open range patterns

This is the last remaining detail in the implementation of half-open range patterns. Until now, a half-open range pattern like `10..` was converted to `10..T::MAX` before lowering to MIR, which generated an extra pointless comparison. With this PR we don't generate it.
2024-02-29 17:08:37 +01:00
Zalathar
a7832b14b1 Make the success arms of if lhs || rhs meet up in a separate block
In the previous code, the success block of `lhs` would jump directly to the
success block of `rhs`. However, `rhs_success_block` could already contain
statements that are specific to the RHS, and the direct goto causes them to be
executed in the LHS success path as well.

This patch therefore creates a fresh block that the LHS and RHS success blocks
can both jump to.
2024-02-29 20:24:43 +11:00
Trevor Gross
e3f63d9375 Add f16 and f128 to rustc_type_ir::FloatTy and rustc_abi::Primitive
Make changes necessary to support these types in the compiler.
2024-02-28 12:58:32 -05:00
Nadrieril
d6332ae79c Separate the bool case from other integers in TestKind 2024-02-28 18:23:26 +01:00
Nadrieril
ae1e1bd216 No need to pass fake_borrows everywhere now 2024-02-28 01:48:00 +01:00
Nadrieril
ca5edfa724 Collect fake borrows ahead of time 2024-02-28 01:47:31 +01:00
Nadrieril
29666118b6 Pre-simplify or-patterns too 2024-02-28 01:44:44 +01:00
Nadrieril
00497ad24b Lower bindings in a predictable order 2024-02-28 01:41:25 +01:00
Nadrieril
5d31e29b56 Appease rust-analyzer
For some reason it doesn't figure out the slice coercion.
2024-02-28 00:30:22 +01:00
Nicholas Nethercote
8199632aa8 Rename DiagnosticArg{,Map,Name,Value} as DiagArg{,Map,Name,Value}. 2024-02-28 08:55:37 +11:00
Nicholas Nethercote
899cb40809 Rename DiagnosticBuilder as Diag.
Much better!

Note that this involves renaming (and updating the value of)
`DIAGNOSTIC_BUILDER` in clippy.
2024-02-28 08:55:35 +11:00
Nadrieril
f363c1a3fe Group default cases in sort_candidate 2024-02-27 22:37:44 +01:00
Nadrieril
5e11a99bb6 Remove hacky branch in sort_candidate
Reusing `self.test` wasn't actually pulling a lot of weight.
2024-02-27 22:37:44 +01:00
Nadrieril
205319d962 Skip unnecessary comparison with half-open ranges 2024-02-27 17:22:21 +01:00
Ralf Jung
5b7786cd1d make non-PartialEq-typed consts as patterns a hard error 2024-02-25 11:30:10 +01:00
Matthias Krüger
f4ba47f1ed
Rollup merge of #121374 - Nadrieril:factor-explain, r=matthewjasper
match lowering: Split off `test_candidates` into several functions and improve comments

The logic of `test_candidates` has three steps: pick a test, sort the candidates, and generate code for everything. So I split it off into three methods.

I also ended up reworking the comments that explain the algorithm. In particular I added detailed examples. I removed the digression about https://github.com/rust-lang/rust/issues/29740 because it's no longer relevant to how the code is structured today.

r? ``@matthewjasper``
2024-02-24 22:38:58 +01:00
Gary Guo
3b1dd1bfa9 Implement asm goto in MIR and MIR lowering 2024-02-24 18:50:09 +00:00
Gary Guo
b044aaa905 Change InlineAsm to allow multiple targets instead 2024-02-24 18:50:09 +00:00
Gary Guo
040ab7d4b6 Add asm label support to THIR 2024-02-24 18:49:39 +00:00
Gary Guo
93fa8579c6 Add asm label support to AST and HIR 2024-02-24 18:49:39 +00:00
Guillaume Boisseau
de4efa5e46
Tweak debug!() call
Co-authored-by: matthewjasper <20113453+matthewjasper@users.noreply.github.com>
2024-02-24 09:17:26 +01:00
Matthias Krüger
86a7fc840f compiler: clippy::complexity fixes 2024-02-23 19:56:35 +01:00
Matthias Krüger
01ec4eb319
Rollup merge of #121427 - nnethercote:fix-Rocket, r=oli-obk
Fix panic when compiling `Rocket`.

This panic was reported [here](https://github.com/rust-lang/rust/pull/120576#issuecomment-1957515484).

r? ``@oli-obk``
2024-02-22 18:09:54 +01:00
Nicholas Nethercote
02423a5747 Make some IntoDiagnostic impls generic.
PR #119097 made the decision to make all `IntoDiagnostic` impls generic,
because this allowed a bunch of nice cleanups. But four hand-written
impls were unintentionally overlooked. This commit makes them generic.
2024-02-22 13:47:30 +11:00
Nadrieril
0610f59194 Inline simplify_match_pair 2024-02-21 21:19:00 +01:00
Nadrieril
b1a0607e10 Process bindings and ascriptions in MatchPair::new() 2024-02-21 21:19:00 +01:00
Nadrieril
a181bdc065 Introduce TestCase enum to replace most matching on PatKind 2024-02-21 21:18:59 +01:00
Nadrieril
5c9d580fea Tiny simplification 2024-02-21 21:17:43 +01:00
León Orell Valerian Liehr
4daa43aaff
Rollup merge of #121175 - Nadrieril:simplify-or-selection, r=matthewjasper
match lowering: test one or pattern at a time

This is a bit more opinionated than the previous PRs. On the face of it this is less efficient and more complex than before, but I personally found the loop that digs into `leaf_candidates` on each iteration very confusing. Instead this does "generate code for this or-pattern" then "generate further code for each branch if needed" in two steps.

Incidentally this way we don't _require_ or patterns to be sorted at the end. It's still an important optimization but I find it clearer to not rely on it for correctness.

r? `@matthewjasper`
2024-02-21 16:32:57 +01:00
Nadrieril
893cb760e0 Split off test_candidates into several functions and improve comments 2024-02-21 11:45:04 +01:00
Nadrieril
c1514a6324 Test one or pattern at a time 2024-02-21 11:35:44 +01:00
Nadrieril
780beda83c Tweak block management 2024-02-21 11:25:11 +01:00
Dylan DPC
d5206c6ecd
Rollup merge of #121208 - nnethercote:delayed_bug-to-bug, r=lcnr
Convert `delayed_bug`s to `bug`s.

I have a suspicion that quite a few delayed bug paths are impossible to reach, so I did an experiment.

I converted every `delayed_bug` to a `bug`, ran the full test suite, then converted back every `bug` that was hit. A surprising number were never hit.

This is too dangerous to merge. Increased coverage (fuzzing or a crater run) would likely hit more cases. But it might be useful for people to look at and think about which paths are genuinely unreachable.

r? `@ghost`
2024-02-21 08:55:56 +00:00
bors
096598dc79 Auto merge of #121172 - Nadrieril:simplify-empty-selection, r=matthewjasper
match lowering: simplify empty candidate selection

In match lowering, `match_simplified_candidates` is tasked with removing candidates that are fully matched and linking them up properly. The code that does that was needlessly complicated; this PR simplifies it.

The overall change isn't big but I split it up into tiny commits to convince myself that I was correctly preserving behavior. The test changes are all due to the first commit. Let me know if you'd prefer me to split up the PR to make reviewing easier.

r? `@matthewjasper`
2024-02-21 03:11:24 +00:00
bors
4e65074933 Auto merge of #120904 - Nadrieril:match-lowering-intermediate-repr, r=matthewjasper
match lowering: eagerly simplify match pairs

This removes one important complication from match lowering. Before this, match pair simplification (which includes collecting bindings and type ascriptions) was intertwined with the whole match lowering algorithm.

I'm avoiding this by storing in each `MatchPair` the sub-`MatchPair`s that correspond to its subfields. This makes it possible to simplify everything (except or-patterns) in `Candidate::new()`.

This should open up further simplifications. It will also give us proper control over the order of bindings.

r? `@matthewjasper`
2024-02-21 01:11:34 +00:00
Nicholas Nethercote
2903bbbc15 Convert bugs back to delayed_bugs.
This commit undoes some of the previous commit's mechanical changes,
based on human judgment.
2024-02-21 10:35:54 +11:00
Nicholas Nethercote
010f3944e0 Convert delayed_bugs to bugs.
I have a suspicion that quite a few delayed bug paths are impossible to
reach, so I did an experiment.

I converted every `delayed_bug` to a `bug`, ran the full test suite,
then converted back every `bug` that was hit. A surprising number were
never hit.

The next commit will convert some more back, based on human judgment.
2024-02-21 10:20:05 +11:00
Nadrieril
a45d8925b8 Upgrade a debug_assert to assert 2024-02-20 16:53:16 +01:00
Nicholas Nethercote
f6f8779843 Reduce capabilities of Diagnostic.
Currently many diagnostic modifier methods are available on both
`Diagnostic` and `DiagnosticBuilder`. This commit removes most of them
from `Diagnostic`. To minimize the diff size, it keeps them within
`diagnostic.rs` but changes the surrounding `impl Diagnostic` block to
`impl DiagnosticBuilder`. (I intend to move things around later, to give
a more sensible code layout.)

`Diagnostic` keeps a few methods that it still needs, like `sub`,
`arg`, and `replace_args`.

The `forward!` macro, which defined two additional methods per call
(e.g. `note` and `with_note`), is replaced by the `with_fn!` macro,
which defines one additional method per call (e.g. `with_note`). It's
now also only used when necessary -- not all modifier methods currently
need a `with_*` form. (New ones can be easily added as necessary.)

All this also requires changing `trait AddToDiagnostic` so its methods
take `DiagnosticBuilder` instead of `Diagnostic`, which leads to many
mechanical changes. `SubdiagnosticMessageOp` gains a type parameter `G`.

There are three subdiagnostics -- `DelayedAtWithoutNewline`,
`DelayedAtWithNewline`, and `InvalidFlushedDelayedDiagnosticLevel` --
that are created within the diagnostics machinery and appended to
external diagnostics. These are handled at the `Diagnostic` level, which
means it's now hard to construct them via `derive(Diagnostic)`, so
instead we construct them by hand. This has no effect on what they look
like when printed.

There are lots of new `allow` markers for `untranslatable_diagnostics`
and `diagnostics_outside_of_impl`. This is because
`#[rustc_lint_diagnostics]` annotations were present on the `Diagnostic`
modifier methods, but missing from the `DiagnosticBuilder` modifier
methods. They're now present.
2024-02-20 13:22:17 +11:00
Nadrieril
328c77683e Update comments 2024-02-19 21:34:55 +01:00
Nadrieril
0ca1d220d2 Don't default fully_matched to false to avoid mistakes 2024-02-19 21:31:15 +01:00
Nadrieril
15072766af Compute subpairs when creating match pair 2024-02-19 21:28:26 +01:00
Nadrieril
d936ab63d4 Eagerly simplify match pairs 2024-02-19 21:28:26 +01:00
Nadrieril
308b4824aa Don't repeatedly simplify already-simplified match pairs 2024-02-19 21:28:26 +01:00
Nadrieril
e86c82296f Make simplify_candidate more general
Because we will soon need to apply it to match pairs that aren't
directly in a candidate.
2024-02-19 21:28:26 +01:00
Nadrieril
bafad5a737 Move Or test outside of simplify_candidate 2024-02-19 21:28:26 +01:00
Nadrieril
48b83e8a63 Switch to Vec of MatchPairs
Because I'm about to make MatchPair recursive, which I can't do with
SmallVec, and I need to share code between the two.
2024-02-19 21:28:26 +01:00
Nadrieril
cd0fc78c95 Replace the loop with recursive calls for clarity 2024-02-17 20:21:57 +01:00
Nadrieril
998d0e9793 Move the loop out of the function 2024-02-17 20:21:57 +01:00
Nadrieril
e561dbb0b6 Move everything into the loop 2024-02-17 20:21:57 +01:00
Nadrieril
0896a4963f No need for empty special case anymore 2024-02-17 20:21:57 +01:00
Nadrieril
b4f0e76021 It's fine to assign otherwise_blocks to unreachable candidates 2024-02-17 20:21:57 +01:00
Nadrieril
105bdf7086 Reuse next_prebinding
The moment we get a candidate without guard, the return block becomes a
fresh block linked to nothing. So we can keep assigning a fresh block
every iteration to reuse the `next_prebinding` logic.
2024-02-17 20:21:57 +01:00
Nadrieril
a11abc6343 Simplify return block computation 2024-02-17 20:21:57 +01:00
Nadrieril
a0fa2874e6 Merge the two loops 2024-02-17 20:21:57 +01:00
Nadrieril
b2edcc7130 Tweak the function boundary 2024-02-17 20:21:57 +01:00
Nadrieril
c00b38e9fb Don't bother to save a block 2024-02-17 20:21:57 +01:00
Matthias Krüger
45d5773704
Rollup merge of #121085 - davidtwco:always-eager-diagnostics, r=nnethercote
errors: only eagerly translate subdiagnostics

Subdiagnostics don't need to be lazily translated, they can always be eagerly translated. Eager translation is slightly more complex as we need to have a `DiagCtxt` available to perform the translation, which involves slightly more threading of that context.

This slight increase in complexity should enable later simplifications - like passing `DiagCtxt` into `AddToDiagnostic` and moving Fluent messages into the diagnostic structs rather than having them in separate files (working on that was what led to this change).

r? ```@nnethercote```
2024-02-17 18:47:40 +01:00
Oli Scherer
db4ba498d9 Fix an ICE in the recursion lint 2024-02-16 09:29:39 +00:00
David Wood
b80fc5d4e8
errors: only eagerly translate subdiagnostics
Subdiagnostics don't need to be lazily translated, they can always be
eagerly translated. Eager translation is slightly more complex as we need
to have a `DiagCtxt` available to perform the translation, which involves
slightly more threading of that context.

This slight increase in complexity should enable later simplifications -
like passing `DiagCtxt` into `AddToDiagnostic` and moving Fluent messages
into the diagnostic structs rather than having them in separate files
(working on that was what led to this change).

Signed-off-by: David Wood <david@davidtw.co>
2024-02-15 10:34:41 +00:00
Nicholas Nethercote
25ed6e43b0 Add ErrorGuaranteed to ast::LitKind::Err, token::LitKind::Err.
This mostly works well, and eliminates a couple of delayed bugs.

One annoying thing is that we should really also add an
`ErrorGuaranteed` to `proc_macro::bridge::LitKind::Err`. But that's
difficult because `proc_macro` doesn't have access to `ErrorGuaranteed`,
so we have to fake it.
2024-02-15 14:46:08 +11:00
bors
ee9c7c940c Auto merge of #120847 - oli-obk:track_errors9, r=compiler-errors
Continue compilation after check_mod_type_wf errors

The ICEs fixed here were probably reachable through const eval gymnastics before, but now they are easily reachable without that, too.

The new errors are often bugfixes, where useful errors were missing, because they were reported after the early abort. In other cases sometimes they are just duplication of already emitted errors, which won't be user-visible due to deduplication.

fixes https://github.com/rust-lang/rust/issues/120860
2024-02-14 18:32:19 +00:00
Oli Scherer
5f6390f947 Continue compilation after check_mod_type_wf errors 2024-02-14 11:00:30 +00:00
Nicholas Nethercote
05849e8c2f Use fewer delayed bugs.
For some cases where it's clear that an error has already occurred,
e.g.:
- there's a comment stating exactly that, or
- things like HIR lowering, where we are lowering an error kind

The commit also tweaks some comments around delayed bug sites.
2024-02-14 20:30:37 +11:00
Matthias Krüger
b785fdb80b
Rollup merge of #120978 - Nadrieril:sane-blocks, r=matthewjasper
match lowering: simplify block creation

Match lowering was doing complicated things with block creation. As far as I can tell it was trying to avoid creating unneeded blocks, but of the three places that start out with `otherwise = &mut None`, two of them called `otherwise.unwrap_or_else(|| self.cfg.start_new_block())` anyway. As far as I can tell the only place where this PR makes a difference is in `lower_match_tree`, which did indeed sometimes avoid creating the unreachable final block + FakeRead. Unless this is important I propose we do the naive thing instead.

I have not checked all the graph isomorphisms by hand, but at a glance the test diff looks sensible.

r? `@matthewjasper`
2024-02-13 17:38:11 +01:00
Matthias Krüger
cb0d74be28
Rollup merge of #120958 - ShoyuVanilla:remove-subst, r=oli-obk
Dejargonize `subst`

In favor of #110793, replace almost every occurence of `subst` and `substitution` from rustc codes, but they still remains in subtrees under `src/tools/` like clippy and test codes (I'd like to replace them after this)
2024-02-12 23:18:54 +01:00
Nadrieril
faaf81bbbc Start blocks eagerly 2024-02-12 17:37:05 +01:00
Shoyu Vanilla
3856df059e Dejargnonize subst 2024-02-12 15:46:35 +09:00
Frank King
0c0df4efe0 Lowering field access for anonymous adts 2024-02-12 12:47:30 +08:00
Matthias Krüger
4c154a1a48
Rollup merge of #120872 - petrochenkov:opthirpar, r=cjgillot
hir: Refactor getters for HIR parents

See individual commits.

I ended up removing on of the FIXMEs from https://github.com/rust-lang/rust/pull/120206 instead of addressing it.
2024-02-11 23:19:08 +01:00
Vadim Petrochenkov
b07283815b hir: Remove hir::Map::{opt_parent_id,parent_id,get_parent,find_parent} 2024-02-10 12:24:46 +03:00
Zalathar
a2479a4ae7 Remove unnecessary min_specialization after bootstrap
These crates all needed specialization for `newtype_index!`, which will no
longer be necessary when the current nightly eventually becomes the next
bootstrap compiler.
2024-02-10 18:15:11 +11:00
Matthias Krüger
116efb5bb1
Rollup merge of #120817 - compiler-errors:more-mir-errors, r=oli-obk
Fix more `ty::Error` ICEs in MIR passes

Fixes #120791 - Add a check for `ty::Error` in the `ByMove` coroutine pass
Fixes #120816 - Add a check for `ty::Error` in the MIR validator

Also a drive-by fix for a FIXME I had asked oli to add

r? oli-obk
2024-02-09 14:41:51 +01:00
Matthias Krüger
46a0448405
Rollup merge of #120693 - nnethercote:invert-diagnostic-lints, r=davidtwco
Invert diagnostic lints.

That is, change `diagnostic_outside_of_impl` and `untranslatable_diagnostic` from `allow` to `deny`, because more than half of the compiler has been converted to use translated diagnostics.

This commit removes more `deny` attributes than it adds `allow` attributes, which proves that this change is warranted.

r? ````@davidtwco````
2024-02-09 14:41:50 +01:00
Michael Goulet
698a3c7ade Don't ICE in ByMoveBody when coroutine is tainted 2024-02-09 00:36:30 +00:00
Matthias Krüger
ed528515d0
Rollup merge of #120801 - oli-obk:drop_recursion_ice, r=Nilstrieb
Avoid ICE in drop recursion check in case of invalid drop impls

fixes #120787
2024-02-08 20:35:01 +01:00
Matthias Krüger
949e55299d
Rollup merge of #120775 - Nadrieril:more-min_exh_pats, r=compiler-errors
Make `min_exhaustive_patterns` match `exhaustive_patterns` better

Split off from https://github.com/rust-lang/rust/pull/120742.

There remained two edge cases where `min_exhaustive_patterns` wasn't behaving like `exhaustive_patterns`. This fixes them, and tests the feature in a bunch more cases. I essentially went through all uses of `exhaustive_patterns` to see which ones would be interesting to compare between the two features.

r? `@compiler-errors`
2024-02-08 20:34:59 +01:00
Oli Scherer
ad511ef92e Avoid ICE in drop recursion check in case of invalid drop impls 2024-02-08 17:33:04 +00:00
bors
1280928a99 Auto merge of #120767 - matthiaskrgr:rollup-0k8ib1c, r=matthiaskrgr
Rollup of 9 pull requests

Successful merges:

 - #119592 (resolve: Unload speculatively resolved crates before freezing cstore)
 - #120103 (Make it so that async-fn-in-trait is compatible with a concrete future in implementation)
 - #120206 (hir: Make sure all `HirId`s have corresponding HIR `Node`s)
 - #120214 (match lowering: consistently lower bindings deepest-first)
 - #120688 (GVN: also turn moves into copies with projections)
 - #120702 (docs: also check the inline stmt during redundant link check)
 - #120727 (exhaustiveness: Prefer "`0..MAX` not covered" to "`_` not covered")
 - #120734 (Add `SubdiagnosticMessageOp` as a trait alias.)
 - #120739 (improve pretty printing for associated items in trait objects)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-02-08 12:14:19 +00:00
Nadrieril
30793ca818 Match min_exhaustive_patterns implementation with exhaustive_patterns 2024-02-08 11:23:52 +01:00
Oli Scherer
eab2adb660 Continue to borrowck even if there were previous errors 2024-02-08 08:10:43 +00:00
Matthias Krüger
87e1e05aa1
Rollup merge of #120734 - nnethercote:SubdiagnosticMessageOp, r=compiler-errors
Add `SubdiagnosticMessageOp` as a trait alias.

It avoids a lot of repetition.

r? matthewjasper
2024-02-08 09:06:36 +01:00
Matthias Krüger
7fb36f2d3b
Rollup merge of #120214 - Nadrieril:fix-120210, r=pnkfelix
match lowering: consistently lower bindings deepest-first

Currently when lowering match expressions to MIR, we do a funny little dance with the order of bindings. I attempt to explain it in the third commit: we handle refutable (i.e. needing a test) patterns differently than irrefutable ones. This leads to inconsistencies, as reported in https://github.com/rust-lang/rust/issues/120210. The reason we need a dance at all is for situations like:

```rust
fn foo1(x: NonCopyStruct) {
    let y @ NonCopyStruct { copy_field: z } = x;
    // the above should turn into
    let z = x.copy_field;
    let y = x;
}
```

Here the `y ```````@```````` binding will move out of `x`, so we need to copy the field first.

I believe that the inconsistency came about when we fixed https://github.com/rust-lang/rust/issues/69971, and didn't notice that the fix didn't extend to refutable patterns. My guess then is that ordering bindings by "deepest-first, otherwise source order" is a sound choice. This PR implements that (at least I hope, match lowering is hard to follow 🥲).

Fixes https://github.com/rust-lang/rust/issues/120210

r? ```````@oli-obk``````` since you merged the original fix to https://github.com/rust-lang/rust/issues/69971
cc ```````@matthewjasper```````
2024-02-08 09:06:33 +01:00
Nicholas Nethercote
6b175a848d Add SubdiagnosticMessageOp as a trait alias.
It avoids a lot of repetition.
2024-02-08 13:02:44 +11:00
Matthias Krüger
176c4ba5c3
Rollup merge of #120423 - RalfJung:indirect-structural-match, r=petrochenkov
update indirect structural match lints to match RFC and to show up for dependencies

This is a large step towards implementing https://github.com/rust-lang/rfcs/pull/3535.
We currently have five lints related to "the structural match situation":
- nontrivial_structural_match
- indirect_structural_match
- pointer_structural_match
- const_patterns_without_partial_eq
- illegal_floating_point_literal_pattern

This PR concerns the first 3 of them. (The 4th already is set up to show for dependencies, and the 5th is removed by https://github.com/rust-lang/rust/pull/116284.) nontrivial_structural_match is being removed as per the RFC; the other two are enabled to show up in dependencies.

Fixes https://github.com/rust-lang/rust/issues/73448 by removing the affected analysis.
2024-02-06 22:45:41 +01:00
Matthias Krüger
ce32d4862b
Rollup merge of #120331 - Nadrieril:no-arena, r=compiler-errors
pattern_analysis: use a plain `Vec` in `DeconstructedPat`

The use of an arena-allocated slice in `DeconstructedPat` dates to when we needed the arena anyway for lifetime reasons. Now that we don't, I'm thinking that if `thir::Pat` can use plain old `Vec`s, maybe so can I.

r? ```@ghost```
2024-02-06 22:45:40 +01:00
Michael Goulet
a82bae2172 Teach typeck/borrowck/solvers how to deal with async closures 2024-02-06 02:22:58 +00:00
Michael Goulet
c567eddec2 Add CoroutineClosure to TyKind, AggregateKind, UpvarArgs 2024-02-06 02:22:58 +00:00
Nicholas Nethercote
0ac1195ee0 Invert diagnostic lints.
That is, change `diagnostic_outside_of_impl` and
`untranslatable_diagnostic` from `allow` to `deny`, because more than
half of the compiler has be converted to use translated diagnostics.

This commit removes more `deny` attributes than it adds `allow`
attributes, which proves that this change is warranted.
2024-02-06 13:12:33 +11:00
Ralf Jung
9f58cf43c7 get rid of nontrivial_structural_match lint and custom_eq const qualif 2024-02-05 20:36:09 +01:00
Matthias Krüger
ed27148812
Rollup merge of #116284 - RalfJung:no-nan-match, r=cjgillot
make matching on NaN a hard error, and remove the rest of illegal_floating_point_literal_pattern

These arms would never be hit anyway, so the pattern makes little sense. We have had a future-compat lint against float matches in general for a *long* time, so I hope we can get away with immediately making this a hard error.

This is part of implementing https://github.com/rust-lang/rfcs/pull/3535.

Closes https://github.com/rust-lang/rust/issues/41620 by removing the lint.

https://github.com/rust-lang/reference/pull/1456 updates the reference to match.
2024-02-05 11:07:26 +01:00
Nadrieril
f65fe3ba59 Remove pattern_arena from RustcMatchCheckCtxt 2024-01-31 19:25:40 +01:00
bors
d53ddcd8bb Auto merge of #120346 - petrochenkov:ownodes, r=oli-obk
hir: Refactor getters for owner nodes
2024-01-31 05:37:49 +00:00
Vadim Petrochenkov
db41f4aaa0 hir: Remove hir::Map::{owner,expect_owner} 2024-01-30 15:00:52 +03:00
Guillaume Gomez
f99b510429
Rollup merge of #120488 - nnethercote:diag-lifetimes, r=oli-obk
Diagnostic lifetimes cleanups

Some diagnostic simplifications.

r? `@oli-obk`
2024-01-30 11:19:20 +01:00
Nicholas Nethercote
45dc19785d Remove lifetimes from some diagnostics.
Because the `&'a str` fields can be trivially converted to `String`
without causing any extra allocations.
2024-01-30 18:46:08 +11:00
Nicholas Nethercote
5350edb9e8 Remove the lifetime from DiagnosticArgValue.
Because it's almost always static.

This makes `impl IntoDiagnosticArg for DiagnosticArgValue` trivial,
which is nice.

There are a few diagnostics constructed in
`compiler/rustc_mir_build/src/check_unsafety.rs` and
`compiler/rustc_mir_transform/src/errors.rs` that now need symbols
converted to `String` with `to_string` instead of `&str` with `as_str`,
but that' no big deal, and worth it for the simplifications elsewhere.
2024-01-30 18:46:06 +11:00
Dylan DPC
549eeb077d
Rollup merge of #120390 - matthewjasper:inline-constant-pat-mir, r=davidtwco
Borrow check inline const patterns

Add type annotations to MIR so that borrowck can pass constraints from inline constants in patterns to the containing function.
Also enables some inline constant pattern tests that were fixed by the THIR unsafeck stabilization.

cc #76001
2024-01-29 12:56:53 +00:00
Matthew Jasper
83fa46fe5b Borrow check inline const patterns
Add type annotations to MIR so that borrowck can pass constraints from
inline constants in patterns to the containing function.
2024-01-29 09:17:00 +00:00
Nicholas Nethercote
5d9dfbd08f Stop using String for error codes.
Error codes are integers, but `String` is used everywhere to represent
them. Gross!

This commit introduces `ErrCode`, an integral newtype for error codes,
replacing `String`. It also introduces a constant for every error code,
e.g. `E0123`, and removes the `error_code!` macro. The constants are
imported wherever used with `use rustc_errors::codes::*`.

With the old code, we have three different ways to specify an error code
at a use point:
```
error_code!(E0123)  // macro call

struct_span_code_err!(dcx, span, E0123, "msg");  // bare ident arg to macro call

\#[diag(name, code = "E0123")]  // string
struct Diag;
```

With the new code, they all use the `E0123` constant.
```
E0123  // constant

struct_span_code_err!(dcx, span, E0123, "msg");  // constant

\#[diag(name, code = E0123)]  // constant
struct Diag;
```

The commit also changes the structure of the error code definitions:
- `rustc_error_codes` now just defines a higher-order macro listing the
  used error codes and nothing else.
- Because that's now the only thing in the `rustc_error_codes` crate, I
  moved it into the `lib.rs` file and removed the `error_codes.rs` file.
- `rustc_errors` uses that macro to define everything, e.g. the error
  code constants and the `DIAGNOSTIC_TABLES`. This is in its new
  `codes.rs` file.
2024-01-29 07:41:41 +11:00
Ralf Jung
1254ee48c4 remove illegal_floating_point_literal_pattern lint 2024-01-26 17:25:02 +01:00
Ralf Jung
cda3588572 make matching on NaN a hard error 2024-01-26 17:23:36 +01:00
Deadbeef
e17f91dd8b Classify closure arguments in refutable pattern in argument error 2024-01-26 23:54:08 +08:00
bors
69db514ed9 Auto merge of #119968 - clubby789:unused-feature, r=compiler-errors
Remove unused/unnecessary features

~~The bulk of the actual code changes here is replacing try blocks with equivalent closures. I'm not entirely sure that's a good idea since it may have perf impact, happy to revert if that's the case/the change is unwanted.~~

I also removed a lot of `recursion_limit = "256"` since everything seems to build fine without that and most don't have any comment justifying it.
2024-01-26 03:18:34 +00:00