Commit Graph

1929 Commits

Author SHA1 Message Date
Eric Holk
7b7992fbcf
Begin experimental support for pin reborrowing
This commit adds basic support for reborrowing `Pin` types in argument
position. At the moment it only supports reborrowing `Pin<&mut T>` as
`Pin<&mut T>` by inserting a call to `Pin::as_mut()`, and only in
argument position (not as the receiver in a method call).
2024-09-18 12:36:31 -07:00
León Orell Valerian Liehr
03e8b6bbfa
Rollup merge of #130294 - nnethercote:more-lifetimes, r=lcnr
Lifetime cleanups

The last commit is very opinionated, let's see how we go.

r? `@oli-obk`
2024-09-14 18:12:13 +02:00
Matthias Krüger
c5e0f9ae42
Rollup merge of #130297 - nnethercote:dataflow-cleanups, r=cjgillot
Dataflow cleanups

r? `@cjgillot`
2024-09-13 18:25:45 +02:00
Nicholas Nethercote
bb943f93ff Rename FlowState as Domain.
Because that's what it is; no point having a different name for it.
2024-09-13 16:27:24 +10:00
Nicholas Nethercote
8d32578fe1 Rename and reorder lots of lifetimes.
- Replace non-standard names like 's, 'p, 'rg, 'ck, 'parent, 'this, and
  'me with vanilla 'a. These are cases where the original name isn't
  really any more informative than 'a.
- Replace names like 'cx, 'mir, and 'body with vanilla 'a when the lifetime
  applies to multiple fields and so the original lifetime name isn't
  really accurate.
- Put 'tcx last in lifetime lists, and 'a before 'b.
2024-09-13 15:46:20 +10:00
Nicholas Nethercote
606b9cb406 Rename some lifetimes.
Giving them more typical names.
2024-09-13 15:36:55 +10:00
bors
a5efa01895 Auto merge of #107251 - dingxiangfei2009:let-chain-rescope, r=jieyouxu
Rescope temp lifetime in if-let into IfElse with migration lint

Tracking issue #124085

This PR shortens the temporary lifetime to cover only the pattern matching and consequent branch of a `if let`.

At the expression location, means that the lifetime is shortened from previously the deepest enclosing block or statement in Edition 2021. This warrants an Edition change.

Coming with the Edition change, this patch also implements an edition lint to warn about the change and a safe rewrite suggestion to preserve the 2021 semantics in most cases.

Related to #103108.
Related crater runs: https://github.com/rust-lang/rust/pull/129466.
2024-09-13 03:47:30 +00:00
Stuart Cook
3ba12756d3
Rollup merge of #130235 - compiler-errors:nested-if, r=michaelwoerister
Simplify some nested `if` statements

Applies some but not all instances of `clippy::collapsible_if`. Some ended up looking worse afterwards, though, so I left those out. Also applies instances of `clippy::collapsible_else_if`

Review with whitespace disabled please.
2024-09-12 20:37:16 +10:00
Jubilee
a31a8fe0cf
Rollup merge of #130114 - eduardosm:needless-returns, r=compiler-errors
Remove needless returns detected by clippy in the compiler
2024-09-11 15:53:22 -07:00
Michael Goulet
af8d911d63 Also fix if in else 2024-09-11 17:24:01 -04:00
Michael Goulet
954419aab0 Simplify some nested if statements 2024-09-11 13:45:23 -04:00
Ding Xiang Fei
89682a5313
downgrade borrowck suggestion level due to possible span conflict 2024-09-11 04:10:04 +08:00
Ding Xiang Fei
f93df1f7dc
rescope temp lifetime in let-chain into IfElse
apply rules by span edition
2024-09-11 04:10:00 +08:00
Eduardo Sánchez Muñoz
0b20ffcb63 Remove needless returns detected by clippy in the compiler 2024-09-09 13:32:22 +02:00
Nicholas Nethercote
28a6dc4d1e Rename some lifetimes.
Give them the names used in most places.
2024-09-09 16:25:44 +10:00
Nicholas Nethercote
3fe7dd6893 Remove unnecessary lifetimes in dataflow structs.
There are four related dataflow structs: `MaybeInitializedPlaces`,
`MaybeUninitializedPlaces`, and `EverInitializedPlaces`,
`DefinitelyInitializedPlaces`. They all have a `&Body` and a
`&MoveData<'tcx>` field. The first three use different lifetimes for the
two fields, but the last one uses the same lifetime for both.

This commit changes the first three to use the same lifetime, removing
the need for one of the lifetimes. Other structs that also lose a
lifetime as a result of this are `LivenessContext`, `LivenessResults`,
`InitializationData`.

It then does similar things in various other structs.
2024-09-09 16:14:18 +10:00
Matthias Krüger
0180b8fff0
Rollup merge of #129969 - GrigorenkoPV:boxed-ty, r=compiler-errors
Make `Ty::boxed_ty` return an `Option`

Looks like a good place to use Rust's type system.

---

Most of 4ac7bcbaad/compiler/rustc_middle/src/ty/sty.rs (L971-L1963) looks like it could be moved to `TyKind` (then I guess  `Ty` should be made to deref to `TyKind`).
2024-09-06 07:33:58 +02:00
Matthias Krüger
e903b29dc3
Rollup merge of #129021 - compiler-errors:ptr-cast-outlives, r=lcnr
Check WF of source type's signature on fn pointer cast

This PR patches the implied bounds holes slightly for #129005, #25860.

Like most implied bounds related unsoundness fixes, this isn't complete w.r.t. higher-ranked function signatures, but I believe it implements a pretty good heuristic for now.

### What does this do?

This PR makes a partial patch for a soundness hole in a `FnDef` -> `FnPtr` "reifying" pointer cast where we were never checking that the signature we are casting *from* is actually well-formed. Because of this, and because `FnDef` doesn't require its signature to be well-formed (just its predicates must hold), we are essentially allowed to "cast away" implied bounds that are assumed within the body of the `FnDef`:

```
fn foo<'a, 'b, T>(_: &'a &'b (), v: &'b T) -> &'a T { v }

fn bad<'short, T>(x: &'short T) -> &'static T {
    let f: fn(_, &'short T) -> &'static T = foo;
    f(&&(), x)
}
```

