Commit Graph

34329 Commits

Author SHA1 Message Date
bors
196ff446d2 Auto merge of #122493 - lukas-code:sized-constraint, r=lcnr
clean up `Sized` checking

This PR cleans up `sized_constraint` and related functions to make them simpler and faster. This should not make more or less code compile, but it can change error output in some rare cases.

## enums and unions are `Sized`, even if they are not WF

The previous code has some special handling for enums, which made them sized if and only if the last field of each variant is sized. For example given this definition (which is not WF)
```rust
enum E<T1: ?Sized, T2: ?Sized, U1: ?Sized, U2: ?Sized> {
    A(T1, T2),
    B(U1, U2),
}
```
the enum was sized if and only if `T2` and `U2` are sized, while `T1` and `T2` were ignored for `Sized` checking. After this PR this enum will always be sized.

Unsized enums are not a thing in Rust and removing this special case allows us to return an `Option<Ty>` from `sized_constraint`, rather than a `List<Ty>`.

Similarly, the old code made an union defined like this
```rust
union Union<T: ?Sized, U: ?Sized> {
    head: T,
    tail: U,
}
```
sized if and only if `U` is sized, completely ignoring `T`. This just makes no sense at all and now this union is always sized.

## apply the "perf hack" to all (non-error) types, instead of just type parameters

This "perf hack" skips evaluating `sized_constraint(adt): Sized` if `sized_constraint(adt): Sized` exactly matches a predicate defined on `adt`, for example:

```rust
// `Foo<T>: Sized` iff `T: Sized`, but we know `T: Sized` from a predicate of `Foo`
struct Foo<T /*: Sized */>(T);
```

Previously this was only applied to type parameters and now it is applied to every type. This means that for example this type is now always sized:

```rust
// Note that this definition is WF, but the type `S<T>` not WF in the global/empty ParamEnv
struct S<T>([T]) where [T]: Sized;
```

I don't anticipate this to affect compile time of any real-world program, but it makes the code a bit nicer and it also makes error messages a bit more consistent if someone does write such a cursed type.

## tuples are sized if the last type is sized

The old solver already has this behavior and this PR also implements it for the new solver and `is_trivially_sized`. This makes it so that tuples work more like a struct defined like this:

```rust
struct TupleN<T1, T2, /* ... */ Tn: ?Sized>(T1, T2, /* ... */ Tn);
```

This might improve the compile time of programs with large tuples a little, but is mostly also a consistency fix.

## `is_trivially_sized` for more types

This function is used post-typeck code (borrowck, const eval, codegen) to skip evaluating `T: Sized` in some cases. It will now return `true` in more cases, most notably `UnsafeCell<T>` and `ManuallyDrop<T>` where `T.is_trivially_sized`.

I'm anticipating that this change will improve compile time for some real world programs.
2024-03-19 04:21:14 +00:00
Gurinder Singh
3c70d60c4f Gracefully handle AnonConst in diagnostic_hir_wf_check()
when it is the default value of a generic param
2024-03-19 09:20:23 +05:30
Nadrieril
d697dd44d1 Add a crate-custom test harness 2024-03-19 02:22:43 +01:00
Nadrieril
e4487ad391 Improve the WitnessPat: Debug impl 2024-03-19 02:22:43 +01:00
Nadrieril
3dfd0fd858 Report arm intersections 2024-03-19 02:20:36 +01: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
Lukas Markeffsky
99efae342e address nits 2024-03-18 22:28:29 +01:00
Matthias Krüger
3c3b398b35
Rollup merge of #122701 - compiler-errors:allocator-suspend, r=oli-obk
Detect allocator for box in `must_not_suspend` lint

I don't expect this to happen in practice, but better to check than not.

Fixes #122643
2024-03-18 22:24:41 +01:00
Matthias Krüger
e906205607
Rollup merge of #122687 - lcnr:normalizes-to-emit-nested-goals, r=compiler-errors
`NormalizesTo`: return nested goals to caller

Fixes the regression of `paperclip-core`. see https://hackmd.io/IsVAafiOTAaPIFcUxRJufw for more details.

r? ```@compiler-errors```
2024-03-18 22:24:39 +01:00
Matthias Krüger
980248605a
Rollup merge of #122158 - estebank:feature-sugg, r=WaffleLapkin
Provide structured suggestion for `#![feature(foo)]`

```
error: `S2<'_>` is forbidden as the type of a const generic parameter
  --> $DIR/lifetime-in-const-param.rs:5:23
   |
LL | struct S<'a, const N: S2>(&'a ());
   |                       ^^
   |
   = note: the only supported types are integers, `bool` and `char`
help: add `#![feature(adt_const_params)]` to the crate attributes to enable more complex and user defined types
   |
LL + #![feature(adt_const_params)]
   |
```

Fix #55941.
2024-03-18 22:24:38 +01:00
Matthias Krüger
b19c67c0fc
Rollup merge of #122060 - clubby789:stabilize-imported-main, r=lcnr
Stabilize `imported_main`

FCP: https://github.com/rust-lang/rust/issues/28937#issuecomment-1977822831
Docs: https://github.com/rust-lang/reference/pull/1461
2024-03-18 22:24:37 +01: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
Matthias Krüger
05f763344d
Rollup merge of #121258 - fmease:assoc-const-eq-reject-overly-generic-tys, r=compiler-errors
Reject overly generic assoc const binding types

Split off from #119385 to make #119385 easier to review.

---

In the *instantiated* type of assoc const bindings

1. reject **early-bound generic params**
   * Provide a rich error message instead of ICE'ing ([#108271](https://github.com/rust-lang/rust/issues/108271)).
   * This is a temporary and semi-artificial restriction until the arrival of *generic const generics*.
   * It's quite possible that rustc could already perfectly support this subset of generic const generics if we just removed some checks (some `.no_bound_vars().expect(…)`) but even if that was the case, I'd rather gate it behind a new feature flag. Reporting an error instead of ICE'ing is a good first step towards an eventual feature gate error.
2. reject **escaping late-bound generic params**
   * They lead to ICEs before & I'm pretty sure that they remain incorrect even in a world with *generic const generics*

---

Together with #118668 & #119385, this supersedes #118360.
Fixes #108271.
2024-03-18 22:24:36 +01:00
Oli Scherer
69c4e813fe Use hir::Node helper methods instead of repeat the same impl multiple times
There already were inconsistencies, so this ensures we don't introduce subtle surprising bugs
2024-03-18 18:12:45 +00:00
Oli Scherer
419d205dad Deduplicate associated_body and body_id
They match on almost the same patterns, which is fishy.

Also turn `associated_body` into a method and do some cleanups nearby the call sites
2024-03-18 18:12:32 +00:00
Michael Goulet
0db06bf004 Detect allocator for box in must_not_suspend lint 2024-03-18 14:12:28 -04:00
lcnr
0b29b71a2f cleanup + review 2024-03-18 18:13:25 +01:00
lcnr
7c5a99b6a8 improve comments 2024-03-18 18:13:25 +01:00
Boxy
e34e344118 rename instantiate_canonical_with_fresh_inference_vars 2024-03-18 16:44:16 +00:00
Boxy
8124b26122 update region debug formatting 2024-03-18 16:44:12 +00:00
Esteban Küber
cc9631a371 When displaying multispans, ignore empty lines adjacent to ...
```
error[E0308]: `match` arms have incompatible types
   --> tests/ui/codemap_tests/huge_multispan_highlight.rs:98:18
    |