In this example, subtyping ends up casting the `_` type (which should be `&'static &'short ()`) to some other type that no longer serves as a "witness" to the lifetime relationship `'short: 'static` which would otherwise be required for this call to be WF. This happens regardless of if `foo`'s lifetimes are early- or late-bound.

This PR implements two checks:
1. We check that the signature of the `FnDef` is well-formed *before* casting it. This ensures that there is at least one point in the MIR where we ensure that the `FnDef`'s implied bounds are actually satisfied by the caller.
2. Implements a special case where if we're casting from a higher-ranked `FnDef` to a non-higher-ranked, we instantiate the binder of the `FnDef` with *infer vars* and ensure that it is a supertype of the target of the cast.

The (2.) is necessary to validate that these pointer casts are valid for higher-ranked `FnDef`. Otherwise, the example above would still pass even if `help`'s `'a` lifetime were late-bound.

### Further work

The WF checks for function calls are scattered all over the MIR. We check the WF of args in call terminators, we check the WF of `FnDef` when we create a `const` operand referencing it, and we check the WF of the return type in #115538, to name a few.

One way to make this a bit cleaner is to simply extend #115538 to always check that the signature is WF for `FnDef` types. I may do this as a follow-up, but I wanted to keep this simple since this leads to some pretty bad NLL diagnostics regressions, and AFAICT this solution is *complete enough*.

### Crater triage

Done here: https://github.com/rust-lang/rust/pull/129021#issuecomment-2297702647

r? lcnr
2024-09-06 07:33:56 +02:00
Pavel Grigorenko
f6e8a84eea Make Ty::boxed_ty return an Option 2024-09-06 00:30:36 +03:00
Michael Goulet
e8472e84e3 Check unnormalized signature on pointer cast 2024-09-05 06:37:38 -04:00
Folkert de Vries
49e3b9a2d2 fix ICE when asm_const and const_refs_to_static are combined 2024-09-04 20:06:38 +02:00
Folkert de Vries
f7679d0507 propagate tainted_by_errors in MirBorrowckCtxt::emit_errors 2024-09-04 20:06:33 +02:00
Alexander Cyon
ac69544a17
chore: Fix typos in 'compiler' (batch 1) 2024-09-02 07:42:38 +02:00
Matthias Krüger
7d025bb63d
Rollup merge of #129767 - nnethercote:rm-extern-crate-tracing-4, r=jieyouxu
Remove `#[macro_use] extern crate tracing`, round 4

Because explicit importing of macros via use items is nicer (more standard and readable) than implicit importing via #[macro_use]. Continuing the work from #124511, #124914, and #125434. After this PR no `rustc_*` crates use `#[macro_use] extern crate tracing` except for `rustc_codegen_gcc` which is a special case and I will do separately.

r? ```@jieyouxu```
2024-08-31 14:46:11 +02:00
Nicholas Nethercote
67556eca99 Remove #[macro_use] extern crate tracing from rustc_borrowck. 2024-08-30 17:14:53 +10:00
Rémy Rakic
dff3d3588d add borrows to NLL MIR dumps
explicitly disable `-Zmir-include-spans` in mir-opt tests

This will override the NLL default of true, and keep the blessed dumps
easier to work with.
2024-08-30 07:14:31 +00:00
Rémy Rakic
f3f5b4dcf2 refactor NLL MIR dump entry point 2024-08-30 07:14:31 +00:00
Rémy Rakic
92e1046502 enable extra comments in NLL MIR dumps 2024-08-30 07:14:31 +00:00
Matthias Krüger
53f5294c0f
Rollup merge of #129340 - stephen-lazaro:u/slazaro/issue-129274, r=compiler-errors
Remove Duplicate E0381 Label

Aims to resolve https://github.com/rust-lang/rust/issues/129274, and adds a test for the case.

Essentially, we are duplicating this span for some reason. For now, I'm just using a set to collect the spans rather than the vec. I imagine there's probably no real reason to inspect duplicates in this area, but if I'm wrong I can adjust to collect "seen spans" in just the point where this label is applied.

I'm not sure why it's producing duplicate spans. Looks like this has been this way for a while? I think it gives the duplicate label on 1.75.0 for example.
2024-08-27 00:42:00 +02:00
Matthias Krüger
110c3df7fd
Rollup merge of #126013 - nnethercote:unreachable_pub, r=Urgau
Add `#[warn(unreachable_pub)]` to a bunch of compiler crates

By default `unreachable_pub` identifies things that need not be `pub` and tells you to make them `pub(crate)`. But sometimes those things don't need any kind of visibility. So they way I did these was to remove the visibility entirely for each thing the lint identifies, and then add `pub(crate)` back in everywhere the compiler said it was necessary. (Or occasionally `pub(super)` when context suggested that was appropriate.) Tedious, but results in more `pub` removal.

There are plenty more crates to do but this seems like enough for a first PR.

r? `@compiler-errors`
2024-08-27 00:41:57 +02:00
Matthias Krüger
d6a3aa4fc4
Rollup merge of #129590 - compiler-errors:ref-tykind, r=fmease
Avoid taking reference of &TyKind

It's already a ref anyways. Just a tiny cleanup here.
2024-08-26 01:49:04 +02:00
Michael Goulet
48f43fa0ed Avoid taking reference of &TyKind 2024-08-25 16:02:29 -04:00
Stephen Lazaro
e91f32829c Deduplicate Spans in Uninitialized Check
Prevents reporting labels or diagnostics on spans that are produced
multiple times.
2024-08-22 09:36:14 -07:00
Michael Goulet
a97b41f188 Use subtyping for UnsafeFnPointer coercion, too 2024-08-19 21:26:10 -04:00
Ralf Jung
35709be02d rename AddressOf -> RawBorrow inside the compiler 2024-08-18 19:46:53 +02:00
Nicholas Nethercote
0685c97843 Add warn(unreachable_pub) to rustc_borrowck. 2024-08-16 08:46:57 +10:00
许杰友 Jieyou Xu (Joe)
2200910659
Rollup merge of #129059 - compiler-errors:subtyping-correct-type, r=lcnr
Record the correct target type when coercing fn items/closures to pointers

Self-explanatory. We were previously not recording the *target* type of a coercion as the output of an adjustment. This should remedy that.

We must also modify the function pointer casts in MIR typeck to use subtyping, since those broke since #118247.

r? lcnr
2024-08-14 21:43:08 +08:00
bors
e9c965df7b Auto merge of #128812 - nnethercote:shrink-TyKind-FnPtr, r=compiler-errors
Shrink `TyKind::FnPtr`.

By splitting the `FnSig` within `TyKind::FnPtr` into `FnSigTys` and `FnHeader`, which can be packed more efficiently. This reduces the size of the hot `TyKind` type from 32 bytes to 24 bytes on 64-bit platforms. This reduces peak memory usage by a few percent on some benchmarks. It also reduces cache misses and page faults similarly, though this doesn't translate to clear cycles or wall-time improvements on CI.

r? `@compiler-errors`
2024-08-14 00:56:53 +00:00
Michael Goulet
5df13af56f Use the right type when coercing fn items to pointers 2024-08-13 16:23:20 -04:00
Matthias Krüger
4c49418472
Rollup merge of #128712 - compiler-errors:normalize-borrowck, r=lcnr
Normalize struct tail properly for `dyn` ptr-to-ptr casting in new solver

Realized that the new solver didn't handle ptr-to-ptr casting correctly.

r? lcnr

Built on #128694
2024-08-12 23:10:50 +02:00
Guillaume Gomez
7c6dca9050
Rollup merge of #128978 - compiler-errors:assert-matches, r=jieyouxu
Use `assert_matches` around the compiler more

It's a useful assertion, especially since it actually prints out the LHS.
2024-08-12 17:09:19 +02:00
Guillaume Gomez
ea74eff55c
Rollup merge of #128886 - GrigorenkoPV:untranslatable-diagnostic, r=nnethercote
Get rid of some `#[allow(rustc::untranslatable_diagnostic)]`

`@rustbot` label +A-translation
cc https://github.com/rust-lang/rust/issues/100717
2024-08-12 17:09:17 +02:00
Michael Goulet
b5d2079fb9 Rename normalization functions to raw 2024-08-11 19:40:03 -04:00
Michael Goulet
c5205e9d56 Normalize struct tail properly in borrowck and hir typeck 2024-08-11 19:40:03 -04:00
Michael Goulet
c361c924a0 Use assert_matches around the compiler 2024-08-11 12:25:39 -04:00
Matthias Krüger
32e0fe129d
Rollup merge of #128762 - fmease:use-more-slice-pats, r=compiler-errors
Use more slice patterns inside the compiler

Nothing super noteworthy. Just replacing the common 'fragile' pattern of "length check followed by indexing or unwrap" with slice patterns for legibility and 'robustness'.

r? ghost
2024-08-11 07:51:51 +02:00
Pavel Grigorenko
f43cdcea22 rustc_borrowck: fmt 2024-08-10 14:32:56 +03:00
Pavel Grigorenko
1481ab3f75 rustc_borrowck: make "implicit static" suff translatable 2024-08-10 14:32:55 +03:00
Pavel Grigorenko
1b6cc24c20 rustc_borrowck: make some suggestion about static lifetimes translatable 2024-08-10 14:32:55 +03:00
Pavel Grigorenko
446e03e3c9 rustc_borrowck: make suggestion to move closure translatable 2024-08-10 14:32:55 +03:00
Pavel Grigorenko
48413cf078 rustc_borrowck: make dereference suggestion translatable 2024-08-10 14:32:55 +03:00
Folkert
38874a6927
use stable sort to sort multipart diagnostics 2024-08-09 09:45:01 +02:00
Nicholas Nethercote
c4717cc9d1 Shrink TyKind::FnPtr.
By splitting the `FnSig` within `TyKind::FnPtr` into `FnSigTys` and
`FnHeader`, which can be packed more efficiently. This reduces the size
of the hot `TyKind` type from 32 bytes to 24 bytes on 64-bit platforms.
This reduces peak memory usage by a few percent on some benchmarks. It
also reduces cache misses and page faults similarly, though this doesn't
translate to clear cycles or wall-time improvements on CI.
2024-08-09 14:33:25 +10:00
León Orell Valerian Liehr
c4c518d2d4
Use more slice patterns inside the compiler 2024-08-07 13:37:52 +02:00
Michael Goulet
c656ce7aeb Don't arbitrarily choose one upper bound for hidden captured region 2024-08-06 15:43:41 -04:00
Michael Goulet
c6f8672dd5 Normalize when equating dyn tails in MIR borrowck 2024-08-05 14:28:06 -04:00
Matthias Krüger
52f7d33109
Rollup merge of #128244 - compiler-errors:move-clone-sugg, r=estebank
Peel off explicit (or implicit) deref before suggesting clone on move error in borrowck, remove some hacks

Also remove a heck of a lot of weird hacks in `suggest_cloning` that I don't think we should have around.

I know this regresses tests, but I don't believe most of these suggestions were accurate, b/c:
1. They either produced type errors (e.g. turning `&x` into `x.clone()`)
2. They don't fix the issue
3. They fix the issue ostensibly, but introduce logic errors (e.g. cloning a `&mut Option<T>` to then `Option::take` out...)

Most of the suggestions are still wrong, but they're not particularly *less* wrong IMO.

Stacked on top of #128241, which is an "obviously worth landing" subset of this PR.

r? estebank
2024-07-31 23:20:11 +02:00
Michael Goulet
f990239b34 Stop using MoveDataParamEnv for places that don't need a param-env 2024-07-29 11:59:47 -04:00
Nicholas Nethercote
84ac80f192 Reformat use declarations.
The previous commit updated `rustfmt.toml` appropriately. This commit is
the outcome of running `x fmt --all` with the new formatting options.
2024-07-29 08:26:52 +10:00
Trevor Gross
ee25d99299
Rollup merge of #128241 - compiler-errors:clone-sugg, r=jieyouxu
Remove logic to suggest clone of function output