6   |       let _ = match true {
    |               ---------- `match` arms have incompatible types
7   |           true => (
    |  _________________-
8   | |             // last line shown in multispan header
...   |
96  | |
97  | |         ),
    | |_________- this is found to be of type `()`
98  |           false => "
    |  __________________^
...   |
119 | |
120 | |         ",
    | |_________^ expected `()`, found `&str`

error[E0308]: `match` arms have incompatible types
   --> tests/ui/codemap_tests/huge_multispan_highlight.rs:215:18
    |
122 |       let _ = match true {
    |               ---------- `match` arms have incompatible types
123 |           true => (
    |  _________________-
124 | |
125 | |         1 // last line shown in multispan header
...   |
213 | |
214 | |         ),
    | |_________- this is found to be of type `{integer}`
215 |           false => "
    |  __________________^
216 | |
217 | |
218 | |         1 last line shown in multispan
...   |
237 | |
238 | |         ",
    | |_________^ expected integer, found `&str`
```
2024-03-18 16:25:36 +00:00
Esteban Küber
6c31f6ce12 Provide structured suggestion for #![feature(foo)]
```
error: `S2<'_>` is forbidden as the type of a const generic parameter
  --> $DIR/lifetime-in-const-param.rs:5:23
   |
LL | struct S<'a, const N: S2>(&'a ());
   |                       ^^
   |
   = note: the only supported types are integers, `bool` and `char`
help: add `#![feature(adt_const_params)]` to the crate attributes to enable more complex and user defined types
   |
LL + #![feature(adt_const_params)]
   |
```

Fix #55941.
2024-03-18 16:08:58 +00:00
Veera
97cc7003ca Fix ICE: global_asm!() Don't Panic When Unable to Evaluate Constant
A bit of an inelegant fix but given that the error is created only
after call to `const_eval_poly()` and that the calling function
cannot propagate the error anywhere else, the error has to be
explicitly handled inside `mono_item.rs`.
2024-03-18 11:35:40 -04:00
Matthias Krüger
9011e67c91
Rollup merge of #122689 - Jarcho:missing_try, r=compiler-errors
Add missing `try_visit` calls in visitors.
2024-03-18 16:27:11 +01:00
Matthias Krüger
72e2c7c45a
Rollup merge of #122680 - lqd:nested-await-args, r=compiler-errors
Do not eat nested expressions' results in `MayContainYieldPoint` format args visitor

#121563 unintentionally changed the `MayContainYieldPoint` format args visitor behavior, now missing yield points in nested expressions, as seen in #122674.

The walk can find a yield point in an expression but it was ignored.

r? ``@petrochenkov`` as the reviewer of #121563
cc ``@Jarcho`` as the author

Fixes #122674.
We're in the 1.77 release week. #121563 will land on 1.78 but beta is still 1.77.9: this PR will likely need to be backported soon after beta is cut.
2024-03-18 16:27:10 +01:00
Matthias Krüger
1ac0239bd2
Rollup merge of #122649 - cuviper:min-llvm-17, r=nikic
Update the minimum external LLVM to 17

With this change, we'll have stable support for LLVM 17 and 18.
For reference, the previous increase to LLVM 16 was #117947.
2024-03-18 16:27:09 +01:00
Matthias Krüger
3fa48ec849
Rollup merge of #122647 - RalfJung:box-to-raw-retag, r=oli-obk
add_retag: ensure box-to-raw-ptr casts are preserved for Miri

In https://github.com/rust-lang/rust/pull/122233 I added `retag_box_to_raw` not realizing that we can already do `addr_of_mut!(*bx)` to turn a box into a raw pointer without an intermediate reference. We just need to ensure this information is preserved past the ElaborateBoxDerefs pass.

r? ``@oli-obk``
2024-03-18 16:27:08 +01:00
Matthias Krüger
acc45ebf72
Rollup merge of #122588 - klensy:imported_source_file, r=michaelwoerister
less useless filter calls in imported_source_file

This reduces calls to `filter` greatly, giving 0.3% instructions win on some tests.
2024-03-18 16:27:08 +01:00
Matthias Krüger
87b5679ab0
Rollup merge of #122567 - erikdesjardins:noname, r=oli-obk
Remove fixme about LLVM basic block naming

~This may be a small perf win.~

Originally, this PR implemented the fixme, but it didn't have any measurable perf improvement.

r? ``@ghost``
2024-03-18 16:27:07 +01:00
Jason Newcomb
407b58cb77 Add missing try_visit calls in visitors. 2024-03-18 11:21:06 -04:00
lcnr
f26e1e8b63 NormalizesTo return nested goals 2024-03-18 15:53:16 +01:00
lcnr
33c274f658 move normalizes_to_hack to AliasRelate 2024-03-18 12:08:06 +01:00
Oli Scherer
be9317d1ec Prevent opaque types being instantiated twice with different regions within the same function 2024-03-18 10:26:10 +00: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
Ralf Jung
bcf8015177 remove retag_box_to_raw, it is no longer needed 2024-03-18 10:32:25 +01:00
Ralf Jung
c96fa5e143 add_retag: ensure box-to-raw-ptr casts are preserved for Miri 2024-03-18 10:32:25 +01:00
Rémy Rakic
8beec62315 do not eat nested exprs result in format args visitor 2024-03-18 09:27:47 +00:00
Matthias Krüger
3fc3142df1
Rollup merge of #122656 - RalfJung:simplify-cfg, r=compiler-errors
simplify_cfg: rename some passes so that they make more sense

I was extremely confused by `SimplifyCfg::ElaborateDrops`, since it runs way later than drop elaboration. It is used e.g. in `mir-opt/retag.rs` even though that pass doesn't care about drop elaboration at all.

"Early opt" is also very confusing since that makes it sounds like it runs early during optimizations, i.e. on runtime MIR, but actually it runs way before that.

So I decided to rename
- early-opt -> post-analysis
- elaborate-drops -> pre-optimizations

I am open to other suggestions.
2024-03-18 06:58:50 +01:00
Matthias Krüger
86bb0bc41d
Rollup merge of #122654 - RalfJung:interpret-comment, r=matthiaskrgr
interpret/memory: explain why we use == on bool

This came up in https://github.com/rust-lang/rust/pull/122636.
2024-03-18 06:58:49 +01:00
Matthias Krüger
d9b47c1f2b
Rollup merge of #122639 - omahs:patch-2, r=estebank
Fix typos

Fix typos
2024-03-18 06:58:49 +01:00
bors
5608c7f9aa Auto merge of #121652 - estebank:move-in-loop-break-condition, r=Nadrieril
Detect when move of !Copy value occurs within loop and should likely not be cloned

When encountering a move error on a value within a loop of any kind,
identify if the moved value belongs to a call expression that should not
be cloned and avoid the semantically incorrect suggestion. Also try to
suggest moving the call expression outside of the loop instead.

```
error[E0382]: use of moved value: `vec`
  --> $DIR/recreating-value-in-loop-condition.rs:6:33
   |
LL |     let vec = vec!["one", "two", "three"];
   |         --- move occurs because `vec` has type `Vec<&str>`, which does not implement the `Copy` trait
LL |     while let Some(item) = iter(vec).next() {
   |     ----------------------------^^^--------
   |     |                           |
   |     |                           value moved here, in previous iteration of loop
   |     inside of this loop
   |
note: consider changing this parameter type in function `iter` to borrow instead if owning the value isn't necessary
  --> $DIR/recreating-value-in-loop-condition.rs:1:17
   |
LL | fn iter<T>(vec: Vec<T>) -> impl Iterator<Item = T> {
   |    ----         ^^^^^^ this parameter takes ownership of the value
   |    |
   |    in this function
help: consider moving the expression out of the loop so it is only moved once
   |
LL ~     let mut value = iter(vec);
LL ~     while let Some(item) = value.next() {
   |
```

We use the presence of a `break` in the loop that would be affected by
the moved value as a heuristic for "shouldn't be cloned".

Fix https://github.com/rust-lang/rust/issues/121466.

---

*Point at continue and break that might be in the wrong place*

Sometimes move errors are because of a misplaced `continue`, but we didn't
surface that anywhere. Now when there are more than one set of nested loops
we show them out and point at the `continue` and `break` expressions within
that might need to go elsewhere.

```
error[E0382]: use of moved value: `foo`
  --> $DIR/nested-loop-moved-value-wrong-continue.rs:46:18
   |
LL |     for foo in foos {
   |         ---
   |         |
   |         this reinitialization might get skipped
   |         move occurs because `foo` has type `String`, which does not implement the `Copy` trait
...
LL |         for bar in &bars {
   |         ---------------- inside of this loop
...
LL |                 baz.push(foo);
   |                          --- value moved here, in previous iteration of loop
...
LL |         qux.push(foo);
   |                  ^^^ value used here after move
   |
note: verify that your loop breaking logic is correct
  --> $DIR/nested-loop-moved-value-wrong-continue.rs:41:17
   |
LL |     for foo in foos {
   |     ---------------
...
LL |         for bar in &bars {
   |         ----------------
...
LL |                 continue;
   |                 ^^^^^^^^ this `continue` advances the loop at line 33
help: consider moving the expression out of the loop so it is only moved once
   |
LL ~         let mut value = baz.push(foo);
LL ~         for bar in &bars {
LL |
 ...
LL |             if foo == *bar {
LL ~                 value;
   |
help: consider cloning the value if the performance cost is acceptable
   |
LL |                 baz.push(foo.clone());
   |                             ++++++++
```

Fix https://github.com/rust-lang/rust/issues/92531.
2024-03-18 02:10:34 +00:00
bors
62f98b44cc Auto merge of #122627 - RalfJung:collector-stack-space, r=compiler-errors
collector: move ensure_sufficient_stack out of the loop

According to the docs this call has some overhead to putting it inside the loop doesn't seem like a good idea.

r? `@oli-obk`
2024-03-18 00:03:56 +00:00
Esteban Küber
3b237d7d8a Move suggest_hoisting_call_outside_loop out of suggest_cloning 2024-03-17 21:52:12 +00:00
Esteban Küber
da2364d746 Move Visitor impl out to the mod level 2024-03-17 21:46:52 +00:00
Esteban Küber
78d29ad8d6 Point at continue and break that might be in the wrong place
Sometimes move errors are because of a misplaced `continue`, but we didn't
surface that anywhere. Now when there are more than one set of nested loops
we show them out and point at the `continue` and `break` expressions within
that might need to go elsewhere.

```
error[E0382]: use of moved value: `foo`
  --> $DIR/nested-loop-moved-value-wrong-continue.rs:46:18
   |
LL |     for foo in foos {
   |         ---
   |         |
   |         this reinitialization might get skipped
   |         move occurs because `foo` has type `String`, which does not implement the `Copy` trait
...
LL |         for bar in &bars {
   |         ---------------- inside of this loop
...
LL |                 baz.push(foo);
   |                          --- value moved here, in previous iteration of loop
...
LL |         qux.push(foo);
   |                  ^^^ value used here after move
   |
note: verify that your loop breaking logic is correct
  --> $DIR/nested-loop-moved-value-wrong-continue.rs:41:17
   |
LL |     for foo in foos {
   |     ---------------
...
LL |         for bar in &bars {
   |         ----------------
...
LL |                 continue;
   |                 ^^^^^^^^ this `continue` advances the loop at line 33
help: consider moving the expression out of the loop so it is only moved once
   |
LL ~         let mut value = baz.push(foo);
LL ~         for bar in &bars {
LL |
 ...
LL |             if foo == *bar {
LL ~                 value;
   |
help: consider cloning the value if the performance cost is acceptable
   |
LL |                 baz.push(foo.clone());
   |                             ++++++++
```

Fix #92531.
2024-03-17 21:32:26 +00:00
Esteban Küber
14473adf42 Detect when move of !Copy value occurs within loop and should likely not be cloned
When encountering a move error on a value within a loop of any kind,
identify if the moved value belongs to a call expression that should not
be cloned and avoid the semantically incorrect suggestion. Also try to
suggest moving the call expression outside of the loop instead.

```
error[E0382]: use of moved value: `vec`
  --> $DIR/recreating-value-in-loop-condition.rs:6:33
   |
LL |     let vec = vec!["one", "two", "three"];
   |         --- move occurs because `vec` has type `Vec<&str>`, which does not implement the `Copy` trait
LL |     while let Some(item) = iter(vec).next() {
   |     ----------------------------^^^--------
   |     |                           |
   |     |                           value moved here, in previous iteration of loop
   |     inside of this loop
   |
note: consider changing this parameter type in function `iter` to borrow instead if owning the value isn't necessary
  --> $DIR/recreating-value-in-loop-condition.rs:1:17
   |
LL | fn iter<T>(vec: Vec<T>) -> impl Iterator<Item = T> {
   |    ----         ^^^^^^ this parameter takes ownership of the value
   |    |
   |    in this function
help: consider moving the expression out of the loop so it is only moved once
   |
LL ~     let mut value = iter(vec);
LL ~     while let Some(item) = value.next() {
   |
```

We use the presence of a `break` in the loop that would be affected by
the moved value as a heuristic for "shouldn't be cloned".

Fix #121466.
2024-03-17 21:32:26 +00:00
Ralf Jung
23a4ad12ce simplify_cfg: rename some passes so that they make more sense 2024-03-17 19:59:15 +01:00
Ralf Jung
872781b226 interpret/memory: explain why we use == on bool 2024-03-17 19:32:03 +01:00
Matthias Krüger
1588d9bdc8
Rollup merge of #122636 - matthiaskrgr:compl3, r=compiler-errors
some minor code simplifications
2024-03-17 19:26:23 +01:00
Matthias Krüger
8e748c0a41
Rollup merge of #122578 - jieyouxu:guard-decorate, r=fee1-dead
Only invoke `decorate` if the diag can eventually be emitted

Lints can call [`trimmed_def_paths`](https://doc.rust-lang.org/nightly/nightly-rustc/rustc_middle/ty/print/fn.trimmed_def_paths.html#), such as through manual implementations of `LintDiagnostic` and calling `def_path_str`.

05a2be3def/compiler/rustc_lint/src/lints.rs (L1834-L1839)

The emission of a lint eventually relies on [`TyCtxt::node_lint`](https://doc.rust-lang.org/nightly/nightly-rustc/rustc_middle/ty/context/struct.TyCtxt.html#method.node_lint), which has a `decorate` closure which is responsible for decorating the diagnostic with "lint stuff". `node_lint` in turn relies on [`lint_level`](https://doc.rust-lang.org/nightly/nightly-rustc/rustc_middle/lint/fn.lint_level.html). Within `lint_level`, `decorate` is eventually called just before `Diag::emit` is called to decorate the diagnostic. However, if `-A warnings` or `--cap-lint=allow` are set, or if the unused_must_use lint is explicitly allowed, then `decorate` would be called, which would call `def_path_str`, but the diagnostic would never be emitted and hence would trigger the `must_produce_diag` ICE.

To avoid calling `decorate` when we don't eventually emit the diagnostic, we check that:

- if `--force-warn` is specified, then call `decorate`; otherwise
- if we can emit warnings (or higher), then call `decorate`.

Fixes #121774.
2024-03-17 19:26:22 +01:00
Josh Stone
29430554f6 Update the minimum external LLVM to 17 2024-03-17 10:11:04 -07:00
许杰友 Jieyou Xu (Joe)
bdab02ca99
Guard decorate on when not to skip instead 2024-03-17 15:07:22 +00:00
许杰友 Jieyou Xu (Joe)
60de7554de
Invoke decorate when error level is beyond warning, including error 2024-03-17 14:41:37 +00:00
许杰友 Jieyou Xu (Joe)
772d8598d2
Only invoke decorate if the diag can eventually be emitted 2024-03-17 14:41:36 +00:00
Ralf Jung
ee746fb8ed collector: move ensure_sufficient_stack out of the loop 2024-03-17 15:17:00 +01:00
omahs
758f642c29
fix typo 2024-03-17 14:25:24 +01:00
omahs
96e3c2c1ac
fix typo 2024-03-17 14:25:06 +01:00
Matthias Krüger
12137462b4
Rollup merge of #122633 - matthiaskrgr:col, r=fmease
avoid unnecessary collect()
2024-03-17 14:04:15 +01:00
Matthias Krüger
3ec2b7bd1d
Rollup merge of #121236 - long-long-float:rust-fix-consider-slicing, r=Nadrieril
Don't show suggestion if slice pattern is not top-level

Close #120605

Don't show suggestion to add slicing (`[..]`) if the slice pattern is enclosed by struct like `Struct { a: [] }`.

For example, current rustc makes a suggestion as a comment. However, the pattern `a: []` is wrong, not scrutinee `&self.a`.
In this case, the structure type `a: Vec<Struct>` and the pattern `a: []` are different so I think the pattern should be fixed, not the scrutinee.
If the parent of the pattern that was the target of the error is a structure, I made the compiler not show a suggestion.

```rs
pub struct Struct {
    a: Vec<Struct>,
}

impl Struct {
    pub fn test(&self) {
        if let [Struct { a: [] }] = &self.a {
//             ^^^^^^^^^^^^^^^^^^   ------- help: consider slicing here: `&self.a[..]`
            println!("matches!")
        }
    }
}
```

Note:

* ~~I created `PatInfo.history` to store parent-child relationships for patterns, but this may be inefficient.~~
  * I use two fields `parent_kind` and `current_kind` instead of vec. It may not performance issue.
* Currently only looking at direct parents, but may need to look at deeper ancestry.
2024-03-17 14:04:14 +01:00
Matthias Krüger
0437a0c372 some minor code simplifications 2024-03-17 13:44:44 +01:00
Matthias Krüger
b8db431f37 avoid unnecessary collect() 2024-03-17 12:19:46 +01:00
long-long-float
78e94cba77 Don't show suggestion if slice pattern is enclosed by any patterns 2024-03-17 19:21:13 +09:00
Matthias Krüger
325678c979
Rollup merge of #122608 - Urgau:check-cfg-move-diagnostic-logic, r=fmease
Move check-cfg diagnostic logic into a separate file

as well as adding some triagebot mentions (for me) for check-cfg related files.

``@rustbot`` label +F-check-cfg
2024-03-17 08:23:26 +01:00
Matthias Krüger
33b4ed225a
Rollup merge of #122574 - cuviper:llvm-oom, r=nikic
Register LLVM handlers for bad-alloc / OOM

LLVM's default bad-alloc handler may throw if exceptions are enabled,
and `operator new` isn't hooked at all by default. Now we register our
own handler that prints a message similar to fatal errors, then aborts.
We also call the function that registers the C++ `std::new_handler`.

Fixes #121305
Cc llvm/llvm-project#85281
r? ``@nikic``
2024-03-17 08:23:26 +01:00
bors
a615cea333 Auto merge of #121885 - reitermarkus:generic-nonzero-inner, r=oli-obk,wesleywiser
Move generic `NonZero` `rustc_layout_scalar_valid_range_start` attribute to inner type.

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

r? `@dtolnay`
2024-03-17 02:27:52 +00:00
Urgau
bf8715e6ee Move check-cfg diagnostic logic into it's own module 2024-03-16 23:33:54 +01:00
许杰友 Jieyou Xu (Joe)
52a1125036
Extend format arg help for simple tuple index access expression 2024-03-16 22:33:02 +00:00
León Orell Valerian Liehr
caa6131ae5
Rollup merge of #122605 - osiewicz:metadata-register-crate-store-crate-name-in-profile, r=Nadrieril
rustc-metadata: Store crate name in self-profile of metadata_register_crate

When profiling a build of Zed, I found myself in need of names of crates that take the longest to register in downstream crates.
2024-03-16 23:28:50 +01:00
León Orell Valerian Liehr
4cbfa15a2d
Rollup merge of #122577 - fmease:speculative-say-what, r=compiler-errors
Remove obsolete parameter `speculative` from `instantiate_poly_trait_ref`

In #122527 I totally missed that `speculative` has become obsolete with the removal of `hir_trait_to_predicates` / due to #113671.

Fixes #114635.

r? `@compiler-errors`
2024-03-16 23:28:49 +01:00
León Orell Valerian Liehr
7b7a7fc891
Rollup merge of #122564 - Bryanskiy:delegation-fixes, r=compiler-errors
Delegation: fix ICE on duplicated associative items

Currently, functions delegation is only supported for delegation items with early resolved paths e.g. free functions and trait methods. During name resolution, information about function signatures is collected, including the number of parameters and whether there are self arguments. This information is then used when lowering from a delegation item into a regular function(`rustc_ast_lowering/src/delegation.rs`). The signature is usually inherited from path resolution id(`path_id`). However, in the case of trait impls `path_id` and `item_id` may be different:

```rust
trait Trait {
    fn foo(&self) -> u32 { 0 }
}

struct S;

mod to_reuse {
    use crate::S;

    pub fn foo(_: &S) -> u32 { 0 }
}

impl Trait for S {
    reuse to_reuse::foo { self }
    //~^ The signature should be inherited from item id instead of resolution id
}

```

Let's now consider an example from [issue](https://github.com/rust-lang/rust/issues/119920). Due to duplicated associative elements partial resolution for one of them will not be recorded:

9023f908cf/compiler/rustc_resolve/src/late.rs (L3153-L3162)

Which leads to an incorrect `is_in_trait_impl`

9023f908cf/compiler/rustc_ast_lowering/src/item.rs (L981-L986)

Which leads to an incorrect id for signature inheritance

9023f908cf/compiler/rustc_ast_lowering/src/delegation.rs (L99-L105)

Which lead to an ICE from original issue.

This patch fixes wrong `is_in_trait_impl`  calculation.

fixes https://github.com/rust-lang/rust/issues/119920
2024-03-16 23:28:48 +01:00
León Orell Valerian Liehr
0995508562
Rollup merge of #121720 - tmandry:split-refining, r=compiler-errors
Split refining_impl_trait lint into _reachable, _internal variants

As discussed in https://github.com/rust-lang/rust/issues/119535#issuecomment-1909352040:

> We discussed this today in triage and developed a consensus to:
>
> * Add a separate lint against impls that refine a return type defined with RPITIT even when the trait is not crate public.
> * Place that in a lint group along with the analogous crate public lint.
> * Create an issue to solicit feedback on these lints (or perhaps two separate ones).
> * Have the warnings displayed with each lint reference this issue in a similar manner to how we do that today with the required `Self: '0'` bound on GATs.
> * Make a note to review this feedback on 2-3 release cycles.

This points users to https://github.com/rust-lang/rust/issues/121718 to leave feedback.
2024-03-16 23:28:47 +01:00
León Orell Valerian Liehr
79c1e58801
Rollup merge of #121545 - gvozdvmozgu:fix-attribute-validation-associated-items, r=fmease
fix attribute validation on associated items in traits

#121537, fixed attribute validation on associated items in traits
2024-03-16 23:28:47 +01:00
León Orell Valerian Liehr
c00c5fec2a
Rollup merge of #117918 - daxpedda:wasm-c-abi-warning, r=workingjubilee
Add `wasm_c_abi` `future-incompat` lint

This is a warning that will tell users to update to `wasm-bindgen` v0.2.88, which supports spec-compliant C ABI.

The idea is to prepare for a future where Rust will switch to the spec-compliant C ABI by default; so not to break everyone's world, this warning is introduced.

Addresses #71871.
2024-03-16 23:28:46 +01:00
Piotr Osiewicz
ad84934e6f rustc-metadata: Store crate name in self-profile of metadata_register_crate
When profiling a build of Zed, I found myself in need of names of crates that take the longest to register in downstream crates.
2024-03-16 21:35:10 +01:00
Bryanskiy
b2ed9d0911 Delegation: fix ICE on duplicated associative items 2024-03-16 21:03:36 +03:00
bjorn3
6697186f59 Merge commit '4cf4ffc6ba514f171b3f52d1c731063e4fc45be3' into sync_cg_clif-2024-03-16 2024-03-16 17:23:11 +00:00
John Kåre Alsaker
38518c44b0 Print the crates not available as static 2024-03-16 17:12:24 +01:00
Erik Desjardins
a7d4258e00 revert changes and just delete the fixme
Avoiding the naming didn't have any meaningful perf impact.
2024-03-16 11:11:53 -04:00
will
7c4b07d5e8 added pretty_print_const_expr 2024-03-17 01:38:45 +11:00
klensy
4bfc48585d less useless array builds in imported_source_file 2024-03-16 12:31:57 +03:00
bors
774ae599ab Auto merge of #122309 - g-yziquel:issue-122262, r=saethlin
Use `MAP_PRIVATE` (not unsound-prone `MAP_SHARED`)

Solves https://github.com/rust-lang/rust/issues/122262
2024-03-16 09:19:08 +00:00
daxpedda
873a0f264e
Add wasm_c_abi future-incompat lint 2024-03-16 09:57:15 +01:00
bors
c563f2ee79 Auto merge of #122371 - oli-obk:visit_nested_body, r=tmiasko
Stop walking the bodies of statics for reachability, and evaluate them instead

cc `@saethlin` `@RalfJung`

cc #119214

This reuses the `DefIdVisitor` from `rustc_privacy`, because they basically try to do the same thing.

This PR's changes can probably be extended to constants, too, but let's tackle that separately, it's likely more involved.
2024-03-16 04:35:02 +00: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
León Orell Valerian Liehr
a37fe00ea1
Remove obsolete parameter speculative from instantiate_poly_trait_ref 2024-03-16 02:33:21 +01:00
Josh Stone
8d374b1f2a Install the bad-alloc handler before fatal errors
The bad-alloc installer was incorrectly asserting that the other handler
isn't set yet, instead of checking its own, but we can avoid that by
changing the order we install them.

Ref: https://github.com/llvm/llvm-project/issues/83040
2024-03-15 16:49:08 -07:00
Josh Stone
adf57a75d5 Aggressively ignore write errors during bad-alloc 2024-03-15 16:48:16 -07:00
Josh Stone
0ade5a11f5 Register LLVM handlers for bad-alloc / OOM
LLVM's default bad-alloc handler may throw if exceptions are enabled,
and `operator new` isn't hooked at all by default. Now we register our
own handler that prints a message similar to fatal errors, then aborts.
We also call the function that registers the C++ `std::new_handler`.
2024-03-15 15:49:06 -07:00
Guillaume Yziquel
3fc5ed8067 Issue 122262: MAP_PRIVATE for more reliability on virtualised filesystems.
Adding support of quirky filesystems occuring in virtualised settings not
having full POSIX support for memory mapped files. Example: current virtiofs
with cache disabled, occuring in Incus/LXD or Kata Containers. Has been
hitting various virtualised filesystems since 2016, depending on their levels
of maturity at the time. The situation will perhaps improve when virtiofs DAX
support patches will have made it into the qemu mainline.

On a reliability level, using the MAP_PRIVATE sycall flag instead of the
MAP_SHARED syscall flag for the mmap() system call does have some undefined
behaviour when the caller update the memory mapping of the mmap()ed file, but
MAP_SHARED does allow not only the calling process but other processes to
modify the memory mapping. Thus, in the current context, using MAP_PRIVATE
copy-on-write is marginally more reliable than MAP_SHARED.

This discussion of reliability is orthogonal to the type system enforced safety
policy of rust, which does not claim to handle memory modification of memory
mapped files triggered through the operating system and not the running rust
process.
2024-03-15 18:31:07 -04:00
bors
c67326b063 Auto merge of #122571 - matthiaskrgr:rollup-36wwovk, r=matthiaskrgr
Rollup of 6 pull requests

Successful merges:

 - #122254 (Detect calls to .clone() on T: !Clone types on borrowck errors)
 - #122495 (Visually mark 👻hidden👻 items with document-hidden-items)
 - #122543 (Add `#![rustc_never_type_mode = "..."]` crate-level attribute to allow experimenting)
 - #122560 (Safe Transmute: Use 'not yet supported', not 'unspecified' in errors)
 - #122562 (Mention labelled blocks in `break` docs)
 - #122563 (CI: cache PR CI Docker builds)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-03-15 21:18:36 +00:00
Matthias Krüger
b482523607
Rollup merge of #122560 - jswrenn:not-yet-supported, r=compiler-errors
Safe Transmute: Use 'not yet supported', not 'unspecified' in errors

We can (and will) support analyzing the transmutability of types whose layouts aren't completely specified by its repr. This change ensures that the error messages remain sensible after this support lands.

r? ``@compiler-errors``
2024-03-15 21:51:57 +01:00
Matthias Krüger
82d5b568b8
Rollup merge of #122543 - WaffleLapkin:never-flags, r=compiler-errors
Add `#![rustc_never_type_mode = "..."]` crate-level attribute to allow experimenting

Demonstrating how different approaches with the never type work is somewhat hard when you can't actually provide a runnable example. Let's add features that change the fallback behavior.

This adds `#![rustc_never_type_mode = "no_fallback"]` and `#![rustc_never_type_mode = "fallback_to_never"]`, but I also plan to add others (in future PRs).

cc ``@traviscross``
r? ``@compiler-errors``
2024-03-15 21:51:57 +01: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
Erik Desjardins
129b5e48f0 avoid naming LLVM basic blocks when fewer_names is true 2024-03-15 15:53:49 -04:00
bors
1ca424ca43 Auto merge of #122341 - compiler-errors:alias-wfness, r=lcnr
Consolidate WF for aliases

Make RPITs/TAITs/weak (type) aliases/projections all enforce:
1. their nominal predicates
2. their args are WF

This possibly does extra work, but is also nice for consistency sake.

r? lcnr
2024-03-15 19:19:35 +00:00
Jack Wrenn
107807d393 Safe Transmute: lowercase diagnostics 2024-03-15 17:55:49 +00:00
Maybe Waffle
adfdd273ae Add rustc_never_type_mode = "no_fallback" 2024-03-15 17:48:26 +00:00
Maybe Waffle
19bc337063 Add rustc_never_type_mode crate-level attribute to allow experimenting 2024-03-15 17:48:26 +00:00
Jack Wrenn
dc35339514 Safe Transmute: Use 'not yet supported', not 'unspecified' in errors
We can (and will) support analyzing the transmutability of types
whose layouts aren't completely specified by its repr. This change
ensures that the error messages remain sensible after this support
lands.
2024-03-15 17:42:29 +00:00
bors
72d78970ec Auto merge of #122555 - GuillaumeGomez:rollup-tr6wu54, r=GuillaumeGomez
Rollup of 6 pull requests

Successful merges:

 - #114651 (rustdoc: add `--test-builder-wrapper` arg to support wrappers such as RUSTC_WRAPPER when building doctests)
 - #122468 (Cleanup `MirBorrowckCtxt::prefixes`)
 - #122496 (Greatly reduce GCC build logs)
 - #122512 (Cursor.rs documentation fix)
 - #122513 (hir: Remove `opt_local_def_id_to_hir_id` and `opt_hir_node_by_def_id`)
 - #122530 (less symbol interner locks)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-03-15 16:39:42 +00:00
Guillaume Gomez
6ec4092eaf
Rollup merge of #122530 - klensy:as_str, r=fee1-dead
less symbol interner locks

This reduces instructions under 1% (in rustdoc run), but essentially free.
2024-03-15 17:24:10 +01:00
Guillaume Gomez
3d4464d4d7
Rollup merge of #122513 - petrochenkov:somehir4, r=fmease
hir: Remove `opt_local_def_id_to_hir_id` and `opt_hir_node_by_def_id`

Also replace a few `hir_node()` calls with `hir_node_by_def_id()`.

Follow up to https://github.com/rust-lang/rust/pull/120943.
2024-03-15 17:24:09 +01:00
Guillaume Gomez
5c0012b953
Rollup merge of #122468 - beepster4096:borrowck_prefixes_cleanup, r=Nadrieril
Cleanup `MirBorrowckCtxt::prefixes`

Some of the uses of this method aren't necessary anymore and `PrefixSet::Supporting` is not used anywhere.

With `PrefixSet::Supporting` removed, this could technically be moved to an extension trait on `PlaceRef`. However, it would have to be moved back to `MirBorrowckCtxt` when the `Derefer` MIR pass is moved before borrowck so I didn't.
2024-03-15 17:24:07 +01:00
许杰友 Jieyou Xu (Joe)
85bad8d1bf
Don't trigger unused_qualifications on global paths
# Conflicts:
#	tests/ui/lint/lint-qualification.stderr
2024-03-15 14:59:05 +00:00
Ralf Jung
7be47b219d interpret/allocation: fix aliasing issue in interpreter and refactor getters a bit
- rename mutating functions to be more scary
- add a new raw bytes getter
2024-03-15 15:58:37 +01:00
bors
c5b571310d Auto merge of #121297 - michaelwoerister:set-pdb-alt-path, r=wesleywiser
link.exe: Don't embed full path to PDB file in binary.

This PR makes `rustc` unconditionally pass `/PDBALTPATH:%_PDB%` to MSVC-style linkers, causing the linker to only embed the filename of the PDB in the binary instead of the full path. This will help implement the [trim-paths RFC](https://github.com/rust-lang/rust/issues/111540) for `*-msvc` targets.

Passing `/PDBALTPATH:%_PDB%` to the linker is already done by many projects that need reproducible builds and [debugger's should still be able to find the PDB](https://learn.microsoft.com/cpp/build/reference/pdbpath) if it is in the same directory as the binary.

r? `@ghost`

Fixes https://github.com/rust-lang/rust/issues/87825
2024-03-15 14:14:34 +00:00
Maybe Waffle
75d940f637 Use do yeet () and do yeet _ instead of None? and Err(_)? in compiler
This prevents breakage when `?` no longer skews inference.
2024-03-15 11:37:42 +00:00
Maybe Waffle
defcc44238 Make unexpected always "return" PResult<()> & add unexpected_any
This prevents breakage when `?` no longer skews inference.
2024-03-15 11:36:21 +00:00
Matthias Krüger
277df5e176
Rollup merge of #122527 - fmease:clean-up-hir-ty-lowering, r=compiler-errors
Clean up AstConv

Split off from #120926 to make it only contain the renaming & (doc) comment updates.
Any changes other than that which have accumulated over time are now part of this PR.
Let's be disciplined ;) Inspired by https://github.com/rust-lang/rust/pull/120926#issuecomment-1997984483.

---

* Remove `hir_trait_to_predicates`
  * Unused since #113671
* Inline `create_args_for_ast_trait_ref`
  * Only had a single call site
  * Having it as a separate method didn't gain us anything
* Use an if-let guard somewhere to avoid unwrapping
* Avoid explicit trait object lifetimes
  * More legible, stylistic-only (the updated code is 100% semantically identical)
  * Use explicitly elided lifetimes in impl headers, they get elaborated to distinct lifetimes
  * Make use of [object lifetime defaulting](https://doc.rust-lang.org/reference/lifetime-elision.html#default-trait-object-lifetimes) for a trait object type inside of a reference type somewhere
* Use preexisting dedicated method `ItemCtxt::to_ty` over `<dyn AstConv<'_>>::ast_ty_to_ty`
* Use preexisting dedicated method `AstConv::astconv` over explicit coercions
* Simplify the function signature of `create_args_for_ast_path` and of `check_generic_arg_count`
  * In both cases redundant information was passed rendering the call sites verbose and confusing
  * No perf impact (tested in [#120926](https://github.com/rust-lang/rust/pull/120926))
* Move diagnostic method `report_ambiguous_associated_type` from `astconv` to `astconv::errors`
  * The submodule `errors` exists specifically for that purpose
  * Use it to keep the main module clean & short
2024-03-15 10:14:56 +01:00
Matthias Krüger
7a7b65abbe
Rollup merge of #122526 - Zalathar:thir-expr-docs, r=oli-obk
Docs for `thir::ExprKind::Use` and `thir::ExprKind::Let`

These docs are based on my own recent investigations; hopefully they're reasonably accurate.

`Use` was particularly puzzling to me at first, since the name is not very suggestive, and the old docs were quite cryptic.
2024-03-15 10:14:56 +01:00
Matthias Krüger
ee940f87fc
Rollup merge of #122523 - compiler-errors:ensure-associated-types, r=oli-obk
Ensure RPITITs are created before def-id freezing

From the test:

```rust
// `ty::Error` in a trait ref will silence any missing item errors, but will also
// prevent the `associated_items` query from being called before def ids are frozen.
```

Essentially, the code that checks that `impl`s have all their items (`check_impl_items_against_trait`) is also (implicitly) responsible for fetching the `associated_items` query before, but since we early return here:
c2901f5435/compiler/rustc_hir_analysis/src/check/check.rs (L732-L737)
...that means that this never happens for trait refs that reference errors.

Fixes #122518
r? oli-obk
2024-03-15 10:14:55 +01:00
Matthias Krüger
42af99383a
Rollup merge of #122515 - jieyouxu:ice-self-ty-mismatch, r=compiler-errors
Pass the correct DefId when suggesting writing the aliased Self type out

Fixes #122467.
2024-03-15 10:14:55 +01:00
Matthias Krüger
f4afbe1389
Rollup merge of #122471 - RalfJung:const-eval-span, r=oli-obk
preserve span when evaluating mir::ConstOperand

This lets us show to the user where they were using the faulty const (which can be quite relevant when generics are involved).

I wonder if we should change "erroneous constant encountered" to something like "the above error was encountered while evaluating this constant" or so, to make this more similar to what the collector emits when showing a "backtrace" of where things get monomorphized? It seems a bit strange to rely on the order of emitted diagnostics for that but it seems the collector already [does that](da8a8c9223/compiler/rustc_monomorphize/src/collector.rs (L472-L475)).
2024-03-15 10:14:54 +01:00
Matthias Krüger
e66c7e479c
Rollup merge of #122174 - notriddle:master, r=TaKO8Ki
diagnostics: suggest `Clone` bounds when noop `clone()`

Fixes #121524
2024-03-15 10:14:54 +01:00
Matthias Krüger
2b8fc6fd54
Rollup merge of #121207 - chriswailes:z-external-clangrt, r=michaelwoerister
Add `-Z external-clangrt`

This adds the unstable `-Z external-clangrt` flag that will prevent rustc from emitting linker paths for the in-tree LLVM sanitizer runtime library.
2024-03-15 10:14:53 +01:00
klensy
7ea4f35766 less symbols interner locks 2024-03-15 10:54:40 +03:00
León Orell Valerian Liehr
5beda81b71
Clean up AstConv 2024-03-15 05:06:38 +01:00
Zalathar
cac0b121b6 Docs for thir::ExprKind::Use and thir::ExprKind::Let 2024-03-15 13:11:00 +11:00
bors
ee03c286cf Auto merge of #122517 - petrochenkov:bodihash, r=oli-obk
Fill in HIR hash for associated opaque types

Fixes https://github.com/rust-lang/rust/issues/122508
2024-03-15 02:04:04 +00:00
Michael Goulet
571f945713 Ensure RPITITs are created before def-id freezing 2024-03-14 20:30:57 -04:00
bors
c2901f5435 Auto merge of #122511 - matthiaskrgr:rollup-swzilin, r=matthiaskrgr
Rollup of 10 pull requests

Successful merges:

 - #117118 ([AIX] Remove AixLinker's debuginfo() implementation)
 - #121650 (change std::process to drop supplementary groups based on CAP_SETGID)
 - #121764 (Make incremental sessions identity no longer depend on the crate names provided by source code)
 - #122212 (Copy byval argument to alloca if alignment is insufficient)
 - #122322 (coverage: Initial support for branch coverage instrumentation)
 - #122373 (Fix the conflict problem between the diagnostics fixes of lint `unnecessary_qualification`  and  `unused_imports`)
 - #122479 (Implement `Duration::as_millis_{f64,f32}`)
 - #122487 (Rename `StmtKind::Local` variant into `StmtKind::Let`)
 - #122498 (Update version of cc crate)
 - #122503 (Make `SubdiagMessageOp` well-formed)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-03-15 00:03:58 +00:00
Ralf Jung
48f2f0d725 preserve span when evaluating mir::ConstOperand 2024-03-14 21:55:07 +01:00
Vadim Petrochenkov
ef5513f278 Fill in HIR hash for associated opaque types 2024-03-14 23:29:12 +03:00
Lukas Markeffsky
ee66acbea8 use a let chain 2024-03-14 21:28:48 +01:00
Lukas Markeffsky
8fe99f57a4 remove unnecessary sized checks 2024-03-14 21:28:48 +01:00
Lukas Markeffsky
8ad94111ad clean up ADT sized constraint computation 2024-03-14 21:28:47 +01:00
Lukas Markeffsky
0e7e1bfdbc make Representability::Infinite carry ErrorGuaranteed 2024-03-14 20:52:13 +01:00
许杰友 Jieyou Xu (Joe)
87ced1561f
Pass the correct DefId when suggesting writing the aliased Self type out 2024-03-14 19:39:15 +00:00
Vadim Petrochenkov
89b536dbc8 hir: Remove opt_local_def_id_to_hir_id and opt_hir_node_by_def_id
Also replace a few `hir_node()` calls with `hir_node_by_def_id()`
2024-03-14 22:34:24 +03:00
Matthias Krüger
6ce3110ce9
Rollup merge of #122503 - compiler-errors:trait-alias-wf, r=Nilstrieb
Make `SubdiagMessageOp` well-formed

`WF(Diag<'_, G>)` requires `G: EmissionGuarantee`, but we don't currently check this is true due to limitations in the solver. Probably still worth enforcing.

r? `@nnethercote` (or anyone can r+ this, really)
2024-03-14 20:00:22 +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
b200108bc5
Rollup merge of #122373 - surechen:fix_121331, r=petrochenkov
Fix the conflict problem between the diagnostics fixes of lint `unnecessary_qualification`  and  `unused_imports`

fixes #121331

For an `item` that triggers lint unnecessary_qualification, if the `use item` which imports this item is also trigger unused import, fixing the two lints at the same time may lead to the problem that the `item` cannot be found.
This PR will avoid reporting lint unnecessary_qualification when conflict occurs.

r? ``@petrochenkov``
2024-03-14 20:00:20 +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
Matthias Krüger
722514f466
Rollup merge of #122212 - erikdesjardins:byval-align2, r=wesleywiser
Copy byval argument to alloca if alignment is insufficient

Fixes #122211

"Ignore whitespace" recommended.
2024-03-14 20:00:18 +01:00
Matthias Krüger
4dff106433
Rollup merge of #121764 - Zoxc:incr-sess-no-source, r=oli-obk
Make incremental sessions identity no longer depend on the crate names provided by source code

This makes incremental sessions identity no longer depend on the crate names provided by source code, implementing
https://github.com/rust-lang/compiler-team/issues/726.

r? ````@oli-obk````
2024-03-14 20:00:18 +01:00
Matthias Krüger
68ca795286
Rollup merge of #117118 - bzEq:aix-linker, r=wesleywiser
[AIX] Remove AixLinker's debuginfo() implementation

AIX ld's `-s` option doesn't perfectly fit` debuginfo()`'s semantics and may unexpectedly remove metadata in shared libraries. Remove the implementation of `AixLinker` and suggest user to use `strip` utility instead.
2024-03-14 20:00:17 +01:00
bors
fd27e8745f Auto merge of #119849 - lcnr:eagerly-instantiate-binders, r=compiler-errors
more eagerly instantiate binders

The old solver sometimes incorrectly used `sub`, change it to explicitly instantiate binders and use `eq` instead. While doing so I also moved the instantiation before the normalize calls. This caused some observable changes, will explain these inline. This PR therefore requires a crater run and an FCP.

r? types
2024-03-14 18:58:53 +00:00
Chris Wailes
f46aceaaf7 Restore correct version of comment and fix logic bug 2024-03-14 11:06:39 -07:00
Trevor Gross
e782d27ec6 Add feature gates for f16 and f128
Includes related tests and documentation pages.

Michael Goulet: Don't issue feature error in resolver for f16/f128
unless finalize

Co-authored-by: Michael Goulet <michael@errs.io>
2024-03-14 13:32:54 -04:00
Michael Goulet
6e4cd8b7cc Make SubdiagMessageOp well-formed 2024-03-14 13:13:08 -04:00
bors
30f74ff0dc Auto merge of #122497 - matthiaskrgr:rollup-pg9ux4r, r=matthiaskrgr
Rollup of 10 pull requests

Successful merges:

 - #119029 (Avoid closing invalid handles)
 - #122238 (Document some builtin impls in the next solver)
 - #122247 (rustdoc-search: depth limit `T<U>` -> `U` unboxing)
 - #122287 (add test ensuring simd codegen checks don't run when a static assertion failed)
 - #122368 (chore: remove repetitive words)
 - #122397 (Various cleanups around the const eval query providers)
 - #122406 (Fix WF for `AsyncFnKindHelper` in new trait solver)
 - #122477 (Change some attribute to only_local)
 - #122482 (Ungate the `UNKNOWN_OR_MALFORMED_DIAGNOSTIC_ATTRIBUTES` lint)
 - #122490 (Update build instructions for OpenHarmony)

Failed merges:

 - #122471 (preserve span when evaluating mir::ConstOperand)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-03-14 16:36:02 +00:00
Markus Reiter
40f8227d6d
Fix lint. 2024-03-14 17:34:57 +01:00
lcnr
323069fd59 rebase 2024-03-14 17:19:40 +01:00
lcnr
24a1729566 eagerly instantiate binders to avoid relying on sub 2024-03-14 17:19:40 +01:00
Michael Goulet
04524c8f6a Consolidate WF for aliases 2024-03-14 12:17:00 -04:00
Matthias Krüger
c0fd2db49a
Rollup merge of #122482 - weiznich:fix/122446, r=compiler-errors
Ungate the `UNKNOWN_OR_MALFORMED_DIAGNOSTIC_ATTRIBUTES` lint

This was missed during stablisation of the `#[diagnostic]` attribute namespace.

Fixes #122446
2024-03-14 15:44:36 +01:00
Matthias Krüger
8303c6ae48
Rollup merge of #122477 - surechen:change_attribute_only_local_20240314, r=lcnr
Change some attribute to only_local

Modified according to https://github.com/rust-lang/compiler-team/issues/505.

r? `@lcnr`
2024-03-14 15:44:36 +01:00
Matthias Krüger
54b73006c6
Rollup merge of #122406 - compiler-errors:next-solver-asynckind-wf, r=lcnr
Fix WF for `AsyncFnKindHelper` in new trait solver

`to_opt_closure_kind` ICEs when it sees placeholders... so don't do that

no test b/c I'm too lazy to write a no-core test for this, but I could be convinced otherwise

r? lcnr
2024-03-14 15:44:35 +01:00
Matthias Krüger
b4dffc9926
Rollup merge of #122397 - oli-obk:machine-read-hook2, r=RalfJung
Various cleanups around the const eval query providers

r? `@RalfJung`

after this, working on running validation before interning starts with swapping the order of two lines of code
2024-03-14 15:44:34 +01:00
Matthias Krüger
1dce191441
Rollup merge of #122368 - pavedroad:master, r=oli-obk
chore: remove repetitive words
2024-03-14 15:44:34 +01:00
Matthias Krüger
6a4dd19ade
Rollup merge of #122287 - RalfJung:simd-static-assert, r=pnkfelix
add test ensuring simd codegen checks don't run when a static assertion failed

stdarch relies on this to ensure that SIMD indices are in bounds.

I would love to know why this works, but I can't figure out where codegen decides to not codegen a function if a required-const does not evaluate. `@oli-obk` `@bjorn3` do you have any idea?
2024-03-14 15:44:33 +01:00
Matthias Krüger
7997ef4eba
Rollup merge of #122238 - fee1-dead-contrib:builtin-impl-next-solver-dox, r=lcnr
Document some builtin impls in the next solver

This does not cover all builtin impls, but ones that I were able to go over within a cycle.

r? `@lcnr`

Let me know if the place isn't correct for these, or if you'd like me to change how the impls are presented ^^
2024-03-14 15:44:32 +01:00
bors
fe61575228 Auto merge of #120943 - petrochenkov:somehir3, r=oli-obk
Create some minimal HIR for associated opaque types

`LocalDefId`s for opaque types in traits and impls are created after AST -> HIR lowering, so they don't have corresponding HIR and return their various properties through fed queries.

In this PR I also feed some core HIR-related queries for these `LocalDefId`s (which happen to be HIR owners).
As a result all `LocalDefId`s now have corresponding `HirId`s and HIR nodes, and "optional" methods like `opt_local_def_id_to_hir_id` and `opt_hir_node_by_def_id` can be removed.

Follow up to https://github.com/rust-lang/rust/pull/120206.
2024-03-14 14:28:58 +00:00
Oli Scherer
746e4eff26 Test and implement reachability for trait objects and generic parameters of functions 2024-03-14 14:10:45 +00:00
Oli Scherer
8332b47cae Stop walking the bodies of statics for reachability, and evaluate them instead 2024-03-14 14:10:45 +00:00
Oli Scherer
a316c21dc8 Rename some things around validation error reporting to signal that it is in fact about validation failures 2024-03-14 12:21:35 +00:00
Oli Scherer
16046c77aa Move the entire success path into eval_body_using_ecx 2024-03-14 12:21:29 +00:00
Oli Scherer
2e6c4900b6 Move validation into eval_body_using_ecx 2024-03-14 12:21:23 +00:00
Oli Scherer
cc7e0b2200 Share the InterpCx creation between static and const evaluation 2024-03-14 12:21:18 +00:00
Oli Scherer
02a0ac8058 Remove an argument that can be computed cheaply 2024-03-14 12:21:12 +00:00
Oli Scherer
d3b7b558aa Directly pass in the stack instead of computing it from a machine 2024-03-14 12:21:06 +00:00
Oli Scherer
d2d2bd2736 Move generate_stacktrace_from_stack away from InterpCx to avoid having to know the Machine type 2024-03-14 12:20:58 +00:00
Deadbeef
69d781abef move impl documentation to their actual locations 2024-03-14 20:18:04 +08:00
Guillaume Gomez
a4e0e50a3f Rename hir::StmtKind::Local into hir::StmtKind::Let 2024-03-14 12:42:04 +01:00
Guillaume Gomez
ca9f0630a9 Rename ast::StmtKind::Local into ast::StmtKind::Let 2024-03-14 12:42:04 +01:00
Oli Scherer
6b936b6c08 Move InterpCx into eval_in_interpreter 2024-03-14 11:40:42 +00:00
Oli Scherer
8b8efd157b Move error handling into const_validate_mplace 2024-03-14 11:40:36 +00:00
Oli Scherer
93888cd0a4 Move only usage of take_static_root_alloc to its definition and inline it 2024-03-14 11:40:30 +00:00
Oli Scherer
d6c999754c Generalize eval_in_interpreter with a helper trait 2024-03-14 11:40:23 +00:00
Oli Scherer
71f1943cbf Fix accidental re-addition of removed code in a previous PR 2024-03-14 11:39:27 +00:00
Matthias Krüger
0286591d59
Rollup merge of #122416 - Zalathar:levels, r=petrochenkov
Various style improvements to `rustc_lint::levels`

While reading this file, I noticed a few opportunities to make things a little nicer:

- Replace some nested if-let with let-chains
- Tweak a match pattern to allow shorthand struct syntax
- Fuse an `is_empty` check with getting the last element
- Merge some common code that emits `MalformedAttribute` and continues
- Format `"{tool}::{name}"` in a way that's consistent with other match arms
- Replace if-let-else-panic with let-else
- Use early-exit to flatten a method body

Some of these changes cause indentation churn, so ignoring whitespace is recommended.
2024-03-14 11:09:59 +01:00
Matthias Krüger
bd53d1eee3
Rollup merge of #122405 - celinval:smir-new-const, r=oli-obk
Add methods to create StableMIR constant

I've been experimenting with transforming the StableMIR to instrument the code with potential UB checks.

The modified body will only be used by our analysis tool, however, constants in StableMIR must be backed by rustc constants. Thus, I'm adding a few functions to build constants, such as building string and other primitives.

One question I have is whether we should create a global allocation instead for strings.

r? ``````@oli-obk``````
2024-03-14 11:09:58 +01:00
Matthias Krüger
7a744af83e
Rollup merge of #121899 - shepmaster:dead-code-docs, r=wesleywiser
Document how removing a type's field can be bad and what to do instead

Related to #119645
2024-03-14 11:09:57 +01:00
Matthias Krüger
fce6e752ab
Rollup merge of #120699 - nnethercote:rm-useless-TRACK_DIAGNOSTIC-calls, r=oli-obk
Document `TRACK_DIAGNOSTIC` calls.

r? ```````@cjgillot```````
2024-03-14 11:09:57 +01:00
Georg Semmler
25411113c1
Ungate the UNKNOWN_OR_MALFORMED_DIAGNOSTIC_ATTRIBUTES lint
This was missed during stablisation of the `#[diagnostic]` attribute
namespace.

Fixes #122446
2024-03-14 10:49:28 +01:00
surechen
5dd44f43c7 change some attribute to only_local 2024-03-14 17:12:39 +08:00
Michael Wörister
3c49fe0cbd link.exe: don't embed full path to PDB file in binary. 2024-03-14 09:54:29 +01:00
bors
cb580ff677 Auto merge of #122243 - RalfJung:local-place-sanity-check, r=oli-obk
interpret: ensure that Place is never used for a different frame

We store the address where the stack frame stores its `locals`. The idea is that even if we pop and push, or switch to a different thread with a larger number of frames, then the `locals` address will most likely change so we'll notice that problem. This is made possible by some recent changes by `@WaffleLapkin,` where we no longer use `Place` across things that change the number of stack frames.

I made these debug assertions for now, just to make sure this can't cost us any perf.

The first commit is unrelated but it's a one-line comment change so it didn't warrant a separate PR...

r? `@oli-obk`
2024-03-14 07:28:07 +00:00
Zalathar
060c7ce7e9 coverage: -Zcoverage-options=branch is no longer a placeholder 2024-03-14 17:19:06 +11:00
Zalathar
31d0b50178 coverage: Include recorded branch info in coverage instrumentation 2024-03-14 17:19:02 +11:00
Trevor Gross
dc65095298 Enable f16 and f128 in HIR 2024-03-14 00:40:22 -05: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
bors
6f3eb1ce3d Auto merge of #122454 - matthiaskrgr:rollup-xbmufdc, r=matthiaskrgr
Rollup of 11 pull requests

Successful merges:

 - #122422 (compiletest: Allow `only-unix` in test headers)
 - #122424 (fix: typos)
 - #122425 (Increase timeout for new bors bot)
 - #122426 (Fix StableMIR `WrappingRange::is_full` computation)
 - #122429 (Add Exploit Mitigations PG to triagebot.toml)
 - #122430 (Generate link to `Local` in `hir::Let` documentation)
 - #122434 (pattern analysis: rename a few types)
 - #122437 (pattern analysis: remove `MaybeInfiniteInt::JustAfterMax`)
 - #122438 (Safe Transmute: Require that source referent is smaller than destination)
 - #122442 (extend docs of -Zprint-mono-items)
 - #122449 (Delay a bug for stranded opaques)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-03-14 04:54:37 +00:00
bors
5ac0b2d021 Auto merge of #122347 - oli-obk:track_errors13, r=compiler-errors
Revert "Auto merge of #122140 - oli-obk:track_errors13, r=davidtwco"

This reverts commit 65cd843ae0, reversing changes made to d255c6a57c.

reverts https://github.com/rust-lang/rust/pull/122140

It was a large regression in wall time due to trashing CPU caches
2024-03-14 02:54:10 +00:00
surechen
1a81a941ad fixes #121331 2024-03-14 09:54:42 +08:00
bors
c7fed9f854 Auto merge of #122204 - pnkfelix:downgrade-const-eval-dnagling-ptr-in-final-to-future-incompat-lint, r=wesleywiser
Downgrade const eval dangling ptr in final to future incompat lint

Short term band-aid for issue #121610, downgrading the prior hard error to a future-incompat lint (tracked in issue #122153).

Note we should not mark #121610 as resolved until after this (or something analogous) is beta backported.
2024-03-14 00:06:26 +00:00
Esteban Küber
0953608deb Account for UnOps in borrowck message 2024-03-13 23:05:17 +00:00
Esteban Küber
b367c25367 Tweak wording 2024-03-13 23:05:17 +00:00
Esteban Küber
2d3435b4df 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;
   |
```
2024-03-13 23:05:11 +00:00
beepster4096
a5cb61d39b cleanup prefixes iterator 2024-03-13 12:34:58 -07:00
Matthias Krüger
c52ce4eabb
Rollup merge of #122449 - compiler-errors:stranded-opaque, r=oli-obk
Delay a bug for stranded opaques

r? oli-obk

Fixes #122445
2024-03-13 20:01:58 +01:00
Matthias Krüger
8d2f79c3f1
Rollup merge of #122442 - RalfJung:print-mono-items, r=compiler-errors
extend docs of -Zprint-mono-items

Currently the values one can set this to are not documented anywhere.

I think ideally this flag wouldn't overwrite the collector's behavior, a "print" flag should just print what happens but not change what happens. But our codegen-units tests rely on being able to collect all items without the other side-effects of `-C link-dead-code` and I can't tell whether that reliance is incidental or crucial, so I'm not touching this and just documenting the (messy) status quo.
2024-03-13 20:01:58 +01:00
Matthias Krüger
89c3fa92d4
Rollup merge of #122438 - jswrenn:check-referent-size, r=compiler-errors
Safe Transmute: Require that source referent is smaller than destination

`BikeshedIntrinsicFrom` currently models transmute-via-union; i.e., it attempts to provide a `where` bound for this function:
```rust
pub unsafe fn transmute_via_union<Src, Dst>(src: Src) -> Dst {
    use core::mem::*;

    #[repr(C)]
    union Transmute<T, U> {
        src: ManuallyDrop<T>,
        dst: ManuallyDrop<U>,
    }

    let transmute = Transmute { src: ManuallyDrop::new(src) };

    // SAFETY: The caller must guarantee that the transmutation is safe.
    let dst = transmute.dst;

    ManuallyDrop::into_inner(dst)
}
```
A quirk of this model is that it admits padding extensions in value-to-value transmutation: The destination type can be bigger than the source type, so long as the excess consists of uninitialized bytes. However, this isn't permissible for reference-to-reference transmutations (introduced in #110662) — extra referent bytes cannot come from thin air.

This PR patches our analysis for reference-to-reference transmutations to require that the destination referent is no larger than the source referent.

r? `@compiler-errors`
2024-03-13 20:01:58 +01:00
Matthias Krüger
5c2aa6dc6f
Rollup merge of #122437 - Nadrieril:no-after-max, r=compiler-errors
pattern analysis: remove `MaybeInfiniteInt::JustAfterMax`

It was inherited from before half-open ranges, but it doesn't pull its weight anymore. We lose a tiny bit of diagnostic precision as can be seen in the test. I'm generally in favor of half-open ranges over explicit `x..=MAX` ranges anyway.
2024-03-13 20:01:57 +01:00
Matthias Krüger
b3376bb92f
Rollup merge of #122434 - Nadrieril:renames, r=compiler-errors
pattern analysis: rename a few types

A few long overdue renames. `ValidityConstraint` was supposed to serve double purpose but I don't need that anymore. I don't know what I was thinking with `TypeCx` I think I was trying to be clever. That's fixed now 😄

r? ``@compiler-errors``
2024-03-13 20:01:57 +01:00
Matthias Krüger
b84d1b8ec9
Rollup merge of #122430 - GuillaumeGomez:link-to-local, r=TaKO8Ki
Generate link to `Local` in `hir::Let` documentation

This PR adds a missing link generation to `Local` type.
2024-03-13 20:01:56 +01:00
Matthias Krüger
96a41ce513
Rollup merge of #122426 - celinval:smir-fix-full, r=oli-obk
Fix StableMIR `WrappingRange::is_full` computation

`WrappingRange::is_full` computation assumed that to be full the range couldn't wrap, which is not necessarily true.

For example, a range of 1..=0 is a valid representation of a full wrapping range.
2024-03-13 20:01:55 +01:00
Matthias Krüger
ff5e1eb8ac
Rollup merge of #122424 - testwill:typos, r=michaelwoerister
fix: typos
2024-03-13 20:01:54 +01:00