I can't exactly tell, but I believe that this suggestion is operating off of a heuristic that the lifetime of a function's input is correlated with the lifetime of a function's output in such a way that cloning would fix an error. I don't think that actually manages to hit the bar of "actually provides useful suggestions" most of the time.

Specifically, I've hit false-positives due to this suggestion *twice* when fixing ICEs in the compiler, so I don't think it's worthwhile having this logic around. Neither of the two affected UI tests are actually fixed by the suggestion.
2024-07-27 13:32:57 -04:00
Michael Goulet
91acacf85b Peel off explicit (or implicit) deref before suggesting clone on move error in borrowck 2024-07-26 14:41:56 -04:00
Michael Goulet
e7eae5370e Remove logic to suggest clone of function output 2024-07-26 13:56:06 -04:00
Michael Goulet
5a9959fd9d Suppress useless clone suggestion 2024-07-26 12:53:55 -04:00
Michael Goulet
d004edf311 Don't ICE if HIR and middle types disagree in borrowck error reporting 2024-07-24 23:36:47 -04:00
Matthias Krüger
4d6f74b450
Rollup merge of #128049 - compiler-errors:E0626, r=petrochenkov
Reword E0626 to mention static coroutine, add structured suggestion for adding `static`

Not certain how to make the example feel less artificial. 🤷

My main point though is that we should probably emphasize that the first solution to making a coroutine allow a borrow across an await is making it `static`.

Also adds a structured suggestion.
2024-07-23 13:06:55 +02:00
Michael Goulet
ce8a625092 Move all error reporting into rustc_trait_selection 2024-07-21 22:34:35 -04:00
Michael Goulet
fc1e7ceb4b Move some stuff to TypeErrCtxt 2024-07-21 22:33:15 -04:00
Michael Goulet
6dfc9f8886 Explain that coroutine can be marked static
And also point out the def span of the coroutine
2024-07-21 22:32:29 -04:00
Matthias Krüger
767b3cb54b
Rollup merge of #127948 - surechen:fix_127915, r=compiler-errors
fixes panic error `index out of bounds` in conflicting error

fixes #127915
2024-07-20 07:13:44 +02:00
surechen
9747a2c3ef fixes panic error
fixes #127915
2024-07-19 09:34:32 +08:00
Michael Goulet
8dbb63a585 Remove tag field from relations 2024-07-18 14:34:05 -04:00
Matthias Krüger
b2b14deca5
Rollup merge of #127810 - compiler-errors:less-tcx, r=lcnr
Rename `tcx` to `cx` in `rustc_type_ir`

Self-explanatory. Forgot that we had to do this in type_ir too, and not just the new solver crate lol.

r? lcnr
2024-07-18 08:09:00 +02:00
Michael Goulet
0b5ce54bc2 Fix relations 2024-07-17 10:46:10 -04:00
surechen
4821b84b92 If the moved value is a mut reference, it is used in a generic function and it's type is a generic param, it can be reborrowed to avoid moving.
for example:

```rust
struct Y(u32);
// x's type is '& mut Y' and it is used in `fn generic<T>(x: T) {}`.
fn generic<T>(x: T) {}
```

fixes #127285
2024-07-17 10:07:02 +08:00
Trevor Gross
059222ddc9
Rollup merge of #127501 - compiler-errors:invert-infer-error-mod-struture, r=lcnr
Invert infer `error_reporting` mod struture

Parallel change to #127493, which moves `rustc_infer::infer::error_reporting` to `rustc_infer::error_reporting::infer`. After this, we should just be able to merge this into `rustc_trait_selection::error_reporting::infer`, and pull down `TypeErrCtxt` into that crate. 👍

r? lcnr
2024-07-16 16:15:16 -05:00
Trevor Gross
12fd2f94b3
Rollup merge of #120990 - chenyukang:yukang-fix-120327-dbg, r=oli-obk
Suggest a borrow when using dbg

Fixes #120327
r? ````@estebank````
2024-07-16 02:02:23 -05:00
Michael Goulet
e86fbcfd70 Move rustc_infer::infer::error_reporting to rustc_infer::error_reporting::infer 2024-07-15 20:16:12 -04:00
yukang
317952677a Suggest a borrow when using dbg 2024-07-16 02:48:47 +08:00
yukang
7ff71e5fb4 Remove invalid help diagnostics for const pointer 2024-07-16 01:56:27 +08:00
Michael Goulet
dc20733913 Stop using the gen keyword in the compiler 2024-07-14 14:01:01 -04:00
Matthias Krüger
c2b7842555
Rollup merge of #127625 - SkiFire13:revert-comment-deletion, r=workingjubilee
Revert accidental comment deletion

This reverts an accidental comment deletion made in #113128

See also https://github.com/rust-lang/rust/pull/113128#discussion_r1674614882
2024-07-12 03:43:36 +02:00
Giacomo Stevanato
d9021791eb Revert accidental comment deletion 2024-07-11 22:38:34 +02:00
Matthias Krüger
8de487fdbd
Rollup merge of #124599 - estebank:issue-41708, r=wesleywiser
Suggest borrowing on fn argument that is `impl AsRef`

When encountering a move conflict, on an expression that is `!Copy` passed as an argument to an `fn` that is `impl AsRef`, suggest borrowing the expression.

```
error[E0382]: use of moved value: `bar`
  --> f204.rs:14:15
   |
12 |     let bar = Bar;
   |         --- move occurs because `bar` has type `Bar`, which does not implement the `Copy` trait
13 |     foo(bar);
   |         --- value moved here
14 |     let baa = bar;
   |               ^^^ value used here after move
   |
help: borrow the value to avoid moving it
   |
13 |     foo(&bar);
   |         +
```

Fix #41708
2024-07-11 17:01:36 +02:00
bors
f25e92bd42 Auto merge of #127500 - compiler-errors:consolidate-region-errors, r=lcnr
Consolidate region error reporting in `rustc_infer`

More work on https://github.com/rust-lang/rust/issues/127492. Separate but important step, since I'm gonna likely pull everything else here into another module.

I don't think I'm confident whether `nice_region_error` should be a submodule of the new `rustc_infer::infer::error_reporting::region` module, so I left it alone for now.

r? lcnr
2024-07-09 13:43:15 +00:00
Michael Goulet
9a92526b98 Consolidate region error reporting in rustc_infer 2024-07-08 20:35:30 -04:00
Michael Goulet
fe4c995ccb Move trait selection error reporting to its own top-level module 2024-07-08 16:04:47 -04:00
Matthias Krüger
c4ee2df539
Rollup merge of #120248 - WaffleLapkin:bonk-ptr-object-casts, r=compiler-errors,oli-obk,lnicola
Make casts of pointers to trait objects stricter

This is an attempt to `fix` https://github.com/rust-lang/rust/issues/120222 and https://github.com/rust-lang/rust/issues/120217.

This is done by adding restrictions on casting pointers to trait objects.

Before this PR the rules were as follows:

> When casting `*const X<dyn A>` -> `*const Y<dyn B>`, principal traits in `A` and `B` must refer to the same trait definition (or no trait).

With this PR the rules are changed to

> When casting `*const X<dyn Src>` -> `*const Y<dyn Dst>`
> - if `Dst` has a principal trait `DstP`,
>   - `Src` must have a principal trait `SrcP`
>   - `dyn SrcP` and `dyn DstP` must be the same type (modulo the trait object lifetime, `dyn T+'a` -> `dyn T+'b` is allowed)
>   - Auto traits in `Dst` must be a subset of auto traits in `Src`
>     - Not adhering to this is currently a FCW (warn-by-default + `FutureReleaseErrorReportInDeps`), instead of an error
> - if `Src` has a principal trait `Dst` must as well
>   - this restriction will be removed in a follow up PR

This ensures that
1. Principal trait's generic arguments match (no `*const dyn Tr<A>` -> `*const dyn Tr<B>` casts, which are a problem for [#120222](https://github.com/rust-lang/rust/issues/120222))
2. Principal trait's lifetime arguments match (no `*const dyn Tr<'a>` -> `*const dyn Tr<'b>` casts, which are a problem for [#120217](https://github.com/rust-lang/rust/issues/120217))
3. No auto traits can be _added_ (this is a problem for arbitrary self types, see [this comment](https://github.com/rust-lang/rust/pull/120248#discussion_r1463835350))

Some notes:
 - We only care about the metadata/last field, so you can still cast `*const dyn T` to `*const WithHeader<dyn T>`, etc
- The lifetime of the trait object itself (`dyn A + 'lt`) is not checked, so you can still cast `*mut FnOnce() + '_` to `*mut FnOnce() + 'static`, etc
  - This feels fishy, but I couldn't come up with a reason it must be checked

The diagnostics are currently not great, to say the least, but as far as I can tell this correctly fixes the issues.

cc `@oli-obk` `@compiler-errors` `@lcnr`
2024-07-08 16:28:15 +02:00
bors
9af6fee87d Auto merge of #113128 - WaffleLapkin:become_trully_unuwuable, r=oli-obk,RalfJung
Support tail calls in mir via `TerminatorKind::TailCall`

This is one of the interesting bits in tail call implementation — MIR support.

This adds a new `TerminatorKind` which represents a tail call:
```rust
    TailCall {
        func: Operand<'tcx>,
        args: Vec<Operand<'tcx>>,
        fn_span: Span,
    },
```

*Structurally* this is very similar to a normal `Call` but is missing a few fields:
- `destination` — tail calls don't write to destination, instead they pass caller's destination to the callee (such that eventual `return` will write to the caller of the function that used tail call)
- `target` — similarly to `destination` tail calls pass the caller's return address to the callee, so there is nothing to do
- `unwind` — I _think_ this is applicable too, although it's a bit confusing
- `call_source` — `become` forbids operators and is not created as a lowering of something else; tail calls always come from HIR (at least for now)

It might be helpful to read the interpreter implementation to understand what `TailCall` means exactly, although I've tried documenting it too.

-----

There are a few `FIXME`-questions still left, ideally we'd be able to answer them during review ':)

-----

r? `@oli-obk`
cc `@scottmcm` `@DrMeepster` `@JakobDegen`
2024-07-08 04:35:04 +00:00
Maybe Waffle
484152d562 Support tail calls in mir via TerminatorKind::TailCall 2024-07-07 17:11:04 +02:00
Michael Goulet
e5d6a416e8 Uplift PredicateEmittingRelation first 2024-07-06 10:05:49 -04:00
Maybe Lapkin
073f3a263b Equate types instead of using Unsize 2024-07-05 22:35:14 +02:00
Oli Scherer
7dca61b68b Use ControlFlow results for visitors that are only looking for a single value 2024-07-05 15:00:40 +00:00
bors
8a9cccb100 Auto merge of #127326 - matthiaskrgr:rollup-kz7vd3w, r=matthiaskrgr
Rollup of 9 pull requests

Successful merges:

 - #123043 (Disable dead variant removal for `#[repr(C)]` enums.)
 - #126405 (Migrate some rustc_builtin_macros to SessionDiagnostic)
 - #127037 (Remove some duplicated tests)
 - #127283 (Reject SmartPointer constructions not serving the purpose)
 - #127301 (Tweak some structured suggestions to be more verbose and accurate)
 - #127307 (Allow to have different types for arguments of `Rustc::remap_path_prefix`)
 - #127309 (jsondocck: add `$FILE` built-in variable)
 - #127314 (Trivial update on tidy bless note)
 - #127319 (Remove a use of `StructuredDiag`, which is incompatible with automatic error tainting and error translations)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-07-04 16:37:39 +00:00
Maybe Lapkin
a1f20f17c8 Properly normalize types in bck when checking pointer casts 2024-07-04 17:57:31 +02:00
Maybe Lapkin
52ba120700 Remove unhelpful comments and add helpful ones 2024-07-04 17:57:31 +02:00
Maybe Lapkin
340d69be12 Align the changes to the lang decision 2024-07-04 17:57:29 +02:00
Maybe Waffle
5645e8e285 Add more checks for pointers with vtable meta
The rules for casting `*mut X<dyn A>` -> `*mut Y<dyn B>` are as follows:
- If `B` has a principal
  - `A` must have exactly the same principal (including generics)
  - Auto traits of `B` must be a subset of autotraits in `A`

Note that `X<_>` and `Y<_>` can be identity, or arbitrary structs with last field being the dyn type.
The lifetime of the trait object itself (`dyn ... + 'a`) is not checked.

This prevents a few soundness issues with `#![feature(arbitrary_self_types)]` and trait upcasting.
Namely, these checks make sure that vtable is always valid for the pointee.
2024-07-04 17:56:09 +02:00
bors
9f877c9cd2 Auto merge of #127170 - bjorn3:no_specialize_index_borrowck, r=michaelwoerister
Stop using specialization in rustc_index and rustc_borrowck

For rustc_borrowck the version with specialization isn't much more readable anyway IMO. For rustc_index it probably doesn't affect perf in any noticeable way anyway.
2024-07-04 14:24:43 +00:00
Esteban Küber
ff92ab0903 More accurate mutability suggestion 2024-07-04 05:36:34 +00:00
Esteban Küber
9344779f71 Fix &mut removal suggestion 2024-07-04 04:36:52 +00:00
Esteban Küber
89ecae5d85 Better span for "make binding mutable" suggestion 2024-07-04 02:02:21 +00:00
bors
c872a1418a Auto merge of #125507 - compiler-errors:type-length-limit, r=lcnr
Re-implement a type-size based limit

r? lcnr

This PR reintroduces the type length limit added in #37789, which was accidentally made practically useless by the caching changes to `Ty::walk` in #72412, which caused the `walk` function to no longer walk over identical elements.

Hitting this length limit is not fatal unless we are in codegen -- so it shouldn't affect passes like the mir inliner which creates potentially very large types (which we observed, for example, when the new trait solver compiles `itertools` in `--release` mode).

This also increases the type length limit from `1048576 == 2 ** 20` to `2 ** 24`, which covers all of the code that can be reached with craterbot-check. Individual crates can increase the length limit further if desired.

Perf regression is mild and I think we should accept it -- reinstating this limit is important for the new trait solver and to make sure we don't accidentally hit more type-size related regressions in the future.

Fixes #125460
2024-07-03 11:56:36 +00:00
bors
67f0d43890 Auto merge of #123720 - amandasystems:dyn-enable-refactor, r=nikomatsakis
Rewrite handling of universe-leaking placeholder regions into outlives constraints

This commit prepares for Polonius by moving handling of leak check/universe errors out of the inference step by rewriting any universe error into an outlives-static constraint.

This variant is a work in progress but seems to pass most tests.

Note that a few debug assertions no longer hold; a few extra eyes on those changes are appreciated!
2024-07-03 01:24:07 +00:00
Michael Goulet
b1059ccda2 Instance::resolve -> Instance::try_resolve, and other nits 2024-07-02 17:28:03 -04:00
Amanda Stjerna
9be3a3d761 Add description for why this PR was made 2024-07-01 11:52:38 +02:00
Amanda Stjerna
eea5cf87b2 Code review: rename the method min_universe() 2024-07-01 11:32:45 +02:00
Amanda Stjerna
b3ef0e8487 Handle universe leaks by rewriting the constraint graph
This version is a squash-rebased version of a series
of exiermental commits, since large parts of them
were broken out into PR #125069.

It explicitly handles universe violations in higher-kinded
outlives constraints by adding extra outlives static constraints.
2024-07-01 10:39:42 +02:00
bors
7b21c18fe4 Auto merge of #126996 - oli-obk:do_not_count_errors, r=nnethercote
Automatically taint InferCtxt when errors are emitted

r? `@nnethercote`

Basically `InferCtxt::dcx` now returns a `DiagCtxt` that refers back to the `Cell<Option<ErrorGuaranteed>>` of the `InferCtxt` and thus when invoking `Diag::emit`, and the diagnostic is an error, we taint the `InferCtxt` directly.

That change on its own has no effect at all, because `InferCtxt` already tracks whether errors have been emitted by recording the global error count when it gets opened, and checking at the end whether the count changed. So I removed that error count check, which had a bit of fallout that I immediately fixed by invoking `InferCtxt::dcx` instead of `TyCtxt::dcx` in a bunch of places.

The remaining new errors are because an error was reported in another query, and never bubbled up. I think they are minor enough for this to be ok, and sometimes it actually improves diagnostics, by not silencing useful diagnostics anymore.

fixes #126485 (cc `@olafes)`

There are more improvements we can do (like tainting in hir ty lowering), but I would rather do that in follow up PRs, because it requires some refactorings.
2024-07-01 06:35:58 +00:00
bjorn3
449581d89b Remove usage of specialization from rustc_borrowck 2024-06-30 16:42:53 +00:00
Lin Yihai
8dc36c1647 fix: prefer (*p).clone to p.clone if the p is a raw pointer 2024-06-29 19:58:18 +08:00
Oli Scherer
ba198af81f Rename 'cx to 'infcx 2024-06-27 09:07:57 +00:00
Oli Scherer
86c8eae774 Automatically taint InferCtxt when errors are emitted 2024-06-26 16:01:45 +00:00
Oli Scherer
5988078aa2 Restrict diagnostic context lifetime of InferCtxt to itself instead of TyCtxt 2024-06-26 16:01:44 +00:00
Oli Scherer
ef559199ef Restrict diagnostic context lifetime of mir borrowck to InferCtxt instead of TyCtxt 2024-06-26 16:01:44 +00:00
Oli Scherer
81695a147a Split lifetimes on mir borrowck dataflow 2024-06-26 16:01:44 +00:00
Matthias Krüger
175756f683
Rollup merge of #126884 - estebank:issue-125634, r=Nadrieril
Do not ICE when suggesting dereferencing closure arg

Account for `for` lifetimes when constructing closure to see if dereferencing the return value would be valid.

Fix #125634, fix #124563.
2024-06-25 18:03:00 +02:00
Oli Scherer
8fc6b3de19 Separate the mir body lifetime from the other lifetimes 2024-06-24 14:28:14 +00:00
Oli Scherer
1c4d0ced58 Separate the lifetimes of the BorrowckInferCtxt from the other borrowed items 2024-06-24 14:28:13 +00:00
Esteban Küber
a2298a6f19 Do not ICE when suggesting dereferencing closure arg
Account for `for` lifetimes when constructing closure to see if dereferencing the return value would be valid.

Fix #125634, fix #124563.
2024-06-24 03:39:54 +00:00
bors
d49994b060 Auto merge of #126023 - amandasystems:you-dropped-this-again, r=nikomatsakis
Remove confusing `use_polonius` flag and do less cloning

The `use_polonius` flag is both redundant and confusing since every function it's propagated to also checks if `all_facts` is `Some`, the true test of whether to generate Polonius facts for Polonius or for external consumers. This PR makes that path clearer by simply doing away with the argument and handling the logic in precisely two places: where facts are populated (check for `Some`), and where `all_facts` are initialised. It also delays some statements until after that check to avoid the miniscule performance penalty of executing them when Polonius is disabled.

This also addresses `@lqd's` concern in #125652 by reducing the size of what is cloned out of Polonius facts to just the facts being added, as opposed to the entire vector of potential inputs, and added descriptive comments.

*Reviewer note*: the comments in `add_extra_drop_facts` should be inspected by a reviewer, in particular the one on [L#259](https://github.com/rust-lang/rust/compare/master...amandasystems:you-dropped-this-again?expand=1#diff-aa727290e6670264df2face84f012897878e11a70e9c8b156543cfcd9619bac3R259) in this PR, which should be trivial for someone with the right background knowledge to address.

I also included some lints I found on the way there that I couldn't help myself from addressing.
2024-06-24 00:24:51 +00:00
Michael Goulet
db638ab968 Rename a bunch of things 2024-06-21 12:32:05 -04:00
Oli Scherer
3f34196839 Remove redundant argument from subdiagnostic method 2024-06-18 15:42:11 +00:00
Oli Scherer
7ba82d61eb Use a dedicated type instead of a reference for the diagnostic context
This paves the way for tracking more state (e.g. error tainting) in the diagnostic context handle
2024-06-18 15:42:11 +00:00
Oli Scherer
7e5893019c Use a more precise lifetime 2024-06-18 13:45:08 +00:00
Matthias Krüger
940ff24ec0
Rollup merge of #126567 - compiler-errors:instance-kind, r=oli-obk,lcnr
Rename `InstanceDef` -> `InstanceKind`

Renames `InstanceDef` to `InstanceKind`. The `Def` here is confusing, and makes it hard to distinguish `Instance` and `InstanceDef`. `InstanceKind` makes this more obvious, since it's really just describing what *kind* of instance we have.

Not sure if this is large enough to warrant a types team MCP -- it's only 53 files. I don't personally think it does, but happy to write one if anyone disagrees. cc ``@rust-lang/types``

r? types
2024-06-17 20:34:51 +02:00
Guillaume Gomez
020c07718f
Rollup merge of #126570 - nnethercote:fix-126385, r=lcnr
Convert a `span_bug` to a `span_delayed_bug`.

PR #121208 converted this from a `span_delayed_bug` to a `span_bug` because nothing in the test suite caused execution to hit this path. But now fuzzing has found a test case that does hit it. So this commit converts it back to `span_delayed_bug` and adds the relevant test.

Fixes #126385.

r? `@lcnr`
2024-06-17 11:28:54 +02:00
Guillaume Gomez
9f5e2e314c
Rollup merge of #126226 - gurry:125325-improve-closure-arg-sugg, r=oli-obk
Make suggestion to change `Fn` to `FnMut` work with methods as well

Fixes #125325

The issue occurred because the code that emitted the suggestion to change `Fn` to `FnMut` worked only for function calls  and not method calls. This PR makes it work with methods as well.
2024-06-17 11:28:53 +02:00
Nicholas Nethercote
bd32c4c21e Convert a span_bug to a span_delayed_bug.
PR #121208 converted this from a `span_delayed_bug` to a `span_bug`
because nothing in the test suite caused execution to hit this path. But
now fuzzing has found a test case that does hit it. So this commit
converts it back to `span_delayed_bug` and adds the relevant test.

Fixes #126385.
2024-06-17 15:21:07 +10:00
Michael Goulet
342c1b03d6 Rename InstanceDef -> InstanceKind 2024-06-16 21:35:21 -04:00
Guillaume Gomez
53364c3e07
Rollup merge of #126508 - beepster4096:minor_borrowck_cherrypick, r=compiler-errors
Make uninitialized_error_reported a set of locals

Another artifact of how places used to be able to be based on statics and not just locals. This set is exclusively filled with PlaceRefs that are just locals, so it should just contain locals directly.
2024-06-15 19:51:37 +02:00
Guillaume Gomez
be1d42776d
Rollup merge of #126410 - RalfJung:smir-const-operand, r=oli-obk
smir: merge identical Constant and ConstOperand types

The first commit renames the const operand visitor functions on regular MIR to match the type name, that was forgotten in the original rename.

The second commit changes stable MIR, fixing https://github.com/rust-lang/project-stable-mir/issues/71. Previously there were two different smir types for the MIR type `ConstOperand`, one used in `Operand` and one in `VarDebugInfoContents`.

Maybe we should have done this with https://github.com/rust-lang/rust/pull/125967, so there's only a single breaking change... but I saw that PR too late.

Fixes https://github.com/rust-lang/project-stable-mir/issues/71
2024-06-15 19:51:35 +02:00
Matthias Krüger
335e320baa
Rollup merge of #126354 - compiler-errors:variance, r=lcnr
Use `Variance` glob imported variants everywhere

Fully commit to using the globbed variance. Could be convinced the other way, and change this PR to not use the globbed variants anywhere, but I'd rather we do one or the other.

r? lcnr
2024-06-15 10:56:40 +02:00
beepster4096
58b065eb44 make uninitialized_error_reported a set of locals 2024-06-14 21:56:51 -07:00
Michael Goulet
93ff86ed7c Use is_lang_item more aggressively 2024-06-14 16:54:29 -04:00
Matthias Krüger
2b3fb62b93
Rollup merge of #126320 - oli-obk:pat_ice, r=lcnr
Avoid ICES after reporting errors on erroneous patterns

fixes #109812
fixes #125914
fixes #124004
2024-06-14 08:35:48 +02:00
Ralf Jung
ed1618dedc MIR visitor: constant -> const_operand 2024-06-13 15:37:13 +02:00
Oli Scherer
a6217011f6 Replace some Option<Diag> with Result<(), Diag> 2024-06-13 06:16:12 +00:00
bors
8cf5101d77 Auto merge of #125069 - amandasystems:scc-refactor, r=nikomatsakis
Extend SCC construction to enable extra functionality

Do YOU feel like your SCC construction doesn't do enough? Then I have a patch for you! SCCs can now do *everything*! Well, almost.

This patch has been extracted from #123720. It specifically enhances
`Sccs` to allow tracking arbitrary commutative properties (think min/max mappings on nodes vs arbitrary closures) of strongly connected components, including
- reachable values (max/min)
- SCC-internal values (max/min)

This helps with among other things universe computation. We can now identify
SCC universes as a reasonably straightforward "find max/min" operation during SCC construction. This is also included in this patch.

It's also more or less zero-cost; don't use the new features, don't pay for them.

This commit also vastly extends the documentation of the SCCs module, which I had a very hard time following. It may or may not have gotten easier to read for someone else.

I believe this logic can also be used in leak check, but haven't checked. Ha. ha. Ha.
2024-06-12 23:15:33 +00:00
Michael Goulet
54fa4b0b74 Use Variance glob import everywhere 2024-06-12 16:25:45 -04:00
Amanda Stjerna
d63708b907 Address code review comments on the comments 2024-06-12 15:48:34 +02:00
Amanda Stjerna
2e1e119ba1 Move RegionTracker to region_infer
In terms of code organisation, this is a lot cleaner and allows
tighter access modifiers.
2024-06-12 15:48:34 +02:00
Amanda Stjerna
e6eb63d4b9 Resurrect some comments, remove a pub
This commit addresses @lqd's code review and resurrects
a lost comment and removes some dead code.
2024-06-12 15:47:32 +02:00
Amanda Stjerna
7782d2023b Roll back a few #[instrument]
Apparently this interferes with inlining and murders performance
on `wg-grammar`.
2024-06-12 15:47:32 +02:00
Amanda Stjerna
582c613be8 Formatting, weird because I just did that 2024-06-12 15:47:32 +02:00
Amanda Stjerna
905db03b28 Simplify path compression logic 2024-06-12 15:47:32 +02:00
Amanda Stjerna
b1ace388c0 Extend SCC construction to enable extra functionality
This patch has been extracted from #123720. It specifically enhances
`Sccs` to allow tracking arbitrary commutative properties of SCCs, including
- reachable values (max/min)
- SCC-internal values (max/min)

This helps with among other things universe computation: we can now identify
SCC universes as a straightforward "find max/min" operation during SCC construction.

It's also more or less zero-cost; don't use the new features, don't pay for them.

This commit also vastly extends the documentation of the SCCs module, which I had a very hard time following.
2024-06-12 15:47:32 +02:00
Guillaume Gomez
876ef7f021
Rollup merge of #126295 - linyihai:uninitalized-in-match-arm, r=pnkfelix
No uninitalized report in a pre-returned match arm

This is a attemp to address https://github.com/rust-lang/rust/issues/126133
2024-06-12 15:45:01 +02:00
Jubilee
36e828fab5
Rollup merge of #126301 - nnethercote:sort-crate-attributes, r=davidtwco
Use `tidy` to sort crate attributes for all compiler crates.

We already do this for a number of crates, e.g. `rustc_middle`, `rustc_span`, `rustc_metadata`, `rustc_span`, `rustc_errors`.

For the ones we don't, in many cases the attributes are a mess.
- There is no consistency about order of attribute kinds (e.g. `allow`/`deny`/`feature`).
- Within attribute kind groups (e.g. the `feature` attributes), sometimes the order is alphabetical, and sometimes there is no particular order.
- Sometimes the attributes of a particular kind aren't even grouped all together, e.g. there might be a `feature`, then an `allow`, then another `feature`.

This commit extends the existing sorting to all compiler crates, increasing consistency. If any new attribute line is added there is now only one place it can go -- no need for arbitrary decisions.

Exceptions:
- `rustc_log`, `rustc_next_trait_solver` and `rustc_type_ir_macros`, because they have no crate attributes.
- `rustc_codegen_gcc`, because it's quasi-external to rustc (e.g. it's ignored in `rustfmt.toml`).

r? `@davidtwco`
2024-06-12 03:57:24 -07:00
Nicholas Nethercote
75b164d836 Use tidy to sort crate attributes for all compiler crates.
We already do this for a number of crates, e.g. `rustc_middle`,
`rustc_span`, `rustc_metadata`, `rustc_span`, `rustc_errors`.

For the ones we don't, in many cases the attributes are a mess.
- There is no consistency about order of attribute kinds (e.g.
  `allow`/`deny`/`feature`).
- Within attribute kind groups (e.g. the `feature` attributes),
  sometimes the order is alphabetical, and sometimes there is no
  particular order.
- Sometimes the attributes of a particular kind aren't even grouped
  all together, e.g. there might be a `feature`, then an `allow`, then
  another `feature`.

This commit extends the existing sorting to all compiler crates,
increasing consistency. If any new attribute line is added there is now
only one place it can go -- no need for arbitrary decisions.

Exceptions:
- `rustc_log`, `rustc_next_trait_solver` and `rustc_type_ir_macros`,
  because they have no crate attributes.
- `rustc_codegen_gcc`, because it's quasi-external to rustc (e.g. it's
  ignored in `rustfmt.toml`).
2024-06-12 15:49:10 +10:00
Lin Yihai
5d8f40a63a No uninitalized report in a pre-returned match arm 2024-06-12 11:11:02 +08:00